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

KMP Darwin Coroutine & Swift Task Bidirectional Cancellation Invariant

Mandates deterministic cancellation propagation and ARC-safe memory management between Kotlin Multiplatform Coroutine scopes and Darwin native Swift Concurrency/GCD tasks. Prevents orphaned Kotlin background jobs, uncancelled DispatchWorkItems, and cross-runtime retain cycles between the Kotlin/Native GC and Apple ARC runtime boundaries.

Prohibited Anti-Pattern: Unbridged Darwin Swift Task Execution Leaking Orphaning Kotlin Coroutines and Retaining ARC Boundary Closures

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Darwin Coroutine & Swift Task Bidirectional Cancellation Invariant - Mandates deterministic cancellation propagation and ARC-safe memory management between Kotlin Multiplatform Coroutine scopes and Darwin native Swift Concurrency/GCD tasks. Prevents orphaned Kotlin background jobs, uncancelled DispatchWorkItems, and cross-runtime retain cycles between the Kotlin/Native GC and Apple ARC runtime boundaries.
globs: shared/src/iosMain/**/*.kt, iosApp/**/*.swift, **/interop/**/*.swift, **/bridge/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-darwin-gcd-cancellation-bridge-guardrail"
---

# KMP Darwin Coroutine & Swift Task Bidirectional Cancellation Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbridged Darwin Swift Task Execution Leaking Orphaning Kotlin Coroutines and Retaining ARC Boundary Closures

## System Constraints
You are a Principal Mobile Architect enforcing strict Kotlin Multiplatform (KMP) Coroutine and Darwin (GCD / Swift Concurrency) interop standards. Mandate zero cross-runtime memory leaks, deterministic cancellation propagation across the Objective-C/Swift-Kotlin boundary, and strict avoidance of detached background jobs across lifecycle transitions.

## Strict Guidelines
- Engineers MUST ALWAYS bind Swift async Tasks to Kotlin Coroutine Jobs using `withTaskCancellationHandler` to forward native cancellation down to Kotlin's `Job.cancel()`.
- Engineers MUST NOT expose raw Kotlin `suspend` functions directly to Swift without explicit cancellation bridge wrappers or verified compiler plugin bridges (e.g., SKIE or custom `Cancellable` adapters).
- Swift adapters MUST capture Kotlin `Job` or `DisposableHandle` instances through non-retaining or lifecycle-bounded references to prevent cross-runtime ARC-Kotlin GC deadlocks.
- Kotlin-to-GCD bridges MUST implement `suspendCancellableCoroutine` and register `invokeOnCancellation` to explicitly cancel native `DispatchWorkItem` or `Task` references.
- Components NEVER bridge cold `Flow` instances into Swift `AsyncSequence` without handling `AsyncStream.onTermination` to cancel the underlying Kotlin `CoroutineScope`.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly calling generated Kotlin suspend wrappers from Swift async functions ignores Swift Task cancellation tokens. If the Swift Task is cancelled, the Kotlin Coroutine continues running indefinitely in its SupervisorScope, retaining parameters and leaking native runtime references.
```swift
import SharedLibrary

final class ProfileViewModel: ObservableObject {
    private let repository: UserProfileRepository
    
    init(repository: UserProfileRepository) {
        self.repository = repository
    }
    
    func loadUserProfile(userId: String) async throws -> UserProfile {
        // ANTI-PATTERN: Direct invocation of generated KMP suspend wrapper.
        // Swift Task cancellation is NOT propagated to the underlying Kotlin coroutine.
        // If the Swift view dismisses, the Kotlin coroutine continues executing,
        // causing wasted network I/O and potential cross-runtime memory leaks.
        return try await repository.fetchProfile(id: userId)
    }
}
```

