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

Kotlin Multiplatform Swift Export Memory Ownership & ARC-GC Bridge Invariants

Enforces strict memory boundary management between Swift ARC and Kotlin Native GC across Swift Export boundaries. Guarantees deterministic deallocation and eliminates bidirectional retain cycles by mandating unidirectional state flow, serializable value-type snapshots, and explicit handle lifecycles instead of bidirectional object-reference graphs.

Prohibited Anti-Pattern: Bidirectional Long-Lived References Between Swift ViewModels and Kotlin Native Singletons Causing Silent Native Heap Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Swift Export Memory Ownership & ARC-GC Bridge Invariants - Enforces strict memory boundary management between Swift ARC and Kotlin Native GC across Swift Export boundaries. Guarantees deterministic deallocation and eliminates bidirectional retain cycles by mandating unidirectional state flow, serializable value-type snapshots, and explicit handle lifecycles instead of bidirectional object-reference graphs.
globs: shared/src/commonMain/**/*.kt, shared/src/iosMain/**/*.kt, iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-memory-ownership-invariant"
---

# Kotlin Multiplatform Swift Export Memory Ownership & ARC-GC Bridge Invariants

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Bidirectional Long-Lived References Between Swift ViewModels and Kotlin Native Singletons Causing Silent Native Heap Leaks

## System Constraints
You are a Principal Mobile Architect enforcing strict native memory ownership invariants between Apple ARC and Kotlin Native GC via Swift Export. Bidirectional strong reference graphs between Swift and Kotlin cross-runtime boundaries are strictly prohibited. You must mandate value-type transfers, structured cancellation scopes, and explicit handle patterns to guarantee deterministic deallocation without GC-ARC deadlocks or native heap leaks.

## Strict Guidelines
- Engineers MUST ALWAYS transfer domain data across the Swift Export boundary as immutable value projections (primitives, plain Kotlin data classes projecting to Swift structs/records) rather than stateful object graphs.
- Engineers MUST NOT pass Swift reference closures (such as ViewModel callbacks or escaping SwiftUI state mutators) into Kotlin Native long-lived scopes or singletons without explicit weak wrappers.
- Swift observers MUST consume Kotlin Flows exclusively via structured lifecycle adapters that expose explicit cancel/dispose functions invoked during Swift deinit or SwiftUI task cancellation.
- Kotlin Native exports MUST NEVER retain strong references to native Swift delegate protocols or objective-c pointers beyond the synchronous execution frame of a single function invocation.
- Shared business engines MUST expose deterministic dispose() or close() lifecycle methods that clear internal CoroutineScopes, ensuring Kotlin Native objects do not pin platform resources post-deinit.

## Bad vs Good Implementations
### Bridging Asynchronous Kotlin State Flow to Swift ARC Lifecycle

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin Native holds an exported closure callback reference in its root-set, which retains the Swift ViewModel instance. Concurrently, the ViewModel retains the Kotlin repository. Because Kotlin Native GC cannot traverse ARC root blocks, this forms an uncollectable cross-runtime retain cycle.
```swift
// BAD: Retaining a strong closure capture of Swift ViewModel inside long-lived Kotlin flow wrapper
import SharedKit

@MainActor
final class ProfileViewModel: ObservableObject {
    @Published private(set) var userState: UserState = .empty
    private let repository = UserRepositoryCompanion.shared.getInstance()

    init() {
        // Leaks memory: repository retains Swift closure strongly, Swift ViewModel retains repository
        repository.observeUser { [self] state in
            self.userState = state
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The Swift ViewModel relies on Swift Concurrency (AsyncSequence/Task) combined with [weak self]. When the ViewModel's ARC count drops to zero, deinit immediately cancels the observation task, terminating the Kotlin flow collection cleanly on both sides of the bridge.
```swift
// GOOD: Structured lifecycle binding with deterministic Task cancellation and weak Swift capture
import SharedKit

@MainActor
final class ProfileViewModel: ObservableObject {
    @Published private(set) var userProfile: UserProfileValue = .empty
    private let repository: UserRepository
    private var observationTask: Task<Void, Never>?

    init(repository: UserRepository = UserRepositoryCompanion.shared.getInstance()) {
        self.repository = repository
        self.observationTask = Task { [weak self] in
            for await snapshot in repository.profileSnapshots {
                guard let self = self else { break }
                // Pure value type transfer with no cross-runtime object retention
                self.userProfile = snapshot.toValue()
            }
        }
    }

    deinit {
        observationTask?.cancel()
    }
}
```

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 Memory Ownership & ARC-GC Bridge Invariants

Kotlin Multiplatform Swift Export Memory Ownership & ARC-GC Bridge Invariants defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory boundary management between Swift ARC and Kotlin Native GC across Swift Export boundaries. Guarantees deterministic deallocation and eliminates bidirectional retain cycles by mandating unidirectional state flow, serializable value-type snapshots, and explicit handle lifecycles instead of bidirectional object-reference graphs. 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 Long-Lived References Between Swift ViewModels and Kotlin Native Singletons Causing Silent Native Heap 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 Long-Lived References Between Swift ViewModels and Kotlin Native Singletons Causing Silent Native Heap 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 transfer domain data across the Swift Export boundary as immutable value projections (primitives, plain Kotlin data classes projecting to Swift structs/records) rather than stateful object graphs.

Engineers MUST ALWAYS transfer domain data across the Swift Export boundary as immutable value projections (primitives, plain Kotlin data classes projecting to Swift structs/records) rather than stateful object graphs.

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 reference closures (such as ViewModel callbacks or escaping SwiftUI state mutators) into Kotlin Native long-lived scopes or singletons without explicit weak wrappers.

Engineers MUST NOT pass Swift reference closures (such as ViewModel callbacks or escaping SwiftUI state mutators) into Kotlin Native long-lived scopes or singletons without explicit weak wrappers.

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

Swift observers MUST consume Kotlin Flows exclusively via structured lifecycle adapters that expose explicit cancel/dispose functions invoked during Swift deinit or SwiftUI task cancellation.

Swift observers MUST consume Kotlin Flows exclusively via structured lifecycle adapters that expose explicit cancel/dispose functions invoked during Swift deinit or SwiftUI task cancellation.

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

Kotlin Native exports MUST NEVER retain strong references to native Swift delegate protocols or objective-c pointers beyond the synchronous execution frame of a single function invocation.

Kotlin Native exports MUST NEVER retain strong references to native Swift delegate protocols or objective-c pointers beyond the synchronous execution frame of a single function invocation.

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

Shared business engines MUST expose deterministic dispose() or close() lifecycle methods that clear internal CoroutineScopes, ensuring Kotlin Native objects do not pin platform resources post-deinit.

Shared business engines MUST expose deterministic dispose() or close() lifecycle methods that clear internal CoroutineScopes, ensuring Kotlin Native objects do not pin platform resources post-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.
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 Memory Ownership & ARC-GC Bridge Invariants critical for AI coding assistants?

Enforces strict memory boundary management between Swift ARC and Kotlin Native GC across Swift Export boundaries. Guarantees deterministic deallocation and eliminates bidirectional retain cycles by mandating unidirectional state flow, serializable value-type snapshots, and explicit handle lifecycles instead of bidirectional object-reference graphs. 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 Long-Lived References Between Swift ViewModels and Kotlin Native Singletons Causing Silent Native Heap 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