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

Kotlin Native & Swift ARC Interop Boundary Memory Isolation

Enforces strict isolation between Swift Automatic Reference Counting (ARC) and Kotlin/Native tracing Garbage Collection (GC) across the Objective-C/Swift-Export ABI. Prohibits cross-runtime cyclic retain paths where Kotlin objects hold strong references to Swift instances implementing exported interfaces without deterministic lifecycle detachment.

Prohibited Anti-Pattern: Cross-Runtime Cyclic Retain Graph Causing Undetectable Native Memory Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Native & Swift ARC Interop Boundary Memory Isolation - Enforces strict isolation between Swift Automatic Reference Counting (ARC) and Kotlin/Native tracing Garbage Collection (GC) across the Objective-C/Swift-Export ABI. Prohibits cross-runtime cyclic retain paths where Kotlin objects hold strong references to Swift instances implementing exported interfaces without deterministic lifecycle detachment.
globs: iosApp/**/*.swift, shared/src/iosMain/**/*.kt, shared/src/commonMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-arc-boundary-isolation"
---

# Kotlin Native & Swift ARC Interop Boundary Memory Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Cross-Runtime Cyclic Retain Graph Causing Undetectable Native Memory Leaks

## System Constraints
You are a Principal Mobile Architect enforcing Kotlin Multiplatform (KMP) and Swift-Export memory boundary contracts. Kotlin/Native's tracing garbage collector and Swift's ARC cannot trace references across their shared runtime boundary; a reference cycle spanning both runtimes will never be reclaimed by either collector. You must ensure all boundary crossers use weak listener proxies, deterministic teardown hooks, or unidirectional event streams.

## Strict Guidelines
- Engineers MUST ALWAYS invalidate listeners, observers, and coroutine scopes crossing the Swift/Kotlin boundary during Swift lifecycle deinitialization (e.g., UIViewController.viewDidDisappear, SwiftUI .onDisappear, or deinit).
- Engineers MUST NOT pass Swift closures or delegates capturing strong references to Swift actors/classes into long-lived Kotlin singletons or retained state holders.
- Code SHOULD utilize unidirectional Kotlin StateFlow/SharedFlow wrapped in SKIE or Swift-Export AsyncSequences rather than bidirectional observer interfaces.
- Services MUST provide an explicit `detach()`, `dispose()`, or `close()` method in Kotlin interfaces exported to Swift when bridging non-ephemeral instances.
- Components NEVER store raw Swift protocol implementations in long-lived Kotlin coroutine context elements or collection fields without a WeakReference wrapper.

## Bad vs Good Implementations
### Swift Retain Cycle Across KMP Boundary via Callback Listener

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Kotlin presenter is held strongly by Swift ViewModel, and the Kotlin presenter holds a strong native reference to the Swift closure, which captures Swift `self`. Because Swift ARC cannot trace Kotlin GC roots, and Kotlin GC cannot trace Swift retain counts, neither engine reclaims memory.
```swift
import SwiftUI
import SharedKit

final class UserProfileViewModel: ObservableObject {
    private let presenter: KmpUserProfilePresenter
    @Published var userName: String = ""

    init(presenter: KmpUserProfilePresenter) {
        self.presenter = presenter
        // CRITICAL BUG: Strong reference cycle across KMP ABI boundary.
        // Presenter (Kotlin GC) holds strong reference to listener.
        // Listener closure captures Swift self strongly.
        // ViewModel (Swift ARC) holds strong reference to Presenter.
        // Neither Kotlin GC nor Swift ARC can detect or break this cross-runtime cycle.
        self.presenter.setListener(listener: { [self] newName in
            self.userName = newName
        })
    }
}
```

#### Production Standard (Correct)
> **Standard**: Capturing `[weak self]` in the Swift closure prevents Swift ARC from closing a retain cycle with the Kotlin object, and calling `dispose()` in `deinit` explicitly dereferences the closure on the Kotlin side.
```swift
import SwiftUI
import SharedKit

final class UserProfileViewModel: ObservableObject {
    private let presenter: KmpUserProfilePresenter
    @Published var userName: String = ""
    private var taskHandle: KmpTaskHandle?

    init(presenter: KmpUserProfilePresenter) {
        self.presenter = presenter
        // Invariant: Break cycle with [weak self] and retain deterministic handle for disposal
        self.taskHandle = presenter.observeProfile { [weak self] newName in
            Task { @MainActor in
                self?.userName = newName
            }
        }
    }

    deinit {
        // Explicitly sever the cross-runtime boundary bridge
        taskHandle?.dispose()
    }
}
```

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 Native & Swift ARC Interop Boundary Memory Isolation

Kotlin Native & Swift ARC Interop Boundary Memory Isolation defines an industrial-grade behavioral standard for mobile engineering. Enforces strict isolation between Swift Automatic Reference Counting (ARC) and Kotlin/Native tracing Garbage Collection (GC) across the Objective-C/Swift-Export ABI. Prohibits cross-runtime cyclic retain paths where Kotlin objects hold strong references to Swift instances implementing exported interfaces without deterministic lifecycle detachment. 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 Cyclic Retain Graph Causing Undetectable Native Memory Leaks 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 Cyclic Retain Graph Causing Undetectable Native Memory LeaksCritical
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 invalidate listeners, observers, and coroutine scopes crossing the Swift/Kotlin boundary during Swift lifecycle deinitialization (e.g., UIViewController.viewDidDisappear, SwiftUI .onDisappear, or deinit).

Engineers MUST ALWAYS invalidate listeners, observers, and coroutine scopes crossing the Swift/Kotlin boundary during Swift lifecycle deinitialization (e.g., UIViewController.viewDidDisappear, SwiftUI .onDisappear, or deinit).

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 closures or delegates capturing strong references to Swift actors/classes into long-lived Kotlin singletons or retained state holders.

Engineers MUST NOT pass Swift closures or delegates capturing strong references to Swift actors/classes into long-lived Kotlin singletons or retained state holders.

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 utilize unidirectional Kotlin StateFlow/SharedFlow wrapped in SKIE or Swift-Export AsyncSequences rather than bidirectional observer interfaces.

Code SHOULD utilize unidirectional Kotlin StateFlow/SharedFlow wrapped in SKIE or Swift-Export AsyncSequences rather than bidirectional observer interfaces.

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 provide an explicit `detach()`, `dispose()`, or `close()` method in Kotlin interfaces exported to Swift when bridging non-ephemeral instances.

Services MUST provide an explicit `detach()`, `dispose()`, or `close()` method in Kotlin interfaces exported to Swift when bridging non-ephemeral instances.

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 raw Swift protocol implementations in long-lived Kotlin coroutine context elements or collection fields without a WeakReference wrapper.

Components NEVER store raw Swift protocol implementations in long-lived Kotlin coroutine context elements or collection fields without a WeakReference 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Kotlin Native & Swift ARC Interop Boundary Memory Isolation critical for AI coding assistants?

Enforces strict isolation between Swift Automatic Reference Counting (ARC) and Kotlin/Native tracing Garbage Collection (GC) across the Objective-C/Swift-Export ABI. Prohibits cross-runtime cyclic retain paths where Kotlin objects hold strong references to Swift instances implementing exported interfaces without deterministic lifecycle detachment. 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 Cyclic Retain Graph Causing Undetectable Native Memory Leaks) 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