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

KMP SKIE Swift Concurrency Bidirectional Cancellation and Thread Invariant

Enforces cooperative, bidirectional cancellation propagation across the Kotlin Multiplatform (KMP) coroutine and Swift Task runtime boundary using Touchlab SKIE. Prevents Swift cooperative pool starvation and Kotlin Native Worker deadlocks by strictly forbidding synchronous bridge blocking, unmanaged Job wrapping, and detached Swift task unbinding.

Prohibited Anti-Pattern: Unchecked Swift Task bridging leaking orphaned Kotlin coroutines and starving the Swift cooperative thread pool via blocking await calls.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP SKIE Swift Concurrency Bidirectional Cancellation and Thread Invariant - Enforces cooperative, bidirectional cancellation propagation across the Kotlin Multiplatform (KMP) coroutine and Swift Task runtime boundary using Touchlab SKIE. Prevents Swift cooperative pool starvation and Kotlin Native Worker deadlocks by strictly forbidding synchronous bridge blocking, unmanaged Job wrapping, and detached Swift task unbinding.
globs: iosApp/**/*.swift, shared/src/commonMain/kotlin/**/*.kt, shared/src/iosMain/kotlin/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-skie-swift-concurrency-bidirectional-cancellation"
---

# KMP SKIE Swift Concurrency Bidirectional Cancellation and Thread Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unchecked Swift Task bridging leaking orphaned Kotlin coroutines and starving the Swift cooperative thread pool via blocking await calls.

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform and iOS runtime interop. Your mandate is to enforce deterministic cancellation semantics across the KMP Coroutines and Swift Concurrency boundary. Touchlab SKIE transforms suspend functions into Swift async/await interfaces backed by cooperative cancellation hooks. You must ensure that every bridge invocation connects Swift Task cancellation tokens directly to Kotlin Coroutine Job cancellations without blocking GCD queues or Swift global concurrency dispatch threads. Any uncooperative or blocking pattern must be blocked immediately.

## Strict Guidelines
- Engineers MUST ALWAYS expose KMP suspend functions directly to Swift using SKIE-generated async APIs or pass explicitly managed CoroutineScope instances configured with SupervisorJob.
- Engineers MUST NOT invoke Kotlin coroutines from Swift using runBlocking, unmanaged MainScope(), or unmonitored Task.detached closures that swallow cancellation signals.
- Code SHOULD verify Task.isCancelled before and after invoking SKIE-generated suspend bindings when executing heavy transformation pipelines on the Swift actor boundary.
- Services MUST ensure that long-running Kotlin Native operations yield cooperatively via ensureActive() or yield() so Swift Task.cancel() interrupts execution promptly.
- Components NEVER bridge Kotlin Flows into Swift AsyncSequence via manual notification loops; SKIE-generated Swift AsyncSequences must be consumed directly inside structured Task contexts.

## Bad vs Good Implementations
### Consuming KMP Suspend Functions across Swift Concurrency Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Task.detached disconnects the execution context from the caller's cancellation hierarchy. If the view disposes or the parent task is cancelled, the underlying Kotlin coroutine spawned by the SKIE bridge continues running, causing uncollected memory, wasted network cycles, and potential state corruption.
```swift
// BAD: Detached execution without cancellation propagation; swallows Swift cancellation
// and leaves the Kotlin coroutine running indefinitely in KMP runtime.
class AccountViewModel: ObservableObject {
    private let repository = AccountRepository()

    func loadProfile() {
        Task.detached {
            do {
                // Bypasses structured task tree; does not propagate cancel
                let profile = try await self.repository.fetchProfile()
                DispatchQueue.main.async {
                    // UI mutation
                }
            } catch {
                print("Failed: \(error)")
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Using a bound structured Task ensures that when loadTask is cancelled (or upon ViewModel deinit), the Swift cancellation token propagates through the SKIE bridge into the Kotlin Job hierarchy, causing immediate cooperative termination in Kotlin Native without leaking resources.
```swift
// GOOD: Structured concurrency binding SKIE cancellation directly to Swift Task scope
@MainActor
final class AccountViewModel: ObservableObject {
    @Published private(set) var state: ViewState = .idle
    private let repository: AccountRepository
    private var loadTask: Task<Void, Never>?

    init(repository: AccountRepository) {
        self.repository = repository
    }

    func loadProfile() {
        loadTask?.cancel()
        loadTask = Task { [weak self] in
            guard let self else { return }
            do {
                // SKIE bridges Swift cancellation directly to Kotlin coroutine Job
                let profile = try await self.repository.fetchProfile()
                try Task.checkCancellation()
                self.state = .success(profile)
            } catch is CancellationError {
                // Swift cancellation caught cleanly
                self.state = .cancelled
            } catch {
                self.state = .error(error)
            }
        }
    }

