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

Deterministic Swift Task Tree & Kotlin Coroutine Scope Bridging

Enforces bidirectional, deterministic cancellation propagation and bounded backpressure between Swift Concurrency Tasks and Kotlin Multiplatform 2.1 Coroutine Scopes. Prevents orphaned zombie coroutines in the Kotlin runtime when Swift Tasks are cancelled, and eliminates unbounded memory leaks when transforming Kotlin Flows into Swift AsyncSequences.

Prohibited Anti-Pattern: Unbounded Dispatch and Fire-and-Forget Coroutine Bridging Without Cooperative Cancellation Handlers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Swift Task Tree & Kotlin Coroutine Scope Bridging - Enforces bidirectional, deterministic cancellation propagation and bounded backpressure between Swift Concurrency Tasks and Kotlin Multiplatform 2.1 Coroutine Scopes. Prevents orphaned zombie coroutines in the Kotlin runtime when Swift Tasks are cancelled, and eliminates unbounded memory leaks when transforming Kotlin Flows into Swift AsyncSequences.
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-cancellation-bridge"
---

# Deterministic Swift Task Tree & Kotlin Coroutine Scope Bridging

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Dispatch and Fire-and-Forget Coroutine Bridging Without Cooperative Cancellation Handlers

## System Constraints
You are a Principal Mobile Architect enforcing strict KMP 2.1 and Swift Structured Concurrency invariants. Reject any Swift-to-Kotlin bridging implementation that does not bind Kotlin Job cancellation deterministically to Swift Task lifecycle via cooperative cancellation handlers. Mandate bounded backpressure for all Kotlin Flow exposures to Swift AsyncSequence.

## Strict Guidelines
- Engineers MUST ALWAYS bind Swift `Task` cancellation to the underlying Kotlin `Job` using `withTaskCancellationHandler` or SKIE/KMP 2.1 cooperative Swift export bindings.
- Engineers MUST NOT invoke Kotlin suspend functions from Swift through unmanaged global dispatch or detached top-level Tasks without a parent Job cancellation hook.
- Flow bridging to Swift `AsyncSequence` MUST implement explicit bounded buffer strategies (e.g., `BufferOverflow.SUSPEND` or bounded `onBufferOverflow`) to enforce upstream Kotlin backpressure.
- Engineers MUST verify `Task.isCancelled` before initiating bridged JNI/Kotlin C-interop calls to prevent launching orphaned async work on already cancelled parent Tasks.
- Any bridged custom `AsyncIteratorProtocol` MUST explicitly invoke `job.cancel(CancellationException)` upon termination or early loop `break`.

## Bad vs Good Implementations
### Swift Task Cancellation to Kotlin Coroutine Job Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Launching an unmanaged Swift Task wrapper around a Kotlin suspend function severs structured concurrency. Swift Task cancellation does not propagate to the underlying Kotlin Job, causing zombie coroutines and resource leaks.
```swift
func observeUserProfile(userId: String) async throws -> UserProfile {
    // ANTI-PATTERN: Native Swift Task cancellation is completely ignored.
    // If the caller's Task cancels (e.g. view dismiss), the Kotlin coroutine continues executing,
    // leaking CPU cycles and network resources in the Kotlin Native runtime.
    return try await Task {
        return try await userSdk.getUserProfile(id: userId)
    }.value
}
```

#### Production Standard (Correct)
> **Standard**: Leverages withTaskCancellationHandler to guarantee that whenever the parent Swift Task is cancelled, the Kotlin Job cancellation handler is triggered immediately, freeing Kotlin Native coroutine resources deterministically.
```swift
func observeUserProfile(userId: String) async throws -> UserProfile {
    // PRODUCTION FIX: Deterministic cancellation binding with withTaskCancellationHandler
    try Task.checkCancellation()
    let canceller = AtomicKotlinJobHandle()
    
    return try await withTaskCancellationHandler {
        return try await withCheckedThrowingContinuation { continuation in
            let job = userSdk.getUserProfile(id: userId) { profile, error in
                if let error = error {
                    continuation.resume(throwing: error)
                } else if let profile = profile {
                    continuation.resume(returning: profile)
                }
            }
            canceller.set(job)
        }
    } onCancel: {
        canceller.cancel()
    }
}
```

