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

Kotlin 2.1 & Swift Concurrency ARC Cooperative Cancellation Bridge Standard

Enforces deterministic memory lifecycle management and bi-directional cooperative task cancellation when bridging Kotlin Multiplatform 2.1 coroutines with Swift async/await. Eliminates cross-runtime ARC-to-Kotlin-GC reference cycles, dangling continuation leaks, and thread-starvation deadlocks.

Prohibited Anti-Pattern: Leaking unmanaged Kotlin Job handles and creating zombie coroutines via unlinked Swift Task cancellations and strong closure captures.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin 2.1 & Swift Concurrency ARC Cooperative Cancellation Bridge Standard - Enforces deterministic memory lifecycle management and bi-directional cooperative task cancellation when bridging Kotlin Multiplatform 2.1 coroutines with Swift async/await. Eliminates cross-runtime ARC-to-Kotlin-GC reference cycles, dangling continuation leaks, and thread-starvation deadlocks.
globs: iosApp/**/*.swift, **/iosMain/**/*.kt, **/*Ios.kt, **/*Bridge*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-concurrency-arc-task-bridge-guardrail"
---

# Kotlin 2.1 & Swift Concurrency ARC Cooperative Cancellation Bridge Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Leaking unmanaged Kotlin Job handles and creating zombie coroutines via unlinked Swift Task cancellations and strong closure captures.

## System Constraints
You are a Principal Engineer enforcing strict Kotlin Multiplatform 2.1 and Swift Concurrency ARC interoperability. Mandate invariants that eliminate cross-runtime reference cycles, prevent dangling continuations, and enforce strict bi-directional cooperative cancellation across Kotlin Coroutines and Swift async/await Tasks.

## Strict Guidelines
- Engineers MUST ALWAYS wrap Kotlin suspend bridges inside `withTaskCancellationHandler` to propagate Swift Task cancellations directly to the underlying Kotlin `Job.cancel()`.
- Engineers MUST NOT strongly capture Swift continuations or Kotlin `Job` references inside asynchronous callbacks where cancellation can preempt resumption.
- Code MUST guarantee that `CheckedContinuation` or `UnsafeContinuation` is resumed EXACTLY ONCE; engineers MUST guard resumption using an atomic gate or thread-safe state machine to avoid Swift runtime continuation panic.
- Services MUST dispatch Kotlin background operations using detached scopes or structured bridge adapters, NEVER holding raw objective-c pointers to Kotlin coroutines past the Swift Task lifetime.
- Components NEVER block the Swift `@MainActor` with synchronous locks or thread-waiting mechanisms waiting for Kotlin `Dispatchers.Main` executions, preventing inter-runtime mutual exclusion deadlocks.

## Bad vs Good Implementations
### Bridging Kotlin Suspend Function to Swift async/await with ARC & Cancellation Safe Hooks

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to propagate Swift cooperative cancellation to Kotlin Native. If the parent Swift Task is cancelled before the network/database returns, the completion handler may never be invoked or may invoke a continuation that is already discarded. Strong references retained across the Kotlin-ObjC boundary leak ARC allocations and cause zombie execution.
```swift
import Shared

final class ProfileViewModel {
    private let repository: UserRepository
    
    init(repository: UserRepository) {
        self.repository = repository
    }
    
    func loadUserData() async throws -> UserData {
        // ANTI-PATTERN: Raw continuation without cancellation binding.
        // If the Swift Task is cancelled, the Kotlin coroutine continues executing,
        // holding repository and ViewModel in an ARC cycle, leaking native memory.
        return try await withCheckedThrowingContinuation { continuation in
            repository.fetchUserData { data, error in
                if let error = error {
                    continuation.resume(throwing: error)
                } else if let data = data {
                    continuation.resume(returning: data)
                }
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Properly links Swift's `withTaskCancellationHandler` to the Kotlin `Job.cancel()`. Protects the continuation from multiple resumptions using `OSAllocatedUnfairLock`, prevents ARC retention cycles, and preempts Kotlin coroutine execution if the Swift Task is already cancelled before starting.
```swift
import Shared
import Foundation

final class ProfileViewModel: @unchecked Sendable {
    private let repository: UserRepository
    
    init(repository: UserRepository) {
        self.repository = repository
    }
    
