oficina / docs Public

Docs native S1a: the realtime probes on main, under DOCS_PROBES

Brings native/benchmarks/realtime (ui-probe, run-ui.py, run-e2e.py), the
RealtimeAudit*Tests, the Go fixture server and the peer-update generator
from perf/native-realtime-audit (d23f3ca), adapted to main's replica API.

DocsAuditProbe becomes DocsProbes, compiled only under DOCS_PROBES:
Package.swift defines it for debug builds (swift test holds §7's hard
counters as gates) and the probe builds pass -Xswiftc -DDOCS_PROBES to a
release build. New counters beside the audit's: host body evaluations,
block renders, iOS attributedText assignments, publications. Before S1a
the workspace's body is the text view's host, so it counts there.

run-matrix.sh runs §7's Mac matrix with the load average beside each run.
Nothing a user sees changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 96fcd01eb225546a7a9de0c34b1a31c7c8ad6110 parent 2704697
18 files changed, +1,364 −4
  • fixtures/generate-peer-updates.mjs +26 −0
  • internal/docs/native_realtime_audit_test.go +171 −0
  • native/.gitignore +1 −0
  • native/apple/Package.swift +9 −3
  • native/apple/Sources/DocsKit/DocsProbes.swift +46 −0
  • native/apple/Sources/DocsKit/DocsWorkspace.swift +5 −1
  • native/apple/Sources/DocsKit/DocumentRenderReconciliation.swift +4 −0
  • native/apple/Sources/DocsKit/NativeDocumentTextView.swift +11 −0
  • native/apple/Sources/DocsKit/NativeTextProjection.swift +4 −0
  • native/apple/Tests/DocsKitTests/RealtimeAuditE2ETests.swift +300 −0
  • native/apple/Tests/DocsKitTests/RealtimeAuditIOSTests.swift +64 −0
  • native/apple/Tests/DocsKitTests/RealtimeAuditTests.swift +270 −0
  • native/benchmarks/realtime/README.md +85 −0
  • native/benchmarks/realtime/run-e2e.py +61 −0
  • native/benchmarks/realtime/run-matrix.sh +25 −0
  • native/benchmarks/realtime/run-ui.py +114 −0
  • native/benchmarks/realtime/ui-probe/Package.swift +9 −0
  • native/benchmarks/realtime/ui-probe/Sources/UIProbe.swift +159 −0
