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

Kotlin Multiplatform Swift Concurrency Cooperative Cancellation Invariant

Mandates bidirectional cooperative cancellation across the Swift-to-Kotlin Native C-interop boundary. Every Swift Task consuming Kotlin Coroutine suspend functions or Flows must bind its lifecycle to the underlying Kotlin Job via withTaskCancellationHandler to guarantee deterministic teardown of unmanaged native allocations and background workloads.

Prohibited Anti-Pattern: Orphaned Kotlin Coroutine Jobs and Leaked Native Memory via Naive Swift Async Bridging

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Swift Concurrency Cooperative Cancellation Invariant - Mandates bidirectional cooperative cancellation across the Swift-to-Kotlin Native C-interop boundary. Every Swift Task consuming Kotlin Coroutine suspend functions or Flows must bind its lifecycle to the underlying Kotlin Job via withTaskCancellationHandler to guarantee deterministic teardown of unmanaged native allocations and background workloads.
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-concurrency-cooperative-cancellation-bridge"
---

# Kotlin Multiplatform Swift Concurrency Cooperative Cancellation Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Orphaned Kotlin Coroutine Jobs and Leaked Native Memory via Naive Swift Async Bridging

## System Constraints
You are a Principal Mobile Architect enforcing absolute lifecycle parity between Apple Swift Concurrency and Kotlin Multiplatform Coroutines. You must prevent memory leaks, abandoned network sessions, and zombie coroutines by enforcing deterministic cooperative cancellation across the Objective-C/Swift interop boundary.

## Strict Guidelines
- Engineers MUST ALWAYS wrap Kotlin suspending function calls in Swift with `withTaskCancellationHandler` when converting completions or continuations to `async`/`await`.
- Engineers MUST NOT use unmanaged `withCheckedContinuation` or `withUnsafeContinuation` without registering an immediate `onCancel` closure that invokes the underlying Kotlin `Job.cancel()` or `Cancellable.cancel()`.
- Swift asynchronous streams consuming Kotlin `Flow` instances MUST explicitly invoke `close()` or cancel the collector's underlying Kotlin `Job` upon Swift `AsyncSequence` iteration termination or consumer cancellation.
- Kotlin-facing interop layers MUST return a handle (such as `Job` or a custom `Cancellable` interface) to Swift caller wrappers rather than executing unmonitored launches on global scopes.
- Services MUST NEVER rely on Swift reference counting (ARC) or garbage collection finalizers to cancel active Kotlin Coroutine scopes.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using withCheckedThrowingContinuation without withTaskCancellationHandler creates an unmonitored coroutine job across the C-interop boundary. When the parent Swift Task cancels, fetchUser continues running in KMP until completion.
```swift
import Shared

func fetchUserData(userId: String) async throws -> UserProfile {
    // ANTI-PATTERN: Swift Task cancellation has no visibility into the Kotlin Job.
    // If the calling Swift Task is cancelled, the underlying Kotlin coroutine executes indefinitely,
    // leaking CPU cycles and network sockets.
    return try await withCheckedThrowingContinuation { continuation in
        SharedUserRepository().fetchUser(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**: withTaskCancellationHandler registers an onCancel callback executed immediately when the Swift Task is cancelled. This triggers job.cancel(), cascading cancellation through the Kotlin Coroutine hierarchy across the C-interop bridge.
```swift
import Shared

func fetchUserData(userId: String) async throws -> UserProfile {
    var job: KMPJob? = nil
    
    return try await withTaskCancellationHandler(
        operation: {
            try Task.checkCancellation()
            return try await withCheckedThrowingContinuation { continuation in
                // Shared repo returns a cancellable job handle across interop
                job = SharedUserRepository().fetchUser(userId: userId) { profile, error in
                    if let error = error {
                        continuation.resume(throwing: error)
                    } else if let profile = profile {
                        continuation.resume(returning: profile)
                    }
                }
            }
        },
        onCancel: {
            // Deterministically propagates Swift cancellation to Kotlin Job hierarchy
            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: Kotlin Multiplatform Swift Concurrency Cooperative Cancellation Invariant

Kotlin Multiplatform Swift Concurrency Cooperative Cancellation Invariant defines an industrial-grade behavioral standard for mobile engineering. Mandates bidirectional cooperative cancellation across the Swift-to-Kotlin Native C-interop boundary. Every Swift Task consuming Kotlin Coroutine suspend functions or Flows must bind its lifecycle to the underlying Kotlin Job via withTaskCancellationHandler to guarantee deterministic teardown of unmanaged native allocations and background workloads. 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: Orphaned Kotlin Coroutine Jobs and Leaked Native Memory via Naive Swift Async Bridging 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 DriftOrphaned Kotlin Coroutine Jobs and Leaked Native Memory via Naive Swift Async BridgingCritical
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 suspending function calls in Swift with `withTaskCancellationHandler` when converting completions or continuations to `async`/`await`.

Engineers MUST ALWAYS wrap Kotlin suspending function calls in Swift with `withTaskCancellationHandler` when converting completions or continuations to `async`/`await`.

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 use unmanaged `withCheckedContinuation` or `withUnsafeContinuation` without registering an immediate `onCancel` closure that invokes the underlying Kotlin `Job.cancel()` or `Cancellable.cancel()`.

Engineers MUST NOT use unmanaged `withCheckedContinuation` or `withUnsafeContinuation` without registering an immediate `onCancel` closure that invokes the underlying Kotlin `Job.cancel()` or `Cancellable.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.
3

Swift asynchronous streams consuming Kotlin `Flow` instances MUST explicitly invoke `close()` or cancel the collector's underlying Kotlin `Job` upon Swift `AsyncSequence` iteration termination or consumer cancellation.

Swift asynchronous streams consuming Kotlin `Flow` instances MUST explicitly invoke `close()` or cancel the collector's underlying Kotlin `Job` upon Swift `AsyncSequence` iteration termination or consumer cancellation.

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-facing interop layers MUST return a handle (such as `Job` or a custom `Cancellable` interface) to Swift caller wrappers rather than executing unmonitored launches on global scopes.

Kotlin-facing interop layers MUST return a handle (such as `Job` or a custom `Cancellable` interface) to Swift caller wrappers rather than executing unmonitored launches on global scopes.

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

Services MUST NEVER rely on Swift reference counting (ARC) or garbage collection finalizers to cancel active Kotlin Coroutine scopes.

Services MUST NEVER rely on Swift reference counting (ARC) or garbage collection finalizers to cancel active Kotlin Coroutine scopes.

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 Kotlin Multiplatform Swift Concurrency Cooperative Cancellation Invariant critical for AI coding assistants?

Mandates bidirectional cooperative cancellation across the Swift-to-Kotlin Native C-interop boundary. Every Swift Task consuming Kotlin Coroutine suspend functions or Flows must bind its lifecycle to the underlying Kotlin Job via withTaskCancellationHandler to guarantee deterministic teardown of unmanaged native allocations and background workloads. 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 (Orphaned Kotlin Coroutine Jobs and Leaked Native Memory via Naive Swift Async Bridging) 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

Kotlin