This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-atomic-statemachine-dispatcher-boundary

Kotlin Multiplatform 2.1 Atomic State Machine & Darwin/Android Dispatcher Boundary

Enforces strict confinement of state machine mutative transitions to dedicated single-threaded dispatcher boundaries while using atomic primitives and immutable snapshots across Android ART and Apple Darwin GCD runtimes. Precludes invalid memory access, cross-thread mutation crashes (SIGSEGV/IllegalState), and coroutine deadlocks when synchronizing offline-first persistent states across platform boundaries in Kotlin Multiplatform 2.1.

Prohibited Anti-Pattern: Unconfined MutableStateFlow Mutations Across Native GCD Worker Threads and ART Thread Pools

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform 2.1 Atomic State Machine & Darwin/Android Dispatcher Boundary - Enforces strict confinement of state machine mutative transitions to dedicated single-threaded dispatcher boundaries while using atomic primitives and immutable snapshots across Android ART and Apple Darwin GCD runtimes. Precludes invalid memory access, cross-thread mutation crashes (SIGSEGV/IllegalState), and coroutine deadlocks when synchronizing offline-first persistent states across platform boundaries in Kotlin Multiplatform 2.1.
globs: **/commonMain/**/*.kt, **/iosMain/**/*.kt, **/androidMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-atomic-statemachine-dispatcher-boundary"
---

# Kotlin Multiplatform 2.1 Atomic State Machine & Darwin/Android Dispatcher Boundary

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unconfined MutableStateFlow Mutations Across Native GCD Worker Threads and ART Thread Pools

## System Constraints
You are a Principal Mobile Architect enforcing absolute thread safety, immutable state isolation, and strict coroutine dispatcher boundaries in Kotlin Multiplatform 2.1 projects bridging Darwin GCD and Android ART.

## Strict Guidelines
- Engineers MUST ALWAYS isolate state transitions inside a single-threaded linearized actor or dedicated single-threaded CoroutineDispatcher (`newSingleThreadContext` or serial `CoroutineScope`) to guarantee sequential consistency across platforms.
- Engineers MUST NOT expose `MutableStateFlow` directly across public architectural boundaries; exposure MUST be strictly as read-only `StateFlow<T>` yielding deeply immutable data classes.
- State data models MUST be pure Kotlin immutable data classes where all nested members are declared with `val` and use persistent collections (e.g., `kotlinx.collections.immutable`) instead of standard mutable collections.
- Darwin interoperability code MUST ALWAYS observe state streams via a designated `MainCoroutineDispatcher` or platform-safe adapter that bridges Darwin's `dispatch_queue_main_t` without capturing mutable state across GCD concurrent queues.
- Engineers MUST NEVER execute database I/O, heavy disk persistence, or network synchronization on the state machine's serial transition dispatcher; offload strictly via `withContext(Dispatchers.IO)`.
- Mutations to atomic flags and references MUST use `kotlinx.atomicfu.atomic` or `kotlin.concurrent.AtomicReference` with thread-safe compare-and-swap (CAS) loops when outside coroutine contexts.

## Bad vs Good Implementations
### State Machine Thread-Boundary Violation vs. Serialized Confined Reducer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Mutating internal fields of an existing instance and writing back to an exposed MutableStateFlow concurrently across Dispatchers.Default leads to lost updates, torn reads on Darwin, and cross-thread mutation hazards across ART and GCD workers.
```kotlin
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

data class SyncState(var isSyncing: Boolean = false, var count: Int = 0)

// Anti-pattern: Exposed mutable state flow and unconfined concurrent updates
class BadOfflineSyncEngine(private val scope: CoroutineScope) {
    // VIOLATION: Mutable state exposed; mutable data class properties
    val state = MutableStateFlow(SyncState())

    // VIOLATION: Called directly from Darwin GCD queue or Android background thread concurrently
    fun onEventReceived(delta: Int) {
        scope.launch(Dispatchers.Default) {
            // Race condition: In-place mutation and non-atomic read-modify-write across threads
            val current = state.value
            current.count += delta
            current.isSyncing = true
            state.value = current // Misses concurrent updates; leads to torn state
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: All state transitions are strictly serialized using `limitedParallelism(1)` and an unbuffered/unlimited channel actor. State data classes are immutable with persistent collections, and I/O work is strictly offloaded using `withContext(Dispatchers.IO)`, preventing any Darwin/ART thread affinity crashes.
```kotlin
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.persistentListOf

// Invariant: Deeply immutable state value object
@kotlin.jvm.JvmImmutable
data class OfflineState(
    val isSyncing: Boolean = false,
    val pendingMutations: PersistentList<String> = persistentListOf(),
    val failureCount: Int = 0
)

sealed interface StateIntent {
    data class QueueSync(val payloadId: String) : StateIntent
    data class CompleteSync(val payloadId: String) : StateIntent
    data class FailSync(val cause: Throwable) : StateIntent
}

