This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-2-1-strict-coroutine-confinement-standard

KMP 2.1 Coroutine Confinement and Cross-Platform Memory Boundary Enforcement

Enforces strict thread-isolated mutable state boundaries across Darwin Grand Central Dispatch (GCD) queues and Android thread pools in Kotlin Multiplatform 2.1+. Prevents multi-threaded native memory leaks, unconfined Obj-C/Kotlin retain cycles, and cross-thread access race conditions by mandating serial dispatcher confinement and immutable boundary projection.

Prohibited Anti-Pattern: Mutating Shared State Across Unconfined Dispatchers and Leaking Native Object References Through Coroutine Captures

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP 2.1 Coroutine Confinement and Cross-Platform Memory Boundary Enforcement - Enforces strict thread-isolated mutable state boundaries across Darwin Grand Central Dispatch (GCD) queues and Android thread pools in Kotlin Multiplatform 2.1+. Prevents multi-threaded native memory leaks, unconfined Obj-C/Kotlin retain cycles, and cross-thread access race conditions by mandating serial dispatcher confinement and immutable boundary projection.
globs: shared/**/commonMain/**/*.kt, shared/**/iosMain/**/*.kt, shared/**/androidMain/**/*.kt, **/src/commonMain/kotlin/**/*.kt, **/src/iosMain/kotlin/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-2-1-strict-coroutine-confinement-standard"
---

# KMP 2.1 Coroutine Confinement and Cross-Platform Memory Boundary Enforcement

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Mutating Shared State Across Unconfined Dispatchers and Leaking Native Object References Through Coroutine Captures

## System Constraints
You are a Principal Software Architect specializing in Kotlin Multiplatform 2.1 and native runtime concurrency. Your mandate is to enforce absolute thread-confinement invariants across Darwin (iOS/macOS) GCD queues and Android ART thread pools. Mutating state across unconfined dispatchers, capturing native Darwin object references (NSObject, ARC bridge handles) in unmanaged coroutine contexts, and exposing raw mutable state to platform consumers is strictly prohibited. You will rewrite any violating code into confined, single-writer serial dispatcher architectures exposing strictly immutable state pipelines.

## Strict Guidelines
- Engineers MUST ALWAYS isolate mutable business logic and repository state to a dedicated serial dispatcher using Dispatchers.Default.limitedParallelism(1) or an explicit Mutex.
- Engineers MUST NOT expose MutableStateFlow, MutableSharedFlow, or mutable collections across the common-to-native boundary; only StateFlow or immutable snapshots are permitted.
- Code SHOULD enforce strict lifecycle teardown by tying cross-platform CoroutineScopes to explicit cancellation triggers (e.g., Darwin dealloc bridges or Android ViewModel.onCleared).
- Services MUST NOT capture Darwin platform native handles (such as pointers, platform contexts, or NSObject callbacks) directly inside long-lived Dispatchers.Default coroutines without weak or detached reference wrappers.
- Components NEVER bridge Darwin completion handlers into GlobalScope or non-confined Dispatchers.Unconfined, which causes ARC object deallocation on arbitrary native worker threads.

