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-invariant

Kotlin Multiplatform Swift-Export ARC Memory Boundary Invariant

Enforces strict ownership, weak listener delegation, and explicit lifetime management across the Swift ARC and Kotlin/Native Garbage Collector boundary. Prevents invisible cross-runtime retain cycles that neither Swift ARC nor Kotlin GC can collect autonomously. Guarantees deterministic resource teardown without leaking Native/Swift bridge proxy stubs.

Prohibited Anti-Pattern: Bidirectional Retain Cycles Across Cross-Runtime FFI Boundaries Causing Permanent Memory Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Swift-Export ARC Memory Boundary Invariant - Enforces strict ownership, weak listener delegation, and explicit lifetime management across the Swift ARC and Kotlin/Native Garbage Collector boundary. Prevents invisible cross-runtime retain cycles that neither Swift ARC nor Kotlin GC can collect autonomously. Guarantees deterministic resource teardown without leaking Native/Swift bridge proxy stubs.
globs: **/*.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-invariant"
---

# Kotlin Multiplatform Swift-Export ARC Memory Boundary Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Bidirectional Retain Cycles Across Cross-Runtime FFI Boundaries Causing Permanent Memory Leaks

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform and Swift interoperability. You must strictly enforce memory ownership boundaries across Swift ARC and Kotlin/Native GC. The Kotlin Native collector cannot traverse ARC reference graphs, and ARC cannot trace Kotlin heap allocations. When Swift delegates, callbacks, or observers are passed to Kotlin, you must mandate weak references, explicit tokenized unsubscription, and cancellation of bidirectional roots.

## Strict Guidelines
- Engineers MUST NEVER pass strong Swift closure references or strong delegate instances into long-lived Kotlin objects without explicit lifecycle-bound cancellation tokens.
- Engineers MUST ALWAYS capture '[weak self]' in any Swift completion handler or observer closure passed into Kotlin suspend-bridged tasks or Flow collectors.
- Kotlin bridge interfaces implemented by Swift MUST be exposed as weak delegates or backed by explicit 'AutoCloseable'/'DisposableHandle' cancellation contracts in commonMain.
- Code SHOULD prefer reactive stream collection via cancellation-scoped wrappers (e.g., SKIE or Swift-Export AsyncStream adapters) rather than ad-hoc listener registration.
- Services MUST explicitly call de-registration or cleanup methods in iOS UIViewController/SwiftUI view teardown (such as 'deinit' or '.onDisappear').
- Components NEVER assume Kotlin Native GC will trigger Swift ARC 'deinit' deterministically for objects held across the FFI wrapper boundary.

## Bad vs Good Implementations
### Swift Observer Registered with KMP StateManager

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing a closure capturing strong 'self' to a long-lived Kotlin object creates a cross-runtime cycle: Swift owns ProfileViewModel, Kotlin StateManager holds Swift closure wrapper, Swift closure wrapper strongly retains ProfileViewModel. Kotlin GC cannot see the ARC reference, leading to an immortal leak.
```swift
class ProfileViewModel {
    private let stateManager: UserStateManager

    init(stateManager: UserStateManager) {
        self.stateManager = stateManager
        // ANTI-PATTERN: Strong capture of self across the KMP FFI boundary.
        // Neither Swift ARC nor Kotlin GC can break this cross-runtime cycle.
        self.stateManager.observeProfileUpdates { profile in
            self.updateUI(profile: profile)
        }
    }

    private func updateUI(profile: UserProfile) {
        // UI update logic
    }
}
```

#### Production Standard (Correct)
> **Standard**: The Swift closure captures '[weak self]', preventing ARC from retaining ProfileViewModel through the callback wrapper. Additionally, storing and disposing the 'DisposableHandle' in 'deinit' guarantees deterministic release of the Kotlin Native proxy reference.
```swift
class ProfileViewModel {
    private let stateManager: UserStateManager
    private var updateSubscription: DisposableHandle?

    init(stateManager: UserStateManager) {
        self.stateManager = stateManager
        // INVARIANT FIX: Capture weak self and hold a disposable subscription token
        self.updateSubscription = self.stateManager.observeProfileUpdates { [weak self] profile in
            guard let self = self else { return }
            self.updateUI(profile: profile)
        }
    }

    private func updateUI(profile: UserProfile) {
        // UI update logic
    }

    deinit {
        // Explicit deterministic boundary teardown
        updateSubscription?.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 Multiplatform Swift-Export ARC Memory Boundary Invariant

Kotlin Multiplatform Swift-Export ARC Memory Boundary Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces strict ownership, weak listener delegation, and explicit lifetime management across the Swift ARC and Kotlin/Native Garbage Collector boundary. Prevents invisible cross-runtime retain cycles that neither Swift ARC nor Kotlin GC can collect autonomously. Guarantees deterministic resource teardown without leaking Native/Swift bridge proxy stubs. 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: Bidirectional Retain Cycles Across Cross-Runtime FFI Boundaries Causing Permanent 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 DriftBidirectional Retain Cycles Across Cross-Runtime FFI Boundaries Causing Permanent 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 NEVER pass strong Swift closure references or strong delegate instances into long-lived Kotlin objects without explicit lifecycle-bound cancellation tokens.

Engineers MUST NEVER pass strong Swift closure references or strong delegate instances into long-lived Kotlin objects without explicit lifecycle-bound cancellation tokens.

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 capture '[weak self]' in any Swift completion handler or observer closure passed into Kotlin suspend-bridged tasks or Flow collectors.

Engineers MUST ALWAYS capture '[weak self]' in any Swift completion handler or observer closure passed into Kotlin suspend-bridged tasks or Flow collectors.

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

Kotlin bridge interfaces implemented by Swift MUST be exposed as weak delegates or backed by explicit 'AutoCloseable'/'DisposableHandle' cancellation contracts in commonMain.

Kotlin bridge interfaces implemented by Swift MUST be exposed as weak delegates or backed by explicit 'AutoCloseable'/'DisposableHandle' cancellation contracts in commonMain.

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 prefer reactive stream collection via cancellation-scoped wrappers (e.g., SKIE or Swift-Export AsyncStream adapters) rather than ad-hoc listener registration.

Code SHOULD prefer reactive stream collection via cancellation-scoped wrappers (e.g., SKIE or Swift-Export AsyncStream adapters) rather than ad-hoc listener registration.

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

Services MUST explicitly call de-registration or cleanup methods in iOS UIViewController/SwiftUI view teardown (such as 'deinit' or '.onDisappear').

Services MUST explicitly call de-registration or cleanup methods in iOS UIViewController/SwiftUI view teardown (such as 'deinit' or '.onDisappear').

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

Components NEVER assume Kotlin Native GC will trigger Swift ARC 'deinit' deterministically for objects held across the FFI wrapper boundary.

Components NEVER assume Kotlin Native GC will trigger Swift ARC 'deinit' deterministically for objects held across the FFI wrapper boundary.

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

Enforces strict ownership, weak listener delegation, and explicit lifetime management across the Swift ARC and Kotlin/Native Garbage Collector boundary. Prevents invisible cross-runtime retain cycles that neither Swift ARC nor Kotlin GC can collect autonomously. Guarantees deterministic resource teardown without leaking Native/Swift bridge proxy stubs. 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 (Bidirectional Retain Cycles Across Cross-Runtime FFI Boundaries Causing Permanent 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