For the past while I've been testing CKSyncEngine for a reading app of mine, with two iPads on the same iCloud account and a library of about 14,000 books, and most of it behaved the way Apple's docs and the WWDC session describe. The part that didn't is what happens when the record zone your data lives in gets deleted, so these are my notes on how that deletion reaches the app, and on what went wrong when we tried to recover from it.
How a deleted zone reaches you
There are two ways the engine tells you the zone is gone. On the read path it comes as a database change, with a reason attached, and the reason decides what we do next. Only .deleted means "recreate the zone and upload again", since .purged (the user deleted the app's iCloud data) and .encryptedDataReset (the user reset their encryption keys) mean the user wants that data gone, so for those we stop syncing instead:
func handleEvent(_ event: CKSyncEngine.Event, syncEngine: CKSyncEngine) async {
switch event {
case .fetchedDatabaseChanges(let changes):
for deletion in changes.deletions where deletion.zoneID == libraryZoneID {
switch deletion.reason {
case .deleted: // another device deleted it, so recreate it and upload again
await beginReset(.zoneLost)
default: // .purged or .encryptedDataReset: stop syncing, don't recreate
await seal(deletion.reason)
}
}
// ...
default:
break
}
}
On the write path it comes as a failed save, when the engine tries to send a record into a zone that no longer exists, and there are two error codes for it:
case .sentRecordZoneChanges(let sent):
let zoneMissing = sent.failedRecordSaves.contains { failed in
failed.record.recordID.zoneID == libraryZoneID
&& (failed.error.code == .zoneNotFound || failed.error.code == .userDeletedZone)
}
if zoneMissing {
await beginReset(.zoneLost)
}
Apple's guidance is that the client handles the deletion and recreates the zone, and for .deleted that's what we set out to test, with one iPad deleting the zone and the other noticing it. When the delete came from the other device, the second iPad got fetchedDatabaseChanges with .deleted about two seconds after the fetch started.
My first attempt at this test went sideways (I deleted the zone in the CloudKit Console instead, six fetches over 50 minutes came back empty, and I wrote it down as "a zone deleted out of band is invisible on read" before the container's operation log showed the Console had been signed into my second test Apple ID the whole time, so I had deleted a zone in a different account). So, if you test this through the Console, check that the owner record name it shows matches the account the device is signed into before you delete anything, and have the app log which account it resolved at start (an index or a hash, never the record ID itself), because otherwise neither the app nor you can tell.
Note: deleting the app's data from Settings, Apple ID, iCloud, Manage Storage didn't purge a Development zone for us and never delivered
.purged, on two accounts. If you want to see.purgedyou'll have to test it against Production.
Don't wait for your own delegate callback
The first real deletion hung the app for 20 minutes, and it took a while to see why. Our reset started by bumping a generation counter, which cancelled every in-flight engine operation and waited for all of them to finish, which seemed like the safe thing to do before wiping state:
func beginReset(_ reason: ResetReason) async {
await setPhase(.resetting)
await bumpGeneration(excluding: nil)
resetTask = Task { await self.runReset(reason) }
}
func bumpGeneration(excluding own: Operation?) async {
generation += 1
let doomed = inFlight.filter { $0.key != own }
for task in doomed.values { task.cancel() }
for task in doomed.values { await task.value } // never returns
// ...
}
The problem is where beginReset is being called from. The deletion arrives inside handleEvent, and handleEvent is running because a fetch we started (and registered in inFlight) is suspended in engine.fetchChanges(). That call can't return until handleEvent returns, and handleEvent is now waiting for that same task, so it waits forever, and cancelling doesn't help because the task isn't doing anything cancellable, it's waiting on us.
Our start path already guarded against this exact cycle (it passes itself as excluding and removes its own task from the map before replaying deferred events), but a delegate callback doesn't know which operation it's running under, so the fix was to count how deep we are in delegate callbacks and, while we're inside one, cancel the tasks that may be parked in an engine call without waiting for them:
func handleEvent(_ event: CKSyncEngine.Event, syncEngine: CKSyncEngine) async {
engineCallbackDepth += 1
defer { engineCallbackDepth -= 1 }
// ...
}
func bumpGeneration(excluding own: Operation?) async {
generation += 1
let doomed = inFlight.filter { $0.key != own }
for task in doomed.values { task.cancel() }
let insideCallback = engineCallbackDepth > 0
for (operation, task) in doomed where !(insideCallback && operation.mayBeParkedInAnEngineCall) {
await task.value
}
// ...
}
Skipping the wait is safe because the wait only ever bought quiescence, and what keeps a cancelled task from writing into the new state is the generation check it does after every await. The same shape shows up anywhere an event drives a state change (a zoneNotFound from a send, a sign-out from accountChange), and the same rule applies to cancelling a reset that's already running. The advice I gave myself at the time, to just press Fetch again if the deletion didn't show up, was wrong as well, since that press is exactly what deadlocked.
Don't recreate the zone on the engine that saw it deleted
With the deadlock gone, the reset for .zoneLost did what we designed it to do. The reset task the event started cleared the saved server record from every row of our sync metadata table (the zone is gone, so those system fields point at nothing), queued the zone to be saved again on the same engine and asked it to send:
// runReset(.zoneLost), on the engine that just reported the deletion
let rows = try await syncMetadata.allRows()
try await syncMetadata.upsert(rows: rows.map { var row = $0; row.lastKnownServerRecord = nil; return row })
engine.state.add(pendingDatabaseChanges: [.saveZone(CKRecordZone(zoneID: libraryZoneID))])
try await engine.sendChanges(.init())
// ...and only after the reset completes, re-queue every local row
That crashed with EXC_BREAKPOINT, a Swift assertion failure two frames deep inside CloudKit, reached from our sendChanges call, on iPadOS 26.6.1. The crash report had no assertion message, so I can only describe it by what triggers it: saving a zone through the same engine that has just processed that zone's deletion. It isn't zone saves in general, since the deleting iPad saved the same zone twice and deleted it once on the same build without trapping, and the second iPad saved the zone cleanly after a relaunch, with a new engine.
So the direction is to let the current engine go and recreate the zone from a new one, the way the relaunch did. This is the shape I'd try, with a clean state as the conservative choice:
func recreateAfterZoneLoss() async throws {
await stopEngine() // the old engine and its persisted state go away
let config = CKSyncEngine.Configuration(
database: container.privateCloudDatabase,
stateSerialization: nil, // start clean
delegate: self
)
let engine = CKSyncEngine(config)
engine.state.add(pendingDatabaseChanges: [.saveZone(CKRecordZone(zoneID: libraryZoneID))])
engine.state.add(pendingRecordZoneChanges: allLocalRecordIDs().map { .saveRecord($0) })
self.engine = engine
}
I haven't run that version on a device yet, so take it as where the evidence points and not as something I've watched work.
The reset has to survive being interrupted
The crash turned out to be useful, because it showed a hole in our own reset that's worse than the assertion. Our .zoneLost arm cleared the server records first and re-queued the rows only at the very end, so the crash landed between the two and left all 14,001 rows on the device with no server record and nothing in the pending set.
Nothing put them back. Our reconciliation, which runs at every start, re-adds rows that are missing from the sync index, and these rows weren't missing, they were present with no server record, so the next start logged that it rebuilt 0 rows and went on as if everything was fine. That iPad then held a whole library that existed nowhere on the server and would never upload it again, and a sign-out, a jetsam or the user killing the app in the same window would do the same thing.
Reconciliation should look at whether a row has a server record, not only whether the row exists. A local row with no saved server record and no pending save is a row that will never sync, whatever the reason it got that way, so finding those rows at start and queueing them again closes the window no matter where the reset was interrupted. The alternative, keeping a durable "reset in progress" marker and finishing the reset on the next start, works too, though every reset arm then has to set and clear that marker in the right place, and the presence check is the one I'd want even with the marker.
Detecting the deletion turned out to be the easy part, as long as we look at the reason and treat only .deleted as "recreate". The recovery is where it goes wrong, and it needs three things I didn't get from the docs: a state change triggered from inside a delegate callback must not wait for a task that's parked in the engine call delivering that callback, the zone has to be recreated on a new engine rather than the one that just reported it gone, and every step of the reset has to be safe to cut off halfway, which in practice means reconciliation that checks each row for a server record and not just that the row exists.
Top comments (0)