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

Kotlin Multiplatform 2.1 Swift Export ARC Cycle Sentinel

Enforces strict memory boundary decoupling between Swift Automatic Reference Counting (ARC) and Kotlin/Native tracing GC across Kotlin 2.1 Swift Export boundaries. Cross-runtime strong references form uncollectible islands because neither Swift ARC nor Kotlin GC can traverse the foreign runtime heap. Mandates unidirectional event streaming and explicit RAII cancellation tokens over bidirectional callback or delegate retention.

Prohibited Anti-Pattern: Cross-Runtime Retain Cycles Between Swift ARC and Kotlin/Native Tracing Garbage Collector

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform 2.1 Swift Export ARC Cycle Sentinel - Enforces strict memory boundary decoupling between Swift Automatic Reference Counting (ARC) and Kotlin/Native tracing GC across Kotlin 2.1 Swift Export boundaries. Cross-runtime strong references form uncollectible islands because neither Swift ARC nor Kotlin GC can traverse the foreign runtime heap. Mandates unidirectional event streaming and explicit RAII cancellation tokens over bidirectional callback or delegate retention.
globs: shared/src/commonMain/kotlin/**/*.kt, shared/src/iosMain/kotlin/**/*.kt, iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-2-1-swift-export-arc-cycle-sentinel"
---

# Kotlin Multiplatform 2.1 Swift Export ARC Cycle Sentinel

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Cross-Runtime Retain Cycles Between Swift ARC and Kotlin/Native Tracing Garbage Collector

## System Constraints
You are a Principal Mobile Architect enforcing the Kotlin Multiplatform 2.1 Swift Export ARC Cycle Sentinel. Cross-heap reference cycles between Kotlin Native's Garbage Collector and Apple Swift ARC cause permanent, silent native heap leaks that survive view teardown. You must mandate clean lifecycle-bound token observation, prohibit direct Swift object references passed into persistent Kotlin objects without explicit disposal semantics, and enforce RAII-based Swift Task lifecycle management for exported asynchronous streams.

## Strict Guidelines
- Engineers MUST ALWAYS enforce unidirectional data flow across the Swift Export boundary by exposing read-only Kotlin `StateFlow` or `SharedFlow` exposed via Swift `AsyncSequence` instead of passing stateful Swift callback delegates into Kotlin.
- Engineers MUST NOT pass Swift class instances or escaping closures directly into long-lived Kotlin singletons or domain repositories as listeners, delegates, or observers.
- Code SHOULD utilize Swift's `Task` cancellation and Kotlin's `DisposableHandle` or `AutoCloseable` to cleanly sever FFI references when a Swift View, Presenter, or ViewModel deinitializes.
- Services MUST emit scalar values, immutably serialized data transfer objects, or detached value types across the exported interface rather than maintaining shared mutable state across runtime boundaries.
- Components NEVER store a bidirectional strong pointer across the C-interop/Swift Export FFI boundary without a deterministic teardown mechanism invoked on Swift `deinit`.

## Bad vs Good Implementations
### Uncollectible Cross-Runtime Delegate Cycle (Swift ARC <-> Kotlin GC)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin Native holds a strong FFI reference to the Swift instance via the delegate bridge, while Swift holds a strong ARC reference to the Kotlin Presenter. Because Kotlin GC and Swift ARC operate on distinct memory heaps with independent collection semantics, this circular graph is invisible to both collectors, creating an irrecoverable leak.
```swift
// Swift View/Presenter retaining Kotlin Presenter, and Kotlin retaining Swift Delegate
final class ProfileViewController: UIViewController, ProfileKotlinDelegate {
    private let presenter = ProfilePresenter() // Kotlin object exported to Swift

    override func viewDidLoad() {
        super.viewDidLoad()
        // CRITICAL BUG: presenter holds strong reference to self via ObjC/Swift bridge.
        // Kotlin GC cannot inspect Swift ARC; Swift ARC sees presenter retained by self.
        // Result: Permanent uncollectible heap island across the FFI runtime boundary.
        presenter.setDelegate(delegate: self)
    }

    func onProfileLoaded(profile: ProfileData) {
        // UI updates
    }
}
```

