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

KMP Swift Concurrency Cancellation Bridge & Thread Leak Invariant

Enforces deterministic, bidirectional cancellation bridging between Kotlin Coroutines (Job) and Swift Structured Concurrency (Task/TaskGroup). Eliminates Darwin dispatch thread pool exhaustion and orphaned continuation memory leaks across the Kotlin/Native Objective-C interop boundary.

Prohibited Anti-Pattern: Dangling Swift CheckedContinuation Leaking Darwin Threads on Unbridged Kotlin Coroutine Cancellation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Swift Concurrency Cancellation Bridge & Thread Leak Invariant - Enforces deterministic, bidirectional cancellation bridging between Kotlin Coroutines (Job) and Swift Structured Concurrency (Task/TaskGroup). Eliminates Darwin dispatch thread pool exhaustion and orphaned continuation memory leaks across the Kotlin/Native Objective-C interop boundary.
globs: iosApp/**/*.{swift,h,m}, shared/src/iosMain/**/*.{kt,swift}, shared/src/commonMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-concurrency-cancellation-bridge-guardrail-kmp-swift-concur-498"
---

# KMP Swift Concurrency Cancellation Bridge & Thread Leak Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Dangling Swift CheckedContinuation Leaking Darwin Threads on Unbridged Kotlin Coroutine Cancellation

## System Constraints
You are a Principal Mobile Architect enforcing absolute memory safety and concurrency invariants across Kotlin Multiplatform (KMP) and Swift Structured Concurrency boundaries. You MUST prevent Darwin thread pool starvation and unhandled continuation retention when bridging Kotlin Jobs and Swift Tasks.

## Strict Guidelines
- Engineers MUST ALWAYS wrap Kotlin Native suspend functions or Flow collectors in Swift with `withTaskCancellationHandler` to forward Swift Task cancellations directly to the underlying Kotlin `Job.cancel(cause:)`.
- Engineers MUST NOT rely on default Kotlin-to-Objective-C async bridge generation without handling `CancellationException` translation to Swift's native `CancellationError`.
- Bridge adapters MUST guarantee that `CheckedContinuation` is resumed EXACTLY ONCE; dropping a continuation during a cancel or unhandled KMP exception permanently leaks Darwin worker threads.
- Swift `TaskGroup` child tasks consuming Kotlin Flows MUST explicitly cancel their Kotlin Collector Jobs in an `onTermination` or `defer` block before leaving scope.
- Engineers MUST NEVER dispatch asynchronous bridge callbacks onto unconfined GCD queues without thread-safe atomics or Actor isolation guarding continuation state transitions.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: If the parent Swift Task is cancelled before the Kotlin coroutine completes, the cancellation is never signaled to Kotlin. If Kotlin internally cancels or times out, the completion block is either skipped or delivers an unmapped CancellationException, leaving the Swift CheckedContinuation hanging forever and leaking a thread.
```swift
import Shared

// ANTI-PATTERN: Native suspend export invoked directly without Task cancellation hooks.
// Cancelling the enclosing Swift Task leaves the Kotlin Job running indefinitely
// and locks Darwin thread resources.
func fetchUserProfile(userId: String) async throws -> UserProfile {
    return try await withCheckedThrowingContinuation { continuation in
        UserProfileRepository().getUserProfile(id: userId) { profile, error in
            if let error = error {
                continuation.resume(throwing: error)
            } else if let profile = profile {
                continuation.resume(returning: profile)
            }
            // BUG: If Swift Task is cancelled, Kotlin job remains active.
            // If Kotlin cancels silently with CancellationException, continuation never resumes.
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The good implementation uses `withTaskCancellationHandler` to immediately cancel the Kotlin `job` when Swift initiates task cancellation, wraps references atomically to avoid data races, and translates Kotlin cancellation exceptions directly into `CancellationError` ensuring the continuation is always resumed exactly once.
```swift
import Shared

// PRODUCTION INVARIANT: Bidirectional bridge with deterministic cancellation
// and guaranteed single-resumption of Swift CheckedContinuation.
func fetchUserProfile(userId: String) async throws -> UserProfile {
    let repository = UserProfileRepository()
    let canceller = AtomicKotlinJobHolder()
    
    return try await withTaskCancellationHandler {
        try await withCheckedThrowingContinuation { continuation in
            let job = repository.getUserProfile(id: userId) { profile, error in
                canceller.clear()
                if let error = error {
                    let nsError = error as NSError
                    if nsError.isKotlinCancellationException() {
                        continuation.resume(throwing: CancellationError())
                    } else {
                        continuation.resume(throwing: error)
                    }
                } else if let profile = profile {
                    continuation.resume(returning: profile)
                } else {
                    continuation.resume(throwing: CancellationError())
                }
            }
            canceller.set(job: job)
        }
    } onCancel: {
        canceller.cancel()
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP Swift Concurrency Cancellation Bridge & Thread Leak Invariant

KMP Swift Concurrency Cancellation Bridge & Thread Leak Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic, bidirectional cancellation bridging between Kotlin Coroutines (Job) and Swift Structured Concurrency (Task/TaskGroup). Eliminates Darwin dispatch thread pool exhaustion and orphaned continuation memory leaks across the Kotlin/Native Objective-C interop boundary. 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: Dangling Swift CheckedContinuation Leaking Darwin Threads on Unbridged Kotlin Coroutine 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 DriftDangling Swift CheckedContinuation Leaking Darwin Threads on Unbridged Kotlin Coroutine 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 wrap Kotlin Native suspend functions or Flow collectors in Swift with `withTaskCancellationHandler` to forward Swift Task cancellations directly to the underlying Kotlin `Job.cancel(cause

Engineers MUST ALWAYS wrap Kotlin Native suspend functions or Flow collectors in Swift with `withTaskCancellationHandler` to forward Swift Task cancellations directly to the underlying Kotlin `Job.cancel(cause:)`.

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 Kotlin-to-Objective-C async bridge generation without handling `CancellationException` translation to Swift's native `CancellationError`.

Engineers MUST NOT rely on default Kotlin-to-Objective-C async bridge generation without handling `CancellationException` translation to Swift's native `CancellationError`.

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

Bridge adapters MUST guarantee that `CheckedContinuation` is resumed EXACTLY ONCE

Bridge adapters MUST guarantee that `CheckedContinuation` is resumed EXACTLY ONCE; dropping a continuation during a cancel or unhandled KMP exception permanently leaks Darwin worker threads.

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

Swift `TaskGroup` child tasks consuming Kotlin Flows MUST explicitly cancel their Kotlin Collector Jobs in an `onTermination` or `defer` block before leaving scope.

Swift `TaskGroup` child tasks consuming Kotlin Flows MUST explicitly cancel their Kotlin Collector Jobs in an `onTermination` or `defer` block before leaving scope.

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

Engineers MUST NEVER dispatch asynchronous bridge callbacks onto unconfined GCD queues without thread-safe atomics or Actor isolation guarding continuation state transitions.

Engineers MUST NEVER dispatch asynchronous bridge callbacks onto unconfined GCD queues without thread-safe atomics or Actor isolation guarding continuation state transitions.

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 KMP Swift Concurrency Cancellation Bridge & Thread Leak Invariant critical for AI coding assistants?

Enforces deterministic, bidirectional cancellation bridging between Kotlin Coroutines (Job) and Swift Structured Concurrency (Task/TaskGroup). Eliminates Darwin dispatch thread pool exhaustion and orphaned continuation memory leaks across the Kotlin/Native Objective-C interop boundary. 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 (Dangling Swift CheckedContinuation Leaking Darwin Threads on Unbridged Kotlin Coroutine 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

KMP