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

Bidirectional Coroutine and Swift Task Cancellation via SKIE Bridge

Enforces deterministic bidirectional cancellation propagation between Swift Tasks and Kotlin Coroutines across the Swift/Kotlin Native FFI boundary using Touchlab SKIE. Prevents thread pool starvation, native memory leaks, and corrupt asynchronous state caused by severed cancellation signals and generic exception swallowing.

Prohibited Anti-Pattern: Catch-All Exception Swallowing and Unstructured Swift Tasks Severing Cooperative Cancellation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bidirectional Coroutine and Swift Task Cancellation via SKIE Bridge - Enforces deterministic bidirectional cancellation propagation between Swift Tasks and Kotlin Coroutines across the Swift/Kotlin Native FFI boundary using Touchlab SKIE. Prevents thread pool starvation, native memory leaks, and corrupt asynchronous state caused by severed cancellation signals and generic exception swallowing.
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-skie-swift-task-cancellation-bridge-kotlin-multiplat-606"
---

# Bidirectional Coroutine and Swift Task Cancellation via SKIE Bridge

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Catch-All Exception Swallowing and Unstructured Swift Tasks Severing Cooperative Cancellation

## System Constraints
You are a Principal Mobile Architect enforcing strict Kotlin Multiplatform (KMP) and Swift concurrency invariants via SKIE. Mandate that every Kotlin suspend function and Flow exported to iOS integrates seamlessly with Swift's cooperative cancellation model. Enforce that Kotlin Coroutine Jobs respond to Swift Task cancellation, and Swift Task handlers cleanly propagate CancellationError when a Kotlin Job is cancelled across the Objective-C/Swift bridge.

## Strict Guidelines
- Engineers MUST ALWAYS rethrow `CancellationException` in Kotlin whenever catching generic `Exception` or `Throwable` to permit SKIE to forward cancellation back to Swift as a `CancellationError`.
- Engineers MUST NOT spawn detached or unmanaged Swift `Task` blocks (`Task.detached`) when bridging SKIE suspend calls in SwiftUI or UIKit lifecycle-bound view components.
- Code SHOULD verify `coroutineContext.ensureActive()` or invoke `yield()` during compute-intensive loops in Kotlin to guarantee cooperative interruption when a Swift Task cancels.
- Services MUST leverage SKIE's generated async/await and AsyncSequence wrappers rather than manually wrapping raw Kotlin completion handlers with `withCheckedContinuation`.
- Components NEVER store long-lived strong references to active Swift `Task` instances or Kotlin `Job` handles inside singletons without explicit cancellation in teardown routines.

## Bad vs Good Implementations
### Kotlin Side: Generic Exception Handling Severing Cancellation Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Catching `Exception` without rethrowing `CancellationException` intercepts coroutine cancellation. The coroutine finishes as a normal failure, SKIE fails to notify the Swift caller that the Task was cancelled, and native resources remain allocated.
```kotlin
class UserRepository(private val api: UserApi) {
    suspend fun syncUserData(userId: String): Result<UserData> {
        return try {
            val data = api.fetchUser(userId)
            Result.success(data)
        } catch (e: Exception) { // ANTI-PATTERN: Swallows CancellationException, preventing Swift Task cancellation
            Result.failure(e)
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly rethrowing `CancellationException` allows SKIE's runtime bridge to translate the cancellation into a Swift `CancellationError`, releasing native bridging wrappers and maintaining structured concurrency.
```kotlin
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive

