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

KMP Swift Export GC-ARC Boundary Cycle Reclamation

Enforces strict ownership semantics and decoupling patterns across the Kotlin/Native tracing GC and Swift Automatic Reference Counting (ARC) boundary. Cross-runtime strong reference cycles prevent Kotlin GC root disposal and Swift deallocation, causing persistent native heap memory leaks. Developers must break cross-runtime cycles using explicit lifecycle teardowns, Kotlin weak wrappers, or unidirectional messaging adapters.

Prohibited Anti-Pattern: Retaining bidirectional strong references across Swift ARC and Kotlin/Native GC boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Swift Export GC-ARC Boundary Cycle Reclamation - Enforces strict ownership semantics and decoupling patterns across the Kotlin/Native tracing GC and Swift Automatic Reference Counting (ARC) boundary. Cross-runtime strong reference cycles prevent Kotlin GC root disposal and Swift deallocation, causing persistent native heap memory leaks. Developers must break cross-runtime cycles using explicit lifecycle teardowns, Kotlin weak wrappers, or unidirectional messaging adapters.
globs: shared/src/commonMain/kotlin/**/*.kt, shared/src/iosMain/kotlin/**/*.kt, iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-gc-arc-reclamation-standard"
---

# KMP Swift Export GC-ARC Boundary Cycle Reclamation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Retaining bidirectional strong references across Swift ARC and Kotlin/Native GC boundaries

## System Constraints
You are a Principal Mobile Architect enforcing memory safety across the Kotlin/Native Garbage Collector and Apple Swift Automatic Reference Counting (ARC) boundary. You must prevent memory leaks originating from cross-runtime reference cycles by mandating weak references on the Swift consumer side, avoiding Kotlin holding direct strong references to Swift delegates/listeners, and enforcing explicit teardown/cancellation protocols on shared ViewModels, Presenters, and CoroutineScope holders.

## Strict Guidelines
- Engineers MUST NEVER hold a strong reference from a Kotlin/Native class back to a Swift delegate or callback that transitively owns that same Kotlin instance.
- Swift code MUST ALWAYS mark Kotlin-facing delegates, closures, or observer wrappers as 'weak' or use unowned/weak capture lists in closures bound to Kotlin listeners.
- Engineers MUST implement an explicit 'clear()' or 'close()' lifecycle teardown method in Kotlin long-lived types (e.g., ViewModels) to nullify cross-boundary listeners and cancel running CoroutineScopes.
- Swift UI controllers or Coordinators MUST invoke teardown hooks in 'deinit', 'viewDidDisappear', or SwiftUI 'onDisappear' to sever Swift-to-Kotlin strong reference trees.
- Engineers MUST use 'kotlin.native.ref.WeakReference' when a Kotlin/Native object must cache or observe a Swift-bridged interface without taking ownership.

## Bad vs Good Implementations
### Cross-Runtime Delegate Pattern Leaking Memory Across GC/ARC

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin creates a native retain root to the Swift delegate. Swift retains the Kotlin ViewModel. Because Kotlin/Native GC cannot inspect the Swift ARC graph, and Swift ARC cannot inspect the Kotlin tracing GC heap, this creates an uncollectible cross-runtime island leak.
```swift
// Swift View/Controller Layer
class ProfileViewController: UIViewController, ProfileViewModelDelegate {
    private var viewModel: ProfileViewModel?

    override func viewDidLoad() {
        super.viewDidLoad()
        // ProfileViewModel (Kotlin) strongly retains delegate (Swift Self),
        // while Swift Self strongly retains ProfileViewModel.
        // Neither Kotlin tracing GC nor Swift ARC can reclaim this cycle!
        viewModel = ProfileViewModel(delegate: self)
    }

    func onProfileLoaded(name: String) {
        // Handle state
    }
}
```

#### Production Standard (Correct)
> **Standard**: The Swift wrapper prevents the Kotlin GC root from forming a strong reference back to the UIViewController. Additionally, invoking viewModel.clear() in deinit guarantees bidirectional clean-up.
```swift
// Swift View/Controller Layer
class ProfileViewController: UIViewController, ProfileViewModelDelegate {
    private var viewModel: ProfileViewModel?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Shared Kotlin ViewModel accepts an explicit weak wrapper or unbinds in teardown
        viewModel = ProfileViewModel()
        viewModel?.setDelegate(WeakProfileDelegateWrapper(delegate: self))
    }

    deinit {
        // Explicit teardown to break any lingering cross-runtime bridge references
        viewModel?.clear()
    }

    func onProfileLoaded(name: String) {
        // Handle state
    }
}

// Swift wrapper breaking the strong retention bridge
final class WeakProfileDelegateWrapper: ProfileViewModelDelegate {
    private weak var delegate: ProfileViewModelDelegate?
    init(delegate: ProfileViewModelDelegate) { self.delegate = delegate }
    func onProfileLoaded(name: String) { delegate?.onProfileLoaded(name: name) }
}
```

