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

Kotlin Multiplatform Swift-Coroutines Interop Cancellation Invariants

Enforces strict structured concurrency bridging between Kotlin Coroutines and Swift async/await concurrency models in Kotlin Multiplatform projects. Bridging layers must bind Swift Task cancellation tokens directly to Kotlin Job cancellation and avoid unbound GlobalScope allocations or untracked async wrappers. Failure to preserve bidirectional cancellation leads to zombie coroutines, thread pool exhaustion, memory leaks, and severe iOS UI freezes.

Prohibited Anti-Pattern: Leaking zombie Kotlin Coroutine Jobs across the ObjC/Swift interop barrier when Swift async Tasks are cancelled.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Swift-Coroutines Interop Cancellation Invariants - Enforces strict structured concurrency bridging between Kotlin Coroutines and Swift async/await concurrency models in Kotlin Multiplatform projects. Bridging layers must bind Swift Task cancellation tokens directly to Kotlin Job cancellation and avoid unbound GlobalScope allocations or untracked async wrappers. Failure to preserve bidirectional cancellation leads to zombie coroutines, thread pool exhaustion, memory leaks, and severe iOS UI freezes.
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-coroutines-cancellation-invariants"
---

# Kotlin Multiplatform Swift-Coroutines Interop Cancellation Invariants

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Leaking zombie Kotlin Coroutine Jobs across the ObjC/Swift interop barrier when Swift async Tasks are cancelled.

## System Constraints
You are a Principal Mobile Architect enforcing Kotlin Multiplatform (KMP) Swift-Coroutines Interop Cancellation Invariants. You must ensure that every suspend function or Flow exported to Swift via Objective-C interop establishes deterministic, bidirectional cancellation propagation with Swift's async/await Task system. Prevent unmanaged Job allocations, unhandled CancellationException swallowing, and disconnected async wrappers that leak native resources on Apple platforms.

## Strict Guidelines
- Engineers MUST ALWAYS wrap Swift async calls to Kotlin suspend functions inside `withTaskCancellationHandler` to explicitly invoke `job.cancel()` upon Swift Task cancellation.
- Engineers MUST NOT swallow `kotlinx.coroutines.CancellationException` in Kotlin code or catch general `Throwable` / `Exception` without re-throwing `CancellationException`.
- Code consuming Kotlin Flows in Swift MUST use SKIE-generated async sequences or an explicit `Task` lifecycle-bound collector that releases the Kotlin CoroutineScope when the enclosing Swift view or controller deallocates.
- Services MUST NEVER expose `GlobalScope` or unbound `CoroutineScope` invocations to Swift callers without returning a disposable handle or `Job` reference.
- Components NEVER execute long-running Kotlin loops or non-cancellable blocking operations without periodic `ensureActive()` or `yield()` invocations inside shared code.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Default Swift-to-Kotlin Objective-C interop suspend bridges create an underlying coroutine that does not listen to parent Swift Task cancellation unless explicitly hooked via SKIE or explicit TaskCancellationHandler.
```swift
// BAD: Direct invocation without cancellation propagation
func loadProfile(userId: String) async throws -> UserProfile {
    // When the calling Swift Task is cancelled, the underlying Kotlin coroutine
    // continues running in the background until completion, leaking network and memory.
    return try await ProfileRepository().fetchUserProfile(userId: userId)
}
```

#### Production Standard (Correct)
> **Standard**: The Swift Task cancellation handler actively signals the Kotlin Job to cancel, terminating the underlying coroutine immediately when the view disappears or the parent Task aborts.
```swift
// GOOD: Explicit cancellation wiring or SKIE-enabled cancellation support
func loadProfile(userId: String) async throws -> UserProfile {
    let repo = ProfileRepository()
    var activeJob: SharedJob? = nil
    
    return try await withTaskCancellationHandler {
        try await repo.fetchUserProfile(userId: userId, onJobCreated: { job in
            activeJob = job
        })
    } onCancel: {
        activeJob?.cancel(cause: nil)
    }
}
```

