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

KMP Swift Concurrency Bidirectional Cancellation Propagation Standard

Mandates deterministic, non-blocking cooperative cancellation propagation between Swift Tasks and Kotlin Multiplatform CoroutineScopes across the foreign function interface. Prevents orphaned background compute, unbounded memory leaks, and actor thread-pool deadlocks caused by unbridged async continuations.

Prohibited Anti-Pattern: Bridging Kotlin Suspend Functions into Swift Async/Await via Raw Continuations Without Cancellation Handlers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Swift Concurrency Bidirectional Cancellation Propagation Standard - Mandates deterministic, non-blocking cooperative cancellation propagation between Swift Tasks and Kotlin Multiplatform CoroutineScopes across the foreign function interface. Prevents orphaned background compute, unbounded memory leaks, and actor thread-pool deadlocks caused by unbridged async continuations.
globs: iosApp/**/*.swift, shared/src/commonMain/**/*.kt, shared/src/iosMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-concurrency-bidirectional-cancellation-propagation-standard"
---

# KMP Swift Concurrency Bidirectional Cancellation Propagation Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Bridging Kotlin Suspend Functions into Swift Async/Await via Raw Continuations Without Cancellation Handlers

## System Constraints
You are a Principal Mobile Architect enforcing strict bidirectional cancellation propagation across Kotlin Multiplatform and Swift Concurrency boundaries. You must prohibit unmanaged continuations, ensure Swift Tasks cancel underlying Kotlin Jobs immediately, and verify Kotlin CancellationExceptions map cleanly to Swift CancellationErrors without thread-blocking.

