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

Kotlin Multiplatform Swift Async Cancellation Bridge Invariant

Exporting Kotlin suspend functions directly to Swift via default Kotlin/Native Objective-C bridges creates Swift async calls that do not propagate cooperative cancellation backward to the Kotlin runtime. When an iOS Swift Task is cancelled, the underlying Kotlin CoroutineScope/Job remains active, creating orphaned background executions, thread starvation, and persistent memory leaks. All cross-boundary async invocations must bind Swift Task cancellation handlers directly to Kotlin Job cancellation tokens or utilize robust compiler plugin abstractions (such as SKIE or KMP-NativeCoroutines).

Prohibited Anti-Pattern: Unbridged Kotlin Suspend Invocation via Default Swift Concurrency Bridging

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Swift Async Cancellation Bridge Invariant - Exporting Kotlin suspend functions directly to Swift via default Kotlin/Native Objective-C bridges creates Swift async calls that do not propagate cooperative cancellation backward to the Kotlin runtime. When an iOS Swift Task is cancelled, the underlying Kotlin CoroutineScope/Job remains active, creating orphaned background executions, thread starvation, and persistent memory leaks. All cross-boundary async invocations must bind Swift Task cancellation handlers directly to Kotlin Job cancellation tokens or utilize robust compiler plugin abstractions (such as SKIE or KMP-NativeCoroutines).
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-async-cancellation-bridge-guardrail"
---

# Kotlin Multiplatform Swift Async Cancellation Bridge Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbridged Kotlin Suspend Invocation via Default Swift Concurrency Bridging

## System Constraints
You are a Principal Software Architect enforcing cross-runtime concurrency invariants in Kotlin Multiplatform (KMP) iOS integrations. Default Kotlin/Native Objective-C bridging exposes suspend functions as Swift async functions, but Swift Task cancellation is completely severed from Kotlin Job cancellation. You must enforce bidirectional cancellation propagation on every coroutine exposed to Apple platforms. Never permit unbridged, raw suspend function calls from Swift Tasks without explicit cancellation wiring or proven ABI-level bridges.

## Strict Guidelines
- Engineers MUST ALWAYS wire Swift Task cancellation to the underlying Kotlin Job cancellation using `withTaskCancellationHandler` or an established toolchain plugin like SKIE.
- Engineers MUST NOT invoke auto-generated Kotlin/Native `async` wrappers directly inside Swift structured concurrency without an attached cancellation listener.
- Services exposing KMP asynchronous flows to iOS MUST return a disposable handle or `Cancellable` abstraction if direct Swift async compilation is used without plugin-level bridging.
- Components NEVER assume Swift `Task.cancel()` terminates the underlying Kotlin coroutine; explicit cancellation calls into Kotlin dispatchers are required.
- Swift ViewModel and View layers MUST ensure that when a SwiftUI `.task` modifier or structured `TaskGroup` finishes or cancels, the corresponding Kotlin `Job` immediately transitions to `Cancelled`.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Default Kotlin/Native bridging emits a Swift async method backed by an Objective-C completion handler. Cancelling the enclosing Swift `Task` triggers cancellation in Swift, but the underlying Kotlin `suspendCancellableCoroutine` or `Job` is never notified, running to completion and holding strong references.
```swift
// ANTI-PATTERN: Calling raw generated suspend function directly in Swift Task.
// When the SwiftUI View dismisses or Task is cancelled, the Kotlin coroutine continues
// running indefinitely, causing persistent memory leaks and orphaned network/DB tasks.

import SwiftUI
import SharedKit

@MainActor
final class UserProfileViewModel: ObservableObject {
    @Published var state: ViewState = .idle
    private let repository = UserRepository()
    private var loadTask: Task<Void, Never>?

    func loadUserProfile(userId: String) {
        loadTask?.cancel()
        loadTask = Task {
            do {
                // The generated Swift async function does NOT propagate Task.isCancelled to Kotlin!
                let profile = try await repository.fetchUserProfile(id: userId)
                self.state = .success(profile)
            } catch {
                self.state = .error(error.localizedDescription)
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Wrapping execution within `withTaskCancellationHandler` ensures that when the Swift concurrency context is cancelled, the registered `onCancel` closure executes synchronously and interrupts the underlying Kotlin Coroutine Job, preventing resource leaks and orphaned execution.
```swift
// PRODUCTION STANDARD: Explicitly bridging Swift Task cancellation to Kotlin Job handle.
// Swift Task cancellation immediately triggers Kotlin Job cancellation.

