This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-swift-structured-concurrency-bridge

Deterministic Kotlin Coroutine to Swift Structured Concurrency Bridge

Enforces strict bidirectional cancellation propagation and lifecycle binding between Kotlin Coroutines and Swift Structured Concurrency. Prevents GCD worker thread-pool starvation and cross-runtime reference cycle memory leaks between Kotlin's GC and Swift ARC.

Prohibited Anti-Pattern: Unmanaged Detached Task Bridging Leaking Zombie Coroutines and Native ARC Retain Cycles

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Kotlin Coroutine to Swift Structured Concurrency Bridge - Enforces strict bidirectional cancellation propagation and lifecycle binding between Kotlin Coroutines and Swift Structured Concurrency. Prevents GCD worker thread-pool starvation and cross-runtime reference cycle memory leaks between Kotlin's GC and Swift ARC.
globs: iosApp/**/*.swift, shared/src/iosMain/**/*.kt, shared/src/commonMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-structured-concurrency-bridge"
---

# Deterministic Kotlin Coroutine to Swift Structured Concurrency Bridge

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unmanaged Detached Task Bridging Leaking Zombie Coroutines and Native ARC Retain Cycles

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform (KMP) and Apple Platform Interoperability. You mandate deterministic concurrency boundaries between Kotlin Native and Swift. Enforce strict bidirectional cancellation mapping between Kotlin Coroutine Jobs and Swift Task hierarchies, eliminate detached Task spawns across the FFI boundary, and prevent retain cycles across the Kotlin GC / Apple ARC barrier.

## Strict Guidelines
- Engineers MUST ALWAYS bind Swift `Task` cancellation to Kotlin `CancellableContinuation` or `Job.cancel()` via `withTaskCancellationHandler`.
- Engineers MUST NOT bridge Kotlin suspending functions or `Flow` emissions using detached, unmanaged Swift `Task { ... }` blocks or escaping callbacks without lifecycle disposal.
- Engineers MUST ensure Kotlin `CoroutineScope` instances on the native boundary are tied to explicit lifecycle owners (e.g., Swift `ObservableObject` or UIKit `UIViewController` deinitialization).
- Services MUST clean up active `Job` references immediately upon Swift task completion or failure to prevent Kotlin-ObjC export wrapper retain cycles.
- Components NEVER bridge Kotlin `StateFlow` or `SharedFlow` into Swift without wrapping emission listeners in cooperative cancellation-aware `AsyncSequence` or SKIE auto-generated async adapters.

## Bad vs Good Implementations
### Bridging Kotlin Suspending Function to Swift Async/Await with Deterministic Cancellation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to attach a cancellation handler leaves the underlying Kotlin coroutine executing indefinitely when the enclosing Swift Task is cancelled, causing thread-pool starvation and uncollected garbage across the runtime bridge.
```swift
// BAD: Detached Task or naive completion bridge leaks Kotlin coroutine if Swift caller cancels
func fetchUserData(userId: String) async throws -> UserProfile {
    return try await withCheckedThrowingContinuation { continuation in
        // Native Kotlin bridge invoking suspend function with a completion handler
        UserRepositoryBridge().fetchUser(id: userId) { profile, error in
            if let error = error {
                continuation.resume(throwing: error)
            } else if let profile = profile {
                continuation.resume(returning: profile)
            }
        }
        // Failure: If the calling Swift Task is cancelled, the Kotlin coroutine continues executing,
        // holding GCD threads and memory in the Kotlin runtime.
    }
}
```

#### Production Standard (Correct)
> **Standard**: Registers an onCancel closure that guarantees the underlying Kotlin Job is cancelled immediately when the calling Swift Task cancels, preserving cooperative execution semantics and freeing runtime resources.
```swift
// GOOD: Bidirectional cancellation mapping using withTaskCancellationHandler and Job handle
func fetchUserData(userId: String) async throws -> UserProfile {
    var job: KMPJob? = nil
    
    return try await withTaskCancellationHandler {
        try Task.checkCancellation()
        return try await withCheckedThrowingContinuation { continuation in
            job = UserRepositoryBridge().fetchUserWithJob(id: userId) { profile, error in
                if let error = error {
                    continuation.resume(throwing: error)
                } else if let profile = profile {
                    continuation.resume(returning: profile)
                } else {
                    continuation.resume(throwing: CancellationError())
                }
            }
        }
    } onCancel: {
        // Deterministically cancel the Kotlin Job when the Swift Task is cancelled
        job?.cancel(cause: nil)
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Deterministic Kotlin Coroutine to Swift Structured Concurrency Bridge

Deterministic Kotlin Coroutine to Swift Structured Concurrency Bridge defines an industrial-grade behavioral standard for mobile engineering. Enforces strict bidirectional cancellation propagation and lifecycle binding between Kotlin Coroutines and Swift Structured Concurrency. Prevents GCD worker thread-pool starvation and cross-runtime reference cycle memory leaks between Kotlin's GC and Swift ARC. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unmanaged Detached Task Bridging Leaking Zombie Coroutines and Native ARC Retain Cycles Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnmanaged Detached Task Bridging Leaking Zombie Coroutines and Native ARC Retain CyclesCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS bind Swift `Task` cancellation to Kotlin `CancellableContinuation` or `Job.cancel()` via `withTaskCancellationHandler`.

Engineers MUST ALWAYS bind Swift `Task` cancellation to Kotlin `CancellableContinuation` or `Job.cancel()` via `withTaskCancellationHandler`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT bridge Kotlin suspending functions or `Flow` emissions using detached, unmanaged Swift `Task { ... }` blocks or escaping callbacks without lifecycle disposal.

Engineers MUST NOT bridge Kotlin suspending functions or `Flow` emissions using detached, unmanaged Swift `Task { ... }` blocks or escaping callbacks without lifecycle disposal.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST ensure Kotlin `CoroutineScope` instances on the native boundary are tied to explicit lifecycle owners (e.g., Swift `ObservableObject` or UIKit `UIViewController` deinitialization).

Engineers MUST ensure Kotlin `CoroutineScope` instances on the native boundary are tied to explicit lifecycle owners (e.g., Swift `ObservableObject` or UIKit `UIViewController` deinitialization).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST clean up active `Job` references immediately upon Swift task completion or failure to prevent Kotlin-ObjC export wrapper retain cycles.

Services MUST clean up active `Job` references immediately upon Swift task completion or failure to prevent Kotlin-ObjC export wrapper retain cycles.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER bridge Kotlin `StateFlow` or `SharedFlow` into Swift without wrapping emission listeners in cooperative cancellation-aware `AsyncSequence` or SKIE auto-generated async adapters.

Components NEVER bridge Kotlin `StateFlow` or `SharedFlow` into Swift without wrapping emission listeners in cooperative cancellation-aware `AsyncSequence` or SKIE auto-generated async adapters.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Deterministic Kotlin Coroutine to Swift Structured Concurrency Bridge critical for AI coding assistants?

Enforces strict bidirectional cancellation propagation and lifecycle binding between Kotlin Coroutines and Swift Structured Concurrency. Prevents GCD worker thread-pool starvation and cross-runtime reference cycle memory leaks between Kotlin's GC and Swift ARC. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unmanaged Detached Task Bridging Leaking Zombie Coroutines and Native ARC Retain Cycles) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Deterministic