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

Kotlin Multiplatform Swift-ARC Cross-Runtime Memory Cycle Isolation

Enforces deterministic memory boundaries across the Kotlin/Native Garbage Collector and Apple Automatic Reference Counting (ARC) runtime bridge. Eliminates dual-runtime retain cycles where Swift objects retain Kotlin objects that indirectly retain Swift callbacks or delegates via Objective-C bridge wrappers, leading to catastrophic native memory leaks and frozen uncollected roots.

Prohibited Anti-Pattern: Bypassing weak reference semantics across the Swift/KMP bridge creating cross-runtime zombie retain cycles

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Swift-ARC Cross-Runtime Memory Cycle Isolation - Enforces deterministic memory boundaries across the Kotlin/Native Garbage Collector and Apple Automatic Reference Counting (ARC) runtime bridge. Eliminates dual-runtime retain cycles where Swift objects retain Kotlin objects that indirectly retain Swift callbacks or delegates via Objective-C bridge wrappers, leading to catastrophic native memory leaks and frozen uncollected roots.
globs: **/*.kt, **/*.swift, iosApp/**/*.swift, shared/src/commonMain/**/*.kt, shared/src/iosMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-arc-cross-runtime-cycle-isolation"
---

# Kotlin Multiplatform Swift-ARC Cross-Runtime Memory Cycle Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Bypassing weak reference semantics across the Swift/KMP bridge creating cross-runtime zombie retain cycles

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform and Apple ARC interop. Enforce strict isolation boundaries between Kotlin/Native's mark-and-sweep garbage collector and Swift's ARC. Prevent cross-runtime reference cycle deadlocks by mandating explicit unsubscription tokens, weak proxy adapters, and closure decoupling across foreign function boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS capture `[weak self]` inside any Swift closure or callback supplied to an exported Kotlin component, Flow, or suspend function wrapper.
- Engineers MUST NEVER allow an exported Kotlin class to retain a strong reference to a Swift protocol implementer; delegate properties in Kotlin targeting iOS consumers MUST use a weak holder or explicit unbind lifecycle pattern.
- Code SHOULD enforce deterministic cancellation via `Closeable` or `Cancellable` subscription tokens that Swift clients invoke in `deinit` or UI lifecycle teardown (`viewDidDisappear`).
- Services MUST NOT store Swift callback lambdas in long-lived Kotlin singletons, global scopes, or static companion objects without exposing explicit release mechanisms.
- Components NEVER bridge bidirectional observer relationships without breaking the ARC-to-GC edge; either the Swift observer holds a weak handle or the Kotlin source releases its observer table upon client disposal.

## Bad vs Good Implementations
### Swift-KMP Flow Subscription Cycle Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Kotlin `SharedUserManager` maintains a strong reference to the Objective-C/Swift bridge block. The block captures `self` strongly, while `self` strongly retains `userManager`. The Kotlin Native GC and Swift ARC cannot cross-collect this circular dependency, leaking both the native Swift view model and the Kotlin coroutine hierarchy.
```swift
class ProfileViewModel {
    private let userManager: SharedUserManager // Kotlin class retained by Swift ARC
    private var observationTask: Task<Void, Never>?

    init(userManager: SharedUserManager) {
        self.userManager = userManager
        // ANTI-PATTERN: Strong capture of self in Swift closure passed to Kotlin Flow collection
        // The Kotlin Flow wrapper retains the closure, which retains self, while self retains userManager
        self.userManager.observeUserState { state in
            self.updateUi(state: state)
        }
    }

    func updateUi(state: UserState) {
        // State updates
    }
}
```

#### Production Standard (Correct)
> **Standard**: Capturing `[weak self]` prevents the Objective-C callback block from holding an owning ARC retain count on `ProfileViewModel`. Returning an explicit `CloseableHandle` allows `deinit` to notify the Kotlin/Native GC to release its listener reference, cleanly reclaiming memory in both runtimes.
```swift
class ProfileViewModel {
    private let userManager: SharedUserManager
    private var cancellableToken: CloseableHandle?

    init(userManager: SharedUserManager) {
        self.userManager = userManager
        // Explicit weak capture and cancellation handle registration
        self.cancellableToken = self.userManager.observeUserState(
            onState: { [weak self] state in
                guard let self = self else { return }
                self.updateUi(state: state)
            }
        )
    }

    func updateUi(state: UserState) {
        // State updates
    }

    deinit {
        // Break cross-runtime bridge connection deterministically
        cancellableToken?.close()
        cancellableToken = nil
    }
}
```