    func loadUserData() async throws -> UserData {
        try Task.checkCancellation()
        
        let handle = AtomicJobHandle()
        
        return try await withTaskCancellationHandler {
            try await withCheckedThrowingContinuation { continuation in
                let isResumed = OSAllocatedUnfairLock(initialState: false)
                
                let job = repository.fetchUserData {
                    data, error in
                    isResumed.withLock { resumed in
                        guard !resumed else { return }
                        resumed = true
                        
                        if let error = error {
                            continuation.resume(throwing: error)
                        } else if let data = data {
                            continuation.resume(returning: data)
                        } else {
                            continuation.resume(throwing: CancellationError())
                        }
                    }
                }
                
                handle.set(job)
            }
        } onCancel: {
            // Cooperatively cancel the Kotlin coroutine Job immediately
            handle.cancel()
        }
    }
}

private final class AtomicJobHandle: @unchecked Sendable {
    private let lock = OSAllocatedUnfairLock<Kotlinx_coroutines_coreJob?>(initialState: nil)
    
    func set(_ job: Kotlinx_coroutines_coreJob) {
        lock.withLock { $0 = job }
    }
    
    func cancel() {
        lock.withLock {
            $0?.cancel(cause: nil)
            $0 = 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 2.1 & Swift Concurrency ARC Cooperative Cancellation Bridge Standard

Kotlin 2.1 & Swift Concurrency ARC Cooperative Cancellation Bridge Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic memory lifecycle management and bi-directional cooperative task cancellation when bridging Kotlin Multiplatform 2.1 coroutines with Swift async/await. Eliminates cross-runtime ARC-to-Kotlin-GC reference cycles, dangling continuation leaks, and thread-starvation deadlocks. 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: Leaking unmanaged Kotlin Job handles and creating zombie coroutines via unlinked Swift Task cancellations and strong closure captures. 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 DriftLeaking unmanaged Kotlin Job handles and creating zombie coroutines via unlinked Swift Task cancellations and strong closure captures.Critical
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 Kotlin suspend bridges inside `withTaskCancellationHandler` to propagate Swift Task cancellations directly to the underlying Kotlin `Job.cancel()`.

Engineers MUST ALWAYS wrap Kotlin suspend bridges inside `withTaskCancellationHandler` to propagate Swift Task cancellations directly to the underlying Kotlin `Job.cancel()`.

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 strongly capture Swift continuations or Kotlin `Job` references inside asynchronous callbacks where cancellation can preempt resumption.

Engineers MUST NOT strongly capture Swift continuations or Kotlin `Job` references inside asynchronous callbacks where cancellation can preempt resumption.

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 MUST guarantee that `CheckedContinuation` or `UnsafeContinuation` is resumed EXACTLY ONCE

Code MUST guarantee that `CheckedContinuation` or `UnsafeContinuation` is resumed EXACTLY ONCE; engineers MUST guard resumption using an atomic gate or thread-safe state machine to avoid Swift runtime continuation panic.

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 dispatch Kotlin background operations using detached scopes or structured bridge adapters, NEVER holding raw objective-c pointers to Kotlin coroutines past the Swift Task lifetime.

Services MUST dispatch Kotlin background operations using detached scopes or structured bridge adapters, NEVER holding raw objective-c pointers to Kotlin coroutines past the Swift Task lifetime.

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 block the Swift `@MainActor` with synchronous locks or thread-waiting mechanisms waiting for Kotlin `Dispatchers.Main` executions, preventing inter-runtime mutual exclusion deadlocks.

Components NEVER block the Swift `@MainActor` with synchronous locks or thread-waiting mechanisms waiting for Kotlin `Dispatchers.Main` executions, preventing inter-runtime mutual exclusion deadlocks.

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 2.1 & Swift Concurrency ARC Cooperative Cancellation Bridge Standard critical for AI coding assistants?

Enforces deterministic memory lifecycle management and bi-directional cooperative task cancellation when bridging Kotlin Multiplatform 2.1 coroutines with Swift async/await. Eliminates cross-runtime ARC-to-Kotlin-GC reference cycles, dangling continuation leaks, and thread-starvation deadlocks. 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 (Leaking unmanaged Kotlin Job handles and creating zombie coroutines via unlinked Swift Task cancellations and strong closure captures.) 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