| 1 | import CryptoKit |
| 2 | import Foundation |
| 3 | import RastrilloApple |
| 4 | import RastrilloNative |
| 5 | import RastrilloTestSupport |
| 6 | import XCTest |
| 7 | @testable import DocsKit |
| 8 | |
| 9 | /// End-to-end realtime probes against the real Docs server |
| 10 | /// (internal/docs/native_realtime_audit_test.go), driven by |
| 11 | /// native/benchmarks/realtime/run-e2e.py. The model is the production |
| 12 | /// DocsModel with a sealed on-disk store; the probe plays the text view's |
| 13 | /// part (render + reconcile once per published generation) and reads the |
| 14 | /// server's request log afterwards. |
| 15 | @MainActor final class RealtimeAuditE2ETests: XCTestCase { |
| 16 | struct Config: Decodable { let origin: String; let sqid: String; let name: String; let value: String; let base_unix_ms: Double } |
| 17 | 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? } |
| 18 | |
| 19 | /// Main-queue lateness: a 5 ms timer, recording how late each tick ran. |
| 20 | final class StallMonitor: @unchecked Sendable { |
| 21 | private var timer: DispatchSourceTimer? |
| 22 | private var last = DispatchTime.now() |
| 23 | private(set) var gaps: [Double] = [] |
| 24 | func start() { |
| 25 | let t = DispatchSource.makeTimerSource(queue: .main) |
| 26 | t.schedule(deadline: .now(), repeating: .milliseconds(5), leeway: .microseconds(100)) |
| 27 | last = .now() |
| 28 | t.setEventHandler { [weak self] in |
| 29 | guard let self else { return } |
| 30 | let now = DispatchTime.now(); self.gaps.append(Double(now.uptimeNanoseconds - self.last.uptimeNanoseconds) / 1e6); self.last = now |
| 31 | } |
| 32 | t.resume(); timer = t |
| 33 | } |
| 34 | func stop() { timer?.cancel(); timer = nil } |
| 35 | var summary: String { |
| 36 | let s = gaps.sorted() |
| 37 | let over16 = gaps.filter { $0 > 16.7 } |
| 38 | 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, +)) |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | var dir: URL! |
| 43 | var config: Config! |
| 44 | var client: NativeHTTP! |
| 45 | var model: DocsModel! |
| 46 | var account: DocsOfflineAccount! |
| 47 | var storeRoot: URL! |
| 48 | |
| 49 | /// Process CPU seconds (user + system), every thread. |
| 50 | static func cpu() -> Double { |
| 51 | var usage = rusage(); getrusage(RUSAGE_SELF, &usage) |
| 52 | return Double(usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) + Double(usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) / 1e6 |
| 53 | } |
| 54 | func serverNow() -> Double { Date().timeIntervalSince1970 * 1000 - config.base_unix_ms } |
| 55 | func requests(from: Double, to: Double) throws -> [Request] { |
| 56 | let text = try String(contentsOf: dir.appendingPathComponent("requests.jsonl"), encoding: .utf8) |
| 57 | return text.split(separator: "\n").compactMap { try? JSONDecoder().decode(Request.self, from: Data($0.utf8)) } |
| 58 | .filter { $0.start_ms >= from && $0.start_ms <= to } |
| 59 | } |
| 60 | func plain() -> String { model.projection?.children.map(\.plainText).joined(separator: "\n") ?? "" } |
| 61 | |
| 62 | func openModel() async throws { |
| 63 | guard let path = ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_DIR"] else { throw XCTSkip("Run native/benchmarks/realtime/run-e2e.py") } |
| 64 | dir = URL(fileURLWithPath: path) |
| 65 | config = try JSONDecoder().decode(Config.self, from: Data(contentsOf: dir.appendingPathComponent("connection.json"))) |
| 66 | client = NativeHTTP(origin: URL(string: config.origin)!, credential: NativeSession(name: config.name, value: config.value)) |
| 67 | let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied)) |
| 68 | storeRoot = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("docs-rt-e2e-\(UUID().uuidString)") |
| 69 | let store = NativeSealedStore(root: storeRoot, accountID: "rt", keys: ScriptedKeyProvider(key: SymmetricKey(data: Data(repeating: 5, count: 32)))) |
| 70 | let client = self.client! |
| 71 | account = DocsOfflineAccount(store: store, accountID: "rt", connectivity: connectivity, transport: { client }) |
| 72 | model = DocsModel(transport: { client }, connectivity: connectivity, offlineAccount: account) |
| 73 | let t = ContinuousClock.now |
| 74 | await model.open(config.sqid) |
| 75 | XCTAssertNotNil(model.projection, "open failed: \(model.errorKey ?? "")") |
| 76 | print("RTE2E open: \(RealtimeAuditTests.ms(t)) ms, utf16=\(plain().utf16.count)") |
| 77 | try await Task.sleep(for: .seconds(2)) // stream opens, connect-time event settles |
| 78 | } |
| 79 | func finish() async { |
| 80 | await model.stop(); account.drainer.stop() |
| 81 | try? FileManager.default.removeItem(at: storeRoot) |
| 82 | } |
| 83 | |
| 84 | func summarize(_ label: String, _ list: [Request], seconds: Double) { |
| 85 | func line(_ name: String, _ items: [Request]) { |
| 86 | guard !items.isEmpty else { print("RTE2E \(label) \(name): 0"); return } |
| 87 | let durations = items.compactMap { r in r.end_ms.map { $0 - r.start_ms } } |
| 88 | 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", |
| 89 | label, name, items.count, Double(items.count) / seconds, |
| 90 | items.compactMap(\.req_bytes).reduce(0, +), items.compactMap(\.req_bytes).max() ?? 0, |
| 91 | items.compactMap(\.resp_bytes).reduce(0, +), items.compactMap(\.resp_bytes).max() ?? 0, |
| 92 | RealtimeAuditTests.median(durations), durations.max() ?? 0)) |
| 93 | } |
| 94 | let done = list.filter { $0.event == nil } |
| 95 | line("POST /updates", done.filter { $0.method == "POST" && $0.path.contains("/updates") }) |
| 96 | line("GET /updates?since", done.filter { $0.method == "GET" && $0.path.contains("/updates?since") }) |
| 97 | line("GET /updates (full)", done.filter { $0.method == "GET" && $0.path.hasSuffix("/updates") }) |
| 98 | line("stream opens", list.filter { $0.event == "open" }) |
| 99 | line("other", done.filter { !$0.path.contains("/updates") && !$0.path.hasSuffix("/stream") }) |
| 100 | } |
| 101 | |
| 102 | /// The text view's part: one render and one reconcile per published |
| 103 | /// generation. Since S1a `projection` is `@ObservationIgnored` (the editor |
| 104 | /// draws per block from the surface), so this observes |
| 105 | /// `projectionGeneration`, which every remote change moves (a fresh |
| 106 | /// source). A local keystroke that reuses its source keeps its generation |
| 107 | /// and is not re-rendered here, as the app no longer redraws it whole. |
| 108 | /// (Observing `projection` saw nothing, and the remote probe reported |
| 109 | /// n=0 from S1a until the live-push slice 0.) |
| 110 | final class Published: @unchecked Sendable { var changed = true } |
| 111 | let published = Published() |
| 112 | func armObservation() { |
| 113 | withObservationTracking { _ = model.projectionGeneration } onChange: { [published] in published.changed = true } |
| 114 | } |
| 115 | func viewRender(_ storage: NSTextStorage, _ last: inout UInt64, _ mainCost: inout [Double]) -> NSAttributedString? { |
| 116 | guard published.changed || model.projectionGeneration != last, let projection = model.projection, model.canRender(model.projectionGeneration) else { return nil } |
| 117 | published.changed = false; armObservation() |
| 118 | let t = ContinuousClock.now |
| 119 | let content = NativeTextProjection.render(projection) |
| 120 | DocumentRenderReconciliation.apply(content, to: storage) |
| 121 | mainCost.append(RealtimeAuditTests.ms(t)) |
| 122 | last = model.projectionGeneration |
| 123 | model.didRender(last) |
| 124 | return content |
| 125 | } |
| 126 | |
| 127 | func testEndToEndLocalTyping() async throws { |
| 128 | try await openModel() |
| 129 | let count = Int(ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_KEYS"] ?? "40") ?? 40 |
| 130 | let cadence = Double(ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_CADENCE_MS"] ?? "125") ?? 125 |
| 131 | // NOWAIT=1: keys arrive at the cadence whatever the model is doing, as |
| 132 | // they do from a keyboard; the view renders whenever it may. |
| 133 | let noWait = ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_NOWAIT"] == "1" |
| 134 | var rendered = NativeTextProjection.render(model.projection!) |
| 135 | let storage = NSTextStorage(attributedString: rendered) |
| 136 | var shown = model.projectionGeneration; model.didRender(shown) |
| 137 | var at = RealtimeAuditTests.middle(rendered) |
| 138 | var local: [Double] = [], view: [Double] = [], keyTimes: [Double] = [] |
| 139 | let monitor = StallMonitor(); monitor.start() |
| 140 | let t0 = serverNow() |
| 141 | let cpu0 = Self.cpu() |
| 142 | let clock = ContinuousClock.now |
| 143 | for i in 0..<count { |
| 144 | let due = clock.advanced(by: .milliseconds(Int(Double(i) * cadence))) |
| 145 | if due > .now { try await Task.sleep(until: due) } |
| 146 | if let content = viewRender(storage, &shown, &view) { rendered = content } |
| 147 | // As the text view: the command is mapped against its own optimistic |
| 148 | // storage, then the character is inserted (shouldChangeText -> true). |
| 149 | guard var cmd = TextEditMapping.displayCommand(in: storage, range: NSRange(location: at, length: 0), replacement: "x") else { XCTFail(); break } |
| 150 | cmd["generation"] = .number(Double(shown)) |
| 151 | keyTimes.append(serverNow()) |
| 152 | let t = ContinuousClock.now |
| 153 | XCTAssertTrue(model.enqueue(cmd), "input paused: \(model.errorKey ?? "")") |
| 154 | storage.replaceCharacters(in: NSRange(location: at, length: 0), with: "x") |
| 155 | if !noWait { |
| 156 | while model.hasPendingInput { try await Task.sleep(for: .milliseconds(1)) } |
| 157 | local.append(RealtimeAuditTests.ms(t)) |
| 158 | if let content = viewRender(storage, &shown, &view) { rendered = content } |
| 159 | } |
| 160 | at += 1 |
| 161 | } |
| 162 | let typed = ContinuousClock.now |
| 163 | let deadline = typed.advanced(by: .seconds(120)) |
| 164 | var publishedAfter = Double.nan |
| 165 | while (model.hasUnsavedChanges || model.hasPendingInput) && .now < deadline { |
| 166 | if noWait, let content = viewRender(storage, &shown, &view) { rendered = content } |
| 167 | if publishedAfter.isNaN, !model.hasPendingInput { publishedAfter = RealtimeAuditTests.ms(typed) } |
| 168 | try await Task.sleep(for: .milliseconds(2)) |
| 169 | } |
| 170 | if publishedAfter.isNaN { publishedAfter = RealtimeAuditTests.ms(typed) } |
| 171 | let drained = RealtimeAuditTests.ms(typed) |
| 172 | print(String(format: "RTE2E typing: model caught up (no pending input) %.0f ms after the last key", publishedAfter)) |
| 173 | try await Task.sleep(for: .seconds(2)) // echoes |
| 174 | let cpuUsed = Self.cpu() - cpu0 |
| 175 | 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))) |
| 176 | monitor.stop() |
| 177 | let t1 = serverNow() |
| 178 | let seconds = (t1 - t0) / 1000 |
| 179 | RealtimeAuditTests.record("e2e", "typing: enqueue -> published (local)", local) |
| 180 | RealtimeAuditTests.record("e2e", "typing: view render+reconcile per gen", view) |
| 181 | print("RTE2E typing: \(count) keys at \(cadence) ms; outbox drained \(String(format: "%.0f", drained)) ms after last key; \(monitor.summary); errorKey=\(model.errorKey ?? "nil")") |
| 182 | let list = try requests(from: t0, to: t1) |
| 183 | summarize("typing", list, seconds: seconds) |
| 184 | // Server acknowledgement latency per keystroke: the first POST that |
| 185 | // starts after the key went durable carries it. |
| 186 | let posts = list.filter { $0.event == nil && $0.method == "POST" && $0.path.contains("/updates") }.sorted { $0.start_ms < $1.start_ms } |
| 187 | var ack: [Double] = [] |
| 188 | for (i, k) in keyTimes.enumerated() { |
| 189 | let durableAt = k + (local.indices.contains(i) ? local[i] : 0) |
| 190 | if let p = posts.first(where: { $0.start_ms >= durableAt - 0.5 }), let end = p.end_ms { ack.append(end - k) } |
| 191 | } |
| 192 | RealtimeAuditTests.record("e2e", "typing: key -> server ack (approx)", ack) |
| 193 | XCTAssertTrue(plain().contains(String(repeating: "x", count: count))) |
| 194 | try RealtimeAuditTests.dump("e2e-typing") |
| 195 | await finish() |
| 196 | } |
| 197 | |
| 198 | func testEndToEndRemoteUpdates() async throws { |
| 199 | try await openModel() |
| 200 | // A peer: its own replica of the document, posting as the browser does. |
| 201 | let initial = try await client.responseDetails("/d/\(config.sqid)/updates", maxBytes: 8 * 1024 * 1024) |
| 202 | let peer = CRDTReplica(guid: model.detail!.guid) |
| 203 | _ = try await peer.open(update: initial.data) |
| 204 | let peerText = NativeTextProjection.render(try await peer.projection()) |
| 205 | let at = RealtimeAuditTests.middle(peerText) + 25 |
| 206 | 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 |
| 207 | init(_ r: NSAttributedString) { rendered = r } } |
| 208 | let box = Box(NativeTextProjection.render(model.projection!)) |
| 209 | box.at = at |
| 210 | let storage = NSTextStorage(attributedString: box.rendered) |
| 211 | box.shown = model.projectionGeneration; model.didRender(box.shown) |
| 212 | let monitor = StallMonitor(); monitor.start() |
| 213 | let count = Int(ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_KEYS"] ?? "30") ?? 30 |
| 214 | let cadence = Double(ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_CADENCE_MS"] ?? "125") ?? 125 |
| 215 | let burst = Int(ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_BURST"] ?? "10") ?? 10 |
| 216 | |
| 217 | // Watch: when does each posted character appear in a published projection? |
| 218 | let watcher = Task { @MainActor in |
| 219 | while box.watching { |
| 220 | if let content = self.viewRender(storage, &box.shown, &box.view) { |
| 221 | box.rendered = content |
| 222 | let z = self.plain().reduce(0) { $0 + ($1 == "Z" ? 1 : 0) } |
| 223 | while box.seenAt.count < z { box.seenAt.append(self.serverNow()) } |
| 224 | } |
| 225 | try? await Task.sleep(for: .milliseconds(2)) |
| 226 | } |
| 227 | } |
| 228 | func post(_ i: Int) async throws { |
| 229 | let update = try await peer.command(["op": .string("display_edit"), "at": .number(Double(box.at)), "length": .number(0), "text": .string("Z")]) |
| 230 | box.at += 1 |
| 231 | box.postedAt.append(serverNow()) |
| 232 | let reply = try await client.responseDetails("/d/\(config.sqid)/updates", method: "POST", body: update, contentType: "application/octet-stream", maxBytes: 1024) |
| 233 | try reply.requireSuccess() |
| 234 | } |
| 235 | let t0 = serverNow() |
| 236 | let cpu0 = Self.cpu() |
| 237 | let clock = ContinuousClock.now |
| 238 | for i in 0..<count { |
| 239 | let due = clock.advanced(by: .milliseconds(Int(Double(i) * cadence))) |
| 240 | if due > .now { try await Task.sleep(until: due) } |
| 241 | try await post(i) |
| 242 | } |
| 243 | var deadline = ContinuousClock.now.advanced(by: .seconds(120)) |
| 244 | while box.seenAt.count < count && .now < deadline { try await Task.sleep(for: .milliseconds(5)) } |
| 245 | let steady = zip(box.postedAt, box.seenAt).map { $1 - $0 } |
| 246 | let peerCPU = 0.0 // the peer's own commands are excluded below by measuring them |
| 247 | let cpuUsed = Self.cpu() - cpu0 - peerCPU |
| 248 | print(String(format: "RTE2E remote: process CPU %.2f s for %d peer updates (includes the probe peer's own command per update)", cpuUsed, count)) |
| 249 | let t1 = serverNow() |
| 250 | try await Task.sleep(for: .seconds(1)) |
| 251 | // A burst: a paste-sized flurry from the peer, as fast as it can post. |
| 252 | let b0 = serverNow() |
| 253 | let burstStart = box.postedAt.count |
| 254 | for i in 0..<burst { try await post(count + i) } |
| 255 | deadline = ContinuousClock.now.advanced(by: .seconds(120)) |
| 256 | while box.seenAt.count < count + burst && .now < deadline { try await Task.sleep(for: .milliseconds(5)) } |
| 257 | let burstLatency = box.seenAt.count >= count + burst ? box.seenAt[count + burst - 1] - box.postedAt[burstStart] : .nan |
| 258 | try await Task.sleep(for: .seconds(1)) |
| 259 | box.watching = false; await watcher.value |
| 260 | monitor.stop() |
| 261 | let b1 = serverNow() |
| 262 | RealtimeAuditTests.record("e2e", "remote: peer POST start -> visible", steady) |
| 263 | RealtimeAuditTests.record("e2e", "remote: view render+reconcile per gen", box.view) |
| 264 | print("RTE2E remote: \(count) peer updates at \(cadence) ms; \(monitor.summary); seen \(box.seenAt.count)/\(count + burst)") |
| 265 | summarize("remote-steady", try requests(from: t0, to: t1), seconds: (t1 - t0) / 1000) |
| 266 | print(String(format: "RTE2E remote-burst: %d updates posted back to back; first post -> all visible %.0f ms", burst, burstLatency)) |
| 267 | summarize("remote-burst", try requests(from: b0, to: b1), seconds: (b1 - b0) / 1000) |
| 268 | await peer.close() |
| 269 | try RealtimeAuditTests.dump("e2e-remote") |
| 270 | await finish() |
| 271 | } |
| 272 | |
| 273 | /// NativeHTTP reads every response one byte at a time through |
| 274 | /// AsyncBytes; price that against a plain URLSession read of the same GET. |
| 275 | func testEndToEndFetchCost() async throws { |
| 276 | try await openModel() |
| 277 | var kit: [Double] = [], plainRead: [Double] = [] |
| 278 | var size = 0 |
| 279 | var request = URLRequest(url: URL(string: config.origin + "/d/\(config.sqid)/updates")!) |
| 280 | request.setValue(config.origin, forHTTPHeaderField: "Origin") |
| 281 | request.setValue("\(config.name)=\(config.value)", forHTTPHeaderField: "Cookie") |
| 282 | let session = URLSession(configuration: .ephemeral) |
| 283 | for _ in 0..<5 { |
| 284 | var t = ContinuousClock.now |
| 285 | let reply = try await client.responseDetails("/d/\(config.sqid)/updates", maxBytes: 8 * 1024 * 1024) |
| 286 | kit.append(RealtimeAuditTests.ms(t)); size = reply.data.count |
| 287 | t = .now |
| 288 | let (data, _) = try await session.data(for: request) |
| 289 | plainRead.append(RealtimeAuditTests.ms(t)); XCTAssertEqual(data.count, size) |
| 290 | } |
| 291 | RealtimeAuditTests.record("e2e", "fetch: NativeHTTP.responseDetails full log", kit, bytes: size) |
| 292 | RealtimeAuditTests.record("e2e", "fetch: URLSession.data same GET", plainRead, bytes: size) |
| 293 | await finish() |
| 294 | } |
| 295 | |
| 296 | func testEndToEndIdle() async throws { |
| 297 | try await openModel() |
| 298 | let seconds = Double(ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_IDLE_S"] ?? "40") ?? 40 |
| 299 | let t0 = serverNow() |
| 300 | try await Task.sleep(for: .seconds(seconds)) |
| 301 | let t1 = serverNow() |
| 302 | summarize("idle", try requests(from: t0, to: t1), seconds: seconds) |
| 303 | await finish() |
| 304 | } |
| 305 | } |
| 306 | |