This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: swiftdata-actor-isolated-persistence-sync

Strict Actor Confinement & Background Synchronization in SwiftData (iOS 18)

Enforces strict ModelActor isolation and PersistentIdentifier passing across background sync pipelines and multi-window SwiftUI presentations in iOS 18. Eliminates cross-thread SQLite database locking, EXC_BAD_ACCESS exceptions, and multi-threaded write deadlocks by guaranteeing single-writer actor ownership and strictly preventing PersistentModel instances from crossing actor boundaries.

Prohibited Anti-Pattern: Passing Live PersistentModel References Across Concurrent Tasks and Capturing Main-Queue Contexts in Background Operations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Strict Actor Confinement & Background Synchronization in SwiftData (iOS 18) - Enforces strict ModelActor isolation and PersistentIdentifier passing across background sync pipelines and multi-window SwiftUI presentations in iOS 18. Eliminates cross-thread SQLite database locking, EXC_BAD_ACCESS exceptions, and multi-threaded write deadlocks by guaranteeing single-writer actor ownership and strictly preventing PersistentModel instances from crossing actor boundaries.
globs: **/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/swiftdata-actor-isolated-persistence-sync"
---

# Strict Actor Confinement & Background Synchronization in SwiftData (iOS 18)

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Passing Live PersistentModel References Across Concurrent Tasks and Capturing Main-Queue Contexts in Background Operations

## System Constraints
You are a Principal Mobile Architect enforcing iOS 18 Swift 6 strict concurrency and SwiftData persistence invariants. Mandate that all asynchronous background persistence operations use custom ModelActor implementations, transfer records exclusively through PersistentIdentifier or immutable DTOs, and forbid passing live PersistentModel instances across isolation boundaries to prevent SQLite thread contention and application crashes.

## Strict Guidelines
- Engineers MUST ALWAYS isolate background mutations and synchronization inside custom @ModelActor implementations bound to the shared ModelContainer.
- Engineers MUST NEVER pass live SwiftData PersistentModel instances across actor or concurrency boundaries; pass PersistentIdentifier or Sendable DTO values instead.
- Code MUST resolve PersistentIdentifier instances via modelContext.model(for:) within the destination actor before reading or modifying persistent state.
- Engineers MUST explicitly set autosaveEnabled to false on background ModelContext instances and invoke modelContext.save() atomically within error-handling blocks.
- Services MUST NOT execute multi-model batch processing or network ingestion directly on @MainActor or UI view scopes.
- Components NEVER capture the view's Environment ModelContext inside detached Task instances or dispatch queues.

## Bad vs Good Implementations
### Background Persistence Synchronization Pipeline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing live PersistentModel instances into a detached Task and executing modifications on a ModelContext originated from another actor violates Swift 6 strict concurrency. In SwiftData, concurrent access to the same managed object graph across arbitrary threads corrupts internal state and leads to SQLite locking deadlocks or EXC_BAD_ACCESS crashes.
```swift
import SwiftUI
import SwiftData

struct SyncService {
    let context: ModelContext
    
    // ANTI-PATTERN: Capturing main context into Task.detached and passing live PersistentModel
    func synchronizeItems(models: [ItemRecord]) {
        Task.detached {
            for model in models {
                // Concurrent mutation of model associated with another context/thread
                model.lastSyncedAt = .now
                model.status = "synchronized"
            }
            // Direct save on captured foreign context causes SQLite thread deadlock
            try? context.save()
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to strict actor isolation by defining a `@ModelActor` with an internal, isolated `ModelContext`. Instead of transmitting unconfined, non-Sendable `PersistentModel` instances, only Sendable `PersistentIdentifier` instances cross isolation boundaries. The target actor re-materializes models within its thread-confined context, preventing multi-threaded SQLite lock escalation and crashes.
```swift
import Foundation
import SwiftData

