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

KMP Native Coroutine ARC Scope Bridging and Bidirectional Cancellation Guardrail

Enforces deterministic memory deallocation and bidirectional cancellation when bridging Kotlin Multiplatform (KMP) Flows and CoroutineScopes into Swift Concurrency. Eliminates dangling native coroutine handles, cross-runtime ARC retain cycles, and silent thread pool exhaustion on iOS.

Prohibited Anti-Pattern: Leaking KMP CoroutineJobs in Unstructured Swift Tasks with Implicit Strong ARC Self-Captures

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Native Coroutine ARC Scope Bridging and Bidirectional Cancellation Guardrail - Enforces deterministic memory deallocation and bidirectional cancellation when bridging Kotlin Multiplatform (KMP) Flows and CoroutineScopes into Swift Concurrency. Eliminates dangling native coroutine handles, cross-runtime ARC retain cycles, and silent thread pool exhaustion on iOS.
globs: iosApp/**/*.swift, shared/src/iosMain/**/*.kt, **/*Bridge*.{swift,kt}, **/*Adapter*.{swift,kt}, **/*ViewModel*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-native-coroutine-arc-bridge-invariant"
---

# KMP Native Coroutine ARC Scope Bridging and Bidirectional Cancellation Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Leaking KMP CoroutineJobs in Unstructured Swift Tasks with Implicit Strong ARC Self-Captures

## System Constraints
You are a Principal Software Architect enforcing the KMP Native Coroutine ARC Scope Bridging Invariant. Engineers and AI agents frequently create catastrophic memory leaks and zombie collectors when bridging Kotlin Coroutines/Flows across the Objective-C/Swift bridge into Swift Concurrency. You must strictly mandate bidirectional cancellation propagation, weak reference captures, and explicit Scope disposal via withTaskCancellationHandler or proper AsyncSequence adapter boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS wrap Swift-consumed Kotlin Flows in an AsyncSequence that binds Swift Task cancellation directly to the underlying Kotlin DisposableHandle/Job.cancel().
- Engineers MUST NOT invoke Kotlin suspend functions or Flow collectors inside an unstructured Task.detached without explicitly propagating structured cancellation and life-cycle ownership.
- Bridging closures passing Swift closures to Kotlin callbacks MUST capture Swift dependencies weakly ([weak self]) to break cross-runtime strong reference cycles between ARC and Kotlin's Garbage Collector.
- Swift ViewModels or presenters bridging Kotlin CoroutineScopes MUST explicitly invoke CoroutineScope.cancel() in their Swift deinit or when the associated SwiftUI view disappears.
- Code MUST NEVER use raw, unchecked completion handlers across the C-interop boundary without defensive error handling for CancellationException to avoid unhandled NSExceptions.

## Bad vs Good Implementations
### Bridging Kotlin Flow to Swift AsyncSequence with Bidirectional Cancellation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Swift Task captures 'self' strongly, forming a cross-runtime retain cycle between the Kotlin FlowCollector and the Swift ViewModel. Furthermore, when the Swift UI lifecycle ends, the Kotlin Flow collection is not cancelled, silently burning network and CPU resources in the background.
```swift
import SharedLibrary

final class UserProfileViewModel: ObservableObject {
    @Published var profile: UserProfile? = nil
    private let repository: UserRepository

    init(repository: UserRepository) {
        self.repository = repository
        // BUG: Unstructured Task creates strong retain cycle and ignores scope cancellation.
        // If the ViewModel is deallocated, the Kotlin Flow remains active on the background thread.
        Task {
            self.repository.observeProfile().collect(collector: FlowCollector {
                self.profile = $0
            }) { error in
                if let error = error { print("Flow error: \(error)") }
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Uses an AsyncStream bounded to a weak self capture. The AsyncStream's onTermination hook guarantees that cancelling the Swift Task calls handle.dispose() on the Kotlin DisposableHandle, cleanly severing the flow collector and breaking ARC retain cycles on ViewModel deinit.
```swift
import SharedLibrary

final class UserProfileViewModel: ObservableObject {
    @Published private(set) var profile: UserProfile? = nil
    private let repository: UserRepository
    private var observeTask: Task<Void, Never>? = nil

    init(repository: UserRepository) {
        self.repository = repository
        bindProfileStream()
    }

    private func bindProfileStream() {
        observeTask = Task { [weak self] in
            // Invariant: Bridge Kotlin Flow into an AsyncStream with explicit cancellation hook
            let stream = AsyncStream<UserProfile> { continuation in
                guard let self = self else { continuation.finish(); return }
                let handle = self.repository.observeProfile().subscribe(
                    onEach: { profile in continuation.yield(profile) },
                    onCompletion: { error in continuation.finish() }
                )
                continuation.onTermination = { @Sendable _ in
                    // Enforce Swift-to-Kotlin cancellation propagation
                    handle.dispose()
                }
            }

            for await profile in stream {
                guard !Task.isCancelled else { break }
                await MainActor.run { [weak self] in
                    self?.profile = profile
                }
            }
        }
    }

    deinit {
        observeTask?.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 Native Coroutine ARC Scope Bridging and Bidirectional Cancellation Guardrail

KMP Native Coroutine ARC Scope Bridging and Bidirectional Cancellation Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic memory deallocation and bidirectional cancellation when bridging Kotlin Multiplatform (KMP) Flows and CoroutineScopes into Swift Concurrency. Eliminates dangling native coroutine handles, cross-runtime ARC retain cycles, and silent thread pool exhaustion on iOS. 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 KMP CoroutineJobs in Unstructured Swift Tasks with Implicit Strong ARC Self-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 KMP CoroutineJobs in Unstructured Swift Tasks with Implicit Strong ARC Self-CapturesCritical
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 Swift-consumed Kotlin Flows in an AsyncSequence that binds Swift Task cancellation directly to the underlying Kotlin DisposableHandle/Job.cancel().

Engineers MUST ALWAYS wrap Swift-consumed Kotlin Flows in an AsyncSequence that binds Swift Task cancellation directly to the underlying Kotlin DisposableHandle/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 invoke Kotlin suspend functions or Flow collectors inside an unstructured Task.detached without explicitly propagating structured cancellation and life-cycle ownership.

Engineers MUST NOT invoke Kotlin suspend functions or Flow collectors inside an unstructured Task.detached without explicitly propagating structured cancellation and life-cycle ownership.

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

Bridging closures passing Swift closures to Kotlin callbacks MUST capture Swift dependencies weakly ([weak self]) to break cross-runtime strong reference cycles between ARC and Kotlin's Garbage Collector.

Bridging closures passing Swift closures to Kotlin callbacks MUST capture Swift dependencies weakly ([weak self]) to break cross-runtime strong reference cycles between ARC and Kotlin's Garbage Collector.

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 ViewModels or presenters bridging Kotlin CoroutineScopes MUST explicitly invoke CoroutineScope.cancel() in their Swift deinit or when the associated SwiftUI view disappears.

Swift ViewModels or presenters bridging Kotlin CoroutineScopes MUST explicitly invoke CoroutineScope.cancel() in their Swift deinit or when the associated SwiftUI view disappears.

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

Code MUST NEVER use raw, unchecked completion handlers across the C-interop boundary without defensive error handling for CancellationException to avoid unhandled NSExceptions.

Code MUST NEVER use raw, unchecked completion handlers across the C-interop boundary without defensive error handling for CancellationException to avoid unhandled NSExceptions.

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 Native Coroutine ARC Scope Bridging and Bidirectional Cancellation Guardrail critical for AI coding assistants?

Enforces deterministic memory deallocation and bidirectional cancellation when bridging Kotlin Multiplatform (KMP) Flows and CoroutineScopes into Swift Concurrency. Eliminates dangling native coroutine handles, cross-runtime ARC retain cycles, and silent thread pool exhaustion on iOS. 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 KMP CoroutineJobs in Unstructured Swift Tasks with Implicit Strong ARC Self-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

KMP