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

Kotlin Native Darwin GC and Apple ARC Interop Boundary Leak & Deadlock Guardrail

Prevents catastrophic cross-runtime retain cycles and interop deadlocks across Kotlin/Native Garbage Collector and Apple Automatic Reference Counting (ARC). Mandates explicit cancellation of cross-boundary state observers, safe disposal of StableRef wrappers, and non-blocking asynchronous cleanup during Darwin object deallocation.

Prohibited Anti-Pattern: Cross-Runtime Retain Cycles and Synchronous Interop Deallocation Deadlocks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Native Darwin GC and Apple ARC Interop Boundary Leak & Deadlock Guardrail - Prevents catastrophic cross-runtime retain cycles and interop deadlocks across Kotlin/Native Garbage Collector and Apple Automatic Reference Counting (ARC). Mandates explicit cancellation of cross-boundary state observers, safe disposal of StableRef wrappers, and non-blocking asynchronous cleanup during Darwin object deallocation.
globs: **/iosMain/**/*.kt, **/darwinMain/**/*.kt, iosApp/**/*.swift, **/swift/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-darwin-arc-gc-boundary-leak-guardrail"
---

# Kotlin Native Darwin GC and Apple ARC Interop Boundary Leak & Deadlock Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Cross-Runtime Retain Cycles and Synchronous Interop Deallocation Deadlocks

## System Constraints
You are a Principal Mobile Architect enforcing absolute memory safety and deadlock prevention across the Kotlin/Native (Darwin GC) and Apple ARC runtime boundaries. Cross-runtime object graphs cannot be resolved automatically by either runtime's garbage collector or reference counting engine. You must enforce explicit weak capturing, deterministic subscription disposal, zero synchronous worker blocking during deinitialization, and safe StableRef lifecycle management.

## Strict Guidelines
- Engineers MUST ALWAYS capture Darwin objects weakly (`[weak self]`) when binding closures or delegates to Kotlin Multiplatform state engines or coroutine flows.
- Engineers MUST ALWAYS store and deterministically cancel Kotlin Flow observation tokens (e.g., `SKIE` Task, `Closeable`, or `Job`) in Swift lifecycle deinit or view disappearance hooks.
- Engineers MUST NOT invoke synchronous Kotlin dispatchers or blocking Kotlin interop calls (e.g., `runBlocking`, synchronous Kotlin thread joins) inside Swift `deinit` or Objective-C `dealloc`.
- Code interacting with Kotlin Native `StableRef` MUST guarantee exactly-once invocation of `.dispose()` via try-finally blocks or structured RAII-style wrappers to avoid permanent uncollectible root pinning.
- Components NEVER store direct strong references to Darwin delegate instances inside long-lived Kotlin Singletons; delegates MUST be wrapped in Kotlin `WeakReference` or detached on component teardown.
- Services exposing Darwin interop boundaries MUST expose dedicated `close()` or `detach()` lifecycle methods to break bidirectional cross-heap references prior to runtime teardown.

## Bad vs Good Implementations
### Swift State Engine Subscription Across KMP Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin Native holds a strong reference to the observation lambda in its heap. The lambda strongly captures the Swift ObservableObject, while Swift holds the Kotlin engine and Closeable handle. Neither ARC nor Kotlin's GC can trace across the foreign runtime boundary, creating a permanent cross-heap retain cycle.
```swift
// BAD: Strong reference cycle across ARC and Kotlin GC runtime boundaries
final class UserProfileViewModel: ObservableObject {
    @Published var state: UserState = .initial
    private let stateEngine: UserStateEngine // Kotlin KMP Instance
    private var cancellable: Closeable? 

    init(stateEngine: UserStateEngine) {
        self.stateEngine = stateEngine
        // Anti-pattern: Strongly captures 'self' into Kotlin GC heap without lifecycle detachment
        self.cancellable = stateEngine.observeState { newState in
            self.state = newState
        }
    }
    // No deinit cancellation: Kotlin GC holds callback, callback holds Swift VM,
    // Swift VM holds KMP stateEngine. Uncollectible memory leak across both runtimes.
}
```

#### Production Standard (Correct)
> **Standard**: Using weak capture prevents the Kotlin coroutine iterator/closure from holding a strong reference to the Swift object. Structured Task cancellation in deinit ensures all cross-language streaming operations terminate cleanly without blocking the Darwin main deallocation thread.
```swift
// GOOD: Weak capture in Swift closure combined with deterministic deinit disposal
final class UserProfileViewModel: ObservableObject {
    @Published var state: UserState = .initial
    private let stateEngine: UserStateEngine
    private var observationTask: Task<Void, Never>?

    init(stateEngine: UserStateEngine) {
        self.stateEngine = stateEngine
        // Invariant: Capture self weakly across runtime boundary
        self.observationTask = Task { [weak self] in
            for await newState in stateEngine.stateFlow {
                guard let self = self else { return }
                await MainActor.run {
                    self.state = newState
                }
            }
        }
    }

    deinit {
        // Invariant: Non-blocking asynchronous cancellation on native teardown
        observationTask?.cancel()
    }
}
```

