Repository Public License
1import Foundation2import NavigatorCore3import Persistence4import Testing5@testable import SyncEngine67@Suite struct SyncMergeRuleTests {8 func stamp(_ version: Int64, at time: Double = 100, device: String = "A", deleted: Bool = false, hash: String? = "h", id: String = "x") -> SyncStamp {9 SyncStamp(entity: .note, entityID: id, version: version, deviceID: device, modifiedAt: time, deletedAt: deleted ? time : nil, payloadHash: deleted ? nil : hash)10 }1112 @Test func precedenceIsVersionThenTimeThenDeviceThenDeletion() {13 #expect(SyncMerge.wins(stamp(2), over: stamp(1, at: 999, device: "Z")))14 #expect(!SyncMerge.wins(stamp(1, at: 999, device: "Z"), over: stamp(2)))15 #expect(SyncMerge.wins(stamp(1, at: 101), over: stamp(1, at: 100, device: "Z")))16 #expect(SyncMerge.wins(stamp(1, device: "B"), over: stamp(1, device: "A")))17 #expect(!SyncMerge.wins(stamp(1, device: "A"), over: stamp(1, device: "B")))18 // Exact tie on version, time and device: the deletion wins, in both directions of arrival.19 #expect(SyncMerge.wins(stamp(1, deleted: true), over: stamp(1)))20 #expect(!SyncMerge.wins(stamp(1), over: stamp(1, deleted: true)))21 // An edit made knowing of the deletion (higher version) brings the item back.22 #expect(SyncMerge.wins(stamp(2), over: stamp(1, deleted: true)))23 #expect(!SyncMerge.wins(stamp(1, at: 500), over: stamp(2, at: 1, deleted: true)))24 // Equal stamps: nothing to do (idempotence).25 #expect(!SyncMerge.wins(stamp(1), over: stamp(1)))26 #expect(SyncMerge.wins(stamp(1), over: nil))27 #expect(SyncMerge.wins(stamp(1, hash: "b"), over: stamp(1, hash: "a")))28 // The order is strict and total: exactly one of two different stamps precedes the other.29 let all = [stamp(1), stamp(1, deleted: true), stamp(1, at: 101), stamp(1, device: "B"), stamp(2), stamp(2, deleted: true), stamp(1, hash: "z")]30 for a in all { for b in all { #expect(SyncMerge.precedes(a, b) != SyncMerge.precedes(b, a) || a == b) } }31 }3233 @Test func malformedChangesNeverEnterTheState() {34 let payload = Data("{\"a\":1}".utf8)35 let good = SyncChange(stamp: stamp(1, hash: SyncMerge.hash(payload)), payload: payload)36 #expect(good.isWellFormed)37 #expect(!SyncChange(stamp: stamp(1, hash: "wrong"), payload: payload).isWellFormed)38 #expect(!SyncChange(stamp: stamp(1, hash: SyncMerge.hash(payload)), payload: nil).isWellFormed)39 #expect(!SyncChange(stamp: stamp(1, hash: nil), payload: payload).isWellFormed)40 #expect(!SyncChange(stamp: stamp(1, deleted: true), payload: payload).isWellFormed)41 #expect(SyncChange(stamp: stamp(1, deleted: true), payload: nil).isWellFormed)42 var state: [SyncKey: SyncChange] = [:]43 #expect(SyncMerge.merge([SyncChange(stamp: stamp(9, hash: "wrong"), payload: payload), good], into: &state) == [good.key])44 #expect(state[good.key] == good)45 }4647 @Test func planSeparatesRequestsFromDeletions() {48 let local: [SyncKey: SyncStamp] = [SyncKey(.note, "a"): stamp(3, id: "a"), SyncKey(.note, "b"): stamp(1, id: "b"), SyncKey(.note, "c"): stamp(5, id: "c")]49 let remote = [stamp(2, id: "a"), stamp(2, id: "b"), stamp(6, deleted: true, id: "c"), stamp(1, id: "d"), stamp(1, deleted: true, id: "e")]50 let plan = SyncMerge.plan(remote: remote, local: local)51 #expect(plan.request == [SyncKey(.note, "b"), SyncKey(.note, "d")])52 #expect(plan.tombstones.map(\.entityID) == ["c", "e"])53 }5455 /// Random edits and deletions of a few keys by several devices, each with its own Lamport counter that it56 /// advances when it "sees" what another device did.57 static func randomHistory(devices: Int, seed: UInt64, count: Int = 120) -> [SyncChange] {58 var generator = SeededGenerator(seed: seed)59 var counters = [Int64](repeating: 0, count: devices)60 var changes: [SyncChange] = []61 for step in 0..<count {62 let device = Int.random(in: 0..<devices, using: &generator)63 // Sometimes a device has caught up with another one before writing.64 if Bool.random(using: &generator) { counters[device] = max(counters[device], counters.randomElement(using: &generator)!) }65 counters[device] += 166 let key = "k\(Int.random(in: 0..<8, using: &generator))"67 // Few distinct times, so ties on version and time actually occur.68 let time = Double(Int.random(in: 0..<4, using: &generator))69 if Int.random(in: 0..<4, using: &generator) == 0 {70 changes.append(SyncChange(stamp: SyncStamp(entity: .note, entityID: key, version: counters[device], deviceID: "D\(device)", modifiedAt: time, deletedAt: time), payload: nil))71 } else {72 let payload = Data("{\"step\":\(step)}".utf8)73 changes.append(SyncChange(stamp: SyncStamp(entity: .note, entityID: key, version: counters[device], deviceID: "D\(device)", modifiedAt: time,74 payloadHash: SyncMerge.hash(payload)), payload: payload))75 }76 }77 return changes78 }7980 @Test(arguments: [(2, 1), (2, 2), (2, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8)] as [(Int, UInt64)])81 func mergingIsCommutativeAssociativeAndIdempotent(devices: Int, seed: UInt64) {82 let history = Self.randomHistory(devices: devices, seed: seed)83 var generator = SeededGenerator(seed: seed &* 31)84 var reference: [SyncKey: SyncChange] = [:]85 SyncMerge.merge(history, into: &reference)86 // Idempotent: merging everything again changes nothing.87 var again = reference88 #expect(SyncMerge.merge(history, into: &again).isEmpty && again == reference)89 for _ in 0..<25 {90 // Any order, with duplicates.91 var shuffled: [SyncKey: SyncChange] = [:]92 SyncMerge.merge((history + history.shuffled(using: &generator).prefix(40)).shuffled(using: &generator), into: &shuffled)93 #expect(shuffled == reference)94 // Any grouping: each device first merges an arbitrary subset, then the devices exchange states in95 // an arbitrary order until everyone has seen everything.96 var states = [[SyncKey: SyncChange]](repeating: [:], count: devices)97 for change in history { SyncMerge.merge([change], into: &states[Int.random(in: 0..<devices, using: &generator)]) }98 for _ in 0..<(devices * 3) {99 let from = Int.random(in: 0..<devices, using: &generator), to = Int.random(in: 0..<devices, using: &generator)100 SyncMerge.merge(Array(states[from].values).shuffled(using: &generator), into: &states[to])101 }102 for from in 0..<devices { for to in 0..<devices { SyncMerge.merge(Array(states[from].values), into: &states[to]) } }103 for from in 0..<devices { for to in 0..<devices { SyncMerge.merge(Array(states[from].values), into: &states[to]) } }104 for state in states { #expect(state == reference) }105 }106 // Commutative on pairs of states.107 let half = history.count / 2108 var left: [SyncKey: SyncChange] = [:], right: [SyncKey: SyncChange] = [:]109 SyncMerge.merge(history[..<half], into: &left)110 SyncMerge.merge(history[half...], into: &right)111 var leftThenRight = left, rightThenLeft = right112 SyncMerge.merge(Array(right.values), into: &leftThenRight)113 SyncMerge.merge(Array(left.values), into: &rightThenLeft)114 #expect(leftThenRight == rightThenLeft && leftThenRight == reference)115 }116}117118@Suite struct SyncCoordinatorTests {119 struct Device {120 let database: NavigatorDatabase121 let profile: Profile122 let sync: SyncCoordinator123 static func make(_ name: String, settings: Set<String> = []) async throws -> Device {124 let (database, profile) = try await World.empty(name: name)125 var entities: Set<SyncRecord.Entity> = [.bookmark, .space, .tabGroup, .note, .canvas, .workflow]126 if !settings.isEmpty { entities.insert(.settings) }127 return Device(database: database, profile: profile,128 sync: SyncCoordinator(database: database, configuration: SyncConfiguration(entities: entities, fallbackProfileID: profile.id, syncedSettingKeys: settings)))129 }130 func content() async throws -> SyncedContent { try await SyncedContent.of(database) }131 }132133 @Test func localChangesAreDetectedOnceAndDeletionsBecomeTombstones() async throws {134 let device = try await Device.make("A")135 let note = Note(title: "t", body: "b", createdAt: day(), updatedAt: day())136 try await device.database.notes.save(note)137 let bookmark = Bookmark(profileID: device.profile.id, title: "b", url: URL(string: "https://example.org/"), createdAt: day(), updatedAt: day())138 try await device.database.bookmarks.save(bookmark)139 #expect(try await device.sync.detectLocalChanges(at: day(1)) == 2)140 #expect(try await device.sync.detectLocalChanges(at: day(2)) == 0)141 let deviceID = try await device.sync.deviceID()142 let sameAgain = try await device.sync.deviceID()143 #expect(!deviceID.isEmpty && deviceID == sameAgain)144 var index = try await device.sync.index()145 #expect(index.count == 2 && index.allSatisfy { $0.deviceID == deviceID && !$0.isTombstone && $0.payloadHash?.count == 64 && $0.modifiedAt == day(1).timeIntervalSince1970 })146 var edited = note147 edited.body = "changed"148 try await device.database.notes.save(edited)149 try await device.database.bookmarks.delete(bookmark.id)150 #expect(try await device.sync.detectLocalChanges(at: day(3)) == 2)151 index = try await device.sync.index()152 #expect(index.first { $0.entity == .bookmark }?.isTombstone == true)153 #expect(index.map(\.version).sorted() == [3, 4])154 // Payloads are canonical JSON; a bookmark's profile travels beside it, not inside.155 let changes = try await device.sync.allChanges()156 #expect(changes.count == 2 && changes.allSatisfy(\.isWellFormed))157 #expect(changes.first { $0.stamp.entity == .bookmark }?.payload == nil)158 try await device.database.bookmarks.save(bookmark)159 let recreated = try #require(try await device.sync.allChanges().first { $0.stamp.entity == .bookmark })160 #expect(recreated.profileHint == device.profile.id.string && !recreated.stamp.isTombstone)161 #expect(String(decoding: recreated.payload ?? Data(), as: UTF8.self).contains("00000000-0000-0000-0000-000000000000"))162 #expect(!String(decoding: recreated.payload ?? Data(), as: UTF8.self).contains(device.profile.id.string))163 await device.database.close()164 }165166 @Test func aFullDataSetConvergesAndReapplyingChangesNothing() async throws {167 let world = try await World.populated()168 let a = SyncCoordinator(database: world.database, configuration: SyncConfiguration(fallbackProfileID: world.profile.id))169 let b = try await Device.make("B")170 let changes = try await a.allChanges()171 #expect(changes.count == 9) // 5 bookmarks, a note, a canvas, a workflow, a space172 let first = try await b.sync.apply(changes)173 #expect(first.applied == 9 && first.rejected == 0 && first.deferred.isEmpty && first.ignored == 0)174 // Bookmarks and the space belong to B's own profile (profiles are not synchronised).175 let bookmarks = try await b.database.bookmarks.all(profile: b.profile.id)176 #expect(bookmarks.count == 5 && bookmarks.first { $0.id == world.nested.id }?.parentID == world.nested.parentID)177 #expect(try await b.database.spaces.space(world.space.id)?.profileID == b.profile.id)178 #expect(try await b.database.notes.note(world.note.id) == world.note)179 #expect(try await b.database.canvases.document(world.canvas.id) == world.canvas)180 #expect(try await b.database.workflows.workflow(world.workflow.id) == world.workflow)181 // Same stamps on both sides, and B does not mistake what it received for edits of its own.182 #expect(try await b.sync.detectLocalChanges() == 0)183 #expect(try await b.content() == SyncedContent.of(world.database))184 // Idempotent, in any order, with duplicates.185 let again = try await b.sync.apply((changes + changes).reversed())186 #expect(again.applied == 0 && again.deleted == 0 && again.ignored == 18)187 #expect(try await b.content() == SyncedContent.of(world.database))188 // B relays byte-identical payloads to a third device.189 let c = try await Device.make("C")190 let relayed = try await b.sync.allChanges()191 #expect(Set(relayed.map(\.payload)) == Set(changes.map(\.payload)) && relayed.map(\.stamp) == changes.map(\.stamp))192 _ = try await c.sync.apply(relayed.shuffled())193 #expect(try await c.content() == SyncedContent.of(world.database))194 await world.database.close(); await b.database.close(); await c.database.close()195 }196197 @Test func deletionsPropagateAndTheMergeRuleDecidesAgainstConcurrentEdits() async throws {198 let a = try await Device.make("A"), b = try await Device.make("B")199 let kept = Note(title: "kept", body: "1", createdAt: day(), updatedAt: day()), doomed = Note(title: "doomed", body: "1", createdAt: day(), updatedAt: day())200 let revived = Note(title: "revived", body: "1", createdAt: day(), updatedAt: day())201 for note in [kept, doomed, revived] { try await a.database.notes.save(note) }202 try await exchange(a.sync, b.sync)203 #expect(try await b.database.notes.notes().count == 3)204205 // A deletes two notes. B, not knowing, edits one of them twice (so its version is higher).206 try await a.database.notes.delete(doomed.id)207 try await a.database.notes.delete(revived.id)208 _ = try await a.sync.detectLocalChanges(at: day(10))209 var edit = revived210 for round in 1...3 {211 edit.body = "edited \(round)"212 try await b.database.notes.save(edit)213 _ = try await b.sync.detectLocalChanges(at: day(20 + Double(round)))214 }215 try await exchange(a.sync, b.sync)216 // The plain deletion reached B; the note edited with a higher version came back on A.217 #expect(try await b.database.notes.note(doomed.id) == nil)218 #expect(try await a.database.notes.note(revived.id)?.body == "edited 3")219 #expect(try await b.database.notes.note(revived.id)?.body == "edited 3")220 #expect(try await a.content() == b.content())221 #expect(try await a.database.sync.tombstones().map(\.entityID) == [doomed.id.string])222 #expect(try await b.database.sync.tombstones().map(\.entityID) == [doomed.id.string])223 // An older edit does not undo a newer deletion.224 var stale = kept225 stale.body = "stale"226 try await a.database.notes.delete(kept.id)227 for _ in 0..<3 { _ = try await a.sync.detectLocalChanges(at: day(40)); try await a.database.notes.save(kept); _ = try await a.sync.detectLocalChanges(at: day(41)); try await a.database.notes.delete(kept.id) }228 _ = try await a.sync.detectLocalChanges(at: day(42))229 try await b.database.notes.save(stale)230 try await exchange(a.sync, b.sync)231 #expect(try await b.database.notes.note(kept.id) == nil)232 #expect(try await a.database.notes.note(kept.id) == nil)233 #expect(try await a.content() == b.content())234235 // Tombstones are forgotten after the retention period.236 #expect(try await a.sync.purgeTombstones(now: day(100)) == 0)237 #expect(try await a.sync.purgeTombstones(now: day(42 + 181 * 86_400)) == 2)238 #expect(try await a.database.sync.tombstones().isEmpty)239 await a.database.close(); await b.database.close()240 }241242 @Test func aDeletionWinsAnExactTie() async throws {243 let a = try await Device.make("A")244 let note = Note(title: "n", body: "b", createdAt: day(), updatedAt: day())245 try await a.database.notes.save(note)246 let live = try #require(try await a.sync.allChanges().first)247 var tie = live.stamp248 tie.deletedAt = tie.modifiedAt249 tie.payloadHash = nil250 let report = try await a.sync.apply([SyncChange(stamp: tie, payload: nil)])251 #expect(report.deleted == 1)252 #expect(try await a.database.notes.note(note.id) == nil)253 #expect(try await a.database.sync.record(entity: .note, entityID: note.id.string)?.deletedAt != nil)254 // The other way round, the live record does not replace the deletion.255 #expect(try await a.sync.apply([live]).ignored == 1)256 #expect(try await a.database.notes.note(note.id) == nil)257 await a.database.close()258 }259260 @Test func concurrentBookmarkMovesNeverLeaveACycle() async throws {261 let a = try await Device.make("A"), b = try await Device.make("B")262 let x = Bookmark(profileID: a.profile.id, kind: .folder, title: "X", createdAt: day(), updatedAt: day())263 let y = Bookmark(profileID: a.profile.id, kind: .folder, title: "Y", order: 1, createdAt: day(), updatedAt: day())264 let z = Bookmark(profileID: a.profile.id, kind: .folder, title: "Z", order: 2, createdAt: day(), updatedAt: day())265 let leaf = Bookmark(profileID: a.profile.id, parentID: x.id, title: "leaf", url: URL(string: "https://example.org/"), createdAt: day(), updatedAt: day())266 for bookmark in [x, y, z, leaf] { try await a.database.bookmarks.save(bookmark) }267 try await exchange(a.sync, b.sync)268 // A moves X into Y; B, at the same time, moves Y into X.269 try await a.database.bookmarks.move(x.id, to: y.id, at: day(1))270 try await b.database.bookmarks.move(y.id, to: x.id, at: day(1))271 _ = try await a.sync.detectLocalChanges(at: day(2))272 _ = try await b.sync.detectLocalChanges(at: day(3))273 try await exchange(a.sync, b.sync)274 let treeA = try await a.database.bookmarks.all(profile: a.profile.id), treeB = try await b.database.bookmarks.all(profile: b.profile.id)275 func parents(_ tree: [Bookmark]) -> [String: String] {276 let titles = Dictionary(uniqueKeysWithValues: tree.map { ($0.id, $0.title) })277 return Dictionary(uniqueKeysWithValues: tree.map { ($0.title, $0.parentID.flatMap { titles[$0] } ?? "root") })278 }279 #expect(parents(treeA) == parents(treeB))280 // B's move has the later time and wins: Y is in X; A's losing move is undone to the top level.281 #expect(parents(treeA) == ["X": "root", "Y": "X", "Z": "root", "leaf": "X"])282 // The repair is not an edit: nothing new to send, and a second exchange is a no-op.283 #expect(try await a.sync.detectLocalChanges() == 0)284 #expect(try await b.sync.detectLocalChanges() == 0)285 try await exchange(a.sync, b.sync)286 #expect(parents(try await a.database.bookmarks.all(profile: a.profile.id)) == ["X": "root", "Y": "X", "Z": "root", "leaf": "X"])287 #expect(try await a.content().stamps == b.content().stamps)288289 // A three-way loop made by three moves on two devices.290 try await a.database.bookmarks.move(z.id, to: y.id, at: day(5)) // X ⊃ Y ⊃ Z291 _ = try await a.sync.detectLocalChanges(at: day(5))292 try await b.database.bookmarks.move(x.id, to: z.id, at: day(6)) // on B: Z ⊃ X ⊃ Y293 _ = try await b.sync.detectLocalChanges(at: day(6))294 try await exchange(a.sync, b.sync)295 let finalA = parents(try await a.database.bookmarks.all(profile: a.profile.id)), finalB = parents(try await b.database.bookmarks.all(profile: b.profile.id))296 #expect(finalA == finalB)297 for start in ["X", "Y", "Z", "leaf"] {298 var current = start, steps = 0299 while let next = finalA[current], next != "root", steps < 10 { current = next; steps += 1 }300 #expect(steps < 10, "cycle through \(start)")301 }302 await a.database.close(); await b.database.close()303 }304305 @Test func deletingAFolderKeepsWhatAnotherDeviceMovedIntoIt() async throws {306 let a = try await Device.make("A"), b = try await Device.make("B")307 let folder = Bookmark(profileID: a.profile.id, kind: .folder, title: "Folder", createdAt: day(), updatedAt: day())308 let inside = Bookmark(profileID: a.profile.id, parentID: folder.id, title: "inside", url: URL(string: "https://example.org/in"), createdAt: day(), updatedAt: day())309 let outside = Bookmark(profileID: a.profile.id, title: "outside", url: URL(string: "https://example.org/out"), order: 1, createdAt: day(), updatedAt: day())310 for bookmark in [folder, inside, outside] { try await a.database.bookmarks.save(bookmark) }311 try await exchange(a.sync, b.sync)312 // A deletes the folder (and what it knew was in it). B meanwhile moves another bookmark into it.313 try await a.database.bookmarks.delete(folder.id)314 try await b.database.bookmarks.move(outside.id, to: folder.id, at: day(1))315 _ = try await a.sync.detectLocalChanges(at: day(2))316 _ = try await b.sync.detectLocalChanges(at: day(2))317 try await exchange(a.sync, b.sync)318 for device in [a, b] {319 let titles = try await device.database.bookmarks.all(profile: device.profile.id).map { "\($0.title):\($0.parentID == nil ? "root" : "nested")" }320 #expect(titles == ["outside:root"], "\(titles)")321 }322 #expect(try await a.content().stamps == b.content().stamps)323 #expect(try await a.sync.detectLocalChanges() == 0)324 #expect(try await b.sync.detectLocalChanges() == 0)325 await a.database.close(); await b.database.close()326 }327328 @Test func canvasesAreLastWriterWinsAsAWhole() async throws {329 let a = try await Device.make("A"), b = try await Device.make("B")330 var canvas = CanvasDocument(title: "Board", cards: [CanvasCard(content: .note(text: "base"), origin: .zero)], createdAt: day(), updatedAt: day())331 try await a.database.canvases.save(canvas)332 try await exchange(a.sync, b.sync)333 var onA = canvas, onB = canvas334 onA.cards.append(CanvasCard(content: .note(text: "added on A"), origin: CanvasPoint(x: 300, y: 0)))335 onB.cards.append(CanvasCard(content: .note(text: "added on B"), origin: CanvasPoint(x: 0, y: 300)))336 try await a.database.canvases.save(onA)337 try await b.database.canvases.save(onB)338 _ = try await a.sync.detectLocalChanges(at: day(1))339 _ = try await b.sync.detectLocalChanges(at: day(2))340 try await exchange(a.sync, b.sync)341 // The later whole document wins; the other device's card is not merged in (documented limitation).342 canvas = try #require(try await a.database.canvases.document(canvas.id))343 #expect(canvas == onB)344 #expect(try await b.database.canvases.document(canvas.id) == onB)345 await a.database.close(); await b.database.close()346 }347348 @Test func settingsSyncOnlyWhenListedAndNeverInternalOnes() async throws {349 let listed: Set<String> = ["appearance.theme", "memory.enabled", "sync.device_id", "flow.schema_version"]350 let a = try await Device.make("A", settings: listed), b = try await Device.make("B", settings: listed)351 try await a.database.settings.set(SettingKey<String>("appearance.theme", default: ""), to: "dark")352 try await a.database.settings.set(SettingKey<String>("provider.endpoint", default: ""), to: "https://secret.example")353 try await a.database.settings.set(SettingKey<Bool>("memory.enabled", default: false), to: true)354 try await a.database.settings.set(SettingKey<Int>("flow.schema_version", default: 0), to: 1)355 let outgoing = try await a.sync.allChanges()356 // Only the listed, non-internal key leaves the device — not even its own device identifier.357 #expect(outgoing.map(\.key) == [SyncKey(.settings, "appearance.theme")])358 _ = try await b.sync.apply(outgoing)359 #expect(try await b.database.settings.value(SettingKey<String>("appearance.theme", default: "")) == "dark")360 #expect(try await b.database.settings.isSet("provider.endpoint") == false)361 #expect(try await b.database.settings.isSet("memory.enabled") == false)362 // A peer cannot push a setting that is not on the list, whatever it claims.363 let payload = Data("true".utf8)364 let forged = SyncChange(stamp: SyncStamp(entity: .settings, entityID: "memory.enabled", version: 99, deviceID: "evil", modifiedAt: 1, payloadHash: SyncMerge.hash(payload)), payload: payload)365 let unlisted = SyncChange(stamp: SyncStamp(entity: .settings, entityID: "privacy.block_trackers", version: 99, deviceID: "evil", modifiedAt: 1, payloadHash: SyncMerge.hash(payload)), payload: payload)366 #expect(try await b.sync.apply([forged, unlisted]).ignored == 2)367 #expect(try await b.database.settings.isSet("memory.enabled") == false)368 #expect(try await b.database.settings.isSet("privacy.block_trackers") == false)369 // By default no setting is synchronised at all.370 let plain = SyncCoordinator(database: a.database)371 #expect(try await plain.allChanges().isEmpty)372 await a.database.close(); await b.database.close()373 }374375 @Test func invalidOrUnplaceableChangesAreRejectedOrDeferred() async throws {376 let a = try await Device.make("A")377 let (bare, _) = try await World.empty()378 let noFallback = SyncCoordinator(database: bare)379 let space = OrbitSpace(profileID: a.profile.id, name: "S", createdAt: day(), updatedAt: day())380 try await a.database.spaces.save(space)381 let group = TabGroup(spaceID: space.id, name: "G")382 try await a.database.tabGroups.save(group)383 let note = Note(spaceID: space.id, title: "n", body: "b", createdAt: day(), updatedAt: day())384 try await a.database.notes.save(note)385 let changes = try await a.sync.allChanges()386 // Without the profile and without a fallback, the space waits; so does the group that needs it. The387 // note is applied, detached from the space it cannot have here.388 let report = try await noFallback.apply(changes)389 #expect(Set(report.deferred) == [SyncKey(.space, space.id.string), SyncKey(.tabGroup, group.id.string)] && report.applied == 1)390 #expect(try await bare.notes.note(note.id)?.spaceID == nil)391 #expect(try await noFallback.detectLocalChanges() == 0)392 // Deferred changes are still wanted at the next exchange.393 #expect(try await noFallback.plan(remote: changes.map(\.stamp)).request.count == 2)394 // Corrupted, mislabelled or undecodable payloads are refused.395 var tampered = changes[0]396 tampered.payload?.append(0x20)397 var mislabelled = changes[0]398 mislabelled.stamp.entityID = UUID().uuidString399 let garbage = Data("[1,2,3]".utf8)400 let undecodable = SyncChange(stamp: SyncStamp(entity: .note, entityID: UUID().uuidString, version: 5, deviceID: "x", modifiedAt: 1, payloadHash: SyncMerge.hash(garbage)), payload: garbage)401 let rejected = try await a.sync.apply([tampered, undecodable])402 #expect(rejected.rejected == 2 && rejected.applied == 0)403 _ = mislabelled404 await a.database.close(); await bare.close()405 }406407 @Test func removingThisDeviceFromSyncKeepsTheDataAndForgetsTheSyncState() async throws {408 let a = try await Device.make("A"), b = try await Device.make("B")409 try await a.database.notes.save(Note(title: "mine", body: "b", createdAt: day(), updatedAt: day()))410 try await exchange(a.sync, b.sync)411 let before = try await b.sync.deviceID()412 #expect(try await b.database.sync.changes(since: -1).count == 1)413 try await b.sync.removeLocalSyncState()414 #expect(try await b.database.sync.changes(since: -1).isEmpty)415 #expect(try await b.database.sqlite.read { try $0.scalar("SELECT count(*) FROM sync_engine_payloads", as: Int.self) } == 0)416 #expect(try await b.database.notes.notes().count == 1)417 #expect(try await b.sync.deviceID() != before)418 #expect(try await b.database.settings.value(SyncCoordinator.schemaVersionKey) == 1)419 await a.database.close(); await b.database.close()420 }421422 /// Three devices edit, move and delete at random, exchanging with random partners in between; after a423 /// final round of exchanges all three hold the same data and the same stamps.424 @Test(arguments: Array(1...12) as [UInt64])425 func randomisedThreeDeviceHistoriesConverge(seed: UInt64) async throws {426 var generator = SeededGenerator(seed: seed)427 let devices = [try await Device.make("A"), try await Device.make("B"), try await Device.make("C")]428 var clock = 0.0429 var noteIDs: [NoteID] = [], bookmarkIDs: [BookmarkID] = [], workflowIDs: [WorkflowID] = []430 for step in 0..<70 {431 clock += Double(Int.random(in: 0...2, using: &generator)) // repeated times on purpose432 let device = devices.randomElement(using: &generator)!433 let database = device.database434 switch Int.random(in: 0..<11, using: &generator) {435 case 0:436 let note = Note(title: "n\(step)", body: "v0", createdAt: day(), updatedAt: day())437 try await database.notes.save(note); noteIDs.append(note.id)438 case 1:439 if let id = noteIDs.randomElement(using: &generator), var note = try await database.notes.note(id) { note.body = "v\(step)"; try await database.notes.save(note) }440 case 2:441 if let id = noteIDs.randomElement(using: &generator) { try await database.notes.delete(id) }442 case 3:443 let isFolder = Bool.random(using: &generator)444 let bookmark = Bookmark(profileID: device.profile.id, kind: isFolder ? .folder : .link, title: "b\(step)",445 url: isFolder ? nil : URL(string: "https://example.org/\(step)"), order: step, createdAt: day(), updatedAt: day())446 try await database.bookmarks.save(bookmark); bookmarkIDs.append(bookmark.id)447 case 4, 5:448 // Move a bookmark under a random folder (or to the top level); refused moves are simply skipped.449 if let id = bookmarkIDs.randomElement(using: &generator), try await database.bookmarks.bookmark(id) != nil {450 var target: BookmarkID?451 if let candidate = bookmarkIDs.randomElement(using: &generator), Bool.random(using: &generator),452 let folder = try await database.bookmarks.bookmark(candidate), folder.kind == .folder { target = candidate }453 try? await database.bookmarks.move(id, to: target, at: day(clock))454 }455 case 6:456 if let id = bookmarkIDs.randomElement(using: &generator) { try await database.bookmarks.delete(id) }457 case 7:458 if let id = bookmarkIDs.randomElement(using: &generator), var bookmark = try await database.bookmarks.bookmark(id) { bookmark.title = "renamed\(step)"; try await database.bookmarks.save(bookmark) }459 case 8:460 let workflow = Workflow(name: "w\(step)", source: "flow \"w\" version 1\n", createdAt: day(), updatedAt: day())461 try await database.workflows.save(workflow); workflowIDs.append(workflow.id)462 case 9:463 if let id = workflowIDs.randomElement(using: &generator), var workflow = try await database.workflows.workflow(id) { workflow.source += "# \(step)\n"; try await database.workflows.save(workflow) }464 default:465 let other = devices.randomElement(using: &generator)!466 if other.profile.id != device.profile.id { try await exchange(device.sync, other.sync) }467 }468 _ = try await device.sync.detectLocalChanges(at: day(clock))469 }470 // Two full rounds so every device has seen what every other device has.471 for _ in 0..<2 {472 for (first, second) in [(0, 1), (1, 2), (0, 2)] { try await exchange(devices[first].sync, devices[second].sync) }473 }474 let contents = [try await devices[0].content(), try await devices[1].content(), try await devices[2].content()]475 #expect(contents[0] == contents[1], "seed \(seed)\nA: \(contents[0])\nB: \(contents[1])")476 #expect(contents[1] == contents[2], "seed \(seed)\nB: \(contents[1])\nC: \(contents[2])")477 for device in devices {478 // No cycle, no dangling parent, and nothing left to say.479 let bookmarks = try await device.database.bookmarks.all(profile: device.profile.id)480 let ids = Set(bookmarks.map(\.id))481 #expect(bookmarks.allSatisfy { $0.parentID == nil || ids.contains($0.parentID!) })482 #expect(try await device.sync.detectLocalChanges() == 0)483 #expect(try await device.database.checkIntegrity().isEmpty)484 }485 // A further exchange in another order moves nothing.486 try await exchange(devices[2].sync, devices[0].sync)487 #expect(try await devices[0].content() == contents[0])488 #expect(try await devices[2].content() == contents[0])489 for device in devices { await device.database.close() }490 }491}492