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

Bidirectional Structured Concurrency and Cancellation Propagation in KMP Swift Export

Enforces strict cooperative cancellation bridging between Kotlin Coroutines (Job/Deferred) and Swift Concurrency (Task/AsyncStream) across KMP Swift Export boundaries. Prevents uncollected Job leaks in Kotlin and unmanaged Task retain cycles in Swift by mandating explicit CancellationHandler attachments and DisposableHandle cleanup lifecycle management.

Prohibited Anti-Pattern: Fire-and-forget Swift Task wrappers that orphan active Kotlin Coroutines upon Task cancellation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bidirectional Structured Concurrency and Cancellation Propagation in KMP Swift Export - Enforces strict cooperative cancellation bridging between Kotlin Coroutines (Job/Deferred) and Swift Concurrency (Task/AsyncStream) across KMP Swift Export boundaries. Prevents uncollected Job leaks in Kotlin and unmanaged Task retain cycles in Swift by mandating explicit CancellationHandler attachments and DisposableHandle cleanup lifecycle management.
globs: **/shared/**/src/iosMain/**/*.kt, **/shared/**/src/appleMain/**/*.kt, **/iosApp/**/*.swift, **/SharedBridge/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-structured-concurrency-bridge-kotlin-multiplat-543"
---

# Bidirectional Structured Concurrency and Cancellation Propagation in KMP Swift Export

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Fire-and-forget Swift Task wrappers that orphan active Kotlin Coroutines upon Task cancellation

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform and Swift Concurrency interoperability. You enforce zero-leak lifecycle management and strict bidirectional cooperative cancellation across the Swift-Kotlin FFI boundary. Reject any unbounded GlobalScope or unmanaged Task bridging that ignores Task.isCancelled or CoroutineScope cancellation semantics.