### Kotlin Flow Backpressure Bridging to Swift AsyncSequence

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Channel.UNLIMITED removes backpressure propagation. If the iOS main actor or Swift consuming Task runs slower than the producer, memory consumption grows unbounded until jetsam kills the iOS process.
```kotlin
// shared/src/iosMain/kotlin/UserFlowAdapter.kt
// ANTI-PATTERN: Emitting unbounded Flow values without backpressure guarantees
fun <T> Flow<T>.asIosSequence(): IosFlowWrapper<T> {
    return IosFlowWrapper(this.buffer(Channel.UNLIMITED)) // Causes OOM if Swift consumer is slow
}
```

#### Production Standard (Correct)
> **Standard**: Specifying a bounded buffer capacity with BufferOverflow.SUSPEND ensures upstream Kotlin coroutines cooperatively pause execution when the Swift AsyncSequence consumer stalls, maintaining deterministic memory limits.
```kotlin
// shared/src/iosMain/kotlin/UserFlowAdapter.kt
// PRODUCTION FIX: Enforce bounded capacity and cooperative backpressure suspension
fun <T> Flow<T>.asIosBoundedSequence(capacity: Int = 16): IosFlowWrapper<T> {
    return IosFlowWrapper(
        this.buffer(
            capacity = capacity,
            onBufferOverflow = BufferOverflow.SUSPEND
        )
    )
}
```

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 Swift Task Tree & Kotlin Coroutine Scope Bridging

Deterministic Swift Task Tree & Kotlin Coroutine Scope Bridging defines an industrial-grade behavioral standard for mobile engineering. Enforces bidirectional, deterministic cancellation propagation and bounded backpressure between Swift Concurrency Tasks and Kotlin Multiplatform 2.1 Coroutine Scopes. Prevents orphaned zombie coroutines in the Kotlin runtime when Swift Tasks are cancelled, and eliminates unbounded memory leaks when transforming Kotlin Flows into Swift AsyncSequences. 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: Unbounded Dispatch and Fire-and-Forget Coroutine Bridging Without Cooperative Cancellation Handlers 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 DriftUnbounded Dispatch and Fire-and-Forget Coroutine Bridging Without Cooperative Cancellation HandlersCritical
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 the underlying Kotlin `Job` using `withTaskCancellationHandler` or SKIE/KMP 2.1 cooperative Swift export bindings.

Engineers MUST ALWAYS bind Swift `Task` cancellation to the underlying Kotlin `Job` using `withTaskCancellationHandler` or SKIE/KMP 2.1 cooperative Swift export bindings.

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 invoke Kotlin suspend functions from Swift through unmanaged global dispatch or detached top-level Tasks without a parent Job cancellation hook.

Engineers MUST NOT invoke Kotlin suspend functions from Swift through unmanaged global dispatch or detached top-level Tasks without a parent Job cancellation hook.

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

Flow bridging to Swift `AsyncSequence` MUST implement explicit bounded buffer strategies (e.g., `BufferOverflow.SUSPEND` or bounded `onBufferOverflow`) to enforce upstream Kotlin backpressure.

Flow bridging to Swift `AsyncSequence` MUST implement explicit bounded buffer strategies (e.g., `BufferOverflow.SUSPEND` or bounded `onBufferOverflow`) to enforce upstream Kotlin backpressure.

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

Engineers MUST verify `Task.isCancelled` before initiating bridged JNI/Kotlin C-interop calls to prevent launching orphaned async work on already cancelled parent Tasks.

Engineers MUST verify `Task.isCancelled` before initiating bridged JNI/Kotlin C-interop calls to prevent launching orphaned async work on already cancelled parent Tasks.

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

Any bridged custom `AsyncIteratorProtocol` MUST explicitly invoke `job.cancel(CancellationException)` upon termination or early loop `break`.

Any bridged custom `AsyncIteratorProtocol` MUST explicitly invoke `job.cancel(CancellationException)` upon termination or early loop `break`.

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 Swift Task Tree & Kotlin Coroutine Scope Bridging critical for AI coding assistants?

Enforces bidirectional, deterministic cancellation propagation and bounded backpressure between Swift Concurrency Tasks and Kotlin Multiplatform 2.1 Coroutine Scopes. Prevents orphaned zombie coroutines in the Kotlin runtime when Swift Tasks are cancelled, and eliminates unbounded memory leaks when transforming Kotlin Flows into Swift AsyncSequences. 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 (Unbounded Dispatch and Fire-and-Forget Coroutine Bridging Without Cooperative Cancellation Handlers) 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