Repository Public
1// SP Notes Core2// File: Tests/SPNotesSyncTests/MergeConflictTests.swift3// Description: Scenario tests of the synchronisation engine, part 3: two devices editing the same note — automatic merges (blocks,4// title, properties), recorded conflicts and their three resolutions, conflicts that move while the user decides.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import SPNotesAPI10import SPNotesStore11import Testing12@testable import SPNotesSync13@testable import SPNotesTestSupport1415/// Two devices holding the same synced note.16private func twoDevices(_ blocks: [Block] = [("a", "alpha"), ("b", "beta"), ("c", "gamma")], properties: String = "{}") async throws -> (World, Device, Device, String) {17 let world = World()18 let a = try world.device("A")19 let b = try world.device("B")20 let id = try await a.create("Shared note", blocks, properties: properties)21 #expect(await a.sync() == .completed)22 #expect(await b.sync() == .completed)23 return (world, a, b, id)24}2526/// A and B both changed block "b"; A synced first. Returns once B holds the recorded conflict.27private func conflicted() async throws -> (World, Device, Device, String) {28 let (world, a, b, id) = try await twoDevices()29 try await a.edit(id, block: "b", text: "beta by A")30 try await b.edit(id, block: "b", text: "beta by B")31 #expect(await a.sync() == .completed)32 #expect(await b.sync() == .completed)33 #expect(try await b.store.conflict(pageId: id) != nil)34 return (world, a, b, id)35}3637@Suite("Automatic merges")38struct MergeTests {39 @Test("different blocks of the same note: both changes everywhere, no conflict, one sync call each")40 func differentBlocks() async throws {41 let (world, a, b, id) = try await twoDevices()42 try await a.edit(id, block: "a", text: "alpha by A")43 try await b.edit(id, block: "c", text: "gamma by B")44 try await b.append(id, block: "d", text: "delta by B")45 #expect(await a.sync() == .completed)46 #expect(await b.sync() == .completed) // 409 → merge → pushed in the same call47 #expect(await a.sync() == .completed)48 let expected = ["alpha by A", "beta", "gamma by B", "delta by B"]49 #expect(Doc.texts(try #require(world.fake.page(id)).content) == expected)50 #expect(try await a.texts(id) == expected)51 #expect(try await b.texts(id) == expected)52 #expect(try await a.store.conflicts().isEmpty)53 #expect(try await b.store.conflicts().isEmpty)54 try await expectMirror(a)55 try await expectMirror(b)56 await world.closeAll()57 }5859 @Test("a divergence discovered by the feed (edit made between push and pull) is merged and pushed too")60 func mergeOnPull() async throws {61 let (world, a, b, id) = try await twoDevices()62 try await a.edit(id, block: "a", text: "alpha by A")63 #expect(await a.sync() == .completed)64 let gate = Gate()65 world.fake.inject(.hold(gate), method: "GET", path: "^/api/sync", device: "B")66 async let outcome = b.sync()67 await gate.reached()68 try await b.edit(id, block: "c", text: "gamma by B") // typed after B's push phase, before the feed is applied69 gate.open()70 #expect(await outcome == .completed)71 #expect(try await b.store.conflicts().isEmpty)72 #expect(try await b.texts(id) == ["alpha by A", "beta", "gamma by B"])73 #expect(Doc.texts(try #require(world.fake.page(id)).content) == ["alpha by A", "beta", "gamma by B"], "merged AND pushed by the same call")74 try await expectMirror(b)75 await world.closeAll()76 }7778 @Test("title on one side, content on the other: merged")79 func titleAndContent() async throws {80 let (world, a, b, id) = try await twoDevices()81 try await a.setTitle(id, "Renamed by A")82 try await b.edit(id, block: "b", text: "beta by B")83 #expect(await a.sync() == .completed)84 #expect(await b.sync() == .completed)85 #expect(await a.sync() == .completed)86 for device in [a, b] {87 #expect(try await device.page(id).title == "Renamed by A")88 #expect(try await device.texts(id) == ["alpha", "beta by B", "gamma"])89 #expect(try await device.store.conflicts().isEmpty)90 try await expectMirror(device)91 }92 await world.closeAll()93 }9495 @Test("properties changed on different keys: merged key by key")96 func properties() async throws {97 let (world, a, b, id) = try await twoDevices(properties: #"{"color":"blue","keep":1}"#)98 _ = try await a.store.setFavorite(id: id, true)99 _ = try await b.store.setProperties(id: id, properties: Data(#"{"color":"red","keep":1}"#.utf8))100 #expect(await a.sync() == .completed)101 #expect(await b.sync() == .completed)102 #expect(await a.sync() == .completed)103 let expected = Data(#"{"color":"red","favorite":true,"keep":1}"#.utf8)104 #expect(FakeBackend.jsonEqual(try #require(world.fake.page(id)).properties, expected))105 for device in [a, b] {106 #expect(FakeBackend.jsonEqual(try await device.page(id).properties, expected))107 #expect(try await device.page(id).favorite)108 #expect(try await device.store.conflicts().isEmpty)109 try await expectMirror(device)110 }111 await world.closeAll()112 }113114 @Test("the same change made on both sides is not a conflict")115 func identicalChanges() async throws {116 let (world, a, b, id) = try await twoDevices()117 try await a.edit(id, block: "b", text: "the same fix")118 try await b.edit(id, block: "b", text: "the same fix")119 #expect(await a.sync() == .completed)120 #expect(await b.sync() == .completed)121 #expect(try await b.store.conflicts().isEmpty)122 #expect(world.fake.page(id)?.version == 2, "B wrote nothing")123 try await expectMirror(b)124 await world.closeAll()125 }126127 @Test("flags, tags and moves are not version-guarded: they never conflict with a content edit")128 func metaNeverConflicts() async throws {129 let (world, a, b, id) = try await twoDevices()130 try await a.edit(id, block: "a", text: "alpha by A")131 _ = try await b.store.setPinned(id: id, true)132 _ = try await b.store.setTags(id: id, names: ["tagged"])133 #expect(await a.sync() == .completed)134 #expect(await b.sync() == .completed)135 #expect(await a.sync() == .completed)136 let server = try #require(world.fake.page(id))137 #expect(server.pinned && server.tags == ["tagged"] && server.text.hasPrefix("alpha by A"))138 #expect(server.version == 2)139 try await expectMirror(a)140 try await expectMirror(b)141 await world.closeAll()142 }143}144145@Suite("Conflicts")146struct ConflictTests {147 @Test("same block on two devices: a conflict is recorded on the second, both texts are kept, the server is not overwritten")148 func recorded() async throws {149 let (world, a, b, id) = try await conflicted()150 let fake = world.fake151 let record = try #require(try await b.store.conflict(pageId: id))152 #expect(Doc.texts(record.server.content) == ["alpha", "beta by A", "gamma"], "the server copy is available on the device")153 #expect(record.server.version == 2)154 #expect(try await b.texts(id) == ["alpha", "beta by B", "gamma"], "the local text is intact")155 #expect(try await b.page(id).syncState == .conflict)156 #expect(fake.page(id)?.text == "alpha\nbeta by A\ngamma", "nothing on the server was overwritten")157 #expect(fake.page(id)?.version == 2)158 #expect(await b.engine.currentStatus().conflicts == 1)159160 // the conflict stays, cycle after cycle, without any write; local typing goes on161 fake.clearLog()162 try await b.edit(id, block: "c", text: "gamma, still typing on B")163 #expect(await b.sync() == .completed)164 #expect(await b.sync() == .completed)165 #expect(fake.requests.allSatisfy { $0.method == "GET" })166 #expect(try await b.store.conflict(pageId: id) != nil)167 #expect(try await b.texts(id) == ["alpha", "beta by B", "gamma, still typing on B"])168 #expect(await a.sync() == .completed)169 #expect(try await a.texts(id) == ["alpha", "beta by A", "gamma"])170 await world.closeAll()171 }172173 @Test("keepMine: the local text wins everywhere; the other text stays in the server history")174 func keepMine() async throws {175 let (world, a, b, id) = try await conflicted()176 #expect(try await b.engine.resolveConflict(pageId: id, choice: .keepMine) == nil)177 #expect(try await b.store.conflict(pageId: id) == nil)178 #expect(await b.sync() == .completed)179 #expect(await a.sync() == .completed)180 let expected = ["alpha", "beta by B", "gamma"]181 #expect(Doc.texts(try #require(world.fake.page(id)).content) == expected)182 #expect(try await a.texts(id) == expected)183 #expect(try await b.texts(id) == expected)184 #expect(world.fake.history(id).contains { $0.text.contains("beta by A") }, "A's text survives in the server history")185 try await expectMirror(a)186 try await expectMirror(b)187 #expect(await b.engine.currentStatus().conflicts == 0)188 await world.closeAll()189 }190191 @Test("keepTheirs: the server text wins; the local text stays in the server history and in the local versions")192 func keepTheirs() async throws {193 let (world, a, b, id) = try await conflicted()194 #expect(try await b.engine.resolveConflict(pageId: id, choice: .keepTheirs) == nil)195 #expect(await b.sync() == .completed)196 #expect(await a.sync() == .completed)197 let expected = ["alpha", "beta by A", "gamma"]198 #expect(Doc.texts(try #require(world.fake.page(id)).content) == expected)199 #expect(try await b.texts(id) == expected)200 #expect(world.fake.page(id)?.version == 2, "the server copy was not rewritten")201 #expect(world.fake.history(id).contains { $0.text.contains("beta by B") && $0.version < 0 })202 let versions = try await b.store.localVersions(pageId: id)203 let newest = try #require(versions.first)204 let saved = try #require(try await b.store.localVersion(id: newest.id))205 #expect(saved.reason == "conflict-local" && saved.plainText.contains("beta by B"))206 try await expectMirror(a)207 try await expectMirror(b)208 await world.closeAll()209 }210211 @Test("keepBoth: the server text stays in the note, the local text becomes a sibling copy on every device")212 func keepBoth() async throws {213 let (world, a, b, id) = try await conflicted()214 let copyId = try #require(try await b.engine.resolveConflict(pageId: id, choice: .keepBoth))215 #expect(await b.sync() == .completed)216 #expect(await a.sync() == .completed)217 #expect(world.fake.allPages.count == 2)218 for device in [a, b] {219 #expect(try await device.texts(id) == ["alpha", "beta by A", "gamma"])220 #expect(try await device.texts(copyId) == ["alpha", "beta by B", "gamma"])221 #expect(try await device.page(copyId).title == "Shared note (conflict copy)")222 #expect(try await device.page(copyId).parentId == (try await device.page(id).parentId))223 try await expectMirror(device)224 }225 #expect(try await b.store.conflicts().isEmpty)226 await world.closeAll()227 }228229 @Test("keepBoth with a lost answer: the retry does not create a second copy")230 func keepBothLostAnswer() async throws {231 let (world, _, b, id) = try await conflicted()232 world.fake.inject(.dropResponse, method: "POST", path: "/resolve$")233 await #expect(throws: APIError.self) { try await b.engine.resolveConflict(pageId: id, choice: .keepBoth) }234 #expect(try await b.store.conflict(pageId: id) != nil, "still to be decided as far as the device knows")235 let copyId = try #require(try await b.engine.resolveConflict(pageId: id, choice: .keepBoth))236 #expect(world.fake.allPages.count == 2, "one copy, not two")237 #expect(world.fake.page(copyId)?.text.contains("beta by B") == true)238 #expect(await b.sync() == .completed)239 try await expectMirror(b)240 await world.closeAll()241 }242243 @Test("keepMine with a lost answer: the retry sees its own write and settles without asking again")244 func keepMineLostAnswer() async throws {245 let (world, _, b, id) = try await conflicted()246 world.fake.inject(.dropResponse, method: "POST", path: "/resolve$")247 await #expect(throws: APIError.self) { try await b.engine.resolveConflict(pageId: id, choice: .keepMine) }248 _ = try await b.engine.resolveConflict(pageId: id, choice: .keepMine)249 #expect(try await b.store.conflict(pageId: id) == nil)250 #expect(world.fake.page(id)?.text == "alpha\nbeta by B\ngamma")251 #expect(world.fake.page(id)?.version == 3)252 #expect(await b.sync() == .completed)253 try await expectMirror(b)254 await world.closeAll()255 }256257 @Test("the note moves again while the user decides: the newer server copy is recorded, then the decision goes through")258 func movesWhileDeciding() async throws {259 let (world, a, b, id) = try await conflicted()260 try await a.edit(id, block: "a", text: "alpha, second edit by A")261 #expect(await a.sync() == .completed) // server at version 3; B's record still shows version 2262 do {263 _ = try await b.engine.resolveConflict(pageId: id, choice: .keepMine)264 Issue.record("the resolution should have been refused")265 } catch let error as APIError {266 #expect(error.isConflict)267 }268 let record = try #require(try await b.store.conflict(pageId: id))269 #expect(record.server.version == 3)270 #expect(Doc.texts(record.server.content) == ["alpha, second edit by A", "beta by A", "gamma"])271 #expect(try await b.texts(id) == ["alpha", "beta by B", "gamma"])272 #expect(world.fake.page(id)?.version == 3, "nothing was written")273274 _ = try await b.engine.resolveConflict(pageId: id, choice: .keepBoth)275 #expect(await b.sync() == .completed)276 #expect(await a.sync() == .completed)277 try await expectMirror(a)278 try await expectMirror(b)279 await world.closeAll()280 }281282 @Test("a recorded conflict follows the server: a newer copy replaces the record, an identical copy dissolves it")283 func conflictFollowsTheFeed() async throws {284 let (world, _, b, id) = try await conflicted()285 world.fake.webEdit(id, content: Doc.data([("a", "alpha"), ("b", "beta, third opinion"), ("c", "gamma")]))286 #expect(await b.sync() == .completed)287 #expect(try await b.store.conflict(pageId: id)?.server.version == 3)288 #expect(try await b.texts(id) == ["alpha", "beta by B", "gamma"])289 // somebody types on the web exactly what B holds290 world.fake.webEdit(id, content: Doc.data([("a", "alpha"), ("b", "beta by B"), ("c", "gamma")]))291 #expect(await b.sync() == .completed)292 #expect(try await b.store.conflict(pageId: id) == nil)293 try await expectMirror(b)294 await world.closeAll()295 }296297 @Test("keepMine keeps the local properties and whatever was typed during the request")298 func keepMineKeepsPropertiesAndLateEdits() async throws {299 let (world, a, b, id) = try await conflicted()300 _ = try await b.store.setFavorite(id: id, true)301 let gate = Gate()302 world.fake.inject(.hold(gate), method: "POST", path: "/resolve$")303 async let resolution = b.engine.resolveConflict(pageId: id, choice: .keepMine)304 await gate.reached()305 try await b.edit(id, block: "c", text: "gamma, typed while resolving")306 gate.open()307 _ = try await resolution308 #expect(try await b.texts(id) == ["alpha", "beta by B", "gamma, typed while resolving"], "the late edit is on screen")309 #expect(await b.sync() == .completed)310 #expect(await a.sync() == .completed)311 let server = try #require(world.fake.page(id))312 #expect(server.text == "alpha\nbeta by B\ngamma, typed while resolving")313 #expect(FakeBackend.jsonEqual(server.properties, Data(#"{"favorite":true}"#.utf8)))314 try await expectMirror(a)315 try await expectMirror(b)316 await world.closeAll()317 }318319 @Test("a note created on two devices under the same id with different texts is a conflict, not an overwrite")320 func sameIdCreatedTwice() async throws {321 let world = World()322 let a = try world.device("A")323 let b = try world.device("B")324 let id = UUID().uuidString.lowercased()325 try await a.create("From A", [("a", "text of A")], id: id)326 try await b.create("From B", [("b", "text of B")], id: id)327 #expect(await a.sync() == .completed)328 try await a.edit(id, block: "a", text: "text of A, edited")329 #expect(await a.sync() == .completed) // version 2: clearly not B's own first copy330 #expect(await b.sync() == .completed)331 #expect(try await b.store.conflict(pageId: id) != nil)332 #expect(try await b.texts(id) == ["text of B"])333 #expect(world.fake.page(id)?.text == "text of A, edited")334 _ = try await b.engine.resolveConflict(pageId: id, choice: .keepBoth)335 #expect(await b.sync() == .completed)336 #expect(await a.sync() == .completed)337 try await expectMirror(a)338 try await expectMirror(b)339 await world.closeAll()340 }341}342