diff --git a/test/harness/ux_perf_test.py b/test/harness/ux_perf_test.py
new file mode 100644
index 000000000..a806a297a
--- /dev/null
+++ b/test/harness/ux_perf_test.py
@@ -0,0 +1,236 @@
+from __future__ import annotations
+
+import os
+from pathlib import Path
+import sys
+import tempfile
+import unittest
+
+ROOT = Path(__file__).resolve().parents[2]
+for extra in (ROOT / "test", ROOT / "test/manual/ux"):
+ if str(extra) not in sys.path:
+ sys.path.insert(0, str(extra))
+
+from manual.ux import perf, seed # noqa: E402
+
+
+class WorktreeDiscoveryTest(unittest.TestCase):
+ def test_origin_root_follows_jj_and_git_worktree_pointers(self) -> None:
+ with tempfile.TemporaryDirectory() as raw:
+ base = Path(raw)
+ main_repo = base / "main"
+ (main_repo / "cli/bin").mkdir(parents=True)
+ (main_repo / ".jj/repo").mkdir(parents=True)
+ cli_bin = main_repo / "cli/bin/albedo"
+ cli_bin.write_text("#!/bin/sh\nexit 0\n")
+ cli_bin.chmod(0o755)
+
+ jj_wt = base / "wt/jj-child"
+ (jj_wt / ".jj").mkdir(parents=True)
+ (jj_wt / ".jj/repo").write_text(
+ os.path.relpath(main_repo / ".jj/repo", jj_wt / ".jj")
+ )
+ self.assertEqual(seed.origin_root(jj_wt), main_repo.resolve())
+
+ git_wt = base / "wt/git-child"
+ git_wt.mkdir(parents=True)
+ git_dir = main_repo / ".git/worktrees/git-child"
+ git_dir.mkdir(parents=True)
+ (git_wt / ".git").write_text(f"gitdir: {git_dir}\n")
+ self.assertEqual(seed.origin_root(git_wt), main_repo.resolve())
+
+ def test_find_cli_prefers_explicit_and_base_bin(self) -> None:
+ with tempfile.TemporaryDirectory() as raw:
+ base = Path(raw)
+ (base / "bin").mkdir()
+ pinned = base / "bin/albedo"
+ pinned.write_text("#!/bin/sh\nexit 0\n")
+ pinned.chmod(0o755)
+ self.assertEqual(seed.find_cli(base, explicit=pinned), pinned.resolve())
+
+
+class PerfHelpersTest(unittest.IsolatedAsyncioTestCase):
+ async def test_interleave_rotates_order_and_summarizes_medians(self) -> None:
+ order: list[tuple[int, str]] = []
+
+ async def control(rep: int) -> dict[str, float | int]:
+ order.append((rep, "ctl"))
+ return {"nodes": 1000 + rep, "raf_per_s": 0.0}
+
+ async def variant(rep: int) -> dict[str, float | int]:
+ order.append((rep, "var"))
+ return {"nodes": 500 + rep * 2, "raf_per_s": 0.5 * rep}
+
+ rows, summary = await perf.interleave(
+ {"ctl": control, "var": variant}, reps=3, rotate=True
+ )
+ self.assertEqual(
+ order,
+ [
+ (0, "ctl"),
+ (0, "var"),
+ (1, "var"),
+ (1, "ctl"),
+ (2, "ctl"),
+ (2, "var"),
+ ],
+ )
+ self.assertEqual(len(rows), 6)
+ self.assertEqual(summary["ctl"]["nodes"]["text"], "1001 [1000-1002]")
+ self.assertEqual(summary["var"]["nodes"]["text"], "502 [500-504]")
+ self.assertEqual(summary["var"]["raf_per_s"]["text"], "0.50 [0.00-1.00]")
+
+ def test_summarize_trace_events_extracts_rates_and_main_cpu(self) -> None:
+ events = [
+ {
+ "ph": "M",
+ "pid": 10,
+ "tid": 1,
+ "name": "process_name",
+ "args": {"name": "Renderer"},
+ },
+ {
+ "ph": "M",
+ "pid": 10,
+ "tid": 1,
+ "name": "thread_name",
+ "args": {"name": "CrRendererMain"},
+ },
+ {
+ "ph": "M",
+ "pid": 20,
+ "tid": 2,
+ "name": "process_name",
+ "args": {"name": "GPU Process"},
+ },
+ {
+ "ph": "M",
+ "pid": 20,
+ "tid": 2,
+ "name": "thread_name",
+ "args": {"name": "VizCompositorThread"},
+ },
+ {
+ "ph": "X",
+ "pid": 10,
+ "tid": 1,
+ "name": "ThreadControllerImpl::RunTask",
+ "dur": 10_000,
+ "tdur": 8_000,
+ },
+ {
+ "ph": "X",
+ "pid": 10,
+ "tid": 1,
+ "name": "FireAnimationFrame",
+ "dur": 1000,
+ "tdur": 1000,
+ },
+ {
+ "ph": "X",
+ "pid": 10,
+ "tid": 1,
+ "name": "FireAnimationFrame",
+ "dur": 1000,
+ "tdur": 1000,
+ },
+ {
+ "ph": "X",
+ "pid": 10,
+ "tid": 1,
+ "name": "ProxyMain::BeginMainFrame",
+ "dur": 2000,
+ "tdur": 2000,
+ },
+ {
+ "ph": "X",
+ "pid": 20,
+ "tid": 2,
+ "name": "Display::DrawAndSwap",
+ "dur": 500,
+ "tdur": 500,
+ },
+ ]
+ summary = perf.summarize_trace_events(events, elapsed=2.0)
+ self.assertEqual(summary["main_ms_s"], 4.0)
+ self.assertEqual(summary["raf_per_s"], 1.0)
+ self.assertEqual(summary["frames_per_s"], 0.5)
+ self.assertEqual(summary["draws_per_s"], 0.5)
+
+ def test_evaluate_budgets_names_regressions_and_animations(self) -> None:
+ measured = {
+ "dense": {
+ "raf_per_s": 60.0,
+ "nodes": 12000,
+ "animations": ["shimmer@div.ghost"],
+ },
+ "wheel": {"oscillating_frames": 3, "grew_distance": 400},
+ }
+ budgets = {
+ "dense": {"raf_per_s": ("max", 2.0), "nodes": ("max", 9500)},
+ "wheel": {"oscillating_frames": ("max", 0), "grew_distance": ("min", 1200)},
+ }
+ failures = perf.evaluate_budgets(measured, budgets)
+ self.assertEqual(
+ failures,
+ [
+ "dense.raf_per_s grew to 60.0 (budget <= 2.0) (running infinite animations: shimmer@div.ghost)",
+ "dense.nodes grew to 12000 (budget <= 9500)",
+ "wheel.oscillating_frames grew to 3 (budget <= 0)",
+ "wheel.grew_distance fell to 400 (budget >= 1200)",
+ ],
+ )
+
+ async def test_check_builds_temp_dist_by_default_and_cleans_up(self) -> None:
+ from unittest import mock
+ from manual.ux import kit
+
+ built_paths: list[Path] = []
+ started_dists: list[Path] = []
+
+ async def fake_build(target: Path | str | None = None) -> Path:
+ assert target is not None
+ path = Path(target)
+ path.mkdir(parents=True, exist_ok=True)
+ (path / "index.html").write_text("")
+ built_paths.append(path)
+ return path
+
+ class DummyUI:
+ stopped_while_present = False
+
+ async def fresh(self, *_args: object, **_kwargs: object) -> None:
+ raise RuntimeError("stop after verifying dist")
+
+ async def stop(self) -> list[str]:
+ self.stopped_while_present = built_paths[0].exists()
+ return []
+
+ dummy = DummyUI()
+
+ async def fake_start(*_args: object, **kwargs: object) -> DummyUI:
+ dist_arg = kwargs["dist"]
+ assert isinstance(dist_arg, Path)
+ started_dists.append(dist_arg)
+ return dummy
+
+ with (
+ mock.patch.object(kit, "build", side_effect=fake_build),
+ mock.patch.object(perf, "start", side_effect=fake_start),
+ ):
+ with self.assertRaisesRegex(RuntimeError, "stop after verifying dist"):
+ await perf.check(base="/tmp/unused")
+
+ self.assertEqual(len(built_paths), 1)
+ self.assertEqual(started_dists, built_paths)
+ self.assertTrue(dummy.stopped_while_present)
+ self.assertFalse(built_paths[0].exists())
+ self.assertFalse(built_paths[0].parent.exists())
+
+ with tempfile.TemporaryDirectory() as missing:
+ with self.assertRaises(FileNotFoundError):
+ await perf.check(dist=Path(missing) / "no-such-dist")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test/manual/ux/README.md b/test/manual/ux/README.md
index 76fbca369..38bc3cc7c 100644
--- a/test/manual/ux/README.md
+++ b/test/manual/ux/README.md
@@ -5,7 +5,8 @@ local fake provider, and an owned Chrome browser. Drive it from an Albedo Python
kernel. It is an opt-in manual workflow, outside the test gate.
[`seed.py`](seed.py) owns seed creation. [`kit.py`](kit.py) owns each running
-review and its browser. Follow the repository's
+review and its browser. [`perf.py`](perf.py) owns memory, trace, count, and
+interleaved-repetition measurements. Follow the repository's
[private-daemon and UI review rules](../../../AGENTS.md#own-private-daemons) and
the [web client guide](../../../robot-docs/web.md).
@@ -21,13 +22,13 @@ go -C cli build -o bin/albedo ./cmd/albedo
python3 test/manual/ux/seed.py
```
-Install Chrome separately if it is unavailable. The browser binding finds an
-installed browser, rather than downloading one. Run the Python examples below in
-an Albedo kernel, where the `albedo` tool bindings exist, rather than in
-standalone Python. Set the same `ALBEDO_UX` in that kernel's environment
-**before importing `kit`**. Its base path is fixed at import time.
-`seed.py --base PATH` can also select a base, but does not set the kernel's
-environment.
+Install Chrome separately if it is unavailable (`nix develop` provides
+`chrome-headless-shell`). Both `kit` and `perf` run inside an Albedo Python
+kernel and in standalone `nix develop -c python3`. `kit` resolves `ALBEDO_UX`
+dynamically (or via `base=`), discovers a built `albedo` CLI across the current
+worktree, `/bin/albedo`, the enclosing main checkout, or `PATH`, and
+installs `web/node_modules` automatically when `kit.build()` runs in a fresh
+worktree.
Seeding builds a daemon snapshot in `daemon/`, a web build in `dist/`, two Git
workspaces in `ws/`, and a home in `seed/`. It creates chats covering markdown,
@@ -42,8 +43,9 @@ edits. Use separate bases for reviewers who need independent workspace state.
## Start, inspect, and stop
-Choose a new run name for every review. Existing names are rejected, including
-stopped runs, so their screenshots and homes are preserved.
+Choose a new run name for every review, or pass `unique=True` (`perf.start`
+enables this by default) to append a numeric suffix when retrying. Existing
+names are never overwritten, so their screenshots and homes are preserved.
```python
import sys
@@ -165,6 +167,37 @@ helper before using it to understand which state it changes.
and changes the seed's hello chat.
- [`artifact_touch_check.py`](artifact_touch_check.py): exercises artifact touch
behavior and changes preferences and boards. Use a disposable run.
+- [`perf.py`](perf.py):
+ - `await perf.start(name, ...)` starts a review with Chrome's `Accessibility`
+ domain disabled before the first navigation (avoiding Blink AX-tree
+ retention and double reloads) and `unique=True`. Pass `dpr=2` to launch
+ Chrome with `--force-device-scale-factor=2` so WebGL canvases keep 2x
+ backing buffers instead of emulated DPR.
+ - `await perf.counts(ui)` measures deterministic idle counts (`raf_per_s`,
+ `frames_per_s`, `layouts_per_s`, `recalcs_per_s`, `nodes`, `listeners`,
+ `heap_used` after forced GC, `font_combos`, and running infinite
+ `animations`).
+ - `await perf.wheel_up(ui, w)` sends real wheel-up notches (`ui.wheel` accepts
+ `wait=`, default `0.05` s) and checks distance gained, `snap_backs`, and
+ frame-to-frame `scrollHeight` `oscillating_frames`.
+ - `await perf.trace(ui, seconds)` and `await perf.allocators(ui)` summarize
+ per-thread CPU (`tdur`), frame rates, live sub-allocators (`malloc_live`,
+ `blink_gc_live`, `v8_live`), and macOS SF font instances.
+ - `await perf.interleave({"ctl": ..., "var": ...}, reps=3)` rotates variant
+ order across repetitions and returns rows plus `median [min-max]` summaries.
+ - `await perf.snapshot(ui, path)` streams a V8 heap snapshot to disk. Taking a
+ snapshot permanently retains ~9–10 MB of renderer `malloc` on that page;
+ take snapshots last or call `await perf.fresh_browser(ui)` afterward.
+ - `python3 test/manual/ux/perf.py check [--seed] [--base PATH] [--dist PATH]`
+ runs the standalone count and wheel-scroll budget gate across `huge_chat`,
+ `tiles-basic` (focused and unfocused terminal), and `dense`. Without
+ `--dist`, it builds this checkout's `web/` into a temporary directory so a
+ stale `/dist` is never tested by accident; `--seed` builds the CLI if
+ needed and seeds a fresh base first (used by `perf-web.yml` in CI).
+ - In an Albedo kernel, run long benchmark loops directly in a cell (which
+ backgrounds at 60 s and wakes the session on completion) rather than via
+ `asyncio.ensure_future` or `asyncio.create_task`, which never wake an idle
+ session.
[`replies.py`](replies.py) selects fake responses by message content. Examples
include slow or hung replies, failures, tools, jobs, agents, edits, tables, long
diff --git a/test/manual/ux/perf.py b/test/manual/ux/perf.py
index 0f94a282d..8b79143f2 100644
--- a/test/manual/ux/perf.py
+++ b/test/manual/ux/perf.py
@@ -1,19 +1,19 @@
-"""Measure the web client's memory and CPU in a UI review run.
+"""Measure the web client's memory, counts, traces and CPU in a UI review run.
- import sys; sys.path.insert(0, "test/manual/ux"); import kit, perf
- ui = await kit.start("perf-idle-001")
+ import sys; sys.path.insert(0, "test/manual/ux"); import perf
+ ui = await perf.start("perf-idle-001")
try:
- await ui.load("boards-and-empty")
- await ui.open_chat("hello chat")
+ await ui.load("dense")
+ print(await perf.counts(ui))
print(await perf.memory(ui))
- print(await perf.cpu(ui, 20))
- await perf.snapshot(ui, "/tmp/albedo-web-perf/idle.heapsnapshot")
finally:
await ui.stop()
-`python3 test/manual/ux/perf.py heap a.heapsnapshot [b.heapsnapshot]` lists
-what holds a snapshot's memory, or what grew from a to b. It runs in its own
-process because a parsed snapshot outgrows a kernel cell.
+Subcommands (run in their own process):
+- `python3 test/manual/ux/perf.py heap a.heapsnapshot [b.heapsnapshot]` lists
+ what holds a snapshot's memory, or what grew from a to b.
+- `python3 test/manual/ux/perf.py check [--base PATH] [--dist PATH] [--out PATH]`
+ runs the count-based web performance and wheel-scroll gate against a seeded base.
Numbers come from headless Chrome with a software GPU: compare runs with each
other, not with a person's browser.
@@ -21,12 +21,18 @@ other, not with a person's browser.
from __future__ import annotations
+import argparse
import asyncio
import collections
+import contextlib
+from collections.abc import Awaitable, Callable, Mapping, Sequence
import json
+import os
import re
+import statistics
import subprocess
import sys
+import tempfile
import time
from pathlib import Path
from typing import Any
@@ -40,6 +46,170 @@ PERFORMANCE = (
"RecalcStyleCount",
)
+TRACE_CATEGORIES = (
+ "devtools.timeline",
+ "disabled-by-default-devtools.timeline",
+ "disabled-by-default-devtools.timeline.frame",
+ "toplevel",
+ "blink",
+ "cc",
+ "viz",
+ "gpu",
+)
+
+FONT_COMBOS_JS = """() => {
+ const seen = new Set();
+ const walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
+ let node;
+ while ((node = walk.nextNode())) {
+ if (!node.data.trim()) continue;
+ const el = node.parentElement;
+ if (!el || !el.checkVisibility({ checkVisibilityCSS: true }) || el.closest('.window-parking')) continue;
+ const cs = getComputedStyle(el);
+ const fam = cs.fontFamily.split(',')[0].trim().replace(/['"]/g, '');
+ seen.add(`${fam}|${cs.fontSize}|${cs.fontWeight}|${cs.fontStyle}`);
+ }
+ return [...seen].sort();
+}"""
+
+ANIMATIONS_JS = """() => document.getAnimations({ subtree: true }).filter((a) => {
+ const timing = a.effect?.getComputedTiming?.() ?? {};
+ return a.playState === 'running' && timing.iterations === Infinity;
+}).map((a) => {
+ const el = a.effect?.target instanceof Element ? a.effect.target : null;
+ const cls = el?.className ? String(el.className).trim().split(/\s+/)[0] : '';
+ const where = el ? el.tagName.toLowerCase() + (cls ? '.' + cls : '') : '?';
+ return `${a.animationName || a.id || 'animation'}@${where}`;
+})"""
+
+WHEEL_TRACE_JS = """(id) => {
+ const slot = document.querySelector(`.window-slot[data-id="${CSS.escape(id)}"]`);
+ const scroller = slot?.querySelector('.scroller');
+ if (!scroller) throw new Error(`no .scroller in window ${id}`);
+ window.__albedoWheelFrames = [];
+ window.__albedoWheelStop = false;
+ const t0 = performance.now();
+ const tick = () => {
+ const rows = [...scroller.querySelectorAll('[data-index]')];
+ const indices = rows.map((r) => Number(r.dataset.index));
+ window.__albedoWheelFrames.push([
+ Math.round(performance.now() - t0),
+ Math.round(scroller.scrollTop),
+ Math.round(scroller.scrollHeight),
+ Math.round(scroller.clientHeight),
+ indices.length ? Math.min(...indices) : -1,
+ indices.length ? Math.max(...indices) : -1,
+ ]);
+ if (!window.__albedoWheelStop && window.__albedoWheelFrames.length < 600) {
+ requestAnimationFrame(tick);
+ }
+ };
+ requestAnimationFrame(tick);
+ const r = scroller.getBoundingClientRect();
+ return {
+ center: [r.left + r.width / 2, r.top + r.height / 2],
+ initial: [
+ Math.round(scroller.scrollTop),
+ Math.round(scroller.scrollHeight),
+ Math.round(scroller.clientHeight),
+ ],
+ };
+}"""
+
+# Medians measured on the seeded scenarios, plus headroom.
+DEFAULT_BUDGETS: dict[str, dict[str, tuple[str, float]]] = {
+ "huge_chat": {
+ "raf_per_s": ("max", 2.0),
+ "layouts_per_s": ("max", 2.0),
+ "recalcs_per_s": ("max", 2.0),
+ "nodes": ("max", 4500),
+ "listeners": ("max", 500),
+ "heap_used": ("max", 16_000_000),
+ "font_combos": ("max", 18),
+ },
+ "huge_chat_wheel": {
+ "oscillating_frames": ("max", 0),
+ "snap_backs": ("max", 0),
+ "grew_distance": ("min", 1200),
+ },
+ "terminal_focused": {
+ "raf_per_s": ("max", 4.0),
+ "frames_per_s": ("max", 8.0),
+ "layouts_per_s": ("max", 2.0),
+ "recalcs_per_s": ("max", 4.0),
+ "nodes": ("max", 6500),
+ "listeners": ("max", 650),
+ "heap_used": ("max", 18_000_000),
+ "font_combos": ("max", 20),
+ },
+ "terminal_unfocused": {
+ "raf_per_s": ("max", 2.0),
+ "frames_per_s": ("max", 2.0),
+ "layouts_per_s": ("max", 2.0),
+ "recalcs_per_s": ("max", 2.0),
+ },
+ "dense": {
+ "raf_per_s": ("max", 2.0),
+ "layouts_per_s": ("max", 2.0),
+ "recalcs_per_s": ("max", 2.0),
+ "nodes": ("max", 9500),
+ "listeners": ("max", 900),
+ "heap_used": ("max", 22_000_000),
+ "font_combos": ("max", 24),
+ },
+ "dense_allocators": {
+ "sf_font_instances": ("max", 26),
+ },
+}
+
+
+def _kit() -> Any:
+ if __package__:
+ from . import kit
+
+ return kit
+ import kit
+
+ return kit
+
+
+async def start(
+ name: str,
+ *,
+ accessibility: bool = False,
+ unique: bool = True,
+ **kwargs: Any,
+) -> Any:
+ """A review run with accessibility off before the first load and a run name of its own."""
+ return await _kit().start(
+ name, accessibility=accessibility, unique=unique, **kwargs
+ )
+
+
+async def fresh_browser(
+ ui: Any,
+ *,
+ width: int = 1440,
+ height: int = 900,
+ dark: bool = False,
+ reduced_motion: bool = False,
+ accessibility: bool = False,
+ dpr: float | None = None,
+ browser_args: Sequence[str] = (),
+) -> None:
+ """A new Chrome on the same daemon and web server. A heap snapshot leaves the
+ renderer's malloc inflated and font caches live per process."""
+ await _kit().open_browser(
+ ui,
+ width=width,
+ height=height,
+ dark=dark,
+ reduced_motion=reduced_motion,
+ accessibility=accessibility,
+ dpr=dpr,
+ browser_args=browser_args,
+ )
+
async def metrics(ui: Any) -> dict[str, float]:
await ui.page.cdp.send("Performance.enable", {})
@@ -80,11 +250,15 @@ async def renderer(ui: Any) -> int | None:
return max(found, key=lambda p: p["cpuTime"])["id"] if found else None
+async def collect_garbage(ui: Any, rounds: int = 2) -> None:
+ for _ in range(rounds):
+ await ui.page.cdp.send("HeapProfiler.collectGarbage", {})
+
+
async def memory(ui: Any) -> dict[str, Any]:
"""Memory the page keeps after two forced collections."""
cdp = ui.page.cdp
- for _ in range(2):
- await cdp.send("HeapProfiler.collectGarbage", {})
+ await collect_garbage(ui, 2)
heap = await cdp.send("Runtime.getHeapUsage", {})
dom = await cdp.send("Memory.getDOMCounters", {})
pid = await renderer(ui)
@@ -102,10 +276,10 @@ async def cpu(ui: Any, seconds: float) -> dict[str, Any]:
"""CPU each Chrome process used over the next seconds, as a percentage of
one core, and the page's main-thread work in that window."""
before, used = await metrics(ui), await processes(ui)
- start = time.monotonic()
+ started = time.monotonic()
await asyncio.sleep(seconds)
after, now = await metrics(ui), await processes(ui)
- elapsed = time.monotonic() - start
+ elapsed = time.monotonic() - started
spent: collections.Counter[str] = collections.Counter()
for p in now:
spent[p["type"]] += p["cpuTime"]
@@ -146,7 +320,15 @@ def hot(found: dict, count: int = 20) -> list[tuple[str, float]]:
async def snapshot(ui: Any, path: str | Path) -> Path:
"""Write a heap snapshot to path after a forced collection. The chunks go
- straight to the file, so the kernel never holds the whole snapshot."""
+ straight to the file, so the kernel never holds the whole snapshot.
+
+ Note: V8/Blink heap snapshot serialization permanently retains ~9-10 MB of
+ renderer malloc for the rest of this page's life. Take snapshots last, or
+ call `await perf.fresh_browser(ui)` before measuring native memory again.
+ """
+ py_dir = str(Path(__file__).resolve().parents[3] / "python")
+ if py_dir not in sys.path:
+ sys.path.insert(0, py_dir)
from albedo_plugins.browser.errors import WaitTimeout
cdp, path = ui.page.cdp, Path(path)
@@ -177,51 +359,83 @@ async def snapshot(ui: Any, path: str | Path) -> Path:
async def without_accessibility(ui: Any) -> None:
"""Turn off the accessibility tree the browser binding enables on every
- page, and reload. Blink keeps AX objects for removed nodes while it is on,
- which a person's browser only does with an accessibility client running."""
+ page, and reload if it was previously enabled. Prefer `perf.start()`, which
+ disables Accessibility before the first navigation."""
+ was_enabled = getattr(ui, "accessibility", True)
for state in ui.page._sessions.values():
await state.cdp.send("Accessibility.disable", {})
- await ui.reload()
+ ui.accessibility = False
+ if was_enabled:
+ await ui.reload()
-async def breakdown(
- ui: Any, path: str | Path, pid: int | None = None
-) -> dict[str, int]:
- """The review page renderer's memory by allocator (v8, blink_gc,
- partition_alloc, malloc, skia, cc, font_caches, ...), from one detailed
- memory-infra dump. The trace is saved at path for chrome://tracing."""
- cdp, path = ui.browser.cdp, Path(path)
- path.parent.mkdir(parents=True, exist_ok=True)
- pid = pid or await renderer(ui)
+async def _capture_trace(
+ ui: Any,
+ categories: Sequence[str],
+ action: Callable[[Any], Awaitable[None]],
+ path: str | Path | None = None,
+ *,
+ memory_triggers: list[dict[str, Any]] | None = None,
+) -> list[dict[str, Any]]:
+ cdp = ui.browser.cdp
+ temporary: Path | None = None
+ if path is None:
+ fd, raw_name = tempfile.mkstemp(prefix="albedo-ux-trace-", suffix=".json")
+ os.close(fd)
+ target = temporary = Path(raw_name)
+ else:
+ target = Path(path)
+ target.parent.mkdir(parents=True, exist_ok=True)
done = cdp.connection.subscribe(
"Tracing.tracingComplete", cdp.session_id, capacity=4, max_bytes=1 << 16
)
+ trace_config: dict[str, Any] = {
+ "includedCategories": list(categories),
+ "excludedCategories": ["*"],
+ }
+ if memory_triggers is not None:
+ trace_config["memoryDumpConfig"] = {"triggers": memory_triggers}
try:
await cdp.send(
"Tracing.start",
- {
- "traceConfig": {
- "includedCategories": ["disabled-by-default-memory-infra"],
- "excludedCategories": ["*"],
- "memoryDumpConfig": {"triggers": []},
- },
- "transferMode": "ReturnAsStream",
- },
+ {"traceConfig": trace_config, "transferMode": "ReturnAsStream"},
)
- await cdp.send("Tracing.requestMemoryDump", {"levelOfDetail": "detailed"})
+ await action(cdp)
await cdp.send("Tracing.end", {})
- stream = (await done.next(timeout=60))["stream"]
+ stream = (await done.next(timeout=120))["stream"]
+ with target.open("w") as out:
+ while True:
+ chunk = await cdp.send("IO.read", {"handle": stream, "size": 1 << 20})
+ out.write(chunk["data"])
+ if chunk.get("eof"):
+ break
+ await cdp.send("IO.close", {"handle": stream})
+ parsed = json.loads(target.read_text())
+ return parsed["traceEvents"] if isinstance(parsed, dict) else parsed
finally:
done.close()
- with path.open("w") as out:
- while True:
- chunk = await cdp.send("IO.read", {"handle": stream, "size": 1 << 20})
- out.write(chunk["data"])
- if chunk.get("eof"):
- break
- await cdp.send("IO.close", {"handle": stream})
- trace = json.loads(path.read_text())
- events = trace["traceEvents"] if isinstance(trace, dict) else trace
+ if temporary is not None:
+ temporary.unlink(missing_ok=True)
+
+
+async def breakdown(
+ ui: Any, path: str | Path | None = None, pid: int | None = None
+) -> dict[str, int]:
+ """The review page renderer's memory by allocator (v8, blink_gc,
+ partition_alloc, malloc, skia, cc, font_caches, ...), from one detailed
+ memory-infra dump. When path is given, the trace is saved for chrome://tracing."""
+ pid = pid or await renderer(ui)
+
+ async def dump(cdp: Any) -> None:
+ await cdp.send("Tracing.requestMemoryDump", {"levelOfDetail": "detailed"})
+
+ events = await _capture_trace(
+ ui,
+ ["disabled-by-default-memory-infra"],
+ dump,
+ path,
+ memory_triggers=[],
+ )
sizes: dict[str, int] = {}
for event in events:
if event.get("ph") != "v" or event.get("pid") != pid:
@@ -235,7 +449,470 @@ async def breakdown(
return dict(sorted(sizes.items(), key=lambda kv: -kv[1]))
-# The rest runs as its own process: python3 perf.py heap a [b]
+async def allocators(
+ ui: Any, path: str | Path | None = None, pid: int | None = None
+) -> dict[str, int]:
+ """Live and committed bytes per renderer allocator after a forced gc, with
+ macOS SF font instances."""
+ await collect_garbage(ui, 2)
+ pid = pid or await renderer(ui)
+
+ async def dump(cdp: Any) -> None:
+ await cdp.send("Tracing.requestMemoryDump", {"levelOfDetail": "detailed"})
+
+ events = await _capture_trace(
+ ui,
+ ["disabled-by-default-memory-infra"],
+ dump,
+ path,
+ memory_triggers=[],
+ )
+ raw: dict[str, dict[str, int]] = {}
+ for event in events:
+ if event.get("ph") != "v" or event.get("pid") != pid:
+ continue
+ for name, entry in event["args"]["dumps"].get("allocators", {}).items():
+ attrs = entry.get("attrs", {})
+ parsed = {
+ k: int(v["value"], 16)
+ for k, v in attrs.items()
+ if isinstance(v, dict) and v.get("units") in ("bytes", "objects")
+ }
+ if parsed:
+ raw[name] = parsed
+
+ def attr(name: str, key: str = "size") -> int:
+ return raw.get(name, {}).get(key, 0)
+
+ sf_bucket = attr(
+ "malloc/allocated_objects/partitions/allocator/buckets/bucket_0458752"
+ )
+ return {
+ "malloc": attr("malloc"),
+ "malloc_live": attr("malloc/allocated_objects"),
+ "blink_gc": attr("blink_gc"),
+ "blink_gc_live": (
+ attr("blink_gc/main/allocated_objects")
+ or attr("blink_gc/main/heap", "allocated_objects_size")
+ ),
+ "v8": attr("v8"),
+ "v8_live": (
+ attr("v8/main/heap", "allocated_objects_size") or attr("v8/main/heap")
+ ),
+ "cc": attr("cc"),
+ "skia": attr("skia"),
+ "shared_memory": attr("shared_memory"),
+ "partition_alloc": attr("partition_alloc"),
+ "font_caches": attr("font_caches"),
+ "sf_font_instances": round(sf_bucket / 458_752) if sf_bucket else 0,
+ }
+
+
+def summarize_trace_events(
+ events: list[dict[str, Any]], elapsed: float
+) -> dict[str, float]:
+ proc_names = {
+ e["pid"]: e["args"].get("name", "")
+ for e in events
+ if e.get("ph") == "M" and e.get("name") == "process_name"
+ }
+ thread_names = {
+ (e["pid"], e["tid"]): e["args"].get("name", "")
+ for e in events
+ if e.get("ph") == "M" and e.get("name") == "thread_name"
+ }
+ top_tasks = {"ThreadControllerImpl::RunTask", "ThreadPool_RunTask"}
+ busy_ms: collections.Counter[tuple[int, int]] = collections.Counter()
+ for e in events:
+ if e.get("ph") == "X" and e.get("name") in top_tasks:
+ busy_ms[(e["pid"], e["tid"])] += e.get("tdur", e.get("dur", 0)) / 1e3
+
+ rend_totals: collections.Counter[int] = collections.Counter()
+ for (pid, _tid), ms in busy_ms.items():
+ if proc_names.get(pid, "").startswith("Renderer"):
+ rend_totals[pid] += ms
+ if not rend_totals:
+ # An idle renderer can log no RunTask events at all.
+ renderer_pids = [
+ pid for pid, name in proc_names.items() if name.startswith("Renderer")
+ ]
+ rp = renderer_pids[0] if renderer_pids else -1
+ else:
+ rp = rend_totals.most_common(1)[0][0]
+
+ span = max(elapsed, 0.001)
+
+ def thread_rate(pred: Callable[[int, str], bool]) -> float:
+ return round(
+ sum(
+ ms
+ for (p, t), ms in busy_ms.items()
+ if pred(p, thread_names.get((p, t), ""))
+ )
+ / span,
+ 2,
+ )
+
+ counts: collections.Counter[str] = collections.Counter()
+ for e in events:
+ if e.get("ph") != "X":
+ continue
+ name = e.get("name", "")
+ if (
+ e.get("pid") == rp
+ and thread_names.get((rp, e.get("tid", -1))) == "CrRendererMain"
+ ):
+ if name in (
+ "FireAnimationFrame",
+ "ProxyMain::BeginMainFrame",
+ "Layout",
+ "UpdateLayoutTree",
+ "Paint",
+ ):
+ counts[name] += 1
+ elif (
+ proc_names.get(e.get("pid", -1), "").startswith("GPU")
+ and name == "Display::DrawAndSwap"
+ ):
+ counts["Display::DrawAndSwap"] += 1
+
+ return {
+ "span": round(span, 2),
+ "main_ms_s": thread_rate(lambda p, t: p == rp and t == "CrRendererMain"),
+ "compositor_ms_s": thread_rate(lambda p, t: p == rp and t == "Compositor"),
+ "renderer_ms_s": thread_rate(lambda p, _t: p == rp),
+ "gpu_viz_ms_s": thread_rate(
+ lambda p, t: (
+ proc_names.get(p, "").startswith("GPU") and t == "VizCompositorThread"
+ )
+ ),
+ "gpu_ms_s": thread_rate(lambda p, _t: proc_names.get(p, "").startswith("GPU")),
+ "raf_per_s": round(counts["FireAnimationFrame"] / span, 2),
+ "frames_per_s": round(counts["ProxyMain::BeginMainFrame"] / span, 2),
+ "trace_layouts_per_s": round(counts["Layout"] / span, 2),
+ "trace_recalcs_per_s": round(counts["UpdateLayoutTree"] / span, 2),
+ "paints_per_s": round(counts["Paint"] / span, 2),
+ "draws_per_s": round(counts["Display::DrawAndSwap"] / span, 2),
+ }
+
+
+async def trace(
+ ui: Any,
+ seconds: float,
+ path: str | Path | None = None,
+ *,
+ categories: Sequence[str] = TRACE_CATEGORIES,
+) -> dict[str, float]:
+ """Capture a Chrome trace for seconds and return thread-CPU ms/s and frame/layout rates."""
+ started = 0.0
+ elapsed = seconds
+
+ async def wait(_cdp: Any) -> None:
+ nonlocal started, elapsed
+ started = time.monotonic()
+ await asyncio.sleep(seconds)
+ elapsed = time.monotonic() - started
+
+ events = await _capture_trace(ui, categories, wait, path)
+ return summarize_trace_events(events, elapsed)
+
+
+async def counts(ui: Any, *, idle_seconds: float = 2.0) -> dict[str, Any]:
+ """Counts at idle that don't depend on how fast the machine is: rAF callbacks,
+ frames, layouts and style recalcs per second, DOM nodes, listeners, documents,
+ JS heap after gc, font combinations and running infinite animations."""
+ cdp = ui.page.cdp
+ await collect_garbage(ui, 2)
+ heap = await cdp.send("Runtime.getHeapUsage", {})
+ dom = await cdp.send("Memory.getDOMCounters", {})
+ combos: list[str] = await ui.js(FONT_COMBOS_JS)
+ animations: list[str] = await ui.js(ANIMATIONS_JS)
+
+ before = await metrics(ui)
+ elapsed = idle_seconds
+
+ async def wait(_browser_cdp: Any) -> None:
+ nonlocal elapsed
+ t0 = time.monotonic()
+ await asyncio.sleep(idle_seconds)
+ elapsed = time.monotonic() - t0
+
+ events = await _capture_trace(
+ ui,
+ (
+ "devtools.timeline",
+ "disabled-by-default-devtools.timeline.frame",
+ "blink",
+ "cc",
+ "viz",
+ ),
+ wait,
+ )
+ after = await metrics(ui)
+ traced = summarize_trace_events(events, elapsed)
+ span = max(elapsed, 0.001)
+ return {
+ "raf_per_s": traced["raf_per_s"],
+ "frames_per_s": traced["frames_per_s"],
+ "layouts_per_s": round(
+ (after["LayoutCount"] - before.get("LayoutCount", 0)) / span, 2
+ ),
+ "recalcs_per_s": round(
+ (after["RecalcStyleCount"] - before.get("RecalcStyleCount", 0)) / span, 2
+ ),
+ "nodes": dom["nodes"],
+ "listeners": dom["jsEventListeners"],
+ "documents": dom["documents"],
+ "heap_used": heap["usedSize"],
+ "font_combos": len(combos),
+ "animations": animations,
+ }
+
+
+async def wheel_up(
+ ui: Any,
+ w: str = "w0",
+ *,
+ notches: int = 15,
+ delta_y: float = -240,
+ interval: float = 0.03,
+ settle: float = 0.8,
+) -> dict[str, Any]:
+ """Scrolls chat window `w` up with real wheel events. Flags the list flipping
+ between two drawn ranges (scrollHeight alternating every frame) and snap-backs
+ to the end."""
+ window = await ui.window(w)
+ started = await ui.js(WHEEL_TRACE_JS, window["id"])
+ cx, cy = started["center"]
+ st0, sh0, ch0 = started["initial"]
+ start_dist = max(0, sh0 - st0 - ch0)
+
+ for _ in range(notches):
+ await ui.wheel(cx, cy, 0, delta_y, wait=interval)
+ if settle > 0:
+ await asyncio.sleep(settle)
+ frames: list[list[int]] = await ui.js(
+ "() => { window.__albedoWheelStop = true; return window.__albedoWheelFrames ?? []; }"
+ )
+ final_st, final_sh, final_ch = await ui.scroll(w)
+ end_dist = max(0, final_sh - final_st - final_ch)
+
+ oscillating = [
+ i
+ for i in range(2, len(frames))
+ if frames[i][2] == frames[i - 2][2] and frames[i][2] != frames[i - 1][2]
+ ]
+ peaked = start_dist
+ snap_backs = 0
+ for _t, st, sh, ch, _lo, _hi in frames:
+ dist = max(0, sh - st - ch)
+ peaked = max(peaked, dist)
+ if peaked >= 400 and dist < 50:
+ snap_backs += 1
+ peaked = dist
+
+ return {
+ "frames": len(frames),
+ "start_distance": start_dist,
+ "end_distance": end_dist,
+ "grew_distance": end_dist - start_dist,
+ "oscillating_frames": len(oscillating),
+ "snap_backs": snap_backs,
+ }
+
+
+def format_stat(values: Sequence[float | int], *, precision: int = 2) -> str:
+ ordered = sorted(values)
+ med = statistics.median(ordered)
+ if all(isinstance(v, int) and not isinstance(v, bool) for v in ordered):
+ if med == int(med):
+ return f"{int(med)} [{ordered[0]}-{ordered[-1]}]"
+ return f"{med:.1f} [{ordered[0]}-{ordered[-1]}]"
+ return (
+ f"{med:.{precision}f} [{ordered[0]:.{precision}f}-{ordered[-1]:.{precision}f}]"
+ )
+
+
+def summarize(
+ rows: Sequence[Mapping[str, Any]],
+ metrics_keys: Sequence[str] | None = None,
+ *,
+ group_key: str = "variant",
+) -> dict[str, dict[str, dict[str, Any]]]:
+ grouped: dict[str, list[Mapping[str, Any]]] = collections.defaultdict(list)
+ for row in rows:
+ grouped[str(row.get(group_key, "default"))].append(row)
+ if metrics_keys is None:
+ seen: list[str] = []
+ for row in rows:
+ for k, v in row.items():
+ if (
+ k not in (group_key, "rep")
+ and isinstance(v, (int, float))
+ and not isinstance(v, bool)
+ and k not in seen
+ ):
+ seen.append(k)
+ metrics_keys = seen
+
+ out: dict[str, dict[str, dict[str, Any]]] = {}
+ for variant, items in grouped.items():
+ out[variant] = {}
+ for key in metrics_keys:
+ vals = [
+ r[key]
+ for r in items
+ if key in r
+ and isinstance(r[key], (int, float))
+ and not isinstance(r[key], bool)
+ ]
+ if not vals:
+ continue
+ ordered = sorted(vals)
+ med = statistics.median(ordered)
+ out[variant][key] = {
+ "n": len(ordered),
+ "median": med,
+ "min": ordered[0],
+ "max": ordered[-1],
+ "spread": round(ordered[-1] - ordered[0], 4),
+ "text": format_stat(ordered),
+ }
+ return out
+
+
+async def interleave(
+ variants: Mapping[str, Callable[[int], Awaitable[dict[str, Any]]]],
+ *,
+ reps: int = 3,
+ rotate: bool = True,
+) -> tuple[list[dict[str, Any]], dict[str, dict[str, dict[str, Any]]]]:
+ """Rotates the variants' order every rep, so drift on the host lands on all of them."""
+ labels = list(variants.keys())
+ if not labels:
+ raise ValueError("variants must not be empty")
+ rows: list[dict[str, Any]] = []
+ for rep in range(reps):
+ order = (
+ labels[rep % len(labels) :] + labels[: rep % len(labels)]
+ if rotate
+ else labels
+ )
+ for label in order:
+ measured = await variants[label](rep)
+ rows.append({"variant": label, "rep": rep, **measured})
+ return rows, summarize(rows)
+
+
+def evaluate_budgets(
+ scenarios: Mapping[str, Mapping[str, Any]],
+ budgets: Mapping[str, Mapping[str, tuple[str, float]]] = DEFAULT_BUDGETS,
+) -> list[str]:
+ failures: list[str] = []
+ for scenario_name, rules in budgets.items():
+ if scenario_name not in scenarios:
+ failures.append(f"{scenario_name}: scenario missing from measurement")
+ continue
+ measured = scenarios[scenario_name]
+ anims = measured.get("animations") or []
+ hint = f" (running infinite animations: {', '.join(anims)})" if anims else ""
+ for key, (direction, limit) in rules.items():
+ value = measured.get(key)
+ if value is None:
+ failures.append(f"{scenario_name}.{key}: missing metric")
+ continue
+ if direction == "max" and value > limit:
+ extra = hint if key.endswith("_per_s") else ""
+ failures.append(
+ f"{scenario_name}.{key} grew to {value} (budget <= {limit}){extra}"
+ )
+ elif direction == "min" and value < limit:
+ failures.append(
+ f"{scenario_name}.{key} fell to {value} (budget >= {limit})"
+ )
+ return failures
+
+
+async def check(
+ *,
+ base: str | Path | None = None,
+ dist: str | Path | None = None,
+ idle_seconds: float = 2.0,
+ budgets: Mapping[str, Mapping[str, tuple[str, float]]] = DEFAULT_BUDGETS,
+) -> dict[str, Any]:
+ """Without dist, builds this checkout's web client into a temporary directory:
+ an old /dist would check code that isn't this checkout's."""
+ started = time.monotonic()
+ with contextlib.ExitStack() as owned:
+ if dist is None:
+ temp_root = Path(
+ owned.enter_context(
+ tempfile.TemporaryDirectory(prefix="albedo-web-check-")
+ )
+ )
+ served_dist = await _kit().build(temp_root / "dist")
+ else:
+ served_dist = Path(dist)
+ if not (served_dist / "index.html").is_file():
+ raise FileNotFoundError(f"no built web client in {served_dist}")
+ ui = await start(
+ "web-perf-check",
+ base=base,
+ dist=served_dist,
+ accessibility=False,
+ unique=True,
+ )
+ try:
+ scenarios: dict[str, Any] = {}
+
+ await ui.fresh("tiles")
+ await ui.open_chat("a huge chat")
+ await ui.blur()
+ await asyncio.sleep(1.2)
+ scenarios["huge_chat"] = await counts(ui, idle_seconds=idle_seconds)
+ scenarios["huge_chat_wheel"] = await wheel_up(ui, "w0")
+
+ await ui.load("tiles-basic")
+ term = await ui.window("w3")
+ tx, ty, tw, th = term["box"]
+ await ui.click(tx + tw / 2, ty + th / 2)
+ await asyncio.sleep(0.8)
+ scenarios["terminal_focused"] = {
+ **(await counts(ui, idle_seconds=idle_seconds)),
+ "webgl": int(
+ await ui.js("() => !!document.querySelector('.pty-view canvas')")
+ ),
+ }
+
+ await ui.blur()
+ await asyncio.sleep(0.8)
+ scenarios["terminal_unfocused"] = await counts(
+ ui, idle_seconds=idle_seconds
+ )
+
+ await ui.load("dense")
+ await ui.blur()
+ await asyncio.sleep(1.2)
+ scenarios["dense"] = await counts(ui, idle_seconds=idle_seconds)
+ scenarios["dense_allocators"] = await allocators(ui)
+
+ page_errors = await ui.errors()
+ failures = evaluate_budgets(scenarios, budgets)
+ if page_errors:
+ failures.append(f"page errors observed: {page_errors}")
+
+ return {
+ "verdict": "fail" if failures else "pass",
+ "elapsed_s": round(time.monotonic() - started, 2),
+ "scenarios": scenarios,
+ "page_errors": page_errors,
+ "failures": failures,
+ }
+ finally:
+ await ui.stop()
+
+
+# The rest runs as its own process: python3 perf.py heap ... | python3 perf.py check ...
def classes(path: Path) -> dict[str, list[int]]:
@@ -284,8 +961,88 @@ def heap(paths: list[str], count: int = 40) -> None:
print(f"{size / 1e3:+10.0f} KB {n:+8d} {key[:100]}")
+def _seed_fresh_base(base: Path) -> Path:
+ import seed as seed_mod
+ from lifecycle_support import acquire_base
+
+ local_cli = seed_mod.ROOT / "cli/bin/albedo"
+ if not local_cli.is_file():
+ print("cli build", flush=True)
+ seed_mod.sh(
+ *seed_mod.dev_argv(
+ "go", "-C", "cli", "build", "-o", "bin/albedo", "./cmd/albedo"
+ ),
+ cwd=seed_mod.ROOT,
+ )
+ resolved = base.resolve()
+ with acquire_base(resolved, exclusive=True):
+ active = list((resolved / "runs").glob("*/.active"))
+ if active:
+ raise RuntimeError(f"unfinished review runs prevent reseeding: {active}")
+ seed_mod.seed(resolved)
+ return resolved / "dist"
+
+
+def _run_check_cli(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(
+ prog="perf.py check",
+ description="Run count-based web performance and wheel-scroll checks.",
+ )
+ parser.add_argument("--base", type=Path, default=None, help="Seeded ALBEDO_UX base")
+ parser.add_argument(
+ "--dist",
+ type=Path,
+ default=None,
+ help="Prebuilt web dist (default: build this checkout into a temp dir)",
+ )
+ parser.add_argument(
+ "--seed",
+ action="store_true",
+ help="Build CLI if needed and seed --base (or $ALBEDO_UX) before checking",
+ )
+ parser.add_argument("--idle-seconds", type=float, default=2.0)
+ parser.add_argument("--out", type=Path, default=None, help="Write JSON report")
+ args = parser.parse_args(argv)
+
+ here = str(Path(__file__).resolve().parent)
+ if here not in sys.path:
+ sys.path.insert(0, here)
+ dist = args.dist
+ if args.seed:
+ target_base = (
+ args.base
+ if args.base is not None
+ else Path(os.environ.get("ALBEDO_UX", "/tmp/albedo-review"))
+ )
+ seeded_dist = _seed_fresh_base(target_base)
+ if dist is None:
+ dist = seeded_dist
+ result = asyncio.run(
+ check(base=args.base, dist=dist, idle_seconds=args.idle_seconds)
+ )
+ if args.out is not None:
+ args.out.parent.mkdir(parents=True, exist_ok=True)
+ args.out.write_text(json.dumps(result, indent=2) + "\n")
+ for name, metrics_map in result["scenarios"].items():
+ summary = ", ".join(
+ f"{k}={v}" for k, v in metrics_map.items() if k != "animations"
+ )
+ print(f" {name:20s} {summary}")
+ if result["failures"]:
+ print(f"FAIL web perf check ({result['elapsed_s']}s):", file=sys.stderr)
+ for line in result["failures"]:
+ print(f" - {line}", file=sys.stderr)
+ return 1
+ print(f"PASS web perf check ({result['elapsed_s']}s)")
+ return 0
+
+
if __name__ == "__main__":
if len(sys.argv) in (3, 4) and sys.argv[1] == "heap":
heap(sys.argv[2:])
+ elif len(sys.argv) >= 2 and sys.argv[1] == "check":
+ raise SystemExit(_run_check_cli(sys.argv[2:]))
else:
- raise SystemExit("usage: perf.py heap a.heapsnapshot [b.heapsnapshot]")
+ raise SystemExit(
+ "usage: perf.py heap a.heapsnapshot [b.heapsnapshot] | perf.py check [--base PATH] [--dist PATH] [--out PATH]"
+ )