### Kotlin Native C-Interop StableRef Lifecycle Management

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: StableRef.create pins the Kotlin object in memory so GC cannot collect it. Failing to call .dispose() leaks both the Kotlin callback and any objects it references, permanently anchoring them as GC roots.
```kotlin
// BAD: Leaking StableRef and executing blocking call during Darwin interop cleanup
import kotlinx.cinterop.*

class DarwinNativeBridge(private val callback: () -> Unit) {
    private val stableRef = StableRef.create(callback)

    fun registerWithDarwinSystem() {
        darwin_system_register_callback(
            stableRef.asCPointer(),
            staticCFunction { ptr ->
                val cb = ptr?.asStableRef<() -> Unit>()?.get()
                cb?.invoke()
            }
        )
    }
    // Anti-pattern: Missing dispose() leaks uncollected root pin in Kotlin GC
}
```

#### Production Standard (Correct)
> **Standard**: Implements AutoCloseable and explicitly invokes stableRef.dispose(), unregistering from Darwin subsystem and allowing the Kotlin GC to safely reclaim the pinned callback.
```kotlin
// GOOD: Deterministic AutoCloseable cleanup with paired StableRef disposal
import kotlinx.cinterop.*

class DarwinNativeBridge(
    private val callback: () -> Unit
) : AutoCloseable {
    private var stableRef: StableRef<() -> Unit>? = StableRef.create(callback)

    fun registerWithDarwinSystem() {
        val ref = checkNotNull(stableRef) { "Bridge already disposed" }
        darwin_system_register_callback(
            ref.asCPointer(),
            staticCFunction { ptr ->
                val cb = ptr?.asStableRef<() -> Unit>()?.get()
                cb?.invoke()
            }
        )
    }

    override fun close() {
        // Invariant: Strictly paired dispose() releases pinned GC root
        stableRef?.dispose()
        stableRef = null
        darwin_system_unregister_callback()
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kotlin Native Darwin GC and Apple ARC Interop Boundary Leak & Deadlock Guardrail

Kotlin Native Darwin GC and Apple ARC Interop Boundary Leak & Deadlock Guardrail defines an industrial-grade behavioral standard for mobile engineering. Prevents catastrophic cross-runtime retain cycles and interop deadlocks across Kotlin/Native Garbage Collector and Apple Automatic Reference Counting (ARC). Mandates explicit cancellation of cross-boundary state observers, safe disposal of StableRef wrappers, and non-blocking asynchronous cleanup during Darwin object deallocation. 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 Retain Cycles and Synchronous Interop Deallocation Deadlocks 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 Retain Cycles and Synchronous Interop Deallocation DeadlocksCritical
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 Darwin objects weakly (`[weak self]`) when binding closures or delegates to Kotlin Multiplatform state engines or coroutine flows.

Engineers MUST ALWAYS capture Darwin objects weakly (`[weak self]`) when binding closures or delegates to Kotlin Multiplatform state engines or coroutine flows.

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 ALWAYS store and deterministically cancel Kotlin Flow observation tokens (e.g., `SKIE` Task, `Closeable`, or `Job`) in Swift lifecycle deinit or view disappearance hooks.

Engineers MUST ALWAYS store and deterministically cancel Kotlin Flow observation tokens (e.g., `SKIE` Task, `Closeable`, or `Job`) in Swift lifecycle deinit or view disappearance hooks.

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 NOT invoke synchronous Kotlin dispatchers or blocking Kotlin interop calls (e.g., `runBlocking`, synchronous Kotlin thread joins) inside Swift `deinit` or Objective-C `dealloc`.

Engineers MUST NOT invoke synchronous Kotlin dispatchers or blocking Kotlin interop calls (e.g., `runBlocking`, synchronous Kotlin thread joins) inside Swift `deinit` or Objective-C `dealloc`.

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 interacting with Kotlin Native `StableRef` MUST guarantee exactly-once invocation of `.dispose()` via try-finally blocks or structured RAII-style wrappers to avoid permanent uncollectible root pinning.

Code interacting with Kotlin Native `StableRef` MUST guarantee exactly-once invocation of `.dispose()` via try-finally blocks or structured RAII-style wrappers to avoid permanent uncollectible root pinning.

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 direct strong references to Darwin delegate instances inside long-lived Kotlin Singletons

Components NEVER store direct strong references to Darwin delegate instances inside long-lived Kotlin Singletons; delegates MUST be wrapped in Kotlin `WeakReference` or detached on component teardown.

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.
6

Services exposing Darwin interop boundaries MUST expose dedicated `close()` or `detach()` lifecycle methods to break bidirectional cross-heap references prior to runtime teardown.

Services exposing Darwin interop boundaries MUST expose dedicated `close()` or `detach()` lifecycle methods to break bidirectional cross-heap references prior to runtime teardown.

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 Darwin GC and Apple ARC Interop Boundary Leak & Deadlock Guardrail critical for AI coding assistants?

Prevents catastrophic cross-runtime retain cycles and interop deadlocks across Kotlin/Native Garbage Collector and Apple Automatic Reference Counting (ARC). Mandates explicit cancellation of cross-boundary state observers, safe disposal of StableRef wrappers, and non-blocking asynchronous cleanup during Darwin object deallocation. 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 Retain Cycles and Synchronous Interop Deallocation Deadlocks) 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