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

KMP Native Memory Isolation & Swift 6 Structured Concurrency Bridging

Governs thread-safe bidirectional state sharing and structured concurrency interop between Kotlin Coroutines and Swift 6 Sendable actors without GC pressure or main-thread hitching. Enforces SKIE/Swift-export bridging protocols, non-leaking cancellation token handlers, and immutable boundary transfer to satisfy strict Swift 6 concurrency invariants alongside Kotlin Native's Garbage Collector.

Prohibited Anti-Pattern: Bridging raw Kotlin Coroutine Flows and Shared State directly into Swift without Sendable wrappers, explicit scope lifetime management, and freeze/copy boundary invariants.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Native Memory Isolation & Swift 6 Structured Concurrency Bridging - Governs thread-safe bidirectional state sharing and structured concurrency interop between Kotlin Coroutines and Swift 6 Sendable actors without GC pressure or main-thread hitching. Enforces SKIE/Swift-export bridging protocols, non-leaking cancellation token handlers, and immutable boundary transfer to satisfy strict Swift 6 concurrency invariants alongside Kotlin Native's Garbage Collector.
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-native-memory-swift-concurrency-interop"
---

# KMP Native Memory Isolation & Swift 6 Structured Concurrency Bridging

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Bridging raw Kotlin Coroutine Flows and Shared State directly into Swift without Sendable wrappers, explicit scope lifetime management, and freeze/copy boundary invariants.

## System Constraints
You are a Principal Mobile Architect enforcing strict Kotlin Multiplatform (KMP) Native Memory Isolation and Swift 6 Concurrency interop standards. Mandate thread-safe bidirectional state sharing, zero-copy read-only boundary patterns, and structured lifetime binding between Kotlin Coroutines and Swift 6 Task/Actor systems. Never permit unmanaged Job/Task lifetimes or mutable cross-runtime object graphs.

## Strict Guidelines
- Engineers MUST ALWAYS expose Kotlin StateFlow and suspend functions to Swift via strictly typed, async-await and AsyncSequence bindings generated by tools such as SKIE or native Swift-Export.
- Engineers MUST NEVER leak references across the Kotlin-Swift runtime boundary: objects crossing the boundary MUST either be deeply immutable value types (@Immutable/Sendable) or encapsulated behind concurrency-safe thread confinements (Swift Actors or Kotlin Channels with confined dispatchers).
- Engineers MUST ALWAYS bridge Swift Task cancellation explicitly to Kotlin Coroutine Job cancellation using Swift's `withTaskCancellationHandler` to ensure native coroutines are cancelled when Swift scopes teardown.
- Code MUST avoid passing Swift closures retaining Kotlin reference-counted bridge instances back into asynchronous Kotlin background dispatchers to prevent circular GC retention and cross-runtime memory leaks.
- Services MUST ensure Kotlin Native GC runs deterministically without thread starvation by never blocking Kotlin Dispatchers.Default or Swift Cooperative Thread Pool worker threads with synchronous mutex locks crossing boundaries.

## Bad vs Good Implementations
### Swift 6 Cancellation and StateFlow Stream Consumption via AsyncSequence

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Raw callbacks retain Kotlin references, fail Swift 6 strict concurrency checks (missing Sendable and Actor isolation), and cause zombie tasks on iOS when the enclosing object deallocates without explicit `closeable.close()` execution.
```swift
import Shared

// ANTI-PATTERN: Direct subscription to Flow without cancellation lifecycle management or Sendable boundary enforcement
class UserProfileViewModel: ObservableObject {
    @Published var state: UserState? = nil
    private var closeable: KtorCloseable? = nil

    func observe(repository: UserRepository) {
        // Unstructured observation: leaks memory if view disappears, ignores Swift 6 concurrency actors
        self.closeable = repository.userFlow.watch { [weak self] state in
            DispatchQueue.main.async {
                self?.state = state
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Encapsulates state inside Swift's `@MainActor`, uses `Task` with structured cancellation, and handles boundary items via Swift AsyncSequence mapped directly to Kotlin `StateFlow`, eliminating reference leaks and GC boundary deadlocks.
```swift
import Shared

// PRODUCTION FIX: Swift 6 Actor-isolated observation bridging SKIE/AsyncSequence with Task cancellation
@MainActor
public final class UserProfileViewModel: ObservableObject {
    @Published public private(set) var state: UserState
    private var observationTask: Task<Void, Never>? = nil

    public init(initialState: UserState) {
        self.state = initialState
    }

