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

KMP Native Concurrent StateFlow Atomic Mutation Barrier Standard

Enforces thread-safe, atomic mutations and cross-runtime boundary encapsulation for Kotlin Multiplatform StateFlow pipelines consumed by Swift. Precludes memory tearing, race-conditioned telemetry drops, and legacy thread-state freezing crashes during high-throughput concurrent ingress across Darwin GCD queues and Kotlin Native worker dispatchers.

Prohibited Anti-Pattern: Unprotected mutable StateFlow reference exposure and non-atomic field assignments across Darwin-K/N thread boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Native Concurrent StateFlow Atomic Mutation Barrier Standard - Enforces thread-safe, atomic mutations and cross-runtime boundary encapsulation for Kotlin Multiplatform StateFlow pipelines consumed by Swift. Precludes memory tearing, race-conditioned telemetry drops, and legacy thread-state freezing crashes during high-throughput concurrent ingress across Darwin GCD queues and Kotlin Native worker dispatchers.
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-concurrent-stateflow-atomic-barrier"
---

# KMP Native Concurrent StateFlow Atomic Mutation Barrier Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unprotected mutable StateFlow reference exposure and non-atomic field assignments across Darwin-K/N thread boundaries

## System Constraints
You are a Principal Mobile Architect enforcing strict concurrency invariants in Kotlin Multiplatform (KMP) targeting Darwin/Swift runtimes. You must prevent thread-state hazards, unsynchronized mutations of shared state flows, and re-entrancy deadlocks across the Objective-C/Swift interop barrier. Mandate atomic mutation primitives (such as MutableStateFlow.update or Channel-driven serialization), prohibit public MutableStateFlow exposure across the interop boundary, and enforce strictly confined ingestion contexts for telemetry pipelines.

## Strict Guidelines
- Engineers MUST NEVER expose MutableStateFlow or raw mutable references across the KMP module boundary or to the Swift runtime layer; all exposed flows MUST be read-only StateFlow<T> or explicitly wrapped in an interop-safe collector.
- Engineers MUST ALWAYS perform state transitions using atomic CAS operators such as MutableStateFlow.update { ... } or updateAndGet { ... } instead of direct property assignment (state.value = newState).
- High-throughput telemetry producers MUST dispatch incoming data via a serialized Channel (with Channel.BUFFERED or Channel.CONFLATED backpressure policies) or through a CoroutineDispatcher confined with limitedParallelism(1).
- Swift consumers MUST NOT invoke synchronous mutation hooks directly on shared native singletons across asynchronous Grand Central Dispatch queues; mutations MUST traverse explicit, asynchronous shared-boundary entry points.
- Engineers MUST wrap StateFlow Darwin consumption in structured AsyncSequence or Combine publisher bridges that guarantee cooperative cancellation and prevent retain cycles across ARC and Kotlin Garbage Collector runtimes.
- Shared data models exchanged during high-throughput updates MUST be strictly immutable Kotlin data classes with val-only fields to prevent cross-heap mutation hazards.

## Bad vs Good Implementations
### High-Throughput Telemetry StateFlow Ingestion (Kotlin/Native & Swift Bridge)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly reading `telemetryState.value` and writing back `telemetryState.value = ...` is not atomic. Under high concurrency across Swift background threads, concurrent writes overwrite each other (lost updates) and expose uncommitted intermediate states. Furthermore, exposing `MutableStateFlow` directly allows external Swift consumers to dangerously mutate or reset shared state bypass validation.
```kotlin
class TelemetryRepository {
    // ANTI-PATTERN: Exposing MutableStateFlow across the public boundary
    val telemetryState = MutableStateFlow(TelemetrySnapshot())

    // ANTI-PATTERN: Non-atomic read-then-write creates data tearing
    // and lost frames when invoked concurrently from Swift background queues
    fun recordMetric(metricId: String, value: Double) {
        val current = telemetryState.value
        val updatedMap = current.metrics.toMutableMap()
        updatedMap[metricId] = value
        telemetryState.value = current.copy(metrics = updatedMap)
    }
}
```

