#!/usr/bin/env python3 """Run the realtime UI probe: the real DocsWorkspace window (ui-probe/) against the audit fixture server seeded with a generated document. run-ui.py [KEYS=40] [CADENCE_MS=125] [PEER=30] [PEER_CADENCE_MS=125] [PAGED=1] Phase A: the probe types into the text view; the request log gives the uploads. Phase B: this script posts PEER one-character updates from another client (fixtures/generate-peer-updates.mjs) and the probe records when each appears in the text view. Needs a logged-in Mac session (it opens a window), the Go test binary at $DOCS_RT_AUDIT_GOTEST and a release build of ui-probe. """ import json import os from pathlib import Path import signal import statistics import subprocess import sys import tempfile import time import urllib.request root = Path(__file__).resolve().parents[3] seed = sys.argv[1] opts = dict(KEYS="40", CADENCE_MS="125", PEER="30", PEER_CADENCE_MS="125", PAGED="1") opts.update(dict(arg.split("=", 1) for arg in sys.argv[2:])) gotest = os.environ.get("DOCS_RT_AUDIT_GOTEST", "/tmp/rt-audit/docs.test") def summarize(label, reqs, seconds): def line(name, items): if not items: print(f"RTUI {label} {name}: 0") return dur = [r["end_ms"] - r["start_ms"] for r in items if "end_ms" in r] print(f"RTUI {label} {name}: {len(items)} ({len(items)/seconds:.2f}/s); req bytes {sum(r.get('req_bytes', 0) for r in items)} " f"(max {max(r.get('req_bytes', 0) for r in items)}); resp bytes {sum(r.get('resp_bytes', 0) for r in items)} " 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}") done = [r for r in reqs if "event" not in r] line("POST /updates", [r for r in done if r["method"] == "POST" and "/updates" in r["path"]]) line("GET /updates?since", [r for r in done if r["method"] == "GET" and "/updates?since" in r["path"]]) line("GET /updates (full)", [r for r in done if r["method"] == "GET" and r["path"].endswith("/updates")]) line("stream opens", [r for r in reqs if r.get("event") == "open"]) line("other", [r for r in done if "/updates" not in r["path"] and not r["path"].endswith("/stream")]) with tempfile.TemporaryDirectory(prefix="docs-rt-ui-", dir="/tmp") as tmp: scratch = Path(tmp) env = dict(os.environ, DOCS_RT_AUDIT_DIR=tmp, DOCS_RT_AUDIT_SEED=seed, TMPDIR="/tmp", DOCS_RT_AUDIT_KEYS=opts["KEYS"], DOCS_RT_AUDIT_CADENCE_MS=opts["CADENCE_MS"]) subprocess.run(["node", str(root / "fixtures/generate-peer-updates.mjs"), seed, opts["PEER"], str(scratch / "peer")], check=True, capture_output=True) log = (scratch / "server.log").open("w") server = subprocess.Popen([gotest, "-test.run", "^TestNativeRealtimeAuditServer$", "-test.count=1", "-test.timeout=25m"], cwd=root / "internal/docs", env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) probe = None try: while not (scratch / "connection.json").exists(): if server.poll() is not None: raise SystemExit((scratch / "server.log").read_text()[-3000:]) time.sleep(0.05) conn = json.loads((scratch / "connection.json").read_text()) out = (scratch / "probe.log").open("w") binary = root / "native/benchmarks/realtime/ui-probe/.build/release/RealtimeUIProbe" args = [str(binary)] + ([] if opts["PAGED"] == "1" else ["-docs.view.paged", "NO"]) probe = subprocess.Popen(args, env=env, stdout=out, stderr=subprocess.STDOUT, start_new_session=True) t_start = None deadline = time.monotonic() + 900 while not (scratch / "typing-done").exists(): if probe.poll() is not None or time.monotonic() > deadline: raise SystemExit("probe ended before typing-done:\n" + (scratch / "probe.log").read_text()[-3000:]) time.sleep(0.05) time.sleep(1) count, cadence = int(opts["PEER"]), float(opts["PEER_CADENCE_MS"]) / 1000 start = time.monotonic() for k in range(count): due = start + k * cadence if due > time.monotonic(): time.sleep(due - time.monotonic()) body = (scratch / "peer" / f"{k}.bin").read_bytes() req = urllib.request.Request(f"{conn['origin']}/d/{conn['sqid']}/updates", data=body, method="POST", headers={"Origin": conn["origin"], "Content-Type": "application/octet-stream", "Cookie": f"{conn['name']}={conn['value']}"}) urllib.request.urlopen(req).read() (scratch / "remote-done").write_text(str(count)) probe.wait(timeout=600) out.close() text = (scratch / "probe.log").read_text() print("\n".join(l for l in text.splitlines() if l.startswith("RTUI"))) reqs = [json.loads(l) for l in (scratch / "requests.jsonl").read_text().splitlines()] typing_done_ms = (os.path.getmtime(scratch / "typing-done") * 1000) - conn["base_unix_ms"] opened = [r for r in reqs if r.get("event") == "open"] t0 = opened[0]["start_ms"] + 3000 if opened else 0 # the probe settles 3 s before typing typing = [r for r in reqs if t0 <= r["start_ms"] <= typing_done_ms] summarize("typing", typing, (typing_done_ms - t0) / 1000) remote = [r for r in reqs if r["start_ms"] > typing_done_ms] summarize("remote", remote, max(1, (remote[-1]["start_ms"] - typing_done_ms) / 1000) if remote else 1) seen = json.loads((scratch / "seen.json").read_text()) if (scratch / "seen.json").exists() else [] posts = sorted([r for r in remote if "event" not in r and r["method"] == "POST"], key=lambda r: r["start_ms"]) lat = [s - p["start_ms"] for p, s in zip(posts, seen)] if lat: lat_sorted = sorted(lat) 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})") if os.environ.get("DOCS_RT_AUDIT_KEEP"): keep = Path(os.environ["DOCS_RT_AUDIT_KEEP"]); keep.mkdir(parents=True, exist_ok=True) (keep / f"{Path(seed).stem}-ui.requests.jsonl").write_text((scratch / "requests.jsonl").read_text()) (keep / f"{Path(seed).stem}-ui.probe.log").write_text(text) finally: (scratch / "done").touch() for p in (probe, server): if p is not None and p.poll() is None: os.killpg(p.pid, signal.SIGTERM) p.wait(timeout=10) log.close()