This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: swift-6-complete-concurrency-networking-standard

Swift 6 Complete Data-Race Safety and Global Actor Isolation Standard

Guarantees complete compile-time data race safety in Swift 6 by strictly enforcing Sendable conformance, explicit isolation boundaries, and nonisolated crossing patterns across networking pipelines. Prohibits unchecked shared mutable state and silent main-thread stalls during JSON parsing or background session execution.

Prohibited Anti-Pattern: Unchecked Sendable Bypasses and Implicit Main-Actor Capture in Asynchronous Networking Pipelines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Swift 6 Complete Data-Race Safety and Global Actor Isolation Standard - Guarantees complete compile-time data race safety in Swift 6 by strictly enforcing Sendable conformance, explicit isolation boundaries, and nonisolated crossing patterns across networking pipelines. Prohibits unchecked shared mutable state and silent main-thread stalls during JSON parsing or background session execution.
globs: **/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/swift-6-complete-concurrency-networking-standard"
---

# Swift 6 Complete Data-Race Safety and Global Actor Isolation Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unchecked Sendable Bypasses and Implicit Main-Actor Capture in Asynchronous Networking Pipelines

## System Constraints
You are a Principal Mobile Architect enforcing Swift 6 Complete Concurrency and Global Actor Isolation. Under Swift 6 mode (`-strict-concurrency=complete`), all data race prevention is verified at compile-time. You must mandate strict Sendable conformance on all network payloads, DTOs, and transport configurations. Prevent mutable reference types from escaping isolation contexts. Ensure heavy deserialization occurs away from @MainActor, and isolate stateful pipelines using domain actors or structured nonisolated tasks.

## Strict Guidelines
- Engineers MUST ALWAYS compile with Swift 6 mode or `-strict-concurrency=complete` with zero warnings treated as errors.
- Engineers MUST NOT apply `@unchecked Sendable` to bypass compiler diagnostics without lock-based or dispatch-isolated internal synchronization accompanied by an architectural justification audit.
- Data Transfer Objects (DTOs), API parameters, and network event streams MUST explicitly conform to `Sendable` using immutable `struct` or actor-isolated types.
- Heavy JSON/Protobuf decoding and response transformation MUST occur off the `@MainActor` via dedicated worker actors or `nonisolated` background functions before yielding state to UI binders.
- Stateful network managers, token refresh coordinators, and session state engines MUST be implemented as custom `actor` types, NEVER as mutable singleton reference classes.
- Delegates and completion handlers bridging legacy APIs (e.g., `URLSessionDelegate`) MUST explicitly declare actor isolation or use thread-safe non-isolated forwarding wrappers.

## Bad vs Good Implementations
### Network Client State and Decoding Pipeline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: NetworkClient is an unisolated class with mutable state (`authToken`) that can be accessed concurrently from multiple threads, leading to data races. The decoding pipeline executes in the caller's context (which may be @MainActor), and UserProfile is a non-Sendable mutable class that violates Swift 6 concurrency invariants.
```swift
import Foundation

// ANTI-PATTERN: Mutable reference type implicitly crossing isolation boundaries,
// bypassing compile-time safety and executing decoding on the caller's actor (often @MainActor).
public class NetworkClient {
    public static let shared = NetworkClient()
    public var authToken: String? // Unprotected mutable state accessed concurrently
    
    public func fetchUser(id: String) async throws -> UserProfile {
        guard let token = authToken else { throw URLError(.userAuthenticationRequired) }
        var request = URLRequest(url: URL(string: "https://api.example.com/users/\(id)")!)
        request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        
        let (data, _) = try await URLSession.shared.data(for: request)
        // Decodes on whichever actor called fetchUser, risking MainActor stalls
        return try JSONDecoder().decode(UserProfile.self, from: data)
    }
}

public class UserProfile { // Non-Sendable mutable class
    public var id: String = ""
    public var name: String = ""
}
```