#### Production Standard (Correct)
> **Standard**: Encapsulates `_telemetryState` as a private mutable backing property and exposes only an immutable `StateFlow`. Employs `limitedParallelism(1)` to eliminate thread contention and relies on atomic `update { ... }` ensuring Compare-And-Swap safety across Darwin and Kotlin/Native execution contexts.
```kotlin
class TelemetryRepository(
    private val ingestionScope: CoroutineScope
) {
    private val _telemetryState = MutableStateFlow(TelemetrySnapshot())
    val telemetryState: StateFlow<TelemetrySnapshot> = _telemetryState.asStateFlow()

    // Isolated dispatcher ensures serial processing without lock contention
    private val telemetryDispatcher = Dispatchers.Default.limitedParallelism(1)

    fun recordMetric(metricId: String, value: Double) {
        ingestionScope.launch(telemetryDispatcher) {
            // ATOMIC: Invariant-safe CAS update prevents lost telemetry frames
            _telemetryState.update { current ->
                current.copy(
                    metrics = current.metrics + (metricId to value),
                    lastUpdatedEpochMs = Clock.System.now().toEpochMilliseconds()
                )
            }
        }
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP Native Concurrent StateFlow Atomic Mutation Barrier Standard

KMP Native Concurrent StateFlow Atomic Mutation Barrier Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces thread-safe, atomic mutations and cross-runtime boundary encapsulation for Kotlin Multiplatform StateFlow pipelines consumed by Swift. Precludes memory tearing, race-conditioned telemetry drops, and legacy thread-state freezing crashes during high-throughput concurrent ingress across Darwin GCD queues and Kotlin Native worker dispatchers. 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: Unprotected mutable StateFlow reference exposure and non-atomic field assignments across Darwin-K/N thread boundaries 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 DriftUnprotected mutable StateFlow reference exposure and non-atomic field assignments across Darwin-K/N thread boundariesCritical
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 NEVER expose MutableStateFlow or raw mutable references across the KMP module boundary or to the Swift runtime layer

Engineers MUST NEVER expose MutableStateFlow or raw mutable references across the KMP module boundary or to the Swift runtime layer; all exposed flows MUST be read-only StateFlow<T> or explicitly wrapped in an interop-safe collector.

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 perform state transitions using atomic CAS operators such as MutableStateFlow.update { ... } or updateAndGet { ... } instead of direct property assignment (state.value = newState).

Engineers MUST ALWAYS perform state transitions using atomic CAS operators such as MutableStateFlow.update { ... } or updateAndGet { ... } instead of direct property assignment (state.value = newState).

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

High-throughput telemetry producers MUST dispatch incoming data via a serialized Channel (with Channel.BUFFERED or Channel.CONFLATED backpressure policies) or through a CoroutineDispatcher confined with limitedParallelism(1).

High-throughput telemetry producers MUST dispatch incoming data via a serialized Channel (with Channel.BUFFERED or Channel.CONFLATED backpressure policies) or through a CoroutineDispatcher confined with limitedParallelism(1).

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

Swift consumers MUST NOT invoke synchronous mutation hooks directly on shared native singletons across asynchronous Grand Central Dispatch queues

Swift consumers MUST NOT invoke synchronous mutation hooks directly on shared native singletons across asynchronous Grand Central Dispatch queues; mutations MUST traverse explicit, asynchronous shared-boundary entry points.

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 wrap StateFlow Darwin consumption in structured AsyncSequence or Combine publisher bridges that guarantee cooperative cancellation and prevent retain cycles across ARC and Kotlin Garbage Collector runtimes.

Engineers MUST wrap StateFlow Darwin consumption in structured AsyncSequence or Combine publisher bridges that guarantee cooperative cancellation and prevent retain cycles across ARC and Kotlin Garbage Collector runtimes.

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

Shared data models exchanged during high-throughput updates MUST be strictly immutable Kotlin data classes with val-only fields to prevent cross-heap mutation hazards.

Shared data models exchanged during high-throughput updates MUST be strictly immutable Kotlin data classes with val-only fields to prevent cross-heap mutation hazards.

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 Concurrent StateFlow Atomic Mutation Barrier Standard critical for AI coding assistants?

Enforces thread-safe, atomic mutations and cross-runtime boundary encapsulation for Kotlin Multiplatform StateFlow pipelines consumed by Swift. Precludes memory tearing, race-conditioned telemetry drops, and legacy thread-state freezing crashes during high-throughput concurrent ingress across Darwin GCD queues and Kotlin Native worker dispatchers. 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 (Unprotected mutable StateFlow reference exposure and non-atomic field assignments across Darwin-K/N thread boundaries) 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