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.generation, projection = first.projection 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.generation; projection = next.projection } 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.generation } 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.generation, rendered = NativeTextProjection.render(first.projection) 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.generation t = .now; let content = NativeTextProjection.render(next.projection); 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() } }