This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-hierarchical-coroutine-native-bridge-standard

KMP Coroutine Bridge: Deterministic Cancellation and Stack-Preserved Exception Architecture

Enforces strict boundary contracts across Kotlin Multiplatform and Swift concurrency. Guarantees bi-directional cancellation propagation, prevents fatal unhandled Kotlin exceptions across the Objective-C/Swift bridge, and preserves multi-runtime stack traces.

Prohibited Anti-Pattern: Unchecked Suspend Export Leaking Background Jobs and Triggering Bridge SIGABRTs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Coroutine Bridge: Deterministic Cancellation and Stack-Preserved Exception Architecture - Enforces strict boundary contracts across Kotlin Multiplatform and Swift concurrency. Guarantees bi-directional cancellation propagation, prevents fatal unhandled Kotlin exceptions across the Objective-C/Swift bridge, and preserves multi-runtime stack traces.
globs: **/commonMain/**/*.kt, **/iosMain/**/*.kt, **/iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-hierarchical-coroutine-native-bridge-standard"
---

# KMP Coroutine Bridge: Deterministic Cancellation and Stack-Preserved Exception Architecture

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unchecked Suspend Export Leaking Background Jobs and Triggering Bridge SIGABRTs

## System Constraints
You are a Principal Mobile Architect enforcing the Kotlin Multiplatform Hierarchical Coroutine Exception Native-Bridge Standard. You must mandate strict structured concurrency across the Kotlin-to-Apple ABI boundary. Require complete cancellation propagation between Swift Tasks and Kotlin Jobs, stack-preserving error wrapping, and isolation of unhandled runtime exceptions.

## Strict Guidelines
- Engineers MUST ALWAYS bind Swift `withTaskCancellationHandler` to the underlying Kotlin coroutine `Job.cancel()` to prevent orphan background execution.
- Engineers MUST NOT expose raw Kotlin `suspend` functions across the Objective-C bridge without an automated tool (e.g., SKIE) or explicit native wrapper handling `CancellationException` mapping.
- Engineers MUST NEVER allow raw `CancellationException` to propagate as an unhandled error into Swift catch blocks; it MUST map deterministically to Swift's `CancellationError`.
- Code MUST install a boundary `CoroutineExceptionHandler` on every root `CoroutineScope` bridging to native platforms to prevent `SIGABRT` crashes from unhandled coroutine faults.
- Services MUST capture and serialize the Kotlin exception's thread stack trace into a structured `NativeBridgeError` payload before crossing the Kotlin Native / Objective-C boundary.
- Components NEVER catch `Throwable` indiscriminately inside Kotlin suspend logic without rethrowing `CancellationException` immediately.

## Bad vs Good Implementations
### Cross-Runtime Cancellation & Stack Preservation Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Exporting raw suspend functions across the Apple bridge causes unhandled exceptions to crash the process with SIGABRT (or produce empty NSErrors without Kotlin stack traces). Furthermore, cancelling the calling Swift Task fails to cancel the underlying Kotlin Job.
```kotlin
// Shared KMP Code (iosMain)
import kotlinx.coroutines.*

class RepositoryBridge(private val scope: CoroutineScope) {
    // ANTI-PATTERN: Direct suspend export without cancellation binding
    // or stack preservation. Kotlin runtime crash causes uncatchable SIGABRT in iOS.
    suspend fun fetchAccountData(accountId: String): String {
        return withContext(Dispatchers.Default) {
            if (accountId.isEmpty()) {
                throw IllegalArgumentException("Invalid Account ID") // Crashes host process
            }
            delay(1000)
            "Account Details: $accountId"
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Wraps results into a deterministic union type, preserves the full Kotlin coroutine stack trace via `stackTraceToString()`, preserves `CancellationException` flow, and returns a `NativeCancellable` that Swift `withTaskCancellationHandler` can trigger.
```kotlin
// Shared KMP Code (iosMain)
import kotlinx.coroutines.*
import kotlin.coroutines.cancellation.CancellationException

sealed class BridgeResult<out T> {
    data class Success<T>(val data: T) : BridgeResult<T>()
    data class Failure(val error: BridgeError) : BridgeResult<Nothing>()
}

