| 1 | import Foundation |
| 2 | import XCTest |
| 3 | @testable import DocsKit |
| 4 | |
| 5 | /// Delta safety through the real text view (spec 2026-11-22 §11, finding |
| 6 | /// 1): a `DocsTextView` taking optimistic typing, fed by the production |
| 7 | /// replica as `DocsModel` feeds it, while publications are dropped (as |
| 8 | /// `publishCurrent`'s guards drop them), delayed past later ones, and |
| 9 | /// interleaved with extra `projection()` calls; while ja and zh marked text |
| 10 | /// is composed with a peer editing the same block and another; and with a |
| 11 | /// dirty log so short it overflows. At quiescence the storage equals a |
| 12 | /// whole render of the replica's projection. |
| 13 | @MainActor final class DeltaSafetyTests: XCTestCase { |
| 14 | func testPublicationsDroppedDelayedAndExtraProjections() async throws { |
| 15 | for seed: UInt64 in [11, 12, 13] { try await run(seed: seed, logLimit: 512) } |
| 16 | } |
| 17 | func testALogThatOverflows() async throws { |
| 18 | for seed: UInt64 in [21, 22, 23] { try await run(seed: seed, logLimit: 2) } |
| 19 | } |
| 20 | |
| 21 | /// A replace across blocks, from the middle of one to the middle of a |
| 22 | /// later one, by typing, a cut and a paste; the replica takes none of |
| 23 | /// them (it rolled the edit back, or clamped it), so the publication |
| 24 | /// that follows names no block as changed. The storage must still come |
| 25 | /// back to the replica's text: the block that lost its head too, not |
| 26 | /// only the one holding what was typed (Fable on #170, finding 1). |
| 27 | func testAReplaceAcrossBlocksTheReplicaRefusesIsUndone() async throws { |
| 28 | enum Edit { case type, cut, paste } |
| 29 | for edit in [Edit.type, .cut, .paste] { |
| 30 | let replica = CRDTReplica(guid: "across-\(edit)") |
| 31 | try await replica.open(update: Data()) |
| 32 | _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) |
| 33 | let blocks: [JSONValue] = ["aaaa", "bbbb", "cccc", "dddd"].map { text in |
| 34 | .object(["type": .string("paragraph"), "children": .array([.object(["type": .string("text"), "runs": .array([.object(["insert": .string(text), "marks": .object([:])])])])])]) |
| 35 | } |
| 36 | _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array(blocks)]) |
| 37 | let state = SurfaceState(width: 640) |
| 38 | state.surface.hooks.edit = { _ in true } // accepted, then refused by the replica: never applied |
| 39 | func publish() async throws { |
| 40 | await replica.retainGenerations([state.surface.generation]) |
| 41 | let answer = try await replica.presentation(source: state.surface.generation, selection: NSRange(location: 0, length: 0), since: state.surface.appliedRevision) |
| 42 | let presented = try XCTUnwrap(answer) |
| 43 | state.allowed = presented.generation |
| 44 | state.surface.apply(DocumentSurface.Publication(generation: presented.generation, projection: presented.projection, revision: presented.revision, dirty: presented.dirty)) |
| 45 | } |
| 46 | try await publish() |
| 47 | let text = state.text |
| 48 | let shown = state.surface.content.string as NSString |
| 49 | let from = shown.range(of: "aaaa").location + 2, to = shown.range(of: "cccc").location + 2 |
| 50 | Keyboard.select(NSRange(location: from, length: to - from), in: text) |
| 51 | switch edit { |
| 52 | case .type: Keyboard.type("X", in: text) |
| 53 | case .cut: Keyboard.cutSelection(in: text, surface: state.surface) |
| 54 | case .paste: Keyboard.paste(BlockRenderEquivalenceTests.pasted, in: text, surface: state.surface) |
| 55 | } |
| 56 | XCTAssertNotEqual(state.surface.content.string, "aaaa\nbbbb\ncccc\ndddd\n", "\(edit): the text view showed the edit") |
| 57 | try await publish() |
| 58 | SurfaceFixture.assertMatchesWholeRender(state.surface.content, try await replica.projection(), "\(edit) across blocks, refused") |
| 59 | await replica.close() |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | private final class Harness { |
| 64 | let replica: CRDTReplica |
| 65 | let peer: CRDTReplica |
| 66 | let state: SurfaceState |
| 67 | var queue: [[String: JSONValue]] = [] |
| 68 | var projectionGeneration: UInt64 = 0 |
| 69 | var held: DocumentSurface.Publication? |
| 70 | init(replica: CRDTReplica, peer: CRDTReplica, state: SurfaceState) { self.replica = replica; self.peer = peer; self.state = state } |
| 71 | } |
| 72 | |
| 73 | private func run(seed: UInt64, logLimit: Int) async throws { |
| 74 | var random = SeededRandom(seed: seed) |
| 75 | let replica = CRDTReplica(guid: "delta-\(seed)", dirtyLogLimit: logLimit) |
| 76 | try await replica.open(update: Data()) |
| 77 | _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) |
| 78 | _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array(BlockRenderEquivalenceTests.fixture)]) |
| 79 | let peer = CRDTReplica(guid: "delta-\(seed)") |
| 80 | try await peer.open(update: try await replica.persistentState().state) |
| 81 | let state = SurfaceState(width: 640) |
| 82 | let h = Harness(replica: replica, peer: peer, state: state) |
| 83 | state.surface.hooks.edit = { command in h.queue.append(command); state.pending = true; return true } |
| 84 | state.surface.hooks.compositionChanged = { active in if !active { state.surface.flushIfDeferred() } } |
| 85 | let text = state.text |
| 86 | |
| 87 | /// The model's drain: every queued command to the replica (and the |
| 88 | /// peer hears it), then input is no longer pending. |
| 89 | func drain() async throws { |
| 90 | while !h.queue.isEmpty { |
| 91 | let command = h.queue.removeFirst() |
| 92 | if let update = try? await replica.command(command) { try? await peer.apply(update) } |
| 93 | } |
| 94 | state.pending = false |
| 95 | state.surface.flushIfDeferred() // trigger (b) |
| 96 | } |
| 97 | /// The model's publish; `fate` decides whether it is drawn now, |
| 98 | /// dropped, or held back and delivered after a later one. |
| 99 | enum Fate { case publish, drop, hold } |
| 100 | func publish(_ fate: Fate) async throws { |
| 101 | await replica.retainGenerations([state.surface.generation, h.projectionGeneration]) |
| 102 | guard let presented = try await replica.presentation(source: state.surface.generation, selection: state.selection, allowReuse: false, since: state.surface.appliedRevision) else { return } |
| 103 | let publication = DocumentSurface.Publication(generation: presented.generation, projection: presented.projection, revision: presented.revision, dirty: presented.dirty) |
| 104 | switch fate { |
| 105 | case .drop: return |
| 106 | case .hold: h.held = publication |
| 107 | case .publish: |
| 108 | h.projectionGeneration = presented.generation; state.allowed = presented.generation |
| 109 | state.selection = presented.selection |
| 110 | state.surface.apply(publication) |
| 111 | if let held = h.held, random.next() % 2 == 0 { h.held = nil; state.surface.apply(held) } // delayed: stale, dropped |
| 112 | } |
| 113 | } |
| 114 | func peerEdit(near location: Int) async throws { |
| 115 | let shown = NativeTextProjection.render(try await peer.projection()).string as NSString |
| 116 | let at = min(max(0, location), max(0, shown.length - 1)) |
| 117 | // A position the engine refuses (inside an image) changes nothing. |
| 118 | guard let update = try? await peer.command(["op": .string("display_edit"), "at": .number(Double(at)), "length": .number(0), "text": .string("P")]) else { return } |
| 119 | try await replica.apply(update) |
| 120 | } |
| 121 | func caret() -> Int { |
| 122 | let length = state.surface.content.length |
| 123 | return Int(random.next() % UInt64(max(1, length - 1))) |
| 124 | } |
| 125 | |
| 126 | try await publish(.publish) |
| 127 | for step in 0..<60 { |
| 128 | switch random.next() % 9 { |
| 129 | case 0, 1: |
| 130 | Keyboard.select(NSRange(location: caret(), length: 0), in: text) |
| 131 | Keyboard.type(step % 5 == 0 ? "a\nb" : "xy", in: text) |
| 132 | case 2: try await drain() |
| 133 | case 3: try await publish(random.next() % 3 == 0 ? .drop : random.next() % 2 == 0 ? .hold : .publish) |
| 134 | case 4: for _ in 0..<Int(random.next() % 4) { _ = try await replica.projection() } |
| 135 | case 5: try await peerEdit(near: caret()) |
| 136 | case 7: |
| 137 | // A peer far from the caret, then the replica's own extra |
| 138 | // projections: only the log (or a full comparison) knows. |
| 139 | try await peerEdit(near: Int(random.next() % 4000)) |
| 140 | for _ in 0..<Int(random.next() % 3) { _ = try await replica.projection() } |
| 141 | case 6: |
| 142 | // Compose ja or zh while the peer edits this block and another, |
| 143 | // and publications arrive. |
| 144 | try await drain() |
| 145 | let at = caret() |
| 146 | Keyboard.select(NSRange(location: at, length: 0), in: text) |
| 147 | let words = step % 2 == 0 ? ["に", "にほ", "日本"] : ["z", "zh", "中文"] |
| 148 | for word in words.dropLast() { Self.mark(word, in: text) } |
| 149 | try await peerEdit(near: at) |
| 150 | try await peerEdit(near: at + 40) |
| 151 | try await publish(.publish) |
| 152 | XCTAssertTrue(Self.hasMarkedText(text), "seed \(seed): a publication must not replace marked text") |
| 153 | Self.mark(words.last!, in: text) |
| 154 | Self.commit(text) |
| 155 | try await drain() |
| 156 | default: |
| 157 | try await drain(); try await publish(.publish) |
| 158 | } |
| 159 | } |
| 160 | // Quiescence. |
| 161 | try await drain() |
| 162 | try await publish(.publish) |
| 163 | let final = try await replica.projection() |
| 164 | SurfaceFixture.assertMatchesWholeRender(state.surface.content, final, "seed \(seed), log \(logLimit)") |
| 165 | XCTAssertEqual(state.surface.index.runs, DocumentBlockIndex.runs(in: state.surface.content), "seed \(seed): the index") |
| 166 | await replica.close(); await peer.close() |
| 167 | } |
| 168 | |
| 169 | private static func mark(_ word: String, in text: DocsTextView) { |
| 170 | #if os(macOS) |
| 171 | text.setMarkedText(word, selectedRange: NSRange(location: word.utf16.count, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0)) |
| 172 | #else |
| 173 | text.setMarkedText(word, selectedRange: NSRange(location: word.utf16.count, length: 0)) |
| 174 | #endif |
| 175 | } |
| 176 | private static func commit(_ text: DocsTextView) { text.unmarkText() } |
| 177 | private static func hasMarkedText(_ text: DocsTextView) -> Bool { |
| 178 | #if os(macOS) |
| 179 | text.hasMarkedText() |
| 180 | #else |
| 181 | text.markedTextRange != nil |
| 182 | #endif |
| 183 | } |
| 184 | } |
| 185 | |