import Foundation import XCTest @testable import DocsKit /// Block render equivalence (spec 2026-11-22 §11, Low 17): random edit /// sequences on the production replica, published to a `DocumentSurface` /// as the model publishes them. After each publication the storage built /// block by block equals a whole render of the same projection, attribute /// for attribute. @MainActor final class BlockRenderEquivalenceTests: XCTestCase { /// A document with nested lists, a quote, headings, inline code, an /// image, a rule and alignment. static var fixture: [JSONValue] { func text(_ insert: String, _ marks: [String: JSONValue] = [:]) -> JSONValue { .object(["type": .string("text"), "runs": .array([.object(["insert": .string(insert), "marks": .object(marks)])])]) } func block(_ type: String, _ children: [JSONValue], attrs: [String: String] = [:]) -> JSONValue { var object: [String: JSONValue] = ["type": .string(type)] if !children.isEmpty { object["children"] = .array(children) } if !attrs.isEmpty { object["attrs"] = .object(attrs.mapValues(JSONValue.string)) } return .object(object) } func paragraph(_ insert: String, _ marks: [String: JSONValue] = [:], attrs: [String: String] = [:]) -> JSONValue { block("paragraph", [text(insert, marks)], attrs: attrs) } func item(_ children: [JSONValue]) -> JSONValue { block("list_item", children) } return [ block("heading", [text("Millbrook water report")], attrs: ["level": "1"]), paragraph("The survey began in spring."), block("paragraph", [text("Run "), text("make check", ["code": .object([:])]), text(" before the "), text("bold", ["strong": .object([:])]), text(" part.")]), block("bullet_list", [item([paragraph("Private wells")]), item([paragraph("Shared pumps"), block("bullet_list", [item([paragraph("North pump")]), item([paragraph("South pump")])])])]), block("heading", [text("Findings")], attrs: ["level": "2"]), block("blockquote", [paragraph("Water is life."), paragraph("— a resident")]), block("ordered_list", [item([paragraph("Survey the creek")]), item([paragraph("Build the dam")])], attrs: ["order": "3"]), paragraph("Centred note.", attrs: ["align": "center"]), block("paragraph", [.object(["type": .string("image"), "attrs": .object(["src": .string(LoopFixture.picture), "alt": .string("A reservoir")])])]), block("horizontal_rule", []), block("code_block", [text("let x = 1\nlet y = 2")]), block("heading", [text("Small heading")], attrs: ["level": "3"]), paragraph("The end."), ] } static var pasted: [JSONValue] { [.object(["type": .string("heading"), "attrs": .object(["level": .string("2")]), "children": .array([.object(["type": .string("text"), "runs": .array([.object(["insert": .string("Pasted heading"), "marks": .object([:])])])])])]), .object(["type": .string("paragraph"), "children": .array([.object(["type": .string("text"), "runs": .array([.object(["insert": .string("Pasted words"), "marks": .object([:])])])])])])] } func testBlocksDrawnOnTheirOwnEqualAWholeRender() async throws { for seed: UInt64 in [1, 2, 3, 4, 5, 6] { try await run(seed: seed, steps: 50) } } private func run(seed: UInt64, steps: Int) async throws { var random = SeededRandom(seed: seed) let replica = CRDTReplica(guid: "equivalence-\(seed)") try await replica.open(update: Data()) _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array(Self.fixture)]) let state = SurfaceState(width: 640) let image = try XCTUnwrap(DocsAttachments.decode(Data(base64Encoded: String(LoopFixture.picture.split(separator: ",")[1]))!)) let images = [LoopFixture.picture: image] state.surface.imagesChanged(images) var generation: UInt64 = 0 var projection = try await replica.projection() func publish() async throws { await replica.retainGenerations([generation]) guard let presented = try await replica.presentation(source: generation, selection: NSRange(location: 0, length: 0), since: state.surface.appliedRevision) else { return } generation = presented.generation; projection = presented.projection state.allowed = generation state.surface.apply(DocumentSurface.Publication(generation: generation, projection: projection, revision: presented.revision, dirty: presented.dirty)) SurfaceFixture.assertMatchesWholeRender(state.surface.content, projection, images: images, "seed \(seed)") } try await publish() for step in 0..= length - 1 { end = ends.range(of: "\n").location } command = ["op": .string("display_edit"), "at": .number(Double(end)), "length": .number(1), "text": .string("")] case 4: command = ["op": .string("display_paste"), "at": .number(Double(at)), "length": .number(0), "blocks": .array(Self.pasted)] case 5: command = ["op": .string("undo")] case 6: command = ["op": .string("redo")] case 7: let range = NSRange(location: at, length: min(6, max(0, length - 1 - at))) let marks: [String: JSONValue] = random.next() % 2 == 0 ? ["code": .object([:])] : ["strong": .object([:])] command = ["op": .string("batch"), "commands": .array(DocumentCommands.markCommands(content: content, selection: range, marks: marks).map(JSONValue.object))] case 8: let node = projection.children[Int(random.next() % UInt64(projection.children.count))] command = ["op": .string("block"), "node": .string(node.id), "type": .string(random.next() % 2 == 0 ? "heading" : "paragraph"), "level": .number(2)] default: let node = projection.children[Int(random.next() % UInt64(projection.children.count))] command = ["op": .string("attribute"), "node": .string(node.id), "name": .string("align"), "value": .string(random.next() % 2 == 0 ? "right" : "center")] } _ = try? await replica.command(command) // Not every change is published: some accumulate, as when // publications are dropped or deferred. if random.next() % 3 != 0 { try await publish() } } try await publish() await replica.close() } } /// SplitMix64: the same sequence on every run and platform. struct SeededRandom { private var state: UInt64 init(seed: UInt64) { state = seed } mutating func next() -> UInt64 { state &+= 0x9E37_79B9_7F4A_7C15 var z = state z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9 z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB return z ^ (z >> 31) } }