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 /// generation. Since S1a `projection` is `@ObservationIgnored` (the editor /// draws per block from the surface), so this observes /// `projectionGeneration`, which every remote change moves (a fresh /// source). A local keystroke that reuses its source keeps its generation /// and is not re-rendered here, as the app no longer redraws it whole. /// (Observing `projection` saw nothing, and the remote probe reported /// n=0 from S1a until the live-push slice 0.) final class Published: @unchecked Sendable { var changed = true } let published = Published() func armObservation() { withObservationTracking { _ = model.projectionGeneration } onChange: { [published] in published.changed = true } } func viewRender(_ storage: NSTextStorage, _ last: inout UInt64, _ mainCost: inout [Double]) -> NSAttributedString? { guard published.changed || model.projectionGeneration != last, 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.. .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.. .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..= 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() } }