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

Swift 6 SwiftData Actor-Isolated CloudKit Delta Ingestion Invariant

Enforces complete compile-time actor isolation for SwiftData model contexts during background CloudKit delta payload ingestion and local store reconciliation. Prohibits crossing actor boundaries with non-Sendable @Model instances and mandates dedicated @ModelActor execution contexts to eliminate data race heap corruption in Swift 6.

Prohibited Anti-Pattern: Mutating Shared ModelContexts or Passing Non-Sendable @Model Instances Across Task Boundaries During Remote Ingestion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: "Swift 6 SwiftData Actor-Isolated CloudKit Delta Ingestion Invariant - Enforces complete compile-time actor isolation for SwiftData model contexts during background CloudKit delta payload ingestion and local store reconciliation. Prohibits crossing actor boundaries with non-Sendable @Model instances and mandates dedicated @ModelActor execution contexts to eliminate data race heap corruption in Swift 6."
globs: "**/*.swift"
alwaysApply: true
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/swift6-swiftdata-cloudkit-actor-isolation"
---

# Swift 6 SwiftData Actor-Isolated CloudKit Delta Ingestion Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Mutating Shared ModelContexts or Passing Non-Sendable @Model Instances Across Task Boundaries During Remote Ingestion

## System Constraints
You are a Principal Software Architect enforcing Swift 6 Complete Concurrency and SwiftData persistence invariants. Mandate that all CloudKit background delta synchronization occurs within dedicated @ModelActor boundaries. You must strictly disallow non-Sendable PersistentModel references from crossing actor isolation domains, requiring all cross-boundary synchronization to use Sendable DTOs, CKRecord primitives, or PersistentIdentifier handles.

## Strict Guidelines
- Engineers MUST ALWAYS isolate background CloudKit sync workloads inside a dedicated custom actor decorated with @ModelActor.
- Engineers MUST NEVER access or mutate the main thread's ModelContainer.mainContext from background tasks, Task.detached closures, or CloudKit operation callbacks.
- Engineers MUST NOT pass concrete @Model reference types across actor boundaries; instances MUST be transferred solely via PersistentIdentifier and re-fetched inside the target actor isolation domain.
- Sync services MUST process CKRecordZone.ChangeToken deltas into Sendable immutable value-type intermediate payloads before dispatching to the @ModelActor ingestion engine.
- Sync actors MUST disable automatic saving during high-throughput delta reconciliation and explicitly commit changes via try modelContext.save() wrapped in structured do/catch blocks.
- UI components NEVER listen to raw background sync notifications directly; they MUST observe local SwiftData state via @Query on the @MainActor or consume typed Sendable synchronization state events.

## Bad vs Good Implementations
### CloudKit Delta Reconciliation Actor Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Mutating `container.mainContext` from an asynchronous background task introduces severe data races and violates Swift 6 actor-isolation constraints. Non-Sendable `@Model` instances are manipulated concurrently without synchronization.
```swift
import SwiftData
import CloudKit

final class CloudKitSyncManager {
    let container: ModelContainer

    init(container: ModelContainer) {
        self.container = container
    }

    // CRITICAL BUG: Main-actor context mutated in unstructured concurrency;
    // passing unconstrained @Model across boundaries violates Swift 6 strict concurrency.
    func ingestChanges(records: [CKRecord]) async {
        Task.detached {
            let context = self.container.mainContext
            for record in records {
                if let existing = try? context.fetch(FetchDescriptor<Item>()).first(where: { $0.id == record.recordID.recordName }) {
                    existing.updatedAt = record.modificationDate ?? Date()
                } else {
                    let newItem = Item(id: record.recordID.recordName, updatedAt: record.modificationDate ?? Date())
                    context.insert(newItem)
                }
            }
            try? context.save()
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The `@ModelActor` macro guarantees that the `modelContext` is accessed exclusively within the actor's serial isolation domain. Inputs are immutable and `Sendable`, and cross-boundary outputs are restricted to `PersistentIdentifier` values, ensuring complete Swift 6 safety.
```swift
import SwiftData
import CloudKit

// Sendable intermediate payload preserving strict isolation boundaries
struct IngestibleItemPayload: Sendable {
    let id: String
    let timestamp: Date
}

