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

KMP Swift Export ARC Memory Cycle Deadlock Prevention Invariant

Eliminates non-deterministic native memory retention and deadlock between Kotlin/Native tracing GC and Apple ARC runtimes by enforcing bidirectional weak proxy wrappers across compilation boundaries. Prevents cross-runtime strong reference graphs that escape cycle detection in both independent memory managers. Guarantees deterministic teardown of observable listeners, platform delegates, and callback subscriptions crossing the Swift-Kotlin interop boundary.

Prohibited Anti-Pattern: Cross-Runtime Circular Strong References Escaping Both ARC and Kotlin Native GC

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Swift Export ARC Memory Cycle Deadlock Prevention Invariant - Eliminates non-deterministic native memory retention and deadlock between Kotlin/Native tracing GC and Apple ARC runtimes by enforcing bidirectional weak proxy wrappers across compilation boundaries. Prevents cross-runtime strong reference graphs that escape cycle detection in both independent memory managers. Guarantees deterministic teardown of observable listeners, platform delegates, and callback subscriptions crossing the Swift-Kotlin interop boundary.
globs: **/shared/src/iosMain/**/*.kt, **/shared/src/commonMain/**/*.kt, **/iosApp/**/*.swift, **/PlatformInterop/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-arc-memory-cycle-deadlock-prevention"
---

# KMP Swift Export ARC Memory Cycle Deadlock Prevention Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Cross-Runtime Circular Strong References Escaping Both ARC and Kotlin Native GC

## System Constraints
You are a Principal Engineer enforcing KMP Swift Export ARC Memory Cycle Deadlock Prevention Invariant. Mandate that every cross-boundary reference crossing Kotlin/Native and Swift runtimes utilizes bidirectional weak proxy wrappers. Disallow direct strong object references across interop bridges. Mandate explicit lifecycle detach tokens or WeakReference holders on the Kotlin side alongside weak/unowned delegate closures on the Swift side.

## Strict Guidelines
- Engineers MUST ALWAYS encapsulate cross-boundary listeners and delegates within an explicit WeakReference wrapper or Swift-facing weak delegate proxy.
- Engineers MUST NOT allow a Swift class retained by ARC to pass a strong self reference directly into a long-lived Kotlin coroutine scope or state repository.
- Code SHOULD provide deterministic closeable/cancellable unbind semantics to break native bridge bindings during view controller deallocation.
- Services MUST route asynchronous Kotlin Flow subscriptions through explicit lifecycle-aware cancellable tokens that do not strongly capture Swift host contexts.
- Components NEVER bridge cyclical observer patterns (e.g., Swift ViewModel observing Kotlin Engine observing Swift Delegate) without marking at least one traversal edge as weak.

## Bad vs Good Implementations
### Cross-Boundary Listener Registration via Weak Proxy

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin's GC treats the Swift listener interface implementation as a strong GC root, while the Swift coordinator retains the Kotlin hub reference. Neither ARC nor Kotlin's tracing GC can traverse the foreign runtime boundary to identify the cycle, resulting in permanent heap leakage.
```kotlin
// Kotlin Native Platform Interop
class NativeEventHub {
    private val listeners = mutableListOf<NativeEventListener>()

    fun addListener(listener: NativeEventListener) {
        // Strong reference prevents Swift listener from being deallocated by ARC
        listeners.add(listener)
    }
}

// Swift (ARC Side)
// class SwiftCoordinator: NativeEventListener {
//     init(hub: NativeEventHub) {
//         hub.addListener(listener: self) // Retain cycle: SwiftCoordinator <-> NativeEventHub
//     }
// }
```

#### Production Standard (Correct)
> **Standard**: The Kotlin runtime wraps the Swift object via WeakReference, allowing Apple ARC to reclaim the SwiftCoordinator instance when its native hierarchy deallocates. Kotlin cleans up stale weak references on subsequent dispatches without deadlock.
```kotlin
// Kotlin Native Platform Interop with Weak Proxy Bridge
import kotlin.native.ref.WeakReference

interface NativeEventListener : Any

class NativeEventHub {
    private val listeners = mutableListOf<WeakReference<NativeEventListener>>()

    fun addListener(listener: NativeEventListener) {
        listeners.removeAll { it.get() == null }
        listeners.add(WeakReference(listener))
    }

    fun notifyEvent(block: (NativeEventListener) -> Unit) {
        listeners.removeAll { it.get() == null }
        listeners.forEach { ref ->
            ref.get()?.let(block)
        }
    }
}

// Swift (ARC Side)
// final class SwiftCoordinator: NativeEventListener {
//     private let hub: NativeEventHub
//     init(hub: NativeEventHub) {
//         self.hub = hub
//         self.hub.addListener(listener: self)
//     }
//     deinit { /* Deterministically deallocated */ }
// }
```

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 ARC Memory Cycle Deadlock Prevention Invariant

KMP Swift Export ARC Memory Cycle Deadlock Prevention Invariant defines an industrial-grade behavioral standard for mobile engineering. Eliminates non-deterministic native memory retention and deadlock between Kotlin/Native tracing GC and Apple ARC runtimes by enforcing bidirectional weak proxy wrappers across compilation boundaries. Prevents cross-runtime strong reference graphs that escape cycle detection in both independent memory managers. Guarantees deterministic teardown of observable listeners, platform delegates, and callback subscriptions crossing the Swift-Kotlin interop boundary. 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 Strong References Escaping Both ARC and Kotlin Native GC 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 Strong References Escaping Both ARC and Kotlin Native GCCritical
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 encapsulate cross-boundary listeners and delegates within an explicit WeakReference wrapper or Swift-facing weak delegate proxy.

Engineers MUST ALWAYS encapsulate cross-boundary listeners and delegates within an explicit WeakReference wrapper or Swift-facing weak delegate proxy.

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 a Swift class retained by ARC to pass a strong self reference directly into a long-lived Kotlin coroutine scope or state repository.

Engineers MUST NOT allow a Swift class retained by ARC to pass a strong self reference directly into a long-lived Kotlin coroutine scope or state repository.

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 provide deterministic closeable/cancellable unbind semantics to break native bridge bindings during view controller deallocation.

Code SHOULD provide deterministic closeable/cancellable unbind semantics to break native bridge bindings during view controller deallocation.

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 route asynchronous Kotlin Flow subscriptions through explicit lifecycle-aware cancellable tokens that do not strongly capture Swift host contexts.

Services MUST route asynchronous Kotlin Flow subscriptions through explicit lifecycle-aware cancellable tokens that do not strongly capture Swift host 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 bridge cyclical observer patterns (e.g., Swift ViewModel observing Kotlin Engine observing Swift Delegate) without marking at least one traversal edge as weak.

Components NEVER bridge cyclical observer patterns (e.g., Swift ViewModel observing Kotlin Engine observing Swift Delegate) without marking at least one traversal edge as weak.

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 ARC Memory Cycle Deadlock Prevention Invariant critical for AI coding assistants?

Eliminates non-deterministic native memory retention and deadlock between Kotlin/Native tracing GC and Apple ARC runtimes by enforcing bidirectional weak proxy wrappers across compilation boundaries. Prevents cross-runtime strong reference graphs that escape cycle detection in both independent memory managers. Guarantees deterministic teardown of observable listeners, platform delegates, and callback subscriptions crossing the Swift-Kotlin interop boundary. 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 Strong References Escaping Both ARC and Kotlin Native GC) 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