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

Lock-Free StateFlow-to-Darwin RunLoop Bridging and Re-Entrancy Invariant

Mandates lock-free, asynchronous memory-fenced coordination when bridging Kotlin Multiplatform (Kotlin 2.1+) Coroutine StateFlow streams to Darwin CFRunLoop and Swift MainActor execution contexts. Prohibits synchronous queue synchronization (dispatch_sync), runBlocking on Main/UI threads, and re-entrant lock acquisition during high-frequency UI event cycles.

Prohibited Anti-Pattern: Synchronous Darwin RunLoop Dispatching and Re-Entrant Lock Contention in StateFlow Bridges

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Lock-Free StateFlow-to-Darwin RunLoop Bridging and Re-Entrancy Invariant - Mandates lock-free, asynchronous memory-fenced coordination when bridging Kotlin Multiplatform (Kotlin 2.1+) Coroutine StateFlow streams to Darwin CFRunLoop and Swift MainActor execution contexts. Prohibits synchronous queue synchronization (dispatch_sync), runBlocking on Main/UI threads, and re-entrant lock acquisition during high-frequency UI event cycles.
globs: **/iosMain/**/*.kt, **/darwinMain/**/*.kt, iosApp/**/*.swift, shared/src/iosMain/**/*.kt, shared/src/appleMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-stateflow-darwin-runloop-deadlock-guardrail"
---

# Lock-Free StateFlow-to-Darwin RunLoop Bridging and Re-Entrancy Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Synchronous Darwin RunLoop Dispatching and Re-Entrant Lock Contention in StateFlow Bridges

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform and Darwin interop. You enforce strict, non-blocking, lock-free memory fence coordination when streaming Kotlin Coroutine StateFlow states to iOS/Darwin UI threads. You prevent synchronous bridging, CFRunLoop re-entrancy deadlocks, and inversion bugs.

## Strict Guidelines
- Engineers MUST ALWAYS bridge StateFlow to Darwin consumers using asynchronous, non-blocking primitives such as Swift AsyncStream, SKIE-generated async sequences, or conflated Dispatchers.Main.immediate emission pipelines.
- Engineers MUST NOT invoke `runBlocking` or `dispatch_sync(dispatch_get_main_queue(), ...)` within Darwin interop boundaries or UI callbacks observing Kotlin StateFlow.
- Code SHOULD leverage lock-free memory fences (`kotlinx.atomicfu.atomic` or `kotlin.concurrent.AtomicReference`) for instantaneous state snapshots instead of synchronized critical sections when polling state across threads.
- Services MUST decouple high-frequency state updates from Darwin RunLoop execution frames using `.conflate()` or `.debounce()` in Kotlin before triggering MainActor UI reconciliations.
- Components NEVER hold mutex locks (e.g., `NSLock`, POSIX mutexes, `kotlinx.coroutines.sync.Mutex`) across Kotlin-to-ObjC/Swift collector callbacks.

## Bad vs Good Implementations
### StateFlow Darwin MainActor Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using `dispatch_sync` to the Darwin main queue inside a coroutine collector creates a classic inversion deadlock if the main thread is simultaneously waiting on a coroutine task or emitting an update into the StateFlow. Calling `runBlocking` on the main thread freezes the RunLoop.
```kotlin
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import platform.darwin.*

class UnsafeIosStateBridge<T>(private val stateFlow: StateFlow<T>) {
    // ANTI-PATTERN: Blocking dispatch on Darwin main queue while collecting
    // triggers mutual recursion and deadlock if the UI thread triggers an update
    fun observe(onUpdate: (T) -> Unit) {
        val scope = CoroutineScope(Dispatchers.Default)
        scope.launch {
            stateFlow.collect { value ->
                dispatch_sync(dispatch_get_main_queue()) {
                    // Deadlock: Re-entrancy into CFRunLoop while holding coroutine context
                    onUpdate(value)
                }
            }
        }
    }

    // ANTI-PATTERN: runBlocking blocks Darwin main thread waiting for Kotlin coroutine
    val currentState: T
        get() = runBlocking(Dispatchers.Main) {
            stateFlow.first()
        }
}
```

