| 1 | import Foundation |
| 2 | import XCTest |
| 3 | @testable import DocsKit |
| 4 | |
| 5 | /// Block render equivalence (spec 2026-11-22 §11, Low 17): random edit |
| 6 | /// sequences on the production replica, published to a `DocumentSurface` |
| 7 | /// as the model publishes them. After each publication the storage built |
| 8 | /// block by block equals a whole render of the same projection, attribute |
| 9 | /// for attribute. |
| 10 | @MainActor final class BlockRenderEquivalenceTests: XCTestCase { |
| 11 | /// A document with nested lists, a quote, headings, inline code, an |
| 12 | /// image, a rule and alignment. |
| 13 | static var fixture: [JSONValue] { |
| 14 | func text(_ insert: String, _ marks: [String: JSONValue] = [:]) -> JSONValue { |
| 15 | .object(["type": .string("text"), "runs": .array([.object(["insert": .string(insert), "marks": .object(marks)])])]) |
| 16 | } |
| 17 | func block(_ type: String, _ children: [JSONValue], attrs: [String: String] = [:]) -> JSONValue { |
| 18 | var object: [String: JSONValue] = ["type": .string(type)] |
| 19 | if !children.isEmpty { object["children"] = .array(children) } |
| 20 | if !attrs.isEmpty { object["attrs"] = .object(attrs.mapValues(JSONValue.string)) } |
| 21 | return .object(object) |
| 22 | } |
| 23 | func paragraph(_ insert: String, _ marks: [String: JSONValue] = [:], attrs: [String: String] = [:]) -> JSONValue { block("paragraph", [text(insert, marks)], attrs: attrs) } |
| 24 | func item(_ children: [JSONValue]) -> JSONValue { block("list_item", children) } |
| 25 | return [ |
| 26 | block("heading", [text("Millbrook water report")], attrs: ["level": "1"]), |
| 27 | paragraph("The survey began in spring."), |
| 28 | block("paragraph", [text("Run "), text("make check", ["code": .object([:])]), text(" before the "), text("bold", ["strong": .object([:])]), text(" part.")]), |
| 29 | block("bullet_list", [item([paragraph("Private wells")]), item([paragraph("Shared pumps"), block("bullet_list", [item([paragraph("North pump")]), item([paragraph("South pump")])])])]), |
| 30 | block("heading", [text("Findings")], attrs: ["level": "2"]), |
| 31 | block("blockquote", [paragraph("Water is life."), paragraph("— a resident")]), |
| 32 | block("ordered_list", [item([paragraph("Survey the creek")]), item([paragraph("Build the dam")])], attrs: ["order": "3"]), |
| 33 | paragraph("Centred note.", attrs: ["align": "center"]), |
| 34 | block("paragraph", [.object(["type": .string("image"), "attrs": .object(["src": .string(LoopFixture.picture), "alt": .string("A reservoir")])])]), |
| 35 | block("horizontal_rule", []), |
| 36 | block("code_block", [text("let x = 1\nlet y = 2")]), |
| 37 | block("heading", [text("Small heading")], attrs: ["level": "3"]), |
| 38 | paragraph("The end."), |
| 39 | ] |
| 40 | } |
| 41 | static var pasted: [JSONValue] { |
| 42 | [.object(["type": .string("heading"), "attrs": .object(["level": .string("2")]), "children": .array([.object(["type": .string("text"), "runs": .array([.object(["insert": .string("Pasted heading"), "marks": .object([:])])])])])]), |
| 43 | .object(["type": .string("paragraph"), "children": .array([.object(["type": .string("text"), "runs": .array([.object(["insert": .string("Pasted words"), "marks": .object([:])])])])])])] |
| 44 | } |
| 45 | |
| 46 | func testBlocksDrawnOnTheirOwnEqualAWholeRender() async throws { |
| 47 | for seed: UInt64 in [1, 2, 3, 4, 5, 6] { |
| 48 | try await run(seed: seed, steps: 50) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | private func run(seed: UInt64, steps: Int) async throws { |
| 53 | var random = SeededRandom(seed: seed) |
| 54 | let replica = CRDTReplica(guid: "equivalence-\(seed)") |
| 55 | try await replica.open(update: Data()) |
| 56 | _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) |
| 57 | _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array(Self.fixture)]) |
| 58 | let state = SurfaceState(width: 640) |
| 59 | let image = try XCTUnwrap(DocsAttachments.decode(Data(base64Encoded: String(LoopFixture.picture.split(separator: ",")[1]))!)) |
| 60 | let images = [LoopFixture.picture: image] |
| 61 | state.surface.imagesChanged(images) |
| 62 | var generation: UInt64 = 0 |
| 63 | var projection = try await replica.projection() |
| 64 | func publish() async throws { |
| 65 | await replica.retainGenerations([generation]) |
| 66 | guard let presented = try await replica.presentation(source: generation, selection: NSRange(location: 0, length: 0), since: state.surface.appliedRevision) else { return } |
| 67 | generation = presented.generation; projection = presented.projection |
| 68 | state.allowed = generation |
| 69 | state.surface.apply(DocumentSurface.Publication(generation: generation, projection: projection, revision: presented.revision, dirty: presented.dirty)) |
| 70 | SurfaceFixture.assertMatchesWholeRender(state.surface.content, projection, images: images, "seed \(seed)") |
| 71 | } |
| 72 | try await publish() |
| 73 | for step in 0..<steps { |
| 74 | let content = NativeTextProjection.render(projection) |
| 75 | let length = content.length |
| 76 | let at = step % 7 == 0 ? 0 : Int(random.next() % UInt64(max(1, length - 1))) |
| 77 | let command: [String: JSONValue] |
| 78 | switch random.next() % 10 { |
| 79 | case 0: command = ["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(0), "text": .string("typed ")] |
| 80 | case 1: command = ["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(Double(min(3, max(0, length - 1 - at)))), "text": .string("")] |
| 81 | case 2: command = ["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(0), "text": .string("\n")] |
| 82 | case 3: |
| 83 | // Merge: delete a paragraph end. |
| 84 | let ends = (content.string as NSString) |
| 85 | var end = ends.range(of: "\n", range: NSRange(location: at, length: length - at)).location |
| 86 | if end == NSNotFound || end >= length - 1 { end = ends.range(of: "\n").location } |
| 87 | command = ["op": .string("display_edit"), "at": .number(Double(end)), "length": .number(1), "text": .string("")] |
| 88 | case 4: command = ["op": .string("display_paste"), "at": .number(Double(at)), "length": .number(0), "blocks": .array(Self.pasted)] |
| 89 | case 5: command = ["op": .string("undo")] |
| 90 | case 6: command = ["op": .string("redo")] |
| 91 | case 7: |
| 92 | let range = NSRange(location: at, length: min(6, max(0, length - 1 - at))) |
| 93 | let marks: [String: JSONValue] = random.next() % 2 == 0 ? ["code": .object([:])] : ["strong": .object([:])] |
| 94 | command = ["op": .string("batch"), "commands": .array(DocumentCommands.markCommands(content: content, selection: range, marks: marks).map(JSONValue.object))] |
| 95 | case 8: |
| 96 | let node = projection.children[Int(random.next() % UInt64(projection.children.count))] |
| 97 | command = ["op": .string("block"), "node": .string(node.id), "type": .string(random.next() % 2 == 0 ? "heading" : "paragraph"), "level": .number(2)] |
| 98 | default: |
| 99 | let node = projection.children[Int(random.next() % UInt64(projection.children.count))] |
| 100 | command = ["op": .string("attribute"), "node": .string(node.id), "name": .string("align"), "value": .string(random.next() % 2 == 0 ? "right" : "center")] |
| 101 | } |
| 102 | _ = try? await replica.command(command) |
| 103 | // Not every change is published: some accumulate, as when |
| 104 | // publications are dropped or deferred. |
| 105 | if random.next() % 3 != 0 { try await publish() } |
| 106 | } |
| 107 | try await publish() |
| 108 | await replica.close() |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | /// SplitMix64: the same sequence on every run and platform. |
| 113 | struct SeededRandom { |
| 114 | private var state: UInt64 |
| 115 | init(seed: UInt64) { state = seed } |
| 116 | mutating func next() -> UInt64 { |
| 117 | state &+= 0x9E37_79B9_7F4A_7C15 |
| 118 | var z = state |
| 119 | z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9 |
| 120 | z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB |
| 121 | return z ^ (z >> 31) |
| 122 | } |
| 123 | } |
| 124 | |