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

KMP Native ARC Cycle-Breaking Bridge Standard

Enforces deterministic cycle-breaking boundaries across Kotlin/Native GC and Apple Objective-C/Swift ARC runtimes. Prevents uncollectable cross-runtime retained memory islands caused by dual-root strong reference cycles between Kotlin class instances and native Apple delegates or closures.

Prohibited Anti-Pattern: Cross-Runtime Retain Islands from Bidirectional Strong References Across K/N GC and Swift ARC

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Native ARC Cycle-Breaking Bridge Standard - Enforces deterministic cycle-breaking boundaries across Kotlin/Native GC and Apple Objective-C/Swift ARC runtimes. Prevents uncollectable cross-runtime retained memory islands caused by dual-root strong reference cycles between Kotlin class instances and native Apple delegates or closures.
globs: **/iosMain/**/*.kt, **/appleMain/**/*.kt, **/nativeMain/**/*.kt, iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-native-arc-cycle-breaking-bridge-standard"
---

# KMP Native ARC Cycle-Breaking Bridge Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Cross-Runtime Retain Islands from Bidirectional Strong References Across K/N GC and Swift ARC

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform and Apple runtime internals. Your task is to enforce zero-leak boundaries between Kotlin/Native's garbage-collected heap and Apple's Automatic Reference Counting (ARC) graph. When Kotlin/Native objects interact with Swift/Objective-C classes via protocols, listeners, or callbacks, you must enforce strict weak-referencing topologies or explicit deterministic teardown mechanisms to prevent cross-runtime retain cycles that evade both collectors.

## Strict Guidelines
- Engineers MUST ALWAYS wrap Swift/Objective-C protocol delegates in `kotlin.native.ref.WeakReference` when held within Kotlin/Native long-lived classes.
- Engineers MUST NOT allow bidirectional strong references between a Swift observer/closure and a Kotlin ViewModel, Presenter, or CoroutineScope.
- Swift clients observing Kotlin StateFlow or Flow bridges MUST hold the bridge wrapper weakly or explicitly cancel and clear the collection handle in `deinit` or `viewDidDisappear`.
- Engineers MUST explicitly invoke `StableRef.dispose()` exactly once for every `StableRef.create()` allocated to pass pointer handles across C/ObjC interop boundaries.
- Kotlin callbacks exposed to Swift via closures MUST NEVER capture the enclosing Swift instance strongly; Swift code MUST pass `[weak self]` in completion handlers and delegate adapters.
- Components holding native Apple resources (such as `UIViewController`, `CVPixelBuffer`, or `NSObject`) inside Kotlin multiplatform expect/actual implementations MUST implement an explicit `Disposable` or `AutoCloseable` interface and nullify native pointers.

## Bad vs Good Implementations
### Bridging Swift Delegate in Kotlin/Native without Retain Cycles

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin holds a strong reference to NativeAudioPlayerDelegate. If the Swift class implementing NativeAudioPlayerDelegate holds a strong reference to AudioPlayerManager, Kotlin GC considers the delegate reachable from GC root, and ARC considers AudioPlayerManager reachable from Swift root. Memory is leaked permanently.
```kotlin
import platform.darwin.NSObject

interface NativeAudioPlayerDelegate {
    fun onPlaybackFinished()
}

// ANTI-PATTERN: Strong reference to an Apple ARC-managed object inside Kotlin GC runtime.
// When the Swift delegate retains this Kotlin AudioPlayerManager, neither ARC nor Kotlin GC
// can collect the retain cycle.
class AudioPlayerManager(private val delegate: NativeAudioPlayerDelegate) {
    fun complete() {
        delegate.onPlaybackFinished()
    }
}
```

#### Production Standard (Correct)
> **Standard**: Wrapping the Swift/Objective-C delegate inside `kotlin.native.ref.WeakReference` allows the Apple runtime's ARC to deallocate the delegate naturally when Swift releases its view controller or owner. `weakDelegate.get()` safely returns null once collected.
```kotlin
import kotlin.native.ref.WeakReference

interface NativeAudioPlayerDelegate {
    fun onPlaybackFinished()
}

// PRODUCTION FIX: WeakReference wraps the ARC-managed boundary target.
// Breaks the cross-runtime retain cycle while keeping API ergonomics safe.
class AudioPlayerManager(delegate: NativeAudioPlayerDelegate) {
    private val weakDelegate = WeakReference(delegate)

    fun complete() {
        weakDelegate.get()?.onPlaybackFinished()
    }

    fun clearDelegate() {
        // Explicit cleanup hook for deterministic lifecycle integration
        weakDelegate.clear()
    }
}
```

