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

Kotlin Multiplatform Swift-Export Safe Concurrency Memory Invariants

Enforces strict memory isolation, reference cycle avoidance, and thread-safe boundaries between Kotlin/Native runtime and Swift 6 structured concurrency. Prevents deadlocks, uncollected native references, and race conditions resulting from improper coroutine-to-async bridging and shared mutable state across FFI boundaries.

Prohibited Anti-Pattern: Unchecked Shared Mutable State and Leaked Kotlin Coroutine Job Handles Across Swift 6 Concurrency Domains

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Swift-Export Safe Concurrency Memory Invariants - Enforces strict memory isolation, reference cycle avoidance, and thread-safe boundaries between Kotlin/Native runtime and Swift 6 structured concurrency. Prevents deadlocks, uncollected native references, and race conditions resulting from improper coroutine-to-async bridging and shared mutable state across FFI boundaries.
globs: shared/src/iosMain/**/*.kt, shared/src/commonMain/**/*.kt, iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-export-safe-concurrency-invariants"
---

# Kotlin Multiplatform Swift-Export Safe Concurrency Memory Invariants

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unchecked Shared Mutable State and Leaked Kotlin Coroutine Job Handles Across Swift 6 Concurrency Domains

## System Constraints
You are a Principal Engineer enforcing Kotlin Multiplatform Swift-Export Safe Concurrency Memory Invariants. Mandate strict boundary verification across Kotlin/Native and Swift 6 runtimes, forbidding unconstrained shared mutable state, raw completion-handler bridging without Task cancellation propagation, and circular strong references between Kotlin Coroutine scopes and Swift reference types.

## Strict Guidelines
- Engineers MUST ALWAYS expose immutable, frozen value types or Sendable data structures across the Kotlin-Swift boundary rather than mutable stateful classes.
- Engineers MUST ALWAYS bridge Kotlin Flows to Swift AsyncSequence using explicit cancellation tokens that bind the Swift Task lifecycle directly to the underlying Kotlin Job.
- Engineers MUST NOT pass Swift non-Sendable class references into long-running Kotlin coroutine dispatchers or callbacks.
- Code SHOULD wrap exported Kotlin async interfaces with Swift @MainActor or custom Actor isolation at the Swift ingestion boundary to satisfy Swift 6 complete concurrency checking.
- Services MUST ensure Kotlin Native StableRef pointers and GC roots are explicitly disposed of when bridging raw callbacks, avoiding permanent leaks in the Native runtime.
- Components NEVER bridge Kotlin StateFlow to Swift UI without a deterministic lifecycle-aware unsubscriber mechanism to break retain cycles across the Objective-C/Swift bridge.

## Bad vs Good Implementations
### Bridging Kotlin Flow to Swift AsyncSequence with Deterministic Task Cancellation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using raw closure-based watch/collect callbacks across the bridge creates unmanaged Kotlin native GC roots. When Swift views dismiss, the Kotlin Flow collection continues in the background, consuming CPU and causing memory leaks.
```swift
// Swift 6 Anti-Pattern: Flow collection without Task cancellation binding causes Kotlin Job leaks
import SharedKit

@MainActor
final class ProfileViewModel: ObservableObject {
    @Published private(set) var state: ProfileState = .initial
    private let repository: ProfileRepository

    init(repository: ProfileRepository) {
        self.repository = repository
    }

    func observeUpdates() {
        // Leaks Kotlin Coroutine Job when view model deinitializes or Task is cancelled
        repository.profileFlow.watch { [weak self] newState in
            Task { @MainActor in
                self?.state = newState
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The AsyncStream termination handler guarantees that cancelling the Swift Task explicitly triggers Kotlin's Job.cancel(), terminating the coroutine, reclaiming Kotlin GC roots, and respecting Swift 6 actor boundaries.
```swift
// Production Invariant: Swift 6 AsyncStream with bounded Task cancellation and Sendable safety
import SharedKit