// PRODUCTION INVARIANT: Custom ModelActor isolating background mutations
@ModelActor
public actor BackgroundSyncActor {
    public func synchronizeItems(with identifiers: [PersistentIdentifier]) throws {
        // Disable autosave during batch mutations for explicit transaction control
        modelContext.autosaveEnabled = false
        
        for id in identifiers {
            // Re-fetch model inside this actor's dedicated context
            guard let model = modelContext.model(for: id) as? ItemRecord else {
                continue
            }
            model.lastSyncedAt = .now
            model.status = "synchronized"
        }
        
        if modelContext.hasChanges {
            try modelContext.save()
        }
    }
}

@MainActor
final class SyncCoordinator {
    private let syncActor: BackgroundSyncActor
    
    init(container: ModelContainer) {
        self.syncActor = BackgroundSyncActor(modelContainer: container)
    }
    
    func triggerSync(for items: [ItemRecord]) async throws {
        // Only send Sendable PersistentIdentifiers across actor boundaries
        let ids = items.map(\.persistentModelID)
        try await syncActor.synchronizeItems(with: ids)
    }
}
```

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: Strict Actor Confinement & Background Synchronization in SwiftData (iOS 18)

Strict Actor Confinement & Background Synchronization in SwiftData (iOS 18) defines an industrial-grade behavioral standard for mobile engineering. Enforces strict ModelActor isolation and PersistentIdentifier passing across background sync pipelines and multi-window SwiftUI presentations in iOS 18. Eliminates cross-thread SQLite database locking, EXC_BAD_ACCESS exceptions, and multi-threaded write deadlocks by guaranteeing single-writer actor ownership and strictly preventing PersistentModel instances from crossing actor boundaries. 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: Passing Live PersistentModel References Across Concurrent Tasks and Capturing Main-Queue Contexts in Background Operations 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 DriftPassing Live PersistentModel References Across Concurrent Tasks and Capturing Main-Queue Contexts in Background OperationsCritical
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 isolate background mutations and synchronization inside custom @ModelActor implementations bound to the shared ModelContainer.

Engineers MUST ALWAYS isolate background mutations and synchronization inside custom @ModelActor implementations bound to the shared ModelContainer.

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 NEVER pass live SwiftData PersistentModel instances across actor or concurrency boundaries

Engineers MUST NEVER pass live SwiftData PersistentModel instances across actor or concurrency boundaries; pass PersistentIdentifier or Sendable DTO values instead.

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 MUST resolve PersistentIdentifier instances via modelContext.model(for

Code MUST resolve PersistentIdentifier instances via modelContext.model(for:) within the destination actor before reading or modifying persistent 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.
4

Engineers MUST explicitly set autosaveEnabled to false on background ModelContext instances and invoke modelContext.save() atomically within error-handling blocks.

Engineers MUST explicitly set autosaveEnabled to false on background ModelContext instances and invoke modelContext.save() atomically within error-handling 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.
5

Services MUST NOT execute multi-model batch processing or network ingestion directly on @MainActor or UI view scopes.

Services MUST NOT execute multi-model batch processing or network ingestion directly on @MainActor or UI view scopes.

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

Components NEVER capture the view's Environment ModelContext inside detached Task instances or dispatch queues.

Components NEVER capture the view's Environment ModelContext inside detached Task instances or dispatch queues.

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 Strict Actor Confinement & Background Synchronization in SwiftData (iOS 18) critical for AI coding assistants?

Enforces strict ModelActor isolation and PersistentIdentifier passing across background sync pipelines and multi-window SwiftUI presentations in iOS 18. Eliminates cross-thread SQLite database locking, EXC_BAD_ACCESS exceptions, and multi-threaded write deadlocks by guaranteeing single-writer actor ownership and strictly preventing PersistentModel instances from crossing actor boundaries. 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 (Passing Live PersistentModel References Across Concurrent Tasks and Capturing Main-Queue Contexts in Background Operations) 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

Strict