This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-atomicfu-swift-concurrency-lock-free-invariant

KMP AtomicFU Lock-Free Mutation Invariant across Swift 6 Concurrency

Enforces lock-free AtomicFU atomic state transitions and non-blocking bridge boundaries between Kotlin Multiplatform state machines and Swift 6 strict-concurrency actors. Prevents cooperative thread pool starvation, priority inversions, and deadlocks caused by synchronous spinlocks or blocking CAS retry loops on iOS Grand Central Dispatch and Swift Concurrency runtime threads.

Prohibited Anti-Pattern: Blocking Swift Cooperative Thread Pools via Synchronous KMP AtomicFU Spin-Wait Mutation Loops

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP AtomicFU Lock-Free Mutation Invariant across Swift 6 Concurrency - Enforces lock-free AtomicFU atomic state transitions and non-blocking bridge boundaries between Kotlin Multiplatform state machines and Swift 6 strict-concurrency actors. Prevents cooperative thread pool starvation, priority inversions, and deadlocks caused by synchronous spinlocks or blocking CAS retry loops on iOS Grand Central Dispatch and Swift Concurrency runtime threads.
globs: **/*.kt, **/*.swift, **/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-atomicfu-swift-concurrency-lock-free-invariant"
---

# KMP AtomicFU Lock-Free Mutation Invariant across Swift 6 Concurrency

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Blocking Swift Cooperative Thread Pools via Synchronous KMP AtomicFU Spin-Wait Mutation Loops

## System Constraints
You are a Principal Mobile Architect enforcing absolute safety and lock-free execution semantics between Kotlin Multiplatform (KMP) shared state engines and Apple Swift 6 strict-concurrency runtimes. You must prohibit any synchronous blocking, POSIX pthread locking, or unbounded spin-wait retry loops executed from Swift actor contexts into KMP AtomicFU references. Ensure all multiplatform mutations expose asynchronous suspension points, use bounded CAS backoff protocols, and strictly preserve Swift 6 Sendable and actor-isolation invariants without exhausting iOS cooperative thread pools.

## Strict Guidelines
- Engineers MUST ALWAYS expose Kotlin state updates to Swift as asynchronous suspending functions (`suspend fun`) or reactive streams (`StateFlow`), never as blocking synchronous functions containing AtomicFU `updateAndGet` or `loop` blocks.
- Engineers MUST NOT execute synchronous AtomicFU CAS (`compareAndSet`) retry loops or POSIX spinlocks directly on Swift 6 actor-isolated threads, as Swift uses a fixed-width cooperative thread pool vulnerable to starvation.
- Engineers MUST ensure that any exported Kotlin class mutating internal `atomic<T>` state is marked with `@ObjCName` and consumed as a detached `@Sendable` or isolated within a dedicated Swift `actor` wrapper to satisfy Swift 6 strict concurrency checks.
- Code MUST route heavy contention AtomicFU state mutations onto dedicated Kotlin Native worker dispatchers (`Dispatchers.Default` backed by an asynchronous channel or actor loop) before executing CAS operations.
- Components NEVER use `kotlinx.atomicfu.locks.Synchronized` or NSLock bridging across KMP-Swift interop surfaces when bridging state between Kotlin and Swift Task contexts.

## Bad vs Good Implementations
### KMP Shared State Machine: Blocking Spinlock Bridge vs. Asynchronous Lock-Free Pipeline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Exposing a synchronous CAS loop directly to Swift via Objective-C interop blocks the calling Swift cooperative thread. Under contention, this starvates Swift's limited concurrent thread pool (equal to CPU core count) and causes severe priority inversions.
```kotlin
import kotlinx.atomicfu.atomic
import kotlinx.atomicfu.update

class SessionStateMachine {
    private val state = atomic<State>(State.Idle)

    // ANTI-PATTERN: Synchronous blocking call exposing a CAS loop directly to Swift.
    // When invoked from Swift async/await actor context, high contention causes thread starvation
    // and priority inversion in the Swift cooperative pool.
    fun transitionSynchronously(event: Event): State {
        state.loop { current ->
            val next = current.reduce(event)
            if (state.compareAndSet(current, next)) {
                return next
            }
            // Unbounded busy-wait spin-loop blocks Swift actor thread
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: State transitions are mediated via suspendable Kotlin coroutines offloaded to `Dispatchers.Default`. Swift callers invoke this via `async` bridging, safely suspending without occupying or stalling the Swift 6 actor cooperative pool.
```kotlin
import kotlinx.atomicfu.atomic
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.withContext
import kotlinx.coroutines.Dispatchers

class SessionStateMachine {
    private val _state = MutableStateFlow<State>(State.Idle)
    val state: StateFlow<State> = _state.asStateFlow()
    private val atomicCounter = atomic(0L)

    // PRODUCTION FIX: Explicit suspending function dispatched off the cooperative pool,
    // utilizing lock-free StateFlow/Atomic updates with cooperative yield safety.
    suspend fun transition(event: Event): State = withContext(Dispatchers.Default) {
        var updatedState: State
        do {
            val current = _state.value
            updatedState = current.reduce(event)
            atomicCounter.incrementAndGet()
        } while (!_state.compareAndSet(current, updatedState))
        updatedState
    }
}
```

### Swift 6 Strict Concurrency Interop: Actor Invariant Consumption

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling synchronous AtomicFU mutation code directly from `@MainActor` causes direct main-thread UI hangs if contention occurs in the shared state machine.
```swift
import SharedKit