    deinit {
        loadTask?.cancel()
    }
}
```

### Kotlin Side Cooperative Cancellation Check for Swift Bridges

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin Native suspension routines that perform heavy CPU operations without calling ensureActive() or yield() cannot be cancelled by Swift Task.cancel(). The SKIE bridge sets the coroutine Job to cancelled, but execution continues until the loop finishes, starving the thread.
```kotlin
// BAD: Monolithic loop in Kotlin Native ignoring coroutine cancellation checks
class DataSyncService {
    suspend fun processBatch(items: List<SyncItem>): ProcessResult = withContext(Dispatchers.Default) {
        for (item in items) {
            // Blocking calculation with no cancellation checkpoint
            heavyComputation(item)
        }
        ProcessResult.Success
    }
}
```

#### Production Standard (Correct)
> **Standard**: Calling coroutineContext.ensureActive() on each iteration allows the CancellationException initiated by the SKIE Swift cancellation listener to immediately unwind the Kotlin stack and release native worker resources.
```kotlin
// GOOD: Cooperative cancellation checkpoints allowing SKIE Swift cancel to abort execution
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import kotlinx.coroutines.Dispatchers

class DataSyncService {
    suspend fun processBatch(items: List<SyncItem>): ProcessResult = withContext(Dispatchers.Default) {
        for (item in items) {
            coroutineContext.ensureActive() // Cooperatively terminates when Swift Task cancels
            heavyComputation(item)
        }
        ProcessResult.Success
    }
}
```

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 SKIE Swift Concurrency Bidirectional Cancellation and Thread Invariant

KMP SKIE Swift Concurrency Bidirectional Cancellation and Thread Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces cooperative, bidirectional cancellation propagation across the Kotlin Multiplatform (KMP) coroutine and Swift Task runtime boundary using Touchlab SKIE. Prevents Swift cooperative pool starvation and Kotlin Native Worker deadlocks by strictly forbidding synchronous bridge blocking, unmanaged Job wrapping, and detached Swift task unbinding. 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: Unchecked Swift Task bridging leaking orphaned Kotlin coroutines and starving the Swift cooperative thread pool via blocking await calls. 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 DriftUnchecked Swift Task bridging leaking orphaned Kotlin coroutines and starving the Swift cooperative thread pool via blocking await calls.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 expose KMP suspend functions directly to Swift using SKIE-generated async APIs or pass explicitly managed CoroutineScope instances configured with SupervisorJob.

Engineers MUST ALWAYS expose KMP suspend functions directly to Swift using SKIE-generated async APIs or pass explicitly managed CoroutineScope instances configured with SupervisorJob.

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 coroutines from Swift using runBlocking, unmanaged MainScope(), or unmonitored Task.detached closures that swallow cancellation signals.

Engineers MUST NOT invoke Kotlin coroutines from Swift using runBlocking, unmanaged MainScope(), or unmonitored Task.detached closures that swallow cancellation signals.

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 verify Task.isCancelled before and after invoking SKIE-generated suspend bindings when executing heavy transformation pipelines on the Swift actor boundary.

Code SHOULD verify Task.isCancelled before and after invoking SKIE-generated suspend bindings when executing heavy transformation pipelines on the Swift actor 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.
4

Services MUST ensure that long-running Kotlin Native operations yield cooperatively via ensureActive() or yield() so Swift Task.cancel() interrupts execution promptly.

Services MUST ensure that long-running Kotlin Native operations yield cooperatively via ensureActive() or yield() so Swift Task.cancel() interrupts execution promptly.

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 Kotlin Flows into Swift AsyncSequence via manual notification loops

Components NEVER bridge Kotlin Flows into Swift AsyncSequence via manual notification loops; SKIE-generated Swift AsyncSequences must be consumed directly inside structured Task contexts.

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 SKIE Swift Concurrency Bidirectional Cancellation and Thread Invariant critical for AI coding assistants?

Enforces cooperative, bidirectional cancellation propagation across the Kotlin Multiplatform (KMP) coroutine and Swift Task runtime boundary using Touchlab SKIE. Prevents Swift cooperative pool starvation and Kotlin Native Worker deadlocks by strictly forbidding synchronous bridge blocking, unmanaged Job wrapping, and detached Swift task unbinding. 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 (Unchecked Swift Task bridging leaking orphaned Kotlin coroutines and starving the Swift cooperative thread pool via blocking await calls.) 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