diff --git a/fixtures/generate-peer-updates.mjs b/fixtures/generate-peer-updates.mjs
new file mode 100644
index 0000000..0ebd7ae
--- /dev/null
+++ b/fixtures/generate-peer-updates.mjs
@@ -0,0 +1,26 @@
+// fixtures/generate-peer-updates.mjs <seed.bin> <count> <outdir> — a peer's
+// typing, for the native realtime audit's UI probe: <count> Yjs updates
+// from client 999, each inserting one "Z" after the previous one, in a
+// paragraph in the middle of the seed document. Written as 0.bin, 1.bin…
+import * as Y from 'yjs'
+import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
+const [seed, countArg = '30', outdir = '/tmp/docs-peer'] = process.argv.slice(2)
+const doc = new Y.Doc()
+doc.clientID = 999
+Y.applyUpdate(doc, readFileSync(seed))
+const root = doc.getXmlFragment('prosemirror')
+const blocks = root.toArray()
+let text = null
+for (let i = Math.floor(blocks.length / 2); i < blocks.length && !text; i++) {
+ const first = blocks[i].toArray ? blocks[i].toArray()[0] : null
+ if (blocks[i].nodeName === 'paragraph' && first instanceof Y.XmlText && first.length > 40) text = first
+}
+if (!text) throw new Error('no paragraph to type into')
+mkdirSync(outdir, { recursive: true })
+const at = 20
+for (let k = 0; k < Number(countArg); k++) {
+ const before = Y.encodeStateVector(doc)
+ text.insert(at + k, 'Z')
+ writeFileSync(`${outdir}/${k}.bin`, Y.encodeStateAsUpdate(doc, before))
+}
+console.log(JSON.stringify({ count: Number(countArg), outdir }))
diff --git a/internal/docs/native_realtime_audit_test.go b/internal/docs/native_realtime_audit_test.go
new file mode 100644
index 0000000..2e0f442
--- /dev/null
+++ b/internal/docs/native_realtime_audit_test.go
@@ -0,0 +1,171 @@
+package docs_test
+
+// Realtime audit fixture (perf/native-realtime-audit, 2026-11-21). Not a
+// gate: skipped unless DOCS_RT_AUDIT_DIR is set by
+// native/benchmarks/realtime/run-e2e.py. It serves the real authenticated
+// application on loopback, seeds one document with DOCS_RT_AUDIT_SEED (a
+// Yjs update from fixtures/generate-large-doc.mjs), and appends one JSON
+// line per request to $DOCS_RT_AUDIT_DIR/requests.jsonl: when it started
+// and ended, method, path, bytes each way and status. The native probe
+// (RealtimeAuditTests.testEndToEnd*) reads that log to count requests.
+
+import (
+ "bytes"
+ "encoding/json"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/docs/internal/docs"
+)
+
+type auditWriter struct {
+ http.ResponseWriter
+ status int
+ bytes int64
+}
+
+func (w *auditWriter) WriteHeader(code int) { w.status = code; w.ResponseWriter.WriteHeader(code) }
+func (w *auditWriter) Write(p []byte) (int, error) {
+ if w.status == 0 {
+ w.status = 200
+ }
+ n, err := w.ResponseWriter.Write(p)
+ w.bytes += int64(n)
+ return n, err
+}
+func (w *auditWriter) Flush() {
+ if f, ok := w.ResponseWriter.(http.Flusher); ok {
+ f.Flush()
+ }
+}
+func (w *auditWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
+
+type countingBody struct {
+ r interface {
+ Read([]byte) (int, error)
+ Close() error
+ }
+ n int64
+}
+
+func (b *countingBody) Read(p []byte) (int, error) {
+ n, err := b.r.Read(p)
+ b.n += int64(n)
+ return n, err
+}
+func (b *countingBody) Close() error { return b.r.Close() }
+
+func TestNativeRealtimeAuditServer(t *testing.T) {
+ dir := os.Getenv("DOCS_RT_AUDIT_DIR")
+ if dir == "" {
+ t.Skip("Run native/benchmarks/realtime/run-e2e.py")
+ }
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer listener.Close()
+ origin := "http://" + listener.Addr().String()
+ app, err := docs.NewForTestWith(t, docs.Config{AllowedAddresses: "audit@example.com", Origin: origin})
+ if err != nil {
+ t.Fatal(err)
+ }
+ cookies := signInCookies(t, app, "audit@example.com")
+ create := httptest.NewRequest("POST", "/documents", strings.NewReader("title=Realtime+audit"))
+ create.Header.Set("Origin", origin)
+ create.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ for _, cookie := range cookies {
+ create.AddCookie(cookie)
+ }
+ created := httptest.NewRecorder()
+ app.Handler().ServeHTTP(created, create)
+ if created.Code != http.StatusSeeOther {
+ t.Fatalf("create: status %d", created.Code)
+ }
+ sqid := strings.TrimPrefix(created.Header().Get("Location"), "/d/")
+ if seed := os.Getenv("DOCS_RT_AUDIT_SEED"); seed != "" {
+ update, err := os.ReadFile(seed)
+ if err != nil {
+ t.Fatal(err)
+ }
+ post := httptest.NewRequest("POST", "/d/"+sqid+"/updates", bytes.NewReader(update))
+ post.Header.Set("Origin", origin)
+ post.Header.Set("Content-Type", "application/octet-stream")
+ for _, cookie := range cookies {
+ post.AddCookie(cookie)
+ }
+ posted := httptest.NewRecorder()
+ app.Handler().ServeHTTP(posted, post)
+ if posted.Code/100 != 2 {
+ t.Fatalf("seed: status %d %s", posted.Code, posted.Body.String())
+ }
+ }
+
+ logFile, err := os.OpenFile(filepath.Join(dir, "requests.jsonl"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer logFile.Close()
+ var mu sync.Mutex
+ base := time.Now()
+ inner := app.Handler()
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ start := time.Since(base)
+ body := &countingBody{r: r.Body}
+ r.Body = body
+ aw := &auditWriter{ResponseWriter: w}
+ // Stream lines are logged when the stream opens too, so an idle
+ // probe can see a reconnect without waiting for its end.
+ if strings.HasSuffix(r.URL.Path, "/stream") {
+ mu.Lock()
+ json.NewEncoder(logFile).Encode(map[string]any{"event": "open", "start_ms": float64(start.Microseconds()) / 1000, "method": r.Method, "path": r.URL.RequestURI()})
+ mu.Unlock()
+ }
+ inner.ServeHTTP(aw, r)
+ end := time.Since(base)
+ mu.Lock()
+ defer mu.Unlock()
+ json.NewEncoder(logFile).Encode(map[string]any{
+ "start_ms": float64(start.Microseconds()) / 1000, "end_ms": float64(end.Microseconds()) / 1000,
+ "method": r.Method, "path": r.URL.RequestURI(), "req_bytes": body.n, "resp_bytes": aw.bytes,
+ "status": aw.status, "gzip": r.Header.Get("Content-Encoding"),
+ })
+ })
+ server := httptest.NewUnstartedServer(handler)
+ server.Listener.Close()
+ server.Listener = listener
+ server.Start()
+ defer server.Close()
+ // NativeSession carries one "name=value"; any further cookies ride in
+ // its value after "; ", which makes the same Cookie header.
+ value := cookies[0].Value
+ names := []string{cookies[0].Name}
+ for _, c := range cookies[1:] {
+ value += "; " + c.Name + "=" + c.Value
+ names = append(names, c.Name)
+ }
+ t.Logf("cookies: %v", names)
+ config := map[string]any{"origin": server.URL, "sqid": sqid, "name": cookies[0].Name, "value": value, "base_unix_ms": base.UnixMilli()}
+ data, err := json.Marshal(config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "connection.json"), data, 0600); err != nil {
+ t.Fatal(err)
+ }
+ deadline := time.Now().Add(20 * time.Minute)
+ for time.Now().Before(deadline) {
+ if _, err := os.Stat(filepath.Join(dir, "done")); err == nil {
+ return
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ t.Fatal("audit never completed")
+}
diff --git a/native/.gitignore b/native/.gitignore
index a792582..78ccf58 100644
--- a/native/.gitignore
+++ b/native/.gitignore
@@ -5,3 +5,4 @@ build/
*.xcodeproj/
apple/Artifacts/
+benchmarks/realtime/ui-probe/Package.resolved
diff --git a/native/apple/Package.swift b/native/apple/Package.swift
index 50b7e3c..819459c 100644
--- a/native/apple/Package.swift
+++ b/native/apple/Package.swift
@@ -5,16 +5,22 @@ import Foundation
let sharedNative: Package.Dependency = ProcessInfo.processInfo.environment["OFICINA_NATIVE_PACKAGE_PATH"].map { .package(name: "native", path: $0) }
?? .package(url: "https://amadan.net/rastrillo/native", revision: "0254817dc9dd118ab271f1120cd2b03c1270a1f9")
+/// The editor's probe counters (DocsKit/DocsProbes.swift): on in debug
+/// builds, where `swift test` holds them as gates, and in the release probe
+/// builds, which pass `-Xswiftc -DDOCS_PROBES` (native/benchmarks/realtime).
+/// Never in a shipping (release) build.
+let probes: [SwiftSetting] = [.define("DOCS_PROBES", .when(configuration: .debug))]
+
let package = Package(name: "DocsNative", defaultLocalization: "en", platforms: [.macOS(.v26), .iOS(.v26)],
products: [.library(name: "DocsKit", targets: ["DocsKit"]), .executable(name: "DocsMac", targets: ["DocsMac"])],
dependencies: [sharedNative],
targets: [
.binaryTarget(name: "DocsCRDT", path: "Artifacts/DocsCRDT.xcframework"),
- .target(name: "DocsKit", dependencies: ["DocsCRDT", .product(name: "RastrilloApple", package: "native")], resources: [.process("Resources"), .copy("Fonts")]),
+ .target(name: "DocsKit", dependencies: ["DocsCRDT", .product(name: "RastrilloApple", package: "native")], resources: [.process("Resources"), .copy("Fonts")], swiftSettings: probes),
.executableTarget(name: "DocsMac", dependencies: [.product(name: "RastrilloMacUpdates", package: "native", condition: .when(platforms: [.macOS])), "DocsKit", .product(name: "RastrilloApple", package: "native")], path: "Sources/DocsApp"),
- .testTarget(name: "DocsKitTests", dependencies: ["DocsKit", .product(name: "RastrilloTestSupport", package: "native")]),
+ .testTarget(name: "DocsKitTests", dependencies: ["DocsKit", .product(name: "RastrilloTestSupport", package: "native")], swiftSettings: probes),
.testTarget(name: "DocsWindowTests", dependencies: ["DocsMac", "DocsKit", .product(name: "RastrilloApple", package: "native"),
- .product(name: "RastrilloTestSupport", package: "native")]),
+ .product(name: "RastrilloTestSupport", package: "native")], swiftSettings: probes),
// The screenshot gate's Mac half; native/scripts/snapshots.sh runs it,
// plain `swift test` skips it. ios/project.yml builds the same file
// as DocsPhoneSnapshots for the iPhone half.
diff --git a/native/apple/Sources/DocsKit/DocsProbes.swift b/native/apple/Sources/DocsKit/DocsProbes.swift
new file mode 100644
index 0000000..14e8fca
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocsProbes.swift
@@ -0,0 +1,46 @@
+#if DOCS_PROBES
+import Foundation
+
+/// Counters for the editor's rendering path (spec 2026-11-22 §7,
+/// "Measurement and targets"). Compiled only under the `DOCS_PROBES`
+/// condition: Package.swift sets it for debug builds, where `swift test`
+/// holds the hard counters as gates, and the release probe builds pass
+/// `-Xswiftc -DDOCS_PROBES` (native/benchmarks/realtime). A shipping build
+/// is release without the flag, so it carries none of this.
+///
+/// Main thread only; nothing here changes what the editor does.
+public enum DocsProbes {
+ /// `NativeTextProjection.render`: the whole document.
+ nonisolated(unsafe) public static var wholeRenders = 0
+ nonisolated(unsafe) public static var wholeRenderMs = 0.0
+ /// `NativeTextProjection.renderBlock`: one top-level block.
+ nonisolated(unsafe) public static var blockRenders = 0
+ nonisolated(unsafe) public static var blockRenderMs = 0.0
+ /// `DocumentRenderReconciliation.apply`, whole storage or one range.
+ nonisolated(unsafe) public static var reconciles = 0
+ nonisolated(unsafe) public static var reconcileMs = 0.0
+ /// `updateNSView` / `updateUIView` of the text view's representable.
+ nonisolated(unsafe) public static var viewUpdates = 0
+ nonisolated(unsafe) public static var viewUpdateMs = 0.0
+ /// Body evaluations of the view that hosts the text view.
+ nonisolated(unsafe) public static var hostBodies = 0
+ /// iOS `UITextView.attributedText` assignments by the editor.
+ nonisolated(unsafe) public static var attributedTextAssignments = 0
+ /// Publications applied to the text view, and the main-thread time from
+ /// a publication reaching the main actor to its storage being reconciled.
+ nonisolated(unsafe) public static var publications = 0
+ nonisolated(unsafe) public static var publicationMs = 0.0
+ public static func reset() {
+ wholeRenders = 0; wholeRenderMs = 0; blockRenders = 0; blockRenderMs = 0
+ reconciles = 0; reconcileMs = 0; viewUpdates = 0; viewUpdateMs = 0
+ hostBodies = 0; attributedTextAssignments = 0; publications = 0; publicationMs = 0
+ }
+ public static var summary: String {
+ String(format: "wholeRenders=%d (%.1f ms) blockRenders=%d (%.1f ms) reconciles=%d (%.1f ms) viewUpdates=%d (%.1f ms) hostBodies=%d attributedText=%d publications=%d (%.1f ms)",
+ wholeRenders, wholeRenderMs, blockRenders, blockRenderMs, reconciles, reconcileMs, viewUpdates, viewUpdateMs,
+ hostBodies, attributedTextAssignments, publications, publicationMs)
+ }
+ static func now() -> UInt64 { DispatchTime.now().uptimeNanoseconds }
+ static func ms(since start: UInt64) -> Double { Double(DispatchTime.now().uptimeNanoseconds - start) / 1e6 }
+}
+#endif
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift
index 38dd179..c12f2da 100644
--- a/native/apple/Sources/DocsKit/DocsWorkspace.swift
+++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift
@@ -256,7 +256,11 @@ import SwiftUI
private var showsInspector: Bool { inspectorOpen && model.documentAccess == .writable }
#endif
private var editor: some View {
- VStack(spacing: 0) {
+ #if DOCS_PROBES
+ // Today the workspace's body is the text view's host.
+ let _ = DocsProbes.hostBodies += 1
+ #endif
+ return VStack(spacing: 0) {
#if os(iOS)
NativeSyncStatusView(status: model.syncStatus)
#endif
diff --git a/native/apple/Sources/DocsKit/DocumentRenderReconciliation.swift b/native/apple/Sources/DocsKit/DocumentRenderReconciliation.swift
index 496d92c..87e13aa 100644
--- a/native/apple/Sources/DocsKit/DocumentRenderReconciliation.swift
+++ b/native/apple/Sources/DocsKit/DocumentRenderReconciliation.swift
@@ -9,6 +9,10 @@ import UIKit
/// Equal visible text can still carry a new CRDT node mapping after publication.
@MainActor enum DocumentRenderReconciliation {
static func apply(_ content: NSAttributedString, to storage: NSMutableAttributedString) {
+ #if DOCS_PROBES
+ let probeStart = DocsProbes.now()
+ defer { DocsProbes.reconciles += 1; DocsProbes.reconcileMs += DocsProbes.ms(since: probeStart) }
+ #endif
guard !storage.isEqual(to: content) else { return }
storage.beginEditing()
defer { storage.endEditing() }
diff --git a/native/apple/Sources/DocsKit/NativeDocumentTextView.swift b/native/apple/Sources/DocsKit/NativeDocumentTextView.swift
index 0c57811..661fbc0 100644
--- a/native/apple/Sources/DocsKit/NativeDocumentTextView.swift
+++ b/native/apple/Sources/DocsKit/NativeDocumentTextView.swift
@@ -61,6 +61,10 @@ struct NativeDocumentTextView: NSViewRepresentable {
return scroll
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
+ #if DOCS_PROBES
+ let probeStart = DocsProbes.now()
+ defer { DocsProbes.viewUpdates += 1; DocsProbes.viewUpdateMs += DocsProbes.ms(since: probeStart) }
+ #endif
guard let desk = scroll.documentView as? DocsDeskView, let text = desk.page as? NSTextView else { return }
desk.inspector = inspector
let magnification = zoom * 4.0 / 3.0
@@ -205,6 +209,10 @@ struct NativeDocumentTextView: UIViewRepresentable {
return text
}
func updateUIView(_ text: UITextView, context: Context) {
+ #if DOCS_PROBES
+ let probeStart = DocsProbes.now()
+ defer { DocsProbes.viewUpdates += 1; DocsProbes.viewUpdateMs += DocsProbes.ms(since: probeStart) }
+ #endif
context.coordinator.applyRender(self, to: text)
}
@MainActor final class Coordinator: NSObject, UITextViewDelegate {
@@ -233,6 +241,9 @@ struct NativeDocumentTextView: UIViewRepresentable {
rendered = NSAttributedString(attributedString: candidate.content)
generation = candidate.generation
text.attributedText = candidate.content
+ #if DOCS_PROBES
+ DocsProbes.attributedTextAssignments += 1
+ #endif
text.selectedRange = NSRange(location: min(selected.location, candidate.content.length), length: min(selected.length, max(0, candidate.content.length - selected.location)))
candidate.didRender(candidate.generation)
}
diff --git a/native/apple/Sources/DocsKit/NativeTextProjection.swift b/native/apple/Sources/DocsKit/NativeTextProjection.swift
index f0e768b..606b74a 100644
--- a/native/apple/Sources/DocsKit/NativeTextProjection.swift
+++ b/native/apple/Sources/DocsKit/NativeTextProjection.swift
@@ -24,6 +24,10 @@ extension NSAttributedString.Key {
return encoder
}()
static func render(_ projection: CRDTProjection, images: [String: DocsPlatformImage] = [:]) -> NSAttributedString {
+ #if DOCS_PROBES
+ let probeStart = DocsProbes.now()
+ defer { DocsProbes.wholeRenders += 1; DocsProbes.wholeRenderMs += DocsProbes.ms(since: probeStart) }
+ #endif
let output = NSMutableAttributedString(string: "")
for node in projection.children {
let start = output.length
diff --git a/native/apple/Tests/DocsKitTests/RealtimeAuditE2ETests.swift b/native/apple/Tests/DocsKitTests/RealtimeAuditE2ETests.swift
new file mode 100644
index 0000000..9dfc682
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/RealtimeAuditE2ETests.swift
@@ -0,0 +1,300 @@
+import CryptoKit
+import Foundation
+import RastrilloApple
+import RastrilloNative
+import RastrilloTestSupport
+import XCTest
+@testable import DocsKit
+
+/// End-to-end realtime probes against the real Docs server
+/// (internal/docs/native_realtime_audit_test.go), driven by
+/// native/benchmarks/realtime/run-e2e.py. The model is the production
+/// DocsModel with a sealed on-disk store; the probe plays the text view's
+/// part (render + reconcile once per published generation) and reads the
+/// server's request log afterwards.
+@MainActor final class RealtimeAuditE2ETests: XCTestCase {
+ struct Config: Decodable { let origin: String; let sqid: String; let name: String; let value: String; let base_unix_ms: Double }
+ struct Request: Decodable { let event: String?; let start_ms: Double; let end_ms: Double?; let method: String; let path: String; let req_bytes: Int?; let resp_bytes: Int?; let status: Int? }
+
+ /// Main-queue lateness: a 5 ms timer, recording how late each tick ran.
+ final class StallMonitor: @unchecked Sendable {
+ private var timer: DispatchSourceTimer?
+ private var last = DispatchTime.now()
+ private(set) var gaps: [Double] = []
+ func start() {
+ let t = DispatchSource.makeTimerSource(queue: .main)
+ t.schedule(deadline: .now(), repeating: .milliseconds(5), leeway: .microseconds(100))
+ last = .now()
+ t.setEventHandler { [weak self] in
+ guard let self else { return }
+ let now = DispatchTime.now(); self.gaps.append(Double(now.uptimeNanoseconds - self.last.uptimeNanoseconds) / 1e6); self.last = now
+ }
+ t.resume(); timer = t
+ }
+ func stop() { timer?.cancel(); timer = nil }
+ var summary: String {
+ let s = gaps.sorted()
+ let over16 = gaps.filter { $0 > 16.7 }
+ return String(format: "main-queue gaps: max %.1f ms, p99 %.1f ms, %d gaps > 16.7 ms totalling %.0f ms", s.last ?? 0, s.isEmpty ? 0 : s[Int(Double(s.count - 1) * 0.99)], over16.count, over16.reduce(0, +))
+ }
+ }
+
+ var dir: URL!
+ var config: Config!
+ var client: NativeHTTP!
+ var model: DocsModel!
+ var account: DocsOfflineAccount!
+ var storeRoot: URL!
+
+ /// Process CPU seconds (user + system), every thread.
+ static func cpu() -> Double {
+ var usage = rusage(); getrusage(RUSAGE_SELF, &usage)
+ return Double(usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) + Double(usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) / 1e6
+ }
+ func serverNow() -> Double { Date().timeIntervalSince1970 * 1000 - config.base_unix_ms }
+ func requests(from: Double, to: Double) throws -> [Request] {
+ let text = try String(contentsOf: dir.appendingPathComponent("requests.jsonl"), encoding: .utf8)
+ return text.split(separator: "\n").compactMap { try? JSONDecoder().decode(Request.self, from: Data($0.utf8)) }
+ .filter { $0.start_ms >= from && $0.start_ms <= to }
+ }
+ func plain() -> String { model.projection?.children.map(\.plainText).joined(separator: "\n") ?? "" }
+
+ func openModel() async throws {
+ guard let path = ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_DIR"] else { throw XCTSkip("Run native/benchmarks/realtime/run-e2e.py") }
+ dir = URL(fileURLWithPath: path)
+ config = try JSONDecoder().decode(Config.self, from: Data(contentsOf: dir.appendingPathComponent("connection.json")))
+ client = NativeHTTP(origin: URL(string: config.origin)!, credential: NativeSession(name: config.name, value: config.value))
+ let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied))
+ storeRoot = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("docs-rt-e2e-\(UUID().uuidString)")
+ let store = NativeSealedStore(root: storeRoot, accountID: "rt", keys: ScriptedKeyProvider(key: SymmetricKey(data: Data(repeating: 5, count: 32))))
+ let client = self.client!
+ account = DocsOfflineAccount(store: store, accountID: "rt", connectivity: connectivity, transport: { client })
+ model = DocsModel(transport: { client }, connectivity: connectivity, offlineAccount: account)
+ let t = ContinuousClock.now
+ await model.open(config.sqid)
+ XCTAssertNotNil(model.projection, "open failed: \(model.errorKey ?? "")")
+ print("RTE2E open: \(RealtimeAuditTests.ms(t)) ms, utf16=\(plain().utf16.count)")
+ try await Task.sleep(for: .seconds(2)) // stream opens, connect-time event settles
+ }
+ func finish() async {
+ await model.stop(); account.drainer.stop()
+ try? FileManager.default.removeItem(at: storeRoot)
+ }
+
+ func summarize(_ label: String, _ list: [Request], seconds: Double) {
+ func line(_ name: String, _ items: [Request]) {
+ guard !items.isEmpty else { print("RTE2E \(label) \(name): 0"); return }
+ let durations = items.compactMap { r in r.end_ms.map { $0 - r.start_ms } }
+ print(String(format: "RTE2E %@ %@: %d (%.2f/s), req bytes total %d (max %d), resp bytes total %d (max %d), server ms median %.1f max %.1f",
+ label, name, items.count, Double(items.count) / seconds,
+ items.compactMap(\.req_bytes).reduce(0, +), items.compactMap(\.req_bytes).max() ?? 0,
+ items.compactMap(\.resp_bytes).reduce(0, +), items.compactMap(\.resp_bytes).max() ?? 0,
+ RealtimeAuditTests.median(durations), durations.max() ?? 0))
+ }
+ let done = list.filter { $0.event == nil }
+ line("POST /updates", done.filter { $0.method == "POST" && $0.path.contains("/updates") })
+ line("GET /updates?since", done.filter { $0.method == "GET" && $0.path.contains("/updates?since") })
+ line("GET /updates (full)", done.filter { $0.method == "GET" && $0.path.hasSuffix("/updates") })
+ line("stream opens", list.filter { $0.event == "open" })
+ line("other", done.filter { !$0.path.contains("/updates") && !$0.path.hasSuffix("/stream") })
+ }
+
+ /// The text view's part: one render and one reconcile per published
+ /// projection (a reused source keeps its generation number, so the
+ /// publication itself is observed, as SwiftUI does).
+ final class Published: @unchecked Sendable { var changed = true }
+ let published = Published()
+ func armObservation() {
+ withObservationTracking { _ = model.projection } onChange: { [published] in published.changed = true }
+ }
+ func viewRender(_ storage: NSTextStorage, _ last: inout UInt64, _ mainCost: inout [Double]) -> NSAttributedString? {
+ guard published.changed, let projection = model.projection, model.canRender(model.projectionGeneration) else { return nil }
+ published.changed = false; armObservation()
+ let t = ContinuousClock.now
+ let content = NativeTextProjection.render(projection)
+ DocumentRenderReconciliation.apply(content, to: storage)
+ mainCost.append(RealtimeAuditTests.ms(t))
+ last = model.projectionGeneration
+ model.didRender(last)
+ return content
+ }
+
+ func testEndToEndLocalTyping() async throws {
+ try await openModel()
+ let count = Int(ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_KEYS"] ?? "40") ?? 40
+ let cadence = Double(ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_CADENCE_MS"] ?? "125") ?? 125
+ // NOWAIT=1: keys arrive at the cadence whatever the model is doing, as
+ // they do from a keyboard; the view renders whenever it may.
+ let noWait = ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_NOWAIT"] == "1"
+ var rendered = NativeTextProjection.render(model.projection!)
+ let storage = NSTextStorage(attributedString: rendered)
+ var shown = model.projectionGeneration; model.didRender(shown)
+ var at = RealtimeAuditTests.middle(rendered)
+ var local: [Double] = [], view: [Double] = [], keyTimes: [Double] = []
+ let monitor = StallMonitor(); monitor.start()
+ let t0 = serverNow()
+ let cpu0 = Self.cpu()
+ let clock = ContinuousClock.now
+ for i in 0..<count {
+ let due = clock.advanced(by: .milliseconds(Int(Double(i) * cadence)))
+ if due > .now { try await Task.sleep(until: due) }
+ if let content = viewRender(storage, &shown, &view) { rendered = content }
+ // As the text view: the command is mapped against its own optimistic
+ // storage, then the character is inserted (shouldChangeText -> true).
+ guard var cmd = TextEditMapping.displayCommand(in: storage, range: NSRange(location: at, length: 0), replacement: "x") else { XCTFail(); break }
+ cmd["generation"] = .number(Double(shown))
+ keyTimes.append(serverNow())
+ let t = ContinuousClock.now
+ XCTAssertTrue(model.enqueue(cmd), "input paused: \(model.errorKey ?? "")")
+ storage.replaceCharacters(in: NSRange(location: at, length: 0), with: "x")
+ if !noWait {
+ while model.hasPendingInput { try await Task.sleep(for: .milliseconds(1)) }
+ local.append(RealtimeAuditTests.ms(t))
+ if let content = viewRender(storage, &shown, &view) { rendered = content }
+ }
+ at += 1
+ }
+ let typed = ContinuousClock.now
+ let deadline = typed.advanced(by: .seconds(120))
+ var publishedAfter = Double.nan
+ while (model.hasUnsavedChanges || model.hasPendingInput) && .now < deadline {
+ if noWait, let content = viewRender(storage, &shown, &view) { rendered = content }
+ if publishedAfter.isNaN, !model.hasPendingInput { publishedAfter = RealtimeAuditTests.ms(typed) }
+ try await Task.sleep(for: .milliseconds(2))
+ }
+ if publishedAfter.isNaN { publishedAfter = RealtimeAuditTests.ms(typed) }
+ let drained = RealtimeAuditTests.ms(typed)
+ print(String(format: "RTE2E typing: model caught up (no pending input) %.0f ms after the last key", publishedAfter))
+ try await Task.sleep(for: .seconds(2)) // echoes
+ let cpuUsed = Self.cpu() - cpu0
+ print(String(format: "RTE2E typing: process CPU %.2f s for %d keys = %.0f ms CPU per key (incl. 2 s idle tail)", cpuUsed, count, cpuUsed * 1000 / Double(count)))
+ monitor.stop()
+ let t1 = serverNow()
+ let seconds = (t1 - t0) / 1000
+ RealtimeAuditTests.record("e2e", "typing: enqueue -> published (local)", local)
+ RealtimeAuditTests.record("e2e", "typing: view render+reconcile per gen", view)
+ print("RTE2E typing: \(count) keys at \(cadence) ms; outbox drained \(String(format: "%.0f", drained)) ms after last key; \(monitor.summary); errorKey=\(model.errorKey ?? "nil")")
+ let list = try requests(from: t0, to: t1)
+ summarize("typing", list, seconds: seconds)
+ // Server acknowledgement latency per keystroke: the first POST that
+ // starts after the key went durable carries it.
+ let posts = list.filter { $0.event == nil && $0.method == "POST" && $0.path.contains("/updates") }.sorted { $0.start_ms < $1.start_ms }
+ var ack: [Double] = []
+ for (i, k) in keyTimes.enumerated() {
+ let durableAt = k + (local.indices.contains(i) ? local[i] : 0)
+ if let p = posts.first(where: { $0.start_ms >= durableAt - 0.5 }), let end = p.end_ms { ack.append(end - k) }
+ }
+ RealtimeAuditTests.record("e2e", "typing: key -> server ack (approx)", ack)
+ XCTAssertTrue(plain().contains(String(repeating: "x", count: count)))
+ try RealtimeAuditTests.dump("e2e-typing")
+ await finish()
+ }
+
+ func testEndToEndRemoteUpdates() async throws {
+ try await openModel()
+ // A peer: its own replica of the document, posting as the browser does.
+ let initial = try await client.responseDetails("/d/\(config.sqid)/updates", maxBytes: 8 * 1024 * 1024)
+ let peer = CRDTReplica(guid: model.detail!.guid)
+ _ = try await peer.open(update: initial.data)
+ let peerText = NativeTextProjection.render(try await peer.projection())
+ let at = RealtimeAuditTests.middle(peerText) + 25
+ final class Box { var rendered: NSAttributedString; var shown: UInt64 = 0; var view: [Double] = []; var postedAt: [Double] = []; var seenAt: [Double] = []; var watching = true; var at = 0
+ init(_ r: NSAttributedString) { rendered = r } }
+ let box = Box(NativeTextProjection.render(model.projection!))
+ box.at = at
+ let storage = NSTextStorage(attributedString: box.rendered)
+ box.shown = model.projectionGeneration; model.didRender(box.shown)
+ let monitor = StallMonitor(); monitor.start()
+ let count = Int(ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_KEYS"] ?? "30") ?? 30
+ let cadence = Double(ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_CADENCE_MS"] ?? "125") ?? 125
+ let burst = Int(ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_BURST"] ?? "10") ?? 10
+
+ // Watch: when does each posted character appear in a published projection?
+ let watcher = Task { @MainActor in
+ while box.watching {
+ if let content = self.viewRender(storage, &box.shown, &box.view) {
+ box.rendered = content
+ let z = self.plain().reduce(0) { $0 + ($1 == "Z" ? 1 : 0) }
+ while box.seenAt.count < z { box.seenAt.append(self.serverNow()) }
+ }
+ try? await Task.sleep(for: .milliseconds(2))
+ }
+ }
+ func post(_ i: Int) async throws {
+ let update = try await peer.command(["op": .string("display_edit"), "at": .number(Double(box.at)), "length": .number(0), "text": .string("Z")])
+ box.at += 1
+ box.postedAt.append(serverNow())
+ let reply = try await client.responseDetails("/d/\(config.sqid)/updates", method: "POST", body: update, contentType: "application/octet-stream", maxBytes: 1024)
+ try reply.requireSuccess()
+ }
+ let t0 = serverNow()
+ let cpu0 = Self.cpu()
+ let clock = ContinuousClock.now
+ for i in 0..<count {
+ let due = clock.advanced(by: .milliseconds(Int(Double(i) * cadence)))
+ if due > .now { try await Task.sleep(until: due) }
+ try await post(i)
+ }
+ var deadline = ContinuousClock.now.advanced(by: .seconds(120))
+ while box.seenAt.count < count && .now < deadline { try await Task.sleep(for: .milliseconds(5)) }
+ let steady = zip(box.postedAt, box.seenAt).map { $1 - $0 }
+ let peerCPU = 0.0 // the peer's own commands are excluded below by measuring them
+ let cpuUsed = Self.cpu() - cpu0 - peerCPU
+ print(String(format: "RTE2E remote: process CPU %.2f s for %d peer updates (includes the probe peer's own command per update)", cpuUsed, count))
+ let t1 = serverNow()
+ try await Task.sleep(for: .seconds(1))
+ // A burst: a paste-sized flurry from the peer, as fast as it can post.
+ let b0 = serverNow()
+ let burstStart = box.postedAt.count
+ for i in 0..<burst { try await post(count + i) }
+ deadline = ContinuousClock.now.advanced(by: .seconds(120))
+ while box.seenAt.count < count + burst && .now < deadline { try await Task.sleep(for: .milliseconds(5)) }
+ let burstLatency = box.seenAt.count >= count + burst ? box.seenAt[count + burst - 1] - box.postedAt[burstStart] : .nan
+ try await Task.sleep(for: .seconds(1))
+ box.watching = false; await watcher.value
+ monitor.stop()
+ let b1 = serverNow()
+ RealtimeAuditTests.record("e2e", "remote: peer POST start -> visible", steady)
+ RealtimeAuditTests.record("e2e", "remote: view render+reconcile per gen", box.view)
+ print("RTE2E remote: \(count) peer updates at \(cadence) ms; \(monitor.summary); seen \(box.seenAt.count)/\(count + burst)")
+ summarize("remote-steady", try requests(from: t0, to: t1), seconds: (t1 - t0) / 1000)
+ print(String(format: "RTE2E remote-burst: %d updates posted back to back; first post -> all visible %.0f ms", burst, burstLatency))
+ summarize("remote-burst", try requests(from: b0, to: b1), seconds: (b1 - b0) / 1000)
+ await peer.close()
+ try RealtimeAuditTests.dump("e2e-remote")
+ await finish()
+ }
+
+ /// NativeHTTP reads every response one byte at a time through
+ /// AsyncBytes; price that against a plain URLSession read of the same GET.
+ func testEndToEndFetchCost() async throws {
+ try await openModel()
+ var kit: [Double] = [], plainRead: [Double] = []
+ var size = 0
+ var request = URLRequest(url: URL(string: config.origin + "/d/\(config.sqid)/updates")!)
+ request.setValue(config.origin, forHTTPHeaderField: "Origin")
+ request.setValue("\(config.name)=\(config.value)", forHTTPHeaderField: "Cookie")
+ let session = URLSession(configuration: .ephemeral)
+ for _ in 0..<5 {
+ var t = ContinuousClock.now
+ let reply = try await client.responseDetails("/d/\(config.sqid)/updates", maxBytes: 8 * 1024 * 1024)
+ kit.append(RealtimeAuditTests.ms(t)); size = reply.data.count
+ t = .now
+ let (data, _) = try await session.data(for: request)
+ plainRead.append(RealtimeAuditTests.ms(t)); XCTAssertEqual(data.count, size)
+ }
+ RealtimeAuditTests.record("e2e", "fetch: NativeHTTP.responseDetails full log", kit, bytes: size)
+ RealtimeAuditTests.record("e2e", "fetch: URLSession.data same GET", plainRead, bytes: size)
+ await finish()
+ }
+
+ func testEndToEndIdle() async throws {
+ try await openModel()
+ let seconds = Double(ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_IDLE_S"] ?? "40") ?? 40
+ let t0 = serverNow()
+ try await Task.sleep(for: .seconds(seconds))
+ let t1 = serverNow()
+ summarize("idle", try requests(from: t0, to: t1), seconds: seconds)
+ await finish()
+ }
+}
diff --git a/native/apple/Tests/DocsKitTests/RealtimeAuditIOSTests.swift b/native/apple/Tests/DocsKitTests/RealtimeAuditIOSTests.swift
new file mode 100644
index 0000000..40c8035
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/RealtimeAuditIOSTests.swift
@@ -0,0 +1,64 @@
+#if os(iOS)
+import Foundation
+import UIKit
+import XCTest
+@testable import DocsKit
+
+/// iPhone text-view cost per publication (realtime probes). The iOS
+/// NativeDocumentTextView replaces `attributedText` wholesale for every
+/// published projection; this prices that against reconciling the same
+/// change into the view's own text storage, plus the per-keystroke getters.
+@MainActor final class RealtimeAuditIOSTests: XCTestCase {
+ func testTextViewPublicationCost() 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,p10,p20,p50").split(separator: ",").map(String.init)
+ for name in names {
+ let bytes = try Data(contentsOf: URL(fileURLWithPath: "\(dir)/\(name).bin"))
+ let replica = CRDTReplica(guid: "ios-" + name)
+ try await replica.open(update: bytes)
+ let projection = try await replica.projection()
+ var content = NativeTextProjection.render(projection)
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
+ // The production view: DocsTextView (TextKit 1, ensureLayout in layoutSubviews).
+ let text = DocsTextView(frame: window.bounds)
+ text.paged = ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_PAGED"] != "0"
+ window.addSubview(text); window.makeKeyAndVisible()
+ var t = ContinuousClock.now
+ text.attributedText = content; text.layoutIfNeeded()
+ RealtimeAuditTests.record(name, "ios: initial attributedText + layout", [RealtimeAuditTests.ms(t)], note: "utf16=\(content.length)")
+ let middle = RealtimeAuditTests.middle(content)
+ text.selectedRange = NSRange(location: middle, length: 0)
+ text.scrollRangeToVisible(text.selectedRange)
+ var replace: [Double] = [], reconcile: [Double] = [], getAttributed: [Double] = [], getText: [Double] = []
+ for i in 0..<8 {
+ let next = NSMutableAttributedString(attributedString: content)
+ next.replaceCharacters(in: NSRange(location: middle + i, length: 0), with: NSAttributedString(string: "x", attributes: content.attributes(at: middle + i, effectiveRange: nil)))
+ // Production path (NativeDocumentTextView.swift, iOS applyRender).
+ t = .now
+ text.attributedText = next
+ text.selectedRange = NSRange(location: middle + i + 1, length: 0)
+ text.layoutIfNeeded()
+ replace.append(RealtimeAuditTests.ms(t))
+ // Alternative: the Mac's reconciliation into the live storage.
+ let again = NSMutableAttributedString(attributedString: next)
+ again.replaceCharacters(in: NSRange(location: middle + i + 1, length: 0), with: NSAttributedString(string: "y", attributes: next.attributes(at: middle + i, effectiveRange: nil)))
+ t = .now
+ DocumentRenderReconciliation.apply(again, to: text.textStorage)
+ text.layoutIfNeeded()
+ reconcile.append(RealtimeAuditTests.ms(t))
+ content = again
+ // Per keystroke: shouldChangeTextIn reads attributedText (a copy);
+ // textViewDidChangeSelection reads text twice.
+ t = .now; _ = text.attributedText; getAttributed.append(RealtimeAuditTests.ms(t))
+ t = .now; _ = text.text.utf16.count; _ = text.text.hasSuffix("\n"); getText.append(RealtimeAuditTests.ms(t))
+ }
+ RealtimeAuditTests.record(name, "ios: attributedText = (production) + layout", replace)
+ RealtimeAuditTests.record(name, "ios: reconcile into textStorage + layout", reconcile)
+ RealtimeAuditTests.record(name, "ios: textView.attributedText getter", getAttributed)
+ RealtimeAuditTests.record(name, "ios: textView.text x2 (selection change)", getText)
+ window.isHidden = true
+ await replica.close()
+ }
+ }
+}
+#endif
diff --git a/native/apple/Tests/DocsKitTests/RealtimeAuditTests.swift b/native/apple/Tests/DocsKitTests/RealtimeAuditTests.swift
new file mode 100644
index 0000000..fd84abd
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/RealtimeAuditTests.swift
@@ -0,0 +1,270 @@
+import CryptoKit
+import DocsCRDT
+import Foundation
+import RastrilloApple
+import RastrilloNative
+import RastrilloTestSupport
+import XCTest
+@testable import DocsKit
+#if os(macOS)
+import AppKit
+#endif
+
+/// Realtime audit probes (perf/native-realtime-audit, 2026-11-21). Not a gate:
+/// skipped unless DOCS_RT_AUDIT_DOCS names a directory of Yjs updates made by
+/// fixtures/generate-large-doc.mjs. Each probe times the exact production call
+/// the editor makes per keystroke / per remote update, at several document sizes.
+/// See native/benchmarks/realtime/README.md.
+final class RealtimeAuditTests: XCTestCase {
+ struct Row: Encodable { var doc: String; var step: String; var ms: [Double]; var bytes: Int? = nil; var note: String? = nil }
+ nonisolated(unsafe) static var rows: [Row] = []
+
+ static func median(_ values: [Double]) -> Double { let s = values.sorted(); return s.isEmpty ? .nan : s[s.count / 2] }
+ static func ms(_ start: ContinuousClock.Instant) -> Double {
+ let d = start.duration(to: .now); return Double(d.components.seconds) * 1000 + Double(d.components.attoseconds) / 1e15
+ }
+ static func record(_ doc: String, _ step: String, _ samples: [Double], bytes: Int? = nil, note: String? = nil) {
+ rows.append(Row(doc: doc, step: step, ms: samples, bytes: bytes, note: note))
+ let m = median(samples)
+ print(String(format: "RTAUDIT %@ %-44@ median %9.2f ms (n=%d, min %.2f, max %.2f)%@%@", doc, step as NSString, m, samples.count,
+ samples.min() ?? .nan, samples.max() ?? .nan, bytes.map { " bytes=\($0)" } ?? "", note.map { " " + $0 } ?? ""))
+ }
+
+ /// The host ABI directly, to price each WASM call the replica makes.
+ final class RawHost {
+ let host: UnsafeMutableRawPointer
+ init() throws { guard let h = docs_host_new() else { throw CRDTReplica.Failure.unavailable }; host = h }
+ deinit { docs_host_free(host) }
+ func call(_ data: Data) throws -> Data {
+ let maximum = 8 * 1024 * 1024 + 1
+ var output = Data(count: maximum)
+ let count = output.withUnsafeMutableBytes { target in data.withUnsafeBytes { source in
+ docs_host_call(host, source.bindMemory(to: UInt8.self).baseAddress!, data.count, target.bindMemory(to: UInt8.self).baseAddress!, maximum)
+ } }
+ guard count >= 0 else { throw CRDTReplica.Failure.rejected }
+ output.count = Int(count); return output
+ }
+ func call(_ command: [String: JSONValue]) throws -> Data { try call(JSONEncoder().encode(command)) }
+ }
+
+ func documents() throws -> [(String, Data)] {
+ guard let dir = ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_DOCS"] else { throw XCTSkip("Set DOCS_RT_AUDIT_DOCS") }
+ let only = ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_ONLY"].map { Set($0.split(separator: ",").map(String.init)) }
+ let names = try FileManager.default.contentsOfDirectory(atPath: dir).filter { $0.hasSuffix(".bin") }.sorted { a, b in
+ let n = { (s: String) in Int(s.filter(\.isNumber)) ?? 0 }; return n(a) == n(b) ? a < b : n(a) < n(b)
+ }
+ return try names.filter { only?.contains(String($0.dropLast(4))) ?? true }.map { (String($0.dropLast(4)), try Data(contentsOf: URL(fileURLWithPath: dir + "/" + $0))) }
+ }
+
+ /// A display offset in the middle of the document that is inside text.
+ @MainActor static func middle(_ text: NSAttributedString) -> Int {
+ let s = text.string as NSString
+ var at = s.length / 2
+ while at < s.length, s.character(at: at) == 10 || s.character(at: at) == 0x2028 { at += 1 }
+ return at
+ }
+
+ // MARK: - 1. Raw WASM call prices
+
+ func testRawHostCallPrices() throws {
+ for (name, bytes) in try documents() {
+ var compile: [Double] = [], open: [Double] = [], snapshot: [Double] = [], project: [Double] = [], decode: [Double] = [], clients: [Double] = []
+ var snapshotBytes = 0, projectionBytes = 0, failure: String?
+ for _ in 0..<5 {
+ var t = ContinuousClock.now
+ let host = try RawHost(); compile.append(Self.ms(t))
+ var step = "open"
+ do {
+ t = .now
+ _ = try host.call(["op": .string("open"), "guid": .string("audit"), "client": .number(7)])
+ step = "apply full state"
+ _ = try host.call(Data([255]) + bytes); open.append(Self.ms(t))
+ step = "clients"
+ t = .now; _ = try host.call(["op": .string("clients")]); clients.append(Self.ms(t))
+ step = "snapshot"
+ t = .now; let snap = try host.call(["op": .string("snapshot")]); snapshot.append(Self.ms(t)); snapshotBytes = snap.count
+ step = "project"
+ t = .now; let json = try host.call(["op": .string("project")]); project.append(Self.ms(t)); projectionBytes = json.count
+ t = .now; _ = try JSONDecoder().decode(CRDTProjection.self, from: json); decode.append(Self.ms(t))
+ } catch { failure = "\(step) failed after \(String(format: "%.1f", Self.ms(t))) ms: \(error)"; break }
+ }
+ Self.record(name, "raw: new host (wasmi module compile)", compile)
+ if let failure { Self.record(name, "raw: FAILED", [], note: failure); continue }
+ Self.record(name, "raw: open + apply full state", open, bytes: bytes.count)
+ Self.record(name, "raw: clients", clients)
+ Self.record(name, "raw: snapshot (encode full state)", snapshot, bytes: snapshotBytes)
+ Self.record(name, "raw: project (full JSON projection)", project, bytes: projectionBytes)
+ Self.record(name, "swift: JSONDecode CRDTProjection", decode)
+ }
+ try Self.dump("raw")
+ }
+
+ // MARK: - 2. Local keystroke, exactly as DocsModel.drainEdits + publishCurrent
+
+ @MainActor func testLocalKeystrokePipeline() async throws {
+ for (name, bytes) in try documents() {
+ let replica = CRDTReplica(guid: "audit-" + name)
+ var t = ContinuousClock.now
+ do { _ = try await replica.open(update: bytes) } catch { Self.record(name, "local: open FAILED", [], note: "\(error)"); continue }
+ Self.record(name, "local: CRDTReplica.open", [Self.ms(t)], bytes: bytes.count)
+ guard let first = try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0)) else { XCTFail(); continue }
+ var generation = first.0, projection = first.1
+ t = .now
+ var rendered = NativeTextProjection.render(projection)
+ Self.record(name, "main: NativeTextProjection.render (cold)", [Self.ms(t)], note: "utf16=\(rendered.length)")
+ #if os(macOS)
+ let storage = NSTextStorage(attributedString: rendered)
+ #else
+ let storage = NSTextStorage(attributedString: rendered)
+ #endif
+ var at = Self.middle(rendered)
+ var command: [Double] = [], present: [Double] = [], render: [Double] = [], reconcile: [Double] = [], equal: [Double] = [], updates: [Int] = []
+ var failed: String?
+ for _ in 0..<12 {
+ // The text view inserts optimistically, then asks for the command.
+ storage.replaceCharacters(in: NSRange(location: at, length: 0), with: "x")
+ guard let cmd = TextEditMapping.displayCommand(in: rendered, range: NSRange(location: at, length: 0), replacement: "x") else { XCTFail(); break }
+ var full = cmd; full["generation"] = .number(Double(generation))
+ do {
+ t = .now
+ let update = try await replica.command(full); command.append(Self.ms(t)); updates.append(update.count)
+ await replica.retainGenerations([generation])
+ t = .now
+ guard let next = try await replica.presentation(source: generation, selection: NSRange(location: at + 1, length: 0), allowReuse: true) else { failed = "presentation nil"; break }
+ present.append(Self.ms(t))
+ generation = next.0; projection = next.1
+ } catch { failed = "\(error)"; break }
+ t = .now; let content = NativeTextProjection.render(projection); render.append(Self.ms(t))
+ t = .now; _ = rendered.isEqual(to: content); equal.append(Self.ms(t))
+ t = .now; DocumentRenderReconciliation.apply(content, to: storage); reconcile.append(Self.ms(t))
+ rendered = content; at += 1
+ }
+ if let failed { Self.record(name, "local: keystroke FAILED", [], note: failed) }
+ Self.record(name, "local: replica.command(display_edit)", command, bytes: updates.max())
+ Self.record(name, "local: replica.presentation(reuse)", present)
+ Self.record(name, "main: NativeTextProjection.render", render)
+ Self.record(name, "main: NSAttributedString.isEqual (body guard)", equal)
+ Self.record(name, "main: DocumentRenderReconciliation.apply", reconcile)
+ XCTAssertEqual(storage.string, rendered.string)
+
+ // A presentation that cannot reuse its source (after any peer update,
+ // undo, or an unacknowledged render): a fresh sandbox per generation.
+ var fresh: [Double] = []
+ for _ in 0..<4 {
+ await replica.retainGenerations([generation])
+ t = .now
+ guard let next = try await replica.presentation(source: generation, selection: NSRange(location: at, length: 0), allowReuse: false) else { break }
+ fresh.append(Self.ms(t)); generation = next.0
+ }
+ Self.record(name, "local: replica.presentation(fresh source)", fresh)
+ await replica.close()
+ }
+ try Self.dump("local")
+ }
+
+ // MARK: - 3. Remote update, exactly as DocsModel.refresh
+
+ @MainActor func testRemoteUpdatePipeline() async throws {
+ for (name, bytes) in try documents() {
+ let replica = CRDTReplica(guid: "audit-" + name), peer = CRDTReplica(guid: "audit-" + name)
+ do { _ = try await replica.open(update: bytes); _ = try await peer.open(update: bytes) }
+ catch { Self.record(name, "remote: open FAILED", [], note: "\(error)"); continue }
+ guard let first = try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0)) else { continue }
+ var generation = first.0, rendered = NativeTextProjection.render(first.1)
+ let storage = NSTextStorage(attributedString: rendered)
+ let peerText = NativeTextProjection.render(try await peer.projection())
+ var at = Self.middle(peerText) + 40
+ var peerCommand: [Double] = [], apply: [Double] = [], present: [Double] = [], render: [Double] = [], reconcile: [Double] = []
+ for _ in 0..<8 {
+ guard let cmd = TextEditMapping.displayCommand(in: peerText, range: NSRange(location: at, length: 0), replacement: "y") else { break }
+ do {
+ var t = ContinuousClock.now
+ let update = try await peer.command(cmd); peerCommand.append(Self.ms(t))
+ t = .now; _ = try await replica.apply(update); apply.append(Self.ms(t))
+ await replica.retainGenerations([generation])
+ t = .now
+ guard let next = try await replica.presentation(source: generation, selection: NSRange(location: 10, length: 0), allowReuse: true) else { break }
+ present.append(Self.ms(t)); generation = next.0
+ t = .now; let content = NativeTextProjection.render(next.1); render.append(Self.ms(t))
+ t = .now; DocumentRenderReconciliation.apply(content, to: storage); reconcile.append(Self.ms(t))
+ rendered = content
+ } catch { Self.record(name, "remote: FAILED", [], note: "\(error)"); break }
+ at += 1
+ }
+ Self.record(name, "remote: replica.apply (apply+project+snapshot)", apply)
+ Self.record(name, "remote: replica.presentation (fresh source)", present)
+ Self.record(name, "main: render after remote", render)
+ Self.record(name, "main: reconcile after remote", reconcile)
+ _ = rendered
+ await replica.close(); await peer.close()
+ }
+ try Self.dump("remote")
+ }
+
+ // MARK: - 4. Durability and send-side whole-document work
+
+ @MainActor func testPersistenceAndSendCosts() async throws {
+ let root = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("docs-rt-audit-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: root) }
+ let sealed = NativeSealedStore(root: root, accountID: "audit", keys: ScriptedKeyProvider(key: SymmetricKey(data: Data(repeating: 9, count: 32))))
+ for (name, bytes) in try documents() {
+ let replica = CRDTReplica(guid: "audit-" + name)
+ do { _ = try await replica.open(update: bytes) } catch { continue }
+ let state = try await replica.persistentState()
+ for (label, store) in [("memory", EphemeralDocsStore() as BlobStore), ("sealed disk", sealed as BlobStore)] {
+ let cache = DocsReplicaCache(store: store)
+ var samples: [Double] = []
+ for _ in 0..<5 {
+ let t = ContinuousClock.now
+ try await cache.commit(PersistedReplica(format: 1, sequence: 1, guid: state.guid, savedAt: Date(), state: state.state), key: name, generation: 0)
+ samples.append(Self.ms(t))
+ }
+ let file = try store.read("cache/docs/\(name)/replica")?.count
+ Self.record(name, "persist: DocsReplicaCache.commit (\(label))", samples, bytes: file)
+ }
+ // The JSON+base64 part of the commit runs on the main actor.
+ var encode: [Double] = [], decode: [Double] = []
+ for _ in 0..<5 {
+ var t = ContinuousClock.now
+ let data = try JSONEncoder().encode(PersistedReplica(format: 1, sequence: 1, guid: state.guid, savedAt: Date(), state: state.state)); encode.append(Self.ms(t))
+ t = .now; _ = try JSONDecoder().decode(PersistedReplica.self, from: data); decode.append(Self.ms(t))
+ }
+ Self.record(name, "main: PersistedReplica JSON encode", encode)
+ Self.record(name, "main: PersistedReplica JSON decode", decode)
+ // Send path: a fresh merger replica per batch.
+ var merger: [Double] = []
+ let a = try await replica.command(["op": .string("display_edit"), "at": .number(5), "length": .number(0), "text": .string("a")])
+ let b = try await replica.command(["op": .string("display_edit"), "at": .number(6), "length": .number(0), "text": .string("b")])
+ for _ in 0..<5 {
+ let t = ContinuousClock.now
+ let m = CRDTReplica(guid: state.guid); _ = try await m.open(update: Data()); _ = try await m.mergeUpdates([a, b]); await m.close()
+ merger.append(Self.ms(t))
+ }
+ Self.record(name, "send: merger open(empty)+merge 2 updates", merger)
+ await replica.close()
+ }
+ // Outbox: one sealed file per keystroke.
+ let outbox = Outbox(store: sealed, account: "audit")
+ try await outbox.load()
+ var enqueue: [Double] = [], summary: [Double] = []
+ for i in 0..<200 {
+ let t = ContinuousClock.now
+ try await outbox.enqueue(lane: "doc:k", kind: "update", payload: Data(repeating: UInt8(i % 255), count: 28))
+ enqueue.append(Self.ms(t))
+ let u = ContinuousClock.now; _ = await outbox.sendable(lane: "doc:k", maxBytes: nil); summary.append(Self.ms(u))
+ }
+ Self.record("-", "durable: Outbox.enqueue 28 B (sealed disk)", enqueue)
+ Self.record("-", "durable: Outbox.sendable (compact check)", summary)
+ let ids = await outbox.entries(lane: "doc:k").map(\.id)
+ var ack: [Double] = []
+ for id in ids.prefix(50) { let t = ContinuousClock.now; try await outbox.ack([id]); ack.append(Self.ms(t)) }
+ Self.record("-", "durable: Outbox.ack 1 entry (sealed disk)", ack)
+ try Self.dump("persist")
+ }
+
+ static func dump(_ name: String) throws {
+ guard let out = ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_OUT"] else { return }
+ try JSONEncoder().encode(rows).write(to: URL(fileURLWithPath: out + "/\(name).json"))
+ rows.removeAll()
+ }
+}
diff --git a/native/benchmarks/realtime/README.md b/native/benchmarks/realtime/README.md
new file mode 100644
index 0000000..04e5055
--- /dev/null
+++ b/native/benchmarks/realtime/README.md
@@ -0,0 +1,85 @@
+# Native realtime probes
+
+Brought onto main by S1a of the native redesign (spec
+`docs/superpowers/specs/2026-11-22-native-redesign-design.md` §7,
+"Measurement and targets"), from the 2026-11-21 audit branch
+`perf/native-realtime-audit`. Measurement tools, not gates: every probe
+skips unless its environment variable is set, and nothing here changes what
+the apps do. The counters are `DocsKit/DocsProbes.swift`, compiled only
+under the `DOCS_PROBES` condition: Package.swift sets it for debug builds
+(where `swift test` holds the §7 hard counters as gates), and the probe
+builds below pass `-Xswiftc -DDOCS_PROBES` to a release build. A shipping
+build is release without it. The audit's report is
+`oficina/native-levelup/docs-realtime-audit.md`; the baseline and the
+numbers after each slice are in `../README.md`.
+
+## Documents
+
+```sh
+cd fixtures && npm ci --ignore-scripts
+node generate-large-doc.mjs 20 /tmp/rt-audit/docs/p20.bin # 20 pages, built in one go
+node generate-large-doc.mjs 20 /tmp/rt-audit/docs/p20h.bin 1200 # plus 1,200 small edits from 20 clients
+node generate-large-doc.mjs 200 /tmp/rt-audit/docs/p200h.bin 10000 # §7's p200h, as check-native.sh builds it
+```
+
+A page is ~3,000 characters: five paragraphs with bold/italic runs, a heading
+every second page, a bullet list every fifth. The `h` variants carry the
+tombstones and fragmentation of a document that has been edited.
+
+## Build
+
+```sh
+cd native
+cargo build --manifest-path crdt/Cargo.toml --release --target wasm32-unknown-unknown --lib --locked
+cargo build --manifest-path host/Cargo.toml --release --target aarch64-apple-darwin --lib --locked
+xcodebuild -create-xcframework -library "$PWD/host/target/aarch64-apple-darwin/release/libdocs_native_host.a" \
+ -headers "$PWD/host/include" -output "$PWD/apple/Artifacts/DocsCRDT.xcframework"
+cd apple && swift build -c release --build-tests -Xswiftc -enable-testing
+GOTOOLCHAIN=go1.26.5 CGO_ENABLED=0 go test -c -o /tmp/rt-audit/docs.test ./internal/docs/ # from the repo root
+```
+
+The audit (on the old fixed 40M fuel budget) could not open documents over
+about 30 pages without raising `FUEL` by hand. The host's budget now grows
+with the instance (`native/host/src/lib.rs`, `BASE_FUEL` +
+`FUEL_PER_MEMORY_BYTE` …), so p50 and p200h open on production fuel and no
+edit is needed.
+
+## Probes
+
+| Probe | What it times |
+| --- | --- |
+| `RealtimeAuditTests/testRawHostCallPrices` | each WASM call the replica makes: module compile, open+apply, snapshot, project, Swift JSON decode |
+| `RealtimeAuditTests/testLocalKeystrokePipeline` | per keystroke, as `drainEdits` + `publishCurrent`: `command`, `presentation`, render, reconcile |
+| `RealtimeAuditTests/testRemoteUpdatePipeline` | per peer update, as `refresh`: `apply`, fresh-source `presentation`, render, reconcile |
+| `RealtimeAuditTests/testPersistenceAndSendCosts` | `DocsReplicaCache.commit` (memory and sealed disk), send merger, outbox enqueue/ack |
+| `RealtimeAuditE2ETests/*` via `run-e2e.py` | the production `DocsModel` + sealed store against the real server: request counts, bytes, ack and visibility latency, process CPU |
+| `RealtimeAuditIOSTests` (iOS simulator) | the iOS `DocsTextView`: `attributedText =` per publication vs reconciling into its storage |
+| `ui-probe` via `run-ui.py` | the real `DocsWorkspace` window: keyDown time, renders per key, main-queue stalls, peer update → visible |
+
+```sh
+cd native/apple
+DOCS_RT_AUDIT_DOCS=/tmp/rt-audit/docs DOCS_RT_AUDIT_ONLY=p1,p10,p20 \
+ swift test -c release -Xswiftc -enable-testing --skip-build --filter RealtimeAuditTests
+
+cd ../..
+python3 native/benchmarks/realtime/run-e2e.py /tmp/rt-audit/docs/p10.bin testEndToEndLocalTyping KEYS=40 CADENCE_MS=125 NOWAIT=1
+python3 native/benchmarks/realtime/run-e2e.py /tmp/rt-audit/docs/p10.bin testEndToEndRemoteUpdates KEYS=30 CADENCE_MS=125 BURST=10
+python3 native/benchmarks/realtime/run-e2e.py /tmp/rt-audit/docs/p10.bin testEndToEndIdle IDLE_S=40
+
+(cd native/benchmarks/realtime/ui-probe && swift build -c release -Xswiftc -DDOCS_PROBES)
+python3 native/benchmarks/realtime/run-ui.py /tmp/rt-audit/docs/p10.bin KEYS=40 PEER=30 [PAGED=0]
+native/benchmarks/realtime/run-matrix.sh /tmp/rt-audit/docs p20 p200h # the §7 matrix, RUNS=3 each
+
+# iOS (needs the aarch64-apple-ios-sim host slice in the XCFramework; DocsColophonTests
+# needs `import SwiftUI` to compile for iOS)
+TEST_RUNNER_DOCS_RT_AUDIT_DOCS=/tmp/rt-audit/docs xcodebuild test -scheme DocsNative-Package \
+ -destination 'platform=iOS Simulator,id=<udid>' -configuration Release \
+ -only-testing:DocsKitTests/RealtimeAuditIOSTests ENABLE_TESTABILITY=YES
+```
+
+The fixture server (`internal/docs/native_realtime_audit_test.go`) is the real
+authenticated app on loopback with a request log. Its sign-in returns three
+cookies (`rastrillo_attempt`, `rastrillo_last_signin`, `rastrillo_session`);
+the probe sends all of them. (`TestNativeKillServer` sends only `cookies[0]`,
+which is now `rastrillo_attempt`, so its native client is redirected; it was
+not run here.)
diff --git a/native/benchmarks/realtime/run-e2e.py b/native/benchmarks/realtime/run-e2e.py
new file mode 100644
index 0000000..b32e3eb
--- /dev/null
+++ b/native/benchmarks/realtime/run-e2e.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python3
+"""Run one end-to-end realtime probe: the real Docs server (seeded with a
+generated document) and the production DocsModel in an XCTest process.
+
+ run-e2e.py <seed.bin> <TestName> [KEY=VALUE ...]
+
+TestName is testEndToEndLocalTyping, testEndToEndRemoteUpdates or
+testEndToEndIdle. KEY=VALUE pairs become DOCS_RT_AUDIT_* environment
+variables (KEYS=40 CADENCE_MS=125 BURST=10 IDLE_S=40). Expects the Go test
+binary at $DOCS_RT_AUDIT_GOTEST (built with `go test -c ./internal/docs`)
+and a release test build of native/apple. Never touches user data.
+"""
+import os
+from pathlib import Path
+import signal
+import subprocess
+import sys
+import tempfile
+import time
+
+root = Path(__file__).resolve().parents[3]
+seed, test = sys.argv[1], sys.argv[2]
+extra = dict(arg.split("=", 1) for arg in sys.argv[3:])
+gotest = os.environ.get("DOCS_RT_AUDIT_GOTEST", "/tmp/rt-audit/docs.test")
+
+with tempfile.TemporaryDirectory(prefix="docs-rt-e2e-", dir="/tmp") as tmp:
+ scratch = Path(tmp)
+ env = dict(os.environ, DOCS_RT_AUDIT_DIR=tmp, DOCS_RT_AUDIT_SEED=seed, TMPDIR="/tmp")
+ for key, value in extra.items():
+ env["DOCS_RT_AUDIT_" + key] = value
+ log = (scratch / "server.log").open("w")
+ server = subprocess.Popen([gotest, "-test.run", "^TestNativeRealtimeAuditServer$", "-test.count=1", "-test.timeout=25m"],
+ cwd=root / "internal/docs", env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
+ try:
+ deadline = time.monotonic() + 120
+ while not (scratch / "connection.json").exists():
+ if server.poll() is not None:
+ print((scratch / "server.log").read_text()[-4000:])
+ raise SystemExit("server exited")
+ if time.monotonic() > deadline:
+ raise SystemExit("server did not start")
+ time.sleep(0.05)
+ result = subprocess.run(["swift", "test", "-c", "release", "-Xswiftc", "-enable-testing", "--skip-build",
+ "--package-path", str(root / "native/apple"), "--filter", "RealtimeAuditE2ETests/" + test],
+ env=env, capture_output=True, text=True, timeout=1500)
+ out = result.stdout + result.stderr
+ for line in out.splitlines():
+ if line.startswith(("RTE2E", "RTAUDIT")) or ": error:" in line:
+ print(line)
+ if os.environ.get("DOCS_RT_AUDIT_KEEP"):
+ keep = Path(os.environ["DOCS_RT_AUDIT_KEEP"])
+ keep.mkdir(parents=True, exist_ok=True)
+ (keep / f"{Path(seed).stem}-{test}.requests.jsonl").write_text((scratch / "requests.jsonl").read_text())
+ (scratch / "done").touch()
+ server.wait(timeout=20)
+ raise SystemExit(result.returncode)
+ finally:
+ if server.poll() is None:
+ os.killpg(server.pid, signal.SIGTERM)
+ server.wait(timeout=10)
+ log.close()
diff --git a/native/benchmarks/realtime/run-matrix.sh b/native/benchmarks/realtime/run-matrix.sh
new file mode 100755
index 0000000..ecc86ec
--- /dev/null
+++ b/native/benchmarks/realtime/run-matrix.sh
@@ -0,0 +1,25 @@
+#!/bin/sh
+# The §7 matrix (spec 2026-11-22, "Measurement and targets") on the Mac:
+# run-ui.py over each document, paged and pageless, RUNS times each, with
+# the machine's load average beside every run. Prints only RTUI lines.
+#
+# native/benchmarks/realtime/run-matrix.sh <docs dir> [docs...]
+# RUNS=3 KEYS=40 PEER=30 (defaults)
+#
+# <docs dir> holds p10.bin, p20.bin, p50.bin, p200h.bin from
+# fixtures/generate-large-doc.mjs (README.md). Build ui-probe first:
+# (cd ui-probe && swift build -c release -Xswiftc -DDOCS_PROBES)
+set -eu
+dir=$1; shift
+docs=${*:-p10 p20 p50 p200h}
+here=$(cd "$(dirname "$0")" && pwd)
+for doc in $docs; do
+ for paged in 1 0; do
+ run=1
+ while [ "$run" -le "${RUNS:-3}" ]; do
+ echo "=== $doc paged=$paged run $run; $(uptime | sed 's/.*load/load/'); $(sw_vers -productVersion) $(sysctl -n machdep.cpu.brand_string)"
+ python3 "$here/run-ui.py" "$dir/$doc.bin" KEYS="${KEYS:-40}" PEER="${PEER:-30}" PAGED="$paged" | grep -E '^RTUI (typing|remote)' || echo "RTUI run failed"
+ run=$((run + 1))
+ done
+ done
+done
diff --git a/native/benchmarks/realtime/run-ui.py b/native/benchmarks/realtime/run-ui.py
new file mode 100644
index 0000000..4dc8f67
--- /dev/null
+++ b/native/benchmarks/realtime/run-ui.py
@@ -0,0 +1,114 @@
+#!/usr/bin/env python3
+"""Run the realtime UI probe: the real DocsWorkspace window (ui-probe/)
+against the audit fixture server seeded with a generated document.
+
+ run-ui.py <seed.bin> [KEYS=40] [CADENCE_MS=125] [PEER=30] [PEER_CADENCE_MS=125] [PAGED=1]
+
+Phase A: the probe types into the text view; the request log gives the
+uploads. Phase B: this script posts PEER one-character updates from another
+client (fixtures/generate-peer-updates.mjs) and the probe records when each
+appears in the text view. Needs a logged-in Mac session (it opens a window),
+the Go test binary at $DOCS_RT_AUDIT_GOTEST and a release build of ui-probe.
+"""
+import json
+import os
+from pathlib import Path
+import signal
+import statistics
+import subprocess
+import sys
+import tempfile
+import time
+import urllib.request
+
+root = Path(__file__).resolve().parents[3]
+seed = sys.argv[1]
+opts = dict(KEYS="40", CADENCE_MS="125", PEER="30", PEER_CADENCE_MS="125", PAGED="1")
+opts.update(dict(arg.split("=", 1) for arg in sys.argv[2:]))
+gotest = os.environ.get("DOCS_RT_AUDIT_GOTEST", "/tmp/rt-audit/docs.test")
+
+
+def summarize(label, reqs, seconds):
+ def line(name, items):
+ if not items:
+ print(f"RTUI {label} {name}: 0")
+ return
+ dur = [r["end_ms"] - r["start_ms"] for r in items if "end_ms" in r]
+ print(f"RTUI {label} {name}: {len(items)} ({len(items)/seconds:.2f}/s); req bytes {sum(r.get('req_bytes', 0) for r in items)} "
+ f"(max {max(r.get('req_bytes', 0) for r in items)}); resp bytes {sum(r.get('resp_bytes', 0) for r in items)} "
+ f"(max {max(r.get('resp_bytes', 0) for r in items)}); server ms median {statistics.median(dur) if dur else 0:.1f} max {max(dur) if dur else 0:.1f}")
+ done = [r for r in reqs if "event" not in r]
+ line("POST /updates", [r for r in done if r["method"] == "POST" and "/updates" in r["path"]])
+ line("GET /updates?since", [r for r in done if r["method"] == "GET" and "/updates?since" in r["path"]])
+ line("GET /updates (full)", [r for r in done if r["method"] == "GET" and r["path"].endswith("/updates")])
+ line("stream opens", [r for r in reqs if r.get("event") == "open"])
+ line("other", [r for r in done if "/updates" not in r["path"] and not r["path"].endswith("/stream")])
+
+
+with tempfile.TemporaryDirectory(prefix="docs-rt-ui-", dir="/tmp") as tmp:
+ scratch = Path(tmp)
+ env = dict(os.environ, DOCS_RT_AUDIT_DIR=tmp, DOCS_RT_AUDIT_SEED=seed, TMPDIR="/tmp",
+ DOCS_RT_AUDIT_KEYS=opts["KEYS"], DOCS_RT_AUDIT_CADENCE_MS=opts["CADENCE_MS"])
+ subprocess.run(["node", str(root / "fixtures/generate-peer-updates.mjs"), seed, opts["PEER"], str(scratch / "peer")], check=True, capture_output=True)
+ log = (scratch / "server.log").open("w")
+ server = subprocess.Popen([gotest, "-test.run", "^TestNativeRealtimeAuditServer$", "-test.count=1", "-test.timeout=25m"],
+ cwd=root / "internal/docs", env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
+ probe = None
+ try:
+ while not (scratch / "connection.json").exists():
+ if server.poll() is not None:
+ raise SystemExit((scratch / "server.log").read_text()[-3000:])
+ time.sleep(0.05)
+ conn = json.loads((scratch / "connection.json").read_text())
+ out = (scratch / "probe.log").open("w")
+ binary = root / "native/benchmarks/realtime/ui-probe/.build/release/RealtimeUIProbe"
+ args = [str(binary)] + ([] if opts["PAGED"] == "1" else ["-docs.view.paged", "NO"])
+ probe = subprocess.Popen(args, env=env, stdout=out, stderr=subprocess.STDOUT, start_new_session=True)
+ t_start = None
+ deadline = time.monotonic() + 900
+ while not (scratch / "typing-done").exists():
+ if probe.poll() is not None or time.monotonic() > deadline:
+ raise SystemExit("probe ended before typing-done:\n" + (scratch / "probe.log").read_text()[-3000:])
+ time.sleep(0.05)
+ time.sleep(1)
+ count, cadence = int(opts["PEER"]), float(opts["PEER_CADENCE_MS"]) / 1000
+ start = time.monotonic()
+ for k in range(count):
+ due = start + k * cadence
+ if due > time.monotonic():
+ time.sleep(due - time.monotonic())
+ body = (scratch / "peer" / f"{k}.bin").read_bytes()
+ req = urllib.request.Request(f"{conn['origin']}/d/{conn['sqid']}/updates", data=body, method="POST",
+ headers={"Origin": conn["origin"], "Content-Type": "application/octet-stream",
+ "Cookie": f"{conn['name']}={conn['value']}"})
+ urllib.request.urlopen(req).read()
+ (scratch / "remote-done").write_text(str(count))
+ probe.wait(timeout=600)
+ out.close()
+ text = (scratch / "probe.log").read_text()
+ print("\n".join(l for l in text.splitlines() if l.startswith("RTUI")))
+ reqs = [json.loads(l) for l in (scratch / "requests.jsonl").read_text().splitlines()]
+ typing_done_ms = (os.path.getmtime(scratch / "typing-done") * 1000) - conn["base_unix_ms"]
+ opened = [r for r in reqs if r.get("event") == "open"]
+ t0 = opened[0]["start_ms"] + 3000 if opened else 0 # the probe settles 3 s before typing
+ typing = [r for r in reqs if t0 <= r["start_ms"] <= typing_done_ms]
+ summarize("typing", typing, (typing_done_ms - t0) / 1000)
+ remote = [r for r in reqs if r["start_ms"] > typing_done_ms]
+ summarize("remote", remote, max(1, (remote[-1]["start_ms"] - typing_done_ms) / 1000) if remote else 1)
+ seen = json.loads((scratch / "seen.json").read_text()) if (scratch / "seen.json").exists() else []
+ posts = sorted([r for r in remote if "event" not in r and r["method"] == "POST"], key=lambda r: r["start_ms"])
+ lat = [s - p["start_ms"] for p, s in zip(posts, seen)]
+ if lat:
+ lat_sorted = sorted(lat)
+ print(f"RTUI remote: peer POST start -> visible in text view: median {statistics.median(lat):.0f} ms, p90 {lat_sorted[int(len(lat)*0.9)-1]:.0f} ms, max {max(lat):.0f} ms (n={len(lat)}/{count})")
+ if os.environ.get("DOCS_RT_AUDIT_KEEP"):
+ keep = Path(os.environ["DOCS_RT_AUDIT_KEEP"]); keep.mkdir(parents=True, exist_ok=True)
+ (keep / f"{Path(seed).stem}-ui.requests.jsonl").write_text((scratch / "requests.jsonl").read_text())
+ (keep / f"{Path(seed).stem}-ui.probe.log").write_text(text)
+ finally:
+ (scratch / "done").touch()
+ for p in (probe, server):
+ if p is not None and p.poll() is None:
+ os.killpg(p.pid, signal.SIGTERM)
+ p.wait(timeout=10)
+ log.close()
diff --git a/native/benchmarks/realtime/ui-probe/Package.swift b/native/benchmarks/realtime/ui-probe/Package.swift
new file mode 100644
index 0000000..6dec285
--- /dev/null
+++ b/native/benchmarks/realtime/ui-probe/Package.swift
@@ -0,0 +1,9 @@
+// swift-tools-version: 6.2
+// Realtime audit UI probe: the real DocsWorkspace window against the audit
+// fixture server (run-ui.py). Build it with -Xswiftc -DDOCS_PROBES.
+import PackageDescription
+let package = Package(name: "RealtimeUIProbe", platforms: [.macOS(.v26)],
+ dependencies: [.package(path: "../../../apple")],
+ targets: [.executableTarget(name: "RealtimeUIProbe", dependencies: [
+ .product(name: "DocsKit", package: "apple")
+ ], path: "Sources")])
diff --git a/native/benchmarks/realtime/ui-probe/Sources/UIProbe.swift b/native/benchmarks/realtime/ui-probe/Sources/UIProbe.swift
new file mode 100644
index 0000000..62b4aff
--- /dev/null
+++ b/native/benchmarks/realtime/ui-probe/Sources/UIProbe.swift
@@ -0,0 +1,159 @@
+import AppKit
+import DocsKit
+import RastrilloApple
+import SwiftUI
+
+// Realtime UI probe (spec 2026-11-22 §7, "Measurement and targets"). Opens the real DocsWorkspace
+// (memory store: accountID nil, nothing on disk) against the audit fixture
+// server described by $DOCS_RT_AUDIT_DIR/connection.json, then:
+// A. types $DOCS_RT_AUDIT_KEYS characters into the real NSTextView with
+// keyDown at $DOCS_RT_AUDIT_CADENCE_MS, counting whole-document and block
+// renders, reconciliations, view updates and host body evaluations
+// (DocsProbes; build with -Xswiftc -DDOCS_PROBES) and main-queue stalls;
+// B. writes typing-done, then watches the text view for the peer's "Z"s that
+// run-ui.py posts, recording when each became visible.
+
+struct Connection: Decodable { let origin: String; let sqid: String; let name: String; let value: String; let base_unix_ms: Double }
+let dir = URL(fileURLWithPath: ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_DIR"]!)
+let connection = try! JSONDecoder().decode(Connection.self, from: Data(contentsOf: dir.appendingPathComponent("connection.json")))
+func serverNow() -> Double { Date().timeIntervalSince1970 * 1000 - connection.base_unix_ms }
+
+@MainActor final class Stalls {
+ var timer: DispatchSourceTimer?
+ var last = DispatchTime.now()
+ var gaps: [Double] = []
+ func start() {
+ gaps = []
+ let t = DispatchSource.makeTimerSource(queue: .main)
+ t.schedule(deadline: .now(), repeating: .milliseconds(5), leeway: .microseconds(100))
+ last = .now()
+ t.setEventHandler { [weak self] in
+ MainActor.assumeIsolated {
+ guard let self else { return }
+ let now = DispatchTime.now(); self.gaps.append(Double(now.uptimeNanoseconds - self.last.uptimeNanoseconds) / 1e6); self.last = now
+ }
+ }
+ t.resume(); timer = t
+ }
+ func stop() -> String {
+ timer?.cancel(); timer = nil
+ let s = gaps.sorted(), over = gaps.filter { $0 > 16.7 }
+ return String(format: "max %.1f ms, p99 %.1f ms, %d gaps > 16.7 ms totalling %.0f ms; busy %.1f ms", s.last ?? 0, s.isEmpty ? 0 : s[Int(Double(s.count - 1) * 0.99)], over.count, over.reduce(0, +), busy)
+ }
+ /// Main-thread time the 5 ms tick waited for: every gap beyond its period.
+ var busy: Double { gaps.reduce(0) { $0 + max(0, $1 - 5) } }
+}
+
+func counters(_ label: String, per count: Int) {
+ print("RTUI \(label) \(DocsProbes.summary)")
+ let n = Double(max(1, count))
+ print(String(format: "RTUI %@ per event (n=%d): wholeRenders %.2f blockRenders %.2f reconciles %.2f viewUpdates %.2f hostBodies %.2f", label, count,
+ Double(DocsProbes.wholeRenders) / n, Double(DocsProbes.blockRenders) / n, Double(DocsProbes.reconciles) / n,
+ Double(DocsProbes.viewUpdates) / n, Double(DocsProbes.hostBodies) / n))
+}
+
+@MainActor private enum Run { static var started = false }
+
+@main struct RealtimeUIProbe: App {
+ var body: some Scene {
+ Window("Probe Home", id: "home") { Launcher() }
+ WindowGroup("Probe Document", id: "document", for: String.self) { _ in
+ DocsWorkspace(client: NativeHTTP(origin: URL(string: connection.origin)!, credential: NativeSession(name: connection.name, value: connection.value)),
+ signOut: {}, documentID: connection.sqid)
+ }.defaultSize(width: 1120, height: 820).restorationBehavior(.disabled)
+ }
+}
+
+private struct Launcher: View {
+ @Environment(\.openWindow) private var openWindow
+ var body: some View {
+ Text("Realtime audit probe").frame(width: 300, height: 100).task {
+ guard !Run.started else { return }
+ Run.started = true
+ NSApp.setActivationPolicy(.regular)
+ openWindow(id: "document", value: connection.sqid)
+ for _ in 0..<600 {
+ if let window = NSApp.windows.first(where: { $0.title == "Realtime audit" }), let editor = window.contentView.flatMap(findEditor), !editor.string.isEmpty {
+ await exercise(window, editor)
+ return
+ }
+ try? await Task.sleep(for: .milliseconds(100))
+ }
+ print("RTUI FAILED: document did not load")
+ exit(2)
+ }
+ }
+ func findEditor(_ view: NSView) -> NSTextView? {
+ if let text = view as? NSTextView, text.accessibilityIdentifier() == "docs.editor" { return text }
+ return view.subviews.lazy.compactMap(findEditor).first
+ }
+ func exercise(_ window: NSWindow, _ editor: NSTextView) async {
+ let env = ProcessInfo.processInfo.environment
+ let keys = Int(env["DOCS_RT_AUDIT_KEYS"] ?? "40") ?? 40
+ let cadence = Double(env["DOCS_RT_AUDIT_CADENCE_MS"] ?? "125") ?? 125
+ NSApp.activate(ignoringOtherApps: true)
+ window.makeKeyAndOrderFront(nil); window.makeFirstResponder(editor)
+ try? await Task.sleep(for: .seconds(2))
+ let ns = editor.string as NSString
+ var at = ns.length / 3
+ while at < ns.length, ns.character(at: at) == 10 { at += 1 }
+ editor.setSelectedRange(NSRange(location: at, length: 0))
+ editor.scrollRangeToVisible(editor.selectedRange())
+ try? await Task.sleep(for: .seconds(1))
+
+ // A. Typing.
+ DocsProbes.reset()
+ let stalls = Stalls(); stalls.start()
+ var keyDown: [Double] = []
+ let clock = ContinuousClock.now
+ for i in 0..<keys {
+ let due = clock.advanced(by: .milliseconds(Int(Double(i) * cadence)))
+ if due > .now { try? await Task.sleep(until: due) }
+ window.makeFirstResponder(editor)
+ let event = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil, characters: "x", charactersIgnoringModifiers: "x", isARepeat: false, keyCode: 7)!
+ let t = DispatchTime.now().uptimeNanoseconds
+ editor.keyDown(with: event)
+ keyDown.append(Double(DispatchTime.now().uptimeNanoseconds - t) / 1e6)
+ }
+ let typedAt = ContinuousClock.now
+ try? await Task.sleep(for: .seconds(Double(env["DOCS_RT_AUDIT_SETTLE_S"] ?? "6") ?? 6))
+ let typedStall = stalls.stop()
+ let sorted = keyDown.sorted()
+ print(String(format: "RTUI typing: %d keys at %.0f ms; keyDown sync median %.2f ms p95 %.2f ms max %.2f ms; main queue %@", keys, cadence, sorted[sorted.count / 2], sorted[min(sorted.count - 1, Int(Double(sorted.count) * 0.95))], sorted.last ?? 0, typedStall))
+ counters("typing (\(keys) keys + settle)", per: keys)
+ let x = (editor.string as NSString).components(separatedBy: "x").count - 1
+ print("RTUI typing: settle after last key \(typedAt.duration(to: .now)); x in editor \(x)")
+
+ // B. Remote: run-ui.py posts the peer's updates once this file exists.
+ DocsProbes.reset()
+ stalls.start()
+ try? Data().write(to: dir.appendingPathComponent("typing-done"))
+ var seen: [Double] = []
+ var lastLength = -1
+ let deadline = ContinuousClock.now.advanced(by: .seconds(240))
+ while ContinuousClock.now < deadline {
+ let text = editor.string as NSString
+ if text.length != lastLength {
+ lastLength = text.length
+ var count = 0, range = NSRange(location: 0, length: text.length)
+ while true {
+ let found = text.range(of: "Z", options: .literal, range: range)
+ if found.location == NSNotFound { break }
+ count += 1; range = NSRange(location: found.location + 1, length: text.length - found.location - 1)
+ }
+ while seen.count < count { seen.append(serverNow()) }
+ }
+ if FileManager.default.fileExists(atPath: dir.appendingPathComponent("remote-done").path),
+ let expected = Int((try? String(contentsOf: dir.appendingPathComponent("remote-done"), encoding: .utf8)) ?? ""), seen.count >= expected { break }
+ try? await Task.sleep(for: .milliseconds(3))
+ }
+ try? await Task.sleep(for: .seconds(2))
+ let remoteStall = stalls.stop()
+ print("RTUI remote: main queue \(remoteStall)")
+ print(String(format: "RTUI remote: main-thread busy per peer change %.2f ms (n=%d)", stalls.busy / Double(max(1, seen.count)), seen.count))
+ counters("remote", per: seen.count)
+ try? JSONEncoder().encode(seen).write(to: dir.appendingPathComponent("seen.json"))
+ print("RTUI remote: seen \(seen.count)")
+ exit(0)
+ }
+}