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

Kotlin Multiplatform Swift Task Cancellation Boundary Guardrail

Enforces strict bidirectional cancellation propagation across the Kotlin Multiplatform Objective-C/Swift interop boundary. Prevents zombie coroutine execution, Darwin thread pool exhaustion, and memory leaks caused by uncoordinated Swift Task and Kotlin Coroutine lifecycles.

Prohibited Anti-Pattern: Unlinked Swift Continuations and Dangling Kotlin Bridge Jobs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Swift Task Cancellation Boundary Guardrail - Enforces strict bidirectional cancellation propagation across the Kotlin Multiplatform Objective-C/Swift interop boundary. Prevents zombie coroutine execution, Darwin thread pool exhaustion, and memory leaks caused by uncoordinated Swift Task and Kotlin Coroutine lifecycles.
globs: iosApp/**/*.swift, shared/src/**/*.kt, shared/src/**/*.swift, **/bridge/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-task-cancellation-boundary"
---

# Kotlin Multiplatform Swift Task Cancellation Boundary Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unlinked Swift Continuations and Dangling Kotlin Bridge Jobs

## System Constraints
You are a Principal Mobile Systems Architect specializing in Kotlin Multiplatform (KMP) and Swift Concurrency integration. Your responsibility is to strictly enforce bidirectional lifecycle and cancellation guarantees across the Obj-C/Swift interop boundary. Every asynchronous call crossing the bridge must guarantee immediate propagation of Swift Task cancellation to the underlying Kotlin Job, and propagate Kotlin CancellationException as Swift CancellationError without thread starvation or uncollected coroutine scopes.

## Strict Guidelines
- Engineers MUST ALWAYS register cancellation hooks using 'withTaskCancellationHandler' or verified toolchains (e.g., SKIE or KMP-NativeCoroutines) when wrapping Kotlin suspend functions in Swift async APIs.
- Engineers MUST ALWAYS cancel the underlying Kotlin Job when a Swift Task is cancelled, ensuring coroutine dispatchers release native worker threads immediately.
- Engineers MUST NEVER use raw 'withCheckedContinuation' without attaching a cancellation handler that actively invokes the Kotlin Job's cancellation handle.
- Code bridging Kotlin Flows to Swift 'AsyncSequence' or 'AsyncThrowingStream' MUST bind 'onTermination' to explicitly cancel the underlying Flow collector Job.
- Kotlin bridge wrappers MUST rethrow Kotlin 'CancellationException' and map it cleanly to Swift 'CancellationError', avoiding swallowing cancellations as generic runtime exceptions.
- Components NEVER bind native UI lifecycles directly to unbounded Kotlin CoroutineScopes without explicit lifecycle-aware tear-down triggers on the Swift side.

## Bad vs Good Implementations
### Bridging Kotlin Suspend Function to Swift Task with Cancellation Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to capture and invoke the Kotlin bridge handle during cancellation leaves the underlying Kotlin coroutine executing indefinitely, causing native thread starvation and unnecessary network/battery usage.
```swift
import SharedKit

func fetchUserProfile(userId: String) async throws -> UserProfile {
    // BAD: Using raw withCheckedThrowingContinuation ignores Swift Task cancellation.
    // If the caller's Task is cancelled or the SwiftUI view unmounts, the underlying
    // Kotlin coroutine runs indefinitely on the Kotlin background thread pool.
    return try await withCheckedThrowingContinuation { continuation in
        SharedUserApi().getUserProfile(id: 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**: Wrapping the continuation in 'withTaskCancellationHandler' captures the Kotlin cancellation handle and invokes 'cancel()' the instant the Swift Task is cancelled, preserving cooperative cancellation across both runtimes.
```swift
import SharedKit

func fetchUserProfile(userId: String) async throws -> UserProfile {
    // GOOD: Holds reference to Kotlin Cancellable/Job and propagates Swift Task cancellation immediately.
    var cancellableJob: SharedKit.Cancellable? = nil
    
    return try await withTaskCancellationHandler {
        try await withCheckedThrowingContinuation { continuation in
            cancellableJob = SharedUserApi().getUserProfile(id: userId) { profile, error in
                if let error = error {
                    if error._code == KotlinExceptionConstants.cancellationCode {
                        continuation.resume(throwing: CancellationError())
                    } else {
                        continuation.resume(throwing: error)
                    }
                } else if let profile = profile {
                    continuation.resume(returning: profile)
                }
            }
        }
    } onCancel: {
        cancellableJob?.cancel()
    }
}
```

### Bridging Kotlin Flow to Swift AsyncThrowingStream

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When the Swift consumer terminates or drops the AsyncThrowingStream iteration, the underlying Kotlin coroutine collector remains active and continues to pump events, causing severe memory leaks.
```swift
import SharedKit