// ANTI-PATTERN: Synchronously calling KMP AtomicFU mutation on Swift 6 MainActor
@MainActor
final class SessionViewModel: ObservableObject {
    private let machine = SessionStateMachine()

    func handleUserAction(event: SharedKit.Event) {
        // Synchronous call enters AtomicFU CAS spinlock, freezing UI and MainActor runloop
        let newState = machine.transitionSynchronously(event: event)
        self.apply(newState)
    }
    private func apply(_ state: SharedKit.State) {}
}
```

#### Production Standard (Correct)
> **Standard**: The Swift boundary safely routes execution through an isolated `actor` using Swift 6 cooperative async suspension (`try await machine.transition`), entirely shielding the main thread and thread pool from CAS retry contention.
```swift
import SharedKit

// PRODUCTION FIX: Swift actor isolates boundary and consumes suspending KMP bridge without blocking
actor SessionController {
    private let machine: SessionStateMachine

    init(machine: SessionStateMachine) {
        self.machine = machine
    }

    func handleUserAction(event: SharedKit.Event) async throws -> SharedKit.State {
        // Non-blocking asynchronous suspension point bridged to Kotlin suspend fun
        let newState = try await machine.transition(event: event)
        return newState
    }
}

@MainActor
final class SessionViewModel: ObservableObject {
    private let controller: SessionController

    init(controller: SessionController) {
        self.controller = controller
    }

    func trigger(event: SharedKit.Event) {
        Task { @MainActor in
            do {
                let state = try await controller.handleUserAction(event: event)
                self.apply(state)
            } catch {
                // Handle cancellation or transition failure
            }
        }
    }
    private func apply(_ state: SharedKit.State) {}
}
```

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 AtomicFU Lock-Free Mutation Invariant across Swift 6 Concurrency

KMP AtomicFU Lock-Free Mutation Invariant across Swift 6 Concurrency defines an industrial-grade behavioral standard for mobile engineering. Enforces lock-free AtomicFU atomic state transitions and non-blocking bridge boundaries between Kotlin Multiplatform state machines and Swift 6 strict-concurrency actors. Prevents cooperative thread pool starvation, priority inversions, and deadlocks caused by synchronous spinlocks or blocking CAS retry loops on iOS Grand Central Dispatch and Swift Concurrency runtime threads. 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: Blocking Swift Cooperative Thread Pools via Synchronous KMP AtomicFU Spin-Wait Mutation Loops 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 DriftBlocking Swift Cooperative Thread Pools via Synchronous KMP AtomicFU Spin-Wait Mutation LoopsCritical
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 Kotlin state updates to Swift as asynchronous suspending functions (`suspend fun`) or reactive streams (`StateFlow`), never as blocking synchronous functions containing AtomicFU `updateAndGet` or `loop` blocks.

Engineers MUST ALWAYS expose Kotlin state updates to Swift as asynchronous suspending functions (`suspend fun`) or reactive streams (`StateFlow`), never as blocking synchronous functions containing AtomicFU `updateAndGet` or `loop` blocks.

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 execute synchronous AtomicFU CAS (`compareAndSet`) retry loops or POSIX spinlocks directly on Swift 6 actor-isolated threads, as Swift uses a fixed-width cooperative thread pool vulnerable to starvation.

Engineers MUST NOT execute synchronous AtomicFU CAS (`compareAndSet`) retry loops or POSIX spinlocks directly on Swift 6 actor-isolated threads, as Swift uses a fixed-width cooperative thread pool vulnerable to starvation.

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 ensure that any exported Kotlin class mutating internal `atomic<T>` state is marked with `@ObjCName` and consumed as a detached `@Sendable` or isolated within a dedicated Swift `actor` wrapper to satisfy Swift 6 strict concurrency checks.

Engineers MUST ensure that any exported Kotlin class mutating internal `atomic<T>` state is marked with `@ObjCName` and consumed as a detached `@Sendable` or isolated within a dedicated Swift `actor` wrapper to satisfy Swift 6 strict concurrency checks.

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 MUST route heavy contention AtomicFU state mutations onto dedicated Kotlin Native worker dispatchers (`Dispatchers.Default` backed by an asynchronous channel or actor loop) before executing CAS operations.

Code MUST route heavy contention AtomicFU state mutations onto dedicated Kotlin Native worker dispatchers (`Dispatchers.Default` backed by an asynchronous channel or actor loop) before executing CAS operations.

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 use `kotlinx.atomicfu.locks.Synchronized` or NSLock bridging across KMP-Swift interop surfaces when bridging state between Kotlin and Swift Task contexts.

Components NEVER use `kotlinx.atomicfu.locks.Synchronized` or NSLock bridging across KMP-Swift interop surfaces when bridging state between Kotlin and Swift Task 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 KMP AtomicFU Lock-Free Mutation Invariant across Swift 6 Concurrency critical for AI coding assistants?

Enforces lock-free AtomicFU atomic state transitions and non-blocking bridge boundaries between Kotlin Multiplatform state machines and Swift 6 strict-concurrency actors. Prevents cooperative thread pool starvation, priority inversions, and deadlocks caused by synchronous spinlocks or blocking CAS retry loops on iOS Grand Central Dispatch and Swift Concurrency runtime threads. 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 (Blocking Swift Cooperative Thread Pools via Synchronous KMP AtomicFU Spin-Wait Mutation Loops) 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