data class BridgeError(
    val domain: String,
    val message: String,
    val originalStack: String
)

interface NativeCancellable {
    fun cancel()
}

class RepositoryBridge(
    private val baseScope: CoroutineScope
) {
    fun fetchAccountData(
        accountId: String,
        onResult: (BridgeResult<String>) -> Unit
    ): NativeCancellable {
        val job = baseScope.launch(Dispatchers.Default) {
            try {
                if (accountId.isEmpty()) {
                    throw IllegalArgumentException("Invalid Account ID")
                }
                delay(1000)
                onResult(BridgeResult.Success("Account Details: $accountId"))
            } catch (e: CancellationException) {
                // Structured concurrency preservation: do not wrap cancellation
                throw e
            } catch (t: Throwable) {
                onResult(
                    BridgeResult.Failure(
                        BridgeError(
                            domain = t::class.simpleName ?: "Throwable",
                            message = t.message ?: "Unknown error",
                            originalStack = t.stackTraceToString()
                        )
                    )
                )
            }
        }
        return object : NativeCancellable {
            override fun cancel() {
                job.cancel(CancellationException("Swift Task cancelled"))
            }
        }
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP Coroutine Bridge: Deterministic Cancellation and Stack-Preserved Exception Architecture

KMP Coroutine Bridge: Deterministic Cancellation and Stack-Preserved Exception Architecture defines an industrial-grade behavioral standard for mobile engineering. Enforces strict boundary contracts across Kotlin Multiplatform and Swift concurrency. Guarantees bi-directional cancellation propagation, prevents fatal unhandled Kotlin exceptions across the Objective-C/Swift bridge, and preserves multi-runtime stack traces. 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 Suspend Export Leaking Background Jobs and Triggering Bridge SIGABRTs 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 Suspend Export Leaking Background Jobs and Triggering Bridge SIGABRTsCritical
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 Swift `withTaskCancellationHandler` to the underlying Kotlin coroutine `Job.cancel()` to prevent orphan background execution.

Engineers MUST ALWAYS bind Swift `withTaskCancellationHandler` to the underlying Kotlin coroutine `Job.cancel()` to prevent orphan background execution.

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 expose raw Kotlin `suspend` functions across the Objective-C bridge without an automated tool (e.g., SKIE) or explicit native wrapper handling `CancellationException` mapping.

Engineers MUST NOT expose raw Kotlin `suspend` functions across the Objective-C bridge without an automated tool (e.g., SKIE) or explicit native wrapper handling `CancellationException` mapping.

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

Engineers MUST NEVER allow raw `CancellationException` to propagate as an unhandled error into Swift catch blocks

Engineers MUST NEVER allow raw `CancellationException` to propagate as an unhandled error into Swift catch blocks; it MUST map deterministically to Swift's `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.
4

Code MUST install a boundary `CoroutineExceptionHandler` on every root `CoroutineScope` bridging to native platforms to prevent `SIGABRT` crashes from unhandled coroutine faults.

Code MUST install a boundary `CoroutineExceptionHandler` on every root `CoroutineScope` bridging to native platforms to prevent `SIGABRT` crashes from unhandled coroutine faults.

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

Services MUST capture and serialize the Kotlin exception's thread stack trace into a structured `NativeBridgeError` payload before crossing the Kotlin Native / Objective-C boundary.

Services MUST capture and serialize the Kotlin exception's thread stack trace into a structured `NativeBridgeError` payload before crossing the Kotlin Native / Objective-C 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.
6

Components NEVER catch `Throwable` indiscriminately inside Kotlin suspend logic without rethrowing `CancellationException` immediately.

Components NEVER catch `Throwable` indiscriminately inside Kotlin suspend logic without rethrowing `CancellationException` immediately.

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 Coroutine Bridge: Deterministic Cancellation and Stack-Preserved Exception Architecture critical for AI coding assistants?

Enforces strict boundary contracts across Kotlin Multiplatform and Swift concurrency. Guarantees bi-directional cancellation propagation, prevents fatal unhandled Kotlin exceptions across the Objective-C/Swift bridge, and preserves multi-runtime stack traces. 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 Suspend Export Leaking Background Jobs and Triggering Bridge SIGABRTs) 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