import Foundation import XCTest @testable import DocsKit /// Delta safety through the real text view (spec 2026-11-22 §11, finding /// 1): a `DocsTextView` taking optimistic typing, fed by the production /// replica as `DocsModel` feeds it, while publications are dropped (as /// `publishCurrent`'s guards drop them), delayed past later ones, and /// interleaved with extra `projection()` calls; while ja and zh marked text /// is composed with a peer editing the same block and another; and with a /// dirty log so short it overflows. At quiescence the storage equals a /// whole render of the replica's projection. @MainActor final class DeltaSafetyTests: XCTestCase { func testPublicationsDroppedDelayedAndExtraProjections() async throws { for seed: UInt64 in [11, 12, 13] { try await run(seed: seed, logLimit: 512) } } func testALogThatOverflows() async throws { for seed: UInt64 in [21, 22, 23] { try await run(seed: seed, logLimit: 2) } } /// A replace across blocks, from the middle of one to the middle of a /// later one, by typing, a cut and a paste; the replica takes none of /// them (it rolled the edit back, or clamped it), so the publication /// that follows names no block as changed. The storage must still come /// back to the replica's text: the block that lost its head too, not /// only the one holding what was typed (Fable on #170, finding 1). func testAReplaceAcrossBlocksTheReplicaRefusesIsUndone() async throws { enum Edit { case type, cut, paste } for edit in [Edit.type, .cut, .paste] { let replica = CRDTReplica(guid: "across-\(edit)") try await replica.open(update: Data()) _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) let blocks: [JSONValue] = ["aaaa", "bbbb", "cccc", "dddd"].map { text in .object(["type": .string("paragraph"), "children": .array([.object(["type": .string("text"), "runs": .array([.object(["insert": .string(text), "marks": .object([:])])])])])]) } _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array(blocks)]) let state = SurfaceState(width: 640) state.surface.hooks.edit = { _ in true } // accepted, then refused by the replica: never applied func publish() async throws { await replica.retainGenerations([state.surface.generation]) let answer = try await replica.presentation(source: state.surface.generation, selection: NSRange(location: 0, length: 0), since: state.surface.appliedRevision) let presented = try XCTUnwrap(answer) state.allowed = presented.generation state.surface.apply(DocumentSurface.Publication(generation: presented.generation, projection: presented.projection, revision: presented.revision, dirty: presented.dirty)) } try await publish() let text = state.text let shown = state.surface.content.string as NSString let from = shown.range(of: "aaaa").location + 2, to = shown.range(of: "cccc").location + 2 Keyboard.select(NSRange(location: from, length: to - from), in: text) switch edit { case .type: Keyboard.type("X", in: text) case .cut: Keyboard.cutSelection(in: text, surface: state.surface) case .paste: Keyboard.paste(BlockRenderEquivalenceTests.pasted, in: text, surface: state.surface) } XCTAssertNotEqual(state.surface.content.string, "aaaa\nbbbb\ncccc\ndddd\n", "\(edit): the text view showed the edit") try await publish() SurfaceFixture.assertMatchesWholeRender(state.surface.content, try await replica.projection(), "\(edit) across blocks, refused") await replica.close() } } private final class Harness { let replica: CRDTReplica let peer: CRDTReplica let state: SurfaceState var queue: [[String: JSONValue]] = [] var projectionGeneration: UInt64 = 0 var held: DocumentSurface.Publication? init(replica: CRDTReplica, peer: CRDTReplica, state: SurfaceState) { self.replica = replica; self.peer = peer; self.state = state } } private func run(seed: UInt64, logLimit: Int) async throws { var random = SeededRandom(seed: seed) let replica = CRDTReplica(guid: "delta-\(seed)", dirtyLogLimit: logLimit) 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(BlockRenderEquivalenceTests.fixture)]) let peer = CRDTReplica(guid: "delta-\(seed)") try await peer.open(update: try await replica.persistentState().state) let state = SurfaceState(width: 640) let h = Harness(replica: replica, peer: peer, state: state) state.surface.hooks.edit = { command in h.queue.append(command); state.pending = true; return true } state.surface.hooks.compositionChanged = { active in if !active { state.surface.flushIfDeferred() } } let text = state.text /// The model's drain: every queued command to the replica (and the /// peer hears it), then input is no longer pending. func drain() async throws { while !h.queue.isEmpty { let command = h.queue.removeFirst() if let update = try? await replica.command(command) { try? await peer.apply(update) } } state.pending = false state.surface.flushIfDeferred() // trigger (b) } /// The model's publish; `fate` decides whether it is drawn now, /// dropped, or held back and delivered after a later one. enum Fate { case publish, drop, hold } func publish(_ fate: Fate) async throws { await replica.retainGenerations([state.surface.generation, h.projectionGeneration]) guard let presented = try await replica.presentation(source: state.surface.generation, selection: state.selection, allowReuse: false, since: state.surface.appliedRevision) else { return } let publication = DocumentSurface.Publication(generation: presented.generation, projection: presented.projection, revision: presented.revision, dirty: presented.dirty) switch fate { case .drop: return case .hold: h.held = publication case .publish: h.projectionGeneration = presented.generation; state.allowed = presented.generation state.selection = presented.selection state.surface.apply(publication) if let held = h.held, random.next() % 2 == 0 { h.held = nil; state.surface.apply(held) } // delayed: stale, dropped } } func peerEdit(near location: Int) async throws { let shown = NativeTextProjection.render(try await peer.projection()).string as NSString let at = min(max(0, location), max(0, shown.length - 1)) // A position the engine refuses (inside an image) changes nothing. guard let update = try? await peer.command(["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(0), "text": .string("P")]) else { return } try await replica.apply(update) } func caret() -> Int { let length = state.surface.content.length return Int(random.next() % UInt64(max(1, length - 1))) } try await publish(.publish) for step in 0..<60 { switch random.next() % 9 { case 0, 1: Keyboard.select(NSRange(location: caret(), length: 0), in: text) Keyboard.type(step % 5 == 0 ? "a\nb" : "xy", in: text) case 2: try await drain() case 3: try await publish(random.next() % 3 == 0 ? .drop : random.next() % 2 == 0 ? .hold : .publish) case 4: for _ in 0.. Bool { #if os(macOS) text.hasMarkedText() #else text.markedTextRange != nil #endif } }