| 1 | import CryptoKit |
| 2 | import DocsCRDT |
| 3 | import Foundation |
| 4 | import RastrilloApple |
| 5 | import RastrilloNative |
| 6 | import RastrilloTestSupport |
| 7 | import XCTest |
| 8 | @testable import DocsKit |
| 9 | #if os(macOS) |
| 10 | import AppKit |
| 11 | #endif |
| 12 | |
| 13 | /// Realtime audit probes (perf/native-realtime-audit, 2026-11-21). Not a gate: |
| 14 | /// skipped unless DOCS_RT_AUDIT_DOCS names a directory of Yjs updates made by |
| 15 | /// fixtures/generate-large-doc.mjs. Each probe times the exact production call |
| 16 | /// the editor makes per keystroke / per remote update, at several document sizes. |
| 17 | /// See native/benchmarks/realtime/README.md. |
| 18 | final class RealtimeAuditTests: XCTestCase { |
| 19 | struct Row: Encodable { var doc: String; var step: String; var ms: [Double]; var bytes: Int? = nil; var note: String? = nil } |
| 20 | nonisolated(unsafe) static var rows: [Row] = [] |
| 21 | |
| 22 | static func median(_ values: [Double]) -> Double { let s = values.sorted(); return s.isEmpty ? .nan : s[s.count / 2] } |
| 23 | static func ms(_ start: ContinuousClock.Instant) -> Double { |
| 24 | let d = start.duration(to: .now); return Double(d.components.seconds) * 1000 + Double(d.components.attoseconds) / 1e15 |
| 25 | } |
| 26 | static func record(_ doc: String, _ step: String, _ samples: [Double], bytes: Int? = nil, note: String? = nil) { |
| 27 | rows.append(Row(doc: doc, step: step, ms: samples, bytes: bytes, note: note)) |
| 28 | let m = median(samples) |
| 29 | print(String(format: "RTAUDIT %@ %-44@ median %9.2f ms (n=%d, min %.2f, max %.2f)%@%@", doc, step as NSString, m, samples.count, |
| 30 | samples.min() ?? .nan, samples.max() ?? .nan, bytes.map { " bytes=\($0)" } ?? "", note.map { " " + $0 } ?? "")) |
| 31 | } |
| 32 | |
| 33 | /// The host ABI directly, to price each WASM call the replica makes. |
| 34 | final class RawHost { |
| 35 | let host: UnsafeMutableRawPointer |
| 36 | init() throws { guard let h = docs_host_new() else { throw CRDTReplica.Failure.unavailable }; host = h } |
| 37 | deinit { docs_host_free(host) } |
| 38 | func call(_ data: Data) throws -> Data { |
| 39 | let maximum = 8 * 1024 * 1024 + 1 |
| 40 | var output = Data(count: maximum) |
| 41 | let count = output.withUnsafeMutableBytes { target in data.withUnsafeBytes { source in |
| 42 | docs_host_call(host, source.bindMemory(to: UInt8.self).baseAddress!, data.count, target.bindMemory(to: UInt8.self).baseAddress!, maximum) |
| 43 | } } |
| 44 | guard count >= 0 else { throw CRDTReplica.Failure.rejected } |
| 45 | output.count = Int(count); return output |
| 46 | } |
| 47 | func call(_ command: [String: JSONValue]) throws -> Data { try call(JSONEncoder().encode(command)) } |
| 48 | } |
| 49 | |
| 50 | func documents() throws -> [(String, Data)] { |
| 51 | guard let dir = ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_DOCS"] else { throw XCTSkip("Set DOCS_RT_AUDIT_DOCS") } |
| 52 | let only = ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_ONLY"].map { Set($0.split(separator: ",").map(String.init)) } |
| 53 | let names = try FileManager.default.contentsOfDirectory(atPath: dir).filter { $0.hasSuffix(".bin") }.sorted { a, b in |
| 54 | let n = { (s: String) in Int(s.filter(\.isNumber)) ?? 0 }; return n(a) == n(b) ? a < b : n(a) < n(b) |
| 55 | } |
| 56 | return try names.filter { only?.contains(String($0.dropLast(4))) ?? true }.map { (String($0.dropLast(4)), try Data(contentsOf: URL(fileURLWithPath: dir + "/" + $0))) } |
| 57 | } |
| 58 | |
| 59 | /// A display offset in the middle of the document that is inside text. |
| 60 | @MainActor static func middle(_ text: NSAttributedString) -> Int { |
| 61 | let s = text.string as NSString |
| 62 | var at = s.length / 2 |
| 63 | while at < s.length, s.character(at: at) == 10 || s.character(at: at) == 0x2028 { at += 1 } |
| 64 | return at |
| 65 | } |
| 66 | |
| 67 | // MARK: - 1. Raw WASM call prices |
| 68 | |
| 69 | func testRawHostCallPrices() throws { |
| 70 | for (name, bytes) in try documents() { |
| 71 | var compile: [Double] = [], open: [Double] = [], snapshot: [Double] = [], project: [Double] = [], decode: [Double] = [], clients: [Double] = [] |
| 72 | var snapshotBytes = 0, projectionBytes = 0, failure: String? |
| 73 | for _ in 0..<5 { |
| 74 | var t = ContinuousClock.now |
| 75 | let host = try RawHost(); compile.append(Self.ms(t)) |
| 76 | var step = "open" |
| 77 | do { |
| 78 | t = .now |
| 79 | _ = try host.call(["op": .string("open"), "guid": .string("audit"), "client": .number(7)]) |
| 80 | step = "apply full state" |
| 81 | _ = try host.call(Data([255]) + bytes); open.append(Self.ms(t)) |
| 82 | step = "clients" |
| 83 | t = .now; _ = try host.call(["op": .string("clients")]); clients.append(Self.ms(t)) |
| 84 | step = "snapshot" |
| 85 | t = .now; let snap = try host.call(["op": .string("snapshot")]); snapshot.append(Self.ms(t)); snapshotBytes = snap.count |
| 86 | step = "project" |
| 87 | t = .now; let json = try host.call(["op": .string("project")]); project.append(Self.ms(t)); projectionBytes = json.count |
| 88 | t = .now; _ = try JSONDecoder().decode(CRDTProjection.self, from: json); decode.append(Self.ms(t)) |
| 89 | } catch { failure = "\(step) failed after \(String(format: "%.1f", Self.ms(t))) ms: \(error)"; break } |
| 90 | } |
| 91 | Self.record(name, "raw: new host (wasmi module compile)", compile) |
| 92 | if let failure { Self.record(name, "raw: FAILED", [], note: failure); continue } |
| 93 | Self.record(name, "raw: open + apply full state", open, bytes: bytes.count) |
| 94 | Self.record(name, "raw: clients", clients) |
| 95 | Self.record(name, "raw: snapshot (encode full state)", snapshot, bytes: snapshotBytes) |
| 96 | Self.record(name, "raw: project (full JSON projection)", project, bytes: projectionBytes) |
| 97 | Self.record(name, "swift: JSONDecode CRDTProjection", decode) |
| 98 | } |
| 99 | try Self.dump("raw") |
| 100 | } |
| 101 | |
| 102 | // MARK: - 2. Local keystroke, exactly as DocsModel.drainEdits + publishCurrent |
| 103 | |
| 104 | @MainActor func testLocalKeystrokePipeline() async throws { |
| 105 | for (name, bytes) in try documents() { |
| 106 | let replica = CRDTReplica(guid: "audit-" + name) |
| 107 | var t = ContinuousClock.now |
| 108 | do { _ = try await replica.open(update: bytes) } catch { Self.record(name, "local: open FAILED", [], note: "\(error)"); continue } |
| 109 | Self.record(name, "local: CRDTReplica.open", [Self.ms(t)], bytes: bytes.count) |
| 110 | guard let first = try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0)) else { XCTFail(); continue } |
| 111 | var generation = first.generation, projection = first.projection |
| 112 | t = .now |
| 113 | var rendered = NativeTextProjection.render(projection) |
| 114 | Self.record(name, "main: NativeTextProjection.render (cold)", [Self.ms(t)], note: "utf16=\(rendered.length)") |
| 115 | #if os(macOS) |
| 116 | let storage = NSTextStorage(attributedString: rendered) |
| 117 | #else |
| 118 | let storage = NSTextStorage(attributedString: rendered) |
| 119 | #endif |
| 120 | var at = Self.middle(rendered) |
| 121 | var command: [Double] = [], present: [Double] = [], render: [Double] = [], reconcile: [Double] = [], equal: [Double] = [], updates: [Int] = [] |
| 122 | var failed: String? |
| 123 | for _ in 0..<12 { |
| 124 | // The text view inserts optimistically, then asks for the command. |
| 125 | storage.replaceCharacters(in: NSRange(location: at, length: 0), with: "x") |
| 126 | guard let cmd = TextEditMapping.displayCommand(in: rendered, range: NSRange(location: at, length: 0), replacement: "x") else { XCTFail(); break } |
| 127 | var full = cmd; full["generation"] = .number(Double(generation)) |
| 128 | do { |
| 129 | t = .now |
| 130 | let update = try await replica.command(full); command.append(Self.ms(t)); updates.append(update.count) |
| 131 | await replica.retainGenerations([generation]) |
| 132 | t = .now |
| 133 | guard let next = try await replica.presentation(source: generation, selection: NSRange(location: at + 1, length: 0), allowReuse: true) else { failed = "presentation nil"; break } |
| 134 | present.append(Self.ms(t)) |
| 135 | generation = next.generation; projection = next.projection |
| 136 | } catch { failed = "\(error)"; break } |
| 137 | t = .now; let content = NativeTextProjection.render(projection); render.append(Self.ms(t)) |
| 138 | t = .now; _ = rendered.isEqual(to: content); equal.append(Self.ms(t)) |
| 139 | t = .now; DocumentRenderReconciliation.apply(content, to: storage); reconcile.append(Self.ms(t)) |
| 140 | rendered = content; at += 1 |
| 141 | } |
| 142 | if let failed { Self.record(name, "local: keystroke FAILED", [], note: failed) } |
| 143 | Self.record(name, "local: replica.command(display_edit)", command, bytes: updates.max()) |
| 144 | Self.record(name, "local: replica.presentation(reuse)", present) |
| 145 | Self.record(name, "main: NativeTextProjection.render", render) |
| 146 | Self.record(name, "main: NSAttributedString.isEqual (body guard)", equal) |
| 147 | Self.record(name, "main: DocumentRenderReconciliation.apply", reconcile) |
| 148 | XCTAssertEqual(storage.string, rendered.string) |
| 149 | |
| 150 | // A presentation that cannot reuse its source (after any peer update, |
| 151 | // undo, or an unacknowledged render): a fresh sandbox per generation. |
| 152 | var fresh: [Double] = [] |
| 153 | for _ in 0..<4 { |
| 154 | await replica.retainGenerations([generation]) |
| 155 | t = .now |
| 156 | guard let next = try await replica.presentation(source: generation, selection: NSRange(location: at, length: 0), allowReuse: false) else { break } |
| 157 | fresh.append(Self.ms(t)); generation = next.generation |
| 158 | } |
| 159 | Self.record(name, "local: replica.presentation(fresh source)", fresh) |
| 160 | await replica.close() |
| 161 | } |
| 162 | try Self.dump("local") |
| 163 | } |
| 164 | |
| 165 | // MARK: - 3. Remote update, exactly as DocsModel.refresh |
| 166 | |
| 167 | @MainActor func testRemoteUpdatePipeline() async throws { |
| 168 | for (name, bytes) in try documents() { |
| 169 | let replica = CRDTReplica(guid: "audit-" + name), peer = CRDTReplica(guid: "audit-" + name) |
| 170 | do { _ = try await replica.open(update: bytes); _ = try await peer.open(update: bytes) } |
| 171 | catch { Self.record(name, "remote: open FAILED", [], note: "\(error)"); continue } |
| 172 | guard let first = try await replica.presentation(source: 0, selection: NSRange(location: 0, length: 0)) else { continue } |
| 173 | var generation = first.generation, rendered = NativeTextProjection.render(first.projection) |
| 174 | let storage = NSTextStorage(attributedString: rendered) |
| 175 | let peerText = NativeTextProjection.render(try await peer.projection()) |
| 176 | var at = Self.middle(peerText) + 40 |
| 177 | var peerCommand: [Double] = [], apply: [Double] = [], present: [Double] = [], render: [Double] = [], reconcile: [Double] = [] |
| 178 | for _ in 0..<8 { |
| 179 | guard let cmd = TextEditMapping.displayCommand(in: peerText, range: NSRange(location: at, length: 0), replacement: "y") else { break } |
| 180 | do { |
| 181 | var t = ContinuousClock.now |
| 182 | let update = try await peer.command(cmd); peerCommand.append(Self.ms(t)) |
| 183 | t = .now; _ = try await replica.apply(update); apply.append(Self.ms(t)) |
| 184 | await replica.retainGenerations([generation]) |
| 185 | t = .now |
| 186 | guard let next = try await replica.presentation(source: generation, selection: NSRange(location: 10, length: 0), allowReuse: true) else { break } |
| 187 | present.append(Self.ms(t)); generation = next.generation |
| 188 | t = .now; let content = NativeTextProjection.render(next.projection); render.append(Self.ms(t)) |
| 189 | t = .now; DocumentRenderReconciliation.apply(content, to: storage); reconcile.append(Self.ms(t)) |
| 190 | rendered = content |
| 191 | } catch { Self.record(name, "remote: FAILED", [], note: "\(error)"); break } |
| 192 | at += 1 |
| 193 | } |
| 194 | Self.record(name, "remote: replica.apply (apply+project+snapshot)", apply) |
| 195 | Self.record(name, "remote: replica.presentation (fresh source)", present) |
| 196 | Self.record(name, "main: render after remote", render) |
| 197 | Self.record(name, "main: reconcile after remote", reconcile) |
| 198 | _ = rendered |
| 199 | await replica.close(); await peer.close() |
| 200 | } |
| 201 | try Self.dump("remote") |
| 202 | } |
| 203 | |
| 204 | // MARK: - 4. Durability and send-side whole-document work |
| 205 | |
| 206 | @MainActor func testPersistenceAndSendCosts() async throws { |
| 207 | let root = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("docs-rt-audit-\(UUID().uuidString)") |
| 208 | defer { try? FileManager.default.removeItem(at: root) } |
| 209 | let sealed = NativeSealedStore(root: root, accountID: "audit", keys: ScriptedKeyProvider(key: SymmetricKey(data: Data(repeating: 9, count: 32)))) |
| 210 | for (name, bytes) in try documents() { |
| 211 | let replica = CRDTReplica(guid: "audit-" + name) |
| 212 | do { _ = try await replica.open(update: bytes) } catch { continue } |
| 213 | let state = try await replica.persistentState() |
| 214 | for (label, store) in [("memory", EphemeralDocsStore() as BlobStore), ("sealed disk", sealed as BlobStore)] { |
| 215 | let cache = DocsReplicaCache(store: store) |
| 216 | var samples: [Double] = [] |
| 217 | for _ in 0..<5 { |
| 218 | let t = ContinuousClock.now |
| 219 | try await cache.commit(PersistedReplica(format: 1, sequence: 1, guid: state.guid, savedAt: Date(), state: state.state), key: name, generation: 0) |
| 220 | samples.append(Self.ms(t)) |
| 221 | } |
| 222 | let file = try store.read("cache/docs/\(name)/replica")?.count |
| 223 | Self.record(name, "persist: DocsReplicaCache.commit (\(label))", samples, bytes: file) |
| 224 | } |
| 225 | // The JSON+base64 part of the commit runs on the main actor. |
| 226 | var encode: [Double] = [], decode: [Double] = [] |
| 227 | for _ in 0..<5 { |
| 228 | var t = ContinuousClock.now |
| 229 | let data = try JSONEncoder().encode(PersistedReplica(format: 1, sequence: 1, guid: state.guid, savedAt: Date(), state: state.state)); encode.append(Self.ms(t)) |
| 230 | t = .now; _ = try JSONDecoder().decode(PersistedReplica.self, from: data); decode.append(Self.ms(t)) |
| 231 | } |
| 232 | Self.record(name, "main: PersistedReplica JSON encode", encode) |
| 233 | Self.record(name, "main: PersistedReplica JSON decode", decode) |
| 234 | // Send path: a fresh merger replica per batch. |
| 235 | var merger: [Double] = [] |
| 236 | let a = try await replica.command(["op": .string("display_edit"), "at": .number(5), "length": .number(0), "text": .string("a")]) |
| 237 | let b = try await replica.command(["op": .string("display_edit"), "at": .number(6), "length": .number(0), "text": .string("b")]) |
| 238 | for _ in 0..<5 { |
| 239 | let t = ContinuousClock.now |
| 240 | let m = CRDTReplica(guid: state.guid); _ = try await m.open(update: Data()); _ = try await m.mergeUpdates([a, b]); await m.close() |
| 241 | merger.append(Self.ms(t)) |
| 242 | } |
| 243 | Self.record(name, "send: merger open(empty)+merge 2 updates", merger) |
| 244 | await replica.close() |
| 245 | } |
| 246 | // Outbox: one sealed file per keystroke. |
| 247 | let outbox = Outbox(store: sealed, account: "audit") |
| 248 | try await outbox.load() |
| 249 | var enqueue: [Double] = [], summary: [Double] = [] |
| 250 | for i in 0..<200 { |
| 251 | let t = ContinuousClock.now |
| 252 | try await outbox.enqueue(lane: "doc:k", kind: "update", payload: Data(repeating: UInt8(i % 255), count: 28)) |
| 253 | enqueue.append(Self.ms(t)) |
| 254 | let u = ContinuousClock.now; _ = await outbox.sendable(lane: "doc:k", maxBytes: nil); summary.append(Self.ms(u)) |
| 255 | } |
| 256 | Self.record("-", "durable: Outbox.enqueue 28 B (sealed disk)", enqueue) |
| 257 | Self.record("-", "durable: Outbox.sendable (compact check)", summary) |
| 258 | let ids = await outbox.entries(lane: "doc:k").map(\.id) |
| 259 | var ack: [Double] = [] |
| 260 | for id in ids.prefix(50) { let t = ContinuousClock.now; try await outbox.ack([id]); ack.append(Self.ms(t)) } |
| 261 | Self.record("-", "durable: Outbox.ack 1 entry (sealed disk)", ack) |
| 262 | try Self.dump("persist") |
| 263 | } |
| 264 | |
| 265 | static func dump(_ name: String) throws { |
| 266 | guard let out = ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_OUT"] else { return } |
| 267 | try JSONEncoder().encode(rows).write(to: URL(fileURLWithPath: out + "/\(name).json")) |
| 268 | rows.removeAll() |
| 269 | } |
| 270 | } |
| 271 | |