#### Production Standard (Correct)
> **Standard**: The Swift consumer observes updates via an asynchronous stream without registering a long-lived reverse pointer in the Kotlin heap. Cancellation inside Swift's `deinit` immediately releases the native continuation handle, preserving strict single-direction dependency flow and preventing cross-heap retention.
```swift
// Unidirectional, RAII-governed observation across Swift Export
final class ProfileViewController: UIViewController {
    private let presenter = ProfilePresenter() // Kotlin 2.1 exported class
    private var observationTask: Task<Void, Never>?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Consume Kotlin StateFlow as a native Swift AsyncSequence
        observationTask = Task { [weak self] in
            for await state in self?.presenter.stateFlow ?? AsyncStream.never {
                guard !Task.isCancelled else { break }
                self?.render(state: state)
            }
        }
    }

    deinit {
        // Deterministic cancellation severs the Swift-to-Kotlin coroutine subscription
        observationTask?.cancel()
    }

    private func render(state: ProfileUiState) {
        // UI updates
    }
}
```

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 2.1 Swift Export ARC Cycle Sentinel

Kotlin Multiplatform 2.1 Swift Export ARC Cycle Sentinel defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory boundary decoupling between Swift Automatic Reference Counting (ARC) and Kotlin/Native tracing GC across Kotlin 2.1 Swift Export boundaries. Cross-runtime strong references form uncollectible islands because neither Swift ARC nor Kotlin GC can traverse the foreign runtime heap. Mandates unidirectional event streaming and explicit RAII cancellation tokens over bidirectional callback or delegate retention. 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 Between Swift ARC and Kotlin/Native Tracing Garbage Collector 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 Between Swift ARC and Kotlin/Native Tracing Garbage CollectorCritical
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 enforce unidirectional data flow across the Swift Export boundary by exposing read-only Kotlin `StateFlow` or `SharedFlow` exposed via Swift `AsyncSequence` instead of passing stateful Swift callback delegates into Kotlin.

Engineers MUST ALWAYS enforce unidirectional data flow across the Swift Export boundary by exposing read-only Kotlin `StateFlow` or `SharedFlow` exposed via Swift `AsyncSequence` instead of passing stateful Swift callback delegates into Kotlin.

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 class instances or escaping closures directly into long-lived Kotlin singletons or domain repositories as listeners, delegates, or observers.

Engineers MUST NOT pass Swift class instances or escaping closures directly into long-lived Kotlin singletons or domain repositories as listeners, delegates, or observers.

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 Swift's `Task` cancellation and Kotlin's `DisposableHandle` or `AutoCloseable` to cleanly sever FFI references when a Swift View, Presenter, or ViewModel deinitializes.

Code SHOULD utilize Swift's `Task` cancellation and Kotlin's `DisposableHandle` or `AutoCloseable` to cleanly sever FFI references when a Swift View, Presenter, or ViewModel deinitializes.

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 emit scalar values, immutably serialized data transfer objects, or detached value types across the exported interface rather than maintaining shared mutable state across runtime boundaries.

Services MUST emit scalar values, immutably serialized data transfer objects, or detached value types across the exported interface rather than maintaining shared mutable state across runtime boundaries.

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 a bidirectional strong pointer across the C-interop/Swift Export FFI boundary without a deterministic teardown mechanism invoked on Swift `deinit`.

Components NEVER store a bidirectional strong pointer across the C-interop/Swift Export FFI boundary without a deterministic teardown mechanism invoked on Swift `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 2.1 Swift Export ARC Cycle Sentinel critical for AI coding assistants?

Enforces strict memory boundary decoupling between Swift Automatic Reference Counting (ARC) and Kotlin/Native tracing GC across Kotlin 2.1 Swift Export boundaries. Cross-runtime strong references form uncollectible islands because neither Swift ARC nor Kotlin GC can traverse the foreign runtime heap. Mandates unidirectional event streaming and explicit RAII cancellation tokens over bidirectional callback or delegate retention. 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 Between Swift ARC and Kotlin/Native Tracing Garbage Collector) 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