## Strict Guidelines
- Engineers MUST ALWAYS bridge Swift 'withTaskCancellationHandler' to Kotlin 'Job.cancel()' when converting Kotlin Coroutines to Swift 'async' functions.
- Engineers MUST NOT rely on default Swift-ObjC exporter suspend-function bridging that discards Swift Task cancellation signals.
- Code SHOULD propagate Kotlin 'CancellationException' by converting it directly to Swift 'CancellationError' rather than throwing generic or wrapped NSError instances.
- Services MUST encapsulate native CoroutineScopes within lifecycle-aware holders that invoke 'scope.cancel()' upon native deinit or deallocation.
- Components NEVER capture strong references to self within Swift 'withTaskCancellationHandler' onCancel closures, preventing retain cycles.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When the calling Swift Task is cancelled, the underlying Kotlin coroutine remains active and unnotified. This causes orphaned network requests, uncollected background jobs, and memory leaks across the FFI boundary.
```swift
// BAD: Task cancellation is completely ignored; Kotlin coroutine continues executing in background
func fetchUserData(userId: String) async throws -> UserProfile {
    return try await withCheckedThrowingContinuation { continuation in
        sharedRepository.fetchUserProfile(userId: userId) { profile, error in
            if let error = error {
                continuation.resume(throwing: error)
            } else if let profile = profile {
                continuation.resume(returning: profile)
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly wraps the continuation in withTaskCancellationHandler, stores the Kotlin Job reference atomically, and triggers job.cancel() the instant the Swift Task cancels. Translates Kotlin CancellationException into Swift CancellationError.
```swift
// GOOD: Bidirectional cancellation bridge using withTaskCancellationHandler and DisposableHandle
func fetchUserData(userId: String) async throws -> UserProfile {
    let jobHolder = AtomicReference<CancellableJob?>(nil)
    
    return try await withTaskCancellationHandler {
        try Task.checkCancellation()
        return try await withCheckedThrowingContinuation { continuation in
            let job = sharedRepository.fetchUserProfileCancellable(userId: userId) { result, error in
                if let error = error {
                    if error.isKotlinCancellationException() {
                        continuation.resume(throwing: CancellationError())
                    } else {
                        continuation.resume(throwing: error)
                    }
                } else if let result = result {
                    continuation.resume(returning: result)
                }
            }
            jobHolder.value = job
            if Task.isCancelled {
                job.cancel()
            }
        }
    } onCancel: {
        jobHolder.value?.cancel()
    }
}
```

### Kotlin Flow to Swift AsyncSequence Cancellation Protocol

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The CoroutineScope is allocated without returning a handle or teardown mechanism. When the Swift consumer stops iterating or deallocates, the Flow continues emitting indefinitely.
```kotlin
// BAD: Launches detached CoroutineScope without cancellation registration from Swift
fun <T : Any> CommonFlow<T>.watch(block: (T) -> Unit) {
    val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
    scope.launch {
        [email protected] { block(it) }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Returns an explicit CancellableBridge handle to Swift. Swift can register this handle in AsyncStream.onTermination or an AsyncSequence iterator to cooperatively cancel the Kotlin coroutine upon teardown.
```kotlin
// GOOD: Exposes DisposableHandle and propagates cancellation back to Kotlin coroutine context
fun interface CancellableBridge {
    fun cancel()
}

fun <T : Any> CommonFlow<T>.watchCancellable(
    onEach: (T) -> Unit,
    onCompletion: (Throwable?) -> Unit
): CancellableBridge {
    val job = Job()
    val scope = CoroutineScope(job + Dispatchers.Main.immediate)
    scope.launch {
        try {
            [email protected] { onEach(it) }
            onCompletion(null)
        } catch (e: CancellationException) {
            onCompletion(e)
            throw e
        } catch (t: Throwable) {
            onCompletion(t)
        }
    }
    return CancellableBridge { job.cancel() }
}
```

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: Bidirectional Structured Concurrency and Cancellation Propagation in KMP Swift Export

Bidirectional Structured Concurrency and Cancellation Propagation in KMP Swift Export defines an industrial-grade behavioral standard for mobile engineering. Enforces strict cooperative cancellation bridging between Kotlin Coroutines (Job/Deferred) and Swift Concurrency (Task/AsyncStream) across KMP Swift Export boundaries. Prevents uncollected Job leaks in Kotlin and unmanaged Task retain cycles in Swift by mandating explicit CancellationHandler attachments and DisposableHandle cleanup lifecycle management. 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: Fire-and-forget Swift Task wrappers that orphan active Kotlin Coroutines upon Task cancellation 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 DriftFire-and-forget Swift Task wrappers that orphan active Kotlin Coroutines upon Task cancellationCritical
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 bridge Swift 'withTaskCancellationHandler' to Kotlin 'Job.cancel()' when converting Kotlin Coroutines to Swift 'async' functions.

Engineers MUST ALWAYS bridge Swift 'withTaskCancellationHandler' to Kotlin 'Job.cancel()' when converting Kotlin Coroutines to Swift 'async' functions.

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 rely on default Swift-ObjC exporter suspend-function bridging that discards Swift Task cancellation signals.

Engineers MUST NOT rely on default Swift-ObjC exporter suspend-function bridging that discards Swift Task cancellation signals.

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

Code SHOULD propagate Kotlin 'CancellationException' by converting it directly to Swift 'CancellationError' rather than throwing generic or wrapped NSError instances.

Code SHOULD propagate Kotlin 'CancellationException' by converting it directly to Swift 'CancellationError' rather than throwing generic or wrapped NSError instances.

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 encapsulate native CoroutineScopes within lifecycle-aware holders that invoke 'scope.cancel()' upon native deinit or deallocation.

Services MUST encapsulate native CoroutineScopes within lifecycle-aware holders that invoke 'scope.cancel()' upon native deinit or deallocation.

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 capture strong references to self within Swift 'withTaskCancellationHandler' onCancel closures, preventing retain cycles.

Components NEVER capture strong references to self within Swift 'withTaskCancellationHandler' onCancel closures, preventing 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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is Bidirectional Structured Concurrency and Cancellation Propagation in KMP Swift Export critical for AI coding assistants?

Enforces strict cooperative cancellation bridging between Kotlin Coroutines (Job/Deferred) and Swift Concurrency (Task/AsyncStream) across KMP Swift Export boundaries. Prevents uncollected Job leaks in Kotlin and unmanaged Task retain cycles in Swift by mandating explicit CancellationHandler attachments and DisposableHandle cleanup lifecycle management. 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 (Fire-and-forget Swift Task wrappers that orphan active Kotlin Coroutines upon Task cancellation) 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

Bidirectional