import Foundation import XCTest @testable import DocsKit /// The replica's revisions and dirty log (spec 2026-11-22 §7 Design 1–2, /// §11 "Replica dirty log"). final class ReplicaDirtyLogTests: XCTestCase { private func replica(limit: Int = 512) async throws -> CRDTReplica { let replica = CRDTReplica(guid: "dirty-log", dirtyLogLimit: limit) try await replica.open(update: Data()) _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) let blocks: [JSONValue] = (0..<4).map { index in .object(["type": .string("paragraph"), "children": .array([.object(["type": .string("text"), "runs": .array([.object(["insert": .string("Block \(index)"), "marks": .object([:])])])])])]) } _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array(blocks)]) return replica } private func type(_ text: String, inBlock block: Int, of replica: CRDTReplica) async throws { let projection = try await replica.projection() let offset = projection.children.prefix(block).reduce(0) { $0 + $1.plainText.utf16.count + 1 } _ = try await replica.command(["op": .string("display_edit"), "at": .number(Double(offset)), "length": .number(0), "text": .string(text)]) } func testRevisionsAdvanceOnEveryProjectionWhoeverAsks() async throws { let replica = try await replica() let start = await replica.presentedRevision _ = try await replica.projection() _ = try await replica.projection() let presented = try await XCTUnwrapAsync(try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0))) let after = await replica.presentedRevision XCTAssertEqual(after, start + 3) XCTAssertEqual(presented.revision, after) } func testDirtyCoversExactlyTheRevisionsSince() async throws { let replica = try await replica() let opened = try await XCTUnwrapAsync(try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0))) let ids = opened.projection.children.map(\.id) // The first projection is a whole one: only a full comparison says. XCTAssertNil(opened.dirty) try await type("x", inBlock: 1, of: replica) let first = try await XCTUnwrapAsync(try await replica.presentation(source: opened.generation, selection: NSRange(location: 0, length: 0), since: opened.revision)) XCTAssertEqual(first.dirty, [ids[1]]) try await type("y", inBlock: 3, of: replica) // An extra projection between presentations: still in the log. _ = try await replica.projection() let second = try await XCTUnwrapAsync(try await replica.presentation(source: first.generation, selection: NSRange(location: 0, length: 0), since: first.revision)) XCTAssertEqual(second.dirty, [ids[3]]) // A text view still at the first revision gets the union. let again = await replica.dirty(since: opened.revision, through: second.revision) XCTAssertEqual(again, [ids[1], ids[3]]) // Nothing since the latest. let none = await replica.dirty(since: second.revision, through: second.revision) XCTAssertEqual(none, []) // Spanning the whole projection at open: unknown. let fromStart = await replica.dirty(since: 0, through: second.revision) XCTAssertNil(fromStart) } func testStructuralEditsNameTheirBlocks() async throws { let replica = try await replica() let opened = try await XCTUnwrapAsync(try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0))) let ids = opened.projection.children.map(\.id) // A Return in block 1 splits it: block 1 changes and a new one appears. let offset = opened.projection.children.prefix(1).reduce(0) { $0 + $1.plainText.utf16.count + 1 } + 3 _ = try await replica.command(["op": .string("display_edit"), "at": .number(Double(offset)), "length": .number(0), "text": .string("\n")]) let split = try await XCTUnwrapAsync(try await replica.presentation(source: opened.generation, selection: NSRange(location: 0, length: 0), since: opened.revision)) let inserted = Set(split.projection.children.map(\.id)).subtracting(ids) XCTAssertEqual(inserted.count, 1) XCTAssertEqual(split.dirty, Set([ids[1]]).union(inserted)) } func testPastTheLogIsUnknown() async throws { let replica = try await replica(limit: 4) let opened = try await XCTUnwrapAsync(try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0))) var latest = opened for step in 0..<10 { try await type("z", inBlock: step % 4, of: replica) await replica.retainGenerations([latest.generation]) latest = try await XCTUnwrapAsync(try await replica.presentation(source: latest.generation, selection: NSRange(location: 0, length: 0), since: latest.revision)) XCTAssertNotNil(latest.dirty, "one revision back is always in the log") } let overflowed = await replica.dirty(since: opened.revision + 1, through: latest.revision) XCTAssertNil(overflowed, "a span older than the log cannot be answered") let recent = await replica.dirty(since: latest.revision - 2, through: latest.revision) XCTAssertNotNil(recent) } func testAWholeProjectionIsUnknownWhateverTheReason() async throws { // Recovery: an update that will not apply replaces the authority. let replica = try await replica() let opened = try await XCTUnwrapAsync(try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0))) do { try await replica.apply(Data([0x01, 0xff, 0xff, 0xff, 0xff])); XCTFail("garbage applied") } catch {} let recovered = try await XCTUnwrapAsync(try await replica.presentation(source: opened.generation, selection: NSRange(location: 0, length: 0), since: opened.revision)) XCTAssertNil(recovered.dirty, "after recovery the projection is whole") // A delta that does not apply to what the replica presented. try await type("q", inBlock: 2, of: replica) await replica.retainGenerations([recovered.generation]) let before = try await XCTUnwrapAsync(try await replica.presentation(source: recovered.generation, selection: NSRange(location: 0, length: 0), since: recovered.revision)) XCTAssertNotNil(before.dirty) await replica.replacePresentedForTesting { projection in var changed = projection; changed.children.append(projection.children[0]); return changed } try await type("r", inBlock: 2, of: replica) await replica.retainGenerations([before.generation]) let mismatched = try await XCTUnwrapAsync(try await replica.presentation(source: before.generation, selection: NSRange(location: 0, length: 0), since: before.revision)) XCTAssertNil(mismatched.dirty, "delta.applied returned nil: the full branch ran") XCTAssertEqual(mismatched.projection.children.count, before.projection.children.count) } } func XCTUnwrapAsync(_ value: @autoclosure () async throws -> T?, file: StaticString = #filePath, line: UInt = #line) async throws -> T { let unwrapped = try await value() return try XCTUnwrap(unwrapped, file: file, line: line) }