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

KMP 2.1 Swift Export Dynamic ARC Retain-Cycle Guardrail

Enforces weak-reference proxy boundaries and explicit detachment lifecycle hooks on all bidirectional listeners exposed across Kotlin Multiplatform 2.1 Swift Export. Eliminates cross-runtime memory leaks caused by independent garbage collection mechanisms (Swift ARC and Kotlin/Native GC) forming uncollected cyclic references across the foreign function interface.

Prohibited Anti-Pattern: Strong Bidirectional References Between Swift ARC Objects and Kotlin/Native Exported State Holders

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP 2.1 Swift Export Dynamic ARC Retain-Cycle Guardrail - Enforces weak-reference proxy boundaries and explicit detachment lifecycle hooks on all bidirectional listeners exposed across Kotlin Multiplatform 2.1 Swift Export. Eliminates cross-runtime memory leaks caused by independent garbage collection mechanisms (Swift ARC and Kotlin/Native GC) forming uncollected cyclic references across the foreign function interface.
globs: **/*.kt, **/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-arc-retain-cycle-guardrail"
---

# KMP 2.1 Swift Export Dynamic ARC Retain-Cycle Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Strong Bidirectional References Between Swift ARC Objects and Kotlin/Native Exported State Holders

## System Constraints
You are a Principal Software Architect enforcing cross-runtime memory safety in Kotlin Multiplatform (KMP 2.1+) with direct Swift Export. The Kotlin/Native tracing garbage collector and Swift Automatic Reference Counting (ARC) cannot trace references across their runtime boundaries. You must strictly mandate weak-reference proxy boundaries, explicit Disposable subscription tokens, and zero strong callback retain cycles across native Swift and Kotlin boundary code.

## Strict Guidelines
- Engineers MUST ALWAYS enforce weak referencing across the Swift/Kotlin runtime boundary by passing weakly referenced adapter proxies or explicit closure callbacks wrapped in Disposable tokens.
- Engineers MUST NOT store strong references to Swift-conforming listener or delegate interfaces inside long-lived Kotlin/Native singletons, repositories, or ViewModels.
- Services MUST return a lifecycle-bound `Cancellable` or `Disposable` handle upon listener registration that automatically tears down the cross-runtime pointer bridge upon invocation.
- Swift components NEVER pass `self` directly into a Kotlin observer registration API without establishing a weak proxy wrapper or capturing `[weak self]` inside an adapter closure.
- Code SHOULD verify in UI view controllers and SwiftUI view modifiers that subscription teardowns execute deterministically inside `onDisappear` or `deinit`.

## Bad vs Good Implementations
### Kotlin/Native Listener Boundary (Strong Reference vs Disposable Proxy)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Kotlin SessionManager maintains a strong reference in its `observers` list to the native Swift proxy object. When the Swift receiver also references SessionManager, neither Swift ARC nor Kotlin GC can collect the cyclic graph.
```kotlin
package com.example.kmp.session

// ANTI-PATTERN: Direct strong reference across runtime boundary.
// When exported to Swift, Kotlin holds a strong bridge pointer to the Swift object,
// while Swift holds a strong reference to SessionManager, causing a cross-runtime leak.
interface SessionObserver {
    fun onSessionExpired()
}

class SessionManager {
    private val observers = mutableListOf<SessionObserver>()

    fun registerObserver(observer: SessionObserver) {
        observers.add(observer)
    }

    fun notifyExpired() {
        observers.forEach { it.onSessionExpired() }
    }
}
```

#### Production Standard (Correct)
> **Standard**: SessionManager guards the boundary using `WeakReference` and emits a `CancellableSubscription`. Dead references are automatically cleaned, preventing cyclic ARC-to-GC retention.
```kotlin
package com.example.kmp.session

import kotlin.native.ref.WeakReference

fun interface SessionObserver {
    fun onSessionExpired()
}

fun interface CancellableSubscription {
    fun cancel()
}

class SessionManager {
    // Guarded boundary: holds weak reference wrapper or generates clean subscription tokens
    private val observers = mutableListOf<WeakReference<SessionObserver>>()

    fun registerObserver(observer: SessionObserver): CancellableSubscription {
        val weakRef = WeakReference(observer)
        observers.add(weakRef)
        
        return CancellableSubscription {
            observers.removeAll { it.get() == null || it.get() === observer }
        }
    }

    fun notifyExpired() {
        val deadReferences = mutableListOf<WeakReference<SessionObserver>>()
        for (ref in observers) {
            val target = ref.get()
            if (target != null) {
                target.onSessionExpired()
            } else {
                deadReferences.add(ref)
            }
        }
        observers.removeAll(deadReferences)
    }
}
```

