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

Kotlin Multiplatform Swift Export Dual-ARC Reference Deallocation Gate

Enforces strict memory boundary separation between Apple's Swift Automatic Reference Counting (ARC) and Kotlin/Native's garbage collector when using Swift Export. Prevents cross-runtime cyclic memory leaks and zombie wrapper retention caused by mutual strong references across Objective-C/Swift interop bindings. Mandates explicit lifecycle ownership gates, weak interop bridges, and deterministic scope teardown mechanisms.

Prohibited Anti-Pattern: Cross-Runtime Circular Retain Cycles and Opaque Wrapper Pinning in Swift Export Bridges

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Swift Export Dual-ARC Reference Deallocation Gate - Enforces strict memory boundary separation between Apple's Swift Automatic Reference Counting (ARC) and Kotlin/Native's garbage collector when using Swift Export. Prevents cross-runtime cyclic memory leaks and zombie wrapper retention caused by mutual strong references across Objective-C/Swift interop bindings. Mandates explicit lifecycle ownership gates, weak interop bridges, and deterministic scope teardown mechanisms.
globs: shared/src/iosMain/kotlin/**/*.kt, shared/src/commonMain/kotlin/**/*.kt, iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-dual-arc-gate"
---

# Kotlin Multiplatform Swift Export Dual-ARC Reference Deallocation Gate

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Cross-Runtime Circular Retain Cycles and Opaque Wrapper Pinning in Swift Export Bridges

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform and Darwin runtime internals. You strictly enforce deterministic memory reclamation between Swift ARC and Kotlin/Native GC. You prevent cross-runtime retain cycles across Swift Export interfaces by requiring non-owning delegates, explicit termination protocols, and detached callback lifecycles.

## Strict Guidelines
- Engineers MUST ALWAYS mark callback listeners and delegate interfaces exported from Kotlin to Swift as non-retaining or pass them via WeakReference wrappers to avoid Swift closures capturing Kotlin references indefinitely.
- Engineers MUST NOT permit bi-directional strong reference graphs across the Swift/Kotlin boundary (e.g., a Kotlin ViewModel holding a Swift View controller listener that holds the same Kotlin ViewModel).
- Services MUST implement an explicit deterministic teardown interface (e.g., `Disposable`, `Closeable`, or `clear()`) invoked from the Swift consumer's `deinit` block to sever cross-runtime bridges before ARC drops to zero.
- Code SHOULD leverage immutable state flow streams or unidirectional value transfers across Swift Export rather than stateful interactive bridges holding long-lived closure contexts.
- Components NEVER store long-lived Swift escaping closures directly in Kotlin/Native state properties without explicit dissociation mechanisms.

## Bad vs Good Implementations
### Dual-Runtime Circular Retain Cycle Prevention

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin ViewModel stores the Swift escaping closure in native memory while Swift ViewController holds the Kotlin ViewModel via ARC. The cross-runtime strong reference loop creates permanent heap leaks on both Darwin ARC and Kotlin Native GC runtimes.
```swift
// Swift View Controller strongly holding Kotlin Controller
final class ProfileViewController: UIViewController {
    private let viewModel = ProfileViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        // CRITICAL BUG: Kotlin ViewModel strongly holds closure retaining 'self',
        // while 'self' strongly holds ViewModel. Neither ARC nor K/N GC can resolve this cross-runtime cycle.
        viewModel.observeProfileUpdates { [self] profile in
            self.updateUI(with: profile)
        }
    }

    private func updateUI(with profile: ProfileData) { /* update views */ }
}
```

#### Production Standard (Correct)
> **Standard**: Weak reference capture inside the Swift closure breaks the ARC-to-Swift retain path, and subscription handle teardown inside deinit deterministically frees the Kotlin interop wrapper from native retention.
```swift
// Kotlin Boundary Protocol
// interface DisposableHandle { fun dispose() }

final class ProfileViewController: UIViewController {
    private let viewModel = ProfileViewModel()
    private var subscriptionHandle: DisposableHandle?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Enforce ARC weak capture and capture token for explicit lifecycle unbinding
        subscriptionHandle = viewModel.observeProfileUpdates { [weak self] profile in
            guard let self = self else { return }
            self.updateUI(with: profile)
        }
    }

    deinit {
        // Mandate deterministic cross-runtime gate teardown
        subscriptionHandle?.dispose()
        subscriptionHandle = nil
        viewModel.clear()
    }

    private func updateUI(with profile: ProfileData) { /* update views */ }
}
```

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 Export Dual-ARC Reference Deallocation Gate

Kotlin Multiplatform Swift Export Dual-ARC Reference Deallocation Gate defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory boundary separation between Apple's Swift Automatic Reference Counting (ARC) and Kotlin/Native's garbage collector when using Swift Export. Prevents cross-runtime cyclic memory leaks and zombie wrapper retention caused by mutual strong references across Objective-C/Swift interop bindings. Mandates explicit lifecycle ownership gates, weak interop bridges, and deterministic scope teardown mechanisms. 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 Circular Retain Cycles and Opaque Wrapper Pinning in Swift Export Bridges 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 Circular Retain Cycles and Opaque Wrapper Pinning in Swift Export BridgesCritical
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 mark callback listeners and delegate interfaces exported from Kotlin to Swift as non-retaining or pass them via WeakReference wrappers to avoid Swift closures capturing Kotlin references indefinitely.

Engineers MUST ALWAYS mark callback listeners and delegate interfaces exported from Kotlin to Swift as non-retaining or pass them via WeakReference wrappers to avoid Swift closures capturing Kotlin references indefinitely.

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 permit bi-directional strong reference graphs across the Swift/Kotlin boundary (e.g., a Kotlin ViewModel holding a Swift View controller listener that holds the same Kotlin ViewModel).

Engineers MUST NOT permit bi-directional strong reference graphs across the Swift/Kotlin boundary (e.g., a Kotlin ViewModel holding a Swift View controller listener that holds the same Kotlin ViewModel).

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 implement an explicit deterministic teardown interface (e.g., `Disposable`, `Closeable`, or `clear()`) invoked from the Swift consumer's `deinit` block to sever cross-runtime bridges before ARC drops to zero.

Services MUST implement an explicit deterministic teardown interface (e.g., `Disposable`, `Closeable`, or `clear()`) invoked from the Swift consumer's `deinit` block to sever cross-runtime bridges before ARC drops to zero.

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

Code SHOULD leverage immutable state flow streams or unidirectional value transfers across Swift Export rather than stateful interactive bridges holding long-lived closure contexts.

Code SHOULD leverage immutable state flow streams or unidirectional value transfers across Swift Export rather than stateful interactive bridges holding long-lived closure contexts.

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 store long-lived Swift escaping closures directly in Kotlin/Native state properties without explicit dissociation mechanisms.

Components NEVER store long-lived Swift escaping closures directly in Kotlin/Native state properties without explicit dissociation 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.
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 Export Dual-ARC Reference Deallocation Gate critical for AI coding assistants?

Enforces strict memory boundary separation between Apple's Swift Automatic Reference Counting (ARC) and Kotlin/Native's garbage collector when using Swift Export. Prevents cross-runtime cyclic memory leaks and zombie wrapper retention caused by mutual strong references across Objective-C/Swift interop bindings. Mandates explicit lifecycle ownership gates, weak interop bridges, and deterministic scope teardown mechanisms. 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 Circular Retain Cycles and Opaque Wrapper Pinning in Swift Export Bridges) 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