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

KMP 2.1 Swift Export Cross-Runtime ARC-to-GC Memory Lifecycle Guardrail

Enforces strict lifecycle boundaries and bridge patterns between Apple ARC and Kotlin Native Garbage Collection (GC) in KMP 2.1+ Swift Export environments. Eliminates cross-language retain cycles, dangling Swift closure references, and premature deallocation of asynchronous Kotlin Coroutine Scopes bridged into iOS native runtimes.

Prohibited Anti-Pattern: Retaining Strong Kotlin Native References in Swift Closures and Escaping Native Observers Without ARC Disposables

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP 2.1 Swift Export Cross-Runtime ARC-to-GC Memory Lifecycle Guardrail - Enforces strict lifecycle boundaries and bridge patterns between Apple ARC and Kotlin Native Garbage Collection (GC) in KMP 2.1+ Swift Export environments. Eliminates cross-language retain cycles, dangling Swift closure references, and premature deallocation of asynchronous Kotlin Coroutine Scopes bridged into iOS native runtimes.
globs: iosApp/**/*.swift, shared/src/iosMain/**/*.kt, shared/src/commonMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-memory-lifecycle-guardrail"
---

# KMP 2.1 Swift Export Cross-Runtime ARC-to-GC Memory Lifecycle Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Retaining Strong Kotlin Native References in Swift Closures and Escaping Native Observers Without ARC Disposables

## System Constraints
You are a Principal Mobile Architect enforcing rock-solid memory safety across Kotlin Multiplatform 2.1 Swift Export boundaries. The bridging boundary between Kotlin Native's tracing garbage collector and Apple's Automatic Reference Counting (ARC) is prone to bidirectional retain cycles, hidden rootings, and orphaned asynchronous tasks. You must mandate unmanaged ARC handle safety, explicit lifecycle disposal tokens, weak capturing across bridged callbacks, and safe Kotlin Coroutine bridging.

## Strict Guidelines
- Engineers MUST ALWAYS expose an explicit, idempotent `Disposable` or `Cancellable` token from Kotlin whenever long-lived streams, listeners, or Coroutine scopes are bridged to Swift.
- Engineers MUST NOT capture strong Swift instance references inside callbacks or closures passed down into long-lived Kotlin objects; closures passed across the boundary MUST use `[weak self]`.
- Swift bridging layers MUST cancel and release Kotlin subscription handles inside `deinit` or SwiftUI `onDisappear` life-cycle hooks to break GC root retention.
- Kotlin Native exports MUST NEVER hold strong references to Swift delegate protocols or closures beyond the immediate call stack unless wrapped inside explicit lifecycle-managed weak wrappers.
- Engineers MUST use structured cancellation via `kotlinx.coroutines.Job` termination rather than relying on GC finalizers (`Cleaner`) to tear down bridged native resources.
- Code MUST prevent Swift UI views from directly holding long-running Kotlin Coroutine Job instances without binding their lifecycle to the corresponding view's `Task` or view-model deallocation.

## Bad vs Good Implementations
### Observing Kotlin Shared Flow in Swift UI / ViewModel

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin Native holds a strong reference to the callback lambda, which strongly retains `self` (ProfileViewModel). Because Swift also retains `userManager`, a cross-language reference cycle is established: Kotlin GC roots the closure, and Swift ARC roots the Kotlin instance. Neither can ever be collected.
```swift
import SwiftUI
import SharedKit

final class ProfileViewModel: ObservableObject {
    @Published var userName: String = ""
    private let userManager = UserManager()

    func startObserving() {
        // ANTI-PATTERN: Strong capture of self in Kotlin callback bridge;
        // ignores returned Disposable token, creating a cross-boundary ARC-GC leak.
        userManager.observeProfile { profile in
            self.userName = profile.name
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Using `[weak self]` eliminates the retain cycle from Kotlin Native into Swift ARC. Storing and explicitly disposing of `DisposableHandle` in `deinit` instructs Kotlin Native to detach the listener and release GC root anchors.
```swift
import SwiftUI
import SharedKit

final class ProfileViewModel: ObservableObject {
    @Published var userName: String = ""
    private let userManager = UserManager()
    private var profileSubscription: DisposableHandle? = nil

    func startObserving() {
        profileSubscription?.dispose()
        // PRODUCTION FIX: Capture [weak self] and capture subscription handle for explicit teardown
        profileSubscription = userManager.observeProfile { [weak self] profile in
            guard let self = self else { return }
            Task { @MainActor in
                self.userName = profile.name
            }
        }
    }