#### Production Standard (Correct)
> **Standard**: Uses `Dispatchers.Main.immediate` to execute synchronously only if already on the main thread without re-scheduling, drops obsolete intermediate states with `.conflate()`, and provides a lock-free snapshot via `atomicfu`.
```kotlin
import kotlinx.atomicfu.atomic
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import platform.darwin.*

class SafeDarwinStateBridge<T : Any>(
    private val stateFlow: StateFlow<T>,
    private val scope: CoroutineScope
) {
    // Lock-free atomic reference providing single-clock-cycle memory fence snapshots
    private val atomicState = atomic(stateFlow.value)

    // Non-blocking current state snapshot without RunLoop suspension
    val currentState: T
        get() = atomicState.value

    fun subscribe(onUpdate: (T) -> Unit): () -> Unit {
        val job = scope.launch(Dispatchers.Main.immediate) {
            stateFlow
                .conflate() // Prevent queue saturation during high-frequency events
                .collect { value ->
                    atomicState.value = value
                    // Non-blocking asynchronous schedule onto CFRunLoop via immediate dispatcher
                    onUpdate(value)
                }
        }

        return { job.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: Lock-Free StateFlow-to-Darwin RunLoop Bridging and Re-Entrancy Invariant

Lock-Free StateFlow-to-Darwin RunLoop Bridging and Re-Entrancy Invariant defines an industrial-grade behavioral standard for mobile engineering. Mandates lock-free, asynchronous memory-fenced coordination when bridging Kotlin Multiplatform (Kotlin 2.1+) Coroutine StateFlow streams to Darwin CFRunLoop and Swift MainActor execution contexts. Prohibits synchronous queue synchronization (dispatch_sync), runBlocking on Main/UI threads, and re-entrant lock acquisition during high-frequency UI event cycles. 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: Synchronous Darwin RunLoop Dispatching and Re-Entrant Lock Contention in StateFlow Bridges 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 DriftSynchronous Darwin RunLoop Dispatching and Re-Entrant Lock Contention in StateFlow BridgesCritical
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 bridge StateFlow to Darwin consumers using asynchronous, non-blocking primitives such as Swift AsyncStream, SKIE-generated async sequences, or conflated Dispatchers.Main.immediate emission pipelines.

Engineers MUST ALWAYS bridge StateFlow to Darwin consumers using asynchronous, non-blocking primitives such as Swift AsyncStream, SKIE-generated async sequences, or conflated Dispatchers.Main.immediate emission pipelines.

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 invoke `runBlocking` or `dispatch_sync(dispatch_get_main_queue(), ...)` within Darwin interop boundaries or UI callbacks observing Kotlin StateFlow.

Engineers MUST NOT invoke `runBlocking` or `dispatch_sync(dispatch_get_main_queue(), ...)` within Darwin interop boundaries or UI callbacks observing Kotlin StateFlow.

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 leverage lock-free memory fences (`kotlinx.atomicfu.atomic` or `kotlin.concurrent.AtomicReference`) for instantaneous state snapshots instead of synchronized critical sections when polling state across threads.

Code SHOULD leverage lock-free memory fences (`kotlinx.atomicfu.atomic` or `kotlin.concurrent.AtomicReference`) for instantaneous state snapshots instead of synchronized critical sections when polling state across 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.
4

Services MUST decouple high-frequency state updates from Darwin RunLoop execution frames using `.conflate()` or `.debounce()` in Kotlin before triggering MainActor UI reconciliations.

Services MUST decouple high-frequency state updates from Darwin RunLoop execution frames using `.conflate()` or `.debounce()` in Kotlin before triggering MainActor UI reconciliations.

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 hold mutex locks (e.g., `NSLock`, POSIX mutexes, `kotlinx.coroutines.sync.Mutex`) across Kotlin-to-ObjC/Swift collector callbacks.

Components NEVER hold mutex locks (e.g., `NSLock`, POSIX mutexes, `kotlinx.coroutines.sync.Mutex`) across Kotlin-to-ObjC/Swift collector callbacks.

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 Lock-Free StateFlow-to-Darwin RunLoop Bridging and Re-Entrancy Invariant critical for AI coding assistants?

Mandates lock-free, asynchronous memory-fenced coordination when bridging Kotlin Multiplatform (Kotlin 2.1+) Coroutine StateFlow streams to Darwin CFRunLoop and Swift MainActor execution contexts. Prohibits synchronous queue synchronization (dispatch_sync), runBlocking on Main/UI threads, and re-entrant lock acquisition during high-frequency UI event cycles. 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 (Synchronous Darwin RunLoop Dispatching and Re-Entrant Lock Contention in StateFlow Bridges) 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

Lock-Free