This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-swift-coroutines-memory-boundary-safety

KMP to Swift Coroutine Bridge Memory Leak and Cancellation Safety

Prevents catastrophic memory leaks and zombie execution states across the Kotlin Native and Swift ARC memory boundaries. Calling suspend functions or collecting Kotlin StateFlows directly from Swift creates uncollected bridge references and unhandled Job lifecycles. All bridging must enforce structural cancellation bindings to Swift Task contexts or SwiftUI lifecycle owners via wrapped disposable adapters.

Prohibited Anti-Pattern: Unbounded Swift Async/Await Bridging of Kotlin Coroutines Causing ARC Cyclic Retain Leaks and Dangling Native Jobs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP to Swift Coroutine Bridge Memory Leak and Cancellation Safety - Prevents catastrophic memory leaks and zombie execution states across the Kotlin Native and Swift ARC memory boundaries. Calling suspend functions or collecting Kotlin StateFlows directly from Swift creates uncollected bridge references and unhandled Job lifecycles. All bridging must enforce structural cancellation bindings to Swift Task contexts or SwiftUI lifecycle owners via wrapped disposable adapters.
globs: iosApp/**/*.swift, shared/**/*.kt, composeApp/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-coroutines-memory-boundary-safety"
---

# KMP to Swift Coroutine Bridge Memory Leak and Cancellation Safety

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Swift Async/Await Bridging of Kotlin Coroutines Causing ARC Cyclic Retain Leaks and Dangling Native Jobs

## System Constraints
You are a Principal Mobile Architect enforcing strict memory and concurrency boundaries between Kotlin Multiplatform (Kotlin/Native) and Apple Swift (ARC). Mandate explicit cancellation bridges, prevent strong reference cycles in coroutine continuations, and enforce structured lifecycle teardown across the foreign function boundary.

## Strict Guidelines
- Engineers MUST ALWAYS expose Kotlin Flows to Swift via a lifecycle-aware wrapper (e.g., SKIE or custom Cinterop DisposableHandle) that attaches cancellation to Swift Task or SwiftUI view lifecycles.
- Engineers MUST NOT bridge Kotlin suspend functions directly into Swift using raw Objective-C exported completions without unregistering completion closures or tying them to swift withTaskCancellationHandler.
- Swift clients MUST capture references weakly ([weak self]) inside any task or observation scope invoking Kotlin Native suspend functions to prevent ARC root cycles from retaining Kotlin Job instances.
- Kotlin Native exports MUST avoid retaining Swift completion handlers across indeterminate dispatch boundaries without an explicit timeout or cancellation mechanism.
- Services exposing CoroutineScope across KMP boundaries MUST implement explicit Closeable or Cancellable cleanup protocols that Swift view models trigger during deinit or View.onDisappear.

## Bad vs Good Implementations
### SwiftUI Consumption of Kotlin Coroutines without ARC Retain Cycles

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin's Objective-C exported completion handler retains the Swift closure strongly. Because the closure implicitly or explicitly captures 'self' strongly, and the Kotlin scope continues executing, the Swift ViewModel cannot be deallocated by ARC, leaking memory and running useless work.
```swift
import SwiftUI
import SharedKit

class ProfileViewModel: ObservableObject {
    @Published var user: User? = nil
    private let repository = UserRepository()

    func startObserving() {
        // CRITICAL BUG: Directly invoking raw bridged completion creates an ARC cycle.
        // Swift closure captures strong `self`, and Kotlin CoroutineScope holds the bridge continuation forever
        // if the screen pops before execution finishes, causing a silent zombie leak.
        repository.observeUser { [self] result, _ in
            if let user = result {
                self.user = user
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Leverages Swift AsyncSequence with structured concurrency. The task explicitly captures weak self, cleans up on deinit, and breaks the reference link across the Kotlin Native concurrent memory manager boundary.
```swift
import SwiftUI
import SharedKit

@MainActor
final class ProfileViewModel: ObservableObject {
    @Published private(set) var user: User? = nil
    private let repository: UserRepository
    private var observationTask: Task<Void, Never>? = nil

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

    func startObserving() {
        observationTask?.cancel()
        observationTask = Task { [weak self] in
            // Enforce task-bound cancellation and weak closure capturing
            do {
                for await user in self?.repository.userFlow.asAsyncSequence() ?? [] {
                    guard !Task.isCancelled, let self else { break }
                    self.user = user
                }
            } catch {
                // Handle cancellation cleanly across the boundary
            }
        }
    }

