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

KMP to Swift Concurrency Bidirectional Memory and Cancellation Bridge

Enforces deterministic threading, actor isolation, and cooperative cancellation between Kotlin Coroutines and Swift Concurrency. Eliminates memory leaks, cross-thread race conditions, and deadlocks arising from uncoordinated bridging between Kotlin/Native memory runtimes and Swift Tasks.

Prohibited Anti-Pattern: Unconfined Suspend Bridging and Unbounded Main-Thread Blocking Across the KMP-Swift FFI Boundary

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP to Swift Concurrency Bidirectional Memory and Cancellation Bridge - Enforces deterministic threading, actor isolation, and cooperative cancellation between Kotlin Coroutines and Swift Concurrency. Eliminates memory leaks, cross-thread race conditions, and deadlocks arising from uncoordinated bridging between Kotlin/Native memory runtimes and Swift Tasks.
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-memory-model-guardrail"
---

# KMP to Swift Concurrency Bidirectional Memory and Cancellation Bridge

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unconfined Suspend Bridging and Unbounded Main-Thread Blocking Across the KMP-Swift FFI Boundary

## System Constraints
You are a Principal Mobile Architect enforcing Kotlin Multiplatform (KMP) and Swift Concurrency memory model safety. You strictly prohibit unmanaged completion-handler suspension bridges, uncoordinated Task cancellation, and blocking coroutines on Swift Actors. You must guarantee bidirectional cancellation propagation, actor isolation adherence, and explicit dispatcher confinement across the Foreign Function Interface (FFI).

## Strict Guidelines
- Engineers MUST ALWAYS wrap Kotlin suspend interop in Swift `withTaskCancellationHandler` or leverage SKIE (Swift-Kotlin Interface Enhancer) to propagate Swift Task cancellation to Kotlin `Job.cancel()`.
- Engineers MUST NOT invoke `runBlocking` on the iOS Main Thread (`DispatchQueue.main` or `@MainActor`) under any circumstance to avoid immediate thread starvation and deadlocks.
- Code MUST explicitly specify Kotlin Coroutine Dispatchers (`Dispatchers.Default`, `Dispatchers.Main.immediate`) on exported Kotlin interfaces rather than relying on `Dispatchers.Unconfined` across the Objective-C/Swift bridge.
- Services MUST ensure Swift modern actors do not pass mutable state by reference across the Kotlin boundary without value-type freezing or copy-on-write semantics.
- Components NEVER hold non-weak references to Swift Task handles inside long-lived Kotlin CoroutineScopes or Singletons, preventing memory retention cycles.

## Bad vs Good Implementations
### Swift Bridge for Kotlin Suspend Interop with Bidirectional Cancellation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin's generated Objective-C completion handler ignores parent Swift Task cancellation. If the Swift Task is cancelled, the Kotlin coroutine continues executing in the background, wasting CPU/network and leaking references across the native runtime.
```swift
// BAD: Ignores Swift Task cancellation and risks context leaks across the FFI
func fetchUserData(userId: String) async throws -> UserProfile {
    return try await withCheckedThrowingContinuation { continuation in
        // Direct call to Kotlin suspend interop generated completion handler
        UserRepositoryCompanion.shared.fetchUser(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**: Explicitly captures the Kotlin Coroutine Job handle and triggers `cancel()` immediately when the enclosing Swift Task is cancelled. Guarantees structured concurrency across the KMP-Swift boundary without dangling executions.
```swift
// GOOD: Bidirectional cancellation bridge binding Swift Task to Kotlin Job
@MainActor
func fetchUserData(userId: String) async throws -> UserProfile {
    var jobRef: Kotlinx_coroutines_coreJob?
    
    return try await withTaskCancellationHandler {
        try await withCheckedThrowingContinuation { continuation in
            jobRef = UserRepositoryCompanion.shared.fetchUserCancellable(
                id: userId,
                onSuccess: { profile in continuation.resume(returning: profile) },
                onError: { error in continuation.resume(throwing: error) }
            )
        }
    } onCancel: {
        // Cooperative cancellation dispatched across the FFI boundary
        jobRef?.cancel(cause: nil)
    }
}
```

### Kotlin Dispatcher Confinement for iOS Boundary Entry Points

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using `Dispatchers.Unconfined` allows resumption on arbitrary thread pools, triggering Swift Actor reentrancy violations or unexpected thread context switches when calling back into Swift code.
```kotlin
// BAD: Relies on default context or Unconfined, risking execution on unknown Apple threads
class UserRepository : KmpRepository {
    private val scope = CoroutineScope(Dispatchers.Unconfined)