    public func startObserving(repository: UserRepository) {
        observationTask?.cancel()
        observationTask = Task { [weak self] in
            // SKIE or custom AsyncSequence bridge maintaining structured cancellation
            for await updatedState in repository.userFlow {
                guard !Task.isCancelled else { break }
                self?.state = updatedState
            }
        }
    }

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

### Kotlin Native Coroutine Job Bridging to Swift Task Completion

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Spawns an unmanaged coroutine scope without cancellation propagation; invoking raw Swift callbacks directly from background Kotlin dispatchers violates Swift 6 Actor isolation and causes undefined thread jumps.
```kotlin
// ANTI-PATTERN: Leaking suspend function bridge without Job cancellation hook across Objective-C interop
package com.example.shared

import kotlinx.coroutines.*

class DataBridge {
    private val scope = CoroutineScope(Dispatchers.Default)

    fun fetchDataAsync(callback: (String) -> Unit) {
        scope.launch {
            val data = performLongRunningWork()
            callback(data) // Runs on Kotlin Dispatcher, invokes unisolated Swift pointer
        }
    }

    private suspend fun performLongRunningWork(): String = "payload"
}
```

#### Production Standard (Correct)
> **Standard**: Provides direct `suspend` hooks compatible with Swift async/await (or SKIE bridging), guarantees Main dispatcher callback boundaries, and returns a cancellation handle to bridge `withTaskCancellationHandler` on the Swift layer.
```kotlin
// PRODUCTION FIX: Structured Suspend Bridge with Cancellation Token Support
package com.example.shared

import kotlinx.coroutines.*

class DataBridge {
    private val supervisorScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)

    @Throws(CancellationException::class, Exception::class)
    suspend fun fetchData(): String = withContext(Dispatchers.Default) {
        performLongRunningWork()
    }

    // Exposed bridge helper for native targets lacking direct suspend codegen
    fun fetchDataCancellable(
        onSuccess: (String) -> Unit,
        onError: (Throwable) -> Unit
    ): () -> Unit {
        val job = supervisorScope.launch {
            try {
                val result = performLongRunningWork()
                withContext(Dispatchers.Main) { onSuccess(result) }
            } catch (e: CancellationException) {
                // Structured cooperative cancellation
            } catch (t: Throwable) {
                withContext(Dispatchers.Main) { onError(t) }
            }
        }
        return { job.cancel() }
    }

    private suspend fun performLongRunningWork(): String = "payload"
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP Native Memory Isolation & Swift 6 Structured Concurrency Bridging

KMP Native Memory Isolation & Swift 6 Structured Concurrency Bridging defines an industrial-grade behavioral standard for mobile engineering. Governs thread-safe bidirectional state sharing and structured concurrency interop between Kotlin Coroutines and Swift 6 Sendable actors without GC pressure or main-thread hitching. Enforces SKIE/Swift-export bridging protocols, non-leaking cancellation token handlers, and immutable boundary transfer to satisfy strict Swift 6 concurrency invariants alongside Kotlin Native's Garbage Collector. 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: Bridging raw Kotlin Coroutine Flows and Shared State directly into Swift without Sendable wrappers, explicit scope lifetime management, and freeze/copy boundary invariants. 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 DriftBridging raw Kotlin Coroutine Flows and Shared State directly into Swift without Sendable wrappers, explicit scope lifetime management, and freeze/copy boundary invariants.Critical
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 Kotlin StateFlow and suspend functions to Swift via strictly typed, async-await and AsyncSequence bindings generated by tools such as SKIE or native Swift-Export.

Engineers MUST ALWAYS expose Kotlin StateFlow and suspend functions to Swift via strictly typed, async-await and AsyncSequence bindings generated by tools such as SKIE or native Swift-Export.

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 NEVER leak references across the Kotlin-Swift runtime boundary

Engineers MUST NEVER leak references across the Kotlin-Swift runtime boundary: objects crossing the boundary MUST either be deeply immutable value types (@Immutable/Sendable) or encapsulated behind concurrency-safe thread confinements (Swift Actors or Kotlin Channels with confined dispatchers).

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 ALWAYS bridge Swift Task cancellation explicitly to Kotlin Coroutine Job cancellation using Swift's `withTaskCancellationHandler` to ensure native coroutines are cancelled when Swift scopes teardown.

Engineers MUST ALWAYS bridge Swift Task cancellation explicitly to Kotlin Coroutine Job cancellation using Swift's `withTaskCancellationHandler` to ensure native coroutines are cancelled when Swift scopes 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.
4

Code MUST avoid passing Swift closures retaining Kotlin reference-counted bridge instances back into asynchronous Kotlin background dispatchers to prevent circular GC retention and cross-runtime memory leaks.

Code MUST avoid passing Swift closures retaining Kotlin reference-counted bridge instances back into asynchronous Kotlin background dispatchers to prevent circular GC retention and cross-runtime memory leaks.

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 GC runs deterministically without thread starvation by never blocking Kotlin Dispatchers.Default or Swift Cooperative Thread Pool worker threads with synchronous mutex locks crossing boundaries.

Services MUST ensure Kotlin Native GC runs deterministically without thread starvation by never blocking Kotlin Dispatchers.Default or Swift Cooperative Thread Pool worker threads with synchronous mutex locks crossing 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is KMP Native Memory Isolation & Swift 6 Structured Concurrency Bridging critical for AI coding assistants?

Governs thread-safe bidirectional state sharing and structured concurrency interop between Kotlin Coroutines and Swift 6 Sendable actors without GC pressure or main-thread hitching. Enforces SKIE/Swift-export bridging protocols, non-leaking cancellation token handlers, and immutable boundary transfer to satisfy strict Swift 6 concurrency invariants alongside Kotlin Native's Garbage Collector. 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 (Bridging raw Kotlin Coroutine Flows and Shared State directly into Swift without Sendable wrappers, explicit scope lifetime management, and freeze/copy boundary invariants.) 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

KMP