### Swift Flow Bridge Observation Teardown

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The watch closure retains `self` strongly, while `viewModel` maintains the active coroutine subscription reference in Kotlin memory. When the ViewController is popped, ARC cannot release it because the Kotlin bridge holds the closure wrapper.
```swift
// ANTI-PATTERN: Swift UI layer strongly capturing FlowAdapter without cancellation
final class ProfileViewController: UIViewController {
    private let viewModel = ProfileViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Closures and bridges strongly held without unbind/weak self
        viewModel.uiState.watch { state in
            self.render(state: state)
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Swift uses `[weak self]` in the closure to prevent ARC capture, and holds a closeable handle that invokes cancellation on the Kotlin scope during `deinit`, guaranteeing zero lingering bridge roots.
```swift
// PRODUCTION FIX: Retain cancellable handle and explicitly disconnect in deinit
final class ProfileViewController: UIViewController {
    private let viewModel = ProfileViewModel()
    private var cancellable: CloseableWrapper?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        cancellable = viewModel.uiState.watch { [weak self] state in
            guard let self = self else { return }
            self.render(state: state)
        }
    }
    
    deinit {
        cancellable?.close()
        cancellable = nil
    }
}
```

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 Native ARC Cycle-Breaking Bridge Standard

KMP Native ARC Cycle-Breaking Bridge Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic cycle-breaking boundaries across Kotlin/Native GC and Apple Objective-C/Swift ARC runtimes. Prevents uncollectable cross-runtime retained memory islands caused by dual-root strong reference cycles between Kotlin class instances and native Apple delegates or closures. 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: Cross-Runtime Retain Islands from Bidirectional Strong References Across K/N GC and Swift ARC 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 DriftCross-Runtime Retain Islands from Bidirectional Strong References Across K/N GC and Swift ARCCritical
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 wrap Swift/Objective-C protocol delegates in `kotlin.native.ref.WeakReference` when held within Kotlin/Native long-lived classes.

Engineers MUST ALWAYS wrap Swift/Objective-C protocol delegates in `kotlin.native.ref.WeakReference` when held within Kotlin/Native long-lived classes.

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 allow bidirectional strong references between a Swift observer/closure and a Kotlin ViewModel, Presenter, or CoroutineScope.

Engineers MUST NOT allow bidirectional strong references between a Swift observer/closure and a Kotlin ViewModel, Presenter, or CoroutineScope.

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 observing Kotlin StateFlow or Flow bridges MUST hold the bridge wrapper weakly or explicitly cancel and clear the collection handle in `deinit` or `viewDidDisappear`.

Swift clients observing Kotlin StateFlow or Flow bridges MUST hold the bridge wrapper weakly or explicitly cancel and clear the collection handle in `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.
4

Engineers MUST explicitly invoke `StableRef.dispose()` exactly once for every `StableRef.create()` allocated to pass pointer handles across C/ObjC interop boundaries.

Engineers MUST explicitly invoke `StableRef.dispose()` exactly once for every `StableRef.create()` allocated to pass pointer handles across C/ObjC interop boundaries.

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

Kotlin callbacks exposed to Swift via closures MUST NEVER capture the enclosing Swift instance strongly

Kotlin callbacks exposed to Swift via closures MUST NEVER capture the enclosing Swift instance strongly; Swift code MUST pass `[weak self]` in completion handlers and delegate adapters.

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

Components holding native Apple resources (such as `UIViewController`, `CVPixelBuffer`, or `NSObject`) inside Kotlin multiplatform expect/actual implementations MUST implement an explicit `Disposable` or `AutoCloseable` interface and nullify native pointers.

Components holding native Apple resources (such as `UIViewController`, `CVPixelBuffer`, or `NSObject`) inside Kotlin multiplatform expect/actual implementations MUST implement an explicit `Disposable` or `AutoCloseable` interface and nullify native pointers.

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 Native ARC Cycle-Breaking Bridge Standard critical for AI coding assistants?

Enforces deterministic cycle-breaking boundaries across Kotlin/Native GC and Apple Objective-C/Swift ARC runtimes. Prevents uncollectable cross-runtime retained memory islands caused by dual-root strong reference cycles between Kotlin class instances and native Apple delegates or closures. 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 (Cross-Runtime Retain Islands from Bidirectional Strong References Across K/N GC and Swift ARC) 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