#### Production Standard (Correct)
> **Standard**: Wrapping the KMP cancellable handle in `withTaskCancellationHandler` guarantees that when the calling Swift Task is aborted, the cancellation is propagated across the Darwin ABI to the underlying Kotlin Job, terminating execution immediately and releasing ARC/GC object references.
```swift
import SharedLibrary

final class ProfileViewModel: ObservableObject {
    private let repository: UserProfileRepository
    
    init(repository: UserProfileRepository) {
        self.repository = repository
    }
    
    func loadUserProfile(userId: String) async throws -> UserProfile {
        // PRODUCTION PATTERN: Explicit Swift Task cancellation bridging with reference isolation
        let handle = repository.fetchProfileCancellable(id: userId)
        
        return try await withTaskCancellationHandler {
            try Task.checkCancellation()
            return try await handle.awaitResult()
        } onCancel: {
            // Propagate Darwin cancellation deterministically across KMP boundary
            handle.cancel(cause: CancellationException(message: "Swift Task cancelled"))
        }
    }
}
```

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: KMP Darwin Coroutine & Swift Task Bidirectional Cancellation Invariant

KMP Darwin Coroutine & Swift Task Bidirectional Cancellation Invariant defines an industrial-grade behavioral standard for mobile engineering. Mandates deterministic cancellation propagation and ARC-safe memory management between Kotlin Multiplatform Coroutine scopes and Darwin native Swift Concurrency/GCD tasks. Prevents orphaned Kotlin background jobs, uncancelled DispatchWorkItems, and cross-runtime retain cycles between the Kotlin/Native GC and Apple ARC runtime boundaries. 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: Unbridged Darwin Swift Task Execution Leaking Orphaning Kotlin Coroutines and Retaining ARC Boundary Closures 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 DriftUnbridged Darwin Swift Task Execution Leaking Orphaning Kotlin Coroutines and Retaining ARC Boundary ClosuresCritical
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 async Tasks to Kotlin Coroutine Jobs using `withTaskCancellationHandler` to forward native cancellation down to Kotlin's `Job.cancel()`.

Engineers MUST ALWAYS bind Swift async Tasks to Kotlin Coroutine Jobs using `withTaskCancellationHandler` to forward native cancellation down to Kotlin's `Job.cancel()`.

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 expose raw Kotlin `suspend` functions directly to Swift without explicit cancellation bridge wrappers or verified compiler plugin bridges (e.g., SKIE or custom `Cancellable` adapters).

Engineers MUST NOT expose raw Kotlin `suspend` functions directly to Swift without explicit cancellation bridge wrappers or verified compiler plugin bridges (e.g., SKIE or custom `Cancellable` 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.
3

Swift adapters MUST capture Kotlin `Job` or `DisposableHandle` instances through non-retaining or lifecycle-bounded references to prevent cross-runtime ARC-Kotlin GC deadlocks.

Swift adapters MUST capture Kotlin `Job` or `DisposableHandle` instances through non-retaining or lifecycle-bounded references to prevent cross-runtime ARC-Kotlin GC deadlocks.

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

Kotlin-to-GCD bridges MUST implement `suspendCancellableCoroutine` and register `invokeOnCancellation` to explicitly cancel native `DispatchWorkItem` or `Task` references.

Kotlin-to-GCD bridges MUST implement `suspendCancellableCoroutine` and register `invokeOnCancellation` to explicitly cancel native `DispatchWorkItem` or `Task` references.

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 cold `Flow` instances into Swift `AsyncSequence` without handling `AsyncStream.onTermination` to cancel the underlying Kotlin `CoroutineScope`.

Components NEVER bridge cold `Flow` instances into Swift `AsyncSequence` without handling `AsyncStream.onTermination` to cancel the underlying Kotlin `CoroutineScope`.

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 Darwin Coroutine & Swift Task Bidirectional Cancellation Invariant critical for AI coding assistants?

Mandates deterministic cancellation propagation and ARC-safe memory management between Kotlin Multiplatform Coroutine scopes and Darwin native Swift Concurrency/GCD tasks. Prevents orphaned Kotlin background jobs, uncancelled DispatchWorkItems, and cross-runtime retain cycles between the Kotlin/Native GC and Apple ARC runtime boundaries. 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 (Unbridged Darwin Swift Task Execution Leaking Orphaning Kotlin Coroutines and Retaining ARC Boundary Closures) 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