    fun fetchUser(id: String, callback: (UserProfile?, Exception?) -> Unit) {
        scope.launch {
            val data = networkClient.fetch(id) // Suspends and resumes on arbitrary thread
            callback(data, null)
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Uses `Dispatchers.Default` for non-blocking computation, returns the `Job` to Swift for cancellation lifecycle control, and marshals callbacks back to `Dispatchers.Main.immediate` to align with Swift's `@MainActor` expectation.
```kotlin
// GOOD: Explicitly confined dispatcher with structured cancellation handle
class UserRepository : KmpRepository {
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)

    fun fetchUserCancellable(
        id: String,
        onSuccess: (UserProfile) -> Unit,
        onError: (Exception) -> Unit
    ): Job {
        return scope.launch {
            try {
                val data = networkClient.fetch(id)
                withContext(Dispatchers.Main.immediate) {
                    onSuccess(data)
                }
            } catch (e: Exception) {
                if (e is CancellationException) throw e
                withContext(Dispatchers.Main.immediate) {
                    onError(e)
                }
            }
        }
    }
}
```

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 to Swift Concurrency Bidirectional Memory and Cancellation Bridge

KMP to Swift Concurrency Bidirectional Memory and Cancellation Bridge defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic threading, actor isolation, and cooperative cancellation between Kotlin Coroutines and Swift Concurrency. Eliminates memory leaks, cross-thread race conditions, and deadlocks arising from uncoordinated bridging between Kotlin/Native memory runtimes and Swift Tasks. 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: Unconfined Suspend Bridging and Unbounded Main-Thread Blocking Across the KMP-Swift FFI Boundary 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 DriftUnconfined Suspend Bridging and Unbounded Main-Thread Blocking Across the KMP-Swift FFI BoundaryCritical
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 Kotlin suspend interop in Swift `withTaskCancellationHandler` or leverage SKIE (Swift-Kotlin Interface Enhancer) to propagate Swift Task cancellation to Kotlin `Job.cancel()`.

Engineers MUST ALWAYS wrap Kotlin suspend interop in Swift `withTaskCancellationHandler` or leverage SKIE (Swift-Kotlin Interface Enhancer) to propagate Swift Task cancellation to Kotlin `Job.cancel()`.

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 `runBlocking` on the iOS Main Thread (`DispatchQueue.main` or `@MainActor`) under any circumstance to avoid immediate thread starvation and deadlocks.

Engineers MUST NOT invoke `runBlocking` on the iOS Main Thread (`DispatchQueue.main` or `@MainActor`) under any circumstance to avoid immediate thread starvation and deadlocks.

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 MUST explicitly specify Kotlin Coroutine Dispatchers (`Dispatchers.Default`, `Dispatchers.Main.immediate`) on exported Kotlin interfaces rather than relying on `Dispatchers.Unconfined` across the Objective-C/Swift bridge.

Code MUST explicitly specify Kotlin Coroutine Dispatchers (`Dispatchers.Default`, `Dispatchers.Main.immediate`) on exported Kotlin interfaces rather than relying on `Dispatchers.Unconfined` across the Objective-C/Swift bridge.

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 Swift modern actors do not pass mutable state by reference across the Kotlin boundary without value-type freezing or copy-on-write semantics.

Services MUST ensure Swift modern actors do not pass mutable state by reference across the Kotlin boundary without value-type freezing or copy-on-write semantics.

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 hold non-weak references to Swift Task handles inside long-lived Kotlin CoroutineScopes or Singletons, preventing memory retention cycles.

Components NEVER hold non-weak references to Swift Task handles inside long-lived Kotlin CoroutineScopes or Singletons, preventing memory retention cycles.

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 to Swift Concurrency Bidirectional Memory and Cancellation Bridge critical for AI coding assistants?

Enforces deterministic threading, actor isolation, and cooperative cancellation between Kotlin Coroutines and Swift Concurrency. Eliminates memory leaks, cross-thread race conditions, and deadlocks arising from uncoordinated bridging between Kotlin/Native memory runtimes and Swift Tasks. 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 (Unconfined Suspend Bridging and Unbounded Main-Thread Blocking Across the KMP-Swift FFI Boundary) 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