import CryptoKit import Foundation import RastrilloApple import RastrilloNative import RastrilloTestSupport import XCTest @testable import DocsKit /// Live-push latency probe (spec/live-push, 2026-11-26). Skipped unless /// DOCS_LIVE_NATIVE_CONN names a connection.json from /// native/benchmarks/live-push/run-probe.py SERVER_ONLY=1. The production /// DocsModel with a sealed on-disk store, playing the text view's part as /// RealtimeAuditE2ETests does (render + reconcile into an NSTextStorage once /// per published projection). One process types (`testTypes`), another /// watches (`testWatches`), so native to native is two apps, each with its own /// main thread, as two devices are. Times are Unix ms, comparable with the /// browser probe's and the server's log. Results: DOCS_LIVE_NATIVE_OUT (JSON). @MainActor final class LivePushLatencyTests: XCTestCase { struct Cookie: Decodable { let Name: String; let Value: String } struct Conn: Decodable { let origin: String; let sqids: [String]; let cookies: [Cookie] } static func now() -> Double { Date().timeIntervalSince1970 * 1000 } var env: [String: String] { ProcessInfo.processInfo.environment } func openModel() async throws -> (DocsModel, DocsOfflineAccount, URL) { guard let path = env["DOCS_LIVE_NATIVE_CONN"] else { throw XCTSkip("Run native/benchmarks/live-push/run-native.sh") } let conn = try JSONDecoder().decode(Conn.self, from: Data(contentsOf: URL(fileURLWithPath: path))) let sqid = conn.sqids[Int(env["DOCS_LIVE_NATIVE_INDEX"] ?? "0") ?? 0] let value = ([conn.cookies[0].Value] + conn.cookies.dropFirst().map { "\($0.Name)=\($0.Value)" }).joined(separator: "; ") let client = NativeHTTP(origin: URL(string: conn.origin)!, credential: NativeSession(name: conn.cookies[0].Name, value: value)) let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied)) let root = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("docs-live-push-\(UUID().uuidString)") let id = UUID().uuidString let store = NativeSealedStore(root: root, accountID: id, keys: ScriptedKeyProvider(key: SymmetricKey(data: Data(repeating: 7, count: 32)))) let account = DocsOfflineAccount(store: store, accountID: id, connectivity: connectivity, transport: { client }) let model = DocsModel(transport: { client }, connectivity: connectivity, offlineAccount: account) await model.open(sqid) XCTAssertNotNil(model.projection, "open failed: \(model.errorKey ?? "")") try await Task.sleep(for: .seconds(2)) return (model, account, root) } final class Flag: @unchecked Sendable { var changed = true } @MainActor final class View { let storage: NSTextStorage var shown: UInt64 = 0 let flag = Flag() init(_ model: DocsModel) { storage = NSTextStorage(attributedString: NativeTextProjection.render(model.projection!)) shown = model.projectionGeneration; model.didRender(shown) } func observe(_ model: DocsModel) { withObservationTracking { _ = model.projectionGeneration } onChange: { [flag] in flag.changed = true } } /// The text view's part: render and reconcile a new publication. func render(_ model: DocsModel) -> Bool { guard flag.changed, let projection = model.projection, model.canRender(model.projectionGeneration) else { return false } flag.changed = false; observe(model) DocumentRenderReconciliation.apply(NativeTextProjection.render(projection), to: storage) shown = model.projectionGeneration; model.didRender(shown) return true } var qs: Int { storage.string.reduce(0) { $0 + ($1 == "Q" ? 1 : 0) } } } /// Same distribution as live_push_probe_test.go and browser-probe.mjs. static func schedule(_ keys: Int, mean: Double, seed: UInt64) -> [Double] { var s = seed func rand() -> Double { s = (s &* 1103515245 &+ 12345) % 2147483648; return Double(s) / 2147483648 } var out: [Double] = [], at = 0.0, nextPause = 30 + Int(rand() * 30) for k in 0.. Self.now() { try await Task.sleep(for: .milliseconds(Int(startAt - Self.now()))) } let s = view.storage.string as NSString var at = s.length / 2 while at < s.length, s.character(at: at) == 10 || s.character(at: at) == 0x2028 { at += 1 } var times: [Double] = [] let renderer = Task { @MainActor in while !Task.isCancelled { _ = view.render(model); try? await Task.sleep(for: .milliseconds(1)) } } let clock = ContinuousClock.now for due in Self.schedule(keys, mean: mean, seed: 4242) { let deadline = clock.advanced(by: .milliseconds(Int(due))) if deadline > .now { try await Task.sleep(until: deadline) } guard var cmd = TextEditMapping.displayCommand(in: view.storage, range: NSRange(location: at, length: 0), replacement: "Q") else { XCTFail(); break } cmd["generation"] = .number(Double(view.shown)) times.append(Self.now()) XCTAssertTrue(model.enqueue(cmd), "input paused: \(model.errorKey ?? "")") view.storage.replaceCharacters(in: NSRange(location: at, length: 0), with: "Q") at += 1 } let end = ContinuousClock.now.advanced(by: .seconds(30)) while (model.hasUnsavedChanges || model.hasPendingInput) && .now < end { try await Task.sleep(for: .milliseconds(5)) } try await Task.sleep(for: .seconds(3)) renderer.cancel() try write(["mode": "native-types", "keys": times]) print("LIVENATIVE types \(times.count) keys; errorKey=\(model.errorKey ?? "nil")") await model.stop(); account.drainer.stop() try? FileManager.default.removeItem(at: root) } func testWatches() async throws { let (model, account, root) = try await openModel() // The moment a publication lands (projectionGeneration moves), which is // when the app's per-block drawing starts (S1a: 1-3 ms to reconciled). func qs() -> Int { (model.projection?.children ?? []).reduce(0) { $0 + $1.plainText.reduce(0) { $0 + ($1 == "Q" ? 1 : 0) } } } let base = qs() var seen: [[Double]] = [] if let ready = env["DOCS_LIVE_NATIVE_OUT"] { FileManager.default.createFile(atPath: ready + ".ready", contents: Data()) } let until = ContinuousClock.now.advanced(by: .milliseconds(Int(env["WATCH_MS"] ?? "60000") ?? 60000)) var count = base, generation = model.projectionGeneration while .now < until { if model.projectionGeneration != generation { let t = Self.now() generation = model.projectionGeneration model.didRender(generation) let c = qs() if c > count { for i in count..