Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

studiobench: the verdict tools, so a performance number can be shown to be real (#9297)

Daniel Han83539fa973f0
diff --git a/.github/workflows/studiobench-ci.yml b/.github/workflows/studiobench-ci.yml
index 82c0978ec93..d358bced0a3 100644
--- a/.github/workflows/studiobench-ci.yml
+++ b/.github/workflows/studiobench-ci.yml
@@ -262,8 +262,14 @@ jobs:
--out outputs/studiobench-ci
# THE GATE. Exits non-zero unless every scheduled action reports ran=true
- # with no missed slot, and refuses a payload with no cell rows rather than
- # passing over it vacuously.
+ # with no missed slot and a passing expect_ok, and refuses a payload with no
+ # cell rows rather than passing over it vacuously.
+ #
+ # expect_ok is in that list because ran is not did-what-it-claimed: an action
+ # whose own assertion failed keeps its timings, and the report already drops
+ # them as "must not be quoted". If the gate did not read it, a selector
+ # regression that fails every cell's assertion would leave this job green with
+ # the surface no longer functional, since --report exits 0 after excluding it.
#
# `image_upload` is excused, and it is the only one. It reports NOT RUN on
# every cell of every 100K run measured, always with the same evidence: the
diff --git a/tests/studio/studiobench/CONTRIBUTING-perf.md b/tests/studio/studiobench/CONTRIBUTING-perf.md
index b4d601c9635..93c55d45503 100644
--- a/tests/studio/studiobench/CONTRIBUTING-perf.md
+++ b/tests/studio/studiobench/CONTRIBUTING-perf.md
@@ -11,20 +11,60 @@ answer was produced by not having it.
## The loop
```
-1. Screen python -m tests.studio.studiobench --tier fast ~5 min, direction only
-2. Confirm python -m tests.studio.studiobench --tier standard --reps 4 ~1 h, ~2 h for an A/B
-3. Gate per-metric floor, sign consistency, stability
-4. Parity prove you did not change what is rendered
-5. Read python -m tests.studio.studiobench --report <out>/payload.jsonl --tier standard
+# 1. Screen: about 5 minutes, direction only
+python -m tests.studio.studiobench --tier fast --ab YOUR_REF --out outputs/screen
+
+# 2. Confirm: about 1 hour, and about 2 hours for an A/B. A NEW --out: the payload is
+# append-only, so writing a standard run into the screen's directory leaves one file
+# holding two films.
+python -m tests.studio.studiobench --tier standard --reps 4 --ab YOUR_REF --out outputs/mine
+
+# ... and the same film with BOTH arms on the base, as your null control. --ab sets the
+# TREATMENT ref only; --branch is the base arm and defaults to main, so passing --ab BASE_REF
+# alone measures main against BASE_REF and calls the difference noise.
+python -m tests.studio.studiobench --tier standard --reps 4 \
+ --branch BASE_REF --ab BASE_REF --out outputs/null
+
+# ... and, before you read any timing at all, that the runs actually ran. Here rather than at
+# the end: floor_table DROPS a repetition whose action did not run instead of refusing it, so
+# a missed slot leaves the paired table quietly and the repetitions that survive print as a
+# clean win on a smaller n.
+python -m tests.studio.studiobench --assert-liveness outputs/mine/payload.jsonl
+
+# ... BOTH payloads. The null control is the one people forget, and a hole there is worse: the
+# floor is max(|null delta|, null spread) over the repetitions that SURVIVED pairing, so a
+# slot the null run missed drops its noisiest repetition and tightens the bar your result is
+# then measured against. Your own payload passes this gate while it happens.
+python -m tests.studio.studiobench --assert-liveness outputs/null/payload.jsonl
+
+# 3. Gate: per-metric floor, sign consistency, stability
+python -m tests.studio.studiobench.sweep.floor_table --floor outputs/null outputs/mine
+
+# 4. Parity: prove you did not change what is rendered
+python -m tests.studio.studiobench.sweep.ui_parity --null outputs/null outputs/mine
+
+# 5. Read the payload back as a scored report. No Studio, no browser, no network.
+python -m tests.studio.studiobench --report outputs/mine/payload.jsonl --tier standard
```
-Every step above except the last drives a real Studio and therefore needs credentials. The
-commands are written short here; see **"You need a Studio, and you need its password"** in
-[README.md](README.md) before you run the first one, because a missing `--password` fails as an
-HTTP 401 only after the browser has started, and `--doctor` reports PASS on that configuration.
-Step 5 needs neither Studio nor network.
-
-Steps 3 and 4 are not optional extras. A number that has not cleared them is not evidence.
+The three commands in steps 1 and 2 drive a real Studio and therefore need credentials. The rest
+read a payload that already exists: `--assert-liveness`, `floor_table`, `ui_parity` and `--report`
+run offline, with no Studio, no browser and no network.
+See **"You need a Studio, and you need its password"** in [README.md](README.md) before you
+run the first one: a missing `--password` fails as an HTTP 401 only after the browser has
+already started, and `--doctor` reports PASS on that exact configuration. If you drive the wave
+against Studios you started yourself rather than letting studiobench install them, `--ab` needs
+`--attach` **and** `--attach-b`, one URL per arm, or it exits before measuring anything.
+
+`--assert-liveness` is strict on purpose and an action that could not run is a real finding, not
+noise. But two of the eighteen are unreachable on a fixture that loads no model (`image_upload`
+has no attachments button, `message_menu` no More button), and a small tier can leave others with
+nothing to act on. Read the reasons it prints before you reach for `--allow-not-run`, and name
+only the actions you have understood.
+
+Steps 3 and 4 are not optional extras. A number that has not cleared them is not evidence, and
+`floor_table` will tell you so: run without `--floor` and it prints the deltas followed by a
+refusal to call any of them a result.
## 1. Screen on the fast tier
@@ -57,7 +97,7 @@ A result must clear all three. Failing any one makes it **void**, not "a small w
You need a **null control**: the same build against itself, base versus base, producing a delta that
you know is exactly zero in truth. Whatever it reports is your noise.
-Two rules about it, both learned the hard way:
+Three rules about it, all learned the hard way:
- **The floor is per metric, not global.** A single global floor derived from the frame tail says
nothing about whether `settings.open_ms` can resolve 5%. Each metric gets its own floor from the
@@ -66,6 +106,12 @@ Two rules about it, both learned the hard way:
A floor measured on a quiet machine does not transfer to a busy one. Session-to-session drift on
this metric set is about 8%, which is larger than most real effects, so a floor from yesterday's
run is not a floor.
+- **A hole in the null control tightens the floor**, so the null gets `--assert-liveness` too. The
+ floor is computed from the repetitions that survived pairing, and the repetition a null run drops
+ is the one that was slow enough to miss a slot, which is the noisiest one it had. Four null
+ repetitions reading 1.000, 1.002, 0.999 and 1.300 set a 30.1% floor on
+ `message_menu.open_close_ms` and void a 10% result; lose the fourth to a missed slot and the same
+ three survivors set a 0.3% floor and the same 10% prints as `faster`.
The floor for a metric is `max(|null delta|, spread)`. The null control's own systematic bias has to
be cleared as well as its scatter.
@@ -98,6 +144,29 @@ parity-clean and still visibly wrong. **If you touched CSS, take screenshots as
`NOT EXERCISED` is not a pass. An action that never ran is not evidence that it is stable.
+### The digest cannot judge a change that alters the DOM on purpose
+
+Virtualization, windowing and progressive mount all change what is mounted by design, so the digest
+reports differences everywhere and proves nothing. For those changes parity means screenshots at
+matched scroll positions plus the behavioural invariants below.
+
+## 5. Invariant counts: the metrics whose sign means the opposite
+
+Rows named `action.count.key` are correctness invariants, not timings, and the table scores them
+with the same paired arithmetic and the opposite sign. A timing falling is the result a change is
+trying to produce. A count falling is a regression, and a count is often the only thing that can see
+it.
+
+`select_all_copy.count.selected_chars` is the case this exists for. The selection is taken over the
+viewport's DOM, and the action's own assertion is only that the character count is above zero, so
+anything that stops mounting the whole thread truncates the clipboard from roughly 400,000
+characters to a few thousand while every timing improves and the action still reports `expect_ok`.
+Scored as a timing that reads `faster`; scored as an invariant it reads `LOST (invariant fell)`.
+
+The comparison is against the other arm rather than an absolute threshold, so no per-rung
+calibration is needed: both arms seed a byte-identical thread. A count on an action that did not run
+is dropped like any other reading from an action that did not run.
+
## Before you trust any number at all
### Check that the thing you measured actually ran
diff --git a/tests/studio/studiobench/__main__.py b/tests/studio/studiobench/__main__.py
index d615dc48938..7382d629e90 100644
--- a/tests/studio/studiobench/__main__.py
+++ b/tests/studio/studiobench/__main__.py
@@ -1698,7 +1698,7 @@ def report_only(args) -> int:
def assert_liveness(args) -> int:
- """Fail unless every scheduled action in a payload actually ran.
+ """Fail unless every scheduled action in a payload ran, kept its slot and proved its effect.
THE FAILURE THIS CATCHES. The most expensive wrong answers this harness has produced were not
wrong numbers, they were absent ones reported as "no effect": four scene actions recorded NOT
@@ -1768,12 +1768,36 @@ def assert_liveness(args) -> int:
problems.append(f"{where}: the cell did not complete")
for action in row.get("actions") or []:
name = action.get("action") or action.get("name") or "?"
- if name in allowed:
- continue
- if not action.get("ran"):
- problems.append(f"{where}: {name} NOT RUN ({action.get('reason') or 'no reason'})")
- elif action.get("slot_missed"):
+ if action.get("slot_missed"):
+ # A MISSED SLOT IS NOT AN ACTION THE PLATFORM CANNOT PERFORM, so it is checked
+ # before the allowance rather than inside it. `scene/schedule.py` records an
+ # overrun as `ran = False, slot_missed = True`, so a listed name reached the
+ # not-ran branch and inherited an excuse written for a different failure: the
+ # machine was too slow to reach a window it could otherwise have used. That is
+ # the scheduling regression this gate is for, and on the only allowance the repo
+ # actually ships it would have been the difference between a timed benchmark and
+ # an untimed one.
problems.append(f"{where}: {name} missed its slot")
+ elif not action.get("ran"):
+ # THE ALLOWANCE IS EXACTLY WHAT ITS NAME SAYS. `--allow-not-run` excuses an action
+ # the fixture cannot mount at all; it is not a blanket exemption from the gate.
+ # `image_upload` is listed in studiobench-ci.yml only because the fixture cannot
+ # mount it, so if it ever does mount, an upload that produces no attachment must
+ # be a failure rather than an excuse inherited from a different reason.
+ if name in allowed:
+ continue
+ problems.append(f"{where}: {name} NOT RUN ({action.get('reason') or 'no reason'})")
+ elif action.get("expect_ok") is False:
+ # RAN IS NOT DID WHAT IT CLAIMED. `scoring/from_payload.py` and
+ # `report/payload.py` both already refuse a timing whose own assertion failed;
+ # this loop did not, so `ran = True` with `expect_ok = False` fell past both
+ # branches above and the gate exited 0. A selector regression that fails EVERY
+ # cell's assertion left the workflow green with the surface non-functional --
+ # the same "absent reported as no effect" this gate exists for, one branch over.
+ problems.append(
+ f"{where}: {name} ran but its own assertion failed "
+ f"({action.get('reason') or 'no reason'})"
+ )
if cells == 0:
# An empty payload passing every check is the same false negative in a different costume.
@@ -1841,16 +1865,18 @@ def parse_args(argv: list):
metavar = "PAYLOAD",
dest = "assert_liveness",
help = "exit non-zero unless every scheduled action in an existing "
- "payload.jsonl actually ran. Offline. This is the gate that catches an "
- "action which never fired reporting as 'no effect'",
+ "payload.jsonl actually ran, kept its slot and passed its own assertion. "
+ "Offline. This is the gate that catches an action which never fired, or "
+ "never did what it claimed, reporting as 'no effect'",
)
ap.add_argument(
"--allow-not-run",
metavar = "ACTIONS",
dest = "allow_not_run",
- help = "comma-separated action names --assert-liveness may excuse. Use only "
- "for an action a platform genuinely cannot perform, and say which in "
- "the pull request: every name here is a hole in the gate",
+ help = "comma-separated action names --assert-liveness may excuse for NOT RUNNING "
+ "only. A listed action that does run is still held to its slot and its own "
+ "assertion. Use only for an action a platform genuinely cannot perform, and say "
+ "which in the pull request: every name here is a hole in the gate",
)
ap.add_argument("--rungs", help = "comma-separated rung override, e.g. 1K,10K")
ap.add_argument("--reps", type = int, default = 1)
diff --git a/tests/studio/studiobench/report/render.py b/tests/studio/studiobench/report/render.py
index 7afb3492f70..fa8da31048a 100644
--- a/tests/studio/studiobench/report/render.py
+++ b/tests/studio/studiobench/report/render.py
@@ -275,6 +275,22 @@ def render_ab_table(result: AbResult) -> str:
f"({abs(1.0 - result.headline_ratio) * 100:.1f}% {direction}, weighted)"
)
lines.append(f"VERDICT: {result.verdict}")
+ unresolved = [m for m in result.metrics if m.withheld]
+ if unresolved:
+ lines.append("")
+ lines.append(
+ "These metrics cleared the noise floor without a 95% CI that clears 1.0, either "
+ "because the interval contains it or because there were too few pairs to compute "
+ "one, so no direction is claimed for them. They are excluded from the headline "
+ "ratio above, which would otherwise quote their size as a measured win:"
+ )
+ for metric in unresolved:
+ why = (
+ f"ci95 {metric.ci_low:.3f}-{metric.ci_high:.3f} contains 1.0"
+ if metric.ci_low is not None and metric.ci_high is not None
+ else f"no ci95 from {metric.n_pairs} usable pair(s)"
+ )
+ lines.append(f" {metric.metric_key}: ratio {metric.ratio_geomean:.3f}, {why}")
if result.regressions:
lines.append("")
lines.append(
diff --git a/tests/studio/studiobench/report/selftest/test_studiobench_ab_report_resume.py b/tests/studio/studiobench/report/selftest/test_studiobench_ab_report_resume.py
index e0084938f45..e45b170246e 100644
--- a/tests/studio/studiobench/report/selftest/test_studiobench_ab_report_resume.py
+++ b/tests/studio/studiobench/report/selftest/test_studiobench_ab_report_resume.py
@@ -71,7 +71,10 @@ def test_a_fully_resumed_ab_keeps_the_table_the_measured_run_wrote(tmp_path):
_render_ab(paths, SIDES, MEASURED, "c0ffee")
measured = (paths.out / "ab.md").read_text(encoding = "utf-8")
- assert "IMPROVED" in measured
+ # A real reading, as opposed to an empty table. The fixture is one pair, so the verdict is
+ # INCONCLUSIVE rather than a direction; what matters here is that something was measured.
+ assert "NO READING" not in measured
+ assert "keystroke_p95_ms" in measured
# The resumed run: same output directory, new session id, not one cell of its own.
_render_ab(paths, SIDES, RESUMED, "c0ffee")
@@ -87,7 +90,8 @@ def test_a_run_that_measured_still_rewrites_the_table(tmp_path):
_render_ab(paths, SIDES, MEASURED, "c0ffee")
text = (paths.out / "ab.md").read_text(encoding = "utf-8")
assert "stale table" not in text
- assert "IMPROVED" in text
+ assert "NO READING" not in text
+ assert "keystroke_p95_ms" in text
def test_a_first_run_with_no_readings_still_gets_a_table(tmp_path):
diff --git a/tests/studio/studiobench/report/selftest/test_studiobench_liveness.py b/tests/studio/studiobench/report/selftest/test_studiobench_liveness.py
index 6665a5cb1e1..4a29162dc69 100644
--- a/tests/studio/studiobench/report/selftest/test_studiobench_liveness.py
+++ b/tests/studio/studiobench/report/selftest/test_studiobench_liveness.py
@@ -67,6 +67,54 @@ def test_a_missed_slot_fails_even_though_the_action_ran(tmp_path):
assert main(["--assert-liveness", str(path)]) == 1
+def test_an_action_whose_own_assertion_failed_fails(tmp_path):
+ """RAN IS NOT DID WHAT IT CLAIMED, and this gate is the machine that checks it.
+
+ `scoring/from_payload.py` refuses to score a timing whose `expect_ok` is False and
+ `report/payload.py` lists the cell under EXCLUDED CELLS saying its timings "must not be
+ quoted". Read raw, this gate agreed with neither: `ran = True, expect_ok = False` reached
+ neither the NOT RUN branch nor the missed-slot branch, so the CI liveness job exited 0 and
+ the report that dropped every excluded number exited 0 as well. A selector regression that
+ fails EVERY cell's assertion is precisely the "absent read as no effect" failure this gate
+ exists for.
+ """
+
+ path = write_payload(
+ tmp_path,
+ [
+ cell(
+ [
+ ran("keystroke"),
+ ran(
+ "message_menu",
+ expect_ok = False,
+ reason = "the menu opened with no items",
+ timings = {"open_ms": 31.0},
+ ),
+ ]
+ )
+ ],
+ )
+ assert main(["--assert-liveness", str(path)]) == 1
+
+
+def test_an_action_that_passed_its_assertion_still_passes(tmp_path):
+ # The pair for the test above: `expect_ok = True` is the healthy recording, and a gate that
+ # failed on it would be unusable rather than strict.
+ path = write_payload(tmp_path, [cell([ran("keystroke", expect_ok = True)])])
+ assert main(["--assert-liveness", str(path)]) == 0
+
+
+def test_an_unattempted_action_reports_not_run_rather_than_its_assertion(tmp_path):
+ # `ActionResult.__post_init__` forces `expect_ok = None` when `ran` is False, so the two
+ # failures never blur: the reader is told the action never happened, not that it misbehaved.
+ path = write_payload(
+ tmp_path,
+ [cell([{"action": "message_menu", "ran": False, "expect_ok": None, "reason": "no slot"}])],
+ )
+ assert main(["--assert-liveness", str(path)]) == 1
+
+
def test_an_incomplete_cell_fails(tmp_path):
path = write_payload(tmp_path, [cell([ran("keystroke")], completed = False)])
assert main(["--assert-liveness", str(path)]) == 1
@@ -285,3 +333,75 @@ def test_a_run_killed_during_a_later_cell_does_not_pass_on_its_earlier_ones(tmp_
],
)
assert main(["--assert-liveness", str(path)]) == 1
+
+
+def test_an_allowed_action_that_ran_and_failed_its_assertion_still_fails(tmp_path):
+ """`--allow-not-run` excuses NOT RUNNING, not everything the gate checks.
+
+ The allow-list skip used to sit above all three branches, so a listed name was exempt from
+ the gate entirely. `image_upload` is listed in studiobench-ci.yml only because the fixture
+ cannot mount an upload; the day it does mount, an upload that produces no attachment has to
+ be a failure rather than an excuse inherited from a different reason.
+ """
+
+ path = write_payload(
+ tmp_path,
+ [cell([ran("image_upload", expect_ok = False, reason = "no attachment appeared")])],
+ )
+ assert main(["--assert-liveness", str(path), "--allow-not-run", "image_upload"]) == 1
+
+
+def test_an_allowed_action_that_did_not_run_is_still_excused(tmp_path):
+ """The pair: scoping the allowance must not break what it is actually for."""
+
+ path = write_payload(
+ tmp_path,
+ [
+ cell(
+ [
+ {
+ "action": "image_upload",
+ "ran": False,
+ "reason": "fixture cannot mount an upload",
+ }
+ ]
+ )
+ ],
+ )
+ assert main(["--assert-liveness", str(path), "--allow-not-run", "image_upload"]) == 0
+
+
+def test_an_allowed_action_that_ran_and_missed_its_slot_still_fails(tmp_path):
+ """A listed name that ran is still held to its slot, for the same reason."""
+
+ path = write_payload(tmp_path, [cell([ran("image_upload", slot_missed = True)])])
+ assert main(["--assert-liveness", str(path), "--allow-not-run", "image_upload"]) == 1
+
+
+def test_a_missed_slot_is_not_excused_by_a_not_run_allowance(tmp_path):
+ """`--allow-not-run` excuses an action the platform cannot perform, not one it was late for.
+
+ `scene/schedule.py` records an overrun as `ran = False, slot_missed = True`, so checking the
+ allowance first let a listed name inherit an excuse written for a different failure. The
+ action could have been performed; the machine was too slow to reach the window. On
+ `image_upload`, the only allowance this repo ships, that is the difference between a timed
+ benchmark and an untimed one, and the help text already promises a listed action is still
+ held to its slot.
+ """
+
+ path = write_payload(
+ tmp_path,
+ [
+ cell(
+ [
+ {
+ "action": "image_upload",
+ "ran": False,
+ "slot_missed": True,
+ "reason": "the slot opened at 1000ms and this machine reached it at 2000ms",
+ }
+ ]
+ )
+ ],
+ )
+ assert main(["--assert-liveness", str(path), "--allow-not-run", "image_upload"]) == 1
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_failed_cell_verdict.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_failed_cell_verdict.py
index 54b12418896..3f768f87b83 100644
--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_failed_cell_verdict.py
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_failed_cell_verdict.py
@@ -118,13 +118,22 @@ def test_the_same_payload_complete_is_the_fail_the_omission_erased(tmp_path):
def test_the_unguarded_render_is_the_wrong_verdict(tmp_path):
- """What the guard is for, through the same path: without the plan, the surviving 100K pair is
- published as a 20% win over a payload whose measured 10K pair is a 100% regression."""
+ """What the guard is for, through the same path: without the plan, the surviving 100K pair
+ stands in for a payload whose measured 10K pair is a 100% regression.
+
+ The 20% win this used to publish is now withheld on its own, because one pair carries no
+ bootstrap CI and no direction is claimed without one. The guard is still what this test is
+ about: unguarded, nothing names the failed cell and the regression is simply absent, whereas
+ the guarded render VOIDs the run and says which cell died.
+ """
table = _table(tmp_path, failed = "r10K.base.rep0", planned_known = False)
- assert "VERDICT: IMPROVED" in table
- assert "20.0% faster" in table
+ assert "VERDICT: INCONCLUSIVE" in table
+ assert "20.0% faster" not in table
+ # The failure the guard exists to catch: unguarded, the dead cell is never mentioned.
+ assert "VOID" not in table
+ assert "r10K.base.rep0" not in table
def test_a_complete_plan_is_not_voided(tmp_path):
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_pair_resume.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_pair_resume.py
index 9ca31316762..8d20e329a53 100644
--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_pair_resume.py
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_pair_resume.py
@@ -188,7 +188,10 @@ def _resumed_table(tmp_path, *, pair_granular: bool) -> str:
def test_the_resumed_session_measures_both_arms_and_gets_a_table(tmp_path):
table = _resumed_table(tmp_path, pair_granular = True)
- assert "VERDICT: IMPROVED" in table
+ # Both arms measured, so the pair exists and the table has a reading. One pair carries no
+ # bootstrap CI, so the verdict is INCONCLUSIVE; the contrast with the test below, where the
+ # arms never pair at all and the table says NO READING, is the thing under test.
+ assert "VERDICT: INCONCLUSIVE" in table
assert "NO READING" not in table
@@ -262,7 +265,10 @@ def test_skipping_the_recorded_pair_publishes_a_verdict_over_the_remainder(tmp_p
table = _two_rung_resumed_table(tmp_path, whole_table = False)
assert "keystroke_p95_ms 1" in table, table
- assert "VERDICT: IMPROVED" in table, table
+ # The remainder is a single pair, so it can no longer be published as a direction; the bug
+ # this documents is unchanged and is the two assertions around this one: the 30% regression
+ # is gone from the table and nothing names the rung it came from.
+ assert "VERDICT: INCONCLUSIVE" in table, table
assert "10K" not in table
diff --git a/tests/studio/studiobench/runtime/types.py b/tests/studio/studiobench/runtime/types.py
index eb5ef140da4..d650d72317a 100644
--- a/tests/studio/studiobench/runtime/types.py
+++ b/tests/studio/studiobench/runtime/types.py
@@ -168,12 +168,34 @@ class ActionResult:
expect_ok: Optional[bool] = None
expect: dict = field(default_factory = dict)
timings: dict = field(default_factory = dict)
+ # CORRECTNESS INVARIANTS, not timings, and kept apart from them on purpose.
+ #
+ # A count here answers "did the action still do the whole job", where a timing answers "how
+ # long did it take". They are scored the same way and they mean opposite things when they
+ # move: a timing falling is the result, a count falling is a regression.
+ #
+ # This exists because `select_all_copy` asserted only `chars > 0`. Its selection is taken over
+ # the viewport's DOM, so any change that stops mounting the whole thread -- windowing,
+ # virtualization, a progressive mount that never widens -- truncates the clipboard silently
+ # and still passes. From a user's point of view a copy that drops most of the conversation is
+ # data loss, and it is the classic regression of every list that starts unmounting rows.
+ #
+ # The reference is the OTHER ARM rather than an absolute threshold. Both arms of an A/B seed a
+ # byte-identical thread, so a treatment that truncates reads as a large negative delta scored
+ # against the null control's own spread, and nothing has to be calibrated per rung or per
+ # platform. A count is therefore only meaningful in a paired comparison, which is the only
+ # place it is read.
+ counts: dict = field(default_factory = dict)
reason: Optional[str] = None
slot_missed: bool = False
def __post_init__(self) -> None:
if not self.ran:
self.timings = {}
+ # Same rule as `timings`, for the same reason: an action that did not happen has no
+ # invariant to report, and a zero left here would read as "the whole job was done, and
+ # it did nothing", which is the exact inversion of what happened.
+ self.counts = {}
self.expect_ok = None
if not self.reason:
self.reason = "action did not run and gave no reason"
@@ -190,6 +212,7 @@ class ActionResult:
"expect_ok": self.expect_ok,
"expect": self.expect,
"timings": self.timings,
+ "counts": self.counts,
"reason": self.reason,
"slot_missed": self.slot_missed,
}
diff --git a/tests/studio/studiobench/scene/actions.py b/tests/studio/studiobench/scene/actions.py
index 79f2e4d4389..28c96b916a9 100644
--- a/tests/studio/studiobench/scene/actions.py
+++ b/tests/studio/studiobench/scene/actions.py
@@ -946,6 +946,12 @@ def select_all_copy(ctx: ActionContext) -> ActionResult:
"copy_ms": round(copy_ms, 1),
"total_ms": round((time.monotonic() - started) * 1000, 1),
},
+ # `expect_ok` stays `chars > 0` deliberately. Within ONE run there is nothing to compare
+ # against: the selection is taken over the viewport's DOM, so if the DOM is windowed the
+ # selection and every DOM-derived reference shrink together and agree with each other.
+ # An absolute floor would need calibrating per rung and per platform, and would still be a
+ # guess. The count below is the real check, and it is paired against the other arm.
+ counts = {"selected_chars": raw["chars"]},
reason = None if ok else "select-all selected nothing",
)
diff --git a/tests/studio/studiobench/scoring/ab.py b/tests/studio/studiobench/scoring/ab.py
index b424ec2ad0d..5a997301c0d 100644
--- a/tests/studio/studiobench/scoring/ab.py
+++ b/tests/studio/studiobench/scoring/ab.py
@@ -20,6 +20,18 @@ A REGRESSION BEYOND THE NOISE FLOOR IS A FAIL REGARDLESS OF THE HEADLINE. A chan
the aggregate by 12% while tripling the worst frame is not a win, and a single headline number is
exactly the instrument that would let it ship. Every metric is checked individually.
+A POINT ESTIMATE PAST THE NOISE FLOOR IS NOT YET AN EFFECT. The noise floor answers "could this
+machine resolve a difference of this size at all", which is a question about the harness; it says
+nothing about whether these repetitions agree. Ratios of 0.7, 0.7, 1.2, 1.2 have a geometric mean
+of 0.917, clear of a 5% floor, and a bootstrap CI of 0.700-1.200 that contains 1.0: the pairs do
+not agree on the sign, and the honest reading is that nothing was resolved. So a direction is only
+claimed when the CI clears 1.0, and an interval that does not exist cannot clear it: below three
+usable pairs there is no bootstrap CI at all, and that reads as unresolved rather than as
+permission. The refusal is one-sided: an unresolved WIN is withheld from the headline, while an
+unresolved regression keeps both its FAIL and its place in the aggregate, where it can only pull
+the number toward worse. Withholding a win costs a headline; withholding a loss ships it. `sweep/floor_table.py` applies the same rule to its own pooled ratios under
+"VOID (pairs disagree on sign)".
+
FOUR REFUSALS. Rendering is refused outright when `bench_version`, `corpus_hash`, `rung_ladder_id`
or `weights_id` differ between the two sides. Each of those changes what the numbers mean, and a
table that prints them side by side is not a comparison, it is a category error with column
@@ -172,11 +184,50 @@ class MetricComparison:
ci_high: float | None
verdict: str = "no_reading"
beyond_noise: bool = False
+ #: The 95% CI of the paired geometric mean contains 1.0, so the data cannot rule out "no
+ #: effect" however far the point estimate landed from the noise floor. Carried so the table
+ #: can say the size is unresolved rather than print a direction as a finding.
+ ci_spans_no_effect: bool = False
#: At least one contributing pair had a sub-floor arm, so the ratio is a BOUND: the true
#: magnitude is larger. Carried so the table can say so rather than let a number derived from
#: an instrument floor be quoted as a measurement.
bounded: bool = False
+ @property
+ def ci_rules_out_no_effect(self) -> bool:
+ """An interval exists AND it lies entirely on one side of 1.0."""
+ if self.ci_low is None or self.ci_high is None:
+ return False
+ return not (self.ci_low <= 1.0 <= self.ci_high)
+
+ @property
+ def withheld(self) -> bool:
+ """An unresolved BETTER-side metric, whose magnitude is kept out of the headline.
+
+ Only the better side is withheld. An unresolved regression keeps contributing, where it
+ can only pull the aggregate toward worse; dropping it would make the headline read rosier
+ than the run actually was, which is the one direction this table must never round toward.
+ """
+ return self.verdict == "inconclusive"
+
+ @property
+ def unresolved(self) -> bool:
+ """Moved past the floor without an interval that rules out no effect.
+
+ Covers two cases, and the second is the one that failed open. An interval can straddle
+ 1.0, or there can be no interval at all: `bootstrap_geomean_ci` returns `(None, None)`
+ below three usable pairs, which a short ladder or a partially measured metric reaches
+ easily. A rule that claims a direction only when the CI clears 1.0 cannot be satisfied
+ by a CI that does not exist, so an absent one has to read as unresolved rather than as
+ permission. Two pairs at 0.5 used to print a 50% win with no interval behind it.
+ """
+ return self.beyond_noise and not self.ci_rules_out_no_effect
+
+ @property
+ def resolves_direction(self) -> bool:
+ """Cleared the floor AND its own CI, so this metric can speak for a headline."""
+ return self.verdict in ("improved", "regressed")
+
def to_json(self) -> dict[str, Any]:
return {
"metric_key": self.metric_key,
@@ -186,6 +237,7 @@ class MetricComparison:
"ci95": [self.ci_low, self.ci_high],
"verdict": self.verdict,
"beyond_noise": bool(self.beyond_noise),
+ "ci_spans_no_effect": bool(self.ci_spans_no_effect),
"bounded": bool(self.bounded),
}
@@ -252,7 +304,22 @@ class AbResult:
if self.regressions:
return "FAIL"
if self.headline_ratio is None:
+ # UNRESOLVED IS NOT UNMEASURED. `compare` keeps unresolved metrics out of the headline
+ # entirely, so a run whose every moving metric straddled 1.0 arrives here with no
+ # ratio at all. That is not the same as an empty payload: the data exists and says
+ # nothing, which is INCONCLUSIVE, while NO READING means there was nothing to read.
+ if any(m.unresolved for m in self.metrics):
+ return "INCONCLUSIVE"
return "NO READING"
+ # NO DIFFERENCE IS A CLAIM, AND A STRONGER ONE THAN THIS DATA SUPPORTS. Excluding an
+ # unresolved mover from the headline can leave only flat metrics behind, putting the
+ # aggregate back inside the noise floor. Reporting "no difference" there would assert the
+ # change did nothing, when in fact one metric moved and could not resolve its own sign.
+ # Only say that once some metric actually resolved a direction.
+ if any(m.unresolved for m in self.metrics) and not any(
+ m.resolves_direction for m in self.metrics
+ ):
+ return "INCONCLUSIVE"
if abs(self.headline_ratio - 1.0) * 100.0 <= self.noise_floor_pct:
return "NO DIFFERENCE"
return "IMPROVED" if self.headline_ratio < 1.0 else "REGRESSED"
@@ -333,18 +400,42 @@ def compare(
lower_is_better = anchor.lower_is_better if anchor else True
worse = delta_pct > 0 if lower_is_better else delta_pct < 0
comparison.beyond_noise = abs(delta_pct) > noise_floor_pct
+ comparison.ci_spans_no_effect = lo is not None and hi is not None and lo <= 1.0 <= hi
if not comparison.beyond_noise:
comparison.verdict = "within noise"
elif worse:
- comparison.verdict = "regressed"
+ # THE ASYMMETRY IS THE POINT, ON BOTH THE LABEL AND THE HEADLINE. Withholding an
+ # unresolved win costs a headline; withholding an unresolved loss ships the
+ # regression. So the worse side keeps counting and keeps contributing to the
+ # aggregate, where it can only drag the number toward worse, which is the
+ # conservative direction. A single bounded pair over a zero base is the case that
+ # proves it: `_divisible` exists because that regression once vanished from the
+ # table, the headline and this list at once, and it must not vanish again.
+ comparison.verdict = (
+ "regressed (unresolved)" if comparison.ci_spans_no_effect else "regressed"
+ )
+ unresolved = (
+ f"; 95% CI {lo:.3f}-{hi:.3f} spans no effect, so the size is unresolved"
+ if comparison.ci_spans_no_effect
+ else ""
+ )
result.regressions.append(
f"{metric_key}: {abs(delta_pct):.1f}% worse "
- f"(noise floor {noise_floor_pct:.1f}%)"
+ f"(noise floor {noise_floor_pct:.1f}%{unresolved})"
)
else:
- comparison.verdict = "improved"
- weight = anchor.weight if anchor else 1.0
- weighted_logs.append((weight, math.log(geo)))
+ comparison.verdict = "inconclusive" if comparison.unresolved else "improved"
+ # AN UNRESOLVED METRIC LENDS ITS MAGNITUDE TO NOTHING. The headline is a weighted
+ # geometric mean of point estimates and carries no interval of its own, so a metric
+ # that moved a long way but could not resolve its own sign would otherwise supply most
+ # of the number that gets quoted. keystroke_p95_ms at 0.2, 0.2, 1.5, 1.5 (geomean
+ # 0.548, CI 0.200-1.500) beside a resolved menu_open_ms of 0.900 produced a headline
+ # of 0.631 and the word IMPROVED: a quoted 36.9% win almost entirely made of data the
+ # table itself labels inconclusive. Metrics still within noise keep contributing --
+ # they pull the headline toward 1.0, which is the conservative direction.
+ if not comparison.withheld:
+ weight = anchor.weight if anchor else 1.0
+ weighted_logs.append((weight, math.log(geo)))
result.metrics.append(comparison)
if weighted_logs:
diff --git a/tests/studio/studiobench/scoring/selftest/test_studiobench_scoring.py b/tests/studio/studiobench/scoring/selftest/test_studiobench_scoring.py
index eb1bbce4ec6..58c8f8a9533 100644
--- a/tests/studio/studiobench/scoring/selftest/test_studiobench_scoring.py
+++ b/tests/studio/studiobench/scoring/selftest/test_studiobench_scoring.py
@@ -537,6 +537,104 @@ def test_bootstrap_ci_brackets_the_geometric_mean():
assert metric.ci_low <= metric.ratio_geomean <= metric.ci_high
+# ---------------------------------------------------------------------------------------
+# A CI that contains 1.0 is not a result: the pairs have to agree on the sign
+# ---------------------------------------------------------------------------------------
+#
+# The noise floor is a fact about the HARNESS -- whether a difference of this size is resolvable
+# here at all -- and it was the only gate a direction had to pass. Repetitions that disagree
+# produce a geometric mean well clear of the floor anyway: 0.7, 0.7, 1.2, 1.2 averages to 0.917
+# with a CI of 0.700-1.200, and the table said "improved" over it, in the one column anybody
+# quotes. The CI was computed, printed, and never consulted.
+
+
+def _split_pairs(metric: str, ratios: list[float]) -> list[Pair]:
+ """One metric, one ratio per rung, so the pairs can be made to disagree on the sign."""
+ out = []
+ for index, ratio in enumerate(ratios):
+ base = 100.0 + index
+ out.append(
+ Pair(
+ rung_tokens = 1_000 * (index + 1),
+ metric_key = metric,
+ base = Measure.read(base, "ms"),
+ treatment = Measure.read(base * ratio, "ms"),
+ )
+ )
+ return out
+
+
+def test_a_ci_that_spans_no_effect_is_not_an_improvement():
+ result = compare(
+ "treatment",
+ _split_pairs("keystroke_p95_ms", [0.7, 0.7, 1.2, 1.2]),
+ _identity(),
+ _identity(),
+ noise_floor_pct = 5.0,
+ )
+ metric = result.metrics[0]
+ assert metric.beyond_noise is True # 8.3% clear of a 5% floor
+ assert metric.ci_low <= 1.0 <= metric.ci_high
+ assert metric.ci_spans_no_effect is True
+ assert metric.verdict == "inconclusive"
+ # The headline has no interval of its own, so it is the line most likely to be quoted.
+ assert result.verdict == "INCONCLUSIVE"
+ assert result.regressions == []
+
+
+def test_a_ci_that_spans_no_effect_does_not_clear_a_regression():
+ """An unresolved regression is still a regression: the fail-safe direction is FAIL.
+
+ The mirror of the case above must NOT be symmetric. Refusing to claim a win costs a
+ contributor a headline; refusing to raise a fail lets the regression ship. So the metric is
+ labelled unresolved and still counted.
+ """
+ result = compare(
+ "treatment",
+ _split_pairs("keystroke_p95_ms", [1.4, 1.4, 0.9, 0.9]),
+ _identity(),
+ _identity(),
+ noise_floor_pct = 5.0,
+ )
+ metric = result.metrics[0]
+ assert metric.ci_spans_no_effect is True
+ assert metric.verdict == "regressed (unresolved)"
+ assert result.verdict == "FAIL"
+ assert any("unresolved" in r for r in result.regressions)
+
+
+def test_agreeing_pairs_still_carry_their_direction():
+ """The gate must not swallow a real effect: four ratios that agree keep their verdict."""
+ result = compare(
+ "treatment",
+ _split_pairs("keystroke_p95_ms", [0.70, 0.72, 0.68, 0.74]),
+ _identity(),
+ _identity(),
+ noise_floor_pct = 5.0,
+ )
+ metric = result.metrics[0]
+ assert metric.ci_spans_no_effect is False
+ assert metric.verdict == "improved"
+ assert result.verdict == "IMPROVED"
+
+
+def test_the_table_does_not_print_a_direction_it_could_not_resolve():
+ from studiobench.report.render import render_ab_table
+
+ result = compare(
+ "treatment",
+ _split_pairs("keystroke_p95_ms", [0.7, 0.7, 1.2, 1.2]),
+ _identity(),
+ _identity(),
+ noise_floor_pct = 5.0,
+ )
+ text = render_ab_table(result)
+ assert "VERDICT: INCONCLUSIVE" in text
+ assert "improved" not in text
+ assert "no direction is claimed" in text
+ assert "contains it" in text # the interval straddles 1.0, as opposed to being absent
+
+
# ---------------------------------------------------------------------------------------
# A measured zero is a reading: sub-floor arms bound the ratio rather than voiding the pair
# ---------------------------------------------------------------------------------------
@@ -691,3 +789,140 @@ def test_a_null_control_of_only_bounded_ratios_falls_back_to_the_declared_defaul
assert "declared default" in source
assert "under an instrument floor" in source
+
+
+def test_an_unresolved_metric_does_not_lend_its_magnitude_to_the_headline():
+ """A metric that cannot resolve its own sign must not supply the number that gets quoted.
+
+ The headline is a weighted geometric mean of point estimates with no interval of its own, so
+ an inconclusive metric that happened to move a long way used to dominate it. keystroke_p95_ms
+ at 0.2, 0.2, 1.5, 1.5 (geomean 0.548, CI 0.200-1.500) beside a resolved menu_open_ms of 0.900
+ produced a headline of 0.631 and the word IMPROVED: a quoted 36.9% win almost entirely made
+ of data the same table labels inconclusive.
+ """
+
+ pairs = _split_pairs("keystroke_p95_ms", [0.2, 0.2, 1.5, 1.5])
+ pairs += _split_pairs("menu_open_ms", [0.9, 0.9, 0.9, 0.9])
+ result = compare("treatment", pairs, _identity(), _identity(), noise_floor_pct = 5.0)
+
+ by_key = {m.metric_key: m for m in result.metrics}
+ assert by_key["keystroke_p95_ms"].verdict == "inconclusive"
+ assert by_key["menu_open_ms"].verdict == "improved"
+ # Only the resolved metric survives into the headline, so the quoted size is the real one.
+ assert result.headline_ratio == pytest.approx(0.9, abs = 1e-9)
+ assert result.verdict == "IMPROVED"
+
+
+def test_a_run_whose_every_moving_metric_is_unresolved_is_inconclusive_not_no_reading():
+ """Dropping unresolved metrics from the headline must not turn "says nothing" into "no data".
+
+ NO READING means there was nothing to read. This run measured fine and simply failed to
+ resolve a direction, which is a different answer and the one the operator has to act on.
+ """
+
+ pairs = _split_pairs("keystroke_p95_ms", [0.7, 0.7, 1.2, 1.2])
+ pairs += _split_pairs("menu_open_ms", [0.6, 0.6, 1.3, 1.3])
+ result = compare("treatment", pairs, _identity(), _identity(), noise_floor_pct = 5.0)
+
+ assert all(m.ci_spans_no_effect for m in result.metrics)
+ assert result.headline_ratio is None
+ assert result.verdict == "INCONCLUSIVE"
+
+
+def test_an_unresolved_mover_beside_a_flat_metric_is_not_no_difference():
+ """ "No difference" asserts the change did nothing, which is stronger than this data supports.
+
+ Dropping an unresolved mover from the headline can leave only flat metrics behind, putting the
+ aggregate back inside the noise floor. Reading that as NO DIFFERENCE would convert a refusal
+ to answer into a positive finding of no effect, when one metric did move and simply could not
+ resolve its own sign.
+ """
+
+ pairs = _split_pairs("keystroke_p95_ms", [0.7, 0.7, 1.2, 1.2])
+ pairs += _split_pairs("menu_open_ms", [1.0, 1.0, 1.0, 1.0])
+ result = compare("treatment", pairs, _identity(), _identity(), noise_floor_pct = 5.0)
+
+ by_key = {m.metric_key: m for m in result.metrics}
+ assert by_key["keystroke_p95_ms"].unresolved is True
+ assert by_key["menu_open_ms"].verdict == "within noise"
+ assert result.headline_ratio == pytest.approx(1.0, abs = 1e-9)
+ assert result.verdict == "INCONCLUSIVE"
+
+
+def test_an_unresolved_metric_never_clears_a_resolved_regression():
+ """A fail is never cleared by the exclusion: regressions are collected independently."""
+
+ pairs = _split_pairs("keystroke_p95_ms", [0.7, 0.7, 1.2, 1.2])
+ pairs += _split_pairs("menu_open_ms", [1.3, 1.3, 1.3, 1.3])
+ result = compare("treatment", pairs, _identity(), _identity(), noise_floor_pct = 5.0)
+
+ assert result.regressions
+ assert result.verdict == "FAIL"
+
+
+def test_a_metric_with_no_ci_at_all_does_not_claim_a_direction():
+ """An interval that does not exist cannot clear 1.0, so it must not read as permission.
+
+ `bootstrap_geomean_ci` returns (None, None) below three usable pairs, which a short ladder or
+ a partially measured metric reaches easily. The rule added here claims a direction only when
+ the CI clears no effect, and testing "does the interval contain 1.0" fails open when there is
+ no interval: two pairs at 0.5 printed a 50% win with nothing behind it.
+ """
+
+ result = compare(
+ "treatment",
+ _split_pairs("keystroke_p95_ms", [0.5, 0.5]),
+ _identity(),
+ _identity(),
+ noise_floor_pct = 5.0,
+ )
+ metric = result.metrics[0]
+ assert metric.n_pairs == 2
+ assert (metric.ci_low, metric.ci_high) == (None, None)
+ assert metric.beyond_noise is True
+ assert metric.ci_spans_no_effect is False # nothing to span
+ assert metric.unresolved is True
+ assert metric.verdict == "inconclusive"
+ assert result.headline_ratio is None
+ assert result.verdict == "INCONCLUSIVE"
+
+
+def test_a_regression_with_no_ci_is_still_a_regression_and_still_in_the_headline():
+ """The refusal is one-sided: a missing interval withholds a win, never a loss.
+
+ Withholding an unresolved win costs a headline; withholding an unresolved loss ships the
+ regression. So the worse side keeps its plain "regressed" label, its FAIL, and its place in
+ the aggregate, where it can only pull the number toward worse.
+ """
+
+ result = compare(
+ "treatment",
+ _split_pairs("keystroke_p95_ms", [1.5, 1.5]),
+ _identity(),
+ _identity(),
+ noise_floor_pct = 5.0,
+ )
+ metric = result.metrics[0]
+ assert (metric.ci_low, metric.ci_high) == (None, None)
+ assert metric.verdict == "regressed"
+ assert metric.withheld is False
+ assert result.headline_ratio == pytest.approx(1.5, abs = 1e-9)
+ assert result.regressions
+ assert result.verdict == "FAIL"
+
+
+def test_three_pairs_still_resolve_a_direction():
+ """The control: the threshold is three, so three agreeing pairs still read as a win."""
+
+ result = compare(
+ "treatment",
+ _split_pairs("keystroke_p95_ms", [0.5, 0.5, 0.5]),
+ _identity(),
+ _identity(),
+ noise_floor_pct = 5.0,
+ )
+ metric = result.metrics[0]
+ assert metric.ci_low is not None
+ assert metric.unresolved is False
+ assert metric.verdict == "improved"
+ assert result.verdict == "IMPROVED"
diff --git a/tests/studio/studiobench/sweep/__init__.py b/tests/studio/studiobench/sweep/__init__.py
new file mode 100644
index 00000000000..03e79b8dcb3
--- /dev/null
+++ b/tests/studio/studiobench/sweep/__init__.py
@@ -0,0 +1,12 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+"""Turning two studiobench payloads into a verdict.
+
+The benchmark answers "how long did this take". These answer the question that actually decides a
+pull request, which is "is that difference real". They are separate from `scoring/` because they
+operate on a PAIR of runs rather than on one, and separate from `report/` because a verdict needs
+something `report/` does not have: a null control to measure the floor against.
+
+ python -m tests.studio.studiobench.sweep.floor_table --floor outputs/null outputs/mine
+ python -m tests.studio.studiobench.sweep.ui_parity --null outputs/null outputs/mine
+"""
diff --git a/tests/studio/studiobench/sweep/floor_table.py b/tests/studio/studiobench/sweep/floor_table.py
new file mode 100644
index 00000000000..0dbbc122825
--- /dev/null
+++ b/tests/studio/studiobench/sweep/floor_table.py
@@ -0,0 +1,385 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+"""Per-metric detection floor, and the three gates a result has to clear to be quotable.
+
+ python -m tests.studio.studiobench.sweep.floor_table --floor OUT_NULL OUT_MINE
+
+WHY PER METRIC. The A/B renderer prints ONE floor, which is the right default for a headline and
+the wrong tool for deciding a pull request: a floor of 16.5% driven entirely by `jank_index` says
+nothing about whether `message_menu.open_close_ms` can resolve a 5% change. Every numeric timing on
+every action is harvested here and given its own floor, so a change is quoted against the floor of
+the metric it was written to move rather than against the worst metric in the run.
+
+WHY PAIRED BY REPETITION. The two arms of a repetition run adjacent in time, so pairing removes the
+session drift that pooling leaves in. The element census climbs monotonically through a session,
+and a pooled comparison charges that climb to whichever arm ran later.
+
+WHAT THE FLOOR IS. Run the SAME build against itself, base versus base, and whatever spread that
+produces is how far apart two identical builds land on this machine under this load. A difference
+smaller than it is not a small effect. It is an effect that cannot be distinguished from zero, and
+it prints as VOID rather than as a number.
+
+The floor must be measured in band, concurrently with the comparison it judges. Session-to-session
+drift on this metric set is about 8%, which is larger than most real effects, so a floor from a
+different session is not a floor.
+"""
+
+from __future__ import annotations
+
+import argparse
+import collections
+import json
+import statistics
+import sys
+from pathlib import Path
+
+if __package__ in (None, ""): # pragma: no cover
+ # Running the file directly rather than as a module. Supported because the first thing a new
+ # contributor does with a script is run it by path, and failing there with an import error is a
+ # bad first minute.
+ sys.path.insert(0, str(Path(__file__).resolve().parents[4]))
+
+from tests.studio.studiobench.scoring.from_payload import ( # noqa: E402
+ ACTION_SOURCES,
+ FRAME_METRICS,
+ IDLE_WINDOW_KINDS,
+ _actions_for,
+ _frame_measures,
+)
+
+METRICS = tuple(ACTION_SOURCES) + FRAME_METRICS
+
+
+def _action_timings(records: list[dict], cid: str) -> dict[str, float]:
+ """Every numeric timing on every action that RAN, as `action.timing`.
+
+ Only three action timings are wired into the scoring anchors, and those three do not cover what
+ most performance changes actually move: a menus change moves `message_menu`, a model-picker
+ change moves `model_change`, a re-open change moves `thread_reopen`, and neither of the latter
+ two is scored. Harvesting all of them is what lets each change be judged on its own metric.
+
+ `ran` is checked first. An action that did not happen has no timing worth pairing, and folding
+ its absence in as a fast number is the single most common way this harness has produced a
+ confident wrong answer.
+
+ AN ACTION WHOSE OWN ASSERTION FAILED IS TREATED THE SAME WAY. `report/payload.py` already
+ records `ran = True` with `expect_ok = False` as a note saying its timings "exist and must not
+ be quoted", and this is where they would be quoted. `keystroke` is the case: if half the
+ characters never reach the controlled component the action still ran, its p95 reads lower for
+ exactly that reason, and pairing it would print the failure as `faster`.
+ """
+ out: dict[str, float] = {}
+ for name, row in _actions_for(records, cid).items():
+ if not row.get("ran") or row.get("expect_ok") is False:
+ continue
+ for key, value in (row.get("timings") or {}).items():
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ out[f"{name}.{key}"] = float(value)
+ # Correctness invariants, harvested alongside the timings and named apart from them.
+ #
+ # Same paired arithmetic, opposite meaning. A timing falling is the result a change is
+ # trying to produce; a count falling is a regression, and one that no timing can reveal.
+ # `select_all_copy.count.selected_chars` is the case this exists for: the selection is
+ # taken over the viewport's DOM, so anything that stops mounting the whole thread
+ # truncates the clipboard while every timing improves and the action still reports
+ # `expect_ok`. Reading it against the other arm needs no calibration, because both arms
+ # seed a byte-identical thread.
+ for key, value in (row.get("counts") or {}).items():
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ out[f"{name}.count.{key}"] = float(value)
+ return out
+
+
+def cell_metrics(records: list[dict]) -> dict[str, dict[str, float]]:
+ """{cell_id: {metric: value}} for every COMPLETED cell in the payload.
+
+ SCOPED TO THE CELL'S OWN SESSION, not to its cell id. The payload is append-only and a cell id
+ is REUSED: `--resume` re-runs a cell that died, and a second run into the same output directory
+ repeats every id. Selecting on the id alone pools the dead attempt's windows with the retry's
+ and reports the average as the completed cell, which is a number nothing ever measured.
+
+ IDLE WINDOWS ARE EXCLUDED, exactly as `scoring/from_payload` excludes them. Every cell records a
+ 1.5 s `idle:calibrate` window with the frame recorder running, and pooling that quiet into the
+ frame metrics dilutes `time_in_jank_pct` and `jank_index` away from the film that was measured.
+ A metric here has to be the same quantity the rest of the tool calls by that name.
+ """
+ out: dict[str, dict[str, float]] = {}
+ for row in records:
+ if row.get("row_type") != "cell" or not row.get("completed"):
+ continue
+ cid = row["cell_id"]
+ sid = row.get("session_id")
+ own = [r for r in records if r.get("cell_id") == cid and r.get("session_id") == sid]
+ vals: dict[str, float] = _action_timings(own, cid)
+ windows = [
+ w
+ for w in own
+ if w.get("row_type") == "window" and str(w.get("kind") or "") not in IDLE_WINDOW_KINDS
+ ]
+ for key, m in _frame_measures(windows).items():
+ if m.value is not None:
+ vals[key] = float(m.value)
+ out[cid] = vals
+ return out
+
+
+def arm_of(cell_id: str) -> str:
+ return "treatment" if ".treatment." in cell_id else "base"
+
+
+def rep_of(cell_id: str) -> str:
+ return cell_id.rsplit(".", 1)[-1]
+
+
+def cell_sessions(records: list[dict]) -> dict[str, str]:
+ """{cell_id: session_id} for every COMPLETED cell, resolved the way `cell_metrics` resolves it.
+
+ Same last-writer-wins rule as `cell_metrics`, so the session reported here is the session whose
+ numbers that function returned. Anything else would pair a reading against a session it did not
+ come from, which is the thing the caller is trying to stop.
+ """
+ out: dict[str, str] = {}
+ for row in records:
+ if row.get("row_type") == "cell" and row.get("completed"):
+ out[row["cell_id"]] = str(row.get("session_id") or "")
+ return out
+
+
+def paired(records: list[dict], shard: str = "") -> dict[str, list[tuple[float, float]]]:
+ """{metric: [(base, treatment), ...]} matched on (shard, rung, repetition, session).
+
+ The shard is part of the key because sharding restarts the repetition counter: two independent
+ sessions both produce `rep0`, and pairing on the repetition alone would silently overwrite one
+ session's base with the other's. Pairing WITHIN a shard is also the correct thing to do, since
+ a pair only means anything when both arms come from the same session.
+
+ THE SESSION IS PART OF THE KEY FOR THE SAME REASON, and one shard is not one session. `--resume`
+ is the case: when one arm completed and its partner died, the resumed run skips the completed
+ arm and re-runs the dead one under a NEW session id, into the same shard directory. Keyed on the
+ repetition alone those two arms pair, and the ~8% session-to-session drift this file's header
+ measures is then charged in full to whichever arm was re-run. `scoring/ab.py` already refuses
+ that comparison outright; this is the same refusal in the place the sweep does its pairing.
+
+ A payload recorded before session ids existed has `""` on both arms and pairs exactly as before.
+ """
+ cells = cell_metrics(records)
+ sessions = cell_sessions(records)
+ by_key: dict[tuple[str, str, str, str], dict[str, dict[str, float]]] = collections.defaultdict(
+ dict
+ )
+ for cid, vals in cells.items():
+ rung = cid.split(".", 1)[0]
+ by_key[(shard, rung, rep_of(cid), sessions.get(cid, ""))][arm_of(cid)] = vals
+ out: dict[str, list[tuple[float, float]]] = collections.defaultdict(list)
+ for sides in by_key.values():
+ if "base" not in sides or "treatment" not in sides:
+ continue
+ for metric in set(sides["base"]) & set(sides["treatment"]):
+ b, t = sides["base"][metric], sides["treatment"][metric]
+ if b:
+ out[metric].append((b, t))
+ return out
+
+
+def tiers_of(records: list[dict]) -> set[str]:
+ """EVERY tier in one file, not the first.
+
+ One payload can hold more than one run: the recorder appends, so a second invocation into the
+ same output directory writes a second `run_meta` behind the first. Reading only the first is
+ what let a fast-tier film and a standard-tier film sit in one file and pass the refusal below.
+ """
+ return {str(r.get("tier") or "?") for r in records if r.get("row_type") == "run_meta"} or {"?"}
+
+
+def tier_of(records: list[dict]) -> str:
+ for r in records:
+ if r.get("row_type") == "run_meta":
+ return str(r.get("tier") or "?")
+ return "?"
+
+
+def read_rows(path: Path) -> list[dict]:
+ return [
+ json.loads(line) for line in path.read_text(encoding = "utf-8").splitlines() if line.strip()
+ ]
+
+
+def load(paths: list[Path]) -> tuple[dict[str, list[tuple[float, float]]], set[str]]:
+ """Pool paired ratios across every shard of one logical result, plus the tiers seen.
+
+ The tiers come back with the data because they gate whether pooling was legitimate at all: the
+ fast tier runs a 57 s film where the standard runs 243 s, so the same action is measured with
+ different amounts of thread settled around it. Two such payloads are two different measurements
+ of one quantity, not two samples of it.
+ """
+ pooled: dict[str, list[tuple[float, float]]] = collections.defaultdict(list)
+ tiers: set[str] = set()
+ for path in paths:
+ records = read_rows(path)
+ tiers |= tiers_of(records)
+ for metric, rows in paired(records, shard = str(path.parent.name)).items():
+ pooled[metric].extend(rows)
+ if len(tiers) > 1:
+ raise SystemExit(
+ f"refusing to pool payloads from different tiers: {sorted(tiers)}. A "
+ f"fast-tier film and a standard-tier film are different measurements of "
+ f"the same action, not repetitions of one."
+ )
+ return pooled, tiers
+
+
+def summarise(paths: list[Path]) -> dict[str, dict[str, float]]:
+ out: dict[str, dict[str, float]] = {}
+ pooled, _tiers = load(paths)
+ for metric, rows in pooled.items():
+ ratios = [t / b for b, t in rows]
+ out[metric] = {
+ "n": len(rows),
+ "base": statistics.fmean(b for b, _ in rows),
+ "treat": statistics.fmean(t for _, t in rows),
+ "delta_pct": (statistics.fmean(ratios) - 1.0) * 100.0,
+ # GATE 2. Do the pairs even agree on the SIGN? A metric whose four paired ratios
+ # straddle 1.0 has no direction, however far its mean happens to land from the floor.
+ # This is what separates "the change moved it" from "the metric is thrashing".
+ "consistent": all(r > 1.0 for r in ratios) or all(r < 1.0 for r in ratios),
+ # The spread of the paired ratios. From a null control it is the detection floor; from
+ # a real comparison it is the effect's own scatter, which is GATE 3.
+ "spread_pct": (max(ratios) - min(ratios)) * 100.0,
+ }
+ return out
+
+
+def verdict_for(
+ stat: dict,
+ floor: dict | None,
+ is_count: bool = False,
+) -> tuple[float | None, str]:
+ """The three gates, in the order that makes a failure most informative.
+
+ Gate 1, the per-metric floor, is `max(|null delta|, null spread)` rather than the spread alone.
+ In a null control several metrics show a systematic offset between the two arm LABELS with
+ identical builds behind them: `stop_generation.stop_ms` reads 6.6% faster on the treatment side,
+ tightly, across every repetition. Whatever causes it, arm B's page being created second inside
+ each repetition being the likely candidate, it is charged to the treatment arm in a real A/B
+ too. So the bar is the larger of the null control's own bias and its scatter.
+
+ Gate 3 is applied last because it is the one that most often surprises: an effect can clear the
+ floor on its mean while its own spread is an order of magnitude larger than the effect it
+ claims. Twelve rows in a 40-comparison audit passed gates 1 and 2 and were junk.
+ """
+ if floor is None:
+ return None, "no floor measured"
+ f = max(abs(floor["delta_pct"]), floor["spread_pct"])
+ if abs(stat["delta_pct"]) < f:
+ return f, "VOID (under floor)"
+ if not stat["consistent"]:
+ return f, "VOID (pairs disagree on sign)"
+ if stat["n"] > 1 and stat["spread_pct"] > abs(stat["delta_pct"]):
+ return f, "VOID (effect under its own scatter)"
+ if is_count:
+ # A count is an invariant, so the sign means the opposite of what it means for a timing.
+ # Less of the conversation copied is not an improvement, and calling it "faster" because
+ # the number went down is exactly the kind of misreading this table exists to prevent.
+ return f, ("LOST (invariant fell)" if stat["delta_pct"] < 0 else "gained")
+ return f, ("faster" if stat["delta_pct"] < 0 else "SLOWER")
+
+
+def is_count_metric(metric: str) -> bool:
+ """`action.count.key` is an invariant; `action.key` and the frame metrics are timings."""
+ return ".count." in metric
+
+
+def render(
+ paths: list[Path],
+ title: str,
+ floors: dict | None = None,
+ floor_tier: str | None = None,
+) -> int:
+ stats = summarise(paths)
+ tier = tier_of(read_rows(paths[0]))
+ if floor_tier is not None and floor_tier != tier:
+ raise SystemExit(
+ f"refusing to score a {tier}-tier payload against a {floor_tier}-tier "
+ f"floor: the two run different films, so their spreads are not the same "
+ f"quantity. Run a null control at --tier {tier}."
+ )
+ if tier == "fast":
+ print("\n NOTE: fast tier. These are directions for iteration, not reportable numbers.")
+ print(f"\n{title}")
+ print(f" payloads: {len(paths)} shard(s): {', '.join(p.parent.name for p in paths)}")
+ head = f" {'metric':<28}{'n':>3}{'base':>11}{'treat':>11}{'delta %':>10}{'spread %':>10}"
+ print(head + (" floor % verdict" if floors else ""))
+ print(" " + "-" * (len(head) + (26 if floors else 0)))
+ survivors = 0
+ for metric in sorted(stats, key = lambda m: (m in METRICS, m)):
+ s = stats[metric]
+ line = (
+ f" {metric:<28}{s['n']:>3}{s['base']:>11.1f}{s['treat']:>11.1f}"
+ f"{s['delta_pct']:>+10.1f}{s['spread_pct']:>10.1f}"
+ )
+ if floors is not None:
+ f, verdict = verdict_for(s, floors.get(metric), is_count_metric(metric))
+ line += (f"{'--':>13}" if f is None else f"{f:>13.1f}") + f" {verdict}"
+ if verdict in ("faster", "SLOWER", "LOST (invariant fell)", "gained"):
+ survivors += 1
+ print(line)
+ if floors is not None:
+ print(f"\n {survivors} metric(s) cleared all three gates.")
+ return survivors
+
+
+def shards_of(pattern: str) -> list[Path]:
+ """`outputs/sbench_mine*` to every shard's payload, in a stable order."""
+ root = Path(pattern).parent if "/" in pattern else Path(".")
+ stem = Path(pattern).name
+ found = sorted(p / "payload.jsonl" for p in root.glob(stem) if (p / "payload.jsonl").exists())
+ return found or ([Path(pattern)] if Path(pattern).exists() else [])
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser(
+ prog = "studiobench.sweep.floor_table",
+ description = "Per-metric detection floor and the three verdict gates.",
+ )
+ ap.add_argument(
+ "payloads",
+ nargs = "+",
+ help = "studiobench output directories or payload paths (globs allowed)",
+ )
+ ap.add_argument(
+ "--floor",
+ metavar = "OUTDIR",
+ help = "the null control (base vs base) whose spread sets the floor. Without "
+ "it this prints deltas and REFUSES to call any of them a result",
+ )
+ args = ap.parse_args(argv)
+
+ floors, floor_tier = None, None
+ if args.floor:
+ floor_paths = shards_of(args.floor)
+ if not floor_paths:
+ print(f"no null-control payload found for {args.floor}")
+ return 2
+ floors = summarise(floor_paths)
+ floor_tier = tier_of(read_rows(floor_paths[0]))
+
+ seen = 0
+ for arg in args.payloads:
+ paths = shards_of(arg)
+ if not paths:
+ print(f"\nno payload found for {arg}")
+ continue
+ seen += 1
+ render(paths, f"PAIRED PER-METRIC TABLE: {arg}", floors, floor_tier)
+ if not seen:
+ return 2
+ if floors is None:
+ print(
+ "\n NO FLOOR SUPPLIED. Nothing above is a result: without a null control there is "
+ "\n no way to tell any of these deltas from the noise of two identical builds."
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.py
new file mode 100644
index 00000000000..9a371396633
--- /dev/null
+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.py
@@ -0,0 +1,1191 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+"""The verdict gates, and the refusals that keep a number from being quoted when it should not be.
+
+Every gate here is paired: one test that a clean result passes it, one that a result which should
+fail it does. A gate that only ever passes is indistinguishable from no gate, and it is worse than
+no gate because it gets cited.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[4]))
+
+from tests.studio.studiobench.__main__ import main as cli_main # noqa: E402
+from tests.studio.studiobench.sweep import floor_table as F # noqa: E402
+from tests.studio.studiobench.sweep import ui_parity as U # noqa: E402
+
+
+# ── building a payload ───────────────────────────────────────────────
+
+
+def cell(rung: str, arm: str, rep: str, timings: dict[str, float]) -> list[dict]:
+ cid = f"{rung}.{arm}.{rep}"
+ return [
+ {"row_type": "cell", "cell_id": cid, "completed": True},
+ {
+ "row_type": "action",
+ "cell_id": cid,
+ "action": "message_menu",
+ "ran": True,
+ "timings": timings,
+ },
+ ]
+
+
+def payload(
+ tmp_path: Path,
+ name: str,
+ pairs: list[tuple[float, float]],
+ tier: str = "standard",
+) -> Path:
+ """One shard: `pairs[i]` is (base, treatment) for repetition i."""
+ out = tmp_path / name
+ out.mkdir(parents = True, exist_ok = True)
+ rows: list[dict] = [{"row_type": "run_meta", "tier": tier}]
+ for i, (base, treat) in enumerate(pairs):
+ rows += cell("100K", "base", f"rep{i}", {"open_close_ms": base})
+ rows += cell("100K", "treatment", f"rep{i}", {"open_close_ms": treat})
+ path = out / "payload.jsonl"
+ path.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding = "utf-8")
+ return path
+
+
+def verdict(
+ tmp_path,
+ result_pairs,
+ floor_pairs,
+ tier = "standard",
+) -> str:
+ result = F.summarise([payload(tmp_path, "result", result_pairs, tier)])
+ floor = F.summarise([payload(tmp_path, "null", floor_pairs, tier)])
+ _f, v = F.verdict_for(result["message_menu.open_close_ms"], floor["message_menu.open_close_ms"])
+ return v
+
+
+# ── gate 1: the per-metric floor ─────────────────────────────────────
+
+
+def test_a_large_consistent_effect_over_a_tight_floor_passes(tmp_path):
+ assert (
+ verdict(
+ tmp_path,
+ [(1000.0, 100.0), (1010.0, 101.0), (990.0, 99.0), (1000.0, 100.0)],
+ [(1000.0, 1000.0), (1010.0, 1012.0), (990.0, 989.0), (1000.0, 1001.0)],
+ )
+ == "faster"
+ )
+
+
+def test_an_effect_under_the_floor_is_void(tmp_path):
+ # 3% claimed, against a null control whose own two identical builds land 20% apart.
+ assert (
+ verdict(
+ tmp_path,
+ [(1000.0, 970.0), (1000.0, 970.0), (1000.0, 970.0), (1000.0, 970.0)],
+ [(1000.0, 900.0), (1000.0, 1100.0), (1000.0, 950.0), (1000.0, 1050.0)],
+ )
+ == "VOID (under floor)"
+ )
+
+
+def test_the_floor_clears_the_null_controls_bias_not_only_its_spread(tmp_path):
+ # A null control that is TIGHT but systematically offset: identical builds, yet the treatment
+ # label reads 10% faster on every repetition. Spread is nearly zero, so a floor built from
+ # spread alone would admit any effect at all. The bar is max(|bias|, spread).
+ floor_pairs = [(1000.0, 900.0)] * 4
+ assert verdict(tmp_path, [(1000.0, 950.0)] * 4, floor_pairs) == "VOID (under floor)"
+ assert verdict(tmp_path, [(1000.0, 700.0)] * 4, floor_pairs) == "faster"
+
+
+# ── gate 2: sign consistency ─────────────────────────────────────────
+
+
+def test_pairs_that_disagree_on_sign_are_void_however_large_the_mean(tmp_path):
+ # Mean lands well past the floor; two repetitions say faster and two say slower.
+ assert (
+ verdict(
+ tmp_path,
+ [(1000.0, 400.0), (1000.0, 1300.0), (1000.0, 300.0), (1000.0, 1200.0)],
+ [(1000.0, 1000.0)] * 4,
+ )
+ == "VOID (pairs disagree on sign)"
+ )
+
+
+# ── gate 3: the effect must exceed its own scatter ───────────────────
+
+
+def test_an_effect_smaller_than_its_own_scatter_is_void(tmp_path):
+ # Every repetition agrees on the direction and the mean clears the floor, but the readings
+ # range from 2% to 60% faster. Twelve rows in a 40-comparison audit looked exactly like this.
+ assert (
+ verdict(
+ tmp_path,
+ [(1000.0, 980.0), (1000.0, 400.0), (1000.0, 950.0), (1000.0, 500.0)],
+ [(1000.0, 1000.0)] * 4,
+ )
+ == "VOID (effect under its own scatter)"
+ )
+
+
+def test_gate_three_does_not_fire_on_a_tight_large_effect(tmp_path):
+ assert (
+ verdict(
+ tmp_path,
+ [(1000.0, 100.0), (1000.0, 102.0), (1000.0, 98.0), (1000.0, 101.0)],
+ [(1000.0, 1000.0)] * 4,
+ )
+ == "faster"
+ )
+
+
+def test_gate_three_cannot_fire_on_a_single_pair(tmp_path):
+ # With n=1 the spread is 0 by construction, so the gate has nothing to say. It must not
+ # silently pass a single reading off as having survived a scatter check.
+ result = F.summarise([payload(tmp_path, "result", [(1000.0, 500.0)])])
+ assert result["message_menu.open_close_ms"]["n"] == 1
+ _f, v = F.verdict_for(
+ result["message_menu.open_close_ms"], {"delta_pct": 0.0, "spread_pct": 1.0}
+ )
+ assert v == "faster"
+
+
+# ── correctness invariants, scored with the same arithmetic and the opposite sign ────
+
+
+def count_cell(cid: str, chars: float) -> list[dict]:
+ return [
+ {"row_type": "cell", "cell_id": cid, "completed": True},
+ {
+ "row_type": "action",
+ "cell_id": cid,
+ "action": "select_all_copy",
+ "ran": True,
+ "timings": {"copy_ms": 10.0},
+ "counts": {"selected_chars": chars},
+ },
+ ]
+
+
+def count_payload(tmp_path: Path, name: str, pairs: list[tuple[float, float]]) -> Path:
+ out = tmp_path / name
+ out.mkdir(parents = True, exist_ok = True)
+ rows: list[dict] = [{"row_type": "run_meta", "tier": "standard"}]
+ for i, (base, treat) in enumerate(pairs):
+ rows += count_cell(f"100K.base.rep{i}", base)
+ rows += count_cell(f"100K.treatment.rep{i}", treat)
+ path = out / "payload.jsonl"
+ path.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding = "utf-8")
+ return path
+
+
+COUNT_METRIC = "select_all_copy.count.selected_chars"
+
+
+def test_a_count_is_harvested_under_a_name_that_marks_it_as_an_invariant(tmp_path):
+ stats = F.summarise([count_payload(tmp_path, "r", [(400000.0, 400000.0)])])
+ assert COUNT_METRIC in stats
+ assert F.is_count_metric(COUNT_METRIC)
+ # The timing on the same action must stay a timing.
+ assert "select_all_copy.copy_ms" in stats
+ assert not F.is_count_metric("select_all_copy.copy_ms")
+
+
+def test_a_count_that_fell_reads_as_a_loss_and_never_as_faster(tmp_path):
+ # The regression this exists to catch: virtualization truncates select-all from 400k characters
+ # to 3k. Every timing improves, `expect_ok` stays true because chars > 0, and the only thing
+ # that can say so is this row. Scored as a timing it would read "faster".
+ stats = F.summarise([count_payload(tmp_path, "r", [(400000.0, 3000.0)] * 4)])
+ floor = {"delta_pct": 0.0, "spread_pct": 1.0}
+ _f, v = F.verdict_for(stats[COUNT_METRIC], floor, F.is_count_metric(COUNT_METRIC))
+ assert v == "LOST (invariant fell)"
+ # Same numbers, scored as a timing, would have been reported as an improvement.
+ assert F.verdict_for(stats[COUNT_METRIC], floor, False)[1] == "faster"
+
+
+def test_a_count_that_rose_is_reported_but_not_as_a_slowdown(tmp_path):
+ stats = F.summarise([count_payload(tmp_path, "r", [(3000.0, 400000.0)] * 4)])
+ _f, v = F.verdict_for(stats[COUNT_METRIC], {"delta_pct": 0.0, "spread_pct": 1.0}, is_count = True)
+ assert v == "gained"
+
+
+def test_an_unchanged_count_is_void_like_any_other_metric_under_the_floor(tmp_path):
+ stats = F.summarise([count_payload(tmp_path, "r", [(400000.0, 400000.0)] * 4)])
+ _f, v = F.verdict_for(stats[COUNT_METRIC], {"delta_pct": 0.0, "spread_pct": 1.0}, is_count = True)
+ assert v == "VOID (under floor)"
+
+
+def test_a_lost_invariant_is_printed_and_counted_by_the_table(tmp_path, capsys):
+ result = count_payload(tmp_path, "result", [(400000.0, 3000.0)] * 4)
+ floors = {COUNT_METRIC: {"delta_pct": 0.0, "spread_pct": 1.0}}
+ survivors = F.render([result], "t", floors = floors)
+ out = capsys.readouterr().out
+ assert "LOST (invariant fell)" in out
+ # It has to be counted as a finding, not dropped for not being one of the two timing verdicts.
+ assert survivors >= 1
+
+
+def test_a_count_on_an_action_that_did_not_run_contributes_nothing(tmp_path):
+ rows = [
+ {"row_type": "run_meta", "tier": "standard"},
+ {"row_type": "cell", "cell_id": "100K.base.rep0", "completed": True},
+ {
+ "row_type": "action",
+ "cell_id": "100K.base.rep0",
+ "action": "select_all_copy",
+ "ran": False,
+ "counts": {"selected_chars": 400000.0},
+ },
+ ]
+ out = tmp_path / "z"
+ out.mkdir()
+ (out / "payload.jsonl").write_text(
+ "".join(json.dumps(r) + "\n" for r in rows), encoding = "utf-8"
+ )
+ assert F._action_timings(F.read_rows(out / "payload.jsonl"), "100K.base.rep0") == {}
+
+
+def test_a_boolean_count_is_not_harvested_as_a_number(tmp_path):
+ # `True` is an int in Python, and a flag flipping is not a 100% regression.
+ rows = [
+ {"row_type": "run_meta", "tier": "standard"},
+ {"row_type": "cell", "cell_id": "100K.base.rep0", "completed": True},
+ {
+ "row_type": "action",
+ "cell_id": "100K.base.rep0",
+ "action": "select_all_copy",
+ "ran": True,
+ "counts": {"selected_chars": 12.0, "truncated": True},
+ },
+ ]
+ out = tmp_path / "w"
+ out.mkdir()
+ (out / "payload.jsonl").write_text(
+ "".join(json.dumps(r) + "\n" for r in rows), encoding = "utf-8"
+ )
+ harvested = F._action_timings(F.read_rows(out / "payload.jsonl"), "100K.base.rep0")
+ assert harvested == {"select_all_copy.count.selected_chars": 12.0}
+
+
+# ── refusals ─────────────────────────────────────────────────────────
+
+
+def test_no_floor_at_all_yields_no_verdict_rather_than_a_pass(tmp_path):
+ result = F.summarise([payload(tmp_path, "result", [(1000.0, 100.0)] * 4)])
+ _f, v = F.verdict_for(result["message_menu.open_close_ms"], None)
+ assert v == "no floor measured"
+
+
+def test_pooling_across_tiers_is_refused(tmp_path):
+ fast = payload(tmp_path, "fast", [(1000.0, 900.0)], tier = "fast")
+ standard = payload(tmp_path, "standard", [(1000.0, 900.0)], tier = "standard")
+ with pytest.raises(SystemExit) as exc:
+ F.load([fast, standard])
+ assert "different tiers" in str(exc.value)
+
+
+def test_scoring_against_a_floor_from_another_tier_is_refused(tmp_path):
+ result = payload(tmp_path, "result", [(1000.0, 100.0)] * 4, tier = "fast")
+ with pytest.raises(SystemExit) as exc:
+ F.render([result], "t", floors = {}, floor_tier = "standard")
+ assert "different films" in str(exc.value)
+
+
+def test_an_action_that_did_not_run_contributes_no_timing(tmp_path):
+ # The rule the whole harness turns on: an absent action is not a fast one.
+ rows = [
+ {"row_type": "run_meta", "tier": "standard"},
+ {"row_type": "cell", "cell_id": "100K.base.rep0", "completed": True},
+ {
+ "row_type": "action",
+ "cell_id": "100K.base.rep0",
+ "action": "message_menu",
+ "ran": False,
+ "timings": {"open_close_ms": 3.0},
+ },
+ ]
+ out = tmp_path / "x"
+ out.mkdir()
+ (out / "payload.jsonl").write_text(
+ "".join(json.dumps(r) + "\n" for r in rows), encoding = "utf-8"
+ )
+ records = F.read_rows(out / "payload.jsonl")
+ assert F._action_timings(records, "100K.base.rep0") == {}
+
+
+def test_an_incomplete_cell_is_not_measured(tmp_path):
+ rows = [
+ {"row_type": "run_meta", "tier": "standard"},
+ {"row_type": "cell", "cell_id": "100K.base.rep0", "completed": False},
+ {
+ "row_type": "action",
+ "cell_id": "100K.base.rep0",
+ "action": "message_menu",
+ "ran": True,
+ "timings": {"open_close_ms": 3.0},
+ },
+ ]
+ out = tmp_path / "y"
+ out.mkdir()
+ (out / "payload.jsonl").write_text(
+ "".join(json.dumps(r) + "\n" for r in rows), encoding = "utf-8"
+ )
+ assert F.cell_metrics(F.read_rows(out / "payload.jsonl")) == {}
+
+
+def test_a_shard_pairs_within_itself_and_never_across(tmp_path):
+ # Two shards both number their repetitions from rep0. Pairing on the repetition alone would
+ # cross them over and silently compare one session's base with another's treatment.
+ a = payload(tmp_path / "a", "s0", [(1000.0, 500.0)])
+ b = payload(tmp_path / "b", "s0", [(2000.0, 1000.0)])
+ pooled, _ = F.load([a, b])
+ rows = pooled["message_menu.open_close_ms"]
+ assert sorted(rows) == [(1000.0, 500.0), (2000.0, 1000.0)]
+
+
+def test_an_action_whose_own_assertion_failed_contributes_no_timing(tmp_path):
+ # `ran = True, expect_ok = False` is the action that happened and did not do its job. Its p95
+ # is lower BECAUSE it failed, so pairing it prints the failure as an improvement. The payload
+ # notes layer already says these timings must not be quoted.
+ rows = [
+ {"row_type": "run_meta", "tier": "standard"},
+ {"row_type": "cell", "cell_id": "100K.base.rep0", "completed": True},
+ {
+ "row_type": "action",
+ "cell_id": "100K.base.rep0",
+ "action": "keystroke",
+ "ran": True,
+ "expect_ok": False,
+ "timings": {"p95_ms": 3.0},
+ "counts": {"typed_chars": 4.0},
+ },
+ ]
+ out = tmp_path / "e"
+ out.mkdir()
+ (out / "payload.jsonl").write_text(
+ "".join(json.dumps(r) + "\n" for r in rows), encoding = "utf-8"
+ )
+ assert F._action_timings(F.read_rows(out / "payload.jsonl"), "100K.base.rep0") == {}
+
+
+def test_an_action_with_no_expectation_recorded_is_still_harvested(tmp_path):
+ # `expect_ok` is None on an action that asserts nothing, and on every payload recorded before
+ # the field existed. Only an explicit False is a failed assertion.
+ rows = [
+ {"row_type": "run_meta", "tier": "standard"},
+ {"row_type": "cell", "cell_id": "100K.base.rep0", "completed": True},
+ {
+ "row_type": "action",
+ "cell_id": "100K.base.rep0",
+ "action": "keystroke",
+ "ran": True,
+ "expect_ok": None,
+ "timings": {"p95_ms": 3.0},
+ },
+ ]
+ out = tmp_path / "n"
+ out.mkdir()
+ (out / "payload.jsonl").write_text(
+ "".join(json.dumps(r) + "\n" for r in rows), encoding = "utf-8"
+ )
+ assert F._action_timings(F.read_rows(out / "payload.jsonl"), "100K.base.rep0") == {
+ "keystroke.p95_ms": 3.0
+ }
+
+
+def write(tmp_path: Path, name: str, rows: list[dict]) -> Path:
+ out = tmp_path / name
+ out.mkdir(parents = True, exist_ok = True)
+ path = out / "payload.jsonl"
+ path.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding = "utf-8")
+ return path
+
+
+def frame_window(cid: str, kind: str, gaps: list[float], duration_ms: float, **extra) -> dict:
+ row = {
+ "row_type": "window",
+ "cell_id": cid,
+ "kind": kind,
+ "name": f"{kind}:w",
+ "duration_ms": duration_ms,
+ "instruments": {
+ "frames": {
+ "frames_attempted": True,
+ "frame_gaps_ms": gaps,
+ "max_frame_ms": max(gaps),
+ }
+ },
+ }
+ row.update(extra)
+ return row
+
+
+def test_the_enforced_idle_window_is_not_pooled_into_the_frame_metrics(tmp_path):
+ # Every cell records a 1.5 s `idle:calibrate` window with the frame recorder running. Pooling
+ # its quiet into the film halves the jank share, so the column would not be the quantity the
+ # rest of the tool prints under that name.
+ cid = "r100K.base.rep0"
+ rows = [
+ {"row_type": "run_meta", "tier": "standard"},
+ {"row_type": "cell", "cell_id": cid, "completed": True},
+ frame_window(cid, "action", [200.0] * 10, 2000.0),
+ frame_window(cid, "idle", [16.0] * 94, 1500.0),
+ ]
+ vals = F.cell_metrics(F.read_rows(write(tmp_path, "c", rows)))[cid]
+ assert vals["time_in_jank_pct"] == 100.0
+ assert vals["max_frame_ms"] == 200.0
+
+
+def test_a_resumed_cell_is_measured_from_its_own_attempt_only(tmp_path):
+ # `--resume` re-runs a cell that died, and the payload is append-only, so the dead attempt's
+ # windows sit in the file under the SAME cell id. Pooling them into the retry reports a number
+ # that no single run of the film ever produced.
+ cid = "r100K.base.rep0"
+ rows = [
+ {"row_type": "run_meta", "tier": "standard", "session_id": "s1"},
+ {"row_type": "cell", "cell_id": cid, "completed": False, "session_id": "s1"},
+ frame_window(cid, "action", [5000.0] * 10, 2000.0, session_id = "s1"),
+ {"row_type": "run_meta", "tier": "standard", "session_id": "s2"},
+ {"row_type": "cell", "cell_id": cid, "completed": True, "session_id": "s2"},
+ frame_window(cid, "action", [16.0] * 100, 1600.0, session_id = "s2"),
+ ]
+ vals = F.cell_metrics(F.read_rows(write(tmp_path, "r", rows)))[cid]
+ assert vals["max_frame_ms"] == 16.0
+ assert vals["time_in_jank_pct"] == 0.0
+
+
+def test_one_file_holding_two_tiers_is_refused_like_two_files(tmp_path):
+ # The recorder appends, so a second run into the same --out leaves both films in one payload.
+ # Reading only the first run_meta let that file through the refusal it was written for.
+ rows = [
+ {"row_type": "run_meta", "tier": "fast"},
+ *cell("100K", "base", "rep0", {"open_close_ms": 1000.0}),
+ *cell("100K", "treatment", "rep0", {"open_close_ms": 900.0}),
+ {"row_type": "run_meta", "tier": "standard"},
+ ]
+ path = write(tmp_path, "mixed", rows)
+ assert F.tiers_of(F.read_rows(path)) == {"fast", "standard"}
+ with pytest.raises(SystemExit) as exc:
+ F.load([path])
+ assert "different tiers" in str(exc.value)
+
+
+# ── the session is part of a pair's identity ─────────────────────────
+
+
+def timed_action(cid: str, sid: str, ms: float) -> dict:
+ return {
+ "row_type": "action",
+ "cell_id": cid,
+ "session_id": sid,
+ "action": "message_menu",
+ "ran": True,
+ "expect_ok": True,
+ "timings": {"open_close_ms": ms},
+ }
+
+
+def resumed_payload(tmp_path: Path, name: str, retry_session: str) -> Path:
+ """One arm completed, its partner died, and `--resume` re-ran the dead arm.
+
+ `retry_session` is the session the retry was recorded under. The real `--resume` mints a new
+ one; passing the original back is the control that shows the refusal keys on the session and
+ not on there being two attempts.
+ """
+ return write(
+ tmp_path,
+ name,
+ [
+ {"row_type": "run_meta", "tier": "standard", "session_id": "s1"},
+ {
+ "row_type": "cell",
+ "cell_id": "r100K.base.rep0",
+ "session_id": "s1",
+ "completed": True,
+ },
+ timed_action("r100K.base.rep0", "s1", 100.0),
+ {
+ "row_type": "cell",
+ "cell_id": "r100K.treatment.rep0",
+ "session_id": "s1",
+ "completed": False,
+ },
+ timed_action("r100K.treatment.rep0", "s1", 999.0),
+ {"row_type": "run_meta", "tier": "standard", "session_id": retry_session},
+ {
+ "row_type": "cell",
+ "cell_id": "r100K.treatment.rep0",
+ "session_id": retry_session,
+ "completed": True,
+ },
+ # 8%: the cross-session drift this module's header measures, with no real effect in it.
+ timed_action("r100K.treatment.rep0", retry_session, 108.0),
+ ],
+ )
+
+
+def test_an_arm_resumed_into_a_new_session_is_not_paired_with_the_old_one(tmp_path):
+ # `--resume` skips the arm that completed and re-runs the one that died, under a NEW session id
+ # in the SAME shard directory. Keyed on the repetition alone the two pair, and the whole 8%
+ # session drift is charged to whichever arm was re-run. `scoring/ab.py` refuses exactly this
+ # comparison; the sweep's own pairing has to refuse it too.
+ path = resumed_payload(tmp_path, "resumed", "s2")
+ assert F.cell_metrics(F.read_rows(path))["r100K.treatment.rep0"] == {
+ "message_menu.open_close_ms": 108.0
+ }
+ assert F.paired(F.read_rows(path), shard = "resumed") == {}
+
+
+def test_an_arm_resumed_inside_the_same_session_still_pairs(tmp_path):
+ # The other direction, so the refusal above cannot pass by rejecting every resumed run. Two
+ # attempts in ONE session are still one session, and the retry's own numbers pair normally.
+ path = resumed_payload(tmp_path, "same", "s1")
+ assert F.paired(F.read_rows(path), shard = "same") == {
+ "message_menu.open_close_ms": [(100.0, 108.0)]
+ }
+
+
+def test_a_payload_with_no_session_ids_pairs_exactly_as_before(tmp_path):
+ # Payloads recorded before session ids existed carry none, so both arms resolve to "" and the
+ # new key term is inert. A refusal that also rejected these would delete every old reading.
+ path = payload(tmp_path, "legacy", [(1000.0, 900.0)])
+ assert F.paired(F.read_rows(path), shard = "legacy") == {
+ "message_menu.open_close_ms": [(1000.0, 900.0)]
+ }
+
+
+# ── ui parity: the rung is part of a pair's identity ──────────────────
+
+
+def parity_action(cid: str, action: str, digest: str) -> dict:
+ capture = {
+ "parity_attempted": True,
+ "root_kind": "thread",
+ "chars": 10,
+ "digest": digest,
+ "messages": [{"i": 0, "role": "assistant", "chars": 10, "digest": digest}],
+ "overlays": [],
+ "style": {"style_attempted": True, "capped": False, "nodes": []},
+ }
+ return {
+ "row_type": "action",
+ "cell_id": cid,
+ "action": action,
+ "ran": True,
+ "timings": {"open_ms": 5.0},
+ "parity": capture,
+ }
+
+
+def test_a_mismatch_at_a_smaller_rung_survives_the_later_rungs(tmp_path):
+ # A standard-tier repetition walks 1K, 10K and 100K. Keyed on the repetition alone, the 100K
+ # rows overwrite the 1K ones and a real difference at 1K is reported as a pass.
+ rows = [{"row_type": "run_meta", "tier": "standard"}]
+ for rung, base_digest, treat_digest in (("r1K", "AAA", "BBB"), ("r100K", "CCC", "CCC")):
+ rows.append(parity_action(f"{rung}.A0.rep0", "settings", base_digest))
+ rows.append(parity_action(f"{rung}.treatment.rep0", "settings", treat_digest))
+ path = write(tmp_path, "mine", rows)
+
+ assert len(U.collect([path])["pairs"]) == 2
+ results, _ = U.compare_all([path])
+ assert sorted(cell for _a, _s, cell, _r in results) == ["r100K rep0", "r1K rep0"]
+ assert U.report([path], "t", U.UNSTABLE_ACTIONS) == 1
+
+
+def test_matching_rungs_still_report_a_pass(tmp_path):
+ rows = [{"row_type": "run_meta", "tier": "standard"}]
+ for rung in ("r1K", "r10K", "r100K"):
+ rows.append(parity_action(f"{rung}.A0.rep0", "settings", "CCC"))
+ rows.append(parity_action(f"{rung}.treatment.rep0", "settings", "CCC"))
+ path = write(tmp_path, "clean", rows)
+ assert U.report([path], "t", U.UNSTABLE_ACTIONS) == 0
+
+
+# ── ui parity: derived instability is a property of the rung too ─────
+
+
+def parity_run(tmp_path: Path, name: str, cells: list[tuple[str, str, str, str]]) -> Path:
+ """`cells` is (rung, rep, base digest, treatment digest) for the action `settings`."""
+ rows: list[dict] = [{"row_type": "run_meta", "tier": "standard"}]
+ for rung, rep, base_digest, treat_digest in cells:
+ rows.append(parity_action(f"{rung}.base.{rep}", "settings", base_digest))
+ rows.append(parity_action(f"{rung}.treatment.{rep}", "settings", treat_digest))
+ return write(tmp_path, name, rows)
+
+
+def test_instability_measured_at_one_rung_does_not_silence_a_stable_rung(tmp_path):
+ # A standard-tier null control at the default --reps 1 walks 1K, 10K and 100K. `settings`
+ # races only at 100K, where the mounted thread is largest. Derived over the pooled action
+ # name, that single differing observation borrows the other two rungs' observation COUNT,
+ # clears min_observations, and marks `settings` unstable everywhere -- so a real DOM
+ # regression at 1K, a rung the null control measured clean, prints as expected variation and
+ # the command exits 0.
+ null = parity_run(
+ tmp_path,
+ "null",
+ [("r1K", "rep0", "Q", "Q"), ("r10K", "rep0", "Q", "Q"), ("r100K", "rep0", "X", "Y")],
+ )
+ unstable, _derived, _checks = U.unstable_set([null])
+ assert ("r100K", "settings") not in unstable # one observation is not evidence
+ assert "settings" not in unstable
+
+ mine = parity_run(
+ tmp_path,
+ "mine",
+ [
+ ("r1K", "rep0", "Q", "REGRESSED"),
+ ("r10K", "rep0", "Q", "Q"),
+ ("r100K", "rep0", "X", "X"),
+ ],
+ )
+ assert U.report([mine], "t", unstable) == 1
+
+
+def test_instability_measured_at_a_rung_still_silences_that_rung(tmp_path):
+ # The other direction, so the scoping above cannot pass by never silencing anything. With two
+ # repetitions the null control has the observations to MEAN it at 100K, and a mismatch there
+ # is expected variation -- while the same action at 1K, measured clean, still carries a
+ # verdict.
+ null = parity_run(
+ tmp_path,
+ "null2",
+ [
+ ("r1K", "rep0", "Q", "Q"),
+ ("r1K", "rep1", "Q", "Q"),
+ ("r100K", "rep0", "X", "Y"),
+ ("r100K", "rep1", "X", "Z"),
+ ],
+ )
+ unstable, _derived, _checks = U.unstable_set([null])
+ assert ("r100K", "settings") in unstable
+ assert ("r1K", "settings") not in unstable
+
+ at_100k = parity_run(tmp_path, "m100", [("r1K", "rep0", "Q", "Q"), ("r100K", "rep0", "X", "W")])
+ assert U.report([at_100k], "t", unstable) == 0
+ at_1k = parity_run(tmp_path, "m1k", [("r1K", "rep0", "Q", "W"), ("r100K", "rep0", "X", "X")])
+ assert U.report([at_1k], "t", unstable) == 1
+
+
+def test_a_declared_unstable_action_still_holds_at_every_rung(tmp_path):
+ # A declared entry carries a MECHANISM that is a property of the action, so it is not scoped
+ # to a rung and a null control is not needed to honour it.
+ rows = [{"row_type": "run_meta", "tier": "standard"}]
+ rows.append(parity_action("r1K.base.rep0", "stop_generation", "A"))
+ rows.append(parity_action("r1K.treatment.rep0", "stop_generation", "B"))
+ path = write(tmp_path, "declared", rows)
+ assert U.report([path], "t", U.unstable_set(None)[0]) == 0
+
+
+# ── ui parity: the session is part of a pair's identity too ──────────
+
+
+def in_session(row: dict, sid: str) -> dict:
+ row["session_id"] = sid
+ return row
+
+
+def resumed_parity(tmp_path: Path, name: str, retry_session: str) -> Path:
+ """A null control whose treatment arm died at 100K and was re-run by `--resume`.
+
+ The base arm completed under `s1` and stays there; `--resume` skips it and re-runs only the
+ arm that died, under `retry_session`, appending into the SAME shard directory. The retry's
+ digests carry a session-scoped volatile the normaliser did not catch, so they differ from the
+ base arm's for a reason that has nothing to do with either build.
+
+ `retry_session` is the session the retry was recorded under. The real `--resume` mints a new
+ one; passing `s1` back is the control that shows the refusal keys on the SESSION and not on
+ there being two attempts.
+ """
+ rows: list[dict] = [{"row_type": "run_meta", "tier": "standard", "session_id": "s1"}]
+ for rep in ("rep0", "rep1"):
+ rows.append(in_session(parity_action(f"r100K.base.{rep}", "settings", "STABLE"), "s1"))
+ rows.append({"row_type": "run_meta", "tier": "standard", "session_id": retry_session})
+ for rep in ("rep0", "rep1"):
+ rows.append(
+ in_session(
+ parity_action(f"r100K.treatment.{rep}", "settings", f"VOLATILE-{rep}"),
+ retry_session,
+ )
+ )
+ return write(tmp_path, name, rows)
+
+
+def test_a_resumed_arm_is_not_paired_with_its_partner_from_the_old_session(tmp_path):
+ # `--resume` re-runs the arm that died under a NEW session id in the SAME shard, so the
+ # completed partner is left under the old one. Keyed on the repetition alone the two pair, and
+ # every session-scoped volatile the normaliser missed reads as a difference between the arms.
+ # Two of them at one rung are enough for `derive_unstable` to call `settings` unstable AT THAT
+ # RUNG, and a real DOM regression at 100K then prints as expected variation and exits 0.
+ null = resumed_parity(tmp_path, "null_resumed", "s2")
+ unstable, _derived, _checks = U.unstable_set([null])
+ assert ("r100K", "settings") not in unstable
+ assert "settings" not in unstable
+
+ regressed = parity_run(tmp_path, "mine_resumed", [("r100K", "rep0", "X", "REGRESSED")])
+ assert U.report([regressed], "t", unstable) == 1
+
+
+def test_a_cross_session_pair_carries_no_verdict_in_either_direction(tmp_path):
+ # And it is not silently dropped either. Both arms ran, so the reader is told the surface went
+ # unmeasured rather than being shown a pass -- which is the distinction the NOT COMPARABLE
+ # outcome exists to make.
+ null = resumed_parity(tmp_path, "blind_resumed", "s2")
+ verdicts = {r["verdict"] for _a, _s, _c, r in U.compare_all([null])[0]}
+ assert verdicts == {U.P.NOT_COMPARABLE}
+ assert U.report([null], "t", U.UNSTABLE_ACTIONS) == 0
+
+
+def test_a_parity_arm_resumed_inside_the_same_session_still_pairs(tmp_path):
+ # The other direction, so the refusal above cannot pass by rejecting every resumed payload.
+ # Two attempts in ONE session are still one session, the pairs are real, and the instability
+ # they show is derived exactly as before.
+ null = resumed_parity(tmp_path, "same_session", "s1")
+ unstable, _derived, _checks = U.unstable_set([null])
+ assert ("r100K", "settings") in unstable
+
+
+def test_a_parity_payload_with_no_session_ids_pairs_exactly_as_before(tmp_path):
+ # Payloads recorded before session ids existed carry none, so both arms resolve to "" and the
+ # new key term is inert. A refusal that also rejected these would blind the tool to every
+ # older run.
+ path = parity_run(tmp_path, "legacy_parity", [("r1K", "rep0", "A", "B")])
+ assert U.report([path], "t", U.UNSTABLE_ACTIONS) == 1
+
+
+# ── ui parity: a superseded attempt is not an observation ────────────
+
+
+def parity_cell(cid: str, arm: str, sid: str, rep: str, completed: bool) -> dict:
+ """The `cell` row the recorder closes an attempt with, which is what names the attempt.
+
+ `CellRunner.run` emits it from a `finally`, so it lands AFTER every action row the scene
+ wrote and it lands whether the cell completed or not.
+ """
+ return {
+ "row_type": "cell",
+ "cell_id": cid,
+ "session_id": sid,
+ "cell": {"arm": arm, "rep": int(rep.removeprefix("rep"))},
+ "target_tokens": 100_000,
+ "completed": completed,
+ }
+
+
+def drained_arm(rows: list[dict], arm: str, rep: str, sid: str, digest: str, completed: bool):
+ """Append one arm's attempt: its action row, then the cell row that closes it."""
+ cid = f"r100K.{arm}.{rep}"
+ rows.append(in_session(parity_action(cid, "settings", digest), sid))
+ rows.append(parity_cell(cid, arm, sid, rep, completed))
+
+
+def resumed_both_arms(tmp_path: Path, name: str) -> Path:
+ """A null control interrupted mid-pair and resumed the way `skippable_cells` resumes.
+
+ A pair is skipped only when EVERY arm of it completed, so an interruption between the two
+ adjacent cells of one repetition re-runs BOTH arms under one new session. The treatment arm
+ died inside `stream:drain`, which the scene reaches only AFTER its action rows are written, so
+ the dead attempt sits in the append-only payload carrying a full set of digests -- and one of
+ them differs, because it was captured off an arm that was already on its way down.
+
+ So the file holds a complete base/treatment pair under `s1` and another under `s2`, and they
+ are one logical repetition, not two.
+ """
+ rows: list[dict] = [{"row_type": "run_meta", "tier": "standard", "session_id": "s1"}]
+ drained_arm(rows, "base", "rep0", "s1", "STABLE", True)
+ drained_arm(rows, "treatment", "rep0", "s1", "DYING", False)
+ rows.append({"row_type": "run_meta", "tier": "standard", "session_id": "s2"})
+ drained_arm(rows, "base", "rep0", "s2", "STABLE", True)
+ drained_arm(rows, "treatment", "rep0", "s2", "STABLE", True)
+ return write(tmp_path, name, rows)
+
+
+def test_a_superseded_attempt_is_not_a_second_parity_observation(tmp_path):
+ # One repetition ran twice, so the payload holds two comparable pairs for it. Counted as two,
+ # the differing dead attempt and the matching retry are exactly `min_observations` and
+ # `derive_unstable` marks `settings` unstable at 100K on the strength of a reading the run
+ # itself threw away.
+ null = resumed_both_arms(tmp_path, "null_both_arms")
+ assert len(U.collect([null])["pairs"]) == 1
+
+ unstable, derived, _checks = U.unstable_set([null])
+ assert derived["settings@r100K"]["observations"] == 1
+ assert derived["settings@r100K"]["differed"] == 0
+ assert ("r100K", "settings") not in unstable
+ assert "settings" not in unstable
+
+
+def test_a_superseded_attempt_does_not_silence_a_real_parity_regression(tmp_path):
+ # The consequence, end to end. Scored against that unstable set, a genuine DOM difference on
+ # `settings` at 100K prints under "expected to vary" and the gate exits 0 on a regression.
+ unstable, _derived, _checks = U.unstable_set([resumed_both_arms(tmp_path, "null_silencer")])
+ regressed = parity_run(tmp_path, "mine_both_arms", [("r100K", "rep0", "X", "REGRESSED")])
+ assert U.report([regressed], "t", unstable) == 1
+
+
+def test_two_repetitions_of_one_pair_are_still_two_parity_observations(tmp_path):
+ # The control: superseding is keyed on the ATTEMPT, not on the cell id, so two repetitions of
+ # one rung inside one session remain two independent observations and still derive as
+ # unstable. A filter that kept only one reading per cell would pass the two tests above by
+ # deleting the evidence they are meant to preserve.
+ rows: list[dict] = [{"row_type": "run_meta", "tier": "standard", "session_id": "s1"}]
+ for rep, treat in (("rep0", "Y"), ("rep1", "Z")):
+ drained_arm(rows, "base", rep, "s1", "X", True)
+ drained_arm(rows, "treatment", rep, "s1", treat, True)
+ null = write(tmp_path, "two_reps", rows)
+
+ assert len(U.collect([null])["pairs"]) == 2
+ unstable, derived, _checks = U.unstable_set([null])
+ assert derived["settings@r100K"]["observations"] == 2
+ assert ("r100K", "settings") in unstable
+
+
+def test_an_attempt_that_was_never_re_run_still_carries_its_parity_verdict(tmp_path):
+ # The other control: a cell that died and was never resumed is the LATEST attempt at itself,
+ # so its rows stay. Dropping every incomplete cell instead would blind the tool to the runs
+ # that have the most to say, and would silence the difference below rather than report it.
+ rows: list[dict] = [{"row_type": "run_meta", "tier": "standard", "session_id": "s1"}]
+ drained_arm(rows, "base", "rep0", "s1", "STABLE", True)
+ drained_arm(rows, "treatment", "rep0", "s1", "DIFFERENT", False)
+ path = write(tmp_path, "never_resumed", rows)
+
+ assert len(U.collect([path])["pairs"]) == 1
+ assert U.report([path], "t", U.UNSTABLE_ACTIONS) == 1
+
+
+# ── ui parity: one set, one tier ─────────────────────────────────────
+
+
+def two_tier_parity(tmp_path: Path, name: str, fast: tuple[str, str], standard: tuple[str, str]):
+ """One shard holding a fast run and a standard run, both at 100K, appended in that order.
+
+ The shape a second `--out` reuse at the other tier leaves behind: `fast` walks 100K only and
+ `standard` walks 1K, 10K and 100K, so the two films meet on that rung.
+ """
+ rows: list[dict] = [{"row_type": "run_meta", "tier": "fast", "session_id": "s1"}]
+ rows.append(in_session(parity_action("r100K.base.rep0", "settings", fast[0]), "s1"))
+ rows.append(in_session(parity_action("r100K.treatment.rep0", "settings", fast[1]), "s1"))
+ rows.append({"row_type": "run_meta", "tier": "standard", "session_id": "s2"})
+ rows.append(in_session(parity_action("r100K.base.rep0", "settings", standard[0]), "s2"))
+ rows.append(in_session(parity_action("r100K.treatment.rep0", "settings", standard[1]), "s2"))
+ return write(tmp_path, name, rows)
+
+
+def test_a_null_control_holding_two_tiers_is_refused_before_the_set_is_derived(tmp_path):
+ # THE POOLING THIS USED TO DEMONSTRATE IS GONE, and it was fixed underneath rather than here.
+ # The setup assertion used to be `("r100K", "settings") in unstable`: one differing 100K pair
+ # from the fast film and one matching 100K pair from the standard film pooled into exactly
+ # `min_observations`, marking the action unstable on the strength of two different films.
+ #
+ # `latest_attempt_rows` now keys an attempt on any attempt-stamped row rather than on the
+ # terminal cell row alone, and the two films write the SAME cell ids, so they are read as two
+ # attempts of one cell and the superseded one is dropped before pairing. Only the standard
+ # film's matching pair survives, so there is one observation and nothing is derived. Asserting
+ # the old pooling here would be asserting a bug that no longer exists.
+ null = two_tier_parity(tmp_path, "null_mixed", ("X", "Y"), ("Q", "Q"))
+ unstable, _derived, _checks = U.unstable_set([null])
+ assert ("r100K", "settings") not in unstable
+
+ # The refusal is kept regardless, as the layer that does not depend on the two films colliding
+ # on a cell id. Two tiers that walk different ladders need not collide at all, and a set
+ # derived across films is wrong whether or not de-duplication happened to absorb it.
+ with pytest.raises(SystemExit) as exc:
+ U.main([str(tmp_path / "mine_any"), "--null", str(null.parent)])
+ assert "more than one tier" in str(exc.value)
+
+
+def test_two_mixed_tier_sets_do_not_pass_by_matching_each_other(tmp_path):
+ # The case the tier-mismatch WARNING cannot see: both sides were re-run at the other tier, so
+ # both sets are {fast, standard}, they compare EQUAL, and no warning fires. The pooled null
+ # control then silences `settings` at 100K and the real 100K regression in the payload prints
+ # as expected variation with the command exiting 0.
+ null = two_tier_parity(tmp_path, "null_both", ("X", "Y"), ("Q", "Q"))
+ mine = two_tier_parity(tmp_path, "mine_both", ("Q", "Q"), ("Q", "REGRESSED"))
+ assert U.tier_of([null]) == U.tier_of([mine]) == {"fast", "standard"}
+
+ with pytest.raises(SystemExit) as exc:
+ U.main([str(mine.parent), "--null", str(null.parent)])
+ assert "more than one tier" in str(exc.value)
+
+
+def test_a_payload_holding_two_tiers_is_refused_even_with_no_null_control(tmp_path):
+ # The declared unstable set is not derived from anything, so nothing is pooled -- but the
+ # payload's own 100K pairs still come from two films, and reporting them as repetitions of one
+ # measurement is the same misreading.
+ mine = two_tier_parity(tmp_path, "mine_alone", ("Q", "Q"), ("Q", "REGRESSED"))
+ with pytest.raises(SystemExit) as exc:
+ U.main([str(mine.parent)])
+ assert "more than one tier" in str(exc.value)
+
+
+def test_one_tier_on_each_side_still_scores_in_both_directions(tmp_path):
+ # The control, so the refusal cannot pass by rejecting every run. A single-tier null control
+ # and a single-tier payload score exactly as before, and a real regression still exits 1.
+ null = parity_run(tmp_path, "null_one", [("r100K", "rep0", "Q", "Q")])
+ clean = parity_run(tmp_path, "mine_clean", [("r100K", "rep0", "Q", "Q")])
+ regressed = parity_run(tmp_path, "mine_bad", [("r100K", "rep0", "Q", "REGRESSED")])
+ assert U.main([str(clean.parent), "--null", str(null.parent)]) == 0
+ assert U.main([str(regressed.parent), "--null", str(null.parent)]) == 1
+
+
+def test_a_tier_mismatch_between_two_single_tier_sets_still_only_warns(tmp_path, capsys):
+ # The other control. Two sets that each hold ONE tier are comparable enough to score; the
+ # existing warning says the derived set does not transfer, and that stays a warning.
+ null = write(
+ tmp_path,
+ "null_fast",
+ [
+ {"row_type": "run_meta", "tier": "fast"},
+ parity_action("r100K.base.rep0", "settings", "Q"),
+ parity_action("r100K.treatment.rep0", "settings", "Q"),
+ ],
+ )
+ mine = parity_run(tmp_path, "mine_standard", [("r100K", "rep0", "Q", "REGRESSED")])
+ assert U.main([str(mine.parent), "--null", str(null.parent)]) == 1
+ assert "WARNING: the null control was recorded at tier" in capsys.readouterr().out
+
+
+def test_main_prints_a_mixed_unstable_set_without_dying(tmp_path, capsys):
+ # The set now holds bare action names and (rung, action) pairs together, and `sorted()` over
+ # the two raises TypeError. The one place that formats it is the run header.
+ null = parity_run(tmp_path, "nullm", [("r1K", "rep0", "X", "Y"), ("r1K", "rep1", "X", "Z")])
+ mine = parity_run(tmp_path, "minem", [("r1K", "rep0", "Q", "Q")])
+ assert U.main([str(mine.parent), "--null", str(null.parent)]) == 0
+ assert "settings@r1K" in capsys.readouterr().out
+
+
+def test_main_without_a_floor_says_so_and_still_prints(tmp_path, capsys):
+ payload(tmp_path, "result", [(1000.0, 100.0)] * 4)
+ assert F.main([str(tmp_path / "result")]) == 0
+ assert "NO FLOOR SUPPLIED" in capsys.readouterr().out
+
+
+def test_main_returns_two_when_nothing_matches(tmp_path, capsys):
+ assert F.main([str(tmp_path / "does-not-exist")]) == 2
+ assert "no payload found" in capsys.readouterr().out
+
+
+# ── the documented loop runs liveness before it reads a timing ───────
+
+
+LOOP_DOC = Path(__file__).resolve().parents[2] / "CONTRIBUTING-perf.md"
+
+
+def loop_commands() -> list[str]:
+ """The commands in the fenced block under `## The loop`, in the order a reader runs them."""
+ block = LOOP_DOC.read_text(encoding = "utf-8").split("## The loop", 1)[1].split("```")[1]
+ return [
+ line.strip()
+ for line in block.splitlines()
+ if line.strip() and not line.strip().startswith("#")
+ ]
+
+
+def index_of(commands: list[str], needle: str) -> int:
+ for i, line in enumerate(commands):
+ if needle in line:
+ return i
+ raise AssertionError(f"the documented loop no longer runs {needle}")
+
+
+SLOT_MISSED = (
+ "the slot opened at 73000ms and this machine reached it at 79000ms, past its 12000ms budget"
+)
+
+
+def liveness_action(cell_id: str, ms: float | None) -> dict:
+ """One action row. `ms` of `None` is the repetition whose slot the film moved on without."""
+ if ms is None:
+ return {
+ "row_type": "action",
+ "cell_id": cell_id,
+ "action": "message_menu",
+ "ran": False,
+ "slot_missed": True,
+ "timings": {},
+ "reason": SLOT_MISSED,
+ }
+ return {
+ "row_type": "action",
+ "cell_id": cell_id,
+ "action": "message_menu",
+ "ran": True,
+ "slot_missed": False,
+ "timings": {"open_close_ms": ms},
+ "reason": None,
+ }
+
+
+def liveness_payload(tmp_path: Path, name: str, pairs: list[tuple[float, float | None]]) -> Path:
+ """One shard whose cells carry their own actions, which is what `--assert-liveness` reads.
+
+ `paired` reads the standalone action rows and the liveness gate reads the list embedded in the
+ cell row, so a payload that exercises both has to carry the action twice, exactly as a real
+ `SceneRunner` cell does.
+ """
+ out = tmp_path / name
+ out.mkdir(parents = True, exist_ok = True)
+ rows: list[dict] = [{"row_type": "run_meta", "tier": "standard"}]
+ for i, (base, treat) in enumerate(pairs):
+ for arm, ms in (("base", base), ("treatment", treat)):
+ cid = f"100K.{arm}.rep{i}"
+ action = liveness_action(cid, ms)
+ rows.append(
+ {"row_type": "cell", "cell_id": cid, "completed": True, "actions": [action]}
+ )
+ rows.append(action)
+ path = out / "payload.jsonl"
+ path.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding = "utf-8")
+ return path
+
+
+def test_the_documented_loop_asserts_liveness_before_it_reads_any_timing():
+ commands = loop_commands()
+ liveness = index_of(commands, "--assert-liveness")
+ for reader in ("sweep.floor_table", "sweep.ui_parity", "--report"):
+ assert liveness < index_of(commands, reader), (
+ f"the loop runs {reader} before --assert-liveness, so a contributor reads a verdict "
+ f"out of a payload nothing has checked for missed slots"
+ )
+
+
+def test_floor_table_prints_a_clean_verdict_from_a_run_that_liveness_voids(tmp_path, capsys):
+ # WHY THAT ORDER IS LOAD-BEARING, and the reason the line above is a gate rather than a note.
+ # The treatment build is 10% faster on the three repetitions it managed, and on the fourth it
+ # was so slow that `message_menu` never reached its slot. `paired` matches on the metrics BOTH
+ # arms recorded, so that repetition leaves the table with no trace except a smaller `n`, and
+ # the survivors print as a clean win over a tight floor.
+ mine = liveness_payload(
+ tmp_path, "mine", [(1000.0, 900.0), (1000.0, 900.0), (1000.0, 900.0), (1000.0, None)]
+ )
+ null = liveness_payload(
+ tmp_path,
+ "null",
+ [(1000.0, 1000.0), (1010.0, 1012.0), (990.0, 989.0), (1000.0, 1001.0)],
+ )
+ assert F.main(["--floor", str(null.parent), str(mine.parent)]) == 0
+ table = capsys.readouterr().out
+ assert "faster" in table
+ assert "1 metric(s) cleared all three gates." in table
+ # The same payload, read by the gate the loop now runs first.
+ assert cli_main(["--assert-liveness", str(mine)]) == 1
+
+
+def test_the_repetition_that_missed_its_slot_is_what_the_verdict_turns_on(tmp_path, capsys):
+ # The control for the test above. With the fourth repetition's timing present, the same run is
+ # VOID on the same floor: the clean win is an artefact of the reading that went missing, not a
+ # property of the change. Every other number in the payload is identical.
+ mine = liveness_payload(
+ tmp_path, "mine", [(1000.0, 900.0), (1000.0, 900.0), (1000.0, 900.0), (1000.0, 2500.0)]
+ )
+ null = liveness_payload(
+ tmp_path,
+ "null",
+ [(1000.0, 1000.0), (1010.0, 1012.0), (990.0, 989.0), (1000.0, 1001.0)],
+ )
+ assert F.main(["--floor", str(null.parent), str(mine.parent)]) == 0
+ table = capsys.readouterr().out
+ assert "VOID (pairs disagree on sign)" in table
+ assert "0 metric(s) cleared all three gates." in table
+ assert cli_main(["--assert-liveness", str(mine)]) == 0
+
+
+# ── the null control needs the same liveness gate the treatment run gets ───────
+
+
+# A null control is base against base, so its four paired ratios are the noise this machine puts
+# between two identical builds. The fourth repetition is the one that hiccupped.
+NULL_WITH_A_NOISY_REPETITION = [
+ (1000.0, 1000.0),
+ (1010.0, 1012.0),
+ (990.0, 989.0),
+ (1000.0, 1300.0),
+]
+
+# The same null control on a run where that fourth repetition was slow enough to miss the slot, so
+# the reading that carried the noise is the reading that never happened.
+NULL_THAT_MISSED_THE_SLOT = NULL_WITH_A_NOISY_REPETITION[:3] + [(1000.0, None)]
+
+# A treatment payload that is 10% faster, consistently, with a spread well inside its own effect:
+# it clears gates 2 and 3 outright, so the only thing standing between it and `faster` is gate 1.
+MINE_TEN_PERCENT_FASTER = [
+ (1000.0, 900.0),
+ (1000.0, 905.0),
+ (1000.0, 895.0),
+ (1000.0, 900.0),
+]
+
+
+def liveness_commands(commands: list[str]) -> list[str]:
+ return [line for line in commands if "--assert-liveness" in line]
+
+
+def credentials_prose() -> str:
+ """The paragraph between the loop's fenced block and the first numbered section."""
+ body = LOOP_DOC.read_text(encoding = "utf-8").split("## The loop", 1)[1]
+ return body.split("```")[2].split("## 1.")[0]
+
+
+def test_the_documented_loop_asserts_liveness_on_the_null_control_too():
+ commands = loop_commands()
+ gated = liveness_commands(commands)
+ for payload in ("outputs/mine", "outputs/null"):
+ assert any(payload in line for line in gated), (
+ f"the loop never runs --assert-liveness on {payload}/payload.jsonl, so a missed slot "
+ f"in that run reaches the verdict table unchecked"
+ )
+ last_gate = max(commands.index(line) for line in gated)
+ for reader in ("sweep.floor_table", "sweep.ui_parity", "--report"):
+ assert last_gate < index_of(commands, reader), (
+ f"the loop runs {reader} before both liveness gates, so a contributor reads a verdict "
+ f"built from a payload nothing has checked for missed slots"
+ )
+
+
+def test_the_doc_says_which_commands_in_the_loop_need_a_studio():
+ # The loop is now four offline commands and three that drive a browser, so "every command
+ # above except the last" bills `--assert-liveness`, `floor_table` and `ui_parity` for
+ # credentials none of them read. All three run against a payload file on disk.
+ prose = credentials_prose()
+ for offline in ("--assert-liveness", "floor_table", "ui_parity", "--report"):
+ assert offline in prose, (
+ f"the paragraph under the loop does not say that {offline} runs offline, so it reads "
+ f"as though a contributor needs a Studio to score a payload they already have"
+ )
+
+
+def test_a_missed_slot_in_the_null_control_prints_noise_as_a_result(tmp_path, capsys):
+ # WHY THE NULL CONTROL IS GATED TOO. The floor is `max(|null delta|, null spread)` over the
+ # repetitions that survived pairing, and `paired` keys on the metrics BOTH arms recorded, so a
+ # null repetition that missed its slot leaves no trace either. The repetition a run drops is
+ # the one that was slow enough to miss a budget, which is the noisiest one it had, so the loss
+ # is not symmetric: it can only tighten the floor.
+ mine = liveness_payload(tmp_path, "mine", MINE_TEN_PERCENT_FASTER)
+ null = liveness_payload(tmp_path, "null", NULL_THAT_MISSED_THE_SLOT)
+ assert F.main(["--floor", str(null.parent), str(mine.parent)]) == 0
+ table = capsys.readouterr().out
+ assert "0.3 faster" in table
+ assert "1 metric(s) cleared all three gates." in table
+ # And the gate the loop used to run only on `outputs/mine` has nothing to say about it: the
+ # contributor's own payload is whole. The hole is in the run that set the bar.
+ assert cli_main(["--assert-liveness", str(mine)]) == 0
+ assert cli_main(["--assert-liveness", str(null)]) == 1
+
+
+def test_the_null_repetition_that_kept_its_reading_voids_the_same_result(tmp_path, capsys):
+ # The control for the test above, and the reading the missed slot removed. The treatment
+ # payload is byte-identical; only the null control differs, by the one repetition it managed to
+ # finish. Its floor is 30.1% rather than 0.3%, and the same 10% is noise.
+ mine = liveness_payload(tmp_path, "mine", MINE_TEN_PERCENT_FASTER)
+ null = liveness_payload(tmp_path, "null", NULL_WITH_A_NOISY_REPETITION)
+ assert F.main(["--floor", str(null.parent), str(mine.parent)]) == 0
+ table = capsys.readouterr().out
+ assert "30.1 VOID (under floor)" in table
+ assert "0 metric(s) cleared all three gates." in table
+ assert cli_main(["--assert-liveness", str(null)]) == 0
diff --git a/tests/studio/studiobench/sweep/ui_parity.py b/tests/studio/studiobench/sweep/ui_parity.py
new file mode 100644
index 00000000000..3b4d97c47d5
--- /dev/null
+++ b/tests/studio/studiobench/sweep/ui_parity.py
@@ -0,0 +1,432 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+"""UI parity across the arms of a studiobench A/B: does the PR change what is on screen?
+
+The performance question and the parity question are the same experiment run once. studiobench
+already drives both arms through the same eighteen scripted actions against a byte-identical
+seeded thread inside one session, so at the close of every action the two DOMs are supposed to
+agree. This reads the digests taken there and reports, per action, whether they did.
+
+WHAT A MISMATCH MEANS, AND WHAT IT DOES NOT. A differing digest is not automatically a defect and
+is never reported as one. Three things produce it:
+
+ a real UI change the PR renders something different. This is the finding.
+ a volatile the
+ normaliser missed a generated id, a rendered duration, a backend-minted record id. The fix
+ is in parity.js, and until it is fixed the reading is noise. The first
+ null control this tool ever ran failed on all eighteen actions for exactly
+ one such volatile; run `parity_null_control.py --hunt` before believing a
+ wall of red.
+ a legitimately
+ divergent action `stop_generation` stops a live stream, so how much text arrived before the
+ stop differs between two runs of ANY build.
+
+So the output separates STABLE actions, where a mismatch is a genuine signal, from actions that
+are expected to vary. A tool that reported all eighteen equally would be ignored within a day.
+
+WHAT A PASS DOES NOT MEAN. The digest is a serialisation of the DOM. It cannot see CSS coming from
+a stylesheet, computed layout, colour, typography, images or canvas pixels. `scene/parity.js`
+states the full list at the top of the file, and the bounded computed-style probe reported here
+covers three properties on a few dozen elements, no more. "18 actions, 0 differences" is not
+"the UI is pixel-identical", and quoting it as that is the misreading this paragraph exists to
+prevent.
+
+THE THIRD OUTCOME. An action whose digest could not be captured on one side is NOT COMPARABLE, and
+it is counted and printed as its own outcome rather than folded into the passes. An action that
+was never measured and an action that matched produce the same silence otherwise, and telling them
+apart is the entire difference between an instrument and a decoration.
+
+ python -m tests.studio.studiobench.sweep.ui_parity outputs/mine
+ python -m tests.studio.studiobench.sweep.ui_parity --null outputs/null outputs/mine
+"""
+
+from __future__ import annotations
+
+import argparse
+import collections
+import json
+import sys
+from pathlib import Path
+
+if __package__ in (None, ""): # pragma: no cover
+ # Running the file directly rather than as a module, which is the first thing anyone tries.
+ sys.path.insert(0, str(Path(__file__).resolve().parents[4]))
+
+from tests.studio.studiobench.analysis import parity as P # noqa: E402
+from tests.studio.studiobench.scoring.from_payload import latest_attempt_rows # noqa: E402
+
+# The DECLARED unstable set, each entry carrying its mechanism. It lives in the studiobench
+# package rather than here so that a test can require a mechanism for every entry, and so that
+# this script and the null control cannot drift into two different opinions about which actions
+# are trusted.
+#
+# Declared is not the same as true. `--null` replaces it with the set MEASURED from a base-vs-base
+# run and reports every disagreement in both directions, which is the only way an entry here gets
+# audited rather than inherited.
+UNSTABLE_ACTIONS = frozenset(P.UNSTABLE_ACTIONS)
+
+
+def rows(path: Path) -> list[dict]:
+ return [
+ json.loads(line) for line in path.read_text(encoding = "utf-8").splitlines() if line.strip()
+ ]
+
+
+def arm_of(cell_id: str) -> str:
+ return "treatment" if ".treatment." in cell_id else "base"
+
+
+def rung_of(cell_id: str) -> str:
+ return cell_id.split(".", 1)[0]
+
+
+def collect(paths: list[Path]) -> dict:
+ """{(shard, rung, rep, session, action): {arm: action row}} plus a tally of what was captured.
+
+ THE RUNG IS PART OF THE IDENTITY. A standard-tier run walks 1K, 10K and 100K inside one
+ repetition, so keying on the repetition alone makes every action collide two rungs deep and
+ only the last one read survives. A stable action that rendered differently at 1K was then
+ overwritten by the matching 100K row and the gate reported success.
+
+ THE SESSION IS PART OF IT FOR THE SAME REASON, and one shard is not one session. `--resume`
+ re-runs a pair under a new session id, appending into the same shard directory, and it can
+ stop again partway: a resume that re-ran the base arm and died before its partner leaves the
+ payload holding one arm under the old session and the other under the new one. Keyed on the
+ repetition alone those two arms pair, and the comparison is then across sessions:
+ `sweep/floor_table.paired` and `scoring/ab.py` both refuse exactly that, the first for the ~8%
+ session-to-session drift it charges to whichever arm was re-run, and this one because the
+ digests are of two different browser sessions. A pair that differs only for that reason is
+ counted by `derive_unstable` as evidence that the action is unstable, and two of them at one
+ rung silence a real DOM regression at that rung for good.
+
+ A payload recorded before session ids existed has `""` on both arms and pairs exactly as before.
+
+ A SUPERSEDED ATTEMPT IS NOT AN OBSERVATION, so `latest_attempt_rows` drops it before any of
+ that pairing happens. `runtime/ab.skippable_cells` skips a `(rung, rep)` pair only when EVERY
+ arm of it completed, and re-runs BOTH arms otherwise, so an interruption leaves the payload
+ holding a full base/treatment pair under the dead session AND another under the retry's. The
+ scene emits its action rows before `stream:drain`, so a cell that dies draining has already
+ written every digest it captured: keyed by session alone those two pairs are two comparable
+ observations of ONE logical repetition, and the first of them compares a completed arm against
+ an arm that was on its way down.
+
+ That is the shape `derive_unstable` is least able to survive. One differing superseded pair
+ plus one matching replacement is exactly `min_observations`, so the action is marked unstable
+ at that rung on the strength of a reading the run itself threw away, a real DOM regression
+ there prints under "expected to vary", and the command exits 0. `readings_by_arm` filters the
+ same rows for the same reason on the timing side, and `sweep/floor_table.cell_metrics` gets it
+ for free by keying completed cells on the cell id -- this was the one path left reading both.
+
+ A row whose parity is missing or failed is KEPT, as the failed capture it is. Dropping it here
+ would delete the evidence that the surface went unmeasured, and the comparison layer needs to
+ see the failure in order to call the pair not comparable.
+
+ The WHOLE ROW is carried, not just its digest, because `ran` is part of what the comparison
+ means: a matching digest on an action that never ran is not coverage of that action.
+ """
+ out: dict[tuple, dict] = collections.defaultdict(dict)
+ attempted = missing = 0
+ for path in paths:
+ shard = path.parent.name
+ # Per file: the payload is append-only within one shard, and a cell id is reused across
+ # shards, so superseding has to be resolved inside the stream that appended it.
+ for r in latest_attempt_rows(rows(path)):
+ if r.get("row_type") != "action":
+ continue
+ parity = r.get("parity")
+ if isinstance(parity, dict) and parity.get("parity_attempted"):
+ attempted += 1
+ else:
+ missing += 1
+ cid = r.get("cell_id") or ""
+ rep = cid.rsplit(".", 1)[-1]
+ sid = str(r.get("session_id") or "")
+ out[(shard, rung_of(cid), rep, sid, r.get("action"))][arm_of(cid)] = r
+ return {"pairs": out, "attempted": attempted, "missing": missing}
+
+
+def compare_all(paths: list[Path]) -> tuple[list[tuple], dict]:
+ """[(action, shard, cell, compare-result)] over every base/treatment pair found.
+
+ `cell` is `rung rep`, so the two rungs of one repetition stay two observations.
+ """
+ got = collect(paths)
+ results = []
+ for (shard, rung, rep, sid, action), sides in sorted(got["pairs"].items()):
+ cell = f"{rung} {rep}"
+ if "base" not in sides or "treatment" not in sides:
+ # One arm never produced this row at all. Recorded rather than skipped: an action that
+ # ran on one arm and not the other is itself a difference between the arms.
+ #
+ # A resumed run lands here too, with the two arms under two session ids, and the
+ # session is named so the reader can tell that case from a surface one build never
+ # rendered. Both carry NOT_COMPARABLE, which is the honest verdict for either.
+ results.append(
+ (
+ action,
+ shard,
+ cell,
+ {
+ "verdict": P.NOT_COMPARABLE,
+ "moved": [],
+ "reason": f"only the {next(iter(sides))} arm recorded this action"
+ + (f" in session {sid}" if sid else ""),
+ "style_verdict": P.NOT_COMPARABLE,
+ "style_reason": "",
+ },
+ )
+ )
+ continue
+ results.append((action, shard, cell, P.compare_rows(sides["base"], sides["treatment"])))
+ return results, got
+
+
+def rung_of_cell(cell: str) -> str:
+ """The rung half of a `compare_all` cell label, which is built as `f"{rung} {rep}"`."""
+ return cell.split(" ", 1)[0]
+
+
+def is_unstable(unstable: frozenset, action: str, cell: str) -> bool:
+ """Is this action expected to vary AT THIS RUNG?
+
+ Two kinds of entry live in the same set. A bare action name is a DECLARED entry and holds at
+ every rung, because its mechanism is a property of the action. A `(rung, action)` tuple is a
+ MEASURED entry and holds only at the rung it was measured at.
+ """
+ return action in unstable or (rung_of_cell(cell), action) in unstable
+
+
+def unstable_label(entry) -> str:
+ return entry if isinstance(entry, str) else f"{entry[1]}@{entry[0]}"
+
+
+def unstable_set(paths: list[Path] | None) -> tuple[frozenset, dict, dict]:
+ """The unstable set to score with, derived from a null control when one is supplied.
+
+ DERIVED BEATS DECLARED, and the declared set is kept as the cross-check rather than thrown
+ away: an entry that the null control never saw differ is costing real signal, and an action
+ that differs against itself without being declared is producing noise. Both are printed.
+
+ DERIVED PER RUNG, because instability is a property of the rung and not only of the action.
+ `collect()` already keeps the rung in a pair's identity, and the reason it has to is the same
+ reason this does: the mechanisms in `UNSTABLE_ACTIONS` are races between a scripted slot and a
+ stream, and how that race lands depends on how much thread the rung mounted. The tool's own
+ rung ladder says so out loud -- at 10K "the UI work disappears underneath the scene's own
+ scripted timings", at 100K it does not.
+
+ Pooling the rungs is not a smaller version of this. It is the failure mode the whole `--null`
+ mechanism exists to avoid: one differing observation at 100K, which `derive_unstable` would
+ call undetermined on its own, borrows the observation COUNT of the 1K and 10K pairs, clears
+ `min_observations`, and silences that action at every rung. A genuine DOM regression at 1K then
+ prints under "expected to vary" and the command exits 0.
+ """
+ if not paths:
+ return frozenset(UNSTABLE_ACTIONS), {}, {}
+ results, _ = compare_all(paths)
+ by_rung: dict[str, list[tuple[str, dict]]] = collections.defaultdict(list)
+ for action, _shard, cell, r in results:
+ by_rung[rung_of_cell(cell)].append((action, r))
+ derived: dict[str, dict] = {}
+ measured: set[tuple[str, str]] = set()
+ for rung, pairs in sorted(by_rung.items()):
+ for action, row in P.derive_unstable(pairs).items():
+ derived[f"{action}@{rung}"] = row
+ if row["unstable"]:
+ measured.add((rung, action))
+ # The cross-check stays pooled ON PURPOSE. It audits the DECLARED list, whose entries claim to
+ # hold at every rung, so the question it answers -- did this run ever see this action differ --
+ # is an action-level question. It is advisory output and carries no verdict.
+ checks = P.cross_check(
+ P.derive_unstable([(a, r) for a, _s, _c, r in results]), UNSTABLE_ACTIONS
+ )
+ # UNION, not replacement. An action the null control could not reach -- `image_upload` has no
+ # visible attachments button on this fixture -- would otherwise silently move from "declared
+ # unstable" to "stable" on the strength of a measurement that never happened.
+ return frozenset(measured) | frozenset(UNSTABLE_ACTIONS), derived, checks
+
+
+def report(paths: list[Path], label: str, unstable: frozenset) -> int:
+ results, got = compare_all(paths)
+ if not results:
+ # An empty result is reported as an empty result. "No mismatches found" when nothing was
+ # ever compared is the exact shape of a check that silently does nothing.
+ print(
+ f"\n{label}: NO PARITY DATA in {len(paths)} payload(s). "
+ f"{got['missing']} action rows carried no digest. "
+ f"Was this run recorded before the parity instrument existed?"
+ )
+ return 2
+
+ stable_bad, unstable_bad, blind, style_bad, idle = [], [], [], [], []
+ matched = 0
+ for action, shard, cell, r in results:
+ if r["verdict"] == P.NOT_EXERCISED:
+ idle.append((action, shard, cell, [r.get("reason", "")]))
+ continue
+ if r["verdict"] == P.NOT_COMPARABLE:
+ blind.append((action, shard, cell, [r.get("reason", "")]))
+ continue
+ if r["style_verdict"] == P.DIFFER:
+ style_bad.append((action, shard, cell, [r.get("style_reason", "")]))
+ if r["verdict"] == P.MATCH:
+ matched += 1
+ continue
+ entry = (action, shard, cell, r["moved"])
+ (unstable_bad if is_unstable(unstable, action, cell) else stable_bad).append(entry)
+
+ print(f"\n{label}")
+ print(f" {len(results)} action pairs across {len(paths)} shard(s)")
+ print(f" matched: {matched}")
+ print(f" stable actions differing: {len(stable_bad)}")
+ print(f" unstable actions differing: {len(unstable_bad)} (expected to vary; not a verdict)")
+ print(f" NOT COMPARABLE: {len(blind)} (never measured; not a pass)")
+ print(f" NOT EXERCISED: {len(idle)} (the action did not run; not coverage)")
+ print(
+ f" style probe differing: {len(style_bad)} (advisory: display/visibility/"
+ f"pointer-events)"
+ )
+
+ if stable_bad:
+ print("\n UI PARITY DIFFERENCES ON STABLE ACTIONS -- these need explaining:")
+ for action, shard, cell, moved in stable_bad:
+ print(f" {action:<26} {shard} {cell}: {', '.join(moved[:4])}")
+ else:
+ print("\n No stable action rendered differently between the two arms.")
+
+ if blind:
+ print("\n NOT COMPARABLE -- these surfaces carry no verdict in either direction:")
+ for action, shard, cell, why in blind[:8]:
+ print(f" {action:<26} {shard} {cell}: {why[0]}")
+
+ if idle:
+ # Named surfaces, deduplicated: what matters is WHICH actions this run never opened, not
+ # that it failed to open one of them sixteen separate times.
+ names = sorted({action for action, _s, _c, _w in idle})
+ print(
+ f"\n NOT EXERCISED -- {len(idle)} pair(s) over {len(names)} action(s) that did not "
+ f"run. These surfaces are UNCHECKED, not unchanged:"
+ )
+ for name in names:
+ why = next(w[0] for a, _s, _c, w in idle if a == name)
+ print(f" {name:<26} {why}")
+
+ if style_bad:
+ print("\n (advisory) the bounded computed-style probe differed:")
+ for action, shard, cell, why in style_bad[:8]:
+ print(f" {action:<26} {shard} {cell}: {why[0]}")
+
+ if unstable_bad:
+ print("\n (reported, not counted) actions that vary between runs of any build:")
+ for action, shard, cell, moved in unstable_bad[:8]:
+ print(f" {action:<26} {shard} {cell}: {', '.join(moved[:3])}")
+ return 1 if stable_bad else 0
+
+
+def tier_of(paths: list[Path]) -> set[str]:
+ """The tier(s) a payload was recorded at, from its own run_meta row.
+
+ Instability is a property of the FILM, not only of the action. On the fast film `copy_markdown`
+ opens 2.7 s after a `send_turn` and lands inside that turn's stream, so it differs against
+ itself; on the standard film the same action opens 26 s later against a finished reply. An
+ unstable set derived from one tier and applied to another would silence a real signal at one
+ end and admit noise at the other, so the mismatch is said out loud rather than assumed away.
+ """
+ tiers: set[str] = set()
+ for path in paths:
+ for r in rows(path):
+ if r.get("row_type") == "run_meta" and r.get("tier"):
+ tiers.add(r["tier"])
+ return tiers
+
+
+def one_tier(paths: list[Path], label: str) -> set[str]:
+ """The ONE tier `paths` were recorded at, refusing a set that holds more than one.
+
+ The recorder appends, so a second run into the same `--out` leaves both films in one payload
+ and `tier_of` reports both tiers. Comparing the two SETS is not enough on its own: when the
+ null control and the payload have each been re-run at the other tier they hold the same two
+ tiers, the sets are equal, and the mismatch warning below never fires.
+
+ Equal is not the same as comparable here, because the harm is inside one set. `fast` and
+ `standard` both walk 100K, so the two films' 100K pairs land on one rung in `unstable_set`,
+ and `derive_unstable` counts them together: one differing observation from the fast film plus
+ one matching observation from the standard film reads as two observations of one action, which
+ is exactly `min_observations`, so the action is marked unstable at 100K. A real DOM regression
+ at 100K in the payload then prints under "expected to vary" and the command exits 0.
+
+ `sweep/floor_table.load` already refuses the same file for the same reason on the timing side.
+ This is that refusal on the parity side, and it has to happen BEFORE the set is derived rather
+ than after, because by then the pooling has already happened.
+ """
+ tiers = tier_of(paths)
+ if len(tiers) > 1:
+ raise SystemExit(
+ f"refusing to score a {label} recorded at more than one tier: {sorted(tiers)}. "
+ f"Which actions are unstable is a property of the film, and the fast and standard "
+ f"films share the 100K rung, so their pairs would be pooled into one rung's "
+ f"observation count. Record each tier into its own --out."
+ )
+ return tiers
+
+
+def shards_of(pattern: str) -> list[Path]:
+ root = Path(pattern).parent if "/" in pattern else Path(".")
+ stem = Path(pattern).name
+ return sorted(p / "payload.jsonl" for p in root.glob(stem) if (p / "payload.jsonl").exists())
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser(
+ description = __doc__, formatter_class = argparse.RawDescriptionHelpFormatter
+ )
+ ap.add_argument("payloads", nargs = "+", help = "studiobench output dirs (globs allowed)")
+ ap.add_argument(
+ "--null",
+ metavar = "OUTDIR",
+ action = "append",
+ default = [],
+ help = "a base-vs-base run to derive the unstable set from",
+ )
+ args = ap.parse_args(argv)
+
+ null_paths: list[Path] = []
+ for pattern in args.null:
+ null_paths.extend(shards_of(pattern))
+ null_tiers = one_tier(null_paths, "null control")
+ unstable, derived, checks = unstable_set(null_paths or None)
+ if derived:
+ print(f"UNSTABLE SET DERIVED from {len(null_paths)} null-control shard(s)")
+ for key, entries in checks.items():
+ print(f" {key:<32} {', '.join(entries) if entries else '(none)'}")
+ print(
+ f" scoring against {len(unstable)} unstable entr(ies), `action@rung` where the "
+ f"instability was MEASURED at one rung: "
+ f"{', '.join(sorted(unstable_label(e) for e in unstable))}"
+ )
+ else:
+ print(
+ f"UNSTABLE SET DECLARED, not measured: "
+ f"{', '.join(sorted(unstable_label(e) for e in unstable))}"
+ )
+ print(" pass --null OUTDIR of a base-vs-base run to derive it instead.")
+
+ worst = 0
+ for pattern in args.payloads:
+ paths = shards_of(pattern)
+ if not paths:
+ print(f"\nno payload found for {pattern}")
+ worst = max(worst, 2)
+ continue
+ tiers = one_tier(paths, "payload")
+ if null_tiers and tiers and null_tiers != tiers:
+ print(
+ f"\n WARNING: the null control was recorded at tier {sorted(null_tiers)} and "
+ f"this payload at {sorted(tiers)}. Which actions are unstable depends on the "
+ f"film's slot spacing, so this unstable set does not transfer."
+ )
+ worst = max(worst, report(paths, f"UI PARITY: {pattern}", unstable))
+ return worst
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())