import Foundation import RastrilloNative import RastrilloTestSupport import XCTest @testable import DocsKit /// Audit finding 8: the replica is stored as a base plus appended segments, /// folded into the base now and then, instead of being rewritten whole after /// every send and every remote change. Each write boundary must keep I1 (no /// lost or duplicated text, no local edit without its outbox entry). @MainActor final class ReplicaSegmentTests: XCTestCase { private let guid = "segments" private func seed() async throws -> Data { let replica = CRDTReplica(guid: guid) try await replica.open(update: Data()) let update = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) await replica.close(); return update } private func type(_ replica: CRDTReplica, _ text: String) async throws -> Data { let at = try await replica.projection().children.map(\.plainText).joined().utf16.count return try await replica.command(["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(0), "text": .string(text)]) } private func reopenText(_ store: BlobStore, fallback: Data = Data()) async throws -> String { let replica = CRDTReplica(guid: guid) let lane = DocsPersistence(store: store, outbox: Outbox(store: store, account: "a"), key: "doc", replica: replica) try await lane.reopen(fallback: fallback, sequence: 0) let text = try await replica.projection().children.map(\.plainText).joined() await replica.close() return text } private func segments(_ store: MemoryBlobStore) -> Int { store.contents.keys.filter { $0.hasPrefix(DocsReplicaCache.logPath("doc") + "/") }.count } func testPersistAppendsAndCompactsWithoutLosingAnything() async throws { let disk = MemoryBlobStore(), replica = CRDTReplica(guid: guid) let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica) try await lane.reopen(fallback: try await seed(), sequence: 4) let first = try await lane.persist() XCTAssertTrue(first, "the first persist stores a base") let base = disk.contents[DocsReplicaCache.basePath("doc")] var expected = "" for index in 0..<(DocsReplicaCache.compactionSegments + 5) { let text = "\(index)," try await lane.enqueue(try await type(replica, text)); expected += text await replica.setSequence(Int64(5 + index)) let wrote = try await lane.persist() XCTAssertTrue(wrote) if index < DocsReplicaCache.compactionSegments - 1 { XCTAssertEqual(disk.contents[DocsReplicaCache.basePath("doc")], base, "appending never rewrites the base") XCTAssertEqual(segments(disk), index + 1) } } XCTAssertLessThan(segments(disk), DocsReplicaCache.compactionSegments, "segments were folded into the base") XCTAssertNotEqual(disk.contents[DocsReplicaCache.basePath("doc")], base) XCTAssertEqual(try DocsReplicaCache(store: disk).load("doc")?.sequence, Int64(4 + DocsReplicaCache.compactionSegments + 5)) let reopened = try await reopenText(disk) XCTAssertEqual(reopened, expected) // Nothing new: nothing written. let files = disk.contents let again = try await lane.persist() XCTAssertTrue(again) XCTAssertEqual(disk.contents, files) await replica.close() } func testEveryAppendAndCompactionCrashBoundaryReopensWithEverything() async throws { let base = MemoryBlobStore(), source = CRDTReplica(guid: guid) let setup = DocsPersistence(store: base, outbox: Outbox(store: base, account: "a"), key: "doc", replica: source) try await setup.reopen(fallback: try await seed(), sequence: 0) _ = try await setup.persist() var expected = "" for text in ["A", "B", "C"] { try await setup.enqueue(try await type(source, text)); expected += text _ = try await setup.persist() } XCTAssertEqual(segments(base), 3) // A remote update arrives and is appended; crash at every operation of // that append and of the compaction after it. let peer = CRDTReplica(guid: guid) try await peer.open(update: try await source.persistentState().state) let remote = try await type(peer, "R") for crashAfter in 0...24 { let disk = FaultingBlobStore(MemoryBlobStore(base.contents)) let replica = CRDTReplica(guid: guid) let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica) try await lane.reopen(fallback: Data(), sequence: 0) try await replica.apply(remote) await replica.setSequence(9) disk.crash(after: crashAfter) do { _ = try await lane.persist() try await DocsReplicaCache(store: disk).compact("doc", generation: 0) } catch is SimulatedCrash { } let frozen = disk.committed let text = try await reopenText(frozen) let stored = try XCTUnwrap(DocsReplicaCache(store: frozen).load("doc")) if stored.sequence == 9 { XCTAssertEqual(text, expected + "R", "crash \(crashAfter): the sequence moved with its update") } else { XCTAssertEqual(text, expected, "crash \(crashAfter)"); XCTAssertEqual(stored.sequence, 0) } await replica.close() } await source.close(); await peer.close() } func testSegmentsWithoutABaseAreDiscardedStateAndNeverRead() async throws { let disk = MemoryBlobStore(), seed = try await seed() // An interrupted discard left a segment holding discarded text. let ghost = CRDTReplica(guid: guid) try await ghost.open(update: seed) let discarded = try await type(ghost, "discarded") let segment = DocsReplicaCache.Segment(index: 0, sequence: 99, update: discarded) try disk.write(segment.encoded, to: DocsReplicaCache.logPath("doc") + "/" + segment.name) let replica = CRDTReplica(guid: guid) let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica) try await lane.reopen(fallback: seed, sequence: 1) let shown = try await replica.projection().children.map(\.plainText).joined() XCTAssertEqual(shown, "") _ = try await lane.persist() XCTAssertEqual(segments(disk), 0, "writing a new base removes the orphaned segments") let text = try await reopenText(disk) XCTAssertEqual(text, "") XCTAssertEqual(try DocsReplicaCache(store: disk).load("doc")?.sequence, 1) await ghost.close(); await replica.close() } func testAnUnreadableSegmentDropsTheWholeReplicaNotPartOfIt() async throws { let disk = MemoryBlobStore(), replica = CRDTReplica(guid: guid), server = try await seed() let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica) try await lane.reopen(fallback: server, sequence: 0) _ = try await lane.persist() try await lane.enqueue(try await type(replica, "kept in the outbox")) _ = try await lane.persist() let name = try XCTUnwrap(disk.contents.keys.first { $0.hasPrefix(DocsReplicaCache.logPath("doc") + "/") }) try disk.write(Data("not a segment".utf8), to: name) do { _ = try DocsReplicaCache(store: disk).load("doc"); XCTFail("An unreadable segment must not be skipped") } catch BlobStoreError.corrupt { } XCTAssertNil(disk.contents[DocsReplicaCache.basePath("doc")]) XCTAssertEqual(segments(disk), 0) // The outbox still holds the edit; the server holds the rest. let text = try await reopenText(disk, fallback: server) XCTAssertEqual(text, "kept in the outbox") await replica.close() } func testChangesTooLargeToKeepInMemoryAreStoredAsAWholeState() async throws { let disk = MemoryBlobStore(), replica = CRDTReplica(guid: guid, unpersistedLimit: 64 * 1024) let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica) try await lane.reopen(fallback: try await seed(), sequence: 0) _ = try await lane.persist() // Remote changes pile up while the store cannot be written. let peer = CRDTReplica(guid: guid) try await peer.open(update: try await replica.persistentState().state) let chunk = String(repeating: "r", count: 8 * 1024) for _ in 0..<10 { try await replica.apply(try await type(peer, chunk)) } await replica.setSequence(8) let changes = try await replica.persistentChanges(wholeAbove: DocsPersistence.appendLimit) XCTAssertLessThan(changes.updates.reduce(0) { $0 + $1.count }, 64 * 1024, "memory stays bounded") XCTAssertNotNil(changes.whole, "the dropped changes are stored as the whole state") _ = try await lane.persist() let text = try await reopenText(disk) XCTAssertEqual(text.count, chunk.count * 10) XCTAssertEqual(try DocsReplicaCache(store: disk).load("doc")?.sequence, 8) await replica.close(); await peer.close() } /// Review finding 3: segments are numbered without gaps from the base. A /// missing one (removed after a failed read, or lost) is not silently /// skipped while a later segment's sequence claims its updates: the /// replica is dropped and the outbox plus the server restore it. func testAMissingSegmentDropsTheReplicaLikeACorruptOne() async throws { let disk = MemoryBlobStore(), replica = CRDTReplica(guid: guid), server = try await seed() let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica) try await lane.reopen(fallback: server, sequence: 0) _ = try await lane.persist() for (index, text) in ["A", "B", "C"].enumerated() { try await lane.enqueue(try await type(replica, text)) await replica.setSequence(Int64(index + 1)) _ = try await lane.persist() } let names = disk.contents.keys.filter { $0.hasPrefix(DocsReplicaCache.logPath("doc") + "/") }.sorted() XCTAssertEqual(names.count, 3) XCTAssertEqual(names.map { DocsReplicaCache.Segment.index(of: String($0.split(separator: "/").last!)) }, [0, 1, 2]) try disk.remove(names[1]) do { _ = try DocsReplicaCache(store: disk).load("doc"); XCTFail("A gap must not load") } catch BlobStoreError.corrupt { } XCTAssertTrue(disk.contents.keys.filter { $0.contains("/replica") }.isEmpty, "the whole replica is dropped") let text = try await reopenText(disk, fallback: server) XCTAssertEqual(text, "ABC", "the outbox restores every edit") await replica.close() } func testCompactionContinuesTheNumberingAndSkipsWhatTheBaseHolds() async throws { let disk = MemoryBlobStore(), replica = CRDTReplica(guid: guid) let lane = DocsPersistence(store: disk, outbox: Outbox(store: disk, account: "a"), key: "doc", replica: replica) try await lane.reopen(fallback: try await seed(), sequence: 0) _ = try await lane.persist() for text in ["A", "B"] { try await lane.enqueue(try await type(replica, text)); _ = try await lane.persist() } // A compaction that stops after writing the base leaves its segments. let before = disk.contents let cache = DocsReplicaCache(store: disk) try await cache.compact("doc", generation: 0) let base = try XCTUnwrap(disk.contents[DocsReplicaCache.basePath("doc")]) let interrupted = MemoryBlobStore(before.merging([DocsReplicaCache.basePath("doc"): base]) { $1 }) let stored = try XCTUnwrap(DocsReplicaCache(store: interrupted).load("doc")) XCTAssertEqual(stored.replica.segmentsFrom, 2) XCTAssertTrue(stored.segments.isEmpty, "segments the base holds are skipped") // New segments continue from the base, in both stores. for store in [disk, interrupted] { let next = DocsReplicaCache(store: store) XCTAssertTrue(try next.append(Data([0, 0]), sequence: 5, key: "doc", generation: 0)) let loaded = try XCTUnwrap(next.load("doc")) XCTAssertEqual(loaded.segments.map(\.index), [2]) XCTAssertEqual(loaded.sequence, 5) } let text = try await reopenText(interrupted) XCTAssertEqual(text, "AB") await replica.close() } /// #147: the base's accepted parking survives compaction, and a replace /// (after a replica settles) stores the candidate's parking as the base. func testCompactionKeepsAcceptedParkingAndReplaceSetsIt() async throws { let disk = MemoryBlobStore(), cache = DocsReplicaCache(store: disk), seed = try await seed() try await cache.commit(PersistedReplica(format: 1, sequence: 1, guid: guid, savedAt: Date(), state: seed, parked: "7 0-1;"), key: "doc", generation: 0) let writer = CRDTReplica(guid: guid) try await writer.open(update: seed) for text in ["A", "B"] { let update = try await type(writer, text); XCTAssertTrue(try cache.append(update, sequence: 2, key: "doc", generation: 0)) } try await cache.compact("doc", generation: 0) var stored = try XCTUnwrap(cache.load("doc")) XCTAssertEqual(stored.replica.parked, "7 0-1;") XCTAssertTrue(stored.segments.isEmpty) let third = try await type(writer, "C") XCTAssertTrue(try cache.append(third, sequence: 3, key: "doc", generation: 0)) let whole = try await writer.persistentState().state let replaced = try await cache.replace(with: PersistedReplica(format: 1, sequence: 4, guid: guid, savedAt: Date(), state: whole, parked: ""), key: "doc", generation: 0) XCTAssertTrue(replaced) stored = try XCTUnwrap(cache.load("doc")) XCTAssertEqual(stored.replica.parked, "") XCTAssertEqual(stored.sequence, 4) XCTAssertTrue(stored.segments.isEmpty, "the replaced base holds every segment") let text = try await reopenText(disk) XCTAssertEqual(text, "ABC") await writer.close() } }