oficina / docs Public

Docs native S1b: iPhone keystroke and large-document probes

Probes, skipped unless their environment is set, that S1b's discussion
reports from:

- SurfaceTimingTests.testKeystroke: per key, the keyboard's path into the
  iPhone text view and the layout UIKit runs before it draws, with the
  line-fragment requests our container gets, at 1 to 200 pages.
- PhoneLargeDocumentTests (DOCS_PHONE_LARGE): §7's iPhone check on 200
  pages paged, opening, typing and jumping to the end, and the same edits
  on a bare layout stack with background layout on and off. It fails on
  the iPhone as it is: UIKit's TextKit 1 lays out a container that is not
  a simple rectangle contiguously, and its background layout (not public
  API on iOS) lays the rest of the document out synchronously after any
  edit that changes a line count. The spec's iPhone plan cannot hold;
  the discussion has the numbers and the options.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 8dffa3d37759844d47b55d8a1500c84072527f9b parent 59592b6
3 files changed, +196 −0
  • native/apple/Tests/DocsKitTests/PhoneLargeDocumentTests.swift +131 −0
  • native/apple/Tests/DocsKitTests/SurfaceTimingTests.swift +64 −0
  • native/ios/project.yml +1 −0
diff --git a/native/apple/Tests/DocsKitTests/PhoneLargeDocumentTests.swift b/native/apple/Tests/DocsKitTests/PhoneLargeDocumentTests.swift
new file mode 100644
index 0000000..308cbc9
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/PhoneLargeDocumentTests.swift
@@ -0,0 +1,131 @@
+#if os(iOS) && DOCS_PROBES
+import UIKit
+import XCTest
+@testable import DocsKit
+
+/// The iPhone's large-document check (spec 2026-11-22 §7 "iPhone layout";
+/// §11 "Large documents"), as a probe: skipped unless DOCS_PHONE_LARGE is
+/// set (TEST_RUNNER_DOCS_PHONE_LARGE=1 through xcodebuild). S1b found the
+/// spec's iPhone plan cannot hold with UIKit's TextKit 1 (discussion on
+/// perf/native-s1b): the container is not a simple rectangle, so the
+/// layout manager never lays out non-contiguously, and its background
+/// layout (on, and not public API on iOS) lays the rest of the document out
+/// synchronously after every edit that changes a line count. This prints
+/// what opening a 200-page document paged, typing in its middle and
+/// jumping to its end cost, and runs the check's assertions; then the same
+/// storage edits on a bare stack with the non-public `backgroundLayoutEnabled`
+/// off, for comparison (setting it on the text view's own manager ended the
+/// test process).
+@MainActor final class PhoneLargeDocumentTests: XCTestCase {
+ func testJumpToTheEndOfALongPagedDocument() async throws {
+ guard ProcessInfo.processInfo.environment["DOCS_PHONE_LARGE"] != nil else { throw XCTSkip("Set DOCS_PHONE_LARGE") }
+ DocsFonts.register()
+ let projection = SurfaceFixture.projection(SurfaceFixture.pages(200))
+ do {
+ let mode = "as shipped"
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
+ window.makeKeyAndVisible()
+ let text = DocsTextView(frame: window.bounds)
+ text.paged = true
+ window.addSubview(text)
+ let surface = DocumentSurface()
+ var hooks = DocumentSurface.Hooks()
+ hooks.edit = { _ in true }
+ surface.hooks = hooks
+ surface.isEditable = true
+ surface.attach(text)
+ var requests = DocsProbes.lineRequests
+ var start = ContinuousClock.now
+ surface.apply(DocumentSurface.Publication(generation: 1, projection: projection, revision: 1, dirty: nil))
+ text.layoutIfNeeded()
+ let manager = text.layoutManager
+ let container = text.textContainer
+ let storage = text.textStorage
+ print("PHONE LARGE \(mode): open \(start.duration(to: .now)), \(DocsProbes.lineRequests - requests) line requests; laid out to \(manager.firstUnlaidCharacterIndex()) of \(storage.length)")
+ XCTAssertNil(manager.textContainer(forGlyphAt: manager.numberOfGlyphs - 1, effectiveRange: nil, withoutAdditionalLayout: true),
+ "\(mode): nothing at the end is laid out at open")
+
+ // Keys in the middle, one of them making a new line.
+ let middle = storage.length / 2
+ for (index, typed) in ["x", "x", String(repeating: "Words to wrap the line. ", count: 4), "x"].enumerated() {
+ let range = NSRange(location: middle, length: 0)
+ requests = DocsProbes.lineRequests
+ start = .now
+ if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: typed) ?? true {
+ storage.replaceCharacters(in: range, with: NSAttributedString(string: typed, attributes: text.typingAttributes))
+ text.selectedRange = NSRange(location: range.location + typed.utf16.count, length: 0)
+ text.delegate?.textViewDidChange?(text)
+ }
+ text.layoutIfNeeded()
+ print("PHONE LARGE \(mode): key \(index) (\(typed.count) characters): \(start.duration(to: .now)), \(DocsProbes.lineRequests - requests) line requests")
+ }
+
+ // The jump.
+ let end = storage.length - 8
+ requests = DocsProbes.lineRequests
+ start = .now
+ text.selectedRange = NSRange(location: end, length: 0)
+ text.scrollRangeToVisible(text.selectedRange)
+ text.layoutIfNeeded()
+ print("PHONE LARGE \(mode): jump to the end \(start.duration(to: .now)), \(DocsProbes.lineRequests - requests) line requests")
+ let geometry = (container as! DocsPageTextContainer).geometry
+ let glyph = manager.glyphIndexForCharacter(at: end)
+ let line = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil)
+ let caret = text.caretRect(for: text.selectedTextRange!.start)
+ print("PHONE LARGE \(mode): caret \(caret), its glyph's line \(line)")
+ XCTAssertTrue(caret.midY > line.minY && caret.midY < line.maxY, "\(mode): the caret (\(caret)) is on its glyph's line (\(line))")
+ let shown = manager.glyphRange(forBoundingRect: text.bounds, in: container)
+ manager.enumerateLineFragments(forGlyphRange: shown) { rect, _, _, _, _ in
+ let page = geometry.page(at: rect.minY)
+ let top = CGFloat(page) * geometry.stride + DocsPageGeometry.verticalMargin
+ XCTAssertGreaterThanOrEqual(rect.minY, top - 0.01, "\(mode): a line (\(rect)) starts in a gap")
+ XCTAssertLessThanOrEqual(rect.maxY, top + geometry.bodyHeight + 0.01, "\(mode): a line (\(rect)) straddles a page gap")
+ }
+ // Settled: the lines near the end against a whole layout.
+ let reference = NSTextStorage(attributedString: storage)
+ let referenceManager = NSLayoutManager()
+ referenceManager.usesFontLeading = false
+ let referenceContainer = DocsPageTextContainer(size: container.size)
+ referenceContainer.lineFragmentPadding = 0
+ referenceContainer.geometry = geometry
+ reference.addLayoutManager(referenceManager)
+ referenceManager.addTextContainer(referenceContainer)
+ referenceManager.ensureLayout(for: referenceContainer)
+ var mismatches = 0, compared = 0
+ manager.enumerateLineFragments(forGlyphRange: shown) { rect, _, _, glyphs, _ in
+ let character = manager.characterIndexForGlyph(at: glyphs.location)
+ let other = referenceManager.lineFragmentRect(forGlyphAt: referenceManager.glyphIndexForCharacter(at: character), effectiveRange: nil)
+ compared += 1
+ if abs(other.minY - rect.minY) > 0.5 || abs(other.minX - rect.minX) > 0.5 { mismatches += 1 }
+ }
+ XCTAssertGreaterThan(compared, 5)
+ XCTAssertEqual(mismatches, 0, "\(mode): lines near the end where a whole layout puts them (\(mismatches) of \(compared) differ)")
+ print("PHONE LARGE \(mode): \(compared) lines near the end compared with a whole layout, \(mismatches) differ")
+ withExtendedLifetime(reference) {}
+ text.removeFromSuperview()
+ window.isHidden = true
+ }
+ // The layout manager alone, background layout on and off.
+ let content = NativeTextProjection.render(projection)
+ for background in [true, false] {
+ let storage = NSTextStorage()
+ let manager = NSLayoutManager()
+ if !background { manager.setValue(false, forKey: "backgroundLayoutEnabled") }
+ let container = DocsPageTextContainer(size: CGSize(width: 402, height: 1_000_000))
+ container.lineFragmentPadding = 0
+ container.geometry = DocsPageGeometry(viewportWidth: 402, paged: true)
+ storage.addLayoutManager(manager)
+ manager.addTextContainer(container)
+ func report(_ what: String, _ body: () -> Void) {
+ let requests = DocsProbes.lineRequests, start = ContinuousClock.now
+ body()
+ print("PHONE LARGE bare stack, background layout \(background ? "on" : "off"): \(what): \(start.duration(to: .now)), \(DocsProbes.lineRequests - requests) line requests")
+ }
+ report("the document set") { storage.setAttributedString(content) }
+ report("the first screen laid out") { manager.ensureLayout(forBoundingRect: CGRect(x: 0, y: 0, width: 402, height: 874), in: container) }
+ report("a new line typed near the start") { storage.replaceCharacters(in: NSRange(location: 10, length: 0), with: String(repeating: "Words to wrap the line. ", count: 4)) }
+ report("the first screen laid out again") { manager.ensureLayout(forBoundingRect: CGRect(x: 0, y: 0, width: 402, height: 874), in: container) }
+ }
+ }
+}
+#endif
diff --git a/native/apple/Tests/DocsKitTests/SurfaceTimingTests.swift b/native/apple/Tests/DocsKitTests/SurfaceTimingTests.swift
index 5cfbbb7..14c3559 100644
--- a/native/apple/Tests/DocsKitTests/SurfaceTimingTests.swift
+++ b/native/apple/Tests/DocsKitTests/SurfaceTimingTests.swift
@@ -67,6 +67,70 @@ import XCTest
window.isHidden = true
}
}
+ /// The keystroke on the iPhone (S1b step 0): the keyboard's path into
+ /// the text view (the delegate asked, the storage edited, the caret
+ /// moved), then the layout UIKit runs before it draws, per key; and the
+ /// line-fragment requests our container gets for it.
+ func testKeystroke() async throws {
+ guard let dir = ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_DOCS"] else { throw XCTSkip("Set DOCS_RT_AUDIT_DOCS") }
+ let names = (ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_ONLY"] ?? "p1,p5,p20,p50,p200h").split(separator: ",").map(String.init)
+ DocsFonts.register()
+ for name in names {
+ let replica = CRDTReplica(guid: "keys-" + name)
+ try await replica.open(update: try Data(contentsOf: URL(fileURLWithPath: "\(dir)/\(name).bin")))
+ let projection = try await replica.projection()
+ await replica.close()
+ for paged in [true, false] {
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
+ window.makeKeyAndVisible()
+ let text = DocsTextView(frame: window.bounds)
+ text.paged = paged
+ window.addSubview(text)
+ let surface = DocumentSurface()
+ var hooks = DocumentSurface.Hooks()
+ hooks.edit = { _ in true }
+ surface.hooks = hooks
+ surface.isEditable = true
+ surface.attach(text)
+ var start = ContinuousClock.now
+ surface.apply(DocumentSurface.Publication(generation: 1, projection: projection, revision: 1, dirty: nil))
+ text.layoutIfNeeded()
+ let open = Self.ms(start)
+ let content = text.textStorage.string as NSString
+ var at = content.length / 3
+ while at < content.length, content.character(at: at) == 10 { at += 1 }
+ text.selectedRange = NSRange(location: at, length: 0)
+ text.scrollRangeToVisible(text.selectedRange)
+ text.layoutIfNeeded()
+ try await Task.sleep(for: .milliseconds(200))
+ var keys: [Double] = [], lines: [Int] = []
+ for _ in 0..<40 {
+ #if DOCS_PROBES
+ let lines0 = DocsProbes.lineRequests
+ #endif
+ start = .now
+ let range = text.selectedRange
+ if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: "x") ?? true {
+ text.textStorage.replaceCharacters(in: range, with: NSAttributedString(string: "x", attributes: text.typingAttributes))
+ text.selectedRange = NSRange(location: range.location + 1, length: 0)
+ text.delegate?.textViewDidChange?(text)
+ }
+ text.layoutIfNeeded()
+ keys.append(Self.ms(start))
+ #if DOCS_PROBES
+ lines.append(DocsProbes.lineRequests - lines0)
+ #endif
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ let sorted = keys.sorted()
+ print(String(format: "KEYSTROKE TIMING %@ paged=%d: open %.1f ms; key + layout median %.2f ms p95 %.2f ms max %.2f ms; line requests per key median %d max %d",
+ name, paged ? 1 : 0, open, Self.median(keys), sorted[Int(Double(sorted.count - 1) * 0.95)], sorted.last ?? 0,
+ lines.sorted()[lines.count / 2], lines.max() ?? 0))
+ text.removeFromSuperview()
+ window.isHidden = true
+ }
+ }
+ }
static func ms(_ start: ContinuousClock.Instant) -> Double {
let d = start.duration(to: .now); return Double(d.components.seconds) * 1000 + Double(d.components.attoseconds) / 1e15
}
diff --git a/native/ios/project.yml b/native/ios/project.yml
index c3cb173..36337f5 100644
--- a/native/ios/project.yml
+++ b/native/ios/project.yml
@@ -142,6 +142,7 @@ targets:
- path: ../apple/Tests/DocsKitTests/RenderIsolationTests.swift
- path: ../apple/Tests/DocsKitTests/SurfaceTimingTests.swift
- path: ../apple/Tests/DocsKitTests/SurfaceLifecycleTests.swift
+ - path: ../apple/Tests/DocsKitTests/PhoneLargeDocumentTests.swift
dependencies:
- package: DocsNative
product: DocsKit