    deinit {
        profileSubscription?.dispose()
        profileSubscription = nil
    }
}
```

### Kotlin Side Native Callback & Lifecycle Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Kotlin collection indefinitely retains foreign function wrappers originating from Swift's runtime without providing cancellation handles, permanently leaking native Swift execution frames and contexts.
```kotlin
// Shared Kotlin Code (commonMain / iosMain)
class ProfileRepository {
    private val listeners = mutableListOf<(Profile) -> Unit>()

    // ANTI-PATTERN: Indefinitely stores un-scoped function pointers crossing the Swift bridge
    fun observeProfile(callback: (Profile) -> Unit) {
        listeners.add(callback)
    }
}
```

#### Production Standard (Correct)
> **Standard**: Returns a clean `DisposableHandle` that wraps Coroutine Job cancellation. Once disposed, the coroutine unregisters, dropping the closure reference and freeing the bridged Swift wrapper from the Kotlin Native root set.
```kotlin
// Shared Kotlin Code (commonMain / iosMain)
import kotlinx.coroutines.*

interface DisposableHandle {
    fun dispose()
}

class ProfileRepository(private val coroutineScope: CoroutineScope) {
    fun observeProfile(callback: (Profile) -> Unit): DisposableHandle {
        val job = coroutineScope.launch(Dispatchers.Main.immediate) {
            profileFlow.collect { profile ->
                callback(profile)
            }
        }
        return object : DisposableHandle {
            override fun dispose() {
                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 2.1 Swift Export Cross-Runtime ARC-to-GC Memory Lifecycle Guardrail

KMP 2.1 Swift Export Cross-Runtime ARC-to-GC Memory Lifecycle Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict lifecycle boundaries and bridge patterns between Apple ARC and Kotlin Native Garbage Collection (GC) in KMP 2.1+ Swift Export environments. Eliminates cross-language retain cycles, dangling Swift closure references, and premature deallocation of asynchronous Kotlin Coroutine Scopes bridged into iOS native runtimes. 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: Retaining Strong Kotlin Native References in Swift Closures and Escaping Native Observers Without ARC Disposables 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 DriftRetaining Strong Kotlin Native References in Swift Closures and Escaping Native Observers Without ARC DisposablesCritical
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 an explicit, idempotent `Disposable` or `Cancellable` token from Kotlin whenever long-lived streams, listeners, or Coroutine scopes are bridged to Swift.

Engineers MUST ALWAYS expose an explicit, idempotent `Disposable` or `Cancellable` token from Kotlin whenever long-lived streams, listeners, or Coroutine scopes are bridged to Swift.

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 capture strong Swift instance references inside callbacks or closures passed down into long-lived Kotlin objects

Engineers MUST NOT capture strong Swift instance references inside callbacks or closures passed down into long-lived Kotlin objects; closures passed across the boundary MUST use `[weak self]`.

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 bridging layers MUST cancel and release Kotlin subscription handles inside `deinit` or SwiftUI `onDisappear` life-cycle hooks to break GC root retention.

Swift bridging layers MUST cancel and release Kotlin subscription handles inside `deinit` or SwiftUI `onDisappear` life-cycle hooks to break GC root retention.

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 NEVER hold strong references to Swift delegate protocols or closures beyond the immediate call stack unless wrapped inside explicit lifecycle-managed weak wrappers.

Kotlin Native exports MUST NEVER hold strong references to Swift delegate protocols or closures beyond the immediate call stack unless wrapped inside explicit lifecycle-managed weak wrappers.

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

Engineers MUST use structured cancellation via `kotlinx.coroutines.Job` termination rather than relying on GC finalizers (`Cleaner`) to tear down bridged native resources.

Engineers MUST use structured cancellation via `kotlinx.coroutines.Job` termination rather than relying on GC finalizers (`Cleaner`) to tear down bridged native resources.

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

Code MUST prevent Swift UI views from directly holding long-running Kotlin Coroutine Job instances without binding their lifecycle to the corresponding view's `Task` or view-model deallocation.

Code MUST prevent Swift UI views from directly holding long-running Kotlin Coroutine Job instances without binding their lifecycle to the corresponding view's `Task` or view-model 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is KMP 2.1 Swift Export Cross-Runtime ARC-to-GC Memory Lifecycle Guardrail critical for AI coding assistants?

Enforces strict lifecycle boundaries and bridge patterns between Apple ARC and Kotlin Native Garbage Collection (GC) in KMP 2.1+ Swift Export environments. Eliminates cross-language retain cycles, dangling Swift closure references, and premature deallocation of asynchronous Kotlin Coroutine Scopes bridged into iOS native runtimes. 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 (Retaining Strong Kotlin Native References in Swift Closures and Escaping Native Observers Without ARC Disposables) 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