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

KMP Structured Concurrency & Swift async/await Bridge Guardrail

Enforces strict bi-directional cancellation propagation and thread safety when bridging Kotlin Coroutines with Swift async/await primitives. Eliminates dangling coroutine executions, thread pool starvation, and unhandled CancellationException crashes across the Kotlin/Native Objective-C runtime boundary.

Prohibited Anti-Pattern: Unbound Coroutine Invocation via Detached Swift Tasks Causing Thread Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Structured Concurrency & Swift async/await Bridge Guardrail - Enforces strict bi-directional cancellation propagation and thread safety when bridging Kotlin Coroutines with Swift async/await primitives. Eliminates dangling coroutine executions, thread pool starvation, and unhandled CancellationException crashes across the Kotlin/Native Objective-C runtime boundary.
globs: **/*.kt, **/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-structured-concurrency-swift-bridge"
---

# KMP Structured Concurrency & Swift async/await Bridge Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbound Coroutine Invocation via Detached Swift Tasks Causing Thread Leaks

## System Constraints
You are a Principal Mobile Architect enforcing structured concurrency invariants between Kotlin Multiplatform (KMP) and Swift. You must ensure that every suspend function and Kotlin Flow exposed to Apple platforms maintains explicit lifecycle ownership, guarantees bi-directional cooperative cancellation, and never leaks jobs or suppresses CancellationException across foreign function boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS bind Kotlin Job lifecycles to the calling Swift Task lifecycle using withTaskCancellationHandler or an equivalent architectural runtime like SKIE or KMP-NativeCoroutines.
- Engineers MUST NOT convert Kotlin suspend functions to Swift async functions without explicit cancellation handlers, as Swift's Task cancellation will not automatically propagate across standard Objective-C export headers.
- Kotlin-exposed APIs MUST NEVER catch and swallow kotlin.coroutines.cancellation.CancellationException; it must be rethrown to guarantee structured coroutine unwinding.
- Swift clients MUST check Task.isCancelled and invoke the Kotlin Job/Cancellable handle explicitly upon task termination or scope deinitialization.
- Engineers MUST NOT expose raw GlobalScope, NonCancellable, or unbound CoroutineScope instances to platform-specific presentation layers.
- Shared Kotlin Flows exposed as Swift AsyncSequence MUST trigger flow cancellation upstream immediately when the Swift async consumer terminates iteration or is cancelled.

## Bad vs Good Implementations
### Swift Bridge with Task Cancellation Propagation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When the Swift Task running loadUserData is cancelled, the underlying Kotlin coroutine remains active and runs to completion in the Kotlin Native worker pool, wasting CPU, network, and memory.
```swift
// BAD: Direct invocation of standard KMP-generated completion handler
// Swift Task cancellation will not propagate to the underlying Kotlin Coroutine,
// causing dangling worker threads and leaked Ktor/SQLDelight resources.
func loadUserData(userId: String) async throws -> UserProfile {
    return try await withCheckedThrowingContinuation { continuation in
        userRepository.fetchUserProfile(userId: 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**: Attaches withTaskCancellationHandler to cancel the underlying Kotlin Job handle immediately when the Swift Task is cancelled, properly mapping foreign CancellationExceptions to Swift's CancellationError.
```swift
// GOOD: Structured lifecycle binding using withTaskCancellationHandler
// Guarantees immediate cancellation of the Kotlin Job when the Swift Task is cancelled.
func loadUserData(userId: String) async throws -> UserProfile {
    var cancellableJob: KmpCancellable? = nil
    
    return try await withTaskCancellationHandler {
        try Task.checkCancellation()
        return try await withCheckedThrowingContinuation { continuation in
            cancellableJob = userRepository.fetchUserProfileWithCancel(userId: userId) { profile, error in
                if let error = error {
                    // Map Kotlin CancellationException to Swift CancellationError
                    if (error as NSError).isKotlinCancellationException {
                        continuation.resume(throwing: CancellationError())
                    } else {
                        continuation.resume(throwing: error)
                    }
                } else if let profile = profile {
                    continuation.resume(returning: profile)
                }
            }
        }
    } onCancel: {
        cancellableJob?.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: KMP Structured Concurrency & Swift async/await Bridge Guardrail

KMP Structured Concurrency & Swift async/await Bridge Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict bi-directional cancellation propagation and thread safety when bridging Kotlin Coroutines with Swift async/await primitives. Eliminates dangling coroutine executions, thread pool starvation, and unhandled CancellationException crashes across the Kotlin/Native Objective-C runtime 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: Unbound Coroutine Invocation via Detached Swift Tasks Causing Thread Leaks 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 DriftUnbound Coroutine Invocation via Detached Swift Tasks Causing Thread LeaksCritical
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 bind Kotlin Job lifecycles to the calling Swift Task lifecycle using withTaskCancellationHandler or an equivalent architectural runtime like SKIE or KMP-NativeCoroutines.

Engineers MUST ALWAYS bind Kotlin Job lifecycles to the calling Swift Task lifecycle using withTaskCancellationHandler or an equivalent architectural runtime like SKIE or KMP-NativeCoroutines.

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 convert Kotlin suspend functions to Swift async functions without explicit cancellation handlers, as Swift's Task cancellation will not automatically propagate across standard Objective-C export headers.

Engineers MUST NOT convert Kotlin suspend functions to Swift async functions without explicit cancellation handlers, as Swift's Task cancellation will not automatically propagate across standard Objective-C export headers.

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

Kotlin-exposed APIs MUST NEVER catch and swallow kotlin.coroutines.cancellation.CancellationException

Kotlin-exposed APIs MUST NEVER catch and swallow kotlin.coroutines.cancellation.CancellationException; it must be rethrown to guarantee structured coroutine unwinding.

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

Swift clients MUST check Task.isCancelled and invoke the Kotlin Job/Cancellable handle explicitly upon task termination or scope deinitialization.

Swift clients MUST check Task.isCancelled and invoke the Kotlin Job/Cancellable handle explicitly upon task termination or scope deinitialization.

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

Engineers MUST NOT expose raw GlobalScope, NonCancellable, or unbound CoroutineScope instances to platform-specific presentation layers.

Engineers MUST NOT expose raw GlobalScope, NonCancellable, or unbound CoroutineScope instances to platform-specific presentation layers.

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

Shared Kotlin Flows exposed as Swift AsyncSequence MUST trigger flow cancellation upstream immediately when the Swift async consumer terminates iteration or is cancelled.

Shared Kotlin Flows exposed as Swift AsyncSequence MUST trigger flow cancellation upstream immediately when the Swift async consumer terminates iteration or is 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 KMP Structured Concurrency & Swift async/await Bridge Guardrail critical for AI coding assistants?

Enforces strict bi-directional cancellation propagation and thread safety when bridging Kotlin Coroutines with Swift async/await primitives. Eliminates dangling coroutine executions, thread pool starvation, and unhandled CancellationException crashes across the Kotlin/Native Objective-C runtime 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 (Unbound Coroutine Invocation via Detached Swift Tasks Causing Thread Leaks) 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