oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1#!/usr/bin/env python3
2"""Run the realtime UI probe: the real DocsWorkspace window (ui-probe/)
3against the audit fixture server seeded with a generated document.
4
5 run-ui.py <seed.bin> [KEYS=40] [CADENCE_MS=125] [PEER=30] [PEER_CADENCE_MS=125] [PAGED=1]
6
7Phase A: the probe types into the text view; the request log gives the
8uploads. Phase B: this script posts PEER one-character updates from another
9client (fixtures/generate-peer-updates.mjs) and the probe records when each
10appears in the text view. Needs a logged-in Mac session (it opens a window),
11the Go test binary at $DOCS_RT_AUDIT_GOTEST and a release build of ui-probe.
12"""
13import json
14import os
15from pathlib import Path
16import signal
17import statistics
18import subprocess
19import sys
20import tempfile
21import time
22import urllib.request
23
24root = Path(__file__).resolve().parents[3]
25seed = sys.argv[1]
26opts = dict(KEYS="40", CADENCE_MS="125", PEER="30", PEER_CADENCE_MS="125", PAGED="1")
27opts.update(dict(arg.split("=", 1) for arg in sys.argv[2:]))
28gotest = os.environ.get("DOCS_RT_AUDIT_GOTEST", "/tmp/rt-audit/docs.test")
29
30
31def summarize(label, reqs, seconds):
32 def line(name, items):
33 if not items:
34 print(f"RTUI {label} {name}: 0")
35 return
36 dur = [r["end_ms"] - r["start_ms"] for r in items if "end_ms" in r]
37 print(f"RTUI {label} {name}: {len(items)} ({len(items)/seconds:.2f}/s); req bytes {sum(r.get('req_bytes', 0) for r in items)} "
38 f"(max {max(r.get('req_bytes', 0) for r in items)}); resp bytes {sum(r.get('resp_bytes', 0) for r in items)} "
39 f"(max {max(r.get('resp_bytes', 0) for r in items)}); server ms median {statistics.median(dur) if dur else 0:.1f} max {max(dur) if dur else 0:.1f}")
40 done = [r for r in reqs if "event" not in r]
41 line("POST /updates", [r for r in done if r["method"] == "POST" and "/updates" in r["path"]])
42 line("GET /updates?since", [r for r in done if r["method"] == "GET" and "/updates?since" in r["path"]])
43 line("GET /updates (full)", [r for r in done if r["method"] == "GET" and r["path"].endswith("/updates")])
44 line("stream opens", [r for r in reqs if r.get("event") == "open"])
45 line("other", [r for r in done if "/updates" not in r["path"] and not r["path"].endswith("/stream")])
46
47
48with tempfile.TemporaryDirectory(prefix="docs-rt-ui-", dir="/tmp") as tmp:
49 scratch = Path(tmp)
50 env = dict(os.environ, DOCS_RT_AUDIT_DIR=tmp, DOCS_RT_AUDIT_SEED=seed, TMPDIR="/tmp",
51 DOCS_RT_AUDIT_KEYS=opts["KEYS"], DOCS_RT_AUDIT_CADENCE_MS=opts["CADENCE_MS"])
52 subprocess.run(["node", str(root / "fixtures/generate-peer-updates.mjs"), seed, opts["PEER"], str(scratch / "peer")], check=True, capture_output=True)
53 log = (scratch / "server.log").open("w")
54 server = subprocess.Popen([gotest, "-test.run", "^TestNativeRealtimeAuditServer$", "-test.count=1", "-test.timeout=25m"],
55 cwd=root / "internal/docs", env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
56 probe = None
57 try:
58 while not (scratch / "connection.json").exists():
59 if server.poll() is not None:
60 raise SystemExit((scratch / "server.log").read_text()[-3000:])
61 time.sleep(0.05)
62 conn = json.loads((scratch / "connection.json").read_text())
63 out = (scratch / "probe.log").open("w")
64 binary = root / "native/benchmarks/realtime/ui-probe/.build/release/RealtimeUIProbe"
65 args = [str(binary)] + ([] if opts["PAGED"] == "1" else ["-docs.view.paged", "NO"])
66 probe = subprocess.Popen(args, env=env, stdout=out, stderr=subprocess.STDOUT, start_new_session=True)
67 t_start = None
68 deadline = time.monotonic() + 900
69 while not (scratch / "typing-done").exists():
70 if probe.poll() is not None or time.monotonic() > deadline:
71 raise SystemExit("probe ended before typing-done:\n" + (scratch / "probe.log").read_text()[-3000:])
72 time.sleep(0.05)
73 time.sleep(1)
74 count, cadence = int(opts["PEER"]), float(opts["PEER_CADENCE_MS"]) / 1000
75 start = time.monotonic()
76 for k in range(count):
77 due = start + k * cadence
78 if due > time.monotonic():
79 time.sleep(due - time.monotonic())
80 body = (scratch / "peer" / f"{k}.bin").read_bytes()
81 req = urllib.request.Request(f"{conn['origin']}/d/{conn['sqid']}/updates", data=body, method="POST",
82 headers={"Origin": conn["origin"], "Content-Type": "application/octet-stream",
83 "Cookie": f"{conn['name']}={conn['value']}"})
84 urllib.request.urlopen(req).read()
85 (scratch / "remote-done").write_text(str(count))
86 probe.wait(timeout=600)
87 out.close()
88 text = (scratch / "probe.log").read_text()
89 print("\n".join(l for l in text.splitlines() if l.startswith("RTUI")))
90 reqs = [json.loads(l) for l in (scratch / "requests.jsonl").read_text().splitlines()]
91 typing_done_ms = (os.path.getmtime(scratch / "typing-done") * 1000) - conn["base_unix_ms"]
92 opened = [r for r in reqs if r.get("event") == "open"]
93 t0 = opened[0]["start_ms"] + 3000 if opened else 0 # the probe settles 3 s before typing
94 typing = [r for r in reqs if t0 <= r["start_ms"] <= typing_done_ms]
95 summarize("typing", typing, (typing_done_ms - t0) / 1000)
96 remote = [r for r in reqs if r["start_ms"] > typing_done_ms]
97 summarize("remote", remote, max(1, (remote[-1]["start_ms"] - typing_done_ms) / 1000) if remote else 1)
98 seen = json.loads((scratch / "seen.json").read_text()) if (scratch / "seen.json").exists() else []
99 posts = sorted([r for r in remote if "event" not in r and r["method"] == "POST"], key=lambda r: r["start_ms"])
100 lat = [s - p["start_ms"] for p, s in zip(posts, seen)]
101 if lat:
102 lat_sorted = sorted(lat)
103 print(f"RTUI remote: peer POST start -> visible in text view: median {statistics.median(lat):.0f} ms, p90 {lat_sorted[int(len(lat)*0.9)-1]:.0f} ms, max {max(lat):.0f} ms (n={len(lat)}/{count})")
104 if os.environ.get("DOCS_RT_AUDIT_KEEP"):
105 keep = Path(os.environ["DOCS_RT_AUDIT_KEEP"]); keep.mkdir(parents=True, exist_ok=True)
106 (keep / f"{Path(seed).stem}-ui.requests.jsonl").write_text((scratch / "requests.jsonl").read_text())
107 (keep / f"{Path(seed).stem}-ui.probe.log").write_text(text)
108 finally:
109 (scratch / "done").touch()
110 for p in (probe, server):
111 if p is not None and p.poll() is None:
112 os.killpg(p.pid, signal.SIGTERM)
113 p.wait(timeout=10)
114 log.close()
115