## Strict Guidelines
- Engineers MUST ALWAYS wrap manual Swift async bridges with `withTaskCancellationHandler` to forward Swift `Task.cancel()` directly to the underlying Kotlin `Job.cancel()` or custom cancellation token.
- Engineers MUST NOT bridge Kotlin suspend functions to Swift using isolated `withCheckedContinuation` or `withCheckedThrowingContinuation` without binding an active `onCancel` closure.
- Engineers MUST ALWAYS translate Kotlin `kotlinx.coroutines.CancellationException` into Swift `CancellationError()` rather than wrapping it in generic domain error types.
- Code SHOULD rely on battle-tested compiler plugins like SKIE or KMP-NativeCoroutines for automated cancellation contract generation rather than hand-rolled Objective-C continuation wrappers.
- Services MUST ensure shared Kotlin routines periodically invoke `ensureActive()`, `yield()`, or cooperative suspension points to guarantee cancellation responsiveness during CPU-bound tasks.
- Components NEVER execute blocking operations (e.g., `runBlocking`, dispatch semaphores, or locks) across the interop boundary to await cancellation confirmation, avoiding Swift cooperative thread-pool exhaustion.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When the calling Swift Task is cancelled (e.g., user navigates away and view disappears), the continuation does not register a cancellation handler. The underlying Kotlin coroutine remains active in background dispatchers, causing orphaned work and delayed memory deallocation.
```swift
// BAD: Naive continuation bridge that ignores Swift Task cancellation.
// If the Swift Task is cancelled, the Kotlin coroutine continues executing in the background,
// wasting CPU/network resources and holding references to deallocated UI controllers.
func fetchUserProfile(userId: String) async throws -> UserProfile {
    return try await withCheckedThrowingContinuation { continuation in
        sharedRepository.fetchUserProfile(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**: Uses withTaskCancellationHandler to bind Swift Task lifecycle to the returned Kotlin job handle. If Swift cancels, the job cancels immediately, preventing orphaned work. Kotlin cancellation exceptions are properly converted to Swift CancellationError.
```swift
// GOOD: Bidirectional cancellation bridge via withTaskCancellationHandler.
// Swift Task cancellation immediately invokes job.cancel(), stopping Kotlin execution.
func fetchUserProfile(userId: String) async throws -> UserProfile {
    var kotlinJob: SharedCancellable? = nil
    
    return try await withTaskCancellationHandler {
        try await withCheckedThrowingContinuation { continuation in
            // Guard against suspension if Task was cancelled prior to bridge entry
            if Task.isCancelled {
                continuation.resume(throwing: CancellationError())
                return
            }
            
            kotlinJob = sharedRepository.fetchUserProfile(userId: userId) { profile, error in
                if let error = error {
                    if error is KotlinCoroutinesCancellationException {
                        continuation.resume(throwing: CancellationError())
                    } else {
                        continuation.resume(throwing: error)
                    }
                } else if let profile = profile {
                    continuation.resume(returning: profile)
                }
            }
        }
    } onCancel: {
        // Immediate non-blocking forward propagation into Kotlin runtime
        kotlinJob?.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: KMP Swift Concurrency Bidirectional Cancellation Propagation Standard

KMP Swift Concurrency Bidirectional Cancellation Propagation Standard defines an industrial-grade behavioral standard for mobile engineering. Mandates deterministic, non-blocking cooperative cancellation propagation between Swift Tasks and Kotlin Multiplatform CoroutineScopes across the foreign function interface. Prevents orphaned background compute, unbounded memory leaks, and actor thread-pool deadlocks caused by unbridged async continuations. 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: Bridging Kotlin Suspend Functions into Swift Async/Await via Raw Continuations Without 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 DriftBridging Kotlin Suspend Functions into Swift Async/Await via Raw Continuations Without 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 wrap manual Swift async bridges with `withTaskCancellationHandler` to forward Swift `Task.cancel()` directly to the underlying Kotlin `Job.cancel()` or custom cancellation token.

Engineers MUST ALWAYS wrap manual Swift async bridges with `withTaskCancellationHandler` to forward Swift `Task.cancel()` directly to the underlying Kotlin `Job.cancel()` or custom cancellation token.

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 bridge Kotlin suspend functions to Swift using isolated `withCheckedContinuation` or `withCheckedThrowingContinuation` without binding an active `onCancel` closure.

Engineers MUST NOT bridge Kotlin suspend functions to Swift using isolated `withCheckedContinuation` or `withCheckedThrowingContinuation` without binding an active `onCancel` closure.

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 ALWAYS translate Kotlin `kotlinx.coroutines.CancellationException` into Swift `CancellationError()` rather than wrapping it in generic domain error types.

Engineers MUST ALWAYS translate Kotlin `kotlinx.coroutines.CancellationException` into Swift `CancellationError()` rather than wrapping it in generic domain error types.

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 SHOULD rely on battle-tested compiler plugins like SKIE or KMP-NativeCoroutines for automated cancellation contract generation rather than hand-rolled Objective-C continuation wrappers.

Code SHOULD rely on battle-tested compiler plugins like SKIE or KMP-NativeCoroutines for automated cancellation contract generation rather than hand-rolled Objective-C continuation wrappers.

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 ensure shared Kotlin routines periodically invoke `ensureActive()`, `yield()`, or cooperative suspension points to guarantee cancellation responsiveness during CPU-bound tasks.

Services MUST ensure shared Kotlin routines periodically invoke `ensureActive()`, `yield()`, or cooperative suspension points to guarantee cancellation responsiveness during CPU-bound 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.
6

Components NEVER execute blocking operations (e.g., `runBlocking`, dispatch semaphores, or locks) across the interop boundary to await cancellation confirmation, avoiding Swift cooperative thread-pool exhaustion.

Components NEVER execute blocking operations (e.g., `runBlocking`, dispatch semaphores, or locks) across the interop boundary to await cancellation confirmation, avoiding Swift cooperative thread-pool exhaustion.

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 Bidirectional Cancellation Propagation Standard critical for AI coding assistants?

Mandates deterministic, non-blocking cooperative cancellation propagation between Swift Tasks and Kotlin Multiplatform CoroutineScopes across the foreign function interface. Prevents orphaned background compute, unbounded memory leaks, and actor thread-pool deadlocks caused by unbridged async continuations. 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 (Bridging Kotlin Suspend Functions into Swift Async/Await via Raw Continuations Without 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

KMP