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

KMP Structured Concurrency Bidirectional Swift Task Cancellation Bridge

Enforces strict cooperative cancellation semantics across the Kotlin Native/Objective-C/Swift interop boundary. Requires binding Kotlin Job completion handles and Swift withTaskCancellationHandler hooks to eliminate orphaned background threads, resource leaks, and uncoordinated task execution.

Prohibited Anti-Pattern: Fire-and-Forget Kotlin Coroutines Inside Unbound Swift Async Contexts Causing Zombie Executions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Structured Concurrency Bidirectional Swift Task Cancellation Bridge - Enforces strict cooperative cancellation semantics across the Kotlin Native/Objective-C/Swift interop boundary. Requires binding Kotlin Job completion handles and Swift withTaskCancellationHandler hooks to eliminate orphaned background threads, resource leaks, and uncoordinated task execution.
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-task-cancellation-bridge-standard-kmp-structured-c-258"
---

# KMP Structured Concurrency Bidirectional Swift Task Cancellation Bridge

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Fire-and-Forget Kotlin Coroutines Inside Unbound Swift Async Contexts Causing Zombie Executions

## System Constraints
You are a Principal Mobile Architect enforcing the KMP Structured Concurrency Swift Task Cancellation Bridge Standard. Mandate that every asynchronous operation crossing the KMP Swift/Kotlin boundary registers strict, reciprocal cancellation handlers using withTaskCancellationHandler and Kotlin's Job.invokeOnCompletion or Skie/KMP-NativeCoroutines equivalents. Never allow unmonitored CoroutineScopes or unbounded Swift Tasks to execute cross-boundary logic.

## Strict Guidelines
- Engineers MUST ALWAYS bind Swift `Task.isCancelled` observation to the Kotlin `Job.cancel(CancellationException)` invocation using `withTaskCancellationHandler` or an automated wrapper like SKIE.
- Engineers MUST NOT invoke Kotlin `suspend` functions directly through default Objective-C exported completion handlers without capturing and storing the returned `Cancellable` reference.
- Code SHOULD leverage SKIE (Swift-Kotlin Interop Engine) or KMP-NativeCoroutines to generate idiomatic Swift `AsyncSequence` and `async/await` adapters with baked-in cooperative cancellation.
- Services MUST ensure that if a Kotlin coroutine fails or cancels internally, the Swift continuation is resumed throwing a matching Swift `CancellationError` or domain exception immediately.
- Components NEVER bridge streaming APIs (`Flow<T>`) to Swift without wiring the consumer's iteration lifecycle to the underlying `Job` cancellation to prevent memory bloat on view dismissals.

## Bad vs Good Implementations
### Swift-to-KMP Async Suspension Cancellation Adapter

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: If the parent Swift Task is cancelled (e.g., SwiftUI view dismissal or navigation back), the Kotlin coroutine continues executing in the background, consuming CPU, bandwidth, and battery as a zombie process.
```swift
import Shared

// ANTI-PATTERN: Default Obj-C bridge completion ignores Swift Task lifecycle
func fetchUserProfile(userId: String) async throws -> UserProfile {
    return try await withCheckedThrowingContinuation { continuation in
        // The Kotlin suspend function initiates a CoroutineScope that cannot be cancelled
        UserRepositoryKt.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**: The continuation is wrapped inside withTaskCancellationHandler. As soon as the Swift Task transitions to cancelled, onCancel immediately fires, invoking the Kotlin Job's cancellation handle and tearing down the downstream coroutine hierarchy.
```swift
import Shared

// PRODUCTION INVARIANT: Cooperative cancellation wired via withTaskCancellationHandler and Job handle
func fetchUserProfile(userId: String) async throws -> UserProfile {
    var jobRef: SharedCancellable? = nil
    
    return try await withTaskCancellationHandler {
        try await withCheckedThrowingContinuation { continuation in
            jobRef = UserRepositoryBridgeKt.fetchUserProfileWithHandle(userId: userId) { profile, error in
                if let error = error {
                    continuation.resume(throwing: error)
                } else if let profile = profile {
                    continuation.resume(returning: profile)
                }
            }
        }
    } onCancel: {
        // Instantly propagates Swift cooperative cancellation to Kotlin Coroutine Job
        jobRef?.cancel()
    }
}
```

### Kotlin Side Cancellation Bridging with Skie or Custom DisposableHandle

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using GlobalScope without returning a Cancellable handle makes it impossible for the Swift consumer to propagate cancellation back into the coroutine tree.
```kotlin
// shared/src/iosMain/kotlin/UserRepositoryBridge.kt
package com.standard.kmp

