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

Kotlin Multiplatform to Swift Coroutines Bridge Concurrency Guardrail

Enforces strict cancellation propagation and retain-cycle elimination across the Kotlin/Native Objective-C and Swift concurrency boundary. Prevents unhandled Kotlin CancellationException crashes in Swift async contexts and eliminates zombie coroutines holding strong references across the ARC and Kotlin GC boundary.

Prohibited Anti-Pattern: Unbridged Swift Tasks Leaking Kotlin Coroutine Jobs and Crashing on CancellationException

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform to Swift Coroutines Bridge Concurrency Guardrail - Enforces strict cancellation propagation and retain-cycle elimination across the Kotlin/Native Objective-C and Swift concurrency boundary. Prevents unhandled Kotlin CancellationException crashes in Swift async contexts and eliminates zombie coroutines holding strong references across the ARC and Kotlin GC boundary.
globs: **/*.kt, **/*.swift, **/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-interop-guardrail"
---

# Kotlin Multiplatform to Swift Coroutines Bridge Concurrency Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbridged Swift Tasks Leaking Kotlin Coroutine Jobs and Crashing on CancellationException

## System Constraints
You are a Principal Mobile Architect enforcing rock-solid concurrency safety across the Kotlin Multiplatform (KMP) and Swift native runtime bridge. You must enforce explicit coroutine cancellation plumbing via Swift Task cancellation handlers or validated bridging libraries (e.g., SKIE or KMP-NativeCoroutines), prevent unhandled CancellationException traps, and mandate lifecycle-bound scope disposal to eliminate cross-runtime ARC-to-Kotlin-GC retain cycles.

## Strict Guidelines
- Engineers MUST ALWAYS tie Swift Task cancellation to underlying Kotlin Job cancellation using `withTaskCancellationHandler` or SKIE-generated async wrappers.
- Engineers MUST NEVER expose bare Kotlin Flow instances directly to Swift without an explicit cancellation token or a lifecycle-aware collector wrapper.
- Engineers MUST ALWAYS intercept `kotlinx.coroutines.CancellationException` at the interop boundary to prevent unhandled NSError conversions from terminating the Swift process.
- Engineers MUST NEVER capture strong references to Swift view models or controllers within long-running Kotlin coroutine callbacks crossing the interop boundary.
- Shared Kotlin components MUST expose an explicit `close()` or `cancel()` lifecycle method for any `CoroutineScope` retained on the Swift side.
- Engineers SHOULD use SKIE or KMP-NativeCoroutines to generate idiomatic Swift async/await signatures instead of manually invoking Objective-C completion handlers.

## Bad vs Good Implementations
### Bridging Swift Task Cancellation to Kotlin Coroutine Job

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin coroutines invoked through unbridged completion handlers do not listen to Swift Task cancellation. When the SwiftUI view dismisses, the Kotlin coroutine continues executing, wasting battery and network resources while potentially crashing when attempting to access deallocated Swift instances.
```swift
// BAD: Direct completion handler wrapping without cancellation plumbing.
// If Swift Task is cancelled, the Kotlin Job continues indefinitely,
// leaking memory and firing stale closures into deallocated Swift callers.
func fetchUserProfile(userId: String) async throws -> UserProfile {
    return try await withCheckedThrowingContinuation { continuation in
        sharedRepository.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**: The good implementation intercepts Swift Task cancellation via `withTaskCancellationHandler` and invokes `.cancel()` on the Kotlin `Job` reference. It also gracefully translates Kotlin's `CancellationException` into Swift's standard `CancellationError` rather than propagating an unhandled error.
```swift
// GOOD: Explicit cancellation propagation using withTaskCancellationHandler and Job handle.
// Ensures Swift Task cancellation instantly cancels the Kotlin Coroutine Job.
func fetchUserProfile(userId: String) async throws -> UserProfile {
    let cancellableWrapper = CancellableTaskRef()
    
    return try await withTaskCancellationHandler {
        try await withCheckedThrowingContinuation { continuation in
            let job = sharedRepository.getUserProfile(id: userId) { profile, error in
                if let error = error {
                    let nsError = error as NSError
                    // Treat Kotlin CancellationException as Swift CancellationError
                    if nsError.domain == "KotlinException" && nsError.userInfo["KotlinExceptionType"] as? String == "kotlinx.coroutines.CancellationException" {
                        continuation.resume(throwing: CancellationError())
                    } else {
                        continuation.resume(throwing: error)
                    }
                } else if let profile = profile {
                    continuation.resume(returning: profile)
                }
            }
            cancellableWrapper.set(job)
        }
    } onCancel: {
        cancellableWrapper.cancel()
    }
}
```

### Kotlin Boundary Safe Flow Exposure to Swift Interop

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Raw Flow interfaces exported over Kotlin/Native Objective-C bridges lack automatic cancellation semantics for Swift callers, resulting in orphan collectors that survive across screen transitions.
```kotlin
// BAD: Exposing raw StateFlow or SharedFlow without interop scope management.
// Consuming this in Swift via Objective-C generics results in permanent subscriptions
// and memory leaks because Swift cannot natively cancel Kotlin flow collection.
class UserSessionManager {
    val sessionState: StateFlow<SessionStatus> = MutableStateFlow(SessionStatus.Idle)
    
