This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: swift6-actor-reentrancy-state-invariants

Swift 6 Actor Reentrancy State Mutability Invariant Guardrail

Enforces strict isolation and validation of mutable actor state across asynchronous suspension points (await) within high-concurrency native engine bindings. Prevents silent state corruption, interleaved race conditions, and uncoordinated bridge state updates caused by Swift actor reentrancy semantics.

Prohibited Anti-Pattern: Interleaved Actor State Mutation Across Async Suspension Points

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Swift 6 Actor Reentrancy State Mutability Invariant Guardrail - Enforces strict isolation and validation of mutable actor state across asynchronous suspension points (await) within high-concurrency native engine bindings. Prevents silent state corruption, interleaved race conditions, and uncoordinated bridge state updates caused by Swift actor reentrancy semantics.
globs: ios/**/*.{swift,h,mm}, apple/**/*.{swift,h,mm}, Packages/**/*.swift, native/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/swift6-actor-reentrancy-state-invariants"
---

# Swift 6 Actor Reentrancy State Mutability Invariant Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Interleaved Actor State Mutation Across Async Suspension Points

## System Constraints
You are a Principal Software Architect enforcing Swift 6 Actor Reentrancy and Memory Isolation Guardrails. Mandate that actor-isolated state is never assumed immutable across an 'await' suspension point. Ensure all native cross-platform engine interactions isolate state transitions via transactional phases, monotonic generation counters, or synchronous reduction cycles.

## Strict Guidelines
- Engineers MUST ALWAYS re-validate all internal actor invariants immediately after resuming from any 'await' suspension point.
- Engineers MUST NOT assume local or actor state persists unchanged across an asynchronous bridge call to cross-platform native engines (e.g., C++ core, Rust FFI, Metal render loops).
- Code SHOULD extract external async operations out of state-modifying sequences, adopting the 'Fetch Out-of-Actor -> Verify -> Synchronously Mutate' architectural pattern.
- Services MUST utilize monotonic epoch/generation counters or cancellation tokens to discard stale execution frames resuming after actor suspension.
- Components NEVER execute multi-step cross-thread bridge dispatches while holding uncommitted local actor state.

## Bad vs Good Implementations
### Actor Reentrancy State Corruption vs Monotonic Epoch Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Swift 6, actors do not prevent reentrancy during 'await'. While 'ForeignEngineInterop.bootEngine' suspends, 'terminateSession()' or a secondary initialization can interleave, leading to dangling native handles and silent state divergence between Swift and the underlying C++ engine.
```swift
actor NativeEngineBridge {
    private var sessionToken: String?
    private var isEngineActive: Bool = false

    func initializeEngineSession(token: String) async throws {
        // ANTI-PATTERN: State mutation initiated before suspension point
        self.sessionToken = token
        self.isEngineActive = true

        // Async suspension point: Actor lock is released while C++ engine boots
        let result = try await ForeignEngineInterop.bootEngine(with: token)

        // REENTRANCY BUG: Another caller could have called 'terminateSession()' or
        // re-entered 'initializeEngineSession()' during the bootEngine suspension,
        // causing stale results to overwrite newer state.
        ForeignEngineInterop.bindNativeViewport(result.handle)
    }

    func terminateSession() {
        self.sessionToken = nil
        self.isEngineActive = false
        ForeignEngineInterop.teardown()
    }
}
```

#### Production Standard (Correct)
> **Standard**: Introduces monotonic epoch validation. State is not prematurely committed before 'await', and upon resumption, the actor verifies that no interleaving operation altered 'currentEpoch'. Stale engine handles are released deterministically.
```swift
actor NativeEngineBridge {
    private struct SessionState: Sendable {
        let token: String
        let epoch: UInt64
    }

    private var activeSession: SessionState?
    private var currentEpoch: UInt64 = 0

    func initializeEngineSession(token: String) async throws {
        // 1. Advance epoch synchronously to invalidate prior runs
        self.currentEpoch += 1
        let sessionEpoch = self.currentEpoch

        // 2. Perform external work out-of-line without committing final state
        let result = try await ForeignEngineInterop.bootEngine(with: token)

        // 3. Post-suspension check: Verify invariants hold and no reentrancy occurred
        guard self.currentEpoch == sessionEpoch else {
            // Safe cancellation: Another operation invalidated this execution context
            ForeignEngineInterop.releaseHandle(result.handle)
            throw CancellationError()
        }

        // 4. Atomic synchronous commit phase
        self.activeSession = SessionState(token: token, epoch: sessionEpoch)
        ForeignEngineInterop.bindNativeViewport(result.handle)
    }

    func terminateSession() {
        self.currentEpoch += 1
        self.activeSession = nil
        ForeignEngineInterop.teardown()
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Swift 6 Actor Reentrancy State Mutability Invariant Guardrail

Swift 6 Actor Reentrancy State Mutability Invariant Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict isolation and validation of mutable actor state across asynchronous suspension points (await) within high-concurrency native engine bindings. Prevents silent state corruption, interleaved race conditions, and uncoordinated bridge state updates caused by Swift actor reentrancy semantics. 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: Interleaved Actor State Mutation Across Async Suspension Points 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 DriftInterleaved Actor State Mutation Across Async Suspension PointsCritical
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 re-validate all internal actor invariants immediately after resuming from any 'await' suspension point.

Engineers MUST ALWAYS re-validate all internal actor invariants immediately after resuming from any 'await' suspension point.

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 assume local or actor state persists unchanged across an asynchronous bridge call to cross-platform native engines (e.g., C++ core, Rust FFI, Metal render loops).

Engineers MUST NOT assume local or actor state persists unchanged across an asynchronous bridge call to cross-platform native engines (e.g., C++ core, Rust FFI, Metal render loops).

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 extract external async operations out of state-modifying sequences, adopting the 'Fetch Out-of-Actor -> Verify -> Synchronously Mutate' architectural pattern.

Code SHOULD extract external async operations out of state-modifying sequences, adopting the 'Fetch Out-of-Actor -> Verify -> Synchronously Mutate' architectural pattern.

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 utilize monotonic epoch/generation counters or cancellation tokens to discard stale execution frames resuming after actor suspension.

Services MUST utilize monotonic epoch/generation counters or cancellation tokens to discard stale execution frames resuming after actor suspension.

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 execute multi-step cross-thread bridge dispatches while holding uncommitted local actor state.

Components NEVER execute multi-step cross-thread bridge dispatches while holding uncommitted local actor state.

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 Swift 6 Actor Reentrancy State Mutability Invariant Guardrail critical for AI coding assistants?

Enforces strict isolation and validation of mutable actor state across asynchronous suspension points (await) within high-concurrency native engine bindings. Prevents silent state corruption, interleaved race conditions, and uncoordinated bridge state updates caused by Swift actor reentrancy semantics. 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 (Interleaved Actor State Mutation Across Async Suspension Points) 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

Swift