import kotlinx.coroutines.*

// ANTI-PATTERN: Scope detached from lifecycle without exposing cancellation capability
fun fetchUserProfileUnsafe(userId: String, callback: (UserProfile?, Throwable?) -> Unit) {
    GlobalScope.launch {
        try {
            val profile = repository.fetch(userId)
            callback(profile, null)
        } catch (e: Throwable) {
            callback(null, e)
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Returns a SharedCancellable interface capturing the Job. Cancelling it throws a CancellationException inside the coroutine hierarchy, terminating child suspended operations cleanly.
```kotlin
// shared/src/iosMain/kotlin/UserRepositoryBridge.kt
package com.standard.kmp

import kotlinx.coroutines.*

interface SharedCancellable {
    fun cancel()
}

// PRODUCTION INVARIANT: Exposes DisposableHandle / Cancellable token bound to child Job
fun fetchUserProfileWithHandle(
    userId: String,
    callback: (UserProfile?, Throwable?) -> Unit
): SharedCancellable {
    val job = Job()
    val scope = CoroutineScope(Dispatchers.Default + job)
    
    scope.launch {
        try {
            val profile = repository.fetch(userId)
            callback(profile, null)
        } catch (e: CancellationException) {
            // Propagate cooperative cancellation correctly
            callback(null, e)
        } catch (e: Throwable) {
            callback(null, e)
        }
    }
    
    return object : SharedCancellable {
        override fun cancel() {
            job.cancel(CancellationException("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 Structured Concurrency Bidirectional Swift Task Cancellation Bridge

KMP Structured Concurrency Bidirectional Swift Task Cancellation Bridge defines an industrial-grade behavioral standard for mobile engineering. Enforces strict cooperative cancellation semantics across the Kotlin Native/Objective-C/Swift interop boundary. Requires binding Kotlin Job completion handles and Swift withTaskCancellationHandler hooks to eliminate orphaned background threads, resource leaks, and uncoordinated task execution. 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: Fire-and-Forget Kotlin Coroutines Inside Unbound Swift Async Contexts Causing Zombie Executions 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 DriftFire-and-Forget Kotlin Coroutines Inside Unbound Swift Async Contexts Causing Zombie ExecutionsCritical
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 `Task.isCancelled` observation to the Kotlin `Job.cancel(CancellationException)` invocation using `withTaskCancellationHandler` or an automated wrapper like SKIE.

Engineers MUST ALWAYS bind Swift `Task.isCancelled` observation to the Kotlin `Job.cancel(CancellationException)` invocation using `withTaskCancellationHandler` or an automated wrapper like SKIE.

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 invoke Kotlin `suspend` functions directly through default Objective-C exported completion handlers without capturing and storing the returned `Cancellable` reference.

Engineers MUST NOT invoke Kotlin `suspend` functions directly through default Objective-C exported completion handlers without capturing and storing the returned `Cancellable` reference.

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

Code SHOULD leverage SKIE (Swift-Kotlin Interop Engine) or KMP-NativeCoroutines to generate idiomatic Swift `AsyncSequence` and `async/await` adapters with baked-in cooperative cancellation.

Code SHOULD leverage SKIE (Swift-Kotlin Interop Engine) or KMP-NativeCoroutines to generate idiomatic Swift `AsyncSequence` and `async/await` adapters with baked-in cooperative 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

Services MUST ensure that if a Kotlin coroutine fails or cancels internally, the Swift continuation is resumed throwing a matching Swift `CancellationError` or domain exception immediately.

Services MUST ensure that if a Kotlin coroutine fails or cancels internally, the Swift continuation is resumed throwing a matching Swift `CancellationError` or domain exception 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.
5

Components NEVER bridge streaming APIs (`Flow<T>`) to Swift without wiring the consumer's iteration lifecycle to the underlying `Job` cancellation to prevent memory bloat on view dismissals.

Components NEVER bridge streaming APIs (`Flow<T>`) to Swift without wiring the consumer's iteration lifecycle to the underlying `Job` cancellation to prevent memory bloat on view dismissals.

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 Structured Concurrency Bidirectional Swift Task Cancellation Bridge critical for AI coding assistants?

Enforces strict cooperative cancellation semantics across the Kotlin Native/Objective-C/Swift interop boundary. Requires binding Kotlin Job completion handles and Swift withTaskCancellationHandler hooks to eliminate orphaned background threads, resource leaks, and uncoordinated task execution. 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 (Fire-and-Forget Kotlin Coroutines Inside Unbound Swift Async Contexts Causing Zombie Executions) 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