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

Kotlin Native ARC-to-GC Reference Cycle Confinement

Eliminates catastrophic native memory leaks in Kotlin Multiplatform iOS applications caused by cross-runtime retain cycles between Swift ARC and Kotlin Native's Garbage Collector. Because Swift's reference counter cannot trace Kotlin heap allocations and Kotlin's GC treats foreign references as roots, bidirectional object graphs across the bridge must be strictly confined via deterministic weak-reference wrappers and explicit teardown lifecycles.

Prohibited Anti-Pattern: Unconfined Bidirectional Strong Retain Cycles Across Swift ARC and Kotlin Native GC Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Native ARC-to-GC Reference Cycle Confinement - Eliminates catastrophic native memory leaks in Kotlin Multiplatform iOS applications caused by cross-runtime retain cycles between Swift ARC and Kotlin Native's Garbage Collector. Because Swift's reference counter cannot trace Kotlin heap allocations and Kotlin's GC treats foreign references as roots, bidirectional object graphs across the bridge must be strictly confined via deterministic weak-reference wrappers and explicit teardown lifecycles.
globs: shared/src/iosMain/**/*.kt, shared/src/commonMain/**/*.kt, iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-native-arc-to-gc-cycle-confinement"
---

# Kotlin Native ARC-to-GC Reference Cycle Confinement

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unconfined Bidirectional Strong Retain Cycles Across Swift ARC and Kotlin Native GC Boundaries

## System Constraints
You are a Principal Mobile Architect enforcing strict Kotlin Multiplatform (KMP) iOS memory safety rules. Mandate memory boundary invariants between Apple Automatic Reference Counting (ARC) and Kotlin Native Tracing Garbage Collection (GC). Prevent persistent leaks, uncollectable root references, and native OOM crashes across the cinterop boundary.

## Strict Guidelines
- Engineers MUST ALWAYS encapsulate Swift delegates and observers in Kotlin's 'iosMain' source set using 'kotlin.native.ref.WeakReference' to prevent holding native ARC roots in the Kotlin GC heap.
- Engineers MUST NOT pass Swift instances with strong self-references into Kotlin long-lived singleton registries, Coroutine Job listeners, or StateFlow observers without a deterministic cancellation token.
- Swift consumers MUST capture Kotlin object references using '[weak self]' in every completion handler, callback block, or Flow collector bridge.
- Kotlin-exported classes that hold Objective-C/Swift delegates MUST provide an explicit 'detach()' or 'close()' lifecycle method that sets native delegate references to null.
- UI components (such as UIViewController or SwiftUI Views) MUST cancel active Kotlin Coroutine scopes and nullify bridge listeners inside 'deinit' or 'viewDidDisappear'.

## Bad vs Good Implementations
### Kotlin Native Delegate Holding via WeakReference

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin holds a strong reference to an Objective-C/Swift delegate. If the Swift delegate holds a reference back to LocationEngineBridge, a cross-runtime cycle is established. Tracing GC treats the Swift object as a live root, and ARC sees a non-zero reference count, causing a permanent native memory leak.
```kotlin
// shared/src/iosMain/kotlin/com/example/engine/LocationBridge.kt
package com.example.engine

import platform.CoreLocation.CLLocationManagerDelegateProtocol
import platform.darwin.NSObject

class LocationEngineBridge(
    // VIOLATION: Strong reference to an iOS ARC-managed delegate.
    // If the Swift delegate retains this LocationEngineBridge, neither
    // Kotlin GC nor Apple ARC can deallocate either object graph.
    private val delegate: CLLocationManagerDelegateProtocol
) : NSObject() {
    fun notifyUpdate(location: String) {
        delegate.locationManager(null, didUpdateLocations = emptyList<Any?>())
    }
}
```

#### Production Standard (Correct)
> **Standard**: Encapsulating the native delegate inside `kotlin.native.ref.WeakReference` ensures Kotlin GC does not artificially increment ARC retain counts or treat the delegate as an uncollectable GC root. When iOS releases the delegate, the weak reference evaluates to null.
```kotlin
// shared/src/iosMain/kotlin/com/example/engine/LocationBridge.kt
package com.example.engine

import kotlin.native.ref.WeakReference
import platform.CoreLocation.CLLocationManagerDelegateProtocol
import platform.darwin.NSObject

class LocationEngineBridge(
    delegate: CLLocationManagerDelegateProtocol
) : NSObject() {
    // CONFINEMENT: Wrap native ARC delegate in a Kotlin WeakReference.
    private val delegateRef = WeakReference(delegate)

    fun notifyUpdate(location: String) {
        val target = delegateRef.get()
        if (target != null) {
            target.locationManager(null, didUpdateLocations = emptyList<Any?>())
        } else {
            detach()
        }
    }

    fun detach() {
        delegateRef.clear()
    }
}
```