### Preserving CancellationException in Common Kotlin Multiplatform Code

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Kotlin Coroutines, cancellation is cooperative and propagated via CancellationException (a subclass of IllegalStateException/Exception). Catching generic Exception prevents the parent Job from identifying cancellation.
```kotlin
// BAD: Catching generic Exception or Throwable swallows CancellationException
suspend fun fetchUserProfile(userId: String): UserProfile {
    return try {
        apiClient.get("/users/$userId")
    } catch (e: Exception) {
        // Swallows CancellationException, preventing coroutine tree cancellation
        logger.log("Fetch failed: ${e.message}")
        UserProfile.EMPTY
    }
}
```

#### Production Standard (Correct)
> **Standard**: Re-throwing CancellationException preserves cooperative cancellation, allowing the interop bridge and parent CoroutineScope to release resources properly.
```kotlin
// GOOD: Re-throwing CancellationException to guarantee structured concurrency
suspend fun fetchUserProfile(userId: String): UserProfile {
    return try {
        apiClient.get("/users/$userId")
    } catch (e: CancellationException) {
        throw e
    } catch (e: Exception) {
        logger.log("Fetch failed: ${e.message}")
        UserProfile.EMPTY
    }
}
```

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-Coroutines Interop Cancellation Invariants

Kotlin Multiplatform Swift-Coroutines Interop Cancellation Invariants defines an industrial-grade behavioral standard for mobile engineering. Enforces strict structured concurrency bridging between Kotlin Coroutines and Swift async/await concurrency models in Kotlin Multiplatform projects. Bridging layers must bind Swift Task cancellation tokens directly to Kotlin Job cancellation and avoid unbound GlobalScope allocations or untracked async wrappers. Failure to preserve bidirectional cancellation leads to zombie coroutines, thread pool exhaustion, memory leaks, and severe iOS UI freezes. 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: Leaking zombie Kotlin Coroutine Jobs across the ObjC/Swift interop barrier when Swift async Tasks are cancelled. 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 DriftLeaking zombie Kotlin Coroutine Jobs across the ObjC/Swift interop barrier when Swift async Tasks are cancelled.Critical
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 Swift async calls to Kotlin suspend functions inside `withTaskCancellationHandler` to explicitly invoke `job.cancel()` upon Swift Task cancellation.

Engineers MUST ALWAYS wrap Swift async calls to Kotlin suspend functions inside `withTaskCancellationHandler` to explicitly invoke `job.cancel()` upon Swift Task 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.
2

Engineers MUST NOT swallow `kotlinx.coroutines.CancellationException` in Kotlin code or catch general `Throwable` / `Exception` without re-throwing `CancellationException`.

Engineers MUST NOT swallow `kotlinx.coroutines.CancellationException` in Kotlin code or catch general `Throwable` / `Exception` without re-throwing `CancellationException`.

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 consuming Kotlin Flows in Swift MUST use SKIE-generated async sequences or an explicit `Task` lifecycle-bound collector that releases the Kotlin CoroutineScope when the enclosing Swift view or controller deallocates.

Code consuming Kotlin Flows in Swift MUST use SKIE-generated async sequences or an explicit `Task` lifecycle-bound collector that releases the Kotlin CoroutineScope when the enclosing Swift view or controller deallocates.

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 NEVER expose `GlobalScope` or unbound `CoroutineScope` invocations to Swift callers without returning a disposable handle or `Job` reference.

Services MUST NEVER expose `GlobalScope` or unbound `CoroutineScope` invocations to Swift callers without returning a disposable handle or `Job` 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.
5

Components NEVER execute long-running Kotlin loops or non-cancellable blocking operations without periodic `ensureActive()` or `yield()` invocations inside shared code.

Components NEVER execute long-running Kotlin loops or non-cancellable blocking operations without periodic `ensureActive()` or `yield()` invocations inside shared code.

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-Coroutines Interop Cancellation Invariants critical for AI coding assistants?

Enforces strict structured concurrency bridging between Kotlin Coroutines and Swift async/await concurrency models in Kotlin Multiplatform projects. Bridging layers must bind Swift Task cancellation tokens directly to Kotlin Job cancellation and avoid unbound GlobalScope allocations or untracked async wrappers. Failure to preserve bidirectional cancellation leads to zombie coroutines, thread pool exhaustion, memory leaks, and severe iOS UI freezes. 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 (Leaking zombie Kotlin Coroutine Jobs across the ObjC/Swift interop barrier when Swift async Tasks are cancelled.) 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