Docs native S1b: a seeded pagination fuzz gate
Fable on #173, finding 3, adopting that review's fuzz. Random storage edits on a bare paged text view, 8 fixed seeds × 80 edits, with and without a window (4/3), paged and pageless; every fourth edit, breaks, separators, every line origin (0.5 pt) and the frame height are compared with a fresh DocumentPageLayoutOracle run (paged) or a whole plain layout (pageless). The edits: characters, wrapping inserts, Return, a whole block deleted, in-paragraph deletes, pastes of 1–4 rendered blocks with headings, a block replaced by another kind, two distant edits in one editing group, a Backspace at a block's start then its publication, Pages toggled, jumps with a single idle chunk, and every block's attributes at once (kern, which moves every line, or metadata): the path where more than 50 blocks changed. Lines laid out between comparisons stay laid out, so a missed invalidation shows. About 120 comparisons, 60 of them begun with measuring incomplete; 2–3 s. Seen to fail with the live layout's invalidation removed (line origins off by 42–114 pt).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+212
−0
native/apple/Tests/DocsKitTests/PaginationEquivalenceTests.swift+212 −0
diff --git a/native/apple/Tests/DocsKitTests/PaginationEquivalenceTests.swift b/native/apple/Tests/DocsKitTests/PaginationEquivalenceTests.swift| index ece0cdc..6d8d462 100644 |
| --- a/native/apple/Tests/DocsKitTests/PaginationEquivalenceTests.swift |
| +++ b/native/apple/Tests/DocsKitTests/PaginationEquivalenceTests.swift |
| @@ -318,3 +318,215 @@ import XCTest |
| } |
| } |
| #endif |
| + |
| +#if os(macOS) |
| +/// A seeded fuzz gate against the oracle (Fable on #173, finding 3, after |
| +/// the fuzz of that review): random storage edits on a bare paged text view, |
| +/// with and without a window, compared with a fresh `DocumentPageLayoutOracle` |
| +/// run (paged) or a whole plain layout (pageless) every few edits. It |
| +/// covers what the scripted test does not: edits while measuring is still |
| +/// incomplete, the path where more than 50 blocks changed at once, pageless |
| +/// line origins, two edits in one editing group, Pages toggled, jumps, |
| +/// single idle chunks, and long mixed sequences. Fixed seeds, a few seconds. |
| +@MainActor final class PaginationFuzzTests: XCTestCase { |
| + struct Generator { |
| + var state: UInt64 |
| + 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) |
| + } |
| + mutating func below(_ bound: Int) -> Int { bound <= 0 ? 0 : Int(next() % UInt64(bound)) } |
| + } |
| + |
| + static func fixture() -> [CRDTNode] { |
| + var nodes = (1...20).map { SurfaceFixture.paragraph("a\($0)", PaginationEquivalenceTests.ledger($0) + ($0 % 4 == 0 ? " And a longer sentence that wraps onto a second line of the page." : "")) } |
| + nodes.append(SurfaceFixture.heading("h1", "A heading near a break", level: 1)) |
| + nodes += (21...34).map { SurfaceFixture.paragraph("a\($0)", PaginationEquivalenceTests.ledger($0)) } |
| + nodes.append(CRDTNode(id: "img", type: "paragraph", children: [CRDTNode(id: "imgi", type: "image", attrs: ["src": PaginationEquivalenceTests.picture, "alt": "A picture"])])) |
| + nodes.append(SurfaceFixture.list("list", "bullet_list", (1...30).map { "Item \($0) of a long list" })) |
| + nodes.append(CRDTNode(id: "code", type: "paragraph", children: [CRDTNode(id: "codet", type: "text", runs: [ |
| + CRDTRun(insert: "inline.code", marks: ["code": .object([:])]), CRDTRun(insert: " starts this line, which goes on long enough to wrap at the edge."), |
| + ])])) |
| + nodes += (35...44).map { SurfaceFixture.paragraph("a\($0)", PaginationEquivalenceTests.ledger($0)) } |
| + return nodes |
| + } |
| + |
| + @MainActor final class Host { |
| + let view = DocsTextView(frame: CGRect(x: 0, y: 0, width: DocsDeskLayout.paperWidth, height: 700)) |
| + var window: NSWindow? |
| + init(window inWindow: Bool, paged: Bool) { |
| + view.paged = paged |
| + if inWindow { |
| + let scroll = NSScrollView(frame: NSRect(x: 0, y: 0, width: 1000, height: 800)) |
| + scroll.hasVerticalScroller = true |
| + scroll.allowsMagnification = true |
| + scroll.documentView = DocsDeskView(page: view) |
| + scroll.magnification = 4.0 / 3.0 |
| + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 800), styleMask: [.titled], backing: .buffered, defer: false) |
| + window.isReleasedWhenClosed = false |
| + window.contentView = scroll |
| + self.window = window |
| + } |
| + } |
| + func close() { window?.contentView = nil; window?.close() } |
| + } |
| + |
| + static func render(_ nodes: [CRDTNode]) -> NSAttributedString { |
| + NativeTextProjection.render(SurfaceFixture.projection(nodes), images: PaginationEquivalenceTests.images) |
| + } |
| + |
| + /// The whole layout pageless production must equal: the storage laid |
| + /// out plainly in the live container's geometry, no breaks. |
| + static func plain(_ storage: NSAttributedString) -> PaginationEquivalenceTests.Plan { |
| + let copy = NSTextStorage(attributedString: storage) |
| + let manager = DocsLayoutManager() |
| + let container = DocsPageTextContainer(size: CGSize(width: DocsDeskLayout.paperWidth, height: 1_000_000)) |
| + container.lineFragmentPadding = 0 |
| + container.geometry = DocsPageGeometry(viewportWidth: DocsDeskLayout.paperWidth, paged: false) |
| + container.isMeasurement = true |
| + copy.addLayoutManager(manager) |
| + manager.addTextContainer(container) |
| + manager.ensureLayout(for: container) |
| + let bottom = manager.numberOfGlyphs > 0 ? manager.lineFragmentRect(forGlyphAt: manager.numberOfGlyphs - 1, effectiveRange: nil).maxY : DocsPageGeometry.verticalMargin |
| + let lines = PaginationEquivalenceTests.lines(manager) |
| + withExtendedLifetime(copy) {} |
| + return .init(starts: [:], separators: [], lines: lines, height: container.geometry.documentHeight(usedHeight: bottom)) |
| + } |
| + |
| + /// After a Backspace at a block's start, until its publication, one |
| + /// paragraph holds two runs; the oracle may break between them, and |
| + /// production may not (§7 Design 4): no comparison then. |
| + static func transient(_ storage: NSAttributedString) -> Bool { |
| + let characters = storage.string as NSString |
| + var found = false |
| + storage.enumerateAttribute(.docsTopBlock, in: NSRange(location: 0, length: storage.length)) { _, range, stop in |
| + if range.location > 0, characters.character(at: range.location - 1) != 10 { found = true; stop.pointee = true } |
| + } |
| + return found |
| + } |
| + |
| + func testSeededEditsMatchTheOracle() throws { |
| + DocsFonts.register() |
| + var comparisons = 0, incomplete = 0, stalePath = 0 |
| + let start = ContinuousClock.now |
| + for seed in UInt64(1)...8 { |
| + var random = Generator(state: seed &* 7919) |
| + let host = Host(window: seed % 2 == 0, paged: seed % 4 != 3) |
| + defer { host.close() } |
| + let view = host.view |
| + let storage = view.textStorage! |
| + storage.setAttributedString(Self.render(Self.fixture())) |
| + var fresh = 0 |
| + func paragraphStarts() -> [Int] { |
| + let characters = storage.string as NSString |
| + var starts = [0] |
| + for index in 0..<max(0, storage.length - 1) where characters.character(at: index) == 10 { starts.append(index + 1) } |
| + return starts |
| + } |
| + func attributes(at location: Int) -> [NSAttributedString.Key: Any] { |
| + storage.length == 0 ? [:] : storage.attributes(at: min(max(0, location - 1), storage.length - 1), effectiveRange: nil) |
| + } |
| + func block(at location: Int) -> NSRange { |
| + var range = NSRange() |
| + _ = storage.attribute(.docsTopBlock, at: min(location, storage.length - 1), longestEffectiveRange: &range, in: NSRange(location: 0, length: storage.length)) |
| + return range |
| + } |
| + func newBlocks(_ count: Int) -> NSAttributedString { |
| + let nodes: [CRDTNode] = (0..<count).map { _ in |
| + fresh += 1 |
| + return fresh % 3 == 0 ? SurfaceFixture.heading("n\(seed)-\(fresh)", "A pasted heading \(fresh)", level: 1 + fresh % 3) |
| + : SurfaceFixture.paragraph("n\(seed)-\(fresh)", "A pasted paragraph \(fresh), with enough words in it to wrap the line once or twice.") |
| + } |
| + return Self.render(nodes) |
| + } |
| + func edit() { |
| + let length = storage.length |
| + let at = random.below(max(1, length - 1)) |
| + switch random.below(13) { |
| + case 0, 1: storage.replaceCharacters(in: NSRange(location: at, length: 0), with: NSAttributedString(string: "x", attributes: attributes(at: at))) |
| + case 2: storage.replaceCharacters(in: NSRange(location: at, length: 0), with: NSAttributedString(string: " words enough to wrap this line onto the next one of the page", attributes: attributes(at: at))) |
| + case 3: storage.replaceCharacters(in: NSRange(location: at, length: 0), with: NSAttributedString(string: "\n", attributes: attributes(at: at))) |
| + case 4: |
| + let range = block(at: at) |
| + if range.length < length { storage.replaceCharacters(in: range, with: "") } |
| + case 5: |
| + let paragraph = (storage.string as NSString).paragraphRange(for: NSRange(location: at, length: 0)) |
| + let cut = NSRange(location: paragraph.location + random.below(max(1, paragraph.length - 1)), length: min(5, max(0, paragraph.length - 2))) |
| + if NSMaxRange(cut) < NSMaxRange(paragraph) { storage.replaceCharacters(in: cut, with: "") } |
| + case 6: |
| + let starts = paragraphStarts() |
| + storage.replaceCharacters(in: NSRange(location: starts[random.below(starts.count)], length: 0), with: newBlocks(1 + random.below(4))) |
| + case 7: |
| + let range = block(at: at) |
| + if range.length < length { storage.replaceCharacters(in: range, with: newBlocks(1)) } |
| + case 8: |
| + storage.beginEditing() |
| + storage.replaceCharacters(in: NSRange(location: at / 2, length: 0), with: NSAttributedString(string: "early words that wrap the line ", attributes: attributes(at: at / 2))) |
| + let later = min(storage.length - 1, at + storage.length / 2) |
| + storage.replaceCharacters(in: NSRange(location: later, length: 0), with: NSAttributedString(string: "\n", attributes: attributes(at: later))) |
| + storage.endEditing() |
| + case 9: |
| + // A Backspace at a block's start, then its publication: |
| + // the merged paragraph drawn as one block. |
| + let starts = paragraphStarts().filter { $0 > 0 } |
| + guard let joint = starts.isEmpty ? nil : starts[random.below(starts.count)] else { return } |
| + storage.replaceCharacters(in: NSRange(location: joint - 1, length: 1), with: "") |
| + view.layout() |
| + let merged = (storage.string as NSString).paragraphRange(for: NSRange(location: joint - 1, length: 0)) |
| + let text = (storage.string as NSString).substring(with: merged).trimmingCharacters(in: .newlines) |
| + fresh += 1 |
| + storage.replaceCharacters(in: merged, with: Self.render([SurfaceFixture.paragraph("m\(seed)-\(fresh)", text.isEmpty ? "Merged." : text)])) |
| + case 10: view.paged.toggle() |
| + case 11: |
| + view.scrollRangeToVisible(NSRange(location: at, length: 0)) |
| + view.pagination.update(visibleBottom: -.greatestFiniteMagnitude, idle: true) |
| + default: |
| + // Every block's attributes at once: more than 50 stale |
| + // blocks (in a window, the full path's visible-first order). |
| + if view.pagination.units.filter({ !$0.measured }).isEmpty && view.pagination.units.count > DocsPagination.staleLimit { stalePath += 1 } |
| + // Half the time something that moves every line (as a font |
| + // every block uses arriving would), else metadata only. |
| + if random.below(2) == 0 { |
| + storage.addAttribute(.kern, value: CGFloat(random.below(4)) * 0.1, range: NSRange(location: 0, length: storage.length)) |
| + } else { |
| + storage.addAttribute(NSAttributedString.Key("FuzzMetadata"), value: random.below(1000), range: NSRange(location: 0, length: storage.length)) |
| + } |
| + } |
| + } |
| + func compare(_ label: String) { |
| + guard !Self.transient(storage) else { return } |
| + if !view.pagination.isComplete { incomplete += 1 } |
| + comparisons += 1 |
| + let expected = view.paged ? PaginationEquivalenceTests.oracle(storage) : Self.plain(storage) |
| + let actual = PaginationEquivalenceTests.production(view) |
| + XCTAssertEqual(Set(actual.starts.keys), Set(expected.starts.keys), "breaks: \(label)") |
| + for (location, top) in expected.starts { if let mine = actual.starts[location] { XCTAssertEqual(mine, top, accuracy: 0.5, "break top: \(label)") } } |
| + XCTAssertEqual(actual.separators.count, expected.separators.count, "separators: \(label)") |
| + for (mine, theirs) in zip(actual.separators, expected.separators) { XCTAssertEqual(mine, theirs, accuracy: 0.5, "separator: \(label)") } |
| + XCTAssertEqual(Set(actual.lines.keys), Set(expected.lines.keys), "line starts: \(label)") |
| + let worst = expected.lines.map { start, origin in actual.lines[start].map { max(abs($0.y - origin.y), abs($0.x - origin.x)) } ?? 0 }.max() ?? 0 |
| + XCTAssertLessThanOrEqual(worst, 0.5, "line origins: \(label)") |
| + XCTAssertEqual(actual.height, expected.height, accuracy: 0.5, "frame height: \(label)") |
| + } |
| + view.layout() |
| + for step in 0..<80 { |
| + edit() |
| + // Sometimes a turn passes (the text view lays out) before the next edit. |
| + if random.below(2) == 0 { view.layout() } |
| + if step % 4 == 3 { compare("seed \(seed) step \(step) (\(view.paged ? "paged" : "pageless"), \(host.window == nil ? "no window" : "window"))") } |
| + // Lines laid out between edits stay laid out, so a missed |
| + // invalidation shows as a stale origin later. |
| + if step % 4 == 1, storage.length > 0 { |
| + view.layoutManager!.ensureLayout(forCharacterRange: NSRange(location: random.below(storage.length), length: 1)) |
| + } |
| + } |
| + } |
| + print("PAGINATION FUZZ: \(comparisons) comparisons, \(incomplete) with measuring incomplete, \(stalePath) whole-document attribute edits, \(start.duration(to: .now))") |
| + XCTAssertGreaterThan(incomplete, 0, "edits compared while measuring was incomplete") |
| + XCTAssertGreaterThan(stalePath, 0, "the more-than-50-stale path ran") |
| + } |
| +} |
| +#endif |