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

Kotlin Multiplatform Swift-Export Cancellation Interlock Standard

Guarantees Swift Concurrency Task cancellation trees bidirectionally propagate into native Kotlin Multiplatform Job hierarchies and vice versa. Prevents orphaned background dispatchers, unmanaged CoroutineScopes, and native memory leaks caused by retained Cinterop/Obj-C blocks.

Prohibited Anti-Pattern: Unlinked Swift Task wrapping that drops cooperative cancellation signals and leaks Kotlin Native worker threads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Swift-Export Cancellation Interlock Standard - Guarantees Swift Concurrency Task cancellation trees bidirectionally propagate into native Kotlin Multiplatform Job hierarchies and vice versa. Prevents orphaned background dispatchers, unmanaged CoroutineScopes, and native memory leaks caused by retained Cinterop/Obj-C blocks.
globs: iosApp/**/*.swift, **/iosMain/**/*.kt, **/appleMain/**/*.kt, **/commonMain/**/interop/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-cancellation-interlock-guardrail"
---

# Kotlin Multiplatform Swift-Export Cancellation Interlock Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unlinked Swift Task wrapping that drops cooperative cancellation signals and leaks Kotlin Native worker threads

## System Constraints
You are a Principal Software Architect enforcing rigorous Swift Concurrency to Kotlin Multiplatform (KMP) cancellation interlock. You must mandate that every bridged suspend function, Flow, or async sequence bound across the Swift-Export or Objective-C export barrier establishes an atomic, bidirectional cancellation contract. Ensure that cancelling an enclosing Swift Task immediately cancels the underlying Kotlin Job via Job.cancel(cause:), and that Kotlin Coroutine failures or cancellations are non-destructively reflected into Swift's error propagation without leaving active Kotlin Native background dispatchers or ARC reference cycles.

## Strict Guidelines
- Engineers MUST ALWAYS wrap bridged Kotlin suspend calls inside Swift's `withTaskCancellationHandler` to immediately relay cancellation to the active Kotlin `Job` or `Cancellable` wrapper.
- Engineers MUST NOT rely on unchecked Swift `Task { await ... }` blocks when calling KMP suspend functions without retaining and linking the underlying Kotlin Job reference.
- Code SHOULD enforce structured lifecycle bridging where Swift `AsyncSequence` adapters for Kotlin `Flow` explicitly invoke `Closeable.close()` or `Job.cancel()` upon iterator termination or task deallocation.
- Services MUST ensure Kotlin Native dispatchers release native memory references immediately when `CancellationException` is caught across the Cinterop boundary.
- Components NEVER hold strong bidirectional references between Swift completion handlers and Kotlin CoroutineScope instances; weak reference semantics or explicit unbinding MUST be enforced.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The continuation ignores Swift Task cancellation. When the caller's Task is cancelled (e.g., SwiftUI view dismissal), the Kotlin repository continues fetching data, burning CPU cycles on native worker threads and creating an ARC/Kotlin Native retention cycle until completion.
```swift
// ANTI-PATTERN: Fire-and-forget Task bridge ignoring Swift cancellation.
// Cancelling the parent Swift Task will leave the Kotlin coroutine running on Dispatchers.Default.
func fetchUserProfile(id: String) async throws -> UserProfile {
    return try await withCheckedThrowingContinuation { continuation in
        // Strong reference leak: KMP repository retains closure, ignoring Task cancellation
        UserRepositoryCompanion.shared.fetchProfile(id: id) { profile, error in
            if let error = error {
                continuation.resume(throwing: error)
            } else if let profile = profile {
                continuation.resume(returning: profile)
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Wraps the execution in `withTaskCancellationHandler` and retains the returned native Kotlin `Job`. If the Swift `Task` is cancelled, `onCancel` immediately invokes `jobRef?.cancel(cause: nil)`, which propagates cooperative cancellation down the Kotlin CoroutineScope hierarchy and frees native dispatcher resources.
```swift
// PRODUCTION STANDARD: Explicit cancellation interlock with bidirectional teardown.
func fetchUserProfile(id: String) async throws -> UserProfile {
    var jobRef: Kotlinx_coroutines_coreJob? = nil
    
    return try await withTaskCancellationHandler {
        try await withCheckedThrowingContinuation { continuation in
            jobRef = UserRepositoryCompanion.shared.fetchProfileJob(
                id: id,
                onSuccess: { profile in
                    continuation.resume(returning: profile)
                },
                onError: { error in
                    continuation.resume(throwing: error)
                }
            )
        }
    } onCancel: {
        // Atomically abort native Kotlin Job when enclosing Swift Task cancels
        jobRef?.cancel(cause: nil)
    }
}
```

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-Export Cancellation Interlock Standard

Kotlin Multiplatform Swift-Export Cancellation Interlock Standard defines an industrial-grade behavioral standard for mobile engineering. Guarantees Swift Concurrency Task cancellation trees bidirectionally propagate into native Kotlin Multiplatform Job hierarchies and vice versa. Prevents orphaned background dispatchers, unmanaged CoroutineScopes, and native memory leaks caused by retained Cinterop/Obj-C blocks. 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: Unlinked Swift Task wrapping that drops cooperative cancellation signals and leaks Kotlin Native worker threads 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 DriftUnlinked Swift Task wrapping that drops cooperative cancellation signals and leaks Kotlin Native worker threadsCritical
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 wrap bridged Kotlin suspend calls inside Swift's `withTaskCancellationHandler` to immediately relay cancellation to the active Kotlin `Job` or `Cancellable` wrapper.

Engineers MUST ALWAYS wrap bridged Kotlin suspend calls inside Swift's `withTaskCancellationHandler` to immediately relay cancellation to the active Kotlin `Job` or `Cancellable` wrapper.

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 rely on unchecked Swift `Task { await ... }` blocks when calling KMP suspend functions without retaining and linking the underlying Kotlin Job reference.

Engineers MUST NOT rely on unchecked Swift `Task { await ... }` blocks when calling KMP suspend functions without retaining and linking the underlying Kotlin Job reference.

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 enforce structured lifecycle bridging where Swift `AsyncSequence` adapters for Kotlin `Flow` explicitly invoke `Closeable.close()` or `Job.cancel()` upon iterator termination or task deallocation.

Code SHOULD enforce structured lifecycle bridging where Swift `AsyncSequence` adapters for Kotlin `Flow` explicitly invoke `Closeable.close()` or `Job.cancel()` upon iterator termination or task deallocation.

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 Kotlin Native dispatchers release native memory references immediately when `CancellationException` is caught across the Cinterop boundary.

Services MUST ensure Kotlin Native dispatchers release native memory references immediately when `CancellationException` is caught across the Cinterop 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.
5

Components NEVER hold strong bidirectional references between Swift completion handlers and Kotlin CoroutineScope instances

Components NEVER hold strong bidirectional references between Swift completion handlers and Kotlin CoroutineScope instances; weak reference semantics or explicit unbinding MUST be enforced.

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-Export Cancellation Interlock Standard critical for AI coding assistants?

Guarantees Swift Concurrency Task cancellation trees bidirectionally propagate into native Kotlin Multiplatform Job hierarchies and vice versa. Prevents orphaned background dispatchers, unmanaged CoroutineScopes, and native memory leaks caused by retained Cinterop/Obj-C blocks. 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 (Unlinked Swift Task wrapping that drops cooperative cancellation signals and leaks Kotlin Native worker threads) 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