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

KMP Atomic StateFlow and Swift Concurrency Confinement Guardrail

Enforces strict unidirectional data flow, bidirectional immutability, and thread confinement across Kotlin Multiplatform and Swift Concurrency boundary. Guarantees that StateFlow emissions are observed under MainActor isolation on Darwin while mutations within Kotlin Common code use atomic state updates, preventing torn reads and native runtime crashes.

Prohibited Anti-Pattern: Exposing Unconfined MutableStateFlow Across the KMP Boundary Leading to Swift Data Races and Undefined State

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Atomic StateFlow and Swift Concurrency Confinement Guardrail - Enforces strict unidirectional data flow, bidirectional immutability, and thread confinement across Kotlin Multiplatform and Swift Concurrency boundary. Guarantees that StateFlow emissions are observed under MainActor isolation on Darwin while mutations within Kotlin Common code use atomic state updates, preventing torn reads and native runtime crashes.
globs: **/*.kt, **/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-atomic-stateflow-concurrency-confinement"
---

# KMP Atomic StateFlow and Swift Concurrency Confinement Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exposing Unconfined MutableStateFlow Across the KMP Boundary Leading to Swift Data Races and Undefined State

## System Constraints
You are a Principal Mobile Architect enforcing the Kotlin Multiplatform Atomic StateFlow Concurrency Confinement Standard. You must block any code that leaks mutable state flows across module boundaries, directly mutates StateFlow values without atomic operators, uses mutable collection types in cross-platform state models, or consumes Kotlin asynchronous streams in Swift outside of @MainActor confinement.

## Strict Guidelines
- Engineers MUST ALWAYS expose public state as read-only StateFlow<T> using .asStateFlow() and retain backing storage in private MutableStateFlow<T>.
- Engineers MUST ALWAYS mutate StateFlow values using atomic update loops (_state.update { current -> ... }) rather than direct property assignment (_state.value = ...).
- Engineers MUST NOT expose mutable collections (e.g., ArrayList, MutableMap, Array) inside StateFlow state classes; state schemas MUST be deeply immutable data classes using kotlinx.collections.immutable or read-only List/Set/Map interfaces.
- Code bridging KMP flows to Darwin platforms MUST enforce @MainActor isolation at the Swift observation call site to guarantee safe UI rendering and prevent thread hopping violations.
- ViewModels in Common code MUST launch state mutations within a strictly confined CoroutineScope utilizing a deterministic Dispatcher (e.g., Dispatchers.Main.immediate for UI states) and non-cancellable atomic critical sections when modifying persistent stores.

## Bad vs Good Implementations
### StateFlow Exposure and Mutation Confinement in KMP

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly exposing MutableStateFlow permits external modifications from both Kotlin and Swift layers. Assigning uiState.value directly introduces race conditions where concurrent updates overwrite each other. Using a mutable ArrayList inside the data class breaks cross-runtime immutability guarantees.
```kotlin
class UserProfileViewModel : ViewModel() {
    // ANTI-PATTERN: Leaking MutableStateFlow directly to callers
    val uiState = MutableStateFlow(UserProfileState())

    fun updateUser(name: String, email: String) {
        // ANTI-PATTERN: Non-atomic property assignment prone to lost updates under race conditions
        uiState.value = uiState.value.copy(
            name = name,
            email = email,
            // ANTI-PATTERN: Mutable collection exposed in state
            tags = uiState.value.tags.apply { add("updated") }
        )
    }
}

data class UserProfileState(
    var name: String = "",
    var email: String = "",
    val tags: ArrayList<String> = ArrayList()
)
```

#### Production Standard (Correct)
> **Standard**: The backing state is isolated via private MutableStateFlow and exposed solely as read-only StateFlow. Updates use the thread-safe atomic CAS .update operator, and the state model relies on persistent, immutable collections that cannot mutate across runtime dispatchers.
```kotlin
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.persistentListOf

class UserProfileViewModel : ViewModel() {
    private val _uiState = MutableStateFlow(UserProfileState())
    // Confinement: Expose strictly read-only StateFlow to clients (Android & Swift)
    val uiState: StateFlow<UserProfileState> = _uiState.asStateFlow()

    fun updateUser(name: String, email: String) {
        // Invariant: Atomic CAS loop via update prevents lost updates
        _uiState.update { current ->
            current.copy(
                name = name,
                email = email,
                tags = current.tags.add("updated")
            )
        }
    }
}

// Invariant: Value-typed, deeply immutable data structure
data class UserProfileState(
    val name: String = "",
    val email: String = "",
    val tags: ImmutableList<String> = persistentListOf()
)
```

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 Atomic StateFlow and Swift Concurrency Confinement Guardrail

KMP Atomic StateFlow and Swift Concurrency Confinement Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict unidirectional data flow, bidirectional immutability, and thread confinement across Kotlin Multiplatform and Swift Concurrency boundary. Guarantees that StateFlow emissions are observed under MainActor isolation on Darwin while mutations within Kotlin Common code use atomic state updates, preventing torn reads and native runtime crashes. 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: Exposing Unconfined MutableStateFlow Across the KMP Boundary Leading to Swift Data Races and Undefined State 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 DriftExposing Unconfined MutableStateFlow Across the KMP Boundary Leading to Swift Data Races and Undefined StateCritical
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 public state as read-only StateFlow<T> using .asStateFlow() and retain backing storage in private MutableStateFlow<T>.

Engineers MUST ALWAYS expose public state as read-only StateFlow<T> using .asStateFlow() and retain backing storage in private MutableStateFlow<T>.

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 mutate StateFlow values using atomic update loops (_state.update { current -> ... }) rather than direct property assignment (_state.value = ...).

Engineers MUST ALWAYS mutate StateFlow values using atomic update loops (_state.update { current -> ... }) rather than direct property assignment (_state.value = ...).

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 expose mutable collections (e.g., ArrayList, MutableMap, Array) inside StateFlow state classes

Engineers MUST NOT expose mutable collections (e.g., ArrayList, MutableMap, Array) inside StateFlow state classes; state schemas MUST be deeply immutable data classes using kotlinx.collections.immutable or read-only List/Set/Map interfaces.

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 bridging KMP flows to Darwin platforms MUST enforce @MainActor isolation at the Swift observation call site to guarantee safe UI rendering and prevent thread hopping violations.

Code bridging KMP flows to Darwin platforms MUST enforce @MainActor isolation at the Swift observation call site to guarantee safe UI rendering and prevent thread hopping violations.

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

ViewModels in Common code MUST launch state mutations within a strictly confined CoroutineScope utilizing a deterministic Dispatcher (e.g., Dispatchers.Main.immediate for UI states) and non-cancellable atomic critical sections when modifying persistent stores.

ViewModels in Common code MUST launch state mutations within a strictly confined CoroutineScope utilizing a deterministic Dispatcher (e.g., Dispatchers.Main.immediate for UI states) and non-cancellable atomic critical sections when modifying persistent stores.

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 Atomic StateFlow and Swift Concurrency Confinement Guardrail critical for AI coding assistants?

Enforces strict unidirectional data flow, bidirectional immutability, and thread confinement across Kotlin Multiplatform and Swift Concurrency boundary. Guarantees that StateFlow emissions are observed under MainActor isolation on Darwin while mutations within Kotlin Common code use atomic state updates, preventing torn reads and native runtime crashes. 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 (Exposing Unconfined MutableStateFlow Across the KMP Boundary Leading to Swift Data Races and Undefined State) 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