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

KMP StateFlow Sequential Consistency Across Kotlin/Native and Swift ARC Boundary

Enforces sequentially consistent cross-thread state propagation across the Kotlin/Native and Swift ARC interop boundary. Prevents data races, torn reads, and stale cache lines when mutating StateFlow instances observed concurrently across distinct runtime runloops by mandating strict memory fence barriers and thread confinement.

Prohibited Anti-Pattern: Unconfined Cross-Thread StateFlow Mutation Causing Out-of-Order Memory Visibility Across Swift Interop

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP StateFlow Sequential Consistency Across Kotlin/Native and Swift ARC Boundary - Enforces sequentially consistent cross-thread state propagation across the Kotlin/Native and Swift ARC interop boundary. Prevents data races, torn reads, and stale cache lines when mutating StateFlow instances observed concurrently across distinct runtime runloops by mandating strict memory fence barriers and thread confinement.
globs: shared/src/commonMain/kotlin/**/*.kt, shared/src/iosMain/kotlin/**/*.kt, iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-concurrent-stateflow-memory-fence-guardrail"
---

# KMP StateFlow Sequential Consistency Across Kotlin/Native and Swift ARC Boundary

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unconfined Cross-Thread StateFlow Mutation Causing Out-of-Order Memory Visibility Across Swift Interop

## System Constraints
You are a Principal Mobile Architect enforcing strict memory consistency models across Kotlin Multiplatform and Swift ARC boundaries. When code bridges Kotlin Coroutines StateFlow to Swift via Objective-C/C Interop, you MUST mandate sequentially consistent memory fences, prevent raw volatile bypasses across the FFI, and guarantee that mutations and observations adhere to structured actor isolation or explicit main-dispatcher confinement.

## Strict Guidelines
- Engineers MUST ALWAYS mutate Kotlin `MutableStateFlow` using atomic read-modify-write primitives (e.g., `.update { ... }`) rather than direct property assignment (`.value = ...`) when state is shared across interop boundaries.
- Engineers MUST NOT expose raw `MutableStateFlow` across the Swift/Obj-C bridge; all exposed flows MUST be read-only `StateFlow` wrapped with SKIE or dedicated Darwin memory-safe bridging adaptors.
- Swift consumers MUST isolate StateFlow observation tasks to `@MainActor` or an explicit Swift Actor runtime to prevent unsynchronized ARC retain-release cycles from executing across Native GC safepoints.
- Kotlin/Native background emitters MUST ensure a memory-order acquire-release fence prior to emitting state intended for Darwin threads, explicitly utilizing `Dispatchers.Main.immediate` or sequential coroutine channels for cross-runtime delivery.
- Components NEVER read raw `.value` from a Kotlin `StateFlow` synchronously within Swift background worker threads without establishing an explicit memory barrier.

## Bad vs Good Implementations
### Kotlin Side: Atomic StateFlow Updates with Memory-Order Barrier

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly assigning `sessionState.value` from a non-cooperating coroutine dispatcher does not guarantee a release fence across the Foreign Function Interface (FFI). Swift threads reading the cached reference may observe stale pointer addresses or partially initialized state across the ARC/K-N GC boundary.
```kotlin
class SessionRepository {
    // ANTI-PATTERN: Direct property mutation across unconfined background threads
    val sessionState = MutableStateFlow<SessionState>(SessionState.Idle)

    fun updateToken(token: String) {
        kotlinx.coroutines.GlobalScope.launch(kotlinx.coroutines.Dispatchers.Default) {
            // Torn read/write hazard across Swift ARC boundary: unconfined memory visibility
            sessionState.value = SessionState.Authenticated(token)
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Encapsulates state via a read-only StateFlow interface, uses atomic `.update { ... }` (CAS loop), and dispatches across `Dispatchers.Main.immediate`, establishing an acquire-release memory fence synchronized with Darwin's main runloop.
```kotlin
class SessionRepository(
    private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main.immediate
) {
    private val _sessionState = MutableStateFlow<SessionState>(SessionState.Idle)
    val sessionState: StateFlow<SessionState> = _sessionState.asStateFlow()

    suspend fun updateToken(token: String) = withContext(mainDispatcher) {
        // Enforces sequentially consistent CAS operation and main runloop fence for Swift interop
        _sessionState.update { currentState ->
            SessionState.Authenticated(token)
        }
    }
}
```

### Swift Side: Actor-Isolated StateFlow Observation via SKIE / AsyncSequence

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Consuming Kotlin StateFlow within an unconfined `Task.detached` executes Swift ARC retain/release operations concurrently against Kotlin Native garbage-collected objects without memory ordering synchronization, causing undefined memory behavior and potential SIGSEGV.
```swift
class SessionViewModel {
    private let repository: SessionRepository
    var currentState: SessionState = SessionStateIdle()

