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

KMP 2.1 Swift-Export Cross-Runtime ARC/GC Retain Cycle Guardrail

Enforces deterministic lifecycle-bound reference disposal and weak bridge wrappers between Swift ARC and Kotlin/Native 2.1 GC runtimes. Prevents uncollected native heap islands caused by cyclic references across the Swift-Kotlin interop boundary where neither runtime can traverse cross-boundary reference graphs.

Prohibited Anti-Pattern: Invisible Cross-Runtime Retain Cycles Between Swift ARC and Kotlin Tracing GC

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP 2.1 Swift-Export Cross-Runtime ARC/GC Retain Cycle Guardrail - Enforces deterministic lifecycle-bound reference disposal and weak bridge wrappers between Swift ARC and Kotlin/Native 2.1 GC runtimes. Prevents uncollected native heap islands caused by cyclic references across the Swift-Kotlin interop boundary where neither runtime can traverse cross-boundary reference graphs.
globs: **/*.kt, **/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-interop-retain-cycle-guardrail"
---

# KMP 2.1 Swift-Export Cross-Runtime ARC/GC Retain Cycle Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Invisible Cross-Runtime Retain Cycles Between Swift ARC and Kotlin Tracing GC

## System Constraints
You are a Principal Software Architect enforcing deterministic cross-runtime memory management across Kotlin Multiplatform 2.1 (Swift-Export) and iOS Swift ARC. Kotlin/Native concurrent GC and Apple ARC cannot traverse each other's heap graphs. You must mandate explicit lifecycle teardown contracts, weak bridge delegates, and capture-list sanitization on all cross-runtime boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS implement an explicit lifecycle unbind or dispose contract (e.g., `close()`, `detach()`) on exported Kotlin classes that retain Swift delegate or callback references.
- Engineers MUST NOT pass Swift closures that strongly capture reference types (`self`) into Kotlin-exported state observers, flows, or long-lived coroutine bridges.
- Code SHOULD enforce weak reference wrapping on Swift-side delegate implementations that are consumed by Kotlin/Native exported interfaces.
- Swift components MUST explicitly trigger Kotlin cancellation/detachment in view teardown hooks (such as SwiftUI `.onDisappear` or UIKit `viewDidDisappear`/`deinit`).
- Components NEVER assume that Swift `deinit` will execute automatically if a long-lived Kotlin instance holds an unmanaged reference back to a Swift class; ARC retain count remains pinned at >= 1 indefinitely.

## Bad vs Good Implementations
### SwiftUI ViewModel Subscribing to Kotlin 2.1 Swift-Export Store

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin's ProfileStore holds a reference to the Swift closure on the Kotlin Native heap. The closure strongly captures self (ProfileViewModel), and ProfileViewModel holds store. Because Kotlin GC cannot trace Swift retain counts and ARC cannot trace Kotlin GC roots, neither runtime reclaims the memory, leaking the entire screen hierarchy.
```swift
import SwiftUI
import SharedKit

@Observable
final class ProfileViewModel {
    private let store: ProfileStore // Exported Kotlin class
    var state: ProfileState = .initial

    init(store: ProfileStore = ProfileStore()) {
        self.store = store
        // FATAL: Strongly capturing self in a closure held by Kotlin Native heap.
        // ProfileStore (Kotlin) keeps the closure; closure retains self (ARC).
        // self retains store (ARC). deinit will NEVER fire; both runtimes leak permanently.
        self.store.observeState { newState in
            self.state = newState
        }
    }

    deinit {
        print("ProfileViewModel deinit") // Never executed
    }
}
```

#### Production Standard (Correct)
> **Standard**: Using [weak self] prevents ARC from being retained by the Kotlin callback closure. Exposing an explicit `StoreSubscriptionHandle` with a `dispose()` contract breaks the cross-runtime retain graph deterministically during lifecycle exit (e.g., .onDisappear or deinit).
```swift
import SwiftUI
import SharedKit

@Observable
final class ProfileViewModel {
    private let store: ProfileStore // Exported Kotlin class
    private var subscriptionTask: StoreSubscriptionHandle? // Kotlin Closeable/Handle
    var state: ProfileState = .initial

    init(store: ProfileStore = ProfileStore()) {
        self.store = store
    }

    func startObserving() {
        guard subscriptionTask == nil else { return }
        // 1. Explicit [weak self] prevents ARC pinning inside Kotlin closure wrapper
        subscriptionTask = self.store.observeState { [weak self] newState in
            self?.state = newState
        }
    }

    func stopObserving() {
        // 2. Deterministic cross-runtime reference clearing
        subscriptionTask?.dispose()
        subscriptionTask = nil
    }

    deinit {
        // 3. Fallback deterministic detachment on deallocation
        subscriptionTask?.dispose()
        subscriptionTask = nil
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP 2.1 Swift-Export Cross-Runtime ARC/GC Retain Cycle Guardrail

KMP 2.1 Swift-Export Cross-Runtime ARC/GC Retain Cycle Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic lifecycle-bound reference disposal and weak bridge wrappers between Swift ARC and Kotlin/Native 2.1 GC runtimes. Prevents uncollected native heap islands caused by cyclic references across the Swift-Kotlin interop boundary where neither runtime can traverse cross-boundary reference graphs. 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: Invisible Cross-Runtime Retain Cycles Between Swift ARC and Kotlin Tracing GC 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 DriftInvisible Cross-Runtime Retain Cycles Between Swift ARC and Kotlin Tracing GCCritical
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 implement an explicit lifecycle unbind or dispose contract (e.g., `close()`, `detach()`) on exported Kotlin classes that retain Swift delegate or callback references.

Engineers MUST ALWAYS implement an explicit lifecycle unbind or dispose contract (e.g., `close()`, `detach()`) on exported Kotlin classes that retain Swift delegate or callback references.

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 pass Swift closures that strongly capture reference types (`self`) into Kotlin-exported state observers, flows, or long-lived coroutine bridges.

Engineers MUST NOT pass Swift closures that strongly capture reference types (`self`) into Kotlin-exported state observers, flows, or long-lived coroutine bridges.

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 weak reference wrapping on Swift-side delegate implementations that are consumed by Kotlin/Native exported interfaces.

Code SHOULD enforce weak reference wrapping on Swift-side delegate implementations that are consumed by Kotlin/Native exported interfaces.

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 components MUST explicitly trigger Kotlin cancellation/detachment in view teardown hooks (such as SwiftUI `.onDisappear` or UIKit `viewDidDisappear`/`deinit`).

Swift components MUST explicitly trigger Kotlin cancellation/detachment in view teardown hooks (such as SwiftUI `.onDisappear` or UIKit `viewDidDisappear`/`deinit`).

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 assume that Swift `deinit` will execute automatically if a long-lived Kotlin instance holds an unmanaged reference back to a Swift class

Components NEVER assume that Swift `deinit` will execute automatically if a long-lived Kotlin instance holds an unmanaged reference back to a Swift class; ARC retain count remains pinned at >= 1 indefinitely.

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/GC Retain Cycle Guardrail critical for AI coding assistants?

Enforces deterministic lifecycle-bound reference disposal and weak bridge wrappers between Swift ARC and Kotlin/Native 2.1 GC runtimes. Prevents uncollected native heap islands caused by cyclic references across the Swift-Kotlin interop boundary where neither runtime can traverse cross-boundary reference graphs. 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 (Invisible Cross-Runtime Retain Cycles Between Swift ARC and Kotlin Tracing GC) 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