| 1 | import Foundation |
| 2 | import RastrilloNative |
| 3 | import RastrilloTestSupport |
| 4 | import XCTest |
| 5 | @testable import DocsKit |
| 6 | |
| 7 | /// Audit finding 8: the replica is stored as a base plus appended segments, |
| 8 | /// folded into the base now and then, instead of being rewritten whole after |
| 9 | /// every send and every remote change. Each write boundary must keep I1 (no |
| 10 | /// lost or duplicated text, no local edit without its outbox entry). |
| 11 | @MainActor final class ReplicaSegmentTests: XCTestCase { |
| 12 | private let guid = "segments" |
| 13 | private func seed() async throws -> Data { |
| 14 | let replica = CRDTReplica(guid: guid) |
| 15 | try await replica.open(update: Data()) |
| 16 | let update = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) |
| 17 | await replica.close(); return update |
| 18 | } |
| 19 | private func type(_ replica: CRDTReplica, _ text: String) async throws -> Data { |
| 20 | let at = try await replica.projection().children.map(\.plainText).joined().utf16.count |
| 21 | return try await replica.command(["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(0), "text": .string(text)]) |
| 22 | } |
| 23 | private func reopenText(_ store: BlobStore, fallback: Data = Data()) async throws -> String { |
| 24 | let replica = CRDTReplica(guid: guid) |
| 25 | let lane = DocsPersistence(store: store, outbox: Outbox(store: store, account: "a"), key: "doc", replica: replica) |
| 26 | try await lane.reopen(fallback: fallback, sequence: 0) |
| 27 | let text = try await replica.projection().children.map(\.plainText).joined() |
| 28 | await replica.close() |
| 29 | return text |
| 30 | } |
| 31 | private func segments(_ store: MemoryBlobStore) -> Int { |
| 32 | store.contents.keys.filter { $0.hasPrefix(DocsReplicaCache.logPath("doc") + "/") }.count |
| 33 | } |
| 34 | |
| 35 | func testPersistAppendsAndCompactsWithoutLosingAnything() async throws { |
| 36 | let disk = MemoryBlobStore(), replica = CRDTReplica(guid: guid) |
| 37 | let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica) |
| 38 | try await lane.reopen(fallback: try await seed(), sequence: 4) |
| 39 | let first = try await lane.persist() |
| 40 | XCTAssertTrue(first, "the first persist stores a base") |
| 41 | let base = disk.contents[DocsReplicaCache.basePath("doc")] |
| 42 | var expected = "" |
| 43 | for index in 0..<(DocsReplicaCache.compactionSegments + 5) { |
| 44 | let text = "\(index)," |
| 45 | try await lane.enqueue(try await type(replica, text)); expected += text |
| 46 | await replica.setSequence(Int64(5 + index)) |
| 47 | let wrote = try await lane.persist() |
| 48 | XCTAssertTrue(wrote) |
| 49 | if index < DocsReplicaCache.compactionSegments - 1 { |
| 50 | XCTAssertEqual(disk.contents[DocsReplicaCache.basePath("doc")], base, "appending never rewrites the base") |
| 51 | XCTAssertEqual(segments(disk), index + 1) |
| 52 | } |
| 53 | } |
| 54 | XCTAssertLessThan(segments(disk), DocsReplicaCache.compactionSegments, "segments were folded into the base") |
| 55 | XCTAssertNotEqual(disk.contents[DocsReplicaCache.basePath("doc")], base) |
| 56 | XCTAssertEqual(try DocsReplicaCache(store: disk).load("doc")?.sequence, Int64(4 + DocsReplicaCache.compactionSegments + 5)) |
| 57 | let reopened = try await reopenText(disk) |
| 58 | XCTAssertEqual(reopened, expected) |
| 59 | // Nothing new: nothing written. |
| 60 | let files = disk.contents |
| 61 | let again = try await lane.persist() |
| 62 | XCTAssertTrue(again) |
| 63 | XCTAssertEqual(disk.contents, files) |
| 64 | await replica.close() |
| 65 | } |
| 66 | |
| 67 | func testEveryAppendAndCompactionCrashBoundaryReopensWithEverything() async throws { |
| 68 | let base = MemoryBlobStore(), source = CRDTReplica(guid: guid) |
| 69 | let setup = DocsPersistence(store: base, outbox: Outbox(store: base, account: "a"), key: "doc", replica: source) |
| 70 | try await setup.reopen(fallback: try await seed(), sequence: 0) |
| 71 | _ = try await setup.persist() |
| 72 | var expected = "" |
| 73 | for text in ["A", "B", "C"] { |
| 74 | try await setup.enqueue(try await type(source, text)); expected += text |
| 75 | _ = try await setup.persist() |
| 76 | } |
| 77 | XCTAssertEqual(segments(base), 3) |
| 78 | // A remote update arrives and is appended; crash at every operation of |
| 79 | // that append and of the compaction after it. |
| 80 | let peer = CRDTReplica(guid: guid) |
| 81 | try await peer.open(update: try await source.persistentState().state) |
| 82 | let remote = try await type(peer, "R") |
| 83 | for crashAfter in 0...24 { |
| 84 | let disk = FaultingBlobStore(MemoryBlobStore(base.contents)) |
| 85 | let replica = CRDTReplica(guid: guid) |
| 86 | let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica) |
| 87 | try await lane.reopen(fallback: Data(), sequence: 0) |
| 88 | try await replica.apply(remote) |
| 89 | await replica.setSequence(9) |
| 90 | disk.crash(after: crashAfter) |
| 91 | do { |
| 92 | _ = try await lane.persist() |
| 93 | try await DocsReplicaCache(store: disk).compact("doc", generation: 0) |
| 94 | } catch is SimulatedCrash { } |
| 95 | let frozen = disk.committed |
| 96 | let text = try await reopenText(frozen) |
| 97 | let stored = try XCTUnwrap(DocsReplicaCache(store: frozen).load("doc")) |
| 98 | if stored.sequence == 9 { XCTAssertEqual(text, expected + "R", "crash \(crashAfter): the sequence moved with its update") } |
| 99 | else { XCTAssertEqual(text, expected, "crash \(crashAfter)"); XCTAssertEqual(stored.sequence, 0) } |
| 100 | await replica.close() |
| 101 | } |
| 102 | await source.close(); await peer.close() |
| 103 | } |
| 104 | |
| 105 | func testSegmentsWithoutABaseAreDiscardedStateAndNeverRead() async throws { |
| 106 | let disk = MemoryBlobStore(), seed = try await seed() |
| 107 | // An interrupted discard left a segment holding discarded text. |
| 108 | let ghost = CRDTReplica(guid: guid) |
| 109 | try await ghost.open(update: seed) |
| 110 | let discarded = try await type(ghost, "discarded") |
| 111 | let segment = DocsReplicaCache.Segment(index: 0, sequence: 99, update: discarded) |
| 112 | try disk.write(segment.encoded, to: DocsReplicaCache.logPath("doc") + "/" + segment.name) |
| 113 | let replica = CRDTReplica(guid: guid) |
| 114 | let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica) |
| 115 | try await lane.reopen(fallback: seed, sequence: 1) |
| 116 | let shown = try await replica.projection().children.map(\.plainText).joined() |
| 117 | XCTAssertEqual(shown, "") |
| 118 | _ = try await lane.persist() |
| 119 | XCTAssertEqual(segments(disk), 0, "writing a new base removes the orphaned segments") |
| 120 | let text = try await reopenText(disk) |
| 121 | XCTAssertEqual(text, "") |
| 122 | XCTAssertEqual(try DocsReplicaCache(store: disk).load("doc")?.sequence, 1) |
| 123 | await ghost.close(); await replica.close() |
| 124 | } |
| 125 | |
| 126 | func testAnUnreadableSegmentDropsTheWholeReplicaNotPartOfIt() async throws { |
| 127 | let disk = MemoryBlobStore(), replica = CRDTReplica(guid: guid), server = try await seed() |
| 128 | let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica) |
| 129 | try await lane.reopen(fallback: server, sequence: 0) |
| 130 | _ = try await lane.persist() |
| 131 | try await lane.enqueue(try await type(replica, "kept in the outbox")) |
| 132 | _ = try await lane.persist() |
| 133 | let name = try XCTUnwrap(disk.contents.keys.first { $0.hasPrefix(DocsReplicaCache.logPath("doc") + "/") }) |
| 134 | try disk.write(Data("not a segment".utf8), to: name) |
| 135 | do { _ = try DocsReplicaCache(store: disk).load("doc"); XCTFail("An unreadable segment must not be skipped") } |
| 136 | catch BlobStoreError.corrupt { } |
| 137 | XCTAssertNil(disk.contents[DocsReplicaCache.basePath("doc")]) |
| 138 | XCTAssertEqual(segments(disk), 0) |
| 139 | // The outbox still holds the edit; the server holds the rest. |
| 140 | let text = try await reopenText(disk, fallback: server) |
| 141 | XCTAssertEqual(text, "kept in the outbox") |
| 142 | await replica.close() |
| 143 | } |
| 144 | |
| 145 | func testChangesTooLargeToKeepInMemoryAreStoredAsAWholeState() async throws { |
| 146 | let disk = MemoryBlobStore(), replica = CRDTReplica(guid: guid, unpersistedLimit: 64 * 1024) |
| 147 | let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica) |
| 148 | try await lane.reopen(fallback: try await seed(), sequence: 0) |
| 149 | _ = try await lane.persist() |
| 150 | // Remote changes pile up while the store cannot be written. |
| 151 | let peer = CRDTReplica(guid: guid) |
| 152 | try await peer.open(update: try await replica.persistentState().state) |
| 153 | let chunk = String(repeating: "r", count: 8 * 1024) |
| 154 | for _ in 0..<10 { try await replica.apply(try await type(peer, chunk)) } |
| 155 | await replica.setSequence(8) |
| 156 | let changes = try await replica.persistentChanges(wholeAbove: DocsPersistence.appendLimit) |
| 157 | XCTAssertLessThan(changes.updates.reduce(0) { $0 + $1.count }, 64 * 1024, "memory stays bounded") |
| 158 | XCTAssertNotNil(changes.whole, "the dropped changes are stored as the whole state") |
| 159 | _ = try await lane.persist() |
| 160 | let text = try await reopenText(disk) |
| 161 | XCTAssertEqual(text.count, chunk.count * 10) |
| 162 | XCTAssertEqual(try DocsReplicaCache(store: disk).load("doc")?.sequence, 8) |
| 163 | await replica.close(); await peer.close() |
| 164 | } |
| 165 | |
| 166 | /// Review finding 3: segments are numbered without gaps from the base. A |
| 167 | /// missing one (removed after a failed read, or lost) is not silently |
| 168 | /// skipped while a later segment's sequence claims its updates: the |
| 169 | /// replica is dropped and the outbox plus the server restore it. |
| 170 | func testAMissingSegmentDropsTheReplicaLikeACorruptOne() async throws { |
| 171 | let disk = MemoryBlobStore(), replica = CRDTReplica(guid: guid), server = try await seed() |
| 172 | let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica) |
| 173 | try await lane.reopen(fallback: server, sequence: 0) |
| 174 | _ = try await lane.persist() |
| 175 | for (index, text) in ["A", "B", "C"].enumerated() { |
| 176 | try await lane.enqueue(try await type(replica, text)) |
| 177 | await replica.setSequence(Int64(index + 1)) |
| 178 | _ = try await lane.persist() |
| 179 | } |
| 180 | let names = disk.contents.keys.filter { $0.hasPrefix(DocsReplicaCache.logPath("doc") + "/") }.sorted() |
| 181 | XCTAssertEqual(names.count, 3) |
| 182 | XCTAssertEqual(names.map { DocsReplicaCache.Segment.index(of: String($0.split(separator: "/").last!)) }, [0, 1, 2]) |
| 183 | try disk.remove(names[1]) |
| 184 | do { _ = try DocsReplicaCache(store: disk).load("doc"); XCTFail("A gap must not load") } |
| 185 | catch BlobStoreError.corrupt { } |
| 186 | XCTAssertTrue(disk.contents.keys.filter { $0.contains("/replica") }.isEmpty, "the whole replica is dropped") |
| 187 | let text = try await reopenText(disk, fallback: server) |
| 188 | XCTAssertEqual(text, "ABC", "the outbox restores every edit") |
| 189 | await replica.close() |
| 190 | } |
| 191 | |
| 192 | func testCompactionContinuesTheNumberingAndSkipsWhatTheBaseHolds() async throws { |
| 193 | let disk = MemoryBlobStore(), replica = CRDTReplica(guid: guid) |
| 194 | let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica) |
| 195 | try await lane.reopen(fallback: try await seed(), sequence: 0) |
| 196 | _ = try await lane.persist() |
| 197 | for text in ["A", "B"] { try await lane.enqueue(try await type(replica, text)); _ = try await lane.persist() } |
| 198 | // A compaction that stops after writing the base leaves its segments. |
| 199 | let before = disk.contents |
| 200 | let cache = DocsReplicaCache(store: disk) |
| 201 | try await cache.compact("doc", generation: 0) |
| 202 | let base = try XCTUnwrap(disk.contents[DocsReplicaCache.basePath("doc")]) |
| 203 | let interrupted = MemoryBlobStore(before.merging([DocsReplicaCache.basePath("doc"): base]) { $1 }) |
| 204 | let stored = try XCTUnwrap(DocsReplicaCache(store: interrupted).load("doc")) |
| 205 | XCTAssertEqual(stored.replica.segmentsFrom, 2) |
| 206 | XCTAssertTrue(stored.segments.isEmpty, "segments the base holds are skipped") |
| 207 | // New segments continue from the base, in both stores. |
| 208 | for store in [disk, interrupted] { |
| 209 | let next = DocsReplicaCache(store: store) |
| 210 | XCTAssertTrue(try next.append(Data([0, 0]), sequence: 5, key: "doc", generation: 0)) |
| 211 | let loaded = try XCTUnwrap(next.load("doc")) |
| 212 | XCTAssertEqual(loaded.segments.map(\.index), [2]) |
| 213 | XCTAssertEqual(loaded.sequence, 5) |
| 214 | } |
| 215 | let text = try await reopenText(interrupted) |
| 216 | XCTAssertEqual(text, "AB") |
| 217 | await replica.close() |
| 218 | } |
| 219 | |
| 220 | /// #147: the base's accepted parking survives compaction, and a replace |
| 221 | /// (after a replica settles) stores the candidate's parking as the base. |
| 222 | func testCompactionKeepsAcceptedParkingAndReplaceSetsIt() async throws { |
| 223 | let disk = MemoryBlobStore(), cache = DocsReplicaCache(store: disk), seed = try await seed() |
| 224 | try await cache.commit(PersistedReplica(format: 1, sequence: 1, guid: guid, savedAt: Date(), state: seed, parked: "7 0-1;"), key: "doc", generation: 0) |
| 225 | let writer = CRDTReplica(guid: guid) |
| 226 | try await writer.open(update: seed) |
| 227 | for text in ["A", "B"] { let update = try await type(writer, text); XCTAssertTrue(try cache.append(update, sequence: 2, key: "doc", generation: 0)) } |
| 228 | try await cache.compact("doc", generation: 0) |
| 229 | var stored = try XCTUnwrap(cache.load("doc")) |
| 230 | XCTAssertEqual(stored.replica.parked, "7 0-1;") |
| 231 | XCTAssertTrue(stored.segments.isEmpty) |
| 232 | let third = try await type(writer, "C") |
| 233 | XCTAssertTrue(try cache.append(third, sequence: 3, key: "doc", generation: 0)) |
| 234 | let whole = try await writer.persistentState().state |
| 235 | let replaced = try await cache.replace(with: PersistedReplica(format: 1, sequence: 4, guid: guid, savedAt: Date(), state: whole, parked: ""), key: "doc", generation: 0) |
| 236 | XCTAssertTrue(replaced) |
| 237 | stored = try XCTUnwrap(cache.load("doc")) |
| 238 | XCTAssertEqual(stored.replica.parked, "") |
| 239 | XCTAssertEqual(stored.sequence, 4) |
| 240 | XCTAssertTrue(stored.segments.isEmpty, "the replaced base holds every segment") |
| 241 | let text = try await reopenText(disk) |
| 242 | XCTAssertEqual(text, "ABC") |
| 243 | await writer.close() |
| 244 | } |
| 245 | } |
| 246 | |