    deinit {
        observationTask?.cancel()
    }
}
```

### Kotlin Side Cancellation Adapter for Swift Bridging

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Flow collection never stops because there is no handle or cancellation mechanism returned to the foreign language runtime, causing infinite coroutine execution in Kotlin Native.
```kotlin
package com.example.shared

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

class UserRepository {
    private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
    private val _userFlow = MutableStateFlow<User?>(null)
    
    // CRITICAL BUG: Raw iOS export has no cancellation mechanism.
    // Once invoked from Swift, cancellation cannot be propagated upstream to cancel downstream network/DB work.
    fun observeUser(callback: (User?) -> Unit) {
        scope.launch {
            _userFlow.collect { callback(it) }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Returns a deterministic BridgeCancellable back to Swift, allowing ARC deinit or Swift Task scopes to trigger Job.cancel() upstream across the native memory boundary.
```kotlin
package com.example.shared

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

interface BridgeCancellable {
    fun cancel()
}

class UserRepository {
    private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
    val userFlow: StateFlow<User?> = MutableStateFlow<User?>(null)

    fun subscribe(onUpdate: (User?) -> Unit): BridgeCancellable {
        val job = scope.launch {
            userFlow.collect { onUpdate(it) }
        }
        return object : BridgeCancellable {
            override fun cancel() {
                job.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 to Swift Coroutine Bridge Memory Leak and Cancellation Safety

KMP to Swift Coroutine Bridge Memory Leak and Cancellation Safety defines an industrial-grade behavioral standard for mobile engineering. Prevents catastrophic memory leaks and zombie execution states across the Kotlin Native and Swift ARC memory boundaries. Calling suspend functions or collecting Kotlin StateFlows directly from Swift creates uncollected bridge references and unhandled Job lifecycles. All bridging must enforce structural cancellation bindings to Swift Task contexts or SwiftUI lifecycle owners via wrapped disposable adapters. 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: Unbounded Swift Async/Await Bridging of Kotlin Coroutines Causing ARC Cyclic Retain Leaks and Dangling Native Jobs 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 DriftUnbounded Swift Async/Await Bridging of Kotlin Coroutines Causing ARC Cyclic Retain Leaks and Dangling Native JobsCritical
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 expose Kotlin Flows to Swift via a lifecycle-aware wrapper (e.g., SKIE or custom Cinterop DisposableHandle) that attaches cancellation to Swift Task or SwiftUI view lifecycles.

Engineers MUST ALWAYS expose Kotlin Flows to Swift via a lifecycle-aware wrapper (e.g., SKIE or custom Cinterop DisposableHandle) that attaches cancellation to Swift Task or SwiftUI view lifecycles.

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 bridge Kotlin suspend functions directly into Swift using raw Objective-C exported completions without unregistering completion closures or tying them to swift withTaskCancellationHandler.

Engineers MUST NOT bridge Kotlin suspend functions directly into Swift using raw Objective-C exported completions without unregistering completion closures or tying them to swift withTaskCancellationHandler.

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

Swift clients MUST capture references weakly ([weak self]) inside any task or observation scope invoking Kotlin Native suspend functions to prevent ARC root cycles from retaining Kotlin Job instances.

Swift clients MUST capture references weakly ([weak self]) inside any task or observation scope invoking Kotlin Native suspend functions to prevent ARC root cycles from retaining Kotlin Job instances.

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

Kotlin Native exports MUST avoid retaining Swift completion handlers across indeterminate dispatch boundaries without an explicit timeout or cancellation mechanism.

Kotlin Native exports MUST avoid retaining Swift completion handlers across indeterminate dispatch boundaries without an explicit timeout or cancellation mechanism.

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 exposing CoroutineScope across KMP boundaries MUST implement explicit Closeable or Cancellable cleanup protocols that Swift view models trigger during deinit or View.onDisappear.

Services exposing CoroutineScope across KMP boundaries MUST implement explicit Closeable or Cancellable cleanup protocols that Swift view models trigger during deinit or View.onDisappear.

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 to Swift Coroutine Bridge Memory Leak and Cancellation Safety critical for AI coding assistants?

Prevents catastrophic memory leaks and zombie execution states across the Kotlin Native and Swift ARC memory boundaries. Calling suspend functions or collecting Kotlin StateFlows directly from Swift creates uncollected bridge references and unhandled Job lifecycles. All bridging must enforce structural cancellation bindings to Swift Task contexts or SwiftUI lifecycle owners via wrapped disposable adapters. 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 (Unbounded Swift Async/Await Bridging of Kotlin Coroutines Causing ARC Cyclic Retain Leaks and Dangling Native Jobs) 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