@MainActor
final class ProfileViewModel: ObservableObject {
    @Published private(set) var state: ProfileState = .initial
    private let repository: ProfileRepository
    private var observationTask: Task<Void, Never>?

    init(repository: ProfileRepository) {
        self.repository = repository
    }

    func startObserving() {
        observationTask?.cancel()
        observationTask = Task { [weak self, repository] in
            let stream = AsyncStream<ProfileState> { continuation in
                let job = repository.collectProfileStream(
                    onEach: { state in continuation.yield(state) },
                    onCompletion: { continuation.finish() }
                )
                continuation.onTermination = { @Sendable _ in
                    job.cancel()
                }
            }
            for await newState in stream {
                guard !Task.isCancelled else { break }
                self?.state = newState
            }
        }
    }

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

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kotlin Multiplatform Swift-Export Safe Concurrency Memory Invariants

Kotlin Multiplatform Swift-Export Safe Concurrency Memory Invariants defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory isolation, reference cycle avoidance, and thread-safe boundaries between Kotlin/Native runtime and Swift 6 structured concurrency. Prevents deadlocks, uncollected native references, and race conditions resulting from improper coroutine-to-async bridging and shared mutable state across FFI boundaries. 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: Unchecked Shared Mutable State and Leaked Kotlin Coroutine Job Handles Across Swift 6 Concurrency Domains 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 DriftUnchecked Shared Mutable State and Leaked Kotlin Coroutine Job Handles Across Swift 6 Concurrency DomainsCritical
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 expose immutable, frozen value types or Sendable data structures across the Kotlin-Swift boundary rather than mutable stateful classes.

Engineers MUST ALWAYS expose immutable, frozen value types or Sendable data structures across the Kotlin-Swift boundary rather than mutable stateful classes.

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 bridge Kotlin Flows to Swift AsyncSequence using explicit cancellation tokens that bind the Swift Task lifecycle directly to the underlying Kotlin Job.

Engineers MUST ALWAYS bridge Kotlin Flows to Swift AsyncSequence using explicit cancellation tokens that bind the Swift Task lifecycle directly to the underlying Kotlin Job.

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 pass Swift non-Sendable class references into long-running Kotlin coroutine dispatchers or callbacks.

Engineers MUST NOT pass Swift non-Sendable class references into long-running Kotlin coroutine dispatchers or callbacks.

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 wrap exported Kotlin async interfaces with Swift @MainActor or custom Actor isolation at the Swift ingestion boundary to satisfy Swift 6 complete concurrency checking.

Code SHOULD wrap exported Kotlin async interfaces with Swift @MainActor or custom Actor isolation at the Swift ingestion boundary to satisfy Swift 6 complete concurrency checking.

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 ensure Kotlin Native StableRef pointers and GC roots are explicitly disposed of when bridging raw callbacks, avoiding permanent leaks in the Native runtime.

Services MUST ensure Kotlin Native StableRef pointers and GC roots are explicitly disposed of when bridging raw callbacks, avoiding permanent leaks in the Native runtime.

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 bridge Kotlin StateFlow to Swift UI without a deterministic lifecycle-aware unsubscriber mechanism to break retain cycles across the Objective-C/Swift bridge.

Components NEVER bridge Kotlin StateFlow to Swift UI without a deterministic lifecycle-aware unsubscriber mechanism to break retain cycles across the Objective-C/Swift bridge.

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 Safe Concurrency Memory Invariants critical for AI coding assistants?

Enforces strict memory isolation, reference cycle avoidance, and thread-safe boundaries between Kotlin/Native runtime and Swift 6 structured concurrency. Prevents deadlocks, uncollected native references, and race conditions resulting from improper coroutine-to-async bridging and shared mutable state across FFI boundaries. 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 (Unchecked Shared Mutable State and Leaked Kotlin Coroutine Job Handles Across Swift 6 Concurrency Domains) 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