func observeUserEvents() -> AsyncThrowingStream<UserEvent, Error> {
    // BAD: Flow collector continues indefinitely because termination callback is absent.
    return AsyncThrowingStream { continuation in
        SharedEventRepository().watchEvents().collect(
            onEach: { event in continuation.yield(event) },
            onCompletion: { error in
                if let error = error { continuation.finish(throwing: error) }
                else { continuation.finish() }
            }
        )
    }
}
```

#### Production Standard (Correct)
> **Standard**: Registering 'onTermination' ensures that when the Swift AsyncSequence is aborted or finishes early, the underlying Kotlin collection Job is promptly cancelled, stopping further event generation.
```swift
import SharedKit

func observeUserEvents() -> AsyncThrowingStream<UserEvent, Error> {
    // GOOD: Explicitly cancels the Kotlin collector job via onTermination.
    return AsyncThrowingStream { continuation in
        let collectorJob = SharedEventRepository().watchEvents().collect(
            onEach: { event in
                continuation.yield(event)
            },
            onCompletion: { error in
                if let error = error {
                    continuation.finish(throwing: error)
                } else {
                    continuation.finish()
                }
            }
        )
        
        continuation.onTermination = { @Sendable _ in
            collectorJob.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: Kotlin Multiplatform Swift Task Cancellation Boundary Guardrail

Kotlin Multiplatform Swift Task Cancellation Boundary Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict bidirectional cancellation propagation across the Kotlin Multiplatform Objective-C/Swift interop boundary. Prevents zombie coroutine execution, Darwin thread pool exhaustion, and memory leaks caused by uncoordinated Swift Task and Kotlin Coroutine lifecycles. 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: Unlinked Swift Continuations and Dangling Kotlin Bridge Jobs 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 DriftUnlinked Swift Continuations and Dangling Kotlin Bridge JobsCritical
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 register cancellation hooks using 'withTaskCancellationHandler' or verified toolchains (e.g., SKIE or KMP-NativeCoroutines) when wrapping Kotlin suspend functions in Swift async APIs.

Engineers MUST ALWAYS register cancellation hooks using 'withTaskCancellationHandler' or verified toolchains (e.g., SKIE or KMP-NativeCoroutines) when wrapping Kotlin suspend functions in Swift async APIs.

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 ALWAYS cancel the underlying Kotlin Job when a Swift Task is cancelled, ensuring coroutine dispatchers release native worker threads immediately.

Engineers MUST ALWAYS cancel the underlying Kotlin Job when a Swift Task is cancelled, ensuring coroutine dispatchers release native worker threads immediately.

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

Engineers MUST NEVER use raw 'withCheckedContinuation' without attaching a cancellation handler that actively invokes the Kotlin Job's cancellation handle.

Engineers MUST NEVER use raw 'withCheckedContinuation' without attaching a cancellation handler that actively invokes the Kotlin Job's cancellation handle.

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

Code bridging Kotlin Flows to Swift 'AsyncSequence' or 'AsyncThrowingStream' MUST bind 'onTermination' to explicitly cancel the underlying Flow collector Job.

Code bridging Kotlin Flows to Swift 'AsyncSequence' or 'AsyncThrowingStream' MUST bind 'onTermination' to explicitly cancel the underlying Flow collector Job.

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

Kotlin bridge wrappers MUST rethrow Kotlin 'CancellationException' and map it cleanly to Swift 'CancellationError', avoiding swallowing cancellations as generic runtime exceptions.

Kotlin bridge wrappers MUST rethrow Kotlin 'CancellationException' and map it cleanly to Swift 'CancellationError', avoiding swallowing cancellations as generic runtime exceptions.

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.
6

Components NEVER bind native UI lifecycles directly to unbounded Kotlin CoroutineScopes without explicit lifecycle-aware tear-down triggers on the Swift side.

Components NEVER bind native UI lifecycles directly to unbounded Kotlin CoroutineScopes without explicit lifecycle-aware tear-down triggers on the Swift side.

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 Task Cancellation Boundary Guardrail critical for AI coding assistants?

Enforces strict bidirectional cancellation propagation across the Kotlin Multiplatform Objective-C/Swift interop boundary. Prevents zombie coroutine execution, Darwin thread pool exhaustion, and memory leaks caused by uncoordinated Swift Task and Kotlin Coroutine lifecycles. 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 (Unlinked Swift Continuations and Dangling Kotlin Bridge Jobs) 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