Commit b74f0ac4ae

b74f0ac4ae1d6d024c71ed43c37ebd7b596aeb9d

parent: 31c6251b9a

Unsigned

cmc <hello@cleberg.net> · 2026-10-28 23:59 UTC

Age tombstone records out of the CloudKit zone after a year (!63)

Nothing ever deleted a tombstone record from the zone, so they accumulated
server-side for the life of the account (C5). The local ledger was already
bounded at 200 entries; the zone was not.

`CloudSyncMerge.partitionedTombstones` splits them at a 365-day window.
`pushMergedPayload` saves the live ones and adds the expired ones to the delete
list it already builds, so a single `modifyRecords` call does both — saving and
deleting the same record in one operation would contradict itself. Tombstones
are only ever written to the private database, so there is no shared-zone
permission case to handle.

## A tombstone the server has never seen never expires

Whatever its date. No server date means the deletion is still only on this
device, so ageing it out would discard the deletion itself rather than a record
of one — a device offline past the window would hand its deleted rows back on
the next sync.

This was not foreseen; it surfaced as two `CloudSyncStoreTests` failures on the
first attempt, both deletions recorded locally and never pushed, dropped on
save. Only a deletion the zone has held can be forgotten, which also makes the
window mean what it says: a year in which every online device had the chance to
see it.

## Why a fixed window

The finding proposed per-device acknowledgement so nothing is guessed. That
needs a production CloudKit schema addition, a device identity surviving
reinstalls (`identifierForVendor` does not), acknowledgement for `CKShare`
participants the owner cannot enumerate — and still a retirement window for a
device that goes silent forever, or one dead device pins every tombstone
permanently. It reduces to this with more moving parts.

The existing 200-entry ledger limit is already the same trade expressed as a
count: a device past 200 deletions drops its oldest with no acknowledgement
from anyone.

Also worth recording: the finding says these records are "re-fetched and
re-merged on every sync". `!7`'s per-zone `serverChangeToken` made that false —
after a device's first sync only changed records come down. The remaining cost
was storage and a one-off pull on a fresh device, which is why this is a window
rather than a schema change.

## Tests

Six in `CloudSyncMergeTests`: the window, the boundary (kept — resurrecting a
deleted row is the worse mistake), workflow tombstones, the all-recent case, the
unpushed case, and the constant itself so shortening it is deliberate.

383 tests green. `./Scripts/audit-a11y.sh` passes on both tiers with no enforced
failures. Ratchet unchanged at 280.

Closes #21 C5

Layout: unified · split