@ModelActor
actor CloudKitSyncActor {
    // @ModelActor automatically synthesizes: nonisolated let modelExecutor: any ModelExecutor
    // and nonisolated let modelContainer: ModelContainer, with an isolated modelContext.

    public func reconcileDeltas(_ payloads: [IngestibleItemPayload]) throws -> [PersistentIdentifier] {
        var mutatedIdentifiers: [PersistentIdentifier] = []
        
        for payload in payloads {
            let targetId = payload.id
            let predicate = #Predicate<Item> { $0.id == targetId }
            var descriptor = FetchDescriptor<Item>(predicate: predicate)
            descriptor.fetchLimit = 1
            
            if let existing = try modelContext.fetch(descriptor).first {
                existing.updatedAt = payload.timestamp
                mutatedIdentifiers.append(existing.persistentModelID)
            } else {
                let newItem = Item(id: payload.id, updatedAt: payload.timestamp)
                modelContext.insert(newItem)
                try modelContext.save() // Materialize permanent identifier
                mutatedIdentifiers.append(newItem.persistentModelID)
            }
        }
        
        if modelContext.hasChanges {
            try modelContext.save()
        }
        
        // Only return Sendable PersistentIdentifier values across actor boundaries
        return mutatedIdentifiers
    }
}
```

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: Swift 6 SwiftData Actor-Isolated CloudKit Delta Ingestion Invariant

Swift 6 SwiftData Actor-Isolated CloudKit Delta Ingestion Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces complete compile-time actor isolation for SwiftData model contexts during background CloudKit delta payload ingestion and local store reconciliation. Prohibits crossing actor boundaries with non-Sendable @Model instances and mandates dedicated @ModelActor execution contexts to eliminate data race heap corruption in Swift 6. 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: Mutating Shared ModelContexts or Passing Non-Sendable @Model Instances Across Task Boundaries During Remote Ingestion 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 DriftMutating Shared ModelContexts or Passing Non-Sendable @Model Instances Across Task Boundaries During Remote IngestionCritical
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 CloudKit sync workloads inside a dedicated custom actor decorated with @ModelActor.

Engineers MUST ALWAYS isolate background CloudKit sync workloads inside a dedicated custom actor decorated with @ModelActor.

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 access or mutate the main thread's ModelContainer.mainContext from background tasks, Task.detached closures, or CloudKit operation callbacks.

Engineers MUST NEVER access or mutate the main thread's ModelContainer.mainContext from background tasks, Task.detached closures, or CloudKit operation 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.
3

Engineers MUST NOT pass concrete @Model reference types across actor boundaries

Engineers MUST NOT pass concrete @Model reference types across actor boundaries; instances MUST be transferred solely via PersistentIdentifier and re-fetched inside the target actor isolation domain.

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

Sync services MUST process CKRecordZone.ChangeToken deltas into Sendable immutable value-type intermediate payloads before dispatching to the @ModelActor ingestion engine.

Sync services MUST process CKRecordZone.ChangeToken deltas into Sendable immutable value-type intermediate payloads before dispatching to the @ModelActor ingestion engine.

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

Sync actors MUST disable automatic saving during high-throughput delta reconciliation and explicitly commit changes via try modelContext.save() wrapped in structured do/catch blocks.

Sync actors MUST disable automatic saving during high-throughput delta reconciliation and explicitly commit changes via try modelContext.save() wrapped in structured do/catch 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.
6

UI components NEVER listen to raw background sync notifications directly

UI components NEVER listen to raw background sync notifications directly; they MUST observe local SwiftData state via @Query on the @MainActor or consume typed Sendable synchronization state events.

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 SwiftData Actor-Isolated CloudKit Delta Ingestion Invariant critical for AI coding assistants?

Enforces complete compile-time actor isolation for SwiftData model contexts during background CloudKit delta payload ingestion and local store reconciliation. Prohibits crossing actor boundaries with non-Sendable @Model instances and mandates dedicated @ModelActor execution contexts to eliminate data race heap corruption in Swift 6. 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 (Mutating Shared ModelContexts or Passing Non-Sendable @Model Instances Across Task Boundaries During Remote Ingestion) 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