class UserRepository(private val api: UserApi) {
    suspend fun syncUserData(userId: String): Result<UserData> {
        return try {
            currentCoroutineContext().ensureActive()
            val data = api.fetchUser(userId)
            Result.success(data)
        } catch (e: CancellationException) {
            throw e // INVARIANT: Propagate CancellationException to SKIE bridge
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
}
```

### Swift Side: Structured Task Bridging with Lifecycle Binding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: `Task.detached` breaks the structural hierarchy of SwiftUI. When the view unmounts, the detached Task keeps running, keeping the SKIE Kotlin coroutine alive and holding strong native references.
```swift
import SwiftUI
import SharedKit

struct ProfileView: View {
    @StateObject private var viewModel = ProfileViewModel()

    var body: some View {
        Text(viewModel.userName)
            .onAppear {
                // ANTI-PATTERN: Unstructured detached Task ignores view lifecycle;
                // navigation pop will not cancel the underlying Kotlin coroutine
                Task.detached {
                    await viewModel.loadUser()
                }
            }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Using SwiftUI's `.task` modifier attaches the execution to the view's lifecycle. Cancellation propagates down through SKIE directly into the Kotlin Coroutine Job, triggering cooperative cancellation.
```swift
import SwiftUI
import SharedKit

struct ProfileView: View {
    @StateObject private var viewModel = ProfileViewModel()

    var body: some View {
        Text(viewModel.userName)
            .task {
                // INVARIANT: SwiftUI .task modifier automatically binds Task cancellation
                // to view lifecycle, triggering SKIE Kotlin Job cancellation on pop/dismiss
                do {
                    try await viewModel.loadUser()
                } catch is CancellationError {
                    // Expected behavior when view dismisses; cleanly handled
                } catch {
                    viewModel.handleError(error)
                }
            }
    }
}
```

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: Bidirectional Coroutine and Swift Task Cancellation via SKIE Bridge

Bidirectional Coroutine and Swift Task Cancellation via SKIE Bridge defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic bidirectional cancellation propagation between Swift Tasks and Kotlin Coroutines across the Swift/Kotlin Native FFI boundary using Touchlab SKIE. Prevents thread pool starvation, native memory leaks, and corrupt asynchronous state caused by severed cancellation signals and generic exception swallowing. 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: Catch-All Exception Swallowing and Unstructured Swift Tasks Severing Cooperative Cancellation 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 DriftCatch-All Exception Swallowing and Unstructured Swift Tasks Severing Cooperative CancellationCritical
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 rethrow `CancellationException` in Kotlin whenever catching generic `Exception` or `Throwable` to permit SKIE to forward cancellation back to Swift as a `CancellationError`.

Engineers MUST ALWAYS rethrow `CancellationException` in Kotlin whenever catching generic `Exception` or `Throwable` to permit SKIE to forward cancellation back to Swift as a `CancellationError`.

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 spawn detached or unmanaged Swift `Task` blocks (`Task.detached`) when bridging SKIE suspend calls in SwiftUI or UIKit lifecycle-bound view components.

Engineers MUST NOT spawn detached or unmanaged Swift `Task` blocks (`Task.detached`) when bridging SKIE suspend calls in SwiftUI or UIKit lifecycle-bound view components.

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 `coroutineContext.ensureActive()` or invoke `yield()` during compute-intensive loops in Kotlin to guarantee cooperative interruption when a Swift Task cancels.

Code SHOULD verify `coroutineContext.ensureActive()` or invoke `yield()` during compute-intensive loops in Kotlin to guarantee cooperative interruption when a Swift Task cancels.

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 leverage SKIE's generated async/await and AsyncSequence wrappers rather than manually wrapping raw Kotlin completion handlers with `withCheckedContinuation`.

Services MUST leverage SKIE's generated async/await and AsyncSequence wrappers rather than manually wrapping raw Kotlin completion handlers with `withCheckedContinuation`.

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 store long-lived strong references to active Swift `Task` instances or Kotlin `Job` handles inside singletons without explicit cancellation in teardown routines.

Components NEVER store long-lived strong references to active Swift `Task` instances or Kotlin `Job` handles inside singletons without explicit cancellation in teardown routines.

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 Bidirectional Coroutine and Swift Task Cancellation via SKIE Bridge critical for AI coding assistants?

Enforces deterministic bidirectional cancellation propagation between Swift Tasks and Kotlin Coroutines across the Swift/Kotlin Native FFI boundary using Touchlab SKIE. Prevents thread pool starvation, native memory leaks, and corrupt asynchronous state caused by severed cancellation signals and generic exception swallowing. 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 (Catch-All Exception Swallowing and Unstructured Swift Tasks Severing Cooperative Cancellation) 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

Bidirectional