import SwiftUI
import SharedKit

@MainActor
final class UserProfileViewModel: ObservableObject {
    @Published var state: ViewState = .idle
    private let repository = UserRepository()
    private var loadTask: Task<Void, Never>?

    func loadUserProfile(userId: String) {
        loadTask?.cancel()
        loadTask = Task {
            do {
                let profile = try await withTaskCancellationHandler {
                    try await repository.fetchUserProfileBridged(id: userId)
                } onCancel: {
                    // Explicitly signal Kotlin runtime to cancel execution
                    repository.cancelUserProfileFetch(id: userId)
                }
                guard !Task.isCancelled else { return }
                self.state = .success(profile)
            } catch is CancellationError {
                // Clean exit on structured task cancellation
            } catch {
                self.state = .error(error.localizedDescription)
            }
        }
    }
}
```

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 Async Cancellation Bridge Invariant

Kotlin Multiplatform Swift Async Cancellation Bridge Invariant defines an industrial-grade behavioral standard for mobile engineering. Exporting Kotlin suspend functions directly to Swift via default Kotlin/Native Objective-C bridges creates Swift async calls that do not propagate cooperative cancellation backward to the Kotlin runtime. When an iOS Swift Task is cancelled, the underlying Kotlin CoroutineScope/Job remains active, creating orphaned background executions, thread starvation, and persistent memory leaks. All cross-boundary async invocations must bind Swift Task cancellation handlers directly to Kotlin Job cancellation tokens or utilize robust compiler plugin abstractions (such as SKIE or KMP-NativeCoroutines). 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 Kotlin Suspend Invocation via Default Swift Concurrency Bridging 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 Kotlin Suspend Invocation via Default Swift Concurrency BridgingCritical
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 wire Swift Task cancellation to the underlying Kotlin Job cancellation using `withTaskCancellationHandler` or an established toolchain plugin like SKIE.

Engineers MUST ALWAYS wire Swift Task cancellation to the underlying Kotlin Job cancellation using `withTaskCancellationHandler` or an established toolchain plugin like SKIE.

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 auto-generated Kotlin/Native `async` wrappers directly inside Swift structured concurrency without an attached cancellation listener.

Engineers MUST NOT invoke auto-generated Kotlin/Native `async` wrappers directly inside Swift structured concurrency without an attached cancellation listener.

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

Services exposing KMP asynchronous flows to iOS MUST return a disposable handle or `Cancellable` abstraction if direct Swift async compilation is used without plugin-level bridging.

Services exposing KMP asynchronous flows to iOS MUST return a disposable handle or `Cancellable` abstraction if direct Swift async compilation is used without plugin-level bridging.

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

Components NEVER assume Swift `Task.cancel()` terminates the underlying Kotlin coroutine

Components NEVER assume Swift `Task.cancel()` terminates the underlying Kotlin coroutine; explicit cancellation calls into Kotlin dispatchers are required.

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

Swift ViewModel and View layers MUST ensure that when a SwiftUI `.task` modifier or structured `TaskGroup` finishes or cancels, the corresponding Kotlin `Job` immediately transitions to `Cancelled`.

Swift ViewModel and View layers MUST ensure that when a SwiftUI `.task` modifier or structured `TaskGroup` finishes or cancels, the corresponding Kotlin `Job` immediately transitions to `Cancelled`.

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 Async Cancellation Bridge Invariant critical for AI coding assistants?

Exporting Kotlin suspend functions directly to Swift via default Kotlin/Native Objective-C bridges creates Swift async calls that do not propagate cooperative cancellation backward to the Kotlin runtime. When an iOS Swift Task is cancelled, the underlying Kotlin CoroutineScope/Job remains active, creating orphaned background executions, thread starvation, and persistent memory leaks. All cross-boundary async invocations must bind Swift Task cancellation handlers directly to Kotlin Job cancellation tokens or utilize robust compiler plugin abstractions (such as SKIE or KMP-NativeCoroutines). 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 Kotlin Suspend Invocation via Default Swift Concurrency Bridging) 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