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: measure the composer click instead of dying on it, and the 500K and 1M rungs (#9356)

Daniel Han0e1968dc61b2
diff --git a/tests/studio/studiobench/CONTRIBUTING-perf.md b/tests/studio/studiobench/CONTRIBUTING-perf.md
index 83be0e8af0f..37e9fb196bc 100644
--- a/tests/studio/studiobench/CONTRIBUTING-perf.md
+++ b/tests/studio/studiobench/CONTRIBUTING-perf.md
@@ -54,7 +54,10 @@ See **"You need a Studio, and you need its password"** in [README.md](README.md)
run the first one: a missing `--password` fails as an HTTP 401 only after the browser has
already started, and `--doctor` reports PASS on that exact configuration. If you drive the wave
against Studios you started yourself rather than letting studiobench install them, `--ab` needs
-`--attach` **and** `--attach-b`, one URL per arm, or it exits before measuring anything.
+`--attach` **and** `--attach-b`, one URL per arm, or it exits before measuring anything. It also
+needs `--password` **and** `--password-b`, one per arm: two separately booted Studios mint two
+different bootstrap passwords, so a single `--password` is a 401 on the treatment alone, after
+the browser is already up.
`--assert-liveness` is strict on purpose and an action that could not run is a real finding, not
noise. But two of the eighteen are unreachable on a fixture that loads no model (`image_upload`
@@ -150,6 +153,50 @@ Virtualization, windowing and progressive mount all change what is mounted by de
reports differences everywhere and proves nothing. For those changes parity means screenshots at
matched scroll positions plus the behavioural invariants below.
+### When the equivalence is proved by a differential, the fixture is the claim
+
+Some optimisations are not "the DOM still matches" but "this cheaper path returns the same bytes as
+the expensive one it replaces". You prove those with a randomized differential: generate inputs,
+run both paths, compare. The number of frames it clears is then quoted as the evidence, so the
+generator, not the run, is what the claim actually rests on.
+
+Two ways that goes wrong, both paid for on unslothai/unsloth#9517, where the cheap path repaired a
+bounded window of an open code fence instead of the whole tail:
+
+- **A fixture that generates only short lines cannot find a bug about long ones.** The first sweep
+ reported byte-identical output on 17,436 adversarial open-fence frames and was quoted in the pull
+ request. Every generated piece was a short line, so the window never elided a whole line, and the
+ bug lived exactly there: a whitespace-only line longer than the window moved the cut past it, and
+ the repair then appended a zero-width space into code that the copy button would put on the
+ clipboard. A reviewer found it by reading. Adding lines longer than the window, whitespace-only
+ and not, immediately produced 60 divergences, and then a second, unrelated family of 57.
+- **A clean result from a fixture you built yourself is weaker evidence than a clean result from one
+ designed to break you.** The two are not the same measurement and should not carry the same
+ weight in a pull request. Before quoting a differential, write down the dimension your generator
+ varies and the dimension it holds constant, and go looking for a bug in the constant one.
+
+A corollary about hunting the second bug: **a check that comes back clean against code you believe
+is broken is usually a hole in the check.** The first probe for that second family reported the
+production code unaffected, and the reason was that its head set contained no stray backtick before
+the fence. It was reachable. Prove reachability against the real code path with the real input
+before deciding a class of bug does not apply.
+
+### Getting a guard backwards costs a sweep, so state its direction in words first
+
+The same round produced two guards that were written the wrong way round and only caught by
+re-sweeping:
+
+- The refusal gated the cut **from below** when the risk is a cut landing **past** the marker.
+ The condition and its inverse both read plausibly at the call site.
+- It then tracked the **last** marker in the body when the one that matters is the **first**: a
+ marker sitting in the retained window masks an earlier one sitting in the elided middle, which is
+ the half that gets dropped. First is also monotone, so it is the cheaper thing to carry anyway.
+
+Write the invariant as a sentence about which region must be clean before writing the comparison,
+and keep the shrunk reproducers verbatim in the test with a comment saying so. Both of these needed
+a stray backtick before the fence, a longer opener and an escaped fence inside it; a tidier-looking
+case stops covering the bug.
+
## 5. Invariant counts: the metrics whose sign means the opposite
Rows named `action.count.key` are correctness invariants, not timings, and the table scores them
@@ -248,6 +295,181 @@ straight line makes a *null* informative, which an on/off arm cannot do.
Which knob removes the slope names the fix. If none does, your hypothesis was wrong, and saying so
is a better contribution than a fix aimed at the wrong mechanism.
+## The `content-visibility` trap, in full
+
+This mechanism has cost this project three separate investigations and produced two nulls that were
+not nulls. It is written out here so nobody spends a fourth day on it. **Do not open another
+`content-visibility: auto` arm on the message roots.** The arm is dead, for the reason in the last
+subsection, and it is dominated: deferring off-screen fence highlighting monotonically reaches
+LayoutObjects -74.0% and `pre span` -96.9% at the same rung with a viewport `scrollHeight` delta of
+**0 px**, byte-identical `selected_chars`, and `select_all_ms` at -67.5% instead of +33%.
+
+Everything below generalises past this one property, which is why it is here and not in a commit
+message.
+
+### How to prove an arm fired
+
+`contentvisibilityautostatechange` is emitted by Blink's own relevance machinery and by nothing
+else. No stylesheet, no selector and no author code can produce one. That makes it a potency
+counter of a strictly stronger kind than anything you can read out of `getComputedStyle`.
+
+The method: before writing any property, attach a listener to every candidate element exactly once,
+and count events by `event.skipped`. Then run the same probe on a control arm that has no rule at
+all. On a 100K thread this read **193 `skipped === true` events on the armed side against exactly 0
+on the control**, with 384 state changes in total and 22 roots simultaneously in the skipped state.
+
+A computed-value read cannot give you that. Computed `content-visibility: auto` proves only that
+the declaration won the cascade. An element can compute to `auto` and be painted on every frame
+because it never stopped being relevant to the user, and then your arm reads null for a reason that
+has nothing to do with rendering.
+
+`arms/content_visibility_probe.js` is the working probe. Install it with
+`SBENCH_EXTRA_INIT_SCRIPT`, read it back with `SBENCH_PAGE_CONSOLE="CVPOT "`. Both are unset by
+default, so a scored run is unaffected. A probe run drives a real Studio like everything else in
+the loop, so it needs the credentials above; the file's own header carries the full command.
+
+A run carrying a probe is **not scorable**, because the probe samples the DOM and forces layout on
+its own schedule. That is a gate, not a convention. The init script's path is written into
+`run_meta.probe_init_script`, the run records a `probe_free` gate, and **all three scoring entry
+points refuse the payload on that evidence**: the session prints no `ab.md` at the end, `--report`
+refuses, and `floor_table` refuses. There is no flag to override any of them. The payload is still
+kept, because `--assert-liveness` and the probe's own output are exactly what you wanted from that
+run. Re-run with the variable unset to get a number.
+
+Into a **fresh `--out`**, though, because that refusal is whole-file. `run_meta.probe_init_script`
+is on the payload identity, so `--resume` refuses before anything is installed when the variable
+was set for the payload and not for this run or the other way round. Without that refusal a
+variable still set in the shell from an earlier experiment turned a half-finished clean ladder into
+a file no reader will ever accept, cells already recorded included, and a payload is append-only.
+
+A probe must be **self-contained**. Playwright does not define the evaluation order of separate
+init scripts, and the scene scripts are deliberately kept as separate scripts so that a throw in
+one cannot stop the others, so a probe cannot assume `window.__sb` exists when it is installed.
+A probe that fails to install is **reported, never silent**: one that did not run to the end is
+named on the console, and one that parsed and then threw arrives as a `pageerror` too, so the pair
+says which of the two happened and the run log carries both. On chromium and firefox a probe that
+does not parse also leaves the scene scripts alone.
+On **webkit**, the default engine on Linux and macOS, it does not: Playwright hands webkit its init
+scripts as one bootstrap unit, so a syntax error in the probe stops dom.js, parity.js and
+surfaces.js as well. The probe is installed as plain source rather than through `eval` because
+Studio serves `script-src 'self'` with no `'unsafe-eval'`, and webkit enforces that against an init
+script, so an eval-installed probe never ran there at all. The source **opens** its script, with
+nothing put in front of it, so a probe that begins `"use strict"` keeps its directive prologue and
+runs under the semantics the file was written for.
+
+Attach your listeners at **insertion**, from a `MutationObserver` installed before the app boots,
+not on your sampling tick. `contentvisibilityautostatechange` fires on a *change* of state, and a
+root inserted off screen becomes skipped once and then never changes again while the user stays
+put. A whole seeded thread mounts inside two seconds, so a probe that adopts roots on a two-second
+tick misses every one of their only events and reports zero.
+
+### The geometry route is self-defeating
+
+This is the subtle one, and it is the first thing everyone reaches for.
+
+The reasoning is sound: a skipped subtree is not laid out, so its element descendants generate no
+layout boxes, so counting boxes should tell you whether skipping happened. The measurement is still
+useless, because **asking is what breaks it**. `getClientRects()` on content inside a locked subtree
+makes Chromium render that subtree in order to answer. The probe unlocks exactly what it came to
+observe.
+
+Measured side by side in one session, the geometry route reported **0 off-screen unrendered roots
+while the event counter recorded 22 roots in the skipped state**. Read on its own it is a clean,
+confident, wrong "the arm did not fire". Use the events.
+
+The same forced render is the mechanism behind the select-all cost below, so this is not a quirk of
+the instrument. It is the property under test biting the instrument.
+
+### The cascade rule that silently voids an arm
+
+`index.css` opens `@layer utilities` at **line 1051** and closes it at **line 2572** (check by brace
+depth, not by eye). Inside it, at **lines 2565-2567**:
+
+```css
+.aui-thread-root [data-streamdown="code-block"] {
+ content-visibility: visible !important;
+ contain-intrinsic-size: none !important;
+}
+```
+
+Per css-cascade-5 the sorting order is Origin and Importance, then Context, then **Element-Attached
+Styles**, then **Layers**, then Specificity, then Order of Appearance, and for important rules the
+declaration in the **earliest** layer wins while unlayered declarations sit in an implicit **final**
+layer. So:
+
+- an **unlayered** `content-visibility: auto !important` on code blocks **loses** to that rule at
+ any specificity, however many `html body` prefixes you pile on;
+- an **inline** `!important` **wins**, because Element-Attached Styles are checked before Layers;
+- a rule targeting the **message roots** never contests it at all, because that selector matches
+ code blocks only.
+
+An arm that loses this way reports a perfectly clean null. If you inject CSS, emit it into the same
+layer or inline, and then verify with `getComputedStyle` before you believe any timing.
+
+Worth knowing separately: a descendant's `content-visibility: visible` does **not** stop an ancestor
+from skipping. In the session above the code blocks kept computing to `visible` on both arms and
+their message roots skipped anyway.
+
+### You cannot opt out of the last remembered size
+
+Chromium ships `content-visibility: auto` **implies** `contain-intrinsic-size: auto` (Blink intent
+"content-visibility: auto implies contain-intrinsic-size: auto", CSSWG issue #8407). Declaring a
+plain `<length>` does not opt out: on Chromium 151, `contain-intrinsic-size: 300px` on such an
+element computes back as `auto 300px`. A variant built with the keyword deliberately removed
+produced byte-identical geometry to one with it, which is what that behaviour predicts and which
+wastes a build and a run if you have not read this.
+
+### The actual killer: a remembered size of zero
+
+`contain-intrinsic-size: auto <length>` uses the **last remembered size** and falls back to the
+`<length>` only if one does not yet exist (css-sizing-4 5.2, 5.2.1). The fallback being too small is
+the failure everyone anticipates. It is not the one that happens here.
+
+A message root is mounted **before its content arrives**, so the remembered size is recorded while
+the root is empty, and it is recorded as zero. The root is then skipped and frozen at zero forever.
+Measured at rest on a freshly loaded 100K thread, 13 of 18 roots reported their **padding alone**
+(18 px and 40 px), and the raw height list carried no root at 318 px or 100 px, which is where the
+declared 300 px and 60 px fallbacks would have put one: `getBoundingClientRect()` is the border box,
+so a fallback-sized root measures the fallback *plus* the root's padding. The thread's scroll height
+read **58,355 px on the control against 11,949 px armed** (min 5,101). The concurrent null control
+read 58,355 against 58,355, to the pixel.
+
+It self-heals: once the user has scrolled the whole thread, real sizes get remembered and the armed
+side climbs back to ~58,000 px. So the damage is on load and after every remount, which is the worst
+possible shape for it to have. **Static CSS has no way to override a remembered size.**
+
+UI parity records the same thing from the other side: **0 of 64 action pairs matched** on the armed
+comparison against **47 of 64** for the null in the same wave. Every timing from an arm in that
+state is a bound at best.
+
+### The select-all cost
+
+Skipped content has to be rendered before it can be selected, so select-all pays for the unlock.
+Three independent measurements, all at the 100K rung:
+
+| run | base | armed | delta | n | floor | verdict |
+| --- | --- | --- | --- | --- | --- | --- |
+| `u6i_` sweep | | | **+28.8%** | 4 | 16.7% | cleared |
+| probe run, fast tier | 176.2 ms | 236.1 ms | **+34%** | 2 | none | direction only |
+| `cvs1_` standard tier | 196.2 ms | 250.8 ms | **+33.2%** | 4 | 37.5% | **void**, spread 71.5% |
+
+Stated honestly: the third run's own scatter was wider than its effect, so gate 3 voided it. Three
+measurements agreeing on sign and magnitude is not the same as one that cleared the gates, and the
+row above is the one to quote. The mechanism is not in doubt; the certification is.
+
+`select_all_copy.count.selected_chars` did **not** fall (194,992 against 195,006), which is the
+expected direction: the selection forces the content back into existence, so the clipboard is intact
+and only the clock suffers.
+
+### The 60.2 versus 64.8 figure is not a message-roots null
+
+This number has circulated as evidence that `content-visibility: auto` on message roots does
+nothing. It is not that measurement. It was `content-visibility: auto` on the **reasoning pane's
+code blocks**, PR 9073, **n=1, no floor**, and PR 9073's own investigation notes had already
+withdrawn it for the cascade reason two subsections above: the rule lost to `index.css:2566` and the
+arm never fired. Please stop citing it. The message-roots arm was never null; it fires hard and dies
+on geometry instead.
+
## If you have many cores
Running several comparisons at once is fine and is how the 40-PR audit was done, but contention is a
diff --git a/tests/studio/studiobench/INTERFACES.md b/tests/studio/studiobench/INTERFACES.md
index b894fc0585b..24b2887cbd1 100644
--- a/tests/studio/studiobench/INTERFACES.md
+++ b/tests/studio/studiobench/INTERFACES.md
@@ -68,7 +68,7 @@ accumulate. Windows do not nest and do not overlap; opening one while another is
@dataclass
class Window:
name: str # "action:scroll_after", "stream:gap3", "idle:calibrate"
- kind: str # "action" | "stream" | "gap" | "idle" | "settle" | "teardown"
+ kind: str # "action" | "stream" | "gap" | "idle" | "setup" | "settle" | "teardown"
cell: Cell
t_open_ms: float # driver monotonic ms since session t0
t_close_ms: float | None
@@ -89,6 +89,13 @@ The NAMES still read `stream:gapN`, because they are the join key in every paylo
Trust the `kind`, not the name, and to find the streaming phase itself detect it from the SSE
traffic rather than from either.
+**`setup` is not `action`, for the same class of reason.** The only `setup` window is
+`setup:composer_click`, the click that starts the film. Most of what it costs is Playwright's own
+injected actionability script -- selector resolution, visibility, stability and the
+`elementsFromPoint` hit test -- and that script runs on the PAGE'S main thread, so it blocks frames
+indistinguishably from app work. At 500K the window is around 11 s against a `max_frame_ms` anchor
+whose worst case is 2,000 ms. It is instrumented and reported, and `scoring/from_payload.py` keeps
+it out of the frame pool via `UNSCORED_WINDOW_KINDS`.
Opened as a context manager on the session:
```python
diff --git a/tests/studio/studiobench/__main__.py b/tests/studio/studiobench/__main__.py
index 49c012bb2df..c6979aa686a 100644
--- a/tests/studio/studiobench/__main__.py
+++ b/tests/studio/studiobench/__main__.py
@@ -580,14 +580,45 @@ def run(args, ab_ref = None) -> int:
corpus = Corpus.load()
_log(f" corpus_hash {corpus.corpus_hash}")
+ # READ NOW, BEFORE ANYTHING IS STARTED OR MOVED. The probe's source is not needed until the
+ # browser is launched, but reading it there means a path typo raises after Studio and the pacer
+ # are up and before the cleanup `finally` that would stop them is entered, so a detached Studio
+ # keeps running and holds its port. The cheapest correct fix is to fail while there is nothing
+ # to clean up: a missing, unreadable or non-UTF-8 file is a mistake in the invocation, and the
+ # right moment to say so is the first second of the run.
+ #
+ # AHEAD OF `prepare_payload` FOR THE SAME REASON THE ARCHIVE IS AHEAD OF THE RECORDER. Reusing
+ # an `--out` without `--resume` archives the payload that is already there, so reading the
+ # probe afterwards meant a path typo exited 2 having run no benchmark and having already taken
+ # `payload.jsonl` off the path every reader looks at: `--report`, `--assert-liveness` and the
+ # next `--resume` all open that name. A refusal that the first millisecond of the run could
+ # have issued must not cost the previous run's payload its standard path.
+ extra_init = os.environ.get("SBENCH_EXTRA_INIT_SCRIPT")
+ extra_init_source = ""
+ if extra_init:
+ try:
+ extra_init_source = Path(extra_init).read_text(encoding = "utf-8")
+ except (OSError, UnicodeDecodeError) as exc:
+ _log(
+ f" FATAL: SBENCH_EXTRA_INIT_SCRIPT={extra_init} could not be read: "
+ f"{type(exc).__name__}: {exc}"
+ )
+ return 2
+
# BEFORE the first install, the first launch and the first recorded row. See `prepare_payload`:
# a refusal that arrives after two clones and two builds has cost the caller an hour to say
# something it could have said in a millisecond, and an archive that arrives after the Recorder
# has opened the file has already appended this run's header to the payload it was moving.
- prepare_payload(
+ archived = prepare_payload(
paths, requested_identity(args, ab_ref, corpus.corpus_hash), resume = bool(args.resume)
)
+ # AND THE REPORTS THE ARCHIVE LEFT BEHIND. See `invalidate_stale_reports`: this is the one
+ # point every reuse of an output directory passes through, whichever of the two ways it
+ # invalidates what is already sitting there.
+ invalidate_stale_reports(paths.out, archived = archived, extra_init = extra_init)
+
+ # One spec per side, with its own home and password. Without --ab there is exactly one.
specs = side_specs(args, ab_ref)
# Armed AFTER the sides are known, because what it has to cover depends on them: see
# `watchdog_deadline_s`. Nothing between here and there can hang -- `Corpus.load` reads a
@@ -804,14 +835,46 @@ def run(args, ab_ref = None) -> int:
)
auth = sides[0]["auth"]
+
+ # ONE `add_init_script` CALL PER SCENE SCRIPT, which is what this always did.
+ #
+ # These were briefly concatenated into a single script, on the reasoning that Playwright
+ # says "the order of evaluation of multiple scripts installed via
+ # browserContext.addInitScript() and page.addInitScript() is not defined", and surfaces.js
+ # reads what dom.js and parity.js put on `window.__sb`. The reasoning is sound and the
+ # change was a REGRESSION, caught by CI: joining them means the browser parses and
+ # evaluates the three as one unit, so a throw or a parse error in any one of them stops
+ # the other two running as well. Separate scripts are separate failure domains, and on the
+ # CI fixture that difference cost `message_menu` its More button and turned a green job
+ # red. An ordering guarantee is not worth trading fault isolation for when the ordering
+ # has been correct in practice for the life of the file.
+ #
+ # surfaces.js is loaded unconditionally, even without --surfaces. It defines selectors and
+ # never runs on its own. Making the page's JS depend on a CLI flag would mean the flag
+ # changes what is on the page during the FILM as well, and the film's numbers must not
+ # depend on whether a later phase was asked for.
init_scripts.append(resources.read_text("scene/dom.js"))
init_scripts.append(resources.read_text("scene/parity.js"))
- # Loaded unconditionally, even without --surfaces. It defines selectors and reads dom.js and
- # parity.js; it never runs on its own. Making the page's JS depend on a CLI flag would mean
- # the flag changes what is on the page during the FILM as well, and the film's numbers must
- # not depend on whether a later phase was asked for.
init_scripts.append(resources.read_text("scene/surfaces.js"))
+ # AN EXTERNAL PROBE OR ABLATION ARM, its own script like the three above. One environment
+ # variable rather than a CLI flag per experiment, and WITH THE VARIABLE UNSET NOTHING IS
+ # APPENDED: the run is byte-identical to a run of a tree that does not have this hook. That
+ # property is the point. A potency probe perturbs the page it observes, so the probe run and
+ # the scored run have to be different runs of one harness, and the only safe way to arrange
+ # that is for the probe to be absent by default.
+ #
+ # BECAUSE THE ORDER IS UNDEFINED, A PROBE MUST BE SELF-CONTAINED. It cannot assume the
+ # scene scripts have run, so it cannot read `window.__sb` at install time. That is a real
+ # constraint and it is written down in CONTRIBUTING-perf.md rather than papered over with
+ # a guarantee this file is not in a position to give.
+ if extra_init:
+ init_scripts.extend(_probe_init_scripts(extra_init, extra_init_source))
+ _log(
+ f" EXTRA INIT SCRIPT: {extra_init} -- this run carries an external probe and "
+ f"is NOT a clean measurement of the build"
+ )
+
procs_before = {}
try:
from .instruments.rss import new_roots, snapshot_children
@@ -822,6 +885,31 @@ def run(args, ab_ref = None) -> int:
bundle = browser_mod.launch(
args.engine, headless = not args.headed, init_scripts = init_scripts, log = _log
)
+ # THE RETURN PATH for a probe installed by the hook above. Studio ships `connect-src
+ # 'self'`, so a beacon to a collector on another port is blocked by CSP before it leaves
+ # the page, and the payload schema has no row for a one-off probe. The console is what is
+ # left. Lines are filtered on a caller-supplied prefix so they can be recovered from the
+ # run log by exact match, and so a probe cannot drown the log in the app's own traffic.
+ console_prefix = os.environ.get("SBENCH_PAGE_CONSOLE")
+ if console_prefix:
+ bundle.page.on(
+ "console",
+ lambda m: _log(f" [page] {m.text}") if m.text.startswith(console_prefix) else None,
+ )
+ if extra_init:
+ # A probe that throws on load is the same silence as a probe that was never installed,
+ # and the console filter above cannot show it because a failing probe never gets as far
+ # as printing its own prefix. Attached only when a probe was asked for, so an ordinary
+ # run is unchanged. `console.error` from the isolation wrapper arrives here as a
+ # console message rather than a page error, so both channels are listened to.
+ bundle.page.on("pageerror", lambda err: _log(f" [page error] {err}"))
+ bundle.page.on(
+ "console",
+ lambda m: _log(f" [page error] {m.text}")
+ if m.type == "error" and "SBENCH_EXTRA_INIT_SCRIPT" in m.text
+ else None,
+ )
+
procs = []
if new_roots is not None:
time.sleep(1.0)
@@ -884,6 +972,15 @@ def run(args, ab_ref = None) -> int:
# 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
@@ -922,6 +1019,29 @@ def run(args, ab_ref = None) -> int:
else "standard measurement protocol",
},
)
+ # THE SAME SHAPE OF GATE, for the same reason. A probe forces layout on a schedule of its
+ # own, so its payload is perturbed, and "the docs say probe payloads are never scored" is a
+ # convention rather than a gate. A convention is what this subsystem keeps being wrong
+ # about: the run still records ordinary cells and still renders an A/B table, so a probe
+ # invocation on the standard tier produces something that reads exactly like a result. The
+ # gate is what lets `floor_table` refuse it instead of trusting the caller to remember.
+ rec.gate(
+ "probe_free",
+ not extra_init,
+ {
+ "probe_init_script": extra_init or None,
+ "reason": (
+ "an external init script was installed via SBENCH_EXTRA_INIT_SCRIPT, so this "
+ "page was instrumented while it was measured"
+ )
+ if extra_init
+ else "no external init script was installed",
+ },
+ )
+ if extra_init:
+ _log("")
+ _log(" PROBE RUN: this payload is NOT scorable. floor_table will refuse it.")
+ _log("")
image_path = ensure_probe_image(paths)
for side in sides:
@@ -934,6 +1054,7 @@ def run(args, ab_ref = None) -> int:
pacer = pacer,
seeder = side_seeder,
corpus = corpus,
+ click_probe = bool(getattr(args, "click_probe", False)),
base_url = side["base_url"],
model_id = model_id,
tier = args.tier,
@@ -1161,6 +1282,86 @@ def _sweep_surfaces(sides: list, ctx, paths) -> None:
ctx.recorder.gate(f"surface_sweep:{label}", passed, manifest)
+def _probe_init_scripts(path: str, source: str) -> list[str]:
+ """The external script AS SOURCE, plus a separate script that says when it did not install.
+
+ NO `eval`, AND THAT IS THE WHOLE POINT. This used to hand the file to indirect eval as a
+ string, so that a malformed probe degraded to a caught `SyntaxError` instead of taking the
+ scene scripts with it. Studio serves `script-src 'self'` with no `'unsafe-eval'`
+ (`studio/backend/main.py::_build_csp`), and `runtime/browser.py::default_engine` picks WEBKIT
+ on both Linux and macOS, so on the DEFAULT engine that eval was refused by CSP and the probe
+ never installed at all. Measured against a page served with Studio's own header:
+
+ chromium indirect eval runs; a bad init script leaves the other init scripts alone
+ firefox indirect eval runs; a bad init script leaves the other init scripts alone
+ webkit indirect eval REFUSED; a bad init script kills every other init script
+
+ So the isolation the wrapper was bought for does not exist on webkit either way -- Playwright
+ installs webkit's init scripts as one bootstrap unit -- and on the two engines where it does
+ exist, separate `add_init_script` calls already provide it without evaluating a string. The
+ source is therefore installed as its own script, opening it, exactly as it reads on disk.
+
+ THE STAMP GOES AFTER THE SOURCE, NOT BEFORE IT. A directive prologue is the run of expression
+ statements a Script or FunctionBody OPENS with (ECMA-262, "Directive Prologues and the Use
+ Strict Directive"), so a statement in front of a probe's leading `"use strict"` demotes it to a
+ string expression that does nothing. The probe then runs sloppy: an undeclared assignment
+ silently creates a global instead of throwing, and the harness is no longer executing the file
+ as it reads on disk. Playwright wraps every init script in `(() => { ... })();`
+ (`playwright-core/src/server/page.ts`, `class InitScript`), which keeps the file's own prologue
+ working as a FunctionBody prologue -- until something is prepended to it.
+
+ THE EMPTY STATEMENT BETWEEN THEM IS THE ATTESTATION. This used to append the stamp on a bare
+ newline, on the reasoning that ASI made that safe because the appended line opens with an
+ identifier. That reasoning only covers a source whose last line is COMPLETE. ASI does not
+ terminate a source that ends mid-expression, so a probe truncated after an assignment operator
+ -- `var result =` -- is a SyntaxError on its own and STOPS BEING ONE once the stamp is
+ concatenated onto it: the stamp becomes that variable's initializer, `window.__sbExtraInitScript`
+ is set by the very assignment that was supposed to prove the probe finished, and the deferred
+ check below returns early. The probe reported nothing and the harness called that a clean run,
+ which is the one conclusion this pair of scripts exists to prevent. Measured on webkit and
+ chromium alike: stamp set, no `pageerror`, console silent, byte-identical to a healthy probe.
+
+ A bare `;` closes any pending operand slot, so that class stays a parse error. It goes AFTER the
+ source and never in front of it, because a leading empty statement is not a StringLiteral
+ ExpressionStatement and would end the directive prologue before the probe's own `"use strict"`
+ was reached.
+
+ WHAT THIS STILL DOES NOT CLOSE, stated so nobody reads the `;` as more than it is: a source
+ truncated after a STATEMENT HEAD rather than inside an expression -- `if (x)`, `while (a)`,
+ `for (;;)` -- takes the empty statement as its body and parses either way, so the stamp still
+ lands. Closing that needs the probe to be PARSED, which this harness deliberately does not do
+ (that is the whole point of the no-`eval` note above). The `;` narrows the hole; it does not
+ seal it, and the attestation is a smoke alarm rather than a proof.
+
+ The second script is the report. The last line of the probe script stamps
+ `window.__sbExtraInitScript`, so a probe that failed to PARSE, or that THREW on the way down,
+ leaves it unset and the deferred check names it on the console. A throw also arrives as a
+ `pageerror`, which `bundle.page.on("pageerror", ...)` already logs, and that is what separates
+ the two cases. On webkit the check dies in the same bootstrap unit as the probe, and the
+ `pageerror` is what reports there.
+ """
+ where = json.dumps(path)
+ return [
+ f"{source}\n;\nwindow.__sbExtraInitScript = {where};\n",
+ (
+ "(function () {\n"
+ " setTimeout(function () {\n"
+ " if (window.__sbExtraInitScript) { return; }\n"
+ " try {\n"
+ " window.console.error(\n"
+ f" 'SBENCH_EXTRA_INIT_SCRIPT ' + {where} + ' never installed: it did not "
+ "parse, or it threw before it finished. '" + " +\n"
+ " 'This probe reported nothing, which is NOT the same as an arm that did not '"
+ " +\n"
+ " 'fire.'\n"
+ " );\n"
+ " } catch (ignored) {}\n"
+ " }, 0);\n"
+ "})();\n"
+ ),
+ ]
+
+
def _render_ab(
paths,
sides,
@@ -1192,10 +1393,47 @@ def _render_ab(
continue
out = paths.out / "ab.md"
+
+ # NO TABLE AT ALL for a probe run, rather than a table with a warning printed above it. The
+ # warning scrolls off; `ab.md` sits in the output directory and gets pasted into a pull
+ # request. This is the same refusal `--report` and `floor_table` make, on the same evidence,
+ # and it is the entry point that actually runs at the end of every session.
+ from .scoring.from_payload import probe_scripts
+
+ probes = probe_scripts(records)
+ if probes:
+ reason = (
+ f"NO A/B TABLE: this run carried an external init script ({', '.join(probes)}), so "
+ f"its timings measure the page and the instrument together. The payload is kept "
+ f"for the probe's own output and for --assert-liveness; it is not scorable."
+ )
+ _log("")
+ _log(reason)
+ # OVERWRITTEN, not left alone and not deleted. `--resume` reuses the output directory, so
+ # an `ab.md` from an earlier clean run of the same directory would survive this refusal
+ # and sit at the standard artifact path, where it reads as this run's result. Deleting it
+ # would leave whoever opens the path with nothing to explain the absence, so the file is
+ # replaced by the refusal itself.
+ stale = paths.out / "ab.md"
+ if stale.exists():
+ stale.write_text(f"# No A/B table\n\n{reason}\n", encoding = "utf-8")
+ _log(f" a previous {stale} was replaced by this refusal")
+ _log("")
+ return
+
# A FULLY RESUMED A/B MEASURED NOTHING OF ITS OWN. `--resume` against a finished output skips
# every cell and is a success, but the ratio is scoped to THIS session, so re-rendering here
# replaced a real table with NO READING and exited 0 while doing it. The run that measured
# keeps its report; a run with no prior table still gets one, since there is nothing to lose.
+ #
+ # AFTER THE PROBE REFUSAL, NOT BEFORE IT. The payload the resume keeps is the payload this
+ # check is deciding on behalf of, and a probed one is not scorable no matter which session
+ # recorded it. Run first, this returned early for the one sequence that needs the refusal
+ # most: a fresh PROBE run into a directory that already holds a clean `ab.md`, killed after
+ # its last cell was fsynced and before it rendered -- `archive_payload` moves `payload.jsonl`
+ # and nothing else, so the clean table stays at the standard artifact path -- and then
+ # resumed, which finds every cell complete, records none of its own and left that table
+ # standing over an unscorable probe payload.
if not any(r.get("row_type") == "cell" and r.get("session_id") == session_id for r in records):
if out.exists():
_log(f"\nno cell ran in this session; keeping the A/B table already at {out}")
@@ -1283,6 +1521,15 @@ IDENTITY_AXES = (
# back as the defaults (see `HISTORICAL_DEFAULTS`).
"stream_tail_chars",
"corpus_dollars",
+ # `--click-probe`, whose own help text says it "makes the cell's timings incomparable with a
+ # cell that did not run it". That is the definition of an identity axis: the probe runs a full
+ # `page.click`, a real mouse click, a dispatch, a focus and a hover over the thread before the
+ # film starts, and the cell then records a `composer_click_ms` measured on a composer those
+ # paths have already been through plus a `click_attribution` block a cell without the flag
+ # does not have at all. None of it moves the cell id, so a resume that toggles the flag skips
+ # the completed cells and appends the rest under the same ids -- the one ladder built from two
+ # films this check exists to refuse.
+ "click_probe",
# `--inject-stream-cost-ms`, on the same rule and for a larger perturbation than either of
# those two. It burns a known amount of main-thread time per SSE chunk on the TREATMENT arm,
# so a treatment cell recorded with it is a different reading from one recorded without it,
@@ -1294,6 +1541,17 @@ IDENTITY_AXES = (
# Both land as a recovery fraction near zero, which reads as "the metric is blind" and is the
# single verdict this flag exists to make trustworthy.
"inject_stream_cost_ms",
+ # `SBENCH_EXTRA_INIT_SCRIPT`, the external probe. Unlike the axes above it cannot end in a
+ # wrong NUMBER -- `refuse_if_probed` reads every `run_meta` in the file and every scoring entry
+ # point calls it, so one probed session makes the whole payload unscorable and there is no flag
+ # to override that. It is here for what the refusal costs instead. The variable is an
+ # ENVIRONMENT variable rather than a flag, so it survives in a shell after the experiment that
+ # set it is over, and `--resume` into a half-finished clean payload then installs both sides,
+ # runs the rungs that are still owed with the probe in the page, and appends a probed
+ # `run_meta` to the file. The payload is append-only and the refusal is whole-file, so the
+ # 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",
)
#: The axes that describe the SECOND side, which only exist when a run has one. See
@@ -1306,18 +1564,20 @@ TREATMENT_AXES = ("treatment_ref", "treatment_url")
#: never declared cannot be a difference. That is right for the axes `run_meta` has always carried:
#: a payload missing one of those is a payload this check has nothing to say about.
#:
-#: It is WRONG for these three. They arrived with the flags that set them, so a payload written
-#: before them did not decline to record a value -- there was no way to ask for anything but the
-#: default, and it ran under `stream_tail_chars = None`, `corpus_dollars = False` and
-#: `inject_stream_cost_ms = None` by construction. Skipping them therefore accepted `--resume
-#: --stream-tail-chars 24000` against such a payload, skipped its completed cells, and recorded the
-#: rest under a different streamed fixture beneath the same cell ids: one ladder built from two
-#: films, which is what this check exists to refuse. Absence proves the value here, so it is read
-#: as the value.
+#: It is WRONG for the ones below. They arrived with the flag or the variable that sets them, so a
+#: payload written before them did not decline to record a value -- there was no way to ask for
+#: anything but the default, and it ran under `stream_tail_chars = None`, `corpus_dollars = False`,
+#: `click_probe = False`, `inject_stream_cost_ms = None` and `probe_init_script = None` by
+#: construction. Skipping them therefore accepted `--resume --stream-tail-chars 24000` against such
+#: a payload, skipped its completed cells, and recorded the rest under a different streamed fixture
+#: beneath the same cell ids: one ladder built from two films, which is what this check exists to
+#: refuse. Absence proves the value here, so it is read as the value.
HISTORICAL_DEFAULTS = {
"stream_tail_chars": None,
"corpus_dollars": False,
+ "click_probe": False,
"inject_stream_cost_ms": None,
+ "probe_init_script": None,
}
#: THE RATIO THE LADDER WAS SIZED BY, carried on every cell's `meta` by `session.build_cells`.
@@ -1383,7 +1643,14 @@ def requested_identity(args, ab_ref, corpus_hash: str) -> dict:
"treatment_url": attach_b if (ab_ref and attach_b) else "",
"stream_tail_chars": args.stream_tail_chars,
"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),
+ # 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
+ # the same reason `studio_ref` is, so the requested value and the recorded one compare
+ # without a second convention to keep in step.
+ "probe_init_script": os.environ.get("SBENCH_EXTRA_INIT_SCRIPT") or None,
}
@@ -1675,6 +1942,80 @@ def rollback_session_rows(
return dropped
+def invalidate_stale_reports(
+ out,
+ *,
+ archived,
+ extra_init,
+ log = _log,
+) -> list:
+ """Replace `summary.md` and `ab.md` when the payload they describe is no longer the one there.
+
+ `archive_payload` moves `payload.jsonl` and nothing else, so a `summary.md` written by an
+ earlier `--report` of this directory -- step three of the README quickstart, into the same
+ `--out` -- stays at the standard artifact path while the payload underneath it is replaced.
+ Nothing later puts that right, because the report that would overwrite it is a command the
+ next run has no reason to issue: a plain run writes `summary.md` never (only `--report` does)
+ and `ab.md` only under `--ab`, so a single-arm run produces no report-shaped file at all and
+ both stale ones survive it.
+
+ TWO INDEPENDENT INVALIDATIONS, and each is sufficient on its own.
+
+ `archived` is the general case: the payload these reports described has been moved aside, so
+ they describe a file that is no longer at the path they name, whatever the incoming run is.
+ This is the half that was missing. Keying only on `extra_init` closed the clean-then-probed
+ direction and left probed-then-clean open, where a probe run's refusal text -- which says in
+ so many words that the payload beside it is not scorable -- survives into a directory whose
+ payload is now perfectly scorable. A refusal that outlives its reason is worse than no file,
+ because it is read as a finding about the run that is actually there.
+
+ `extra_init` is the narrower case and is NOT covered by `archived`: a `--resume` that
+ `prepare_payload` accepts archives nothing, so `archived` is `None` while the continued
+ payload is being extended by a probed run and becomes unscorable under the old summary.
+
+ OVERWRITTEN, not deleted, for the reason `_render_ab` gives: whoever opens the path gets the
+ reason rather than a missing file. HERE, not at the probe banner further down, for the reason
+ 52fc3e848 moved the `ab.md` refusal above its early return: everything between this point and
+ the banner can `return`, raise or be killed by the wall-clock watchdog, and every one of those
+ paths has already archived the payload the summary belongs to. After `prepare_payload`,
+ though, because a `--resume` it refuses touched nothing.
+
+ BOTH ARTIFACTS, and `ab.md` is not already covered by the refusal inside `_render_ab`. That
+ function runs only under `if ab_ref`, so a fresh SINGLE-ARM run into a directory left by an
+ earlier `--ab` run never reaches it, and the old table survives beside the new payload for as
+ long as the directory lasts.
+
+ Returns the paths it rewrote, so a caller can assert on them.
+ """
+ if not archived and not extra_init:
+ return []
+ if extra_init:
+ why = (
+ f"this output directory was reused by a run carrying an external init script "
+ f"({extra_init}), so its timings measure the page and the instrument together. The "
+ f"payload beside it now is not scorable. Re-run with SBENCH_EXTRA_INIT_SCRIPT unset."
+ )
+ else:
+ why = (
+ f"this output directory was reused by a later run, which moved the payload this "
+ f"described to {Path(archived).name} and recorded a new one beside it. Re-report the "
+ f"payload that is there now, or read the archived one directly."
+ )
+
+ rewritten = []
+ for name, heading, what in (
+ ("summary.md", "# No summary", "summary"),
+ ("ab.md", "# No A/B table", "table"),
+ ):
+ stale = Path(out) / name
+ if not stale.exists():
+ continue
+ stale.write_text(f"{heading}\n\nNO {what.upper()}: {why}\n", encoding = "utf-8")
+ log(f" a previous {stale} was replaced by this refusal")
+ rewritten.append(stale)
+ return rewritten
+
+
def prepare_payload(
paths,
requested: dict,
@@ -1858,8 +2199,21 @@ def report_only(args) -> int:
_log(f"scoring against the ladder this run recorded: {','.join(recorded)}")
else:
declared = _rung_tokens(TIER_RUNGS[args.tier])
+ out = path.parent / "summary.md"
try:
text, ladder, _payload = build_report(path, declared)
+ except SystemExit as exc:
+ # A REFUSAL, not a crash, and it has to reach the artefact rather than only the terminal.
+ # `SystemExit` is not an `Exception`, so without this clause it would leave the process
+ # before the write below. `--resume` reuses the output directory, so a `summary.md` from
+ # an earlier clean report of the same directory would survive the refusal and sit next to
+ # a now-probed payload, reading as its result. Same reasoning as the stale `ab.md` in
+ # `_render_ab`: overwritten rather than deleted, so opening the path gives the reason.
+ _log(str(exc))
+ if out.exists():
+ out.write_text(f"# No summary\n\n{exc}\n", encoding = "utf-8")
+ _log(f" a previous {out} was replaced by this refusal")
+ return 2
except Exception as exc: # noqa: BLE001
# A payload that cannot be scored is reported as such rather than half-rendered: a
# partial report is exactly the artefact that gets quoted without its caveats.
@@ -1867,7 +2221,6 @@ def report_only(args) -> int:
return 1
print(text)
- out = path.parent / "summary.md"
out.write_text(text, encoding = "utf-8")
_log(f"summary written to {out}")
return 0
@@ -2084,6 +2437,15 @@ def parse_args(argv: list):
"assertion. Use only for an action a platform genuinely cannot perform, and say "
"which in the pull request: every name here is a hole in the gate",
)
+ ap.add_argument(
+ "--click-probe",
+ dest = "click_probe",
+ action = "store_true",
+ help = "before the film starts, split the composer click into what a USER pays and "
+ "what Playwright's actionability check pays, plus a hover-only reading. Off by "
+ "default: it costs seconds at large rungs and makes the cell's timings "
+ "incomparable with a cell that did not run it",
+ )
ap.add_argument(
"--allow-slot-misses",
metavar = "N",
diff --git a/tests/studio/studiobench/arms/content_visibility_probe.js b/tests/studio/studiobench/arms/content_visibility_probe.js
new file mode 100644
index 00000000000..b0f5bd629e6
--- /dev/null
+++ b/tests/studio/studiobench/arms/content_visibility_probe.js
@@ -0,0 +1,507 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/* POTENCY PROBE for `content-visibility: auto` on Studio's chat message roots.
+ *
+ * Installed through `SBENCH_EXTRA_INIT_SCRIPT`, reporting through `SBENCH_PAGE_CONSOLE`:
+ *
+ * SBENCH_EXTRA_INIT_SCRIPT=tests/studio/studiobench/arms/content_visibility_probe.js \
+ * SBENCH_PAGE_CONSOLE="CVPOT " \
+ * python -m tests.studio.studiobench --tier fast --ab probe --out outputs/probe \
+ * --attach http://127.0.0.1:PORT --attach-b http://127.0.0.1:OTHER \
+ * --password "$(cat "$STUDIO_HOME_A/auth/.bootstrap_password")" \
+ * --password-b "$(cat "$STUDIO_HOME_B/auth/.bootstrap_password")"
+ *
+ * The credential flags are spelled out rather than trailed off with an ellipsis. A probe run
+ * drives a real Studio like every other command in the loop, and without `--password` it dies on
+ * an HTTP 401 only after the browser has already started. See "You need a Studio, and you need
+ * its password" in the studiobench README.
+ *
+ * ONE PASSWORD PER ARM when both arms are attached. Two separately booted Studios mint two
+ * different bootstrap passwords, so reusing the first for the treatment is a 401 on the second
+ * arm only, after the browser is up. `--password-b` defaults to `--password`, which is right
+ * for the single-Studio case and wrong for this one.
+ *
+ * A run carrying this is a PROBE RUN and its payload is never scored: the probe forces layout on
+ * every sample, and one of the things it forces is the very rendering it is asking about. See the
+ * warning on `descendantBoxes`.
+ *
+ * WHY A PROBE AT ALL, AND WHY IT RUNS BEFORE ANY TIMING IS COLLECTED.
+ *
+ * A null from an arm that never fired is not a measurement of the mechanism; it is a measurement
+ * of the cascade, or of a selector, or of the fact that nothing was ever off screen. This exact
+ * null has already been produced twice in this codebase for `content-visibility`. So nothing here
+ * times anything. It answers one question: did the browser genuinely skip rendering an off-screen
+ * subtree, on the elements this arm targets, in the running app.
+ *
+ * THREE INDEPENDENT ANSWERS, WEAKEST FIRST.
+ *
+ * 1. cvAuto elements whose COMPUTED content-visibility is `auto`. This proves the
+ * declaration won the cascade and nothing more. An element can compute to
+ * `auto` and be painted on every single frame because it never stopped
+ * being relevant to the user.
+ * 2. skipEvents `contentvisibilityautostatechange` events with `skipped === true`. This
+ * event is fired by the engine's own relevance machinery and by nothing
+ * else: no stylesheet, no selector and no author code can produce one. A
+ * non-zero count is proof that a subtree was locked and its rendering
+ * skipped.
+ * 3. offUnrendered off-screen armed roots whose element descendants generate NO layout
+ * boxes. This is the route everybody reaches for first and it DOES NOT
+ * WORK for `content-visibility: auto`. It is kept, and reported, only so
+ * that its zero is on the record next to a non-zero skip count rather than
+ * being rediscovered. See `descendantBoxes`.
+ *
+ * IT ALSO WATCHES THE SIZING TRAP. `content-visibility: auto` imposes size containment while
+ * skipping, so a skipped root's height is its `contain-intrinsic-size`. With the `auto` keyword
+ * that is the LAST REMEMBERED SIZE (css-sizing-4 5.2, 5.2.1), and an element that has never been
+ * rendered without size containment has none and falls back to the <length>. Both failure modes
+ * wreck scroll geometry on a long thread and they are different, so the viewport's scrollHeight,
+ * the count of roots sitting on the declared fallback, and the count sitting on their PADDING
+ * ALONE (a remembered size of zero) are all reported every sample, to be read against the
+ * unarmed side of the same session.
+ *
+ * OUT OF THE PAGE VIA THE CONSOLE. Studio ships `connect-src 'self'`, so a beacon to a collector
+ * on another port is blocked by CSP before it is sent. The console is the one channel that costs
+ * nothing and cannot be silently dropped.
+ */
+(function () {
+ "use strict";
+
+ var PREFIX = "CVPOT ";
+ var MESSAGE_SELECTOR = "[data-message-id]";
+ var VIEWPORT_SELECTOR = ".aui-thread-viewport";
+ var SAMPLE_MS = 2000;
+ var MAX_ROOTS_SCANNED = 60;
+ var MAX_DESCENDANTS_PER_ROOT = 40;
+ /* Per role, the two heights a skipped root can land on, and they mean OPPOSITE things:
+ *
+ * fallback the declared `contain-intrinsic-size` length, used because no last remembered
+ * size exists yet. The arm is working as designed and the length is a guess.
+ * padding the root's own padding and nothing else, which is a remembered size of ZERO,
+ * recorded while the root was mounted and still empty. That is the trap.
+ *
+ * They have to be told apart or the probe attributes one to the other, and on this app they
+ * are close enough to collide: the user root's fallback is 60px against 40px of padding. So
+ * each is matched against its OWN target height, the fallback first so that it wins ties, and
+ * a root that is neither is counted as neither. A single `height <= 64` bucket put a user root
+ * sitting exactly on its fallback into both counters at once. */
+ var ROLE_PX = {
+ assistant: { fallback: 300, padding: 18 },
+ user: { fallback: 60, padding: 40 }
+ };
+ /* `getBoundingClientRect().height` is the BORDER BOX, so both targets carry the root's own
+ * padding: an assistant root on its 300px fallback measures 318, and one whose remembered
+ * size is zero measures 18. Comparing the rect against the bare declared length instead left
+ * `fallbackBite` structurally pinned at zero, which reads as "the fallback is never used" no
+ * matter what the browser did. */
+ function targetHeight(px, which) {
+ return (which === "fallback" ? px.fallback : 0) + px.padding;
+ }
+ /* Half the gap between the two smallest interesting heights, so neither test can reach the
+ * other's target. Sub-pixel layout means an exact equality test would miss. */
+ var PX_EPS = 2;
+
+ if (typeof window === "undefined" || !window.document) {
+ return;
+ }
+ if (window.__cvPotInstalled) {
+ return;
+ }
+ window.__cvPotInstalled = true;
+
+ var doc = window.document;
+ var watched = [];
+ var watchedSet = typeof WeakSet === "function" ? new WeakSet() : null;
+ /* element -> its record, so a sample can ask whether THIS root is currently skipped. Weak so
+ * that a root the app has thrown away is not held alive by the probe. */
+ var recOf = typeof WeakMap === "function" ? new WeakMap() : null;
+ var ev = { stateChange: 0, skip: 0, unskip: 0, watchers: 0, listenerErrors: 0 };
+ var seq = 0;
+
+ function computed(el, prop) {
+ try {
+ var s = window.getComputedStyle(el);
+ return s ? String(s.getPropertyValue(prop) || "").trim() : "";
+ } catch (e) {
+ return "";
+ }
+ }
+
+ function all(selector, scope) {
+ try {
+ var root = scope || doc;
+ var list = root.querySelectorAll(selector);
+ var out = [];
+ for (var i = 0; i < list.length; i++) {
+ out.push(list[i]);
+ }
+ return out;
+ } catch (e) {
+ return [];
+ }
+ }
+
+ function rect(el) {
+ try {
+ return el.getBoundingClientRect();
+ } catch (e) {
+ return null;
+ }
+ }
+
+ function intersects(a, b) {
+ if (!a || !b) {
+ return false;
+ }
+ return a.bottom > b.top && a.top < b.bottom && a.right > b.left && a.left < b.right;
+ }
+
+ /* Attached BEFORE anything is read, and exactly once per element. The event is the only
+ * signal here that no amount of author CSS can fake. */
+ function watch(el) {
+ try {
+ if (watchedSet) {
+ if (watchedSet.has(el)) {
+ return;
+ }
+ watchedSet.add(el);
+ } else if (el.__cvPotWatched) {
+ return;
+ } else {
+ el.__cvPotWatched = true;
+ }
+ var rec = { el: el, skipped: null, events: 0 };
+ el.addEventListener("contentvisibilityautostatechange", function (e) {
+ ev.stateChange += 1;
+ rec.events += 1;
+ if (e && e.skipped) {
+ ev.skip += 1;
+ rec.skipped = true;
+ } else {
+ ev.unskip += 1;
+ rec.skipped = false;
+ }
+ });
+ watched.push(rec);
+ if (recOf) {
+ recOf.set(el, rec);
+ } else {
+ el.__cvPotRec = rec;
+ }
+ ev.watchers += 1;
+ } catch (e) {
+ ev.listenerErrors += 1;
+ }
+ }
+
+ /* How many of this element's first `cap` element descendants generate a layout box.
+ *
+ * A KNOWN FALSE NEGATIVE, KEPT ON PURPOSE. The reasoning is that a skipped subtree is not laid
+ * out, so its descendants have no boxes. The reasoning is correct and the measurement is still
+ * useless, because ASKING is what breaks it: `getClientRects()` on content inside a locked
+ * subtree makes Chromium render that subtree in order to answer, so the probe unlocks exactly
+ * what it came to observe. Measured on a 100K thread this returned 0 off-screen unrendered
+ * roots while the event counter recorded 22 roots simultaneously in the skipped state. Read
+ * alone it is a clean, confident, wrong "the arm did not fire". Use `ev_skip`. */
+ function descendantBoxes(el, cap) {
+ var kids;
+ try {
+ kids = el.querySelectorAll("*");
+ } catch (e) {
+ return -1;
+ }
+ var limit = Math.min(kids.length, cap);
+ var n = 0;
+ for (var i = 0; i < limit; i++) {
+ try {
+ if (kids[i].getClientRects().length > 0) {
+ n += 1;
+ }
+ } catch (e2) {
+ /* an element that cannot be measured is counted as having no box */
+ }
+ }
+ return n;
+ }
+
+ /* Whether the browser last told us THIS root is skipping its contents.
+ *
+ * `null` means no transition has been seen, which is not the same as "rendered" and must not
+ * be read as either. Callers that care about the difference check for `true` explicitly. */
+ function skippedState(el) {
+ var rec = null;
+ try {
+ rec = recOf ? recOf.get(el) : el.__cvPotRec;
+ } catch (e) {
+ rec = null;
+ }
+ return rec ? rec.skipped : null;
+ }
+
+ function roleOf(el) {
+ try {
+ return String(el.getAttribute("data-role") || "");
+ } catch (e) {
+ return "";
+ }
+ }
+
+ function percentile(sorted, q) {
+ if (sorted.length === 0) {
+ return 0;
+ }
+ var i = Math.min(sorted.length - 1, Math.max(0, Math.round((sorted.length - 1) * q)));
+ return sorted[i];
+ }
+
+ function sample() {
+ seq += 1;
+ var roots = all(MESSAGE_SELECTOR);
+ var i;
+ for (i = 0; i < roots.length; i++) {
+ watch(roots[i]);
+ }
+
+ var vp = null;
+ try {
+ vp = doc.querySelector(VIEWPORT_SELECTOR);
+ } catch (e) {
+ vp = null;
+ }
+ var vpRect = vp ? rect(vp) : null;
+
+ var out = {
+ seq: seq,
+ origin: String(window.location.origin || ""),
+ href_thread: String(window.location.hash || window.location.pathname || ""),
+ messages: roots.length,
+ cvAuto: 0,
+ cvVisible: 0,
+ armedOffscreen: 0,
+ offUnrendered: 0,
+ offRendered: 0,
+ armedOnscreen: 0,
+ onRendered: 0,
+ onUnrendered: 0,
+ skippedNow: 0,
+ fallbackBite: 0,
+ paddingOnly: 0,
+ droppedDetached: 0,
+ scanned: 0,
+ codeBlocks: 0,
+ codeBlocksAuto: 0
+ };
+
+ var heights = [];
+ var scanned = 0;
+ for (i = 0; i < roots.length; i++) {
+ var el = roots[i];
+ var cv = computed(el, "content-visibility");
+ if (cv === "auto") {
+ out.cvAuto += 1;
+ } else if (cv === "visible") {
+ out.cvVisible += 1;
+ }
+ if (out.cis === undefined) {
+ out.cis = computed(el, "contain-intrinsic-size");
+ out.cis_role = roleOf(el);
+ }
+ var r = rect(el);
+ if (r) {
+ heights.push(Math.round(r.height));
+ /* Two MUTUALLY EXCLUSIVE buckets, in priority order. `content-visibility: auto`
+ * imposes size containment while skipping, so a skipped root's height is its
+ * padding plus its intrinsic size. Landing on the declared <length> means no
+ * remembered size exists yet; landing on the padding alone means one exists and
+ * it is ZERO, recorded while the root was mounted and still empty. The fallback
+ * is tested first and wins ties, because a root sitting on its fallback is
+ * behaving exactly as the declaration asks and must never be charged to the
+ * trap. Anything else is counted as neither. */
+ /* ONLY WHILE SKIPPED. `content-visibility: auto` computes to `auto` whether or
+ * not the element is currently skipping, and size containment applies only while
+ * it is. An armed root that is on screen has its ordinary rendered height, and if
+ * that height happens to land within the tolerance of a role target it would be
+ * charged to the remembered-size trap. Ordinary geometry must not be able to
+ * masquerade as the finding. */
+ var px = ROLE_PX[roleOf(el)];
+ if (cv === "auto" && px && skippedState(el) === true) {
+ if (Math.abs(r.height - targetHeight(px, "fallback")) <= PX_EPS) {
+ out.fallbackBite += 1;
+ } else if (Math.abs(r.height - targetHeight(px, "padding")) <= PX_EPS) {
+ out.paddingOnly += 1;
+ }
+ }
+ }
+ /* The geometry question is asked only of armed roots, and only of as many as can be
+ * asked cheaply: this forces layout, and the probe must not become the load. */
+ if (cv === "auto" && r && vpRect && scanned < MAX_ROOTS_SCANNED) {
+ scanned += 1;
+ var hasOwnBox = r.width > 0 || r.height > 0;
+ var boxes = descendantBoxes(el, MAX_DESCENDANTS_PER_ROOT);
+ var off = !intersects(r, vpRect);
+ if (off) {
+ out.armedOffscreen += 1;
+ if (hasOwnBox && boxes === 0) {
+ out.offUnrendered += 1;
+ } else if (boxes > 0) {
+ out.offRendered += 1;
+ }
+ } else {
+ out.armedOnscreen += 1;
+ if (boxes > 0) {
+ out.onRendered += 1;
+ } else {
+ out.onUnrendered += 1;
+ }
+ }
+ }
+ }
+ out.scanned = scanned;
+
+ var blocks = all('[data-streamdown="code-block"]');
+ out.codeBlocks = blocks.length;
+ for (i = 0; i < blocks.length; i++) {
+ if (computed(blocks[i], "content-visibility") === "auto") {
+ out.codeBlocksAuto += 1;
+ }
+ }
+
+ /* CONNECTED roots only, and the detached ones are dropped as we go.
+ *
+ * `thread_reopen` is in the film: it tears the thread down and rebuilds it, so the old
+ * roots leave the document. A detached root receives no further transitions, so one whose
+ * last event said `skipped` would go on being counted in `skippedNow` for the rest of the
+ * session, reporting roots as skipped that are not in the page at all. Pruning here also
+ * stops `watched` growing a strong reference per root for the life of a long run. */
+ var live = [];
+ for (i = 0; i < watched.length; i++) {
+ var wel = watched[i].el;
+ var connected = false;
+ try {
+ connected = wel.isConnected !== false && doc.contains(wel);
+ } catch (e) {
+ connected = false;
+ }
+ if (!connected) {
+ out.droppedDetached += 1;
+ continue;
+ }
+ live.push(watched[i]);
+ if (watched[i].skipped === true) {
+ out.skippedNow += 1;
+ }
+ }
+ watched = live;
+
+ heights.sort(function (a, b) {
+ return a - b;
+ });
+ out.h_min = heights.length ? heights[0] : 0;
+ out.h_p50 = percentile(heights, 0.5);
+ out.h_max = heights.length ? heights[heights.length - 1] : 0;
+ out.h_list = heights.slice(0, 24);
+ out.h_sum = 0;
+ for (i = 0; i < heights.length; i++) {
+ out.h_sum += heights[i];
+ }
+
+ if (vp) {
+ try {
+ out.vp_scrollHeight = vp.scrollHeight;
+ out.vp_clientHeight = vp.clientHeight;
+ out.vp_scrollTop = Math.round(vp.scrollTop);
+ } catch (e) {
+ /* leave the keys absent rather than reporting a zero that looks like a collapse */
+ }
+ }
+
+ out.ev_stateChange = ev.stateChange;
+ out.ev_skip = ev.skip;
+ out.ev_unskip = ev.unskip;
+ out.ev_watchers = ev.watchers;
+ out.ev_listenerErrors = ev.listenerErrors;
+
+ try {
+ window.console.log(PREFIX + JSON.stringify(out));
+ } catch (e) {
+ /* nothing to do: the console is the only way out */
+ }
+ }
+
+ window.__cvPotSample = sample;
+
+ /* THE LISTENER HAS TO EXIST BEFORE THE ELEMENT'S FIRST TRANSITION, and polling cannot
+ * guarantee that.
+ *
+ * `contentvisibilityautostatechange` fires on a CHANGE of state. A root that is inserted
+ * off screen becomes skipped once, at its first lifecycle update, and then never changes
+ * again while the user stays where they are. If the listener is attached on a two-second
+ * tick, every root mounted and skipped inside that first tick emits its only event into a
+ * void, `ev_skip` stays at zero, and the probe reports precisely the false NOT RUN it was
+ * written to prevent. A whole thread can mount inside two seconds; a seeded one does.
+ *
+ * So roots are adopted at INSERTION, from a MutationObserver installed before the app boots.
+ * The observer callback runs in a microtask after the mutation and before the next lifecycle
+ * update, which is early enough. The interval is kept, because a root can also acquire the
+ * property later without being re-inserted, and `adoptAll` is idempotent.
+ *
+ * OBSERVE THE DOCUMENT, NOT `documentElement`. An init script is evaluated after the Document
+ * exists but before the page's own scripts run, and at that instant the parser may not have
+ * created the root element yet. `observe(null, ...)` throws, the catch below would swallow it,
+ * and adoption would silently fall back to the two-second tick: the exact false zero this
+ * whole arrangement exists to prevent, reintroduced by the fix for it. A Document node is a
+ * valid target and it always exists here. */
+ function adoptAll() {
+ var roots = all(MESSAGE_SELECTOR);
+ for (var i = 0; i < roots.length; i++) {
+ watch(roots[i]);
+ }
+ }
+
+ /* Only the ADDED NODES, never a document-wide re-scan. Streaming produces thousands of
+ * mutations a second, and a `querySelectorAll` per mutation would make this probe the load
+ * it is trying to observe. `watch` is idempotent, so a node reached twice costs a WeakSet
+ * lookup. */
+ function adoptAdded(records) {
+ for (var i = 0; i < records.length; i++) {
+ var added = records[i].addedNodes;
+ for (var j = 0; j < (added ? added.length : 0); j++) {
+ var node = added[j];
+ if (!node || node.nodeType !== 1) {
+ continue;
+ }
+ try {
+ if (typeof node.matches === "function" && node.matches(MESSAGE_SELECTOR)) {
+ watch(node);
+ }
+ } catch (e) {
+ ev.listenerErrors += 1;
+ }
+ var inner = all(MESSAGE_SELECTOR, node);
+ for (var k = 0; k < inner.length; k++) {
+ watch(inner[k]);
+ }
+ }
+ }
+ }
+
+ try {
+ if (typeof window.MutationObserver === "function") {
+ new window.MutationObserver(adoptAdded).observe(doc, {
+ childList: true,
+ subtree: true
+ });
+ } else {
+ ev.listenerErrors += 1;
+ }
+ } catch (e) {
+ ev.listenerErrors += 1;
+ }
+
+ adoptAll();
+ try {
+ window.setInterval(sample, SAMPLE_MS);
+ } catch (e) {
+ /* a probe that cannot schedule itself reports nothing, which is the honest failure */
+ }
+})();
diff --git a/tests/studio/studiobench/arms/selftest/test_studiobench_probe_hooks.py b/tests/studio/studiobench/arms/selftest/test_studiobench_probe_hooks.py
new file mode 100644
index 00000000000..507acc542e3
--- /dev/null
+++ b/tests/studio/studiobench/arms/selftest/test_studiobench_probe_hooks.py
@@ -0,0 +1,462 @@
+# 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 two halves of the external-probe channel, pinned so neither can rot on its own.
+
+A probe needs a way IN (`SBENCH_EXTRA_INIT_SCRIPT`, concatenated after the scene scripts) and a way
+OUT (`SBENCH_PAGE_CONSOLE`, a prefix filter on the page's console). Neither is exercised by a
+normal run, because both are off unless the environment asks for them, which is exactly the
+property that makes them safe and exactly the property that lets them break unnoticed: delete the
+console filter and the probe still installs, still samples, and reports nothing, which reads as
+"the arm did not fire".
+
+The off-by-default half is the one worth stating. A hook that changed the page even slightly when
+unset would make every scored run a probe run.
+"""
+
+from __future__ import annotations
+
+import re
+import sys
+from pathlib import Path
+
+import pytest
+
+STUDIOBENCH = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(STUDIOBENCH.parent))
+
+PROBE = STUDIOBENCH / "arms" / "content_visibility_probe.js"
+MAIN = STUDIOBENCH / "__main__.py"
+
+
[email protected](scope = "module")
+def main_src() -> str:
+ return MAIN.read_text(encoding = "utf-8")
+
+
[email protected](scope = "module")
+def build_src() -> str:
+ return (STUDIOBENCH / "report" / "build.py").read_text(encoding = "utf-8")
+
+
[email protected](scope = "module")
+def probe_src() -> str:
+ return PROBE.read_text(encoding = "utf-8")
+
+
+def test_both_hooks_are_read_from_the_environment(main_src: str):
+ for var in ("SBENCH_EXTRA_INIT_SCRIPT", "SBENCH_PAGE_CONSOLE"):
+ assert f'os.environ.get("{var}")' in main_src, (
+ f"{var} is no longer read by __main__; a probe that relies on it will install and "
+ "report nothing, which is indistinguishable from an arm that did not fire"
+ )
+
+
+def test_the_hooks_are_off_unless_asked_for(main_src: str, monkeypatch):
+ """Unset means NOTHING is appended and no listener is attached."""
+
+ monkeypatch.delenv("SBENCH_EXTRA_INIT_SCRIPT", raising = False)
+ monkeypatch.delenv("SBENCH_PAGE_CONSOLE", raising = False)
+ import os
+
+ assert os.environ.get("SBENCH_EXTRA_INIT_SCRIPT") is None
+ assert os.environ.get("SBENCH_PAGE_CONSOLE") is None
+ # Both call sites are guarded by a plain truthiness check on the variable, so an unset
+ # variable cannot reach `add_init_script` or `page.on`. Pinned as source, because the failure
+ # this guards is a refactor that hoists either call out of its `if`.
+ for guarded in ("if extra_init:", "if console_prefix:"):
+ assert guarded in main_src, f"{guarded!r} is gone; the hook may no longer be opt-in"
+
+
+def test_the_probe_path_is_validated_before_anything_is_started(main_src: str):
+ """A path typo must not leave a detached Studio holding a port.
+
+ The source is not needed until the browser launches, but reading it there raises after Studio
+ and the pacer are up and before the cleanup `finally` around the cell loop is entered, so
+ nothing stops them. Reading it in the first second of the run fails while there is nothing to
+ clean up.
+ """
+
+ read_at = main_src.index("extra_init_source = Path(extra_init).read_text")
+ assert read_at < main_src.index("install_studio(ref, home)")
+ assert read_at < main_src.index("_probe_init_scripts(extra_init, extra_init_source)")
+ assert "except (OSError, UnicodeDecodeError) as exc:" in main_src
+ # Read once, used later. A second read at launch time would reintroduce the window.
+ assert main_src.count("Path(extra_init).read_text") == 1
+ # AND ahead of the archive, which is the other thing a refusal must not arrive after. Reusing
+ # an --out without --resume moves the payload aside, so reading the probe after that call let a
+ # path typo take payload.jsonl off its standard path while running no benchmark at all. The
+ # behaviour is pinned in runtime/selftest/test_studiobench_run_acquisition.py; the order is
+ # pinned here because that is what makes it true.
+ assert read_at < main_src.index("prepare_payload(")
+
+
+def test_the_probe_is_installed_without_eval(main_src: str):
+ """CSP, not style. Studio serves `script-src 'self'` with no `'unsafe-eval'`, and the DEFAULT
+ engine on Linux and macOS is webkit, which enforces that against an init script.
+
+ The probe was briefly handed to indirect eval as a string so that a malformed file could not
+ stop the scene scripts. Measured against a page carrying Studio's own header, with the real
+ `content_visibility_probe.js`: chromium and firefox installed the probe either way, and webkit
+ refused the eval with `EvalError` and installed NOTHING. The isolation was not real there
+ either -- Playwright gives webkit its init scripts as one bootstrap unit, so a parse error
+ kills them all however the probe is written -- and on the two engines where it is real,
+ separate `add_init_script` calls already provide it. So the source goes in as source.
+ """
+
+ assert "def _probe_init_scripts(" in main_src
+ assert "init_scripts.extend(_probe_init_scripts(extra_init, extra_init_source))" in main_src
+ assert "(0, eval)(" not in main_src, (
+ "the probe is back on eval; Studio's script-src 'self' blocks it and the probe will not "
+ "install at all on the default engine"
+ )
+ assert "eval(" not in main_src, "any string evaluation is refused by Studio's CSP"
+
+
+def test_the_probe_exists_and_is_not_a_stub(probe_src: str):
+ assert PROBE.is_file()
+ assert len(probe_src) > 4_000
+
+
+def test_the_probe_prefix_is_the_one_the_console_filter_expects(probe_src: str):
+ """The filter is an exact prefix match, so a probe with a different prefix is silent."""
+
+ assert 'var PREFIX = "CVPOT ";' in probe_src
+ assert "CVPOT " in (STUDIOBENCH / "CONTRIBUTING-perf.md").read_text(encoding = "utf-8"), (
+ "the documented invocation and the probe's own prefix have to agree, or the recipe in "
+ "CONTRIBUTING-perf.md produces an empty log and a false NOT RUN"
+ )
+
+
+def test_a_probe_run_records_the_gate_that_makes_it_unscorable(main_src: str):
+ """The guarantee has to be a gate, not a sentence in a doc.
+
+ A probe run otherwise looks entirely ordinary: same cells, same A/B table. `floor_table`
+ refuses it on this field, and it can only do that if `__main__` writes it.
+ """
+
+ assert '"probe_init_script": extra_init or None' in main_src
+ # Matched without pinning the indent. `run()` puts side acquisition under a cleanup guard, so
+ # everything from the acquisition loop to the end of setup sits one level deeper than it did,
+ # and the gate moving with it is not the thing this test is here to notice.
+ assert re.search(r"rec\.gate\(\s*\n\s*\"probe_free\",", main_src)
+
+
+def test_roots_are_adopted_at_insertion_not_on_the_sample_tick(probe_src: str):
+ """The listener must exist before the element's FIRST transition.
+
+ A root inserted off screen becomes skipped once and then never changes again. Attach on a
+ two-second tick and every root mounted inside that tick emits its only event into a void,
+ which is exactly the false NOT RUN this probe exists to prevent.
+ """
+
+ assert "MutationObserver" in probe_src
+ assert "adoptAdded" in probe_src
+ # The DOCUMENT, not documentElement. An init script can run before the parser has created
+ # the root element, and `observe(null, ...)` throws into the catch that hides it.
+ assert "observe(doc, {" in probe_src
+ # Added nodes only. A document-wide re-scan per mutation would make the probe the load.
+ assert "addedNodes" in probe_src
+ assert "adoptAll();" in probe_src
+
+
+def test_the_fallback_and_padding_buckets_cannot_both_count_one_root(probe_src: str):
+ """They mean opposite things, and on this app they are close enough to collide.
+
+ The user root's declared fallback is 60px and its padding is 40px. A single `height <= 64`
+ bucket charged a root sitting exactly on its fallback to the zero-remembered-size trap as
+ well. Fallback is tested first and wins ties.
+ """
+
+ assert "ROLE_PX" in probe_src
+ assert "out.fallbackBite += 1;" in probe_src
+ assert 'targetHeight(px, "padding")' in probe_src
+ # getBoundingClientRect() is the border box, so BOTH targets carry the root's own padding.
+ # Comparing against the bare declared length pinned fallbackBite at zero whatever happened.
+ assert 'targetHeight(px, "fallback")' in probe_src
+ assert 'return (which === "fallback" ? px.fallback : 0) + px.padding;' in probe_src
+
+
+def test_only_a_skipped_root_can_land_in_a_size_bucket(probe_src: str):
+ """`content-visibility: auto` computes to `auto` whether or not it is currently skipping.
+
+ An armed root that is on screen has its ordinary rendered height, and size containment is not
+ applying to it. Without the gate, a natural height near a role target reads as the trap.
+ """
+
+ assert "skippedState(el) === true" in probe_src
+
+
+def test_detached_roots_stop_counting_as_skipped(probe_src: str):
+ """`thread_reopen` rebuilds the thread, so watched roots leave the document.
+
+ A detached root receives no further transitions, so one whose last event said `skipped` would
+ keep inflating `skippedNow` for the rest of the session.
+ """
+
+ assert "droppedDetached" in probe_src
+ assert "doc.contains(wel)" in probe_src
+
+
+def test_each_scene_script_keeps_its_own_failure_domain(main_src: str):
+ """Separate `add_init_script` calls, which is what this always did.
+
+ They were briefly joined into one script to pin the evaluation order, which Playwright does
+ not define. That was a regression: the browser evaluates a joined script as one unit, so a
+ throw in any one of the three stops the other two, and on the CI fixture it cost
+ `message_menu` its More button. Fault isolation beats an ordering guarantee for a sequence
+ that has been correct in practice for the life of the file.
+ """
+
+ for name in ("scene/dom.js", "scene/parity.js", "scene/surfaces.js"):
+ assert f'init_scripts.append(resources.read_text("{name}"))' in main_src
+ assert "page_scripts" not in main_src
+
+
+def test_the_probe_is_its_own_script_and_says_when_it_did_not_install(main_src: str):
+ """Order is undefined, so a probe has to be self-contained; that is the documented rule.
+
+ A probe that installed nothing must not read as an arm that did not fire, so both failure
+ modes have a channel. A probe that did not PARSE leaves `window.__sbExtraInitScript` unset and
+ the second script names it on the console; a probe that parsed and then THREW arrives as a
+ `pageerror`. Both listeners are attached whenever a probe is asked for.
+ """
+
+ assert "init_scripts.extend(_probe_init_scripts(extra_init, extra_init_source))" in main_src
+ assert "window.__sbExtraInitScript" in main_src
+ assert "never installed: it did not " in main_src
+ assert 'bundle.page.on("pageerror"' in main_src
+
+
+def test_the_probe_source_is_the_first_thing_in_its_script():
+ """REGRESSION. A directive prologue is only a prologue while nothing precedes it.
+
+ ECMA-262 defines a Directive Prologue as the run of expression statements a Script or
+ FunctionBody OPENS with, so a probe beginning `"use strict"` stops being strict the moment a
+ statement is put in front of it: the directive degrades into a string expression that does
+ nothing, and an undeclared assignment inside the probe creates a global instead of throwing.
+ The installation stamp used to be that statement. It goes last instead, which changes nothing
+ about the probe and still leaves the stamp unset when the file did not run.
+
+ Playwright wraps each init script in `(() => { ... })();` (`playwright-core`, `class
+ InitScript`), so the file's own prologue is a FunctionBody prologue -- real, and equally
+ destroyed by a prepend.
+ """
+
+ import studiobench.__main__ as sb
+
+ source = '"use strict";\nvar ticks = 0;\n'
+ scripts = sb._probe_init_scripts("probes/p.js", source)
+
+ assert scripts[0].startswith(source), (
+ "something is being prepended to the probe source; a leading directive such as "
+ '"use strict" is no longer in the directive prologue and the probe runs with different '
+ "semantics than the file it was read from"
+ )
+ assert "window.__sbExtraInitScript" in scripts[0]
+ # Appended after an explicit statement boundary, so neither ASI nor an unterminated
+ # expression can join it to the probe's last line.
+ assert (
+ scripts[0][len(source) :]
+ .lstrip("\n")
+ .lstrip(";")
+ .lstrip("\n")
+ .startswith("window.__sbExtraInitScript")
+ )
+
+
+def _seed(tmp_path: Path, text: str = "old report") -> Path:
+ for name in ("summary.md", "ab.md"):
+ (tmp_path / name).write_text(text, encoding = "utf-8")
+ return tmp_path
+
+
+def test_a_probe_run_invalidates_the_reports_it_inherited(tmp_path: Path):
+ """The clean-then-probed direction: the payload beside these is no longer scorable."""
+ from studiobench.__main__ import invalidate_stale_reports
+
+ out = _seed(tmp_path)
+ rewritten = invalidate_stale_reports(
+ out, archived = None, extra_init = "/probes/x.js", log = lambda *_: None
+ )
+
+ assert {p.name for p in rewritten} == {"summary.md", "ab.md"}
+ for name in ("summary.md", "ab.md"):
+ body = (out / name).read_text(encoding = "utf-8")
+ assert "not scorable" in body
+ assert "/probes/x.js" in body
+
+
+def test_a_clean_run_invalidates_the_probe_refusal_it_inherited(tmp_path: Path):
+ """The probed-then-clean direction, which keying only on the init script left open.
+
+ A probe run replaces both reports with text saying the payload beside them is not scorable.
+ The next clean run into the same directory archives that payload and records a scorable one,
+ and writes neither report of its own -- `summary.md` only under `--report`, `ab.md` only under
+ `--ab` -- so the refusal survives and is read as a finding about a run it never saw.
+ """
+ from studiobench.__main__ import invalidate_stale_reports
+
+ out = _seed(tmp_path, "NO SUMMARY: ... is not scorable ...")
+ archived = out / "payload-20260101-000000.jsonl"
+ rewritten = invalidate_stale_reports(
+ out, archived = archived, extra_init = None, log = lambda *_: None
+ )
+
+ assert {p.name for p in rewritten} == {"summary.md", "ab.md"}
+ for name in ("summary.md", "ab.md"):
+ body = (out / name).read_text(encoding = "utf-8")
+ assert "payload-20260101-000000.jsonl" in body
+ # The stale claim is GONE, not merely accompanied by a correction.
+ assert "is not scorable" not in body
+
+
+def test_a_resume_that_changed_nothing_leaves_the_reports_alone(tmp_path: Path):
+ """The control. Nothing was archived and nothing is probed, so nothing is stale."""
+ from studiobench.__main__ import invalidate_stale_reports
+
+ out = _seed(tmp_path)
+ assert invalidate_stale_reports(out, archived = None, extra_init = None) == []
+ assert (out / "summary.md").read_text(encoding = "utf-8") == "old report"
+ assert (out / "ab.md").read_text(encoding = "utf-8") == "old report"
+
+
+def test_only_the_reports_that_exist_are_written(tmp_path: Path):
+ """A missing report stays missing: this replaces stale files, it does not manufacture them."""
+ from studiobench.__main__ import invalidate_stale_reports
+
+ (tmp_path / "summary.md").write_text("old report", encoding = "utf-8")
+ rewritten = invalidate_stale_reports(
+ tmp_path, archived = tmp_path / "p.jsonl", extra_init = None, log = lambda *_: None
+ )
+
+ assert [p.name for p in rewritten] == ["summary.md"]
+ assert not (tmp_path / "ab.md").exists()
+
+
+def test_the_run_passes_the_archive_result_to_the_invalidation(main_src: str):
+ """The wiring the behavioural tests above cannot see: `run` must capture what it archived."""
+
+ assert "archived = prepare_payload(" in main_src
+ assert (
+ "invalidate_stale_reports(paths.out, archived = archived, extra_init = extra_init)"
+ in main_src
+ )
+
+
+def test_a_refused_run_does_not_leave_a_stale_ab_table(main_src: str):
+ """`--resume` reuses the output directory, so `ab.md` may already exist from a clean run."""
+
+ assert 'stale = paths.out / "ab.md"' in main_src
+ assert "stale.write_text(" in main_src
+
+
+def test_a_refused_report_does_not_leave_a_stale_summary(main_src: str):
+ """`--report` writes `summary.md` beside the payload, and `--resume` reuses the directory.
+
+ The refusal is a `SystemExit`, which is not an `Exception`, so it would leave the process
+ before the write and an earlier clean summary would survive next to a probed payload.
+ """
+
+ assert "except SystemExit as exc:" in main_src
+ assert 'out = path.parent / "summary.md"' in main_src
+ assert "# No summary" in main_src
+
+
+def test_the_report_refuses_before_it_assembles(build_src: str):
+ """A refusal any other failure can pre-empt is not a refusal.
+
+ `assemble_rows` validates the payload schema on the way past, so a probed payload that also
+ tripped an unrelated schema complaint reported that instead and was never refused.
+ """
+
+ before = build_src.index("refuse_if_probed(_records(path)")
+ assert before < build_src.index("payload = assemble_rows(path)")
+
+
+def test_the_event_counter_is_the_one_potency_rests_on(probe_src: str):
+ """`ev_skip` is the only potency signal here that no author CSS can fake."""
+
+ assert "contentvisibilityautostatechange" in probe_src
+ assert "ev_skip" in probe_src
+ # The geometry route is a documented false negative and must stay documented rather than
+ # quietly removed: someone will reimplement it otherwise.
+ assert "KNOWN FALSE NEGATIVE" in probe_src
+
+
+def _node_parses(source: str):
+ """Parse `source` the way Playwright ships it: wrapped in its `class InitScript` arrow IIFE.
+
+ Returns None when it parses, or the engine's message when it does not. Skips with no node.
+ """
+
+ import shutil
+ import subprocess
+ import tempfile
+
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("no node on PATH; this assertion needs a real JS parser, not a regex")
+ with tempfile.TemporaryDirectory() as tmp:
+ # `--check` reads a FILE, so the IIFE is written out rather than passed with `-e`: an
+ # argument would have to survive the shell, and the point of this helper is that nothing
+ # between the producer and the parser is allowed to edit the bytes.
+ script = Path(tmp) / "init_script.js"
+ script.write_text("(() => {\n" + source + "\n})();", encoding = "utf-8")
+ done = subprocess.run([node, "--check", str(script)], capture_output = True, text = True)
+ return None if done.returncode == 0 else done.stderr.strip().splitlines()[-1]
+
+
+ "truncated",
+ [
+ "var result =",
+ "let out =",
+ "const seen =",
+ "window.__cvpot = {\n count: 0,\n};\nvar next =",
+ '"use strict";\nvar result =',
+ ],
+)
+def test_a_truncated_probe_cannot_stamp_itself_installed(truncated: str):
+ """REGRESSION. The stamp must not be able to complete the source it is attesting to.
+
+ A file cut off after an assignment operator is a SyntaxError on its own, and concatenating the
+ stamp onto it USED TO MAKE IT VALID: `window.__sbExtraInitScript = <path>` became the dangling
+ initializer, so the one variable the probe never got to compute was assigned the stamp and the
+ deferred check returned early. Nothing threw, so `pageerror` said nothing either. Measured on
+ webkit and chromium: stamp set, console silent, probe never ran -- the harness reporting a
+ clean probe run for a probe whose source does not parse.
+
+ This drives the PRODUCER and a real parser, because the defect is JavaScript grammar: any
+ assertion made of string matching would have passed against the broken version too.
+ """
+
+ import studiobench.__main__ as sb
+
+ assert _node_parses(truncated) is not None, "fixture is not actually malformed"
+ combined = sb._probe_init_scripts("probes/p.js", truncated)[0]
+ assert _node_parses(combined) is not None, (
+ "a truncated probe became a VALID script once the stamp was appended, so "
+ "window.__sbExtraInitScript is set by source the probe never executed and the deferred "
+ f"check stays silent about a probe that never ran: {combined!r}"
+ )
+
+
+ "healthy",
+ [
+ '"use strict";\nvar ticks = 0;',
+ "window.__cvpot = 1;",
+ "// nothing but a comment",
+ "function f() { return 1; }\nf();",
+ "(function () { window.q = 1; })()",
+ ],
+)
+def test_a_healthy_probe_still_parses_and_still_stamps(healthy: str):
+ """The boundary must not cost a well-formed probe its stamp."""
+
+ import studiobench.__main__ as sb
+
+ combined = sb._probe_init_scripts("probes/p.js", healthy)[0]
+ assert _node_parses(combined) is None, f"the boundary broke a valid probe: {combined!r}"
+ assert combined.startswith(healthy), "the probe source is no longer the first thing in it"
diff --git a/tests/studio/studiobench/report/build.py b/tests/studio/studiobench/report/build.py
index 19246089ff7..c03dd8d0f2c 100644
--- a/tests/studio/studiobench/report/build.py
+++ b/tests/studio/studiobench/report/build.py
@@ -20,7 +20,11 @@ from collections.abc import Mapping, Sequence
from pathlib import Path
from typing import Any
-from ..scoring.from_payload import latest_attempt_rows, measures_from_records
+from ..scoring.from_payload import (
+ latest_attempt_rows,
+ measures_from_records,
+ refuse_if_probed,
+)
from ..scoring.score import LadderScore, RungScore, score_ladder, score_rung
from .payload import assemble_rows
from .render import render_summary
@@ -67,12 +71,19 @@ def _completion_by_rung(records: Sequence[Mapping[str, Any]]) -> dict[int, tuple
def score_payload(path: str | Path, declared_rungs: Sequence[int] | None = None) -> LadderScore:
"""Score one run. `declared_rungs` is the ladder the tier promised, in tokens."""
+ # BEFORE anything is scored, and against the RAW rows. `--report` reads the same file the run
+ # wrote, so a probe run that was allowed to print its own A/B table would be scorable a second
+ # time here, hours later, by somebody who was not the one who set the variable. It reads the
+ # unfiltered rows deliberately: a probed attempt that was later superseded still means this
+ # payload was recorded with the camera in the shot.
+ raw = _records(path)
+ refuse_if_probed(raw, str(path))
# A CELL THAT WAS RE-RUN IS SCORED ON THE RUN THAT FINISHED IT. `--resume` re-runs the cells
# that died, under the same `cell_id`, into the same file; scoring both attempts as one cell
# kept the crash forever, so a rung that had since been re-run successfully still came out
# INCOMPLETE and zero. The dead attempt is still in the payload and still in EXCLUDED CELLS,
# which is where a superseded crash belongs -- it is only kept out of the score.
- records = latest_attempt_rows(_records(path))
+ records = latest_attempt_rows(raw)
measures = measures_from_records(records)
completion = _completion_by_rung(records)
@@ -103,6 +114,11 @@ def build_report(
) -> tuple[str, LadderScore, dict[str, Any]]:
"""Return (rendered summary, ladder, assembled payload)."""
+ # FIRST, before the payload is assembled. `score_payload` refuses too, but it runs second
+ # here, and `assemble_rows` validates the schema on the way past: a probed payload that also
+ # trips some unrelated schema complaint would report THAT instead, and the refusal would
+ # never be reached. A refusal that any other failure can pre-empt is not a refusal.
+ refuse_if_probed(_records(path), str(path))
payload = assemble_rows(path)
ladder = score_payload(path, declared_rungs)
text = render_summary(payload, ladder, extra_sections = extra_sections)
diff --git a/tests/studio/studiobench/report/selftest/test_studiobench_ab_report_resume.py b/tests/studio/studiobench/report/selftest/test_studiobench_ab_report_resume.py
index e45b170246e..eae5980188c 100644
--- a/tests/studio/studiobench/report/selftest/test_studiobench_ab_report_resume.py
+++ b/tests/studio/studiobench/report/selftest/test_studiobench_ab_report_resume.py
@@ -18,7 +18,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
-from studiobench.__main__ import _render_ab # noqa: E402
+from studiobench.__main__ import _render_ab, _resume_set, archive_payload # noqa: E402
from studiobench.runtime.types import Paths # noqa: E402
MEASURED = "s-measured"
@@ -102,6 +102,69 @@ def test_a_first_run_with_no_readings_still_gets_a_table(tmp_path):
assert "NO READING" in (paths.out / "ab.md").read_text(encoding = "utf-8")
+def _probe_rows(session: str, probe: str) -> list:
+ """What a PROBE run records: the metadata field and the failed gate, then its cells."""
+ return [
+ {"row_type": "run_meta", "session_id": session, "probe_init_script": probe},
+ {
+ "row_type": "gate",
+ "session_id": session,
+ "name": "probe_free",
+ "passed": False,
+ "detail": {"probe_init_script": probe},
+ },
+ _cell("r10K.base.rep0", "base", session),
+ _keystroke("r10K.base.rep0", session, 100.0),
+ _cell("r10K.treatment.rep0", "treatment", session),
+ _keystroke("r10K.treatment.rep0", session, 50.0),
+ ]
+
+
+def test_a_resumed_probe_replaces_the_clean_table_it_inherited(tmp_path):
+ """The sequence that put a clean verdict over an unscorable payload.
+
+ A clean A/B leaves `ab.md`. A FRESH probe run reuses that `--out`, and `archive_payload` moves
+ `payload.jsonl` and nothing else, so the clean table stays where every reader opens it. Every
+ cell is fsynced as it is recorded, then the run dies before it renders -- the wall-clock
+ watchdog is `os._exit(2)` and is only cancelled after the last cell. The `--resume` that
+ follows finds every cell complete and records none of its own, so the no-cell early return
+ used to keep the inherited table: a clean verdict standing over a probed payload.
+ """
+
+ paths = _payload(tmp_path / "run", MEASURED)
+ _render_ab(paths, SIDES, MEASURED, "c0ffee")
+ clean = (paths.out / "ab.md").read_text(encoding = "utf-8")
+ assert "keystroke_p95_ms" in clean
+
+ # The fresh probe run: archived payload, new one recorded whole, killed before rendering.
+ archive_payload(paths, log = lambda _msg: None)
+ paths.payload_jsonl.write_text(
+ "".join(json.dumps(r) + "\n" for r in _probe_rows("s-probe", "potency.js")),
+ encoding = "utf-8",
+ )
+ assert (paths.out / "ab.md").read_text(encoding = "utf-8") == clean
+
+ # The resume: every cell already complete, so nothing runs and nothing is recorded.
+ assert _resume_set(paths) == {"r10K.base.rep0", "r10K.treatment.rep0"}
+ _render_ab(paths, SIDES, "s-resumed-probe", "c0ffee", planned = [])
+
+ text = (paths.out / "ab.md").read_text(encoding = "utf-8")
+ assert "NO A/B TABLE" in text
+ assert "potency.js" in text
+ assert "keystroke_p95_ms" not in text
+
+
+def test_a_clean_fully_resumed_ab_still_keeps_its_table(tmp_path):
+ """The control the fix must not break: no probe, no cells, table kept."""
+
+ paths = _payload(tmp_path / "run", MEASURED)
+ _render_ab(paths, SIDES, MEASURED, "c0ffee")
+ measured = (paths.out / "ab.md").read_text(encoding = "utf-8")
+
+ _render_ab(paths, SIDES, RESUMED, "c0ffee", planned = [])
+ assert (paths.out / "ab.md").read_text(encoding = "utf-8") == measured
+
+
if __name__ == "__main__":
import pytest
raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_composer_click.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_composer_click.py
new file mode 100644
index 00000000000..6ecb6e8b617
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_composer_click.py
@@ -0,0 +1,168 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""`composer_click_ms` must be the click, and only the click.
+
+The session opens every instrument before the window's body and closes them after it, and at
+instrument level 1-3 those hooks stop a CPU profile, collect coverage and write and analyse a
+trace. Timed around the `with` rather than inside it, this reading would grow with the instrument
+level while still being labelled a `page.click` duration -- and it is the number the slow-click
+warning is compared against.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import sys
+import time
+import types
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.runtime.session import CellRunner # noqa: E402
+
+TEARDOWN_S = 0.4
+CLICK_S = 0.1
+
+
+class _Session:
+ """A session whose instrument hooks are expensive, which is the whole point."""
+
+ def __init__(self) -> None:
+ self.opened: list[tuple] = []
+
+ @contextlib.contextmanager
+ def window(
+ self,
+ name,
+ kind = "action",
+ ):
+ self.opened.append((name, kind))
+ time.sleep(TEARDOWN_S) # the `open` hooks
+ try:
+ yield types.SimpleNamespace(note = lambda *a: None)
+ finally:
+ time.sleep(TEARDOWN_S) # the `close` hooks
+
+
+class _Page:
+ def wait_for_selector(
+ self,
+ selector,
+ timeout = None,
+ ):
+ return None
+
+ def click(
+ self,
+ selector,
+ timeout = None,
+ ):
+ time.sleep(CLICK_S)
+
+ def fill(self, selector, value):
+ return None
+
+ def wait_for_timeout(self, ms):
+ return None
+
+ def query_selector(self, selector):
+ return types.SimpleNamespace(click = lambda: None)
+
+
+def _run():
+ runner = types.SimpleNamespace(
+ session = _Session(),
+ click_probe = False,
+ log = lambda *a: None,
+ _composer_click_ms = None,
+ _click_attribution_result = None,
+ )
+ CellRunner._press_send(runner, _Page())
+ return runner
+
+
+def test_composer_click_ms_excludes_the_instrument_hooks():
+ runner = _run()
+ got = runner._composer_click_ms
+ assert got is not None
+ # The click is 100 ms and the hooks are 800 ms between them. Timed around the window this
+ # came back near 900.
+ assert CLICK_S * 1000 <= got < CLICK_S * 1000 + TEARDOWN_S * 1000
+
+
+def test_the_click_is_filed_as_setup_and_not_as_an_action():
+ """`action` would pool an 11 s driver stall into the cell's frame metrics. See
+ `scoring/from_payload.UNSCORED_WINDOW_KINDS`."""
+ runner = _run()
+ assert runner.session.opened == [("setup:composer_click", "setup")]
+
+
+# ── the probe's own output has to survive the payload schema ─────────────────────────────────
+
+
+class _ProbePage(_Page):
+ """Every in-page reading comes back 0, which is the case that matters: an unseeded rung has no
+ code blocks, and `performance.now()` is coarsened to 100 us in a page that is not
+ cross-origin isolated, so a sub-100 us operation genuinely reads 0."""
+
+ def evaluate(
+ self,
+ expr,
+ arg = None,
+ ):
+ return 0
+
+ def query_selector(self, selector):
+ return types.SimpleNamespace(
+ click = lambda: None,
+ bounding_box = lambda: {"x": 0.0, "y": 0.0, "width": 10.0, "height": 10.0},
+ )
+
+ def dispatch_event(self, selector, event):
+ return None
+
+ def eval_on_selector(self, selector, expr):
+ return None
+
+ @property
+ def mouse(self):
+ return types.SimpleNamespace(click = lambda *a: None, move = lambda *a: None)
+
+
+def test_the_probe_block_validates_against_the_payload_schema():
+ from studiobench.scoring.schema import validate_payload
+
+ runner = types.SimpleNamespace(session = _Session(), log = lambda *a: None)
+ out = CellRunner._click_attribution(runner, _ProbePage(), "textarea")
+
+ assert out["code_token_spans"] == 0
+ cell = {
+ "row_type": "cell",
+ "cell_id": "r1K.A0.rep0",
+ "target_tokens": 1000,
+ "completed": True,
+ "click_attribution": out,
+ }
+ validate_payload(
+ {
+ "schema": "studiobench/payload/1",
+ "source": "recorder_rows",
+ "complete": True,
+ "truncated_records": 0,
+ "record_counts": {"cells": 1},
+ "header": {},
+ "selfcheck": [],
+ "windows": [],
+ "actions": [],
+ "cells": [cell],
+ "samples": [],
+ "surfaces": [],
+ "crashes": [],
+ "arms": [],
+ "unknown_rows": [],
+ "footer": None,
+ "excluded_cells": [],
+ }
+ )
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 ff8056e342f..e2bb746c507 100644
--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.py
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.py
@@ -663,10 +663,113 @@ def test_a_payload_from_before_the_fixture_axes_is_refused_under_a_non_default_f
assert "predates this axis" in message
+# ── the measurement-mode axis ───────────────────────────────────────────────────────────────
+#
+# `--click-probe` runs a full `page.click`, a real mouse click, a dispatch, a focus and a hover
+# over the thread BEFORE the film starts, and the tool's own help text for the flag says it "makes
+# the cell's timings incomparable with a cell that did not run it". The cell then carries a
+# `composer_click_ms` measured on a composer all of those paths have already been through, and a
+# `click_attribution` block a cell without the flag does not have at all. None of that moves the
+# cell id, so it is on `IDENTITY_AXES` for the same reason the tier is.
+
+
+def test_resuming_after_toggling_the_click_probe_is_refused(tmp_path):
+ """REGRESSION. Both directions, because either one produces the same mixed ladder.
+
+ Without this the flag was invisible to the check: `click_probe` was in neither `run_meta` nor
+ `requested_identity`, so `--resume --click-probe` against a finished plain payload skipped
+ every completed cell, appended the remaining rungs measured the other way, and reported the
+ two halves as one ladder.
+ """
+
+ probed = _fixture_payload(tmp_path, "probed", "sess-probed", click_probe = True)
+ with pytest.raises(SystemExit) as excinfo:
+ prepare_payload(
+ probed,
+ requested_identity(_resume_args(), None, CORPUS),
+ resume = True,
+ log = lambda *_a: None,
+ )
+ message = str(excinfo.value)
+ assert "click_probe" in message
+ assert "True" in message and "False" in message
+
+ plain = _fixture_payload(tmp_path, "plain", "sess-plain", click_probe = False)
+ with pytest.raises(SystemExit) as excinfo:
+ prepare_payload(
+ plain,
+ requested_identity(_resume_args("--click-probe"), None, CORPUS),
+ resume = True,
+ log = lambda *_a: None,
+ )
+ assert "click_probe" in str(excinfo.value)
+
+
+def test_a_payload_from_before_the_probe_flag_is_refused_under_a_probed_resume(tmp_path):
+ """Absence proves the default here too. A payload with no `click_probe` key was written when
+ there was no way to ask for the probe, so it ran without it."""
+
+ paths = _fixture_payload(tmp_path, "legacy-probe", "sess-old")
+ assert "click_probe" not in paths.payload_jsonl.read_text(encoding = "utf-8")
+
+ with pytest.raises(SystemExit) as excinfo:
+ prepare_payload(
+ paths,
+ requested_identity(_resume_args("--click-probe"), None, CORPUS),
+ resume = True,
+ log = lambda *_a: None,
+ )
+
+ message = str(excinfo.value)
+ assert "click_probe" in message
+ assert "predates this axis" in message
+
+
+def test_an_unchanged_probe_setting_resumes_and_returns_its_completed_cells(tmp_path):
+ """The control. The axis may not swallow a resume that is asking for the run it already has,
+ on either setting."""
+
+ probed = _fixture_payload(tmp_path, "probed-same", "sess-probed", click_probe = True)
+ assert (
+ prepare_payload(
+ probed,
+ requested_identity(_resume_args("--click-probe"), None, CORPUS),
+ resume = True,
+ log = lambda *_a: None,
+ )
+ is None
+ )
+ assert _resume_set(probed) == {"r10K.A0.rep0"}
+
+ plain = _fixture_payload(tmp_path, "plain-same", "sess-plain")
+ assert (
+ prepare_payload(
+ plain,
+ requested_identity(_resume_args(), None, CORPUS),
+ resume = True,
+ log = lambda *_a: None,
+ )
+ is None
+ )
+ assert _resume_set(plain) == {"r10K.A0.rep0"}
+
+
+def test_the_probe_flag_reaches_the_identity_this_invocation_asks_for():
+ """The check can only refuse a difference it was told about, so the flag has to be requested.
+
+ What the payload has to carry for it to be compared against is asserted end to end, over a
+ `run_meta` a real run wrote, in `test_studiobench_run_acquisition`.
+ """
+
+ for flags, expected in ((("--click-probe",), True), ((), False)):
+ args = parse_args(["--tier", "standard", "--branch", "main", *flags])
+ assert requested_identity(args, None, CORPUS)["click_probe"] is expected
+
+
def test_the_skip_rule_still_holds_for_an_axis_that_really_did_decline_to_say(tmp_path):
"""The other axes keep the general rule: `run_meta` has always carried them, so a payload that
omits one omitted it for its own reasons and this check has nothing to say about it. Only the
- two fixture axes read absence as a value."""
+ axes that arrived with a flag of their own read absence as a value."""
paths = Paths.under(tmp_path / "quiet")
_record(
@@ -976,6 +1079,179 @@ def test_an_unchanged_injection_resumes(tmp_path):
assert _resume_set(paths) == {"r10K.base.rep0", "r10K.treatment.rep0"}
+# ── the external probe axis ─────────────────────────────────────────────────────────────────
+#
+# `SBENCH_EXTRA_INIT_SCRIPT` installs a caller's own init script into the page, and the run says so
+# in its log: "this run carries an external probe and is NOT a clean measurement of the build".
+# What it cannot end in is a wrong number, because `refuse_if_probed` reads EVERY `run_meta` in the
+# file and every scoring entry point calls it. It is on `IDENTITY_AXES` for what that refusal
+# costs: the refusal is whole-file and the payload is append-only, so a resume that toggles the
+# probe takes the cells recorded before it down with it, and nothing here can put them back.
+#
+# It is also the axis most easily toggled by accident. The other four are typed on the command
+# line every time; this one is an environment variable, and a variable that is still set is
+# indistinguishable from one that was never set until the run is over.
+
+PROBE = "probes/paint_counter.js"
+
+
+def _probe_resume_args():
+ return parse_args(["--tier", "standard", "--branch", "main", "--resume"])
+
+
+def test_resuming_a_clean_payload_with_the_probe_variable_still_set_is_refused(
+ tmp_path, monkeypatch
+):
+ """REGRESSION, and the destructive direction.
+
+ Half a clean ladder is on disk, the variable from an earlier probe experiment is still set in
+ the shell, and the resume was not asking for a probe run at all. Without the axis this
+ installed both sides, ran every rung still owed with the probe in the page, and appended a
+ probed `run_meta` -- after which `refuse_if_probed` refuses the file, INCLUDING the cells that
+ were recorded cleanly hours earlier.
+ """
+
+ paths = _fixture_payload(tmp_path, "clean", "sess-clean")
+ monkeypatch.setenv("SBENCH_EXTRA_INIT_SCRIPT", PROBE)
+
+ with pytest.raises(SystemExit) as excinfo:
+ prepare_payload(
+ paths,
+ requested_identity(_probe_resume_args(), None, CORPUS),
+ resume = True,
+ log = lambda *_a: None,
+ )
+
+ message = str(excinfo.value)
+ assert "probe_init_script" in message
+ assert PROBE in message
+ assert "predates this axis" in message
+
+
+def test_resuming_a_probed_payload_with_the_variable_unset_is_refused(tmp_path, monkeypatch):
+ """The other direction. It cannot poison anything -- the payload is already unscorable -- but
+ it is a full wave of installs and rungs spent on a file no reader will ever accept."""
+
+ paths = _fixture_payload(tmp_path, "probed", "sess-probed", probe_init_script = PROBE)
+ monkeypatch.delenv("SBENCH_EXTRA_INIT_SCRIPT", raising = False)
+
+ with pytest.raises(SystemExit) as excinfo:
+ prepare_payload(
+ paths,
+ requested_identity(_probe_resume_args(), None, CORPUS),
+ resume = True,
+ log = lambda *_a: None,
+ )
+
+ message = str(excinfo.value)
+ assert "probe_init_script" in message
+ assert PROBE in message
+
+
+def test_resuming_a_probed_payload_under_a_different_probe_is_refused(tmp_path, monkeypatch):
+ """Which probe is the experiment. Two scripts sample different things on different schedules,
+ so half a ladder under each is not one arm however unscorable both halves already are."""
+
+ paths = _fixture_payload(tmp_path, "other", "sess-probed", probe_init_script = PROBE)
+ monkeypatch.setenv("SBENCH_EXTRA_INIT_SCRIPT", "probes/layout_counter.js")
+
+ with pytest.raises(SystemExit) as excinfo:
+ prepare_payload(
+ paths,
+ requested_identity(_probe_resume_args(), None, CORPUS),
+ resume = True,
+ log = lambda *_a: None,
+ )
+ assert "probe_init_script" in str(excinfo.value)
+
+
+def test_a_payload_from_before_the_probe_hook_resumes_under_the_default(tmp_path, monkeypatch):
+ """THE CONTROL, and the one `HISTORICAL_DEFAULTS` exists for. A payload with no
+ `probe_init_script` key was written when there was no way to install a probe, so absence reads
+ as clean and an ordinary resume is still an ordinary resume."""
+
+ paths = _fixture_payload(tmp_path, "old", "sess-old")
+ assert "probe_init_script" not in paths.payload_jsonl.read_text(encoding = "utf-8")
+ monkeypatch.delenv("SBENCH_EXTRA_INIT_SCRIPT", raising = False)
+
+ assert (
+ prepare_payload(
+ paths,
+ requested_identity(_probe_resume_args(), None, CORPUS),
+ resume = True,
+ log = lambda *_a: None,
+ )
+ is None
+ )
+ assert _resume_set(paths) == {"r10K.A0.rep0"}
+
+
+def test_an_unchanged_probe_resumes(tmp_path, monkeypatch):
+ """THE SECOND CONTROL. A probe ladder that died is meant to be resumable AS a probe ladder.
+ The payload is not scorable either way, but a potency run is a run, and refusing every value
+ would make the axis useless rather than safe."""
+
+ paths = _fixture_payload(tmp_path, "same", "sess-probed", probe_init_script = PROBE)
+ monkeypatch.setenv("SBENCH_EXTRA_INIT_SCRIPT", PROBE)
+
+ assert (
+ prepare_payload(
+ paths,
+ requested_identity(_probe_resume_args(), None, CORPUS),
+ resume = True,
+ log = lambda *_a: None,
+ )
+ is None
+ )
+ assert _resume_set(paths) == {"r10K.A0.rep0"}
+
+
+def test_the_probe_variable_reaches_the_identity_this_invocation_asks_for(monkeypatch):
+ """The check can only refuse a difference it was told about, and this one is not on `args`:
+ the hook is an environment variable, so `requested_identity` reads it where it is set."""
+
+ monkeypatch.setenv("SBENCH_EXTRA_INIT_SCRIPT", PROBE)
+ assert requested_identity(_probe_resume_args(), None, CORPUS)["probe_init_script"] == PROBE
+
+ monkeypatch.setenv("SBENCH_EXTRA_INIT_SCRIPT", "")
+ assert requested_identity(_probe_resume_args(), None, CORPUS)["probe_init_script"] is None
+
+ monkeypatch.delenv("SBENCH_EXTRA_INIT_SCRIPT", raising = False)
+ assert requested_identity(_probe_resume_args(), None, CORPUS)["probe_init_script"] is None
+
+
+def test_one_probed_session_makes_the_clean_cells_beside_it_unscorable(tmp_path):
+ """WHAT THE REFUSAL COSTS, which is the whole reason the axis is worth an entry.
+
+ The mixture is never scored as a result -- that part is already safe, whole-file and with no
+ override -- and this is the price of it being safe. The clean session below scores; the same
+ file scores nothing at all once one probed `run_meta` has been appended after it. A payload is
+ append-only, so this is not recoverable by re-running: it is recoverable only by not doing it.
+
+ Passes on the unfixed code, because it is a property of `refuse_if_probed` rather than of the
+ identity check.
+ """
+
+ paths = _fixture_payload(tmp_path, "mixed", "sess-clean")
+ text, _ladder, _payload = build_report(paths.payload_jsonl, [10_000])
+ assert text
+
+ _record(
+ paths,
+ "sess-probed",
+ [
+ _run_meta("standard", "main", ["10K"], probe_init_script = PROBE),
+ _cell("r100K.A0.rep0", 100_000),
+ _keystroke("r100K.A0.rep0", 61.0),
+ ],
+ )
+
+ with pytest.raises(SystemExit) as excinfo:
+ build_report(paths.payload_jsonl, [10_000, 100_000])
+ assert PROBE in str(excinfo.value)
+ assert "refusing to score" in str(excinfo.value)
+
+
def test_a_fresh_run_into_a_new_directory_archives_nothing(tmp_path):
paths = Paths.under(tmp_path / "out")
assert archive_payload(paths, log = lambda *_a: None) is None
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_probe_survives_failure.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_probe_survives_failure.py
new file mode 100644
index 00000000000..43e228fb6e4
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_probe_survives_failure.py
@@ -0,0 +1,251 @@
+# 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 cell that dies after `--click-probe` ran still reports what the probe measured.
+
+THE PROBE HAS NOWHERE ELSE TO LIVE. `composer_click_ms` is taken inside a `setup:composer_click`
+window, and that window's row is emitted by the session whatever happens next, so the click
+timing survives a cell that fails later. The attribution block has no window of its own: it runs
+before the window opens, it is not noted on one, and the only copy of it is the field the cell row
+is built from.
+
+AND THE CELL CAN STILL DIE AFTER IT. `_press_send` sets the 90 s bound on the composer click
+alone. Everything after it -- the `page.fill`, the send-button lookup and its click -- still runs
+under the 8 s default action timeout installed in `runtime/browser.py`, which is the timeout a
+large rung was already observed to blow through: that is why the click needed a bound of its own.
+So the exact run that pays for the probe, at the rung the probe exists for, is the one that loses
+it. Assigned on the way out of `_run_inner`, the whole block went missing from the failure cell.
+
+`CellRunner.run` is driven, with the browser stubbed at the boundary it crosses. The row that gets
+asserted is read back out of the payload the REAL recorder wrote.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.fixture.corpus import RungPlan, Unit # noqa: E402
+from studiobench.runtime.session import CellRunner, Session # noqa: E402
+from studiobench.runtime.types import BenchContext, Cell, Paths, Recorder # noqa: E402
+
+CENSUS = {"messages": 4, "elements": 31_637, "highlight_spans": 1_485}
+
+
+class _Page:
+ """Everything `_run_inner` touches before the send, and a `fill` that fails like the real one.
+
+ Playwright raises `TimeoutError` out of `page.fill` when the composer cannot be filled inside
+ the default action timeout. Raised from `fill` rather than from the send click because it is
+ the first unbounded step after the probe.
+ """
+
+ def __init__(self, fail_on: str = "fill") -> None:
+ self.fail_on = fail_on
+
+ def _maybe_fail(self, where: str) -> None:
+ if where == self.fail_on:
+ raise TimeoutError(f"page.{where}: Timeout 8000ms exceeded")
+
+ def goto(
+ self,
+ url,
+ wait_until = None,
+ timeout = None,
+ ):
+ self._maybe_fail("goto")
+
+ def wait_for_selector(
+ self,
+ selector,
+ timeout = None,
+ ):
+ return None
+
+ def evaluate(
+ self,
+ expr,
+ arg = None,
+ ):
+ if "counts()" in expr:
+ return dict(CENSUS)
+ return 0
+
+ def click(
+ self,
+ selector,
+ timeout = None,
+ ):
+ return None
+
+ def fill(self, selector, value):
+ self._maybe_fail("fill")
+
+ def wait_for_timeout(self, ms):
+ return None
+
+ def query_selector(self, selector):
+ return types.SimpleNamespace(
+ click = lambda: None,
+ bounding_box = lambda: {"x": 0.0, "y": 0.0, "width": 10.0, "height": 10.0},
+ )
+
+ def dispatch_event(self, selector, event):
+ return None
+
+ def eval_on_selector(self, selector, expr):
+ return None
+
+ @property
+ def mouse(self):
+ return types.SimpleNamespace(click = lambda *a: None, move = lambda *a: None)
+
+
+class _Pacer:
+ def reset(self) -> None:
+ pass
+
+ def load(self, reasoning, content, **kwargs) -> None:
+ pass
+
+ def expected_duration_ms(self, reasoning, content, cadence) -> float:
+ return 1_000.0
+
+
+class _Seeder:
+ #: `None`, so `measure_chars_per_token` cannot reach for the network from a unit test.
+ auth = None
+
+ def seed(self, plan):
+ # No messages, so the mount wait is the selector and not a count that never arrives.
+ return types.SimpleNamespace(thread_id = "t-1", seconds = 0.0, messages = 0)
+
+
+def _unit() -> Unit:
+ return Unit(
+ index = 0,
+ kind = "reasoning",
+ reasoning = "thinking about it ",
+ content = "the answer ",
+ chars = 29,
+ sha256 = "0" * 64,
+ )
+
+
+def _plan() -> RungPlan:
+ return RungPlan(
+ rung = "500K",
+ target_tokens = 500_000,
+ target_chars = 2_000_000,
+ streamed_unit = _unit(),
+ )
+
+
+def _runner(
+ tmp_path,
+ *,
+ click_probe: bool,
+ fail_on: str = "fill",
+):
+ paths = Paths.under(tmp_path / "out")
+ recorder = Recorder(paths.payload_jsonl, "sess-1")
+ ctx = BenchContext(
+ page = _Page(fail_on = fail_on),
+ base_url = "http://127.0.0.1:65535",
+ session_id = "sess-1",
+ paths = paths,
+ recorder = recorder,
+ log = lambda *_a: None,
+ )
+ runner = CellRunner(
+ session = Session(ctx = ctx),
+ pacer = _Pacer(),
+ seeder = _Seeder(),
+ corpus = None,
+ base_url = ctx.base_url,
+ model_id = "m",
+ tier = "quick",
+ paths = paths,
+ log = lambda *_a: None,
+ click_probe = click_probe,
+ )
+ return runner, paths, recorder
+
+
+def _cell(cell_id: str = "r500K.A0.rep0") -> Cell:
+ return Cell(cell_id = cell_id, rung = "500K", rung_tokens = 500_000, session_id = "sess-1")
+
+
+def _cell_rows(paths) -> list[dict]:
+ rows = [
+ json.loads(line)
+ for line in paths.payload_jsonl.read_text(encoding = "utf-8").splitlines()
+ if line
+ ]
+ return [r for r in rows if r.get("row_type") == "cell"]
+
+
+def test_a_cell_that_dies_after_the_probe_still_reports_the_attribution(tmp_path):
+ """REGRESSION. The probe ran, the send did not, and the numbers must not go with it."""
+
+ runner, paths, recorder = _runner(tmp_path, click_probe = True)
+ row = runner.run(_cell(), _plan())
+ recorder.close()
+
+ assert row["completed"] is False
+ assert row["failure"]["kind"] == "TimeoutError"
+
+ # Out of the payload, not out of the returned dict: the file is what a failed run leaves
+ # behind, and it is where the diagnostic has to be readable from.
+ cells = _cell_rows(paths)
+ assert len(cells) == 1
+ attribution = cells[0]["click_attribution"]
+ assert attribution["click_attribution_attempted"] is True
+ # The two readings the flag exists to produce: what the driver pays and what a user pays.
+ assert "click_ms" in attribution and "mouse_ms" in attribution
+
+
+def test_the_attribution_of_one_cell_never_lands_on_the_next(tmp_path):
+ """CONTROL. A cell that dies BEFORE its own probe has no attribution to report.
+
+ The reading is filed from the cell's `finally`, so the field has to be cleared per cell rather
+ than beside the click that sets it. A stale block re-filed under the next cell id would be
+ worse than the loss this test's neighbour is about: a measurement of one rung reported as
+ another's.
+ """
+
+ runner, paths, recorder = _runner(tmp_path, click_probe = True)
+ runner.run(_cell(), _plan())
+
+ # The same runner, and this time the page is gone before the probe can run.
+ runner.session.ctx.page = _Page(fail_on = "goto")
+ runner.run(_cell("r500K.A0.rep1"), _plan())
+ recorder.close()
+
+ first, second = _cell_rows(paths)
+ assert "click_attribution" in first
+ assert second["completed"] is False
+ assert "click_attribution" not in second
+
+
+def test_a_cell_that_never_asked_for_the_probe_reports_none(tmp_path):
+ """CONTROL. Without `--click-probe` there is nothing to preserve, and the failed cell says so
+ by carrying no attribution at all rather than an empty one."""
+
+ runner, paths, recorder = _runner(tmp_path, click_probe = False)
+ runner.run(_cell(), _plan())
+ recorder.close()
+
+ cells = _cell_rows(paths)
+ assert cells[0]["completed"] is False
+ assert "click_attribution" not in cells[0]
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
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 a5b7986cf9b..20e93bff92b 100644
--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_run_acquisition.py
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_run_acquisition.py
@@ -354,6 +354,318 @@ def test_the_same_treatment_studio_still_resumes(studio):
)
+# ── whether the probe ran before the film ───────────────────────────────────────────────────
+
+
+def test_a_run_records_whether_the_click_probe_ran(studio):
+ """REGRESSION, and the recording half of the identity axis.
+
+ `--click-probe` runs a full `page.click`, a real mouse click, a dispatch, a focus and a hover
+ over the thread before the film starts, and its own help text says it "makes the cell's
+ timings incomparable with a cell that did not run it". A cell id carries the rung, the arm and
+ the repetition and none of that, so unless `run_meta` says which way the run was measured, a
+ later `--resume` has nothing to compare and cannot refuse a toggle.
+ """
+
+ assert sb.run(_args(studio, "--branch", "main", "--click-probe")) == 0
+
+ meta = [r for r in _rows(studio) if r.get("row_type") == "run_meta"]
+ assert len(meta) == 1
+ assert meta[0]["click_probe"] is True
+
+
+def test_a_resume_that_drops_the_click_probe_is_refused(studio):
+ """End to end, over the payload the run above actually wrote."""
+
+ paths = Paths.under(studio["out"])
+ assert sb.run(_args(studio, "--branch", "main", "--click-probe")) == 0
+ corpus_hash = _rows(studio)[0]["corpus_hash"]
+
+ with pytest.raises(SystemExit) as excinfo:
+ sb.prepare_payload(
+ paths,
+ sb.requested_identity(_args(studio, "--branch", "main", "--resume"), None, corpus_hash),
+ resume = True,
+ log = lambda *_a: None,
+ )
+
+ assert "click_probe" in str(excinfo.value)
+
+
+def test_a_resume_that_keeps_the_click_probe_still_resumes(studio):
+ """The control: the identity this payload was recorded under has to keep resuming."""
+
+ paths = Paths.under(studio["out"])
+ assert sb.run(_args(studio, "--branch", "main", "--click-probe")) == 0
+ corpus_hash = _rows(studio)[0]["corpus_hash"]
+
+ resumed = _args(studio, "--branch", "main", "--click-probe", "--resume")
+
+ assert (
+ sb.prepare_payload(
+ paths,
+ sb.requested_identity(resumed, None, corpus_hash),
+ resume = True,
+ log = lambda *_a: None,
+ )
+ is None
+ )
+
+
+def test_a_plain_run_and_a_plain_resume_are_unaffected(studio):
+ """The other control. A run that never asks for the probe records it as false and resumes."""
+
+ paths = Paths.under(studio["out"])
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+
+ meta = [r for r in _rows(studio) if r.get("row_type") == "run_meta"]
+ assert meta[0]["click_probe"] is False
+ corpus_hash = _rows(studio)[0]["corpus_hash"]
+
+ assert (
+ sb.prepare_payload(
+ paths,
+ sb.requested_identity(_args(studio, "--branch", "main", "--resume"), None, corpus_hash),
+ resume = True,
+ log = lambda *_a: None,
+ )
+ is None
+ )
+
+
+# ── the external probe on the record ────────────────────────────────────────────────────────
+#
+# `SBENCH_EXTRA_INIT_SCRIPT` is an ENVIRONMENT variable, not a flag, so it outlives the command
+# that wanted it. A resume under a shell that still has it set runs the rungs still owed with the
+# probe in the page and appends a probed `run_meta`, and `refuse_if_probed` reads every `run_meta`
+# in a file: the cells recorded cleanly before it stop being scorable too, permanently, because a
+# payload is append-only. So `run_meta` has to carry the probe and `--resume` has to compare it.
+
+
+class _ProbedBundle(_Bundle):
+ """A probe run attaches console and `pageerror` listeners, which a `None` page cannot take."""
+
+ page = types.SimpleNamespace(on = lambda *_a, **_k: None)
+
+
+def probe(tmp_path, monkeypatch):
+ """A probe installed the way a caller installs one, with a file that really is readable."""
+
+ path = tmp_path / "paint_counter.js"
+ path.write_text("window.__probe_ticks = 0;\n", encoding = "utf-8")
+ monkeypatch.setattr(browser_mod, "launch", lambda *a, **k: _ProbedBundle())
+ monkeypatch.setenv("SBENCH_EXTRA_INIT_SCRIPT", str(path))
+ return path
+
+
+def test_a_run_records_which_probe_was_in_the_page(studio, probe):
+ """The recording half of the identity axis, over a `run_meta` a real run wrote."""
+
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+
+ meta = [r for r in _rows(studio) if r.get("row_type") == "run_meta"]
+ assert len(meta) == 1
+ assert meta[0]["probe_init_script"] == str(probe)
+
+
+def test_a_resume_that_drops_the_external_probe_is_refused(studio, probe, monkeypatch):
+ """End to end, over the payload the run above actually wrote."""
+
+ paths = Paths.under(studio["out"])
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+ corpus_hash = _rows(studio)[0]["corpus_hash"]
+ monkeypatch.delenv("SBENCH_EXTRA_INIT_SCRIPT")
+
+ with pytest.raises(SystemExit) as excinfo:
+ sb.prepare_payload(
+ paths,
+ sb.requested_identity(_args(studio, "--branch", "main", "--resume"), None, corpus_hash),
+ resume = True,
+ log = lambda *_a: None,
+ )
+
+ assert "probe_init_script" in str(excinfo.value)
+
+
+def test_an_unreadable_probe_is_refused_before_the_payload_is_archived(studio, monkeypatch):
+ """REGRESSION. A refusal must not cost the previous run's payload its standard path.
+
+ Reusing an `--out` without `--resume` archives the payload already there, and that archive used
+ to run before `SBENCH_EXTRA_INIT_SCRIPT` was read. A path typo therefore exited 2 having
+ installed nothing, launched nothing and recorded nothing, while `payload.jsonl` was gone from
+ the one name every reader opens: `--report`, `--assert-liveness` and the next `--resume`.
+ """
+
+ monkeypatch.delenv("SBENCH_EXTRA_INIT_SCRIPT", raising = False)
+ paths = Paths.under(studio["out"])
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+ recorded = paths.payload_jsonl.read_text(encoding = "utf-8")
+
+ monkeypatch.setenv("SBENCH_EXTRA_INIT_SCRIPT", str(studio["out"] / "typo_not_a_file.js"))
+ assert sb.run(_args(studio, "--branch", "main")) == 2
+
+ assert paths.payload_jsonl.read_text(encoding = "utf-8") == recorded
+ assert sorted(p.name for p in paths.out.glob("payload-*.jsonl")) == []
+ # The refusal is still ahead of everything it was ahead of before.
+ assert studio["installed"] == ["main"]
+
+
+def _clean_summary(studio) -> Path:
+ """A clean run, then the `--report` the README quickstart runs on it, into the same `--out`."""
+
+ paths = Paths.under(studio["out"])
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+ assert sb.main(["--report", str(paths.payload_jsonl), "--tier", "quick", "--rungs", "1K"]) == 0
+ summary = paths.out / "summary.md"
+ assert summary.exists()
+ assert "studiobench summary" in summary.read_text(encoding = "utf-8")
+ return summary
+
+
+def test_a_fresh_probe_run_replaces_the_summary_it_inherited(studio, monkeypatch, tmp_path):
+ """REGRESSION. A clean summary may not sit at the standard path over a probed payload.
+
+ `archive_payload` moves `payload.jsonl` and nothing else, so the `summary.md` an earlier
+ `--report` of this directory wrote stayed where every reader opens it while the payload it
+ described was moved aside and a probed one took its place. Nothing later corrected it: a probe
+ run is read through the probe's own console output, so `--report`, whose `SystemExit` clause
+ does replace the file, is the one command nobody has a reason to run on that payload. Without
+ `--ab` there is no `ab.md` either, so the stale summary was the only report-shaped file in the
+ directory.
+ """
+
+ monkeypatch.delenv("SBENCH_EXTRA_INIT_SCRIPT", raising = False)
+ summary = _clean_summary(studio)
+ clean = summary.read_text(encoding = "utf-8")
+
+ script = tmp_path / "paint_counter.js"
+ script.write_text("window.__probe_ticks = 0;\n", encoding = "utf-8")
+ monkeypatch.setattr(browser_mod, "launch", lambda *a, **k: _ProbedBundle())
+ monkeypatch.setenv("SBENCH_EXTRA_INIT_SCRIPT", str(script))
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+
+ text = summary.read_text(encoding = "utf-8")
+ assert text != clean
+ assert "NO SUMMARY" in text
+ assert script.name in text
+ assert "studiobench summary" not in text
+ # The evidence itself is untouched: the refusal replaces the report, never the payload the
+ # summary described, which is still on disk under its archived name.
+ assert len(list(Paths.under(studio["out"]).out.glob("payload-*.jsonl"))) == 1
+
+
+def test_a_fresh_single_arm_probe_run_replaces_the_ab_table_it_inherited(
+ studio, monkeypatch, tmp_path
+):
+ """REGRESSION. `_render_ab`'s own probe refusal cannot reach this case.
+
+ That function runs only under `if ab_ref`, so a fresh SINGLE-ARM probe run into a directory
+ an earlier `--ab` run left behind never calls it, and the clean table survives beside the new
+ unscorable payload. `archive_payload` moves only `payload.jsonl`, so nothing else touches it
+ either. Distinct from the resumed-A/B hole fixed in 52fc3e848, where `_render_ab` did run and
+ an early return jumped over its refusal.
+ """
+
+ monkeypatch.delenv("SBENCH_EXTRA_INIT_SCRIPT", raising = False)
+ table = Paths.under(studio["out"]).out / "ab.md"
+ table.write_text(
+ "studiobench A/B\n===============\n\n headline_ratio 0.923 (7.7% faster)\n",
+ encoding = "utf-8",
+ )
+ clean = table.read_text(encoding = "utf-8")
+
+ script = tmp_path / "paint_counter.js"
+ script.write_text("window.__probe_ticks = 0;\n", encoding = "utf-8")
+ monkeypatch.setattr(browser_mod, "launch", lambda *a, **k: _ProbedBundle())
+ monkeypatch.setenv("SBENCH_EXTRA_INIT_SCRIPT", str(script))
+ # No --ab, so _render_ab is never called and only this refusal can reach the file.
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+
+ text = table.read_text(encoding = "utf-8")
+ assert text != clean
+ assert "NO TABLE" in text
+ assert script.name in text
+ assert "headline_ratio" not in text, "the clean A/B table survived a probe run"
+
+
+def test_a_probe_run_invents_no_ab_table_where_there_was_none(studio, monkeypatch, tmp_path):
+ """The control, matching the summary one: replace a stale table, never invent one."""
+
+ script = tmp_path / "paint_counter.js"
+ script.write_text("window.__probe_ticks = 0;\n", encoding = "utf-8")
+ monkeypatch.setattr(browser_mod, "launch", lambda *a, **k: _ProbedBundle())
+ monkeypatch.setenv("SBENCH_EXTRA_INIT_SCRIPT", str(script))
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+ assert not (Paths.under(studio["out"]).out / "ab.md").exists()
+
+
+def test_a_probe_run_invents_no_summary_where_there_was_none(studio, monkeypatch, tmp_path):
+ """The control. The refusal replaces a stale report; it does not create a report-shaped file
+ in a directory whose reader was never given one to misread."""
+
+ script = tmp_path / "paint_counter.js"
+ script.write_text("window.__probe_ticks = 0;\n", encoding = "utf-8")
+ monkeypatch.setattr(browser_mod, "launch", lambda *a, **k: _ProbedBundle())
+ monkeypatch.setenv("SBENCH_EXTRA_INIT_SCRIPT", str(script))
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+ assert not (Paths.under(studio["out"]).out / "summary.md").exists()
+
+
+def test_a_clean_rerun_also_invalidates_the_summary_it_inherited(studio, monkeypatch):
+ """REGRESSION, and this test previously asserted the opposite.
+
+ It was written as a control reading "only a PROBE run invalidates", on the reasoning that
+ `--report` rewrites the summary properly afterwards. That reasoning holds only for a reader
+ who runs `--report`, and it is the same asymmetry in reverse that made the probe case a bug:
+ `archive_payload` moves `payload.jsonl` and nothing else, so after ANY rerun of this directory
+ the standing `summary.md` describes a payload that is no longer at the path it names. A plain
+ run writes `summary.md` never and `ab.md` only under `--ab`, so a single-arm rerun produces no
+ report-shaped file to displace it.
+
+ The sharper version of the same hole is probed-then-clean: the probe refusal says in so many
+ words that the payload beside it is not scorable, and that claim survives into a directory
+ whose payload is now perfectly scorable. A refusal that outlives its reason is read as a
+ finding about the run that is actually there.
+
+ `--report` still writes a real summary over it, which is the half of the original control
+ that was correct and is kept below.
+ """
+
+ monkeypatch.delenv("SBENCH_EXTRA_INIT_SCRIPT", raising = False)
+ summary = _clean_summary(studio)
+ paths = Paths.under(studio["out"])
+
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+ text = summary.read_text(encoding = "utf-8")
+ assert "NO SUMMARY" in text
+ assert "studiobench summary" not in text, "a summary of the archived payload survived a rerun"
+ # It names where the payload it described went, so the reader can still reach it.
+ assert "payload-" in text
+
+ # And the legitimate `--report` path still scores the new payload rather than refusing it.
+ assert sb.main(["--report", str(paths.payload_jsonl), "--tier", "quick", "--rungs", "1K"]) == 0
+ assert "studiobench summary" in summary.read_text(encoding = "utf-8")
+
+
+def test_a_resume_under_the_same_probe_still_resumes(studio, probe):
+ """The control. A potency ladder that died is meant to be resumable as the ladder it was."""
+
+ paths = Paths.under(studio["out"])
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+ corpus_hash = _rows(studio)[0]["corpus_hash"]
+
+ assert (
+ sb.prepare_payload(
+ paths,
+ sb.requested_identity(_args(studio, "--branch", "main", "--resume"), None, corpus_hash),
+ resume = True,
+ log = lambda *_a: None,
+ )
+ is None
+ )
+
+
# ── one Studio, two sides: the attached null control ────────────────────────────────────────
diff --git a/tests/studio/studiobench/runtime/session.py b/tests/studio/studiobench/runtime/session.py
index b3f0b840478..efb0d06bfe1 100644
--- a/tests/studio/studiobench/runtime/session.py
+++ b/tests/studio/studiobench/runtime/session.py
@@ -68,6 +68,15 @@ IDLE_CALIBRATION_MS = 1500
EQUIVALENCE_RUNG = "10K"
MOUNT_TIMEOUT_S = 180
+# How long the composer may take to accept the click that starts the film. Not a performance
+# budget: the point is that the cell survives and the number gets recorded. See `_press_send`.
+# 90s because it has to be well clear of the worst real reading and still bounded, since a click
+# that never lands is a different fact from a slow one.
+COMPOSER_CLICK_TIMEOUT_S = 90
+# Above this the log says so out loud, because a multi-second click is the user complaint itself
+# and it should not be something you only find by reading the payload afterwards.
+SLOW_COMPOSER_CLICK_MS = 1_000
+
class WindowInUse(RuntimeError):
pass
@@ -177,6 +186,10 @@ class CellRunner:
# Set once the 10K check fails, and it then labels every LARGER rung, which is the whole
# point: those rungs are mostly seeded and their fidelity depends on this one answer.
equivalence_failed: bool = False
+ # Run the click attribution probe before the film starts. Off by default: it costs a handful
+ # of seconds at small rungs and a great deal at large ones, and it makes the cell's timings
+ # incomparable with a cell that did not run it. See `_click_attribution`.
+ click_probe: bool = False
def run(self, cell: Cell, plan: RungPlan) -> dict:
s = self.session
@@ -201,6 +214,10 @@ class CellRunner:
"target_tokens": plan.target_tokens,
"instruments": {},
}
+ # Cleared HERE, not beside the click that produces it, so the preservation in the `finally`
+ # below cannot attach the PREVIOUS cell's attribution to a cell that died before its own
+ # probe ran. A reading filed under the wrong cell id is worse than a missing one.
+ self._click_attribution_result = None
try:
self._run_inner(cell, plan, row)
row["completed"] = True
@@ -220,6 +237,15 @@ class CellRunner:
# RSS at death, not a gap in the table.
rss = row["instruments"].get("rss") or {}
row["rss_at_death_mb"] = rss.get("rss_peak_mb") if not row["completed"] else None
+ # AND SO IS THE PROBE THAT ALREADY RAN. `--click-probe` finishes inside `_press_send`,
+ # and everything after it there -- the `page.fill`, the send button lookup and its
+ # click -- still runs under the default 8s action timeout, which is exactly what a
+ # large rung exceeds. Assigned only on the way out of `_run_inner`, the whole
+ # attribution was dropped from the cell it was measured for, and unlike
+ # `composer_click_ms` it has no window row of its own to survive in: nothing else in
+ # the payload records it. So it is filed from here, on both paths.
+ if self._click_attribution_result is not None:
+ row["click_attribution"] = self._click_attribution_result
rec.emit(row)
return row
@@ -310,7 +336,14 @@ class CellRunner:
)
before_metrics = cdp_metrics(s.ctx.cdp)
+ self._composer_click_ms = None
+ # `click_attribution` is NOT filed here. It is filed in `run`'s `finally`, because a cell
+ # that dies after the probe has to keep it: see there.
t0 = self._press_send(page)
+ # On the cell rather than in `actions`, because it happens before the first slot opens and
+ # filing it as an action would put a reading outside the film into a list the scoring layer
+ # pairs by slot. It is still a per-cell timing and grows with the rung like any other.
+ row["composer_click_ms"] = self._composer_click_ms
scene = scene_schedule.SCENES.get(self.tier, scene_schedule.QUICK)
runner = SceneRunner(
@@ -640,11 +673,212 @@ class CellRunner:
f"the thread mounted {last} of {expected_messages} messages in " f"{MOUNT_TIMEOUT_S}s"
)
+ def _click_attribution(self, page, selector: str) -> dict:
+ """Split the composer click into what a user pays and what the DRIVER pays.
+
+ `page.click` is not a click. Before dispatching it resolves the selector, waits for the
+ element to be visible, enabled and stable, scrolls it into view, then hit-tests the point
+ with `elementsFromPoint` and checks that what is under the cursor is what was asked for,
+ retrying until it agrees. Every one of those steps is O(DOM), and a human does none of
+ them. The Chromium CPU profile of that window at 500K is dominated by Playwright's own
+ injected script, so a number taken from `page.click` cannot be reported as user cost
+ without first showing how much of it is the driver.
+
+ Four paths, ordered by how much machinery each one skips:
+
+ click `page.click` full actionability, which is what the ladder recorded
+ mouse `page.mouse.click` real input at a point: the browser hit-tests, the driver
+ does not resolve or re-check anything
+ dispatch `dispatch_event` a synthesised event, no hit test at all
+ focus `el.focus()` no event and no hit test, just focus and its handlers
+
+ And one that involves no click whatsoever:
+
+ hover move the cursor from a corner into the transcript, flipping `:hover` down the
+ whole hover chain. If THIS costs seconds then focus was never the variable and
+ the cost is style invalidation from a pseudo-class flip, which is worse news
+ than a slow click: a user pays it on every mouse movement over the thread.
+
+ Each is preceded by a blur and a settle so no repetition inherits the previous one's state.
+ """
+
+ def blur() -> None:
+ page.evaluate("() => document.activeElement && document.activeElement.blur()")
+ page.wait_for_timeout(250)
+
+ def settled(fn) -> float:
+ """Time `fn` AND the wait for the main thread to be free again.
+
+ Timing the call alone measures the wrong thing, and differently wrong per engine.
+ `page.mouse.click` hands an input event to the browser over the debug protocol and
+ returns; whether the acknowledgement waits for the renderer to process it is an
+ implementation detail of each engine's Playwright backend, not a property of the app.
+ Read that way, Chromium came back at 3 ms for both 100K and 500K, which does not mean
+ the work was free, only that the ack did not wait for it.
+
+ So every path is followed by a round trip into the page. `page.evaluate` CANNOT return
+ while the main thread is blocked, and `offsetHeight` forces any pending style and
+ layout to be resolved rather than deferred. The reading is then "how long until the
+ page could serve me again", which is the thing a user actually experiences and is
+ comparable across engines.
+ """
+ started = time.monotonic()
+ fn()
+ page.evaluate("() => document.body.offsetHeight")
+ return (time.monotonic() - started) * 1000.0
+
+ # FIRST, before anything else touches the page: the same trivial operation N times.
+ #
+ # This exists because the biggest number in the whole ladder is one I could not attribute.
+ # The first thing touched after a large thread mounts costs 11 to 24 seconds, and in every
+ # probe the cost vanished, because whatever ran first absorbed it and by the time the
+ # interesting path ran the page was warm. Measuring the decay directly is the way out: if
+ # the first reading is seconds and the rest are milliseconds, the cost is ONE TIME and its
+ # size is the first reading minus the steady state. If they are all expensive, it is a
+ # per-interaction cost and the ladder's number was never a one-off.
+ #
+ # A no-op body on purpose. Every reading is the same work, so any difference between them
+ # is the page's state and not the operation.
+ decay = [settled(lambda: None) for _ in range(5)]
+ out: dict[str, Any] = {
+ # The harness layer's attestation, and it is load-bearing rather than decorative.
+ # `scoring/schema._walk_for_bare_zeros` rejects any bare zero that is not covered by a
+ # sibling `*_attempted` flag, and this block has legitimate zeros: a thread with no
+ # mounted code blocks records `code_token_spans: 0`, and `blur_inpage_ms` and
+ # `forced_layout_ms` come from `performance.now()`, which Chromium coarsens to 100 us
+ # outside a cross-origin-isolated context, so an operation shorter than that reads
+ # exactly 0. Without this flag `--report` refuses the whole payload of a completed
+ # probe run.
+ "click_attribution_attempted": True,
+ "first_touch_ms": decay[0],
+ "settled_touch_ms": min(decay[1:]),
+ "touch_decay_ms": [round(v, 1) for v in decay],
+ }
+ # The blur, timed, and timed again from INSIDE the page.
+ #
+ # The decay series above says the first touch after mount costs 10.6 ms at 500K, so there
+ # is no expensive first interaction. Yet the reading taken right after the first blur came
+ # back at 10,052 ms and 10,017 ms in two of three runs. Two things about that: it sits
+ # between the cheap decay series and the cheap readings that follow, so the blur is what it
+ # attaches to; and 10.0 seconds to three digits is the shape of a TIMEOUT, not of work that
+ # happens to take ten seconds.
+ #
+ # `blur_inpage_ms` decides which. It runs the same blur and the same forced layout inside a
+ # single evaluate and times them with `performance.now()`, so the protocol is excluded. If
+ # the page reports ten seconds, it is real work. If the page reports a millisecond while
+ # the outer reading is ten seconds, the ten seconds is the driver or the transport and not
+ # the app, and must never be quoted as a user cost.
+ out["blur_outer_ms"] = settled(
+ lambda: page.evaluate("() => document.activeElement && document.activeElement.blur()")
+ )
+ out["blur_inpage_ms"] = page.evaluate(
+ "() => { const t = performance.now();"
+ " document.activeElement && document.activeElement.blur();"
+ " void document.body.offsetHeight;"
+ " return performance.now() - t; }"
+ )
+ blur()
+ out["roundtrip_ms"] = settled(lambda: None)
+ box = page.query_selector(selector).bounding_box()
+ x, y = box["x"] + box["width"] / 2, box["y"] + box["height"] / 2
+ blur()
+ out["click_ms"] = settled(
+ lambda: page.click(selector, timeout = COMPOSER_CLICK_TIMEOUT_S * 1000)
+ )
+ blur()
+ out["mouse_ms"] = settled(lambda: page.mouse.click(x, y))
+ blur()
+ out["dispatch_ms"] = settled(lambda: page.dispatch_event(selector, "click"))
+ blur()
+ out["focus_ms"] = settled(lambda: page.eval_on_selector(selector, "e => { e.focus(); }"))
+ blur()
+ page.mouse.move(2, 2)
+ page.wait_for_timeout(250)
+ out["hover_thread_ms"] = settled(lambda: page.mouse.move(x, 300))
+ # The reading that decides what `roundtrip_ms` meant. If the first forced layout of a huge
+ # thread is expensive and every later one is cheap, this comes back near zero and the cost
+ # is a ONE-TIME layout of the mounted thread, not a per-interaction cost. If it is
+ # expensive again, every interaction pays it and the story is the opposite.
+ blur()
+ out["roundtrip_again_ms"] = settled(lambda: None)
+ # Measured INSIDE the page, so the protocol round trip is not in the number. `offsetHeight`
+ # is read after a write that dirties layout, so it cannot be served from a clean tree.
+ out["forced_layout_ms"] = page.evaluate(
+ "() => { const t = performance.now();"
+ " document.body.style.minHeight = (1 + Math.random()) + 'px';"
+ " void document.body.offsetHeight;"
+ " document.body.style.minHeight = '';"
+ " void document.body.offsetHeight;"
+ " return performance.now() - t; }"
+ )
+ out["code_token_spans"] = page.evaluate(
+ "() => document.querySelectorAll('[data-streamdown=\"code-block\"] code > span').length"
+ )
+ self.log(
+ " click attribution: "
+ + ", ".join(
+ f"{k.replace('_ms', '')}={v:,.0f}ms"
+ for k, v in out.items()
+ if k.endswith("_ms") and isinstance(v, (int, float))
+ )
+ + f", code token spans={out['code_token_spans']:,}"
+ + f"\n touch decay: {out['touch_decay_ms']}"
+ )
+ return out
+
def _press_send(self, page) -> float:
- """Type a prompt and press send. Returns the driver monotonic time the film starts."""
+ """Type a prompt and press send. Returns the driver monotonic time the film starts.
+
+ THE CELL MUST SURVIVE THIS, and it took losing a whole rung to notice it did not.
+
+ This runs before the film starts, so it was written as setup and inherited the default
+ 8s action timeout. At 500K `page.click` exceeds it and the exception killed the cell
+ before a single slot opened, three times out of three across two runs, so the ladder had
+ NO data at 500K at all. `COMPOSER_CLICK_TIMEOUT_S` fixes that: the cell survives, the film
+ runs, and the cost is recorded whatever it comes to. Still bounded, because a click that
+ never lands is a different fact from a slow one.
+
+ `composer_click_ms` IS NOT WHAT A USER PAYS, and must never be quoted as though it were.
+ I made exactly that mistake and published it. `page.click` resolves the selector, waits
+ for visible, enabled and stable, scrolls into view, hit-tests the point with
+ `elementsFromPoint` and re-checks that the element under the cursor is the one asked for,
+ retrying until it agrees. All of that is O(DOM) and a human does none of it. Measured at
+ 500K on WebKit with `--click-probe`: `page.click` 11,036 ms, a real mouse click at the
+ same point 573 ms. About 95% of the number is the driver.
+
+ So this reading is a HARNESS health number: it says whether the cell can start. For what
+ the user pays, run `--click-probe` and read `mouse_ms` and `focus_ms`.
+ """
selector = 'textarea[aria-label="Message input"]'
page.wait_for_selector(selector, timeout = 60_000)
- page.click(selector)
+ if self.click_probe:
+ self._click_attribution_result = self._click_attribution(page, selector)
+ # In a window, so every instrument covers it. At 500K this single click is the largest
+ # cost in the whole run by an order of magnitude, and it was the one moment the tool could
+ # not see inside: no window, so no frame recorder, no CPU profile, no RSS delta. A cost
+ # that big being outside every instrument is how it stayed unattributed.
+ #
+ # `setup`, NOT `action`. The scoring layer pools every non-excluded window of the cell into
+ # `max_frame_ms`, `jank_index` and `time_in_jank_pct`, and this window is mostly Playwright's
+ # own injected actionability script running ON THE PAGE'S MAIN THREAD -- it blocks frames
+ # exactly as app work would, so the frame recorder cannot tell them apart. Filed as an
+ # `action` it would put an 11 s driver stall into three weighted headline metrics whose
+ # `max_frame_ms` anchor calls 2,000 ms the worst case, on EVERY run including the ones that
+ # never asked for --click-probe. It is measured, reported and kept out of the film.
+ with self.session.window("setup:composer_click", kind = "setup"):
+ # Timed INSIDE the window, like `Window.duration_ms` itself: the session opens every
+ # instrument before this block and closes them after it, and at instrument level 1-3
+ # those hooks stop a CPU profile, collect coverage and write and analyse a trace.
+ # Timed around the `with`, `composer_click_ms` would grow with the instrument level
+ # and stop being the click.
+ clicked_at = time.monotonic()
+ page.click(selector, timeout = COMPOSER_CLICK_TIMEOUT_S * 1000)
+ self._composer_click_ms = (time.monotonic() - clicked_at) * 1000.0
+ if self._composer_click_ms > SLOW_COMPOSER_CLICK_MS:
+ self.log(
+ f" page.click on the composer took {self._composer_click_ms / 1000:.1f}s. "
+ f"MOST OF THAT IS THE DRIVER, not the app: run --click-probe to split it."
+ )
page.fill(selector, "continue")
page.wait_for_timeout(150)
send = page.query_selector('button[aria-label="Send message"]')
diff --git a/tests/studio/studiobench/runtime/types.py b/tests/studio/studiobench/runtime/types.py
index 63759ccef74..b5652e296ae 100644
--- a/tests/studio/studiobench/runtime/types.py
+++ b/tests/studio/studiobench/runtime/types.py
@@ -118,7 +118,11 @@ def make_cell_id(rung: str, arm: str, rep: int) -> str:
#: `gap` is the quiet stretch the scheduler holds between two slots. It is NOT `stream`: a gap
#: window is opened before every slot, so most of them sit long after the reply finished. See
#: SceneRunner._gap_window for what that mislabelling cost.
-WINDOW_KINDS = frozenset({"action", "stream", "gap", "idle", "settle", "teardown"})
+#: `setup` is work the harness has to do before the film can start -- the composer click is the
+#: one that costs anything -- and it is NOT `action`. It is dominated by the driver rather than by
+#: the app, so the scoring layer keeps it out of the frame pool. See
+#: `scoring/from_payload.UNSCORED_WINDOW_KINDS`.
+WINDOW_KINDS = frozenset({"action", "stream", "gap", "idle", "setup", "settle", "teardown"})
@dataclass
diff --git a/tests/studio/studiobench/scoring/from_payload.py b/tests/studio/studiobench/scoring/from_payload.py
index 6d070dfdaa6..7c0549e98f5 100644
--- a/tests/studio/studiobench/scoring/from_payload.py
+++ b/tests/studio/studiobench/scoring/from_payload.py
@@ -92,15 +92,25 @@ MIN_STREAM_CHARS_PER_WINDOW = 100
# availability signal and this is the bound it has to respect.
MAX_TIMER_CLOCK_RATIO = 1.2
-# Windows that are deliberately quiet. Pooling these into the frame metrics would dilute every
-# jank share with idle time and make a bad build look average.
-IDLE_WINDOW_KINDS: frozenset[str] = frozenset({"idle"})
+# Windows that are not part of the film, and whose frames therefore say nothing about the build.
+#
+# `idle` is deliberately quiet: pooling it into the frame metrics would dilute every jank share
+# with idle time and make a bad build look average.
+#
+# `setup` is the opposite and is excluded for the opposite reason. The only one is the composer
+# click that starts the film, and most of it is Playwright's injected actionability script --
+# selector resolution, visibility, stability and the `elementsFromPoint` hit test -- running on
+# the page's own main thread, where it blocks frames indistinguishably from app work. At 500K
+# that window alone runs about 11 s against a `max_frame_ms` anchor whose worst case is 2,000 ms,
+# so pooling it would peg all three frame metrics on every run, including runs that never asked
+# for the click probe.
+UNSCORED_WINDOW_KINDS: frozenset[str] = frozenset({"idle", "setup"})
# The window kinds in which NO SCRIPTED ACTION IS RUNNING. `gap` is the scheduler's inter-slot
# wait; `stream` is `stream:drain`, the window the session layer opens after the film to wait the
# reply out. Both are quiet by construction, which is the property `_unaided` needs -- see there
# for why the streaming numbers are taken only from these, and for what the `stream` half is worth.
-# `action` is excluded, and `idle` never reaches here (IDLE_WINDOW_KINDS strips it first).
+# `action` is excluded, and `idle` never reaches here (UNSCORED_WINDOW_KINDS strips it first).
UNAIDED_WINDOW_KINDS: frozenset[str] = frozenset({"gap", "stream"})
@@ -603,7 +613,7 @@ def measures_from_records(
for w in records
if w.get("row_type") == "window"
and w.get("cell_id") == cell_id
- and str(w.get("kind") or "") not in IDLE_WINDOW_KINDS
+ and str(w.get("kind") or "") not in UNSCORED_WINDOW_KINDS
]
frames = _frame_measures(windows)
# The streaming phase is NOT in METRIC_BY_KEY, and that is deliberate rather than an
@@ -666,3 +676,50 @@ def measures_by_cell(
for readings in single.values():
out[(int(tokens), rep)] = readings
return out
+
+
+# ── was there an instrument in the shot ──────────────────────────────
+
+
+def probe_scripts(records: Sequence[Mapping[str, Any]]) -> list[str]:
+ """Every external init script this payload records, in order, without duplicates.
+
+ EVERY `run_meta`, not the first one. `--resume` continues an interrupted run by APPENDING to
+ the existing payload, so a file can carry a clean `run_meta` at the top and a second one
+ further down with a probe named in it, above the cells that were re-recorded under that
+ probe. Returning on the first row reads such a file as clean and scores perturbed cells.
+
+ The failed `probe_free` gate is read as well as the metadata field. Two independent records of
+ one fact, so a payload written by a version that emits only one of them is still refused.
+ """
+ found: list[str] = []
+ for row in records:
+ script = ""
+ if row.get("row_type") == "run_meta":
+ script = str(row.get("probe_init_script") or "")
+ elif row.get("row_type") == "gate" and row.get("name") == "probe_free":
+ if not row.get("passed"):
+ detail = row.get("detail")
+ detail = detail if isinstance(detail, Mapping) else {}
+ script = str(detail.get("probe_init_script") or "an unnamed probe")
+ if script and script not in found:
+ found.append(script)
+ return found
+
+
+def refuse_if_probed(records: Sequence[Mapping[str, Any]], where: str) -> None:
+ """Raise rather than score a payload that was recorded with a probe in the page.
+
+ Called from every scoring entry point rather than from one of them. A refusal that only
+ `floor_table` performs still lets the run print an `ab.md` at the end and `--report` produce a
+ score from the same file afterwards, and those are the two tables somebody actually reads.
+ """
+ scripts = probe_scripts(records)
+ if not scripts:
+ return
+ raise SystemExit(
+ f"refusing to score {where}: it was recorded with an external init script "
+ f"installed ({', '.join(scripts)}). A probe samples the DOM and forces layout "
+ f"on its own schedule, so these timings are a measurement of the page and the "
+ f"instrument together. Re-run with SBENCH_EXTRA_INIT_SCRIPT unset."
+ )
diff --git a/tests/studio/studiobench/scoring/selftest/test_studiobench_from_payload.py b/tests/studio/studiobench/scoring/selftest/test_studiobench_from_payload.py
index 90a52d15ca0..5dc3f25c191 100644
--- a/tests/studio/studiobench/scoring/selftest/test_studiobench_from_payload.py
+++ b/tests/studio/studiobench/scoring/selftest/test_studiobench_from_payload.py
@@ -334,6 +334,79 @@ def test_an_action_whose_assertion_passed_is_still_a_reading():
assert measures_from_records(recs)[10_000]["keystroke_p95_ms"].value == 12.0
+# ── the composer click, which is the driver's cost and not the build's ───────────────────────
+
+
+def test_setup_windows_are_excluded_so_the_click_does_not_become_the_worst_frame():
+ """`setup:composer_click` is mostly Playwright's injected actionability script, which blocks
+ the page's main thread exactly as app work would. Pooled into the film it would peg
+ `max_frame_ms` against a 2,000 ms anchor on every run, probe or no probe."""
+ film = _window("c1", [200.0] * 10, duration_ms = 2000.0, kind = "action")
+ click = _window("c1", [11_000.0], duration_ms = 11_000.0, kind = "setup")
+
+ with_click = measures_from_records([_cell(), film, click])[10_000]
+ without = measures_from_records([_cell(), film])[10_000]
+
+ assert with_click["max_frame_ms"].value == pytest.approx(200.0)
+ assert with_click["max_frame_ms"].value == pytest.approx(without["max_frame_ms"].value)
+ assert with_click["jank_index"].value == pytest.approx(without["jank_index"].value)
+ assert with_click["time_in_jank_pct"].value == pytest.approx(without["time_in_jank_pct"].value)
+
+
+def test_setup_is_a_declared_window_kind():
+ from studiobench.runtime.types import WINDOW_KINDS
+ assert "setup" in WINDOW_KINDS
+
+
+def test_a_probe_payload_with_legitimate_zeros_still_validates():
+ """An unseeded rung has no code blocks, and `performance.now()` is coarsened to 100 us, so
+ `code_token_spans`, `blur_inpage_ms` and `forced_layout_ms` can all be a true 0. Before the
+ attestation was written next to them, `--report` refused the whole payload of a run that
+ completed."""
+ cell = _cell()
+ cell["composer_click_ms"] = 120.0
+ cell["click_attribution"] = {
+ "click_attribution_attempted": True,
+ "first_touch_ms": 10.0,
+ "touch_decay_ms": [10.0, 0.0],
+ "blur_inpage_ms": 0.0,
+ "forced_layout_ms": 0.0,
+ "code_token_spans": 0,
+ }
+ validate_payload(_payload_with(cell))
+
+
+def test_the_same_probe_payload_without_the_attestation_is_still_refused():
+ """The exemption must come from the flag, not from the key names: an unattested zero is the
+ thing the walk exists to catch."""
+ cell = _cell()
+ cell["click_attribution"] = {"code_token_spans": 0}
+ with pytest.raises(PayloadSchemaError, match = "code_token_spans"):
+ validate_payload(_payload_with(cell))
+
+
+def _payload_with(cell):
+ return {
+ "schema": "studiobench/payload/1",
+ "source": "recorder_rows",
+ "complete": True,
+ "truncated_records": 0,
+ "record_counts": {"cells": 1},
+ "header": {},
+ "selfcheck": [],
+ "windows": [],
+ "actions": [],
+ "cells": [cell],
+ "samples": [],
+ "surfaces": [],
+ "crashes": [],
+ "arms": [],
+ "unknown_rows": [],
+ "footer": None,
+ "excluded_cells": [],
+ }
+
+
# ---------------------------------------------------------------------------------------
# The latest attempt is the last one that WROTE anything, not the last one that finished
# ---------------------------------------------------------------------------------------
diff --git a/tests/studio/studiobench/sweep/floor_table.py b/tests/studio/studiobench/sweep/floor_table.py
index b626261ca30..bb6bc2f692b 100644
--- a/tests/studio/studiobench/sweep/floor_table.py
+++ b/tests/studio/studiobench/sweep/floor_table.py
@@ -43,11 +43,12 @@ if __package__ in (None, ""): # pragma: no cover
from tests.studio.studiobench.scoring.from_payload import ( # noqa: E402
ACTION_SOURCES,
FRAME_METRICS,
- IDLE_WINDOW_KINDS,
+ UNSCORED_WINDOW_KINDS,
STREAM_METRICS,
_actions_for,
_frame_measures,
_stream_measures,
+ refuse_if_probed,
)
METRICS = tuple(ACTION_SOURCES) + FRAME_METRICS + STREAM_METRICS
@@ -135,13 +136,21 @@ def cell_metrics(records: list[dict]) -> dict[str, dict[str, float]]:
if row.get("row_type") != "cell" or not row.get("completed"):
continue
cid = row["cell_id"]
+ # Scoped to this cell's OWN attempt: `--resume` re-runs a died cell under a new
+ # session_id into the same file, and pooling both attempts mixes two measurements.
sid = row.get("session_id")
own = [r for r in records if r.get("cell_id") == cid and r.get("session_id") == sid]
vals: dict[str, float] = _action_timings(own, cid)
+ # `UNSCORED_WINDOW_KINDS` is idle plus setup, dropped here as in `measures_from_records`.
+ # The setup window is the composer click that starts the film, which is mostly
+ # Playwright's injected actionability script blocking the page's own main thread; pooled
+ # in, an 11 s driver stall would set this table's `max_frame_ms` floor and hide every real
+ # regression under it.
windows = [
w
for w in own
- if w.get("row_type") == "window" and str(w.get("kind") or "") not in IDLE_WINDOW_KINDS
+ if w.get("row_type") == "window"
+ and str(w.get("kind") or "") not in UNSCORED_WINDOW_KINDS
]
for key, m in _frame_measures(windows).items():
if m.value is not None:
@@ -284,6 +293,13 @@ def load(paths: list[Path]) -> tuple[dict[str, list[tuple[float, float]]], set[s
corpora: set[str] = set()
for path in paths:
records = read_rows(path)
+ # REFUSED HERE, not warned about. This is the same class of refusal as the tier and
+ # corpus checks below, one step earlier: those two say "these are different films", and
+ # this one says "this film was shot with the camera in the shot". There is no flag to
+ # override it, because the only correct response is to re-run without the probe. The
+ # check itself lives in the scoring layer so that the A/B table and `--report` refuse on
+ # exactly the same evidence rather than on a second copy of the rule.
+ refuse_if_probed(records, str(path))
tiers |= tiers_of(records)
corpora.add(corpus_of(records))
for metric, rows in paired(records, shard = str(path.parent.name)).items():
diff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.py
index 65338cbacd6..fb55b167d43 100644
--- a/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.py
+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.py
@@ -1214,6 +1214,158 @@ def test_main_returns_two_when_nothing_matches(tmp_path, capsys):
assert "no payload found" in capsys.readouterr().out
+# ── a probe payload is not a measurement ─────────────────────────────
+
+
+def probe_payload(tmp_path: Path, name: str, script: str | None) -> Path:
+ """A payload whose run_meta records the external init script that was in the page."""
+ path = payload(tmp_path, name, [(1000.0, 900.0)] * 4)
+ rows = [json.loads(line) for line in path.read_text(encoding = "utf-8").splitlines()]
+ rows[0]["probe_init_script"] = script
+ path.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding = "utf-8")
+ return path
+
+
+def test_a_payload_recorded_with_a_probe_installed_is_refused(tmp_path):
+ """The instrument was in the shot. There is no flag to override it.
+
+ A probe samples the DOM on its own schedule and forces layout to do it, so the timings are a
+ measurement of the page AND the instrument. Without this the run looks entirely ordinary: it
+ records the same cells and renders the same A/B table, and only the caller's memory stops the
+ numbers being quoted.
+ """
+ path = probe_payload(tmp_path, "probed", "arms/content_visibility_probe.js")
+ with pytest.raises(SystemExit) as excinfo:
+ F.load([path])
+ assert "external init script" in str(excinfo.value)
+ assert "content_visibility_probe.js" in str(excinfo.value)
+
+
+def test_a_probe_named_in_a_later_run_meta_is_still_caught(tmp_path):
+ """`--resume` APPENDS a second run_meta and the remaining cells to the existing file.
+
+ So a payload can carry a clean header above cells that were re-recorded under a probe.
+ Reading only the first run_meta scores those cells.
+ """
+ path = probe_payload(tmp_path, "resumed", None)
+ with path.open("a", encoding = "utf-8") as fh:
+ fh.write(
+ json.dumps(
+ {
+ "row_type": "run_meta",
+ "tier": "standard",
+ "corpus_hash": "corpus0000",
+ "probe_init_script": "late_probe.js",
+ }
+ )
+ + "\n"
+ )
+ with pytest.raises(SystemExit) as excinfo:
+ F.load([path])
+ assert "late_probe.js" in str(excinfo.value)
+
+
+def test_a_failed_probe_free_gate_is_enough_on_its_own(tmp_path):
+ # Two independent records of one fact, so a payload from a version that emits only the gate
+ # is still refused.
+ path = probe_payload(tmp_path, "gated", None)
+ with path.open("a", encoding = "utf-8") as fh:
+ fh.write(
+ json.dumps(
+ {
+ "row_type": "gate",
+ "name": "probe_free",
+ "passed": False,
+ "detail": {"probe_init_script": "gate_only.js"},
+ }
+ )
+ + "\n"
+ )
+ with pytest.raises(SystemExit) as excinfo:
+ F.load([path])
+ assert "gate_only.js" in str(excinfo.value)
+
+
+def test_a_passing_probe_free_gate_scores_normally(tmp_path):
+ path = probe_payload(tmp_path, "clean_gate", None)
+ with path.open("a", encoding = "utf-8") as fh:
+ fh.write(
+ json.dumps(
+ {
+ "row_type": "gate",
+ "name": "probe_free",
+ "passed": True,
+ "detail": {"probe_init_script": None},
+ }
+ )
+ + "\n"
+ )
+ pooled, _ = F.load([path])
+ assert pooled["message_menu.open_close_ms"]
+
+
+def test_the_report_path_refuses_a_probed_payload_too(tmp_path):
+ """floor_table is not the only reader. `--report` scores the same file afterwards."""
+ from tests.studio.studiobench.report.build import score_payload
+
+ path = probe_payload(tmp_path, "probed_report", "arms/content_visibility_probe.js")
+ with pytest.raises(SystemExit) as excinfo:
+ score_payload(path)
+ assert "external init script" in str(excinfo.value)
+
+
+def test_a_null_probe_field_is_the_ordinary_scorable_case(tmp_path):
+ # Explicit null and absent must both score, or every payload written before the field
+ # existed becomes unreadable.
+ pooled, _ = F.load([probe_payload(tmp_path / "explicit", "clean", None)])
+ assert pooled["message_menu.open_close_ms"]
+ pooled, _ = F.load([payload(tmp_path / "absent", "clean", [(1000.0, 900.0)] * 4)])
+ assert pooled["message_menu.open_close_ms"]
+
+
+def test_the_composer_click_does_not_set_the_frame_floor(tmp_path):
+ """The floor table pools the cell's windows too. An 11 s `setup:composer_click` -- almost all
+ of it Playwright's actionability check running on the page's main thread -- would become this
+ table's `max_frame_ms` floor and swallow every regression smaller than itself."""
+
+ def _frames(gaps):
+ return {
+ "frames": {
+ "frames_attempted": True,
+ "frame_gaps_ms": gaps,
+ "frame_gaps_truncated": False,
+ "max_frame_ms": max(gaps),
+ }
+ }
+
+ rows = [
+ {"row_type": "run_meta", "tier": "standard"},
+ {"row_type": "cell", "cell_id": "100K.base.rep0", "completed": True},
+ {
+ "row_type": "window",
+ "cell_id": "100K.base.rep0",
+ "kind": "action",
+ "duration_ms": 2000.0,
+ "instruments": _frames([120.0] * 10),
+ },
+ {
+ "row_type": "window",
+ "cell_id": "100K.base.rep0",
+ "name": "setup:composer_click",
+ "kind": "setup",
+ "duration_ms": 11_000.0,
+ "instruments": _frames([11_000.0]),
+ },
+ ]
+ out = tmp_path / "click"
+ out.mkdir()
+ (out / "payload.jsonl").write_text(
+ "".join(json.dumps(r) + "\n" for r in rows), encoding = "utf-8"
+ )
+ metrics = F.cell_metrics(F.read_rows(out / "payload.jsonl"))["100K.base.rep0"]
+ assert metrics["max_frame_ms"] == 120.0
+
+
# ── the documented loop runs liveness before it reads a timing ───────