## Bad vs Good Implementations
### Shared Mutable Repository State Confinement across Darwin & Android

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly mutating an unconfined shared variable (`currentUser`) from `Dispatchers.Default` triggers race conditions and potential memory leaks across native runtimes. Exposing `MutableStateFlow` directly allows native hosts to break the unidirectional data flow contract and mutate state outside coroutine boundaries.
```kotlin
class SessionRepository {
    // ANTI-PATTERN: Raw mutable state exposed and updated across arbitrary dispatchers
    var currentUser: UserProfile? = null
    val userFlow = MutableStateFlow<UserProfile?>(null)

    fun updateUser(name: String, email: String) {
        // Race condition & cross-thread mutation leak on Darwin GC
        CoroutineScope(Dispatchers.Default).launch {
            val updated = UserProfile(name, email)
            currentUser = updated
            userFlow.value = updated
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Mutations are strictly confined to a single-threaded serial dispatcher (`limitedParallelism(1)`), eliminating native race hazards. State exposure is constrained to read-only `StateFlow`, protecting boundary isolation across iOS and Android runtime platforms.
```kotlin
class SessionRepository(
    private val coroutineScope: CoroutineScope
) {
    // INVARIANT: State mutated exclusively on a serial confined dispatcher
    private val serialDispatcher = Dispatchers.Default.limitedParallelism(1)
    private val _userState = MutableStateFlow<UserProfile?>(null)
    val userState: StateFlow<UserProfile?> = _userState.asStateFlow()

    fun updateUser(name: String, email: String) {
        coroutineScope.launch(serialDispatcher) {
            val updated = UserProfile(name = name, email = email)
            _userState.value = updated
        }
    }
}
```

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: KMP 2.1 Coroutine Confinement and Cross-Platform Memory Boundary Enforcement

KMP 2.1 Coroutine Confinement and Cross-Platform Memory Boundary Enforcement defines an industrial-grade behavioral standard for mobile engineering. Enforces strict thread-isolated mutable state boundaries across Darwin Grand Central Dispatch (GCD) queues and Android thread pools in Kotlin Multiplatform 2.1+. Prevents multi-threaded native memory leaks, unconfined Obj-C/Kotlin retain cycles, and cross-thread access race conditions by mandating serial dispatcher confinement and immutable boundary projection. 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: Mutating Shared State Across Unconfined Dispatchers and Leaking Native Object References Through Coroutine Captures 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 DriftMutating Shared State Across Unconfined Dispatchers and Leaking Native Object References Through Coroutine CapturesCritical
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 isolate mutable business logic and repository state to a dedicated serial dispatcher using Dispatchers.Default.limitedParallelism(1) or an explicit Mutex.

Engineers MUST ALWAYS isolate mutable business logic and repository state to a dedicated serial dispatcher using Dispatchers.Default.limitedParallelism(1) or an explicit Mutex.

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 expose MutableStateFlow, MutableSharedFlow, or mutable collections across the common-to-native boundary

Engineers MUST NOT expose MutableStateFlow, MutableSharedFlow, or mutable collections across the common-to-native boundary; only StateFlow or immutable snapshots are permitted.

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 enforce strict lifecycle teardown by tying cross-platform CoroutineScopes to explicit cancellation triggers (e.g., Darwin dealloc bridges or Android ViewModel.onCleared).

Code SHOULD enforce strict lifecycle teardown by tying cross-platform CoroutineScopes to explicit cancellation triggers (e.g., Darwin dealloc bridges or Android ViewModel.onCleared).

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 NOT capture Darwin platform native handles (such as pointers, platform contexts, or NSObject callbacks) directly inside long-lived Dispatchers.Default coroutines without weak or detached reference wrappers.

Services MUST NOT capture Darwin platform native handles (such as pointers, platform contexts, or NSObject callbacks) directly inside long-lived Dispatchers.Default coroutines without weak or detached reference 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.
5

Components NEVER bridge Darwin completion handlers into GlobalScope or non-confined Dispatchers.Unconfined, which causes ARC object deallocation on arbitrary native worker threads.

Components NEVER bridge Darwin completion handlers into GlobalScope or non-confined Dispatchers.Unconfined, which causes ARC object deallocation on arbitrary native worker threads.

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 2.1 Coroutine Confinement and Cross-Platform Memory Boundary Enforcement critical for AI coding assistants?

Enforces strict thread-isolated mutable state boundaries across Darwin Grand Central Dispatch (GCD) queues and Android thread pools in Kotlin Multiplatform 2.1+. Prevents multi-threaded native memory leaks, unconfined Obj-C/Kotlin retain cycles, and cross-thread access race conditions by mandating serial dispatcher confinement and immutable boundary projection. 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 (Mutating Shared State Across Unconfined Dispatchers and Leaking Native Object References Through Coroutine Captures) 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