DomainDig/CloudSyncMerge.swift +52
@@ -102,6 +102,58 @@ enum CloudSyncMerge {
102 /// How many tombstones the local ledger keeps. 102 /// How many tombstones the local ledger keeps.
103 static let tombstoneLedgerLimit = 200 103 static let tombstoneLedgerLimit = 200
104 104
105 /// How long a tombstone record stays in the zone before it is deleted.
106 ///
107 /// Any retention shorter than a device's longest gap between syncs
108 /// resurrects rows it deleted, because the merge rule is
109 /// `row.updatedAt > tombstone.deletedAt` and a forgotten deletion loses to
110 /// a row that is still being synced. A year is chosen to be longer than any
111 /// plausible gap for a device still in use.
112 ///
113 /// The alternative, acknowledging each device's last sync so nothing is
114 /// guessed, needs a production CloudKit schema addition, a device identity
115 /// that survives reinstalls, acknowledgement for `CKShare` participants the
116 /// owner cannot enumerate — and still a window for a device that goes
117 /// silent forever, or one dead device pins every tombstone. It reduces to
118 /// this with more moving parts.
119 ///
120 /// Note that the ledger limit above is already the same trade expressed as
121 /// a count: a device past 200 deletions drops its oldest tombstones with no
122 /// acknowledgement from anyone.
123 static let tombstoneRetention: TimeInterval = 365 * 24 * 60 * 60
124
125 /// Splits tombstones into the ones still inside the retention window and
126 /// the ones whose record can be deleted from the zone.
127 ///
128 /// **A tombstone the server has never seen never expires**, whatever its
129 /// date. No server date means the deletion is still only on this device, so
130 /// ageing it out would discard the deletion itself rather than a record of
131 /// it — a device offline past the window would hand its deleted rows back
132 /// on the next sync. Only a deletion the zone has held can be forgotten,
133 /// which also makes the window mean what it says: a year during which every
134 /// online device had the chance to see it.
135 ///
136 /// A tombstone exactly at the boundary is kept: of the two possible
137 /// mistakes, resurrecting a row the user deleted is the worse one, which is
138 /// the same tie-break `applyTrackedDomainTombstones` makes.
139 static func partitionedTombstones(
140 _ tombstones: [SyncRow<SyncTombstone>],
141 now: Date,
142 retention: TimeInterval = tombstoneRetention
143 ) -> (kept: [SyncRow<SyncTombstone>], expired: [SyncRow<SyncTombstone>]) {
144 let cutoff = now.addingTimeInterval(-retention)
145 var kept: [SyncRow<SyncTombstone>] = []
146 var expired: [SyncRow<SyncTombstone>] = []
147 for tombstone in tombstones {
148 if tombstone.orderKey.serverDate != nil, tombstone.value.deletedAt < cutoff {
149 expired.append(tombstone)
150 } else {
151 kept.append(tombstone)
152 }
153 }
154 return (kept, expired)
155 }
156
105 // MARK: Rows 157 // MARK: Rows
106 158
107 static func mergeTrackedDomains( 159 static func mergeTrackedDomains(
DomainDig/CloudSyncService.swift +20 −4
@@ -661,7 +661,7 @@ final class CloudSyncService {
661 /// Returns the server-assigned modification date of every record the push 661 /// Returns the server-assigned modification date of every record the push
662 /// saved, keyed by record name. Those dates are what the next sync orders 662 /// saved, keyed by record name. Those dates are what the next sync orders
663 /// its conflicts by. 663 /// its conflicts by.
664 private func pushMergedPayload(_ payload: SyncPayload) async throws -> [String: Date] { 664 private func pushMergedPayload(_ payload: SyncPayload, now: Date = Date()) async throws -> [String: Date] {
665 guard let privateDatabase = cloudKitDatabase(in: .privateDatabase) else { 665 guard let privateDatabase = cloudKitDatabase(in: .privateDatabase) else {
666 throw CloudSyncRuntimeError.missingEntitlement 666 throw CloudSyncRuntimeError.missingEntitlement
667 } 667 }
@@ -698,7 +698,20 @@ final class CloudSyncService {
698 privateRecordsToSave.append(makeMonitoringSettingsRecord(payload.monitoringSettings.value)) 698 privateRecordsToSave.append(makeMonitoringSettingsRecord(payload.monitoringSettings.value))
699 privateRecordsToSave.append(contentsOf: payload.notesByDomain.values.map { makeDomainNoteRecord($0.value) }) 699 privateRecordsToSave.append(contentsOf: payload.notesByDomain.values.map { makeDomainNoteRecord($0.value) })
700 privateRecordsToSave.append(contentsOf: payload.historyMetadataByDomain.values.map { makeHistoryMetadataRecord($0.value) }) 700 privateRecordsToSave.append(contentsOf: payload.historyMetadataByDomain.values.map { makeHistoryMetadataRecord($0.value) })
701 privateRecordsToSave.append(contentsOf: payload.tombstones.map { makeTombstoneRecord($0.value) }) 701 // Expired tombstones are deleted from the zone rather than re-saved;
702 // saving and deleting the same record in one operation would contradict
703 // itself. The rows they refer to are still deleted below, so the row
704 // goes before the record that remembers it did.
705 let agedTombstones = CloudSyncMerge.partitionedTombstones(payload.tombstones, now: now)
706 privateRecordsToSave.append(contentsOf: agedTombstones.kept.map { makeTombstoneRecord($0.value) })
707 for tombstone in agedTombstones.expired.map(\.value) {
708 recordIDsToDelete.append(
709 CKRecord.ID(
710 recordName: tombstoneRecordName(for: tombstone.entityType, identifier: tombstone.identifier),
711 zoneID: customZoneID
712 )
713 )
714 }
702 715
703 for tombstone in payload.tombstones.map(\.value) { 716 for tombstone in payload.tombstones.map(\.value) {
704 switch tombstone.entityType { 717 switch tombstone.entityType {
@@ -849,8 +862,11 @@ final class CloudSyncService {
849 return tombstones 862 return tombstones
850 } 863 }
851 864
852 private func saveTombstones(_ tombstones: [SyncRow<SyncTombstone>]) { 865 private func saveTombstones(_ tombstones: [SyncRow<SyncTombstone>], now: Date = Date()) {
853 if let data = try? encoder.encode(CloudSyncMerge.newestTombstones(tombstones).map(\.value)) { 866 // Dropped locally as well as in the zone: a tombstone kept here would be
867 // re-uploaded on the next push, right after that push deleted it.
868 let kept = CloudSyncMerge.partitionedTombstones(tombstones, now: now).kept
869 if let data = try? encoder.encode(CloudSyncMerge.newestTombstones(kept).map(\.value)) {
854 defaults.set(data, forKey: StorageKey.tombstones) 870 defaults.set(data, forKey: StorageKey.tombstones)
855 } 871 }
856 } 872 }
DomainDigTests/CloudSyncMergeTests.swift +89
@@ -198,6 +198,95 @@ final class CloudSyncMergeTests: XCTestCase {
198 XCTAssertNil(updated.first?.value.lastKnownAvailability) 198 XCTAssertNil(updated.first?.value.lastKnownAvailability)
199 } 199 }
200 200
201 // MARK: Tombstone retention
202
203 /// The window is what stops the zone growing without bound. A tombstone
204 /// older than it is deleted from the zone; everything newer stays, because
205 /// forgetting a deletion resurrects the row.
206 func testATombstoneOlderThanTheWindowExpires() {
207 let now = at(0)
208 let old = tombstoneRow(.trackedDomain, "old.example", serverDate: now.addingTimeInterval(-400 * 86_400), deviceDate: now.addingTimeInterval(-400 * 86_400))
209 let recent = tombstoneRow(.trackedDomain, "recent.example", serverDate: now.addingTimeInterval(-10 * 86_400), deviceDate: now.addingTimeInterval(-10 * 86_400))
210
211 let partitioned = CloudSyncMerge.partitionedTombstones([old, recent], now: now)
212
213 XCTAssertEqual(partitioned.kept.map(\.value.identifier), ["recent.example"])
214 XCTAssertEqual(partitioned.expired.map(\.value.identifier), ["old.example"])
215 }
216
217 /// A tombstone exactly on the boundary is kept. Of the two mistakes
218 /// available, resurrecting a row the user deleted is the worse one — the
219 /// same tie-break `applyTrackedDomainTombstones` makes.
220 func testATombstoneExactlyOnTheBoundaryIsKept() {
221 let now = at(0)
222 let boundary = tombstoneRow(
223 .trackedDomain,
224 "boundary.example",
225 serverDate: now.addingTimeInterval(-CloudSyncMerge.tombstoneRetention),
226 deviceDate: now.addingTimeInterval(-CloudSyncMerge.tombstoneRetention)
227 )
228
229 let partitioned = CloudSyncMerge.partitionedTombstones([boundary], now: now)
230
231 XCTAssertEqual(partitioned.kept.map(\.value.identifier), ["boundary.example"])
232 XCTAssertTrue(partitioned.expired.isEmpty)
233 }
234
235 /// Workflows carry tombstones too, and the window applies to the record
236 /// regardless of what it refers to.
237 func testTheWindowAppliesToWorkflowTombstones() {
238 let now = at(0)
239 let old = tombstoneRow(.workflow, "flow-1", serverDate: now.addingTimeInterval(-400 * 86_400), deviceDate: now.addingTimeInterval(-400 * 86_400))
240
241 XCTAssertEqual(
242 CloudSyncMerge.partitionedTombstones([old], now: now).expired.map(\.value.identifier),
243 ["flow-1"]
244 )
245 }
246
247 /// Nothing is dropped on a device that has only ever deleted rows
248 /// recently, which is the common case and must stay free of churn.
249 func testRecentDeletionsAreAllKept() {
250 let now = at(0)
251 let rows = (1...5).map { index in
252 tombstoneRow(
253 .trackedDomain,
254 "row-\(index).example",
255 serverDate: now.addingTimeInterval(-Double(index) * 86_400),
256 deviceDate: now.addingTimeInterval(-Double(index) * 86_400)
257 )
258 }
259
260 let partitioned = CloudSyncMerge.partitionedTombstones(rows, now: now)
261
262 XCTAssertEqual(partitioned.kept.count, 5)
263 XCTAssertTrue(partitioned.expired.isEmpty)
264 }
265
266 /// The deletion is still only on this device, so ageing it out would throw
267 /// away the deletion rather than a record of one — and the row would come
268 /// back from another device on the next sync.
269 func testADeletionTheServerHasNeverSeenNeverExpires() {
270 let now = at(0)
271 let unpushed = tombstoneRow(
272 .trackedDomain,
273 "offline.example",
274 serverDate: nil,
275 deviceDate: now.addingTimeInterval(-4_000 * 86_400)
276 )
277
278 let partitioned = CloudSyncMerge.partitionedTombstones([unpushed], now: now)
279
280 XCTAssertEqual(partitioned.kept.map(\.value.identifier), ["offline.example"])
281 XCTAssertTrue(partitioned.expired.isEmpty)
282 }
283
284 /// A year, stated as a test so a change to the constant is a deliberate
285 /// one rather than a silent shortening of everyone's safe offline window.
286 func testTheRetentionWindowIsAYear() {
287 XCTAssertEqual(CloudSyncMerge.tombstoneRetention, 365 * 24 * 60 * 60)
288 }
289
201 // MARK: Fixtures 290 // MARK: Fixtures
202 291
203 private func at(_ offset: TimeInterval) -> Date { 292 private func at(_ offset: TimeInterval) -> Date {