### Kotlin Listener Interface Bridging with Weak Proxying

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When Swift implements `NetworkListener` on an object that also retains `NetworkMonitor`, a cross-runtime cycle forms. The Kotlin GC root references the Swift delegate through the Objective-C proxy, preventing ARC from releasing the Swift instance, and Swift retains the Kotlin monitor.
```kotlin
// shared/src/iosMain/kotlin/NetworkMonitor.kt
interface NetworkListener {
    fun onNetworkChanged(isAvailable: Boolean)
}

class NetworkMonitor {
    // ANTI-PATTERN: Strong reference to Swift-implemented interface
    private val listeners = mutableListOf<NetworkListener>()

    fun addListener(listener: NetworkListener) {
        listeners.add(listener)
    }

    fun notify(available: Boolean) {
        listeners.forEach { it.onNetworkChanged(available) }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Wrapping the Swift-implemented `NetworkListener` inside Kotlin's `WeakReference` prevents the Kotlin runtime from creating an artificial strong retain root on the Objective-C object proxy, enabling ARC to deallocate the Swift listener naturally when its owning scope exits.
```kotlin
// shared/src/iosMain/kotlin/NetworkMonitor.kt
import kotlin.native.ref.WeakReference

interface NetworkListener {
    fun onNetworkChanged(isAvailable: Boolean)
}

class NetworkMonitor {
    private val listeners = mutableListOf<WeakReference<NetworkListener>>()

    fun addListener(listener: NetworkListener) {
        listeners.add(WeakReference(listener))
    }

    fun notify(available: Boolean) {
        val iterator = listeners.iterator()
        while (iterator.hasNext()) {
            val listener = iterator.next().get()
            if (listener != null) {
                listener.onNetworkChanged(available)
            } else {
                iterator.remove() // Purge collected references
            }
        }
    }
}
```

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: Kotlin Multiplatform Swift-ARC Cross-Runtime Memory Cycle Isolation

Kotlin Multiplatform Swift-ARC Cross-Runtime Memory Cycle Isolation defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic memory boundaries across the Kotlin/Native Garbage Collector and Apple Automatic Reference Counting (ARC) runtime bridge. Eliminates dual-runtime retain cycles where Swift objects retain Kotlin objects that indirectly retain Swift callbacks or delegates via Objective-C bridge wrappers, leading to catastrophic native memory leaks and frozen uncollected roots. 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: Bypassing weak reference semantics across the Swift/KMP bridge creating cross-runtime zombie retain cycles 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 DriftBypassing weak reference semantics across the Swift/KMP bridge creating cross-runtime zombie retain cyclesCritical
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 capture `[weak self]` inside any Swift closure or callback supplied to an exported Kotlin component, Flow, or suspend function wrapper.

Engineers MUST ALWAYS capture `[weak self]` inside any Swift closure or callback supplied to an exported Kotlin component, Flow, or suspend function wrapper.

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 NEVER allow an exported Kotlin class to retain a strong reference to a Swift protocol implementer

Engineers MUST NEVER allow an exported Kotlin class to retain a strong reference to a Swift protocol implementer; delegate properties in Kotlin targeting iOS consumers MUST use a weak holder or explicit unbind lifecycle pattern.

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 deterministic cancellation via `Closeable` or `Cancellable` subscription tokens that Swift clients invoke in `deinit` or UI lifecycle teardown (`viewDidDisappear`).

Code SHOULD enforce deterministic cancellation via `Closeable` or `Cancellable` subscription tokens that Swift clients invoke in `deinit` or UI lifecycle teardown (`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

Services MUST NOT store Swift callback lambdas in long-lived Kotlin singletons, global scopes, or static companion objects without exposing explicit release mechanisms.

Services MUST NOT store Swift callback lambdas in long-lived Kotlin singletons, global scopes, or static companion objects without exposing explicit release mechanisms.

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 bridge bidirectional observer relationships without breaking the ARC-to-GC edge

Components NEVER bridge bidirectional observer relationships without breaking the ARC-to-GC edge; either the Swift observer holds a weak handle or the Kotlin source releases its observer table upon client disposal.

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 Multiplatform Swift-ARC Cross-Runtime Memory Cycle Isolation critical for AI coding assistants?

Enforces deterministic memory boundaries across the Kotlin/Native Garbage Collector and Apple Automatic Reference Counting (ARC) runtime bridge. Eliminates dual-runtime retain cycles where Swift objects retain Kotlin objects that indirectly retain Swift callbacks or delegates via Objective-C bridge wrappers, leading to catastrophic native memory leaks and frozen uncollected roots. 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 (Bypassing weak reference semantics across the Swift/KMP bridge creating cross-runtime zombie retain cycles) 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