### Kotlin/Native Interface Delegate Retention

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: ProfileViewModel holds a direct hard reference to the Swift delegate bridge. When exported via Swift Export, the generated Objective-C/Swift bridge creates a strong ARC retain reference that cannot be reclaimed if Swift holds the ViewModel.
```kotlin
// Kotlin Native / Common Layer
interface ProfileDelegate {
    fun onProfileLoaded(name: String)
}

class ProfileViewModel(private val delegate: ProfileDelegate) {
    private val scope = CoroutineScope(Dispatchers.Main)

    fun loadData() {
        scope.launch {
            val name = "Alice"
            delegate.onProfileLoaded(name)
        }
    }
    // No lifecycle disposal mechanism provided for the Swift host
}
```

#### Production Standard (Correct)
> **Standard**: Uses 'kotlin.native.ref.WeakReference' to ensure Kotlin does not prevent Swift deallocation, and provides an explicit 'clear()' method to cancel pending Coroutines and clear runtime bridge pointers.
```kotlin
// Kotlin Native / Common Layer
import kotlin.native.ref.WeakReference

interface ProfileDelegate {
    fun onProfileLoaded(name: String)
}

class ProfileViewModel {
    private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    private var delegateRef: WeakReference<ProfileDelegate>? = null

    fun setDelegate(delegate: ProfileDelegate) {
        delegateRef = WeakReference(delegate)
    }

    fun loadData() {
        scope.launch {
            val name = "Alice"
            delegateRef?.get()?.onProfileLoaded(name)
        }
    }

    // Explicit lifecycle reclamation for cross-runtime teardown
    fun clear() {
        scope.cancel()
        delegateRef = null
    }
}
```

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 Swift Export GC-ARC Boundary Cycle Reclamation

KMP Swift Export GC-ARC Boundary Cycle Reclamation defines an industrial-grade behavioral standard for mobile engineering. Enforces strict ownership semantics and decoupling patterns across the Kotlin/Native tracing GC and Swift Automatic Reference Counting (ARC) boundary. Cross-runtime strong reference cycles prevent Kotlin GC root disposal and Swift deallocation, causing persistent native heap memory leaks. Developers must break cross-runtime cycles using explicit lifecycle teardowns, Kotlin weak wrappers, or unidirectional messaging adapters. 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: Retaining bidirectional strong references 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 DriftRetaining bidirectional strong references 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 NEVER hold a strong reference from a Kotlin/Native class back to a Swift delegate or callback that transitively owns that same Kotlin instance.

Engineers MUST NEVER hold a strong reference from a Kotlin/Native class back to a Swift delegate or callback that transitively owns that same Kotlin instance.

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

Swift code MUST ALWAYS mark Kotlin-facing delegates, closures, or observer wrappers as 'weak' or use unowned/weak capture lists in closures bound to Kotlin listeners.

Swift code MUST ALWAYS mark Kotlin-facing delegates, closures, or observer wrappers as 'weak' or use unowned/weak capture lists in closures bound to Kotlin listeners.

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

Engineers MUST implement an explicit 'clear()' or 'close()' lifecycle teardown method in Kotlin long-lived types (e.g., ViewModels) to nullify cross-boundary listeners and cancel running CoroutineScopes.

Engineers MUST implement an explicit 'clear()' or 'close()' lifecycle teardown method in Kotlin long-lived types (e.g., ViewModels) to nullify cross-boundary listeners and cancel running CoroutineScopes.

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 UI controllers or Coordinators MUST invoke teardown hooks in 'deinit', 'viewDidDisappear', or SwiftUI 'onDisappear' to sever Swift-to-Kotlin strong reference trees.

Swift UI controllers or Coordinators MUST invoke teardown hooks in 'deinit', 'viewDidDisappear', or SwiftUI 'onDisappear' to sever Swift-to-Kotlin strong reference trees.

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

Engineers MUST use 'kotlin.native.ref.WeakReference' when a Kotlin/Native object must cache or observe a Swift-bridged interface without taking ownership.

Engineers MUST use 'kotlin.native.ref.WeakReference' when a Kotlin/Native object must cache or observe a Swift-bridged interface without taking ownership.

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 Swift Export GC-ARC Boundary Cycle Reclamation critical for AI coding assistants?

Enforces strict ownership semantics and decoupling patterns across the Kotlin/Native tracing GC and Swift Automatic Reference Counting (ARC) boundary. Cross-runtime strong reference cycles prevent Kotlin GC root disposal and Swift deallocation, causing persistent native heap memory leaks. Developers must break cross-runtime cycles using explicit lifecycle teardowns, Kotlin weak wrappers, or unidirectional messaging adapters. 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 (Retaining bidirectional strong references 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

KMP