#### Production Standard (Correct)
> **Standard**: NetworkClient is declared as an `actor`, strictly isolating mutable authentication state. The response payload conforms to immutable `Sendable`. The decoding logic is encapsulated in a `nonisolated static` method, ensuring it executes concurrently without capturing or blocking the caller's global actor.
```swift
import Foundation

// PRODUCTION FIX: Immutable Sendable DTO, isolated domain Actor, and nonisolated offloaded decoding.
public struct UserProfile: Sendable, Codable, Equatable {
    public let id: String
    public let name: String
    
    public init(id: String, name: String) {
        self.id = id
        self.name = name
    }
}

public actor NetworkClient {
    private var authToken: String?
    private let session: URLSession
    
    public init(session: URLSession = .shared) {
        self.session = session
    }
    
    public func updateToken(_ token: String?) {
        self.authToken = token
    }
    
    public func fetchUser(id: String) async throws -> UserProfile {
        guard let token = authToken else {
            throw URLError(.userAuthenticationRequired)
        }
        var request = URLRequest(url: URL(string: "https://api.example.com/users/\(id)")!)
        request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        
        let (data, response) = try await session.data(for: request)
        guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
            throw URLError(.badServerResponse)
        }
        
        // Guaranteed execution off MainActor to ensure zero frame-drops
        return try Self.decodeResponse(UserProfile.self, from: data)
    }
    
    private nonisolated static func decodeResponse<T: Decodable & Sendable>(
        _ type: T.Type,
        from data: Data
    ) throws -> T {
        let decoder = JSONDecoder()
        return try decoder.decode(T.self, from: data)
    }
}
```

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 Complete Data-Race Safety and Global Actor Isolation Standard

Swift 6 Complete Data-Race Safety and Global Actor Isolation Standard defines an industrial-grade behavioral standard for mobile engineering. Guarantees complete compile-time data race safety in Swift 6 by strictly enforcing Sendable conformance, explicit isolation boundaries, and nonisolated crossing patterns across networking pipelines. Prohibits unchecked shared mutable state and silent main-thread stalls during JSON parsing or background session execution. 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: Unchecked Sendable Bypasses and Implicit Main-Actor Capture in Asynchronous Networking Pipelines 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 DriftUnchecked Sendable Bypasses and Implicit Main-Actor Capture in Asynchronous Networking PipelinesCritical
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 compile with Swift 6 mode or `-strict-concurrency=complete` with zero warnings treated as errors.

Engineers MUST ALWAYS compile with Swift 6 mode or `-strict-concurrency=complete` with zero warnings treated as errors.

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 apply `@unchecked Sendable` to bypass compiler diagnostics without lock-based or dispatch-isolated internal synchronization accompanied by an architectural justification audit.

Engineers MUST NOT apply `@unchecked Sendable` to bypass compiler diagnostics without lock-based or dispatch-isolated internal synchronization accompanied by an architectural justification audit.

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

Data Transfer Objects (DTOs), API parameters, and network event streams MUST explicitly conform to `Sendable` using immutable `struct` or actor-isolated types.

Data Transfer Objects (DTOs), API parameters, and network event streams MUST explicitly conform to `Sendable` using immutable `struct` or actor-isolated types.

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

Heavy JSON/Protobuf decoding and response transformation MUST occur off the `@MainActor` via dedicated worker actors or `nonisolated` background functions before yielding state to UI binders.

Heavy JSON/Protobuf decoding and response transformation MUST occur off the `@MainActor` via dedicated worker actors or `nonisolated` background functions before yielding state to UI binders.

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

Stateful network managers, token refresh coordinators, and session state engines MUST be implemented as custom `actor` types, NEVER as mutable singleton reference classes.

Stateful network managers, token refresh coordinators, and session state engines MUST be implemented as custom `actor` types, NEVER as mutable singleton reference classes.

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

Delegates and completion handlers bridging legacy APIs (e.g., `URLSessionDelegate`) MUST explicitly declare actor isolation or use thread-safe non-isolated forwarding wrappers.

Delegates and completion handlers bridging legacy APIs (e.g., `URLSessionDelegate`) MUST explicitly declare actor isolation or use thread-safe non-isolated forwarding wrappers.

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 Complete Data-Race Safety and Global Actor Isolation Standard critical for AI coding assistants?

Guarantees complete compile-time data race safety in Swift 6 by strictly enforcing Sendable conformance, explicit isolation boundaries, and nonisolated crossing patterns across networking pipelines. Prohibits unchecked shared mutable state and silent main-thread stalls during JSON parsing or background session execution. 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 (Unchecked Sendable Bypasses and Implicit Main-Actor Capture in Asynchronous Networking Pipelines) 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