    // Swift directly calls sessionState.collect(...) -> leaks Job reference!
}
```

#### Production Standard (Correct)
> **Standard**: Encapsulating the Flow collection within an explicit subscription method that requires a bound CoroutineScope and returns a CancellableHandle enables Swift clients to tie the collection directly to a Swift view lifecycle or Task deinit.
```kotlin
// GOOD: Expose a controlled subscription bridge returning a Closeable/Cancellable handle.
class UserSessionManager {
    private val _sessionState = MutableStateFlow<SessionStatus>(SessionStatus.Idle)
    val sessionState: StateFlow<SessionStatus> = _sessionState.asStateFlow()

    fun subscribeSessionState(
        scope: CoroutineScope,
        onEach: (SessionStatus) -> Unit
    ): CancellableHandle {
        val job = _sessionState
            .onEach { onEach(it) }
            .launchIn(scope)
            
        return CancellableHandle { job.cancel() }
    }
}

fun interface CancellableHandle {
    fun 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 to Swift Coroutines Bridge Concurrency Guardrail

Kotlin Multiplatform to Swift Coroutines Bridge Concurrency Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict cancellation propagation and retain-cycle elimination across the Kotlin/Native Objective-C and Swift concurrency boundary. Prevents unhandled Kotlin CancellationException crashes in Swift async contexts and eliminates zombie coroutines holding strong references across the ARC and Kotlin GC boundary. 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: Unbridged Swift Tasks Leaking Kotlin Coroutine Jobs and Crashing on CancellationException 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 DriftUnbridged Swift Tasks Leaking Kotlin Coroutine Jobs and Crashing on CancellationExceptionCritical
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 tie Swift Task cancellation to underlying Kotlin Job cancellation using `withTaskCancellationHandler` or SKIE-generated async wrappers.

Engineers MUST ALWAYS tie Swift Task cancellation to underlying Kotlin Job cancellation using `withTaskCancellationHandler` or SKIE-generated async 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.
2

Engineers MUST NEVER expose bare Kotlin Flow instances directly to Swift without an explicit cancellation token or a lifecycle-aware collector wrapper.

Engineers MUST NEVER expose bare Kotlin Flow instances directly to Swift without an explicit cancellation token or a lifecycle-aware collector wrapper.

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 intercept `kotlinx.coroutines.CancellationException` at the interop boundary to prevent unhandled NSError conversions from terminating the Swift process.

Engineers MUST ALWAYS intercept `kotlinx.coroutines.CancellationException` at the interop boundary to prevent unhandled NSError conversions from terminating the Swift process.

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

Engineers MUST NEVER capture strong references to Swift view models or controllers within long-running Kotlin coroutine callbacks crossing the interop boundary.

Engineers MUST NEVER capture strong references to Swift view models or controllers within long-running Kotlin coroutine callbacks crossing the interop boundary.

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

Shared Kotlin components MUST expose an explicit `close()` or `cancel()` lifecycle method for any `CoroutineScope` retained on the Swift side.

Shared Kotlin components MUST expose an explicit `close()` or `cancel()` lifecycle method for any `CoroutineScope` retained 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.
6

Engineers SHOULD use SKIE or KMP-NativeCoroutines to generate idiomatic Swift async/await signatures instead of manually invoking Objective-C completion handlers.

Engineers SHOULD use SKIE or KMP-NativeCoroutines to generate idiomatic Swift async/await signatures instead of manually invoking Objective-C completion handlers.

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 to Swift Coroutines Bridge Concurrency Guardrail critical for AI coding assistants?

Enforces strict cancellation propagation and retain-cycle elimination across the Kotlin/Native Objective-C and Swift concurrency boundary. Prevents unhandled Kotlin CancellationException crashes in Swift async contexts and eliminates zombie coroutines holding strong references across the ARC and Kotlin GC boundary. 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 (Unbridged Swift Tasks Leaking Kotlin Coroutine Jobs and Crashing on CancellationException) 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