### Swift Flow Collector Cancellation and Weak Self Confinement

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Kotlin UserViewModel registers the closure in a long-lived scope. The closure strongly captures 'self' (ProfileViewController), while the view controller strongly holds the ViewModel. Neither the view controller nor the ViewModel can ever be deallocated.
```swift
// iosApp/iOSApp/Features/UserPresenter.swift
import UIKit
import SharedKit

class ProfileViewController: UIViewController {
    private let viewModel = UserViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        // VIOLATION: Strongly capturing 'self' in Kotlin callback and ignoring Disposable/Closeable
        viewModel.observeUserState {
            self.updateUI(state: $0)
        }
    }

    private func updateUI(state: UserState) {
        // UI updates
    }
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly using '[weak self]' breaks ARC retain retention from the Kotlin-exported closure, and invoking 'cancel()' in 'deinit' guarantees deterministic release of the Kotlin Coroutine subscription.
```swift
// iosApp/iOSApp/Features/UserPresenter.swift
import UIKit
import SharedKit

class ProfileViewController: UIViewController {
    private let viewModel = UserViewModel()
    private var observationWatcher: CancellableWrapper? = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        // CONFINEMENT: Weak self capture and tracking the bridge cancellation handle
        observationWatcher = viewModel.observeUserState { [weak self] state in
            guard let self = self else { return }
            self.updateUI(state: state)
        }
    }

    private func updateUI(state: UserState) {
        // UI updates
    }

    deinit {
        // Deterministically break cross-runtime retain boundary
        observationWatcher?.cancel()
        observationWatcher = 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: Kotlin Native ARC-to-GC Reference Cycle Confinement

Kotlin Native ARC-to-GC Reference Cycle Confinement defines an industrial-grade behavioral standard for mobile engineering. Eliminates catastrophic native memory leaks in Kotlin Multiplatform iOS applications caused by cross-runtime retain cycles between Swift ARC and Kotlin Native's Garbage Collector. Because Swift's reference counter cannot trace Kotlin heap allocations and Kotlin's GC treats foreign references as roots, bidirectional object graphs across the bridge must be strictly confined via deterministic weak-reference wrappers and explicit teardown lifecycles. 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: Unconfined Bidirectional Strong Retain Cycles Across Swift ARC and Kotlin Native GC Boundaries 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 DriftUnconfined Bidirectional Strong Retain Cycles Across Swift ARC and Kotlin Native GC BoundariesCritical
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 encapsulate Swift delegates and observers in Kotlin's 'iosMain' source set using 'kotlin.native.ref.WeakReference' to prevent holding native ARC roots in the Kotlin GC heap.

Engineers MUST ALWAYS encapsulate Swift delegates and observers in Kotlin's 'iosMain' source set using 'kotlin.native.ref.WeakReference' to prevent holding native ARC roots in the Kotlin GC heap.

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 instances with strong self-references into Kotlin long-lived singleton registries, Coroutine Job listeners, or StateFlow observers without a deterministic cancellation token.

Engineers MUST NOT pass Swift instances with strong self-references into Kotlin long-lived singleton registries, Coroutine Job listeners, or StateFlow observers without a deterministic cancellation token.

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 consumers MUST capture Kotlin object references using '[weak self]' in every completion handler, callback block, or Flow collector bridge.

Swift consumers MUST capture Kotlin object references using '[weak self]' in every completion handler, callback block, or Flow collector bridge.

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-exported classes that hold Objective-C/Swift delegates MUST provide an explicit 'detach()' or 'close()' lifecycle method that sets native delegate references to null.

Kotlin-exported classes that hold Objective-C/Swift delegates MUST provide an explicit 'detach()' or 'close()' lifecycle method that sets native delegate references to null.

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

UI components (such as UIViewController or SwiftUI Views) MUST cancel active Kotlin Coroutine scopes and nullify bridge listeners inside 'deinit' or 'viewDidDisappear'.

UI components (such as UIViewController or SwiftUI Views) MUST cancel active Kotlin Coroutine scopes and nullify bridge listeners inside 'deinit' or 'viewDidDisappear'.

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 Kotlin Native ARC-to-GC Reference Cycle Confinement critical for AI coding assistants?

Eliminates catastrophic native memory leaks in Kotlin Multiplatform iOS applications caused by cross-runtime retain cycles between Swift ARC and Kotlin Native's Garbage Collector. Because Swift's reference counter cannot trace Kotlin heap allocations and Kotlin's GC treats foreign references as roots, bidirectional object graphs across the bridge must be strictly confined via deterministic weak-reference wrappers and explicit teardown lifecycles. 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 (Unconfined Bidirectional Strong Retain Cycles Across Swift ARC and Kotlin Native GC Boundaries) 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

Kotlin