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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
studiobench: measure what streaming one character costs, and fix the gap windows that mislabel it (#9351)
Daniel Han0df6fde865c3
diff --git a/tests/studio/studiobench/INTERFACES.md b/tests/studio/studiobench/INTERFACES.mdindex 99ba92de792..b894fc0585b 100644--- a/tests/studio/studiobench/INTERFACES.md+++ b/tests/studio/studiobench/INTERFACES.md@@ -67,8 +67,8 @@ accumulate. Windows do not nest and do not overlap; opening one while another is```python@dataclassclass Window:- name: str # "action:scroll_after", "stream:seg3", "idle:calibrate"- kind: str # "action" | "stream" | "idle" | "settle" | "teardown"+ name: str # "action:scroll_after", "stream:gap3", "idle:calibrate"+ kind: str # "action" | "stream" | "gap" | "idle" | "settle" | "teardown"cell: Cellt_open_ms: float # driver monotonic ms since session t0t_close_ms: float | None@@ -76,6 +76,19 @@ class Window:instruments: dict # {instrument_name: dict}, filled on close```+**`gap` is not `stream`, and the difference has already misled this project.** The scheduler opens+a `gap` window before every slot, to keep frame coverage continuous between actions. On the+standard film that is eighteen of them, and only the first four contain any streaming: the rest are+the quiet stretches between post-generation actions. Measured on a 100K cell, `stream:gap12` ran+32.9 s at 1.6% busy with the reply thirty seconds finished, while `stream:drain` -- the one window+that is genuinely about the stream -- was 7 ms long. These windows carried `kind = "stream"` until+that was corrected, and anyone who filtered on it to find the streaming phase selected mostly+post-stream idle.++The NAMES still read `stream:gapN`, because they are the join key in every payload already written.+Trust the `kind`, not the name, and to find the streaming phase itself detect it from the SSE+traffic rather than from either.+Opened as a context manager on the session:```pythondiff --git a/tests/studio/studiobench/__main__.py b/tests/studio/studiobench/__main__.pyindex 088ead67aed..49c012bb2df 100644--- a/tests/studio/studiobench/__main__.py+++ b/tests/studio/studiobench/__main__.py@@ -460,6 +460,78 @@ def _ab_label(sides: list, is_null: bool) -> str:return f"{sides[0]['ref']} -> {sides[1]['ref']}"+def arm_origins(specs: list) -> list:+ """Each side's ORIGIN, resolved exactly as the acquisition loop resolves its base URL.++ An attached side is the URL the caller typed; one this run installs is launched by+ `launch_studio` on the port `side_specs` handed it and `StudioInstall.base_url` is+ `http://127.0.0.1:{port}`. Read from the specs rather than from the sides so the answer is+ available BEFORE anything is cloned, built or launched.++ CANONICALISED, because a typed URL is not an origin. `origin_scoped` gates on+ `window.location.origin`, which lower-cases the scheme and host, drops a port the scheme+ implies and keeps no path -- so `http://studio:80` and `http://studio` are ONE origin to the+ browser and were two to a comparison on the strings. See `browser_origin`, which is what+ `origin_scoped` now gates on too, so the refusal below and the predicate it protects are+ reading the same thing.+ """+ from .runtime.ab import browser_origin+ return [+ (browser_origin(attach) if attach else f"http://127.0.0.1:{port}")+ for _label, _ref, attach, port, _password in specs+ ]+++def stream_cost_injection_problem(specs: list, inject_ms) -> str | None:+ """Why `--inject-stream-cost-ms` cannot be honoured against these sides. `None` when it can.++ THE INJECTION IS GATED BY ORIGIN AND NOTHING ELSE. Both arms are driven by one browser+ context and one page, so the init scripts assembled in `run` are the context's, not an arm's:+ `add_init_script` fires on every document. `origin_scoped` is the only discriminator available+ and it discriminates on `window.location.origin`, so two arms served from ONE origin both+ match the treatment's predicate and both burn the injected cost.++ That configuration is not a mistake the caller has to be warned off in general -- one attached+ Studio driven twice is a null control `is_null_control` detects on purpose, and+ `test_one_attached_studio_driven_twice_is_a_null_control` pins it. It is only fatal WITH the+ injection, and it is fatal quietly: `evaluate_stream_cost_recovery_gate` reads back+ `(injected_rate - base_rate) * chars`, both rates carry the burn, the difference is zero, and+ the gate fails with "the accumulator is under-attributing" -- a verdict against a metric that+ was working, delivered by the one flag whose entire job is to tell those two apart.++ ONE ORIGIN CAN BE TWO SPELLINGS, which is why `arm_origins` canonicalises rather than+ comparing what was typed. `--attach http://studio --attach-b http://studio:80` is one server+ under two names and a browser reports `http://studio` for both, so the treatment's injection is+ gated on an origin no document has: it burns on NEITHER arm and the difference is zero for the+ other reason. Spelled the other way round the base's predicate is the dead one, the treatment's+ matches every document, and both arms burn. Either way the run reaches the same false verdict,+ and neither is visible in the two URLs the caller typed -- so the refusal names the origin both+ resolve to alongside the spellings.++ Refused rather than isolated. Isolating by arm would mean toggling the burn at every cell+ boundary from the driver, which puts the injection's own timing inside the measured window;+ the cheap and honest answer is to give the two arms two origins.+ """+ if not inject_ms or len(specs) < 2:+ return None+ origins = arm_origins(specs)+ if origins[0] != origins[1]:+ return None+ typed = [spec[2] for spec in specs[:2]]+ spelling = (+ f" ({typed[0]} and {typed[1]} are one origin under two names)"+ if all(typed) and typed[0].rstrip("/") != typed[1].rstrip("/")+ else ""+ )+ return (+ f"--inject-stream-cost-ms needs the two arms on DIFFERENT origins, and both are "+ f"{origins[0]}{spelling}. The injection is installed as a context init script gated on "+ f"window.location.origin, so one origin means both arms burn the cost, the difference "+ f"between them is zero and the recovery gate blames the metric for it. Point --attach and "+ f"--attach-b at two Studios, or drop --attach and let this run install both."+ )++def stop_owned_sides(installs: list,stop,@@ -535,6 +607,15 @@ def run(args, ab_ref = None) -> int:if args.attach and not args.attach_b:_log(" --ab with --attach needs --attach-b URL: the second build has to be somewhere.")return 2+ # Here rather than beside the init script it guards, because by then two Studios have been+ # cloned, built and launched to run a validation that cannot say anything. See+ # `stream_cost_injection_problem`.+ injection_problem = stream_cost_injection_problem(+ specs, getattr(args, "inject_stream_cost_ms", None)+ )+ if injection_problem:+ _log(f" {injection_problem}")+ return 2_log(f" A/B: base={args.branch} vs treatment={ab_ref}, interleaved in ONE session")installs = []@@ -704,6 +785,24 @@ def run(args, ab_ref = None) -> int:side["seed_script"] = _side_seedinit_scripts.append(_side_seed(side_auth))+ if getattr(args, "inject_stream_cost_ms", None) and side is not sides[0]:+ # VALIDATION, not a measurement mode. Burns a known amount of main-thread time per+ # SSE chunk on the TREATMENT side only, so an A/B whose two arms are otherwise the+ # same build has a known answer. It is origin-gated like the seed above, because a+ # context init script fires on every document and burning on both sides would+ # inject the cost into the control as well and read back a recovery of zero.+ from .instruments.selfcheck import stream_cost_injection_init_script+ init_scripts.append(+ origin_scoped(+ side["base_url"],+ stream_cost_injection_init_script(args.inject_stream_cost_ms),+ )+ )+ _log(+ f" {side['label']}: INJECTING {args.inject_stream_cost_ms} ms of main-thread "+ f"time per SSE chunk. This arm is not a measurement of the build."+ )+auth = sides[0]["auth"]init_scripts.append(resources.read_text("scene/dom.js"))init_scripts.append(resources.read_text("scene/parity.js"))@@ -780,6 +879,17 @@ def run(args, ab_ref = None) -> int:"tier_rungs": TIER_RUNGS[args.tier],"reps": args.reps,"instrument_level": args.instrument_level,+ # In the payload, not only in the log. Two runs with different fixtures are+ # not comparable, and a fixture difference that is not recorded is one a later+ # reader has no way to notice before quoting a ratio across it.+ "stream_tail_chars": args.stream_tail_chars,+ "corpus_dollars": bool(args.corpus_dollars),+ # AN ARM RUNNING THIS IS NOT A MEASUREMENT OF THE BUILD, and the payload has to+ # say so itself. A reader who finds a treatment arm 40% slower has no other way+ # to discover that the harness put the 40% there on purpose, and `--resume` reads+ # it back as an identity axis so a calibration cannot be continued as an ordinary+ # run or the other way round. See `IDENTITY_AXES`.+ "inject_stream_cost_ms": getattr(args, "inject_stream_cost_ms", None),})rec.gate("production_build", verdict.production, verdict.as_dict())@@ -856,7 +966,18 @@ def run(args, ab_ref = None) -> int:auth = seeder.auth,model_id = model_id,log = _log,+ stream_tail_chars = args.stream_tail_chars,+ corpus_dollars = args.corpus_dollars,)+ if args.stream_tail_chars or args.corpus_dollars:+ # Loud, because both change the fixture. A payload produced under either of them is+ # not comparable with one produced without, and the pair that says so is printed here+ # and written into the run manifest above.+ _log(+ f" FIXTURE CHANGED: stream tail {args.stream_tail_chars or 'default'}, "+ f"dollars {'on' if args.corpus_dollars else 'off'}. Compare only against a run "+ f"with the same pair."+ )if cells:ladder_ratio = cells[0][0].meta["ladder_chars_per_token"]rec.gate("ladder_ratio_measured", not ladder_ratio["provisional"], ladder_ratio)@@ -891,6 +1012,8 @@ def run(args, ab_ref = None) -> int:)done = _resume_set(paths) if args.resume else set()+ if done:+ _log(f" resuming: {len(done)} cells already in {paths.payload_jsonl.name}")if ab_ref:from .runtime.ab import Target, interleave, order_is_balanced@@ -1154,12 +1277,49 @@ IDENTITY_AXES = ("studio_ref","treatment_ref","treatment_url",+ # Added by this branch with `--stream-tail-chars` / `--corpus-dollars`: both change the reply+ # the cell streams without moving its id, so they belong to the identity for the same reason+ # the tier does. Recorded already, so no schema change and a payload from before them reads+ # back as the defaults (see `HISTORICAL_DEFAULTS`).+ "stream_tail_chars",+ "corpus_dollars",+ # `--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,+ # under a cell id that cannot tell -- the id carries the rung, the arm and the repetition and+ # stops there. Off it, `--resume` had two ways to lie about a calibration: against a FINISHED+ # uninjected payload every pair is skippable, the run exits 0 having measured nothing, and the+ # recovery gate is answered from cells that were never injected; against a HALF-FINISHED+ # injected one the resume drops the flag and the ladder ends up part injected and part not.+ # 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",)#: The axes that describe the SECOND side, which only exist when a run has one. See#: `identity_problems`: an A/B judged against a run that is not one may not differ on them.TREATMENT_AXES = ("treatment_ref", "treatment_url")+#: The axes whose ABSENCE from a payload is itself a reading, and what it reads as.+#:+#: `identity_problems` otherwise skips an axis the payload never declared, because an axis a row+#: 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.+HISTORICAL_DEFAULTS = {+ "stream_tail_chars": None,+ "corpus_dollars": False,+ "inject_stream_cost_ms": None,+}+#: THE RATIO THE LADDER WAS SIZED BY, carried on every cell's `meta` by `session.build_cells`.#: Not in `IDENTITY_AXES`: those are checked by `prepare_payload` before anything is installed,#: and this one is not known until `build_cells` has measured the corpus. Checked instead by@@ -1221,6 +1381,9 @@ def requested_identity(args, ab_ref, corpus_hash: str) -> dict:# the identity check, skipped every completed treatment cell and reported B's measurements# as C's result. Empty for a treatment this run installs itself, whose ref IS its identity."treatment_url": attach_b if (ab_ref and attach_b) else "",+ "stream_tail_chars": args.stream_tail_chars,+ "corpus_dollars": bool(args.corpus_dollars),+ "inject_stream_cost_ms": getattr(args, "inject_stream_cost_ms", None),}@@ -1320,16 +1483,26 @@ def identity_problems(recorded: dict, requested: dict) -> list:# the axis where the two of them do differ.both_ab = bool(requested.get("treatment_ref")) and bool(recorded.get("treatment_ref"))for axis in IDENTITY_AXES:- if axis not in recorded:+ declared = axis in recorded+ if declared:+ got = recorded[axis]+ elif axis in HISTORICAL_DEFAULTS:+ # Not declared, but not silent either: this axis postdates the payload, so the payload+ # ran under the default. See `HISTORICAL_DEFAULTS`.+ got = HISTORICAL_DEFAULTS[axis]+ else:# An axis this payload never declared. See `recorded_identities`.continueif axis in TREATMENT_AXES and not both_ab:continue- want, got = requested.get(axis), recorded[axis]+ want = requested.get(axis)if str(want) != str(got):- problems.append(- f"{axis}: the payload was recorded with {got!r}, this run asks {want!r}"+ where = (+ f"the payload was recorded with {got!r}"+ if declared+ else f"the payload predates this axis and therefore ran with {got!r}")+ problems.append(f"{axis}: {where}, this run asks {want!r}")return problems@@ -1923,6 +2096,40 @@ def parse_args(argv: list):"quiet measurement machine; raise it only on a contended runner, where the ""gate is proving the plumbing works rather than that the runner is fast",)+ ap.add_argument(+ "--stream-tail-chars",+ type = int,+ dest = "stream_tail_chars",+ help = "override how many characters of the last turn STREAM. The rung ladder "+ "pins this at 6,000 on every rung so that the thread is the only thing that "+ "varies, which means a cost scaling with the length of the reply being streamed "+ "is constant across the whole ladder and reads as a floor. This is the axis that "+ "can see one. Raising it makes the film's after-generation slots run mid-stream, "+ "so check the payload with --assert-liveness rather than trusting the labels",+ )+ ap.add_argument(+ "--inject-stream-cost-ms",+ type = float,+ dest = "inject_stream_cost_ms",+ help = "VALIDATION. Burn this many milliseconds of main-thread time per SSE chunk on the "+ "treatment side, inside the task chain the chunk starts. Needs --ab. The point is to "+ "check that the streaming-cost metric reads back a cost this harness injected itself: a "+ "metric that cannot see a known cost cannot see an unknown one, and the recovery fraction "+ "is what says which of the two a null result was. An arm running this is not a "+ "measurement of the build",+ )+ ap.add_argument(+ "--corpus-dollars",+ action = "store_true",+ dest = "corpus_dollars",+ help = "give the STREAMED turns the CURRENCY AND SHELL dollars a real reply has "+ "($HOME, $12.99). Not the same thing as the LaTeX the frozen corpus carries since "+ "corpus v2: that is well-formed math in the SEEDED thread, which exercises the "+ "renderer, and this is malformed-on-purpose dollars in the turn that STREAMS, "+ "which exercises preprocessLaTeX's currency-escape and code-region heuristics. "+ "Measured over one 96,000 character reply, the cheap regime is 15.3 ms and the "+ "expensive one 281.3 ms. The frozen units on disk and their hashes are untouched",+ )ap.add_argument("--rungs", help = "comma-separated rung override, e.g. 1K,10K")ap.add_argument("--reps", type = int, default = 1)ap.add_argument(diff --git a/tests/studio/studiobench/arms/selftest/test_studiobench_selfcheck.py b/tests/studio/studiobench/arms/selftest/test_studiobench_selfcheck.pyindex 9874210a3d3..03c5e674967 100644--- a/tests/studio/studiobench/arms/selftest/test_studiobench_selfcheck.py+++ b/tests/studio/studiobench/arms/selftest/test_studiobench_selfcheck.py@@ -230,3 +230,68 @@ def test_the_abort_message_says_why_reporting_nothing_is_better():with pytest.raises(SelfCheckFailure) as caught:report.raise_if_failed()assert "the numbers get quoted and the blindness does not" in str(caught.value)+++# ── the streaming-cost recovery gate ─────────────────────────────────────────────────────────+++def _recovery(+ base,+ injected,+ total_ms = 600.0,+ chars = 6_000,+):+ from studiobench.instruments.selfcheck import evaluate_stream_cost_recovery_gate+ return evaluate_stream_cost_recovery_gate(base, injected, total_ms, chars)+++def test_full_recovery_of_an_injected_streaming_cost_passes():+ # 600 ms injected over 6,000 characters is 100 ms per thousand on top of the base rate.+ gate = _recovery(110.0, 210.0)+ assert gate.passed+ assert gate.measured.value == pytest.approx(1.0)+++def test_partial_recovery_is_reported_as_a_fraction_not_rounded_up():+ gate = _recovery(110.0, 185.0)+ assert gate.measured.value == pytest.approx(0.75)+ assert gate.passed+++def test_under_recovery_FAILS_rather_than_being_called_close_enough():+ """THE FAILURE DIRECTION. A metric reading back a quarter of a known cost under-reports an+ unknown one by the same factor, and the gate exists to say so out loud."""+ gate = _recovery(110.0, 135.0)+ assert gate.measured.value == pytest.approx(0.25)+ assert not gate.passed+ assert "under-attributing" in gate.detail+++def test_a_metric_that_did_not_move_at_all_fails():+ gate = _recovery(110.0, 110.0)+ assert gate.measured.value == pytest.approx(0.0)+ assert not gate.passed+++def test_a_missing_reading_is_a_failure_not_a_zero_recovery():+ gate = _recovery(None, 210.0)+ assert not gate.passed+ assert gate.measured.value is None+ assert "the base rate" in (gate.measured.note or "")+++def test_a_zero_denominator_refuses_rather_than_dividing():+ gate = _recovery(110.0, 210.0, total_ms = 600.0, chars = 0)+ assert not gate.passed+ assert gate.measured.value is None+++def test_the_injection_script_burns_only_on_sse_chunks():+ from studiobench.instruments.selfcheck import stream_cost_injection_init_script++ js = stream_cost_injection_init_script(3.0)+ assert 'indexOf("data:")' in js+ # Queued, not inline: the burn has to land inside the measured chain whichever TextDecoder+ # wrapper ended up outermost.+ assert "queueMicrotask" in js+ assert "3.0" in jsdiff --git a/tests/studio/studiobench/fixture/corpus.py b/tests/studio/studiobench/fixture/corpus.pyindex 048379ebada..62afbb2543e 100644--- a/tests/studio/studiobench/fixture/corpus.py+++ b/tests/studio/studiobench/fixture/corpus.py@@ -39,7 +39,7 @@ from __future__ import annotationsimport hashlibimport jsonimport random-from dataclasses import dataclass, field+from dataclasses import dataclass, field, replacefrom pathlib import Pathfrom typing import Iterator, Optional@@ -926,6 +926,66 @@ class RungPlan:return self.seeded_chars + self.streamed_chars + self.follow_up_chars+def dollarise(text: str, salt: str) -> str:+ """Give `text` the CURRENCY AND SHELL dollars a real reply has, deterministically.++ WHAT THIS IS FOR, AND WHAT IT IS NO LONGER FOR. This was written when the frozen corpus+ contained zero `$`, zero `\\[` and zero `\\(` across all 519,859 characters, so that+ `preprocessLaTeX` -- which runs on the whole reply once per animation frame -- always took its+ cheap path. That path is an early return after `text.includes("$")` fails+ (`studio/frontend/src/lib/latex.ts`), and the two regimes are an order of magnitude apart:+ measured over one 96,000 character reply, 15.3 ms against 281.3 ms.++ CORPUS v2 CHANGED THAT AND THIS DOCSTRING WOULD OTHERWISE LIE. The frozen corpus now carries+ well-formed LaTeX throughout, and the streamed unit is drawn from it, so the streamed reply+ already contains `$` without this flag: 10 of them at the 10K rung and 6 at 100K, measured.+ The early return is therefore already defeated by default, and the claim that the expensive+ regime "has never been exercised" is dead. Anyone reaching for this flag to reach that regime+ does not need it any more.++ WHAT IT STILL DOES, which is narrower and worth stating exactly. The early return is keyed on+ the reply BEING PROCESSED -- `preprocessLaTeX(displayText)` is called per message+ (`components/assistant-ui/markdown-text.tsx`) -- and past it the cost is the `CURRENCY_REGEX`+ pass, whose callback has three branches: skip inside a code region, skip inside a math region+ just created from `\\(...\\)`, and escape everything else. v2's dollars are well-formed math,+ so they take the SKIP branches. The dollars added here are deliberately not math: `$HOME/...`+ inside fences exercises the code-region exclusion, and `$12.99` in prose exercises the escape+ branch and `hasInlineMathCloser`. That is the false-positive half of the function, and it is+ the half that rewrites the string rather than leaving it alone.++ So the two mechanisms are complementary rather than redundant: v2 puts renderable math in the+ SEEDED thread and exercises the renderer, and this puts malformed-on-purpose dollars in the+ turn that STREAMS and exercises the heuristics, per chunk, on the path a streaming-cost metric+ measures. Expect a far smaller effect from this flag than the 15.3-to-281.3 figure above,+ because that transition now happens without it.++ Applied to the STREAMED unit only, and never to the frozen corpus on disk: the frozen units+ and their hashes are exactly what they were, so a run with this off is byte-identical to a run+ of the same corpus version without it. A run with it on records the fact in its payload,+ because a corpus difference that is not in the payload is a difference two runs will be+ compared across without knowing.+ """+ lines = text.split("\n")+ out: list[str] = []+ fenced = False+ for index, line in enumerate(lines):+ stripped = line.lstrip()+ if stripped.startswith("```") or stripped.startswith("~~~"):+ fenced = not fenced+ out.append(line)+ continue+ # Inside a fence, shell-shaped lines. Outside it, prices in prose. Both are what a real+ # answer contains, and they exercise different branches: the code-region scan has to+ # EXCLUDE the first and the currency heuristic has to escape the second.+ if fenced and index % 11 == 0:+ out.append(f"{line} # $HOME/{salt}{index} costs $1{index % 10}.99")+ elif not fenced and line and index % 17 == 0:+ out.append(f"{line} It costs ${index % 9}{index % 10}.99 or ${index % 7},200 a year.")+ else:+ out.append(line)+ return "\n".join(out)++def _too_small(rung: str, chars_per_token: float, last_index: int, what: str) -> ValueError:"""The one message for every way a rung can outgrow the frozen corpus.@@ -990,6 +1050,8 @@ def plan_rung(corpus: Corpus,rung: str,chars_per_token: float = PROVISIONAL_CHARS_PER_TOKEN,+ stream_tail_chars: Optional[int] = None,+ dollars: bool = False,) -> RungPlan:"""Which units are SEEDED and which one STREAMS.@@ -1015,8 +1077,20 @@ def plan_rung(# Holding the tail constant also isolates the variable under investigation. The question is# what a streamed chunk costs AS A FUNCTION OF THE THREAD ALREADY ON SCREEN, and that needs# the chunk workload held fixed while the thread grows, not both moving together.+ # `stream_tail_chars` overrides the constant, and is the ONLY way to vary reply length in this+ # tool. The paragraphs above explain why the tail is pinned: the rung ladder exists to ask what+ # a chunk costs as a function of the THREAD, and that needs the chunk workload held fixed. The+ # consequence, which cost a whole investigation to rediscover, is that a cost scaling with the+ # length of the reply BEING STREAMED is constant across every rung and reads as a floor. Such a+ # mechanism is real and this ladder cannot see it at any effect size.+ #+ # Raising this makes the film's labels false in the way the note above describes, because the+ # stream then outlasts the after-generation slots. That is a trade a reply-length investigation+ # has to make deliberately, so it is a parameter and not a second constant, and `--assert-+ # liveness` on the resulting payload is how the cost of making it shows up.turns = STREAM_TURNS if target_chars >= MULTI_TURN_MIN_CHARS else 1- tail_target = min(STREAM_TAIL_CHARS, target_chars)+ tail_budget = STREAM_TAIL_CHARS if stream_tail_chars is None else max(1, stream_tail_chars)+ tail_target = min(tail_budget, target_chars) if stream_tail_chars is None else tail_budgetfollow_budget = FOLLOW_UP_CHARS * (turns - 1)seed_target = max(0, target_chars - tail_target - follow_budget)@@ -1064,6 +1138,21 @@ def plan_rung(# against a finished reply while still being labelled "during generation".streamed = corpus.unit(len(seeded)).clipped_to(tail_target)follow_ups = [corpus.unit(len(seeded) + i).clipped_to(FOLLOW_UP_CHARS) for i in range(1, turns)]+ if dollars:+ # The streamed turns only. The seeded prefix is rendered once at mount and never+ # re-preprocessed, so dollars there would change the corpus without changing what the+ # per-frame path is asked to do.+ streamed = replace(+ streamed,+ reasoning = dollarise(streamed.reasoning, "r"),+ content = dollarise(streamed.content, "c"),+ )+ streamed = replace(streamed, chars = len(streamed.reasoning) + len(streamed.content))+ follow_ups = [+ replace(u, reasoning = dollarise(u.reasoning, "r"), content = dollarise(u.content, "c"))+ for u in follow_ups+ ]+ follow_ups = [replace(u, chars = len(u.reasoning) + len(u.content)) for u in follow_ups]plan = RungPlan(rung = rung,diff --git a/tests/studio/studiobench/fixture/selftest/test_studiobench_reply_axis.py b/tests/studio/studiobench/fixture/selftest/test_studiobench_reply_axis.pynew file mode 100644index 00000000000..3591b2e05cb--- /dev/null+++ b/tests/studio/studiobench/fixture/selftest/test_studiobench_reply_axis.py@@ -0,0 +1,339 @@+# 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 reply-length axis and the dollar-bearing corpus, which the rung ladder cannot provide.++The ladder pins the streamed reply at `STREAM_TAIL_CHARS` on every rung, deliberately, so that the+thread is the only thing that varies. The consequence is that a cost scaling with the length of the+reply BEING STREAMED is constant across the whole ladder and reads as a floor rather than as an+effect. These two knobs are the axis that can see one, and the tests below pin the properties that+make them trustworthy: the default is unchanged, the frozen corpus is untouched, and a run that+uses either of them says so.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[3]))++from studiobench.fixture.corpus import ( # noqa: E402+ STREAM_TAIL_CHARS,+ Corpus,+ dollarise,+ plan_rung,+)++FROZEN = Path(__file__).resolve().parents[1] / "corpus" / "frozen"++[email protected](scope = "module")+def corpus() -> Corpus:+ return Corpus.load()+++def _streamed_text(plan) -> str:+ unit = plan.streamed_unit+ return "" if unit is None else unit.reasoning + unit.content+++def test_the_default_is_exactly_what_it_was(corpus: Corpus):+ """No argument means no change, so every earlier payload stays comparable."""+ before = plan_rung(corpus, "100K")+ after = plan_rung(corpus, "100K", stream_tail_chars = None, dollars = False)+ assert before.streamed_chars == after.streamed_chars+ assert _streamed_text(before) == _streamed_text(after)+ assert before.streamed_chars <= STREAM_TAIL_CHARS+++def test_the_ladder_really_does_pin_the_reply_length(corpus: Corpus):+ """The premise of the whole axis, asserted rather than described.++ If this ever fails, the rung ladder has started varying reply length and a reply-length+ investigation can use it directly.++ Not exact equality: the tail is clipped at whole BLOCK boundaries, so it lands a little under+ the budget and where it lands depends on the unit. The invariant is that it does not GROW with+ the rung, which is what decides whether the ladder can see a reply-length effect.+ """+ plans = {rung: plan_rung(corpus, rung) for rung in ("1K", "10K", "100K")}+ lengths = {rung: p.streamed_chars for rung, p in plans.items()}+ assert max(lengths.values()) <= STREAM_TAIL_CHARS, lengths++ # The thread grows tenfold between these two rungs; the reply must not.+ thread_ratio = plans["100K"].total_chars / plans["10K"].total_chars+ reply_ratio = lengths["100K"] / lengths["10K"]+ assert thread_ratio > 8, (thread_ratio, plans["10K"].total_chars, plans["100K"].total_chars)+ assert reply_ratio < 1.1, (reply_ratio, lengths)+++def test_the_tail_override_moves_the_reply_and_not_the_thread(corpus: Corpus):+ """Reply length is the variable; total thread size stays put, or the two are confounded."""+ base = plan_rung(corpus, "100K")+ for tail in (24_000, 96_000):+ plan = plan_rung(corpus, "100K", stream_tail_chars = tail)+ assert abs(plan.streamed_chars - tail) < tail * 0.1, (tail, plan.streamed_chars)+ # Within a few percent: the seeded prefix is trimmed to compensate, so the cell measures+ # a different SPLIT of the same total rather than a bigger thread.+ assert abs(plan.total_chars - base.total_chars) < base.total_chars * 0.05, (+ tail,+ plan.total_chars,+ base.total_chars,+ )+++def test_the_tail_override_grows_monotonically(corpus: Corpus):+ seen = [+ plan_rung(corpus, "100K", stream_tail_chars = t).streamed_chars+ for t in (6_000, 12_000, 24_000, 48_000, 96_000)+ ]+ assert seen == sorted(seen), seen+ assert seen[-1] > seen[0] * 10, seen+++def test_the_frozen_corpus_now_carries_math_of_its_own(corpus: Corpus):+ """This test used to assert the opposite, and the change is the point.++ It was written to pin a defect: the frozen corpus contained zero `$`, so `preprocessLaTeX`+ always took its cheap early return and `--corpus-dollars` was the only way past it. Its+ docstring said that if a future corpus gained a `$` of its own, this test would fail and+ whoever changed it would have to decide whether `--corpus-dollars` was still needed rather+ than let the two silently overlap.++ Corpus v2 did exactly that, and the gate fired as designed. The answer to the question it+ forced is in `dollarise`'s docstring: the flag is no longer what reaches the expensive regime,+ but it is not redundant either, because v2's dollars are well-formed math that the currency+ pass SKIPS and its dollars are false positives that the currency pass REWRITES.++ So the assertion is inverted rather than deleted. A future corpus that loses its math would+ silently return every run to the cheap path, and that must fail here too.+ """+ text = "".join(+ json.loads(line)["reasoning"] + json.loads(line)["content"]+ for line in (FROZEN / "units.jsonl").read_text(encoding = "utf-8").splitlines()+ if line.strip()+ )+ assert text.count("$") > 0, "corpus v2 puts math in the frozen units; this found none"+ # Both delimiter families, because `convertLatexDelimiters` handles them on different paths.+ assert text.count("\\[") > 0+ assert text.count("\\(") > 0+++def test_dollars_reach_the_streamed_turn_and_nothing_else(corpus: Corpus):+ """The flag ADDS to the streamed turn; it no longer creates the only dollars in it.++ Under corpus v2 the streamed unit is drawn from a corpus that carries math, so it already has+ `$` before the flag is applied. What the flag has to do now is add MORE, and add them only+ where they belong.+ """+ plain = plan_rung(corpus, "100K", stream_tail_chars = 24_000)+ salted = plan_rung(corpus, "100K", stream_tail_chars = 24_000, dollars = True)+ assert _streamed_text(salted).count("$") > _streamed_text(plain).count("$")+ # The seeded prefix is rendered once at mount and never re-preprocessed, so dollars there+ # would change the corpus without changing what the per-frame path is asked to do. v2's own+ # math is expected there; what must not appear is anything THIS added, so the prefix has to+ # be byte-identical with the flag on and off.+ assert [(u.reasoning, u.content) for u in salted.seeded_units] == [+ (u.reasoning, u.content) for u in plain.seeded_units+ ]+++def test_the_flag_is_not_a_no_op_under_corpus_v2(corpus: Corpus):+ """FAILURE DIRECTION. A flag that stopped changing anything must not keep shipping quietly.++ v2 defeats `preprocessLaTeX`'s early return on its own, so the flag's original justification is+ gone. It survives because it exercises a different branch of the same function: dollars that+ are NOT math, which the currency pass has to escape or exclude rather than skip. If a future+ corpus makes even that indistinguishable, this fails and the flag should be deleted.+ """+ plain = _streamed_text(plan_rung(corpus, "100K", stream_tail_chars = 24_000))+ salted = _streamed_text(plan_rung(corpus, "100K", stream_tail_chars = 24_000, dollars = True))+ assert salted != plain+ # Shell-shaped and price-shaped, which is what makes them false positives rather than math.+ added = salted.count("$") - plain.count("$")+ assert added > 0, "the flag added no dollars, so it is a no-op and should be removed"+ assert "$HOME/" in salted or ".99" in salted+++def test_dollars_are_deterministic(corpus: Corpus):+ a = _streamed_text(plan_rung(corpus, "100K", stream_tail_chars = 24_000, dollars = True))+ b = _streamed_text(plan_rung(corpus, "100K", stream_tail_chars = 24_000, dollars = True))+ assert a == b+++def test_dollarise_keeps_shell_dollars_inside_the_fence(corpus: Corpus):+ """The two branches are not interchangeable and the test says which is which.++ A `$` inside a fence must be EXCLUDED by the code-region scan and a `$` in prose must be+ escaped by the currency pass. A generator that only produced one of them would exercise half+ the function while looking like it exercised all of it.+ """+ source = "\n".join(+ [+ "```bash",+ *[f"line {i}" for i in range(30)],+ "```",+ "",+ *[f"prose line {i}" for i in range(30)],+ ]+ )+ out = dollarise(source, "x")+ fenced, prose = [], []+ inside = False+ for line in out.split("\n"):+ if line.lstrip().startswith("```"):+ inside = not inside+ continue+ (fenced if inside else prose).append(line)+ assert any("$" in line for line in fenced), out+ assert any("$" in line for line in prose), out+++def test_dollarise_does_not_reduce_the_text(corpus: Corpus):+ """It only adds, so a dollarised cell is never SHORTER than its plain twin."""+ source = "\n".join(f"line {i}" for i in range(50))+ assert len(dollarise(source, "x")) >= len(source)+ assert dollarise("", "x") == ""+++# ── the axis has to survive the film, not just the fixture ───────────────────────────────────+++def test_a_long_tail_really_does_outlast_the_standard_film(corpus: Corpus):+ """The premise of the test below, taken from the real corpus rather than asserted.++ The films are packed against the DEFAULT tail: `stop_generation` opens at 28 s on the standard+ film and the pinned 6,000 character tail drains in at most 17.8 s, so nothing of the cell's own+ is ever running when that slot opens. Raise the tail and the slot lands mid-stream.+ """+ from studiobench.scene.schedule import STANDARD++ field_chars_per_sec = 24 / 0.073+ stop = next(s for s in STANDARD.slots if s.action == "stop_generation")++ default_s = plan_rung(corpus, "100K").streamed_chars / field_chars_per_sec+ assert default_s < stop.t_start_ms / 1000.0, default_s++ long_s = (+ plan_rung(corpus, "100K", stream_tail_chars = 96_000).streamed_chars / field_chars_per_sec+ )+ assert long_s > STANDARD.duration_ms / 1000.0, long_s+ assert long_s > stop.t_start_ms / 1000.0+++class _FakeKeyboard:+ def __init__(self, page) -> None:+ self.pressed: list[str] = []+ self._page = page++ def press(self, key: str) -> None:+ self.pressed.append(key)+ if key == "Enter" and "one more" in self._page.filled:+ # Sending the throwaway turn starts a generation, which is what the own-turn path+ # then waits for and stops.+ self._page.running = True+++class _FakePage:+ """The four page calls `stop_generation` makes, and a record of what it reached for."""++ def __init__(self, *, running: bool) -> None:+ self.running = running+ self.filled: list[str] = []+ self.queried: list[str] = []+ self.clicked = 0+ self.keyboard = _FakeKeyboard(self)++ def evaluate(+ self,+ script,+ arg = None,+ ):+ if "isRunning" in script:+ return self.running+ if "composerText" in script:+ return ""+ if "assistantChars" in script:+ return 9_200+ return {}++ def fill(self, _selector: str, text: str) -> None:+ self.filled.append(text)++ def wait_for_timeout(self, _ms) -> None:+ return None++ def query_selector(self, selector: str):+ self.queried.append(selector)+ page = self++ class _Button:+ def click(self_inner) -> None:+ page.clicked += 1+ page.running = False++ return _Button() if "Stop generating" in selector else None+++def _stop_ctx(page: _FakePage, budget_ms: int = 3_000):+ """3,000 ms because that is the stop slot on the fast and quick films, and the smallest one+ any film gives this action. The budget decides whether the throwaway turn is affordable at+ all -- see `OWN_TURN_RESERVE_MS` -- so a figure no film uses would test a slot that does not+ exist. The truncation test below keeps a deliberately tiny one for its own reason."""++ from studiobench.runtime.types import ActionContext+ return ActionContext(+ page = page,+ cdp = None,+ cell = None,+ window = None,+ args = {},+ budget_ms = budget_ms,+ dom = None,+ log = lambda _m: None,+ )+++def test_stop_refuses_to_truncate_the_cell_s_own_reply():+ """REGRESSION, and the failure it pins is a SILENT one.++ `stop_generation` sends and stops a throwaway turn precisely so that it never truncates the+ reply the rest of the film measures. That guard was written as "if nothing is running, make+ something to stop", so the moment something WAS running the action fell through and clicked+ Stop on it. `--stream-tail-chars 96000` is the supported way to make that happen: the reply+ then streams for 291 s against a 243 s standard film, this slot opens at 28 s, and the reply+ the flag exists to lengthen is cut at about 9,200 characters. Every later action still runs+ against a settled thread, the row still says `ran: true`, and `--assert-liveness` -- which the+ flag's own help text sends the caller to -- still passes, so the reply-length axis reports a+ clean run having measured a reply a tenth of the requested size.+ """+ from studiobench.scene.actions import stop_generation++ page = _FakePage(running = True)+ # 200 ms: too small to hold the throwaway turn at all, so the drain wait is zero and the+ # refusal below is the one this test is about rather than the budget check beside it.+ result = stop_generation(_stop_ctx(page, budget_ms = 200))++ assert result.ran is False, "a stop that would truncate the measured reply must not run"+ assert "truncate" in (result.reason or "")+ assert page.clicked == 0, "the cell's own reply was stopped"+ assert page.queried == [], "the stop button was not even looked for"+ assert "one more" not in page.filled, "a second turn must not be started on top of a live one"+++def test_stop_still_sends_its_own_turn_when_nothing_is_running():+ """The default path, unchanged: with the pinned tail nothing is ever running at this slot."""+ from studiobench.scene.actions import stop_generation++ page = _FakePage(running = False)+ result = stop_generation(_stop_ctx(page))++ assert "one more" in page.filled, "stop must still get its own generation to stop"+ assert page.keyboard.pressed == ["Enter"]+ assert page.clicked == 1, "the throwaway turn is what gets stopped"+ assert result.ran is True+ assert result.expect["own_generation"] is Truediff --git a/tests/studio/studiobench/instruments/selfcheck.py b/tests/studio/studiobench/instruments/selfcheck.pyindex ed263a0c4b7..4a7b5aece84 100644--- a/tests/studio/studiobench/instruments/selfcheck.py+++ b/tests/studio/studiobench/instruments/selfcheck.py@@ -55,6 +55,17 @@ from ..scoring.schema import ExcludedCell, MeasureSTALL_TOLERANCE_MS = 20.0INJECTED_STALL_MS = 120.0+#: Milliseconds of main-thread time burned per SSE chunk when the streaming-cost injection is+#: armed. Sized against what it has to stand in for: preprocessLaTeX over a 96,000 character reply+#: is projected at 246 ms across a whole stream, so a per-chunk figure in the low single digits is+#: the same ORDER as the effect the metric is meant to resolve, not a boulder it cannot miss.+INJECTED_STREAM_COST_MS = 3.0+#: The share of injected cost `stream_cost` must read back. Not 1.0: the metric measures the task+#: chain from the chunk to the event loop draining, and a burn queued as a microtask lands inside+#: that chain but the chain also contains the app's own work, so recovery is bounded below by+#: attribution and above by nothing. Under-recovery is the failure that matters, because a metric+#: that recovers a quarter of a known cost will under-report an unknown one by the same factor.+MIN_STREAM_COST_RECOVERY = 0.70INJECTED_INPUT_DELAY_MS = 400.0MIN_INPUT_P95_SHIFT_MS = 350.0MIN_SCENE_CONTRAST_PCT = 20.0@@ -454,6 +465,102 @@ STALL_INJECT_JS = """}"""+#: Burns a known amount of main-thread time PER SSE CHUNK, inside the task chain that chunk+#: starts. This is the streaming analogue of STALL_INJECT_JS: a stall injected once tests whether+#: the frame recorder is watching the right window, and this tests whether the streaming-cost+#: accumulator integrates a cost spread thinly across a whole stream, which is the shape of every+#: effect it was built for and the shape a single-action metric cannot see.+#:+#: THE BURN IS QUEUED AS A MICROTASK, not run inline in the decode wrapper, and that is what makes+#: the check independent of wrapper order. `add_init_script` runs scripts in the order they were+#: added, and the instrument's own TextDecoder wrapper is installed by `Instrument.attach` after+#: the scripts assembled in __main__. Whichever wrapper ends up outermost, a microtask queued+#: during the decode runs after the current task's synchronous code and before the MessageChannel+#: macrotask that closes the measured chain -- so the burn is inside the chain either way. Burning+#: inline would land it before the accumulator timestamps the chunk under one ordering and after+#: it under the other, and the check would silently measure nothing.+STREAM_COST_INJECT_JS = """+(() => {+ if (window.__sbStreamCostInject) { return; }+ const burnMs = %(burn_ms)f;+ const S = { burnMs: burnMs, chunks: 0, burnedMs: 0 };+ window.__sbStreamCostInject = S;+ const nativeDecode = TextDecoder.prototype.decode;+ TextDecoder.prototype.decode = function (input, options) {+ const out = nativeDecode.call(this, input, options);+ if (typeof out === "string" && out.length > 0 && out.length <= 65536+ && out.indexOf("data:") >= 0) {+ S.chunks += 1;+ queueMicrotask(() => {+ const started = performance.now();+ while (performance.now() - started < burnMs) { /* spin */ }+ S.burnedMs += performance.now() - started;+ });+ }+ return out;+ };+})();+"""+++def stream_cost_injection_init_script(burn_ms: float = INJECTED_STREAM_COST_MS) -> str:+ return STREAM_COST_INJECT_JS % {"burn_ms": float(burn_ms)}+++def evaluate_stream_cost_recovery_gate(+ base_ms_per_kchar: float | None,+ injected_ms_per_kchar: float | None,+ injected_total_ms: float | None,+ streamed_chars: int | None,+ *,+ min_recovery: float = MIN_STREAM_COST_RECOVERY,+) -> Gate:+ """`stream_cost` must read back a cost this harness injected into the stream itself.++ A metric that cannot see a known cost cannot see an unknown one, and this is the only check+ that separates "the change did nothing" from "the metric is not watching". The RECOVERY+ FRACTION is the output that matters and it is reported whether or not the gate passes: a+ metric recovering 40% of what was injected is not broken, but every number it produces is+ four tenths of the truth and a reader has to be told the multiplier.+ """+ missing = [+ name+ for name, value in (+ ("the base rate", base_ms_per_kchar),+ ("the injected rate", injected_ms_per_kchar),+ ("the injected total", injected_total_ms),+ ("the streamed character count", streamed_chars),+ )+ if value is None+ ]+ if missing or not streamed_chars or not injected_total_ms:+ return Gate(+ name = "injected_stream_cost_recovered",+ passed = False,+ measured = Measure.failed(+ "fraction", "missing: " + ", ".join(missing or ["a non-zero denominator"])+ ),+ expected = f">= {min_recovery:.0%} of the injected cost",+ detail = (+ "the streaming-cost metric produced no reading on one side, so nothing can be "+ "said about whether it can see an injected cost"+ ),+ )+ observed_ms = (injected_ms_per_kchar - base_ms_per_kchar) * streamed_chars / 1000.0+ recovery = observed_ms / injected_total_ms+ return Gate(+ name = "injected_stream_cost_recovered",+ passed = recovery >= min_recovery,+ measured = Measure.read(round(recovery, 3), "fraction"),+ expected = f">= {min_recovery:.0%} of the injected cost",+ detail = (+ f"injected {injected_total_ms:.0f} ms across {streamed_chars:,} streamed characters, "+ f"read back {observed_ms:.0f} ms ({recovery:.0%})"+ + ("" if recovery >= min_recovery else "; the accumulator is under-attributing")+ ),+ )++#: Adds a fixed delay to every keydown before the app sees it, by installing a capturing listener#: that blocks. Installed pre-boot so it sits ahead of every app handler.INPUT_DELAY_INIT_JS = """diff --git a/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost.py b/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost.pynew file mode 100644index 00000000000..936bd0e4aef--- /dev/null+++ b/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost.py@@ -0,0 +1,487 @@+# 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 streaming-cost accumulator, on both sides of the page boundary.++WHY THE REAL JAVASCRIPT AND NOT A PYTHON PORT, same reason `test_studiobench_parity_digest.py`+gives: the file that ships is `instruments/streamcost.js`, and a re-implementation tested here+would pass forever while the shipped file drifted. So node runs the actual file against a shim of+the four globals it touches, and if node is missing the test SKIPS rather than passing on a+substitute.++The one thing that cannot be shimmed is the thing being tested: a real blocked main thread. The+stall below is a synchronous busy wait, so the 1 ms timer inside the instrument really is unable+to run for its duration, exactly as it would be during a long task in the app.+"""++from __future__ import annotations++import json+import shutil+import subprocess+import sys+import tempfile+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[3]))++from studiobench.instruments.streamcost import StreamCostInstrument # noqa: E402++STREAMCOST_JS = Path(__file__).resolve().parents[1] / "streamcost.js"++#: `IDLE_GAP_MS` in the instrument. A stall longer than this is the case that used to vanish.+IDLE_GAP_MS = 1500++HARNESS_JS = r"""+const fs = require("fs");+const src = fs.readFileSync(process.argv[2], "utf8");+const stallMs = Number(process.argv[3]);++const window = {};+const document = { querySelectorAll: () => [] };+(new Function("window", "document", src))(window, document);++// frames.js is what owns the clamp; only its shape matters here.+window.__sb.frames = { clamp: () => ({ clampMs: 1.0 }) };++const sc = window.__sb.streamcost;+sc.__markStreaming();++// A REAL block: synchronous, so the instrument's 1 ms timer cannot run for its duration and+// observes the whole stall as one gap once the thread is free again.+const started = performance.now();+while (performance.now() - started < stallMs) { /* spin */ }++// Let the timer catch up, then drain.+setTimeout(() => {+ console.log(JSON.stringify(sc.read(stallMs + 100)));+ // The instrument's 1 ms timer re-arms itself forever, exactly as it does in the page. Nothing+ // stops it, so the harness ends the process rather than waiting for an empty event loop.+ process.exit(0);+}, 60);+"""+++#: The same file, driven through the ordering that loses a burst: a window that closes while the+#: chain the last chunk started has not reached its macrotask yet. `readWhilePending` decides which+#: of the two orderings the harness produces, so the pinned case and its control differ by nothing+#: else.+PENDING_HARNESS_JS = r"""+const fs = require("fs");+const src = fs.readFileSync(process.argv[2], "utf8");+const burnMs = Number(process.argv[3]);+const readWhilePending = process.argv[4] === "pending";++const window = {};+const document = { querySelectorAll: () => [] };+(new Function("window", "document", src))(window, document);+window.__sb.frames = { clamp: () => ({ clampMs: 1.0 }) };+const sc = window.__sb.streamcost;++// ONE BURST AND ITS TASK CHAIN. `__markStreaming` is the decode; the spin after it is the parse,+// the delta accumulation and the render that the chain exists to measure.+const burst = () => {+ sc.__markStreaming();+ const started = performance.now();+ while (performance.now() - started < burnMs) { /* spin */ }+};++const finish = (first) => setTimeout(() => {+ // A SECOND WINDOW, opened and closed after the macrotask has certainly run. Whatever the burst+ // cost belongs to the first window; anything landing here is the leak.+ const second = sc.read(0);+ console.log(JSON.stringify({ first: first, second: second }));+ process.exit(0);+}, 60);++if (readWhilePending) {+ burst();+ // The window closes IN THE SAME TASK, so the MessageChannel message posted by the decode is+ // still queued.+ finish(sc.read(burnMs + 50));+} else {+ burst();+ // The ordinary ordering: the chain reaches its macrotask first and the window closes after it.+ setTimeout(() => finish(sc.read(burnMs + 50)), 30);+}+"""+++#: The same file again, driven through ONE `decode()` of a whole batched read. `payload` decides+#: what that read carries: a burst of the pacer's own frames larger than the decoder's scan bound,+#: the same burst small enough to sit under it, or a blob of the size that bound exists to keep out.+#: The burn after the decode stands in for the SSE parse, the delta accumulation and the render --+#: the task chain `delta_task_ms` is supposed to be charging.+BATCH_HARNESS_JS = r"""+const fs = require("fs");+const src = fs.readFileSync(process.argv[2], "utf8");+const mode = process.argv[3];+const burnMs = Number(process.argv[4]);++const window = {};+const document = { querySelectorAll: () => [] };+(new Function("window", "document", src))(window, document);+window.__sb.frames = { clamp: () => ({ clampMs: 1.0 }) };+const sc = window.__sb.streamcost;++// pacer.py's own framing: `data: ` + the chunk object + a blank line, carrying 64 characters at+// fast cadence. Built here rather than imported so the harness stays a single node process.+const frame = (i) =>+ "data: " ++ JSON.stringify({+ id: "chatcmpl-0123456789abcdef0123",+ object: "chat.completion.chunk",+ created: 1780000000,+ model: "studiobench-pacer",+ choices: [{ index: 0, delta: { content: String.fromCharCode(97 + (i % 26)).repeat(64) },+ finish_reason: null }],+ }) ++ "\n\n";++let payload = "";+if (mode === "blob") {+ // A bundle, a blob or a paste: over the bound and with no relay framing anywhere in it.+ payload = "z".repeat(100000);+} else {+ // A BATCH ABOVE THE BOUND. Everything the browser buffered while the main thread was stalled,+ // handed to the app as one read, exactly as chromium does after a stall past about two seconds.+ let i = 0;+ const want = mode === "batch-over" ? 65537 : 40000;+ while (payload.length < want) payload += frame(i++);+}++// THROUGH THE REAL HOOK. `TextDecoder.prototype.decode` is what the instrument wraps and what the+// app reaches with the bytes of one `reader.read()`, so the batch is decoded in a single call.+const decoded = new TextDecoder().decode(+ new Uint8Array(Buffer.from(payload, "utf8")), { stream: true }+);++// The chain that decode started, still on the same task.+const started = performance.now();+while (performance.now() - started < burnMs) { /* spin */ }++setTimeout(() => {+ console.log(JSON.stringify({+ payload_chars: payload.length,+ decoded_chars: decoded.length,+ read: sc.read(null),+ }));+ process.exit(0);+}, 60);+"""+++def _node() -> str:+ exe = shutil.which("node") or shutil.which("nodejs")+ if exe is None:+ pytest.skip(+ "node is not installed, so the shipped streamcost.js could not be evaluated; "+ "this is NOT MEASURED rather than passing"+ )+ return exe+++def drain_after_stall(stall_ms: float) -> dict:+ exe = _node()+ with tempfile.TemporaryDirectory() as tmp:+ harness = Path(tmp) / "harness.js"+ harness.write_text(HARNESS_JS, encoding = "utf-8")+ got = subprocess.run(+ [exe, str(harness), str(STREAMCOST_JS), str(stall_ms)],+ capture_output = True,+ text = True,+ timeout = 120,+ )+ if got.returncode != 0:+ raise AssertionError(f"the streamcost.js harness failed: {got.stderr.strip()[-800:]}")+ return json.loads(got.stdout)+++def burst_across_a_window_close(burn_ms: float, *, read_while_pending: bool) -> dict:+ exe = _node()+ with tempfile.TemporaryDirectory() as tmp:+ harness = Path(tmp) / "pending.js"+ harness.write_text(PENDING_HARNESS_JS, encoding = "utf-8")+ got = subprocess.run(+ [+ exe,+ str(harness),+ str(STREAMCOST_JS),+ str(burn_ms),+ "pending" if read_while_pending else "settled",+ ],+ capture_output = True,+ text = True,+ timeout = 120,+ )+ if got.returncode != 0:+ raise AssertionError(f"the streamcost.js harness failed: {got.stderr.strip()[-800:]}")+ return json.loads(got.stdout)+++def one_decoded_batch(mode: str, burn_ms: float) -> dict:+ exe = _node()+ with tempfile.TemporaryDirectory() as tmp:+ harness = Path(tmp) / "batch.js"+ harness.write_text(BATCH_HARNESS_JS, encoding = "utf-8")+ got = subprocess.run(+ [exe, str(harness), str(STREAMCOST_JS), mode, str(burn_ms)],+ capture_output = True,+ text = True,+ timeout = 120,+ )+ if got.returncode != 0:+ raise AssertionError(f"the streamcost.js harness failed: {got.stderr.strip()[-800:]}")+ return json.loads(got.stdout)+++#: The task chain one burst starts, in the harness above. Large enough that losing it is+#: unmistakable in the assertions and small enough that node's timers stay honest.+BURST_CHAIN_MS = 40.0+++def test_a_burst_still_in_flight_at_the_window_close_is_charged_to_that_window():+ """REGRESSION. `read()` snapshotted `deltaTaskMs` and then `reset()` zeroed it while the chain+ the last chunk started was still open, so the MessageChannel callback charged that burst to a+ fresh accumulator that nobody ever reads: `StreamCostInstrument.close` discards everything but+ `overhead_ms` from its tail `read(0)`, and `open()` resets before the next window in any case.+ The burst's characters stayed in the denominator and its targeted cost left the numerator.++ `delta_task_ms` is the TARGETED numerator -- the one quantity that separates stream cost from+ the action windows around it, and the one the `--inject-stream-cost-ms` recovery fraction is+ computed from -- so it may not lose a burst it counted.++ HOW OFTEN, MEASURED, because the answer is small and the reader should have it: driving the+ shipped file in real chromium against a real SSE response read through a fetch reader at field+ cadence, a driver-side `read()` found a chain still open 10 to 21 times in 2,600 to 5,500+ reads, or 0.4 to 0.65 per cent. A cell opens about eight windows over its streaming phase, so+ what this costs a real run is a fraction of one burst chain. It is pinned here rather than left+ because the file's own contract is that a burst is charged once, from the first chunk to the+ loop draining, and a burst that is charged to nothing breaks it in the direction that reads+ cheaper.++ The same-task close below is the deterministic way to put the accumulator in the state chromium+ reaches by racing; the invariant it pins is the production one.+ """+ out = burst_across_a_window_close(BURST_CHAIN_MS, read_while_pending = True)++ assert out["first"]["delta_task_ms"] >= BURST_CHAIN_MS * 0.9, (+ "the burst in flight when the window closed was dropped from its own window",+ out,+ )+ assert out["second"]["delta_task_ms"] < BURST_CHAIN_MS * 0.1, (+ "the burst was charged a second time to the window that followed",+ out,+ )+++def test_a_burst_whose_chain_has_already_closed_is_charged_once():+ """THE CONTROL, and it passes with or without the flush: the ordinary ordering, where the+ chain reaches its macrotask before the window closes, must keep charging exactly once."""++ out = burst_across_a_window_close(BURST_CHAIN_MS, read_while_pending = False)++ assert out["first"]["delta_task_ms"] >= BURST_CHAIN_MS * 0.9, out+ assert out["second"]["delta_task_ms"] < BURST_CHAIN_MS * 0.1, out+++#: `MAX_SSE_CHUNK_CHARS` in the instrument. A single decode above it is the case that used to be+#: discarded whole.+MAX_SSE_CHUNK_CHARS = 65536+++def test_a_batched_sse_read_above_the_decoder_scan_bound_is_still_detected():+ """REGRESSION. The detector read `out.length <= MAX_SSE_CHUNK_CHARS` and skipped anything+ longer, on the premise that a decode that large is not relay traffic.++ A read does not carry one cadence gap of the stream, it carries everything the browser buffered+ since the last one, so its size is the arrival rate times the stall in front of it. Measured+ against real chromium reading the real pacer through the app's own `getReader()` loop, the+ largest read of a stream is 32.5 characters per millisecond of stall at fast cadence: a 3,000 ms+ stall lands one well-formed 97,500 character read of 470 `data:` frames, and the guard dropped+ it entirely -- `sseChunks`, `sseBursts`, `lastSseAt` and the `deltaTaskMs` numerator all missed+ the largest burst of the stream, at the moment a stall makes it largest.+ """+ out = one_decoded_batch("batch-over", BURST_CHAIN_MS)++ assert out["decoded_chars"] > MAX_SSE_CHUNK_CHARS, out+ # The decode was seen either way; what used to be lost is everything downstream of it.+ assert out["read"]["decode_calls"] == 1, out+ assert out["read"]["sse_chunks"] == 1, out+ assert out["read"]["sse_bursts"] == 1, out+ assert out["read"]["streaming_observed"] is True, out+ # ONE chain for the batch, charged once: a burst delivered in one task is one task chain.+ assert out["read"]["delta_task_ms"] >= BURST_CHAIN_MS * 0.9, out+++def test_a_batched_sse_read_below_the_decoder_scan_bound_is_detected_too():+ """THE CONTROL, and it passes with or without the fix: the same batch, built to sit under the+ bound, is the path that always worked and may not be broken by widening the one above it."""++ out = one_decoded_batch("batch-under", BURST_CHAIN_MS)++ assert out["decoded_chars"] < MAX_SSE_CHUNK_CHARS, out+ assert out["read"]["sse_chunks"] == 1, out+ assert out["read"]["delta_task_ms"] >= BURST_CHAIN_MS * 0.9, out+++def test_a_decoded_blob_above_the_scan_bound_is_still_kept_out_of_the_detector():+ """THE OTHER CONTROL, and it also passes with or without the fix: the bound still has a job.++ A bundle, a blob or a paste reaches the same wrapper, and counting one as a stream would set+ `lastSseAt`, open a chain and charge that chain's cost to a window with no stream in it -- an+ error in the other direction, which the bound exists to prevent. Widening the guard from a+ rejection to a bounded scan may not turn it into no guard at all.+ """+ out = one_decoded_batch("blob", BURST_CHAIN_MS)++ assert out["decoded_chars"] > MAX_SSE_CHUNK_CHARS, out+ assert out["read"]["decode_calls"] == 1, out+ assert out["read"]["sse_chunks"] == 0, out+ assert out["read"]["streaming_observed"] is False, out+ assert out["read"]["delta_task_ms"] == 0, out+++def test_a_stall_longer_than_the_idle_gap_is_still_charged_to_the_stream():+ """The worst stall in a window is the one the timer sees last, and it must not be dropped.++ A stall that outlasts `IDLE_GAP_MS` is only observed after it has ended, and by then the last+ SSE chunk is older than the idle threshold. Deciding the interval's attribution from the state+ at its END therefore threw away the whole stall, so a streaming regression read CHEAPER once+ it crossed 1.5 s -- the metric moving the wrong way as the defect got worse.+ """+ stall_ms = IDLE_GAP_MS + 400+ out = drain_after_stall(stall_ms)+ assert out["streaming_observed"] is True+ # The stall began while the stream was in flight, so it belongs to the stream.+ assert out["streaming_ms"] >= stall_ms * 0.9, out+ assert out["stream_blocked_ms"] >= stall_ms * 0.9, out+++def test_a_stall_shorter_than_the_idle_gap_is_charged_too():+ """The case that always worked, kept so the fix above cannot be undone by loosening it."""+ stall_ms = 300+ out = drain_after_stall(stall_ms)+ assert out["streaming_ms"] >= stall_ms * 0.9, out+ assert out["stream_blocked_ms"] >= stall_ms * 0.9, out+++class _FakeCell:+ cell_id = "100K.base.rep0"+++def test_overhead_is_reported_per_cell_and_not_accumulated_across_them():+ """One instrument instance serves the whole session, and the rungs run in ascending order.++ An overhead accumulator that is never cleared reports cell k as the sum of cells 1..k, which+ climbs with the rung ladder however flat the instrument actually is. That is the exact shape+ `overhead_growth_with_length` exists to catch, manufactured by the instrument declaring it.+ """+ inst = StreamCostInstrument()++ inst.start_cell(_FakeCell())+ inst._overhead_ms += 40.0+ first = inst.end_cell(_FakeCell())+ assert first["overhead_ms"] == 40.0++ inst.start_cell(_FakeCell())+ inst._overhead_ms += 5.0+ second = inst.end_cell(_FakeCell())+ assert second["overhead_ms"] == 5.0, "the second cell must not carry the first cell's overhead"+++class _FakeWindow:+ duration_ms = 10_000.0+++class _FakeStreamCostPage:+ """The page-side accumulator, on exactly the contract `streamcost.js` implements.++ `read()` snapshots `overheadMs` into its result and THEN resets it; `replyChars()` adds the+ cost of its own `querySelectorAll` to whatever the accumulator currently holds; `reset()`+ zeroes it. Those three facts are the whole of the defect below, and re-stating them here rather+ than driving node keeps the test about the DRIVER's ordering, which is where the defect lives.+ """++ #: What one boundary scan costs. `querySelectorAll` collects its matches up front over the+ #: whole document, so this is the one part of the instrument that grows with the rung.+ SCAN_MS = 3.9++ def __init__(self) -> None:+ self.overhead_ms = 0.0+ self.scans = 0++ def evaluate(+ self,+ expr,+ arg = None,+ ):+ if "reset()" in expr:+ self.overhead_ms = 0.0+ return None+ if "replyChars" in expr:+ self.scans += 1+ self.overhead_ms += self.SCAN_MS+ return 1_000 * self.scans+ if "read(" in expr:+ snapshot = round(self.overhead_ms, 2)+ self.overhead_ms = 0.0+ return {"streaming_observed": True, "overhead_ms": snapshot}+ return None+++def test_the_close_side_reply_scan_is_counted_in_the_declared_overhead():+ """REGRESSION. Half of every window's boundary scans were missing from `overhead_ms`.++ `close()` calls `read(ms)` first, which snapshots the page's overhead total and then resets it,+ and only afterwards calls `replyChars(force)` -- the FORCED, whole-document scan that is the+ one part of this instrument whose cost tracks the rung. That scan accumulated into a fresh+ page-side total which the next `open()` began by resetting, so it was never read by anyone.++ The number this corrupts is the only evidence for the level 0 claim: `end_cell` declares it+ precisely so the claim is checkable from the payload rather than from a docstring, and it was+ reporting about half of the rung-dependent cost it exists to expose.+ """+ inst = StreamCostInstrument()+ page = _FakeStreamCostPage()+ # After `start_cell`, which re-reads the page from the context every cell.+ inst.start_cell(_FakeCell())+ inst.page = page+ for _ in range(3):+ inst.open(_FakeWindow())+ inst.close(_FakeWindow())++ assert page.scans == 6, "three windows means three open scans and three close scans"+ declared = inst.end_cell(_FakeCell())["overhead_ms"]+ assert declared == pytest.approx(6 * _FakeStreamCostPage.SCAN_MS, abs = 0.05), (+ "the close-side scans are missing from the declared overhead",+ declared,+ )+++def test_the_close_side_drain_does_not_disturb_the_window_s_own_reading():+ """The scan is harvested AFTER the window's numbers are taken, so it cannot move them."""+ inst = StreamCostInstrument()+ inst.start_cell(_FakeCell())+ inst.page = _FakeStreamCostPage()+ inst.open(_FakeWindow())+ out = inst.close(_FakeWindow())++ assert out["streaming_observed"] is True+ assert out["reply_chars_delta"] == 1_000+ # The window's own overhead figure is what `read()` returned; the close scan is reported+ # beside it rather than folded into it.+ assert out["overhead_ms"] == pytest.approx(_FakeStreamCostPage.SCAN_MS, abs = 0.05)+ assert out["close_scan_overhead_ms"] == pytest.approx(_FakeStreamCostPage.SCAN_MS, abs = 0.05)+++def test_a_half_open_window_does_not_leak_its_open_reading_into_the_next_cell():+ """`_chars_open` is per window; a cell that died between open and close must not seed the next+ cell's first window with a stale character count."""+ inst = StreamCostInstrument()+ inst.start_cell(_FakeCell())+ inst._chars_open = 12345+ inst.start_cell(_FakeCell())+ assert inst._chars_open is Nonediff --git a/tests/studio/studiobench/instruments/streamcost.js b/tests/studio/studiobench/instruments/streamcost.jsnew file mode 100644index 00000000000..1772a9f3b2b--- /dev/null+++ b/tests/studio/studiobench/instruments/streamcost.js@@ -0,0 +1,324 @@+// 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 streaming-phase cost accumulator. Installed as an init script before any app code runs.+//+// WHAT IS MISSING FROM THE HARNESS THAT THIS FILLS. `time_in_jank_pct`, `jank_index` and+// `max_frame_ms` do cover the stream -- `_frame_measures` pools every window whose kind is not+// `idle`, and the streaming windows are in that pool. What they cannot do is SEPARATE it. One+// 57.3 s film collapses eighteen action windows and the streaming stretch into a single number,+// and the action windows dominate it: measured on a 100K null control, `reasoning_toggle` alone+// contributes 2,865 ms of blocked time at 99.3% busy with a 1,866 ms worst frame, while the+// streaming stretch next to it runs at 3.6% busy. A change to the streaming path moves the second+// and is scored against the first.+//+// The window KIND cannot be used to make that separation, which is the trap this file exists past.+// `SceneRunner._gap_window` opens EVERY inter-slot gap as `kind = "stream"`, so on the standard+// film eighteen windows are labelled `stream:` and only the first four contain any streaming at+// all; `stream:drain` at the end of the cell is 7 ms of nothing, the stream having finished+// forty seconds earlier. The streaming phase is therefore detected here, from the SSE traffic+// itself, and not read off a label.+//+// THREE THINGS ARE ACCUMULATED, and they are different quantities on purpose:+//+// deltaTaskMs The main-thread time of the task chains that SSE chunks start. Measured from+// the first decode of a burst to the moment the event loop next reaches a+// macrotask, so it spans the SSE parse, the delta accumulation, the cumulative+// re-parse and React's own render and commit. This is the TARGETED numerator: it+// excludes the background churn -- highlighting, GC, the app's own timers -- that+// a whole-window blocked-time figure charges to the stream.+//+// blockedMs Blocked time, on exactly the discipline frames.js uses (a 1 ms timer, gap minus+// the calibrated clamp), but ACCUMULATED ONLY WHILE THE STREAM IS RUNNING. This+// is the BROAD numerator, and it is the honest one: it catches stream-driven cost+// that lands outside the delta's own task chain, which is most of the async+// highlighting work.+//+// streamingMs How much of the window the stream was actually running, so a window that is+// half stream and half idle is not read as a whole window of streaming.+//+// WHY THE END OF A TASK CHAIN IS TIMED WITH MessageChannel AND NOT setTimeout. A nested+// `setTimeout(fn, 0)` is clamped to 4 ms once the nesting level passes five, and a chunk arriving+// inside a fetch reader continuation inherits that nesting. That clamp would add a systematic+// ~4 ms to every chunk -- about 720 ms over a 13 s stream -- which is larger than most effects+// this is meant to resolve. A MessageChannel message is not clamped and runs as a macrotask+// immediately after the current task and its microtasks, which is exactly the boundary wanted.+//+// This is NOT the MessageChannel pattern frames.js bans. That one is a ping-pong LOOP that+// re-posts itself and ticks about 150,000 times a second, halving the frame rate before any app+// code runs. This posts once per SSE burst, about fourteen times a second at field cadence, and+// only while a stream is in flight.+//+// AND IT DOES NOT TOUCH requestAnimationFrame. frames.js owns the one rAF loop that counts+// frames. Nothing here schedules, wraps or counts a rAF, so the 888-fps inversion cannot recur+// through this file.++(() => {+ if (window.__sb && window.__sb.streamcost) return;+ window.__sb = window.__sb || {};++ // How long after the last SSE chunk the stream is still considered in flight. Field cadence is+ // 24 characters every 73 ms and the pacer is deficit-scheduled, so it bursts after a jam rather+ // than sleeping a gap per chunk; a jammed renderer can therefore go quiet for a while and then+ // receive a burst. 1500 ms is about twenty cadence gaps, long enough not to chop a jam in half+ // and short enough that the forty seconds of post-stream film are never counted as streaming.+ const IDLE_GAP_MS = 1500;++ // How much of a decoded chunk is scanned for the relay's framing. The substring search below is+ // the per-event work this file declares as O(1), and an unbounded scan over a bundle, a blob or+ // a paste would make it O(the page's whole TextDecoder traffic) instead.+ //+ // IT BOUNDS THE SCAN AND NOT THE PAYLOAD, and it used to bound the payload: the guard read+ // `out.length <= MAX_SSE_CHUNK_CHARS` and dropped anything longer, on the premise that a decode+ // this large is not relay traffic. That premise is false, and it is false in exactly the case+ // this instrument exists for. A read does not carry one cadence gap of the stream, it carries+ // everything the browser buffered since the last one, so the size of a read is the arrival rate+ // times the length of the stall in front of it. Measured against real chromium reading the real+ // pacer through the app's own `getReader()` loop, the largest read of a stream is 32.5+ // characters per millisecond of stall at fast cadence, dead linear over 500 to 3,000 ms: a+ // 2,000 ms stall lands a 65,000 character read and a 3,000 ms stall a 97,500 character one,+ // which the old guard discarded whole. That payload is well-formed SSE -- 470 `data:` frames of+ // the pacer's own framing -- and it is the single largest task chain of the stream, so the guard+ // took the worst burst out of `sseChunks`, `lastSseAt` and the `deltaTaskMs` numerator at the+ // one moment they matter most. Field cadence arrives at 2.97 characters per millisecond and+ // would need a 22 s stall, so this is reachable on `--cadence fast` and not on the default.+ //+ // HOW MUCH IT COST, and it is not a rounding error. The size of the loss is whatever the app+ // spends per streamed character, because what is dropped is one chain over a third of the reply.+ // Sweeping that rate against the real pacer, with the read loop otherwise identical:+ //+ // 0.0 ms per 1,000 characters 15.7 vs 15.4 ms -1.3%, which is the noise floor+ // 0.5 ms per 1,000 characters 55.7 vs 104.7 ms 46.8% of the numerator gone+ // 2.0 ms per 1,000 characters 154.0 vs 350.5 ms 56.1%+ // 5.0 ms per 1,000 characters 349.1 vs 835.5 ms 58.2%+ //+ // A harness that does no work per character loses nothing measurable, which is why this hid: it+ // needs an app that actually renders what it streams. It also gets WORSE as the app gets slower,+ // because a slower reader falls further behind and the batch it is then handed is bigger -- the+ // same shape as the timer attribution above, a build getting worse reading cheaper.+ //+ // Scanning a bounded head rather than rejecting keeps both of the things the cap was for. The+ // work stays bounded by a constant that does not grow with the payload or with the rung, and a+ // bundle still has to put `data:` in its first 65,536 characters to be mistaken for a stream --+ // while a real burst, which starts a frame every 279 characters, is found immediately. Measured+ // in v8: 0.04 us on an SSE batch and 0.68 us on a 2 MB blob with no frame in it, against 0.70 us+ // for the same scan left unbounded.+ const MAX_SSE_CHUNK_CHARS = 65536;++ const S = {+ sseChunks: 0,+ sseBursts: 0,+ deltaTaskMs: 0,+ blockedMs: 0,+ streamingMs: 0,+ lastSseAt: 0,+ // Wall time this file spent inside its own hooks, so the overhead it declares is measured+ // rather than asserted. An instrument that guesses its own cost cannot be checked against+ // the overhead_growth_with_length gate.+ overheadMs: 0,+ decodeCalls: 0,+ everStreamed: false,+ };++ const now = () => performance.now();+ // Takes the instant to judge, rather than reading the clock itself, so a caller that has to+ // attribute a whole INTERVAL can ask about the instant the interval began. See the timer below.+ const streamingAt = (t) => S.lastSseAt > 0 && t - S.lastSseAt < IDLE_GAP_MS;++ // ── the task-chain timer ──────────────────────────────────────────────────────────────────+ //+ // One pending measurement at a time. A burst of chunks delivered in one task must be charged+ // once, from the first chunk to the loop draining, not once per chunk: the pacer sends the+ // whole shortfall in a single burst when it has fallen behind, and charging per chunk would+ // multiply one task chain by the number of chunks that started it.+ let chainStart = null;+ // Close whatever chain is open and charge it to the accumulator it was opened against. Called+ // from the MessageChannel callback -- the ordinary end of a chain -- and from `read()`, which+ // is the case that used to lose it.+ //+ // WHY read() HAS TO DO THIS. `read()` arrives on its own task, from the driver, at a window+ // boundary; the message closing the last burst's chain is a task too, and the two are on+ // different task queues, so a window can close in the gap between a burst's decode and its+ // chain's macrotask. The snapshot then takes `deltaTaskMs` without that burst in it and+ // `reset()` zeroes the accumulator, so the callback charges the burst to a fresh one -- which+ // the tail `read(0)` in `StreamCostInstrument.close` discards, and which the next `open()`+ // resets in any case. The burst's characters are counted in the denominator and its targeted+ // cost is silently gone from the numerator. Reproduced against real chromium under a synthetic+ // stream of known per-burst cost: 0 to 2 of 200 bursts lost per run, one per window boundary at+ // most, and always downward.+ //+ // The stale message is harmless: it finds `chainStart === null` and returns. A burst that+ // starts after this posts a message of its own.+ const closeChain = () => {+ if (chainStart === null) return;+ S.deltaTaskMs += now() - chainStart;+ chainStart = null;+ };+ const chan = new MessageChannel();+ chan.port1.onmessage = closeChain;++ const noteSse = () => {+ S.sseChunks += 1;+ S.everStreamed = true;+ S.lastSseAt = now();+ if (chainStart === null) {+ chainStart = S.lastSseAt;+ S.sseBursts += 1;+ chan.port2.postMessage(0);+ }+ };++ // ── the SSE detector ──────────────────────────────────────────────────────────────────────+ //+ // The app reads the relay's response through its own TextDecoder, so decode() is the first+ // main-thread code that sees a chunk. Wrapping it costs one call per chunk and is O(1) in the+ // thread's size. This hook is the flat part of the instrument; the reply-length read below is+ // the part that is not, and its measured cost is recorded there rather than claimed away here.+ const nativeDecode = TextDecoder.prototype.decode;+ TextDecoder.prototype.decode = function (input, options) {+ const out = nativeDecode.call(this, input, options);+ const t = now();+ S.decodeCalls += 1;+ if (typeof out === "string" && out.length > 0) {+ // A chunk at or under the cap is its own head, so nothing is allocated on the ordinary path+ // and the ordinary path is unchanged. Over the cap, v8 slices a string by reference rather+ // than by copy, so the head costs no walk of the payload either.+ const head = out.length <= MAX_SSE_CHUNK_CHARS ? out : out.slice(0, MAX_SSE_CHUNK_CHARS);+ if (head.indexOf("data:") >= 0) noteSse();+ }+ S.overheadMs += now() - t;+ return out;+ };++ // ── blocked time while streaming ──────────────────────────────────────────────────────────+ //+ // The same 1 ms timer discipline as frames.js, and deliberately the same calibrated clamp:+ // blocked time is a SUBTRACTION against an idle floor, and two instruments subtracting two+ // different floors would report two different amounts of block for one page. The clamp is read+ // from frames.js rather than calibrated again here, so if frames.js could not establish one+ // this reports null with frames.js's own reason.+ let lastTick = now();+ const tick = () => {+ const t = now();+ const gap = t - lastTick;+ // Attributed by the state at the START of the interval, never at its end. A timer callback+ // cannot run while the main thread is blocked -- it is queued when the timer expires and+ // waits for the stack to empty -- so a stall is only ever observed once it is already over.+ // Reading `streaming()` here would therefore ask whether the stream is in flight NOW, after+ // the stall, and a stall longer than IDLE_GAP_MS answers no: the whole interval, which IS+ // the stall, would be dropped from both accumulators. That discards precisely the worst+ // stream-induced stalls, and it discards them at exactly the point where a regression grows+ // past 1.5 s, so a build getting worse would read cheaper. A negative difference (a chunk+ // that arrived DURING the interval) is below the threshold too, which is the overlap case.+ const wasStreaming = streamingAt(lastTick);+ lastTick = t;+ if (wasStreaming) {+ const f = window.__sb.frames;+ const clamp = f && f.clamp ? f.clamp().clampMs : null;+ S.streamingMs += gap;+ if (clamp !== null && clamp !== undefined) S.blockedMs += Math.max(0, gap - clamp);+ }+ setTimeout(tick, 1);+ };+ setTimeout(tick, 1);++ // Characters of the reply currently being streamed. The LAST assistant message only, not the+ // whole thread: at the 100K rung the thread holds about 190,000 assistant characters and+ // reading all of them costs real time on every window boundary, while the quantity wanted is+ // the growth of the one reply the pacer is feeding. Reading the last message alone is O(reply)+ // rather than O(thread), so this stays flat as the rung climbs.+ //+ // It is also the only reading that survives the end of the film. `thread_reopen` and+ // `delete_message` rebuild and then cut the thread, so a whole-thread character count jumps and+ // then falls for reasons that have nothing to do with streaming.+ // MEASURED, and it is not free. `querySelectorAll` is O(the whole DOM), not O(the reply), so+ // this is the one part of the instrument whose cost grows with the rung. Called at both ends of+ // every window it totalled 38.8 ms per cell at 10K and 289.6 ms at 100K -- about 3.9 ms per+ // call against 42,000 elements.+ //+ // Most of that was spent on windows with no stream in them. The standard film opens about+ // thirty-seven windows and only eight carry streaming, so the read is skipped once the stream+ // has been finished for longer than the idle gap. `null` is returned rather than a stale count,+ // and a window that then turns out to have carried traffic reports its growth as unmeasurable+ // with a reason instead of inventing a delta from a reading that was never taken.+ const replyChars = (force) => {+ if (!force && S.lastSseAt > 0 && now() - S.lastSseAt >= IDLE_GAP_MS) return null;+ const all = document.querySelectorAll('[data-role="assistant"]');+ if (all.length === 0) return null;+ const el = all[all.length - 1];+ return (el.textContent || "").length;+ };++ window.__sb.streamcost = {+ // Drain the window. `elapsedMs` is the DRIVER's measure, passed in for the same reason+ // frames.js takes it: the page cannot be trusted to read its own clock promptly in the very+ // windows this is measuring.+ read(elapsedMs) {+ const t = now();+ // BEFORE the snapshot, because a chain still in flight belongs to the window that started+ // it and `reset()` below is about to throw it away. See `closeChain`.+ closeChain();+ const f = window.__sb.frames;+ const clampInfo = f && f.clamp ? f.clamp() : { clampMs: null, reason: "frames.js absent" };+ const out = {+ sse_chunks: S.sseChunks,+ sse_chunks_attempted: true,+ sse_bursts: S.sseBursts,+ decode_calls: S.decodeCalls,+ // Never a bare zero: a window with no streaming in it says so with a flag, and the+ // scoring layer skips it rather than folding a zero cost into the numerator.+ streaming_observed: S.sseChunks > 0,+ streaming_ms: Math.round(S.streamingMs * 10) / 10,+ streaming_ms_attempted: true,+ delta_task_ms: Math.round(S.deltaTaskMs * 10) / 10,+ delta_task_ms_attempted: true,+ driver_elapsed_ms: elapsedMs === null || elapsedMs === undefined ? null : elapsedMs,+ clamp_ms: clampInfo.clampMs === null ? null : clampInfo.clampMs,+ };+ if (clampInfo.clampMs === null || clampInfo.clampMs === undefined) {+ // Blocked time is a subtraction against the idle floor. Without a floor there is no+ // subtraction to make, and reporting the raw lag instead would be a different quantity+ // wearing this one's name.+ out.stream_blocked_ms = null;+ out.stream_blocked_ms_reason =+ "no timer clamp was established, so there is no idle floor to subtract: " ++ (clampInfo.reason || "unknown");+ } else {+ out.stream_blocked_ms = Math.round(S.blockedMs * 10) / 10;+ out.stream_blocked_ms_attempted = true;+ }+ S.overheadMs += now() - t;+ out.overhead_ms = Math.round(S.overheadMs * 100) / 100;+ out.overhead_attempted = true;+ this.reset();+ return out;+ },++ // Read the streamed reply's length WITHOUT draining anything. Called at window open and+ // window close, so the denominator is the growth across the window.+ // `force` is passed at window CLOSE when the window turned out to carry traffic, so a+ // window whose open-read was skipped is not silently given a null close-read as well.+ replyChars(force) {+ const t = now();+ const n = replyChars(Boolean(force));+ S.overheadMs += now() - t;+ return n;+ },++ reset() {+ S.sseChunks = 0;+ S.sseBursts = 0;+ S.deltaTaskMs = 0;+ S.blockedMs = 0;+ S.streamingMs = 0;+ S.decodeCalls = 0;+ S.overheadMs = 0;+ },++ // For the selftest: force the detector into the streaming state without a real stream, so a+ // synthetic injection can be measured on exactly the accumulators a real stream uses.+ __markStreaming() {+ noteSse();+ },+ };+})();diff --git a/tests/studio/studiobench/instruments/streamcost.py b/tests/studio/studiobench/instruments/streamcost.pynew file mode 100644index 00000000000..cd362f25e2a--- /dev/null+++ b/tests/studio/studiobench/instruments/streamcost.py@@ -0,0 +1,164 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Registers `stream_cost`: the streaming-phase cost accumulator.++WHAT THIS ADDS THAT THE HARNESS DID NOT HAVE. Not an integral -- `time_in_jank_pct`, `jank_index`+and `max_frame_ms` already integrate, and `_frame_measures` already pools the streaming windows+into them. What it adds is SEPARATION and a DENOMINATOR:++ SEPARATION. The three frame metrics collapse one film into one number per cell, and the action+ windows dominate it. Measured on a 100K null control, `action:reasoning_toggle` contributes+ 2,865 ms of blocked time at 99.3% busy with a 1,866 ms worst frame, and `action:select_all_copy`+ 3,017 ms at 97.7% with a 2,102 ms worst frame, while the streaming stretch beside them runs at+ 3.6% busy with a 100 ms worst frame. A change to the streaming path moves the second and is+ scored against the first.++ The window KIND cannot make that separation, and this is the trap worth naming because the name+ actively misleads. `SceneRunner._gap_window` opens EVERY inter-slot gap as `kind = "stream"`. On+ the standard film that is eighteen windows called `stream:gapN` of which only the first four+ contain any streaming, plus `stream:drain`, which on a measured 100K cell was 7 ms long because+ the stream had finished forty seconds earlier. Filtering on `kind == "stream"` selects mostly+ post-stream idle. The phase is therefore detected from the SSE traffic itself.++ A DENOMINATOR. Cost per streamed character, not per cell. This is what makes two rungs+ comparable on cost per unit of work, which is the claim the whole effort is testing: that a+ thread twice as long costs more to stream one character into. Worth being honest about what it+ buys and where: WITHIN one rung the denominator is very nearly a constant, because the pacer is+ deficit-scheduled and the tail is pinned, and measured across twelve null-control pairs at 100K+ the streamed character count varies by 0.0%. It earns its keep ACROSS rungs, where it is the+ only way to compare 10K with 100K at all.++WHY IT IS LEVEL 0. Its per-event work is O(1) and its per-window work is O(the reply being+streamed), never O(the thread). The two hooks are a `TextDecoder.prototype.decode` wrapper that+runs about fourteen times a second at field cadence, and a 1 ms timer of exactly the kind+frames.js already runs and documents as costing nothing at about 150 ticks a second. Nothing here+is proportional to the rung, which is what `overhead_growth_with_length` exists to catch, and+`overhead_ms` is measured inside the hooks rather than asserted so the gate has something real to+read.+"""++from __future__ import annotations++from typing import Optional++from ..runtime.types import Cell, Window+from . import register_instrument+from .pagejs import _PageInstrument+++@register_instrument(name = "stream_cost", level = 0)+def _stream_cost():+ return StreamCostInstrument()+++class StreamCostInstrument(_PageInstrument):+ """Per-window streaming cost, and the streamed characters to divide it by."""++ name = "stream_cost"+ level = 0+ script_name = "streamcost.js"++ def __init__(self) -> None:+ super().__init__()+ self._chars_open: Optional[int] = None+ self._overhead_ms = 0.0++ def start_cell(self, cell: Cell) -> None:+ # PER CELL, like every other instrument that declares overhead (heap.py, tracing.py,+ # coverage.py all zero theirs here). One instrument instance serves the whole session, so+ # an accumulator carried across cells reports cell k's overhead as the sum of cells 1..k.+ # The rung ladder is run in ascending order, so that sum climbs with the rung and+ # `overhead_growth_with_length` -- the gate whose entire job is to catch an instrument+ # whose cost tracks the treatment -- would read manufactured growth off a flat instrument.+ super().start_cell(cell)+ self._overhead_ms = 0.0+ self._chars_open = None++ def open(self, window: Window) -> None:+ # Drain first, so the window starts from zero even if the previous close did not run+ # (an instrument that raised is disabled for the rest of the cell, and the accumulator+ # would otherwise carry that cell's remaining traffic into this window).+ self._eval("() => window.__sb.streamcost && window.__sb.streamcost.reset()")+ self._chars_open = self._eval(+ "() => window.__sb.streamcost && window.__sb.streamcost.replyChars()"+ )++ def close(self, window: Window) -> Optional[dict]:+ if self.unavailable:+ return {"unavailable": self.unavailable, "stream_cost_attempted": False}+ elapsed_ms = window.duration_ms+ out = self._eval("(ms) => window.__sb.streamcost.read(ms)", elapsed_ms)+ if out is None:+ return {+ "unavailable": self.unavailable or "the page did not answer",+ "stream_cost_attempted": False,+ }+ # Forced when the window carried SSE traffic: the open-read is skipped on windows long+ # past the stream, and a window that unexpectedly streamed must not be scored from a+ # half-taken pair.+ saw_traffic = bool(out.get("streaming_observed"))+ chars_close = self._eval("(f) => window.__sb.streamcost.replyChars(f)", saw_traffic)+ out["stream_cost_attempted"] = True+ out["reply_chars_open"] = self._chars_open+ out["reply_chars_close"] = chars_close++ if self._chars_open is None or chars_close is None:+ out["reply_chars_delta"] = None+ out["reply_chars_delta_reason"] = (+ "the reply's length was not read at one end of this window, either because no "+ "assistant message was on screen or because the stream had been finished longer "+ "than the idle gap when the window opened"+ )+ elif chars_close < self._chars_open:+ # THE REPLY WAS REPLACED, NOT EXTENDED. `send_turn` starts a new assistant message and+ # `thread_reopen` rebuilds the thread, so the last message can be SHORTER at the close+ # of a window than it was at the open. That is not negative streaming; it is a+ # different message. A signed delta here would subtract from the denominator and+ # inflate the cost per character without anything in the payload saying why.+ out["reply_chars_delta"] = None+ out["reply_chars_delta_reason"] = (+ f"the last assistant message shrank from {self._chars_open} to {chars_close} "+ "characters, so it is a different message and its growth is not measurable here"+ )+ else:+ out["reply_chars_delta"] = chars_close - self._chars_open+ out["reply_chars_delta_attempted"] = True++ self._overhead_ms += float(out.get("overhead_ms") or 0.0)++ # THE CLOSE-SIDE SCAN IS NOT FREE AND WAS NOT COUNTED. `read()` snapshots `overhead_ms`+ # into its result and then calls `reset()`, so the `replyChars()` above -- which at close+ # is FORCED whenever the window carried traffic, and is the `querySelectorAll` that is+ # O(the whole DOM) rather than O(the reply) -- accumulated into a page-side total that+ # nothing ever read: the next `open()` begins by resetting it. Exactly half of every+ # window's boundary scans were therefore missing from the one number whose job is to make+ # the level 0 claim checkable from the payload rather than from a docstring, and the half+ # that was missing is the rung-dependent half. Drained here, after the scan, rather than+ # by reordering the pair: the close read needs `force`, and `force` is+ # `streaming_observed`, which only `read()` can answer. Nothing else is lost by the second+ # drain -- every other accumulator it clears was already snapshotted above, and `open()`+ # clears them again before the next window.+ tail = self._eval("() => window.__sb.streamcost.read(0)")+ close_scan_ms = float(tail.get("overhead_ms") or 0.0) if isinstance(tail, dict) else 0.0+ self._overhead_ms += close_scan_ms+ out["close_scan_overhead_ms"] = round(close_scan_ms, 2)++ self._chars_open = None+ return out++ def end_cell(self, cell: Cell) -> Optional[dict]:+ # Declared even though level 0 is not obliged to: the whole argument for calling this+ # level 0 is that its cost does not grow with the rung, and a claim like that should be+ # checkable from the payload rather than from this docstring.+ return {+ "overhead_ms": round(self._overhead_ms, 2),+ "overhead_attempted": True,+ "overhead_note": (+ "measured inside the decode hook and at the window boundaries, not estimated. "+ "O(1) per SSE chunk, but the reply-length read is a querySelectorAll and so is "+ "O(the whole DOM): 38.8 ms per cell at 10K and 289.6 ms at 100K before the "+ "post-stream windows were skipped. It is identical on both arms of an A/B and "+ "cancels in a paired ratio; it does NOT cancel across rungs"+ ),+ }diff --git a/tests/studio/studiobench/report/selftest/test_studiobench_cli_contracts.py b/tests/studio/studiobench/report/selftest/test_studiobench_cli_contracts.pyindex faa599899d9..d9ed9cdde7f 100644--- a/tests/studio/studiobench/report/selftest/test_studiobench_cli_contracts.py+++ b/tests/studio/studiobench/report/selftest/test_studiobench_cli_contracts.py@@ -39,6 +39,7 @@ from studiobench.__main__ import ( # noqa: E402recorded_ladder,side_home,side_specs,+ stream_cost_injection_problem,)@@ -94,6 +95,172 @@ def test_one_attached_studio_driven_twice_is_a_null_control():assert is_null_control(sides) is True+# ── the stream-cost injection needs two origins ─────────────────────────────────────────────+#+# The injection is a CONTEXT init script gated on `window.location.origin`, and both arms are+# driven by one browser context and one page, so the origin is the only thing that can tell them+# apart. Two arms on one origin therefore BOTH burn the injected cost, the difference between them+# is zero, and `evaluate_stream_cost_recovery_gate` -- which reads back+# `(injected_rate - base_rate) * chars` -- reports a recovery of nothing and blames the+# accumulator. The one flag whose job is to separate "the change did nothing" from "the metric is+# not watching" would answer the second when the truth is neither.+#+# One attached Studio driven twice is not a mistake in general: it is a null control this tool+# detects on purpose, pinned by the test directly above. It is only fatal with the injection on.+++def _inject_args(attach, attach_b, *extra):+ return parse_args(["--attach", attach, "--ab", "main", "--attach-b", attach_b, *extra])+++def test_injecting_stream_cost_into_two_arms_on_one_origin_is_refused():+ """REGRESSION. `--attach U --attach-b U` is the cheapest null control there is -- one Studio,+ no installs -- and it is the obvious place to check that the metric can see a known cost."""++ args = _inject_args(+ "http://127.0.0.1:5401", "http://127.0.0.1:5401", "--inject-stream-cost-ms", "3"+ )+ problem = stream_cost_injection_problem(side_specs(args, "main"), args.inject_stream_cost_ms)++ assert problem is not None+ assert "127.0.0.1:5401" in problem+ assert "origin" in problem+++def test_a_trailing_slash_does_not_make_one_origin_into_two():+ """`--attach-b http://host:5401/` and `--attach http://host:5401` are the same server. The+ acquisition loop strips the slash before it ever reaches `origin_scoped`, so a check that did+ not would pass this and inject into both arms anyway."""++ args = _inject_args(+ "http://127.0.0.1:5401", "http://127.0.0.1:5401/", "--inject-stream-cost-ms", "3"+ )+ assert stream_cost_injection_problem(side_specs(args, "main"), args.inject_stream_cost_ms)+++ ("attach", "attach_b"),+ [+ # The port a scheme does not spell out. Chromium reports `http://studio` for both.+ ("http://studio", "http://studio:80"),+ ("http://studio:80", "http://studio"),+ ("https://studio.example.com", "https://studio.example.com:443"),+ # Case. The URL standard lower-cases the scheme and the host; a string compare does not.+ ("http://studio", "http://STUDIO"),+ ("http://studio", "HTTP://studio"),+ # A path is not part of an origin.+ ("http://studio", "http://studio/app"),+ ],+)+def test_one_origin_spelled_two_ways_is_still_one_origin(attach, attach_b):+ """REGRESSION. `origin_scoped` compares against `window.location.origin`, which is the URL+ standard's canonical origin and not the URL as typed, so the refusal has to compare the same+ thing or it refuses a different question from the one that matters.++ Measured in chromium against real documents: `http://studio:80`, `http://STUDIO`,+ `HTTP://studio` and `http://studio/app` all report an origin of `http://studio`, and the+ shipped `origin_scoped` predicate built from any of those four ran on NONE of them. So the pair+ below is one server under two names and the run goes wrong whichever way round it is spelled --+ the treatment's injection gated on the dead spelling burns on neither arm, or the base's is the+ dead one and the treatment's matches every document and both arms burn. Either way the+ difference between the arms is zero and `evaluate_stream_cost_recovery_gate` reports a working+ metric as under-attributing, which is the exact verdict this refusal exists to prevent."""++ args = _inject_args(attach, attach_b, "--inject-stream-cost-ms", "3")+ problem = stream_cost_injection_problem(side_specs(args, "main"), args.inject_stream_cost_ms)++ assert problem is not None, f"{attach} and {attach_b} are one origin"+ assert "origin" in problem+ # And it says so in terms the caller can act on, because the two URLs they typed do differ.+ assert attach in problem and attach_b in problem+++def test_the_predicate_and_the_refusal_read_the_same_origin():+ """The two halves of this guard are in different files and only agree by construction. If+ `origin_scoped` gated on the URL as typed while `arm_origins` canonicalised, a pair that got+ past the refusal could still be gated onto a document that does not exist."""++ from studiobench.__main__ import arm_origins+ from studiobench.runtime.ab import origin_scoped++ args = _inject_args("http://studio:80", "https://other.example.com:443")+ for spec, origin in zip(side_specs(args, "main"), arm_origins(side_specs(args, "main"))):+ assert f'"{origin}"' in origin_scoped(spec[2], "doThing();")+++def test_localhost_and_the_loopback_address_are_two_origins():+ """THE CONTROL THAT THE CANONICALISATION MUST NOT SWALLOW. `http://localhost:8000` and+ `http://127.0.0.1:8000` reach the same server and are two ORIGINS to a browser -- chromium+ reports each as itself -- so localStorage, the seed and the injection are all separate between+ them. Folding them together would refuse a pair of arms the injection works perfectly well+ against."""++ args = _inject_args(+ "http://localhost:8000", "http://127.0.0.1:8000", "--inject-stream-cost-ms", "3"+ )+ assert (+ stream_cost_injection_problem(side_specs(args, "main"), args.inject_stream_cost_ms) is None+ )+++def test_an_attached_side_and_a_self_installed_one_on_the_same_port_are_refused():+ """The mixed case. A side this run installs is launched on `--port` and serves at+ `http://127.0.0.1:{port}`, so an `--attach` URL naming that port is the same origin twice+ without either flag looking like it."""++ args = parse_args(+ [+ "--attach",+ "http://127.0.0.1:5400",+ "--ab",+ "main",+ "--attach-b",+ "http://127.0.0.1:5400",+ "--port",+ "5399",+ "--inject-stream-cost-ms",+ "3",+ ]+ )+ assert stream_cost_injection_problem(side_specs(args, "main"), args.inject_stream_cost_ms)+++# ── the controls: the refusal may not swallow a run that is fine ────────────────────────────+++def test_two_origins_may_inject():+ args = _inject_args(+ "http://127.0.0.1:5401", "http://127.0.0.1:5402", "--inject-stream-cost-ms", "3"+ )+ assert (+ stream_cost_injection_problem(side_specs(args, "main"), args.inject_stream_cost_ms) is None+ )+++def test_a_self_installed_pair_may_inject():+ """`--branch main --ab main` installs the same ref twice and launches the copies on `--port`+ and `--port + 1`, so their origins differ by construction. This is the null control the+ injection is most likely to be run against and it must keep working."""++ args = parse_args(["--branch", "main", "--ab", "main", "--inject-stream-cost-ms", "3"])+ assert (+ stream_cost_injection_problem(side_specs(args, "main"), args.inject_stream_cost_ms) is None+ )+++def test_one_origin_without_the_injection_is_still_allowed():+ """THE CONTROL THAT MATTERS MOST. One attached Studio driven twice is a null control, and+ refusing it outright would remove the calibration run this tool exists to support."""++ args = _inject_args("http://127.0.0.1:5401", "http://127.0.0.1:5401")+ assert stream_cost_injection_problem(side_specs(args, "main"), None) is None+++def test_a_single_side_is_never_refused():+ args = parse_args(["--branch", "main", "--inject-stream-cost-ms", "3"])+ assert stream_cost_injection_problem(side_specs(args, None), 3.0) is None++def test_one_attached_studio_driven_twice_under_two_labels_is_still_a_null_control():"""`--attach U --attach-b U --branch main --ab fix`: one server, two names it cannot check.diff --git a/tests/studio/studiobench/runtime/ab.py b/tests/studio/studiobench/runtime/ab.pyindex c2e905233b1..482a50e00b7 100644--- a/tests/studio/studiobench/runtime/ab.py+++ b/tests/studio/studiobench/runtime/ab.py@@ -43,6 +43,53 @@ class Target:owns_studio: bool = False+#: The port a scheme does not spell out. `window.location.origin` omits it, so an attach URL that+#: writes it is the same origin under a different name.+DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443}+++def browser_origin(url: str) -> str:+ """The ORIGIN a browser computes for `url`, spelled the way `window.location.origin` spells it.++ THE ONLY THING THAT DISCRIMINATES THE TWO ARMS. Both are driven by one browser context and one+ page, so `origin_scoped`'s `window.location.origin !== <url>` is the whole of the gate, and the+ right-hand side of that comparison has to be what the browser will actually produce rather than+ what the caller typed. Measured in chromium against real documents:+ `http://studio:80` and `HTTP://STUDIO` and `http://studio/app` all report an origin of+ `http://studio`, so every one of those spellings gates a script onto a document that does not+ exist. The failure is silent in both directions -- the base's seed then runs on the treatment's+ documents as well, and the treatment's injection runs on neither -- and it reaches+ `evaluate_stream_cost_recovery_gate` as a recovery of zero blamed on the accumulator.++ WHAT IS NOT FOLDED TOGETHER: `localhost` and `127.0.0.1`. A browser treats those as two+ origins, chromium reports them as two (`http://localhost:8000` stays `http://localhost:8000`),+ and a check that called them one would refuse a perfectly good pair of arms. Only the four+ canonicalisations the URL standard itself performs are applied: the scheme and host are+ lower-cased, a port the scheme implies is dropped, and the path, query, fragment and any+ userinfo are discarded.++ A string this cannot parse as an absolute URL is returned trailing-slash-stripped, which is+ what the acquisition loop does with `--attach` anyway: an unparseable URL is the caller's+ problem to see at `wait_for_healthz`, not a reason for this to guess.+ """+ from urllib.parse import urlsplit++ try:+ split = urlsplit(url.strip())+ host, port = split.hostname, split.port+ except ValueError:+ return url.rstrip("/")+ scheme = split.scheme.lower()+ if not scheme or not host:+ return url.rstrip("/")+ host = host.lower()+ if ":" in host: # IPv6, which serialises with its brackets+ host = f"[{host}]"+ if port is None or port == DEFAULT_PORTS.get(scheme):+ return f"{scheme}://{host}"+ return f"{scheme}://{host}:{port}"++def origin_scoped(base_url: str, script: str) -> str:"""Run `script` only on its own Studio's origin.@@ -51,11 +98,14 @@ def origin_scoped(base_url: str, script: str) -> str:last writes the other build's auth token into this build's storage, and the failure shows upmuch later as a logged-out SPA or a provider that renders as "No longer offered" -- neither ofwhich points back here.++ Gated on the CANONICAL origin rather than on the URL as typed: see `browser_origin` for the+ spellings that otherwise gate a script onto a document no browser will ever produce."""import json as _jsonreturn ("(() => { if (window.location.origin !== "- + _json.dumps(base_url.rstrip("/"))+ + _json.dumps(browser_origin(base_url))+ ") return; "+ script+ " })();"diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab.pyindex ab13a1f4ad3..cf9cb49e337 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab.py@@ -13,10 +13,13 @@ from __future__ import annotationsimport sysfrom pathlib import Path+import pytest+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))from studiobench.runtime.ab import ( # noqa: E402Target,+ browser_origin,interleave,order_is_balanced,origin_scoped,@@ -81,3 +84,49 @@ def test_origin_gate_names_the_exact_origin_and_strips_the_slash():assert '"http://127.0.0.1:5401"' in scriptassert "doThing();" in scriptassert "return" in script+++# ── the gate compares against an ORIGIN, so it has to be given one ──────────────────────────+#+# `window.location.origin` is the URL standard's canonical origin, not the URL the caller typed.+# Every expectation below was read out of chromium, by navigating a real document to the spelling+# on the left and asking the page for `window.location.origin`.+++ ("spelled", "origin"),+ [+ ("http://127.0.0.1:5401", "http://127.0.0.1:5401"),+ ("http://127.0.0.1:5401/", "http://127.0.0.1:5401"),+ # A port the scheme implies is not part of the origin.+ ("http://studio:80", "http://studio"),+ ("http://studio", "http://studio"),+ ("https://studio.example.com:443", "https://studio.example.com"),+ ("https://studio.example.com", "https://studio.example.com"),+ # A port the scheme does NOT imply is.+ ("https://studio.example.com:8443", "https://studio.example.com:8443"),+ ("http://studio:443", "http://studio:443"),+ # The scheme and host are lower-cased; nothing else is touched.+ ("HTTP://STUDIO", "http://studio"),+ # Path, query, fragment and userinfo are not part of an origin.+ ("http://studio/app?x=1#y", "http://studio"),+ ("http://user:secret@studio", "http://studio"),+ # IPv6 keeps its brackets.+ ("http://[::1]:5401", "http://[::1]:5401"),+ # THE ONE THAT MUST NOT BE FOLDED: a browser treats these as two origins and so does this.+ ("http://localhost:8000", "http://localhost:8000"),+ ("http://127.0.0.1:8000", "http://127.0.0.1:8000"),+ ],+)+def test_browser_origin_is_what_the_browser_reports(spelled, origin):+ assert browser_origin(spelled) == origin+ assert f'"{origin}"' in origin_scoped(spelled, "doThing();")++[email protected]("junk", ["", "studio:5401", "not a url", "/relative/path"])+def test_a_string_that_is_not_an_absolute_url_is_left_alone(junk):+ """Guessing at a malformed `--attach` would turn a typo into a silently different origin. The+ caller sees it at `wait_for_healthz` instead, which is where a URL that reaches nothing+ belongs."""++ assert browser_origin(junk) == junk.rstrip("/")diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.pyindex f32e5d08030..ff8056e342f 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.py@@ -403,6 +403,29 @@ def test_a_session_that_died_before_its_first_cell_declares_no_mode(tmp_path):)+# ── the two fixture axes ────────────────────────────────────────────────────────────────────+#+# `--stream-tail-chars` and `--corpus-dollars` change what the last turn STREAMS, and neither of+# them moves `corpus_hash`, which covers the frozen units on disk and the generator's parameters.+# Nor does either move a `cell_id`. They are on `IDENTITY_AXES` for the same reason the tier is:+# without that, a resume under a changed fixture skips cells measured against a different film and+# the payload silently becomes one ladder built from two.+++def _fixture_payload(tmp_path, name, session, **fixture):+ paths = Paths.under(tmp_path / name)+ _record(+ paths,+ session,+ [+ _run_meta("standard", "main", ["10K"], **fixture),+ _cell("r10K.A0.rep0", 10_000),+ _keystroke("r10K.A0.rep0", 55.0),+ ],+ )+ return paths++def _one_engine_rung(tmp_path,engine,@@ -428,6 +451,96 @@ def _one_engine_rung(return paths+def _resume_args(*flags):+ return parse_args(["--tier", "standard", "--branch", "main", "--resume", *flags])+++def test_resuming_under_a_changed_stream_tail_is_refused(tmp_path):+ paths = _fixture_payload(tmp_path, "tail", "sess-1", stream_tail_chars = 24_000)++ with pytest.raises(SystemExit) as excinfo:+ prepare_payload(+ paths,+ requested_identity(_resume_args("--stream-tail-chars", "96000"), None, CORPUS),+ resume = True,+ log = lambda *_a: None,+ )++ message = str(excinfo.value)+ assert "stream_tail_chars" in message+ assert "24000" in message and "96000" in message+++def test_resuming_under_a_changed_dollar_setting_is_refused(tmp_path):+ """Both directions. Dropping the flag on the resume is the likelier of the two."""++ on = _fixture_payload(tmp_path, "on", "sess-on", corpus_dollars = True)+ with pytest.raises(SystemExit) as excinfo:+ prepare_payload(+ on,+ requested_identity(_resume_args(), None, CORPUS),+ resume = True,+ log = lambda *_a: None,+ )+ assert "corpus_dollars" in str(excinfo.value)++ off = _fixture_payload(tmp_path, "off", "sess-off", corpus_dollars = False)+ with pytest.raises(SystemExit) as excinfo:+ prepare_payload(+ off,+ requested_identity(_resume_args("--corpus-dollars"), None, CORPUS),+ resume = True,+ log = lambda *_a: None,+ )+ assert "corpus_dollars" in str(excinfo.value)+++def test_a_payload_that_already_holds_two_fixtures_is_refused_either_way(tmp_path):+ """Two sessions, two films, one file: whichever of them you ask for, the other one is still+ in there and its cells would still be skipped."""++ paths = _fixture_payload(tmp_path, "mixed", "sess-1", stream_tail_chars = 6_000)+ _record(+ paths,+ "sess-2",+ [+ _run_meta("standard", "main", ["10K"], stream_tail_chars = 96_000),+ _cell("r100K.A0.rep0", 100_000),+ ],+ )++ for asked in ("6000", "96000"):+ with pytest.raises(SystemExit) as excinfo:+ prepare_payload(+ paths,+ requested_identity(_resume_args("--stream-tail-chars", asked), None, CORPUS),+ resume = True,+ log = lambda *_a: None,+ )+ assert "stream_tail_chars" in str(excinfo.value)+++# ── the controls: neither axis may swallow a resume that is legitimate ───────────────────────+++def test_an_unchanged_fixture_resumes_and_returns_its_completed_cells(tmp_path):+ paths = _fixture_payload(+ tmp_path, "same", "sess-1", stream_tail_chars = 24_000, corpus_dollars = True+ )+ args = _resume_args("--stream-tail-chars", "24000", "--corpus-dollars")++ assert (+ prepare_payload(+ paths, requested_identity(args, None, CORPUS), resume = True, log = lambda *_a: None+ )+ is None+ )+ assert _resume_set(paths) == {"r10K.A0.rep0"}+++# ── the browser engine that rendered every number ────────────────────────++def test_resuming_under_a_different_browser_engine_is_refused(tmp_path):"""The engine RENDERED every number in the payload, and the cell id does not name it.@@ -493,6 +606,118 @@ def test_the_same_engine_still_resumes(tmp_path):assert _resume_set(paths) == {"r1K.A0.rep0"}+def test_a_payload_from_before_the_fixture_axes_existed_resumes_exactly_as_it_did(tmp_path):+ """No `stream_tail_chars` and no `corpus_dollars` key at all, which is every payload written+ before this branch. Resumed UNDER THE DEFAULTS it is asking for the film it already ran, so it+ resumes and its completed cells are skipped, exactly as they were before either flag existed.++ The other half of that reading -- a resume that does NOT use the defaults -- is the test below.+ """++ paths = _fixture_payload(tmp_path, "old", "sess-old")+ assert "stream_tail_chars" not in paths.payload_jsonl.read_text(encoding = "utf-8")++ assert (+ prepare_payload(+ paths,+ requested_identity(_resume_args(), None, CORPUS),+ resume = True,+ log = lambda *_a: None,+ )+ is None+ )+ assert _resume_set(paths) == {"r10K.A0.rep0"}+++def test_a_payload_from_before_the_fixture_axes_is_refused_under_a_non_default_fixture(tmp_path):+ """REGRESSION. Absence PROVES the default here, and skipping the axis threw that proof away.++ An axis a payload never declared is normally skipped: it declined to say, so there is nothing+ to disagree with. These two axes arrived WITH the flags that set them, so a payload written+ before them could not have run under anything but `stream_tail_chars = None` and+ `corpus_dollars = False`. Skipping them accepted `--resume --stream-tail-chars 24000` against+ such a payload, skipped every cell it had completed, and recorded the remaining cells under a+ different streamed fixture beneath the same cell ids -- the mixed ladder the refusal exists to+ prevent, arrived at through the one door left open.+ """++ for name, flags in (+ ("tail", ["--stream-tail-chars", "24000"]),+ ("dollars", ["--corpus-dollars"]),+ ):+ paths = _fixture_payload(tmp_path, f"legacy-{name}", "sess-old")+ with pytest.raises(SystemExit) as excinfo:+ prepare_payload(+ paths,+ requested_identity(_resume_args(*flags), None, CORPUS),+ resume = True,+ log = lambda *_a: None,+ )++ message = str(excinfo.value)+ assert ("stream_tail_chars" if "--stream-tail-chars" in flags else "corpus_dollars") in (+ message+ )+ # The refusal has to say WHY an axis the payload never mentions is a difference, or the+ # reader's next move is to go looking for a key that was never going to be there.+ assert "predates this axis" in message+++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."""++ paths = Paths.under(tmp_path / "quiet")+ _record(+ paths,+ "sess-quiet",+ [+ {+ "row_type": "run_meta",+ "tier": "standard",+ "tool_version": "0.0.9",+ "corpus_hash": CORPUS,+ "studio_ref": "main",+ "bundle": {"production": True},+ "platform": {"system": "Linux"},+ "started_at": "2026-01-01T00:00:00",+ "stream_tail_chars": 24_000,+ "corpus_dollars": True,+ },+ _cell("r10K.A0.rep0", 10_000),+ ],+ )+ args = _resume_args("--stream-tail-chars", "24000", "--corpus-dollars", "--cadence", "fast")++ assert (+ prepare_payload(+ paths, requested_identity(args, None, CORPUS), resume = True, log = lambda *_a: None+ )+ is None+ )+++def test_a_dead_cell_is_still_re_run_and_a_missing_payload_is_still_empty(tmp_path):+ """The refusal decides WHETHER to resume; this is what a resume then skips. A cell that died+ is re-run, because its failure may have been the machine and not the build."""++ paths = Paths.under(tmp_path / "died")+ _record(+ paths,+ "sess-1",+ [+ _run_meta("standard", "main", ["10K"], stream_tail_chars = None),+ {**_cell("r10K.A0.rep0", 10_000), "completed": False, "fidelity": "died"},+ ],+ )+ assert _resume_set(paths) == set()+ assert _resume_set(Paths.under(tmp_path / "nothing-here")) == set()+++# ── the engine controls ───────────────────────────────────────────────────++def test_a_payload_that_never_recorded_an_engine_still_resumes(tmp_path):"""The legacy control for this axis, and the one for a session that never got a browser up.@@ -628,6 +853,129 @@ def test_the_readme_sequence_no_longer_scores_two_runs_as_one_ladder(tmp_path):assert payload["header"]["studio_ref"] == "main"+# ── the injection axis ──────────────────────────────────────────────────────────────────────+#+# `--inject-stream-cost-ms` burns a known amount of main-thread time per SSE chunk on the TREATMENT+# arm, so a treatment cell recorded with it is not the same reading as one recorded without it --+# and `cell_id` carries the rung, the arm and the repetition and nothing that could tell. It is on+# `IDENTITY_AXES` for the same reason the two fixture axes above are, and for a larger perturbation+# than either of them makes.+++def _injected_payload(tmp_path, name, session, **fixture):+ paths = Paths.under(tmp_path / name)+ _record(+ paths,+ session,+ [+ _run_meta("standard", "main", ["10K"], **fixture),+ _cell("r10K.base.rep0", 10_000, arm = "base"),+ _cell("r10K.treatment.rep0", 10_000, arm = "treatment"),+ ],+ )+ return paths+++def _ab_resume_args(*flags):+ return parse_args(+ ["--tier", "standard", "--branch", "main", "--ab", "main", "--resume", *flags]+ )+++def test_resuming_a_finished_uninjected_run_with_the_injection_on_is_refused(tmp_path):+ """REGRESSION, and the expensive half of it.++ Every pair in this payload is complete, so `skippable_cells` skips all of them, `rows` comes+ back empty with `resumed` non-zero and `completion_exit_code` returns 0. The run pays for two+ installs, measures nothing, and the recovery gate is then answered out of cells that were never+ injected -- a calibration reporting that the metric cannot see a cost nobody put there.+ """++ paths = _injected_payload(tmp_path, "clean", "sess-1")++ with pytest.raises(SystemExit) as excinfo:+ prepare_payload(+ paths,+ requested_identity(_ab_resume_args("--inject-stream-cost-ms", "3"), "main", CORPUS),+ resume = True,+ log = lambda *_a: None,+ )++ message = str(excinfo.value)+ assert "inject_stream_cost_ms" in message+ assert "3.0" in message+++def test_resuming_an_injected_run_without_the_injection_is_refused(tmp_path):+ """The other direction, and the likelier one: an injected A/B dies part way up the ladder and+ the retry is typed without the flag. The rungs already done stay injected, the rungs still to+ come are not, and the ladder the recovery fraction is computed from is half of each."""++ paths = _injected_payload(tmp_path, "injected", "sess-1", inject_stream_cost_ms = 3.0)++ with pytest.raises(SystemExit) as excinfo:+ prepare_payload(+ paths,+ requested_identity(_ab_resume_args(), "main", CORPUS),+ resume = True,+ log = lambda *_a: None,+ )+ assert "inject_stream_cost_ms" in str(excinfo.value)+++def test_resuming_under_a_changed_injection_amount_is_refused(tmp_path):+ """The amount is the measurement. A ladder half of which burned 3 ms per chunk and half 40 ms+ has no recovery fraction at all."""++ paths = _injected_payload(tmp_path, "amount", "sess-1", inject_stream_cost_ms = 3.0)++ with pytest.raises(SystemExit) as excinfo:+ prepare_payload(+ paths,+ requested_identity(_ab_resume_args("--inject-stream-cost-ms", "40"), "main", CORPUS),+ resume = True,+ log = lambda *_a: None,+ )+ assert "inject_stream_cost_ms" in str(excinfo.value)+++def test_a_payload_from_before_the_injection_flag_resumes_under_the_default(tmp_path):+ """THE CONTROL, and the one `HISTORICAL_DEFAULTS` exists for. A payload written before the flag+ could not have been injected, so absence reads as off and an ordinary resume still works."""++ paths = _injected_payload(tmp_path, "old", "sess-old")+ assert "inject_stream_cost_ms" not in paths.payload_jsonl.read_text(encoding = "utf-8")++ assert (+ prepare_payload(+ paths,+ requested_identity(_ab_resume_args(), "main", CORPUS),+ resume = True,+ log = lambda *_a: None,+ )+ is None+ )+ assert _resume_set(paths) == {"r10K.base.rep0", "r10K.treatment.rep0"}+++def test_an_unchanged_injection_resumes(tmp_path):+ """THE SECOND CONTROL. An injected run that died is meant to be resumable AS an injected run;+ a refusal on every value would make the axis useless rather than safe."""++ paths = _injected_payload(tmp_path, "same", "sess-1", inject_stream_cost_ms = 3.0)++ assert (+ prepare_payload(+ paths,+ requested_identity(_ab_resume_args("--inject-stream-cost-ms", "3"), "main", CORPUS),+ resume = True,+ log = lambda *_a: None,+ )+ is None+ )+ assert _resume_set(paths) == {"r10K.base.rep0", "r10K.treatment.rep0"}++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 Nonediff --git a/tests/studio/studiobench/runtime/session.py b/tests/studio/studiobench/runtime/session.pyindex b7a27341c25..b3f0b840478 100644--- a/tests/studio/studiobench/runtime/session.py+++ b/tests/studio/studiobench/runtime/session.py@@ -803,6 +803,8 @@ def build_cells(auth: Optional[StudioAuth] = None,model_id: str = "",log: Callable[[str], None] = lambda _m: None,+ stream_tail_chars: Optional[int] = None,+ corpus_dollars: bool = False,) -> list[tuple[Cell, RungPlan]]:"""The ladder's cells, sized by the MEASURED ratio unless a caller names one.@@ -822,7 +824,17 @@ def build_cells(}out: list[tuple[Cell, RungPlan]] = []for rung in rungs:- plan = plan_rung(corpus, rung, ratio["chars_per_token"])+ # The ladder is sized by `ratio`, not by the raw `chars_per_token` argument: the argument+ # may be None, meaning "measure it", and the measured value is what every cell's `meta`+ # reports. Passing the argument straight through here would size the rungs from a number+ # the payload does not carry.+ plan = plan_rung(+ corpus,+ rung,+ ratio["chars_per_token"],+ stream_tail_chars = stream_tail_chars,+ dollars = corpus_dollars,+ )for rep in range(reps):cell = Cell(cell_id = make_cell_id(rung, "A0", rep),diff --git a/tests/studio/studiobench/runtime/types.py b/tests/studio/studiobench/runtime/types.pyindex d650d72317a..63759ccef74 100644--- a/tests/studio/studiobench/runtime/types.py+++ b/tests/studio/studiobench/runtime/types.py@@ -115,7 +115,10 @@ def make_cell_id(rung: str, arm: str, rep: int) -> str:# ── the window ──────────────────────────────────────────────────────-WINDOW_KINDS = frozenset({"action", "stream", "idle", "settle", "teardown"})+#: `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"})@dataclassdiff --git a/tests/studio/studiobench/scene/actions.py b/tests/studio/studiobench/scene/actions.pyindex 28c96b916a9..52c22b48f5f 100644--- a/tests/studio/studiobench/scene/actions.py+++ b/tests/studio/studiobench/scene/actions.py@@ -419,6 +419,119 @@ def reasoning_toggle(ctx: ActionContext) -> ActionResult:# ── 5. stop generation ──────────────────────────────────────────────+#: What `stop_generation`'s throwaway turn costs in FIXED waits once it starts, on any machine: 80+#: ms for the composer to take the text, 600 ms to let the new turn get going so stop is measured+#: against a live stream rather than a starting one, 400 ms for the chunks already in flight to+#: land, and 200 ms for the cleanup delete to settle. Polling for the turn to start and for the+#: stream to stop is on top of it, so this is a floor.+#:+#: RESERVED OUT OF THE DRAIN WAIT rather than spent past the deadline. The drain wait below is+#: bounded by the slot's remaining budget, so a reply that finishes at the last moment of the slot+#: used to leave nothing at all for the 1.28 s that follows. `stop_generation` closes 300 ms before+#: `scroll_after` opens on the fast film and 500 ms before it on the quick one, and the runner is+#: sequential -- every slot has an absolute start, but nothing enters it until the previous action+#: returns. So the overrun came out of `scroll_after`'s own 1,200 ms window on the fast film and+#: recorded `slot_missed` there, whose reason blames the machine for reaching the slot late when+#: what happened is that this action was still cleaning up its scaffolding.+#:+#: SPLIT, because the two halves are reserved at different moments. The 80 ms that settles the fill+#: is spent BEFORE the turn is sent, so it is already gone by the time the turn-start wait is+#: bounded and a bound that subtracts the whole figure charges it twice.+OWN_TURN_FIXED_AFTER_SEND_MS = 600 + 400 + 200+OWN_TURN_FIXED_MS = 80 + OWN_TURN_FIXED_AFTER_SEND_MS++#: What the SAME throwaway turn costs BEYOND those sleeps: two polls and the driver round trips+#: underneath them, neither of which is free.+#:+#: MEASURED, because the first version of this reserve was not. It was sized from a page shim whose+#: `evaluate` is a Python call and whose clock only moves when `wait_for_timeout` is called, so the+#: waits it recorded were `[100 x29, 80, 600, 400, 200]` and the two polls cost nothing. Driving+#: the same shipped action against real chromium and a real clock, with a page standing in for the+#: five calls it makes, the stretch after the drain costs:+#:+#: a page that answers instantly 1,394 - 1,451 ms (13 - 17% over the fixed 1,280)+#: 120 ms to start, 90 ms to stop, 60 ms+#: to delete -- an unremarkable local app 1,723 - 1,938 ms (35 - 51% over)+#:+#: The gap is nine to thirteen CDP round trips (43 - 130 ms of pure driver time), the 50 ms+#: granularity of both poll loops, and the app's own latency in answering them. Against a 1,280 ms+#: reserve that put the action 506 - 516 ms past the end of its slot on the fast and quick films,+#: whose gaps before `scroll_after` opens are 300 ms and 500 ms, so `scroll_after` recorded+#: `slot_missed` and its reason blamed the machine.+#:+#: 700 ms covers the measured 443 - 658 ms with margin and still leaves every film a real drain+#: wait: the smallest stop slot is 3,000 ms, which keeps 1,020 ms of waiting after the reserve,+#: and the worst-case drain overhang the fast film has to absorb is 400 ms.+#:+#: SPLIT AT THE MOMENT THE TURN STARTS, because that is where the wait below is bounded and a total+#: is not a bound. The stop-settle poll, the cleanup delete's own round trips and the driver calls+#: between them are ALL still ahead at that point, and a bound that reserves only the fixed sleeps+#: leaves the action exactly `OWN_TURN_FIXED_MS` for a stretch that costs more than that. Measured+#: against real chromium on the same page as the totals above, with the turn starting on the last+#: millisecond the bound allows and the fast film's 3,000 ms stop slot:+#:+#: a page that answers instantly 60 ms after the sleeps slot + 0.0 s+#: 90 ms to stop, 60 ms to delete 227 ms after the sleeps slot + 0.15 s+#: 200 ms to stop, 150 ms to delete 424 ms after the sleeps slot + 0.34 s+#:+#: The fast film leaves 300 ms between this slot's deadline and `scroll_after`, so the last row+#: overran into `scroll_after`'s own window and was recorded there as `slot_missed` -- the same+#: symptom, one action later, that the reserve above was written to remove. 500 ms covers the+#: measured 60 - 424 ms; the 200 ms left over is the start poll's own share, which is what the+#: turn-start wait is allowed to spend.+OWN_TURN_STOP_POLL_MS = 500+OWN_TURN_START_POLL_MS = 200+OWN_TURN_POLL_MS = OWN_TURN_START_POLL_MS + OWN_TURN_STOP_POLL_MS++#: What the throwaway turn needs in the slot, in total.+#:+#: RESERVED OUT OF THE DRAIN WAIT rather than spent past the deadline. The drain wait below is+#: bounded by the slot's remaining budget, so a reply that finishes at the last moment of the slot+#: used to leave nothing at all for the ~1.7 s that follows. `stop_generation` closes 300 ms before+#: `scroll_after` opens on the fast film and 500 ms before it on the quick one, and the runner is+#: sequential -- every slot has an absolute start, but nothing enters it until the previous action+#: returns. So the overrun came out of `scroll_after`'s own 1,200 ms window on the fast film and+#: recorded `slot_missed` there, whose reason blames the machine for reaching the slot late when+#: what happened is that this action was still cleaning up its scaffolding.+#:+#: A RESERVE IS NOT ENOUGH ON ITS OWN, which is why `stop_generation` also re-reads the clock+#: before it commits. The drain loop tests its deadline at the TOP, so one iteration -- a 100 ms+#: wait plus a round trip -- lands past it, and no constant chosen here can pay for time that has+#: already been spent. The reserve decides how much of the slot the drain may have; the check+#: decides whether what is actually left is enough to start a turn that cannot be abandoned once+#: it is running.+OWN_TURN_RESERVE_MS = OWN_TURN_FIXED_MS + OWN_TURN_POLL_MS++#: How long to wait for the throwaway turn to start, in total. The wait for a turn this action will+#: still MEASURE is bounded by the slot on top of this -- 8 s is 2.7x the whole budget of the fast+#: film's stop slot, so a turn that was slow to start used to overrun by seconds whatever had been+#: reserved for it -- but the turn does not stop existing when the slot runs out.+#:+#: ENTER IS PRESSED BEFORE THIS WAIT, which is what an earlier version of this comment had wrong+#: when it called cutting the wait short free. Something IS committed by then: the send is+#: accepted, the user turn is in the thread, and the reply starts whenever the relay gets round to+#: it. Returning at the slot bound left exactly the scaffolding the paragraph below refuses to+#: leave -- measured in chromium on a page that took 1,800 ms to start against the fast film's+#: 3,000 ms slot, the action returned `not_run` after 1,759 ms and the thread it handed on had two+#: extra messages in it and a live stream running through the next action's window.+#:+#: So the slot bounds how long the turn is WORTH MEASURING, and this bounds how long it is worth+#: waiting for so it can be taken back: `_reclaim_pending_turn` polls on to this deadline, stops+#: the turn if it ever becomes stoppable and deletes it, then reports `not_run`. The total spent+#: waiting for a start is therefore what it was before the slot bound existed, and the slot bound+#: still does its job on every run where the turn arrives.+#:+#: The stop-settle poll and `STOP_CLEANUP_JS` are deliberately NOT bounded by the slot at all: once+#: Enter is pressed the turn has to be stopped and removed or the thread every later action+#: measures keeps the scaffolding, and a settle poll cut short would report a stop that worked as+#: `still_running`.+TURN_START_TIMEOUT_MS = 8000++#: The composer text the throwaway turn is sent with. Read back as well as written: a composer that+#: still holds it is a send the app REFUSED, and that is the one case on the timeout path where+#: nothing was committed and there is nothing to take back.+OWN_TURN_TEXT = "one more"+#: Remove the throwaway turn `stop_generation` created, so the thread it leaves behind is the#: thread it found. Deletes the assistant turn and then the user turn that prompted it, in that#: order, because deleting the user message first can take the reply with it and leave the count@@ -453,6 +566,104 @@ async (timeoutMs) => {"""+def _own_turn_was_accepted(ctx: ActionContext, messages_before: Any) -> bool:+ """Did Enter actually SEND the throwaway turn?++ Two signals, either of which is enough, because they become true at different moments and the+ question is asked at whichever one the timeout landed on. The composer clears on send, so text+ still in it is a refusal -- `queueDisabled` turns Send into Queue whenever something is already+ running, and a Queue press leaves the box alone. The thread grows on send too, and it can grow+ before the composer's own re-render lands.++ ASKED IN THE CONSERVATIVE DIRECTION: anything that is not clearly a refusal counts as accepted,+ including a page call that threw, because the cost of treating a refusal as a send is a wait+ this action was going to spend anyway and the cost of the reverse is a live turn left in the+ thread.+ """+ if _ev(ctx, "() => window.__sb.dom.composerText()") != OWN_TURN_TEXT:+ return True+ after = _ev(ctx, "() => window.__sb.dom.messageCount()")+ return not (+ isinstance(messages_before, int) and isinstance(after, int) and after <= messages_before+ )+++def _reclaim_pending_turn(+ ctx: ActionContext, messages_before: Any, reason: str, deadline: float+) -> ActionResult:+ """Take back the throwaway turn Enter has ALREADY submitted, then report `not_run`.++ THE SLOT RAN OUT, THE TURN DID NOT. `stop_generation` presses Enter and then waits for the+ reply to start, and that wait is bounded by the slot -- but returning at the bound abandons a+ turn the app has accepted. It starts a second or two later, streams through the windows the+ next actions are being timed in, and leaves a user message and an assistant message in the+ thread that the rest of the film, the final census and the seeded-versus-streamed comparison+ all then measure. That is the same scaffolding `STOP_CLEANUP_JS` exists to remove, arrived at+ by giving up rather than by finishing.++ SO THE WAIT IS SPLIT RATHER THAN SHORTENED. Up to the slot's bound the turn is still worth+ measuring; past it, up to `deadline`, it is only worth catching, and this polls on for it,+ stops it and deletes it. Nothing here is bounded by the slot, for the reason the stop-settle+ poll is not either: an overrun costs the next action's window, and a turn left generating costs+ every window after that plus the census.++ DELETES ONLY WHAT IT ADDED. `STOP_CLEANUP_JS` removes the LAST assistant message, so running it+ when the send was refused or when the app never rendered the turn would take a seeded reply out+ of the thread and every count after this point would be wrong in the other direction. The+ message count is read before Enter and again here, and the delete runs only if the thread grew.+ """+ if not _own_turn_was_accepted(ctx, messages_before):+ return not_run(f"{reason}, and the composer still held it, so nothing was sent")++ running = _ev(ctx, "() => window.__sb.dom.isRunning()")+ while running is not True and time.monotonic() < deadline:+ ctx.page.wait_for_timeout(50)+ running = _ev(ctx, "() => window.__sb.dom.isRunning()")++ stopped = False+ if running is True:+ button = ctx.page.query_selector('button[aria-label="Stop generating"]')+ if button is not None:+ button.click()+ settle_deadline = time.monotonic() + SETTLE_TIMEOUT_MS / 1000.0+ while time.monotonic() < settle_deadline:+ if not _ev(ctx, "() => window.__sb.dom.isRunning()"):+ stopped = True+ break+ ctx.page.wait_for_timeout(50)+ # The chunks already in flight, as on the measured path.+ ctx.page.wait_for_timeout(400)++ messages_after = _ev(ctx, "() => window.__sb.dom.messageCount()")+ grew = (+ isinstance(messages_before, int)+ and isinstance(messages_after, int)+ and messages_after > messages_before+ )+ removed = _ev(ctx, STOP_CLEANUP_JS, SETTLE_TIMEOUT_MS) if grew else None+ if removed is not None:+ ctx.page.wait_for_timeout(200)++ # BOTH HALVES, REPORTED SEPARATELY. A turn that was deleted but never stopped and one that was+ # stopped but not deleted leave the film in different states, and a row that says only "cleaned+ # up" cannot be read in the light of either.+ if running is not True:+ state = f"never started within the {TURN_START_TIMEOUT_MS}ms it was worth waiting for"+ elif stopped:+ state = "was stopped"+ else:+ state = f"could not be stopped within {SETTLE_TIMEOUT_MS}ms"+ if removed is None:+ cleaned = "left nothing in the thread to remove"+ elif removed.get("removed"):+ cleaned = "was deleted from the thread"+ else:+ cleaned = f"is still in the thread ({removed.get('reason')})"+ return not_run(+ f"{reason}. Nothing was measured; the turn it had already sent {state} and {cleaned}"+ )++@register_action(name = "stop_generation", default_budget_ms = 8000)def stop_generation(ctx: ActionContext) -> ActionResult:"""Press stop mid-stream and time until the run is really over.@@ -462,6 +673,14 @@ def stop_generation(ctx: ActionContext) -> ActionResult:Queue control at the same position with the same class. Pressing it queues a message and thestream carries on, and the action reports a fast, precise, entirely wrong number."""+ # THE SLOT, ON THE CLOCK THE ACTION ITSELF RUNS ON. Everything below that is bounded is+ # bounded against this rather than against a constant, because a budget spent is not a budget+ # available: `ctx.budget_ms` is what the slot HAD when the runner entered it.+ slot_deadline = time.monotonic() + ctx.budget_ms / 1000.0++ def remaining_ms() -> float:+ return (slot_deadline - time.monotonic()) * 1000.0+text = _ev(ctx, "() => window.__sb.dom.composerText()")if text:ctx.page.fill('textarea[aria-label="Message input"]', "")@@ -478,23 +697,105 @@ def stop_generation(ctx: ActionContext) -> ActionResult:# Sending its own short turn keeps the measured reply intact and means the action has# something to stop at EVERY rung, instead of reporting `not_run` at the small ones where the# main stream is already over by the time the slot opens.- own_generation = False- if not _ev(ctx, "() => window.__sb.dom.isRunning()"):- ctx.page.fill('textarea[aria-label="Message input"]', "one more")- ctx.page.wait_for_timeout(80)- ctx.page.keyboard.press("Enter")- own_generation = True- deadline = time.monotonic() + 8.0- while time.monotonic() < deadline:- if _ev(ctx, "() => window.__sb.dom.isRunning()"):+ #+ # THE GUARD BELOW IS THE OTHER HALF OF THAT, and without it the paragraph above only held for+ # the default fixture. The own-turn path was entered only when `isRunning()` was FALSE, so the+ # moment anything WAS running this action fell straight through and clicked Stop on it -- the+ # exact behaviour the paragraph above says was removed. The supported way to make that happen+ # is `--stream-tail-chars`, whose entire purpose is a long opening reply: at 96,000 characters+ # the reply streams for 291 s at field cadence against a 243 s standard film, so this slot+ # opens at 28 s with the opening turn still in flight and kills it at about 9,200 characters.+ # The reply-length axis the flag exists to provide is then never exercised, every later action+ # still runs against a settled thread, `ran` is still true, and `--assert-liveness` -- which+ # the flag's own help text sends the caller to -- still passes. A silently truncated fixture+ # reported as a clean run is the most expensive failure shape this harness has.+ #+ # So the reply is given the rest of this slot's budget LESS what the throwaway turn then costs+ # (`OWN_TURN_RESERVE_MS`) to finish on its own, which is all a marginally slow drain needs (the+ # fast film opens this slot 0.4 s after the worst-case drain on the ladder, and 1.0 s of the+ # fast film's 3 s budget is still left over for it). If it has not finished by then, NOTHING IS+ # STOPPED and the row says why. An honest `not_run` costs a column; stopping the reply costs+ # the whole cell, and spending the rest of the slot draining and THEN starting a turn of our+ # own costs the next slot. With the default tail nothing is ever running when this slot opens+ # -- the packing test in fixture/selftest holds every film to that -- so this path is+ # unreachable on an unmodified run and the behaviour there is exactly what it was.+ if _ev(ctx, "() => window.__sb.dom.isRunning()"):+ drain_ms = max(0.0, ctx.budget_ms - OWN_TURN_RESERVE_MS)+ settle_deadline = time.monotonic() + drain_ms / 1000.0+ running: Any = True+ while time.monotonic() < settle_deadline:+ ctx.page.wait_for_timeout(100)+ running = _ev(ctx, "() => window.__sb.dom.isRunning()")+ if not running:break- ctx.page.wait_for_timeout(50)- else:- return not_run("nothing was generating and a new turn did not start within 8s")- if not _ev(ctx, "() => window.__sb.dom.isRunning()"):- return not_run("nothing was generating and a new turn did not start within 8s")- # Let it get going, so stop is measured against a live stream rather than a starting one.- ctx.page.wait_for_timeout(600)+ if running:+ return not_run(+ "the cell's own reply was still streaming when this slot opened and had not "+ f"drained {drain_ms:.0f}ms later -- this slot's remaining {ctx.budget_ms}ms less "+ f"the {OWN_TURN_RESERVE_MS}ms it then takes to start, stop and remove a turn of "+ "our own. Stopping it would permanently truncate the reply the rest of the film "+ "and the final census measure, so nothing was stopped. Lower --stream-tail-chars "+ "or move this slot past the drain"+ )+ # AND THE RESERVE IS CHECKED AGAINST THE CLOCK, not assumed off the budget. The loop above+ # tests `settle_deadline` at the top, so the iteration that finds the reply drained has+ # already spent a 100 ms wait and a round trip past it; a drain that lands in the last+ # iteration therefore leaves LESS than the reserve however the reserve is sized. Starting+ # the turn anyway is the same overrun by a smaller amount, and the turn cannot be+ # abandoned halfway -- once Enter is pressed the thread has to be stopped and cleaned up+ # or every later action measures the scaffolding.+ if remaining_ms() < OWN_TURN_RESERVE_MS:+ return not_run(+ "the cell's own reply drained with only "+ f"{max(0.0, remaining_ms()):.0f}ms left of this slot's {ctx.budget_ms}ms, and "+ f"starting, stopping and removing a turn of our own takes about "+ f"{OWN_TURN_RESERVE_MS}ms. Running it here would finish inside the next slot and "+ "record a missed slot against it, so nothing was stopped. Lower "+ "--stream-tail-chars or move this slot past the drain"+ )++ # READ BEFORE ENTER, because it is the only way to tell the turn this action added from the+ # thread it was handed. `_reclaim_pending_turn` deletes only if this number grew.+ messages_before = _ev(ctx, "() => window.__sb.dom.messageCount()")+ ctx.page.fill('textarea[aria-label="Message input"]', OWN_TURN_TEXT)+ ctx.page.wait_for_timeout(80)+ ctx.page.keyboard.press("Enter")+ own_generation = True+ sent_at = time.monotonic()+ # HOW LONG THE TURN IS WORTH MEASURING. Bounded by the SLOT as well as by+ # `TURN_START_TIMEOUT_MS`: 8 s is 2.7x the whole stop slot on the fast and quick films, so a+ # turn slow to start overran by seconds no matter what had been reserved for it.+ #+ # WHAT IS RESERVED OUT OF IT is the rest of the turn, not only its sleeps. A turn starting on+ # the last millisecond this allows still has the stop-settle poll, the delete and the driver+ # calls between them ahead of it, and reserving `OWN_TURN_FIXED_MS` left 424 ms of that unpaid+ # against real chromium -- 344 ms past a 3,000 ms slot with 300 ms before `scroll_after` opens,+ # recorded there as a missed slot. `OWN_TURN_FIXED_MS` also counts the 80 ms above, which is+ # already spent. See `OWN_TURN_STOP_POLL_MS`.+ start_wait_ms = max(+ 0.0,+ min(+ float(TURN_START_TIMEOUT_MS),+ remaining_ms() - OWN_TURN_FIXED_AFTER_SEND_MS - OWN_TURN_STOP_POLL_MS,+ ),+ )+ deadline = time.monotonic() + start_wait_ms / 1000.0+ # HOW LONG IT IS WORTH WAITING FOR, which is a different question and is NOT bounded by the+ # slot. See `_reclaim_pending_turn`.+ reclaim_deadline = sent_at + TURN_START_TIMEOUT_MS / 1000.0+ started_late = (+ f"nothing was generating and a new turn did not start within {start_wait_ms:.0f}ms"+ )+ while time.monotonic() < deadline:+ if _ev(ctx, "() => window.__sb.dom.isRunning()"):+ break+ ctx.page.wait_for_timeout(50)+ else:+ return _reclaim_pending_turn(ctx, messages_before, started_late, reclaim_deadline)+ if not _ev(ctx, "() => window.__sb.dom.isRunning()"):+ return _reclaim_pending_turn(ctx, messages_before, started_late, reclaim_deadline)+ # Let it get going, so stop is measured against a live stream rather than a starting one.+ ctx.page.wait_for_timeout(600)button = ctx.page.query_selector('button[aria-label="Stop generating"]')if button is None:queue = ctx.page.query_selector('button[aria-label="Queue message"]')diff --git a/tests/studio/studiobench/scene/schedule.py b/tests/studio/studiobench/scene/schedule.pyindex 73ee0ee24fa..10a75bfcaa2 100644--- a/tests/studio/studiobench/scene/schedule.py+++ b/tests/studio/studiobench/scene/schedule.py@@ -331,7 +331,24 @@ class SceneRunner:now_ms = (time.monotonic() - t0) * 1000if until_ms - now_ms < 250:return- with self.open_window(name, "stream") as window:+ # `gap`, NOT `stream`. These windows were labelled `stream` and the label was read by+ # people, including this project, as meaning the stream was running in them. It does not.+ # A gap window is opened before EVERY slot, so on the standard film eighteen of them exist+ # and only the first four contain any streaming at all; the rest are the quiet stretches+ # between post-generation actions. Measured on a 100K cell, `stream:gap12` ran for 32.9 s+ # at 1.6% busy with the reply finished thirty seconds earlier, and `stream:drain` -- the+ # one window that really is about the stream -- was 7 ms long.+ #+ # Anyone filtering on `kind == "stream"` to find the streaming phase therefore selected+ # mostly post-stream idle and diluted whatever they were measuring. The phase has to be+ # detected from the SSE traffic (see instruments/streamcost.py), and this label no longer+ # invites the mistake.+ #+ # The window NAME is deliberately left as `stream:gapN`. It is the join key in every+ # payload this tool has already written and in the analysis scripts pointed at them;+ # renaming it would break those silently, which is a worse failure than a misleading name+ # that is now documented in INTERFACES.md and contradicted by the kind beside it.+ with self.open_window(name, "gap") as window:while (time.monotonic() - t0) * 1000 < until_ms:time.sleep(min(0.2, max(0.01, (until_ms - (time.monotonic() - t0) * 1000) / 1000)))window.note("waited_to_ms", until_ms)diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_stop_slot_budget.py b/tests/studio/studiobench/scene/selftest/test_studiobench_stop_slot_budget.pynew file mode 100644index 00000000000..a448586530a--- /dev/null+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_stop_slot_budget.py@@ -0,0 +1,588 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""`stop_generation` must not spend the NEXT slot's window cleaning up after itself.++Every slot has an absolute start, so an action that overruns pushes no start. It does spend real+time: `SceneRunner._run_slot` is sequential, nothing enters the next slot until the previous action+has returned, and the next slot's remaining budget is `deadline - now`. An overrun therefore comes+straight out of the following action's window, and a big enough one records `slot_missed` there,+whose reason reads "this machine reached it at ...ms" -- the machine blamed for time the previous+action took.++WHERE THAT BECAME REACHABLE. `stop_generation` waits for the cell's own reply to drain rather than+stopping it, and that wait is bounded by the slot's remaining budget. Bounded by ALL of it, the+reply could drain at the last moment of the slot and the action would then start, stop and delete a+throwaway turn on time it no longer had. `stop_generation` closes 300 ms before `scroll_after` opens+on the fast film and 500 ms before it on the quick one, so on both of those the overrun lands inside+`scroll_after`'s own window, and on the fast film -- 1,200 ms of budget behind a 300 ms gap --+it can take the whole of it.++Reachable on supported input, and only on supported input: the drain wait exists for+`--stream-tail-chars`, whose entire purpose is a reply long enough to still be streaming when this+slot opens. A tail that puts the drain near the end of the slot is exactly the case it was written+for.++WHAT IS FAKED AND WHAT IS NOT. The action under test is the shipped `stop_generation`. The page is+a shim of the calls it makes, and the clock is a counter that the shim advances, so the test+measures the time the action ASKS the page for rather than how long this machine took to answer.++THE SHIM'S POLLS ARE NOT FREE, and that correction is why this file was rewritten. The first+version answered `isRunning()` instantly and charged nothing for a page call, so the only cost it+could see was the four fixed sleeps -- `[100 x29, 80, 600, 400, 200]`, 1,280 ms after the drain --+and a reserve sized from that number was 500 ms short of what the action really spends. Driving the+SAME shipped `stop_generation` against real chromium and a real clock, on a page standing in for+the calls it makes, the stretch after the drain costs:++ page answers instantly 1,394 - 1,451 ms (n = 5)+ 120 ms to start, 90 ms to stop, 60 ms to delete 1,723 - 1,938 ms (n = 5)+ 300 ms to start, 200 ms to stop, 150 ms to delete 2,092 - 2,102 ms (n = 2)++against 1,280 ms reserved, which put the action 506 - 516 ms past the end of a 3,000 ms stop slot+on both films whose gap before `scroll_after` is smaller than that. The difference is thirteen to+seventeen CDP round trips at about 4 ms each, the 50 ms granularity of the two poll loops, and the+app's own latency in answering them -- none of which a shim that answers in-process can produce.+So the shim below charges `ROUND_TRIP_MS` for every page call and holds the page to `START_MS`,+`STOP_MS` and `CLEANUP_MS` before it changes its answer. That puts the same stretch at 1,688 ms+against the middle row's 1,723 - 1,938 ms, so it is still a floor -- and with the latency switched+off it returns exactly 1,280 ms, which is the old shim's number and shows the whole correction is+the modelling and not the action.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[3]))++from studiobench.runtime.types import ActionContext # noqa: E402+from studiobench.scene import actions as actions_module # noqa: E402+from studiobench.scene.actions import ( # noqa: E402+ OWN_TURN_FIXED_AFTER_SEND_MS,+ OWN_TURN_FIXED_MS,+ OWN_TURN_POLL_MS,+ OWN_TURN_RESERVE_MS,+ OWN_TURN_START_POLL_MS,+ OWN_TURN_STOP_POLL_MS,+ TURN_START_TIMEOUT_MS,+ stop_generation,+)+from studiobench.scene.schedule import FAST, QUICK, STANDARD # noqa: E402++#: One driver call over CDP. Measured at 43 - 130 ms across nine to thirteen `page.evaluate` calls+#: in one run of the shipped action against real chromium, and the two big ones in that total are+#: page-side waits charged separately below, so about 4 ms is the round trip itself.+ROUND_TRIP_MS = 4.0++#: Enter pressed to `isRunning()` answering true: a POST to the relay and the first SSE frame back.+START_MS = 120.0++#: Stop clicked to `isRunning()` answering false: the abort round trip.+STOP_MS = 90.0++#: The delete inside `STOP_CLEANUP_JS`: the click, the removal, and the two `__sbNextPaint` frames+#: the loop waits on.+CLEANUP_MS = 90.0+++class _Clock:+ """The action reads `time.monotonic`; the page's waits and calls are what move it."""++ def __init__(self) -> None:+ self.t = 1_000.0++ def monotonic(self) -> float:+ return self.t++ def advance_ms(self, ms: float) -> None:+ self.t += ms / 1_000.0+++class _Keyboard:+ def __init__(self, page) -> None:+ self.pressed: list[str] = []+ self._page = page++ def press(self, key: str) -> None:+ self._page.charge()+ self.pressed.append(key)+ if key != "Enter" or not self._page.composer.strip():+ return+ if not self._page.accepts_send:+ # `queueDisabled` in thread.tsx: the press queued nothing and the box keeps its text.+ return+ # SENT, NOT STARTED, and the difference is the whole of the P1 above. The app takes the+ # text out of the composer and puts the user turn and its reply into the thread NOW; the+ # reply begins generating `start_ms` later, and the action has to poll for it -- which is+ # the cost the first version of this shim handed out free.+ self._page.composer = ""+ self._page.messages += 2+ self._page.sent_at_ms = self._page.elapsed_ms+++class _Page:+ """The cell's own reply is streaming and drains `drain_after_ms` into the slot.++ `latency = False` restores the instant-answer page the first version of this file used, which+ is kept only as the control below: it is the floor, not the machine.++ THE COMPOSER AND THE THREAD ARE MODELLED, not stubbed. `composerText()` used to answer "" and+ `messageCount()` was never asked, so a send the app REFUSED and a send it accepted looked+ identical from the driver -- which is exactly the distinction the action has to make before it+ deletes anything, and a shim that cannot make it cannot test the code that does.+ """++ def __init__(+ self,+ clock: _Clock,+ drain_after_ms: float,+ *,+ latency: bool = True,+ start_ms: float = START_MS,+ stop_ms: float = STOP_MS,+ cleanup_ms: float = CLEANUP_MS,+ accepts_send: bool = True,+ ) -> None:+ self._clock = clock+ self._entered = clock.t+ self._drain_after_ms = drain_after_ms+ self._latency = latency+ self._start_ms = start_ms+ self._stop_ms = stop_ms+ self._cleanup_ms = cleanup_ms+ self.accepts_send = accepts_send+ self.running = True+ self.filled: list[str] = []+ self.composer = ""+ # The seeded user turn and the reply it prompted.+ self.messages = 2+ self.deleted = 0+ self.clicked = 0+ self.sent_at_ms: float | None = None+ self.clicked_at_ms: float | None = None+ self.keyboard = _Keyboard(self)++ @property+ def elapsed_ms(self) -> float:+ return (self._clock.t - self._entered) * 1_000.0++ def charge(self, ms: float = ROUND_TRIP_MS) -> None:+ if self._latency:+ self._clock.advance_ms(ms)++ def settle(self, ms: float) -> None:+ """Time passing with nobody driving: what the NEXT action walks into."""+ self._clock.advance_ms(ms)++ def _is_running(self) -> bool:+ if self.clicked_at_ms is not None:+ return self.elapsed_ms < self.clicked_at_ms + (self._stop_ms if self._latency else 0.0)+ if self.sent_at_ms is not None:+ return self.elapsed_ms >= self.sent_at_ms + (self._start_ms if self._latency else 0.0)+ if self.running and self.elapsed_ms >= self._drain_after_ms:+ self.running = False+ return self.running++ def evaluate(+ self,+ script,+ arg = None,+ ):+ self.charge()+ if arg is not None: # STOP_CLEANUP_JS, which is the only call that takes one+ self.charge(self._cleanup_ms)+ before = self.messages+ if self.messages:+ self.messages -= 1+ self.deleted += 1+ return {+ "removed": self.messages < before,+ "before": before,+ "after": self.messages,+ "reason": None,+ }+ if "isRunning" in script:+ return self._is_running()+ if "composerText" in script:+ return self.composer+ if "messageCount" in script:+ return self.messages+ if "assistantChars" in script:+ return 9_200+ raise AssertionError(f"the page was asked something this shim does not model: {script}")++ def fill(self, _selector: str, text: str) -> None:+ self.charge()+ self.filled.append(text)+ self.composer = text++ def wait_for_timeout(self, ms) -> None:+ self._clock.advance_ms(ms)++ def query_selector(self, selector: str):+ self.charge()+ page = self++ class _Button:+ def click(_self) -> None:+ page.charge()+ page.clicked += 1+ page.clicked_at_ms = page.elapsed_ms++ return _Button() if "Stop generating" in selector else None+++def _drive(page, monkeypatch, clock, budget_ms: int):+ monkeypatch.setattr(actions_module, "time", clock)+ return stop_generation(+ ActionContext(+ page = page,+ cdp = None,+ cell = None,+ window = None,+ args = {},+ budget_ms = budget_ms,+ dom = None,+ log = lambda _m: None,+ )+ )+++def _run(+ monkeypatch,+ *,+ budget_ms: int,+ drain_after_ms: float,+ latency: bool = True,+ **page_kwargs,+):+ clock = _Clock()+ page = _Page(clock, drain_after_ms, latency = latency, **page_kwargs)+ return _drive(page, monkeypatch, clock, budget_ms), page+++def _stop_slot(scene):+ """The stop slot, and the gap between its deadline and the next slot's start."""+ index = next(i for i, s in enumerate(scene.slots) if s.action == "stop_generation")+ stop, nxt = scene.slots[index], scene.slots[index + 1]+ return stop, nxt, nxt.t_start_ms - (stop.t_start_ms + stop.budget_ms)++[email protected]("scene", [FAST, QUICK, STANDARD], ids = lambda s: s.name)+def test_a_reply_that_drains_at_the_end_of_the_slot_does_not_spend_the_next_one(monkeypatch, scene):+ """THE REGRESSION, in the film's own numbers.++ A reply that is still streaming 100 ms before this slot closes leaves nothing for the throwaway+ turn. The action has to stop within the gap before the next slot opens -- 300 ms on the fast+ film, 500 ms on the quick one -- or the next action's window pays for it.+ """++ stop, nxt, slack_ms = _stop_slot(scene)+ late = stop.budget_ms - 100+ result, page = _run(monkeypatch, budget_ms = stop.budget_ms, drain_after_ms = late)++ assert page.elapsed_ms <= stop.budget_ms + slack_ms, (+ f"{scene.name}: stop_generation spent {page.elapsed_ms:.0f}ms of a {stop.budget_ms}ms "+ f"slot with only {slack_ms}ms before {nxt.action} opens"+ )+ # And it stopped by declining, not by stopping the cell's own reply, which is the whole point+ # of the wait it just gave up on.+ assert result.ran is False+ assert page.clicked == 0+ assert "one more" not in page.filled++[email protected]("scene", [FAST, QUICK, STANDARD], ids = lambda s: s.name)+def test_no_moment_the_reply_can_drain_lets_the_action_spend_the_next_slot(monkeypatch, scene):+ """THE REGRESSION THE FIXED SLEEPS ALONE DID NOT COVER, and the reason this file was rewritten.++ The case above is refused by the drain wait's own deadline. There is a case between the two+ that is not: a reply draining just INSIDE the reserve, where the action commits to the+ throwaway turn with what the reserve says is exactly enough and then spends the two polls, the+ delete and thirteen to seventeen CDP round trips that a reserve counting only the four fixed+ sleeps never priced. Measured against real chromium that is 1,723 - 1,938 ms of work paid for+ with 1,280 ms, which lands 506 - 516 ms into `scroll_after` on both 3,000 ms films and is+ recorded there as a missed slot.++ SWEPT RATHER THAN AIMED AT ONE BOUNDARY, because the boundary is what is under test: a test+ that drains at `budget - RESERVE - 50` moves with the constant and passes on any reserve at+ all. The invariant does not depend on a number -- WHENEVER the reply drains, the action returns+ inside its slot plus the gap the film leaves before the next one -- so every 50 ms of the slot+ is tried and the assertion is the same at each.++ Two things have to hold for that, and only both together are enough. The reserve has to cover+ what the turn really costs, and the clock has to be re-read before the turn is committed to:+ the drain loop tests its deadline at the top, so the iteration that finds the reply drained has+ already spent a wait and a round trip past it, and no constant pays for time already gone.+ """++ stop, nxt, slack_ms = _stop_slot(scene)+ for drained_at in range(0, stop.budget_ms, 50):+ result, page = _run(monkeypatch, budget_ms = stop.budget_ms, drain_after_ms = drained_at)+ assert page.elapsed_ms <= stop.budget_ms + slack_ms, (+ f"{scene.name}: a reply draining {drained_at}ms into the slot left "+ f"stop_generation spending {page.elapsed_ms:.0f}ms of a {stop.budget_ms}ms slot with "+ f"only {slack_ms}ms before {nxt.action} opens"+ + (f"; it ran the throwaway turn anyway: {result.expect}" if result.ran else "")+ )++[email protected]("scene", [FAST, QUICK, STANDARD], ids = lambda s: s.name)+def test_a_send_the_app_refused_is_bounded_by_the_slot_and_not_by_eight_seconds(monkeypatch, scene):+ """The other unbounded wait after the drain, on the one path where cutting it really is free.++ `TURN_START_TIMEOUT_MS` is 8 s, which is 2.7x the whole stop slot on the fast and quick films,+ so a turn that never came up used to hold the action for eight seconds and take the next two or+ three slots with it. When the app REFUSED the send -- `queueDisabled` turns Send into Queue+ while anything is running, and a Queue press leaves the text in the box -- nothing was+ committed, there is nothing to take back, and the wait may be cut to fit the slot.++ THE CONTROL for the P1 below, and it passes on the code before that fix as well as after it:+ what changed is only which of the two cases this covers."""++ stop, nxt, slack_ms = _stop_slot(scene)+ result, page = _run(+ monkeypatch,+ budget_ms = stop.budget_ms,+ drain_after_ms = 0.0,+ accepts_send = False,+ )++ assert result.ran is False+ assert "did not start" in (result.reason or "")+ assert page.composer == "one more", "the send was refused, so the text is still in the box"+ assert page.messages == 2, "nothing was sent, so nothing may be deleted either"+ assert page.deleted == 0+ assert page.elapsed_ms <= stop.budget_ms + slack_ms, (+ f"{scene.name}: waiting for a send the app refused cost {page.elapsed_ms:.0f}ms of a "+ f"{stop.budget_ms}ms slot with only {slack_ms}ms before {nxt.action} opens"+ )+++def _thread_a_measured_turn_leaves(monkeypatch, budget_ms: int) -> int:+ """What the thread looks like after a turn that DID start, was stopped and was cleaned up.++ The reference for every give-up path below, rather than a literal: `STOP_CLEANUP_JS` is what+ decides how much of the throwaway turn comes back out, and a give-up path is required to leave+ the thread where the measured path leaves it -- not somewhere a number in this file asserts.+ """+ result, page = _run(monkeypatch, budget_ms = budget_ms, drain_after_ms = 0.0, start_ms = 0.0)+ assert result.ran is True, result.reason+ return page.messages++[email protected]("scene", [FAST, QUICK, STANDARD], ids = lambda s: s.name)[email protected]("late_by_ms", [0, 400, 800])+def test_a_turn_that_starts_after_the_slot_bound_is_not_left_generating(+ monkeypatch, scene, late_by_ms+):+ """THE P1. Enter is pressed BEFORE the turn-start wait, so the slot bound on that wait does not+ return from a decision -- it returns from a turn the app has already accepted.++ Measured in real chromium on a page taking 1,800 ms to start against the fast film's 3,000 ms+ stop slot, the action returned `not_run` after 1,759 ms and handed on a thread with two extra+ messages in it and a live stream running through `scroll_after`'s window. Every later action,+ the final census and the seeded-versus-streamed comparison then measure that scaffolding -- the+ same defect `STOP_CLEANUP_JS` was written to remove, reached by giving up instead of by+ finishing. Cutting the wait short is only free when nothing was sent, which is the control+ directly above.++ The turn has to come back stopped and deleted, and the thread has to be the one a measured turn+ would have left."""++ stop, _nxt, _slack = _stop_slot(scene)+ settled = _thread_a_measured_turn_leaves(monkeypatch, stop.budget_ms)+ # Past the slot bound, which is the budget less what the rest of the turn costs, and still+ # inside the time the turn is worth waiting for so it can be taken back.+ start_ms = stop.budget_ms - 1_000 + late_by_ms++ result, page = _run(+ monkeypatch,+ budget_ms = stop.budget_ms,+ drain_after_ms = 0.0,+ start_ms = start_ms,+ )++ assert result.ran is False+ assert page.composer == "", "the send went through, so the box is empty"+ assert page.clicked == 1, "the turn it had already sent was never stopped"+ assert page.deleted == 1, "the turn it had already sent was never deleted"+ assert page.messages == settled, (+ f"{scene.name}: a turn starting {start_ms}ms in was given up on and left the thread at "+ f"{page.messages} messages, where a measured turn leaves it at {settled}"+ )+ # And it is not about to start streaming again the moment the next action opens its window.+ page.settle(2_000)+ assert page._is_running() is False++[email protected]("scene", [FAST, QUICK, STANDARD], ids = lambda s: s.name)+def test_a_turn_that_never_starts_at_all_is_still_taken_out_of_the_thread(monkeypatch, scene):+ """The far end of the same path: the send was accepted and the relay never answered.++ Nothing can be stopped, because nothing ever ran, but the app put the turn in the thread on+ send and it is still there. It comes out, the row says so, and the whole thing is bounded by+ `TURN_START_TIMEOUT_MS` -- the same eight seconds this wait cost before it was bounded by the+ slot at all, so taking the turn back is not paid for with a wait that did not exist before."""++ stop, _nxt, _slack = _stop_slot(scene)+ settled = _thread_a_measured_turn_leaves(monkeypatch, stop.budget_ms)++ result, page = _run(+ monkeypatch,+ budget_ms = stop.budget_ms,+ drain_after_ms = 0.0,+ start_ms = 10 * TURN_START_TIMEOUT_MS,+ )++ assert result.ran is False+ assert "never started" in (result.reason or ""), result.reason+ assert page.clicked == 0, "there was nothing running to stop"+ assert page.messages == settled+ assert page.elapsed_ms <= TURN_START_TIMEOUT_MS + OWN_TURN_RESERVE_MS, (+ f"{scene.name}: taking back a turn that never started cost {page.elapsed_ms:.0f}ms, more "+ f"than the {TURN_START_TIMEOUT_MS}ms this wait cost before it was bounded by the slot"+ )++[email protected]("scene", [FAST, QUICK, STANDARD], ids = lambda s: s.name)+ ("stop_ms", "cleanup_ms"),+ [(0.0, 0.0), (90.0, 60.0), (200.0, 150.0)],+ ids = ["instant", "local", "slow"],+)+def test_no_moment_the_turn_can_start_lets_the_action_spend_the_next_slot(+ monkeypatch, scene, stop_ms, cleanup_ms+):+ """THE P2, and the third thing the reserve has to get right.++ The drain wait reserves the whole turn and the clock is re-read before the turn is committed+ to, but the TURN-START wait is bounded separately, and a turn starting on the last millisecond+ that bound allows still has the stop-settle poll, the delete and the driver calls between them+ ahead of it. Reserving only `OWN_TURN_FIXED_MS` -- which also counts the 80 ms already spent+ settling the fill -- left that stretch unpaid. Measured against real chromium with the turn+ starting at the bound and a 3,000 ms slot:++ page answers instantly 60 ms past the fixed sleeps slot - 20 ms+ 90 ms to stop, 60 ms to delete 227 ms past the fixed sleeps slot + 147 ms+ 200 ms to stop, 150 ms to delete 424 ms past the fixed sleeps slot + 344 ms++ The fast film leaves 300 ms before `scroll_after` opens, so the last row was recorded there as+ `slot_missed` -- the machine blamed for time this action spent, one action later than the+ defect the reserve above already fixed. The three page latencies are the same three the totals+ in `OWN_TURN_POLL_MS` were measured at.++ SWEPT RATHER THAN AIMED AT THE BOUNDARY, for the same reason as the drain sweep: a test that+ starts the turn at `bound - 50` moves with the constant and passes on any bound at all.++ THE INVARIANT IS A PAIR, because past the bound the action stops being able to have both. A+ turn it MEASURES has to fit the slot and the gap the film leaves after it. A turn it gives up+ on does not fit -- taking a turn back costs a stop and a delete whenever the app gets round to+ starting it -- and the price of leaving instead is a live stream in every later window, so what+ is required there is that the thread comes back the way it was found."""++ stop, nxt, slack_ms = _stop_slot(scene)+ settled = _thread_a_measured_turn_leaves(monkeypatch, stop.budget_ms)+ measured = 0+ for start_ms in range(0, stop.budget_ms, 50):+ result, page = _run(+ monkeypatch,+ budget_ms = stop.budget_ms,+ drain_after_ms = 0.0,+ start_ms = start_ms,+ stop_ms = stop_ms,+ cleanup_ms = cleanup_ms,+ )+ if result.ran:+ measured += 1+ assert page.elapsed_ms <= stop.budget_ms + slack_ms, (+ f"{scene.name}: a turn taking {start_ms}ms to start left stop_generation spending "+ f"{page.elapsed_ms:.0f}ms of a {stop.budget_ms}ms slot with only {slack_ms}ms "+ f"before {nxt.action} opens; it ran the turn anyway: {result.expect}"+ )+ else:+ assert page.messages == settled, (+ f"{scene.name}: a turn taking {start_ms}ms to start was given up on and left the "+ f"thread at {page.messages} messages for {nxt.action} to measure, where a measured "+ f"turn leaves it at {settled}"+ )+ assert measured, f"{scene.name}: the bound refused every turn, so it measures nothing"++[email protected]("scene", [FAST, QUICK, STANDARD], ids = lambda s: s.name)+def test_a_reply_that_drains_early_still_gets_its_throwaway_turn(monkeypatch, scene):+ """THE CONTROL. The reserve must not turn the wait into a refusal: a marginally slow drain is+ what it was written for, and the fast film opens this slot only 400 ms after the worst-case+ drain on the ladder. A reply that finishes 500 ms in must still be stopped and measured."""++ stop, _nxt, _slack = _stop_slot(scene)+ result, page = _run(monkeypatch, budget_ms = stop.budget_ms, drain_after_ms = 500)++ assert result.ran is True, result.reason+ assert page.filled == ["one more"]+ assert page.clicked == 1, "the throwaway turn is what gets stopped"+ assert result.expect["own_generation"] is True+ assert page.elapsed_ms <= stop.budget_ms++[email protected]("scene", [FAST, QUICK, STANDARD], ids = lambda s: s.name)+def test_nothing_running_at_the_slot_still_gets_its_throwaway_turn(monkeypatch, scene):+ """THE SECOND CONTROL, and the path every unmodified run takes: with the pinned tail the reply+ is long finished when this slot opens, the drain wait is never entered, and the turn has the+ whole budget. It must still be sent, stopped and cleaned up on every film."""++ stop, _nxt, _slack = _stop_slot(scene)+ clock = _Clock()+ monkeypatch.setattr(actions_module, "time", clock)+ page = _Page(clock, drain_after_ms = 0.0)+ page.running = False+ result = stop_generation(+ ActionContext(+ page = page,+ cdp = None,+ cell = None,+ window = None,+ args = {},+ budget_ms = stop.budget_ms,+ dom = None,+ log = lambda _m: None,+ )+ )++ assert result.ran is True, result.reason+ assert page.clicked == 1+ assert page.elapsed_ms <= stop.budget_ms++[email protected]("scene", [FAST, QUICK, STANDARD], ids = lambda s: s.name)+def test_every_film_still_leaves_a_real_drain_wait_after_the_reserve(scene):+ """The reserve comes out of a budget, so a slot too small to hold it would silently turn the+ wait into an immediate refusal and the axis this guard protects would be unreachable again."""++ stop, _nxt, _slack = _stop_slot(scene)+ assert stop.budget_ms - OWN_TURN_RESERVE_MS >= 1_000, (+ f"{scene.name}: a {stop.budget_ms}ms stop slot leaves "+ f"{stop.budget_ms - OWN_TURN_RESERVE_MS}ms to wait for the drain"+ )+++def test_the_reserve_is_still_the_whole_of_what_its_two_halves_reserve():+ """The reserve is spent at two moments and checked at two, and the two accounts have to be the+ same account. The drain wait holds back `OWN_TURN_RESERVE_MS` for the entire turn; the+ turn-start wait holds back only the part of it that is still AHEAD once the turn is sent. If+ the halves stop summing to the whole, one of the two waits is reserving for a stretch nobody+ else believes in and the film gets the difference."""++ assert OWN_TURN_RESERVE_MS == OWN_TURN_FIXED_MS + OWN_TURN_POLL_MS+ assert OWN_TURN_POLL_MS == OWN_TURN_START_POLL_MS + OWN_TURN_STOP_POLL_MS+ # The 80 ms that settles the fill is the only fixed sleep before the send.+ assert OWN_TURN_FIXED_MS - OWN_TURN_FIXED_AFTER_SEND_MS == 80+ # And what the turn-start wait holds back has to leave the start poll something to spend, or+ # the wait is an immediate refusal and the throwaway turn is unreachable on the tightest drain.+ assert (+ OWN_TURN_RESERVE_MS - 80 - OWN_TURN_FIXED_AFTER_SEND_MS - OWN_TURN_STOP_POLL_MS+ == OWN_TURN_START_POLL_MS+ )diff --git a/tests/studio/studiobench/scoring/from_payload.py b/tests/studio/studiobench/scoring/from_payload.pyindex da9ac280310..6d070dfdaa6 100644--- a/tests/studio/studiobench/scoring/from_payload.py+++ b/tests/studio/studiobench/scoring/from_payload.py@@ -54,10 +54,55 @@ SCROLL_SETTLE_NOTE = (FRAME_METRICS: tuple[str, ...] = ("time_in_jank_pct", "jank_index", "max_frame_ms")+# ── the streaming phase, separated out and normalised per character ─────────────────────────+#+# The three metrics above are not blind to the stream. `_frame_measures` pools every window whose+# kind is not `idle`, and the streaming windows are in that pool. What they cannot do is separate+# it: one 57.3 s film collapses eighteen action windows and the streaming stretch into a single+# number, and the action windows dominate. On a measured 100K null control, `reasoning_toggle`+# alone contributed 2,865 ms of blocked time at 99.3% busy with a 1,866 ms worst frame while the+# streaming stretch beside it ran at 3.6% busy with a 100 ms worst frame.+#+# THE WINDOW KIND CANNOT BE USED TO SEPARATE THEM, and the name is what misleads.+# `SceneRunner._gap_window` opens every inter-slot gap as `kind = "stream"`, so on the standard+# film eighteen windows are named `stream:gapN` and only the first four contain streaming;+# `stream:drain` is opened after the film has finished and measured 7 ms on that same cell. The+# phase is therefore taken from the `stream_cost` instrument, which detects it from the SSE+# traffic, and never from the label.+STREAM_METRICS: tuple[str, ...] = (+ "stream_delta_cost_ms_per_kchar",+ "stream_cost_ms_per_kchar",+ "stream_busy_pct",+ "stream_jank_index",+ "stream_time_in_jank_pct",+ "stream_max_frame_ms",+)++# A window has to carry at least this much streamed text before its cost is divided by it. Below+# it the denominator is small enough that the ratio is dominated by whatever else shared the+# window: on a measured cell an `action:send_turn` window grew the reply by 13 characters while+# accumulating 475 ms of blocked time, which as a rate is 36,500 ms per thousand characters and is+# a statement about opening a menu, not about streaming.+MIN_STREAM_CHARS_PER_WINDOW = 100++# More timer ticks than the clamp says are possible means the clamp is wrong, and every blocked+# figure derived from it is a subtraction against the wrong floor. `clocks_agree` would be the+# gate, but on a headless engine it is null by design (see instruments/pagejs.py: rAF has no vsync+# to be checked against and the screencast is rate-limited), so `timer_clock_ratio` is the sound+# 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"})+# 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).+UNAIDED_WINDOW_KINDS: frozenset[str] = frozenset({"gap", "stream"})+# The row types keyed by `cell_id`, and so the ones a superseded attempt can leak through.ATTEMPT_ROW_TYPES: frozenset[str] = frozenset({"cell", "action", "window"})@@ -243,6 +288,296 @@ def _frame_measures(windows: Sequence[Mapping[str, Any]]) -> dict[str, Measure]:return out+def _stream_windows(windows: Sequence[Mapping[str, Any]]) -> tuple[list[Mapping[str, Any]], dict]:+ """The windows that carried streaming, and why each rejected one was rejected.++ A window qualifies when the `stream_cost` instrument SAW SSE traffic in it and the reply it was+ feeding grew by a usable amount. Both halves are needed. Traffic alone admits the tail window+ in which the stream ended after 400 ms and the remaining twelve seconds were idle; growth alone+ admits `thread_reopen`, which rebuilds the whole thread and grows the character count by tens+ of thousands without a byte of it having been streamed.+ """+ picked: list[Mapping[str, Any]] = []+ rejected: dict[str, int] = {}++ def reject(why: str) -> None:+ rejected[why] = rejected.get(why, 0) + 1++ for w in windows:+ inst = w.get("instruments") or {}+ sc = inst.get("stream_cost")+ if not isinstance(sc, Mapping) or not sc.get("stream_cost_attempted"):+ reject("the stream_cost instrument did not run in this window")+ continue+ if not sc.get("streaming_observed"):+ reject("no SSE traffic reached the page during this window")+ continue+ delta = sc.get("reply_chars_delta")+ if delta is None:+ reject(+ str(sc.get("reply_chars_delta_reason") or "the reply's growth was not measurable")+ )+ continue+ if int(delta) < MIN_STREAM_CHARS_PER_WINDOW:+ reject(f"the reply grew by fewer than {MIN_STREAM_CHARS_PER_WINDOW} characters")+ continue+ frames = inst.get("frames")+ if isinstance(frames, Mapping):+ if frames.get("clocks_agree") is False:+ reject("the window's clocks disagreed, so it is not scoreable")+ continue+ ratio = frames.get("timer_clock_ratio")+ if isinstance(ratio, (int, float)) and float(ratio) > MAX_TIMER_CLOCK_RATIO:+ reject("more timer ticks than the calibrated clamp allows, so the clamp is wrong")+ continue+ picked.append(w)+ return picked, rejected+++def _unaided(windows: Sequence[Mapping[str, Any]]) -> list[Mapping[str, Any]]:+ """Of the streaming windows, the ones with no scripted action running in them.++ EVERY streaming quantity is taken from these, including the targeted numerator, and that is a+ correction the measurements forced rather than a position held from the start.++ The first version of this metric fed `delta_task_ms` from every streaming window, on the+ reasoning that a task chain an SSE chunk started is attributable to the stream wherever it+ happened. That reasoning is wrong, and a standard-tier 10K null shows exactly how. The chain+ is measured from the chunk to the moment the event loop next reaches a macrotask, so ANY work+ that lands in between is charged to it. Three of the film's slots run during generation on+ purpose, and in `action:keystroke` on one cell the chain cost 23.77 ms per burst against 1.69+ ms in the gap windows either side of it. That is typing, billed to the stream.++ The window-wide quantities -- blocked time, the frame distribution, the worst frame -- fail+ the same way and more obviously, because they charge the whole window. On a fast-tier 100K+ null, admitting the action windows put a 1,738 ms worst frame into `stream_max_frame_ms` when+ the unaided stretch beside it peaked at 286 ms: a scroll, reported as a streaming stall.++ So the streaming phase, for scoring, is the quiet stretches where the stream is doing its work+ unaided. Measured against the alternative on the same payload this also has the narrower null+ floor (32.9% against 36.0%), which is the weaker argument of the two but points the same way.++ Restricting FURTHER -- to the opening turn only -- was tried and is much worse (101.5%),+ because fewer windows average less and one outlier then owns the cell. More streaming windows+ is better as long as every one of them is unaided.++ UNAIDED IS NOT THE SAME PREDICATE AS `kind == "gap"`, which is what this used to test. The+ session layer opens one more quiet window that the scheduler does not: `stream:drain`, with+ `kind = "stream"`, held open after the film to wait the reply out. On the default fixture it+ carries nothing -- the tail is pinned at 6,000 characters, drains in 14 to 18 s against a+ 243 s standard film, and the measured drain window was 7 ms long -- so `_stream_windows`+ rejects it for having seen no SSE traffic and the distinction never showed. It shows the+ moment `--stream-tail-chars` is used, which is the one supported way to make the reply long:+ at 96,000 characters the reply streams for 291 s at field cadence, so roughly 48 s of it lands+ AFTER the last slot has closed, in the drain window, with nothing scripted running in it. That+ stretch is unaided streaming by every part of the definition above, and dropping it dropped+ the characters and the cost of the LAST fifth of the reply -- the part streamed into the+ largest thread, so the most expensive part -- out of every streaming metric. Nor is+ `stream_max_frame_ms` a ratio that might absorb it: a worst frame in that stretch was simply+ never seen.++ The kind filter is still what does the work, because it is the only thing that separates a+ quiet window from an action window. It now names both quiet kinds instead of one.+ """+ return [w for w in windows if str(w.get("kind") or "") in UNAIDED_WINDOW_KINDS]+++def _stream_measures(windows: Sequence[Mapping[str, Any]]) -> dict[str, Measure]:+ """The streaming phase alone, integrated, and divided by the characters it streamed.++ TWO NUMERATORS, deliberately, because they fail in opposite directions and a reader should be+ able to see both:++ `stream_delta_cost_ms_per_kchar` is TARGETED. It sums only the main-thread task chains that+ SSE chunks start, so it excludes the background churn -- async highlighting, GC, the app's+ own timers -- that a whole-window figure charges to the stream. It is the sharper of the two+ and the one a change to the delta path should move.++ `stream_cost_ms_per_kchar` is BROAD. It sums blocked time over the streaming stretch, so it+ catches stream-driven cost that lands outside the delta's own task chain, which is most of+ the asynchronous work. It is the honest total and the noisier of the two.++ Both are `null` with a reason rather than zero when the timer clamp was never established:+ blocked time is a subtraction against an idle floor, and without a floor the quantity does not+ exist.+ """+ unit_by_key = {+ "stream_delta_cost_ms_per_kchar": "ms/kchar",+ "stream_cost_ms_per_kchar": "ms/kchar",+ "stream_busy_pct": "%",+ "stream_jank_index": "ms",+ "stream_time_in_jank_pct": "%",+ "stream_max_frame_ms": "ms",+ }+ picked, rejected = _stream_windows(windows)+ if not picked:+ why = (+ "; ".join(f"{n} window(s): {r}" for r, n in sorted(rejected.items()))+ or "this cell recorded no windows"+ )+ return {+ k: Measure.not_attempted(u, f"no window in this cell carried streaming ({why})")+ for k, u in unit_by_key.items()+ }++ # A CELL WHOSE RECORDER DIED IS A TRUNCATED CELL, not a short one. `rejected` above is read+ # only when NOTHING qualified, so once one window has qualified every later rejection is+ # discarded -- including the one that says the page went away. The streaming metrics are+ # integrals divided by the characters that were streamed, and both halves are then missing the+ # same unmeasured stretch, so the result is not a wide error bar, it is a number computed over+ # whatever ran before the crash and reported as if it described the cell.+ #+ # Measured on the payload corpus: 138 unaided windows record `unavailable` while a qualifying+ # window precedes them, carrying `TargetClosedError: Page.evaluate: Target page, context or+ # browser has been closed` and `Error: Page.evaluate: Target crashed`. They are all AFTER the+ # last qualifying window, which is not evidence that they are ordinary end-of-stream windows:+ # a crash is trailing by construction, because nothing can qualify once the page is gone. They+ # are also long, a median of 11.0 s and up to 36.0 s, so what went unmeasured is a real+ # fraction of the reply and not a rounding edge.+ #+ # `unavailable` was consumed nowhere in this module before this, so the crash signal the+ # instrument already emits was being dropped in full. Poisoning here costs 12 cells of 1,461+ # that currently publish, and every one of the 12 is a genuine page crash.+ crashed = sorted(+ {+ str(sc.get("unavailable"))+ for w in _unaided(windows)+ if isinstance((sc := (w.get("instruments") or {}).get("stream_cost")), Mapping)+ and not sc.get("stream_cost_attempted")+ and sc.get("unavailable")+ }+ )+ if crashed:+ reason = (+ "the stream_cost recorder stopped partway through this cell "+ f"({'; '.join(crashed)}), so the streaming metrics would describe only the part of "+ "the reply that streamed before it went away"+ )+ return {k: Measure.failed(u, reason) for k, u in unit_by_key.items()}++ # Every streaming quantity comes from the UNAIDED windows. See _unaided for why the targeted+ # numerator is not exempt from that, which is the one thing here that measurement overturned.+ unaided = _unaided(picked)+ chars = 0+ delta_task_ms = 0.0+ for w in unaided:+ sc = (w.get("instruments") or {}).get("stream_cost") or {}+ chars += int(sc.get("reply_chars_delta") or 0)+ delta_task_ms += float(sc.get("delta_task_ms") or 0.0)++ unaided_chars = 0+ blocked_ms = 0.0+ blocked_reason: str | None = None+ streaming_ms = 0.0+ deltas: list[float] = []+ window_ms = 0.0+ max_frame: float | None = None+ frameless = 0++ for w in unaided:+ inst = w.get("instruments") or {}+ sc = inst.get("stream_cost") or {}+ unaided_chars += int(sc.get("reply_chars_delta") or 0)+ streaming_ms += float(sc.get("streaming_ms") or 0.0)+ blocked = sc.get("stream_blocked_ms")+ if blocked is None:+ blocked_reason = str(+ sc.get("stream_blocked_ms_reason") or "blocked time was not measurable"+ )+ else:+ blocked_ms += float(blocked)++ frames = inst.get("frames")+ if not isinstance(frames, Mapping) or not frames.get("frames_attempted"):+ continue+ mx = frames.get("max_frame_ms")+ if mx is not None:+ max_frame = float(mx) if max_frame is None else max(max_frame, float(mx))+ if frames.get("frame_gaps_truncated"):+ continue+ gaps = frames.get("frame_gaps_ms")+ if not gaps:+ frameless += 1+ continue+ deltas.extend(float(g) for g in gaps)+ window_ms += float(w.get("duration_ms") or 0.0)++ out: dict[str, Measure] = {}+ note = f"{len(unaided)} unaided streaming window(s), {chars} streamed characters"+ unaided_note = (+ f"{len(unaided)} unaided streaming window(s), {unaided_chars} streamed characters"+ )++ out["stream_delta_cost_ms_per_kchar"] = (+ Measure.read(1000.0 * delta_task_ms / chars, "ms/kchar", note = note)+ if chars > 0+ else Measure.failed("ms/kchar", "the streaming windows recorded no streamed characters")+ )+ if blocked_reason:+ out["stream_cost_ms_per_kchar"] = Measure.failed("ms/kchar", blocked_reason)+ elif unaided_chars <= 0:+ out["stream_cost_ms_per_kchar"] = Measure.failed(+ "ms/kchar",+ "no window streamed without a scripted action running in it, so there is no "+ "unaided streaming cost to divide",+ )+ else:+ out["stream_cost_ms_per_kchar"] = Measure.read(+ 1000.0 * blocked_ms / unaided_chars, "ms/kchar", note = unaided_note+ )++ out["stream_busy_pct"] = (+ Measure.failed("%", blocked_reason)+ if blocked_reason+ else (+ Measure.read(100.0 * blocked_ms / streaming_ms, "%", note = unaided_note)+ if streaming_ms > 0+ else Measure.failed(+ "%", "the instrument observed no unaided streaming time in this cell"+ )+ )+ )+ if frameless:+ # THE SAME RULE AS `_frame_measures`, ON THE SAME SHAPE OF WINDOW, AND FOR THE SAME REASON.+ #+ # `instruments/frames.js` emits `frames_attempted: true` with `frame_gaps_ms: []` and a+ # null `max_frame_ms` whenever the rAF loop was never scheduled in the window, and rAF+ # going unscheduled is a rendering fact, not a quiet one: on a headless engine the loop+ # runs off the rendering pipeline, so a renderer that stalls stops delivering callbacks+ # while SSE keeps arriving. Skipped rather than refused, such a window contributes no+ # deltas, no wall time and no worst frame, so the REMAINING unaided windows answer for the+ # whole streaming stretch: one frozen window beside one smooth one reported a 16.7 ms worst+ # frame and 0.0% time in jank, byte-identical to the cell without the freeze in it.+ # An unmeasured window is not an absent one. Only the three FRAME metrics are poisoned --+ # the cost, busy and character figures come from `stream_cost`, which measured this window+ # perfectly well.+ reason = (+ f"{frameless} unaided streaming window(s) recorded no frames at all (rAF may be "+ "unscheduled), so the pooled streaming frame metrics would describe only the windows "+ "that were measured"+ )+ out["stream_max_frame_ms"] = Measure.failed("ms", reason)+ out["stream_time_in_jank_pct"] = Measure.failed("%", reason)+ out["stream_jank_index"] = Measure.failed("ms", reason)+ return out++ out["stream_max_frame_ms"] = (+ Measure.read(max_frame, "ms", note = "worst frame inside the UNAIDED streaming windows")+ if max_frame is not None+ else Measure.failed("ms", "the frame recorder observed no frames streaming unaided")+ )++ if deltas and window_ms > 0:+ stats = compute_frame_stats(deltas, window_ms)+ out["stream_time_in_jank_pct"] = stats.time_in_jank_pct+ out["stream_jank_index"] = stats.jank_index+ else:+ reason = "the unaided streaming windows exported no per-frame deltas"+ out["stream_time_in_jank_pct"] = Measure.failed("%", reason)+ out["stream_jank_index"] = Measure.failed("ms", reason)+ return out++def measures_from_records(records: Sequence[Mapping[str, Any]], metric_keys: Iterable[str] | None = None) -> dict[int, dict[str, Measure]]:@@ -271,6 +606,14 @@ def measures_from_records(and str(w.get("kind") or "") not in IDLE_WINDOW_KINDS]frames = _frame_measures(windows)+ # The streaming phase is NOT in METRIC_BY_KEY, and that is deliberate rather than an+ # omission. The anchor table is hashed into `weights_id`, and a report that compares two+ # runs with different `weights_id` values is refused; adding a seventh weighted metric+ # would change every existing run's composite score and make it incomparable with every+ # run this tool has already taken. So these are scored through the per-metric floor table,+ # which judges a metric on its own floor, and the composite score is left alone. Giving+ # them anchors and a weight is a separate decision that should be argued in anchors.py.+ stream = _stream_measures(windows)readings: dict[str, Measure] = {}for key in keys:@@ -278,6 +621,8 @@ def measures_from_records(readings[key] = _action_measure(key, actions)elif key in frames:readings[key] = frames[key]+ elif key in stream:+ readings[key] = stream[key]else:readings[key] = Measure.not_attempted(METRIC_BY_KEY[key].unit, f"no source is wired for {key}"diff --git a/tests/studio/studiobench/scoring/selftest/test_studiobench_stream_metrics.py b/tests/studio/studiobench/scoring/selftest/test_studiobench_stream_metrics.pynew file mode 100644index 00000000000..b6513785adf--- /dev/null+++ b/tests/studio/studiobench/scoring/selftest/test_studiobench_stream_metrics.py@@ -0,0 +1,500 @@+# 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 streaming-phase metrics, and the ways they are supposed to REFUSE to produce a number.++Half of this file tests the failure direction on purpose. A gate that only ever passes is worse+than no gate, because it gets cited: the harness has three separate occasions on record where code+that could never fire was reported as "no effect", and every one of them would have been caught by+a test that asserted a rejection rather than an acceptance.++The rejections that matter here, each of which corresponds to a real shape in a real payload:++ * a window named `stream:gapN` with no SSE traffic in it. Eighteen of these exist per standard+ film and only the first four carry streaming, so a metric that trusts the label measures+ mostly post-stream idle.+ * `action:send_turn`, which grows the reply by about a dozen characters while spending hundreds+ of milliseconds opening things. Divided out, that is tens of thousands of ms per thousand+ characters, and it is a statement about a button.+ * `action:thread_reopen`, which rebuilds the thread so the last assistant message is REPLACED.+ Its character count can fall, and a signed delta would subtract from the denominator.+ * a cell whose timer clamp was never established, where blocked time is a subtraction against a+ floor that does not exist.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[3]))++from studiobench.scoring.from_payload import ( # noqa: E402+ MIN_STREAM_CHARS_PER_WINDOW,+ STREAM_METRICS,+ _stream_measures,+ _stream_windows,+)+++def _window(+ name: str,+ *,+ kind: str = "gap",+ duration_ms: float = 10_000.0,+ streaming_observed: bool = True,+ streaming_ms: float = 9_000.0,+ delta_task_ms: float = 900.0,+ blocked_ms: float | None = 1_800.0,+ chars_open: int | None = 0,+ chars_close: int | None = 3_000,+ attempted: bool = True,+ frame_gaps: list[float] | None = None,+ max_frame_ms: float | None = 100.0,+ clocks_agree: bool | None = None,+ timer_clock_ratio: float | None = 0.95,+) -> dict:+ sc: dict = {+ "stream_cost_attempted": attempted,+ "streaming_observed": streaming_observed,+ "streaming_ms": streaming_ms,+ "delta_task_ms": delta_task_ms,+ "sse_chunks": 120 if streaming_observed else 0,+ "reply_chars_open": chars_open,+ "reply_chars_close": chars_close,+ }+ if blocked_ms is None:+ sc["stream_blocked_ms"] = None+ sc["stream_blocked_ms_reason"] = "no timer clamp was established"+ else:+ sc["stream_blocked_ms"] = blocked_ms+ sc["stream_blocked_ms_attempted"] = True+ if chars_open is None or chars_close is None:+ sc["reply_chars_delta"] = None+ sc["reply_chars_delta_reason"] = "no assistant message was on screen"+ elif chars_close < chars_open:+ sc["reply_chars_delta"] = None+ sc["reply_chars_delta_reason"] = "the last assistant message shrank"+ else:+ sc["reply_chars_delta"] = chars_close - chars_open+ sc["reply_chars_delta_attempted"] = True++ return {+ "row_type": "window",+ "name": name,+ "kind": kind,+ "duration_ms": duration_ms,+ "instruments": {+ "stream_cost": sc,+ "frames": {+ "frames_attempted": True,+ "frame_gaps_ms": frame_gaps if frame_gaps is not None else [16.7] * 540,+ "frame_gaps_truncated": False,+ "max_frame_ms": max_frame_ms,+ "clocks_agree": clocks_agree,+ "timer_clock_ratio": timer_clock_ratio,+ },+ },+ "notes": {},+ }+++# ── what is selected as "the streaming phase" ────────────────────────────────────────────────+++def test_a_window_with_traffic_and_growth_is_the_streaming_phase():+ picked, rejected = _stream_windows([_window("stream:gap1")])+ assert len(picked) == 1+ assert rejected == {}+++def test_a_stream_named_window_with_no_traffic_is_refused():+ """THE TRAP. Every inter-slot gap is opened with kind `stream`, and most carry no streaming."""+ picked, rejected = _stream_windows(+ [_window("stream:gap12", streaming_observed = False, chars_open = 0, chars_close = 0)]+ )+ assert picked == []+ assert any("no SSE traffic" in reason for reason in rejected)+++def test_stream_drain_after_the_film_is_refused():+ """`stream:drain` is opened after the film; on a measured 100K cell it was 7 ms long."""+ picked, _ = _stream_windows(+ [+ _window(+ "stream:drain",+ duration_ms = 7.0,+ streaming_observed = False,+ streaming_ms = 0.0,+ chars_open = 194_783,+ chars_close = 194_783,+ )+ ]+ )+ assert picked == []+++def test_the_drain_is_scored_when_the_reply_outlasts_the_film():+ """The other half of the drain window, and the half `--stream-tail-chars` creates.++ The test above pins the DEFAULT shape: the tail is pinned at 6,000 characters, the reply is+ finished forty seconds before the film ends, and the drain window is 7 ms of nothing that+ `_stream_windows` refuses for having seen no traffic. Raise the tail to 96,000 -- the one+ supported way to vary reply length -- and the reply streams for 291 s at field cadence against+ a 243 s standard film, so the last 48 s of it lands in the drain window with nothing scripted+ running in it.++ That is unaided streaming, and it was dropped: `_unaided` selected `kind == "gap"` and the+ drain window is `kind = "stream"`. The characters and the cost of the last fifth of the reply+ -- the part streamed into the largest thread -- left every streaming metric, and the worst+ frame in that stretch was never seen at all.+ """+ gap = _window("stream:gap3", kind = "gap", delta_task_ms = 900.0, chars_close = 3_000)+ drain = _window(+ "stream:drain",+ kind = "stream",+ duration_ms = 48_000.0,+ streaming_ms = 47_000.0,+ delta_task_ms = 2_700.0,+ blocked_ms = 5_400.0,+ chars_open = 0,+ chars_close = 9_000,+ max_frame_ms = 640.0,+ )+ picked, _ = _stream_windows([drain])+ assert len(picked) == 1, "a drain window that really carried traffic is a streaming window"++ m = _stream_measures([gap, drain])+ assert "2 unaided streaming window(s)" in m["stream_delta_cost_ms_per_kchar"].note+ assert "12000 streamed characters" in m["stream_delta_cost_ms_per_kchar"].note+ # 3,600 ms over 12,000 characters, not 900 ms over 3,000: the drain is in the integral.+ assert m["stream_delta_cost_ms_per_kchar"].value == pytest.approx(300.0)+ assert m["stream_cost_ms_per_kchar"].value == pytest.approx(600.0)+ # A max is not a ratio, so a dropped window is a silently missing worst frame.+ assert m["stream_max_frame_ms"].value == pytest.approx(640.0)+++def test_an_action_window_is_still_not_unaided():+ """The kind filter widened by one QUIET kind, and must not have widened to the action windows.++ This is the property `_unaided` exists for. On a fast-tier 100K null, admitting the action+ windows put a 1,738 ms scroll frame into `stream_max_frame_ms` against a 286 ms unaided peak.+ """+ windows = [+ _window("stream:gap3", kind = "gap", max_frame_ms = 286.0),+ _window("stream:drain", kind = "stream", max_frame_ms = 300.0),+ _window("action:scroll_during_generation", kind = "action", max_frame_ms = 1_738.0),+ ]+ m = _stream_measures(windows)+ assert m["stream_max_frame_ms"].value == pytest.approx(300.0)+ assert "2 unaided streaming window(s)" in m["stream_delta_cost_ms_per_kchar"].note+++def test_a_window_whose_reply_shrank_is_refused_rather_than_signed():+ """`send_turn` and `thread_reopen` REPLACE the last assistant message."""+ picked, rejected = _stream_windows(+ [_window("action:thread_reopen", kind = "action", chars_open = 96_000, chars_close = 5)]+ )+ assert picked == []+ assert any("shrank" in reason for reason in rejected)+++def test_a_trivial_character_gain_is_refused():+ """The measured `action:send_turn` shape: 13 characters against 475 ms of blocked time."""+ picked, rejected = _stream_windows(+ [+ _window(+ "action:send_turn",+ kind = "action",+ chars_open = 193_548,+ chars_close = 193_561,+ blocked_ms = 475.3,+ )+ ]+ )+ assert picked == []+ assert any(str(MIN_STREAM_CHARS_PER_WINDOW) in reason for reason in rejected)+++def test_a_window_whose_clocks_disagree_is_excluded_from_scoring():+ picked, rejected = _stream_windows([_window("stream:gap1", clocks_agree = False)])+ assert picked == []+ assert any("clocks disagreed" in reason for reason in rejected)+++def test_more_timer_ticks_than_the_clamp_allows_is_excluded():+ picked, rejected = _stream_windows([_window("stream:gap1", timer_clock_ratio = 1.9)])+ assert picked == []+ assert any("clamp is wrong" in reason for reason in rejected)+++def test_a_window_the_instrument_never_ran_in_is_refused():+ picked, rejected = _stream_windows([_window("stream:gap1", attempted = False)])+ assert picked == []+ assert any("did not run" in reason for reason in rejected)+++# ── the numbers themselves ───────────────────────────────────────────────────────────────────+++def test_the_rate_is_cost_per_thousand_streamed_characters():+ m = _stream_measures([_window("stream:gap1", delta_task_ms = 900.0, chars_close = 3_000)])+ assert m["stream_delta_cost_ms_per_kchar"].value == pytest.approx(300.0)+++def test_cost_integrates_across_several_streaming_windows():+ """Two windows of 900 ms over 3,000 characters each is the same RATE as one of them."""+ one = _stream_measures([_window("stream:gap1")])+ two = _stream_measures([_window("stream:gap1"), _window("stream:gap3")])+ assert two["stream_delta_cost_ms_per_kchar"].value == pytest.approx(+ one["stream_delta_cost_ms_per_kchar"].value+ )+ # ... but the integral itself doubled, which is what the note records.+ assert "6000 streamed characters" in two["stream_delta_cost_ms_per_kchar"].note+++def test_doubling_the_per_frame_cost_doubles_the_metric():+ """The detection property. A metric that cannot move with an injected cost cannot detect one."""+ base = _stream_measures([_window("stream:gap1", delta_task_ms = 900.0)])+ heavy = _stream_measures([_window("stream:gap1", delta_task_ms = 1_800.0)])+ ratio = (+ heavy["stream_delta_cost_ms_per_kchar"].value / base["stream_delta_cost_ms_per_kchar"].value+ )+ assert ratio == pytest.approx(2.0)+++def test_a_longer_reply_at_the_same_per_character_cost_reads_the_same_rate():+ """The point of normalising. Twice the characters at twice the cost is not a regression."""+ short = _stream_measures([_window("stream:gap1", delta_task_ms = 900.0, chars_close = 3_000)])+ long = _stream_measures([_window("stream:gap1", delta_task_ms = 1_800.0, chars_close = 6_000)])+ assert short["stream_delta_cost_ms_per_kchar"].value == pytest.approx(+ long["stream_delta_cost_ms_per_kchar"].value+ )+++def test_the_broad_and_targeted_numerators_are_different_quantities():+ m = _stream_measures([_window("stream:gap1", delta_task_ms = 900.0, blocked_ms = 1_800.0)])+ assert m["stream_delta_cost_ms_per_kchar"].value == pytest.approx(300.0)+ assert m["stream_cost_ms_per_kchar"].value == pytest.approx(600.0)+++def test_busy_percent_is_over_the_streaming_time_not_the_window():+ m = _stream_measures(+ [_window("stream:gap1", duration_ms = 18_000.0, streaming_ms = 9_000.0, blocked_ms = 1_800.0)]+ )+ assert m["stream_busy_pct"].value == pytest.approx(20.0)+++def test_the_worst_streaming_frame_excludes_the_action_windows():+ """The separation this exists for: a 1,866 ms reasoning_toggle frame is not a streaming frame."""+ windows = [+ _window("stream:gap1", max_frame_ms = 100.2),+ _window(+ "action:reasoning_toggle",+ kind = "action",+ streaming_observed = False,+ chars_open = 0,+ chars_close = 0,+ max_frame_ms = 1_865.9,+ ),+ ]+ assert _stream_measures(windows)["stream_max_frame_ms"].value == pytest.approx(100.2)+++def test_an_action_running_during_generation_does_not_set_the_worst_streaming_frame():+ """MEASURED. `scroll_during_generation` runs mid-stream by design, so its window carries SSE+ traffic AND a scroll. On a fast-tier 100K null it put a 1,738 ms worst frame into this metric+ while the unaided stretch beside it peaked at 286 ms. A scroll is not a streaming stall."""+ windows = [+ _window("stream:gap3", max_frame_ms = 286.0),+ _window("action:scroll_during_generation", kind = "action", max_frame_ms = 1_738.0),+ ]+ m = _stream_measures(windows)+ assert m["stream_max_frame_ms"].value == pytest.approx(286.0)+ # And its SSE task chains are excluded from the targeted numerator too. Measured on a+ # standard-tier 10K null, an `action:keystroke` chain cost 23.77 ms per burst against 1.69 ms+ # in the gap windows either side: the chain runs until the event loop drains, so the typing+ # lands inside it and is billed to the stream.+ assert "1 unaided streaming window(s)" in m["stream_delta_cost_ms_per_kchar"].note+++# ── refusing rather than reporting zero ──────────────────────────────────────────────────────+++def test_no_clamp_means_null_with_a_reason_not_zero_cost():+ m = _stream_measures([_window("stream:gap1", blocked_ms = None)])+ assert m["stream_cost_ms_per_kchar"].value is None+ assert m["stream_cost_ms_per_kchar"].attempted is True+ assert "clamp" in (m["stream_cost_ms_per_kchar"].note or "")+ # The targeted numerator does not depend on the clamp, so it still reads.+ assert m["stream_delta_cost_ms_per_kchar"].value == pytest.approx(300.0)+++def test_a_cell_with_no_streaming_reports_not_attempted_with_every_reason():+ m = _stream_measures(+ [+ _window("stream:gap12", streaming_observed = False, chars_open = 0, chars_close = 0),+ _window("action:send_turn", kind = "action", chars_open = 10, chars_close = 20),+ ]+ )+ for key in STREAM_METRICS:+ assert m[key].value is None+ assert m[key].attempted is False+ assert "no SSE traffic" in (m["stream_cost_ms_per_kchar"].note or "")+++def test_an_empty_cell_names_that_rather_than_scoring_it():+ m = _stream_measures([])+ assert set(m) == set(STREAM_METRICS)+ assert all(v.value is None for v in m.values())+++def test_a_frameless_streaming_window_poisons_the_pooled_streaming_frame_metrics():+ """A stream window the rAF loop never ran in must not be answered for by the one beside it.++ `instruments/frames.js` emits `frames_attempted: true` with `frame_gaps_ms: []` and a null+ `max_frame_ms` when it saw no callbacks, and rAF stops being scheduled when the renderer+ stalls -- while SSE keeps arriving, so the window still qualifies as streaming. Skipped, it+ contributed no deltas, no wall time and no worst frame, and the cell came back with the other+ window's clean numbers. `_frame_measures` refuses the same shape for the cell-wide metrics.+ """+ smooth = _window("stream:gap1", frame_gaps = [16.7] * 540, max_frame_ms = 16.7)+ frozen = _window("stream:gap2", duration_ms = 4_000.0, frame_gaps = [], max_frame_ms = None)++ m = _stream_measures([smooth, frozen])+ for key in ("stream_max_frame_ms", "stream_time_in_jank_pct", "stream_jank_index"):+ assert m[key].attempted is True+ assert m[key].value is None+ assert "no frames at all" in (m[key].note or "")++ # The cost side is untouched: `stream_cost` measured that window perfectly well.+ assert m["stream_cost_ms_per_kchar"].value is not None+ assert m["stream_delta_cost_ms_per_kchar"].value is not None+ assert m["stream_busy_pct"].value is not None++ # The giveaway: without this the three above were byte-identical to the cell with no freeze.+ alone = _stream_measures([smooth])+ assert alone["stream_max_frame_ms"].value == pytest.approx(16.7)+ assert alone["stream_time_in_jank_pct"].value == pytest.approx(0.0)+++def test_a_window_the_frame_recorder_was_never_installed_in_is_still_only_skipped():+ """The control. Not-attempted is an absent instrument, not an unmeasured window."""+ smooth = _window("stream:gap1", frame_gaps = [16.7] * 540, max_frame_ms = 16.7)+ never = _window("stream:gap2", duration_ms = 4_000.0)+ never["instruments"]["frames"] = {"frames_attempted": False}+ m = _stream_measures([smooth, never])+ assert m["stream_max_frame_ms"].value == pytest.approx(16.7)+ assert m["stream_jank_index"].value is not None+++def test_a_recorder_that_died_partway_poisons_every_streaming_metric():+ """A cell whose page crashed is truncated, and a truncated cell must not report a rate.++ `_stream_windows` records why it rejected each window, but `_stream_measures` reads that only+ when NOTHING qualified. Once one window has qualified, the rejection that says the page went+ away is discarded with the rest, and the cell publishes a rate computed over the prefix that+ ran before the crash. Both halves of the rate lose the same unmeasured stretch, so the error+ does not show up as a wide interval.++ The shape is not hypothetical: 138 unaided windows in the payload corpus carry+ `TargetClosedError` or `Target crashed` after a qualifying window, with a median duration of+ 11.0 s.+ """+ good = _window("stream:gap1")+ dead = _window("stream:gap2", duration_ms = 14_000.0, attempted = False)+ dead["instruments"]["stream_cost"]["unavailable"] = (+ "TargetClosedError: Page.evaluate: Target page, context or browser has been closed"+ )++ m = _stream_measures([good, dead])+ assert set(m) == set(STREAM_METRICS)+ for key, measure in m.items():+ assert measure.attempted is True, key+ assert measure.value is None, key+ assert "stopped partway through this cell" in (measure.note or ""), key+ assert "Target page, context or browser has been closed" in (+ m["stream_cost_ms_per_kchar"].note or ""+ )++ # The giveaway: without this the crashed cell was byte-identical to the one that never+ # crashed, so nothing downstream could tell a truncated run from a complete one.+ assert _stream_measures([good])["stream_cost_ms_per_kchar"].value is not None+++def test_a_window_the_instrument_merely_skipped_does_not_poison_the_cell():+ """The control, and the reason this keys on `unavailable` rather than on not-attempted.++ Windows with no `stream_cost` reading are ordinary -- the instrument is not installed in every+ window -- and they are already handled by being left out of `picked`. Only a window that was+ instrumented and reports the recorder going away means the cell is missing a stretch it cannot+ account for. Poisoning on not-attempted alone would void most of the corpus.+ """+ good = _window("stream:gap1")+ skipped = _window("stream:gap2", duration_ms = 14_000.0, attempted = False)+ assert "unavailable" not in skipped["instruments"]["stream_cost"]++ m = _stream_measures([good, skipped])+ assert m["stream_cost_ms_per_kchar"].value is not None+ assert m["stream_max_frame_ms"].value is not None+++def test_every_declared_stream_metric_is_produced():+ m = _stream_measures([_window("stream:gap1")])+ assert set(m) == set(STREAM_METRICS)+ assert all(v.value is not None for v in m.values())+++# ── the label that caused this ───────────────────────────────────────────────────────────────+++def test_a_gap_window_is_not_labelled_stream():+ """REGRESSION. Every inter-slot gap used to be opened with `kind = "stream"`.++ Eighteen of them exist on the standard film and only the first four contain streaming, so the+ label sent anyone filtering on it to a pool of mostly post-stream idle. It is now `gap`, and+ `stream` is left to `stream:drain`, which is the only window the session layer opens that is+ genuinely about the stream.+ """+ from studiobench.runtime.types import WINDOW_KINDS+ from studiobench.scene.schedule import SceneRunner++ assert "gap" in WINDOW_KINDS++ opened: list[tuple[str, str]] = []++ class _Window:+ notes: dict = {}++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False++ def note(self, *_args, **_kwargs):+ return None++ def _open(name, kind):+ opened.append((name, kind))+ return _Window()++ runner = SceneRunner(+ cell = None,+ page = None,+ cdp = None,+ dom = None,+ recorder = None,+ open_window = _open,+ log = lambda _m: None,+ )+ runner._census = lambda: {}+ # A gap far enough ahead that the scheduler actually opens a window for it.+ runner._gap_window("stream:gap12", until_ms = 300, t0 = __import__("time").monotonic())++ assert opened, "the scheduler opened no window for a gap that was wide enough to need one"+ name, kind = opened[0]+ assert kind == "gap"+ assert kind != "stream"diff --git a/tests/studio/studiobench/sweep/floor_table.py b/tests/studio/studiobench/sweep/floor_table.pyindex 8bb35094ad1..b626261ca30 100644--- a/tests/studio/studiobench/sweep/floor_table.py+++ b/tests/studio/studiobench/sweep/floor_table.py@@ -29,6 +29,7 @@ from __future__ import annotationsimport argparseimport collectionsimport json+import mathimport statisticsimport sysfrom pathlib import Path@@ -43,11 +44,37 @@ from tests.studio.studiobench.scoring.from_payload import ( # noqa: E402ACTION_SOURCES,FRAME_METRICS,IDLE_WINDOW_KINDS,+ STREAM_METRICS,_actions_for,_frame_measures,+ _stream_measures,)-METRICS = tuple(ACTION_SOURCES) + FRAME_METRICS+METRICS = tuple(ACTION_SOURCES) + FRAME_METRICS + STREAM_METRICS++# The metrics compared by DIFFERENCE rather than by ratio, because zero is their CLEAN reading.+#+# Everything else here is a duration, and a duration is zero only when nothing happened. Jank is+# the opposite: a stream that never dropped a frame reports exactly 0.0, and that is the reading a+# good build is supposed to produce. Measured on this repository's recorded payloads,+# `stream_time_in_jank_pct` is exactly 0.0 on 765 of 1,438 scored cells, and 349 of 668 base-vs-+# treatment pairs across 117 payload files have a zero base arm.+#+# Paired as a ratio those pairs cannot survive: `t / 0.0` is undefined, so `paired` dropped them,+# and dropping them is not a conservative choice. It removes exactly the comparisons where the base+# was CLEAN -- the ones a treatment that introduces jank shows up in -- so a regression from 0.0%+# to 12.0% left no row at all, and a run where only some repetitions had a zero base kept the rest+# under the same `n`, pooling a metric over a set whose membership depends on the base arm's value.+#+# A difference is defined from zero, so these are pooled as `treatment - base` in the metric's own+# unit, for EVERY pair rather than only the zero ones: mixing the two within one mean would be a+# second unstable pool. The null control's floor is computed the same way, so the gates compare+# like with like, and the table marks these rows so the column is not read as a percentage change.+#+# Scoped to the two streaming metrics this file has just started harvesting. `time_in_jank_pct`+# has the same shape and loses 3% of its pairs, but it is already published against ratio-based+# floors, and re-basing it would silently re-score every table taken so far.+DIFFERENCE_METRICS: frozenset[str] = frozenset({"stream_time_in_jank_pct", "stream_jank_index"})def _action_timings(records: list[dict], cid: str) -> dict[str, float]:@@ -119,6 +146,13 @@ def cell_metrics(records: list[dict]) -> dict[str, dict[str, float]]:for key, m in _frame_measures(windows).items():if m.value is not None:vals[key] = float(m.value)+ # The streaming phase on its own, per streamed character. Kept separate from the pooled+ # frame metrics rather than replacing them: the pooled ones answer "was this film janky",+ # which is still worth asking, and these answer "what did streaming one character cost",+ # which nothing answered before.+ for key, m in _stream_measures(windows).items():+ if m.value is not None:+ vals[key] = float(m.value)out[cid] = valsreturn out@@ -176,7 +210,13 @@ def paired(records: list[dict], shard: str = "") -> dict[str, list[tuple[float,continuefor metric in set(sides["base"]) & set(sides["treatment"]):b, t = sides["base"][metric], sides["treatment"][metric]- if b:+ # `if b` is a ratio's precondition, not a validity test: a zero base is a real reading+ # for the jank metrics and only an undefined DENOMINATOR. Those are compared by+ # difference (see DIFFERENCE_METRICS), so they are kept whenever both sides are finite.+ if metric in DIFFERENCE_METRICS:+ if math.isfinite(b) and math.isfinite(t):+ out[metric].append((b, t))+ elif b:out[metric].append((b, t))return out@@ -272,6 +312,42 @@ def summarise(paths: list[Path]) -> dict[str, dict[str, float]]:out: dict[str, dict[str, float]] = {}pooled, _tiers = load(paths)for metric, rows in pooled.items():+ if metric in DIFFERENCE_METRICS:+ # Same three quantities, same three gates, measured in the metric's own unit because a+ # ratio from a clean zero base does not exist. `delta_pct` and `spread_pct` are then+ # percentage POINTS (or ms), which is why `render` marks the row.+ diffs = [t - b for b, t in rows]+ # A TIE IS NOT A DISAGREEMENT, AND HERE THE TIE IS THE MODAL READING.+ #+ # The ratio branch below asks `all(r > 1) or all(r < 1)`, and that is sound there+ # because a paired ratio of exactly 1.0 is vanishingly rare for a continuous timing.+ # Reused verbatim on differences it stops being sound, because the tie value is 0.0+ # and 0.0 is what a CLEAN reading of these metrics is: `stream_time_in_jank_pct` is+ # exactly 0.0 on 765 of 1,438 scored cells, so a repetition where neither arm dropped+ # a frame contributes a difference of exactly 0.0.+ #+ # A group of `[0.0, 12.0]` then failed both halves of the strict test and was reported+ # as VOID (pairs disagree on sign), which is not what happened: nothing moved the other+ # way, some repetitions were unchanged and the rest regressed together. Measured over+ # the recorded payloads, that voided 34 of 250 pooled groups, 13.6%, and every one of+ # the 34 came from a tie rather than from a real disagreement. Intermittent and+ # load-dependent jank is exactly the shape that produces ties, so the predicate was+ # discarding the regressions it was most needed for.+ #+ # Direction is therefore "no pair went the other way", with at least one that moved,+ # so an all-zero group stays inconsistent rather than being scored as a finding.+ nonzero = [d for d in diffs if d != 0.0]+ out[metric] = {+ "n": len(rows),+ "base": statistics.fmean(b for b, _ in rows),+ "treat": statistics.fmean(t for _, t in rows),+ "delta_pct": statistics.fmean(diffs),+ "consistent": bool(nonzero)+ and (all(d >= 0.0 for d in diffs) or all(d <= 0.0 for d in diffs)),+ "spread_pct": max(diffs) - min(diffs),+ "difference": True,+ }+ continueratios = [t / b for b, t in rows]out[metric] = {"n": len(rows),@@ -285,6 +361,7 @@ def summarise(paths: list[Path]) -> dict[str, dict[str, float]]:# The spread of the paired ratios. From a null control it is the detection floor; from# a real comparison it is the effect's own scatter, which is GATE 3."spread_pct": (max(ratios) - min(ratios)) * 100.0,+ "difference": False,}return out@@ -360,10 +437,16 @@ def render(print(head + (" floor % verdict" if floors else ""))print(" " + "-" * (len(head) + (26 if floors else 0)))survivors = 0+ marked = Falsefor metric in sorted(stats, key = lambda m: (m in METRICS, m)):s = stats[metric]+ # A difference row is named as one. Its delta is in the metric's own unit, and printing it+ # under a "delta %" heading would be the same class of mistake this file exists to stop.+ label = metric+ if s.get("difference"):+ label, marked = metric + " (abs)", Trueline = (- f" {metric:<28}{s['n']:>3}{s['base']:>11.1f}{s['treat']:>11.1f}"+ f" {label:<28}{s['n']:>3}{s['base']:>11.1f}{s['treat']:>11.1f}"f"{s['delta_pct']:>+10.1f}{s['spread_pct']:>10.1f}")if floors is not None:@@ -372,6 +455,12 @@ def render(if verdict in ("faster", "SLOWER", "LOST (invariant fell)", "gained"):survivors += 1print(line)+ if marked:+ print(+ "\n (abs) = compared by DIFFERENCE, in the metric's own unit rather than as a "+ "percentage\n change: zero is these metrics' clean reading, and a ratio from "+ "zero does not exist."+ )if floors is not None:print(f"\n {survivors} metric(s) cleared all three gates.")return survivorsdiff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.pyindex 60808f95e61..65338cbacd6 100644--- a/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.py+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.py@@ -507,6 +507,130 @@ def frame_window(cid: str, kind: str, gaps: list[float], duration_ms: float, **ereturn row+def stream_window(+ cid: str,+ gaps: list[float],+ duration_ms: float = 10_000.0,+) -> dict:+ """One qualifying, unaided streaming window: SSE traffic plus enough reply growth."""+ return {+ "row_type": "window",+ "cell_id": cid,+ "kind": "gap",+ "name": "stream:gap1",+ "duration_ms": duration_ms,+ "instruments": {+ "stream_cost": {+ "stream_cost_attempted": True,+ "streaming_observed": True,+ "streaming_ms": 9_000.0,+ "delta_task_ms": 900.0,+ "stream_blocked_ms": 1_800.0,+ "reply_chars_delta": 3_000,+ },+ "frames": {+ "frames_attempted": True,+ "frame_gaps_ms": gaps,+ "frame_gaps_truncated": False,+ "max_frame_ms": max(gaps),+ },+ },+ }+++def stream_payload(tmp_path: Path, name: str, pairs: list[tuple[list, list]]) -> Path:+ rows: list[dict] = [{"row_type": "run_meta", "tier": "standard", "corpus_hash": "c0"}]+ for i, (base_gaps, treat_gaps) in enumerate(pairs):+ for arm, gaps in (("base", base_gaps), ("treatment", treat_gaps)):+ cid = f"100K.{arm}.rep{i}"+ rows.append({"row_type": "cell", "cell_id": cid, "completed": True})+ rows.append(stream_window(cid, gaps))+ return write(tmp_path, name, rows)+++SMOOTH = [16.7] * 540 # a clean stream: stream_time_in_jank_pct is exactly 0.0+JANKY = [16.7] * 530 + [120.0] * 10+++def test_a_clean_zero_base_arm_still_pairs_so_a_jank_regression_is_not_lost(tmp_path):+ """Zero is these metrics' CLEAN reading, and `if b` dropped every pair that had one.++ Measured on this repository's recorded payloads, 349 of 668 `stream_time_in_jank_pct` pairs+ have a zero base arm. Dropped, a treatment that introduces jank against a clean base left no+ row in the table at all, and where only some repetitions had a zero base the metric was pooled+ over whichever pairs the BASE arm happened to make non-zero.+ """+ result = stream_payload(tmp_path, "result", [(SMOOTH, JANKY)] * 4)+ null = stream_payload(tmp_path, "null", [(SMOOTH, SMOOTH)] * 4)++ pairs = F.paired(F.read_rows(result))+ assert pairs["stream_time_in_jank_pct"] == [(0.0, 12.0)] * 4+ assert len(pairs["stream_jank_index"]) == 4++ stats, floors = F.summarise([result]), F.summarise([null])+ s = stats["stream_time_in_jank_pct"]+ assert s["n"] == 4+ # Compared by DIFFERENCE, in the metric's own unit: 0.0% to 12.0% is +12.0 points.+ assert s["difference"] is True+ assert s["delta_pct"] == pytest.approx(12.0)+ assert "stream_time_in_jank_pct" in floors+ _f, v = F.verdict_for(s, floors["stream_time_in_jank_pct"])+ assert v == "SLOWER"+++def test_an_unchanged_repetition_does_not_read_as_a_pair_disagreeing_on_sign(tmp_path):+ """REGRESSION. A difference of exactly 0.0 is a TIE, and ties are the modal reading here.++ `all(d > 0) or all(d < 0)` is the right question for ratios, where an exact 1.0 essentially+ never occurs. On differences of a metric whose clean value IS 0.0 it voided a group the moment+ any repetition was unchanged: `[0.0, 12.0]` failed both halves and printed+ VOID (pairs disagree on sign) although nothing moved the other way. Measured over the recorded+ payloads that hit 34 of 250 pooled groups, and all 34 were ties rather than disagreements.++ WHAT THIS DOES AND DOES NOT BUY, measured rather than assumed. Of the 34 groups, ZERO change+ their verdict: a tie drags the spread above the mean, so GATE 3 voids every one of them for+ scatter instead. That is the correct gate doing its job, and it is why this fixes the REASON+ a comparison was refused rather than surfacing a regression. A tool whose refusal states+ something that did not happen is reporting a wrong answer in the right vocabulary, which is+ worth three lines on its own; it is not worth relaxing gate 3 to chase.+ """+ # Two repetitions clean on both arms, two that regress. Nothing regresses the other way.+ result = stream_payload(tmp_path, "result", [(SMOOTH, SMOOTH), (SMOOTH, JANKY)] * 2)+ null = stream_payload(tmp_path, "null", [(SMOOTH, SMOOTH)] * 4)++ s = F.summarise([result])["stream_time_in_jank_pct"]+ assert sorted(t - b for b, t in F.paired(F.read_rows(result))["stream_time_in_jank_pct"]) == [+ 0.0,+ 0.0,+ 12.0,+ 12.0,+ ]+ assert s["consistent"] is True, "an unchanged repetition is a tie, not a disagreement"+ _f, v = F.verdict_for(s, F.summarise([null])["stream_time_in_jank_pct"])+ # Still refused, and that is right, but no longer refused for a reason that did not occur.+ assert v == "VOID (effect under its own scatter)"+ assert v != "VOID (pairs disagree on sign)"+++def test_a_group_that_did_not_move_at_all_is_still_not_a_finding(tmp_path):+ """The other side of the tie rule: all-zero differences must not become 'consistent'.++ Relaxing to `>=` alone would score a metric that never moved as a directional result.+ """+ result = stream_payload(tmp_path, "result", [(SMOOTH, SMOOTH)] * 4)+ s = F.summarise([result])["stream_time_in_jank_pct"]+ assert [t - b for b, t in F.paired(F.read_rows(result))["stream_time_in_jank_pct"]] == [0.0] * 4+ assert s["consistent"] is False+++def test_a_ratio_metric_still_drops_a_zero_base_rather_than_dividing_by_it(tmp_path):+ """The control: only the metrics whose zero is a clean reading changed."""+ result = stream_payload(tmp_path, "result", [(SMOOTH, JANKY)] * 4)+ pairs = F.paired(F.read_rows(result))+ assert F.summarise([result])["stream_max_frame_ms"]["difference"] is False+ assert all(b > 0.0 for b, _ in pairs["stream_max_frame_ms"])++def test_the_enforced_idle_window_is_not_pooled_into_the_frame_metrics(tmp_path):# Every cell records a 1.5 s `idle:calibrate` window with the frame recorder running. Pooling# its quiet into the film halves the jank share, so the column would not be the quantity the