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: settle the instruments that published four wrong numbers (#9542)

Daniel Han02206f389a06
diff --git a/tests/studio/studiobench/CONTRIBUTING-perf.md b/tests/studio/studiobench/CONTRIBUTING-perf.md
index 2f6d6ed8ecb..f0d9f9222cf 100644
--- a/tests/studio/studiobench/CONTRIBUTING-perf.md
+++ b/tests/studio/studiobench/CONTRIBUTING-perf.md
@@ -121,6 +121,47 @@ be cleared as well as its scatter.
If you run waves, **each wave carries its own null control.** Wave 0's floor is not wave 1's floor.
+#### What a null control cannot do
+
+**A null control cannot detect a bias it shares.**
+
+This is the companion to "a check that comes back clean against code you believe is broken is
+usually a hole in the check", and it is the specific hole that a null control has.
+
+A null runs one build against itself. Any skew that is **symmetric between the two sides cancels
+exactly**, so the null reads flat and appears to certify the metric. It has certified only that the
+metric is *repeatable*. It has said nothing about whether the metric is *comparable*.
+
+The case that taught this, in full, because the shape matters more than the story:
+
+`highlight_spans_while_open` counted `pre span` on the first frame where every reasoning pane's
+`data-state` read `open`. Its null control was **0.0% at 100K and 500K, exact to the span, with
+0.0% within-arm spread** -- about as clean as a null control ever comes back. It was adopted
+*because* of that null, to replace a measure whose null swung 70%.
+
+Across two real arms it was 41% wrong. `data-state` flips when the collapse state changes, not when
+the content it reveals has mounted, and the distance between those two frames depends on the
+collapse mechanism -- which was the thing being compared. Settled, both arms mount 74,250 spans.
+Read at the flip, one arm reads 74,917 and the other 44,075.
+
+The null never had a chance: it served one bundle on both sides, so the same timing skew sat on both
+sides of its ratio and divided out.
+
+So, before you trust a flat null:
+
+- Ask what the measurement's terminating condition is, and whether that condition means the same
+ thing on both arms. A moment defined by app state is not a fixed moment when the app state
+ machine is what changed.
+- Prefer a terminating condition defined by the **quantity you are measuring going quiet** over one
+ defined by a signal that merely correlates with it.
+- A null control tests repeatability. To test comparability you need an arm where you know the
+ answer: a deliberately broken build, or an independent measurement of the same quantity by
+ another route.
+
+`scoring/payload_rules.py` carries the rules that came out of this, and
+`scoring/selftest/test_studiobench_payload_rules.py` pins the four numbers that were published and
+withdrawn before they were written down.
+
### Gate 2: sign consistency
Every paired ratio must fall on the same side of 1.0. If three repetitions say faster and one says
diff --git a/tests/studio/studiobench/__main__.py b/tests/studio/studiobench/__main__.py
index 6bf31811a31..d95f564f91d 100644
--- a/tests/studio/studiobench/__main__.py
+++ b/tests/studio/studiobench/__main__.py
@@ -24,7 +24,19 @@ import time
from pathlib import Path
from typing import Optional
-TOOL_VERSION = "0.1.0"
+# BUMPED BECAUSE THE INSTRUMENTS CHANGED, not because the tool gained features. This is one of the
+# fields the comparability key is computed over, and it is the ONLY field that can separate a run
+# taken before this change from one taken after it: the corpus is untouched, so the corpus hash,
+# the tier and the rungs all match across the change.
+#
+# They must not match. `reasoning_toggle` now settles on a quiet DOM, so
+# `highlight_spans_while_open` reads 74,250 where it used to read 44,075 on the same bundle, and
+# `open_ms` now terminates on a settled mount rather than on the `data-state` flip, which makes it
+# a different quantity rather than a better-measured one. A key that certified those two runs as
+# comparable would be the exact failure this key exists to prevent, committed by the guard itself.
+#
+# Any future change to what an instrument MEASURES has to bump this for the same reason.
+TOOL_VERSION = "0.2.0"
TIERS = ("fast", "quick", "standard", "full")
TIER_RUNGS = {
# One rung, and it is 100K on purpose. The 10K rung was measured across six PRs and could
@@ -572,6 +584,52 @@ def stop_owned_sides(
def run(args, ab_ref = None) -> int:
+ """Take the output directory FIRST, then run inside it.
+
+ THE LOCK IS THE FIRST THING THE RUN DOES, and it used to be almost the last. It was taken where
+ the `Recorder` opens `payload.jsonl`, which is after `prepare_payload` has archived what was
+ already in the directory and after every clone, build and launch. So a second invocation into a
+ busy `--out` without `--resume` was refused only once it had:
+
+ * RENAMED THE LIVE PAYLOAD of the run it was about to be refused in favour of. `rename` does
+ not disturb a writer -- the first run's descriptor names the inode, not the path -- so that
+ run went on recording into `payload-<stamp>.jsonl` while `payload.jsonl`, the one name
+ `--report`, `--assert-liveness` and the next `--resume` all open, was gone. The rule
+ `prepare_payload` states for itself is that a refusal leaves the payload exactly as it
+ found it, and this broke it in the one case the guard exists for.
+ * CLONED, BUILT AND LAUNCHED A STUDIO ON A MACHINE THAT WAS MEASURING. Contention between two
+ runs sharing one `--out` is the whole reason for the guard, so it may not be the price of
+ the refusal.
+
+ Held through setup and the cells, and handed to the `Recorder` rather than taken twice. The
+ `finally` releases it on every path, including the refusals that leave by returning, so a
+ second `run()` in one process -- which is how the tests drive this -- still gets the directory.
+ """
+ from .runtime.types import OutDirLock, Paths
+
+ # THE ARM NAMES, BEFORE A SINGLE PROCESS EXISTS AND BEFORE A SINGLE DIRECTORY. Nothing below
+ # this line can be undone without the cleanup `finally`, and that block is a long way down; see
+ # `_windowed_arms`. The labels are READ OFF THE SPECS rather than spelled a second time, so the
+ # check and the sides cannot drift into disagreeing about what an arm is called -- and
+ # `side_specs` is a pure list build, so asking it this early starts nothing.
+ #
+ # AHEAD OF THE OUTPUT DIRECTORY as well as ahead of the processes. A mistyped `--windowed-arm`
+ # must cost nothing at all, and a directory tree with a lock file in it is not nothing. See
+ # test_studiobench_windowed_arm_names.
+ specs = side_specs(args, ab_ref)
+ arm_labels = [label for label, _ref, _attach, _port, _password in specs]
+ windowed = _windowed_arms(getattr(args, "windowed_arm", ""), arm_labels)
+
+ out = Path(args.out or f"studiobench-{args.tier}-{int(time.time())}").resolve()
+ paths = Paths.under(out)
+ out_lock = OutDirLock.take(paths.out)
+ try:
+ return _run_holding_out_dir(args, ab_ref, specs, arm_labels, windowed, paths, out_lock)
+ finally:
+ out_lock.release()
+
+
+def _run_holding_out_dir(args, ab_ref, specs, arm_labels, windowed, paths, out_lock) -> int:
from .fixture.corpus import Corpus
from .instruments import build as build_instruments # noqa: F401
from .pacer import Pacer
@@ -592,19 +650,7 @@ def run(args, ab_ref = None) -> int:
from .runtime.readiness import MODE_FULL, MODE_WINDOWED
from .runtime.session import CellRunner, build_cells, ensure_probe_image, make_context
from .runtime import resources
- from .runtime.types import Paths
-
- # THE ARM NAMES, BEFORE A SINGLE PROCESS EXISTS. Nothing below this line can be undone without
- # the cleanup `finally`, and that block is a long way down; see `_windowed_arms`. The labels are
- # READ OFF THE SPECS rather than spelled a second time, so the check and the sides cannot drift
- # into disagreeing about what an arm is called -- and `side_specs` is a pure list build, so
- # asking it this early starts nothing.
- specs = side_specs(args, ab_ref)
- arm_labels = [label for label, _ref, _attach, _port, _password in specs]
- windowed = _windowed_arms(getattr(args, "windowed_arm", ""), arm_labels)
- out = Path(args.out or f"studiobench-{args.tier}-{int(time.time())}").resolve()
- paths = Paths.under(out)
_log(f"studiobench {TOOL_VERSION} tier={args.tier} out={paths.out}")
corpus = Corpus.load()
@@ -735,10 +781,10 @@ def run(args, ab_ref = None) -> int:
side_install, owns = None, False
_log(f" {label}: attaching to {side_url}")
else:
- home = side_home(args.home, out, label, ab = bool(ab_ref))
+ home = side_home(args.home, paths.out, label, ab = bool(ab_ref))
_log(f" {label}: installing Studio from {ref} into {home} (this takes a while)")
side_install = install_studio(ref, home)
- launch_studio(side_install, port, out / "logs" / f"studio_{label}.log")
+ launch_studio(side_install, port, paths.out / "logs" / f"studio_{label}.log")
side_url, owns = side_install.base_url, True
_log(f" {label}: Studio up at {side_url}")
installs.append((side_install, owns))
@@ -996,61 +1042,124 @@ def run(args, ab_ref = None) -> int:
# back the way it found it. See `rollback_session_rows`.
mark = payload_mark(paths.payload_jsonl)
ctx, session = make_context(
- bundle, base_url, args.tier, args.instrument_level, paths, _log, procs
+ bundle,
+ base_url,
+ args.tier,
+ args.instrument_level,
+ paths,
+ _log,
+ procs,
+ # ADOPTED, NOT TAKEN AGAIN. `run()` has held this directory since before the payload
+ # was archived; the `Recorder` writes its session id into the marker it already holds.
+ out_lock = out_lock,
)
rec = ctx.recorder
# The ladder this run PROMISED, resolved before it is announced. Recorded rather than
# left to be re-derived from the tier later: `--report` reads it back to decide which rungs
# a payload owes, and a `--rungs` override the payload did not carry made that answer wrong.
rungs = planned_rungs(args)
+ meta_row = {
+ "row_type": "run_meta",
+ "tier": args.tier,
+ "tool_version": TOOL_VERSION,
+ "corpus_hash": corpus.corpus_hash,
+ "studio_ref": args.branch if owns_studio else f"attached:{base_url}",
+ # WHICH COMMIT THAT REF NAMED, so a later `--resume` can tell a continuation from
+ # a branch that moved. Empty for an attached Studio, whose build is not visible
+ # from here. See `commit_problems`.
+ "studio_commit": sides[0].get("commit") or "",
+ "bundle": verdict.as_dict(),
+ "platform": {
+ "system": platform.system(),
+ "machine": platform.machine(),
+ # WHICH PHYSICAL MACHINE, which `system` and `machine` do not answer between
+ # them. `platform.machine()` is the ARCHITECTURE -- "the machine type, e.g.
+ # 'AMD64'" -- so two ordinary Linux x86_64 boxes report `Linux` and `x86_64`
+ # alike, and every number this tool produces is machine-local: `report/render.py`
+ # says so in its own words, "machine-local; does not travel between machines".
+ # `platform.node()` is the computer's network name, which is the only thing
+ # recorded here that differs between two such hosts. Empty when it cannot be
+ # determined, exactly as the other two are.
+ "node": platform.node(),
+ "python": sys.version.split()[0],
+ "engine": bundle.engine,
+ "engine_note": bundle.engine_note,
+ },
+ "started_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
+ "pacer_base_url": pacer.base_url,
+ "cadence": args.cadence,
+ "rungs": rungs,
+ "tier_rungs": TIER_RUNGS[args.tier],
+ "reps": args.reps,
+ "instrument_level": args.instrument_level,
+ # In the payload, not only in the log. Two runs with different fixtures are
+ # not comparable, and a fixture difference that is not recorded is one a later
+ # reader has no way to notice before quoting a ratio across it.
+ "stream_tail_chars": args.stream_tail_chars,
+ "corpus_dollars": bool(args.corpus_dollars),
+ # WHICH PROBE, IF ANY, WAS IN THE PAGE. Recorded next to the corpus hash and for
+ # the same reason: a payload nobody can audit against the page it measured has to
+ # be taken on trust. `null` is the normal case and the only scorable one.
+ "probe_init_script": extra_init or None,
+ # WHETHER THE PROBE RAN BEFORE THE FILM, for the same reason and with the same
+ # consequence: it changes what the cell measures without moving the cell id, so
+ # `--resume` needs it on the record to be able to refuse a toggle. See
+ # `IDENTITY_AXES`.
+ "click_probe": bool(getattr(args, "click_probe", False)),
+ # AN ARM RUNNING THIS IS NOT A MEASUREMENT OF THE BUILD, and the payload has to
+ # say so itself. A reader who finds a treatment arm 40% slower has no other way
+ # to discover that the harness put the 40% there on purpose, and `--resume` reads
+ # it back as an identity axis so a calibration cannot be continued as an ordinary
+ # run or the other way round. See `IDENTITY_AXES`.
+ "inject_stream_cost_ms": getattr(args, "inject_stream_cost_ms", None),
+ # WHICH BROWSER ACTUALLY RENDERED THIS, which the engine name does not settle.
+ #
+ # `--headed` flips `headless` at launch, and since Playwright 1.57 the two modes
+ # default to DIFFERENT BINARIES -- headed resolves to `chrome`, headless to
+ # `chrome-headless-shell`. This workflow pins `playwright>=1.45,<2`, so that split is
+ # in range. It is not a mode flag with a mode-shaped effect: one report measures
+ # headless-shell at two to three times the processing time of chrome-stable, headless
+ # falls back to software rendering for GPU-accelerated work, and the compositor still
+ # ticks at 60 Hz in headless unless BeginFrameControl is driven by hand.
+ #
+ # This tool measures frames, jank and time-to-settle. A payload recorded headed and one
+ # recorded headless are two different renderers, and the payload has to say which it
+ # was before anything compares them.
+ "headed": bool(getattr(args, "headed", False)),
+ }
+ rec.emit(meta_row)
+
+ from .scoring import payload_rules
+
+ # THE COMPARABILITY KEY, emitted as its own row so a prose comparison can be checked later.
+ #
+ # `floor_table.load` already refuses to POOL payloads across tiers and corpora, and that
+ # guard works. What it cannot reach is a comparison made in PROSE between two separately
+ # published runs, which is how a wrong number nearly propagated here twice.
+ #
+ # Computed over the run_meta row that was actually emitted, not over a second dict built
+ # to look like it. A hand-copied duplicate is one more value whose provenance is not
+ # stable, which is the whole failure this module exists to stop: the key has to describe
+ # the payload, not a parallel description of it that can drift.
+ #
+ # Keyed on the COMPUTED corpus hash rather than on the harness commit, because a commit is
+ # a claim about provenance and the hash is the thing itself: one tree in this campaign ran
+ # a corpus that matched neither the branch's pre-fix nor its post-fix hash, silently and
+ # self-consistently, and only printing the hash revealed it.
rec.emit(
{
- "row_type": "run_meta",
- "tier": args.tier,
- "tool_version": TOOL_VERSION,
- "corpus_hash": corpus.corpus_hash,
- "studio_ref": args.branch if owns_studio else f"attached:{base_url}",
- # WHICH COMMIT THAT REF NAMED, so a later `--resume` can tell a continuation from
- # a branch that moved. Empty for an attached Studio, whose build is not visible
- # from here. See `commit_problems`.
- "studio_commit": sides[0].get("commit") or "",
- "bundle": verdict.as_dict(),
- "platform": {
- "system": platform.system(),
- "machine": platform.machine(),
- "python": sys.version.split()[0],
- "engine": bundle.engine,
- "engine_note": bundle.engine_note,
- },
- "started_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
- "pacer_base_url": pacer.base_url,
- "cadence": args.cadence,
- "rungs": rungs,
- "tier_rungs": TIER_RUNGS[args.tier],
- "reps": args.reps,
- "instrument_level": args.instrument_level,
- # In the payload, not only in the log. Two runs with different fixtures are
- # not comparable, and a fixture difference that is not recorded is one a later
- # reader has no way to notice before quoting a ratio across it.
- "stream_tail_chars": args.stream_tail_chars,
- "corpus_dollars": bool(args.corpus_dollars),
- # WHICH PROBE, IF ANY, WAS IN THE PAGE. Recorded next to the corpus hash and for
- # the same reason: a payload nobody can audit against the page it measured has to
- # be taken on trust. `null` is the normal case and the only scorable one.
- "probe_init_script": extra_init or None,
- # WHETHER THE PROBE RAN BEFORE THE FILM, for the same reason and with the same
- # consequence: it changes what the cell measures without moving the cell id, so
- # `--resume` needs it on the record to be able to refuse a toggle. See
- # `IDENTITY_AXES`.
- "click_probe": bool(getattr(args, "click_probe", False)),
- # AN ARM RUNNING THIS IS NOT A MEASUREMENT OF THE BUILD, and the payload has to
- # say so itself. A reader who finds a treatment arm 40% slower has no other way
- # to discover that the harness put the 40% there on purpose, and `--resume` reads
- # it back as an identity axis so a calibration cannot be continued as an ordinary
- # run or the other way round. See `IDENTITY_AXES`.
- "inject_stream_cost_ms": getattr(args, "inject_stream_cost_ms", None),
+ "row_type": "comparability",
+ "key": payload_rules.comparability_key(meta_row),
+ "fields": payload_rules.comparability_fields(meta_row),
+ "note": (
+ "quote this key beside any number taken from this payload. Two numbers with "
+ "different keys are not comparable, and `--compare` will name the field that "
+ "differs."
+ ),
}
)
+ _log(f" comparability {payload_rules.comparability_key(meta_row)}")
+
rec.gate("production_build", verdict.production, verdict.as_dict())
if args.tier == "fast":
@@ -1602,6 +1711,17 @@ IDENTITY_AXES = (
"tier",
"cadence",
"engine",
+ # THE INSTRUMENTS THEMSELVES. `TOOL_VERSION` is bumped when what an instrument MEASURES
+ # changes and for no other reason -- this commit bumped it to 0.2.0 because
+ # `reasoning_toggle.open_ms` now terminates on a settled mount rather than on the `data-state`
+ # flip, which makes it a different quantity under the same name. None of that moves a cell id,
+ # so `--resume` into a half-finished 0.1.0 payload from an upgraded tree skipped the completed
+ # cells and appended the rest measured by 0.2.0: one ladder built from two instruments, which
+ # is the same failure the tier and the corpus are on this list for. `merged_run_meta` names the
+ # mixture afterwards, but only `--compare` and a floor-gated `floor_table.render` call it --
+ # plain `--report` takes the FIRST header and pools the two quantities without a word. Refused
+ # here instead, before anything is installed and before anything is measured.
+ "tool_version",
"instrument_level",
"corpus_hash",
"studio_ref",
@@ -1644,6 +1764,14 @@ IDENTITY_AXES = (
# cells that were recorded cleanly before it are unscorable from then on and nothing this tool
# offers takes it back. Refusing here costs a millisecond and happens before the first install.
"probe_init_script",
+ # `--headed`. On the same rule as `engine` directly above the others, and for the same reason
+ # the engine is there at all: it decides which browser binary renders the film. Since
+ # Playwright 1.57 headed and headless resolve to different executables (`chrome` against
+ # `chrome-headless-shell`), headless falls back to software rendering for GPU-accelerated
+ # work, and the compositor's own pacing differs. A resume that toggles it would skip the
+ # completed cells and append the rest under the same ids, building one ladder from two
+ # renderers -- exactly what this check exists to refuse.
+ "headed",
)
#: The axes that describe the SECOND side, which only exist when a run has one. See
@@ -1670,6 +1798,7 @@ HISTORICAL_DEFAULTS = {
"click_probe": False,
"inject_stream_cost_ms": None,
"probe_init_script": None,
+ "headed": False,
}
#: THE RATIO THE LADDER WAS SIZED BY, carried on every cell's `meta` by `session.build_cells`.
@@ -1715,6 +1844,9 @@ def requested_identity(args, ab_ref, corpus_hash: str) -> dict:
return {
"tier": args.tier,
"cadence": args.cadence,
+ # THE INSTRUMENTS THIS TREE CARRIES, as a module constant rather than anything the caller
+ # can ask for. A payload recorded by another version was measured by other instruments.
+ "tool_version": TOOL_VERSION,
# THE ENGINE THAT WILL RENDER, not the flag that asked for it. `--engine` defaults to
# nothing and `browser.launch` resolves the platform's desktop webview family, so the
# requested value has to be resolved the same way `launch` resolves it -- otherwise the
@@ -1737,6 +1869,11 @@ def requested_identity(args, ab_ref, corpus_hash: str) -> dict:
"corpus_dollars": bool(args.corpus_dollars),
"click_probe": bool(getattr(args, "click_probe", False)),
"inject_stream_cost_ms": getattr(args, "inject_stream_cost_ms", None),
+ # Spelled the same way `run_meta` records it, through `bool`, so the recorded False and
+ # the requested value are the same type. Adding the axis without this line made every
+ # resume refuse itself -- the payload declared `False` and the request declared `None` --
+ # which is the failure mode an identity axis has when it is only half wired up.
+ "headed": bool(getattr(args, "headed", False)),
# FROM THE ENVIRONMENT, because that is where this one is asked for: the probe hook is a
# variable rather than a flag on purpose, so `args` never sees it and there is nothing to
# read it from. Spelled exactly as `run_meta` records it -- the path as it was given -- for
@@ -2215,6 +2352,16 @@ def _summarise(rows: list, paths) -> None:
if not r.get("completed"):
f = r.get("failure") or {}
_log(f" FAILED: {f.get('kind')}: {str(f.get('message'))[:100]}")
+ # SAID UNDER THE TABLE THAT PRINTS THEM. `elems` and `spans` come from `census_peak`, whose
+ # action is chosen by a max() over per-action censuses that race their own teardown, so it is
+ # not the same moment on two arms. Differencing these two columns between arms is what
+ # produced a withdrawn "43% more standing DOM" claim. The columns stay because the high-water
+ # mark is a useful diagnostic; the warning stays with them so it cannot be read without it.
+ _log(
+ "\n elems/spans are census_peak: a diagnostic high-water mark, taken at whichever "
+ "action mounted most.\n Do NOT difference them between arms. For a cross-arm census use "
+ "a settled measure."
+ )
def _rung_tokens(labels: list) -> list:
@@ -2318,6 +2465,79 @@ def report_only(args) -> int:
return 0
+def compare_payloads(args) -> int:
+ """Are these two payloads comparable, and if not, exactly which field stops them?
+
+ The guard in `floor_table.load` refuses to POOL payloads across tiers and corpora and it
+ works. It cannot reach a comparison made in prose across two separately published runs, which
+ is how a withdrawn number nearly propagated twice in one campaign. Quoting the comparability
+ key beside a number turns that check from an act of memory into one command.
+ """
+ from .report.payload import read_records
+ from .scoring import payload_rules
+
+ metas = []
+ for raw in args.compare:
+ path = Path(raw)
+ if not path.exists():
+ print(f"no such payload: {path}")
+ return 2
+ # EVERY header, not the first. `--resume` appends a second `run_meta` describing the run
+ # that continued the file, and it may legitimately have extended the ladder: `rungs` is
+ # deliberately outside `IDENTITY_AXES` because adding a rung ADDS cells rather than
+ # reinterpreting the recorded ones. Keying on the first header therefore hashes a ladder
+ # the file has since outgrown, and declares a resumed payload comparable with the one-rung
+ # run it started as. `floor_table.tiers_of` and `corpora_of` were both fixed for exactly
+ # this; `--compare` was the reader left behind.
+ #
+ # READ THE WAY EVERY OTHER READER IN THIS TOOL READS. The payload is append-only and every
+ # row is flushed as it is written, so a run killed during its last append leaves valid rows
+ # followed by a torn one -- the failure this format is chosen to survive, and the reason
+ # `report.read_records` counts a malformed line instead of raising. `recorded_identities`
+ # and `_resume_set` skip one too. Parsing it here with a bare `json.loads` made `--compare`
+ # the only reader that answered an interrupted payload with a JSONDecodeError traceback
+ # rather than with the check it was asked for.
+ records, discarded = read_records(path)
+ if discarded:
+ print(
+ f" {path}: {discarded} malformed line(s) skipped, which is what a run killed "
+ f"mid-append leaves. The check below reads the intact records."
+ )
+ meta, conflicts = payload_rules.merged_run_meta(records)
+ if meta is None:
+ print(f"{path} carries no run_meta row, so it cannot be checked at all")
+ return 2
+ if conflicts:
+ # A file whose own headers disagree is not one measurement, so no single key can stand
+ # for it and the honest answer is a refusal rather than a token.
+ print(f"{path} disagrees with ITSELF across its own run_meta rows:")
+ for line in conflicts:
+ print(f" {line}")
+ print(
+ "\nThis payload holds more than one run and they were not measuring the same "
+ "thing, so no comparability key describes it. Score the sessions apart."
+ )
+ return 2
+ metas.append((path, meta))
+
+ (pa, a), (pb, b) = metas
+ ka = payload_rules.comparability_key(a)
+ kb = payload_rules.comparability_key(b)
+ print(f" {pa} {ka}")
+ print(f" {pb} {kb}")
+ if ka == kb:
+ print("\ncomparable: every field the key covers matches.")
+ return 0
+ print("\nNOT COMPARABLE. These differ:")
+ for line in payload_rules.explain_incomparable(a, b):
+ print(f" {line}")
+ print(
+ "\nA number from one of these must not be quoted against a number from the other. "
+ "Re-run the older side."
+ )
+ return 1
+
+
def assert_liveness(args) -> int:
"""Fail unless every scheduled action in a payload ran, kept its slot and proved its effect.
@@ -2511,6 +2731,16 @@ def parse_args(argv: list):
help = "score and render an existing payload.jsonl, then exit. Runs offline, "
"so a payload mailed in from another machine reports here",
)
+ ap.add_argument(
+ "--compare",
+ metavar = ("PAYLOAD_A", "PAYLOAD_B"),
+ nargs = 2,
+ dest = "compare",
+ help = "offline. Say whether two payloads may be compared at all, and if not, name the "
+ "field that differs. `floor_table` already refuses to POOL across tiers and corpora; "
+ "this is for the case it cannot reach, a comparison made in PROSE between two "
+ "separately published runs",
+ )
ap.add_argument(
"--assert-liveness",
metavar = "PAYLOAD",
@@ -2690,6 +2920,8 @@ def main(argv: list) -> int:
return doctor(args)
if args.report:
return report_only(args)
+ if args.compare:
+ return compare_payloads(args)
if args.assert_liveness:
return assert_liveness(args)
if args.ab:
diff --git a/tests/studio/studiobench/fixture/selftest/test_studiobench_rung_plan.py b/tests/studio/studiobench/fixture/selftest/test_studiobench_rung_plan.py
index c8de9ce6674..73e612dfe0a 100644
--- a/tests/studio/studiobench/fixture/selftest/test_studiobench_rung_plan.py
+++ b/tests/studio/studiobench/fixture/selftest/test_studiobench_rung_plan.py
@@ -165,7 +165,24 @@ def test_settled_actions_open_after_the_follow_up_drains():
last_send = None
for slot in sorted(scene.slots, key = lambda s: s.t_start_ms):
if slot.action == "send_turn":
- last_send = slot.t_start_ms
+ # THE LATEST THE SEND CAN FIRE, not the earliest. The drain starts when the send
+ # actually happens, and a send slot is a WINDOW: the action may legitimately begin
+ # anywhere inside its own budget, which is precisely what it does when the slot
+ # before it overran and pushed it.
+ #
+ # Measured from the start instead, this check reported 1,538 ms of margin on the
+ # fast film where 38 ms existed, and CI then failed the way the arithmetic says it
+ # must: `reasoning_toggle` overran its 3,500 ms budget by 934 ms, `send_turn` was
+ # pushed 1,373 ms late but stayed inside its 1,500 ms budget so nothing recorded a
+ # miss, the send-to-menu gap collapsed from a nominal 5,300 ms to an actual
+ # 3,691 ms, and `message_menu` found a reply still streaming and recorded NOT RUN.
+ # Every slot was individually within budget and the film was still unrunnable.
+ #
+ # This is the same defect the rest of this branch is about, in the check rather
+ # than in the instrument: a quantity computed at a moment whose meaning is not the
+ # one the reader assumes. A margin measured from the earliest possible send is not
+ # a margin.
+ last_send = slot.t_start_ms + slot.budget_ms
elif slot.action in SETTLED_ACTIONS and last_send is not None:
# The slot's WINDOW, not its start. A slot may legitimately open a little before
# the follow-up finishes and wait inside its own budget -- the quick film opens
diff --git a/tests/studio/studiobench/report/payload.py b/tests/studio/studiobench/report/payload.py
index ce83645a5d6..2120689033f 100644
--- a/tests/studio/studiobench/report/payload.py
+++ b/tests/studio/studiobench/report/payload.py
@@ -223,6 +223,23 @@ ROW_TYPE_SECTIONS: Mapping[str, str] = {
# The optional surface sweep. Its own section: a surface row is a coverage fact about the UI,
# not a timing, and folding it into `actions` would put it in front of the scorer.
"surface": "surfaces",
+ # The comparability key. Its own section rather than `header`, for two independent reasons.
+ #
+ # First, `header` is collapsed to its FIRST row when the payload is assembled, so a second row
+ # filed there is dropped without a word. Second, the row's `fields` block is identity
+ # bookkeeping and not a measurement: `instrument_level: 0` is a true statement about how the
+ # run was instrumented, exactly like the `identity` and `config` subtrees, so the section is
+ # exempted from the bare-zero ban rather than made to fake a Measure. Left unmapped the row
+ # fell into `unknown_rows`, which nothing exempts, and the walker killed every real-path
+ # session on `$.unknown_rows[0].fields.instrument_level = 0`.
+ "comparability": "comparability",
+ # The terminal marker for a cell that did not finish. NOT `cells`, which is what the scorer
+ # reads, and NOT an exclusion source: the `cell` row it follows is emitted with
+ # `completed: false` immediately before it on the same path, and `excluded_from_rows` already
+ # turns that into a `rung_incomplete` exclusion. Filing this row as a second exclusion would
+ # count one abort twice. It exists so a reader scanning FORWARD can discard the cell's window
+ # rows, and that is all it is kept for here.
+ "cell_aborted": "aborted_cells",
}
@@ -268,6 +285,8 @@ def assemble_rows(path: str | Path, *, validate: bool = True) -> dict[str, Any]:
"cells": cells,
"samples": sections.get("samples", []),
"surfaces": sections.get("surfaces", []),
+ "aborted_cells": sections.get("aborted_cells", []),
+ "comparability": (sections["comparability"][0] if sections.get("comparability") else {}),
"crashes": sections.get("crashes", []),
"arms": [],
"unknown_rows": unknown,
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_cell_aborted_emitter.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_cell_aborted_emitter.py
new file mode 100644
index 00000000000..80804229282
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_cell_aborted_emitter.py
@@ -0,0 +1,154 @@
+# 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 EMITTER of `cell_aborted`, driven through the real `CellRunner` and a real `Recorder`.
+
+Registering a row type in `ROW_TYPES` and emitting a hand-built copy of it in a test proves the
+schema accepts the row. It does not prove the harness still WRITES it, or still writes it with the
+keys the schema demands, and those are the two ways this fix can rot.
+
+Both were confirmed reachable by mutation, against the whole suite:
+
+ emitter omits the required `reason` key 449 tests pass, and the real CellRunner then dies
+ on the first failed cell with `ValueError:
+ cell_aborted row is missing required keys`
+ emitter stops writing the row entirely 449 tests pass, and the orphan windows are silent
+ again
+
+The first is defect 10 reintroduced one field lower: a guard that crashes the run it protects,
+invisible to every test. The second is defect 4 reintroduced whole -- window rows are written as
+the film runs and the `cell` row when it ends, so a cell that dies leaves a complete-looking set of
+windows behind with nobody owning them. Reading those without a guard reported the 1M rung at
+28.7 fps against a 46.7 fps baseline, drawn entirely from a cell that never finished.
+
+So this drives the real thing: a real `Recorder` writing a real payload, the real `CellRunner.run`,
+and a `_run_inner` that raises, which is exactly the aborted-cell path. Then it reads the payload
+back the way the analysis that published 28.7 fps read it -- scanning FORWARD -- and asks whether a
+forward reader could have discarded the orphans without joining backwards to the cell row.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from tests.studio.studiobench.runtime import session as session_mod
+from tests.studio.studiobench.runtime.types import (
+ BenchContext,
+ Cell,
+ Recorder,
+ new_session_id,
+)
+
+
+class Boom(Exception):
+ """Stands in for anything that kills a film halfway: a crashed tab, a watchdog, a Ctrl-C."""
+
+
+def _aborted_payload(tmp_path: Path) -> list[dict]:
+ """Run one cell that writes seven window rows and then dies. Return the payload rows in order."""
+ rec = Recorder(tmp_path / "payload.jsonl", new_session_id())
+ ctx = BenchContext(recorder = rec, log = lambda *_a, **_k: None)
+ sess = session_mod.Session(ctx = ctx, instruments = [])
+ cell = Cell(cell_id = "r1M.treatment.rep0", rung = "r1M", rung_tokens = 1_000_000)
+
+ runner = object.__new__(session_mod.CellRunner)
+ runner.session = sess
+ runner.log = lambda *_a, **_k: None
+ runner.paths = type("P", (), {"logs": tmp_path})()
+
+ # The film gets some way in and writes its windows, exactly as the real one does.
+ for i in range(7):
+ rec.emit(
+ {
+ "row_type": "window",
+ "cell_id": cell.cell_id,
+ "name": f"stream:gap{i}",
+ "kind": "gap",
+ "t_open_ms": float(i * 100),
+ "duration_ms": 33.0,
+ "instruments": {"frames": {"fps": 28.7}},
+ }
+ )
+
+ def _boom(_cell, _plan, _row):
+ raise Boom("the film did not reach the end")
+
+ runner._run_inner = _boom
+ plan = type(
+ "Plan",
+ (),
+ {
+ "rung": "r1M",
+ "seeded_chars": 1,
+ "streamed_chars": 1,
+ "target_chars": 2,
+ "target_tokens": 1_000_000,
+ },
+ )()
+
+ row = session_mod.CellRunner.run(runner, cell, plan)
+ assert row["completed"] is False, "the cell was supposed to die, so the rest proves nothing"
+ rec.close()
+ return [
+ json.loads(line)
+ for line in (tmp_path / "payload.jsonl").read_text(encoding = "utf-8").splitlines()
+ if line.strip()
+ ]
+
+
+def test_a_cell_that_dies_writes_a_terminal_cell_aborted_row(tmp_path):
+ """The emitter runs at all, and the row lands AFTER the cell row it disowns."""
+ rows = _aborted_payload(tmp_path)
+ kinds = [r["row_type"] for r in rows]
+ assert "cell_aborted" in kinds, (
+ "the real CellRunner finished an aborted cell without announcing it. Every window row it "
+ "already wrote is now an orphan that a forward-scanning reader will pool with completed "
+ "cells, which is how the 1M rung was reported at 28.7 fps from a cell that never finished."
+ )
+ assert kinds.index("cell_aborted") > kinds.index("cell"), (
+ "cell_aborted must be TERMINAL, after the cell row, or a reader scanning forward meets it "
+ "before the thing it is disowning."
+ )
+
+
+def test_the_emitted_row_carries_the_keys_the_schema_demands(tmp_path):
+ """Written through a real `Recorder`, so the schema check the run would hit is the one here.
+
+ This is the mutation that survived the whole suite: drop `reason` from the emitter's dict and
+ every test still passes, while the first failed cell of a real run raises out of its own
+ failure handler. A guard that crashes the run it protects is worse than no guard.
+ """
+ rows = _aborted_payload(tmp_path)
+ aborted = [r for r in rows if r["row_type"] == "cell_aborted"]
+ assert len(aborted) == 1
+ got = aborted[0]
+ assert got["cell_id"] == "r1M.treatment.rep0"
+ assert got["reason"] == "the film did not reach the end"
+ assert got["kind"] == "Boom"
+
+
+def test_a_forward_reader_can_discard_the_orphans_without_joining_backwards(tmp_path):
+ """The property the row exists for, asserted the way the wrong number was produced.
+
+ `floor_table.cell_metrics` guarded the orphans by joining back to the cell row. The analysis
+ that published 28.7 fps did not, because it read window rows in one forward pass. This asserts
+ that the same one-pass reader now has what it needs.
+ """
+ rows = _aborted_payload(tmp_path)
+ disowned: set[str] = set()
+ windows: list[dict] = []
+ for r in rows:
+ if r["row_type"] == "window":
+ windows.append(r)
+ elif r["row_type"] == "cell_aborted":
+ disowned.add(r["cell_id"])
+
+ assert len(windows) == 7
+ keep = [w for w in windows if w.get("cell_id") not in disowned]
+ assert keep == [], (
+ "a forward reader still pooled the windows of a cell that never finished. An incomplete "
+ "cell is not a shorter film but a different one: at 1M a completed cell emitted 6 "
+ "stream:gap windows against 17 at 100K, so an in-flight cell contributes whichever phase "
+ "it had reached rather than a uniform sample."
+ )
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_live_marker_race.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_live_marker_race.py
new file mode 100644
index 00000000000..64a4e5f4217
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_live_marker_race.py
@@ -0,0 +1,303 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Two runs that start at the same moment: exactly one may have the output directory.
+
+THE EXISTING GUARD TEST BUILDS ITS TWO RECORDERS ONE AFTER THE OTHER, which the broken code passed
+trivially. A sequential test cannot see a race, and the guard was racy from the day it landed:
+
+ the marker was named `.running.{session_id}`, so the two contenders raced on DIFFERENT paths.
+ Each globbed the directory, each found no marker but its own, and each then wrote one. Scan
+ and write are two syscalls and the window between them is wide enough to lose.
+
+Measured on the shipped guard with two processes released together, holding their recorders open so
+the overlap is real rather than sequential reuse: 107 of 200 trials admitted BOTH, and with four
+processes 68 of 100 admitted more than one. That is the defect-9 corruption reproduced through the
+guard written to prevent it -- two `run_meta` rows, one `cell_id` completed twice, the two copies
+carrying 73.4 ms and 144.5 ms because the runs were contending with each other.
+
+With the lock acquired by exclusive create on ONE fixed name, the same harness admits exactly one
+in 200 trials at two processes and 100 at four.
+
+A BARRIER, NOT SPAWNED PROCESSES ON A SHARED FLAG FILE. The window between the scan and the write
+is roughly 100 to 200 microseconds, so the release has to be tighter than that or the contenders
+simply arrive at different times and the broken guard looks fine. The first version of this test
+used `subprocess.Popen` children spinning on a flag file and PASSED against the racy code three
+times out of three, which is worth recording: a concurrency test that does not synchronise finely
+enough is not a weak test, it is a green one that proves nothing.
+
+Processes rather than threads: the liveness check is `os.kill(pid, 0)`, so two threads would be
+judged against this process's own pid and the test would say nothing about two runs.
+"""
+
+from __future__ import annotations
+
+import multiprocessing as mp
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[5]
+
+#: SIZED BY MEASUREMENT, not by guesswork. Under `spawn` the per-trial collision rate on the broken
+#: guard is well below the 50% a barrier reaches under `fork`, because each contender pays its own
+#: interpreter startup before arriving. At 10 trials the two headline tests missed the defect in one
+#: run out of four; at 40 they caught it in six runs out of six, and the whole file still costs
+#: about ten seconds. A concurrency test that only usually fails on the broken code is not much
+#: better than one that never does.
+#:
+#: `spawn` rather than `fork` because pytest has already started threads by the time this runs, and
+#: forking a multi-threaded process is deprecated for the good reason that the child can deadlock.
+TRIALS = 40
+
+
+def _contend(repo_root: str, outdir: str, index: int, start, hold, q) -> None:
+ """Take the directory, report, and keep holding until every contender has tried."""
+ sys.path.insert(0, repo_root)
+ from tests.studio.studiobench.runtime.types import Recorder, new_session_id
+
+ rec = None
+ start.wait()
+ try:
+ rec = Recorder(Path(outdir) / "payload.jsonl", new_session_id())
+ q.put((True, ""))
+ except SystemExit as exc:
+ q.put((False, str(exc)))
+ except Exception as exc: # noqa: BLE001 - reported rather than lost
+ q.put((False, f"UNEXPECTED {type(exc).__name__}: {exc}"))
+ finally:
+ # Nobody releases the marker until everyone has attempted, so an admission is genuine
+ # overlap rather than sequential reuse of a directory the first run already let go.
+ try:
+ hold.wait(timeout = 60)
+ except Exception: # noqa: BLE001
+ pass
+ if rec is not None:
+ rec.close()
+
+
+def _dead_pid() -> int:
+ with open("/proc/sys/kernel/pid_max", encoding = "utf-8") as fh:
+ return int(fh.read().strip()) - 1
+
+
+def _trial(
+ tmp_path: Path,
+ n: int,
+ trial: int,
+ stale: bool = False,
+) -> list[tuple[bool, str]]:
+ out = tmp_path / f"out{trial}"
+ out.mkdir()
+ if stale:
+ # What a crashed run leaves behind: a marker naming a pid that is gone.
+ (out / ".running.lock").write_text(f"{_dead_pid()} crashedsession\n", encoding = "utf-8")
+ ctx = mp.get_context("spawn")
+ start, hold, q = ctx.Barrier(n), ctx.Barrier(n), ctx.Queue()
+ procs = [
+ ctx.Process(target = _contend, args = (str(REPO_ROOT), str(out), i, start, hold, q))
+ for i in range(n)
+ ]
+ for p in procs:
+ p.start()
+ for p in procs:
+ p.join(timeout = 120)
+ return [q.get(timeout = 10) for _ in range(n)]
+
+
+def _admissions(
+ tmp_path: Path,
+ n: int,
+ stale: bool = False,
+) -> list[int]:
+ counts = []
+ for trial in range(TRIALS):
+ got = _trial(tmp_path, n, trial, stale = stale)
+ for ok, why in got:
+ if not ok and why.startswith("UNEXPECTED"):
+ pytest.fail(f"a contender failed for the wrong reason: {why}")
+ counts.append(sum(1 for ok, _ in got if ok))
+ return counts
+
+
+def test_two_simultaneous_runs_cannot_both_take_one_output_directory(tmp_path):
+ """The property the guard exists for, asserted against genuine concurrency.
+
+ Against the racy guard this reports about half the trials admitting two.
+ """
+ counts = _admissions(tmp_path, 2)
+ assert set(counts) == {1}, (
+ f"admitted-per-trial counts were {counts}; every trial must admit exactly one. Two runs "
+ f"in one output directory both append to one payload.jsonl, every cell id is written "
+ f"twice, and a reader keyed on the cell id sees whichever was appended last. That is the "
+ f"withdrawn 149.8% regression."
+ )
+
+
+def test_four_simultaneous_runs_admit_exactly_one(tmp_path):
+ """More contenders widen the window, so this is the same property under a harder push."""
+ counts = _admissions(tmp_path, 4)
+ assert set(counts) == {1}, f"admitted-per-trial counts were {counts}"
+
+
+def test_the_refusal_names_the_run_that_holds_the_directory(tmp_path):
+ """A refusal that does not say who holds it sends the reader looking for a phantom."""
+ got = _trial(tmp_path, 2, 0)
+ refused = [why for ok, why in got if not ok]
+ assert len(refused) == 1
+ assert "still running" in refused[0]
+
+
+def test_the_directory_is_free_again_once_the_holder_exits(tmp_path):
+ """The refusal must not outlive the run that caused it, or one race locks the dir forever."""
+ got = _trial(tmp_path, 2, 0)
+ assert sum(1 for ok, _ in got if ok) == 1
+ sys.path.insert(0, str(REPO_ROOT))
+ from tests.studio.studiobench.runtime.types import Recorder, new_session_id
+
+ rec = Recorder(tmp_path / "out0" / "payload.jsonl", new_session_id())
+ rec.close()
+
+
+def test_a_crashed_run_does_not_let_two_launchers_in_at_once(tmp_path):
+ """The reclaim path was the half the exclusive create did not fix.
+
+ A marker naming a dead pid used to be cleared by unlinking it, and two launchers meeting the
+ same stale marker both judged it dead: one unlinked and created its own, the other's unlink
+ then deleted THAT, and both were admitted. Measured on the shipped code, 23 of 200 trials with
+ two processes and 40 of 100 with four.
+
+ There is no atomic "unlink if this is still the same file", so the fix is not a better check
+ but a lock the kernel releases when the holder dies -- which leaves nothing to reclaim and no
+ reclaim path to race.
+ """
+ counts = _admissions(tmp_path, 2, stale = True)
+ assert set(counts) == {1}, (
+ f"admitted-per-trial counts were {counts} against a crashed run's marker. Two launchers "
+ f"reclaimed the same stale lock and both took the directory."
+ )
+
+
+def test_four_launchers_against_a_crashed_run_still_admit_one(tmp_path):
+ counts = _admissions(tmp_path, 4, stale = True)
+ assert set(counts) == {1}, f"admitted-per-trial counts were {counts}"
+
+
+def test_a_crashed_run_does_not_lock_the_directory_forever(tmp_path):
+ """The other direction: the refusal must not outlive the process that earned it."""
+ out = tmp_path / "solo"
+ out.mkdir()
+ (out / ".running.lock").write_text(f"{_dead_pid()} crashedsession\n", encoding = "utf-8")
+ sys.path.insert(0, str(REPO_ROOT))
+ from tests.studio.studiobench.runtime.types import Recorder, new_session_id
+
+ rec = Recorder(out / "payload.jsonl", new_session_id())
+ rec.close()
+
+
+# ── a retained record is not a holder ────────────────────────────────
+#
+# The marker is deliberately never unlinked, so on a directory that has been used before it already
+# contains the PREVIOUS run's `pid session` line. These two are deterministic on purpose: they stand
+# in the window rather than racing for it, so they say the same thing on a loaded runner as on an
+# idle one.
+
+
+def _stalled_holder(
+ marker: Path,
+ write_after_s: float,
+ session: str = "realsession",
+):
+ """A holder that takes the lock and only then publishes itself, which is the required order:
+ the write is what makes the marker say anything, and writing before the lock would let a LOSER
+ publish itself as the holder."""
+ code = (
+ "import os,fcntl,time,sys\n"
+ "fd=os.open(sys.argv[1],os.O_CREAT|os.O_RDWR,0o644)\n"
+ "fcntl.flock(fd,fcntl.LOCK_EX)\n"
+ "print('locked',flush=True)\n"
+ "time.sleep(float(sys.argv[2]))\n"
+ "os.ftruncate(fd,0); os.lseek(fd,0,0)\n"
+ "os.write(fd,('%d %s\\n'%(os.getpid(),sys.argv[3])).encode()); os.fsync(fd)\n"
+ "time.sleep(30)\n"
+ )
+ proc = subprocess.Popen(
+ [sys.executable, "-c", code, str(marker), str(write_after_s), session],
+ stdout = subprocess.PIPE,
+ text = True,
+ )
+ assert proc.stdout is not None
+ proc.stdout.readline()
+ return proc
+
+
+def _refusal(out: Path) -> str:
+ sys.path.insert(0, str(REPO_ROOT))
+ from tests.studio.studiobench.runtime.types import Recorder, new_session_id
+
+ with pytest.raises(SystemExit) as excinfo:
+ Recorder(out / "payload.jsonl", new_session_id())
+ return str(excinfo.value)
+
+
+def test_a_clean_close_leaves_no_identity_behind(tmp_path):
+ """`close()` blanks the marker while it still holds the lock.
+
+ The file stays, because unlinking it reintroduces the reclaim race in reverse. Its CONTENT does
+ not, because a retained `pid session` line outlives the run that wrote it.
+ """
+ sys.path.insert(0, str(REPO_ROOT))
+ from tests.studio.studiobench.runtime.types import Recorder
+
+ out = tmp_path / "out0"
+ out.mkdir()
+ rec = Recorder(out / "payload.jsonl", "sessionAAAA")
+ marker = out / ".running.lock"
+ assert "sessionAAAA" in marker.read_text()
+ rec.close()
+ assert marker.exists(), "the marker must not be unlinked"
+ assert marker.read_text() == "", marker.read_text()
+
+
+def test_a_retained_record_is_not_named_as_the_current_holder(tmp_path):
+ """THE MISATTRIBUTION. A refusal that names the wrong run is worse than one that names none.
+
+ Seeded as an UNCLEAN exit leaves it -- a killed run never reaches the blanking above -- so the
+ stale line survives. A new holder then takes the lock and has not rewritten yet, and a reader
+ that stops at the first non-empty record is handed the dead run and prints it as the holder.
+ """
+ out = tmp_path / "out0"
+ out.mkdir()
+ marker = out / ".running.lock"
+ # A pid that is definitely not running: spawn and reap.
+ dead = subprocess.Popen([sys.executable, "-c", "pass"])
+ dead.wait()
+ marker.write_text(f"{dead.pid} sessionGONE\n")
+
+ holder = _stalled_holder(marker, write_after_s = 0.35)
+ try:
+ message = _refusal(out)
+ finally:
+ holder.kill()
+ assert "sessionGONE" not in message, message
+ assert str(holder.pid) in message, message
+ assert "realsession is still running" in message, message
+
+
+def test_the_refusal_stays_generic_when_no_live_holder_can_be_named(tmp_path):
+ """The bound is not load-bearing: when it expires the wording gets less specific, never wrong.
+
+ A holder that never publishes itself is the shape a run killed between the lock and the write
+ leaves behind, and there is nothing truthful to say about who holds the directory.
+ """
+ out = tmp_path / "out0"
+ out.mkdir()
+ marker = out / ".running.lock"
+ holder = _stalled_holder(marker, write_after_s = 60.0)
+ try:
+ message = _refusal(out)
+ finally:
+ holder.kill()
+ assert "another run is still holding it" in message, message
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.py
index e2bb746c507..4336fe1b8a4 100644
--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.py
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.py
@@ -32,6 +32,7 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from studiobench.__main__ import ( # noqa: E402
+ TOOL_VERSION,
_resume_set,
archive_payload,
parse_args,
@@ -52,7 +53,7 @@ def _run_meta(tier, ref, rungs, **extra):
row = {
"row_type": "run_meta",
"tier": tier,
- "tool_version": "0.1.0",
+ "tool_version": TOOL_VERSION,
"corpus_hash": CORPUS,
"studio_ref": ref,
"bundle": {"production": True},
@@ -280,7 +281,7 @@ def test_a_payload_that_never_recorded_an_axis_still_resumes(tmp_path):
legacy = {
"row_type": "run_meta",
"tier": "standard",
- "tool_version": "0.0.9",
+ "tool_version": TOOL_VERSION,
"corpus_hash": CORPUS,
"studio_ref": "main",
"bundle": {"production": True},
@@ -321,6 +322,57 @@ def test_resuming_an_ab_payload_as_a_single_build_run_is_refused(tmp_path):
assert "mode" in str(excinfo.value)
+def test_resuming_a_payload_measured_by_another_instrument_version_is_refused(tmp_path):
+ """A harness upgrade mid-campaign is the one identity change nobody has to type.
+
+ `TOOL_VERSION` is bumped when what an instrument MEASURES changes and for no other reason: at
+ 0.2.0 `reasoning_toggle.open_ms` terminates on a settled mount rather than on the `data-state`
+ flip, which is a different quantity under the same name. None of that moves a cell id, so
+ `--resume` into a half-finished 0.1.0 payload from an upgraded tree kept the old completed
+ cells and appended new ones measured by the new instruments. `merged_run_meta` names that
+ mixture, but plain `--report` never calls it -- it reads the FIRST header and pools both.
+ """
+
+ paths = Paths.under(tmp_path / "upgraded")
+ _record(
+ paths,
+ "sess-old",
+ [
+ {**_run_meta("standard", "main", ["10K"]), "tool_version": "0.1.0"},
+ _cell("r10K.A0.rep0", 10_000),
+ _keystroke("r10K.A0.rep0", 9),
+ ],
+ )
+ args = parse_args(["--tier", "standard", "--branch", "main", "--rungs", "10K,100K", "--resume"])
+
+ with pytest.raises(SystemExit) as excinfo:
+ prepare_payload(
+ paths, requested_identity(args, None, CORPUS), resume = True, log = lambda *_a: None
+ )
+
+ assert "tool_version" in str(excinfo.value)
+ assert TOOL_VERSION in str(excinfo.value)
+
+
+def test_a_payload_recorded_by_this_version_still_resumes(tmp_path):
+ """The control: the axis must refuse an upgrade, not every resume."""
+
+ paths = Paths.under(tmp_path / "same")
+ _record(
+ paths,
+ "sess-1",
+ [_run_meta("standard", "main", ["10K"]), _cell("r10K.A0.rep0", 10_000)],
+ )
+ args = parse_args(["--tier", "standard", "--branch", "main", "--rungs", "10K,100K", "--resume"])
+
+ assert (
+ prepare_payload(
+ paths, requested_identity(args, None, CORPUS), resume = True, log = lambda *_a: None
+ )
+ is None
+ )
+
+
def test_an_ab_payload_that_never_recorded_a_treatment_url_still_resumes(tmp_path):
"""The legacy control for the newest axis: an `ab_plan` written before the URL was recorded
declares nothing about it, and an axis a row never declared cannot be a difference."""
@@ -779,7 +831,7 @@ def test_the_skip_rule_still_holds_for_an_axis_that_really_did_decline_to_say(tm
{
"row_type": "run_meta",
"tier": "standard",
- "tool_version": "0.0.9",
+ "tool_version": TOOL_VERSION,
"corpus_hash": CORPUS,
"studio_ref": "main",
"bundle": {"production": True},
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_run_acquisition.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_run_acquisition.py
index 20e93bff92b..e4db3e49511 100644
--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_run_acquisition.py
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_run_acquisition.py
@@ -43,7 +43,7 @@ from studiobench.runtime import browser as browser_mod # noqa: E402
from studiobench.runtime import bundle_guard, lifecycle # noqa: E402
from studiobench.runtime import session as session_mod # noqa: E402
from studiobench.runtime.lifecycle import StudioAuth, StudioInstall # noqa: E402
-from studiobench.runtime.types import Paths # noqa: E402
+from studiobench.runtime.types import OutDirLock, Paths # noqa: E402
class _Verdict:
@@ -511,6 +511,101 @@ def test_an_unreadable_probe_is_refused_before_the_payload_is_archived(studio, m
assert studio["installed"] == ["main"]
+def test_a_duplicate_run_is_refused_before_it_archives_or_installs_anything(studio):
+ """REGRESSION. A run refused for the directory must not have moved the live payload first.
+
+ The guard against two runs in one `--out` used to be taken where the `Recorder` opens
+ `payload.jsonl`, which is after `prepare_payload` has archived what was already there and after
+ every clone, build and launch. A second launcher pointed at a busy directory therefore renamed
+ the FIRST run's live payload out from under it -- the writer keeps its inode through a rename,
+ so that run went on recording into `payload-<stamp>.jsonl` while `payload.jsonl`, the one name
+ `--report`, `--assert-liveness` and the next `--resume` open, was gone -- and put a clone and a
+ build on the machine the first run was measuring, before saying the word it could have said in
+ the first millisecond.
+
+ The holder here stands for that first run: it is the same lock a live run holds, so the second
+ invocation meets exactly what it meets in the field.
+ """
+
+ paths = Paths.under(studio["out"])
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+ recorded = paths.payload_jsonl.read_text(encoding = "utf-8")
+
+ studio["installed"].clear()
+ holder = OutDirLock.take(paths.out)
+ try:
+ with pytest.raises(SystemExit) as excinfo:
+ sb.run(_args(studio, "--branch", "main"))
+ finally:
+ holder.release()
+
+ assert "still running" in str(excinfo.value)
+ assert (
+ paths.payload_jsonl.read_text(encoding = "utf-8") == recorded
+ ), "the refused duplicate archived the live payload of the run it was refused in favour of"
+ assert sorted(p.name for p in paths.out.glob("payload-*.jsonl")) == []
+ assert studio["installed"] == [], (
+ "the duplicate installed a Studio on a machine that was already measuring, which is the "
+ "contention the guard exists to prevent, paid as the cost of refusing it"
+ )
+ # And the directory is free again the moment the holder lets go.
+ assert sb.run(_args(studio, "--branch", "main", "--resume")) == 0
+
+
+def test_a_duplicate_is_still_refused_while_the_report_is_being_rendered(studio, monkeypatch):
+ """REGRESSION. The directory stays held until `run()` has finished READING the payload back.
+
+ `rec.close()` runs in the `finally` under the cells; `_render_ab` and `_summarise` then reopen
+ `payload.jsonl` after it and before `run()`'s own outer `finally` lets the directory go. While
+ `Recorder.close` released the lock it had ADOPTED from `run()`, the directory was free for the
+ whole of that window, and a duplicate arriving in it was admitted. It then did what the guard
+ exists to stop, to a run whose cells had all completed:
+
+ * `prepare_payload` renames `payload.jsonl` to `payload-<stamp>.jsonl` BEFORE it clones
+ anything, so for the minutes it spends installing there is no `payload.jsonl` at all and
+ the first run's reporting step dies with `FileNotFoundError` -- after every cell passed.
+ * once it has opened a payload of its own, that empty file is what `_render_ab` reads, so
+ `ab.md` is written out of another run's rows and the first run still exits 0.
+
+ The duplicate is driven through the real `run()`, from inside the reporting window, so it meets
+ the guard exactly where a second launcher meets it in the field. `flock` treats two descriptors
+ on one file independently even within a process, so the in-process contender is refused by the
+ same kernel lock a separate launcher is.
+ """
+
+ paths = Paths.under(studio["out"])
+ real_render = sb._render_ab
+ seen: dict = {}
+
+ def render_with_a_duplicate_arriving(*args, **kwargs):
+ if "duplicate" not in seen:
+ seen["installed_before"] = list(studio["installed"])
+ seen["payload_before"] = paths.payload_jsonl.read_text(encoding = "utf-8")
+ try:
+ seen["duplicate"] = sb.run(_args(studio, "--branch", "main"))
+ except SystemExit as exc:
+ seen["duplicate"] = exc
+ return real_render(*args, **kwargs)
+
+ monkeypatch.setattr(sb, "_render_ab", render_with_a_duplicate_arriving)
+ assert sb.run(_args(studio, "--branch", "main", "--ab", "pr-9296"), ab_ref = "pr-9296") == 0
+
+ assert isinstance(
+ seen["duplicate"], SystemExit
+ ), "a second run was admitted to the output directory while the first was still reporting"
+ assert "still running" in str(seen["duplicate"])
+ # Nothing of the first run's was moved, and nothing was installed on top of it.
+ assert paths.payload_jsonl.exists(), "the duplicate archived the payload being reported on"
+ assert paths.payload_jsonl.read_text(encoding = "utf-8") == seen["payload_before"]
+ assert sorted(p.name for p in paths.out.glob("payload-*.jsonl")) == []
+ assert studio["installed"] == seen["installed_before"]
+ # The report is the first run's own, over its own rows.
+ table = (paths.out / "ab.md").read_text(encoding = "utf-8")
+ assert "main -> pr-9296" in table
+ # And the control: the directory is released once `run()` has actually finished with it.
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+
+
def _clean_summary(studio) -> Path:
"""A clean run, then the `--report` the README quickstart runs on it, into the same `--out`."""
diff --git a/tests/studio/studiobench/runtime/session.py b/tests/studio/studiobench/runtime/session.py
index a2286f49757..6efdaf30550 100644
--- a/tests/studio/studiobench/runtime/session.py
+++ b/tests/studio/studiobench/runtime/session.py
@@ -444,6 +444,34 @@ class CellRunner:
if self._click_attribution_result is not None:
row["click_attribution"] = self._click_attribution_result
rec.emit(row)
+ # A TERMINAL MARKER FOR A CELL THAT DID NOT FINISH, so a reader scanning FORWARD can
+ # discard its windows without having to join backwards to the cell row.
+ #
+ # `window` rows are written as the film runs; the `cell` row is written when the film
+ # ends. An in-flight or aborted cell therefore leaves a complete-looking set of window
+ # rows behind with no completed cell owning them, and an analysis that reads windows
+ # directly picks them up. `floor_table.cell_metrics` has always guarded this; nothing
+ # else did.
+ #
+ # This cost a headline. Reading `stream:gap` windows without the guard reported the
+ # 1M rung at 28.7 fps and 21.8% of frames over 33 ms against a 46.7 fps baseline, an
+ # apparent large regression at the rung closest to the user complaint, drawn entirely
+ # from a cell that had not finished. An incomplete cell is not a shorter film but a
+ # different one: at 1M the completed cell emitted 6 `stream:gap` windows against 17 at
+ # 100K, so an in-flight cell contributes whichever phase it had reached.
+ if not row["completed"]:
+ rec.emit(
+ {
+ "row_type": "cell_aborted",
+ "cell_id": cell.cell_id,
+ "reason": (row.get("failure") or {}).get("message", "did not complete"),
+ "kind": (row.get("failure") or {}).get("kind"),
+ "note": (
+ "every window row carrying this cell_id measures an unfinished film "
+ "and must not be pooled with completed cells"
+ ),
+ }
+ )
return row
# ── the cell ────────────────────────────────────────────────────
@@ -788,6 +816,42 @@ class CellRunner:
row["census_peak"] = peak
row["census_peak_attempted"] = bool(censuses)
+ # WHICH ACTION THE PEAK CAME FROM, and a standing refusal to compare it across arms.
+ #
+ # `census_peak` is whichever per-action census had the most elements. The census attached
+ # to an action is taken after the action returns, and `reasoning_toggle` opens every pane
+ # and then closes them again, so that census races the close. Which action wins the max()
+ # therefore depends on the race and DIFFERS BETWEEN ARMS.
+ #
+ # Measured on a null control -- the same bundle served on both arms -- the winner flipped
+ # between `settings` (panes collapsed, 64,648 elements) and `reasoning_toggle` (panes open,
+ # 106,067), a 70.1% swing in `highlight_spans` WITHIN one arm.
+ #
+ # This produced a published wrong number: main was reported as mounting 48% more Shiki
+ # spans than a pre-campaign baseline, and an attribution bisect was nearly commissioned to
+ # find the cause. Settled, the two trees mount the same document to within 0.3%.
+ #
+ # It stays in the payload because it is useful as a diagnostic high-water mark. It carries
+ # its provenance and an explicit refusal so that no analysis can quote it across arms
+ # without stepping over a flag that says not to.
+ peak_from = next(
+ (
+ w.get("action")
+ for w in row["actions"]
+ if isinstance(w.get("census"), dict)
+ and w["census"].get("elements") == peak.get("elements")
+ ),
+ None,
+ )
+ row["census_peak_from_action"] = peak_from
+ row["census_peak_comparable_across_arms"] = False
+ row["census_peak_note"] = (
+ "diagnostic high-water mark only. The action it comes from is chosen by a max() over "
+ "per-action censuses that race the action's own teardown, so it is not the same "
+ "moment on two arms and must not be differenced across them. For a cross-arm census "
+ "use a measure taken at a defined, settled moment."
+ )
+
census = peak or row["census_after"]
spans = census.get("highlight_spans") or 0
chars = census.get("assistant_chars")
@@ -931,7 +995,19 @@ class CellRunner:
"""
s = self.session
page = s.ctx.page
+ # THE STREAMED SIDE IS THE PEAK, AND THE PEAK IS TAKEN AT AN UNSTABLE MOMENT. Recorded on
+ # the row rather than left implicit, because the seeded side below is read after an
+ # explicit 4 s wait -- a settled moment -- so this gate differences a racing census against
+ # a stable one. That is the same shape as the defect that made `census_peak` unquotable
+ # across arms.
+ #
+ # It is NOT the same harm and the behaviour is deliberately left alone here: both sides of
+ # this comparison come from ONE cell on ONE build, so the instability widens the gate's
+ # tolerance rather than pointing a difference in a direction. Changing which census feeds
+ # it would change what the gate asserts, and that cannot be justified without measuring it
+ # against a browser. Said out loud so the next reader does not have to rediscover it.
streamed = row.get("census_peak") or row.get("census_after") or {}
+ streamed_from = "census_peak" if row.get("census_peak") else "census_after"
follow_ups = self._streamed_follow_ups(plan, row)
try:
all_units = list(plan.seeded_units) + [plan.streamed_unit] + follow_ups
@@ -960,7 +1036,10 @@ class CellRunner:
}
out = compare_signatures(streamed, seeded_sig)
out["streamed_census"] = streamed
+ out["streamed_census_from"] = streamed_from
+ out["streamed_census_settled"] = streamed_from != "census_peak"
out["seeded_census"] = seeded_sig
+ out["seeded_census_settled"] = True
out["readiness_mode"] = self.readiness_mode
if self.readiness_mode == MODE_WINDOWED:
# SAID OUT LOUD RATHER THAN SCORED QUIETLY. Both sides of this check are loaded by the
@@ -1258,9 +1337,14 @@ def make_context(
paths: Paths,
log: Callable[[str], None],
browser_procs: Optional[list] = None,
+ out_lock = None,
) -> tuple[BenchContext, Session]:
session_id = new_session_id()
- recorder = Recorder(paths.payload_jsonl, session_id)
+ # THE LOCK THE CALLER IS ALREADY HOLDING. `run()` takes the output directory before it archives
+ # a payload or installs a Studio, so the `Recorder` adopts that lock rather than opening a
+ # second one against the same path. Without a caller's lock it takes its own, which is what
+ # every test and every other consumer of a payload does.
+ recorder = Recorder(paths.payload_jsonl, session_id, lock = out_lock)
ctx = BenchContext(
browser = browser_bundle.browser,
context = browser_bundle.context,
diff --git a/tests/studio/studiobench/runtime/types.py b/tests/studio/studiobench/runtime/types.py
index 0f846d5abed..bfffb38744f 100644
--- a/tests/studio/studiobench/runtime/types.py
+++ b/tests/studio/studiobench/runtime/types.py
@@ -34,6 +34,13 @@ ROW_TYPES = frozenset(
# UNBALANCED, because whether linear drift cancelled is a property of the run that a reader
# of the table has no other way to recover.
"ab_plan",
+ # A cell that did not finish, announced the moment it fails so a reader scanning FORWARD
+ # can discard its window rows without joining backwards to a cell row it may never reach.
+ "cell_aborted",
+ # The comparability key: everything that must match for two payloads to be compared at
+ # all, hashed into one quotable token. Its own row rather than a field on `run_meta` so a
+ # reader can find it without parsing the whole meta block.
+ "comparability",
# One UI surface swept by the optional `--surfaces` phase: a route, a settings tab, a menu.
# A row type of its own rather than an `action` row with a different name, because a surface
# has no slot, no budget and no timing to miss -- and reusing `action` would put forty rows
@@ -58,6 +65,8 @@ ROW_REQUIRED: dict[str, tuple[str, ...]] = {
"cell": ("cell", "completed", "fidelity"),
"window": ("name", "kind", "t_open_ms", "duration_ms"),
"action": ("action", "ran", "expect_ok", "expect", "timings", "slot_missed"),
+ "cell_aborted": ("cell_id", "reason"),
+ "comparability": ("key", "fields"),
"sample": ("t_ms",),
"failure": ("kind", "detail"),
# `reason` is REQUIRED, not optional. A surface row that lost its reason reads as a surface
@@ -322,6 +331,285 @@ class BenchContext:
browser_procs: list = field(default_factory = list)
+# ── the output directory lock ───────────────────────────────────────
+
+
+class OutDirLock:
+ """One output directory, held by one run, FROM BEFORE THE FIRST THING THAT MOVES OR STARTS.
+
+ SEPARATE FROM THE `Recorder` BECAUSE OF WHEN IT HAS TO BE TAKEN. The guard used to be taken
+ where the payload is opened, which is after `prepare_payload` has archived whatever was in the
+ directory and after both Studios have been cloned, built and launched. A second launcher
+ pointed at a busy `--out` without `--resume` therefore did all of that before being refused,
+ and both halves of it hurt the run it was refused in favour of:
+
+ * `archive_payload` RENAMES the live `payload.jsonl` the first run is still writing. A rename
+ does not disturb the writer -- its descriptor names the inode, not the path -- so the first
+ run goes on recording into a file that is no longer at the name every reader opens.
+ `--report`, `--assert-liveness` and the next `--resume` all open `payload.jsonl`, and the
+ run that was never refused anything has silently lost its evidence from that name. That is
+ exactly the rule `prepare_payload` states for itself: a refusal has to leave the payload it
+ refused exactly as it found it.
+ * A clone, a build and a launch are not free. The first run is MEASURING, and the refusal
+ that arrives after all of that has already put a compiler and a second Studio on the
+ machine the first run thought it had. Contention between two runs sharing one `--out` is
+ the whole reason this guard exists; it must not be the guard's own cost of saying no.
+
+ So the lock is taken by `run()` in the first millisecond, held across setup and the cells, and
+ handed to the `Recorder`, which adopts it rather than taking a second one.
+ """
+
+ def __init__(self, out: Path) -> None:
+ self.out = Path(out)
+ self.path = self.out / ".running.lock"
+ self._fd: Optional[int] = None
+
+ @classmethod
+ def take(
+ cls,
+ out: Path,
+ session_id: str = "starting",
+ ) -> "OutDirLock":
+ """Hold `out`, or raise `SystemExit` naming the run that already holds it.
+
+ `session_id` is written into the marker so a refusal can name a holder. A run takes the
+ directory BEFORE it has a session, so the default stands in until `claim` replaces it.
+ """
+ lock = cls(out)
+ lock.out.mkdir(parents = True, exist_ok = True)
+ # The legacy per-session names, swept once. A directory left by an older build still has to
+ # be read, or the guard would quietly switch itself off on exactly the runs it was added
+ # for. Only the fixed name is ever a mutex.
+ lock._refuse_if_legacy_marker_is_live()
+ lock._acquire(session_id)
+ return lock
+
+ def claim(self, session_id: str) -> None:
+ """Name the session in the marker, now that the run has one.
+
+ The refusal a contender prints reads the marker, so leaving it saying `starting` for the
+ life of the run would make every refusal anonymous.
+ """
+ if self._fd is not None:
+ self._write(session_id)
+
+ def _acquire(self, session_id: str) -> None:
+ """Hold this output directory for the life of the process, or refuse and say who has it.
+
+ A KERNEL LOCK, NOT A FILE THAT STANDS FOR ONE. The previous design created the marker with
+ `O_CREAT | O_EXCL` and reclaimed a marker naming a dead pid by unlinking it. The create is
+ atomic and fixed the cold-start race completely -- 0 of 200 with two launchers on a clean
+ directory. The RECLAIM is not atomic and could not be made so: two launchers meeting the
+ same crashed run's marker both read its dead pid, one unlinks and creates its own, and the
+ other's unlink then deletes THAT, so both are admitted. Measured on a seeded stale marker,
+ 23 of 200 trials with two processes and 40 of 100 with four.
+
+ Verifying the file's identity before unlinking does not fix it and measurably makes it
+ worse -- 80 of 200 against 59 for the plain version -- because there is no atomic
+ "unlink if this is still the same file", so the check only widens the window between the
+ judgement and the unlink. This is the GnuPG dotlock race (T5884); inode verification is a
+ post-acquisition theft detector, not a pre-unlink guard. Renaming the marker aside before
+ unlinking is worse again at four contenders (200 of 200), because the rename leaves the
+ path briefly empty and the next `O_EXCL` create walks straight in.
+
+ An advisory lock removes the whole problem rather than narrowing it: the kernel drops it
+ when the holder dies, so a crashed run leaves nothing to reclaim and there is no reclaim
+ path to race. That also retires the other hazard the old design had to paper over, a marker
+ that exists but has not been written to yet.
+
+ `fcntl` is Unix-only, so Windows takes `msvcrt.locking`, which is the same branch
+ `pre-commit` and `portalocker` use. It locks a byte RANGE rather than the file, hence the
+ seek to 0 and the single byte. The property genuinely given up is NFS correctness, which
+ the `O_EXCL` design did not have either.
+
+ THE LOCK IS NEVER UNLINKED, only released. Unlinking on close reintroduces the same race
+ from the other end: a launcher that has opened the path but not yet locked it would end up
+ holding a lock on an inode with no name, while the next run creates a fresh file and locks
+ that. The file left behind carries no authority, so a stale one is harmless.
+ """
+ fd = os.open(self.path, os.O_CREAT | os.O_RDWR, 0o644)
+ try:
+ self._lock_fd_exclusive(fd)
+ except OSError:
+ held = self._read_marker_once_written(self.path)
+ os.close(fd)
+ who = (
+ f"session {held[0]} is still running as pid {held[1]}"
+ if held
+ else "another run is still holding it"
+ )
+ raise SystemExit(
+ f"refusing to append to {self.out}: {who}. Two concurrent runs sharing "
+ f"one --out contend with each other and write the same cell ids into one file. "
+ f"Give this run its own --out."
+ ) from None
+ self._fd = fd
+ self._write(session_id)
+
+ def _write(self, session_id: str) -> None:
+ fd = self._fd
+ if fd is None:
+ return
+ os.ftruncate(fd, 0)
+ os.lseek(fd, 0, os.SEEK_SET)
+ os.write(fd, f"{os.getpid()} {session_id}\n".encode())
+ try:
+ os.fsync(fd)
+ except OSError:
+ pass
+
+ def release(self) -> None:
+ """Drop the lock. IDEMPOTENT, so a second call is a no-op rather than a double free.
+
+ RELEASED BY WHOEVER TOOK IT. `run()` takes the directory and releases it in its outer
+ `finally`, after the report has been rendered; a `Recorder` that ADOPTED that lock does
+ not release it in `close`, because `close` happens while `run()` still has the payload to
+ read back. See `Recorder.close`.
+
+ RELEASED, NOT DELETED. Dropping the lock is what frees the directory; unlinking the file
+ as well would let a launcher that has already opened the path end up holding a lock on an
+ inode with no name while the next run creates a fresh file and locks that, which is the
+ reclaim race in reverse. The file left behind carries no authority.
+ """
+ fd = self._fd
+ if fd is None:
+ return
+ self._fd = None
+ # BLANKED BEFORE IT IS RELEASED, and only while this process still holds the lock, so
+ # nothing can be reading it as authoritative. The file stays (see above); what goes is
+ # its CONTENT, because a retained `pid session` line outlives the run that wrote it and
+ # the next contender to lose a race would otherwise be handed it as the holder. Not a
+ # substitute for the liveness test in `_read_marker_once_written`: a killed run never
+ # reaches this line.
+ try:
+ os.ftruncate(fd, 0)
+ except OSError:
+ pass
+ self._unlock_fd(fd)
+ try:
+ os.close(fd)
+ except OSError:
+ pass
+
+ @staticmethod
+ def _lock_fd_exclusive(fd: int) -> None:
+ """Take a non-blocking exclusive lock, raising OSError if somebody else holds it."""
+ if os.name == "nt": # pragma: no cover - exercised on the Windows CI leg
+ import msvcrt
+ os.lseek(fd, 0, os.SEEK_SET)
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
+ else:
+ import fcntl
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+
+ @staticmethod
+ def _unlock_fd(fd: int) -> None:
+ if os.name == "nt": # pragma: no cover - exercised on the Windows CI leg
+ import msvcrt
+ try:
+ os.lseek(fd, 0, os.SEEK_SET)
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
+ except OSError:
+ pass
+ else:
+ import fcntl
+ try:
+ fcntl.flock(fd, fcntl.LOCK_UN)
+ except OSError:
+ pass
+
+ @staticmethod
+ def _read_marker(path: Path) -> "Optional[tuple[str, int]]":
+ """(session, pid) written in a marker, or None if it does not yet say."""
+ try:
+ parts = path.read_text(encoding = "utf-8").split()
+ return (
+ parts[1] if len(parts) > 1 else path.name.removeprefix(".running."),
+ int(parts[0]),
+ )
+ except (OSError, ValueError, IndexError):
+ return None
+
+ @classmethod
+ def _read_marker_once_written(
+ cls,
+ path: Path,
+ budget_s: float = 0.5,
+ ) -> "Optional[tuple[str, int]]":
+ """`_read_marker`, waiting out the gap between taking the lock and writing into it.
+
+ THE HOLDER LOCKS FIRST AND WRITES SECOND, and it has to: the write is what makes the marker
+ say anything, and writing before the lock would let a loser publish itself as the holder. So
+ there is a window in which the marker exists, is locked, and is still empty, and a contender
+ that reads it there gets nothing and refuses without naming anybody -- which is exactly what
+ the refusal is not allowed to do, because a reader then goes looking for a phantom.
+
+ The window is microseconds wide and closes on its own, so it is waited out rather than
+ designed around. Bounded, because a holder that died between the lock and the write leaves
+ an empty marker that never fills, and the generic wording is right for that one. Measured:
+ the gap is `ftruncate` + `write` + `fsync`; half a second is three orders of magnitude of
+ headroom on a path that is about to exit anyway. Two-core CI is where this was observed --
+ the same test passes on an unloaded machine, which is what made it look flaky rather than
+ like a hole in the message.
+
+ DO NOT SIMPLIFY THE LOOP BELOW TO `if got is not None`. That is the version this was
+ written as twice, independently, by two people who each then had to fix it the same way --
+ which is the evidence that the wrong shape is the intuitive one and is not visible from the
+ call site. Waiting only for the marker to become NON-EMPTY stops on the retained record
+ described below and names a run that finished hours ago, so the liveness test is the point
+ of the wait rather than a refinement of it.
+ """
+ deadline = time.monotonic() + budget_s
+ while True:
+ got = cls._read_marker(path)
+ # A RETAINED RECORD IS NOT A HOLDER. The marker is deliberately never unlinked, so on
+ # any directory that has been used before it already contains the PREVIOUS run's
+ # `pid session` line. That record is non-empty, so a bare "did it read" test stops on
+ # it and the refusal names a run that finished hours ago as the current holder --
+ # worse than saying nothing, because it sends the reader after a specific dead pid.
+ # Measured: a clean `close()` leaves `2235618 sessionAAAA`, and a contender that meets
+ # a NEW holder inside this window was told `session sessionAAAA is still running as
+ # pid 2235618` while the actual holder was pid 2235621.
+ #
+ # Liveness is what separates them. The holder is by definition a running process, and
+ # the run that wrote a retained record has exited. `close()` also blanks the marker
+ # while it still holds the lock, so a clean exit leaves nothing to mistake; this covers
+ # the unclean ones. What is left is a retained record whose pid has been RECYCLED onto
+ # a live process, which needs an unclean exit and a wrapped pid space in the same
+ # directory.
+ if got is not None and cls._alive(got[1]):
+ return got
+ if time.monotonic() >= deadline:
+ return None
+ time.sleep(0.01)
+
+ @staticmethod
+ def _alive(pid: int) -> bool:
+ if pid <= 0:
+ return False
+ try:
+ os.kill(pid, 0)
+ return True
+ except (OSError, ProcessLookupError):
+ return False
+
+ def _refuse_if_legacy_marker_is_live(self) -> None:
+ """Honour `.running.<session>` markers from older builds, and clear the dead ones."""
+ for other in sorted(self.out.glob(".running.*")):
+ if other == self.path:
+ continue
+ got = self._read_marker(other)
+ if got is not None and self._alive(got[1]):
+ session, pid = got
+ raise SystemExit(
+ f"refusing to append to {self.out}: session {session} is still "
+ f"running as pid {pid}. Two concurrent runs sharing one --out contend with "
+ f"each other and write the same cell ids into one file. Give this run its "
+ f"own --out."
+ )
+ other.unlink(missing_ok = True)
+
+
# ── the recorder ────────────────────────────────────────────────────
@@ -334,11 +622,61 @@ class Recorder:
path: Path,
session_id: str,
t0: Optional[float] = None,
+ lock: Optional[OutDirLock] = None,
) -> None:
self.path = Path(path)
self.path.parent.mkdir(parents = True, exist_ok = True)
self.session_id = session_id
self.t0 = t0 if t0 is not None else time.monotonic()
+ # REFUSE A SECOND LIVE SESSION IN ONE OUTPUT DIRECTORY.
+ #
+ # Appending is correct across SHARDS, which are deliberate and sequential. It is never
+ # correct for two runs going at once: they contend with each other, so neither measures
+ # the machine the other thought it had, and they write the same `cell_id`s into one file
+ # where a reader keyed on `cell_id` sees only the last writer.
+ #
+ # Observed: a launcher started twice produced three `run_meta` rows and every `cell_id`
+ # twice, both marked completed, with `r1M.treatment.rep1` keystroke `p50_ms` reading
+ # 73.4 ms in one session and 144.5 ms in the other. Scored last-wins that payload showed a
+ # 149.8% regression that does not exist at that size.
+ #
+ # The marker carries the pid, so a crashed run leaves a marker that names a dead process
+ # and the next run says so rather than refusing forever.
+ #
+ # ONE FIXED NAME, CREATED EXCLUSIVELY. The name used to be `.running.{session_id}`, and a
+ # per-session name cannot be a mutex however carefully it is written: the two contenders
+ # race on DIFFERENT paths, so each scanned the directory, each found only the other's
+ # absence, and each then created its own marker. Scan-then-write is two syscalls with a
+ # window between them, and the window is wide enough to lose. Measured on this guard
+ # before the change, two processes released from a barrier against one output directory:
+ # 123 of 200 trials admitted BOTH recorders, reproducing the defect-9 signature the guard
+ # exists to prevent -- two `run_meta` rows, one `cell_id` completed twice, 73.4 ms against
+ # 144.5 ms. Two processes merely launched back to back, with no barrier at all, still
+ # collided about 3% of the time.
+ #
+ # `os.open(..., O_CREAT | O_EXCL)` makes the check and the creation one atomic operation
+ # against other opens of the same name, which is the documented lock-file idiom and is
+ # available on Unix and Windows alike. `fcntl.flock` is deliberately NOT used: the `fcntl`
+ # module does not exist on Windows, and this tool is run by external testers there.
+ #
+ # TAKEN BEFORE THIS POINT WHEN THE CALLER HAS ONE, AND THAT IS THE NORMAL PATH. `run()`
+ # holds the directory from its first millisecond, because by the time the payload is opened
+ # a duplicate has already archived the live payload and installed two Studios on top of the
+ # run it is about to be refused in favour of. See `OutDirLock`. A `Recorder` built without
+ # one -- the tests, and any caller that only wants a payload -- still takes its own, so the
+ # guard cannot be switched off by forgetting to pass it.
+ #
+ # WHO OWNS THE LOCK IS RECORDED HERE, because it decides who may let go of it. A lock this
+ # `Recorder` took is this `Recorder`'s to release when it closes. A lock ADOPTED from the
+ # caller outlives the recording -- `run()` closes the recorder and then reads the payload
+ # back to render `ab.md` -- so releasing it in `close` would free the directory for the
+ # length of the report. See `close`.
+ self._owns_lock = lock is None
+ if lock is None:
+ lock = OutDirLock.take(self.path.parent, session_id)
+ else:
+ lock.claim(session_id)
+ self._lock = lock
self._fh = self.path.open("a", encoding = "utf-8")
self._count = 0
@@ -413,6 +751,24 @@ class Recorder:
self._fh.close()
except OSError:
pass
+ # RELEASED, NOT DELETED, and ONLY IF THIS RECORDER TOOK THE LOCK ITSELF.
+ #
+ # AN ADOPTED LOCK IS NOT THIS OBJECT'S TO DROP. `run()` takes the output directory in its
+ # first millisecond and hands it here, then closes the recorder in the `finally` under the
+ # cells and goes on to READ THE PAYLOAD BACK -- `_render_ab` and `_summarise` both open
+ # `payload.jsonl` after that `finally` and before `run()`'s own outer one. Releasing the
+ # adopted lock here freed the directory for exactly that window, and a second invocation
+ # arriving in it was admitted: its `prepare_payload` renames the finished run's
+ # `payload.jsonl` to `payload-<stamp>.jsonl` before it clones anything, so the reporting
+ # step either fails with `FileNotFoundError` on a run whose cells all completed, or -- if
+ # the contender has got as far as opening a payload of its own -- reads THAT file and
+ # writes an `ab.md` describing another run's rows while still exiting 0.
+ #
+ # A `Recorder` that took its own lock -- the tests, and any caller that only wants a
+ # payload -- has nobody else to release it, so it still does so here.
+ lock = getattr(self, "_lock", None)
+ if lock is not None and getattr(self, "_owns_lock", True):
+ lock.release()
def new_session_id() -> str:
diff --git a/tests/studio/studiobench/scene/actions.py b/tests/studio/studiobench/scene/actions.py
index d6070446ca9..480541b2926 100644
--- a/tests/studio/studiobench/scene/actions.py
+++ b/tests/studio/studiobench/scene/actions.py
@@ -382,42 +382,187 @@ def scroll_after(ctx: ActionContext) -> ActionResult:
# ── 4. reasoning expand / collapse ──────────────────────────────────
+# SETTLING ON THE DOM, NOT ON A STATE ATTRIBUTE.
+#
+# `data-state="open"` flips when the Collapsible's state changes. It says nothing about whether the
+# content that state reveals has mounted, and how far apart those two frames are depends on the
+# COLLAPSE MECHANISM -- which is exactly the thing an A/B across a collapse change is comparing. So
+# an instant defined by the attribute means a different thing on each arm.
+#
+# Measured, 100K rung, both arms, same corpus. Reading `pre span` on the frame the attribute
+# settles gives 74,917 on the measured-height arm and 44,075 on the grid-rows arm, a 41% apparent
+# reduction. Reading it once the span count has stopped changing gives 74,250 on BOTH, to the span.
+# The 41% was the grid arm being counted before it had finished mounting.
+#
+# Its null control did not catch this and could not have: the null runs one bundle against itself,
+# so the skew is identical on both sides and cancels exactly. A null cannot see a bias it shares.
+#
+# So both the timing and the census now terminate on a QUIET DOM: the observed quantity has to stop
+# changing for `quietFrames` consecutive animation frames before it is read. If it never goes
+# quiet, nothing is returned for it and the reason is recorded, because silence beats a confident
+# wrong answer.
+SETTLE_QUIET_FRAMES = 4
+
REASONING_JS = """
-async (timeoutMs) => {
+async ([timeoutMs, quietFrames]) => {
const D = window.__sb.dom;
const triggers = D.reasoningTriggers();
if (triggers.length === 0) return { ran: false, reason: "no reasoning pane in the thread" };
const before = D.reasoningOpenCount();
- const settle = async (want) => {
+ const spanCount = () => document.querySelectorAll("pre span").length;
+
+ // Wait for the open count to reach `want` AND for the span census to stop moving. Returns the
+ // elapsed time, the number of frames spent, and why it stopped, so a censored reading is
+ // distinguishable from a fast one rather than both arriving as a number.
+ //
+ // `origin` IS THE CALLER'S MARK, TAKEN BEFORE THE CLICKS, AND THE REPORTED TIMING RUNS FROM IT.
+ // Dispatching the clicks is the first half of opening the panes: `t.click()` runs the app's own
+ // handler synchronously, and on a long thread that is React state plus layout, sixteen times
+ // over. Timing from the settle's own start instead silently redefines `open_ms` as "the wait
+ // after the work", which is a smaller number for the same action -- measured on a page with a
+ // 40 ms handler per pane, `open_ms` read 96 ms against 640 ms of dispatch it had just done.
+ // That is the defect this whole branch is about, so it must not be introduced by the fix for it.
+ //
+ // The BUDGET still runs from the settle's own start, so what counts as censored is unchanged.
+ // The two are reported separately: `ms` is the whole operation, `settle_ms` is the wait alone.
+ const settle = async (want, origin, requireTornDown) => {
const started = performance.now();
+ let frames = 0;
+ let quiet = 0;
+ let last = spanCount();
+ let reachedAt = null;
+ // The RAW state, tracked apart from `reachedAt` so a censored close can say whether the panes
+ // closed and did not tear down, or never closed at all.
+ let countReachedAt = null;
while (performance.now() - started < timeoutMs) {
- if (D.reasoningOpenCount() === want) return performance.now() - started;
await window.__sbNextPaint();
+ frames += 1;
+ const now = spanCount();
+ // A COLLAPSE IS NOT DONE WHEN THE STATE SAYS CLOSED, IT IS DONE WHEN THE CONTENT IS GONE.
+ //
+ // This is the same defect as the one the quiet streak fixes for the open direction, arriving
+ // from the other side. There, the state flips before the spans mount, and a streak counted
+ // from frame one was satisfied by a census that had not started moving. Here the state flips
+ // before the spans UNMOUNT: both mechanisms keep the children in the document for the length
+ // of the exit animation (Radix until `animationend`, the grid arm until the
+ // `grid-template-rows` `transitionend` or its 250 ms backstop), so `pre span` is frozen at
+ // its open value for that entire window. Four quiet frames land inside it whenever a frame is
+ // shorter than the animation -- about 83 ms at 60 Hz against 200 -- and `close_ms` then names
+ // the state flip plus four frames rather than the collapse.
+ //
+ // That is not a constant offset either, which is what makes it a comparison problem rather
+ // than a units one: whether the streak ends before or after the teardown depends on the
+ // paint interval against the animation duration, and the paint interval is what differs
+ // between the arms and the rungs this instrument exists to compare. See
+ // `dom.reasoningContentMounted`.
+ const countReached = D.reasoningOpenCount() === want;
+ if (countReached && countReachedAt === null) countReachedAt = performance.now() - started;
+ const stateReached =
+ countReached && (!requireTornDown || D.reasoningContentMounted() === 0);
+ const justReached = stateReached && reachedAt === null;
+ if (justReached) reachedAt = performance.now() - started;
+ // THE QUIET STREAK BELONGS ENTIRELY TO THE WINDOW AFTER THE STATE IS REACHED.
+ //
+ // Counting it from the first frame instead defeats the whole fix whenever the panes take
+ // `quietFrames` or more frames to reach the open state while nothing has mounted yet -- and
+ // that is the NORMAL case at the rungs this was written for. The catalogue's own 500K
+ // reading is "the open count reached 16 after 10440ms": the census is static through all of
+ // those frames because the content it would count has not been revealed yet, so the streak
+ // is already satisfied on the very frame the state flips, and the read happens exactly where
+ // it used to. Reproduced against this JS with a page whose state flips at frame 6 and whose
+ // spans mount to frame 40: it returned 44,075 with `censored: false`, which is the withdrawn
+ // number, reported confidently, out of the code that exists to stop it.
+ //
+ // The streak also RESTARTS if the state is lost again, so a count that oscillates around
+ // `want` cannot bank quiet frames it did not hold.
+ quiet = stateReached && !justReached && now === last ? quiet + 1 : 0;
+ last = now;
+ if (stateReached && quiet >= quietFrames) {
+ return {
+ // From the caller's mark, so the click dispatch this action performed is inside the
+ // number that names it.
+ ms: performance.now() - origin,
+ settle_ms: performance.now() - started,
+ dispatch_ms: started - origin,
+ frames,
+ // Rebased onto the same origin as `ms`, or the two would be quoted against each other
+ // from different zeroes.
+ state_reached_ms: reachedAt === null ? null : reachedAt + (started - origin),
+ spans: now,
+ censored: false,
+ reason: null,
+ };
+ }
}
- return null;
+ return {
+ ms: null,
+ settle_ms: performance.now() - started,
+ dispatch_ms: started - origin,
+ frames,
+ state_reached_ms: reachedAt === null ? null : reachedAt + (started - origin),
+ spans: null,
+ censored: true,
+ // THE REASON NAMES WHICH HALF OF "SETTLED" WAS MISSING. A close that reached the state but
+ // whose panes never tore down is a different finding from one whose panes never closed, and
+ // reporting both as "the open count never reached 0" would send a reader to the wrong half
+ // of the app.
+ reason: reachedAt === null
+ ? (requireTornDown && countReachedAt !== null
+ ? `the open count reached ${want} after ${Math.round(countReachedAt)}ms but the `
+ + `collapsed panes were still mounted when the ${timeoutMs}ms budget ran out, so `
+ + `nothing here is a reading of a collapsed document`
+ : `the open count never reached ${want} within ${timeoutMs}ms`)
+ : (requireTornDown
+ ? `the panes closed after ${Math.round(countReachedAt)}ms and unmounted after `
+ + `${Math.round(reachedAt)}ms but the span census was still changing when the `
+ + `${timeoutMs}ms budget ran out, so nothing here is a reading of a settled document`
+ : `the open count reached ${want} after ${Math.round(reachedAt)}ms but the span `
+ + `census was still changing when the ${timeoutMs}ms budget ran out, so nothing `
+ + `here is a reading of a settled document`),
+ };
};
+
// Toggle EVERY pane, not one: the mechanism under investigation scales with how much content
// is mounted, and opening a single pane in a thread of forty is a constant-size action being
// reported on an axis of thread length.
const openStart = performance.now();
for (const t of triggers) t.click();
- const openedIn = await settle(triggers.length);
- const openMs = openedIn === null ? null : performance.now() - openStart;
+ const opened = await settle(triggers.length, openStart, false);
const openCount = D.reasoningOpenCount();
- const spansOpen = document.querySelectorAll("pre span").length;
const closeStart = performance.now();
for (const t of D.reasoningTriggers()) t.click();
- const closedIn = await settle(0);
- const closeMs = closedIn === null ? null : performance.now() - closeStart;
+ // `true`: the collapse is settled when the panes have UNMOUNTED, not when they report closed.
+ const closed = await settle(0, closeStart, true);
return {
ran: true,
panes: triggers.length,
before,
openCount,
afterClose: D.reasoningOpenCount(),
- spansOpen,
- openMs: openMs === null ? null : Math.round(openMs * 10) / 10,
- closeMs: closeMs === null ? null : Math.round(closeMs * 10) / 10,
+ // ONLY from a settled document. `null` when the census never went quiet.
+ spansOpen: opened.spans,
+ spansOpenReason: opened.reason,
+ openMs: opened.ms === null ? null : Math.round(opened.ms * 10) / 10,
+ closeMs: closed.ms === null ? null : Math.round(closed.ms * 10) / 10,
+ openCensored: opened.censored,
+ closeCensored: closed.censored,
+ openCensoredReason: opened.reason,
+ closeCensoredReason: closed.reason,
+ // The ruler's own resolution, so a reader can see that a difference smaller than a frame is
+ // not a difference. `open_ms` is quantised to the paint interval by construction.
+ openFrames: opened.frames,
+ closeFrames: closed.frames,
+ openStateReachedMs: opened.state_reached_ms === null
+ ? null : Math.round(opened.state_reached_ms * 10) / 10,
+ // THE SPLIT, so a reader can see how much of the timing was the app's click handlers and how
+ // much was waiting for the DOM to stop moving. They answer different questions and a single
+ // total hides which of the two a change actually moved.
+ openDispatchMs: Math.round(opened.dispatch_ms * 10) / 10,
+ closeDispatchMs: Math.round(closed.dispatch_ms * 10) / 10,
+ openSettleMs: Math.round(opened.settle_ms * 10) / 10,
+ closeSettleMs: Math.round(closed.settle_ms * 10) / 10,
+ quietFramesRequired: quietFrames,
+ timeoutMs,
};
}
"""
@@ -425,21 +570,41 @@ async (timeoutMs) => {
@register_action(name = "reasoning_toggle", default_budget_ms = 12000)
def reasoning_toggle(ctx: ActionContext) -> ActionResult:
- raw = _ev(ctx, REASONING_JS, SETTLE_TIMEOUT_MS)
+ raw = _ev(ctx, REASONING_JS, [SETTLE_TIMEOUT_MS, SETTLE_QUIET_FRAMES])
err = _failed(raw)
if err:
return not_run(err)
if not raw.get("ran"):
return not_run(raw.get("reason", "the reasoning toggle did not run"))
- # Both directions, and the pane count is read from `data-state` on the Collapsible ROOT.
- # Radix keeps collapsed content mounted for its animation, so a presence check on the content
- # element reports every pane as open and the assertion can never fail.
- ok = (
- raw["openMs"] is not None
- and raw["closeMs"] is not None
- and raw["openCount"] == raw["panes"]
- and raw["afterClose"] == 0
- )
+
+ # THE REASON NAMES THE CLAUSE THAT ACTUALLY FAILED.
+ #
+ # This used to be built from the pane counts alone, so a run whose real failure was a censored
+ # timing printed "16 of 16 panes opened and 0 were still open after collapsing" -- a
+ # description of SUCCESS -- under the heading EXPECT FAILED. A reader who trusts the message
+ # concludes the assertion is broken rather than that the timing is missing.
+ failures: list[str] = []
+ if raw["openCount"] != raw["panes"]:
+ failures.append(f"only {raw['openCount']} of {raw['panes']} panes opened")
+ if raw["afterClose"] != 0:
+ failures.append(f"{raw['afterClose']} panes were still open after collapsing")
+ if raw["openMs"] is None:
+ failures.append(f"open_ms is censored: {raw.get('openCensoredReason')}")
+ if raw["closeMs"] is None:
+ failures.append(f"close_ms is censored: {raw.get('closeCensoredReason')}")
+ ok = not failures
+
+ # A CENSORED TIMING IS ABSENT, NOT ZERO, and it is absent LOUDLY. `_action_timings` drops
+ # non-numeric values, so a censored cell silently leaves the pooled metric and the survivors
+ # are the fast ones -- survivorship bias wearing a mean. The censoring is therefore recorded
+ # as its own field so the scoring layer can refuse to pool a metric that is censored at some
+ # rungs and not others.
+ timings = {}
+ if raw["openMs"] is not None:
+ timings["open_ms"] = raw["openMs"]
+ if raw["closeMs"] is not None:
+ timings["close_ms"] = raw["closeMs"]
+
return ActionResult(
ran = True,
expect_ok = ok,
@@ -456,13 +621,23 @@ def reasoning_toggle(ctx: ActionContext) -> ActionResult:
"panes_scope": "mounted",
"open_after_expand": raw["openCount"],
"open_after_collapse": raw["afterClose"],
+ # Present ONLY when the span census went quiet. See the note above REASONING_JS: read
+ # on the frame the state attribute flips, this number was 41% wrong on one arm and
+ # right on the other, and its null control could not see the difference.
"highlight_spans_while_open": raw["spansOpen"],
+ "highlight_spans_while_open_reason": raw.get("spansOpenReason"),
+ "settled": raw["spansOpen"] is not None,
+ "open_censored": bool(raw.get("openCensored")),
+ "close_censored": bool(raw.get("closeCensored")),
+ "open_censored_reason": raw.get("openCensoredReason"),
+ "close_censored_reason": raw.get("closeCensoredReason"),
+ # The ruler's resolution, and how much of `open_ms` was spent after the state flip.
+ "open_frames": raw.get("openFrames"),
+ "open_state_reached_ms": raw.get("openStateReachedMs"),
+ "quiet_frames_required": raw.get("quietFramesRequired"),
},
- timings = {"open_ms": raw["openMs"], "close_ms": raw["closeMs"]},
- reason = None
- if ok
- else f"{raw['openCount']} of {raw['panes']} panes opened and "
- f"{raw['afterClose']} were still open after collapsing",
+ timings = timings,
+ reason = None if ok else "; ".join(failures),
)
@@ -535,10 +710,19 @@ def reasoning_toggle_one(ctx: ActionContext) -> ActionResult:
ran = True,
expect_ok = ok,
expect = {
- # `panes` is context, not an assertion: this action opens one of them whatever the
- # thread holds, which is the whole point of it existing beside `reasoning_toggle`.
+ # SCOPED TO WHAT IS MOUNTED, and always was. `reasoningTriggers()` is a
+ # querySelectorAll, so on the shipped build it finds every pane in the thread and on a
+ # windowed mount it finds the panes in the window. The assertion below stays
+ # self-consistent either way (it opens N and expects N open), so the action still
+ # passes -- but its COST silently stops being a function of thread length and becomes
+ # a function of window size. That is the arm's point, and it is also the reason this
+ # timing is not comparable between a windowed arm and a full one without the pane
+ # count beside it.
"panes": raw["panes"],
"panes_scope": "mounted",
+ # `panes_opened` is the assertion the two above are context for: this action opens
+ # exactly one pane whatever the thread holds, which is the whole point of it existing
+ # beside `reasoning_toggle`. Asserted by test_studiobench_reasoning_one_live.
"panes_opened": 1,
"open_after_expand": raw["openCount"],
"open_after_collapse": raw["afterClose"],
diff --git a/tests/studio/studiobench/scene/dom.js b/tests/studio/studiobench/scene/dom.js
index e9a0e751581..6843bb4414e 100644
--- a/tests/studio/studiobench/scene/dom.js
+++ b/tests/studio/studiobench/scene/dom.js
@@ -152,6 +152,23 @@
// content mounted for the animation, so a presence check reads every pane as open.
return qa('[data-slot="reasoning-root"][data-state="open"]').length;
},
+ // STILL MOUNTED IS NOT THE SAME AS STILL OPEN, and closing needs the other one.
+ //
+ // `reasoningOpenCount` flips on the click, because `data-state` is the state. The CHILDREN
+ // outlive it on both collapse mechanisms and by design: Radix's `Presence` suspends the
+ // unmount until `animationend` of `animate-collapsible-up`, and the grid arm's
+ // `UnmeasuredCollapsibleContent` renders `present && children` until the `grid-template-rows`
+ // `transitionend` or its 250 ms backstop. For that whole window every pane is closed, every
+ // span it contributed is still in the document, and a census asked whether it has stopped
+ // moving answers yes -- because it has not started.
+ //
+ // So a collapse is settled when the content is GONE, which is what this counts. Both arms are
+ // covered by one selector: Radix removes the element, the grid arm leaves it behind with
+ // `hidden`, and neither is a mounted pane.
+ reasoningContentMounted() {
+ return qa('[data-slot="reasoning-content"]').filter((el) => !el.hasAttribute("hidden"))
+ .length;
+ },
// ── action bar ───────────────────────────────────────────────
actionBar(message) {
diff --git a/tests/studio/studiobench/scene/schedule.py b/tests/studio/studiobench/scene/schedule.py
index 8a5399dba36..cc5a8b7b628 100644
--- a/tests/studio/studiobench/scene/schedule.py
+++ b/tests/studio/studiobench/scene/schedule.py
@@ -150,11 +150,18 @@ QUICK = Scene(
("stop_generation", 20_000, 3_000),
("scroll_after", 23_500, 2_500),
("reasoning_toggle", 26_500, 4_500),
- ("send_turn", 31_500, 4_000),
+ # 1,500 rather than 4,000, and the reason is the gap AFTER it rather than the cost of
+ # the send itself. `send_turn` is a sub-100 ms action; a 4,000 ms window to start in is
+ # not headroom, it is permission to begin the follow-up four seconds late without
+ # recording a miss. The drain runs from when the send actually fires, so every one of
+ # those four seconds comes off `message_menu`'s window: measured from the latest legal
+ # send, this film left 3,500 ms for a 4,562 ms drain. The fast film had the same shape
+ # and CI failed on it. See test_settled_actions_open_after_the_follow_up_drains.
+ ("send_turn", 31_500, 1_500),
("message_menu", 36_000, 3_000),
("copy_markdown", 39_500, 2_500),
("select_text", 42_500, 2_000),
- ("send_turn", 45_000, 4_000),
+ ("send_turn", 45_000, 1_500),
("select_all_copy", 49_500, 6_000),
("composer_fill", 56_000, 2_500),
("model_change", 59_000, 2_500),
@@ -221,25 +228,40 @@ FAST = Scene(
("scroll_during_generation", 6_000, 1_200),
("stop_generation", 18_400, 3_000),
("scroll_after", 21_500, 1_200),
- ("reasoning_toggle", 23_000, 3_500),
- ("send_turn", 26_700, 1_500),
- ("message_menu", 32_000, 800),
- ("copy_markdown", 33_000, 600),
- ("select_text", 33_800, 400),
- ("send_turn", 34_400, 1_500),
- ("select_all_copy", 39_500, 4_000),
- ("composer_fill", 43_700, 600),
- ("model_change", 44_500, 1_000),
- ("settings", 45_700, 1_200),
- ("image_upload", 47_100, 800),
+ # THE BUDGET IS SIZED FROM WHAT CI MEASURES, not from the null control's 2,250 ms.
+ # On the GitHub runner this action costs 4,415.9 ms and 4,434.4 ms on two consecutive
+ # jobs -- reaching the open state alone takes 2,898.8 ms there, which already exceeds
+ # the whole-action figure the 3,500 ms budget was derived from. At 3,500 it overran by
+ # 934 ms on every run, and an overrun here lands on `send_turn`, the one slot whose
+ # downstream gap is load-bearing. 5,000 ms covers the measured cost with room.
+ ("reasoning_toggle", 23_000, 5_000),
+ # MOVED OUT FROM UNDER `reasoning_toggle`, which now nominally ends at 28,000. A send
+ # slot that opens before the action before it can finish is a slot that starts late,
+ # and a send that starts late shortens the drain window of everything after it while
+ # reporting no miss of its own.
+ ("send_turn", 28_100, 1_500),
+ # THE GAP IS THE POINT, and it is measured from 29,600 -- the latest this film's send
+ # can fire -- not from 28,100. The follow-up drains in 4,562 ms nominal and 4,400 to
+ # 4,700 ms observed, so a window closing at 35,400 leaves about 1.1 s of real margin
+ # against the worst drain seen. The old packing left 38 ms, which is why CI failed on
+ # a runner no slower than the one that passed.
+ ("message_menu", 34_400, 1_000),
+ ("copy_markdown", 35_400, 600),
+ ("select_text", 36_200, 400),
+ ("send_turn", 36_800, 1_500),
+ ("select_all_copy", 41_900, 4_000),
+ ("composer_fill", 46_100, 600),
+ ("model_change", 46_900, 1_000),
+ ("settings", 48_100, 1_200),
+ ("image_upload", 49_500, 800),
# thread_reopen 6.5 s and delete 2.5 s, not 5 s and 0.6 s. Measured at 100K the pair
# costs about 3.2 s, but the ACTION overran its 5 s window and pushed the last slot: the
# machine arrived at delete_message 834 ms after its 600 ms budget had already closed, so
# on a 36 job sweep delete recorded NOT EXERCISED on the base arm of every null-control
# cell. A last slot with no slack is a slot that measures nothing, and the film's own end
# is the one place an overrun has nowhere to go.
- ("thread_reopen", 48_100, 6_500),
- ("delete_message", 54_800, 2_500),
+ ("thread_reopen", 50_500, 6_500),
+ ("delete_message", 57_200, 2_500),
]
),
)
diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_settle_js.py b/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_settle_js.py
new file mode 100644
index 00000000000..b3cbce9c544
--- /dev/null
+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_settle_js.py
@@ -0,0 +1,371 @@
+# 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 settle loop inside `REASONING_JS`, executed rather than described.
+
+WHY THIS FILE EXISTS. The settling fix is a change to a piece of JAVASCRIPT, and the Python tests
+beside it drive `reasoning_toggle` through a stubbed `evaluate` that returns a canned reply. Those
+tests pin how the Python wrapper reads a reply; they cannot see the loop that produces one. So the
+loop shipped with a defect that inverted the entire fix, and every test still passed:
+
+ `quiet` counted consecutive frames on which the span census had not moved, starting from the
+ FIRST frame of the wait. Whenever the panes needed `quietFrames` or more frames to reach the
+ open state -- with the census necessarily static through them, because the content it would
+ count has not been revealed yet -- the streak was already satisfied on the very frame the state
+ flipped, and the census was read exactly where the unfixed code read it.
+
+That is not a corner. It is the normal shape at the rungs this was written for: the catalogue's own
+500K reading is "the open count reached 16 after 10440ms", which is hundreds of static frames. Run
+against a page whose state flips at frame 6 and whose spans keep mounting to frame 40, the shipped
+loop returned 44,075 with `censored: false` -- the withdrawn number, reported confidently, out of
+the code whose purpose is to stop it.
+
+WHAT IS AND IS NOT COVERED HERE. `reasoningTriggers` and `reasoningOpenCount` are shimmed, so this
+does not test that `dom.js` finds the right elements. What it tests is the part that decides WHEN
+to read, which is the whole of the fix and the whole of the defect. The clock and the paint pump
+are shimmed too, so a frame here is a step rather than 16 ms of wall time; the loop's own budget
+arithmetic runs unmodified against them.
+
+If node is missing the tests SKIP rather than passing on a Python re-implementation, which would be
+a second copy of the instrument to get wrong.
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.scene.actions import REASONING_JS, SETTLE_QUIET_FRAMES # noqa: E402
+
+PANES = 16
+SPANS_BEFORE = 44075 # what the grid arm read at the state flip, and had to stop reading
+SPANS_SETTLED = 74250 # what both arms read once the mount finished
+
+HARNESS_JS = r"""
+const fs = require("fs");
+const src = fs.readFileSync(process.argv[2], "utf8");
+const cfg = JSON.parse(process.argv[3]);
+
+// ── a page whose state flip and whose content mount are SEPARATE events ────────────────────────
+//
+// That separation is the entire subject. `data-state` flips when the Collapsible's state changes;
+// the spans it reveals mount later, and how much later depends on the collapse mechanism, which is
+// the thing an A/B across a collapse change is comparing.
+let frame = 0;
+let now = 0;
+const PAINT_MS = 16;
+
+// Frames are counted per settle() call: the close phase gets its own clock, as it does in the app.
+let phaseStart = 0;
+const f = () => frame - phaseStart;
+
+let closing = false;
+let triggerReads = 0;
+
+// THE CLOSE PHASE HAS THE SAME SEPARATION, RUNNING THE OTHER WAY. `data-state` flips on the click;
+// the children stay in the document until the exit animation ends, so the census does not move at
+// all for `closeUnmountFrame` frames and then drops in one step. `closeUnmountFrame = 0` is the
+// page the shim used to model, where the teardown is instantaneous.
+const spanCount = () => {
+ if (closing) {
+ return f() >= cfg.closeUnmountFrame ? cfg.spansBefore : cfg.spansSettled;
+ }
+ if (cfg.spansStatic) return cfg.spansBefore;
+ if (f() < cfg.flipFrame) return cfg.spansBefore; // STATIC before the flip
+ if (f() >= cfg.mountDoneFrame) return cfg.spansSettled;
+ const t = (f() - cfg.flipFrame) / (cfg.mountDoneFrame - cfg.flipFrame);
+ return Math.round(cfg.spansBefore + t * (cfg.spansSettled - cfg.spansBefore));
+};
+
+// How many reasoning panes still have their content in the document. Open panes are mounted; a
+// closed one stays mounted until its exit animation finishes.
+const mountedCount = () => {
+ if (closing) return f() >= cfg.closeUnmountFrame ? 0 : cfg.panes;
+ return f() >= cfg.flipFrame ? cfg.panes : 0;
+};
+
+const openCount = () => {
+ if (closing) return 0;
+ if (f() < cfg.flipFrame) return 0;
+ // `loseStateAfter` drops the count back below `want` once it has been reached, so a run that
+ // oscillates around the target cannot bank quiet frames it never held.
+ if (cfg.loseStateAfter && f() >= cfg.flipFrame + cfg.loseStateAfter
+ && f() < cfg.flipFrame + cfg.loseStateAfter + cfg.loseStateFor) {
+ return cfg.panes - 1;
+ }
+ return cfg.panes;
+};
+
+globalThis.performance = { now: () => now };
+globalThis.document = {
+ querySelectorAll: (sel) => ({ length: sel === "pre span" ? spanCount() : 0 }),
+};
+globalThis.window = {
+ __sbNextPaint: async () => { frame += 1; now += PAINT_MS; },
+ __sb: { dom: {
+ // The click handler costs real time, because it is the app's own handler running
+ // synchronously and it is the first half of what "opening the panes" means.
+ // THE SECOND CALL IS THE CLOSE. `REASONING_JS` reads the triggers once to open and once more
+ // to collapse, so asking for them again is the shim's signal to enter its close phase and
+ // restart the per-phase frame clock. It used to be a flag that nothing ever set, which left
+ // every close settle waiting for an open count that never fell and censoring itself -- so the
+ // close direction was, in effect, not exercised at all.
+ reasoningTriggers: () => {
+ triggerReads += 1;
+ if (triggerReads === 2) { closing = true; phaseStart = frame; }
+ return Array.from({ length: cfg.panes }, () => ({
+ click: () => { now += cfg.clickMs; },
+ }));
+ },
+ reasoningOpenCount: () => openCount(),
+ reasoningContentMounted: () => mountedCount(),
+ } },
+};
+
+const fn = eval("(" + src.trim() + ")");
+
+fn([cfg.timeoutMs, cfg.quietFrames]).then((out) => {
+ console.log(JSON.stringify(out));
+ process.exit(0);
+}, (err) => { console.error(String((err && err.stack) || err)); process.exit(1); });
+"""
+
+
+def _node() -> str:
+ exe = shutil.which("node") or shutil.which("nodejs")
+ if exe is None:
+ pytest.skip(
+ "node is not installed, so the shipped REASONING_JS could not be evaluated; "
+ "this is NOT MEASURED rather than passing"
+ )
+ return exe
+
+
+def run_settle(
+ flip_frame: int,
+ mount_done_frame: int,
+ *,
+ timeout_ms: int = 8000,
+ quiet_frames: int = SETTLE_QUIET_FRAMES,
+ spans_static: bool = False,
+ lose_state_after: int = 0,
+ lose_state_for: int = 0,
+ click_ms: float = 0.0,
+ close_unmount_frame: int = 0,
+) -> dict:
+ """Run the SHIPPED `REASONING_JS` against a page with a late flip and a later mount."""
+ exe = _node()
+ cfg = {
+ "panes": PANES,
+ "clickMs": click_ms,
+ "flipFrame": flip_frame,
+ "mountDoneFrame": mount_done_frame,
+ "spansBefore": SPANS_BEFORE,
+ "spansSettled": SPANS_SETTLED,
+ "spansStatic": spans_static,
+ "loseStateAfter": lose_state_after,
+ "loseStateFor": lose_state_for,
+ "closeUnmountFrame": close_unmount_frame,
+ "timeoutMs": timeout_ms,
+ "quietFrames": quiet_frames,
+ }
+ with tempfile.TemporaryDirectory() as tmp:
+ harness = Path(tmp) / "harness.js"
+ harness.write_text(HARNESS_JS, encoding = "utf-8")
+ js = Path(tmp) / "reasoning.js"
+ js.write_text(REASONING_JS, encoding = "utf-8")
+ got = subprocess.run(
+ [exe, str(harness), str(js), json.dumps(cfg)],
+ capture_output = True,
+ text = True,
+ timeout = 120,
+ )
+ assert got.returncode == 0, f"node failed:\n{got.stderr}"
+ return json.loads(got.stdout.strip().splitlines()[-1])
+
+
+def test_a_slow_state_flip_does_not_bank_quiet_frames_before_it():
+ """THE REGRESSION. The census must not be read on the frame the state flips.
+
+ The panes take six frames to reach the open state and the census is static through all of
+ them, so a streak counted from frame one is already satisfied when the state arrives. Reading
+ there gives 44,075 -- the number this whole change exists to retract -- and gives it with
+ `censored: false`, which is worse than giving nothing.
+ """
+ out = run_settle(flip_frame = 6, mount_done_frame = 40)
+ assert out["spansOpen"] != SPANS_BEFORE, (
+ "the span census was read on the frame the state flipped, before the content it counts "
+ "had mounted. That is the defect the settling fix exists to remove, reproduced inside "
+ "the fix itself."
+ )
+ assert out["spansOpen"] == SPANS_SETTLED
+ assert out["openCensored"] is False
+ # The flip and the settled read are different moments, and both are reported so a reader can
+ # see how much of open_ms was spent after the state arrived.
+ assert out["openStateReachedMs"] < out["openMs"]
+
+
+def test_the_streak_requires_that_many_frames_after_the_flip():
+ """The quiet window is measured from the flip, so the read lands after the mount finishes."""
+ out = run_settle(flip_frame = 6, mount_done_frame = 40)
+ # The census stops moving at frame 40; the streak then needs SETTLE_QUIET_FRAMES more.
+ assert out["openFrames"] >= 40 + SETTLE_QUIET_FRAMES
+ assert out["quietFramesRequired"] == SETTLE_QUIET_FRAMES
+
+
+def test_a_census_that_never_goes_quiet_is_withheld_with_a_reason():
+ """Silence beats a confident wrong answer: no number, and a reason naming the budget."""
+ # Spans still climbing when the budget runs out: 8000ms / 16ms = 500 frames.
+ out = run_settle(flip_frame = 6, mount_done_frame = 100_000)
+ assert out["spansOpen"] is None
+ assert out["openMs"] is None
+ assert out["openCensored"] is True
+ assert "still changing" in out["openCensoredReason"]
+ # It reached the state, so the reason must say THAT rather than blaming the open count.
+ assert out["openStateReachedMs"] is not None
+
+
+def test_a_state_that_is_never_reached_says_so_instead():
+ """The other censoring reason, so the two failures are not reported as one."""
+ out = run_settle(flip_frame = 100_000, mount_done_frame = 100_001)
+ assert out["openCensored"] is True
+ assert "never reached" in out["openCensoredReason"]
+ assert out["openStateReachedMs"] is None
+
+
+def test_a_page_that_is_already_settled_still_returns_promptly():
+ """The refusal must not swallow the easy case, or every fast reading disappears.
+
+ A page whose panes flip on the first frame and whose census never moves is the cheapest
+ possible reading. It has to come back quickly and uncensored, or the fix has traded a wrong
+ number for no number at all.
+ """
+ out = run_settle(flip_frame = 1, mount_done_frame = 2, spans_static = True)
+ assert out["openCensored"] is False
+ assert out["spansOpen"] == SPANS_BEFORE
+ assert out["openFrames"] <= 1 + SETTLE_QUIET_FRAMES + 1
+
+
+def test_losing_the_state_restarts_the_streak():
+ """A count that oscillates around the target must not bank the frames it did not hold.
+
+ Without this the loop could reach `want`, drop below it while the DOM churned, and still
+ return on a streak accumulated across the gap -- reading a document that was mid-change.
+ """
+ out = run_settle(
+ flip_frame = 2,
+ mount_done_frame = 3,
+ spans_static = True,
+ lose_state_after = 1,
+ lose_state_for = 6,
+ )
+ assert out["openCensored"] is False
+ # It cannot have returned during the window where the count was below `want`.
+ assert out["openFrames"] >= 2 + 1 + 6
+
+
+def test_the_timing_includes_the_click_dispatch_it_names():
+ """`open_ms` must cover the clicks, not just the wait that follows them.
+
+ `t.click()` runs the app's own handler synchronously, and on a long thread that is React state
+ plus layout, once per pane. It is the first half of opening the panes. A timing that starts
+ after the whole loop has returned is a smaller number for the same action, and it moves for a
+ reason a reader cannot see: an arm that makes the handler slower and the settle faster would
+ look unchanged, or better.
+
+ With a 40 ms handler on 16 panes the settle alone reads 96 ms against 640 ms of dispatch it had
+ just performed.
+ """
+ out = run_settle(flip_frame = 2, mount_done_frame = 3, spans_static = True, click_ms = 40.0)
+ dispatch = PANES * 40.0
+ assert out["openDispatchMs"] == dispatch
+ assert out["openMs"] >= dispatch, (
+ "open_ms excluded the click dispatch, so it names an operation larger than the one it "
+ "measures. That is this branch's own defect, committed by the fix for it."
+ )
+ # And the two halves are reported apart, because they answer different questions.
+ assert out["openMs"] == pytest.approx(out["openDispatchMs"] + out["openSettleMs"], abs = 0.2)
+ assert out["openSettleMs"] < out["openMs"]
+
+
+def test_the_state_reached_mark_shares_the_timing_origin():
+ """`open_state_reached_ms` is quoted against `open_ms`, so it cannot start from a later zero."""
+ out = run_settle(flip_frame = 3, mount_done_frame = 20, click_ms = 25.0)
+ dispatch = PANES * 25.0
+ assert out["openStateReachedMs"] >= dispatch, (
+ "the state-reached mark was measured from the settle's start while open_ms was measured "
+ "from before the clicks, so subtracting one from the other yields a phantom interval"
+ )
+ assert out["openStateReachedMs"] <= out["openMs"]
+
+
+# ── the close direction ─────────────────────────────────────────────────────────────────────────
+#
+# The same defect the quiet streak fixes for the open direction, arriving from the other side.
+# `data-state` flips on the click, and BOTH collapse mechanisms keep the children in the document
+# until the exit animation ends: Radix's `Presence` until `animationend`, the grid arm's
+# `UnmeasuredCollapsibleContent` until the `grid-template-rows` `transitionend` or its 250 ms
+# backstop. So `pre span` is frozen at its open value for that whole window, and a streak that only
+# asks whether the census has stopped moving is satisfied by a census that has not started.
+
+
+def test_a_collapse_is_not_settled_while_its_panes_are_still_mounted():
+ """THE REGRESSION. `close_ms` must not name the state flip plus four frames.
+
+ Twelve frames of exit animation is 192 ms at this shim's 16 ms paint, which is the duration
+ both arms actually run. Four quiet frames fit inside it with room to spare, so the unfixed loop
+ returns while every span it would have counted is still in the document -- a pre-settled point,
+ reported as a measurement of the collapse.
+ """
+ out = run_settle(flip_frame = 1, mount_done_frame = 2, close_unmount_frame = 12)
+ assert out["closeCensored"] is False
+ assert out["closeFrames"] >= 12 + SETTLE_QUIET_FRAMES, (
+ f"the close settle returned after {out['closeFrames']} frames, before the panes it had "
+ f"just collapsed unmounted at frame 12. close_ms then measures the state flip plus a "
+ f"quiet streak the teardown had not begun to disturb."
+ )
+
+
+def test_the_close_bias_does_not_depend_on_the_paint_interval():
+ """WHY IT IS A COMPARISON PROBLEM RATHER THAN AN OFFSET.
+
+ Whether the old streak ended before or after the teardown depended on the paint interval
+ against the animation duration -- and the paint interval is exactly what differs between the
+ arms and the rungs this instrument compares. A slow page whose teardown lands inside the streak
+ was measured to the unmount; a fast one was not. Both must now be measured to the unmount, so
+ the two readings mean the same thing.
+ """
+ fast_page = run_settle(flip_frame = 1, mount_done_frame = 2, close_unmount_frame = 20)
+ slow_page = run_settle(flip_frame = 1, mount_done_frame = 2, close_unmount_frame = 2)
+ assert fast_page["closeFrames"] >= 20 + SETTLE_QUIET_FRAMES
+ assert slow_page["closeFrames"] >= 2 + SETTLE_QUIET_FRAMES
+ # Both readings are the same quantity: the teardown, plus the streak that proves it is over.
+ assert fast_page["closeFrames"] - 20 == slow_page["closeFrames"] - 2
+
+
+def test_a_collapse_that_never_tears_down_is_censored_and_says_which_half_failed():
+ """Silence beats a confident wrong answer here too, and the reason has to be usable.
+
+ A pane that reports closed and never unmounts is a different finding from one that never
+ closed. Reported as "the open count never reached 0" it would send a reader to the wrong half
+ of the app.
+ """
+ out = run_settle(flip_frame = 1, mount_done_frame = 2, close_unmount_frame = 100_000)
+ assert out["closeCensored"] is True
+ assert out["closeMs"] is None
+ assert "still mounted" in out["closeCensoredReason"]
+
+
+def test_an_instant_teardown_still_returns_promptly():
+ """The control. The fix must not turn the cheap case into a censored one."""
+ out = run_settle(flip_frame = 1, mount_done_frame = 2, close_unmount_frame = 0)
+ assert out["closeCensored"] is False
+ assert out["closeFrames"] <= 1 + SETTLE_QUIET_FRAMES + 1
diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_settling.py b/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_settling.py
new file mode 100644
index 00000000000..2ef1f08a669
--- /dev/null
+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_settling.py
@@ -0,0 +1,190 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""`reasoning_toggle` must settle on a quiet DOM and say plainly when it could not.
+
+These drive the real `reasoning_toggle` with a stubbed page, so they fail on the tree before the
+fix for the RIGHT reason -- a wrong value or a wrong message -- rather than by failing to import.
+
+Two published wrong numbers came out of this one action:
+
+ * `highlight_spans_while_open` read on the frame `data-state` flipped gave 74,917 on the
+ measured-height arm and 44,075 on the grid-rows arm, an apparent 41% reduction. Settled, both
+ arms read 74,250. Its null control was 0.0% and could not have caught it, because a null runs
+ one bundle against itself and the skew cancels.
+ * `open_ms` terminated on that same flip, and above the 100K rung it never terminated at all, so
+ the metric silently became 100K-only.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+from tests.studio.studiobench.scene.actions import reasoning_toggle
+
+
+@dataclass
+class _Page:
+ """A page that returns a canned reply and remembers how it was called.
+
+ DELIBERATELY TOLERANT of both the old `timeoutMs` argument and the new
+ `[timeoutMs, quietFrames]` pair. If the stub rejected the old shape, every test below would
+ fail on the pre-fix tree for that reason alone, and none of them would demonstrate the
+ substantive defect they exist to pin. The argument shape has its own test.
+ """
+
+ reply: dict
+ last_arg: Any = None
+
+ def evaluate(
+ self,
+ script: str,
+ arg: Any = None,
+ ) -> Any:
+ self.last_arg = arg
+ return self.reply
+
+
+@dataclass
+class _Ctx:
+ page: _Page
+
+ def log(self, *_a: Any, **_k: Any) -> None:
+ return None
+
+
+def _run(reply: dict):
+ return reasoning_toggle(_Ctx(_Page(reply)))
+
+
+def test_the_settle_is_told_how_quiet_is_quiet_enough():
+ """A settle with no quiet-frame requirement is not a settle, it is a timeout."""
+ page = _Page(_settled_reply())
+ reasoning_toggle(_Ctx(page))
+ assert isinstance(page.last_arg, list) and len(page.last_arg) == 2, (
+ f"reasoning_toggle must pass [timeoutMs, quietFrames]; got {page.last_arg!r}. Terminating "
+ f"on a state attribute alone is what made the census 41% wrong on one arm."
+ )
+ assert page.last_arg[1] >= 1
+
+
+def _settled_reply(**over: Any) -> dict:
+ base = {
+ "ran": True,
+ "panes": 10,
+ "before": 0,
+ "openCount": 10,
+ "afterClose": 0,
+ "spansOpen": 74250,
+ "spansOpenReason": None,
+ "openMs": 1777.8,
+ "closeMs": 596.9,
+ "openCensored": False,
+ "closeCensored": False,
+ "openCensoredReason": None,
+ "closeCensoredReason": None,
+ "openFrames": 42,
+ "closeFrames": 18,
+ "openStateReachedMs": 900.0,
+ "quietFramesRequired": 4,
+ "timeoutMs": 8000,
+ }
+ base.update(over)
+ return base
+
+
+def test_a_settled_toggle_reports_its_census_and_passes():
+ res = _run(_settled_reply())
+ assert res.ran and res.expect_ok
+ assert res.reason is None
+ assert res.expect["highlight_spans_while_open"] == 74250
+ assert res.expect["settled"] is True
+ assert res.timings == {"open_ms": 1777.8, "close_ms": 596.9}
+
+
+def test_an_unsettled_census_is_withheld_rather_than_guessed():
+ """Silence beats a confident wrong answer.
+
+ This is the 44,075 case: the panes are open, the state attribute has flipped, and the spans
+ are still arriving. The old code returned the half-mounted count as though it were the answer.
+ """
+ res = _run(
+ _settled_reply(
+ spansOpen = None,
+ spansOpenReason = "the span census was still changing when the budget ran out",
+ openMs = None,
+ openCensored = True,
+ openCensoredReason = "the span census was still changing when the budget ran out",
+ )
+ )
+ assert res.expect["highlight_spans_while_open"] is None, (
+ "a span count read from a DOM that was still mounting was reported as a census. That is "
+ "the reading that produced an apparent 41% reduction between two trees that in fact "
+ "mount the same document."
+ )
+ assert res.expect["settled"] is False
+ assert res.expect["highlight_spans_while_open_reason"]
+
+
+def test_a_censored_timing_is_absent_not_none():
+ """A `None` in `timings` is dropped downstream and becomes an invisible missing cell."""
+ res = _run(
+ _settled_reply(openMs = None, openCensored = True, openCensoredReason = "never went quiet")
+ )
+ assert "open_ms" not in res.timings, (
+ "a censored timing must not be carried as a key at all; downstream it is dropped for "
+ "being non-numeric and the metric silently loses that cell"
+ )
+ assert res.timings["close_ms"] == 596.9
+ assert res.expect["open_censored"] is True
+ assert res.expect["open_censored_reason"] == "never went quiet"
+
+
+def test_the_failure_reason_names_the_clause_that_actually_failed():
+ """The exact message this replaces described a PASSING condition.
+
+ Observed repeatedly at 500K and 1M:
+ `ran EXPECT FAILED -- 16 of 16 panes opened and 0 were still open after collapsing`
+ Every clause of that describes success. The real cause was always a censored `open_ms`.
+ """
+ res = _run(
+ _settled_reply(
+ panes = 16,
+ openCount = 16,
+ afterClose = 0,
+ openMs = None,
+ openCensored = True,
+ openCensoredReason = "the open count reached 16 but the span census kept changing",
+ )
+ )
+ assert res.expect_ok is False
+ assert res.reason is not None
+ assert "censored" in res.reason, (
+ f"the reason must name the clause that failed; got {res.reason!r}, which is the old "
+ f"message describing a passing condition"
+ )
+ assert "16 of 16 panes opened" not in res.reason
+
+
+def test_a_genuine_pane_failure_still_names_the_panes():
+ res = _run(_settled_reply(openCount = 9, panes = 10))
+ assert res.expect_ok is False
+ assert "9 of 10" in res.reason
+
+
+def test_panes_left_open_after_collapse_are_reported():
+ res = _run(_settled_reply(afterClose = 3))
+ assert res.expect_ok is False
+ assert "still open after collapsing" in res.reason
+
+
+def test_the_ruler_resolution_is_reported_beside_the_timing():
+ """`open_ms` is quantised to the paint interval, so the frame count has to travel with it."""
+ res = _run(_settled_reply())
+ assert res.expect["open_frames"] == 42
+ assert res.expect["quiet_frames_required"] == 4
+ assert res.expect["open_state_reached_ms"] == 900.0, (
+ "how much of open_ms was spent AFTER the state attribute flipped is the whole difference "
+ "between the two arms, so it has to be visible in the payload"
+ )
diff --git a/tests/studio/studiobench/scoring/payload_rules.py b/tests/studio/studiobench/scoring/payload_rules.py
new file mode 100644
index 00000000000..fd2e7dface7
--- /dev/null
+++ b/tests/studio/studiobench/scoring/payload_rules.py
@@ -0,0 +1,364 @@
+# 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 rules every reader of a payload has to apply, in one place so nobody reimplements them.
+
+Four numbers were published from this harness and acted on before being withdrawn. All four came
+from the same mistake in different clothes: MEASURING AT A MOMENT WHOSE MEANING IS NOT STABLE
+ACROSS THE THINGS BEING COMPARED.
+
+ census_peak an action chosen by max(), racing its own teardown, so a
+ different action on each arm
+ orphaned window rows windows outlive their cell, so an unfinished film contributes
+ whichever phase it reached
+ highlight_spans_while_open read on the frame a state attribute flipped, which is a
+ different distance from "mounted" on each arm
+ reasoning_toggle.open_ms terminated on that same attribute flip, quantised to a paint
+ and censored at a timeout
+
+`floor_table.cell_metrics` already applied the completed-cell rule; nothing else did, and the one
+consumer that did not apply it produced a headline regression that did not exist. Hence this
+module: the rules are importable, not folklore.
+
+THE COMPANION RULE TO THE NULL CONTROL, which is what makes three of these survivable.
+
+ A null control cannot detect a bias it shares.
+
+A null runs one build against itself. Any skew that is symmetric between the two sides cancels
+exactly, so the null reads flat and certifies the metric. `highlight_spans_while_open` has a null
+of 0.0% at 100K and 500K, exact to the span -- and was still 41% wrong across two real arms,
+because the timing skew it carried was symmetric within the null and asymmetric between the arms.
+A flat null says "this measure is repeatable", never "this measure is comparable".
+"""
+
+from __future__ import annotations
+
+from typing import Any, Iterable
+
+#: Metrics that must never be differenced between two arms, and why.
+UNCOMPARABLE_ACROSS_ARMS: dict[str, str] = {
+ "census_peak": (
+ "chosen by a max() over per-action censuses that race the action's own teardown, so the "
+ "moment it describes differs between arms. Measured swing on a null control, same bundle "
+ "both sides: 70.1% within one arm."
+ ),
+}
+
+
+def completed_cell_ids(records: Iterable[dict]) -> set[str]:
+ """Cell ids whose film ran to the end.
+
+ A `window` row is written while the film runs; the `cell` row is written when it ends. So an
+ in-flight or aborted cell leaves a complete-looking set of window rows with no completed cell
+ owning them. Any analysis that reads window rows directly must intersect with this set.
+ """
+ return {
+ r.get("cell_id")
+ for r in records
+ if r.get("row_type") == "cell" and r.get("completed") and r.get("cell_id")
+ }
+
+
+def aborted_cell_ids(records: Iterable[dict]) -> set[str]:
+ """Cell ids explicitly marked as not having finished, from the terminal `cell_aborted` row."""
+ return {
+ r.get("cell_id")
+ for r in records
+ if r.get("row_type") == "cell_aborted" and r.get("cell_id")
+ }
+
+
+def windows_of_completed_cells(records: list[dict]) -> list[dict]:
+ """Every `window` row that belongs to a cell that finished. The only windows worth pooling.
+
+ REDUCED TO THE LATEST ATTEMPT FIRST, because a cell id is not unique across attempts. `--resume`
+ re-runs a cell that died under the SAME deterministic id in the SAME file under a new session,
+ so a completed retry puts that id in `done` and matching on the id alone hands back the dead
+ attempt's windows as well -- precisely the unfinished film this helper exists to exclude.
+
+ Measured on a payload written through the real Recorder, one aborted attempt at 28.7 fps and
+ its completed retry at 46.7 fps: the helper returned all 13 windows, and pushing its own output
+ through `_frame_measures` gave `max_frame_ms` 34.84 against the truth of 21.41, and a
+ `jank_index` of 2.719 against 0.000 -- a jank score invented entirely by the run that crashed.
+ `floor_table.cell_metrics` got this right on the same records, so the importable rule was wrong
+ where the older ad-hoc guard was right, which is the wrong way round for a module whose claim is
+ that the rules are not folklore.
+
+ `aborted_cell_ids` IS NOT A MITIGATION FOR THIS, and must not be subtracted from `done`: on that
+ payload the same cell id is in both sets, so `done - aborted` is empty and a reader who tries it
+ loses the good reading instead of the bad one.
+ """
+ from .from_payload import latest_attempt_rows
+
+ records = list(latest_attempt_rows(records))
+ done = completed_cell_ids(records)
+ return [r for r in records if r.get("row_type") == "window" and r.get("cell_id") in done]
+
+
+def censored_metrics(records: Iterable[dict]) -> dict[str, set[str]]:
+ """{metric: {cell_id, ...}} for timings that were censored rather than measured.
+
+ A censored timing is ABSENT from `timings`, and absence is invisible once the values are
+ pooled: the cells that survive are the fast ones, and their mean is survivorship bias wearing
+ a number. `reasoning_toggle.open_ms` is censored on every cell above the 100K rung, so a row
+ labelled `open_ms` on a 100K/500K/1M ladder is silently a 100K-only figure.
+
+ A TIMING IS ALSO UNAVAILABLE WHEN ITS ACTION WAS DISCARDED, which is the case that reaches
+ furthest. `_action_timings` drops every timing of an action whose `expect_ok` is False, so a
+ measurement that succeeded on its own terms still contributes nothing -- and nothing marked it.
+
+ `reasoning_toggle` is where this bites. `ok` is one conjunction over four clauses, so a
+ censored `open_ms` above 100K makes the whole action fail, and `close_ms` is thrown away with
+ it while `close_censored` stays False. On a 100K/500K ladder the close row was then pooled from
+ the 100K cells alone and printed under a bare metric name with no refusal, exactly the
+ survivorship bias the open row is marked for. The rule is not specific to that pair: an action
+ that was discarded contributes nothing, so every timing it carries is censored at that cell.
+ """
+ out: dict[str, set[str]] = {}
+ for r in records:
+ if r.get("row_type") != "action":
+ continue
+ action = r.get("action")
+ cell = r.get("cell_id")
+ expect = r.get("expect") or {}
+ for key, value in expect.items():
+ if key.endswith("_censored") and value:
+ metric = f"{action}.{key[:-len('_censored')]}_ms"
+ out.setdefault(metric, set()).add(cell)
+ # The row still CARRIES the timings the scoring layer refuses to read, so the names are
+ # known here even though the values will never be pooled.
+ if r.get("ran") and r.get("expect_ok") is False:
+ for key in r.get("timings") or {}:
+ out.setdefault(f"{action}.{key}", set()).add(cell)
+ return out
+
+
+def measured_cells(records: Iterable[dict], metric: str) -> set[str]:
+ """Completed cells on which `metric` actually produced a number.
+
+ Resolved the way `floor_table._action_timings` resolves it -- the action ran, its own assertion
+ did not fail, and the timing is a real number -- so this is the set the pooled mean is actually
+ built from rather than a second opinion about it.
+ """
+ action, _, key = metric.partition(".")
+ done = completed_cell_ids(records)
+ out: set[str] = set()
+ for r in records:
+ if r.get("row_type") != "action" or r.get("action") != action:
+ continue
+ if r.get("cell_id") not in done or not r.get("ran") or r.get("expect_ok") is False:
+ continue
+ value = (r.get("timings") or {}).get(key)
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ out.add(r.get("cell_id"))
+ return out
+
+
+def refuse_partial_censoring(records: list[dict], metric: str) -> str | None:
+ """Why `metric` must not be pooled across this payload, or None if it is safe.
+
+ PER CELL, NOT PER RUNG NAME. Censoring is decided cell by cell against a fixed budget, on a
+ metric whose own spread is 33 to 42%, so a rung sitting near that budget censors SOME of its
+ repetitions and not others -- which is the expected shape near the boundary, not a contrived
+ one. Comparing sets of rung names cannot see it: every rung appears in both sets, the refusal
+ stays silent, and `paired()` quietly keeps only the repetitions where both arms answered.
+
+ Measured on one rung with three of four treatment repetitions censored, the surviving pair
+ reported +10.0% on n=1 with a full SLOWER verdict, counted as a metric that cleared all three
+ gates. The true paired delta over all four repetitions was +35.7%. The censored repetitions
+ were the slow ones, which is exactly why they were censored, so what survives is not a sample
+ of the effect but a selection against it.
+
+ This module's own docstring already stated the rule in cell terms -- "the cells that survive
+ are the fast ones" -- and only the implementation reduced it to rung names.
+ """
+ censored = censored_metrics(records).get(metric, set())
+ done = completed_cell_ids(records)
+ censored = {c for c in censored if c in done}
+ if not censored:
+ return None
+ measured = measured_cells(records, metric)
+ if not measured:
+ # Censored everywhere it was attempted. Nothing survived to be biased, and there is no
+ # pooled number to refuse -- refusing here would fire on every payload that simply cannot
+ # answer, which is a different and much noisier rule than the one being enforced.
+ return None
+ rungs_censored = sorted({c.split(".", 1)[0] for c in censored if c})
+ rungs_measured = sorted({c.split(".", 1)[0] for c in measured if c})
+ where = (
+ f"at {rungs_censored} and measured at {rungs_measured}"
+ if set(rungs_censored) != set(rungs_measured)
+ else f"on {len(censored)} of {len(censored) + len(measured)} cells within {rungs_censored}"
+ )
+ return (
+ f"{metric} is censored {where}. Pooling what is left reports the cells that could answer "
+ f"as if they were the whole ladder, and the ones that could not are the slow ones."
+ )
+
+
+def refuse_uncomparable(metric: str) -> str | None:
+ """Why `metric` must not be differenced between arms, or None if it may be."""
+ for key, why in UNCOMPARABLE_ACROSS_ARMS.items():
+ if metric == key or metric.startswith(key + "."):
+ return f"{metric} is not comparable across arms: {why}"
+ return None
+
+
+def settled(action_row: dict) -> bool:
+ """Did this action's census come from a DOM that had stopped changing?"""
+ return bool((action_row.get("expect") or {}).get("settled"))
+
+
+def comparability_key(run_meta: dict) -> str:
+ """A short token over everything that must match for two payloads to be comparable.
+
+ KEYED ON THE COMPUTED CORPUS HASH, NOT ON THE HARNESS COMMIT. Two trees can both call
+ themselves studiobench and generate different corpora: one tree here ran a corpus hash that
+ was neither the branch's pre-fix hash nor its post-fix one, silently and self-consistently,
+ and the only reason anyone noticed is that the hash was printed and compared. A commit is a
+ claim about provenance; the computed hash is the thing itself.
+
+ `floor_table.load` already refuses to POOL across tiers and corpora. This exists for the case
+ that guard cannot reach: a comparison made in prose between two separately published runs.
+ Quote the token beside any number and the comparison becomes checkable after the fact.
+ """
+ import hashlib
+ import json
+
+ # COMPUTED OVER `comparability_fields`, not over a second copy of the same dict. The two were
+ # written out separately and had to be kept in step by hand, which is the drift this module
+ # exists to argue against: a field added to one and forgotten in the other would make the key
+ # and its own explanation disagree about what the key covers.
+ blob = json.dumps(comparability_fields(run_meta), sort_keys = True, default = str).encode()
+ return "cmp:" + hashlib.sha256(blob).hexdigest()[:10]
+
+
+def run_metas(records: Iterable[dict]) -> list[dict]:
+ """EVERY `run_meta` row in the payload, in the order written. There is rarely only one."""
+ return [r for r in records if r.get("row_type") == "run_meta"]
+
+
+def merged_run_meta(records: Iterable[dict]) -> tuple[dict | None, list[str]]:
+ """One `run_meta` describing the WHOLE payload, plus the disagreements that forbid one.
+
+ A payload is append-only and `--resume` writes a SECOND header behind the first, so reading
+ only the first describes the run that started the file rather than the cells now in it.
+ `floor_table` has been bitten by this twice and says so where it was fixed: "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." This is the same mistake in the one reader that was not converted.
+
+ `rungs` is UNIONED rather than compared, because extending the ladder is explicitly legitimate.
+ `IDENTITY_AXES` leaves `rungs` and `reps` out on purpose: "Resuming with more repetitions or
+ another rung is a legitimate continuation -- it ADDS cells rather than reinterpreting the ones
+ already recorded." A resumed payload really does describe the union, so the union is what a
+ later reader has to compare against.
+
+ Every OTHER key field is a conflict when the headers disagree, and three of them can differ
+ without `--resume` objecting: `engine` (`--engine` is free on resume), `tool_version` (a module
+ constant, so pulling a harness upgrade mid-campaign changes it), and anything the identity
+ check does not cover. A file whose own headers disagree on those is not one measurement, and no
+ single key can honestly stand for it.
+ """
+ metas = run_metas(records)
+ if not metas:
+ return None, []
+ merged = dict(metas[0])
+ rungs: list = []
+ for m in metas:
+ for rung in m.get("rungs") or []:
+ if rung not in rungs:
+ rungs.append(rung)
+ merged["rungs"] = rungs
+ base = comparability_fields(metas[0])
+ conflicts: list[str] = []
+ for m in metas[1:]:
+ other = comparability_fields(m)
+ for key in sorted(base):
+ if key == "rungs":
+ continue
+ if other.get(key) != base.get(key):
+ line = f"{key}: {base.get(key)!r} != {other.get(key)!r}"
+ if line not in conflicts:
+ conflicts.append(line)
+ return merged, conflicts
+
+
+def comparability_fields(run_meta: dict) -> dict:
+ """The fields the key is computed over, so a mismatch can be explained rather than asserted."""
+ platform = run_meta.get("platform") or {}
+ return {
+ "corpus_hash": run_meta.get("corpus_hash"),
+ "tier": run_meta.get("tier"),
+ "rungs": run_meta.get("rungs"),
+ "engine": platform.get("engine"),
+ "tool_version": run_meta.get("tool_version"),
+ "instrument_level": run_meta.get("instrument_level"),
+ "cadence": run_meta.get("cadence"),
+ "stream_tail_chars": run_meta.get("stream_tail_chars"),
+ "corpus_dollars": run_meta.get("corpus_dollars"),
+ # THE THREE THAT CHANGE WHAT IS MEASURED, not merely what is measured on. The harness
+ # already treats all three as identity axes that `--resume` refuses to toggle, and the
+ # `run_meta` emission says why in its own words -- so a key that ignored them would call
+ # two payloads comparable that the tool itself refuses to continue as one run.
+ #
+ # `inject_stream_cost_ms` is the sharpest: an arm running it is not a measurement of the
+ # build at all, because the harness put the slowdown there on purpose. Nothing in the
+ # scoring path refuses an injected payload, so `--compare` blessing it against a clean run
+ # was a live route to publishing a difference the harness itself created.
+ #
+ # `click_probe` is normalised through `bool` so a payload written before the field existed
+ # reads as False rather than None; the other two are `None` in the ordinary case already.
+ "click_probe": bool(run_meta.get("click_probe")),
+ "probe_init_script": run_meta.get("probe_init_script"),
+ "inject_stream_cost_ms": run_meta.get("inject_stream_cost_ms"),
+ # THE HOST, which the engine alone does not stand in for. `run_meta` records `system` and
+ # `machine` and the key took neither, so two payloads from different hardware and operating
+ # systems hashed the same and `--compare` blessed them.
+ #
+ # It needs no unusual invocation: `browser.default_engine()` returns webkit on Darwin AND
+ # on Linux, so a tester's Mac payload and the Linux dev box's payload, both with default
+ # settings, differ in `system`, `machine` and `engine_note` and were declared comparable.
+ # Only Windows was caught, and only incidentally, because its default engine differs.
+ #
+ # Nothing else in the tool refuses cross-host pooling: `floor_table.load` checks tier,
+ # corpus and probe only, and `platform` is not an identity axis. The sole existing
+ # statement is prose in `report/render.py` -- "machine-local; does not travel between
+ # machines" -- so the authors knew the hazard and the one guard meant to police a prose
+ # comparison was the place it was missing.
+ "system": platform.get("system"),
+ "machine": platform.get("machine"),
+ # AND WHICH PHYSICAL MACHINE, because the two fields above cannot say. `platform.machine()`
+ # is the ARCHITECTURE, not a machine identifier: on two ordinary Linux x86_64 hosts it
+ # returns `x86_64` on both while `system` returns `Linux` on both, so the pair that was
+ # added here to stand for the host caught only the cross-OS case -- a tester's Mac against
+ # the Linux dev box -- and left the commonest one, a dev box against a CI runner or a
+ # second dev box, hashing identically. `platform.node()` is the host's network name and is
+ # the field that separates them.
+ #
+ # This is the axis with the least slack in it: `floor_table.render` refuses a floor whose
+ # comparability fields differ from the payload's, in the words "a floor is the scatter of
+ # THIS measurement on THIS machine", and that refusal is computed from this dict. Without
+ # the host in it a null control measured on one machine certifies a result measured on
+ # another, which is the one comparison the report text says never travels.
+ #
+ # A payload recorded before this field existed carries None and is therefore not comparable
+ # with one that carries a host. That is the honest reading rather than a cost: such a
+ # payload does not record which machine produced it, so nothing can show it was this one.
+ "node": platform.get("node"),
+ # WHICH BROWSER BINARY DREW THE FRAMES, which `engine` does not settle. Since Playwright
+ # 1.57 headed and headless default to different executables -- `chrome` against
+ # `chrome-headless-shell` -- and headless falls back to software rendering for
+ # GPU-accelerated work while its compositor keeps its own pacing. For a tool whose output
+ # is frames, jank and time-to-settle, those are two different renderers under one engine
+ # name. Normalised through `bool` so a payload written before the field existed reads as
+ # the headless default rather than as None.
+ "headed": bool(run_meta.get("headed")),
+ }
+
+
+def explain_incomparable(a: dict, b: dict) -> list[str]:
+ """Which comparability fields differ between two `run_meta` rows."""
+ fa, fb = comparability_fields(a), comparability_fields(b)
+ return [
+ f"{k}: {fa[k]!r} != {fb[k]!r}" for k in sorted(set(fa) | set(fb)) if fa.get(k) != fb.get(k)
+ ]
diff --git a/tests/studio/studiobench/scoring/schema.py b/tests/studio/studiobench/scoring/schema.py
index 56e51e008c8..7e67bbcd1b2 100644
--- a/tests/studio/studiobench/scoring/schema.py
+++ b/tests/studio/studiobench/scoring/schema.py
@@ -135,6 +135,12 @@ EXEMPT_SUBTREE_KEYS = frozenset(
"env",
"identity",
"header",
+ # The comparability key's own section. `fields` is the identity block the key is hashed
+ # over -- `instrument_level`, `stream_tail_chars`, `corpus_dollars` -- every one of which
+ # is a true statement about how the run was configured rather than a measurement of the
+ # app, and every one of which is legitimately 0. Same rule as `identity` and `config`
+ # directly above.
+ "comparability",
"footer",
"record_counts",
"histogram",
diff --git a/tests/studio/studiobench/scoring/selftest/test_studiobench_payload_rules.py b/tests/studio/studiobench/scoring/selftest/test_studiobench_payload_rules.py
new file mode 100644
index 00000000000..f7ebe445630
--- /dev/null
+++ b/tests/studio/studiobench/scoring/selftest/test_studiobench_payload_rules.py
@@ -0,0 +1,639 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regression tests for four numbers this harness published and somebody acted on.
+
+Each test reproduces the SHAPE of the specific wrong number, not merely the class of bug, so that
+a future change which reintroduces the defect fails here rather than in a report two days later.
+Every one of them fails on the tree before `payload_rules` existed.
+
+The four share one root cause: measuring at a moment whose meaning is not stable across the things
+being compared.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from tests.studio.studiobench.scoring import payload_rules
+
+
+# ── defect 4: window rows outlive their cell ────────────────────────────────
+
+
+def _ladder_payload() -> list[dict]:
+ """A 100K rung that finished on both arms, and a 1M rung whose treatment cell did not.
+
+ The numbers are the ones from the run that produced the withdrawn headline: the completed 1M
+ cell emitted 6 `stream:gap` windows where 100K emitted 17, and the unfinished treatment cell
+ emitted 7 -- enough to look complete to a reader that does not check.
+ """
+ rows: list[dict] = []
+ for cell_id, n_windows, completed in (
+ ("r100K.base.rep0", 17, True),
+ ("r100K.treatment.rep0", 17, True),
+ ("r1M.base.rep0", 6, True),
+ ("r1M.treatment.rep0", 7, False),
+ ):
+ for i in range(n_windows):
+ rows.append(
+ {
+ "row_type": "window",
+ "cell_id": cell_id,
+ "name": f"stream:gap{i}",
+ "kind": "gap",
+ "instruments": {"frames": {"frames_attempted": True, "fps": 28.7}},
+ }
+ )
+ rows.append({"row_type": "cell", "cell_id": cell_id, "completed": completed})
+ if not completed:
+ rows.append({"row_type": "cell_aborted", "cell_id": cell_id, "reason": "budget"})
+ return rows
+
+
+def test_windows_of_an_unfinished_cell_are_not_offered_to_an_analysis():
+ rows = _ladder_payload()
+ kept = payload_rules.windows_of_completed_cells(rows)
+ cells = {w["cell_id"] for w in kept}
+ assert "r1M.treatment.rep0" not in cells, (
+ "windows from a cell that never finished were offered for pooling. Reading them is what "
+ "reported the 1M rung at 28.7 fps against a 46.7 fps baseline, a regression drawn "
+ "entirely from an unfinished film."
+ )
+ assert cells == {"r100K.base.rep0", "r100K.treatment.rep0", "r1M.base.rep0"}
+ assert len(kept) == 17 + 17 + 6
+
+
+def test_an_unfinished_cell_is_announced_by_a_terminal_row():
+ rows = _ladder_payload()
+ assert payload_rules.aborted_cell_ids(rows) == {"r1M.treatment.rep0"}, (
+ "a reader scanning forward must be able to discard an aborted cell's windows without "
+ "joining backwards to the cell row it may not have reached yet"
+ )
+
+
+def test_completed_cell_ids_ignores_rows_that_are_not_cells():
+ rows = _ladder_payload() + [{"row_type": "action", "cell_id": "r1M.treatment.rep0"}]
+ assert "r1M.treatment.rep0" not in payload_rules.completed_cell_ids(rows)
+
+
+# ── defect 1: census_peak is not comparable across arms ─────────────────────
+
+
+def test_census_peak_is_refused_for_cross_arm_comparison():
+ why = payload_rules.refuse_uncomparable("census_peak")
+ assert why is not None, (
+ "census_peak was offered for differencing across arms. It is chosen by a max() over "
+ "per-action censuses that race their own teardown, and on a NULL CONTROL -- one bundle "
+ "on both sides -- the winner flipped between `settings` (panes collapsed) and "
+ "`reasoning_toggle` (panes open), a 70.1% swing within one arm. Differencing it reported "
+ "main as mounting 48% more Shiki spans than a baseline that in fact mounts the same "
+ "document to within 0.3%."
+ )
+ assert "70.1%" in why
+ assert payload_rules.refuse_uncomparable("census_peak.highlight_spans") is not None
+
+
+def test_a_normal_metric_is_still_comparable():
+ assert payload_rules.refuse_uncomparable("select_all_copy.copy_ms") is None
+
+
+# ── defect 2: a metric censored at some rungs but not others ───────────────
+
+
+def _censored_payload() -> list[dict]:
+ """`open_ms` measured at 100K and censored at 500K, which is what the ladder actually did."""
+ rows: list[dict] = []
+ for cell_id, censored in (
+ ("r100K.base.rep0", False),
+ ("r100K.treatment.rep0", False),
+ ("r500K.base.rep0", True),
+ ("r500K.treatment.rep0", True),
+ ):
+ rows.append({"row_type": "cell", "cell_id": cell_id, "completed": True})
+ rows.append(
+ {
+ "row_type": "action",
+ "cell_id": cell_id,
+ "action": "reasoning_toggle",
+ "ran": True,
+ "expect": {
+ "open_censored": censored,
+ "close_censored": False,
+ "open_censored_reason": "the span census was still changing"
+ if censored
+ else None,
+ },
+ "timings": {} if censored else {"open_ms": 1777.8},
+ }
+ )
+ return rows
+
+
+def test_a_metric_censored_at_one_rung_is_refused_for_pooling():
+ rows = _censored_payload()
+ why = payload_rules.refuse_partial_censoring(rows, "reasoning_toggle.open_ms")
+ assert why is not None, (
+ "open_ms is censored on every cell above 100K, and a censored timing is simply ABSENT "
+ "from `timings`. Pooled, the ladder row silently becomes a 100K-only number wearing a "
+ "ladder label, and the cells that survive are the fast ones."
+ )
+ assert "r500K" in why and "r100K" in why
+
+
+def test_censored_cells_are_enumerable():
+ rows = _censored_payload()
+ censored = payload_rules.censored_metrics(rows)
+ assert censored["reasoning_toggle.open_ms"] == {"r500K.base.rep0", "r500K.treatment.rep0"}
+
+
+def test_a_metric_measured_everywhere_is_poolable():
+ rows = _censored_payload()
+ assert payload_rules.refuse_partial_censoring(rows, "reasoning_toggle.close_ms") is None
+
+
+# ── defect 7: a census is only a census if the DOM had settled ─────────────
+
+
+def test_an_unsettled_census_is_not_marked_settled():
+ unsettled = {
+ "row_type": "action",
+ "action": "reasoning_toggle",
+ "expect": {"settled": False, "highlight_spans_while_open": None},
+ }
+ settled = {
+ "row_type": "action",
+ "action": "reasoning_toggle",
+ "expect": {"settled": True, "highlight_spans_while_open": 74250},
+ }
+ assert not payload_rules.settled(unsettled)
+ assert payload_rules.settled(settled)
+
+
+# ── the comparability key ──────────────────────────────────────────────────
+
+
+def _meta(
+ corpus_hash: str,
+ tier: str = "full",
+ engine: str = "chromium",
+) -> dict:
+ return {
+ "row_type": "run_meta",
+ "corpus_hash": corpus_hash,
+ "tier": tier,
+ "rungs": ["100K", "500K", "1M"],
+ "tool_version": "0.1.0",
+ "instrument_level": 0,
+ "cadence": "field",
+ "stream_tail_chars": None,
+ "corpus_dollars": False,
+ "platform": {"engine": engine},
+ }
+
+
+def test_a_probed_or_calibration_run_is_not_comparable_with_a_clean_one():
+ """The three fields that change what is MEASURED, not merely what it is measured on.
+
+ All three are `IDENTITY_AXES`, which is to say `--resume` refuses to toggle them mid-payload.
+ A comparability key that ignored them would call two payloads comparable that the harness
+ itself refuses to continue as one run.
+
+ `inject_stream_cost_ms` is the one that could publish a number: an arm running it is not a
+ measurement of the build, because the harness added the slowdown deliberately, and nothing in
+ the scoring path refuses an injected payload. Blessing it against a clean run is a direct route
+ to reporting a difference the harness created.
+ """
+ corpus = "ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c"
+ clean = _meta(corpus)
+ for field, probed_value in (
+ ("inject_stream_cost_ms", 40.0),
+ ("click_probe", True),
+ ("probe_init_script", "/tmp/probe.js"),
+ ):
+ probed = _meta(corpus)
+ probed[field] = probed_value
+ assert payload_rules.comparability_key(clean) != payload_rules.comparability_key(probed), (
+ f"a run with {field}={probed_value!r} carries the same comparability key as a clean "
+ f"run, so `--compare` calls them comparable"
+ )
+ assert any(
+ line.startswith(f"{field}:")
+ for line in payload_rules.explain_incomparable(clean, probed)
+ )
+
+
+def test_a_payload_written_before_the_probe_fields_existed_still_matches_a_clean_run():
+ """`click_probe` normalises through bool, so a legacy payload is not gratuitously orphaned.
+
+ A refusal that invalidated every older payload would be a cost with no safety in it: absent
+ and False mean the same thing here, which is why the harness reads absence as a value.
+ """
+ corpus = "ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c"
+ legacy = _meta(corpus)
+ legacy.pop("click_probe", None)
+ current = _meta(corpus)
+ current["click_probe"] = False
+ assert payload_rules.comparability_key(legacy) == payload_rules.comparability_key(current)
+
+
+def test_a_resumed_payload_is_keyed_on_the_ladder_it_grew_into(tmp_path):
+ """Reading only the FIRST run_meta hashes a ladder the file has since outgrown.
+
+ `--resume` appends a second header, and it may legitimately have extended the ladder:
+ `IDENTITY_AXES` leaves `rungs` out on purpose because adding a rung ADDS cells rather than
+ reinterpreting recorded ones. Keyed on the first header, a payload resumed from one rung to two
+ carries the same key as the one-rung run it started as, and `--compare` pronounces them
+ comparable while the payload's own later comparability row says otherwise.
+ """
+ corpus = "ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c"
+ first = _meta(corpus)
+ first["rungs"] = ["100K"]
+ second = _meta(corpus)
+ second["rungs"] = ["100K", "500K"]
+
+ merged, conflicts = payload_rules.merged_run_meta([first, second])
+ assert conflicts == []
+ assert merged["rungs"] == [
+ "100K",
+ "500K",
+ ], "the merge kept the ladder the run STARTED with rather than the one the file describes"
+ one_rung = payload_rules.comparability_key(first)
+ assert payload_rules.comparability_key(merged) != one_rung
+
+
+def test_a_payload_whose_headers_disagree_has_no_key_at_all():
+ """Two runs in one file that were not measuring the same thing cannot share a token.
+
+ `tool_version` needs no exotic invocation to differ: resume a half-finished payload after
+ pulling a harness upgrade and header one reads 0.1.0 while header two reads 0.2.0. Neither
+ value describes the file.
+ """
+ corpus = "ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c"
+ before = _meta(corpus)
+ before["tool_version"] = "0.1.0"
+ after = _meta(corpus)
+ after["tool_version"] = "0.2.0"
+ _merged, conflicts = payload_rules.merged_run_meta([before, after])
+ assert conflicts == ["tool_version: '0.1.0' != '0.2.0'"]
+
+
+def test_the_key_is_computed_over_the_fields_it_explains():
+ """The token and its explanation must not be able to drift apart.
+
+ They were written as two separate dicts kept in step by hand. A field added to one and missed
+ in the other would make `--compare` hash something its own "these differ" list never mentions,
+ which is the provenance failure this module argues against, committed by the module itself.
+ """
+ corpus = "ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c"
+ a = _meta(corpus)
+ #: Fields the key reads out of the nested `platform` dict rather than off the row itself.
+ #: Written as a set rather than a single special case, because the single special case is what
+ #: had to be edited when `system` and `machine` were added -- and a test that needs editing to
+ #: keep passing when a field is added is a test that can be edited into silence instead.
+ nested = {"engine", "system", "machine", "node"}
+ for field in payload_rules.comparability_fields(a):
+ b = _meta(corpus)
+ if field in nested:
+ b["platform"] = dict(b.get("platform") or {})
+ b["platform"][field] = "CHANGED"
+ else:
+ b[field] = "CHANGED"
+ assert payload_rules.comparability_key(a) != payload_rules.comparability_key(
+ b
+ ), f"{field} is listed in comparability_fields but does not move the key"
+
+
+def test_a_payload_from_another_host_is_not_comparable():
+ """Two machines, default settings, everything else identical.
+
+ `browser.default_engine()` returns webkit on Darwin AND on Linux, so the engine field does not
+ stand in for the host: a tester's Mac payload and the Linux dev box's payload matched on every
+ field the key covered. Only Windows was caught, and only because its default engine differs.
+ """
+ corpus = "ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c"
+ linux = _meta(corpus)
+ linux["platform"] = {"engine": "webkit", "system": "Linux", "machine": "x86_64"}
+ macos = _meta(corpus)
+ macos["platform"] = {"engine": "webkit", "system": "Darwin", "machine": "arm64"}
+ assert payload_rules.comparability_key(linux) != payload_rules.comparability_key(macos)
+ differ = payload_rules.explain_incomparable(linux, macos)
+ assert any(line.startswith("system:") for line in differ)
+ assert any(line.startswith("machine:") for line in differ)
+
+
+def test_two_linux_boxes_are_not_one_host():
+ """The case `system` and `machine` cannot see, which is the commonest one there is.
+
+ `platform.machine()` returns the machine TYPE -- the architecture -- and `platform.system()`
+ the OS name, so two ordinary Linux x86_64 hosts report `Linux` and `x86_64` alike and hashed
+ to one key. The cross-OS pair above was caught and the dev-box-against-CI-runner pair, which
+ is what a team actually compares, was not: `--compare` printed "comparable: every field the
+ key covers matches" over two payloads from two machines, and `floor_table.render` computes its
+ own floor refusal from this same dict, so one machine's null control certified another
+ machine's result on a metric set whose report text reads "machine-local; does not travel
+ between machines".
+ """
+ corpus = "ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c"
+ here, there = _meta(corpus), _meta(corpus)
+ here["platform"] = {
+ "engine": "webkit",
+ "system": "Linux",
+ "machine": "x86_64",
+ "node": "devbox-a",
+ }
+ there["platform"] = {
+ "engine": "webkit",
+ "system": "Linux",
+ "machine": "x86_64",
+ "node": "ci-runner-7",
+ }
+ assert payload_rules.comparability_key(here) != payload_rules.comparability_key(there), (
+ "two different Linux x86_64 machines carry the same comparability key, so `--compare` "
+ "certifies one machine's numbers against the other's"
+ )
+ assert any(line.startswith("node:") for line in payload_rules.explain_incomparable(here, there))
+
+ same = _meta(corpus)
+ same["platform"] = dict(here["platform"])
+ assert payload_rules.comparability_key(here) == payload_rules.comparability_key(
+ same
+ ), "the same host on the same settings must still be comparable with itself"
+
+
+def test_two_payloads_from_before_the_host_was_recorded_still_match_each_other():
+ """Absence is not a wildcard, but it is consistent: two legacy payloads still share a key.
+
+ A payload recorded before `node` was written carries None, so it is not comparable with one
+ that names a host -- it cannot show which machine produced it, and that refusal is the honest
+ answer rather than a cost. What it must not do is stop matching other payloads of its own age.
+ """
+ corpus = "ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c"
+ a, b = _meta(corpus), _meta(corpus)
+ for row in (a, b):
+ row["platform"] = {"engine": "webkit", "system": "Linux", "machine": "x86_64"}
+ assert payload_rules.comparability_key(a) == payload_rules.comparability_key(b)
+ named = _meta(corpus)
+ named["platform"] = {
+ "engine": "webkit",
+ "system": "Linux",
+ "machine": "x86_64",
+ "node": "devbox-a",
+ }
+ assert payload_rules.comparability_key(a) != payload_rules.comparability_key(named)
+
+
+def test_the_harness_records_the_host_it_ran_on():
+ """The key can only cover a field the producer writes, and this one is written.
+
+ `comparability_fields` reading `platform.node` is inert unless `run_meta` carries it, which is
+ the shape of the defect this fixes: a field named in the key and absent from the payload is
+ None on both sides and separates nothing.
+ """
+ import platform as _platform
+
+ from tests.studio.studiobench import __main__ as sb_main
+
+ source = Path(sb_main.__file__).read_text(encoding = "utf-8")
+ assert "platform.node()" in source, (
+ "run_meta does not record the host, so the `node` field of the comparability key is None "
+ "on every payload and cannot separate two machines"
+ )
+ assert isinstance(_platform.node(), str)
+
+
+def test_a_run_from_before_the_settling_fix_is_not_comparable_with_one_from_after():
+ """The corpus did not change here, so `tool_version` is the only field that can separate them.
+
+ This change redefines two published measures on an UNCHANGED corpus:
+ `highlight_spans_while_open` reads 74,250 where it read 44,075 on the same bundle, and
+ `open_ms` now terminates on a settled mount rather than on the `data-state` flip. Every other
+ field the key covers -- corpus hash, tier, rungs, engine, cadence -- is identical across the
+ change. If the key could not tell those two runs apart it would certify as comparable the pair
+ that differs by the largest instrument change in the campaign, which is the failure it exists
+ to prevent.
+ """
+ corpus = "ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c"
+ before = _meta(corpus)
+ before["tool_version"] = "0.1.0"
+ after = _meta(corpus)
+ after["tool_version"] = "0.2.0"
+ assert payload_rules.comparability_key(before) != payload_rules.comparability_key(after)
+ assert payload_rules.explain_incomparable(before, after) == ["tool_version: '0.1.0' != '0.2.0'"]
+
+
+def test_the_shipping_tool_version_is_the_settled_one():
+ """The bump has to be on the constant the harness actually stamps, not only in a fixture."""
+ from tests.studio.studiobench.__main__ import TOOL_VERSION
+ assert TOOL_VERSION != "0.1.0", (
+ "TOOL_VERSION still reads 0.1.0, so every payload written after the settling fix carries "
+ "the same comparability key as one written before it, and `--compare` reports the two as "
+ "comparable."
+ )
+
+
+def test_the_key_is_keyed_on_the_computed_corpus_hash_not_the_harness_commit():
+ old = _meta("f113503e6cea3574e9c1a99653ee140904ab24f7606505f9e0d8d66efda96070")
+ new = _meta("ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c")
+ assert payload_rules.comparability_key(old) != payload_rules.comparability_key(new), (
+ "two runs on different corpora produced the same comparability key. A tree in this "
+ "campaign ran a third corpus, silently and self-consistently, and the only reason anyone "
+ "noticed is that the hash was printed. A commit is a claim; the hash is the thing."
+ )
+ assert payload_rules.explain_incomparable(old, new) == [
+ "corpus_hash: 'f113503e6cea3574e9c1a99653ee140904ab24f7606505f9e0d8d66efda96070' != "
+ "'ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c'"
+ ]
+
+
+def test_the_key_is_stable_for_identical_runs():
+ a = _meta("ac9d5d8e")
+ b = _meta("ac9d5d8e")
+ assert payload_rules.comparability_key(a) == payload_rules.comparability_key(b)
+ assert payload_rules.explain_incomparable(a, b) == []
+
+
+def test_the_key_moves_with_the_engine_and_the_tier():
+ base = _meta("ac9d5d8e")
+ assert payload_rules.comparability_key(base) != payload_rules.comparability_key(
+ _meta("ac9d5d8e", engine = "webkit")
+ )
+ assert payload_rules.comparability_key(base) != payload_rules.comparability_key(
+ _meta("ac9d5d8e", tier = "standard")
+ )
+
+
+def test_the_key_looks_like_a_token_that_can_be_quoted():
+ key = payload_rules.comparability_key(_meta("ac9d5d8e"))
+ assert key.startswith("cmp:") and len(key) == len("cmp:") + 10
+
+
+# ── window rows must belong to the attempt that finished, not merely to the id ──
+
+
+def _resumed_window_payload() -> list[dict]:
+ """One cell that died at 28.7 fps and its completed retry at 46.7 fps, same cell id.
+
+ `--resume` re-runs a died cell under the SAME deterministic id into the SAME file under a new
+ session, so this is the ordinary shape of any resumed run, not a corner case.
+ """
+ cid = "r1M.treatment.rep0"
+
+ def win(session: str, i: int, fps: float, frame_ms: float) -> dict:
+ return {
+ "row_type": "window",
+ "cell_id": cid,
+ "session_id": session,
+ "name": f"stream:gap{i}",
+ "kind": "gap",
+ "t_open_ms": float(i * 100),
+ "duration_ms": 33.0,
+ "instruments": {"frames": {"fps": fps, "max_frame_ms": frame_ms, "long_frames": []}},
+ }
+
+ rows = [win("s1aborted", i, 28.7, 34.84) for i in range(7)]
+ rows.append({"row_type": "cell", "cell_id": cid, "session_id": "s1aborted", "completed": False})
+ rows.append(
+ {"row_type": "cell_aborted", "cell_id": cid, "session_id": "s1aborted", "reason": "died"}
+ )
+ rows += [win("s2resumed", i, 46.7, 21.41) for i in range(6)]
+ rows.append({"row_type": "cell", "cell_id": cid, "session_id": "s2resumed", "completed": True})
+ return rows
+
+
+def test_the_windows_of_a_dead_attempt_do_not_come_back_with_the_retry():
+ """Matching on the cell id alone hands back the very film the helper exists to exclude.
+
+ A completed retry puts the id in `completed_cell_ids`, and the aborted attempt shares that id,
+ so every one of its windows passed the filter. Pushing the helper's own output through the real
+ frame maths gave `max_frame_ms` 34.84 against a true 21.41 and a `jank_index` of 2.719 against
+ 0.000 -- a jank score invented entirely by the run that crashed. `floor_table.cell_metrics` was
+ right on the same records, so the importable rule was wrong where the older ad-hoc guard was
+ right.
+ """
+ got = payload_rules.windows_of_completed_cells(_resumed_window_payload())
+ sessions = {r.get("session_id") for r in got}
+ assert sessions == {
+ "s2resumed"
+ }, f"windows came back from {sorted(sessions)}. The dead attempt's frames became the retry's."
+ assert len(got) == 6
+ fps = [r["instruments"]["frames"]["fps"] for r in got]
+ assert set(fps) == {46.7}
+
+
+def test_subtracting_the_aborted_ids_is_not_the_fix():
+ """Documented because it is the obvious wrong answer and it silently deletes a good reading.
+
+ On a resumed payload the SAME id is both completed and aborted, so `done - aborted` is empty:
+ the reader who reaches for `aborted_cell_ids` as a mitigation loses the film that finished
+ rather than the one that did not.
+ """
+ rows = _resumed_window_payload()
+ done = payload_rules.completed_cell_ids(rows)
+ aborted = payload_rules.aborted_cell_ids(rows)
+ assert done and aborted
+ assert done - aborted == set()
+
+
+def test_a_payload_with_no_resumed_attempt_is_unchanged():
+ """The reduction must not drop windows from an ordinary single-attempt payload."""
+ rows = [
+ {
+ "row_type": "window",
+ "cell_id": "r100K.base.rep0",
+ "session_id": "s1",
+ "name": "stream:gap0",
+ "kind": "gap",
+ "instruments": {"frames": {"fps": 60.0}},
+ },
+ {"row_type": "cell", "cell_id": "r100K.base.rep0", "session_id": "s1", "completed": True},
+ ]
+ assert len(payload_rules.windows_of_completed_cells(rows)) == 1
+
+
+def test_a_headed_run_is_not_comparable_with_a_headless_one():
+ """`engine` does not settle which browser drew the frames.
+
+ Since Playwright 1.57 the two modes default to different binaries -- `chrome` against
+ `chrome-headless-shell` -- and this repo pins `playwright>=1.45,<2`, so that split is in range.
+ Headless also falls back to software rendering for GPU-accelerated work and its compositor
+ keeps its own pacing. For a tool whose output is frames, jank and time-to-settle, those are two
+ different renderers reported under one engine name.
+ """
+ corpus = "ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c"
+ headless = _meta(corpus)
+ headed = _meta(corpus)
+ headed["headed"] = True
+ assert payload_rules.comparability_key(headless) != payload_rules.comparability_key(headed)
+ assert payload_rules.explain_incomparable(headless, headed) == ["headed: False != True"]
+
+
+def test_a_payload_written_before_the_headed_field_reads_as_headless():
+ """Absence is the headless default, not a third state that orphans every older payload."""
+ corpus = "ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c"
+ legacy = _meta(corpus)
+ legacy.pop("headed", None)
+ current = _meta(corpus)
+ current["headed"] = False
+ assert payload_rules.comparability_key(legacy) == payload_rules.comparability_key(current)
+
+
+def test_the_launch_mode_is_an_identity_axis_a_resume_cannot_toggle():
+ """Recording it is not enough: `--resume` must refuse to continue one renderer with another.
+
+ Nothing moves the cell id, so a resume that toggled the flag would skip the completed cells and
+ append the rest under the same ids, building one ladder from two browsers.
+ """
+ from tests.studio.studiobench.__main__ import HISTORICAL_DEFAULTS, IDENTITY_AXES
+
+ assert "headed" in IDENTITY_AXES
+ assert HISTORICAL_DEFAULTS["headed"] is False
+
+
+def test_the_instrument_version_is_an_identity_axis_a_resume_cannot_cross():
+ """Detecting the mixture afterwards is not the same as refusing to create it.
+
+ `merged_run_meta` names a `tool_version` disagreement, but only `--compare` and a floor-gated
+ `floor_table.render` ever call it: plain `--report` reads the FIRST header and pools whatever
+ is in the file. So a half-finished 0.1.0 payload resumed from this tree kept its old cells and
+ appended new ones measured by instruments this commit redefined -- `reasoning_toggle.open_ms`
+ now terminates on a settled mount rather than on the `data-state` flip -- under cell ids that
+ cannot tell the two apart. The refusal has to arrive before anything is measured.
+ """
+ from tests.studio.studiobench.__main__ import IDENTITY_AXES, TOOL_VERSION, identity_problems
+
+ assert "tool_version" in IDENTITY_AXES
+ recorded = _meta("ac9d5d8e")
+ recorded["tool_version"] = "0.1.0"
+ requested = {"tool_version": TOOL_VERSION}
+ problems = identity_problems(recorded, requested)
+ assert any(p.startswith("tool_version:") for p in problems), problems
+
+
+def test_compare_reads_an_interrupted_payload_instead_of_raising(tmp_path, capsys):
+ """A payload killed during its last append ends in a torn record, by design.
+
+ The format is append-only and every row is flushed as it is written precisely so the rows
+ before the interruption survive; `report.read_records` counts a malformed line, and
+ `recorded_identities` and `_resume_set` skip one. `--compare` parsed with a bare `json.loads`
+ and answered an interrupted payload with a JSONDecodeError traceback instead of the check it
+ was asked for.
+ """
+ import json
+
+ from tests.studio.studiobench.__main__ import main
+
+ corpus = "ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c"
+ rows = [json.dumps(_meta(corpus)), json.dumps({"row_type": "cell", "cell_id": "r100K.A0.rep0"})]
+ whole = tmp_path / "whole.jsonl"
+ whole.write_text("\n".join(rows) + "\n", encoding = "utf-8")
+ torn = tmp_path / "torn.jsonl"
+ torn.write_text(
+ "\n".join(rows) + "\n" + json.dumps({"row_type": "cell", "cell_id": "r100K"})[:18],
+ encoding = "utf-8",
+ )
+
+ assert main(["--compare", str(torn), str(whole)]) == 0
+ out = capsys.readouterr().out
+ assert "malformed line" in out, out
+ assert "comparable: every field the key covers matches." in out, out
diff --git a/tests/studio/studiobench/sweep/floor_table.py b/tests/studio/studiobench/sweep/floor_table.py
index 7bcde22278b..34c42d2790c 100644
--- a/tests/studio/studiobench/sweep/floor_table.py
+++ b/tests/studio/studiobench/sweep/floor_table.py
@@ -52,6 +52,7 @@ from tests.studio.studiobench.scoring.from_payload import ( # noqa: E402
latest_attempt_rows,
refuse_if_probed,
)
+from tests.studio.studiobench.scoring import payload_rules # noqa: E402
METRICS = tuple(ACTION_SOURCES) + FRAME_METRICS + STREAM_METRICS
@@ -120,8 +121,205 @@ def _action_timings(records: list[dict], cid: str) -> dict[str, float]:
return out
-def cell_metrics(records: list[dict]) -> dict[str, dict[str, float]]:
- """{cell_id: {metric: value}} for every COMPLETED cell in the payload.
+def sessions_in(records: list[dict]) -> set[str]:
+ """Every `session_id` that produced a completed cell in this payload."""
+ return {
+ r.get("session_id")
+ for r in records
+ if r.get("row_type") == "cell" and r.get("completed") and r.get("session_id")
+ }
+
+
+def refuse_collisions(records: list[dict]) -> None:
+ """Refuse a payload in which one cell completed under more than one session.
+
+ CALLED FROM EVERY ENTRY POINT THAT POOLS, which is the whole point. The refusal used to live
+ inside `cell_metrics` behind `session is None`, and the only production caller -- `paired` --
+ always passes a session, so nothing in the shipped path ever reached it. On the real payload
+ from two concurrent launchers it went straight through: `paired` returned four pairs from two
+ cells, and `summarise` reported keystroke `p50_ms` up 93.4% on n=4. Neither session measured
+ 93.4%; they measured +37.0% and +149.8%. The pooled figure is the mean of two runs contending
+ with each other, presented as four independent repetitions.
+
+ A guard reachable only from a function nobody calls is the same defect as a guard that was
+ never wired up at all, which this branch has now hit three times.
+ """
+ collided = collided_cells(records)
+ if not collided:
+ return
+ # A SEQUENTIAL RE-RUN IS NOT A COLLISION, and refusing it rejected every resumed A/B.
+ #
+ # `ab.skippable_cells` skips a repetition only when EVERY arm of it completed, and an A/B with
+ # any work left re-runs EVERY pair in one new session -- deliberately, because a lone arm
+ # measured in a new session can never be paired and a partial table publishes a verdict over
+ # whichever rungs survived. So a resumed comparison legitimately writes a SECOND completed row
+ # under the same deterministic `cell_id`, and the writer's own docstring says what happens
+ # next: "The old attempt stays in the payload and `latest_attempt_rows` supersedes it."
+ # Nothing here superseded anything, so a resumed run could not be scored at all.
+ #
+ # WHAT IS ASKED IS WHETHER THE TWO SESSIONS WERE RUNNING AT ONCE, which is the property that
+ # makes the readings contended, and it is recorded: each session's `run_meta` carries
+ # `started_at` and every row carries `ts_ms` from that session's own clock. On the real
+ # two-launcher payload of defect 9 the two sessions occupy 23:50:24-00:10:03 and
+ # 23:53:45-00:12:43, sixteen minutes of overlap. A resume starts after its predecessor stopped.
+ #
+ # SILENCE IS NOT A LICENCE. A payload that does not carry the evidence -- no `started_at`, no
+ # `ts_ms` -- is refused exactly as before, because "no proof they overlapped" is not "proof
+ # they did not", and this is the guard that stands between a reader and a blend of two
+ # contending runs. Only a payload that can SHOW its sessions were sequential is superseded.
+ guilty: set[str] = set()
+ for sessions in collided.values():
+ guilty |= sessions
+ verdict, both = concurrent_sessions(records, only = guilty)
+ if verdict == "sequential":
+ # The caller supersedes through `latest_attempt_rows`, which keeps the LAST attempt that
+ # wrote anything -- so a resume that was itself hard-killed leaves an incomplete cell and
+ # drops out, rather than resurrecting the older completed reading.
+ return
+ if verdict == "overlap":
+ why = (
+ f"sessions {both[0]} and {both[1]} were RUNNING AT THE SAME TIME by their own "
+ f"`started_at` and `ts_ms`"
+ )
+ elif verdict == "interleaved":
+ why = (
+ f"the rows of sessions {both[0]} and {both[1]} INTERLEAVE in the file, which one "
+ f"writer appending after another cannot produce"
+ )
+ else:
+ why = (
+ "this payload does not say when its sessions ran -- no `started_at`, or no `ts_ms` -- "
+ "so it cannot show they were sequential rather than concurrent"
+ )
+ listed = ", ".join(f"{cid} in {sorted(s)}" for cid, s in sorted(collided.items())[:4])
+ more = "" if len(collided) <= 4 else f" (and {len(collided) - 4} more)"
+ raise SystemExit(
+ f"refusing to pool {len(collided)} cell id(s) that completed under more than one "
+ f"session in this payload, and {why}: {listed}{more}. `cell_id` is unique within a "
+ f"session, not "
+ f"across them, so keying on it alone would report whichever session was appended last, "
+ f"and pairing across them would report two contending runs as repetitions of one. Two "
+ f"concurrent runs sharing one --out is the usual cause. Split the payload by session, or "
+ f"pass `session=` to score one of them."
+ )
+
+
+def collided_cells(records: list[dict]) -> dict[str, set[str]]:
+ """{cell_id: sessions} for every cell id COMPLETED under more than one session id.
+
+ THIS, AND NOT THE SESSION COUNT, IS WHAT SEPARATES THE TWO CASES. More than one session in a
+ payload is ordinary and legitimate: `--resume` re-runs the arm that died under a new session id
+ into the same shard directory, and sharding appends several sessions on purpose. What is never
+ legitimate is the SAME cell completing twice, because a cell id is unique within a session, so
+ two completed copies mean two runs measured the same thing and only one of them can be
+ reported.
+
+ The resumed case is distinguishable precisely because the attempt that died is not marked
+ completed: only the retry is, so the id does not collide. The concurrent case is the one where
+ every id is present twice with `completed: true` on both.
+ """
+ seen: dict[str, set[str]] = {}
+ for r in records:
+ if r.get("row_type") == "cell" and r.get("completed") and r.get("cell_id"):
+ seen.setdefault(r["cell_id"], set()).add(str(r.get("session_id") or ""))
+ return {cid: s for cid, s in seen.items() if len(s) > 1}
+
+
+def session_spans(records: list[dict]) -> dict[str, tuple[int, int]]:
+ """{session: (first row index, last row index)} over the file as written."""
+ spans: dict[str, list[int]] = {}
+ for i, row in enumerate(records):
+ sid = row.get("session_id")
+ if sid is None:
+ continue
+ sid = str(sid)
+ if sid in spans:
+ spans[sid][1] = i
+ else:
+ spans[sid] = [i, i]
+ return {k: (v[0], v[1]) for k, v in spans.items()}
+
+
+def session_clocks(records: list[dict]) -> dict[str, tuple[float, float]]:
+ """{session: (start, end)} in seconds since the epoch, for sessions that can say.
+
+ A session's `run_meta` records `started_at` in wall clock and every row it writes carries
+ `ts_ms` from that session's own monotonic clock, so its occupancy is `started_at` to
+ `started_at + max(ts_ms)`. A session missing either is absent from this map rather than
+ given a guessed one: the caller treats absence as unknown and refuses.
+ """
+ import datetime
+
+ starts: dict[str, float] = {}
+ spans: dict[str, float] = {}
+ for row in records:
+ sid = row.get("session_id")
+ if sid is None:
+ continue
+ sid = str(sid)
+ if row.get("row_type") == "run_meta" and row.get("started_at") and sid not in starts:
+ try:
+ starts[sid] = datetime.datetime.fromisoformat(str(row["started_at"])).timestamp()
+ except ValueError:
+ continue
+ ts = row.get("ts_ms")
+ if isinstance(ts, (int, float)) and not isinstance(ts, bool):
+ spans[sid] = max(spans.get(sid, 0.0), float(ts) / 1000.0)
+ return {sid: (t0, t0 + spans[sid]) for sid, t0 in starts.items() if sid in spans}
+
+
+def concurrent_sessions(
+ records: list[dict], only: set[str] | None = None
+) -> tuple[str, tuple[str, str] | None]:
+ """Were these sessions running at once? `("sequential"|"overlap"|"interleaved"|"unknown", pair)`.
+
+ TWO INDEPENDENT WITNESSES, because either alone can be fooled. The clocks answer the question
+ actually being asked -- contention is a property of time, not of file layout -- but they rest
+ on a `started_at` a machine with a stepped clock can misreport. File order answers a narrower
+ question that cannot be misreported: a payload is append-only with one writer per process, so
+ a session's rows are one contiguous stretch unless somebody else was writing into the gaps. A
+ run that stalls long enough for a whole second run to start and finish inside its own gap is
+ caught too, since the nested stretch overlaps the enclosing one.
+
+ Sorted by first row, so comparing each session with the next is enough: if any two stretches
+ overlap then some ADJACENT pair does, because the later one's start is at or before the
+ earlier one's end.
+
+ UNKNOWN IS NOT SEQUENTIAL. A payload that cannot show when its sessions ran gets the refusal
+ it got before this distinction existed.
+ """
+ spans = {k: v for k, v in session_spans(records).items() if only is None or k in only}
+ order = sorted(spans.items(), key = lambda kv: kv[1][0])
+ for (first, a), (second, b) in zip(order, order[1:]):
+ if a[1] >= b[0]:
+ return "interleaved", (first, second)
+ clocks = {k: v for k, v in session_clocks(records).items() if only is None or k in only}
+ if set(clocks) != set(spans) or len(clocks) < 2:
+ return "unknown", None
+ by_start = sorted(clocks.items(), key = lambda kv: kv[1][0])
+ for (first, a), (second, b) in zip(by_start, by_start[1:]):
+ if a[1] > b[0]:
+ return "overlap", (first, second)
+ return "sequential", None
+
+
+def cell_metrics(records: list[dict], session: str | None = None) -> dict[str, dict[str, float]]:
+ """{cell_id: {metric: value}} for every COMPLETED cell in ONE session of the payload.
+
+ REFUSES rather than letting the last writer win, when and only when a cell id COMPLETED under
+ more than one session. `cell_id` is unique within a session and NOT across sessions, so keying
+ on it alone silently collapses two measurements of the same cell into whichever was appended
+ last. Several sessions in one payload is not itself the fault -- `--resume` and sharding both
+ produce that legitimately, and refusing them would delete good readings. See `collided_cells`.
+
+ That is not hypothetical. A launcher started twice ran two full sessions concurrently against
+ one `--out`, and both appended: three `run_meta` rows, every `cell_id` present twice, both
+ marked completed, and the two copies carrying materially different timings because the runs
+ were contending with each other -- `r1M.treatment.rep1` keystroke `p50_ms` read 73.4 ms in one
+ session and 144.5 ms in the other. Scored last-wins it reported a 149.8% regression; scored
+ per session it read +149.8% in one and +42.8% in the other.
+
+ Pass `session` to select one, or use `paired`, which keys on the session and pairs within it.
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
@@ -133,6 +331,20 @@ def cell_metrics(records: list[dict]) -> dict[str, dict[str, float]]:
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.
"""
+ if session is None:
+ refuse_collisions(records)
+ # SUPERSEDED ATTEMPTS ARE DROPPED, because a resumed A/B re-runs a repetition that had
+ # already completed and both copies are in the file. Keyed on the LAST attempt that wrote
+ # anything rather than the last that FINISHED: a resume killed inside a cell has flushed
+ # its action rows and never reaches the cell row its `finally` would write, and treating
+ # the older completed attempt as current would hand a stale reading to a floor. Dropped
+ # here, that repetition has no completed cell and falls out of the table instead.
+ #
+ # ONLY WHEN NO SESSION WAS NAMED. `session=` is the escape hatch this module's own refusal
+ # points a reader at -- "pass `session=` to score one of them" -- and superseding inside it
+ # would empty the older of two concurrent sessions and take the hatch away. A caller who
+ # names a session is asking for that session, not for the payload's latest view of it.
+ records = list(latest_attempt_rows(records))
# A CELL THAT FAILED AN INVALIDATING GATE IS NOT A READING, HERE EITHER. Both gates are
# advisory where they are emitted, so such a cell arrives `completed=True` with a full set of
# timings that are CHEAPER than a correct cell's, and this table is where a floor is built and
@@ -146,9 +358,9 @@ def cell_metrics(records: list[dict]) -> dict[str, dict[str, float]]:
# census going from 12 mounted messages to 0 and never recovering, and a headline of 28.2%
# faster weighted. Nothing between the two noticed.
#
- # Read from the RAW stream, because `failed_invalidating_gates` scopes the gate to its own
- # attempt by hand -- a gate row is not one of the row types `latest_attempt_rows` covers -- and
- # it names the winning attempt from the last `cell` row of ANY completion state.
+ # Scoped by hand, because a gate row is not one of the row types `latest_attempt_rows` covers:
+ # that reduction has already dropped the superseded attempt's cells, actions and windows above,
+ # and a `gate` row carries no attempt of its own to supersede.
gate_failures = failed_invalidating_gates(records)
# A SUPERSEDED ATTEMPT'S COMPLETION IS NOT THIS CELL'S READING, and the session scoping below
@@ -165,12 +377,28 @@ def cell_metrics(records: list[dict]) -> dict[str, dict[str, float]]:
# against a clean base arm and printing as `faster`: the 28.2% failure described above,
# arriving through the resume. Same rows, same rule, one lens -- as `runtime/ab.readings_by_arm`
# and `sweep/ui_parity.collect` already read them.
- records = latest_attempt_rows(records)
+ #
+ # THE REDUCTION THAT DOES THIS NOW SITS AT THE TOP OF THE FUNCTION, and it is CONDITIONAL --
+ # skipped when the caller named a `session`. A second unconditional call here would have been
+ # a no-op on the default path and a silent regression on that one: it would supersede inside
+ # the escape hatch, empty the older of two concurrent sessions, and take away the very thing
+ # this module's collision refusal tells the reader to reach for. So the guard above and this
+ # loop still read one lens, and which lens that is now depends on the argument, deliberately.
+ #
+ # Left open on purpose: with `session=` named, `failed_invalidating_gates` still resolves its
+ # winner across every session in the file, so a caller who names the OLDER of two sessions can
+ # have its gate discarded by the newer one while this loop admits its cells. Scoping the gate
+ # search to the named session is the fix, and it is a change to the escape hatch's semantics
+ # rather than to this merge.
out: dict[str, dict[str, float]] = {}
+ if session is not None:
+ records = [r for r in records if r.get("session_id") in (session, None)]
for row in records:
if row.get("row_type") != "cell" or not row.get("completed"):
continue
+ if session is not None and row.get("session_id") != session:
+ continue
if str(row.get("cell_id")) in gate_failures:
continue
cid = row["cell_id"]
@@ -247,14 +475,29 @@ def paired(records: list[dict], shard: str = "") -> dict[str, list[tuple[float,
A payload recorded before session ids existed has `""` on both arms and pairs exactly as before.
"""
- cells = cell_metrics(records)
- sessions = cell_sessions(records)
+ # THE SESSION IS PART OF THE KEY, for the same reason the shard is. Two sessions in one
+ # payload both produce `rep0`, and pairing on the repetition alone matches one session's base
+ # against the other's treatment -- which is a comparison between two different runs under two
+ # different machine loads, reported as a repetition.
+ #
+ # Looped per session because several sessions in one payload is ORDINARY -- a sharded or
+ # resumed run appends legitimately, and each session's repetitions must pair within themselves.
+ # What is never ordinary is one cell completing twice, so that is refused first, here rather
+ # than only inside `cell_metrics`: this loop always passes a session, so the refusal there was
+ # unreachable from the shipped path and a payload of two concurrent runs pooled straight
+ # through it.
+ refuse_collisions(records)
+ # The same superseding `cell_metrics` applies, done once here so the session list below is the
+ # set of sessions that still own a completed cell. Without it a finished ladder re-run pairs
+ # ONCE PER SESSION and one repetition is pooled twice, under two different sets of numbers.
+ records = list(latest_attempt_rows(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
+ for sess in sorted(sessions_in(records)) or [None]:
+ for cid, vals in cell_metrics(records, session = sess).items():
+ rung = cid.split(".", 1)[0]
+ by_key[(shard, str(sess), rung, rep_of(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:
@@ -366,9 +609,69 @@ def load(paths: list[Path]) -> tuple[dict[str, list[tuple[float, float]]], set[s
return pooled, tiers
+def partial_censoring(paths: list[Path]) -> dict[str, str]:
+ """{metric: why it must not be pooled across this ladder}, over every shard.
+
+ THE GUARD WAS WRITTEN AND THEN NEVER CALLED. `payload_rules.refuse_partial_censoring` returned
+ the right refusal from the moment it landed and nothing in the scoring or sweep path asked it
+ anything, so the only code that ever saw the answer was its own selftest. That is the same
+ shape as the row type that was registered nowhere: a guard that cannot fire is not a guard, and
+ it is worse than an absent one because the reader believes the case is covered.
+
+ What it catches is defect 2. `reasoning_toggle.open_ms` is censored on every cell above the
+ 100K rung, so `paired()` pools only the cells that could answer and `render()` prints the mean
+ of those under a bare metric name. On a 100K/500K/1M ladder that row is a 100K-only number
+ wearing a ladder label, and the only hint is a smaller `n` sitting beside the other rows --
+ indistinguishable from a metric that simply had fewer repetitions.
+
+ JUDGED OVER EVERY SHARD AT ONCE, because that is the set `summarise` pools. Asked per file,
+ a ladder split across shards escapes: the shard holding the measured 100K cells sees no
+ censoring at all, the shard holding the censored 500K cells sees censoring at every rung it
+ contains, and neither returns a refusal -- while `load()` pools them together and prints the
+ 100K number under a ladder label. The same rows concatenated into one file are caught. Identical
+ data, opposite treatment, decided by which file they happened to be written to.
+ """
+ everything: list[dict] = []
+ for path in paths:
+ # SUPERSEDED ATTEMPTS DROPPED, exactly as `paired` drops them, because this decides whether
+ # the number `paired` produced may be quoted. A resume that died mid-cell leaves an action
+ # row whose `expect_ok` is False, and `censored_metrics` counts that as a censored cell --
+ # so reading the raw file here would mark a metric partially censored on the strength of an
+ # attempt that contributed nothing to the mean. The two readers have to see one payload.
+ #
+ # NAMESPACED BY SHARD, for the same reason `paired` keys on it: sharding restarts the
+ # repetition counter, so `r500K.base.rep0` names a DIFFERENT cell in each shard. Merged on
+ # the bare id, the completed-cell filter below stops separating them -- one shard's failed
+ # cell and another shard's successful one become a single id that is both censored and
+ # completed, and a metric nothing censored anywhere is refused as partially censored on
+ # the strength of a cell that contributed nothing to the mean. That is the very case the
+ # paragraph above drops superseded attempts to avoid, arriving one file over.
+ #
+ # SUFFIXED rather than prefixed, so `refuse_partial_censoring` still reads the rung off
+ # `cell_id.split(".", 1)[0]` and its message names rungs rather than directories.
+ shard = str(path.parent.name)
+ for row in latest_attempt_rows(read_rows(path)):
+ row = dict(row)
+ if row.get("cell_id") is not None:
+ row["cell_id"] = f"{row['cell_id']}@{shard}"
+ everything.append(row)
+ out: dict[str, str] = {}
+ for metric in sorted(censorable_metrics(everything)):
+ why = payload_rules.refuse_partial_censoring(everything, metric)
+ if why:
+ out[metric] = why
+ return out
+
+
+def censorable_metrics(records: list[dict]) -> set[str]:
+ """Every metric this payload censored anywhere, which is the set worth asking about."""
+ return set(payload_rules.censored_metrics(records))
+
+
def summarise(paths: list[Path]) -> dict[str, dict[str, float]]:
out: dict[str, dict[str, float]] = {}
pooled, _tiers = load(paths)
+ censoring = partial_censoring(paths)
for metric, rows in pooled.items():
if metric in DIFFERENCE_METRICS:
# Same three quantities, same three gates, measured in the metric's own unit because a
@@ -421,6 +724,15 @@ def summarise(paths: list[Path]) -> dict[str, dict[str, float]]:
"spread_pct": (max(ratios) - min(ratios)) * 100.0,
"difference": False,
}
+ # LABELLED, NOT DROPPED AND NOT RAISED. Raising would be the defect-10 mistake: `open_ms`
+ # is censored above 100K on EVERY standard and full run, so a refusal that exited would
+ # abort the whole table on the normal case and the guard would be removed within a day.
+ # Dropping the row silently would delete a reading somebody may still want at the one rung
+ # that produced it. So the row survives, carries the rungs it actually covers, and is
+ # denied a verdict below -- it can no longer clear a gate or be counted as a survivor.
+ if metric in censoring:
+ out[metric]["poolable"] = False
+ out[metric]["censoring"] = censoring[metric]
return out
@@ -464,12 +776,27 @@ def is_count_metric(metric: str) -> bool:
return ".count." in metric
+def merged_meta(paths: list[Path]) -> tuple[dict | None, list[str]]:
+ """One `run_meta` describing every shard of one logical run, plus what forbids one.
+
+ EVERY SHARD AND EVERY HEADER, for the same reason `tiers_of` and `corpora_of` read every
+ header rather than the first: the recorder appends, so `--resume` writes a second header
+ behind the first, and a sharded run spreads its headers across files. A first-header-wins
+ reading describes the run that started the file rather than the cells now in it.
+ """
+ rows: list[dict] = []
+ for path in paths:
+ rows += read_rows(path)
+ return payload_rules.merged_run_meta(rows)
+
+
def render(
paths: list[Path],
title: str,
floors: dict | None = None,
floor_tier: str | None = None,
floor_corpus: str | None = None,
+ floor_meta: dict | None = None,
) -> int:
stats = summarise(paths)
rows = read_rows(paths[0])
@@ -487,6 +814,45 @@ def render(
f"built on {floor_corpus[:16]}: a floor is the scatter of THIS film, and a "
f"different corpus is a different film. Re-run the null control."
)
+ # THE REST OF THE COMPARABILITY IDENTITY, which tier and corpus are only two axes of.
+ #
+ # `--compare` refuses two payloads whose `comparability_key`s differ, and this path -- the one
+ # that actually certifies a number -- checked two of the eleven fields that key covers. So an
+ # 0.1.0 floor could score an 0.2.0 payload on the same corpus and tier, and this commit is
+ # precisely why that matters: it redefines `reasoning_toggle.open_ms` to terminate on a settled
+ # DOM rather than on the `data-state` flip, so the older floor measures a different quantity
+ # under the same name. `host`, `engine`, `cadence`, `headed`, `rungs` and the injection and
+ # probe axes are the same class of difference, and `--compare` is a separate command nobody is
+ # obliged to run first.
+ #
+ # Checked through `explain_incomparable` rather than against a second list of fields, so a
+ # field added to `comparability_fields` is enforced here without being added here too. A guard
+ # kept in step by hand is the drift `payload_rules` exists to argue against.
+ if floor_meta is not None:
+ meta, conflicts = merged_meta(paths)
+ if meta is None:
+ raise SystemExit(
+ "refusing to score a payload that carries no run_meta row against a floor that "
+ "does: nothing in it says which film, which harness or which host produced it, "
+ "so there is no way to tell whether the floor describes the same quantity."
+ )
+ if conflicts:
+ raise SystemExit(
+ "refusing to score a payload that disagrees with ITSELF across its own run_meta "
+ "rows:\n " + "\n ".join(conflicts) + "\nThis payload holds more than one run "
+ "and they were not measuring the same thing, so no floor can be applied to it as "
+ "a whole. Score the runs apart."
+ )
+ differ = payload_rules.explain_incomparable(floor_meta, meta)
+ if differ:
+ raise SystemExit(
+ "refusing to score this payload against a floor that is not comparable with it. "
+ "These differ (floor != payload):\n "
+ + "\n ".join(differ)
+ + "\nA floor is the scatter of THIS measurement on THIS machine with THIS "
+ "harness. A field above changing means the two are not measuring the same "
+ "quantity, whatever the metric is called. Re-run the null control in band."
+ )
if tier == "fast":
print("\n NOTE: fast tier. These are directions for iteration, not reportable numbers.")
print(f"\n{title}")
@@ -495,23 +861,72 @@ def render(
print(head + (" floor % verdict" if floors else ""))
print(" " + "-" * (len(head) + (26 if floors else 0)))
survivors = 0
+ censored_notes: list[str] = []
marked = False
for metric in sorted(stats, key = lambda m: (m in METRICS, m)):
s = stats[metric]
+ # TWO INDEPENDENT CAVEATS, BOTH CARRIED IN THE NAME COLUMN, and neither allowed to hide
+ # the other. They answer different questions -- `(abs)` says what the delta MEANS, `[*]`
+ # says which rungs it covers -- and a metric can need both at once.
+ #
+ # A metric censored at some rungs and measured at others is marked so the caveat cannot be
+ # separated from the number when somebody copies one row out of this table into prose.
+ # That is the route every withdrawn figure in this harness travelled.
+ partial = s.get("poolable") is False
# A difference row is named as one. Its delta is in the metric's own unit, and printing it
# under a "delta %" heading would be the same class of mistake this file exists to stop.
+ #
+ # ORTHOGONAL TO THE TWO CENSORING MARKS BELOW, and applied first so it survives either of
+ # them: `(abs)` says what the delta MEANS, `[*]` and `[f]` say who can judge it. A metric
+ # can need `(abs)` and a censoring mark at once.
label = metric
if s.get("difference"):
- label, marked = metric + " (abs)", True
+ label, marked = f"{metric} (abs)", True
+ # THE FLOOR IS A MEASUREMENT TOO, and it is censored by the same rule on its own cells.
+ #
+ # `summarise` marks the null control's entry `poolable = False` when the metric answered on
+ # some of its cells and was censored on others, and this loop then read only the RESULT's
+ # flag -- so a result measured in full was scored against a floor built from whichever
+ # repetitions of the null happened to survive. Censoring is decided against a fixed budget,
+ # so the repetitions it removes are the slow ones, and `spread_pct` is `max - min` over the
+ # survivors: removing pairs can only narrow it. Observed on a real null control at 100K
+ # plus 500K, `reasoning_toggle.close_ms` censored above 100K, the applied floor came out at
+ # 17.1% from the four surviving 100K pairs while the censored repetitions of that same null
+ # ran 1429-2149 ms against 498-681 ms and paired as far apart as 1.50 on identical builds.
+ # A real result of -24.8% printed `faster` against the 17.1% and is not distinguishable
+ # from the null's own scatter.
+ floor_stat = None if floors is None else floors.get(metric)
+ floor_partial = floor_stat is not None and floor_stat.get("poolable") is False
+ # MARKED APART FROM `[*]`, because the two say different things. `[*]` means this row's own
+ # number is not a ladder number; `[f]` means the number is fine and the null control cannot
+ # judge it. Collapsing them would tell a reader to distrust a figure that is sound.
+ shown = f"{label} [*]" if partial else (f"{label} [f]" if floor_partial else label)
line = (
- f" {label:<28}{s['n']:>3}{s['base']:>11.1f}{s['treat']:>11.1f}"
+ f" {shown:<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
+ if partial:
+ # DENIED A VERDICT. Passing three gates on the rungs that could answer is not
+ # passing them on the ladder the row is labelled with.
+ line += f"{'--':>13} not pooled"
+ elif floor_partial:
+ # DENIED A VERDICT ON THE OTHER SIDE. The three gates are all measured against
+ # this floor, so a floor that is itself a survivor sample cannot certify anything,
+ # however clean the result is.
+ line += f"{'--':>13} no poolable floor"
+ else:
+ f, verdict = verdict_for(s, floor_stat, 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
+ if partial:
+ censored_notes.append(f"[*] {s['censoring']}")
+ elif floor_partial:
+ censored_notes.append(
+ f"[f] the null control's own {floor_stat['censoring']} So it is a floor for the "
+ f"cells that survived, not for this row."
+ )
print(line)
if marked:
print(
@@ -519,6 +934,10 @@ def render(
"percentage\n change: zero is these metrics' clean reading, and a ratio from "
"zero does not exist."
)
+ if censored_notes:
+ print("\n NOT SCORED. [*] the row is NOT A LADDER NUMBER; [f] its floor is not one:")
+ for note in censored_notes:
+ print(f" {note}")
if floors is not None:
print(f"\n {survivors} metric(s) cleared all three gates.")
return survivors
@@ -550,7 +969,7 @@ def main(argv: list[str] | None = None) -> int:
)
args = ap.parse_args(argv)
- floors, floor_tier, floor_corpus = None, None, None
+ floors, floor_tier, floor_corpus, floor_meta = None, None, None, None
if args.floor:
floor_paths = shards_of(args.floor)
if not floor_paths:
@@ -560,6 +979,16 @@ def main(argv: list[str] | None = None) -> int:
floor_rows = read_rows(floor_paths[0])
floor_tier = tier_of(floor_rows)
floor_corpus = corpus_of(floor_rows)
+ # The floor's own comparability identity, read across every shard and every header. A null
+ # whose shards disagree with each other is not one null control, so it gets the same
+ # refusal a result payload gets rather than a token averaged over the disagreement.
+ floor_meta, floor_conflicts = merged_meta(floor_paths)
+ if floor_conflicts:
+ print(
+ "refusing to use a null control that disagrees with ITSELF across its own "
+ "run_meta rows:\n " + "\n ".join(floor_conflicts)
+ )
+ return 2
seen = 0
for arg in args.payloads:
@@ -568,7 +997,14 @@ def main(argv: list[str] | None = None) -> int:
print(f"\nno payload found for {arg}")
continue
seen += 1
- render(paths, f"PAIRED PER-METRIC TABLE: {arg}", floors, floor_tier, floor_corpus)
+ render(
+ paths,
+ f"PAIRED PER-METRIC TABLE: {arg}",
+ floors,
+ floor_tier,
+ floor_corpus,
+ floor_meta,
+ )
if not seen:
return 2
if floors is None:
diff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_floor_applicability.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_floor_applicability.py
new file mode 100644
index 00000000000..ff9676d0978
--- /dev/null
+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_floor_applicability.py
@@ -0,0 +1,412 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A floor may only certify a result it is actually a floor FOR.
+
+Two holes on the same line of `render`, both on the side of the comparison nobody looked at.
+
+THE FLOOR'S OWN CENSORING. `summarise` marks a metric `poolable = False` when it answered on some
+cells and was censored on others, and `render` read that flag on the RESULT only. So a result
+measured in full was scored against a floor built from whichever repetitions of the null control
+survived. Censoring is decided against a fixed budget, so the repetitions it removes are the slow
+ones, and `spread_pct` is `max - min` over what is left: removing pairs can only narrow it.
+
+Measured on the real null control of this campaign, `outputs/rp/sbench_{T,C}_null` pooled as one
+100K plus 500K plus 1M ladder: `reasoning_toggle.close_ms` is censored above 100K, the surviving
+four 100K pairs give a floor of 17.1%, and the campaign result of -24.8% printed `faster` and was
+counted as a metric that cleared all three gates. The repetitions that censoring removed are the
+slow ones by construction -- 1429 to 2149 ms against 498 to 681 ms at 100K -- and they pair as far
+apart as 1.50 on IDENTICAL BUILDS, which is three times the floor that was applied. The null's own
+`settings` action shows the same shape from the other end: one repetition failed its assertion at
+3425.8 ms against a median near 200 ms, and dropping it is what left the tight floor behind.
+
+THE REST OF THE COMPARABILITY IDENTITY. The scoring path validated tier and corpus, which is two
+of the eleven fields `comparability_key` covers. `--compare` covers all eleven and is a separate
+command that nothing obliges a caller to run. So an 0.1.0 floor scored an 0.2.0 payload on the
+same corpus and tier, and this commit is exactly why that is not a formality: it redefines
+`reasoning_toggle.open_ms` to terminate on a settled DOM rather than on the `data-state` flip, so
+an older floor measures a different quantity under the same name. Reproduced on the real payloads:
+the 0.1.0 null control scored a 0.2.0 payload and certified nine metrics, `reasoning_toggle.close_ms
+-24.8% faster` among them. A Darwin/arm64 payload against a Linux/x86_64 floor passed identically.
+
+PRODUCER IN THE LOOP. Every payload below is written through the real `Recorder`, so the schema
+check, the required-key check and the run lock are all on the path -- the row types and the
+required keys are the producer's, not this file's. The row CONTENTS are hand-specified, and the
+values are copied from the real payloads named above; what that does not prove is that the harness
+still emits censoring in this shape, which `test_studiobench_partial_censoring.py` and the
+`expect` contract in `scene/actions.py` cover.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tests.studio.studiobench.runtime.types import Recorder
+from tests.studio.studiobench.scoring import payload_rules
+from tests.studio.studiobench.sweep import floor_table
+
+#: The corpus every payload here is recorded on. Real, from `outputs/rp/sbench_T_null`.
+CORPUS = "ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c"
+
+
+def _meta(**over) -> dict:
+ """A `run_meta` carrying every key the Recorder requires, shaped like a real one."""
+ row = {
+ "row_type": "run_meta",
+ "tier": "full",
+ "tool_version": "0.1.0",
+ "corpus_hash": CORPUS,
+ "studio_ref": "attached:http://127.0.0.1:8708",
+ "bundle": {"production": True},
+ "platform": {"system": "Linux", "machine": "x86_64", "engine": "chromium"},
+ "started_at": "2026-08-23T04:46:10",
+ "cadence": "field",
+ "rungs": ["100K", "500K"],
+ "instrument_level": 0,
+ }
+ row.update(over)
+ return row
+
+
+def _cell(cid: str) -> dict:
+ rung, arm, rep = cid.split(".")
+ return {
+ "row_type": "cell",
+ "cell_id": cid,
+ "cell": {"cell_id": cid, "rung": rung, "arm": arm, "rep": rep},
+ "completed": True,
+ "fidelity": "streamed_and_seeded",
+ }
+
+
+def _toggle(cid: str, close_ms: float, censored: bool) -> dict:
+ """One `reasoning_toggle` action row, censored or measured, in the producer's shape.
+
+ THE CENSORED ROW STILL CARRIES ITS TIMING, which is what the real 500K rows look like:
+ `open_ms` is withheld, `close_ms` was measured, and `expect_ok` is False because `ok` is one
+ conjunction over four clauses. `_action_timings` then discards every timing on the row and
+ `censored_metrics` names them all, which is the case `payload_rules` calls the one that
+ reaches furthest -- a measurement that succeeded on its own terms and contributes nothing.
+ """
+ timings = {"close_ms": close_ms}
+ return {
+ "row_type": "action",
+ "cell_id": cid,
+ "action": "reasoning_toggle",
+ "ran": True,
+ "expect_ok": not censored,
+ "expect": {
+ "settled": not censored,
+ "open_censored": censored,
+ "close_censored": False,
+ "open_censored_reason": (
+ "the open count reached 16 after 10698ms but the span census was still changing "
+ "when the 8000ms budget ran out"
+ if censored
+ else None
+ ),
+ },
+ "timings": timings,
+ "counts": {},
+ "slot_missed": False,
+ }
+
+
+def _write(
+ tmp_path,
+ name: str,
+ rows: list[dict],
+ meta: dict | None = None,
+):
+ """Through the REAL Recorder, so the schema and required keys are the producer's."""
+ out = tmp_path / name
+ out.mkdir(parents = True, exist_ok = True)
+ rec = Recorder(out / "payload.jsonl", "sess-" + name)
+ rec.emit(dict(meta or _meta()))
+ for row in rows:
+ rec.emit(dict(row))
+ rec.close()
+ return out / "payload.jsonl"
+
+
+#: Real 100K `close_ms` readings. Base then treatment, `outputs/rp/sbench_T_campaign`.
+RESULT_100K = ((897.6, 631.4), (665.6, 515.5), (665.6, 498.8), (682.1, 532.3))
+#: Real 100K `close_ms` readings from the null control, `outputs/rp/sbench_T_null`.
+NULL_100K = ((681.4, 564.7), (565.7, 515.7), (532.0, 515.1), (498.8, 498.8))
+#: Real 500K `close_ms` readings from the null control, `outputs/rp/sbench_C_null`. Every one of
+#: these cells is censored: the open settle blew its budget, so the action failed and the harness
+#: refuses to quote any of its timings.
+NULL_500K = ((1429.9, 2149.6), (1571.0, 1965.3), (1444.1, 1528.6), (1439.2, 1521.4))
+
+
+def _ladder(pairs_100k, pairs_500k, censor_500k: bool) -> list[dict]:
+ rows: list[dict] = []
+ for rung, pairs, censored in (
+ ("r100K", pairs_100k, False),
+ ("r500K", pairs_500k, censor_500k),
+ ):
+ for i, (base, treat) in enumerate(pairs):
+ for arm, value in (("base", base), ("treatment", treat)):
+ cid = f"{rung}.{arm}.rep{i}"
+ rows.append(_cell(cid))
+ rows.append(_toggle(cid, value, censored))
+ return rows
+
+
+def _null(tmp_path, censored: bool):
+ return _write(
+ tmp_path,
+ "null" + ("_censored" if censored else "_whole"),
+ _ladder(NULL_100K, NULL_500K, censored),
+ )
+
+
+def _result(tmp_path):
+ """A result that measured the metric on every cell of the ladder."""
+ return _write(tmp_path, "result", _ladder(RESULT_100K, RESULT_100K, False))
+
+
+METRIC = "reasoning_toggle.close_ms"
+
+
+# ── the floor's own censoring ────────────────────────────────────────
+
+
+def test_the_censored_null_is_marked_unpoolable_in_the_first_place(tmp_path):
+ """The precondition, stated so a fix that stopped marking it could not pass the rest."""
+ floors = floor_table.summarise([_null(tmp_path, censored = True)])
+ assert floors[METRIC]["poolable"] is False
+ assert "censored" in floors[METRIC]["censoring"]
+
+
+def test_censoring_the_null_tightens_the_floor_it_leaves_behind(tmp_path):
+ """The quantity at issue, measured on both sides rather than asserted.
+
+ Same null control, same real readings, the only difference being whether the 500K repetitions
+ were censored. `spread_pct` is `max - min` over the surviving paired ratios, so removing pairs
+ can only narrow it -- and the pairs removed here are the slow ones, because censoring is what
+ happens to a cell that ran out of budget.
+ """
+ whole = floor_table.summarise([_null(tmp_path, censored = False)])[METRIC]
+ left = floor_table.summarise([_null(tmp_path, censored = True)])[METRIC]
+ wide = max(abs(whole["delta_pct"]), whole["spread_pct"])
+ tight = max(abs(left["delta_pct"]), left["spread_pct"])
+ assert left["n"] < whole["n"], "the censored null kept every pair, so nothing was censored"
+ assert tight < wide, (
+ f"the censored null's floor ({tight:.1f}%) is not tighter than the whole null's "
+ f"({wide:.1f}%), so this fixture no longer demonstrates the bias"
+ )
+ # The real numbers: 17.1% left behind against 67.5% over the ladder, a factor of 3.9.
+ assert tight == pytest.approx(17.1, abs = 0.5)
+ assert wide == pytest.approx(67.5, abs = 0.5)
+
+
+def test_a_censored_floor_cannot_certify_a_measured_result(tmp_path, capsys):
+ """The bug. A result measured in full, scored against a floor that is a survivor sample."""
+ floors = floor_table.summarise([_null(tmp_path, censored = True)])
+ survivors = floor_table.render([_result(tmp_path)], "t", floors = floors)
+ printed = capsys.readouterr().out
+ row = next(line for line in printed.splitlines() if line.strip().startswith(METRIC))
+ assert (
+ "faster" not in row and "SLOWER" not in row
+ ), f"a result was certified against a floor the tool itself marks unpoolable: {row.strip()}"
+ assert "no poolable floor" in row
+ assert survivors == 0, "the row was counted as a metric that cleared all three gates"
+ assert "the null control's own" in printed, (
+ "the table denied the verdict without saying which side was censored, so a reader cannot "
+ "tell a censored result from a censored floor"
+ )
+
+
+def test_the_result_is_not_labelled_as_the_censored_one(tmp_path, capsys):
+ """`[f]` and `[*]` say different things and must not be collapsed.
+
+ The result's own number is sound here. Marking it `[*]` would tell a reader to distrust a
+ figure that is fine, which is its own way of publishing a wrong thing about a number.
+ """
+ floors = floor_table.summarise([_null(tmp_path, censored = True)])
+ floor_table.render([_result(tmp_path)], "t", floors = floors)
+ row = next(
+ line for line in capsys.readouterr().out.splitlines() if line.strip().startswith(METRIC)
+ )
+ assert "[f]" in row and "[*]" not in row
+
+
+def test_the_same_result_scores_normally_against_a_whole_floor(tmp_path, capsys):
+ """NOT A REFUSAL OF EVERYTHING. Identical result, a null control that censored nothing."""
+ floors = floor_table.summarise([_null(tmp_path, censored = False)])
+ # The whole-ladder floor is 67.5%, which this -24.8% result does not clear, so the verdict
+ # under it is VOID -- itself the point: the censored floor turned a VOID into a `faster`.
+ floor_table.render([_result(tmp_path)], "t", floors = floors)
+ row = next(
+ line for line in capsys.readouterr().out.splitlines() if line.strip().startswith(METRIC)
+ )
+ assert "no poolable floor" not in row and "[f]" not in row
+ assert "VOID" in row
+
+
+def test_a_whole_floor_still_certifies_a_real_effect(tmp_path, capsys):
+ """The other half of the non-vacuity check: a large effect over a whole floor still passes."""
+ floors = floor_table.summarise([_null(tmp_path, censored = False)])
+ tenfold = tuple((b, b / 10.0) for b, _ in RESULT_100K)
+ big = _write(tmp_path, "big", _ladder(tenfold, tenfold, False))
+ stats = floor_table.summarise([big])
+ f, verdict = floor_table.verdict_for(stats[METRIC], floors[METRIC])
+ assert verdict in ("faster", "SLOWER"), f"a whole floor refused a real effect: {verdict}"
+
+
+# ── the rest of the comparability identity ───────────────────────────
+
+
+def _floor_and_result(
+ tmp_path,
+ floor_meta: dict,
+ result_meta: dict,
+ tag: str = "",
+):
+ """A null control and a result differing only in their run metadata.
+
+ `tag` keeps each call in its own directory. The Recorder APPENDS, which is correct for shards
+ and wrong for a fixture reused inside a loop: without it the second call leaves two headers in
+ one file and the payload is refused for disagreeing with itself, which would pass this file's
+ assertions for the wrong reason.
+ """
+ floor = _write(tmp_path, f"cmp_null{tag}", _ladder(NULL_100K, NULL_100K, False), floor_meta)
+ result = _write(
+ tmp_path, f"cmp_result{tag}", _ladder(RESULT_100K, RESULT_100K, False), result_meta
+ )
+ return floor_table.summarise([floor]), floor_meta, result
+
+
+def test_an_older_harness_floor_cannot_score_a_newer_payload(tmp_path):
+ """The case this commit creates.
+
+ `open_ms` now terminates on a settled DOM rather than on the `data-state` flip, and
+ `TOOL_VERSION` was bumped for exactly that reason. A 0.1.0 floor and a 0.2.0 payload therefore
+ hold two different quantities under one metric name, on the same corpus, at the same tier.
+ """
+ from tests.studio.studiobench.__main__ import TOOL_VERSION
+
+ floors, floor_meta, result = _floor_and_result(
+ tmp_path, _meta(tool_version = "0.1.0"), _meta(tool_version = TOOL_VERSION)
+ )
+ with pytest.raises(SystemExit) as exc:
+ floor_table.render([result], "t", floors = floors, floor_meta = floor_meta)
+ assert "tool_version" in str(exc.value)
+
+
+def _meta_differing_in(field: str) -> dict:
+ """A `run_meta` that differs from `_meta()` in exactly `field`, wherever that field lives.
+
+ The nesting is DISCOVERED rather than listed. `engine`, `system`, `machine` and the browser
+ build fields are read out of `platform` and the rest off the row, and a hand-kept list of
+ which is which is the drift this whole file is about: `comparability_fields` grew two more
+ nested fields while this branch was open.
+ """
+ probe = ["100K", "500K", "1M"] if field == "rungs" else "CHANGED"
+ changed = _meta()
+ changed[field] = probe
+ if payload_rules.explain_incomparable(_meta(), changed):
+ return changed
+ changed = _meta()
+ changed["platform"] = dict(changed["platform"])
+ changed["platform"][field] = probe
+ assert payload_rules.explain_incomparable(_meta(), changed), (
+ f"could not construct a payload differing in {field}, so the case below would pass "
+ f"without testing anything"
+ )
+ return changed
+
+
+def test_every_comparability_field_stops_a_floor_from_being_applied(tmp_path):
+ """Enumerated from `comparability_fields`, so a field added there is enforced here for free.
+
+ Written this way rather than as a list of the fields that matter today because the list of
+ fields that matter today is what the scoring path had: it knew about tier and corpus, and
+ every axis added since -- host, engine, headed, cadence, the browser build, the injection and
+ probe flags -- was added to the key and not to the guard that certifies numbers.
+ """
+ for field in payload_rules.comparability_fields(_meta()):
+ floors, floor_meta, result = _floor_and_result(
+ tmp_path, _meta(), _meta_differing_in(field), tag = field
+ )
+ with pytest.raises(SystemExit) as exc:
+ floor_table.render([result], "t", floors = floors, floor_meta = floor_meta)
+ said = str(exc.value)
+ assert field in said or field.split("_")[0] in said, (
+ f"{field} is part of the comparability key, and a floor differing in it was still "
+ f"applied to a result: {said}"
+ )
+
+
+def test_an_identically_configured_run_still_scores(tmp_path, capsys):
+ """The refusal must not swallow the ordinary case: same everything, still a verdict."""
+ floors, floor_meta, result = _floor_and_result(tmp_path, _meta(), _meta())
+ floor_table.render([result], "t", floors = floors, floor_meta = floor_meta)
+ row = next(
+ line for line in capsys.readouterr().out.splitlines() if line.strip().startswith(METRIC)
+ )
+ assert "faster" in row or "VOID" in row or "SLOWER" in row
+
+
+def test_a_payload_that_disagrees_with_its_own_headers_is_not_scored(tmp_path):
+ """`--resume` after a harness upgrade puts two headers in one file. Neither describes it."""
+ floors, floor_meta, _ = _floor_and_result(tmp_path, _meta(), _meta())
+ out = tmp_path / "two_headers"
+ out.mkdir()
+ rec = Recorder(out / "payload.jsonl", "sess-two")
+ rec.emit(_meta(tool_version = "0.1.0"))
+ rec.emit(_meta(tool_version = "0.2.0"))
+ for row in _ladder(RESULT_100K, RESULT_100K, False):
+ rec.emit(dict(row))
+ rec.close()
+ with pytest.raises(SystemExit) as exc:
+ floor_table.render([out / "payload.jsonl"], "t", floors = floors, floor_meta = floor_meta)
+ assert "disagrees with ITSELF" in str(exc.value)
+
+
+def test_a_payload_with_no_run_meta_at_all_is_not_scored(tmp_path):
+ """Absence is not a wildcard here either. Nothing in such a file says what it measured."""
+ floors, floor_meta, _ = _floor_and_result(tmp_path, _meta(), _meta())
+ out = tmp_path / "headerless"
+ out.mkdir()
+ rec = Recorder(out / "payload.jsonl", "sess-none")
+ for row in _ladder(RESULT_100K, RESULT_100K, False):
+ rec.emit(dict(row))
+ rec.close()
+ with pytest.raises(SystemExit) as exc:
+ floor_table.render([out / "payload.jsonl"], "t", floors = floors, floor_meta = floor_meta)
+ assert "no run_meta" in str(exc.value)
+
+
+# ── both guards have to be reachable from the shipped entry point ────
+
+
+def test_the_cli_applies_both_guards(tmp_path, capsys):
+ """A guard reachable only from a keyword argument nobody passes is not a guard.
+
+ This branch has now hit that three times -- `refuse_partial_censoring` with no caller,
+ `refuse_collisions` behind an unreachable branch, a row type registered nowhere -- so the
+ check is driven through `main`, the way a person runs it.
+ """
+ _null(tmp_path, censored = True)
+ _result(tmp_path)
+ rc = floor_table.main([str(tmp_path / "result"), "--floor", str(tmp_path / "null_censored")])
+ printed = capsys.readouterr().out
+ assert rc == 0
+ row = next(line for line in printed.splitlines() if line.strip().startswith(METRIC))
+ assert "no poolable floor" in row, "the CLI scored against the censored floor"
+ assert "0 metric(s) cleared all three gates." in printed
+
+ older = _write(
+ tmp_path, "older_null", _ladder(NULL_100K, NULL_100K, False), _meta(tool_version = "0.1.0")
+ )
+ newer = _write(
+ tmp_path,
+ "newer_result",
+ _ladder(RESULT_100K, RESULT_100K, False),
+ _meta(tool_version = "0.2.0"),
+ )
+ with pytest.raises(SystemExit) as exc:
+ floor_table.main([str(newer.parent), "--floor", str(older.parent)])
+ assert "tool_version" in str(exc.value)
diff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_partial_censoring.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_partial_censoring.py
new file mode 100644
index 00000000000..ecf718ed183
--- /dev/null
+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_partial_censoring.py
@@ -0,0 +1,475 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A metric censored at some rungs and measured at others must not be printed as a ladder number.
+
+THE GUARD EXISTED AND WAS NEVER CALLED. `payload_rules.refuse_partial_censoring` returned the
+correct refusal from the day it landed, and no scoring or sweep code asked it anything -- its only
+caller was its own selftest. A guard that cannot fire is the same defect as a row type that is
+registered nowhere, and it is the more dangerous of the two, because nothing crashes: the reader
+simply believes the case is covered.
+
+What it was supposed to stop is defect 2. `reasoning_toggle.open_ms` is censored on every cell
+above the 100K rung, because the open settle exceeds the budget and the timing is withheld rather
+than guessed. `paired()` then pools only the cells that could answer, and `render()` prints their
+mean under a bare metric name. On a 100K/500K ladder that row is a 100K-only number wearing a
+ladder label, and the only hint is a smaller `n` beside the other rows -- which is exactly what a
+metric with fewer repetitions looks like.
+
+The refusal LABELS rather than raises. Raising would repeat the mistake this branch's own defect 10
+records: `open_ms` is censored above 100K on every standard and full run, so an exiting guard would
+abort the normal case and be deleted within a day.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from tests.studio.studiobench.scoring import payload_rules
+from tests.studio.studiobench.sweep import floor_table
+
+CENSORED_RUNG = "r500K"
+MEASURED_RUNG = "r100K"
+
+
+def _payload(tmp_path: Path) -> Path:
+ """A standard-tier ladder where `open_ms` answers at 100K and is censored at 500K."""
+ rows: list[dict] = [
+ {
+ "row_type": "run_meta",
+ "tier": "standard",
+ "session_id": "s1",
+ "corpus_hash": "abc",
+ "rungs": ["100K", "500K"],
+ }
+ ]
+ for rung, open_ms in ((MEASURED_RUNG, 1000.0), (CENSORED_RUNG, None)):
+ for arm, mult in (("base", 1.0), ("treatment", 1.1)):
+ for rep in (0, 1):
+ cid = f"{rung}.{arm}.rep{rep}"
+ rows.append(
+ {
+ "row_type": "cell",
+ "cell_id": cid,
+ "session_id": "s1",
+ "completed": True,
+ }
+ )
+ # A control that is measured at BOTH rungs, so the refusal cannot pass by
+ # rejecting everything.
+ rows.append(
+ {
+ "row_type": "action",
+ "cell_id": cid,
+ "session_id": "s1",
+ "action": "keystroke",
+ "ran": True,
+ "timings": {"p50_ms": (50.0 if rung == MEASURED_RUNG else 90.0) * mult},
+ "counts": {},
+ }
+ )
+ if open_ms is None:
+ # Censored: the timing is ABSENT from `timings`, announced in `expect`.
+ rows.append(
+ {
+ "row_type": "action",
+ "cell_id": cid,
+ "session_id": "s1",
+ "action": "reasoning_toggle",
+ "ran": True,
+ "timings": {"close_ms": 300.0},
+ "counts": {},
+ "expect": {"open_censored": True, "close_censored": False},
+ }
+ )
+ else:
+ rows.append(
+ {
+ "row_type": "action",
+ "cell_id": cid,
+ "session_id": "s1",
+ "action": "reasoning_toggle",
+ "ran": True,
+ "timings": {"open_ms": open_ms * mult, "close_ms": 300.0},
+ "counts": {},
+ "expect": {"open_censored": False, "close_censored": False},
+ }
+ )
+ out = tmp_path / "sbench_mine"
+ out.mkdir()
+ path = out / "payload.jsonl"
+ path.write_text("\n".join(json.dumps(r) for r in rows), encoding = "utf-8")
+ return path
+
+
+def test_the_pooling_path_consults_the_censoring_guard(tmp_path):
+ """The guard is reachable from production code, not only from its own test."""
+ path = _payload(tmp_path)
+ found = floor_table.partial_censoring([path])
+ assert "reasoning_toggle.open_ms" in found, (
+ "the sweep pooled a metric that is censored at one rung and measured at another without "
+ "ever asking the guard that exists to refuse it. The guard was dead code."
+ )
+ assert CENSORED_RUNG in found["reasoning_toggle.open_ms"]
+ assert MEASURED_RUNG in found["reasoning_toggle.open_ms"]
+
+
+def test_the_partial_metric_is_marked_unpoolable_and_denied_a_verdict(tmp_path):
+ """It keeps its numbers, loses its claim to the ladder, and cannot clear a gate."""
+ path = _payload(tmp_path)
+ stats = floor_table.summarise([path])
+ assert stats["reasoning_toggle.open_ms"]["poolable"] is False
+ assert "censored" in stats["reasoning_toggle.open_ms"]["censoring"]
+ # The control keeps its verdict: a refusal that swallowed everything would be no refusal.
+ assert stats["keystroke.p50_ms"].get("poolable") is not False
+ assert stats["reasoning_toggle.close_ms"].get("poolable") is not False
+
+
+def test_the_rendered_table_says_so_where_the_number_is_printed(tmp_path, capsys):
+ """The caveat has to travel with the row, because rows get copied out of tables into prose."""
+ path = _payload(tmp_path)
+ floor_table.render([path], "PAIRED PER-METRIC TABLE")
+ printed = capsys.readouterr().out
+ open_line = next(
+ line for line in printed.splitlines() if line.strip().startswith("reasoning_toggle.open_ms")
+ )
+ assert "[*]" in open_line, (
+ "the 100K-only figure was printed under a bare metric name on a 100K/500K ladder, which "
+ "is the survivorship-biased row the guard was written to catch."
+ )
+ assert "NOT A LADDER NUMBER" in printed
+ assert CENSORED_RUNG in printed
+ # The fully measured control is NOT marked.
+ keystroke_line = next(
+ line for line in printed.splitlines() if line.strip().startswith("keystroke.p50_ms")
+ )
+ assert "[*]" not in keystroke_line
+
+
+def test_a_metric_censored_at_every_rung_is_not_a_partial_case(tmp_path):
+ """Nothing survives to be biased, so there is no ladder claim to refuse.
+
+ The distinction matters: refusing here as well would mean the refusal fires on any censoring
+ at all, which is a different and much noisier rule than the one that was asked for.
+ """
+ rows = [
+ {"row_type": "run_meta", "tier": "standard", "session_id": "s1", "corpus_hash": "abc"},
+ ]
+ for rung in (MEASURED_RUNG, CENSORED_RUNG):
+ cid = f"{rung}.base.rep0"
+ rows.append({"row_type": "cell", "cell_id": cid, "session_id": "s1", "completed": True})
+ rows.append(
+ {
+ "row_type": "action",
+ "cell_id": cid,
+ "session_id": "s1",
+ "action": "reasoning_toggle",
+ "ran": True,
+ "timings": {},
+ "counts": {},
+ "expect": {"open_censored": True},
+ }
+ )
+ assert payload_rules.refuse_partial_censoring(rows, "reasoning_toggle.open_ms") is None
+
+
+def _peer_censored_payload(tmp_path: Path) -> Path:
+ """`open_ms` censors above 100K; `close_ms` was measured everywhere but is discarded with it.
+
+ `reasoning_toggle`'s `ok` is one conjunction over four clauses, so a censored open fails the
+ whole action and `_action_timings` then drops every timing it carries -- including a `close_ms`
+ that succeeded on its own terms. `close_censored` stays False, so nothing marked the loss.
+ """
+ rows: list[dict] = [
+ {
+ "row_type": "run_meta",
+ "tier": "standard",
+ "session_id": "s1",
+ "corpus_hash": "abc",
+ "rungs": ["100K", "500K"],
+ }
+ ]
+ for rung, censored in ((MEASURED_RUNG, False), (CENSORED_RUNG, True)):
+ for arm, mult in (("base", 1.0), ("treatment", 1.1)):
+ for rep in (0, 1):
+ cid = f"{rung}.{arm}.rep{rep}"
+ rows.append(
+ {"row_type": "cell", "cell_id": cid, "session_id": "s1", "completed": True}
+ )
+ if censored:
+ rows.append(
+ {
+ "row_type": "action",
+ "cell_id": cid,
+ "session_id": "s1",
+ "action": "reasoning_toggle",
+ "ran": True,
+ "expect_ok": False,
+ "timings": {"close_ms": 900.0 * mult},
+ "counts": {},
+ "expect": {"open_censored": True, "close_censored": False},
+ }
+ )
+ else:
+ rows.append(
+ {
+ "row_type": "action",
+ "cell_id": cid,
+ "session_id": "s1",
+ "action": "reasoning_toggle",
+ "ran": True,
+ "expect_ok": True,
+ "timings": {"open_ms": 1000.0 * mult, "close_ms": 300.0 * mult},
+ "counts": {},
+ "expect": {"open_censored": False, "close_censored": False},
+ }
+ )
+ out = tmp_path / "sbench_peer"
+ out.mkdir()
+ path = out / "payload.jsonl"
+ path.write_text("\n".join(json.dumps(r) for r in rows), encoding = "utf-8")
+ return path
+
+
+def test_a_timing_discarded_with_its_action_counts_as_censored(tmp_path):
+ """The surviving half of a failed action is unavailable too, and must be marked so.
+
+ Unmarked, the close row was pooled from the 100K cells alone and printed +10.0% under a bare
+ metric name on a 100K/500K ladder -- the same survivorship bias the open row is marked for,
+ one level down and completely silent.
+ """
+ path = _peer_censored_payload(tmp_path)
+ found = floor_table.partial_censoring([path])
+ assert "reasoning_toggle.close_ms" in found, (
+ "close_ms was thrown away at 500K with the action that failed, then pooled from 100K and "
+ "printed as a ladder number. Nothing refused it because close_censored was False."
+ )
+ stats = floor_table.summarise([path])
+ assert stats["reasoning_toggle.close_ms"]["poolable"] is False
+ assert stats["reasoning_toggle.open_ms"]["poolable"] is False
+
+
+def test_a_fully_measured_action_is_still_poolable(tmp_path):
+ """The rule must not mark everything: an action that passed keeps its verdict."""
+ path = _payload(tmp_path)
+ stats = floor_table.summarise([path])
+ assert stats["keystroke.p50_ms"].get("poolable") is not False
+ assert stats["reasoning_toggle.close_ms"].get("poolable") is not False
+
+
+def _within_rung_payload(tmp_path: Path) -> Path:
+ """ONE rung, sitting on the settle budget, so some repetitions censor and others do not.
+
+ This is the expected shape near the cutoff rather than a contrived one: censoring is decided
+ per cell against a fixed budget, and `open_ms`'s own spread is 33 to 42%. The censored
+ repetitions are the slow ones, which is exactly why they were censored.
+ """
+ rows: list[dict] = [
+ {
+ "row_type": "run_meta",
+ "tier": "standard",
+ "session_id": "s1",
+ "corpus_hash": "abc",
+ "rungs": ["500K"],
+ }
+ ]
+ for rep, (base_ms, treat_ms, censored) in enumerate(
+ (
+ (6000.0, 6600.0, False),
+ (7000.0, 9200.0, True),
+ (7500.0, 9900.0, True),
+ (6500.0, 11000.0, True),
+ )
+ ):
+ for arm, value, cens in (("base", base_ms, False), ("treatment", treat_ms, censored)):
+ cid = f"{CENSORED_RUNG}.{arm}.rep{rep}"
+ rows.append({"row_type": "cell", "cell_id": cid, "session_id": "s1", "completed": True})
+ if cens:
+ rows.append(
+ {
+ "row_type": "action",
+ "cell_id": cid,
+ "session_id": "s1",
+ "action": "reasoning_toggle",
+ "ran": True,
+ "expect_ok": False,
+ "timings": {},
+ "counts": {},
+ "expect": {"open_censored": True},
+ }
+ )
+ else:
+ rows.append(
+ {
+ "row_type": "action",
+ "cell_id": cid,
+ "session_id": "s1",
+ "action": "reasoning_toggle",
+ "ran": True,
+ "expect_ok": True,
+ "timings": {"open_ms": value},
+ "counts": {},
+ "expect": {"open_censored": False},
+ }
+ )
+ out = tmp_path / "sbench_within"
+ out.mkdir()
+ path = out / "payload.jsonl"
+ path.write_text("\n".join(json.dumps(r) for r in rows), encoding = "utf-8")
+ return path
+
+
+def test_censoring_within_a_single_rung_is_still_partial(tmp_path):
+ """Comparing sets of RUNG NAMES cannot see this, and it is the commonest shape.
+
+ Every rung appears in both the censored and the measured set, so a rung-keyed rule stays
+ silent while `paired()` keeps only the repetitions where both arms answered. The survivor
+ reported +10.0% on n=1 with a full SLOWER verdict; the true paired delta over all four
+ repetitions is +35.7%. What survives is not a sample of the effect, it is a selection against
+ it.
+ """
+ path = _within_rung_payload(tmp_path)
+ stats = floor_table.summarise([path])["reasoning_toggle.open_ms"]
+ assert stats["n"] == 1, "fixture no longer reproduces the survivorship case"
+ assert stats["poolable"] is False, (
+ "three of four treatment repetitions were censored at the only rung in the payload, and "
+ "the one surviving pair was scored as the metric. A rule keyed on rung names cannot see "
+ "censoring that happens WITHIN a rung."
+ )
+ assert "of" in stats["censoring"] and "cells" in stats["censoring"]
+
+
+def test_a_metric_measured_on_every_completed_cell_is_untouched(tmp_path):
+ """The cell-granular rule must not fire on a payload with nothing censored at all."""
+ path = _within_rung_payload(tmp_path)
+ rows = [r for r in floor_table.read_rows(path)]
+ for r in rows:
+ if r.get("row_type") == "action":
+ r["expect_ok"] = True
+ r["expect"] = {"open_censored": False}
+ r.setdefault("timings", {})["open_ms"] = 6000.0
+ assert payload_rules.refuse_partial_censoring(rows, "reasoning_toggle.open_ms") is None
+
+
+def test_a_ladder_split_across_shards_is_judged_as_one_result(tmp_path):
+ """Per-file evaluation lets a rung-disjoint shard set escape the refusal entirely.
+
+ The shard holding the measured 100K cells sees no censoring; the shard holding the censored
+ 500K cells sees censoring at every rung it contains. Neither refuses on its own, and `load()`
+ pools them anyway -- so the same rows are refused in one file and blessed in two.
+ """
+
+ def shard(name: str, rung: str, censored: bool) -> Path:
+ rows: list[dict] = [
+ {
+ "row_type": "run_meta",
+ "tier": "standard",
+ "session_id": "s1",
+ "corpus_hash": "abc",
+ "rungs": ["100K", "500K"],
+ }
+ ]
+ for arm, mult in (("base", 1.0), ("treatment", 1.05)):
+ for rep in (0, 1):
+ cid = f"{rung}.{arm}.rep{rep}"
+ rows.append(
+ {"row_type": "cell", "cell_id": cid, "session_id": "s1", "completed": True}
+ )
+ rows.append(
+ {
+ "row_type": "action",
+ "cell_id": cid,
+ "session_id": "s1",
+ "action": "reasoning_toggle",
+ "ran": True,
+ "expect_ok": not censored,
+ "timings": {} if censored else {"open_ms": 1000.0 * mult + rep},
+ "counts": {},
+ "expect": {"open_censored": censored},
+ }
+ )
+ out = tmp_path / name
+ out.mkdir()
+ path = out / "payload.jsonl"
+ path.write_text("\n".join(json.dumps(r) for r in rows), encoding = "utf-8")
+ return path
+
+ measured = shard("sbench_mine.shard0", MEASURED_RUNG, False)
+ censored = shard("sbench_mine.shard1", CENSORED_RUNG, True)
+ assert floor_table.partial_censoring([measured]) == {}
+ assert floor_table.partial_censoring([censored]) == {}
+ both = floor_table.partial_censoring([measured, censored])
+ assert "reasoning_toggle.open_ms" in both, (
+ "a ladder split across shards escaped the refusal. Identical rows in one file are caught, "
+ "so the verdict depended on which file they were written to."
+ )
+ assert (
+ floor_table.summarise([measured, censored])["reasoning_toggle.open_ms"]["poolable"] is False
+ )
+
+
+def test_one_shards_failed_cell_does_not_censor_another_shards_good_one(tmp_path):
+ """Sharding restarts the repetition counter, so the same `cell_id` names two different cells.
+
+ `CONTRIBUTING-perf.md` prescribes 2 shards of 2 repetitions, and both shards then walk the
+ same ladder writing the same deterministic ids. One ordinary failed cell -- `CellRunner.run`
+ writes `completed: False` and leaves the action row it had already flushed, whose `expect_ok`
+ is False -- is enough: merged on the bare id, that cell is censored in one shard and completed
+ in the other, so the completed-cell filter that exists to discard it stops discarding it. A
+ metric that nothing censored anywhere is then refused as partially censored, and a whole
+ valid row loses its verdict over a cell that contributed nothing to any mean.
+ """
+
+ def shard(name: str, sess: str, failed: set[str]) -> Path:
+ rows: list[dict] = [
+ {
+ "row_type": "run_meta",
+ "tier": "standard",
+ "session_id": sess,
+ "corpus_hash": "abc",
+ "rungs": ["100K", "500K"],
+ }
+ ]
+ for rung in (MEASURED_RUNG, CENSORED_RUNG):
+ for arm, mult in (("base", 1.0), ("treatment", 1.05)):
+ for rep in (0, 1):
+ cid = f"{rung}.{arm}.rep{rep}"
+ bad = cid in failed
+ rows.append(
+ {
+ "row_type": "cell",
+ "cell_id": cid,
+ "session_id": sess,
+ "completed": not bad,
+ }
+ )
+ rows.append(
+ {
+ "row_type": "action",
+ "cell_id": cid,
+ "session_id": sess,
+ "action": "reasoning_toggle",
+ "ran": True,
+ "expect_ok": not bad,
+ "timings": {"open_ms": 1000.0 * mult + rep},
+ "counts": {},
+ "expect": {"open_censored": False},
+ }
+ )
+ out = tmp_path / name
+ out.mkdir()
+ path = out / "payload.jsonl"
+ path.write_text("\n".join(json.dumps(r) for r in rows), encoding = "utf-8")
+ return path
+
+ dead = shard("sbench_mine.shard0", "sessA", {f"{CENSORED_RUNG}.treatment.rep1"})
+ good = shard("sbench_mine.shard1", "sessB", set())
+ assert floor_table.partial_censoring([dead]) == {}
+ assert floor_table.partial_censoring([good]) == {}
+ assert floor_table.partial_censoring([dead, good]) == {}, (
+ "shard0's failed cell borrowed shard1's completion under the same repetition number, so "
+ "a metric censored nowhere was refused as partially censored."
+ )
+ stats = floor_table.summarise([dead, good])["reasoning_toggle.open_ms"]
+ assert stats.get("poolable") is not False
diff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_resumed_collision.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_resumed_collision.py
new file mode 100644
index 00000000000..01c346802c4
--- /dev/null
+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_resumed_collision.py
@@ -0,0 +1,417 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A repeated completed `cell_id` is two runs at once, or it is a resume. They are not the same.
+
+`refuse_collisions` refused every payload holding one `cell_id` completed under two sessions, and
+that is the shape a legitimate resume produces. `ab.skippable_cells` skips a repetition only when
+EVERY arm of it completed, and an A/B with any work left re-runs EVERY pair in one new session, on
+purpose: a lone arm measured in a new session can never be paired, and a partial table publishes a
+verdict over whichever rungs happened to survive. So a resumed comparison writes a second completed
+row under the same deterministic id, and the writer's own docstring says what happens next -- "The
+old attempt stays in the payload and `latest_attempt_rows` supersedes it". Nothing in this module
+superseded anything, so a resumed run could not be scored at all.
+
+WHAT IS ASKED IS WHETHER THE TWO SESSIONS RAN AT ONCE, since that is what makes the readings
+contended, and the payload records it twice over. By the clock: each session's `run_meta` carries
+`started_at` and every row carries `ts_ms`, and on the real two-launcher payload from defect 9,
+`outputs/rp/sbench_F1M_campaign`, the sessions occupy 23:50:24-00:10:03 and 23:53:45-00:12:43,
+sixteen minutes of overlap. By file order: a payload is append-only with one writer per process,
+so a session's rows are one contiguous stretch unless somebody else was writing into the gaps, and
+that same payload's sessions span rows 3-376 and 41-408. Either witness alone can be fooled -- a
+stepped clock, a file written by a tool that batches -- so either one refusing is enough.
+
+SILENCE IS NOT A LICENCE. A payload that cannot show when its sessions ran is refused exactly as
+before. "No proof they overlapped" is not "proof they did not", and this guard stands between a
+reader and a blend of two contending runs.
+
+WHAT THIS MUST NOT REOPEN, and the reason the tests below outnumber the fix. `ui_parity` had the
+neighbouring bug the other way round: a hard-killed null-control cell earned a floor. Superseding
+keys on the LAST attempt that WROTE ANYTHING rather than the last that finished, precisely so a
+resume killed inside a cell -- which has flushed its action rows and never reaches the cell row its
+`finally` would write -- leaves an incomplete cell and drops out, instead of handing the older
+completed reading to a floor as though it were current.
+
+Payloads are written through the real `Recorder`, so the schema, the required keys and the run
+lock are all on the path. The row contents are hand-specified; the interleaving pattern and the
+resume shape are copied from real payloads named above and from `ab.skippable_cells`.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tests.studio.studiobench.runtime.types import Recorder
+from tests.studio.studiobench.sweep import floor_table
+
+METRIC = "message_menu.open_close_ms"
+
+
+#: Wall clock per session. A resume starts after the run it continues has stopped; the real
+#: two-launcher payload of defect 9 overlaps by sixteen minutes, which is what `_at` reproduces
+#: for the concurrent fixtures.
+_STARTED = {
+ "s1": "2026-08-23T00:00:00",
+ "t2": "2026-08-23T02:00:00",
+ "t3": "2026-08-23T04:00:00",
+ "s2": "2026-08-23T00:40:00",
+ "s3": "2026-08-23T01:20:00",
+ "a": "2026-08-23T00:00:00",
+ "b": "2026-08-23T00:00:10",
+ "outer": "2026-08-23T00:00:00",
+ "inner": "2026-08-23T00:00:10",
+}
+
+
+def _meta(sid: str) -> dict:
+ return {
+ "row_type": "run_meta",
+ "tier": "full",
+ "tool_version": "0.2.0",
+ "corpus_hash": "ac9d5d8e",
+ "studio_ref": "attached",
+ "bundle": {"production": True},
+ "platform": {"system": "Linux", "machine": "x86_64", "engine": "chromium"},
+ "started_at": _STARTED[sid],
+ "session_id": sid,
+ "rungs": ["100K"],
+ }
+
+
+def _cell(cid: str, sid: str, completed: bool) -> dict:
+ rung, arm, rep = cid.split(".")
+ return {
+ "row_type": "cell",
+ "cell_id": cid,
+ "session_id": sid,
+ "cell": {"cell_id": cid, "rung": rung, "arm": arm, "rep": rep},
+ "completed": completed,
+ "fidelity": "streamed_and_seeded",
+ }
+
+
+def _action(
+ cid: str,
+ sid: str,
+ ms: float,
+ ok: bool = True,
+) -> dict:
+ return {
+ "row_type": "action",
+ "cell_id": cid,
+ "session_id": sid,
+ "action": "message_menu",
+ "ran": True,
+ "expect_ok": ok,
+ "expect": {},
+ "timings": {"open_close_ms": ms},
+ "counts": {},
+ "slot_missed": False,
+ }
+
+
+def _arm(
+ cid: str,
+ sid: str,
+ ms: float,
+ completed: bool = True,
+ ok: bool = True,
+) -> list[dict]:
+ """One attempt at one arm: its action row, then the cell row that closes it.
+
+ `CellRunner.run` writes the cell row from a `finally`, so it lands after the action rows and
+ only if the process lived to write it.
+ """
+ return [_action(cid, sid, ms, ok), _cell(cid, sid, completed)]
+
+
+def _write(tmp_path, name: str, rows: list[dict]):
+ out = tmp_path / name
+ out.mkdir(parents = True, exist_ok = True)
+ rec = Recorder(out / "payload.jsonl", "sess-" + name)
+ for row in rows:
+ rec.emit(dict(row))
+ rec.close()
+ return out / "payload.jsonl"
+
+
+BASE, TREAT = "r100K.base.rep0", "r100K.treatment.rep0"
+
+
+def _resumed(tmp_path, name = "resumed"):
+ """The shape `skippable_cells` produces: base completed, treatment died, WHOLE pair re-run."""
+ rows = [_meta("s1")]
+ rows += _arm(BASE, "s1", 1000.0)
+ rows += _arm(TREAT, "s1", 900.0, completed = False)
+ rows += [_meta("s2")]
+ rows += _arm(BASE, "s2", 1010.0)
+ rows += _arm(TREAT, "s2", 505.0)
+ return _write(tmp_path, name, rows)
+
+
+def _interleaved(tmp_path, name = "concurrent"):
+ """Two launchers writing at once, in the order the real defect-9 payload shows.
+
+ Emitted through one Recorder because the run lock now stops two of them opening the same
+ directory, which is the write-time half of this guard. What is reproduced is the FILE the two
+ processes left behind: session b opens while session a is still writing, so their stretches
+ overlap.
+ """
+ rows = [_meta("a"), _action(BASE, "a", 1000.0), _meta("b"), _action(BASE, "b", 1400.0)]
+ rows += [_cell(BASE, "a", True), _action(TREAT, "a", 980.0), _cell(BASE, "b", True)]
+ rows += [_cell(TREAT, "a", True), _action(TREAT, "b", 1390.0), _cell(TREAT, "b", True)]
+ return _write(tmp_path, name, rows)
+
+
+# ── the resume must be scored, and scored from the attempt that superseded ──
+
+
+def test_a_resumed_ab_is_scored_rather_than_refused(tmp_path):
+ pooled = floor_table.paired(floor_table.read_rows(_resumed(tmp_path)))
+ assert pooled, (
+ "a resumed A/B was refused outright. `skippable_cells` re-runs every pair of an "
+ "unfinished comparison in one new session, so this is the ordinary shape of a resume, "
+ "not a corner case"
+ )
+ assert pooled[METRIC] == [
+ (1010.0, 505.0)
+ ], "the pair came from the superseded attempt rather than the one the resume just wrote"
+
+
+def test_the_superseded_attempt_is_not_a_second_repetition(tmp_path):
+ """A finished ladder re-run pairs ONCE. Keyed per session without superseding it pairs twice,
+ and one repetition enters the pool under two different sets of numbers."""
+ rows = [_meta("s1")] + _arm(BASE, "s1", 1000.0) + _arm(TREAT, "s1", 500.0)
+ rows += [_meta("s2")] + _arm(BASE, "s2", 1000.0) + _arm(TREAT, "s2", 900.0)
+ pooled = floor_table.paired(floor_table.read_rows(_write(tmp_path, "rerun", rows)))
+ assert pooled[METRIC] == [
+ (1000.0, 900.0)
+ ], "one repetition was pooled twice, so n counts the resume as an independent measurement"
+
+
+def test_a_resume_that_was_itself_hard_killed_resurrects_nothing(tmp_path):
+ """THE HAZARD THIS MUST NOT REOPEN.
+
+ s1 completed the whole pair; the resume re-ran it and was killed inside the treatment cell,
+ which flushes action rows and never reaches the cell row. The older completed reading must not
+ stand in for it -- that is `ui_parity`'s bug, where a hard-killed null-control cell earned a
+ floor and turned a repeated regression from exit 1 into exit 0.
+ """
+ rows = [_meta("s1")] + _arm(BASE, "s1", 1000.0) + _arm(TREAT, "s1", 500.0)
+ rows += [_meta("s2")] + _arm(BASE, "s2", 1010.0) + [_action(TREAT, "s2", 111.0)]
+ pooled = floor_table.paired(floor_table.read_rows(_write(tmp_path, "killed", rows)))
+ assert pooled == {}, (
+ f"the killed resume was scored anyway: {dict(pooled)}. Either the dead attempt's timing "
+ f"was quoted or the superseded completed attempt was resurrected in its place"
+ )
+
+
+def test_the_floor_side_is_reduced_the_same_way(tmp_path):
+ """A null control gets no special treatment, in either direction.
+
+ A resumed null must still produce a floor, and that floor must be the resume's numbers rather
+ than the attempt it replaced.
+ """
+ floors = floor_table.summarise([_resumed(tmp_path, "null_resumed")])
+ assert METRIC in floors
+ assert floors[METRIC]["n"] == 1
+ assert floors[METRIC]["base"] == 1010.0 and floors[METRIC]["treat"] == 505.0
+
+
+# ── the concurrent case must still be refused ────────────────────────
+
+
+def test_two_concurrent_launchers_are_still_refused(tmp_path):
+ with pytest.raises(SystemExit) as exc:
+ floor_table.paired(floor_table.read_rows(_interleaved(tmp_path)))
+ said = str(exc.value)
+ assert "completed under more than one session" in said
+ assert "INTERLEAVE" in said, (
+ "the refusal did not say what actually distinguishes this payload from a resume, so a "
+ "reader cannot tell which of the two they have"
+ )
+ assert "sessions a and b" in said, f"the interleaving sessions were not named: {said}"
+
+
+def test_the_null_control_side_refuses_concurrency_too(tmp_path):
+ with pytest.raises(SystemExit):
+ floor_table.summarise([_interleaved(tmp_path, "null_concurrent")])
+
+
+def test_a_second_run_nested_inside_a_stalled_one_is_caught(tmp_path):
+ """A run that stalls long enough for a whole second run to start and finish inside its gap.
+
+ The nested stretch still overlaps the enclosing one, which is why the check compares spans
+ rather than asking which session was written last.
+ """
+ rows = [_meta("outer"), _action(BASE, "outer", 1000.0)]
+ rows += [_meta("inner")] + _arm(BASE, "inner", 1400.0) + _arm(TREAT, "inner", 1390.0)
+ rows += [_cell(BASE, "outer", True)] + _arm(TREAT, "outer", 980.0)
+ with pytest.raises(SystemExit) as exc:
+ floor_table.paired(floor_table.read_rows(_write(tmp_path, "nested", rows)))
+ assert "INTERLEAVE" in str(exc.value)
+
+
+def test_an_unrelated_interleaved_session_does_not_condemn_a_resume(tmp_path):
+ """The refusal is scoped to the sessions that actually collided.
+
+ A shard file can carry a session that interleaves with nothing this repetition measured. It
+ must not turn a clean sequential resume of a different cell into a refusal.
+ """
+ rows = [_meta("s1")] + _arm(BASE, "s1", 1000.0)
+ rows += _arm(TREAT, "s1", 900.0, completed = False)
+ rows += [_meta("s2")] + _arm(BASE, "s2", 1010.0) + _arm(TREAT, "s2", 505.0)
+ # A third session touching a DIFFERENT rung, written interleaved with s2's stretch.
+ rows.insert(6, _action("r1K.base.rep0", "s3", 12.0))
+ rows.append(_cell("r1K.base.rep0", "s3", True))
+ pooled = floor_table.paired(floor_table.read_rows(_write(tmp_path, "unrelated", rows)))
+ assert pooled[METRIC] == [(1010.0, 505.0)]
+
+
+# ── the censoring guard has to read the rows the numbers came from ───
+
+
+def test_a_superseded_dead_attempt_does_not_mark_a_metric_censored(tmp_path):
+ """`censored_metrics` counts an `expect_ok is False` action as a censored cell.
+
+ A resume exists because the first attempt went wrong, so its rows are exactly the ones that
+ carry failed assertions. Read raw, they would mark the metric partially censored and the
+ resumed run's own clean number would be denied a verdict on the strength of the attempt it
+ replaced.
+ """
+ rows = [_meta("s1")] + _arm(BASE, "s1", 1000.0, ok = False)
+ rows += _arm(TREAT, "s1", 900.0, completed = False, ok = False)
+ rows += [_meta("s2")] + _arm(BASE, "s2", 1010.0) + _arm(TREAT, "s2", 505.0)
+ path = _write(tmp_path, "censor", rows)
+ assert (
+ floor_table.partial_censoring([path]) == {}
+ ), "the superseded attempt's failed assertion was counted against the resume that replaced it"
+ stats = floor_table.summarise([path])
+ assert stats[METRIC].get("poolable") is not False
+
+
+# ── controls: nothing else changes ───────────────────────────────────
+
+
+def test_an_ordinary_single_session_payload_is_untouched(tmp_path):
+ rows = [_meta("s1")] + _arm(BASE, "s1", 1000.0) + _arm(TREAT, "s1", 500.0)
+ pooled = floor_table.paired(floor_table.read_rows(_write(tmp_path, "plain", rows)))
+ assert pooled[METRIC] == [(1000.0, 500.0)]
+
+
+def test_sequential_sessions_with_no_repeated_id_still_pair_within_themselves(tmp_path):
+ """Sharding and extension append sessions legitimately and repeat no id. Unchanged."""
+ rows = [_meta("s1")] + _arm(BASE, "s1", 1000.0) + _arm(TREAT, "s1", 500.0)
+ rows += [_meta("s2")]
+ rows += _arm("r1K.base.rep0", "s2", 20.0) + _arm("r1K.treatment.rep0", "s2", 10.0)
+ pooled = floor_table.paired(floor_table.read_rows(_write(tmp_path, "shards", rows)))
+ assert sorted(pooled[METRIC]) == [(20.0, 10.0), (1000.0, 500.0)]
+
+
+# ── the clock is a second witness, independent of file order ─────────
+
+
+def test_sessions_that_overlap_in_time_are_refused_even_when_the_file_looks_sequential(tmp_path):
+ """Two runs at once whose rows did not happen to interlock in this file.
+
+ The file-order witness sees nothing here: session `a` writes its rows, then `b` writes its
+ own. The clocks say they were running together, and that is the property that makes both sets
+ of numbers contended.
+ """
+ rows = [dict(_meta("a"), started_at = "2026-08-23T00:00:00")]
+ rows += _arm(BASE, "a", 1000.0) + _arm(TREAT, "a", 980.0)
+ rows += [dict(_meta("b"), started_at = "2026-08-23T00:00:01")]
+ rows += _arm(BASE, "b", 1400.0) + _arm(TREAT, "b", 1390.0)
+ # Both sessions occupy about a minute from their own start, so they overlap by the clock.
+ rows = [dict(r, ts_ms = 60_000.0) if r.get("row_type") != "run_meta" else r for r in rows]
+ with pytest.raises(SystemExit) as exc:
+ floor_table.paired(floor_table.read_rows(_write(tmp_path, "clock_overlap", rows)))
+ assert "RUNNING AT THE SAME TIME" in str(exc.value)
+
+
+def test_a_payload_that_cannot_say_when_its_sessions_ran_is_still_refused(tmp_path):
+ """The conservative default, and the shape every older payload has.
+
+ No `run_meta`, so nothing dates either session. Superseding on the strength of file order
+ alone would hand the benefit of the doubt to exactly the payload that cannot account for
+ itself.
+ """
+ rows = _arm(BASE, "s1", 1000.0) + _arm(TREAT, "s1", 500.0)
+ rows += _arm(BASE, "s2", 1010.0) + _arm(TREAT, "s2", 505.0)
+ rows = [{k: v for k, v in r.items() if k != "ts_ms"} for r in rows]
+ with pytest.raises(SystemExit) as exc:
+ floor_table.paired(floor_table.read_rows(_write(tmp_path, "undated", rows)))
+ assert "does not say when its sessions ran" in str(exc.value)
+
+
+def test_naming_a_session_still_reads_that_session(tmp_path):
+ """The escape hatch the refusal itself points at must survive superseding.
+
+ "Split the payload by session, or pass `session=` to score one of them" is the only way to
+ salvage a concurrent payload, and superseding inside a named read would empty the older
+ session and take that away.
+ """
+ path = _resumed(tmp_path, "hatch")
+ rows = floor_table.read_rows(path)
+ first = floor_table.cell_metrics(rows, session = "s1")
+ assert first[BASE][METRIC] == 1000.0, "naming the superseded session returned the resume"
+
+
+# ── the teeth these guards need, found by mutating the fix ───────────
+
+
+def test_a_whole_payload_read_does_not_fall_back_to_the_superseded_cell_row(tmp_path):
+ """`cell_metrics` with no session named is last-writer-wins over `cell_id`.
+
+ A resume killed inside a cell writes no cell row at all, so the row that "wins" is the one the
+ SUPERSEDED attempt wrote, and the stale reading is handed back as though it were current. This
+ is the same shape as `ui_parity`'s hard-killed null-control cell, reached through the other
+ entry point.
+ """
+ rows = [_meta("s1")] + _arm(BASE, "s1", 1000.0) + _arm(TREAT, "s1", 500.0)
+ rows += [_meta("s2")] + _arm(BASE, "s2", 1010.0) + [_action(TREAT, "s2", 111.0)]
+ cells = floor_table.cell_metrics(floor_table.read_rows(_write(tmp_path, "whole", rows)))
+ assert TREAT not in cells, (
+ f"the killed cell came back with {cells.get(TREAT)}, which is the attempt the resume "
+ f"replaced, presented as the current reading"
+ )
+ assert cells[BASE][METRIC] == 1010.0
+
+
+def test_the_file_order_witness_looks_past_the_first_pair_of_sessions(tmp_path):
+ """Three sessions completed the same cell; the two that interlock are the LAST two.
+
+ Their clocks are disjoint, so only file order can see it -- which is the case the second
+ witness exists for, a payload whose `started_at` cannot be trusted.
+ """
+ rows = [_meta("s1")] + _arm(BASE, "s1", 1000.0) + _arm(TREAT, "s1", 500.0)
+ rows += [_meta("t2"), _action(BASE, "t2", 1400.0)]
+ rows += [_meta("t3"), _action(BASE, "t3", 1500.0), _cell(BASE, "t2", True)]
+ rows += [_arm(TREAT, "t2", 1390.0)[0], _cell(BASE, "t3", True)]
+ rows += [_cell(TREAT, "t2", True)] + _arm(TREAT, "t3", 1490.0)
+ with pytest.raises(SystemExit) as exc:
+ floor_table.paired(floor_table.read_rows(_write(tmp_path, "third_pair", rows)))
+ assert "INTERLEAVE" in str(exc.value), (
+ "the interleaving check stopped after the first pair of sessions, so a third run writing "
+ "into a second one's gaps went through"
+ )
+
+
+def test_a_resume_killed_before_it_reached_the_second_arm_leaves_no_pair(tmp_path):
+ """Superseding keys on the attempt that WROTE, not the attempt that FINISHED.
+
+ s1 completed the whole pair. The resume re-ran the base arm and was killed inside it, so it
+ never reached the treatment arm at all. Keyed on the last attempt to FINISH, s1's pair is
+ still the newest completed one and the table prints it -- a reading from a session that was in
+ the middle of being replaced, with no sign that a re-measurement had started and died.
+ `latest_attempt_rows` records the failure that rule already caused: a resume hard-killed
+ inside a cell left the older completed attempt named as the latest, the next `--resume` ran
+ nothing at all, and the run exited 0 over a stale table.
+ """
+ rows = [_meta("s1")] + _arm(BASE, "s1", 1000.0) + _arm(TREAT, "s1", 500.0)
+ rows += [_meta("s2"), _action(BASE, "s2", 4000.0)]
+ pooled = floor_table.paired(floor_table.read_rows(_write(tmp_path, "killed_first_arm", rows)))
+ assert pooled == {}, (
+ f"the superseded session's pair was reported as the reading: {dict(pooled)}. A resume was "
+ f"under way and died; what it replaced is not the current measurement"
+ )
diff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_session_isolation.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_session_isolation.py
new file mode 100644
index 00000000000..dfdab1e0406
--- /dev/null
+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_session_isolation.py
@@ -0,0 +1,275 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Two sessions in one payload must not be collapsed into one, and must not happen in the first
+place.
+
+Found by making the mistake. A launcher was started twice, so two full sessions ran concurrently
+against one `--out` and both appended. `cell_id` is unique within a session and not across them,
+so `cell_metrics` keyed on it alone reported whichever session was written last -- a blend of two
+runs that were contending with each other, under one label.
+
+The numbers below are the real ones from that payload.
+"""
+
+from __future__ import annotations
+
+import os
+
+import pytest
+
+from tests.studio.studiobench.runtime.types import Recorder, new_session_id
+from tests.studio.studiobench.sweep import floor_table
+
+
+def _cell(session: str, cell_id: str, p50: float) -> list[dict]:
+ """One completed cell plus the keystroke action that carries its timing."""
+ return [
+ {
+ "row_type": "action",
+ "session_id": session,
+ "cell_id": cell_id,
+ "action": "keystroke",
+ "ran": True,
+ "timings": {"p50_ms": p50},
+ "counts": {},
+ },
+ {"row_type": "cell", "session_id": session, "cell_id": cell_id, "completed": True},
+ ]
+
+
+def _two_session_payload() -> list[dict]:
+ """The shape that produced the withdrawn +149.8%.
+
+ Session B ran concurrently with session A, so its treatment cells are much slower: 144.5 ms
+ against 73.4 ms for the same cell id.
+ """
+ rows: list[dict] = []
+ for sess, base0, treat0, base1, treat1 in (
+ ("91c4d6d94da8", 45.0, 58.7, 51.1, 73.4),
+ ("430f0b831dda", 37.9, 73.6, 47.3, 144.5),
+ ):
+ rows += _cell(sess, "r1M.base.rep0", base0)
+ rows += _cell(sess, "r1M.treatment.rep0", treat0)
+ rows += _cell(sess, "r1M.base.rep1", base1)
+ rows += _cell(sess, "r1M.treatment.rep1", treat1)
+ return rows
+
+
+def test_cell_metrics_refuses_to_collapse_two_sessions():
+ with pytest.raises(SystemExit) as caught:
+ floor_table.cell_metrics(_two_session_payload())
+ message = str(caught.value)
+ assert "more than one session" in message, (
+ "cell_metrics keyed on cell_id alone and returned the last writer's values. That is how a "
+ "payload holding two concurrent runs reported a 149.8% regression that does not exist."
+ )
+ # The colliding cell is NAMED, not just counted. A refusal that says only "two sessions" sends
+ # the reader back to the payload to find out which reading it was protecting them from.
+ assert "r1M.base.rep0" in message
+ assert "91c4d6d94da8" in message and "430f0b831dda" in message
+
+
+def test_a_resumed_run_is_not_mistaken_for_two_concurrent_ones():
+ """The refusal keys on a COLLIDING COMPLETED CELL, not on the payload holding two sessions.
+
+ `--resume` re-runs the arm that died under a NEW session id into the same shard directory, so a
+ resumed payload legitimately carries two sessions. The attempt that died is not marked
+ completed, so no cell id completes twice and there is nothing to refuse. Keying the refusal on
+ the session count instead would reject every resumed run -- deleting good readings to guard
+ against a collision that is not there.
+ """
+ rows = [
+ {"row_type": "cell", "cell_id": "r100K.base.rep0", "session_id": "s1", "completed": True},
+ # died, then re-run under a new session id
+ {
+ "row_type": "cell",
+ "cell_id": "r100K.treatment.rep0",
+ "session_id": "s1",
+ "completed": False,
+ },
+ {
+ "row_type": "cell",
+ "cell_id": "r100K.treatment.rep0",
+ "session_id": "s2",
+ "completed": True,
+ },
+ ]
+ assert floor_table.collided_cells(rows) == {}
+ assert set(floor_table.cell_metrics(rows)) == {"r100K.base.rep0", "r100K.treatment.rep0"}
+
+
+def test_a_cell_completing_twice_is_what_is_refused():
+ """The other direction: two COMPLETED copies of one cell id is the concurrent-run signature."""
+ rows = [
+ {"row_type": "cell", "cell_id": "r100K.base.rep0", "session_id": "s1", "completed": True},
+ {"row_type": "cell", "cell_id": "r100K.base.rep0", "session_id": "s2", "completed": True},
+ ]
+ assert floor_table.collided_cells(rows) == {"r100K.base.rep0": {"s1", "s2"}}
+ with pytest.raises(SystemExit):
+ floor_table.cell_metrics(rows)
+
+
+def test_a_single_session_payload_is_unaffected():
+ rows = [r for r in _two_session_payload() if r["session_id"] == "91c4d6d94da8"]
+ cells = floor_table.cell_metrics(rows)
+ assert set(cells) == {
+ "r1M.base.rep0",
+ "r1M.treatment.rep0",
+ "r1M.base.rep1",
+ "r1M.treatment.rep1",
+ }
+ assert cells["r1M.treatment.rep1"]["keystroke.p50_ms"] == 73.4
+
+
+def test_a_session_can_be_selected_explicitly():
+ rows = _two_session_payload()
+ a = floor_table.cell_metrics(rows, session = "91c4d6d94da8")
+ b = floor_table.cell_metrics(rows, session = "430f0b831dda")
+ assert a["r1M.treatment.rep1"]["keystroke.p50_ms"] == 73.4
+ assert b["r1M.treatment.rep1"]["keystroke.p50_ms"] == 144.5
+
+
+def _two_session_no_collision() -> list[dict]:
+ """Two sessions in one payload that do NOT collide: each owns its own repetitions.
+
+ The ordinary shape of a sharded or continued run. Session A ran rep0 and rep1, session B
+ added rep2 and rep3, so no cell id ever completes twice and every repetition is a real one.
+ """
+ rows: list[dict] = []
+ for sess, reps in (("91c4d6d94da8", (0, 1)), ("430f0b831dda", (2, 3))):
+ for rep in reps:
+ rows += _cell(sess, f"r1M.base.rep{rep}", 40.0 + rep)
+ rows += _cell(sess, f"r1M.treatment.rep{rep}", 60.0 + rep)
+ return rows
+
+
+def test_paired_keys_on_the_session_and_does_not_cross_match():
+ """Pairing must not match one session's base against another session's treatment.
+
+ Built on a payload whose sessions do not collide, because the colliding one is now refused
+ outright and a test that pooled it would be asserting the guard stays silent.
+ """
+ pairs = floor_table.paired(_two_session_no_collision())["keystroke.p50_ms"]
+ assert sorted(pairs) == sorted([(40.0, 60.0), (41.0, 61.0), (42.0, 62.0), (43.0, 63.0)]), (
+ "pairing crossed the sessions. Two sessions both produce rep0, so a key without the "
+ "session matches a base measured under one machine load against a treatment measured "
+ "under another and calls it a repetition."
+ )
+ assert len(pairs) == 4
+
+
+def test_pairing_refuses_a_payload_whose_cells_completed_twice():
+ """The refusal has to sit on the path that actually pools, not only on the one nobody calls.
+
+ `paired` always selects a session, so the refusal inside `cell_metrics` was unreachable from
+ the shipped path. On the real two-launcher payload it returned four pairs drawn from two cells
+ and `summarise` reported keystroke `p50_ms` up 93.4% -- a figure neither session measured, the
+ two having read +37.0% and +149.8%, presented as four independent repetitions.
+ """
+ with pytest.raises(SystemExit) as caught:
+ floor_table.paired(_two_session_payload())
+ assert "completed under more than one session" in str(caught.value)
+
+
+def test_the_refusal_does_not_send_the_reader_to_a_function_that_also_refuses():
+ """The message used to end 'or use `paired`, which pairs within a session.'
+
+ Once `paired` refuses the same payload that sentence is a loop, and a refusal that hands the
+ reader a remedy which fails the same way is worse than one that says nothing.
+ """
+ with pytest.raises(SystemExit) as caught:
+ floor_table.cell_metrics(_two_session_payload())
+ message = str(caught.value)
+ assert "use `paired`" not in message
+ assert "Split the payload by session" in message
+
+
+def test_sessions_in_lists_only_completed_cells():
+ rows = _two_session_payload() + [
+ {
+ "row_type": "cell",
+ "session_id": "deadbeef",
+ "cell_id": "r1M.base.rep2",
+ "completed": False,
+ }
+ ]
+ assert floor_table.sessions_in(rows) == {"91c4d6d94da8", "430f0b831dda"}
+
+
+# ── the write-time guard ────────────────────────────────────────────────────
+
+
+def test_a_second_live_session_is_refused(tmp_path):
+ first = Recorder(tmp_path / "payload.jsonl", new_session_id())
+ try:
+ with pytest.raises(SystemExit) as caught:
+ Recorder(tmp_path / "payload.jsonl", new_session_id())
+ assert "still running" in str(caught.value), (
+ "a second concurrent run was allowed to append to a live output directory. Both runs "
+ "then contend with each other and write the same cell ids into one file."
+ )
+ finally:
+ first.close()
+
+
+def test_the_directory_is_reusable_once_the_first_run_closes(tmp_path):
+ first = Recorder(tmp_path / "payload.jsonl", new_session_id())
+ first.close()
+ second = Recorder(tmp_path / "payload.jsonl", new_session_id())
+ second.close()
+
+
+def test_a_marker_from_a_dead_process_does_not_block_forever(tmp_path):
+ """A crashed run must not lock the directory against every later one."""
+ stale = tmp_path / ".running.deadsession"
+ tmp_path.mkdir(parents = True, exist_ok = True)
+ # A pid that cannot be alive: this process's own pid is taken, so use one past the max.
+ with open("/proc/sys/kernel/pid_max", encoding = "utf-8") as fh:
+ dead_pid = int(fh.read().strip()) - 1
+ stale.write_text(f"{dead_pid} deadsession\n", encoding = "utf-8")
+ if _pid_alive(dead_pid):
+ pytest.skip("the chosen pid happens to be alive")
+ rec = Recorder(tmp_path / "payload.jsonl", new_session_id())
+ rec.close()
+ assert not stale.exists(), "a marker naming a dead process should be cleared, not obeyed"
+
+
+def _pid_alive(pid: int) -> bool:
+ try:
+ os.kill(pid, 0)
+ except OSError:
+ return False
+ return True
+
+
+# ── the rows these guards emit must actually be emittable ──────────────────
+
+
+def test_the_new_row_types_are_registered_in_the_schema(tmp_path):
+ """A guard that cannot write its own row is a guard that crashes the run it protects.
+
+ Both of these were added and neither was registered in ROW_TYPES, so the first clean run
+ aborted two seconds in with `row_type must be one of [...], got 'comparability'`. The emitter
+ and the schema have to move together.
+ """
+ rec = Recorder(tmp_path / "payload.jsonl", new_session_id())
+ try:
+ rec.emit(
+ {
+ "row_type": "cell_aborted",
+ "cell_id": "r1M.treatment.rep0",
+ "reason": "budget exhausted",
+ }
+ )
+ rec.emit(
+ {
+ "row_type": "comparability",
+ "key": "cmp:0123456789",
+ "fields": {"corpus_hash": "ac9d5d8e"},
+ }
+ )
+ finally:
+ rec.close()
+ written = (tmp_path / "payload.jsonl").read_text(encoding = "utf-8")
+ assert "cell_aborted" in written and "comparability" in written