### Swift ARC Interop Consumption (Direct Self Retain vs Weak Proxy)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing `self` creates an uncollectible ARC retain cycle across the runtime boundary. Kotlin retains the Swift bridge wrapper; Swift retains the Kotlin object. `deinit` will never trigger.
```swift
// ANTI-PATTERN: Swift class passing `self` into Kotlin export without weak decoupling
import SharedKit
import SwiftUI

final class UserProfileViewModel: ObservableObject, SessionObserver {
    private let sessionManager: SessionManager

    init(sessionManager: SessionManager) {
        self.sessionManager = sessionManager
        // Retain Cycle: sessionManager strongly holds `self` as SessionObserver,
        // and `self` strongly retains sessionManager.
        self.sessionManager.registerObserver(observer: self)
    }

    func onSessionExpired() {
        // Handle expiration
    }
}
```

#### Production Standard (Correct)
> **Standard**: WeakSessionObserverBridge breaks the native retain cycle by weakly referencing the Swift ViewModel. In addition, deinit explicitly triggers the cancellation token to prevent orphaned pointers.
```swift
// PRODUCTION STANDARD: Weak proxy boundary with deterministic lifecycle release
import SharedKit
import SwiftUI

private final class WeakSessionObserverBridge: SessionObserver {
    private weak var delegate: SessionObserver?

    init(delegate: SessionObserver) {
        self.delegate = delegate
    }

    func onSessionExpired() {
        delegate?.onSessionExpired()
    }
}

final class UserProfileViewModel: ObservableObject, SessionObserver {
    private let sessionManager: SessionManager
    private var subscription: CancellableSubscription?

    init(sessionManager: SessionManager) {
        self.sessionManager = sessionManager
        let bridge = WeakSessionObserverBridge(delegate: self)
        self.subscription = self.sessionManager.registerObserver(observer: bridge)
    }

    func onSessionExpired() {
        // Handled cleanly without retaining self
    }

    deinit {
        subscription?.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 Dynamic ARC Retain-Cycle Guardrail

KMP 2.1 Swift Export Dynamic ARC Retain-Cycle Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces weak-reference proxy boundaries and explicit detachment lifecycle hooks on all bidirectional listeners exposed across Kotlin Multiplatform 2.1 Swift Export. Eliminates cross-runtime memory leaks caused by independent garbage collection mechanisms (Swift ARC and Kotlin/Native GC) forming uncollected cyclic references across the foreign function interface. 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: Strong Bidirectional References Between Swift ARC Objects and Kotlin/Native Exported State Holders 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 DriftStrong Bidirectional References Between Swift ARC Objects and Kotlin/Native Exported State HoldersCritical
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 enforce weak referencing across the Swift/Kotlin runtime boundary by passing weakly referenced adapter proxies or explicit closure callbacks wrapped in Disposable tokens.

Engineers MUST ALWAYS enforce weak referencing across the Swift/Kotlin runtime boundary by passing weakly referenced adapter proxies or explicit closure callbacks wrapped in Disposable tokens.

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 store strong references to Swift-conforming listener or delegate interfaces inside long-lived Kotlin/Native singletons, repositories, or ViewModels.

Engineers MUST NOT store strong references to Swift-conforming listener or delegate interfaces inside long-lived Kotlin/Native singletons, repositories, or ViewModels.

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

Services MUST return a lifecycle-bound `Cancellable` or `Disposable` handle upon listener registration that automatically tears down the cross-runtime pointer bridge upon invocation.

Services MUST return a lifecycle-bound `Cancellable` or `Disposable` handle upon listener registration that automatically tears down the cross-runtime pointer bridge upon invocation.

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 NEVER pass `self` directly into a Kotlin observer registration API without establishing a weak proxy wrapper or capturing `[weak self]` inside an adapter closure.

Swift components NEVER pass `self` directly into a Kotlin observer registration API without establishing a weak proxy wrapper or capturing `[weak self]` inside an adapter closure.

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 SHOULD verify in UI view controllers and SwiftUI view modifiers that subscription teardowns execute deterministically inside `onDisappear` or `deinit`.

Code SHOULD verify in UI view controllers and SwiftUI view modifiers that subscription teardowns execute deterministically inside `onDisappear` or `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.
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 Dynamic ARC Retain-Cycle Guardrail critical for AI coding assistants?

Enforces weak-reference proxy boundaries and explicit detachment lifecycle hooks on all bidirectional listeners exposed across Kotlin Multiplatform 2.1 Swift Export. Eliminates cross-runtime memory leaks caused by independent garbage collection mechanisms (Swift ARC and Kotlin/Native GC) forming uncollected cyclic references across the foreign function interface. 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 (Strong Bidirectional References Between Swift ARC Objects and Kotlin/Native Exported State Holders) 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