    init(repository: SessionRepository) {
        self.repository = repository
        // ANTI-PATTERN: Consuming KMP StateFlow on background thread without actor isolation
        Task.detached(priority: .background) {
            for await state in self.repository.sessionState {
                // Race condition: unsynchronized Swift ARC reference mutation across K/N GC boundary
                self.currentState = state
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Confines StateFlow consumption strictly to `@MainActor`, synchronizing Swift ARC reference counting with Kotlin/Native's MainDispatcher memory fences and preventing cross-thread state tearing.
```swift
@MainActor
final class SessionViewModel: ObservableObject {
    private let repository: SessionRepository
    @Published private(var) var currentState: SessionState = SessionStateIdle()
    private var stateObservationTask: Task<Void, Never>?

    init(repository: SessionRepository) {
        self.repository = repository
        observeState()
    }

    private func observeState() {
        // Guaranteed sequential execution on Swift MainActor runloop synchronized with Kotlin MainDispatcher
        stateObservationTask = Task { @MainActor [weak self] in
            guard let self = self else { return }
            for await state in self.repository.sessionState {
                self.currentState = state
            }
        }
    }

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

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 StateFlow Sequential Consistency Across Kotlin/Native and Swift ARC Boundary

KMP StateFlow Sequential Consistency Across Kotlin/Native and Swift ARC Boundary defines an industrial-grade behavioral standard for mobile engineering. Enforces sequentially consistent cross-thread state propagation across the Kotlin/Native and Swift ARC interop boundary. Prevents data races, torn reads, and stale cache lines when mutating StateFlow instances observed concurrently across distinct runtime runloops by mandating strict memory fence barriers and thread confinement. 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 Cross-Thread StateFlow Mutation Causing Out-of-Order Memory Visibility Across Swift Interop 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 Cross-Thread StateFlow Mutation Causing Out-of-Order Memory Visibility Across Swift InteropCritical
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 mutate Kotlin `MutableStateFlow` using atomic read-modify-write primitives (e.g., `.update { ... }`) rather than direct property assignment (`.value = ...`) when state is shared across interop boundaries.

Engineers MUST ALWAYS mutate Kotlin `MutableStateFlow` using atomic read-modify-write primitives (e.g., `.update { ... }`) rather than direct property assignment (`.value = ...`) when state is shared across interop 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.
2

Engineers MUST NOT expose raw `MutableStateFlow` across the Swift/Obj-C bridge

Engineers MUST NOT expose raw `MutableStateFlow` across the Swift/Obj-C bridge; all exposed flows MUST be read-only `StateFlow` wrapped with SKIE or dedicated Darwin memory-safe bridging adaptors.

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

Swift consumers MUST isolate StateFlow observation tasks to `@MainActor` or an explicit Swift Actor runtime to prevent unsynchronized ARC retain-release cycles from executing across Native GC safepoints.

Swift consumers MUST isolate StateFlow observation tasks to `@MainActor` or an explicit Swift Actor runtime to prevent unsynchronized ARC retain-release cycles from executing across Native GC safepoints.

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

Kotlin/Native background emitters MUST ensure a memory-order acquire-release fence prior to emitting state intended for Darwin threads, explicitly utilizing `Dispatchers.Main.immediate` or sequential coroutine channels for cross-runtime delivery.

Kotlin/Native background emitters MUST ensure a memory-order acquire-release fence prior to emitting state intended for Darwin threads, explicitly utilizing `Dispatchers.Main.immediate` or sequential coroutine channels for cross-runtime delivery.

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 read raw `.value` from a Kotlin `StateFlow` synchronously within Swift background worker threads without establishing an explicit memory barrier.

Components NEVER read raw `.value` from a Kotlin `StateFlow` synchronously within Swift background worker threads without establishing an explicit memory barrier.

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 StateFlow Sequential Consistency Across Kotlin/Native and Swift ARC Boundary critical for AI coding assistants?

Enforces sequentially consistent cross-thread state propagation across the Kotlin/Native and Swift ARC interop boundary. Prevents data races, torn reads, and stale cache lines when mutating StateFlow instances observed concurrently across distinct runtime runloops by mandating strict memory fence barriers and thread confinement. 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 Cross-Thread StateFlow Mutation Causing Out-of-Order Memory Visibility Across Swift Interop) 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