| 1 | import Foundation |
| 2 | import XCTest |
| 3 | @testable import DocsKit |
| 4 | |
| 5 | /// The replica no longer snapshots or projects per command: its state is a |
| 6 | /// base plus the updates since, and presentations patch only changed blocks. |
| 7 | /// Each must stay exactly what a fresh replica of the same bytes shows. |
| 8 | @MainActor final class CRDTIncrementalTests: XCTestCase { |
| 9 | private func describe(_ nodes: [CRDTNode]) -> String { |
| 10 | nodes.map { node in |
| 11 | let runs = (node.runs ?? []).map { run in "\(run.insert)|\((run.marks ?? [:]).keys.sorted())" }.joined(separator: ",") |
| 12 | return "\(node.id):\(node.type):\((node.attrs ?? [:]).sorted { $0.key < $1.key })[\(runs)]{\(describe(node.children ?? []))}" |
| 13 | }.joined(separator: ";") |
| 14 | } |
| 15 | private func truth(_ replica: CRDTReplica) async throws -> String { |
| 16 | let state = try await replica.persistentState().state |
| 17 | let fresh = CRDTReplica(guid: "incremental") |
| 18 | try await fresh.open(update: state) |
| 19 | let projection = try await fresh.projection() |
| 20 | await fresh.close() |
| 21 | return describe(projection.children) |
| 22 | } |
| 23 | private func paragraphs(_ count: Int) -> [String: JSONValue] { |
| 24 | let blocks: [JSONValue] = (0..<count).map { index in |
| 25 | .object(["type": .string(index % 4 == 0 ? "heading" : "paragraph"), "attrs": .object(index % 4 == 0 ? ["level": .string("2")] : [:]), |
| 26 | "children": .array([.object(["type": .string("text"), "runs": .array([.object(["insert": .string("Paragraph \(index) with some words in it."), "marks": .object([:])])])])])]) |
| 27 | } |
| 28 | return ["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array(blocks)] |
| 29 | } |
| 30 | |
| 31 | func testPresentationsMatchAWholeProjectionThroughTypingPeersAndUndo() async throws { |
| 32 | let replica = CRDTReplica(guid: "incremental"), peer = CRDTReplica(guid: "incremental") |
| 33 | try await replica.open(update: Data()) |
| 34 | _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) |
| 35 | _ = try await replica.command(paragraphs(40)) |
| 36 | try await peer.open(update: try await replica.persistentState().state) |
| 37 | let first = try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0)) |
| 38 | let opened = try XCTUnwrap(first) |
| 39 | var (source, projection) = (opened.generation, opened.projection) |
| 40 | var random = SystemRandomNumberGenerator() |
| 41 | var rendered = source |
| 42 | for step in 0..<120 { |
| 43 | let text = projection.children.map(\.plainText).joined(separator: "\n") |
| 44 | let at = Int.random(in: 0..<max(1, text.utf16.count - 2), using: &random) |
| 45 | switch step % 10 { |
| 46 | case 7: |
| 47 | let update = try await peer.command(["op": .string("display_edit"), "at": .number(Double(at / 2)), "length": .number(0), "text": .string("peer")]) |
| 48 | try await replica.apply(update) |
| 49 | case 8: try await peer.apply(try await replica.command(["op": .string("undo")])) |
| 50 | case 9: try await peer.apply(try await replica.command(["op": .string("redo")])) |
| 51 | default: |
| 52 | let update = try await replica.command(["op": .string("display_edit"), "generation": .number(Double(rendered)), "at": .number(Double(at)), |
| 53 | "length": .number(step % 3 == 0 ? 1 : 0), "text": .string(step % 5 == 0 ? "x\ny" : "typed")]) |
| 54 | try await peer.apply(update) |
| 55 | } |
| 56 | await replica.retainGenerations([rendered, source]) |
| 57 | guard let next = try await replica.presentation(source: rendered, selection: NSRange(location: at, length: 0), allowReuse: rendered == source) else { continue } |
| 58 | (source, projection) = (next.generation, next.projection) |
| 59 | // Acknowledge most renders, so both the reused and fresh paths run. |
| 60 | if step % 4 != 3 { rendered = source } |
| 61 | let expected = try await truth(replica) |
| 62 | XCTAssertEqual(describe(projection.children), expected, "step \(step)") |
| 63 | } |
| 64 | // The peer saw every local update through its own bytes alone. |
| 65 | let mine = try await replica.projection().children.map(\.plainText) |
| 66 | let theirs = try await peer.projection().children.map(\.plainText) |
| 67 | XCTAssertEqual(mine, theirs) |
| 68 | await replica.close(); await peer.close() |
| 69 | } |
| 70 | |
| 71 | func testRecoveryReplaysTheBaseAndEveryUpdateSince() async throws { |
| 72 | let replica = CRDTReplica(guid: "incremental") |
| 73 | try await replica.open(update: Data()) |
| 74 | _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) |
| 75 | _ = try await replica.command(paragraphs(10)) |
| 76 | for index in 0..<300 { |
| 77 | _ = try await replica.command(["op": .string("display_edit"), "at": .number(Double(index)), "length": .number(0), "text": .string("k")]) |
| 78 | } |
| 79 | let before = try await replica.projection().children.map(\.plainText) |
| 80 | // A rejected update poisons the authority; it is rebuilt from state. |
| 81 | do { try await replica.apply(Data([7, 7, 7])); XCTFail("Malformed update must fail") } catch { } |
| 82 | let after = try await replica.projection().children.map(\.plainText) |
| 83 | XCTAssertEqual(after, before) |
| 84 | XCTAssertTrue(after.joined().hasPrefix(String(repeating: "k", count: 300))) |
| 85 | let state = try await replica.persistentState().state |
| 86 | let reopened = CRDTReplica(guid: "incremental") |
| 87 | try await reopened.open(update: state) |
| 88 | let reread = try await reopened.projection().children.map(\.plainText) |
| 89 | XCTAssertEqual(reread, before) |
| 90 | await replica.close(); await reopened.close() |
| 91 | } |
| 92 | |
| 93 | func testProjectionsCannotBeRequestedAsCommands() async throws { |
| 94 | let replica = CRDTReplica(guid: "incremental") |
| 95 | try await replica.open(update: Data()) |
| 96 | for op in ["project", "project_delta", "open", "apply"] { |
| 97 | do { _ = try await replica.command(["op": .string(op)]); XCTFail(op) } catch { } |
| 98 | } |
| 99 | let snapshot = try await replica.command(["op": .string("snapshot")]) |
| 100 | XCTAssertFalse(snapshot.isEmpty) |
| 101 | await replica.close() |
| 102 | } |
| 103 | |
| 104 | /// Review finding 5: a capture marks exactly the updates it covered, even |
| 105 | /// when two captures overlap or are marked out of order. |
| 106 | func testOverlappingCapturesNeverMarkAnUncapturedUpdate() async throws { |
| 107 | let replica = CRDTReplica(guid: "incremental") |
| 108 | try await replica.open(update: Data()) |
| 109 | _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) |
| 110 | func type(_ text: String) async throws { |
| 111 | _ = try await replica.command(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string(text)]) |
| 112 | } |
| 113 | try await type("a"); try await type("b") |
| 114 | let first = try await replica.persistentChanges(wholeAbove: .max) |
| 115 | try await type("c") |
| 116 | let second = try await replica.persistentChanges(wholeAbove: .max) |
| 117 | try await type("d") |
| 118 | XCTAssertEqual(first.updates.count, 3); XCTAssertEqual(second.updates.count, 4) |
| 119 | // The later capture is stored first; the earlier one then marks nothing. |
| 120 | await replica.persisted(second) |
| 121 | await replica.persisted(first) |
| 122 | var left = try await replica.persistentChanges(wholeAbove: .max) |
| 123 | XCTAssertEqual(left.updates.count, 1, "only d is unstored") |
| 124 | // In order: the first marks its three, the second only its fourth. |
| 125 | try await type("e") |
| 126 | left = try await replica.persistentChanges(wholeAbove: .max) |
| 127 | try await type("f") |
| 128 | let wider = try await replica.persistentChanges(wholeAbove: .max) |
| 129 | await replica.persisted(left); await replica.persisted(wider) |
| 130 | let rest = try await replica.persistentChanges(wholeAbove: .max) |
| 131 | XCTAssertTrue(rest.updates.isEmpty) |
| 132 | try await type("g") |
| 133 | await replica.persisted(left) |
| 134 | let last = try await replica.persistentChanges(wholeAbove: .max) |
| 135 | XCTAssertEqual(last.updates.count, 1, "a stale capture cannot mark g") |
| 136 | await replica.close() |
| 137 | } |
| 138 | } |
| 139 | |