class AtomicOfflineSyncEngine(
    // Confined single-threaded dispatcher guaranteeing absolute serial execution
    private val serialDispatcher: kotlinx.coroutines.CoroutineDispatcher = Dispatchers.Default.limitedParallelism(1)
) {
    private val engineScope = CoroutineScope(SupervisorJob() + serialDispatcher)
    private val intentChannel = Channel<StateIntent>(Channel.UNLIMITED)

    private val _state = MutableStateFlow(OfflineState())
    val state: StateFlow<OfflineState> = _state.asStateFlow()

    init {
        engineScope.launch {
            intentChannel.receiveAsFlow().collect { intent ->
                reduce(intent)
            }
        }
    }

    fun dispatch(intent: StateIntent) {
        // Thread-safe channel send from any runtime thread (Darwin GCD or ART)
        intentChannel.trySend(intent)
    }

    private suspend fun reduce(intent: StateIntent) {
        val current = _state.value
        when (intent) {
            is StateIntent.QueueSync -> {
                _state.value = current.copy(
                    isSyncing = true,
                    pendingMutations = current.pendingMutations.add(intent.payloadId)
                )
                persistStateOnIoDispatcher(_state.value)
            }
            is StateIntent.CompleteSync -> {
                _state.value = current.copy(
                    isSyncing = current.pendingMutations.size > 1,
                    pendingMutations = current.pendingMutations.remove(intent.payloadId)
                )
            }
            is StateIntent.FailSync -> {
                _state.value = current.copy(
                    isSyncing = false,
                    failureCount = current.failureCount + 1
                )
            }
        }
    }

    private suspend fun persistStateOnIoDispatcher(snapshot: OfflineState) {
        withContext(Dispatchers.IO) {
            // Safe disk persistence off the state machine thread
        }
    }
}
```

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 Atomic State Machine & Darwin/Android Dispatcher Boundary

Kotlin Multiplatform 2.1 Atomic State Machine & Darwin/Android Dispatcher Boundary defines an industrial-grade behavioral standard for mobile engineering. Enforces strict confinement of state machine mutative transitions to dedicated single-threaded dispatcher boundaries while using atomic primitives and immutable snapshots across Android ART and Apple Darwin GCD runtimes. Precludes invalid memory access, cross-thread mutation crashes (SIGSEGV/IllegalState), and coroutine deadlocks when synchronizing offline-first persistent states across platform boundaries in Kotlin Multiplatform 2.1. 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: Unconfined MutableStateFlow Mutations Across Native GCD Worker Threads and ART Thread Pools 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 DriftUnconfined MutableStateFlow Mutations Across Native GCD Worker Threads and ART Thread PoolsCritical
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 state transitions inside a single-threaded linearized actor or dedicated single-threaded CoroutineDispatcher (`newSingleThreadContext` or serial `CoroutineScope`) to guarantee sequential consistency across platforms.

Engineers MUST ALWAYS isolate state transitions inside a single-threaded linearized actor or dedicated single-threaded CoroutineDispatcher (`newSingleThreadContext` or serial `CoroutineScope`) to guarantee sequential consistency across platforms.

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` directly across public architectural boundaries

Engineers MUST NOT expose `MutableStateFlow` directly across public architectural boundaries; exposure MUST be strictly as read-only `StateFlow<T>` yielding deeply immutable data 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.
3

State data models MUST be pure Kotlin immutable data classes where all nested members are declared with `val` and use persistent collections (e.g., `kotlinx.collections.immutable`) instead of standard mutable collections.

State data models MUST be pure Kotlin immutable data classes where all nested members are declared with `val` and use persistent collections (e.g., `kotlinx.collections.immutable`) instead of standard mutable collections.

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

Darwin interoperability code MUST ALWAYS observe state streams via a designated `MainCoroutineDispatcher` or platform-safe adapter that bridges Darwin's `dispatch_queue_main_t` without capturing mutable state across GCD concurrent queues.

Darwin interoperability code MUST ALWAYS observe state streams via a designated `MainCoroutineDispatcher` or platform-safe adapter that bridges Darwin's `dispatch_queue_main_t` without capturing mutable state across GCD concurrent queues.

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

Engineers MUST NEVER execute database I/O, heavy disk persistence, or network synchronization on the state machine's serial transition dispatcher

Engineers MUST NEVER execute database I/O, heavy disk persistence, or network synchronization on the state machine's serial transition dispatcher; offload strictly via `withContext(Dispatchers.IO)`.

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

Mutations to atomic flags and references MUST use `kotlinx.atomicfu.atomic` or `kotlin.concurrent.AtomicReference` with thread-safe compare-and-swap (CAS) loops when outside coroutine contexts.

Mutations to atomic flags and references MUST use `kotlinx.atomicfu.atomic` or `kotlin.concurrent.AtomicReference` with thread-safe compare-and-swap (CAS) loops when outside coroutine contexts.

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 Atomic State Machine & Darwin/Android Dispatcher Boundary critical for AI coding assistants?

Enforces strict confinement of state machine mutative transitions to dedicated single-threaded dispatcher boundaries while using atomic primitives and immutable snapshots across Android ART and Apple Darwin GCD runtimes. Precludes invalid memory access, cross-thread mutation crashes (SIGSEGV/IllegalState), and coroutine deadlocks when synchronizing offline-first persistent states across platform boundaries in Kotlin Multiplatform 2.1. 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 (Unconfined MutableStateFlow Mutations Across Native GCD Worker Threads and ART Thread Pools) 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