A chef built tomorrow’s prep list on an iPad in a kitchen with no signal. In the office, the Mac opened before its first import and created its own “Tomorrow” list. When the devices met, both lists appeared. One of them looked empty, because its items had not finished importing. Someone deleted it, and with it went the morning shift’s work.

Nothing failed. SwiftData saved both lists locally. CloudKit exported both and imported both. Each component kept its promise, and the chef still lost an afternoon.

The sync engine owns records. It does not own the meaning of “the same list.” That question belongs to the domain, and until the domain answers it, two honest copies will look like a duplicate to be thrown away.

Start with what the local store promises

SwiftData’s CloudKit integration mirrors a local store to the person’s private iCloud database. A successful local save is a complete answer for this device. Export and import happen later, on the system’s schedule, and the app keeps working while another device holds older data. Account availability tells you that sync can happen, not that it has.

That has consequences for the schema. A CloudKit-backed model cannot use unique constraints, because two offline devices can each create a valid row and neither is wrong. Every attribute needs a default or must be optional, relationships must be optional with explicit inverses, and the deny delete rule is not available.

SwiftGitHub
import Foundation
import SwiftData

@Model
final class PrepList {
    var recordID: UUID = UUID()
    var kitchenID: UUID = UUID()
    var serviceDay: String = ""      // yyyy-MM-dd in the kitchen’s time zone
    var shift: String = "morning"
    var createdAt: Date = Date.now
    var deletedAt: Date?
    @Relationship(deleteRule: .cascade, inverse: \PrepItem.list)
    var items: [PrepItem]? = []

    init(kitchenID: UUID, serviceDay: String, shift: String) {
        self.kitchenID = kitchenID
        self.serviceDay = serviceDay
        self.shift = shift
    }

    var logicalKey: String { "\(kitchenID)|\(serviceDay)|\(shift)" }
}

@Model
final class PrepItem {
    var itemID: UUID = UUID()
    var name: String = ""
    var quantity: Int = 0
    var editedAt: Date = Date.now
    var deletedAt: Date?
    var list: PrepList?

    init(name: String, quantity: Int) {
        self.name = name
        self.quantity = quantity
    }
}

Derived indexes, per-window state, and anything that should never leave the device belong in a separate local configuration. Relationships that would cross between the synced and local stores are resolved by product identity, never by object reference.

Give each record two identities

The schema already shows the decision. Each list has two identities.

A logical identity answers which prep list the kitchen meant: the kitchen, the service day in that kitchen’s time zone, and the shift. “Tomorrow” computed in the device’s time zone is a bug waiting for the first chef who travels.

A record identity distinguishes rows that were created independently. It is assigned once, at creation, and synced as an immutable value.

When two records share a logical key, every device must pick the same survivor, whatever order the rows arrived in:

SwiftGitHub
import Foundation

struct PrepListRecord: Sendable {
    let logicalKey: String
    let recordID: UUID
    let createdAt: Date
}

func canonicalRecord(
    in records: [PrepListRecord], for key: String
) -> PrepListRecord? {
    records.lazy.filter { $0.logicalKey == key }.min { lhs, rhs in
        if lhs.createdAt != rhs.createdAt {
            return lhs.createdAt < rhs.createdAt
        }
        return lhs.recordID.uuidString < rhs.recordID.uuidString
    }
}

The logical key cannot break a tie inside the group it defines. The record ID can. Creation time gives a stable preference among the rows a device can see. It is a preference, not evidence of which edit is newer.

Merge the work, then retire the copy

Choosing a survivor solves half the problem. The other row may hold an item, a quantity, or a deletion that has not reached anyone else. Deleting it before its contents are merged is the original loss with better manners.

So items have their own stable identity, and deletion is a fact that syncs rather than an absence:

SwiftGitHub
import Foundation

struct ItemState: Equatable, Sendable {
    let itemID: UUID
    var name: String
    var quantity: Int
    var editedAt: Date
    var deletedAt: Date?
}

enum MergeOutcome: Equatable, Sendable {
    case merged(ItemState)
    case conflict(ItemState, ItemState)
}

func merge(_ a: ItemState, _ b: ItemState) -> MergeOutcome {
    precondition(a.itemID == b.itemID)
    switch (a.deletedAt, b.deletedAt) {
    case let (deleted?, nil) where b.editedAt > deleted:
        return .conflict(a, b)          // edited after it was deleted: the chef decides
    case let (nil, deleted?) where a.editedAt > deleted:
        return .conflict(b, a)
    case let (first?, second?):
        return .merged(first <= second ? a : b)   // both deleted: every device keeps the earlier deletion
    case (_?, nil):
        return .merged(a)
    case (nil, _?):
        return .merged(b)
    case (nil, nil):
        break
    }
    guard a.name != b.name || a.quantity != b.quantity else { return .merged(a) }
    if a.editedAt == b.editedAt { return .conflict(a, b) }
    return .merged(a.editedAt > b.editedAt ? a : b)
}

The timestamps here come from different devices, so they order nothing absolutely. They are good enough to settle routine edits and too weak to settle a deletion against an edit made after it. That case becomes a conflict the chef sees, because a wrong guess there removes work silently.

The reconciliation itself is one repeatable operation: move the items of the retired copy into the survivor, merge items that share an itemID, mark the retired list deleted, and save. Run it again and nothing changes. Physical deletion waits for a retention window, and until then a recently deleted list can be restored. That is also why the retired list is marked, not deleted: the .cascade rule in the model fires only on physical deletion. Run it during a partial import and it removes the very items the reconciler was meant to save.

Run the merge on two devices with the arguments in either order, and the result must be the same. That is why two deletions keep the earlier one instead of whichever came first in the call.

Templates stay local. A synced list is created from a template only when the chef asks for it, which removes the most common source of twins: two devices creating “Tomorrow” on launch.

Test schema changes and account changes

Deploy compatible schema additions to the CloudKit Production environment before any build relies on them, give new fields defaults, and test a mixed-version pair of devices. Renaming a local model and changing the production schema are two migrations, and only one of them can be undone.

Then test the conditions that created the bug, on two devices with a test account:

  • seed the second device before its first import, and create the same logical list on both;
  • edit the same list offline on both, then reconnect in each order;
  • delete an item on one device and edit it on the other;
  • sign out of iCloud with unsynced local work, and record what remains on each OS version you support.

Assert on what survives, not on what the screen shows.

What to ask of your own code

  • What does “the same” mean for each synced entity, and is that meaning computed in the right time zone?
  • Can two devices ever choose different survivors for the same logical key?
  • Does any path delete a copy before its contents are merged?
  • Is a deletion a synced fact, or only a missing row?
  • What evidence does the interface use before it says “Up to date”?

“Saved on this iPad” is something the app knows. “Up to date” is a claim about another device, and it deserves evidence for the specific change. The chef’s afternoon depends on the difference.

References

If this edition sharpened your next review, you can buy me a coffee.