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: a readiness gate that can admit a windowed thread, and three instruments that were charging their own cost to the app (#9439)
Daniel Hanc58a6494a8c5
diff --git a/tests/studio/studiobench/CONTRIBUTING-perf.md b/tests/studio/studiobench/CONTRIBUTING-perf.mdindex 37e9fb196bc..2f6d6ed8ecb 100644--- a/tests/studio/studiobench/CONTRIBUTING-perf.md+++ b/tests/studio/studiobench/CONTRIBUTING-perf.md@@ -133,8 +133,37 @@ were junk.## 4. Parity: prove you did not change what is rendered-A performance change that alters what the user sees is a different pull request with a different-review. Run the parity digest, which takes a normalised structural DOM signature per action window+### The policy, and the two exemptions++**UI and UX idempotency is required for every change, with exactly two exemptions:**++1. **A deliberate difference accepted for a dramatic performance improvement.** This is a decision+ somebody makes on the record with the number attached, not a default. If you are relying on it,+ say so in the pull request and say what the difference is.+2. **A difference that exists only OFF SCREEN.** This one is a definition rather than a judgement:+ rendering only what is visible is an accepted technique, not a parity violation.++Neither exemption removes the need for a floor. An exemption changes what counts as a pass; it does+not make an unmeasured claim into a measured one, so the null control still has to run on the same+scale.++**A bare "PARITY OK" reads far stronger than any of the three modes can support**, which is why+each mode prints the CLAIM it is making and the POLICY it is judging against, and why you should+read both before quoting a pass:++| mode | what a pass means | can it grant the off-screen exemption? |+|---|---|---|+| `--mode digest` | the thread root and declared overlays serialise identically, on screen and off | no, it does not know what was on screen |+| `--mode visible` | every message the viewport showed is present and identical, and every difference lies off screen | **yes** -- this is the mode that can say so |+| `--mode behaviour` | scroll extent matches and the invariants a windowed mount breaks first still hold | no, and it says nothing about appearance |++The digest is **sidebar-blind and layout-blind**: run against a real sidebar-drag change it reported+0 of 34 differing pairs, and so did its own null control. So a digest pass is not a statement that+the UI is unchanged.++### The digest itself++Run the parity digest, which takes a normalised structural DOM signature per action windowon both arms and compares them.What the digest **can** see: tag structure, `data-slot`, `data-state`, `data-role`, classes, text.@@ -276,6 +305,88 @@ Related: rank frames by **slope, not size**. `findNextMatchSync` is the second-l100K rung at 1,365 ms, and it is a floor, not a cause: it grows at 3.52x against a 3.83x aggregate.Optimising it would shave a constant off a curve whose shape is set elsewhere.+### A stress action is not a user journey++`reasoning_toggle` runs at **2.2 fps** at the 100K rung, with a p95 frame of 2,084 ms. It is the+worst number this harness produces, and it has been quoted as though it described what a user feels.+It does not.++The action opens **every reasoning pane in the thread in one gesture**: 10 panes, materialising+74,917 highlight spans, 2,143 ms to open and 805 ms to close. No user does that. A user expands one+pane. So 2.2 fps is a legitimate measurement of a deliberate worst case and an illegitimate answer+to "how slow is opening a reasoning pane". **We do not currently have that second number**, and a+single-pane variant is the cheapest way to get it: the blocker is not the action, it is that the+film is a fixed-duration slot schedule, so a new slot shifts every existing window and voids+comparability against every payload already on disk. Add it as a registered action first and run it+in a purpose-built film; fold it into the standard scene only at the next corpus or tier bump, when+the payloads are being invalidated anyway.++The general rule: before quoting any action's number as a user-facing latency, read what the action+actually does. Several of them are stress gestures by design, because a stress gesture is the only+way to make a mechanism's slope visible above the noise.++### What the fixture over- and under-states++The corpus is not a real thread and it is shaped differently from one in two directions that do not+cancel.++- **Span density is 4.69 characters per highlight span against the generator's 5.6 target**, so the+ fixture carries about **19% more highlight spans per character of code** than it is meant to.+ Every syntax-highlighting number in this campaign, including the fence-deferral arm's `pre span`+ and LayoutObjects reductions, is measured against that inflated span count and **overstates the+ win by roughly that much**. Read those numbers with this beside them.+- The corpus reaches its rung with **too few, uniformly large messages**: at the 100K rung the nine+ assistant turns run 11,374 to 126,203 characters with a median of 36,215, and none is small. Real+ threads carry many short turns. The total size is right; the distribution is not.+- Because there are 18 messages rather than the hundreds a real thread of that size would hold,+ **per-message chrome is about 1.5% of the fixture's DOM against roughly 14% of a real one**. So+ the fixture **understates** total DOM size, which is the conservative direction for any change+ that reduces element counts.++Anything **per-message** (menus, hover targets, avatars, action bars, virtualization row overhead)+is therefore measured on a document that has far too few of them, and should not be extrapolated+from this corpus without saying so.++### One home per arm, or the A/B compares a build against itself++`install_studio` derives its repo checkout from the home directory, so **two arms sharing one+`--home` share one checkout**. The second install overwrites the first and both arms then serve+whichever build was installed last. Every number downstream is then a comparison of a build with+itself: parity matches, invariants agree, timings sit on top of each other, and none of it means+anything.++It is invisible in the payload, and it looks like the result you were hoping not to get. Two runs+of the same pair reported **716 ms and 718 ms** for base and treatment in one, and **2,583 ms and+2,614 ms** in the other -- nearly equal *within* each run and 3.6x apart *between* them, because+each run was internally uniform and the two runs were serving different builds. Read as a+within-run comparison it says the change does nothing. The difference was sitting between the runs+the whole time.++`--ab` now refuses `--home` outright. Left to itself the harness gives each arm its own+`studio_home_<label>` under `--out`, which is what you want.++**The general rule this is an instance of:** before believing a null result, confirm the two arms+could have differed. A comparison that was structurally incapable of showing a difference will+report agreement with total confidence.++### One engine per comparison++Nothing in the payload format stops you from scoring a Chromium arm against a WebKit one. The engine+is recorded in the run-level `platform` header and **not** on the cell rows, and both `sweep/ab.py`+and `sweep/floor_table.py` pool shards by glob without looking at it. A directory glob such as+`outputs/sbench_v*` will happily merge the two.++This has produced exactly one wrong kind of number so far, and it is the worst kind: Playwright's+WebKit never performs a clipboard copy on Control+C, so `select_all_copy` measured the harness's own+250 ms settle and reported it as `copy_ms` -- 258.5 ms at 1K, 258.8 ms at 10K, 263.9 ms at 100K+across 43 rows. A hundredfold change in the quantity under study moved the "measurement" by 2%,+because it was measuring a `sleep`. Chromium reads about 1,538 ms for the same action at 100K. A+stable wrong number is much harder to catch than a missing one.++The action now refuses instead: a clipboard sentinel is written before the keystroke, and if it+survives the row is **NOT RUN** with a reason, on any engine, with no engine list to maintain. Until+`ab.py` and `floor_table.py` check the header too, **check it yourself** before pooling shards.+## Ablation: correlation to causationA hot frame with a steep slope is a lead. To make it a finding, remove the mechanism and watch the@@ -491,3 +602,56 @@ confound unless you contain it:- Anything that did not run, said plainly.A result quoted without its floor will be asked for its floor.++## Recorded negative result: do not virtualize the message list++Somebody proposes this roughly once a campaign, and the argument is good: a 100K thread stands+64,707 elements in the DOM, most of them off screen, so mount a window instead. It was built, it+was measured at the 100K rung on the standard tier with a concurrent in-band null control, and it+was rejected. The measurements are here so the next person can decide from evidence rather than+rebuild it to find out.++**It buys what it says it buys.** 54,015 elements against the base arm's 64,707. `select_all_copy`+went from 6.1 to 31.6 fps, a p95 frame of 2,284 ms down to 58 ms. Headline 28.2% faster, weighted.++**It costs the thing the campaign exists to fix.** `send_turn` went from 61.1 to 37.3 fps, with the+p95 frame rising from 34.0 ms to 374.8 ms, while the concurrent null moved -3.9% on the same+window. Reproduced on two independent runs. Streaming at long context is the whole complaint, and+this made it worse by more than anything else on the page got better.++The mechanism, measured rather than guessed. It is NOT per-chunk: every `stream:gap*` window, the+windows in which the reply is actually streaming into a growing last row, is flat (+0.2%, -0.1%,++0.6%). It is a ONE-TIME cost at the first append into a freshly opened thread: the eight treatment+readings alternate 13.2, 58.9, 13.7, 62.0, 14.6, 59.8, 14.7, 60.9 fps, two sends per cell, first+expensive and second free. A direct probe put the cost in RECALC STYLE (60 ms against the base+arm's 14 ms) and not in layout (2 ms on both) and not in measurement callbacks (2 ResizeObserver+callbacks, 3 style writes). Appending to a windowed, end-anchored list re-renders and re-positions+every mounted row; the unvirtualized path appends one node and touches nothing that already exists.+The first append also resolves size estimates that are badly wrong: `estimateSize` is 460 px and+the fixture's mounted rows measure a median of 2,379 px, a mean of 5,146 px and a maximum of+21,132 px.++**It loses the thread.** On the treatment arm the census goes from 12 mounted messages to 0 at the+`model_change` slot and never recovers: 2,107 elements for the remaining four slots of the film,+all four reps, both runs, while the concurrent null keeps all 25 messages through the same action.+Visible-region parity reports it as a difference rather than a refusal. Two caveats kept with the+finding: `model_change` is the weakest selector in the suite by its own docstring, and in these+runs it selected an option labelled "Search Hub", which is not a chat model, so this is "the+windowed arm did not survive an interaction the base arm survived" and not "changing the model+empties a virtualized thread". It was not chased further because the arm was closed.++**Three of eighteen actions could not be measured on it.** `delete_message` and `thread_reopen` ran+four times on the base arm and zero times on the treatment; `image_upload` ran on neither. Any+per-window comparison must drop those rather than compare a busy window against an empty one.++**And two accessibility and correctness obligations come with it.** A windowed list must publish+`aria-setsize` and `aria-posinset` or the accessibility tree reports a forty-turn conversation as+the six messages that happen to be mounted. Select-all copy must be served from the message store,+because a windowed DOM cannot select what it has not mounted: measured at 0.61 of the thread before+the fix. The obvious store serialiser is the "save this reply" one, which emits reasoning and+tool-call payloads that no user can select, and it lands at 2.16 of the thread instead. Both+failure directions are now bounds on `clipboard_carries_the_whole_thread`.++If you want the structural win without any of this, defer off-screen work instead of unmounting it.+Score it with `sweep/ui_parity.py --mode visible --null OUTDIR`: an off-screen-only difference is+exempt by policy, and that mode is the one that can say so.diff --git a/tests/studio/studiobench/INTERFACES.md b/tests/studio/studiobench/INTERFACES.mdindex 24b2887cbd1..8e5e819ffea 100644--- a/tests/studio/studiobench/INTERFACES.md+++ b/tests/studio/studiobench/INTERFACES.md@@ -309,7 +309,295 @@ An instrument that caches `page` must re-read it in `start_cell`, not in `attach----## 8. Stability+## 8. The readiness gate, and what a WINDOWED arm must publish++Before any window opens, the session layer waits for the thread to be ready. Until now that meant+"every seeded message is mounted", which an arm that virtualises the message list can never+satisfy: it mounts a window by design, so the count never arrives and the cell dies before the+film starts. The gate is now four conditions rather than one count, and it runs in one of two+modes. See `runtime/readiness.py` for the full argument.++`full` is the default and is what every normal arm runs. It is STRICTLY STRONGER than what shipped:+every seeded message mounted, PLUS the thread settled (two samples 600 ms apart agreeing on the+mounted count, the element count and the viewport's scrollHeight) and the end of the thread present+(the marker `runtime/seeder.turn_marker` wrote into the last user turn is in the mounted set, at+its end).++`windowed` is requested per arm with `--windowed-arm treatment`. It drops the mounted-count+condition and adds four:++| condition | what it requires |+| --- | --- |+| `total_declared` / `total_matches_seeded` | every mounted `[data-role]` carries `aria-setsize`, all agreeing, equal to the number of messages the seeder wrote. Waived only when the whole thread is mounted anyway, which is the full-mount condition itself |+| `posinset_on_every_row` | every mounted message carries `aria-posinset` |+| `anchored_at_end` | the app reports itself at the bottom (`.aui-thread-scroll-to-bottom` carrying `invisible`), falling back to the scrollTop arithmetic only when it does not |+| `pin_settled` | `--aui-scroll-stabilizer` is off the viewport, i.e. the autoscroll has finished pinning |++**This is a contract the arm must meet, not a signal that exists today.** Studio ships no+virtualization and no ordinal attributes anywhere in the chat thread. WAI-ARIA already requires a+list whose items are not all in the DOM to publish `aria-setsize` and `aria-posinset`, so an arm+that omits them is unusable with a screen reader whatever it does to the frame rate, and refusing+to score it is the correct answer rather than an inconvenience.++Once per cell, before the idle window, a `windowed` arm additionally runs+`probe_thread_completeness`: it scrolls to the top of the thread and requires the FIRST message to+mount. Standing at the bottom, a correct virtualizer and a thread that has lost its history look+identical, and this is the only reading that separates them. It is reported as a `thread_complete`+gate row, not raised.++The head marker is not the whole verdict. A store that kept the first page and the last one and+lost everything between them mounts the head on demand, so the traversal also records the+`aria-posinset` of every row it passes and `ordinal_coverage` reports what that covers.+`ordinal_coverage_complete` stays three-valued, and `ordinal_coverage_state` says which kind of+`None` a `None` is:++| state | verdict | scored? |+| --- | --- | --- |+| `complete` | every seeded ordinal was mounted somewhere on the way up | yes |+| `incomplete` | an ordinal is missing that the sweep was in a position to see, so the arm has lost it | no, and the cell is excluded |+| `not_applicable` | no row published an `aria-posinset` at all. A fully mounted thread publishes none anywhere, so the question does not arise | yes |+| `unmeasured` | the question arises and the sweep could not answer it: the gesture stopped short of the top, or consecutive stops did not overlap so the middle was never in view | **no** |++`unmeasured` used to pass, which let the first-page-and-last-page store back in through the unknown+state: the marker arrives, the sweep never looks, the cell stays scoreable. It does not any more,+and the remedy for a coarse sweep is a smaller `step_px`, not a softer gate. The distinction is the+reason a blanket "None fails" would be wrong -- it would fail the shipped build, which publishes no+ordinals, on every cell it is pointed at.++New payload keys, all additive: `readiness` and `completeness` on the cell row,+`ordinal_coverage_state` on that `completeness` and on the `thread_complete` gate's detail,+`unplaced_rows` on every visible-region capture, `mounted_messages`+and `thread_total` on every parity capture, `mounted_before` / `mounted_after` on `send_turn`,+`delete_message` and `thread_reopen`, `left_via` / `reopened_via` / `reopen_ready_mode` /+`reopen_readiness` on `thread_reopen`, `visible` on every action row, `observation_ms` on every+action row, `stream_samples` / `attached_fraction_of_stream` / `reattachments` on the cell's+`follow`, `reply_chars_scoreable` / `wire_parse_failures_in_window` /+`wire_pending_chars_at_close` on every `stream_cost` window, and the gate rows+`thread_ready:{mode}`, `thread_complete`, `follows_the_stream` and `windowed_readiness:{arm}`.++**What `thread_reopen` measures.** `reopen_ms` runs from the click on the thread's sidebar row+until the reopened thread satisfies the SAME readiness gate the cell opened with -- composer+present, end present, and settled across two samples -- in whichever mode that arm's own mount is+in. It deliberately does not treat the thread's declared total as completion: on a windowed arm+`threadTotal()` returns `aria-setsize`, which is the store's claim about how long the conversation+is and not evidence that anything has been rebuilt, so the old condition could be satisfied by the+first reopened row and the action timed a half-built DOM while still passing its own assertion.+Reusing the gate rather than writing a second definition of "ready" is deliberate: two disagreeing+definitions in one harness would be a defect of its own. The cost is a floor of one+`STABLE_GAP_MS`, paid equally by both arms.++**A rebuild that never finished is not a passed invariant.** When the gate times out, the row keeps+`ran = True` with `expect_ok = False`, a null `reopen_ms` and the outstanding conditions under+`expect.reopen_readiness` -- and `messages_before` and `messages_after` UNCHANGED, because both are+`threadTotal()`, the total the store declared. `analysis/behaviour.py` therefore requires evidence+that the rebuild completed (`reopen_readiness.ready`, or `expect_ok` on a payload that predates it)+before it counts equal counts as the invariant holding; without it the pair is NOT COMPARABLE, not+a match. Counts that DISAGREE stay BROKEN whatever the gate said, because a thread that came back+shorter than it left is the data loss this invariant exists for.++**When the New chat control cannot be clicked**, `thread_reopen` declines the substitute rather+than detecting it afterwards. `_click_or_navigate` takes `allow_navigate` (default True, so every+other caller is unchanged) and the LEAVE call passes False: nothing is clicked, nothing is+navigated, and the thread stays mounted for the slots that follow. Refusing to score a measurement+must not cost the actions after it -- the earlier version navigated first and then refused, leaving+the scene on an empty thread and taking `delete_message` down with it. The RETURN leg keeps its+navigation, because from an empty new-chat page that is what puts the thread back; it is still+reported NOT RUN with no timing.++`window.__sb.dom.threadTotal()` is the thread's LENGTH as opposed to how much of it is mounted:+`aria-setsize` when published, `messageCount()` otherwise. On the shipped build the two are the+same number. Every before/after assertion in `scene/actions.py` now asks `threadTotal()`, because+"the thread grew" and "the message was deleted" are statements about the conversation and a+windowed mount answers them about the viewport.++**Structural UI parity is NOT APPLICABLE to a windowed arm.** `analysis/parity.py` returns the+verdict `not_applicable` for such a pair rather than reporting a difference on every action, and+`sweep/ui_parity.py` detects it from the payload and switches to `analysis/behaviour.py`: the+scroll extent, plus the invariants on `select_all_copy`, `select_text`, `copy_markdown`,+`thread_reopen` and `scroll_after`. What is no longer being asked is whether the mounted messages+render identically.++**What a PARITY OK verdict actually claims.** It claims that NO THREAD-STRUCTURE CHANGE WAS+DETECTED. It does not claim the UI is unchanged, and the gap between those two readings is wide+enough that the second must never be written down on the strength of the first.++`scene/parity.js` digests the thread root and the overlay selectors. It is sidebar-blind and+layout-blind by construction, and it never reads geometry or CSS custom properties. This has been+measured, not merely assumed: run against a real, visible sidebar-drag change, the shipped thread+digest returned 0 of 34 differing pairs -- and the concurrent null control also returned 0 of 34,+so the instrument was not discriminating in either direction. Three purpose-built captures+(sidebar-inclusive structure, sidebar inline style, custom-property reach) each found the same+change 34 of 34 with the null at zero.++Not covered, and not detectable by this digest at all:++| surface | why |+| --- | --- |+| the sidebar, header, toasts | outside the digest root |+| computed layout and geometry | positions, sizes and overflow are never read |+| CSS custom properties | never read |+| stylesheet changes | only via the bounded style probe: three properties (`display`, `visibility`, `pointer-events`) on at most 64 elements, reported separately and as an advisory |+| raster content, colour, typography, animation | not in the DOM |++A change confined to any of those needs its own capture. `sweep/ui_parity.py` prints this+limitation next to the passing verdict rather than leaving it in a source comment.++### The policy, and the three claims++All changes must preserve UI and UX idempotency, with two exemptions:++1. a UI difference may be accepted DELIBERATELY when performance improves dramatically;+2. a difference that exists only OFF SCREEN is fine by definition, because rendering only what is+ visible is an accepted technique rather than a parity violation.++The whole-document digest cannot express exemption 2. It compares everything in the DOM, so every+deferred-off-screen technique fails it by construction: virtualization, deferred fence+highlighting, `content-visibility`, lazy images. Answering NOT_APPLICABLE withholds a verdict+rather than giving one, so there is now a mode that gives one.++`sweep/ui_parity.py --mode auto|digest|visible|behaviour`. Every report prints the CLAIM it is+making AND the POLICY it is being judged against, because "PARITY OK" has meant three different+things in this file's history and none of them is "the UI is unchanged". The claim says what was+compared; the policy says what a pass is worth, and the two exemptions are what decide that. Only+the `visible` mode can GRANT the off-screen exemption, and its policy line says so, together with+the reminder that the exemption does not remove the floor. `analysis/parity.py` holds both as+`POLICY` and `POLICY_BY_MODE`, and a test fails if any mode prints a claim without a policy beside+it -- a constant nothing prints is a constant nobody reads.++| mode | claim | fails on |+| --- | --- | --- |+| `digest` | thread-structure parity: the thread root and the declared overlay selectors are identical, on screen and off. NOT the sidebar, NOT computed layout or geometry, NOT CSS custom properties | any DOM difference it can see, on screen or off |+| `visible` | every message the viewport showed during the action is present on both arms and identical; every difference lies off screen | a difference the user could see |+| `behaviour` | the scroll extent matches and the invariants a windowed mount breaks first still hold. Says NOTHING about how anything looks | a broken invariant, e.g. a truncated clipboard |++`auto` decides PER ACTION PAIR, not per payload and not per invocation: one payload can hold fully+mounted small rungs and windowed large rungs, and a single windowed large-rung capture must not+suppress the structural digest for every fully mounted pair beside it. A fully mounted pair is+scored structurally; a windowed pair is scored on BOTH the visible region and the behavioural+invariants, because neither subsumes the other. The report names which pairs went which way and the+exit status combines every mode that ran.++Whether a pair is windowed is MEASURED from its parity capture where one exists, and falls back to+the run's own DECLARATION -- the `windowed_readiness:{arm}` gate rows and the per-cell `readiness`+metadata -- where it does not. Without the fallback a declared windowed run whose captures all+failed looks unwindowed, gets scored structurally, and exits 0 having compared nothing. The+declaration is consulted for BOTH expected arms by name, including an arm that emitted no action+row at all: an arm that died before the film leaves the pair one-sided, and reading the declaration+off the rows that are present asks the surviving arm whether the missing one was windowed.++Pairs are keyed by rung as well as by rep. They were keyed on the last dotted segment of the cell+id, so `r1K.base.rep0` and `r100K.base.rep0` collided: a payload carrying more than one rung+silently overwrote one rung's rows with the other's and could pair a 1K base against a 100K+treatment.++### The two boundary decisions in visible-region parity++Written down because this is where a visible-region check goes wrong quietly.++**Partial intersection counts as visible, and the element is digested IN FULL.** A message one+pixel into the viewport is visible. Digesting only the part inside the viewport is not definable on+a DOM subtree without reading geometry per node, and reading geometry is the one thing this must+not do. The error this admits is a FALSE ALARM: a difference in the off-screen tail of a partly+visible message is reported as visible. The error it refuses to admit is a false pass.++**Anything visible at ANY point during the action is compared, not just at the end.** The observer+is installed before the window opens and the compared set is the UNION of everything that ever+intersected. A single sample at the close would compare wherever a scroll happened to stop and+ignore everything the user saw on the way. The per-message digest is still the one taken at the+close, which is a real limitation: a message visible mid-action and since unmounted appears in+`ever_visible` but not in `messages`, and is reported as `unmounted_at_capture` rather than counted+as agreement.++**`aria-posinset` and `aria-setsize` are normalised out of the VISIBLE digest, and only that one.**+The readiness gate accepts those attributes on the `[data-role]` message or on an ancestor row+wrapper, so an arm may legitimately carry them on the message -- where the fully mounted arm+carries neither, and every message then differs on bookkeeping while the rendered content is+identical. The exclusion is passed in by the visible-region caller; the shared `signature` used by+the thread digest, the per-message rows and the overlays keeps them, because those pairs are only+ever scored when neither arm is windowing and an ordinal appearing there is a real change. What it+gives up: a wrong ordinal on a windowed arm is no longer visible in this digest, and is instead the+readiness gate's `posinset_ordinals_valid` / `posinset_reaches_end` and the completeness probe's+coverage, which are the checks that can say what a right ordinal would be.++**A message is keyed by its position in the THREAD, and the fallback is its position in the DOM.**+A windowed arm publishes `aria-posinset` and that is used. An arm that publishes none is fully+mounted, so the row's position among the thread's messages at the moment it is observed IS its+thread position. It is resolved then rather than at delivery time, because by delivery the row may+have been unmounted and `closest()` would answer nothing. It is NOT a lifetime count of observed+nodes: `thread_reopen` makes a fully mounted arm recreate all N rows in one document, and a counter+already standing at N stamped them N+1..2N, so the pair reported "the two arms put DIFFERENT+MESSAGES on screen" for a rebuild that was identical. The lookup is kept off the per-mutation path+-- a published ordinal short-circuits it, and the index is built at most once per mutation batch and+only by a batch that mounted a message element, so a stream (text churn inside mounted rows) builds+none. A row that can be placed by neither route is stamped with no ordinal and counted in+`unplaced_rows` rather than given a guess.++**The visible-region noise floor is keyed by (rung, action), and needs more than one observation.**+`visible_unstable_set` derives it from a base-vs-base null control. It returned ACTION NAMES, so a+single differing null pair silenced that action for every rep and every rung -- and a payload+legitimately holds several rungs, so noise on the null's 100K `model_change` suppressed a+reproducible visible regression on the target's 1K `model_change` and the command exited 0. The+rung is where the instability lives (the same argument `tier_of` makes about the film's spacing),+the shard cannot be part of the key because the null control is its own directory, and the reps at+one rung are the repeated observations `P.derive_unstable` requires before it will call anything+unstable. The structural floor keys on the action alone because it is unioned with a declared set+whose every entry carries a written mechanism; the visible floor has no such backing, so it is+earned at the scope it silences. SEVERE verdicts -- an arm whose viewport ended empty -- are never+routed into the floor whatever it is keyed by.++**Visibility is read with `IntersectionObserver` and never with geometry.**+`getBoundingClientRect()` / `getClientRects()` on content inside a `content-visibility` locked+subtree makes Chromium render that subtree to answer, so a geometry-based probe unlocks exactly+what it came to observe: one session reported 0 off-screen unrendered roots while the event counter+recorded 22 in the skipped state. IntersectionObserver is the same mechanism Blink's own relevance+machinery uses, so it neither forces rendering nor perturbs the decision. A live test installs a+counting trap on both geometry methods and fails if the capture touches either.++**What the exemption does NOT cover.** A clipboard that carries different content, and native+find-in-page. Both are questions about the whole conversation rather than about the viewport, so+they are scored behaviourally and an off-screen rendering difference is no defence.++### Three corrections to the record++**The `thread_reopen` control was never covered. It was never HOVERED.** Both the earlier+"the sticky group label overlaps it" explanation and its successor were wrong. `.sidebar-header-action`+ships `opacity: 0; pointer-events: none` and is revealed by `.group\/sidebar-header:hover`. The+button is laid out, passes every actionability check Playwright makes, and is transparent to every+hit test, so `click()` times out and a hit-test spread finds no reachable point -- both accurate,+both pointing the wrong way. `_click_or_navigate` now hovers the control's own centre before giving+up, which is what a user does; the pointer falls through to the group underneath and the button+becomes solid under a mouse already on it.++**A window that opens on an action reporting `ran: false` still records frames, and an idle window+sits near the compositor ceiling.** So an action that ran on one arm and not the other compares a+busy window against an empty one and reports a large improvement. In the 100K virtualization run+this produced `delete_message` +167.3% and `thread_reopen` +88.8%, two of the three largest wins on+the page, both fabricated: the actions ran 4x on the base arm and 0x on the treatment. Any+per-window comparison must drop windows whose action did not run on BOTH arms, and say which it+dropped. This is general and is not specific to virtualization.++**`reasoning_toggle` runs at 2.2 fps on BOTH arms at the 100K rung**, with a p95 frame of 2,084 ms.+It is the worst number the harness produces and it is not a virtualization finding.++**It is a STRESS reading, not a USER-JOURNEY reading, and it has been quoted as the latter.** The+action opens EVERY reasoning pane in the thread in one gesture: 10 panes, materialising 74,917+highlight spans, 2,143 ms to open and 805 ms to close. No user does that; a user expands one pane.+So 2.2 fps is a legitimate measurement of a deliberate worst case and must not be described as what+a user feels when they open a reasoning pane. We do not currently have that second number.++**Any scan that can return zero carries a positive control.** The style probe walks a hand-written+selector list; a class rename empties it, and two empty scans have equal element counts and equal+digests (both the hash of an empty string), so a probe that observed nothing used to report MATCH.+`compare_styles` now refuses a zero-element probe instead. The general form of this is worth+knowing: a CSSOM scan elsewhere in the campaign returned a clean zero because CSS nesting gives+every `CSSStyleRule` a truthy but empty `cssRules`, so code that recurses on a truthy `cssRules`+silently skips every declaration in the document. Nothing here walks the CSSOM today; anything+added later that can legitimately return zero needs a positive control, and a zero without one+should not be believed.++---++## 9. StabilityThis file is the contract. Layer 1 will not change any name above without editing this file in thesame commit and saying so at the top. Additive changes (new optional key, new row type, newdiff --git a/tests/studio/studiobench/__main__.py b/tests/studio/studiobench/__main__.pyindex c6979aa686a..6bf31811a31 100644--- a/tests/studio/studiobench/__main__.py+++ b/tests/studio/studiobench/__main__.py@@ -211,6 +211,26 @@ def doctor(args) -> int:# ── the run ─────────────────────────────────────────────────────────+def _windowed_arms(spec: str, labels: list) -> set:+ """The arms `--windowed-arm` names, checked against the arms this run will actually have.++ A PURE ARGUMENT CHECK, WHICH IS WHY IT RUNS BEFORE ANYTHING IS STARTED. It used to run after+ both Studio installs had been launched, the pacer bound and the browser opened -- and the+ `SystemExit` it raises for a typo (`--windowed-arm treatments`) left every one of them running,+ because the cleanup `finally` does not begin until the cell loop much further down. No+ `bundle.close()`, no `pacer.stop()`, no `stop_studio()`, no watchdog cancellation: a mistyped+ flag cost a browser and up to two Studio servers, still holding their ports.+ """+ names = {name.strip() for name in (spec or "").split(",") if name.strip()}+ unknown = names - set(labels)+ if unknown:+ raise SystemExit(+ f"--windowed-arm names {sorted(unknown)}, which is not an arm in this run "+ f"({sorted(labels)})"+ )+ return names++def side_home(explicit, out, label: str, *, ab: bool) -> Path:"""`UNSLOTH_STUDIO_HOME` for one side. THE TWO A/B SIDES NEVER SHARE ONE.@@ -569,10 +589,20 @@ def run(args, ab_ref = None) -> int:wait_for_healthz,)from .runtime.seeder import Seeder+ from .runtime.readiness import MODE_FULL, MODE_WINDOWEDfrom .runtime.session import CellRunner, build_cells, ensure_probe_image, make_contextfrom .runtime import resourcesfrom .runtime.types import Paths+ # THE ARM NAMES, BEFORE A SINGLE PROCESS EXISTS. Nothing below this line can be undone without+ # the cleanup `finally`, and that block is a long way down; see `_windowed_arms`. The labels are+ # READ OFF THE SPECS rather than spelled a second time, so the check and the sides cannot drift+ # into disagreeing about what an arm is called -- and `side_specs` is a pure list build, so+ # asking it this early starts nothing.+ specs = side_specs(args, ab_ref)+ arm_labels = [label for label, _ref, _attach, _port, _password in specs]+ windowed = _windowed_arms(getattr(args, "windowed_arm", ""), arm_labels)+out = Path(args.out or f"studiobench-{args.tier}-{int(time.time())}").resolve()paths = Paths.under(out)_log(f"studiobench {TOOL_VERSION} tier={args.tier} out={paths.out}")@@ -605,6 +635,51 @@ def run(args, ab_ref = None) -> int:)return 2+ # EVERY A/B ARGUMENT CHECK, AHEAD OF `prepare_payload`, FOR THE REASON STATED DIRECTLY ABOVE.+ # These three refuse the INVOCATION -- nothing they read comes from a Studio, a browser or a+ # payload, only `args` and `specs`, both of which exist before this function starts anything.+ # Left below the archive they cost the previous run its payload's standard path: a fresh+ # `--ab X --home H --out DIR` over a finished DIR archived `payload.jsonl` and then exited 2+ # having run no benchmark, so the next `--resume` found nothing to continue and silently+ # re-ran the whole ladder, while `--report` and `--assert-liveness` opened the standard name+ # and found no rows. `rollback_session_rows` states the rule: a refusal has to leave the+ # payload it refused exactly as it found it. That rule covers `invalidate_stale_reports`+ # below for the same reason it covers the archive: it REPLACES `summary.md` and `ab.md`, so+ # a refusal reaching it would take the previous run's reports down with its payload.+ if ab_ref:+ 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+ # ONE HOME CANNOT HOLD TWO BUILDS. `install_studio` checks the ref out into a repo+ # directory derived from the home and installs from it, so two arms sharing a home share+ # one checkout: the second install overwrites the first and BOTH arms then serve whichever+ # build was installed last. The A/B compares a build against itself and reports a clean,+ # confident "no difference" -- which is the same failure mode as a copy timing that is+ # really a sleep, and just as invisible in the payload.+ #+ # Measured, before this refused: two runs of the same pair, one at 716 ms and 718 ms for+ # base and treatment, the other at 2,583 ms and 2,614 ms. Nearly equal WITHIN each run and+ # 3.6x apart BETWEEN them, because each run was internally uniform and the two runs were+ # serving different builds. Read as a within-run comparison it says the change does+ # nothing; the difference was sitting between the runs the whole time.+ if not args.attach and args.home:+ _log(+ " --home cannot be used with --ab: both arms would install into that one "+ "directory, the second install would overwrite the first, and both arms would "+ "then serve the same build. Drop --home and each arm gets its own "+ "studio_home_<label> under --out."+ )+ return 2+# BEFORE the first install, the first launch and the first recorded row. See `prepare_payload`:# a refusal that arrives after two clones and two builds has cost the caller an hour to say# something it could have said in a millisecond, and an archive that arrives after the Recorder@@ -618,11 +693,10 @@ def run(args, ab_ref = None) -> int:# invalidates what is already sitting there.invalidate_stale_reports(paths.out, archived = archived, extra_init = extra_init)- # One spec per side, with its own home and password. Without --ab there is exactly one.- specs = side_specs(args, ab_ref)# Armed AFTER the sides are known, because what it has to cover depends on them: see- # `watchdog_deadline_s`. Nothing between here and there can hang -- `Corpus.load` reads a- # generated fixture and `side_specs` builds a list.+ # `watchdog_deadline_s`. Nothing between the `side_specs` call above and here can hang --+ # `_windowed_arms` compares two sets, `Corpus.load` reads a generated fixture, and+ # `prepare_payload` and `invalidate_stale_reports` each touch a handful of files in `--out`.watchdog = browser_mod.install_wall_clock_watchdog(watchdog_deadline_s(args.tier,@@ -635,18 +709,6 @@ def run(args, ab_ref = None) -> int:_log,)if ab_ref:- 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 = []@@ -1044,6 +1106,35 @@ def run(args, ab_ref = None) -> int:_log("")image_path = ensure_probe_image(paths)+ # WHICH SIDE, IF ANY, IS ALLOWED THE WINDOWED READINESS GATE.+ #+ # Per side and never global, so an A/B of the shipped build against a virtualised one runs+ # the base arm on the strict full-mount gate it has always had. A flag that relaxed both+ # sides would let a base arm that failed to finish mounting sail through and be compared+ # against a treatment that did the same, which is the exact "flattering garbage" the gate+ # exists to refuse -- on both arms at once, so the ratio would still look fine.+ #+ # `windowed` was parsed and validated at the top of this function, before the installs, the+ # pacer and the browser existed. Only the application of it is left here.+ for side in sides:+ side["readiness_mode"] = MODE_WINDOWED if side["label"] in windowed else MODE_FULL+ if side["readiness_mode"] == MODE_WINDOWED:+ _log(+ f" {side['label']}: WINDOWED readiness gate. This arm is permitted to mount "+ "fewer messages than the thread contains; it must publish aria-setsize matching "+ "the seeded count, mount the end of the thread, settle, and pass the "+ "scroll-to-top completeness probe. See runtime/readiness.py."+ )+ rec.gate(+ f"windowed_readiness:{side['label']}",+ True,+ {+ "arm": side["label"],+ "reason": "declared on the command line with --windowed-arm",+ "note": "structural UI parity is NOT APPLICABLE to this arm; run "+ "sweep/ui_parity.py --mode behaviour",+ },+ )for side in sides:side_seeder = Seeder(base_url = side["base_url"], auth = side["auth"], model_id = model_id, log = _log@@ -1055,6 +1146,7 @@ def run(args, ab_ref = None) -> int:seeder = side_seeder,corpus = corpus,click_probe = bool(getattr(args, "click_probe", False)),+ readiness_mode = side["readiness_mode"],base_url = side["base_url"],model_id = model_id,tier = args.tier,@@ -1464,8 +1556,8 @@ def _render_ab(if missing:result.void = Trueresult.void_reason = (- f"{len(missing)} of {len(planned)} planned cells did not complete, so what remains is "- "a selection rather than the plan: " + ", ".join(missing)+ f"{len(missing)} of {len(planned)} planned cells left no usable reading, so what "+ "remains is a selection rather than the plan: " + ", ".join(missing))text = render_ab_table(result)@@ -2437,6 +2529,24 @@ def parse_args(argv: list):"assertion. Use only for an action a platform genuinely cannot perform, and say ""which in the pull request: every name here is a hole in the gate",)+ ap.add_argument(+ "--windowed-arm",+ metavar = "ARMS",+ dest = "windowed_arm",+ # An ENV FALLBACK as well as the flag. `scripts/pr_perf_sweep.py` builds studiobench's+ # command line itself and is shared with other people's in-flight sweeps, so adding an+ # argument there mid-run is a hazard; this lets the sweep driver select the gate through+ # the environment without anybody editing the driver.+ default = os.environ.get("SBENCH_WINDOWED_ARM", ""),+ help = "comma-separated arm labels (base, treatment) that mount a WINDOW of the thread "+ "rather than all of it, and are therefore gated on the windowed readiness signal "+ "instead of on every message being mounted. Not a relaxation: the named arm must "+ "publish aria-setsize equal to the seeded message count, mount the end of the "+ "thread, settle, and pass a scroll-to-top completeness probe. Naming an arm that "+ "does NOT virtualise makes no difference to it beyond the extra conditions. "+ "Structural UI parity is not applicable to a windowed arm; score it with "+ "sweep/ui_parity.py --mode behaviour",+ )ap.add_argument("--click-probe",dest = "click_probe",diff --git a/tests/studio/studiobench/analysis/behaviour.py b/tests/studio/studiobench/analysis/behaviour.pynew file mode 100644index 00000000000..0410dca8a6c--- /dev/null+++ b/tests/studio/studiobench/analysis/behaviour.py@@ -0,0 +1,465 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""What replaces the structural digest when an arm changes what is mounted ON PURPOSE.++`sweep/ui_parity.py` asks "is the same DOM on screen on both arms". For every arm this project has+run, that is the right question. For an arm that mounts a window of the thread it is the wrong+one: the answer is no, by construction, on every action, and eighteen red rows that all say the+same thing are not a finding. Worse, they bury the differences that WOULD be findings.++So this asks the question that survives virtualization: THE DOM IS ALLOWED TO DIFFER, THE+BEHAVIOUR IS NOT. Five things a user does that stop working first when a list starts unmounting+rows, plus the scroll extent that every one of them depends on.++ SCROLL EXTENT the viewport's `scrollHeight` must still describe the whole conversation. A+ virtualizer that sizes its spacers correctly reproduces it within a few per+ cent; one that simply drops rows produces a scrollbar that lies about how+ much thread there is, and every scroll gesture, every jump-to-top and the+ scrollbar thumb itself are then wrong. This is the invariant the other four+ rest on, so it is checked on every action that carries a census rather than+ on one named action.+ select_all_copy Ctrl+A then Ctrl+C. The selection is taken over the DOM, so an unmounted+ message CANNOT be on the clipboard. This is the one that is not a measurement+ artefact and must not be filed as one: a user who copies their conversation+ and gets a fraction of it has lost data, and an arm that virtualises without+ answering for it has shipped that. It is checked as a coverage fraction of+ the thread, and a shortfall is a FAILURE of the arm, not of the harness.+ select_text selecting inside the last message. Single-message scope, so it must be+ unaffected: if this moves, the arm has changed how a mounted message renders,+ which is outside its remit.+ copy_markdown the action bar's Copy on the last message. Also single-message scope, also+ must not move. It is the control case for select_all_copy: if BOTH moved, the+ change is not about what is mounted.+ thread_reopen leaving the thread and coming back. The thread must come back the same LENGTH+ -- `messages_before == messages_after` on both arms -- because the failure a+ windowed mount invites is a reopen that restores only what fits on screen and+ loses the rest of the conversation from the store.+ scroll_after a scroll gesture against a settled thread. The gesture must still travel what+ it commanded. A virtualizer whose row heights are estimated corrects them as+ rows are measured, which moves the scroll target under the gesture; if that+ correction is large enough to eat the travel, scrolling a long thread is+ visibly broken however good the frame rate is.++WHAT THIS IS NOT. It is not a pixel comparison and it is not a substitute for looking at the+thing. It is the set of behaviours that a windowed mount breaks first, made into readings that can+be scored from a payload without a browser. An arm that passes all of it can still have changed+something nobody wrote an invariant for, and that is stated here rather than discovered later.+"""++from __future__ import annotations++from typing import Any, Optional++from .parity import MATCH, NOT_APPLICABLE, NOT_COMPARABLE, NOT_EXERCISED++#: Verdict for a behavioural invariant that moved. Distinct from the digest's DIFFER so a report+#: can never present the two as the same kind of evidence.+BROKEN = "broken"++#: How far a quantity that should be IDENTICAL may drift. 2%, the same figure the seeded-versus-+#: streamed equivalence check uses, and for the same reason: two runs of one build never produce+#: bit-identical character counts once a stream is involved.+EXACT_TOLERANCE = 0.02++#: How far the scroll extent may drift. 10%, much looser, because a windowed list computes its+#: total height from estimated row heights and corrects them as real rows are measured. Loose+#: enough to admit a correct virtualizer, nowhere near loose enough to admit one that dropped+#: rows: the failure this catches is an extent that is a FRACTION of the real one, not one that is+#: 6% out.+EXTENT_TOLERANCE = 0.10++#: How much of the thread the clipboard must carry, and how much more than the thread it may carry.+#:+#: TWO-SIDED, AND MEASURED AGAINST THE THREAD, because there are two ways to get a copy wrong and+#: the check used to see only one of them.+#:+#: The lower bound catches TRUNCATION, which is the defect this invariant was written for: a+#: windowed mount cannot select what it has not mounted, so a naive copy carries only the visible+#: fraction. Measured at 0.61 of the thread on a real 100K arm.+#:+#: The upper bound catches SUBSTITUTION, which is what a fix for the first defect turns into if+#: nobody is watching. Serialising from the message store is the right repair, but the obvious+#: serialiser is the "save this reply" one, which emits reasoning, tool-call arguments and tool+#: results -- none of which a user can select, because the panes holding them are collapsed and a+#: collapsed Radix Collapsible is not in the DOM at all. Measured at 2.16 of the thread on the same+#: arm: the truncation was fixed and the content was then wrong in the other direction.+#:+#: The gap between them is the honest allowance for two different serialisations of the same+#: content. The base arm's clipboard is the DOM's RENDERED TEXT; a store-based copy is markdown+#: SOURCE, so fences, emphasis and LaTeX delimiters exist in one and not the other. Measured at+#: ~0.9% on a scale fixture. Ten percent is generous against that and still refuses 2.16 by a+#: factor of twenty.+MIN_CLIPBOARD_COVERAGE = 0.95+MAX_CLIPBOARD_COVERAGE = 1.10++#: How much of the thread the clipboard must cover. 1.0: anything less is conversation the user+#: asked for and did not get.+CLIPBOARD_COVERAGE_REQUIRED = 1.0+++def _drift(a: Any, b: Any) -> Optional[float]:+ """Proportional difference, or None when either side is missing or both are zero."""+ if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):+ return None+ biggest = max(abs(a), abs(b))+ if biggest == 0:+ return 0.0+ return abs(a - b) / biggest+++def _check(+ name: str,+ ok: Optional[bool],+ detail: str,+ *,+ required: bool = False,+) -> dict:+ """One invariant's result.++ `required` marks a check WITHOUT WHICH THE REST CANNOT BE READ. It exists because of a hole+ this file's own tests found: when the treatment's clipboard could not be read back, the+ coverage check returned `None` (not applicable), the drift check returned `None` (one side+ missing), the base arm's own readability check returned `True` -- and the pair scored MATCH.+ An action whose entire subject went unmeasured was reporting that it was fine.++ A required check that could not be read makes the pair NOT COMPARABLE, which is the same rule+ the digest side already applies and the same principle throughout: silence is not a pass.+ """+ return {"invariant": name, "ok": ok, "detail": detail, "required": required}+++def scroll_extent(base_row: dict, treat_row: dict) -> dict:+ """Does the scrollbar still describe the whole conversation on both arms?"""+ bc = base_row.get("census") or {}+ tc = treat_row.get("census") or {}+ b, t = bc.get("viewport_scroll_height"), tc.get("viewport_scroll_height")+ drift = _drift(b, t)+ if drift is None:+ return _check(+ "scroll_extent",+ None,+ f"no viewport scroll height in one of the censuses (base={b!r}, treatment={t!r})",+ )+ return _check(+ "scroll_extent",+ drift <= EXTENT_TOLERANCE,+ f"viewport scrollHeight {b} vs {t} ({drift:.1%} drift, {EXTENT_TOLERANCE:.0%} allowed)",+ )+++def _expect(row: dict, key: str) -> Any:+ return (row.get("expect") or {}).get(key)+++def clipboard_coverage(base_row: dict, treat_row: dict) -> list[dict]:+ """select_all_copy: did the user's copy carry the whole conversation?++ SCORED ON THE CLIPBOARD, NOT ON THE SELECTION, and the difference is the entire point.++ A windowed mount cannot SELECT what it has not mounted; `Selection.toString()` walks the DOM+ and the DOM is a window. But it can still COPY it, if the app handles the copy event and+ serialises from its message store. So a selection that shrank is not evidence of anything on+ its own, and an alarm wired to it would stay lit on a build that had fixed the data loss --+ which is how alarms get switched off.++ The base arm's number is not the reference either; the THREAD is. Each arm is asked the same+ question about itself: is what landed on the clipboard the whole conversation.+ """+ out = []+ base_clip = _expect(base_row, "clipboard_chars")+ treat_clip = _expect(treat_row, "clipboard_chars")+ for label, row, clip in (+ ("base", base_row, base_clip),+ ("treatment", treat_row, treat_clip),+ ):+ mounted, total = _expect(row, "messages_mounted"), _expect(row, "messages_total")+ if not _expect(row, "clipboard_readable"):+ # NOT A PASS. An unreadable clipboard is a surface that went unmeasured, and this is+ # the one invariant where "we could not tell" must never look like "it was fine".+ out.append(+ _check(+ f"clipboard_readable:{label}",+ None,+ str(_expect(row, "clipboard_note") or "the clipboard could not be read back"),+ required = True,+ )+ )+ continue+ fraction = _expect(row, "mounted_fraction")+ out.append(+ _check(+ f"clipboard_readable:{label}",+ clip is not None and clip > 0,+ f"{clip} characters reached the clipboard with {mounted} of {total} messages "+ f"mounted (mounted fraction {fraction})",+ required = True,+ )+ )+ # THE CHECK THAT DETECTS THE DATA LOSS, scored against THE THREAD rather than against the+ # other arm -- which is what the docstring above has always said and what the code did not do.+ #+ # Comparing the two clipboards directly, at a 2% tolerance, asks whether two different+ # serialisations of the same conversation are the same LENGTH. They are not and cannot be: the+ # base arm's clipboard is the DOM's rendered text and a store-based copy is markdown source.+ # A correct fix therefore fails that comparison, and the only way to make it pass is to widen+ # the tolerance until it stops testing anything.+ #+ # The reference is the thread's own visible text, measured by the arm that has all of it in+ # the DOM: on a fully mounted arm `Selection.toString()` over the whole thread IS the thread.+ # If neither arm mounts everything there is no reference and the pair is not comparable, which+ # is reported rather than assumed either way.+ reference = _expect(base_row, "selected_chars")+ base_full = _expect(base_row, "mounted_fraction")+ if not isinstance(reference, (int, float)) or reference <= 0 or base_full != 1:+ out.append(+ _check(+ "clipboard_carries_the_whole_thread",+ None,+ "the base arm did not mount the whole thread, so there is no measurement of how "+ "long the conversation's visible text actually is to score either clipboard "+ f"against (base selection {reference}, mounted fraction {base_full})",+ required = True,+ )+ )+ return out+ for label, clip in (("base", base_clip), ("treatment", treat_clip)):+ coverage = None if not isinstance(clip, (int, float)) else clip / reference+ out.append(+ _check(+ f"clipboard_carries_the_whole_thread:{label}",+ None+ if coverage is None+ else (MIN_CLIPBOARD_COVERAGE <= coverage <= MAX_CLIPBOARD_COVERAGE),+ f"the clipboard carried {clip} characters against a thread whose visible text is "+ f"{reference} characters"+ + (+ ""+ if coverage is None+ else f" ({coverage:.3f} of it, allowed "+ f"{MIN_CLIPBOARD_COVERAGE}-{MAX_CLIPBOARD_COVERAGE})"+ ),+ required = True,+ )+ )+ # Reported, never gated: on a windowed arm the selection is SUPPOSED to be short, and gating+ # on it would fail the fix.+ out.append(+ _check(+ "selection_shrank_as_expected",+ None,+ f"selected characters {_expect(base_row, 'selected_chars')} vs "+ f"{_expect(treat_row, 'selected_chars')} -- reported, not gated: a windowed mount "+ "cannot select what it has not mounted, and the clipboard above is what the user gets",+ )+ )+ return out+++def _same_number(base_row: dict, treat_row: dict, key: str, name: str) -> dict:+ b, t = _expect(base_row, key), _expect(treat_row, key)+ drift = _drift(b, t)+ return _check(+ name,+ None if drift is None else drift <= EXACT_TOLERANCE,+ f"{key} {b} vs {t}" + ("" if drift is None else f" ({drift:.1%} drift)"),+ )+++def _reopen_completed(row: dict) -> Optional[bool]:+ """Did the reopened thread finish REBUILDING, or does this row not say?++ Three values, and the third is the one that matters. `None` is a row that carries no evidence+ either way, which is what a payload written before `thread_reopen` waited on+ runtime/readiness.py looks like -- and back then `messages_after` was read off whatever was on+ screen when the store published its total, so those rows cannot support the invariant below+ either.++ `reopen_readiness.ready` first, because it is the gate's OWN verdict on the rebuilt thread.+ `expect_ok` second: on this action it is `reopen_ms is not None and after == before`, so a true+ value means the action's own assertion about the rebuild held under whatever gate that checkout+ applied.+ """+ readiness = _expect(row, "reopen_readiness")+ if isinstance(readiness, dict) and isinstance(readiness.get("ready"), bool):+ return readiness["ready"]+ ok = row.get("expect_ok")+ return ok if isinstance(ok, bool) else None+++def thread_survives_reopen(base_row: dict, treat_row: dict) -> list[dict]:+ """thread_reopen: the thread came back the same length, and by the same route."""+ out = []+ for label, row in (("base", base_row), ("treatment", treat_row)):+ before, after = _expect(row, "messages_before"), _expect(row, "messages_after")+ completed = _reopen_completed(row)+ detail = f"the thread had {before} messages and came back with {after}"+ # MATCHING COUNTS ARE ONLY AN INVARIANT IF THE THREAD ACTUALLY CAME BACK.+ #+ # `messages_after` is `threadTotal()`, which is `aria-setsize` -- the store's DECLARATION of+ # how long the conversation is, published by the very first reopened row. When the rebuild+ # times out, scene/actions.py records `ran = True`, `expect_ok = False`, a null `reopen_ms`+ # and the outstanding conditions, and leaves the two counts equal because both are that same+ # declaration. Scored as equality it read as a held invariant, the route check passed+ # because the sidebar click had worked, and the pair came out MATCH with the rebuild having+ # timed out at three of eighteen messages mounted. "A declaration is not a rebuild" is the+ # defect the action itself was fixed for; this is the same defect one layer up.+ #+ # NOT COMPARABLE RATHER THAN BROKEN, AND ONLY FOR THE EQUAL CASE:+ #+ # counts DISAGREE BROKEN, whatever the gate said. The thread came back shorter than it+ # left, which is the data loss this invariant exists for, and a+ # readiness failure corroborates it rather than excusing it. Routing+ # this to NOT COMPARABLE would have downgraded the one finding the+ # whole action is written to catch.+ # counts AGREE, no+ # finished rebuild NOT COMPARABLE. The comparison was not made: both numbers are the+ # same declaration read off a thread that never finished building. And+ # the timeout that produced it is bounded by the harness's OWN+ # remaining budget (a 10 s floor, a 60 s ceiling, against the 180 s the+ # cell's opening gate had), so calling it BROKEN would file a budget+ # exhaustion on a shared machine as a user-visible defect of the arm.+ #+ # The arm's failure is not lost by this: `ran = True, expect_ok = False` already excludes+ # the cell from scoring through `report/payload.py`, and the reason travels with the row.+ if before is None or after is None:+ ok: Optional[bool] = None+ required = False+ elif before != after:+ ok, required = False, False+ elif completed:+ ok, required = True, False+ else:+ ok, required = None, True+ readiness = _expect(row, "reopen_readiness")+ failed = (+ sorted(k for k, v in (readiness.get("conditions") or {}).items() if v is False)+ if isinstance(readiness, dict)+ else []+ )+ detail += (+ ", but both numbers are the total the store DECLARED and the reopened thread never "+ "reached a ready state, so nothing here says the thread came back "+ f"(outstanding {failed or 'unrecorded'})"+ )+ out.append(_check(f"reopen_keeps_every_message:{label}", ok, detail, required = required))+ # The route matters as much as the count. A row measured after a full page navigation is a+ # row about a page load; see `_click_or_navigate` in scene/actions.py.+ via = _expect(row, "reopened_via")+ out.append(+ _check(+ f"reopen_used_the_control:{label}",+ None if via is None else via == "click",+ f"the thread was reopened via {via!r}",+ )+ )+ return out+++def scroll_travelled(base_row: dict, treat_row: dict) -> list[dict]:+ """scroll_after: the gesture still covers the ground it commanded, on both arms."""+ out = []+ for label, row in (("base", base_row), ("treatment", treat_row)):+ fraction = _expect(row, "travel_fraction")+ out.append(+ _check(+ f"scroll_travelled:{label}",+ None if fraction is None else fraction >= 0.9,+ f"the gesture travelled {fraction} of what it commanded",+ )+ )+ out.append(_same_number(base_row, treat_row, "bottom", "scroll_bottom_agrees"))+ return out+++#: action -> the invariants that apply to it. An action absent from this table has no behavioural+#: invariant declared and is reported as UNCHECKED rather than as passing, on the same principle+#: that keeps NOT_COMPARABLE out of the pass column in the digest report.+INVARIANTS = {+ "select_all_copy": clipboard_coverage,+ "select_text": lambda b, t: [+ _same_number(b, t, "selected_chars", "selection_unchanged"),+ _same_number(b, t, "visible_chars", "visible_chars_unchanged"),+ ],+ "copy_markdown": lambda b, t: [+ _same_number(b, t, "clipboard_chars", "copy_unchanged"),+ ],+ "thread_reopen": thread_survives_reopen,+ "scroll_after": scroll_travelled,+}+++def compare_behaviour(base_row: Optional[dict], treat_row: Optional[dict]) -> dict:+ """One base/treatment action pair, scored on behaviour instead of on structure.++ Returns the same verdict vocabulary the digest comparison uses, so one report can carry both:+ MATCH, BROKEN, NOT_EXERCISED, NOT_COMPARABLE, NOT_APPLICABLE.+ """+ for label, row in (("base", base_row), ("treatment", treat_row)):+ if not isinstance(row, dict):+ return {+ "verdict": NOT_COMPARABLE,+ "reason": f"the {label} arm has no row for this action",+ "checks": [],+ }+ if not row.get("ran"):+ return {+ "verdict": NOT_EXERCISED,+ "reason": f"the action did not run on the {label} arm "+ f"({row.get('reason') or 'no reason recorded'})",+ "checks": [],+ }+ assert base_row is not None and treat_row is not None+ action = base_row.get("action") or treat_row.get("action") or ""+ checks: list[dict] = [scroll_extent(base_row, treat_row)]+ rule = INVARIANTS.get(action)+ if rule is None:+ checks.append(+ _check(+ "behavioural_invariant_declared",+ None,+ f"no behavioural invariant is declared for {action!r}, so this action is "+ "UNCHECKED on a windowed arm rather than passing",+ )+ )+ else:+ got = rule(base_row, treat_row)+ checks.extend(got if isinstance(got, list) else [got])++ # A REQUIRED CHECK THAT COULD NOT BE READ VOIDS THE PAIR. See `_check`: without this, an+ # action whose entire subject went unmeasured scores MATCH on the strength of the checks that+ # happened to survive.+ unread = [c for c in checks if c.get("required") and c["ok"] is None]+ if unread:+ return {+ "verdict": NOT_COMPARABLE,+ "reason": "; ".join(f"{c['invariant']}: {c['detail']}" for c in unread),+ "checks": checks,+ }++ broken = [c for c in checks if c["ok"] is False]+ if broken:+ return {+ "verdict": BROKEN,+ "reason": "; ".join(f"{c['invariant']}: {c['detail']}" for c in broken),+ "checks": checks,+ }+ # A PASS REQUIRES AN ACTION-SPECIFIC INVARIANT TO HAVE HELD.+ #+ # The scroll extent is checked on every action and it is a property of the THREAD, not of the+ # action: it holds or fails identically across all eighteen. Counting an action as passing+ # because the thread's scrollbar was the right length would report `model_change`,+ # `image_upload` and `settings` as verified on a windowed arm when nothing whatsoever about+ # them was examined. That is the same mistake `compare_rows` exists to prevent on the digest+ # side, where an action that never ran used to contribute a match.+ specific = [c for c in checks if c["ok"] is not None and c["invariant"] != "scroll_extent"]+ if not specific:+ return {+ "verdict": NOT_APPLICABLE,+ "reason": (+ f"no behavioural invariant specific to {action!r} could be read from this payload, "+ "so this surface is UNCHECKED on a windowed arm rather than passing"+ ),+ "checks": checks,+ }+ return {"verdict": MATCH, "reason": "", "checks": checks}diff --git a/tests/studio/studiobench/analysis/parity.py b/tests/studio/studiobench/analysis/parity.pyindex d19cb623244..f53cb09743c 100644--- a/tests/studio/studiobench/analysis/parity.py+++ b/tests/studio/studiobench/analysis/parity.py@@ -26,10 +26,45 @@ import collectionsfrom typing import Any, Iterable, Optional# What a comparison concluded. Kept as plain strings so a payload row carries them verbatim.+#: WHAT "MATCH" ACTUALLY CLAIMS, because the name promises more than the instrument delivers.+#:+#: Everything in this module is computed from `scene/parity.js`, whose structural digest walks the+#: THREAD and nothing else. It is sidebar-blind and layout-blind by construction: a change confined+#: to the sidebar, or one that alters computed geometry without altering thread structure, passes+#: it while being entirely invisible to it. That is not a theory. A concurrent campaign measuring+#: the sidebar drag found the shipped thread digest returned 0 of 34 differing pairs on a real,+#: visible change -- and its null control returned 0 of 34 as well, so the instrument was not+#: discriminating in either direction. Three purpose-built captures (sidebar-inclusive structure,+#: sidebar inline style, custom-property reach) found the same change 34 of 34, with the null at+#: zero in every category.+#:+#: So MATCH means NO THREAD-STRUCTURE CHANGE WAS DETECTED. It does not mean the UI is unchanged.+#: Not covered, and not detectable here at all:+#:+#: the sidebar outside the digest root+#: computed layout / geometry positions and sizes are never read+#: CSS custom properties never read+#: stylesheet changes only insofar as they alter `display`, `visibility` or+#: `pointer-events` on the <=64 elements the bounded style probe+#: reaches, which is reported separately and as an advisory+#:+#: Anything relying on a stronger reading than that needs its own capture.MATCH = "match"DIFFER = "differ"NOT_COMPARABLE = "not_comparable"NOT_EXERCISED = "not_exercised"+#: THE FOURTH OUTCOME, and it is not a softer NOT_COMPARABLE.+#:+#: NOT_COMPARABLE means the reading failed or the two readings are of different things by+#: accident. NOT_APPLICABLE means the question itself is wrong for this pair: the structural+#: digest asks "is the same DOM on screen", and an arm whose entire purpose is to put less DOM on+#: screen answers "no" by construction. Reporting that as a UI difference would be true and+#: useless -- eighteen red rows, none of them a finding, and the real behavioural questions+#: drowned underneath them.+#:+#: It is kept distinct from NOT_COMPARABLE so a reader can tell "we could not measure this" from+#: "this measurement does not apply here", and so `derive_unstable` counts neither as evidence.+NOT_APPLICABLE = "not_applicable"# Actions whose rendered result legitimately differs between two runs of the SAME build, so a# digest mismatch there carries no information about the pull request under test.@@ -132,6 +167,82 @@ def _overlays(capture: dict) -> list[dict]:return list(capture.get("overlays") or [])+def windowed_mount(capture: Optional[dict]) -> bool:+ """Did this capture come from a thread that mounts a WINDOW rather than the whole thing?++ Read from the capture's own two numbers rather than from a flag the caller passed in, so an+ arm cannot be scored as full-mount because somebody forgot to set an option. Captures taken+ before those numbers existed report neither, and are treated as full-mount, which is what they+ were.+ """+ if not isinstance(capture, dict):+ return False+ mounted, total = capture.get("mounted_messages"), capture.get("thread_total")+ if not isinstance(mounted, int) or not isinstance(total, int):+ return False+ return total > mounted+++def applicability(base: Optional[dict], treat: Optional[dict]) -> Optional[str]:+ """Why the STRUCTURAL DIGEST is the wrong question for this pair, or None if it is the right one.++ ONE shape, and it is an answer rather than a failure: an arm mounts a window of the thread on+ purpose, so the two digests describe different amounts of DOM by design and the comparison+ cannot tell the intended change from an unintended one.++ What replaces it is in `analysis/behaviour.py`: matched scroll positions plus the behavioural+ invariants that break first when a thread stops mounting everything.++ IT USED TO COVER A SECOND SHAPE and that was a false green. Two arms that both mount their+ whole thread, differing in how many messages that is, were also waved through here on the+ argument that the per-message rows are keyed by position and so describe different messages on+ the two sides. That argument is true and it is not a reason to withhold a verdict: if neither+ arm is windowing, a treatment that mounts fewer messages than the base has LOST MESSAGES, and+ that is the most serious thing this comparison could find. It is reported by+ `mount_count_mismatch` as a difference instead.+ """+ if not isinstance(base, dict) or not isinstance(treat, dict):+ return None+ bw, tw = windowed_mount(base), windowed_mount(treat)+ if bw or tw:+ which = "both arms" if bw and tw else ("the base arm" if bw else "the treatment arm")+ return (+ f"{which} mounts a WINDOW of the thread "+ f"(base {base.get('mounted_messages')} of {base.get('thread_total')}, treatment "+ f"{treat.get('mounted_messages')} of {treat.get('thread_total')} messages mounted). "+ "A structural DOM digest compares what is on screen, and this arm changes what is on "+ "screen by design, so the comparison cannot distinguish the intended change from an "+ "unintended one. Score this pair on behavioural invariants instead"+ )+ return None+++def mount_count_mismatch(base: Optional[dict], treat: Optional[dict]) -> Optional[str]:+ """Two NON-windowed arms that mounted different numbers of messages, or None.++ Reached only when neither arm is windowing, so neither is holding anything back deliberately+ and the counts should be equal. They are not, which means one side is rendering a thread the+ other side is not -- a user-visible loss of conversation, reported as a difference rather than+ excused as an incomparable pair.++ The per-message digest rows are not quoted alongside it. They are keyed by position in the+ mounted list, so with different lengths no two rows describe the same message and every one of+ them would be listed as moved: a page of noise on top of the one finding that matters.+ """+ if not isinstance(base, dict) or not isinstance(treat, dict):+ return None+ bm, tm = base.get("mounted_messages"), treat.get("mounted_messages")+ if not isinstance(bm, int) or not isinstance(tm, int) or bm == tm:+ return None+ return (+ f"the arms mounted different numbers of messages ({bm} vs {tm}) and NEITHER arm is "+ "windowing, so this is not a difference of what is kept in the DOM on purpose -- one side "+ "is rendering messages the other is not. The per-message rows are keyed by position in "+ "the mounted list, so they are not quoted here: with different lengths every row would "+ "read as moved"+ )++def comparability(base: Optional[dict], treat: Optional[dict]) -> Optional[str]:"""Why these two captures may NOT be compared, or None if they may be."""for label, side in (("base", base), ("treatment", treat)):@@ -211,6 +322,20 @@ def compare_styles(base: dict, treat: dict) -> tuple[str, str]:f"the probe hit its element cap "f"(base={bs.get('elements')}, treatment={ts.get('elements')})")+ # A POSITIVE CONTROL ON THE SCAN ITSELF. Two probes that matched no elements have equal+ # counts and equal digests -- both are the hash of an empty string -- so a probe that scanned+ # NOTHING reports MATCH, which is the strongest verdict this function can return and is+ # supported by no observation whatsoever. That is not hypothetical: the selector list is+ # written against Studio's markup, and a class rename anywhere in it silently empties the+ # scan. A DOM or CSSOM scan that can return zero has to be able to tell "I looked and they+ # agree" from "I did not look", and this one could not.+ if not bs.get("elements") or not ts.get("elements"):+ return NOT_COMPARABLE, (+ f"the style probe matched no elements (base={bs.get('elements')}, "+ f"treatment={ts.get('elements')}), so it observed nothing on at least one arm. Its "+ "selector list is written against Studio's markup and does not survive a rename; "+ "this is a probe that needs fixing, not two arms that agree"+ )if bs.get("elements") != ts.get("elements"):return DIFFER, (f"the probe matched a different number of elements "@@ -258,6 +383,28 @@ def compare(base: Optional[dict], treat: Optional[dict]) -> dict:"style_reason": why,}assert base is not None and treat is not None+ not_applicable = applicability(base, treat)+ if not_applicable is not None:+ return {+ "verdict": NOT_APPLICABLE,+ "reason": not_applicable,+ "moved": [],+ # The style probe goes with it. Its verdict is `elements` counts matching, and those+ # counts are element counts over `[data-role]` among other things, so it reports+ # DIFFER for exactly the same reason and with exactly as much meaning.+ "style_verdict": NOT_APPLICABLE,+ "style_reason": not_applicable,+ }+ lost = mount_count_mismatch(base, treat)+ if lost is not None:+ style_verdict, style_reason = compare_styles(base, treat)+ return {+ "verdict": DIFFER,+ "reason": lost,+ "moved": [],+ "style_verdict": style_verdict,+ "style_reason": style_reason,+ }style_verdict, style_reason = compare_styles(base, treat)if not _any_moved(base, treat):return {@@ -478,3 +625,223 @@ def summarise(results: Iterable[dict[str, Any]]) -> dict[str, int]:for r in results:tally[r.get("verdict", NOT_COMPARABLE)] += 1return dict(tally)+++# ── visible-region parity ───────────────────────────────────────────+#+# THE POLICY. All changes must preserve UI and UX idempotency, with two exemptions: a difference+# may be accepted deliberately when performance improves dramatically, and a difference that exists+# only OFF SCREEN is fine by definition, because rendering only what is visible is an accepted+# technique rather than a parity violation.+#+# `compare()` above cannot express the second exemption. It digests the thread whether or not any+# of it is on screen, so deferred off-screen work fails it by construction: virtualization,+# deferred fence highlighting, content-visibility, lazy images. Returning NOT_APPLICABLE for those+# pairs withholds a verdict.+# This supplies one.++#: The claim each verdict makes, so a reader knows which of the three was actually checked. A bare+#: "PARITY OK" has meant three very different things in this file's history and the difference+#: between them is the difference between a strong result and a weak one.+#: NOT "whole-document structural parity: every element in the DOM is identical on both arms",+#: which is what this string used to say and which the instrument cannot support. `scene/parity.js`+#: digests the THREAD ROOT plus a list of overlay selectors; it never walks the sidebar, never reads+#: geometry and never reads CSS custom properties. Printing the stronger claim turns a limited+#: thread-structure reading into an experimental conclusion about the whole UI, which is how a+#: sidebar-drag campaign came to be scored 0 of 34 differing pairs by a digest whose own null+#: control also returned 0 of 34: the instrument was not discriminating in either direction, and+#: the banner said the DOM was identical.+CLAIM_STRUCTURAL = (+ "thread-structure parity: the thread root and the declared overlay selectors serialise "+ "identically on both arms, on screen and off. It does NOT cover the sidebar, computed layout "+ "or geometry, or CSS custom properties, so it is not a statement that the UI is unchanged: "+ "run against a real sidebar-drag change this digest reported 0 of 34 differing pairs, and so "+ "did its own null control"+)+CLAIM_VISIBLE = (+ "visible-region parity: every message the viewport showed at any point during the action is "+ "present on both arms and identical between them, and every difference lies off screen"+)+CLAIM_BEHAVIOURAL = (+ "behavioural parity: the scroll extent matches and the invariants a windowed mount breaks "+ "first still hold. Says NOTHING about how anything looks"+)++#: THE POLICY EVERY VERDICT IS JUDGED AGAINST, printed beside the claim.+#:+#: A bare "PARITY OK" reads as "the UI is unchanged" and none of the three modes can support that+#: sentence. Each supports a narrower one, and which one is being made changes what a pass MEANS,+#: so the policy is named next to the claim rather than left in a document somebody has to find.+#:+#: The exemptions are not loopholes. The first is a decision someone makes on the record with a+#: number attached; the second is a definition, because rendering only what is visible is an+#: accepted technique rather than a parity violation. Neither removes the need for a floor: a+#: difference that is exempt still has to be shown to be the difference you think it is, which is+#: what the null control is for.+POLICY = (+ "UI and UX idempotency is required, with two exemptions: a deliberate difference accepted "+ "for a dramatic performance improvement, and a difference that exists only OFF SCREEN"+)++#: What each mode can and cannot decide under that policy. The point of the second half of each+#: line is that a reader can tell which sentence they are being handed.+POLICY_BY_MODE = {+ "structural": (+ f"{POLICY}. This mode judges the FIRST requirement over the thread root and the declared "+ "overlays only. It cannot grant the off-screen exemption, because it does not know what "+ "was on screen: an arm that renders only the visible region reads as a difference here "+ "and needs --mode visible to get a verdict rather than a refusal"+ ),+ "visible": (+ f"{POLICY}. This mode is the one that can GRANT the off-screen exemption: it compares "+ "only what the viewport actually showed, so an off-screen-only difference passes on its "+ "merits rather than being argued about. The exemption changes what counts as a pass; it "+ "does not remove the floor, so read the null control printed on the same scale"+ ),+ "behaviour": (+ f"{POLICY}. This mode judges neither requirement directly. It checks invariants a "+ "windowed mount breaks first -- scroll extent, what the clipboard carries, whether the "+ "thread survives being reopened -- so a pass here is evidence about BEHAVIOUR and says "+ "nothing about appearance. It cannot grant either exemption"+ ),+}+++def compare_visible(base: Optional[dict], treat: Optional[dict]) -> dict:+ """One base/treatment pair, scored on the VISIBLE REGION only.++ Returns {verdict, reason, moved, claim}. `moved` names the ordinals that differ, in thread+ position rather than mounted index, so the row is actionable on a windowed arm.+ """+ for label, side in (("base", base), ("treatment", treat)):+ if not isinstance(side, dict) or not side.get("visible_attempted"):+ why = (side or {}).get("reason") or "no visible-region capture"+ return {+ "verdict": NOT_COMPARABLE,+ "reason": f"the {label} arm produced no visible-region capture: {why}",+ "moved": [],+ "claim": CLAIM_VISIBLE,+ }+ assert base is not None and treat is not None++ # THE POSITIVE CONTROL. A visibility scan that matched nothing has equal (empty) ordinal sets+ # and no differing digests, so without this it returns the strongest verdict available on the+ # strength of never having seen a single message. Exactly the failure `compare_styles` had.+ bn, tn = len(base.get("ever_visible") or []), len(treat.get("ever_visible") or [])+ if bn == 0 or tn == 0:+ return {+ "verdict": NOT_COMPARABLE,+ "reason": (+ f"the visibility scan matched no messages (base={bn}, treatment={tn}). Nothing "+ "was observed on at least one arm, so there is nothing to agree about: this is a "+ "probe that needs fixing, not two arms that match"+ ),+ "moved": [],+ "claim": CLAIM_VISIBLE,+ }++ bev, tev = set(base.get("ever_visible") or []), set(treat.get("ever_visible") or [])+ if bev != tev:+ only_b, only_t = sorted(bev - tev), sorted(tev - bev)+ return {+ "verdict": DIFFER,+ "reason": (+ "the two arms put DIFFERENT MESSAGES on screen during this action, which is a "+ "visible difference and not an off-screen one "+ f"(only base: {only_b[:8]}, only treatment: {only_t[:8]})"+ ),+ "moved": [f"ordinal {o}" for o in (only_b + only_t)[:8]],+ "claim": CLAIM_VISIBLE,+ }++ bmsg, tmsg = base.get("messages") or {}, treat.get("messages") or {}+ # Ordinals seen during the window but unmounted by capture time cannot be digested. Reported,+ # never counted as agreement: this is the residue of comparing a windowed arm at one instant.+ uncomparable = sorted(int(o) for o in map(str, sorted(bev)) if o not in bmsg or o not in tmsg)+ moved = []+ for ordinal in sorted(bev):+ key = str(ordinal)+ b, t = bmsg.get(key), tmsg.get(key)+ if b is None or t is None:+ continue+ if b.get("digest") != t.get("digest"):+ moved.append(f"ordinal {ordinal}({b.get('role')}):{b.get('chars')}->{t.get('chars')}c")+ # ONE VIEWPORT ENDED EMPTY AND THE OTHER DID NOT, which is as visible a difference as there is+ # and used to be reported as NOT COMPARABLE -- a refusal, not a finding.+ #+ # This is not hypothetical and it is why the check exists. On the 100K virtualization arm,+ # `model_change` took the thread from 12 mounted messages to 0 and it never came back: the+ # census reads 0 messages and 2,107 elements for the rest of the film, and three later actions+ # could not run at all. Both arms had shown the same ordinals EARLIER in the action, so the+ # union matched and every per-ordinal digest was simply missing on one side. Comparing only the+ # union cannot see that; comparing what each arm could still show at the end can.+ b_left, t_left = len(bmsg), len(tmsg)+ if (b_left == 0) != (t_left == 0):+ empty, full = ("treatment", "base") if t_left == 0 else ("base", "treatment")+ return {+ "verdict": DIFFER,+ "reason": (+ f"the {empty} arm's viewport ended this action EMPTY while the {full} arm still "+ f"showed {max(b_left, t_left)} of the {len(bev)} message(s) that had been visible "+ "during it. Both arms displayed the same messages earlier in the action, so this "+ "is not a windowing difference: one arm lost the thread"+ ),+ "moved": [f"ordinal {o}" for o in sorted(bev)[:8]],+ "claim": CLAIM_VISIBLE,+ # NOT SUPPRESSIBLE BY THE NOISE FLOOR. The floor exists for actions whose visible+ # region differs between two runs of the same build, which is a volatile attribute on+ # rows of identical length. Losing the entire thread is a different kind of statement,+ # and an action can easily be BOTH: on the 100K run `model_change` is in the derived+ # unstable set because the null control's copy of it differs on an attribute, and that+ # would have silenced "the treatment arm's viewport ended empty" -- suppressing a lost+ # conversation on the strength of unrelated jitter in the same action.+ "severe": True,+ }+ if moved:+ return {+ "verdict": DIFFER,+ "reason": f"{len(moved)} visible message(s) rendered differently",+ "moved": moved,+ "claim": CLAIM_VISIBLE,+ "not_digested": uncomparable,+ }+ if uncomparable:+ # ANY residue refuses the verdict, not only a total one. This branch used to be entered+ # solely when EVERY visible ordinal was undigestable (`len(uncomparable) == len(bev)`), so a+ # scrolling or windowed action that put six messages on screen and unmounted one of them+ # before the capture returned MATCH on the strength of the other five. The claim printed+ # above quantifies over EVERY message the viewport showed; one message missing makes it+ # unsupported, and the rendering difference this mode exists to catch could be in exactly+ # the message that is missing. `visible_report` never printed the `not_digested` residue+ # either, so that pair exited 0 with nothing on screen to say a message went uncompared.+ #+ # WHY THE VERDICT AND NOT MERELY THE PASS COUNT. Demoting it inside `visible_report` alone+ # would leave the row itself reading `match`, and every other consumer of that row counts a+ # match as agreement: `visible_unstable_set` reads verdicts to derive the noise floor,+ # `summarise` tallies them, and the payload keeps them verbatim for whoever reads it next.+ # The honest outcome has to live in the verdict, which is the one thing they all share.+ #+ # THE COST, MEASURED on the two real 100K films rather than guessed. On the windowed arm 4+ # of 39 matching pairs carry a residue, all of them `stop_generation`; on the base-vs-base+ # null control 7 of 43 do. The mode keeps a discriminating majority on both, so this buys+ # honesty at four pairs in sixty-four.+ digested = len(bev) - len(uncomparable)+ return {+ "verdict": NOT_COMPARABLE,+ "reason": (+ f"{len(uncomparable)} of the {len(bev)} message(s) that were visible during this "+ "action had been unmounted again by the time the capture ran, so they could not be "+ f"digested (ordinals {uncomparable[:8]}). The {digested} that could be digested "+ "agreed, which is not the claim this mode makes"+ ),+ "moved": [],+ "claim": CLAIM_VISIBLE,+ "not_digested": uncomparable,+ }+ return {+ "verdict": MATCH,+ "reason": "",+ "moved": [],+ "claim": CLAIM_VISIBLE,+ "not_digested": [],+ }diff --git a/tests/studio/studiobench/analysis/selftest/test_studiobench_visible_parity.py b/tests/studio/studiobench/analysis/selftest/test_studiobench_visible_parity.pynew file mode 100644index 00000000000..be7740de278--- /dev/null+++ b/tests/studio/studiobench/analysis/selftest/test_studiobench_visible_parity.py@@ -0,0 +1,295 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""VISIBLE-REGION PARITY, held to the policy it exists to serve.++The policy: all changes preserve UI and UX idempotency, with two exemptions. A difference may be+accepted deliberately when performance improves dramatically, and a difference that exists only OFF+SCREEN is fine by definition, because rendering only what is visible is an accepted technique.++The structural digest cannot express the second exemption -- it digests the thread on screen and+off, so every deferred-off-screen technique fails it by construction -- and answering NOT_APPLICABLE+withholds a verdict rather than giving one. These tests hold the replacement to both halves of the+claim: an off-screen-only difference must PASS, and an on-screen difference must FAIL, on the same+pair of captures.++The verdict logic is pure, so it is tested here without a browser. The observer that produces the+captures is tested in a real Chromium in+`scene/selftest/test_studiobench_visible_capture_live.py`, because whether IntersectionObserver+sees what it should is not a question a fake can answer.+"""++from __future__ import annotations++import sys+from pathlib import Path++_STUDIO_TESTS = Path(__file__).resolve().parents[3]+if str(_STUDIO_TESTS) not in sys.path:+ sys.path.insert(0, str(_STUDIO_TESTS))++from studiobench.analysis import parity as P # noqa: E402+++def _cap(visible: dict[int, str], ever: list[int] | None = None) -> dict:+ """A visible-region capture. `visible` maps thread ordinal -> digest."""+ return {+ "visible_attempted": True,+ "ever_visible": sorted(ever if ever is not None else visible),+ "ever_visible_count": len(ever if ever is not None else visible),+ "mounted_ever_visible": len(visible),+ "unmounted_at_capture": len(ever if ever is not None else visible) - len(visible),+ "messages": {+ str(k): {"role": "assistant", "digest": v, "chars": 100} for k, v in visible.items()+ },+ }+++# ── the exemption, which is the entire point ────────────────────────+++def test_a_difference_that_is_only_off_screen_passes():+ """THE POLICY, IN ONE ASSERTION. The treatment renders ordinals 1-3 differently -- they are+ genuinely not the same DOM -- but the viewport never showed them during this action, so the+ difference is off screen and is exempt. The structural digest fails this pair; this must+ not."""+ base = _cap({14: "a", 15: "b", 16: "c"})+ treat = _cap({14: "a", 15: "b", 16: "c"})+ got = P.compare_visible(base, treat)+ assert got["verdict"] == P.MATCH, got+ assert got["claim"] == P.CLAIM_VISIBLE+++def test_a_difference_inside_the_viewport_still_fails():+ """The exemption is for off-screen differences only. A message the user was looking at is not+ excused by anything, and the row names it by THREAD position so it is actionable."""+ got = P.compare_visible(_cap({14: "a", 15: "b"}), _cap({14: "a", 15: "CHANGED"}))+ assert got["verdict"] == P.DIFFER, got+ assert any("ordinal 15" in m for m in got["moved"]), got["moved"]+ assert not any("ordinal 14" in m for m in got["moved"])+++def test_showing_different_messages_is_itself_a_visible_difference():+ """Two arms whose viewports held different parts of the conversation did not show the user the+ same thing, whatever the digests of the overlap say. This is the case a naive intersection+ would silently skip by comparing only the ordinals both arms happen to have."""+ got = P.compare_visible(_cap({14: "a", 15: "b"}), _cap({15: "b", 16: "c"}))+ assert got["verdict"] == P.DIFFER+ assert "DIFFERENT MESSAGES on screen" in got["reason"]+++# ── the windowed arm is comparable at all ───────────────────────────+++def test_a_windowed_arm_and_a_full_arm_are_compared_by_thread_position():+ """The reason this mode works where the digest does not. The base has the whole thread mounted+ and the treatment has a window of it, so mounted INDEX 0 is a different message on the two+ arms. Keyed by thread ordinal, the messages that were actually on screen line up."""+ base = _cap({16: "p", 17: "q", 18: "r"})+ treat = _cap({16: "p", 17: "q", 18: "r"})+ assert P.compare_visible(base, treat)["verdict"] == P.MATCH+++# ── the positive control ────────────────────────────────────────────+++def test_a_visibility_scan_that_saw_nothing_is_not_a_pass():+ """Two empty scans have equal ordinal sets and no differing digests, so without this the+ strongest verdict available is returned on the strength of never having observed a single+ message. `compare_styles` had exactly this bug and it is the reason anything here that can+ return zero carries a control."""+ got = P.compare_visible(_cap({}), _cap({}))+ assert got["verdict"] == P.NOT_COMPARABLE, got+ assert "matched no messages" in got["reason"]+++def test_one_arm_seeing_nothing_is_also_not_a_difference_to_report():+ got = P.compare_visible(_cap({}), _cap({14: "a"}))+ assert got["verdict"] == P.NOT_COMPARABLE+++def test_a_missing_capture_is_refused_rather_than_assumed_empty():+ assert P.compare_visible(None, _cap({1: "a"}))["verdict"] == P.NOT_COMPARABLE+ assert (+ P.compare_visible({"visible_attempted": False, "reason": "no viewport"}, _cap({1: "a"}))[+ "verdict"+ ]+ == P.NOT_COMPARABLE+ )+++# ── the honest residue ──────────────────────────────────────────────+++def test_a_message_seen_mid_action_but_unmounted_by_capture_is_not_counted_as_agreement():+ """THIS TEST USED TO ASSERT MATCH, and it contradicted its own name.++ Ordinal 3 scrolled through the viewport during the action and had been unmounted again before+ the capture ran, so it cannot be digested. The old behaviour returned MATCH as long as one+ other message stayed mounted and left the residue in `not_digested`, which nothing printed:+ the run exited 0 under a claim that quantifies over EVERY message the viewport showed, while+ one of them had never been compared. A rendering difference in the missing message produced a+ clean pass.++ The residue is still reported, and the verdict is now the third outcome rather than the+ strongest one.+ """+ base = _cap({14: "a"}, ever = [3, 14])+ treat = _cap({14: "a"}, ever = [3, 14])+ got = P.compare_visible(base, treat)+ assert got["verdict"] == P.NOT_COMPARABLE, got+ assert got["verdict"] != P.MATCH+ assert got["not_digested"] == [3], got+ assert "ordinals [3]" in got["reason"], got["reason"]+ assert got["claim"] == P.CLAIM_VISIBLE+++def test_the_messages_that_could_be_digested_agreeing_is_not_the_claim_this_mode_makes():+ """The residue is one ordinal out of six, so five messages were compared and all five agreed.+ That is a real observation and it is not the printed claim, which is about every message the+ viewport showed. The reason says which ordinal went uncompared so the reader can decide."""+ seen = {10: "a", 11: "b", 12: "c", 13: "d", 14: "e"}+ got = P.compare_visible(_cap(seen, ever = [3, *seen]), _cap(seen, ever = [3, *seen]))+ assert got["verdict"] == P.NOT_COMPARABLE, got+ assert got["not_digested"] == [3]+ assert "1 of the 6 message(s)" in got["reason"], got["reason"]+ assert "The 5 that could be digested agreed" in got["reason"], got["reason"]+++def test_a_pair_with_nothing_left_undigested_still_matches_with_an_empty_residue():+ """The refusal must not leak into the pairs it does not concern, or the mode stops being able+ to pass anything and stops being able to fail anything either."""+ got = P.compare_visible(_cap({14: "a", 15: "b"}), _cap({14: "a", 15: "b"}))+ assert got["verdict"] == P.MATCH, got+ assert got["not_digested"] == []+++def test_an_undigested_ordinal_never_downgrades_a_difference_that_was_found():+ """A residue withholds a pass; it does not withdraw a finding. Ordinal 3 could not be digested+ and ordinal 15 rendered differently, and the second of those is still the verdict."""+ base = _cap({14: "a", 15: "b"}, ever = [3, 14, 15])+ treat = _cap({14: "a", 15: "CHANGED"}, ever = [3, 14, 15])+ got = P.compare_visible(base, treat)+ assert got["verdict"] == P.DIFFER, got+ assert got["not_digested"] == [3], got+ assert any("ordinal 15" in m for m in got["moved"]), got["moved"]+++def test_a_pair_where_nothing_visible_could_be_digested_is_not_a_pass():+ """Every ordinal the viewport showed had been unmounted by capture time, so the comparison+ observed the visibility but none of the content. That is not agreement."""+ got = P.compare_visible(_cap({}, ever = [3, 4]), _cap({}, ever = [3, 4]))+ # The zero-length scan control fires first, and either refusal is correct; what must not+ # happen is a MATCH.+ assert got["verdict"] == P.NOT_COMPARABLE, got+++def test_every_verdict_names_the_claim_it_is_making():+ """Three modes have meant three different things by "parity" in this file's history, and the+ difference between them is the difference between a strong result and a weak one."""+ for got in (+ P.compare_visible(_cap({1: "a"}), _cap({1: "a"})),+ P.compare_visible(_cap({1: "a"}), _cap({1: "b"})),+ P.compare_visible(_cap({}), _cap({})),+ ):+ assert got["claim"] == P.CLAIM_VISIBLE+ assert "off screen" in P.CLAIM_VISIBLE+ assert "thread-structure parity" in P.CLAIM_STRUCTURAL+ assert "NOTHING about how anything looks" in P.CLAIM_BEHAVIOURAL+++def test_the_structural_claim_does_not_promise_a_reading_the_digest_cannot_take():+ """IT USED TO SAY "whole-document structural parity: every element in the DOM is identical on+ both arms", and that is false in a way that changes conclusions rather than wording.++ `scene/parity.js` digests the thread root plus a list of overlay selectors. It is sidebar-blind+ and layout-blind by construction and it never reads geometry or CSS custom properties. Measured:+ run against a real sidebar-drag change the thread digest returned 0 of 34 differing pairs, and+ its own null control returned 0 of 34 as well, so the instrument was not discriminating in+ either direction -- while the banner above the result said every element in the DOM was+ identical. Three purpose-built captures found the same change 34 of 34.+ """+ assert "whole-document" not in P.CLAIM_STRUCTURAL+ assert "every element in the DOM" not in P.CLAIM_STRUCTURAL+ assert "thread-structure parity" in P.CLAIM_STRUCTURAL+ # And it states what it does not cover, next to the claim rather than in a source comment.+ for surface in ("sidebar", "geometry", "CSS custom properties"):+ assert surface in P.CLAIM_STRUCTURAL, surface+ assert "0 of 34" in P.CLAIM_STRUCTURAL+++def test_one_viewport_ending_empty_is_a_difference_not_a_refusal():+ """MEASURED, and it is why this check exists. On the 100K virtualization arm `model_change`+ took the thread from 12 mounted messages to 0 and it never came back: the census read 0+ messages and 2,107 elements for the rest of the film and three later actions could not run.++ Both arms had shown the same ordinals earlier in the action, so the union matched and every+ per-ordinal digest was simply absent on one side -- which the union comparison reported as NOT+ COMPARABLE. A refusal, for one arm losing the entire conversation.+ """+ base = _cap({14: "a", 15: "b"}, ever = [14, 15])+ treat = _cap({}, ever = [14, 15])+ got = P.compare_visible(base, treat)+ assert got["verdict"] == P.DIFFER, got+ assert "ended this action EMPTY" in got["reason"]+ assert "one arm lost the thread" in got["reason"]+++def test_both_viewports_ending_empty_is_still_only_a_refusal():+ """Symmetric loss is not evidence about the arm under test; it is an unusable pair."""+ got = P.compare_visible(_cap({}, ever = [14, 15]), _cap({}, ever = [14, 15]))+ assert got["verdict"] == P.NOT_COMPARABLE, got+++def test_every_mode_names_the_policy_it_is_judging_against():+ """A BARE "PARITY OK" READS FAR STRONGER THAN ANY MODE CAN SUPPORT.++ Each mode already prints the CLAIM it is making. The claim says what was compared; it does not+ say what a pass is worth, and the two exemptions are exactly what decide that. So the policy is+ printed beside the claim, per mode, and this holds that every mode has one, that all three name+ both exemptions, and that only the visible mode says it can grant the off-screen one.+ """+ from studiobench.analysis import parity as P++ assert set(P.POLICY_BY_MODE) == {"structural", "visible", "behaviour"}+ for mode, text in P.POLICY_BY_MODE.items():+ assert "idempotency" in text, mode+ assert "performance improvement" in text, mode+ assert "OFF SCREEN" in text or "off-screen" in text, mode+ assert "can GRANT the off-screen exemption" in P.POLICY_BY_MODE["visible"]+ assert "cannot grant" in P.POLICY_BY_MODE["structural"]+ assert "cannot grant either exemption" in P.POLICY_BY_MODE["behaviour"]+ # The floor survives the exemption. An exemption changes what counts as a pass; a measurement+ # with no floor under it is not a pass in the first place.+ assert "does not remove the floor" in P.POLICY_BY_MODE["visible"]+++def test_the_policy_line_is_printed_next_to_every_claim_line():+ """A constant nothing prints is a constant nobody reads."""+ from pathlib import Path++ source = (Path(__file__).resolve().parents[2] / "sweep" / "ui_parity.py").read_text(+ encoding = "utf-8"+ )+ claims = source.count("CLAIM: {P.CLAIM_")+ policies = source.count("POLICY: {P.POLICY_BY_MODE[")+ assert claims == 3, f"expected one claim line per mode, found {claims}"+ assert policies == claims, f"{claims} claim lines but {policies} policy lines"+++def test_the_mode_names_the_pull_request_template_uses_are_accepted():+ """THE TEMPLATE AND THE TOOL MUST AGREE ON WHAT THINGS ARE CALLED.++ The repository's pull request template asks for "the structural digest" and the report header+ prints "(STRUCTURAL MODE)", but the flag was spelled `--mode digest`, so a reader following+ either would type a word argparse rejected. `structural` is an alias for `digest`, not a+ fourth mode, and `behavior` for `behaviour` so the American spelling is not an error either.+ """+ from studiobench.sweep import ui_parity++ source = ui_parity.__file__+ with open(source, encoding = "utf-8") as handle:+ text = handle.read()+ for name in ("auto", "digest", "structural", "visible", "behaviour", "behavior"):+ assert f'"{name}"' in text, name+ assert '{"structural": "digest", "behavior": "behaviour"}' in textdiff --git a/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_digest.py b/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_digest.pyindex 466f21998d0..88c731cab8b 100644--- a/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_digest.py+++ b/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_digest.py@@ -234,6 +234,32 @@ def test_a_volatile_attribute_keeps_its_presence_even_though_its_value_is_droppeassert a == b+def test_the_shared_signature_still_sees_virtualization_bookkeeping():+ """WHERE THE `aria-posinset` EXCLUSION LIVES, and where it does not.++ The VISIBLE-region digest drops `aria-posinset` and `aria-setsize`, because readiness.py lets a+ windowed arm publish them on the message itself and the fully mounted arm publishes neither --+ so comparing them reports every message as changed while the content is identical. That+ exclusion is passed in by that one caller. The shared `signature`, which the whole-thread+ digest, the per-message rows and the overlays all use, keeps them: those pairs are scored only+ when NEITHER arm is windowing, and there an ordinal that appears or moves is a real difference.+ """+ plain, numbered = sigs(+ {"tag": "div", "attrs": {}}, {"tag": "div", "attrs": {"aria-posinset": "3"}}+ )+ assert plain != numbered+ three, four = sigs(+ {"tag": "div", "attrs": {"aria-posinset": "3"}},+ {"tag": "div", "attrs": {"aria-posinset": "4"}},+ )+ assert three != four+ small, large = sigs(+ {"tag": "div", "attrs": {"aria-setsize": "18"}},+ {"tag": "div", "attrs": {"aria-setsize": "180"}},+ )+ assert small != large++def test_added_and_removed_elements_move_the_signature():small, large = sigs({"tag": "div", "children": [{"tag": "span"}]},diff --git a/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_bias.py b/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_bias.pynew file mode 100644index 00000000000..5e445774807--- /dev/null+++ b/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_bias.py@@ -0,0 +1,273 @@+# 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 INSTRUMENT MUST NOT COST LESS ON THE ARM IT IS SCORING.++`streamcost.js` used to read its denominator out of the DOM:+`querySelectorAll('[data-role="assistant"]')`, last element, `textContent.length`, at both ends of+every window. That is O(the whole document) whatever matches, and the file's own note claimed it+"is identical on both arms of an A/B and cancels in a paired ratio".++It cancels between two arms that mount the same DOM. It does NOT cancel against an arm whose whole+purpose is to mount less of it: a virtualised thread pays a fraction of the cost, so the+instrument hands the treatment a saving it never earned, in the direction that flatters the+hypothesis under test. At 100K the read totalled 289.6 ms per cell, which is not a rounding error+next to the effects this campaign argues about.++This measures the residual -- the instrument's own cost on a full document minus its cost on a+windowed one -- for BOTH the old reading and the new one, on the same two pages, in the same run.+The old one is still exported as `replyCharsDom` for a once-per-cell cross-check, so both can be+driven side by side and the comparison is a measurement rather than a claim about deleted code.++ python -m pytest tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_bias.py -q -s+"""++from __future__ import annotations++import statistics+import sys+from pathlib import Path++import pytest++_HERE = Path(__file__).resolve()+_STUDIO_TESTS = _HERE.parents[3]+if str(_STUDIO_TESTS) not in sys.path:+ sys.path.insert(0, str(_STUDIO_TESTS))++_STREAMCOST_JS = _STUDIO_TESTS / "studiobench" / "instruments" / "streamcost.js"++#: The two documents. 40,000 elements is the size the 289.6 ms figure was measured against; 4,000+#: is roughly what a window of six messages leaves standing at the same rung.+FULL_ELEMENTS = 40_000+WINDOWED_ELEMENTS = 4_000++#: How many reads to take. The quantity is a few milliseconds, so one reading is noise.+READS = 40++#: What counts as "no longer biased". The old reading's residual is milliseconds per call; the new+#: one is a property read and must be under a tenth of a millisecond per call even on a loaded+#: shared machine.+MAX_WIRE_RESIDUAL_MS_PER_CALL = 0.1+++def _skip_reason() -> str | None:+ try:+ from playwright.sync_api import sync_playwright # noqa: F401+ except Exception as exc: # noqa: BLE001+ return f"playwright is not installed: {exc}"+ return None+++pytestmark = pytest.mark.skipif(_skip_reason() is not None, reason = _skip_reason() or "")+++BUILD_JS = """+(n) => {+ // A thread-shaped document: assistant messages carrying spans, which is what the real one is+ // mostly made of. The absolute count is what matters to a querySelectorAll, not the shape.+ const perMessage = 40;+ const messages = Math.max(1, Math.floor(n / perMessage));+ const parts = [];+ for (let i = 0; i < messages; i += 1) {+ const spans = new Array(perMessage - 1).fill('<span>token </span>').join("");+ parts.push('<div data-role="assistant">' + spans + '</div>');+ }+ document.body.innerHTML = parts.join("");+ return document.getElementsByTagName("*").length;+}+"""++#: One SSE frame in exactly the shape `_gguf_chat_delta_line` emits, fed through the page's own+#: TextDecoder so the instrument's real hook sees it.+FEED_JS = """+(frames) => {+ const enc = new TextEncoder();+ const dec = new TextDecoder();+ let sent = 0;+ for (let i = 0; i < frames; i += 1) {+ const piece = "token " + i + " ";+ sent += piece.length;+ const frame = 'data: ' + JSON.stringify({+ id: "x", object: "chat.completion.chunk", model: "m",+ choices: [{ index: 0, delta: { content: piece }, finish_reason: null }],+ }) + "\\n\\n";+ dec.decode(enc.encode(frame));+ }+ return sent;+}+"""++TIME_JS = """+([which, reads]) => {+ const sc = window.__sb.streamcost;+ const fn = which === "wire" ? () => sc.replyChars() : () => sc.replyCharsDom(true);+ fn(); // warm, so the first call's one-off costs are not the reading+ const t = performance.now();+ for (let i = 0; i < reads; i += 1) fn();+ return (performance.now() - t) / reads;+}+"""++[email protected](scope = "module")+def browser():+ from playwright.sync_api import sync_playwright+ with sync_playwright() as p:+ try:+ b = p.chromium.launch(args = ["--no-sandbox"])+ except Exception as exc: # noqa: BLE001+ pytest.skip(f"chromium could not be launched: {exc}")+ yield b+ b.close()+++def _page(browser, elements: int):+ page = browser.new_page(viewport = {"width": 900, "height": 600})+ page.set_content("<!doctype html><meta charset=utf-8><body></body>")+ # BEFORE the document exists, exactly as the real harness installs it via add_init_script:+ # the hook has to be on TextDecoder.prototype before any decode happens.+ page.add_script_tag(content = _STREAMCOST_JS.read_text(encoding = "utf-8"))+ got = page.evaluate(BUILD_JS, elements)+ page.evaluate(FEED_JS, 200)+ return page, got+++def _per_call_ms(page, which: str) -> float:+ # Median of several passes. A single pass on a shared machine picks up whatever else is+ # running, and this box is running other people's sweeps.+ return statistics.median(page.evaluate(TIME_JS, [which, READS]) for _ in range(5))+++def test_the_wire_denominator_is_the_same_price_on_a_windowed_document(browser, capsys):+ """THE RESIDUAL, MEASURED, for the old reading and the new one on the same two documents."""+ full, full_n = _page(browser, FULL_ELEMENTS)+ win, win_n = _page(browser, WINDOWED_ELEMENTS)+ try:+ dom_full = _per_call_ms(full, "dom")+ dom_win = _per_call_ms(win, "dom")+ wire_full = _per_call_ms(full, "wire")+ wire_win = _per_call_ms(win, "wire")+ finally:+ full.close()+ win.close()++ dom_residual = dom_full - dom_win+ wire_residual = wire_full - wire_win+ with capsys.disabled():+ print(+ f"\n documents: full {full_n:,} elements, windowed {win_n:,} elements\n"+ f" OLD reading (querySelectorAll, O(document)):\n"+ f" full {dom_full:.4f} ms/call, windowed {dom_win:.4f} ms/call, "+ f"RESIDUAL {dom_residual:+.4f} ms/call\n"+ f" NEW reading (wire counter, O(1)):\n"+ f" full {wire_full:.4f} ms/call, windowed {wire_win:.4f} ms/call, "+ f"RESIDUAL {wire_residual:+.4f} ms/call"+ )++ # The old reading really is cheaper on the smaller document. If this ever stops being true the+ # test below is proving nothing, so it is asserted rather than assumed.+ assert dom_residual > 0, (+ "the O(document) read was not measurably cheaper on the windowed document, so this "+ f"machine cannot demonstrate the bias at all (full {dom_full}, windowed {dom_win})"+ )+ # And the new one is not.+ assert abs(wire_residual) < MAX_WIRE_RESIDUAL_MS_PER_CALL, (+ f"the wire counter cost {wire_residual:+.4f} ms/call more on the full document than on "+ "the windowed one, so it still carries a bias in the treatment's favour"+ )+ # The point of the whole exercise: whatever is left is a small fraction of what was there.+ assert abs(wire_residual) < dom_residual / 10+++def test_the_wire_count_is_identical_on_both_documents_for_identical_traffic(browser):+ """The denominator itself, not just its cost. Both arms are fed by the SAME pacer, so the+ counter has to be a function of the bytes and of nothing else -- least of all of how much of+ the thread the arm chose to mount."""+ full, _ = _page(browser, FULL_ELEMENTS)+ win, _ = _page(browser, WINDOWED_ELEMENTS)+ try:+ a = full.evaluate("() => window.__sb.streamcost.wireStats()")+ b = win.evaluate("() => window.__sb.streamcost.wireStats()")+ finally:+ full.close()+ win.close()+ assert a["wire_chars"] == b["wire_chars"] > 0+ assert a["wire_frames"] == b["wire_frames"] == 200+ assert a["wire_parse_failures"] == b["wire_parse_failures"] == 0+ # The DOM reading, by contrast, is a different number on the two documents -- which is exactly+ # why it could not be the denominator.+ assert a["wire_chars"] == 200 * len("token 0 ") or a["wire_chars"] > 0+++def test_the_counter_survives_a_frame_split_across_two_decode_calls(browser):+ """A decode() call is a slice of the socket, not an SSE frame. A counter that assumed frame+ alignment would silently under-count exactly when the renderer is jammed and the chunks arrive+ ragged, which is the condition the whole instrument exists to measure."""+ page, _ = _page(browser, WINDOWED_ELEMENTS)+ try:+ before = page.evaluate("() => window.__sb.streamcost.wireStats()")+ got = page.evaluate("""+ () => {+ const enc = new TextEncoder();+ const dec = new TextDecoder();+ const frame = 'data: ' + JSON.stringify({+ choices: [{ index: 0, delta: { content: "abcdefghij" }, finish_reason: null }],+ }) + "\\n\\n";+ // Split in the middle of the JSON body, which is the worst place for it.+ const cut = Math.floor(frame.length / 2);+ dec.decode(enc.encode(frame.slice(0, cut)));+ const mid = window.__sb.streamcost.wireStats().wire_chars;+ dec.decode(enc.encode(frame.slice(cut)));+ return { mid, after: window.__sb.streamcost.wireStats() };+ }+ """)+ finally:+ page.close()+ # Nothing is counted until the frame is complete, and then all ten characters are.+ assert got["mid"] == before["wire_chars"]+ assert got["after"]["wire_chars"] == before["wire_chars"] + 10+ assert got["after"]["wire_parse_failures"] == 0+++def test_reasoning_and_content_are_both_counted(browser):+ """`_gguf_chat_delta_line` emits reasoning as `reasoning_content` WITH `content: ""` beside+ it, so summing the two is not double counting."""+ page, _ = _page(browser, WINDOWED_ELEMENTS)+ try:+ got = page.evaluate("""+ () => {+ const enc = new TextEncoder();+ const dec = new TextDecoder();+ const before = window.__sb.streamcost.wireStats().wire_chars;+ const frame = 'data: ' + JSON.stringify({+ choices: [{ index: 0, delta: { reasoning_content: "12345", content: "" } }],+ }) + "\\n\\n";+ dec.decode(enc.encode(frame));+ return window.__sb.streamcost.wireStats().wire_chars - before;+ }+ """)+ finally:+ page.close()+ assert got == 5+++def test_a_malformed_frame_is_counted_as_a_failure_not_silently_dropped(browser):+ """A denominator that is short by an unknown amount inflates every cost above it."""+ page, _ = _page(browser, WINDOWED_ELEMENTS)+ try:+ got = page.evaluate("""+ () => {+ const enc = new TextEncoder();+ const dec = new TextDecoder();+ const before = window.__sb.streamcost.wireStats();+ dec.decode(enc.encode('data: {not json at all\\n\\n'));+ const after = window.__sb.streamcost.wireStats();+ return { failures: after.wire_parse_failures - before.wire_parse_failures,+ chars: after.wire_chars - before.wire_chars };+ }+ """)+ finally:+ page.close()+ assert got["failures"] == 1+ assert got["chars"] == 0diff --git a/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_integrity.py b/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_integrity.pynew file mode 100644index 00000000000..02556f6e297--- /dev/null+++ b/tests/studio/studiobench/instruments/selftest/test_studiobench_streamcost_integrity.py@@ -0,0 +1,504 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A DENOMINATOR THAT IS SHORT BY AN UNKNOWN AMOUNT MUST NOT BE SCORED.++`streamcost` counts the characters delivered on the SSE wire and uses the delta across a window as+the denominator of every cost-per-character figure. A frame that cannot be parsed -- unrelated+`TextDecoder` traffic appended while `pending` holds a split SSE frame, a truncated stream, a+provider that emits something other than the expected shape -- increments a diagnostic counter and+leaves `wireChars` short.++Counting the failures was never the problem. NOTHING CONSULTED THE COUNT: not `streamcost.py`, not+`scoring/from_payload.py`. So the affected delta was still accepted as a denominator and every+cost-per-character derived from it came out inflated by an unknown factor, silently, in the+direction that makes the app look more expensive per character than it is.++Two ways to be short, and both are checked here: a frame that failed to parse INSIDE the window,+and an unterminated frame still sitting in the buffer at the window's close.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++_HERE = Path(__file__).resolve()+_STUDIO_TESTS = _HERE.parents[3]+if str(_STUDIO_TESTS) not in sys.path:+ sys.path.insert(0, str(_STUDIO_TESTS))++_STREAMCOST_JS = _STUDIO_TESTS / "studiobench" / "instruments" / "streamcost.js"+++def _skip_reason() -> str | None:+ try:+ from playwright.sync_api import sync_playwright # noqa: F401+ except Exception as exc: # noqa: BLE001+ return f"playwright is not installed: {exc}"+ return None+++pytestmark = pytest.mark.skipif(_skip_reason() is not None, reason = _skip_reason() or "")++[email protected](scope = "module")+def browser():+ from playwright.sync_api import sync_playwright+ with sync_playwright() as p:+ try:+ b = p.chromium.launch(args = ["--no-sandbox"])+ except Exception as exc: # noqa: BLE001+ pytest.skip(f"chromium could not be launched: {exc}")+ yield b+ b.close()+++def page(browser):+ pg = browser.new_page(viewport = {"width": 900, "height": 600})+ pg.set_content("<!doctype html><meta charset=utf-8><body></body>")+ pg.add_script_tag(content = _STREAMCOST_JS.read_text(encoding = "utf-8"))+ yield pg+ pg.close()+++def _feed(page, text: str) -> None:+ """Push bytes through the real `TextDecoder.prototype.decode` hook, AS ONE RESPONSE.++ The decoder is reused across calls because that is what the app does: `chat-api.ts` builds one+ `TextDecoder` per streaming request and calls `decode(value, {stream: true})` on it for every+ chunk of that response. A split frame is therefore always two chunks through the SAME decoder,+ which is what the reassembly tests below mean by a split. Building a fresh decoder per chunk+ would model a socket rather than a response, and reassembly state is scoped per decoder.+ """+ page.evaluate(+ """(text) => {+ const bytes = new TextEncoder().encode(text);+ if (!window.__testDecoder) window.__testDecoder = new TextDecoder();+ window.__testDecoder.decode(bytes);+ }""",+ text,+ )+++def _feed_other(page, text: str) -> None:+ """Push bytes through a DIFFERENT decoder, as any other component of the page does.++ `TextDecoder.prototype.decode` is hooked page-wide, so every decoder in the document arrives+ here: the app builds one per streaming request and has six other read loops besides the chat+ one. A decoder that is not carrying the relay's framing is not the stream being measured.+ """+ page.evaluate(+ """(text) => {+ const bytes = new TextEncoder().encode(text);+ if (!window.__otherDecoder) window.__otherDecoder = new TextDecoder();+ window.__otherDecoder.decode(bytes);+ }""",+ text,+ )+++def _end_response(page) -> None:+ """Abandon this response's decoder, as the app does when a stream ends or is aborted.++ The next `_feed` builds a new one, exactly as the next `send_turn` does.+ """+ page.evaluate("() => { window.__testDecoder = null; }")+++def _frame(content: str) -> str:+ return 'data: {"choices":[{"delta":{"content":' + __import__("json").dumps(content) + "}}]}\n\n"+++def test_a_clean_stream_is_scoreable_and_counts_every_character(page):+ """The control. Without this the failure tests below could pass on an instrument that marks+ everything unscoreable and counts nothing."""+ page.evaluate("() => window.__sb.streamcost.reset()")+ _feed(page, _frame("hello") + _frame(" world"))+ assert page.evaluate("() => window.__sb.streamcost.replyChars()") == len("hello world")+ got = page.evaluate("() => window.__sb.streamcost.wireIntegrity()")+ assert got == {+ "failures": 0,+ "pending_chars": 0,+ "carried_flushes": got["carried_flushes"],+ }, got+++def test_an_unparseable_frame_is_visible_at_the_window_boundary(page):+ """The counter has to be readable at O(1) cost at both ends of a window, or a window cannot+ tell a failure that happened inside it from one that happened before it."""+ page.evaluate("() => window.__sb.streamcost.reset()")+ _feed(page, _frame("good"))+ before = page.evaluate("() => window.__sb.streamcost.wireIntegrity()")+ _feed(page, "data: {this is not json}\n\n")+ after = page.evaluate("() => window.__sb.streamcost.wireIntegrity()")+ assert after["failures"] > before["failures"], (before, after)+++def test_an_unterminated_frame_is_reported_as_still_buffered(page):+ """The other way to be short. The frame never completed, so its characters were never counted,+ and at the close of the window the count is missing them with nothing to say so."""+ page.evaluate("() => window.__sb.streamcost.reset()")+ _feed(page, 'data: {"choices":[{"delta":{"content":"half a fra')+ got = page.evaluate("() => window.__sb.streamcost.wireIntegrity()")+ assert got["pending_chars"] > 0, got+++# ── the consumer, which is where the defect actually lived ──────────+++def _instrument(page):+ from studiobench.instruments.streamcost import StreamCostInstrument++ inst = StreamCostInstrument()+ inst._eval = lambda script, *a: page.evaluate(script, *a) # noqa: SLF001+ inst.unavailable = None+ return inst+++class _Window:+ duration_ms = 1000.0+++def test_a_window_containing_a_parse_failure_is_marked_unscoreable(page):+ """THE DEFECT. Before the fix this window's `reply_chars_delta` was published with nothing to+ indicate that the wire count underneath it had lost an unknown number of characters, and every+ cost-per-character derived from it was inflated."""+ inst = _instrument(page)+ page.evaluate("() => window.__sb.streamcost.reset()")+ inst.open(_Window())+ _feed(page, _frame("counted"))+ _feed(page, "data: {this is not json}\n\n")+ out = inst.close(_Window())+ assert out["reply_chars_scoreable"] is False, out+ assert out["wire_parse_failures_in_window"] >= 1+ assert "short by an unknown amount" in out["reply_chars_unscoreable_reason"]+++def test_a_window_ending_mid_frame_is_marked_unscoreable(page):+ inst = _instrument(page)+ page.evaluate("() => window.__sb.streamcost.reset()")+ inst.open(_Window())+ _feed(page, _frame("counted"))+ _feed(page, 'data: {"choices":[{"delta":{"content":"unterminat')+ out = inst.close(_Window())+ assert out["reply_chars_scoreable"] is False, out+ assert out["wire_pending_chars_at_close"] > 0+++def test_a_clean_window_stays_scoreable(page):+ """The fix must not mark everything unscoreable; a check that never passes is as useless as one+ that never fails."""+ inst = _instrument(page)+ page.evaluate("() => window.__sb.streamcost.reset()")+ inst.open(_Window())+ _feed(page, _frame("all") + _frame(" good"))+ out = inst.close(_Window())+ assert out["reply_chars_scoreable"] is True, out+ assert out["wire_parse_failures_in_window"] == 0+ assert out["reply_chars_delta"] == len("all good")+++# ── a frame split INSIDE the "data:" prefix ─────────────────────────+#+# The hook starts buffering when a chunk contains a complete `data:`. The socket does not respect+# that boundary: it can cut a frame anywhere, including between the "da" and the "ta:". Neither+# half then contains the marker and neither completes a buffered frame, so both were discarded --+# and the frame's characters left the denominator WITHOUT incrementing `wireParseFailures`, so the+# window-integrity check above could not see it either. Later frames make the window look+# scoreable while the count underneath it is short, which inflates every cost-per-character+# derived from it, at exactly the moment the instrument exists to measure: chunks arrive ragged+# when the renderer is jammed.+++def _halves(text: str, at: int) -> tuple:+ return text[:at], text[at:]+++def test_the_counter_survives_a_split_inside_the_data_prefix(page):+ """THE DEFECT. Two chunks, neither of which contains `data:`, and one whole frame between+ them."""+ page.evaluate("() => window.__sb.streamcost.reset()")+ head, tail = _halves(_frame("split marker"), 2)+ assert "data:" not in head and "data:" not in tail, (head, tail)+ _feed(page, head)+ _feed(page, tail)+ assert page.evaluate("() => window.__sb.streamcost.replyChars()") == len("split marker")+ got = page.evaluate("() => window.__sb.streamcost.wireIntegrity()")+ assert got == {+ "failures": 0,+ "pending_chars": 0,+ "carried_flushes": got["carried_flushes"],+ }, got+++def test_a_held_marker_fragment_is_reported_as_buffered_rather_than_lost(page):+ """While the second half has not arrived, the frame is not counted -- so a window closing here+ has a short denominator and has to say so. Dropping the fragment reported `pending_chars: 0`,+ which is the instrument stating that nothing was outstanding while a frame was."""+ page.evaluate("() => window.__sb.streamcost.reset()")+ _feed(page, _frame("orphan")[:3])+ got = page.evaluate("() => window.__sb.streamcost.wireIntegrity()")+ assert got["pending_chars"] > 0, got+ assert got["failures"] == 0, got+++def test_a_marker_split_three_ways_is_still_one_frame(page):+ """The socket is under no obligation to cut in a convenient place, and a fix that only handles+ a two-way split is a fix for the example rather than for the defect."""+ page.evaluate("() => window.__sb.streamcost.reset()")+ text = _frame("three ways")+ for part in (text[:1], text[1:2], text[2:4], text[4:]):+ _feed(page, part)+ assert page.evaluate("() => window.__sb.streamcost.replyChars()") == len("three ways")+++def test_unrelated_text_ending_in_a_marker_letter_does_not_corrupt_the_next_frame(page):+ """THE WAY THIS FIX COULD HAVE BEEN WORSE THAN THE BUG. Any page traffic may end in "d", "da"+ or "data", and gluing that onto the front of a real frame makes "ddata: {...}", which no longer+ starts with the marker and would be skipped in silence."""+ page.evaluate("() => window.__sb.streamcost.reset()")+ _feed(page, "an unrelated chunk that ends in a d")+ _feed(page, _frame("counted anyway"))+ assert page.evaluate("() => window.__sb.streamcost.replyChars()") == len("counted anyway")+ got = page.evaluate("() => window.__sb.streamcost.wireIntegrity()")+ assert got == {+ "failures": 0,+ "pending_chars": 0,+ "carried_flushes": got["carried_flushes"],+ }, got+++def test_the_speculative_buffer_cannot_grow_with_unrelated_traffic(page):+ """The memory bound, asserted rather than argued. A fix that buffered every chunk in the page+ on the chance that one of them was an SSE frame would be worse than the bug it fixes: a tail+ short enough to be a partial `data:` is at most four characters."""+ page.evaluate("() => window.__sb.streamcost.reset()")+ for i in range(50):+ _feed(page, f"chunk {i} of unrelated traffic, ending in data")+ got = page.evaluate("() => window.__sb.streamcost.wireIntegrity()")+ assert got["pending_chars"] <= 4, got+ assert got["failures"] == 0, got+++def test_a_window_whose_only_frame_was_split_in_the_marker_still_counts_it(page):+ """THE CONSEQUENCE at the window boundary, which is where the number is used. The window used+ to close scoreable, with a `reply_chars_delta` of zero over a frame that really was delivered:+ a denominator short by an unknown amount wearing a clean bill of health."""+ inst = _instrument(page)+ page.evaluate("() => window.__sb.streamcost.reset()")+ inst.open(_Window())+ head, tail = _halves(_frame("inside the window"), 3)+ _feed(page, head)+ _feed(page, tail)+ out = inst.close(_Window())+ assert out["reply_chars_delta"] == len("inside the window"), out+ assert out["reply_chars_scoreable"] is True, out+++def test_a_failure_before_the_window_does_not_taint_it(page):+ """Attribution matters: a window is scoreable or not on its OWN evidence. Counting total+ failures rather than the delta would condemn every window after the first bad frame."""+ page.evaluate("() => window.__sb.streamcost.reset()")+ _feed(page, "data: {this is not json}\n\n")+ inst = _instrument(page)+ inst.open(_Window())+ _feed(page, _frame("clean"))+ out = inst.close(_Window())+ assert out["reply_chars_scoreable"] is True, out+++# ── the OTHER end of a split, which is the window that opens on it ──+++def test_a_window_that_opens_on_a_half_delivered_frame_is_not_scoreable(page):+ """THE DEFECT, one window to the right of the one already covered above.++ `reset()` cannot clear `pending` -- it holds half a frame whose other half has not arrived --+ so a frame the socket cut across a window boundary is still buffered when the NEXT window+ opens. Its suffix lands inside that window, the parser adds the WHOLE frame's characters+ there and empties the buffer, and the close reading then sees zero failures and zero residual+ and calls the window scoreable. Part of its denominator was delivered before it opened, so+ `reply_chars_delta` is not "characters delivered in this window" and the cost per character+ above it is wrong in a direction nothing in the row discloses.+ """+ page.evaluate("() => window.__sb.streamcost.reset()")+ head, tail = _halves(_frame("straddles the boundary"), 30)+ assert "\n\n" not in head, head+ # The first window closes mid-frame: already refused, by `wire_pending_chars_at_close`.+ first = _instrument(page)+ first.open(_Window())+ _feed(page, head)+ closed = first.close(_Window())+ assert closed["reply_chars_scoreable"] is False, closed+ assert closed["wire_pending_chars_at_close"] > 0, closed++ # The second opens holding that frame, and is handed its whole character count.+ second = _instrument(page)+ second.open(_Window())+ _feed(page, tail)+ out = second.close(_Window())+ assert out["wire_parse_failures_in_window"] == 0, out+ assert out["wire_pending_chars_at_close"] == 0, out+ assert out["wire_pending_chars_at_open"] > 0, out+ # The whole frame was charged here, including the part delivered in the window before it.+ assert out["reply_chars_delta"] == len("straddles the boundary"), out+ assert out["reply_chars_scoreable"] is False, out+ assert "already buffered" in out["reply_chars_unscoreable_reason"], out+++def test_a_window_that_opens_on_an_empty_buffer_is_still_scoreable(page):+ """The positive control. A refusal that fires on every window measures nothing at all."""+ page.evaluate("() => window.__sb.streamcost.reset()")+ _feed(page, _frame("before"))+ inst = _instrument(page)+ inst.open(_Window())+ _feed(page, _frame("during"))+ out = inst.close(_Window())+ assert out["wire_pending_chars_at_open"] == 0, out+ assert out["reply_chars_scoreable"] is True, out+ assert out["reply_chars_delta"] == len("during"), out+++# ── an aborted response must not poison the next one ──────────────────────────+++def test_an_aborted_frame_does_not_follow_the_stream_that_replaces_it(page):+ """REGRESSION. `stop_generation` cuts a socket mid-frame, which is what it is for.++ The reassembly buffer used to be one page-wide variable, so the abandoned JSON tail waited+ there for the next response. `send_turn` follows `stop_generation` in all three shipped+ schedules, and its first chunk was glued behind that tail: the merged part no longer began+ `data:`, so it was skipped by `continue` WITHOUT counting a parse failure, and the denominator+ went quietly short -- the one outcome this file exists to prevent. The residue never cleared+ either, so `pending_chars` stayed above zero and every later window was refused as well.+ """+ page.evaluate("() => window.__sb.streamcost.reset()")+ # A response aborted in the middle of a frame.+ _feed(page, 'data: {"choices":[{"delta":{"content":"half a re')+ assert page.evaluate("() => window.__sb.streamcost.wireIntegrity()")["pending_chars"] > 0+ _end_response(page)++ # The next turn is a new response, and it is intact.+ page.evaluate("() => window.__sb.streamcost.reset()")+ _feed(page, _frame("hello"))+ assert page.evaluate("() => window.__sb.streamcost.replyChars()") == len("hello")+ got = page.evaluate("() => window.__sb.streamcost.wireIntegrity()")+ assert got == {+ "failures": 0,+ "pending_chars": 0,+ "carried_flushes": got["carried_flushes"],+ }, got+++def test_a_split_inside_one_response_still_reassembles_after_an_abort(page):+ """The scoping must not cost a genuine split its repair: same decoder, still one frame."""+ page.evaluate("() => window.__sb.streamcost.reset()")+ _feed(page, 'data: {"choices":[{"delta":{"content":"abandoned')+ _end_response(page)++ page.evaluate("() => window.__sb.streamcost.reset()")+ _feed(page, 'data: {"choices":[{"delta":{"con')+ _feed(page, 'tent":"rejoined"}}]}\n\n')+ assert page.evaluate("() => window.__sb.streamcost.replyChars()") == len("rejoined")+ assert page.evaluate("() => window.__sb.streamcost.wireIntegrity()")["pending_chars"] == 0+++def test_an_unrelated_decoder_does_not_hide_a_frame_the_stream_is_holding(page):+ """THE DEFECT. `active` moved to whichever decoder decoded last, before anything had looked at+ the chunk, so any other TextDecoder in the page took the report away from the stream.++ Its buffer is empty, so `wireIntegrity` answered "nothing outstanding" while the SSE decoder+ held half a frame: the window closing there published a denominator short by that frame with a+ clean bill of health, and the window the suffix landed in was handed the whole frame -- both+ ends of the split accepted, which is the one outcome this file exists to prevent."""+ page.evaluate("() => window.__sb.streamcost.reset()")+ head, tail = _halves(_frame("straddles the boundary"), 30)+ assert "\n\n" not in head, head++ first = _instrument(page)+ first.open(_Window())+ _feed(page, head)+ _feed_other(page, "an unrelated chunk of page traffic")+ closed = first.close(_Window())+ assert closed["wire_pending_chars_at_close"] > 0, closed+ assert closed["reply_chars_scoreable"] is False, closed++ second = _instrument(page)+ second.open(_Window())+ _feed(page, tail)+ out = second.close(_Window())+ assert out["wire_pending_chars_at_open"] > 0, out+ assert out["reply_chars_delta"] == len("straddles the boundary"), out+ assert out["reply_chars_scoreable"] is False, out+++def test_a_window_opening_after_an_abort_keeps_the_next_response_scoreable(page):+ """THE OTHER HALF OF THE SAME SCOPING, and a reading that was being thrown away.++ `open()` samples the integrity BEFORE the action has created the response it will measure, so+ the buffer it sees is still the aborted one. That half frame is never completed and never+ counted anywhere, so it takes nothing out of this window's delta -- but `pending_chars > 0` at+ the open refused the window on its own, and `send_turn` follows `stop_generation` in all three+ shipped schedules. Every socket split at the abort cost the next window its denominator."""+ page.evaluate("() => window.__sb.streamcost.reset()")+ _feed(page, 'data: {"choices":[{"delta":{"content":"half a re')+ _end_response(page)++ inst = _instrument(page)+ inst.open(_Window())+ assert inst._integrity_open["pending_chars"] > 0, inst._integrity_open # noqa: SLF001+ _feed(page, _frame("a clean reply"))+ out = inst.close(_Window())+ assert out["reply_chars_delta"] == len("a clean reply"), out+ assert out["wire_carried_frames_counted_in_window"] == 0, out+ assert out["reply_chars_scoreable"] is True, out+++# ── the tail of a split frame is stream traffic on the numerator too ─────────+#+# `noteSse` was gated on the marker while the character counter was gated on `looksSse ||+# pending`, so the two halves of one frame were attributed to two different things: the tail's+# characters went into the denominator and its render work went nowhere. The bias is downward on+# `stream_delta_cost_ms_per_kchar` and it grows with fragmentation, which is the regime the+# instrument exists to measure.+++def test_the_tail_of_a_split_frame_is_counted_as_stream_traffic(page):+ """THE DEFECT, at the quantity the numerator is built from.++ The frame is cut inside its JSON body, so the head carries `data:` and the tail carries no+ marker at all -- it is the rest of the body and the blank line. The tail still completes the+ frame and its characters are counted, so a chunk that the instrument scores the cost of has+ to be a chunk the instrument charges the cost to."""+ inst = _instrument(page)+ page.evaluate("() => window.__sb.streamcost.reset()")+ inst.open(_Window())+ frame = _frame("cut inside the body")+ head, tail = _halves(frame, frame.index("cut") + 3)+ assert "data:" in head and "data:" not in tail, (head, tail)+ _feed(page, head)+ _feed(page, tail)+ out = inst.close(_Window())++ # Both chunks carried this response's bytes, so both are stream chunks.+ assert out["sse_chunks"] == 2, out+ assert out["reply_chars_delta"] == len("cut inside the body"), out+ assert out["reply_chars_scoreable"] is True, out+++def test_unrelated_traffic_is_still_not_stream_traffic(page):+ """The control the widened condition must not break. A decoder carrying no marker and holding+ no frame of its own is not the stream, and feeding it must not add a chunk."""+ inst = _instrument(page)+ page.evaluate("() => window.__sb.streamcost.reset()")+ inst.open(_Window())+ _feed(page, _frame("real"))+ _feed_other(page, "nothing to do with the relay")+ out = inst.close(_Window())++ assert out["sse_chunks"] == 1, out+ assert out["reply_chars_delta"] == len("real"), outdiff --git a/tests/studio/studiobench/instruments/streamcost.js b/tests/studio/studiobench/instruments/streamcost.jsindex 1772a9f3b2b..8ab85a61226 100644--- a/tests/studio/studiobench/instruments/streamcost.js+++ b/tests/studio/studiobench/instruments/streamcost.js@@ -118,6 +118,108 @@overheadMs: 0,decodeCalls: 0,everStreamed: false,+ // CUMULATIVE characters of assistant text this page has been SENT, counted off the wire.+ // Never reset by `reset()`: the denominator a window wants is the growth across it, which is+ // the difference of two readings of this, and resetting it per window would make every+ // reading zero.+ wireChars: 0,+ wireFrames: 0,+ wireParseFailures: 0,+ // How many times a frame that was ALREADY BUFFERED when this call began was completed and+ // counted. Cumulative and never reset, for the same reason `wireChars` is not: a window wants+ // the growth across it. This is what turns "a buffer was pending when the window opened" into+ // "characters that arrived before this window were counted inside it", which is the thing that+ // actually makes the denominator wrong. A buffer left behind by an ABORTED response never+ // completes, so it never increments this and never costs the next response its reading.+ carriedFlushes: 0,+ };+ // The incremental SSE buffer. A decode() call is a slice of the socket, not an SSE frame: one+ // call can carry three frames and half of a fourth. Whatever is left after the last blank line+ // stays here until the rest of it arrives.+ //+ // PER DECODER, NOT PER PAGE. A `TextDecoder` belongs to ONE response: the app builds a new one+ // beside its own `buffer` for every streaming request, so no legitimate frame ever spans two of+ // them. A single page-wide buffer therefore did not model reassembly, it modelled the socket,+ // and `stop_generation` exists to cut a socket mid-frame. The abandoned JSON tail then had no+ // `\n\n` to close it, so the next response's first chunk was glued behind it, the merged part+ // failed `startsWith("data:")` and was skipped by `continue` WITHOUT counting a parse failure --+ // the silently short denominator this file's own comments call the unacceptable outcome. Worse,+ // the residue never cleared, so `pending_chars` stayed above zero and `reply_chars_scoreable`+ // refused EVERY window from the abort onwards, and once non-empty it pulled unrelated decoder+ // traffic in through the `pending.length > 0` branch below.+ //+ // Keyed weakly, so a finished response's buffer is collected with its decoder rather than+ // retained. Within one response the same decoder is reused for every `decode(chunk, {stream:+ // true})` call, so a genuine split still reassembles exactly as before.+ const DECODER_STATE = new WeakMap();+ const stateFor = (decoder) => {+ let st = DECODER_STATE.get(decoder);+ if (!st) {+ st = { pending: "", markerTail: "" };+ DECODER_STATE.set(decoder, st);+ }+ return st;+ };+ //: The decoder that most recently delivered a chunk, which is the stream a window is measuring.+ //: `wireIntegrity` reports THIS buffer: half a frame of the response being measured is a short+ //: denominator and must refuse the window, while half a frame of a response that was aborted+ //: three slots ago says nothing about it.+ let active = { pending: "", markerTail: "" };+ //: The decoder holding a speculative marker fragment, if any, and there is only ever one worth+ //: holding. A fragment is at most four characters and lives on the decoder that produced it, but+ //: it has to be REPORTED whoever holds it: a decoder whose first chunk is "dat" has not been+ //: identified as the stream yet, and leaving its fragment out of `wireIntegrity` would be the+ //: instrument saying nothing was outstanding while a frame was. Erring the other way costs at+ //: most four characters of unrelated traffic marking a window unscoreable, which is the+ //: direction this file has always chosen. It is dropped as soon as some OTHER decoder is+ //: identified as the stream, so an unrelated chunk that happened to end in "data" cannot leave a+ //: permanent residue behind it.+ let markerHold = null;+ const setMarkerTail = (st, frag) => {+ st.markerTail = frag;+ if (frag) markerHold = st;+ else if (markerHold === st) markerHold = null;+ };+ const heldMarkerChars = () =>+ active.markerTail.length ++ (markerHold && markerHold !== active ? markerHold.markerTail.length : 0);+ // A frame is a few hundred bytes. If this ever grows past a sane bound the stream is not what+ // we think it is, and dropping the buffer is better than growing it without limit inside a hook+ // that runs fourteen times a second.+ const MAX_PENDING_CHARS = 262144;++ // ── the frame marker, and the halves of it a split can leave ──────────────────────────────────+ //+ // The socket can cut a frame ANYWHERE, including inside these five characters: one decode()+ // returns "da" and the next "ta: {...}\n\n". Neither chunk contains the marker, so the detector+ // below saw two unrelated chunks, discarded both, and lost the frame WITHOUT counting a parse+ // failure -- which left the wire character count short with nothing anywhere to say so, and+ // `reply_chars_scoreable` reporting the window as sound. The denominator going quietly short+ // inflates every cost-per-character above it, and it goes short exactly when the renderer is+ // jammed and chunks arrive ragged, which is the moment the instrument exists to measure.+ const SSE_MARKER = "data:";+ // The fragment of the marker the last chunk MIGHT have ended on. At most four characters ("d",+ // "da", "dat", "data"), so this cannot become the memory hazard MAX_PENDING_CHARS guards+ // `pending` against: buffering whole unrelated TextDecoder chunks on the chance that one of them+ // is an SSE frame would be a worse bug than the one being fixed.+ // Lives in the per-decoder state above, for the same reason `pending` does.++ //: The longest tail of `s` that is a PROPER PREFIX of the marker, or "".+ const partialMarkerTail = (s) => {+ for (let n = Math.min(SSE_MARKER.length - 1, s.length); n > 0; n -= 1) {+ if (s.endsWith(SSE_MARKER.slice(0, n))) return SSE_MARKER.slice(0, n);+ }+ return "";+ };++ //: Does `s` CONTINUE the marker that `frag` started? This is what keeps a speculative fragment+ //: harmless. Unrelated traffic ending in "d" would otherwise be glued onto the front of the next+ //: chunk, and a real frame arriving there would become "ddata: {...}", which does not start with+ //: the marker and would be skipped in silence -- the same defect one step to the left.+ const continuesMarker = (frag, s) => {+ const rest = SSE_MARKER.slice(frag.length);+ const n = Math.min(rest.length, s.length);+ return n > 0 && s.slice(0, n) === rest.slice(0, n);};const now = () => performance.now();@@ -157,6 +259,72 @@const chan = new MessageChannel();chan.port1.onmessage = closeChain;+ // ── the wire-side character counter ───────────────────────────────────────────────────────+ //+ // THIS REPLACES AN O(DOCUMENT) READ THAT BIASED THE COMPARISON, and the bias only became+ // visible once an arm existed that changes the size of the document.+ //+ // The denominator used to be read from the DOM: `querySelectorAll('[data-role="assistant"]')`,+ // last element, `textContent.length`, at both ends of every window. That is O(the whole+ // document) regardless of how few elements match, and it measured 3.9 ms per call against+ // 42,000 elements -- 38.8 ms per cell at 10K and 289.6 ms at 100K. The file's own note said it+ // "is identical on both arms of an A/B and cancels in a paired ratio". That was true of every+ // arm this project had ever run, and it is FALSE for a virtualised one: an arm whose entire+ // purpose is to put a tenth of the elements in the document pays a tenth of this cost, so the+ // instrument hands the treatment a saving it did not earn, in the direction that flatters+ // exactly the hypothesis under test. Nothing measured on such an arm could be quoted while that+ // read was in the paired path.+ //+ // Counting off the wire removes it rather than balancing it. Both arms are fed by the SAME+ // pacer -- that is a design invariant of runtime/ab.py, not a coincidence -- so the bytes are+ // identical by construction and this counter is identical by construction. It is O(the chunk),+ // about fourteen chunks a second, and independent of the thread's size, the rung and the arm.+ //+ // It is also a BETTER denominator than the one it replaces. The DOM read measured the last+ // assistant message, so a `send_turn` mid-film made the reading shrink and the window's growth+ // unmeasurable ("it is a different message"). Characters delivered in the window is the+ // quantity the cost per character actually wants, and it does not care how many messages they+ // were spread over.+ const countDeltaChars = (st, text, carriedMarker) => {+ const carried = st.pending.length > 0 || Boolean(carriedMarker);+ st.pending += text;+ if (st.pending.length > MAX_PENDING_CHARS) {+ S.wireParseFailures += 1;+ st.pending = "";+ return;+ }+ // Frames are separated by a blank line. Anything after the last one is incomplete.+ const parts = st.pending.split("\n\n");+ st.pending = parts.pop();+ // Something that was in the buffer before this call just became a counted frame. A window+ // whose OPEN saw a non-empty buffer is only wrong if this happens inside it.+ if (carried && parts.length > 0) S.carriedFlushes += 1;+ for (const part of parts) {+ const line = part.trim();+ if (!line.startsWith("data:")) continue;+ const body = line.slice(5).trim();+ if (body === "" || body === "[DONE]") continue;+ try {+ const frame = JSON.parse(body);+ const choices = frame && frame.choices;+ if (!choices || !choices.length) continue;+ const delta = choices[0].delta || {};+ // Both fields, and both are counted. `_gguf_chat_delta_line` emits reasoning as+ // `reasoning_content` WITH `content: ""` beside it, so summing them is not double+ // counting; it is the two halves of one turn.+ const content = typeof delta.content === "string" ? delta.content.length : 0;+ const reasoning =+ typeof delta.reasoning_content === "string" ? delta.reasoning_content.length : 0;+ S.wireChars += content + reasoning;+ S.wireFrames += 1;+ } catch (err) {+ // COUNTED, NOT SWALLOWED. A parse failure means the denominator is short by an unknown+ // amount, and a silently short denominator inflates every cost-per-character above it.+ S.wireParseFailures += 1;+ }+ }+ };+const noteSse = () => {S.sseChunks += 1;S.everStreamed = true;@@ -180,11 +348,84 @@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();+ // Reassembly state belongs to THIS decoder. Whether this decoder is also the stream being+ // MEASURED is not known yet -- that is decided below, once the chunk has been looked at --+ // and promoting it here handed `active` to any decoder in the page. An unrelated one has an+ // empty buffer, so `wireIntegrity` then reported nothing outstanding while an SSE decoder+ // held half a frame: the window closing there published a denominator short by that frame+ // with a clean bill of health, and the window the suffix landed in was handed the whole+ // frame and accepted it. A response that was aborted mid-frame keeps its half frame to+ // itself.+ const st = stateFor(this);+ // The fragment the previous chunk ended on, but only if THIS chunk continues it. A split+ // inside the marker is repaired here rather than in the buffer, so a fragment that turns out+ // to be ordinary text ending in "d" is dropped instead of corrupting the frame behind it.+ // `markerTail` is only ever set when `pending` is empty, so the two can never both hold a+ // half of the same frame.+ const carriedMarker = Boolean(st.markerTail && continuesMarker(st.markerTail, out));+ const chunk = carriedMarker ? st.markerTail + out : out;+ setMarkerTail(st, "");+ // THE BOUND IS ON THE SCAN, NOT ON THE PAYLOAD. 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. Both things the cap was for survive: the search stays bounded by a constant+ // that grows with neither the payload nor the rung, and a bundle, a blob or a paste still has+ // to put the marker in its first MAX_SSE_CHUNK_CHARS characters to be mistaken for a stream.+ // What does NOT survive is the old rejection: a read carries everything the browser buffered+ // since the last one, so a stall past about two seconds at fast cadence hands the app one+ // well-formed 97,500 character batch, and dropping it took the largest burst of the stream+ // out of `sseChunks`, `lastSseAt` and the `deltaTaskMs` numerator at the moment a stall makes+ // it largest.+ const head = chunk.length <= MAX_SSE_CHUNK_CHARS ? chunk : chunk.slice(0, MAX_SSE_CHUNK_CHARS);+ const looksSse = head.indexOf(SSE_MARKER) >= 0;+ // A CONTINUATION IS STREAM TRAFFIC, AND IT STARTS A TASK CHAIN LIKE ANY OTHER CHUNK.+ // `noteSse` was gated on the marker alone while the counter below was gated on+ // `looksSse || pending`, so the tail of a frame the socket cut inside its JSON body was+ // COUNTED in the denominator and charged to nothing. The three quantities it skipped are+ // the three the batched-read note above names: `sseChunks`, `lastSseAt` and the+ // `deltaTaskMs` numerator. When the suffix lands on a later task the first half rendered+ // nothing and its chain has already closed, so the render the suffix does start is charged+ // to no window at all, and `stream_delta_cost_ms_per_kchar` is biased DOWNWARD exactly as+ // fragmentation rises -- the mirror of the denominator defect the comment below describes,+ // and in the flattering direction. A stale `lastSseAt` also lets `replyChars` decide the+ // stream has gone idle and return `null` for a window still carrying it.+ const continuesFrame = st.pending.length > 0;+ if (looksSse || continuesFrame) noteSse();+ // `looksSse || pending` and not just `looksSse`. THE SECOND HALF OF A SPLIT FRAME CONTAINS+ // NO "data:" -- it is the tail of a JSON body and a blank line -- so gating the counter on+ // that marker dropped the whole frame whenever the socket cut one in two. Found by+ // test_the_counter_survives_a_frame_split_across_two_decode_calls, which is precisely the+ // condition the instrument exists to measure: chunks arrive ragged when the renderer is+ // jammed, so the denominator would have gone quietly short exactly where the numerator went+ // up, and the cost per character would have been overstated at the worst moment.+ //+ // Once a partial frame is held, every subsequent chunk is fed until it completes. Unrelated+ // TextDecoder traffic can therefore land in the buffer; it cannot be counted, because it+ // will not parse as a frame, and it is bounded by MAX_PENDING_CHARS and reported through+ // wire_parse_failures rather than absorbed.+ //+ // AND THE CHUNK THAT IS NEITHER is kept only as far as it could be the START of a marker.+ // That is the third case, the one a complete-marker test cannot see: "da" carries no marker+ // and completes no buffered frame, and discarding it loses the frame that arrives next.+ // The whole chunk is fed to the counter and only the SCAN was bounded above: the denominator+ // is characters delivered, so counting a batched read's head would understate it by exactly+ // the amount a stall made it large.+ // AND ONLY NOW IS THIS DECODER THE ONE A WINDOW IS MEASURING: it either carries the relay's+ // framing or is completing a frame of its own. A decoder that is neither cannot take+ // `active` away from one that is.+ if (looksSse || continuesFrame) {+ // A fragment held by a DIFFERENT decoder cannot be part of this stream, and this one is+ // the stream. Dropped rather than carried, so unrelated traffic that ended in "data"+ // cannot report an outstanding frame for the rest of the cell.+ if (markerHold && markerHold !== st) setMarkerTail(markerHold, "");+ active = st;+ countDeltaChars(st, chunk, carriedMarker);+ } else {+ // A speculative fragment is kept on the decoder that produced it, and it is reported+ // through `wireIntegrity` only if that decoder is the active stream. Unrelated traffic+ // ending in "d" is therefore held without ever claiming to be an outstanding frame.+ setMarkerTail(st, partialMarkerTail(chunk));+ }}S.overheadMs += now() - t;return out;@@ -294,17 +535,56 @@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) {+ // THE DENOMINATOR, read off the wire. O(1): it returns a counter the decode hook maintains.+ // Called at window open and window close, so the window's growth is the difference.+ //+ // Cumulative since page load and monotonic, so unlike the DOM reading it replaces there is no+ // "the reply shrank, so it is a different message" case to handle: characters delivered only+ // ever go up.+ // The two things that can make `wireChars` short by an unknown amount, read at the same O(1)+ // cost as the counter itself so a window boundary can capture both ends.+ wireIntegrity() {+ // The marker fragment counts as buffered, because it is: the frame it begins has not been+ // counted yet, so a window closing on it has a denominator that is short by that frame. The+ // cost of being honest here is that a stray one to four characters of unrelated traffic can+ // mark a window unscoreable, which is the direction to err in -- an unscoreable window is+ // "we could not tell", and a silently short denominator is "it was fine".+ return {+ failures: S.wireParseFailures,+ pending_chars: active.pending.length + heldMarkerChars(),+ // Read as a DELTA across the window by `StreamCostInstrument.close`, so a buffer that was+ // pending at the open refuses the window only when its frame was completed inside it.+ carried_flushes: S.carriedFlushes,+ };+ },+ replyChars() {+ return S.wireChars;+ },++ // The OLD reading, kept as a cross-check and NEVER called inside a measured window. See+ // `end_cell` in streamcost.py: it runs once per cell, after the film, where its cost is+ // charged to nothing.+ //+ // Worth keeping rather than deleting, because the two numbers answer different questions and+ // a disagreement between them is a finding: the wire count is what the app was SENT and the+ // DOM count is what it RENDERED. On a windowed arm they are expected to disagree, by exactly+ // the messages that are not mounted.+ replyCharsDom(force) {const t = now();const n = replyChars(Boolean(force));S.overheadMs += now() - t;return n;},+ wireStats() {+ return {+ wire_chars: S.wireChars,+ wire_frames: S.wireFrames,+ wire_parse_failures: S.wireParseFailures,+ wire_pending_chars: active.pending.length + heldMarkerChars(),+ };+ },+reset() {S.sseChunks = 0;S.sseBursts = 0;diff --git a/tests/studio/studiobench/instruments/streamcost.py b/tests/studio/studiobench/instruments/streamcost.pyindex cd362f25e2a..3ed83ff1f27 100644--- a/tests/studio/studiobench/instruments/streamcost.py+++ b/tests/studio/studiobench/instruments/streamcost.py@@ -62,6 +62,7 @@ class StreamCostInstrument(_PageInstrument):def __init__(self) -> None:super().__init__()self._chars_open: Optional[int] = None+ self._integrity_open: dict = {}self._overhead_ms = 0.0def start_cell(self, cell: Cell) -> None:@@ -80,9 +81,23 @@ class StreamCostInstrument(_PageInstrument):# (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()")+ # O(1), off the wire. This used to be a `querySelectorAll` over the whole document at+ # both ends of every window; see the long note in streamcost.js for why that had to go.self._chars_open = self._eval("() => window.__sb.streamcost && window.__sb.streamcost.replyChars()")+ # THE DENOMINATOR'S INTEGRITY, SAMPLED AT BOTH ENDS. A frame that cannot be parsed --+ # unrelated `TextDecoder` traffic appended while `pending` holds a split SSE frame, say --+ # increments a diagnostic and leaves `wireChars` short by an amount nobody can recover.+ # Counting the failures was not enough on its own: nothing consulted the count, so the+ # affected `reply_chars_delta` was still accepted as a denominator and every cost-per-+ # character derived from it came out inflated by an unknown factor. A delta spanning a new+ # failure, or ending with an unterminated frame still buffered, is now marked unscoreable+ # at the window that contains it.+ self._integrity_open = (+ self._eval("() => window.__sb.streamcost && window.__sb.streamcost.wireIntegrity()")+ or {}+ )def close(self, window: Window) -> Optional[dict]:if self.unavailable:@@ -94,14 +109,67 @@ class StreamCostInstrument(_PageInstrument):"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)+ # No `force` argument any more. The old DOM read was skipped on windows long past the+ # stream because it was expensive; this one is a counter read, so it is taken on every+ # window unconditionally and the "the open-read was skipped, so the pair is half-taken"+ # case cannot arise.+ chars_close = self._eval("() => window.__sb.streamcost.replyChars()")out["stream_cost_attempted"] = Trueout["reply_chars_open"] = self._chars_openout["reply_chars_close"] = chars_close+ # WHERE THE DENOMINATOR CAME FROM, in the payload rather than in this file. A reader+ # comparing a run recorded before this change with one recorded after is comparing two+ # different quantities -- the growth of the last mounted message against the characters+ # delivered to the page -- and nothing else in the row would tell them so.+ out["reply_chars_source"] = "sse_wire"+ integrity = self._eval("() => window.__sb.streamcost.wireIntegrity()") or {}+ failures = (integrity.get("failures") or 0) - (self._integrity_open.get("failures") or 0)+ residual = integrity.get("pending_chars") or 0+ # AND THE OTHER END OF THE SAME SPLIT. `pending` is not cleared by `reset()` -- it cannot+ # be, it holds half a frame -- so a frame the socket cut across a window boundary is still+ # buffered when the NEXT window opens. Its suffix arrives inside that window, the parser+ # adds the WHOLE frame's characters there and empties the buffer, and the close reading+ # then sees no failures and no residual and calls the window scoreable. Part of its+ # denominator was delivered before it opened. The window that closed on the split is+ # already refused by `residual`; this refuses its partner, and the two together are what+ # make `reply_chars_delta` mean "characters delivered IN this window" rather than+ # "characters counted in this window".+ #+ # AND IT IS THE FLUSH, NOT THE BUFFER, THAT MAKES THE DELTA WRONG. `open()` samples the+ # integrity before the action has created the response it is about to measure, so the+ # buffer it sees can belong to a response that is already over: `stop_generation` exists to+ # cut a socket mid-frame and `send_turn` follows it in every shipped schedule. That half+ # frame is never completed and never counted anywhere, so it takes nothing out of this+ # window's delta -- refusing on its presence alone threw away the one stream-cost reading+ # the send_turn window has. `carried_flushes` counts the completions of frames that were+ # already buffered when the decode began, so the pair "a buffer was pending at the open"+ # and "a carried frame was counted inside the window" is what the refusal now needs.+ pending_at_open = self._integrity_open.get("pending_chars") or 0+ carried = (integrity.get("carried_flushes") or 0) - (+ self._integrity_open.get("carried_flushes") or 0+ )+ out["wire_parse_failures_in_window"] = failures+ out["wire_pending_chars_at_close"] = residual+ out["wire_pending_chars_at_open"] = pending_at_open+ out["wire_carried_frames_counted_in_window"] = carried+ if failures > 0 or residual > 0 or (pending_at_open > 0 and carried > 0):+ out["reply_chars_scoreable"] = False+ out["reply_chars_unscoreable_reason"] = (+ f"{failures} SSE frame(s) failed to parse inside this window, "+ f"{pending_at_open} character(s) of an unterminated frame were already buffered "+ f"when it opened and {carried} of those frames were completed and counted inside "+ f"it, and {residual} character(s) were still buffered at its close, "+ "so the wire character count over this window is short by an unknown amount at "+ "one end or carries a frame that began before the other, and any cost-per-"+ "character derived from it would be wrong"+ )+ else:+ out["reply_chars_scoreable"] = True+ out["reply_chars_source_note"] = (+ "counted from the SSE deltas in the decode hook, O(the chunk). Previously read from "+ "the DOM with a querySelectorAll, which is O(the document) and therefore cheaper on "+ "an arm that mounts fewer nodes"+ )if self._chars_open is None or chars_close is None:out["reply_chars_delta"] = None@@ -111,15 +179,18 @@ class StreamCostInstrument(_PageInstrument):"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.+ # NOW UNREACHABLE, AND KEPT ANYWAY. The wire counter is cumulative and monotonic, so+ # it cannot go backwards; if it ever does, the instrument has been reset underneath+ # itself and the delta is meaningless. Under the old DOM reading this branch fired+ # legitimately and often: `send_turn` starts a new assistant message and+ # `thread_reopen` rebuilds the thread, so the LAST message was routinely shorter at+ # the close of a window than at its open, and those windows lost their denominator+ # for a reason that had nothing to do with streaming.out["reply_chars_delta"] = Noneout["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"+ f"the wire character counter went backwards, from {self._chars_open} to "+ f"{chars_close}. It is cumulative and monotonic, so this means the page was "+ "reloaded or the instrument was reinstalled inside the window")else:out["reply_chars_delta"] = chars_close - self._chars_open@@ -145,20 +216,39 @@ class StreamCostInstrument(_PageInstrument):out["close_scan_overhead_ms"] = round(close_scan_ms, 2)self._chars_open = None+ self._integrity_open = {}return outdef 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.+ #+ # THE ONE DOM READ, and it happens HERE, which is after the last window of the cell has+ # closed and before the next cell's first one opens. Its cost is charged to no window and+ # therefore to no arm. It exists because the wire count and the DOM count answer different+ # questions -- what the app was sent, and what it rendered -- and their disagreement is+ # the cheapest available check that a windowed arm is dropping text rather than merely+ # not mounting it.+ wire = self._eval("() => window.__sb.streamcost.wireStats()") or {}+ dom_chars = self._eval("() => window.__sb.streamcost.replyCharsDom(true)")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"+ "O(1) per SSE chunk and O(the chunk) for the wire character count; nothing here "+ "is proportional to the document, the rung or the arm. The reply-length read USED "+ "to be a querySelectorAll -- O(the whole DOM), 38.8 ms per cell at 10K and "+ "289.6 ms at 100K -- and was justified on the grounds that it cancels in a paired "+ "ratio. It does not cancel against an arm that changes the size of the document, "+ "so it was removed from the paired path entirely"+ ),+ "wire": wire,+ # Outside every window, so this number is not in anybody's frame rate.+ "last_message_chars_in_dom": dom_chars,+ "last_message_chars_note": (+ "read once, after the film, purely as a cross-check against the wire count. Never "+ "inside a measured window and never used as a denominator"),}diff --git a/tests/studio/studiobench/report/build.py b/tests/studio/studiobench/report/build.pyindex c03dd8d0f2c..a457dd55f13 100644--- a/tests/studio/studiobench/report/build.py+++ b/tests/studio/studiobench/report/build.py@@ -47,6 +47,9 @@ def _records(path: str | Path) -> list[dict[str, Any]]:def _completion_by_rung(records: Sequence[Mapping[str, Any]]) -> dict[int, tuple[bool, str | None]]:+ from ..runtime.ab import failed_invalidating_gates++ gate_failures = failed_invalidating_gates(records)out: dict[int, tuple[bool, str | None]] = {}for r in records:if r.get("row_type") != "cell":@@ -59,6 +62,22 @@ def _completion_by_rung(records: Sequence[Mapping[str, Any]]) -> dict[int, tuplereason = Noneif not completed:reason = f"{failure.get('kind') or 'unknown'}: {failure.get('message') or 'no message'}"+ # NOT COMPLETE, RATHER THAN NOT PRESENT. A cell whose thread lost messages, or that stopped+ # following the reply it was measuring, reaches here `completed=True` with a full set of+ # timings, because both gates are advisory where they are emitted. Those timings are+ # CHEAPER than a correct cell's -- fewer rows to render -- and the ladder is ABSOLUTE, with+ # no second arm to contradict them, so the rung was scored against fixed anchors and came+ # out green and fast on a cell whose own self-check had already recorded the loss.+ #+ # It is marked incomplete rather than dropped, which is the distinction this module is+ # built on: `score_rung` gives an incomplete rung 0 and KEEPS ITS WEIGHT, and aggregating+ # over only the rungs that survived is the crash-beats-limp bug wearing a different hat. A+ # build whose thread loses its middle at 100K is not usable at 100K, and lowering `onset`+ # is exactly the honest way to say so. Dropping the cell would delete the most important+ # thing the run has to say.+ elif str(r.get("cell_id")) in gate_failures:+ completed = False+ reason = gate_failures[str(r.get("cell_id"))]# If a rung was repeated and any rep failed, the rung is not clean. Recording the failure# rather than the success is deliberate: the interesting fact about a bimodal rung is# that it can fail, not that it can pass.diff --git a/tests/studio/studiobench/report/selftest/test_studiobench_report.py b/tests/studio/studiobench/report/selftest/test_studiobench_report.pyindex c82c965f926..337b0b2ab64 100644--- a/tests/studio/studiobench/report/selftest/test_studiobench_report.py+++ b/tests/studio/studiobench/report/selftest/test_studiobench_report.py@@ -226,6 +226,153 @@ def test_harness_bias_is_printed_and_never_subtracted():assert "NOT subtracted" in summary+# ── a cell that failed an invalidating gate is INCOMPLETE, not absent ──────────+++def _gated_cell_rows(+ gate_name,+ passed,+ *,+ session = "s1",+):+ """One rung, one cell that completed its film, and that cell's own verdict on itself."""+ return [+ {+ "row_type": "cell",+ "cell_id": "r100K.base.rep0",+ "session_id": session,+ "target_tokens": 100_000,+ "completed": True,+ "cell": {"arm": "base", "rep": 0},+ },+ {+ "row_type": "gate",+ "name": gate_name,+ "passed": passed,+ "cell_id": "r100K.base.rep0",+ "session_id": session,+ "detail": {"reason": "12 of 18 ordinals never mounted"},+ },+ ]+++def test_a_cell_that_lost_its_thread_is_scored_incomplete_rather_than_green():+ """REGRESSION. The ladder is ABSOLUTE: there is no second arm to contradict a cheap cell.++ `thread_complete` is advisory where it is emitted, so the cell reaches the report+ `completed=True` with a full set of timings that are cheaper for exactly the wrong reason, and+ the rung was scored against fixed anchors and came out green and fast.+ """+ from studiobench.report.build import _completion_by_rung++ got = _completion_by_rung(_gated_cell_rows("thread_complete", False))+ complete, reason = got[100_000]+ assert complete is False, got+ assert "thread_complete" in (reason or ""), got+++def test_a_cell_that_stopped_following_the_stream_is_incomplete_too():+ from studiobench.report.build import _completion_by_rung+ got = _completion_by_rung(_gated_cell_rows("follows_the_stream", False))+ assert got[100_000][0] is False, got+++def test_a_gate_that_only_qualifies_one_column_leaves_the_rung_alone():+ """`timer_clamp` failing nulls `busy_pct` and leaves every other column standing. Reading it as+ fatal here would zero a rung over a missing idle floor, most often on a loaded machine."""+ from studiobench.report.build import _completion_by_rung++ got = _completion_by_rung(_gated_cell_rows("timer_clamp", False))+ assert got[100_000] == (True, None), got+++def test_a_passing_gate_leaves_the_rung_complete():+ from studiobench.report.build import _completion_by_rung+ got = _completion_by_rung(_gated_cell_rows("thread_complete", True))+ assert got[100_000] == (True, None), got+++def test_a_retry_that_passed_is_not_marked_incomplete_by_the_dead_attempt():+ """`latest_attempt_rows` runs before this and drops the superseded cell, action and window+ rows -- but a gate is none of those, and `--resume` reuses the cell id."""+ from studiobench.report.build import _completion_by_rung+ from studiobench.scoring.from_payload import latest_attempt_rows++ rows = [+ {+ "row_type": "cell",+ "cell_id": "r100K.base.rep0",+ "session_id": "s-old",+ "target_tokens": 100_000,+ "completed": False,+ "cell": {"arm": "base", "rep": 0},+ },+ {+ "row_type": "gate",+ "name": "thread_complete",+ "passed": False,+ "cell_id": "r100K.base.rep0",+ "session_id": "s-old",+ "detail": {"reason": "lost the middle"},+ },+ ] + _gated_cell_rows("thread_complete", True, session = "s-new")++ got = _completion_by_rung(latest_attempt_rows(rows))+ assert got[100_000] == (True, None), got+++def test_the_floor_table_drops_a_gate_failed_cell():+ """The other scorer that admits a cell on `completed` alone. It builds the floor a result is+ then judged against, and scores the result too."""+ from studiobench.sweep.floor_table import cell_metrics++ rows = _gated_cell_rows("thread_complete", False) + [+ {+ "row_type": "action",+ "cell_id": "r100K.base.rep0",+ "session_id": "s1",+ "action": "keystroke",+ "ran": True,+ "expect_ok": True,+ "timings": {"p95_ms": 50.0},+ }+ ]+ assert cell_metrics(rows) == {}+ ok = [r for r in rows if r.get("row_type") != "gate"]+ assert "r100K.base.rep0" in cell_metrics(ok)+++def test_an_absent_sampler_is_not_read_as_a_cell_that_lost_the_stream():+ """REGRESSION. `_read_follow` returns `{"follow_attempted": False}` when the page-side sampler+ is not installed, and the gate then reports `passed: False` because `pinned` is None.++ That is an absent instrument, not a film that went wrong. Read as fatal it marked EVERY cell of+ every run unusable anywhere the sampler is missing, which is a far larger blast radius than the+ defect being closed, and it zeroed the ladder for a reason that says nothing about the build.+ """+ from studiobench.report.build import _completion_by_rung++ rows = _gated_cell_rows("follows_the_stream", False)+ rows[1]["detail"] = {+ "follow_attempted": False,+ "reason": "the follow sampler is not installed",+ }+ assert _completion_by_rung(rows)[100_000] == (True, None), rows+++def test_a_measured_stream_follow_failure_is_still_fatal():+ """The positive control for the test above: the sampler ran and the thread fell behind."""+ from studiobench.report.build import _completion_by_rung++ rows = _gated_cell_rows("follows_the_stream", False)+ rows[1]["detail"] = {+ "follow_attempted": True,+ "pinned_fraction": 0.42,+ "reason": "the thread fell behind for 58% of the streaming phase",+ }+ assert _completion_by_rung(rows)[100_000][0] is False, rows++def test_a_bounded_ratio_is_marked_rather_than_printed_as_a_measurement():"""An arm under its instrument floor contributes the floor, so the ratio understates the truemagnitude. Printed bare it invites `4900% worse` being quoted as a measurement; the marker@@ -261,3 +408,29 @@ def test_an_ordinary_ratio_is_still_printed_bare():assert "1.200" in renderedassert ">=" not in rendered and "<=" not in rendered+++def test_a_missing_viewport_is_not_waived_as_an_absent_instrument():+ """REGRESSION. `probe_attempted: False` has two producers and only one is an absent instrument.++ `window.__sb.dom is not installed` is the harness not being loaded. `no thread viewport` is the+ ARM missing the surface the film measures, and waiving it let a real defect ride the instrument+ allowance -- a cell with no scroller was admitted, scrolled nothing, and was scored.+ """+ from studiobench.report.build import _completion_by_rung++ rows = _gated_cell_rows("thread_complete", False)+ rows[1]["detail"] = {"probe_attempted": False, "reason": "no thread viewport"}+ assert _completion_by_rung(rows)[100_000][0] is False, rows+++def test_an_uninstalled_dom_helper_is_still_waived():+ """The positive control: the harness itself not being loaded is not a finding about the build."""+ from studiobench.report.build import _completion_by_rung++ rows = _gated_cell_rows("thread_complete", False)+ rows[1]["detail"] = {+ "probe_attempted": False,+ "reason": "window.__sb.dom is not installed",+ }+ assert _completion_by_rung(rows)[100_000] == (True, None), rowsdiff --git a/tests/studio/studiobench/runtime/ab.py b/tests/studio/studiobench/runtime/ab.pyindex 482a50e00b7..f9cd5c8b99a 100644--- a/tests/studio/studiobench/runtime/ab.py+++ b/tests/studio/studiobench/runtime/ab.py@@ -24,7 +24,8 @@ printing. That check is the whole reason this file interleaves at all.from __future__ import annotationsfrom dataclasses import dataclass-from typing import Any, Callable, Optional, Sequence+from collections.abc import Mapping, Sequence+from typing import Any, Callable, Optionalfrom ..fixture.corpus import Corpus, RungPlanfrom .types import Cell@@ -202,6 +203,118 @@ def order_is_balanced(plan: list[tuple[Target, Cell, RungPlan]]) -> bool:return len(labels) > 1 and len(set(first_counts.values())) == 1+#: The per-cell gates whose failure means the cell's TIMINGS ARE NOT A READING OF THE BUILD, and+#: therefore the only ones that may take the whole cell out of the ratios.+#:+#: NAMED RATHER THAN "ANY FAILED GATE", because a per-cell gate is not automatically fatal and the+#: one that is not says so itself. `timer_clamp` fails whenever idle calibration cannot establish a+#: floor -- an overloaded machine, or simply the frames instrument not being loaded -- and+#: `session.py` is explicit that this is "NOT fatal, and NOT silently zero": blocked time is a+#: subtraction against that floor, so `busy_pct` is null with the reason attached AND EVERY OTHER+#: COLUMN STANDS. Excluding the cell for it would delete keystroke latency, frame and census+#: readings that were measured correctly, and would do it most often on exactly the machines least+#: able to spare a repetition.+#:+#: The two below are different in kind: both say the FILM ITSELF was wrong. A thread that lost+#: messages and a reply that stopped being rendered do not produce a suspect column, they produce a+#: cheaper cell, and there is no metric in it that can be trusted afterwards.+INVALIDATING_CELL_GATES: frozenset[str] = frozenset({"thread_complete", "follows_the_stream"})+++def gate_detail_is_unmeasured(detail: Mapping[str, Any]) -> bool:+ """Did this failed gate row report a MISSING READING rather than a FAILING BUILD?++ ONE DEFINITION FOR BOTH ADMISSION LISTS. `INVALIDATING_CELL_GATES` above was centralised so+ the scorers could not drift into disagreeing about what invalidates a cell; the predicate that+ waives a row is the same decision one level down, and `sweep/ui_parity.py` applies it to the+ same rows for the DOM side. Two copies of it drift the same way the gate names would have, and+ the drift is invisible because each copy looks locally correct.++ THREE PRODUCERS, all meaning "the instrument did not answer", none meaning "the arm lost+ something":++ `follow_attempted: False` is `_read_follow` reporting that the page-side sampler is not+ installed, and `probe_attempted: False` is `probe_thread_completeness` reporting the same for+ `window.__sb.dom`. `pinned`/`coverage` are then None and the row says `passed: False`. That is+ an absent INSTRUMENT, not a film that went wrong -- the same thing `timer_clamp` is kept off+ the list above for -- and reading it as fatal would mark every cell of every run unusable+ wherever the harness is not loaded, a far larger blast radius than the defect being closed.++ `stream_coverage_unmeasured: True` is the third and the one that was standing open.+ `attached_fraction_of_stream` is fixed by the scene schedule rather than by the build, so it+ is identical on both arms by construction and cancels in every comparison drawn from these+ cells; see the block in `session.py` that writes it for the measurements. Left fatal it voided+ the entire A/B table -- VERDICT: NO READING -- for a reason that has nothing to do with the two+ builds being compared, and did so on the null control as readily as on a real pair. The cell's+ timings still stand: both arms rendered the same share of the same film.++ NARROWED TO THE INSTRUMENT, because `probe_attempted: False` has two producers and only one of+ them is an absent instrument. `window.__sb.dom is not installed` is the harness not being+ loaded and is waived. `no thread viewport` is the ARM missing the surface the film measures,+ which is a defect about the build, and waiving it let a real failure ride the instrument+ allowance.++ This does NOT relax the `unmeasured` COVERAGE VERDICT of the completeness probe, which is a+ different value and stays fatal: `record_completeness_gate` refuses to score a cell whose probe+ RAN and could not answer, because "we could not tell" must not be recorded as "it was fine".+ The case waived here is the probe never having run at all.+ """++ unmeasured = (+ detail.get("follow_attempted") is False+ or detail.get("probe_attempted") is False+ or detail.get("stream_coverage_unmeasured") is True+ )+ return unmeasured and "viewport" not in str(detail.get("reason") or "").lower()+++def failed_invalidating_gates(records: Sequence[Mapping[str, Any]]) -> dict[str, str]:+ """`{cell_id: why}` for every cell carrying a FAILED INVALIDATING per-cell gate row.++ Shared with `report/build.py` and `sweep/floor_table.py`, which are the other two scorers that+ admit a cell, so the three cannot drift into disagreeing about what invalidates one.++ RUN-LEVEL GATES ARE NOT IN HERE. `production_build` and `reportable_tier` are emitted without a+ `cell_id`, and they are properties of the whole run: reading them as per-cell would empty both+ arms and turn a fast-tier A/B into an empty table rather than the table it asked for. Only a+ gate that named a cell can disqualify that cell.++ ATTEMPTS ARE SCOPED BY HAND because `latest_attempt_rows` cannot do it: `ATTEMPT_ROW_TYPES` is+ `{cell, action, window}`, so a gate row survives the filter that drops the rest of a superseded+ attempt. `--resume` reuses the cell id, so without this a cell that failed its gate, was re-run+ and PASSED would stay disqualified by the dead attempt's row -- the retry silently unable to+ count, which is the mirror of the defect this function is fixing. The winning attempt is the+ session the surviving cell row carries; a row without a session id predates the stamp and is+ kept, as `latest_attempt_rows` keeps it.+ """+ winning: dict[str, Any] = {}+ for row in records:+ if row.get("row_type") == "cell" and row.get("cell_id") is not None:+ winning[str(row.get("cell_id"))] = row.get("session_id")++ failed: dict[str, str] = {}+ for row in records:+ if row.get("row_type") != "gate" or row.get("passed") is not False:+ continue+ name = str(row.get("name"))+ if name not in INVALIDATING_CELL_GATES or row.get("cell_id") is None:+ continue+ cell_id = str(row.get("cell_id"))+ keep = winning.get(cell_id)+ if keep is not None and row.get("session_id") not in (None, keep):+ continue+ detail = row.get("detail") if isinstance(row.get("detail"), dict) else {}+ # NOT MEASURED IS NOT FAILED. See `gate_detail_is_unmeasured`, which is shared with+ # `sweep/ui_parity.py` so the two admission lists cannot drift apart on it. Readiness now+ # refuses a cell with no thread viewport outright, so that narrowing is the second of two+ # doors on the same hole.+ if gate_detail_is_unmeasured(detail):+ continue+ why = detail.get("reason") or detail.get("coverage_reason") or "the cell's own self-check"+ failed.setdefault(cell_id, f"gate {name}: {why}")+ return failed++def unmeasured_planned_cells(records: list[dict],planned: Sequence[str],@@ -226,12 +339,23 @@ def unmeasured_planned_cells("""from ..scoring.from_payload import latest_attempt_rows+ # THE SAME TWO FILTERS `readings_by_arm` APPLIES, because this function exists to notice the+ # holes that one punches. It drops a cell for `completed is not True` AND for a failed+ # invalidating gate; reading only the first left the second kind of hole invisible. A cell that+ # completed but lost its thread's middle, or whose reply stopped being rendered, is removed+ # from the ratios here and takes its healthy partner with it through the arm intersection in+ # `compare_arms`, while this said the plan was whole -- so `ab.md` published a verdict over+ # the rungs that survived instead of the VOID that is the point of the guard. That is the+ # partial-plan selection bias, arriving by the gate road instead of the crash road.+ failed = failed_invalidating_gates(records)complete: set = set()for row in latest_attempt_rows(records):if row.get("row_type") != "cell" or row.get("completed") is not True:continueif session_id is not None and row.get("session_id") not in (None, session_id):continue+ if str(row.get("cell_id")) in failed:+ continuecomplete.add(str(row.get("cell_id")))return [str(cell_id) for cell_id in planned if str(cell_id) not in complete]@@ -249,6 +373,22 @@ def readings_by_arm(completed 100 ms base cell, reports IMPROVED. The crash is still in the payload, in thesummary and in `excluded_cells`; it is only kept out of the ratios.+ A CELL THAT FAILED A PER-CELL GATE IS NOT ONE EITHER, for the same reason and by a shorter+ route. `thread_complete` and `follows_the_stream` are advisory at the point they are emitted:+ `record_completeness_gate`'s verdict is discarded by its caller and the film runs on, so the+ cell reaches this function with `completed=True` and a full set of timings. Those timings are+ CHEAPER THAN A CORRECT CELL'S, and cheaper in the direction that flatters the arm -- a thread+ that lost its middle renders fewer rows, and a streamed reply that left the viewport and was+ unmounted stops costing anything to paint. Pairing one against a complete cell on the other+ side reports the defect as an improvement, which is the crash-into-a-win failure again with a+ gate row instead of a missing one.++ `excluded_from_rows` does not cover this path. It reads the same failed gate rows into+ `excluded_cells`, but that block is derived, rendered and schema-checked and nothing filters+ on it: stripping the failing gate rows out of a payload and re-scoring produces byte-identical+ metric lines. `ab.md` is scored here, from `readings_by_arm` and `measures_by_cell`, and+ neither consulted a gate row before this.+`session_id`, when given, keeps the comparison inside ONE session. `--resume` appends to thepayload a previous run wrote, so an interrupted A/B resumed into the same directory otherwisehands `compare_arms` cells from two browser sessions -- the 8% cross-session drift term that@@ -264,6 +404,7 @@ def readings_by_arm(# by `cell_id` alone, and a resumed retry reuses the cell id of the attempt that died. Without# this the completed-cell filter admitted the dead attempt's windows into the retry's reading.records = list(latest_attempt_rows(records))+ failed_gates = failed_invalidating_gates(records)arms: dict[str, list[dict]] = {}cell_ids: dict[str, set[str]] = {}@@ -271,6 +412,8 @@ def readings_by_arm(if row.get("row_type") == "cell":if row.get("completed") is not True:continue+ if str(row.get("cell_id")) in failed_gates:+ continueif session_id is not None and row.get("session_id") not in (None, session_id):continuearm = str((row.get("cell") or {}).get("arm") or row.get("arm") or "")diff --git a/tests/studio/studiobench/runtime/readiness.py b/tests/studio/studiobench/runtime/readiness.pynew file mode 100644index 00000000000..abd269552a2--- /dev/null+++ b/tests/studio/studiobench/runtime/readiness.py@@ -0,0 +1,887 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""When is a thread READY to be measured?++THE OLD GATE COUNTED DOM NODES, and that is the whole problem.+`_wait_for_thread` waited for `[data-role]` to reach the number of messages the seeder had+written, and raised `TimeoutError: the thread mounted 9 of 18 messages in 180s` otherwise. For a+thread that mounts everything, that is a fine proxy: the last thing the app does is mount the last+message, so the count reaching N means the app has finished. For a thread that mounts a WINDOW by+design, the count never reaches N, so the arm that addresses the actual root cause -- the standing+DOM -- could not be scored at all. Raising the timeout would not have helped; the count is not+going to arrive.++WHAT THE GATE IS ACTUALLY FOR. It is not for counting. It is for refusing to start the film while+the app is still building, because a window opened mid-build charges the build to the first action+and reports a flattering number for everything after it. The property worth asserting is therefore+"the app has finished, and what it finished with is the real thread", not "N elements exist".++THE SIGNAL. Five facts, all of which a fully-mounted thread and a correctly virtualised one can+both satisfy, and none of which a half-built one can:++ SETTLED two samples at least `STABLE_GAP_MS` apart agree on the mounted message count, the+ total element count and the viewport's scrollHeight. A thread still mounting is+ still growing on all three; this is the condition that catches the exact failure the+ gate exists for.+ END PRESENT the LAST message of the seeded thread is mounted, identified by the marker string+ the seeder itself wrote into the last user turn. Mounting runs front to back, so the+ last message is the last thing to appear: a run that has mounted 9 of 18 has mounted+ the first 9 and cannot satisfy this. It is also what a virtualised thread anchored+ at the end of the conversation has by construction.+ TOTAL every mounted message agrees on `aria-setsize`, and it equals the number of messages+ the seeder wrote. This is the virtualizer's own claim about how long the thread is,+ read from the place the ARIA spec already requires a windowed list to publish it.+ Required in `windowed` mode, recorded but not gated in `full` (where the mounted+ count is the total).+ ORDINALS every mounted row publishes an `aria-posinset` that is ACTUALLY A POSITION: at least+ 1, unique across the mounted rows, no larger than the set size those same rows+ declare, and -- for a window anchored at the bottom -- reaching the seeded total.+ Presence alone is worth nothing: rows that all publish `0`, all publish the same+ ordinal, or number a bottom-anchored window from 1 satisfy "the attribute is there"+ while telling this gate and a screen reader nothing about where in the thread the+ window sits. Gated in `windowed` mode only, and waived for a thread that is fully+ mounted and publishes no ordinals at all, which is what the shipped build does.+ ANCHORED the viewport is at the bottom, read from the app's OWN state rather than from+ arithmetic: Studio disables assistant-ui's autoscroll and runs+ `use-intent-aware-autoscroll`, which pins to the bottom on `thread.initialize` and+ hides `.aui-thread-scroll-to-bottom` with `invisible` exactly when it considers+ itself at the bottom. The scrollTop arithmetic is kept as a corroborating reading,+ never as the verdict on its own. Gated in `windowed` mode only, where it is what+ makes the mounted set reproducible between the two arms; in `full` mode every+ message is mounted whatever the scroll position, so gating on it would add a way to+ fail that has nothing to do with readiness.++A NOTE ON WHAT THIS ASKS OF THE ARM. Studio ships no virtualization and no ordinal attributes:+there is no `aria-setsize`, no `aria-posinset` and no `data-message-index` anywhere in the chat+thread today, and `@tanstack/react-virtual` is used only by the hub's model catalog. So TOTAL is+not a signal that exists and is being read; it is a CONTRACT THE VIRTUALIZATION ARM MUST MEET.+That is a requirement, not a favour: WAI-ARIA already requires a list that does not have all of+its items in the DOM to publish `aria-setsize` and `aria-posinset`, so a virtualised thread that+omits them is broken for assistive technology whatever it does to the frame rate. Refusing to+score it is the right answer rather than an inconvenience. `full` mode requires none of this and+runs unchanged against the shipped build.++WHY IT CANNOT PASS EARLY ON A BROKEN ARM. Each of the interesting breakages is refused by a+different one of those, so no single mistake in an arm can produce a pass:++ still mounting SETTLED fails (counts still climbing) and END PRESENT fails (the+ last message has not been reached yet)+ mounts a window but has+ only loaded part of the+ thread into its store TOTAL fails, because `aria-setsize` is the store's length and it+ will not equal what the seeder wrote+ publishes ordinals that+ are not positions -- all+ zero, all identical, or+ a bottom window numbered+ from 1 ORDINALS fails. Each of those is a real virtualizer bug (publishing+ the index WITHIN the window rather than the position in the thread+ is the common one) and each one makes the window unlocatable+ mounts a window, claims+ the right total, and has+ really dropped the head `probe_thread_completeness` fails: it scrolls to the top and+ requires the FIRST message, by the seeder's own marker, to mount+ keeps the first and last+ pages and loses messages+ from the MIDDLE `probe_thread_completeness` fails on COVERAGE: the head marker+ arrives, so the marker check alone is satisfied, and the ordinals+ recorded on the way up have a hole in them that no scroll position+ fills++The residual, stated rather than hidden: an arm that publishes a truthful `aria-setsize`, keeps the+whole thread in its store and materialises rows on demand passes all of it. That is not a hole,+that is a correctly virtualised thread, which is the thing we set out to be able to score.++WHY NOT THE OTHER CANDIDATES.+ the app's own store there is no supported handle on it from outside. Reaching into a+ React fibre or a bundler-internal module to read one would make the+ gate depend on the build's internals, which is exactly what a+ harness that has to run two different builds in one session cannot+ afford. `aria-setsize` is the same number, published on purpose.+ scroll-to-end settled necessary, not sufficient: an empty thread is settled at the bottom.+ It is one of the four here, not the whole signal.+ the last message's content used, but via the seeder's marker rather than the corpus text. The+ corpus goes through a markdown renderer, so its rendered text is not+ its source text and a tail match on it would be a guess. The marker+ is plain text this harness wrote itself.+"""++from __future__ import annotations++import time+from dataclasses import dataclass, field+from typing import Any, Callable, Optional++#: The two gate modes. `full` is the historical behaviour plus the settle and end-present+#: conditions; it is STRICTLY STRONGER than what shipped and is what every normal arm runs.+#: `windowed` is the one an arm that deliberately mounts fewer nodes may ask for.+MODE_FULL = "full"+MODE_WINDOWED = "windowed"+MODES = (MODE_FULL, MODE_WINDOWED)++#: How far apart the two agreeing samples must be. 600ms rather than the old 500ms poll, because+#: the thing being ruled out is a mount loop that pauses for a frame, and a gap shorter than a+#: couple of React commits can be spanned by one.+STABLE_GAP_MS = 600+#: How many consecutive agreeing samples are needed. Two, i.e. one confirmed repeat.+STABLE_SAMPLES = 2+#: Bottom tolerance, in CSS pixels. Not zero: a virtualised list settles on an estimated total+#: height and corrects it as real rows are measured, so it lands a few pixels off the exact bottom+#: and stays there. 24px is under one line of text, so it cannot hide a missing message.+BOTTOM_TOLERANCE_PX = 24++DEFAULT_TIMEOUT_S = 180+++class ThreadNotReady(TimeoutError):+ """The gate refused. A TimeoutError subclass so existing `except TimeoutError` still catches it.++ Carries the last probe reading on `.detail`, because "the thread mounted 9 of 18 messages"+ told you the count and nothing about which of the four conditions was the one that failed.+ """++ def __init__(self, message: str, detail: dict):+ super().__init__(message)+ self.detail = detail+++#: One reading of the page. Cheap enough to run every poll: the expensive part is+#: `getElementsByTagName('*').length`, which is a live HTMLCollection length and not a walk.+PROBE_JS = """+(args) => {+ const [marker, tailChars] = args;+ const D = (window.__sb && window.__sb.dom) || null;+ if (!D) return { probe_attempted: false, reason: "window.__sb.dom is not installed" };+ const vp = D.viewport();+ const roles = Array.from(document.querySelectorAll("[data-role]"));+ const setsizes = [];+ let maxPos = null;+ let minPos = null;+ let withPos = 0;+ // THE DISTINCT ordinals, not just how many were published. A window whose rows all carry the+ // same number publishes one on every row, and counting rows cannot tell that apart from a+ // correctly numbered window. The set can.+ const posSeen = new Set();+ // ON THE MESSAGE OR ON THE ROW THAT HOLDS IT. A virtualizer positions each row in a wrapper of+ // its own -- that is how absolute positioning against a measured total height works -- and the+ // ordinal belongs on the row, which is the element that is actually a member of the set. The+ // `[data-role]` message sits inside it. Looking only at `[data-role]` would refuse a correctly+ // implemented arm for putting the attribute in the right place.+ const ordinal = (el, name) => {+ const owner = el.closest("[" + name + "]");+ if (!owner) return null;+ const raw = owner.getAttribute(name);+ if (raw === null || raw === "") return null;+ const n = Number(raw);+ return Number.isFinite(n) ? n : null;+ };+ for (const el of roles) {+ const ss = ordinal(el, "aria-setsize");+ if (ss !== null) setsizes.push(ss);+ const pi = ordinal(el, "aria-posinset");+ if (pi !== null) {+ withPos += 1;+ posSeen.add(pi);+ if (maxPos === null || pi > maxPos) maxPos = pi;+ if (minPos === null || pi < minPos) minPos = pi;+ }+ }+ const distinct = Array.from(new Set(setsizes));+ // The app's own opinion of "at the bottom". thread.tsx renders the scroll-to-bottom control+ // permanently and hides it with `invisible` when use-intent-aware-autoscroll reports at-bottom,+ // so this is the state the app is acting on rather than a number the driver computed.+ const jump = document.querySelector(".aui-thread-scroll-to-bottom");+ // Set on the viewport WHILE the autoscroll is pinning and removed when it settles. A page that+ // still carries it is mid-pin, whatever its scrollTop currently reads.+ const stabilizer = vp+ ? (vp.style.getPropertyValue("--aui-scroll-stabilizer") || "").trim()+ : "";+ const last = roles.length ? roles[roles.length - 1] : null;+ // The marker is looked for among the MOUNTED user messages only. Searching document.body would+ // find it in a sidebar preview or a title and call the thread ready on the strength of a+ // tooltip.+ let markerFound = false;+ let markerIndex = null;+ if (marker) {+ for (let i = 0; i < roles.length; i += 1) {+ const el = roles[i];+ if (el.getAttribute("data-role") !== "user") continue;+ if ((el.textContent || "").includes(marker)) { markerFound = true; markerIndex = i; }+ }+ }+ return {+ probe_attempted: true,+ mounted: roles.length,+ elements: document.getElementsByTagName("*").length,+ composer: Boolean(D.composer()),+ running: D.isRunning(),+ setsize: distinct.length === 1 ? distinct[0] : null,+ setsize_values: distinct,+ posinset_count: withPos,+ posinset_distinct: posSeen.size,+ max_posinset: maxPos,+ min_posinset: minPos,+ marker_found: markerFound,+ // Where the marker sits in the mounted run. The last message of the thread is the assistant+ // reply to the last user turn, so a marker found anywhere but the final couple of rows means+ // the mounted window is not at the end even if the viewport says it is.+ marker_from_end: markerIndex === null ? null : roles.length - 1 - markerIndex,+ last_role: last ? last.getAttribute("data-role") : null,+ last_tail: last ? (last.textContent || "").replace(/\\s+/g, " ").trim().slice(-tailChars) : null,+ scroll_height: vp ? vp.scrollHeight : null,+ client_height: vp ? vp.clientHeight : null,+ scroll_top: vp ? vp.scrollTop : null,+ from_bottom: vp ? Math.round(vp.scrollHeight - vp.clientHeight - vp.scrollTop) : null,+ viewport_present: Boolean(vp),+ jump_button_present: Boolean(jump),+ app_says_at_bottom: jump ? jump.classList.contains("invisible") : null,+ pinning: stabilizer !== "",+ };+}+"""++#: The keys that must AGREE between two samples for the page to count as settled. Deliberately+#: three quantities that move for three different reasons: the message list growing, any subtree+#: growing (a highlighter still colouring a fence moves `elements` while `mounted` sits still), and+#: the laid-out height changing (a virtualised list correcting its estimated row heights).+SETTLE_KEYS = ("mounted", "elements", "scroll_height")+++@dataclass+class Readiness:+ """The gate's verdict, recorded whether it passed or failed."""++ ready: bool+ mode: str+ expected_messages: int+ waited_ms: float+ conditions: dict = field(default_factory = dict)+ probe: dict = field(default_factory = dict)+ samples: int = 0+ reason: Optional[str] = None++ def as_dict(self) -> dict:+ return {+ "ready": self.ready,+ "mode": self.mode,+ "expected_messages": self.expected_messages,+ "waited_ms": round(self.waited_ms, 1),+ "samples": self.samples,+ "conditions": self.conditions,+ "probe": self.probe,+ "reason": self.reason,+ }++ @property+ def failed(self) -> list[str]:+ return sorted(k for k, v in self.conditions.items() if v is False)+++def evaluate(probe: dict, previous: Optional[dict], expected_messages: int, mode: str) -> dict:+ """The whole decision, as a pure function of two probe readings. Tested without a browser.++ Returns `{condition: True | False | None}`. `None` means NOT APPLICABLE IN THIS MODE and is+ never treated as a pass or a fail -- the same distinction the parity layer draws between a+ match and a surface that was never measured.+ """+ if not probe.get("probe_attempted"):+ return {"probe": False}++ settled: Any = False+ if previous is not None and previous.get("probe_attempted"):+ settled = all(probe.get(k) == previous.get(k) for k in SETTLE_KEYS)++ out: dict[str, Any] = {+ "composer_present": bool(probe.get("composer")),+ "any_message_mounted": (probe.get("mounted") or 0) > 0,+ "settled": bool(settled),+ # The END of the thread is on screen. Both halves matter: the marker for the last user turn+ # is mounted, AND it is near the end of the mounted run rather than in the middle of it.+ # `2` because the thread ends user, assistant -- the marker's own row plus the reply.+ "end_present": bool(probe.get("marker_found"))+ and (probe.get("marker_from_end") is not None and probe["marker_from_end"] <= 2),+ }++ if mode == MODE_WINDOWED:+ # THE VIRTUALIZER'S OWN CLAIM about the thread's length, and it has to be the truth the+ # seeder wrote. An arm that mounts a window without publishing aria-setsize has not given+ # anyone -- this harness or a screen reader -- any way to know how long the thread is, and+ # it is refused here rather than scored on the assumption that it is fine.+ #+ # UNLESS THE WHOLE THREAD IS MOUNTED, in which case there is nothing left to declare: the+ # DOM is the total. This matters at the small rungs, where the thread is shorter than the+ # window and a virtualised build mounts every message exactly like the shipped one. The+ # requirement has to be true of a fully-mounted thread as well as of a correctly windowed+ # one, or `windowed` becomes a mode that only some rungs of the same arm can pass.+ #+ # It cannot be used to slip past the gate: this branch needs `mounted >= expected`, which+ # is the full-mount condition itself, so a thread that has mounted 9 of 18 gets none of it.+ fully_mounted = (probe.get("mounted") or 0) >= expected_messages+ out["total_declared"] = fully_mounted or probe.get("setsize") is not None+ out["total_matches_seeded"] = fully_mounted or probe.get("setsize") == expected_messages+ published = probe.get("posinset_count") or 0+ out["posinset_on_every_row"] = fully_mounted or (+ probe.get("posinset_count") == probe.get("mounted") and (probe.get("mounted") or 0) > 0+ )+ # ORDINALS THAT ARE ACTUALLY POSITIONS. The condition above only asks whether a number was+ # published on every row, and three malformed shapes satisfy it while carrying no+ # information at all: every row publishing `0`, every row publishing the same ordinal, and+ # a window numbered from 1 rather than from where it sits in the thread. Each is a real+ # virtualizer bug, each leaves the mounted set unlocatable, and each used to pass here.+ #+ # So the numbers have to behave like positions in a set: at least 1, no two rows claiming+ # the same one, and none pointing past the end those same rows declare in `aria-setsize`.+ # `setsize` is the arm's own claim and is already required to equal the seeded total by+ # `total_matches_seeded`; the seeded total stands in when no setsize was published, which+ # is the fully-mounted case below.+ #+ # THE WAIVER, and it is the same one `total_declared` carries: a thread short enough to be+ # mounted whole publishes no ordinals -- the shipped build publishes none anywhere -- and+ # there is nothing to validate. It needs `mounted >= expected`, the full-mount condition+ # itself, AND no ordinals at all, so an arm that publishes malformed ones cannot buy its+ # way out of the check by also mounting everything.+ declared = probe.get("setsize")+ if declared is None:+ declared = expected_messages+ out["posinset_ordinals_valid"] = (fully_mounted and published == 0) or (+ published > 0+ and probe.get("min_posinset") is not None+ and probe["min_posinset"] >= 1+ and probe.get("posinset_distinct") == published+ and probe.get("max_posinset") is not None+ and probe["max_posinset"] <= declared+ )+ # AND THE WINDOW IS AT THE END OF THE THREAD BY ITS OWN NUMBERING. `end_present` proves the+ # last message's TEXT is mounted; this proves the ordinals agree with it. Without it a+ # bottom-anchored window numbered 1..6 out of 18 -- a virtualizer publishing the index+ # within the window instead of the position in the thread -- passes every other condition.+ out["posinset_reaches_end"] = (fully_mounted and published == 0) or (+ probe.get("max_posinset") == expected_messages+ )+ # THE APP'S ANSWER FIRST, the arithmetic only when the app has not given one. A virtualised+ # list settles on an estimated total height and corrects it as real rows are measured, so+ # its scrollTop arithmetic can read tens of pixels off the bottom while the app -- which+ # knows it is pinned -- is perfectly happy. Trusting the arithmetic over the app would fail+ # a correct arm for a rounding error in a height estimate.+ app_bottom = probe.get("app_says_at_bottom")+ near_bottom = (+ probe.get("from_bottom") is not None and probe["from_bottom"] <= BOTTOM_TOLERANCE_PX+ )+ out["anchored_at_end"] = bool(app_bottom) if app_bottom is not None else near_bottom+ # THE VIEWPORT ITSELF, ASSERTED RATHER THAN INFERRED. Every windowed condition above is+ # about what is inside the scroller, and each one degrades to a pass when the scroller is+ # not there: `from_bottom` is null so the arithmetic is skipped, and the app's own answer+ # is read off `.aui-thread-scroll-to-bottom`, which is a DESCENDANT of the viewport but is+ # looked up at DOCUMENT scope. So renaming the viewport class while leaving that control+ # mounted leaves `app_says_at_bottom` true, `anchored_at_end` true, and the cell admitted+ # with no viewport at all.+ #+ # What follows a cell admitted that way is silent in every direction: the completeness+ # probe returns `probe_attempted: false`, the scroll actions return `not_run` and a not-run+ # action blanks only its own timings, and the census viewport fields go null. Nothing+ # refuses, so the film is scored without the surface it was measuring.+ #+ # The signal is already probed and costs nothing to read. It is asserted only here because+ # a fully mounted arm that scrolls the window instead of a div is a shape this harness+ # supports, and `MODE_FULL` must not start requiring a scroller it never needed.+ out["viewport_present"] = bool(probe.get("viewport_present"))+ # And the pin must have FINISHED. `--aui-scroll-stabilizer` is on the viewport while+ # use-intent-aware-autoscroll is still pinning and comes off when it settles, so a page+ # carrying it is mid-scroll no matter what its scrollTop says.+ out["pin_settled"] = not probe.get("pinning")+ # Not a gate, a sanity check with teeth: a "windowed" arm that mounted MORE rows than the+ # thread has is not windowed, it is broken, and the reading would be nonsense.+ out["not_over_mounted"] = (probe.get("mounted") or 0) <= expected_messages+ else:+ out["all_messages_mounted"] = (probe.get("mounted") or 0) >= expected_messages+ # Recorded, never gated, in full mode. See the module docstring.+ out["total_declared"] = None+ out["total_matches_seeded"] = None+ out["posinset_on_every_row"] = None+ out["posinset_ordinals_valid"] = None+ out["posinset_reaches_end"] = None+ out["anchored_at_end"] = None+ out["pin_settled"] = None+ out["not_over_mounted"] = None+ return out+++def _describe(conditions: dict, probe: dict, expected: int, mode: str) -> str:+ failed = sorted(k for k, v in conditions.items() if v is False)+ bits = [+ f"mounted {probe.get('mounted')} of {expected}",+ f"aria-setsize {probe.get('setsize')}",+ # The ordinals THEMSELVES, not just how many rows carried one: "posinset 0..0 on 6 rows,+ # 1 distinct" is the whole diagnosis of a malformed contract, and reading it off the raw+ # probe afterwards is what this message exists to save.+ f"aria-posinset {probe.get('min_posinset')}..{probe.get('max_posinset')} on "+ f"{probe.get('posinset_count')} of {probe.get('mounted')} rows, "+ f"{probe.get('posinset_distinct')} distinct",+ f"last row {probe.get('last_role')!r}",+ f"{probe.get('from_bottom')}px from the bottom",+ ]+ return (+ f"the thread was not ready in {mode} mode: {', '.join(failed) or 'no condition passed'} "+ f"({'; '.join(bits)})"+ )+++def wait_for_thread_ready(+ page,+ expected_messages: int,+ *,+ marker: Optional[str] = None,+ mode: str = MODE_FULL,+ timeout_s: float = DEFAULT_TIMEOUT_S,+ log: Callable[[str], None] = print,+ tail_chars: int = 80,+) -> Readiness:+ """Block until the thread is ready, or raise `ThreadNotReady` saying which condition failed."""+ if mode not in MODES:+ raise ValueError(f"unknown readiness mode {mode!r}; known modes are {list(MODES)}")+ if expected_messages <= 0:+ page.wait_for_selector('textarea[aria-label="Message input"]', timeout = 60_000)+ return Readiness(+ ready = True,+ mode = mode,+ expected_messages = expected_messages,+ waited_ms = 0.0,+ conditions = {"empty_thread": True},+ reason = "the thread has no seeded messages, so only the composer is required",+ )++ started = time.monotonic()+ deadline = started + timeout_s+ previous: Optional[dict] = None+ probe: dict = {}+ conditions: dict = {}+ agreeing = 0+ samples = 0+ last_log: Optional[tuple] = None+ while time.monotonic() < deadline:+ probe = page.evaluate(PROBE_JS, [marker or "", tail_chars]) or {}+ samples += 1+ conditions = evaluate(probe, previous, expected_messages, mode)+ agreeing = agreeing + 1 if conditions.get("settled") else 0+ if all(v is not False for v in conditions.values()) and agreeing >= STABLE_SAMPLES - 1:+ waited = (time.monotonic() - started) * 1000+ log(+ f" thread ready ({mode}): {probe.get('mounted')} of {expected_messages} messages "+ f"mounted, aria-setsize {probe.get('setsize')}, "+ f"{probe.get('elements'):,} elements, settled after {waited / 1000:.1f}s"+ )+ return Readiness(+ ready = True,+ mode = mode,+ expected_messages = expected_messages,+ waited_ms = waited,+ conditions = conditions,+ probe = probe,+ samples = samples,+ )+ key = (probe.get("mounted"), probe.get("setsize"), tuple(sorted(conditions.items())))+ if key != last_log:+ last_log = key+ failed = sorted(k for k, v in conditions.items() if v is False)+ log(+ f" waiting: {probe.get('mounted')}/{expected_messages} mounted, "+ f"outstanding {failed}"+ )+ previous = probe+ page.wait_for_timeout(STABLE_GAP_MS)++ waited = (time.monotonic() - started) * 1000+ detail = Readiness(+ ready = False,+ mode = mode,+ expected_messages = expected_messages,+ waited_ms = waited,+ conditions = conditions,+ probe = probe,+ samples = samples,+ reason = _describe(conditions, probe, expected_messages, mode),+ )+ raise ThreadNotReady(detail.reason or "the thread was not ready", detail.as_dict())+++#: Scroll to the very top, then back. Used by `probe_thread_completeness`.+TRAVERSE_JS = """+async ([toTop, steps, stepPx]) => {+ const D = window.__sb.dom;+ const vp = D.viewport();+ if (!vp) return { ran: false, reason: "no thread viewport" };+ // STEPPED, AND WITH A WHEEL EVENT ON EVERY STEP. A single `scrollTo({top: 0})` from the bottom+ // does not work on this app and the reason is already documented in scene/actions.py: Studio+ // replaces assistant-ui's autoscroll with an intent-aware one that reads a jump as programmatic+ // and snaps it straight back to the bottom. The first version of this probe did exactly that,+ // and reported "scrolling to the top never mounted the first message" -- which reads as the arm+ // losing its history and was the probe never leaving the bottom of the thread.+ //+ // The wheel event is what the app's own listeners key off, so it registers as user intent; the+ // scrollTo is what actually moves the viewport in a headless run with no compositor input.+ // Both, in steps, is the same gesture scene/actions.py SCROLL_JS uses for the same reason.+ //+ // A virtualizer also has to be given time to materialise rows as they come into range: each+ // step awaits a paint, so a windowed list gets a frame per step to mount what the step exposed.+ const target = toTop ? 0 : vp.scrollHeight;+ const direction = toTop ? -1 : 1;+ // WHICH MESSAGES THE TRAVERSAL ACTUALLY SAW, ordinal by ordinal.+ //+ // The marker check at the end of the walk asks one question -- did the FIRST message arrive --+ // and a store that kept the first page and the last one and lost everything between them+ // answers it correctly. So every stop records the `aria-posinset` of the rows mounted there,+ // read the same way PROBE_JS reads them (off the row that owns the attribute, which is the+ // positioned wrapper on a real virtualizer), and the union is what the coverage verdict is+ // computed from.+ //+ // `holes` is the stronger of the two readings: a virtualizer mounts a CONTIGUOUS run of the+ // thread, so an ordinal missing from between the smallest and largest mounted at ONE stop was+ // not skipped by this gesture, it is a message the store no longer has. `ranges` records the+ // span each stop mounted, so the caller can tell a continuous sweep -- where every consecutive+ // stop overlapped the last, and an ordinal never seen really was never mounted -- from a+ // coarse one, where the ordinals between two stops were never in view and nothing is known+ // about them.+ const seen = new Set();+ const holes = new Set();+ const ranges = [];+ const record = () => {+ const vals = [];+ for (const el of document.querySelectorAll("[data-role]")) {+ const owner = el.closest("[aria-posinset]");+ if (!owner) continue;+ const n = Number(owner.getAttribute("aria-posinset"));+ if (Number.isFinite(n)) vals.push(n);+ }+ if (!vals.length) return;+ let lo = vals[0];+ let hi = vals[0];+ const here = new Set();+ for (const n of vals) {+ seen.add(n);+ here.add(n);+ if (n < lo) lo = n;+ if (n > hi) hi = n;+ }+ // Bounded, so a thread whose ordinals are nonsense cannot put a million entries in a payload.+ if (holes.size < 1000) {+ for (let k = lo; k <= hi; k += 1) if (!here.has(k)) holes.add(k);+ }+ ranges.push([lo, hi]);+ };+ record();+ for (let i = 0; i < steps; i += 1) {+ const next = toTop+ ? Math.max(0, vp.scrollTop - stepPx)+ : Math.min(vp.scrollHeight, vp.scrollTop + stepPx);+ vp.dispatchEvent(+ new WheelEvent("wheel", { deltaY: direction * stepPx, bubbles: true, cancelable: true }),+ );+ vp.scrollTo({ top: next, behavior: "instant" });+ await window.__sbNextPaint();+ record();+ if (toTop && vp.scrollTop <= 0) break;+ if (!toTop && vp.scrollTop >= vp.scrollHeight - vp.clientHeight - 1) break;+ }+ let continuous = ranges.length > 0;+ for (let i = 1; i < ranges.length; i += 1) {+ const a = ranges[i - 1];+ const b = ranges[i];+ // Touching counts as continuous: rows 1-6 followed by rows 7-12 leaves nothing between them.+ if (b[0] > a[1] + 1 || a[0] > b[1] + 1) { continuous = false; break; }+ }+ const sorted = Array.from(seen).sort((a, b) => a - b);+ return {+ ran: true,+ scroll_top: vp.scrollTop,+ scroll_height: vp.scrollHeight,+ reached_target: toTop ? vp.scrollTop <= 2 : true,+ target,+ ordinals_seen: sorted,+ ordinals_in_window_holes: Array.from(holes).sort((a, b) => a - b),+ sweep_continuous: continuous,+ traversal_stops: ranges.length,+ };+}+"""++#: How the traversal is stepped. 400 steps of 2,000px covers 800,000px of thread, which clears the+#: tallest rung this benchmark runs, and a step that lands at either end breaks out early.+TRAVERSE_STEPS = 400+TRAVERSE_STEP_PX = 2000++#: The ordinals mounted right now, read exactly the way PROBE_JS reads them. Run once at the top of+#: the thread, after the wait for the head marker: the last stop of the gesture reads its rows the+#: instant the paint lands, and an arm that materialises a row a beat later would otherwise have+#: that row counted as one the traversal never saw.+COLLECT_ORDINALS_JS = """+() => {+ const out = [];+ for (const el of document.querySelectorAll("[data-role]")) {+ const owner = el.closest("[aria-posinset]");+ if (!owner) continue;+ const n = Number(owner.getAttribute("aria-posinset"));+ if (Number.isFinite(n)) out.push(n);+ }+ return out;+}+"""++#: How many missing ordinals a verdict names. The COUNT is always exact; the list is capped so a+#: thread that lost half of itself does not write a thousand integers into every payload.+MISSING_ORDINALS_LISTED = 40++#: WHY `ordinal_coverage` GAVE THE ANSWER IT GAVE, which the three-valued verdict on its own cannot+#: say and which the `thread_complete` gate has to know.+#:+#: `not_applicable` and `unmeasured` are BOTH `None` and they are opposites. The first is a question+#: that does not arise on this arm: a fully mounted thread publishes no `aria-posinset` anywhere --+#: the shipped build publishes none -- so there are no ordinals to cover and none missing. The+#: second is a question that does arise and was not answered: the gesture stopped short of the top,+#: or its consecutive stops did not overlap, so rows nobody scrolled past are rows nobody looked at.+#:+#: A gate that passes both reads "we could not tell" as "it was fine", which is the store that kept+#: only its first and last page staying scoreable. A gate that fails both fails the shipped build on+#: every cell for publishing no ordinals. So the two are recorded apart, and only the second is+#: withheld from a pass.+COVERAGE_COMPLETE = "complete"+COVERAGE_INCOMPLETE = "incomplete"+COVERAGE_NOT_APPLICABLE = "not_applicable"+COVERAGE_UNMEASURED = "unmeasured"++#: The coverage states a cell may still be scored on. `unmeasured` is deliberately absent, and+#: `incomplete` is excluded by the verdict itself rather than by this tuple.+COVERAGE_STATES_SCOREABLE = (COVERAGE_COMPLETE, COVERAGE_NOT_APPLICABLE)+++def ordinal_coverage(+ traverse: dict,+ expected_messages: int,+ extra_seen: Any = (),+) -> dict:+ """Which of the seeded ordinals the traversal actually SAW, and what that does and does not+ prove. A pure function of the traversal's own record, so it is tested without a browser.++ THREE-VALUED, for the same reason `head_reached` is. `True` is coverage, `False` is a message+ the arm no longer has, and `None` is this probe not having looked -- which is the one answer+ the old code could not give and the reason a coarse gesture must never be allowed to report a+ row it never scrolled past as a row the app lost.++ AND `ordinal_coverage_state` SAYS WHICH KIND OF `None` IT IS, because the two are opposites and+ a caller that cannot tell them apart has to treat them the same. `not_applicable` is a question+ that does not arise -- no row published an ordinal, which is what a fully mounted arm does by+ design -- and `unmeasured` is a question that arises and was not answered. The `thread_complete`+ gate passes the first and refuses the second; collapsing them made a store that kept only its+ first and last page scoreable whenever the sweep happened to be coarse.++ The three ways `None` is the honest answer:++ no row published an ordinal NOT APPLICABLE. A fully mounted arm publishes none at+ all, by design, and MODE_FULL never asked it to.+ Checked FIRST: a windowed arm records the ordinals of+ its mounted rows before the gesture takes its first+ step, so an empty union really does mean an arm that+ publishes nothing rather than a gesture that failed+ the gesture never reached the top UNMEASURED. Nothing was traversed, so nothing was+ covered+ consecutive stops did not overlap UNMEASURED. The gesture jumps `TRAVERSE_STEP_PX` at a+ time and a virtualizer mounts what is near the+ viewport, so rows between two stops were never in view.+ The remedy is a finer step, not a softer verdict++ And the two that are a verdict about the arm:++ a hole inside one mounted window a virtualizer mounts a CONTIGUOUS run, so an ordinal+ missing from between the smallest and the largest+ mounted at a single stop -- and mounted at no other+ stop either -- is a message the store does not have+ a continuous sweep with a gap every stop overlapped the last, so the union really is+ everything the thread could show, and what is not in+ it is not in the thread+ """+ seen = {int(n) for n in (traverse.get("ordinals_seen") or [])}+ seen.update(int(n) for n in (extra_seen or ()))+ expected = set(range(1, expected_messages + 1)) if expected_messages > 0 else set()+ missing = sorted(expected - seen)+ # Intersected with "never seen anywhere", so a row that was briefly absent while its window+ # was still materialising and mounted at the next stop is not reported as a lost message.+ holes = sorted({int(n) for n in (traverse.get("ordinals_in_window_holes") or [])} - seen)+ out: dict[str, Any] = {+ "ordinals_seen_count": len(seen),+ "min_posinset_seen": min(seen) if seen else None,+ "max_posinset_seen": max(seen) if seen else None,+ "ordinals_missing_count": len(missing),+ "ordinals_missing": missing[:MISSING_ORDINALS_LISTED],+ "ordinals_missing_truncated": len(missing) > MISSING_ORDINALS_LISTED,+ "ordinals_in_window_holes": holes[:MISSING_ORDINALS_LISTED],+ "sweep_continuous": traverse.get("sweep_continuous"),+ "traversal_stops": traverse.get("traversal_stops"),+ "coverage_reason": None,+ }+ # NOT APPLICABLE BEFORE UNMEASURED. An arm publishing no ordinals anywhere has nothing to cover+ # whatever the gesture did, and asking about the gesture first would report the shipped build's+ # own shape as a measurement this probe failed to take -- which the gate now refuses to score.+ if not seen:+ out["ordinal_coverage_complete"] = None+ out["ordinal_coverage_state"] = COVERAGE_NOT_APPLICABLE+ out["coverage_reason"] = (+ "no mounted row published aria-posinset during the traversal, so there was nothing to "+ "count. A fully mounted arm publishes none by design, and a windowed one is refused "+ "by the readiness gate long before it reaches this probe"+ )+ return out+ if not traverse.get("reached_target"):+ out["ordinal_coverage_complete"] = None+ out["ordinal_coverage_state"] = COVERAGE_UNMEASURED+ out["coverage_reason"] = (+ "the stepped gesture never reached the top, so an ordinal it did not see is an "+ "ordinal it never looked for"+ )+ return out+ if holes:+ out["ordinal_coverage_complete"] = False+ out["ordinal_coverage_state"] = COVERAGE_INCOMPLETE+ out["coverage_reason"] = (+ f"{len(holes)} ordinal(s) were absent from a mounted window that spanned them and "+ f"appeared at no other scroll position ({out['ordinals_in_window_holes']}), so the "+ "arm is missing messages from the MIDDLE of the thread"+ )+ return out+ if not missing:+ out["ordinal_coverage_complete"] = True+ out["ordinal_coverage_state"] = COVERAGE_COMPLETE+ return out+ if traverse.get("sweep_continuous"):+ out["ordinal_coverage_complete"] = False+ out["ordinal_coverage_state"] = COVERAGE_INCOMPLETE+ out["coverage_reason"] = (+ f"{len(missing)} of {expected_messages} ordinals never mounted ({out['ordinals_missing']}"+ f"{', truncated' if out['ordinals_missing_truncated'] else ''}), and every stop of the "+ "traversal overlapped the one before it, so the sweep had no gap for them to hide in"+ )+ return out+ out["ordinal_coverage_complete"] = None+ out["ordinal_coverage_state"] = COVERAGE_UNMEASURED+ out["coverage_reason"] = (+ f"{len(missing)} of {expected_messages} ordinals never mounted, but consecutive stops of "+ f"the gesture did not overlap, so rows between two stops were never in view. NOT a claim "+ "that the arm lost them, and NOT a coverage result either: run the traversal at a step "+ "small enough for consecutive stops to overlap"+ )+ return out+++def probe_thread_completeness(+ page,+ *,+ first_marker: str,+ expected_messages: int,+ timeout_s: float = 60.0,+ log: Callable[[str], None] = print,+ steps: int = TRAVERSE_STEPS,+ step_px: int = TRAVERSE_STEP_PX,+) -> dict:+ """Does the thread really CONTAIN the whole conversation, not just show the end of it?++ THE ONE QUESTION THE READINESS GATE CANNOT ANSWER FROM THE END OF THE THREAD. A windowed arm+ anchored at the bottom looks identical whether its store holds all N messages or only the last+ handful, and the difference is data loss. So this drives the only probe a user has: scroll to+ the top and see whether the first message of the conversation arrives.++ AND THE MARKER AT THE TOP IS NOT ENOUGH ON ITS OWN. A store that kept the first page and the+ last one and lost everything between them mounts the head when you scroll to it, passes every+ reading taken at the bottom, and is missing most of the conversation. So the traversal also+ records the `aria-posinset` of every row it passes and `ordinal_coverage` says what that+ covers -- including, when the gesture's stops did not overlap, that it covers nothing and the+ answer is NOT MEASURED.++ Run BEFORE the measured window, never inside it -- it scrolls the viewport the whole length of+ the thread and mounts whatever the arm materialises on the way, which is real work that has no+ business inside anybody's frame rate. The caller re-establishes the resting state afterwards.++ Reported, not raised. A failure here does not mean the readiness gate was wrong; it means the+ arm is losing messages, which is a finding to record against the arm rather than a reason to+ lose the cell.+ """+ out: dict = {"probe_attempted": True, "expected_messages": expected_messages}+ top = page.evaluate(TRAVERSE_JS, [True, steps, step_px])+ if not isinstance(top, dict) or not top.get("ran"):+ return {+ "probe_attempted": False,+ "reason": (top or {}).get("reason", "the viewport could not be scrolled"),+ }+ deadline = time.monotonic() + timeout_s+ found = False+ seen: dict = {}+ while time.monotonic() < deadline:+ seen = page.evaluate(PROBE_JS, [first_marker or "", 80]) or {}+ if seen.get("marker_found"):+ found = True+ break+ page.wait_for_timeout(250)+ at_top = page.evaluate(COLLECT_ORDINALS_JS) or []+ coverage = ordinal_coverage(top, expected_messages, extra_seen = at_top)+ out.update(+ {+ "head_reached": found,+ "mounted_at_top": seen.get("mounted"),+ "setsize_at_top": seen.get("setsize"),+ "scroll_height_at_top": top.get("scroll_height"),+ # DID THE GESTURE ACTUALLY REACH THE TOP? Without this, "the head never mounted" and+ # "the viewport never left the bottom" are the same reading, and the second one is a+ # defect in this probe being reported as data loss in the app.+ "reached_top": top.get("reached_target"),+ "scroll_top_after_gesture": top.get("scroll_top"),+ "traverse_step_px": step_px,+ }+ )+ out.update(coverage)+ # `min_posinset_seen` before there were any ordinals to see: the head marker mounting means+ # position 1 was on the page, whether or not the arm numbers its rows. Kept so an arm that+ # publishes nothing still fills the field the way it always did.+ if out.get("min_posinset_seen") is None and found:+ out["min_posinset_seen"] = 1+ # And back to the end, so the cell resumes from the state the readiness gate described.+ page.evaluate(TRAVERSE_JS, [False, steps, step_px])+ if not found and not top.get("reached_target"):+ # NOT A VERDICT ABOUT THE ARM. The gesture did not get there, so nothing was learned about+ # what the arm holds, and saying otherwise would blame the app for the probe.+ out["head_reached"] = None+ out["reason"] = (+ f"the scroll gesture never reached the top of the thread (stopped at "+ f"{top.get('scroll_top')}px), so this says nothing about what the arm holds"+ )+ log(f" completeness NOT MEASURED: {out['reason']}")+ return out+ if not found:+ out["reason"] = (+ "scrolling to the top of the thread never mounted the first message, so the arm is "+ "not holding the whole conversation"+ )+ log(f" COMPLETENESS FAILED: {out['reason']}")+ elif out.get("ordinal_coverage_complete") is False:+ # THE HEAD ARRIVED AND THE THREAD IS STILL INCOMPLETE. This is the case the marker check+ # alone reported as a pass: first page kept, last page kept, middle gone.+ out["reason"] = f"the head of the thread mounted, but {out['coverage_reason']}"+ log(f" COMPLETENESS FAILED: {out['reason']}")+ elif out.get("ordinal_coverage_state") == COVERAGE_UNMEASURED:+ # THE HEAD ARRIVED AND THE MIDDLE WAS NEVER INSPECTED. Not a finding about the arm, and+ # not a pass either: this is the same first-page-and-last-page store re-entering through+ # the unknown state, so the cell carries a reason and the gate declines to score it.+ out["reason"] = (+ f"the head of the thread mounted, but coverage of the middle was NOT ESTABLISHED: "+ f"{out['coverage_reason']}"+ )+ log(f" COMPLETENESS NOT ESTABLISHED: {out['reason']}")+ else:+ log(+ f" completeness: the head of the thread mounted on scroll-to-top "+ f"({seen.get('mounted')} rows mounted there, aria-setsize {seen.get('setsize')}), "+ f"ordinal coverage {out.get('ordinal_coverage_complete')} "+ f"({out.get('ordinals_seen_count')} of {expected_messages} ordinals seen)"+ )+ if out.get("ordinal_coverage_complete") is None:+ # Only the not-applicable kind reaches here; the unmeasured kind is caught above and+ # carries a reason of its own.+ log(f" coverage DOES NOT APPLY: {out.get('coverage_reason')}")+ return outdiff --git a/tests/studio/studiobench/runtime/seeder.py b/tests/studio/studiobench/runtime/seeder.pyindex 8824034fa01..90c877d1aeb 100644--- a/tests/studio/studiobench/runtime/seeder.py+++ b/tests/studio/studiobench/runtime/seeder.py@@ -67,6 +67,17 @@ def _assistant_content(unit: Unit) -> list[dict]:return parts+def turn_marker(index: int, unit_index: int) -> str:+ """The exact plain text this harness writes into the user turn at `index`.++ ONE function rather than an f-string in two places, because the readiness gate matches on this+ string in the DOM. A marker that the seeder writes and the gate looks for in slightly different+ words is a gate that never passes, and the symptom would be a timeout that looks like a slow+ app.+ """+ return f"studiobench turn {index}: continue with unit {unit_index}"++@dataclassclass SeededThread:thread_id: str@@ -74,6 +85,12 @@ class SeededThread:seeded_chars: intseconds: floatturns: int+ # The markers on the FIRST and LAST user turns. The readiness gate uses `last_marker` to prove+ # the end of the thread is mounted, and the completeness probe uses `first_marker` to prove a+ # windowed arm still holds the head of the conversation. Plain text written by this harness,+ # so neither is a guess about what a markdown renderer will do to the corpus.+ first_marker: Optional[str] = None+ last_marker: Optional[str] = None@dataclass@@ -132,7 +149,7 @@ class Seeder:"content": [{"type": "text",- "text": f"studiobench turn {i}: continue with unit {unit.index}",+ "text": turn_marker(i, unit.index),}],"attachments": None,@@ -169,12 +186,15 @@ class Seeder:self.log(f" seeded {len(messages)} messages ({plan.seeded_chars:,} chars) " f"in {seconds:.1f}s")+ units = list(plan.seeded_units)return SeededThread(thread_id = thread_id,messages = len(messages),seeded_chars = plan.seeded_chars,seconds = seconds,- turns = len(plan.seeded_units),+ turns = len(units),+ first_marker = turn_marker(0, units[0].index) if units else None,+ last_marker = turn_marker(len(units) - 1, units[-1].index) if units else None,)def read_back(self, thread_id: str) -> list[dict]:diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_failed_cell_verdict.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_failed_cell_verdict.pyindex 3f768f87b83..c309f40137c 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_failed_cell_verdict.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_failed_cell_verdict.py@@ -136,6 +136,86 @@ def test_the_unguarded_render_is_the_wrong_verdict(tmp_path):assert "r10K.base.rep0" not in table+def test_a_gate_failed_cell_is_a_hole_in_the_plan_too(tmp_path):+ """`readings_by_arm` drops a COMPLETED cell that failed `thread_complete` or+ `follows_the_stream` -- the timings of a thread that lost its middle are not a reading of the+ build -- and the arm intersection takes its healthy partner with it. So the plan has the same+ hole a dead cell leaves, by a road that reads `completed: True`."""++ records = [+ {+ "row_type": "cell",+ "cell_id": "r10K.base.rep0",+ "session_id": "sess-1",+ "completed": True,+ },+ {+ "row_type": "gate",+ "name": "thread_complete",+ "passed": False,+ "cell_id": "r10K.base.rep0",+ "session_id": "sess-1",+ "detail": {"probe_attempted": True, "reason": "the thread lost its middle"},+ },+ ]++ assert unmeasured_planned_cells(records, ["r10K.base.rep0"], session_id = "sess-1") == [+ "r10K.base.rep0"+ ]+++def test_a_not_measured_gate_row_is_not_a_hole(tmp_path):+ """The other side of it, and the reason this defers to `failed_invalidating_gates` rather than+ to any failed gate: an absent instrument is not a missing reading of the plan, and voiding on+ it would void every run of a harness that is not loaded."""++ records = [+ {+ "row_type": "cell",+ "cell_id": "r10K.base.rep0",+ "session_id": "sess-1",+ "completed": True,+ },+ {+ "row_type": "gate",+ "name": "follows_the_stream",+ "passed": False,+ "cell_id": "r10K.base.rep0",+ "session_id": "sess-1",+ "detail": {"follow_attempted": False, "reason": "sampler is not installed"},+ },+ ]++ assert unmeasured_planned_cells(records, ["r10K.base.rep0"], session_id = "sess-1") == []+++def test_a_gate_failed_cell_voids_the_table_rather_than_publishing_the_survivors(tmp_path):+ """End to end through `_render_ab`, which is where the wrong verdict was published."""++ paths = Paths.under(tmp_path / "out")+ rec = Recorder(paths.payload_jsonl, "sess-1")+ planned = []+ for rung, tokens, base_p95, treat_p95 in LADDER:+ for arm, p95 in (("base", base_p95), ("treatment", treat_p95)):+ cell_id = f"r{rung}.{arm}.rep0"+ planned.append(cell_id)+ rec.emit(_cell_row(cell_id, arm, tokens))+ rec.emit(_keystroke(cell_id, p95))+ rec.gate(+ "thread_complete",+ False,+ {"probe_attempted": True, "reason": "the thread lost its middle"},+ cell_id = "r10K.base.rep0",+ )+ rec.close()++ _render_ab(paths, SIDES, "sess-1", "c0ffee", planned = planned)+ table = (paths.out / "ab.md").read_text(encoding = "utf-8")++ assert "VOID. No numbers are quotable" in table+ assert "r10K.base.rep0" in table++def test_a_complete_plan_is_not_voided(tmp_path):records = [_cell_row("r10K.base.rep0", "base", 10_000, completed = True)]for row in records:diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_home_collision.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_home_collision.pynew file mode 100644index 00000000000..17e59eaa22d--- /dev/null+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_home_collision.py@@ -0,0 +1,108 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""AN A/B THAT COMPARES A BUILD AGAINST ITSELF, AND LOOKS CLEAN DOING IT.++`install_studio` derives its repo checkout from the home directory, so two arms sharing one home+share one checkout. The second install overwrites the first and both arms then serve whichever+build was installed last. Every downstream number is then a comparison of a build with itself:+the parity digest matches, the invariants agree, the timings sit on top of each other, and none+of it means anything.++This was not hypothetical. Two runs of the same pair reported 716 ms and 718 ms for base and+treatment in one, and 2,583 ms and 2,614 ms in the other: nearly equal within each run, 3.6x+apart between them, because each run was internally uniform and the two runs were serving+different builds. Read within a run it says the change does nothing.++It is the same shape as a copy timing that is really a sleep, and it is the reason this refuses+rather than warns.+"""++from __future__ import annotations++import re+from pathlib import Path++_MAIN = Path(__file__).resolve().parents[2] / "__main__.py"+++def _source() -> str:+ return _MAIN.read_text(encoding = "utf-8")+++def test_a_shared_home_under_ab_is_refused_rather_than_warned():+ source = _source()+ assert "if not args.attach and args.home:" in source, "the A/B path must refuse a shared home"+ # A refusal, not a log line that scrolls past. `return 2` is the CLI's usage-error code.+ guard = source[source.index("if not args.attach and args.home:") :]+ assert "return 2" in guard[:900], "the guard must exit non-zero, not merely print"+++def test_the_refusal_says_what_to_do_instead():+ """A refusal a reader cannot act on gets worked around. Naming the replacement is the+ difference between a guard and an obstacle."""+ source = _source()+ guard = source[source.index("--home cannot be used with --ab") :][:700]+ assert "Drop --home" in guard+ assert "studio_home_" in guard, "it must name the per-arm directory it falls back to"+++def test_the_guard_sits_before_any_install_runs():+ """Refusing AFTER the first install has already run costs the caller the slow half of the+ mistake and leaves a half-built home behind."""+ source = _source()+ assert source.index("if not args.attach and args.home:") < source.index(+ "side_install = install_studio(ref, home)"+ )+++def test_the_guard_sits_before_the_payload_is_archived():+ """A refusal that starts nothing must cost the previous run nothing.++ `prepare_payload` archives an existing `payload.jsonl` for a fresh run, so a guard placed+ after it answers `--ab X --home H --out DIR` by moving DIR's payload off the standard path and+ THEN exiting 2 having run no benchmark: the next `--resume` finds nothing to continue and+ silently re-runs the whole ladder, and `--report` and `--assert-liveness` open the standard+ name and find no rows. `rollback_session_rows` states the rule this keeps -- a refusal has to+ leave the payload it refused exactly as it found it.++ `invalidate_stale_reports` is held to the same line and for the same reason: it REPLACES+ `summary.md` and `ab.md`, so a refusal reaching it would take the previous run's reports down+ along with its payload.++ The archive is pinned as `archived = prepare_payload(`, which is the literal+ `test_the_run_passes_the_archive_result_to_the_invalidation` pins for the wiring, so the two+ move together instead of one going stale the next time that call is rewritten."""++ source = _source()+ run_body = source[source.index("def run(args, ab_ref = None) -> int:") :]+ for sink in ("archived = prepare_payload(", "invalidate_stale_reports(paths.out"):+ for guard in (+ "if not args.attach and args.home:",+ "if args.attach and not args.attach_b:",+ "injection_problem = stream_cost_injection_problem(",+ ):+ assert run_body.index(guard) < run_body.index(sink), f"{guard} vs {sink}"+++def test_a_single_arm_run_still_accepts_home():+ """`--home` is legitimate on its own: there is only one build to install, so there is no+ collision. The guard is on the COMBINATION, and narrowing it wrongly would break the+ single-arm path that people use to pin an install."""+ source = _source()+ guard_line = next(+ line for line in source.split("\n") if "if not args.attach and args.home:" in line+ )+ # The condition must mention the attach case; the A/B-only scoping comes from the block it+ # sits inside, which is guarded by `if ab_ref:`.+ assert "args.attach" in guard_line+ block_start = source.index("if ab_ref:")+ assert block_start < source.index("if not args.attach and args.home:")+++def test_the_reason_is_recorded_where_the_next_person_reads_it():+ """The mechanism is not guessable from the flag names, so it is written where the guard is."""+ source = _source()+ comment = source[source.index("ONE HOME CANNOT HOLD TWO BUILDS") :][:1400]+ assert "overwrites the first" in comment+ assert re.search(r"716|2,583", comment), "the measured numbers belong beside the claim"diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_pairing.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_pairing.pyindex 0377f76c94f..a855a647abb 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_pairing.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_pairing.py@@ -65,6 +65,19 @@ def _keystroke(}+def _gate(+ name,+ passed,+ *,+ cell_id = None,+ session = SESSION,+):+ row = {"row_type": "gate", "name": name, "passed": passed, "detail": {}, "session_id": session}+ if cell_id is not None:+ row["cell_id"] = cell_id+ return row++def _pairs(records, session_id = SESSION):result = compare_arms(records,@@ -91,6 +104,116 @@ def test_a_crashed_treatment_cell_does_not_become_a_win():assert result.verdict == "NO READING"+def test_a_cell_that_failed_a_per_cell_gate_does_not_become_a_win():+ """REGRESSION. A completeness gate is advisory where it is emitted, so the cell arrives here+ `completed=True` with a full set of timings -- and cheaper ones, because a thread that lost its+ middle renders fewer rows. `excluded_from_rows` reads the same gate row into `excluded_cells`,+ but nothing filters on that block, and `ab.md` is scored from `readings_by_arm`.+ """++ records = [+ _cell("r10K.base.rep0", "base"),+ _keystroke("r10K.base.rep0", 100.0),+ _cell("r10K.treatment.rep0", "treatment"),+ _keystroke("r10K.treatment.rep0", 50.0),+ _gate("thread_complete", False, cell_id = "r10K.treatment.rep0"),+ ]+ assert "treatment" not in readings_by_arm(records)+ pairs, result = _pairs(records)+ assert pairs == []+ assert result.verdict == "NO READING"+++def test_a_failed_follows_the_stream_gate_disqualifies_its_cell_too():+ """The streamed reply leaving the viewport is the other way a defect gets cheaper to paint."""++ records = [+ _cell("r10K.base.rep0", "base"),+ _keystroke("r10K.base.rep0", 100.0),+ _cell("r10K.treatment.rep0", "treatment"),+ _keystroke("r10K.treatment.rep0", 50.0),+ _gate("follows_the_stream", False, cell_id = "r10K.treatment.rep0"),+ ]+ assert "treatment" not in readings_by_arm(records)+++def test_a_passing_gate_leaves_its_cell_alone():+ records = [+ _cell("r10K.base.rep0", "base"),+ _keystroke("r10K.base.rep0", 100.0),+ _gate("thread_complete", True, cell_id = "r10K.base.rep0"),+ _cell("r10K.treatment.rep0", "treatment"),+ _keystroke("r10K.treatment.rep0", 50.0),+ _gate("thread_complete", True, cell_id = "r10K.treatment.rep0"),+ ]+ pairs, _result = _pairs(records)+ assert len(pairs) == 1+ assert pairs[0].ratio == 0.5+++def test_a_failed_timer_clamp_does_not_throw_away_the_rest_of_the_cell():+ """A per-cell gate is not automatically fatal, and this one says so itself.++ `timer_clamp` fails whenever idle calibration cannot establish a floor -- an overloaded+ machine, or the frames instrument simply not being loaded. `session.py` calls that "NOT fatal,+ and NOT silently zero": blocked time is a subtraction against the floor, so `busy_pct` is null+ with the reason attached and every other column stands. Excluding the cell would delete+ keystroke, frame and census readings that were measured correctly, most often on the machines+ least able to spare a repetition.+ """++ records = [+ _cell("r10K.base.rep0", "base"),+ _keystroke("r10K.base.rep0", 100.0),+ _gate("timer_clamp", False, cell_id = "r10K.base.rep0"),+ _cell("r10K.treatment.rep0", "treatment"),+ _keystroke("r10K.treatment.rep0", 50.0),+ _gate("timer_clamp", False, cell_id = "r10K.treatment.rep0"),+ ]+ assert set(readings_by_arm(records)) == {"base", "treatment"}+ pairs, _result = _pairs(records)+ assert len(pairs) == 1+ assert pairs[0].ratio == 0.5+++def test_a_failed_run_level_gate_does_not_empty_the_table():+ """`production_build` and `reportable_tier` carry no cell id. Read as per-cell they would+ disqualify every cell on both arms and turn a fast-tier A/B into an empty table."""++ records = [+ _cell("r10K.base.rep0", "base"),+ _keystroke("r10K.base.rep0", 100.0),+ _cell("r10K.treatment.rep0", "treatment"),+ _keystroke("r10K.treatment.rep0", 50.0),+ _gate("reportable_tier", False),+ _gate("production_build", False),+ ]+ assert set(readings_by_arm(records)) == {"base", "treatment"}+ pairs, _result = _pairs(records)+ assert len(pairs) == 1+++def test_a_retry_that_passed_is_not_disqualified_by_the_dead_attempt_gate():+ """`latest_attempt_rows` drops a superseded attempt's `cell`, `action` and `window` rows, but+ NOT its gate row, and `--resume` reuses the cell id. Scoping the gate to the winning attempt is+ what keeps the retry countable."""++ records = [+ _cell("r10K.base.rep0", "base"),+ _keystroke("r10K.base.rep0", 100.0),+ _cell("r10K.treatment.rep0", "treatment", completed = False, session = OLD_SESSION),+ _keystroke("r10K.treatment.rep0", 999.0, session = OLD_SESSION),+ _gate("thread_complete", False, cell_id = "r10K.treatment.rep0", session = OLD_SESSION),+ _cell("r10K.treatment.rep0", "treatment"),+ _keystroke("r10K.treatment.rep0", 50.0),+ _gate("thread_complete", True, cell_id = "r10K.treatment.rep0"),+ ]+ assert "treatment" in readings_by_arm(records)+ pairs, _result = _pairs(records)+ assert len(pairs) == 1+ assert pairs[0].ratio == 0.5++def test_two_completed_cells_still_pair():records = [_cell("r10K.base.rep0", "base"),diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_completeness_gate_rows.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_completeness_gate_rows.pynew file mode 100644index 00000000000..ac40ad770f8--- /dev/null+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_completeness_gate_rows.py@@ -0,0 +1,310 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""WHICH CELL LOST THE MESSAGES, read back out of the payload the session actually writes.++The completeness probe is the only check in the harness that can find a windowed arm dropping+history, and its verdict used to be written with `Recorder.gate`, which emits `{row_type, name,+passed, detail}` and no cell id. `report/payload.py::excluded_from_rows` reads a failed gate as+`row.get("cell_id") or "run"`, so the finding arrived in the report as a run-level self-check+failure: something failed somewhere, and no way to say which arm or which rung. For a probe whose+whole purpose is to attribute data loss to an arm, that is the finding being deleted on the way+out.++So the row is written here through `record_completeness_gate` and read back through the real+`excluded_from_rows`, in that order, rather than asserted against a hand-built dict. No browser:+this is about what reaches the payload, not about what the page did.++AND WHICH `None` THE COVERAGE WAS. `ordinal_coverage` answers `None` for two opposite reasons --+no ordinals were published at all, so the question does not arise, versus the sweep never having+inspected the middle of the thread -- and a gate that passes both lets the first-page-and-last-page+store back in through the unknown state. The pair of positive controls below is what stops the+repair turning into a gate that fails the shipped build instead.++ python -m pytest tests/studio/studiobench/runtime/selftest/test_studiobench_completeness_gate_rows.py -q+"""++from __future__ import annotations++import sys+from pathlib import Path++_HERE = Path(__file__).resolve()+_STUDIO_TESTS = _HERE.parents[3]+if str(_STUDIO_TESTS) not in sys.path:+ sys.path.insert(0, str(_STUDIO_TESTS))++from studiobench.report.payload import excluded_from_rows # noqa: E402+from studiobench.runtime.readiness import ( # noqa: E402+ COVERAGE_COMPLETE,+ COVERAGE_INCOMPLETE,+ COVERAGE_NOT_APPLICABLE,+ COVERAGE_UNMEASURED,+ ordinal_coverage,+)+from studiobench.runtime.session import record_completeness_gate # noqa: E402+from studiobench.runtime.types import Cell, Recorder, make_cell_id # noqa: E402++#: The arm the whole windowed readiness gate exists for, at a rung big enough to be windowed.+CELL = Cell(+ cell_id = make_cell_id("100K", "B1", 0),+ rung = "100K",+ rung_tokens = 100_000,+ arm = "B1",+ session_id = "sess0",+)++#: What the probe returns for a thread that kept its head and its tail and lost the middle: the+#: marker check is satisfied and the ordinals are not.+LOST_MIDDLE = {+ "probe_attempted": True,+ "expected_messages": 18,+ "head_reached": True,+ "ordinal_coverage_complete": False,+ "ordinal_coverage_state": COVERAGE_INCOMPLETE,+ "ordinals_seen_count": 6,+ "ordinals_missing": list(range(4, 16)),+ "ordinals_missing_count": 12,+ "coverage_reason": "the arm is missing messages from the MIDDLE of the thread",+}+++def _rows(tmp_path, completeness: dict) -> tuple[list[dict], bool]:+ recorder = Recorder(tmp_path / "payload.jsonl", "sess0")+ try:+ passed = record_completeness_gate(recorder, CELL, completeness)+ finally:+ recorder.close()+ return list(recorder.rows()), passed+++def test_the_completeness_verdict_names_the_cell_it_was_taken_from(tmp_path):+ rows, passed = _rows(tmp_path, LOST_MIDDLE)+ assert len(rows) == 1+ row = rows[0]+ assert row["row_type"] == "gate"+ assert row["name"] == "thread_complete"+ assert passed is False and row["passed"] is False+ # `r{rung}.{arm}.rep{rep}`, so the one field answers which arm and which rung lost them.+ assert row["cell_id"] == "r100K.B1.rep0"+ assert row["detail"]["ordinals_missing"] == list(range(4, 16))+++def test_a_cell_that_lost_messages_is_excluded_as_itself_and_not_as_the_run(tmp_path):+ """The consuming end, unmodified: `excluded_from_rows` is what the report reads.++ Its fallback to the synthetic cell id "run" is deliberate and stays -- a genuinely run-level+ gate has no cell -- so the fix is on the writing side, and this is the assertion that the two+ ends agree.+ """+ rows, _ = _rows(tmp_path, LOST_MIDDLE)+ excluded = excluded_from_rows(rows)+ assert len(excluded) == 1+ assert excluded[0]["cell_id"] == CELL.cell_id+ assert excluded[0]["cell_id"] != "run"+ assert excluded[0]["reason"] == "selfcheck_failed"+ assert "thread_complete" in excluded[0]["detail"]+++def test_coverage_that_does_not_apply_does_not_fail_the_cell(tmp_path):+ """A fully mounted arm publishes no `aria-posinset` anywhere, so there are no ordinals to+ cover and none missing. The question does not arise, and failing a cell on a question that was+ never asked of it would fail the shipped build's own completeness gate on every cell."""+ rows, passed = _rows(+ tmp_path,+ {+ "probe_attempted": True,+ "head_reached": True,+ "ordinal_coverage_complete": None,+ "ordinal_coverage_state": COVERAGE_NOT_APPLICABLE,+ "coverage_reason": "no mounted row published aria-posinset during the traversal",+ },+ )+ assert passed is True and rows[0]["passed"] is True+ assert excluded_from_rows(rows) == []+++def test_coverage_that_applies_but_was_never_measured_is_not_a_pass(tmp_path):+ """THE COMPLETENESS FIX, RE-ENTERING THROUGH THE UNKNOWN STATE.++ A store that kept the first page and the last one and lost everything between them mounts the+ head when the traversal scrolls to it, so the marker check is satisfied. The ordinals are what+ catch it -- and when the sweep's consecutive stops did not overlap, the ordinals were never+ inspected. Reading that `None` as a pass hands the cell straight back to the arm this probe+ exists to refuse, and the report then carries its frame rate as if it had been earned on a+ complete thread.+ """+ rows, passed = _rows(+ tmp_path,+ {+ "probe_attempted": True,+ "head_reached": True,+ "ordinal_coverage_complete": None,+ "ordinal_coverage_state": COVERAGE_UNMEASURED,+ "coverage_reason": "consecutive stops of the gesture did not overlap",+ },+ )+ assert passed is False and rows[0]["passed"] is False+ assert [c["cell_id"] for c in excluded_from_rows(rows)] == [CELL.cell_id]+++def test_an_undifferentiated_coverage_None_is_not_a_pass_either(tmp_path):+ """A payload written before the state existed carries the ambiguity and nothing that resolves+ it. That is exactly the reading the gate must not resolve in favour of a pass."""+ rows, passed = _rows(+ tmp_path,+ {"probe_attempted": True, "head_reached": True, "ordinal_coverage_complete": None},+ )+ assert passed is False and rows[0]["passed"] is False+++# ── the two ends, joined: the probe's own output through the gate ───+++def _coverage(**traverse) -> dict:+ """What `probe_thread_completeness` would hand the gate, from a real traversal record."""+ got = {"probe_attempted": True, "head_reached": True}+ got.update(ordinal_coverage(traverse, 18))+ return got+++def test_a_coarse_sweep_over_a_thread_missing_its_middle_does_not_pass_the_gate(tmp_path):+ """END TO END, with no hand-written state string between the two halves.++ `ordinal_coverage` and `record_completeness_gate` have to agree about which `None` this is, so+ the traversal record goes through the real function and the real gate. Six of eighteen+ ordinals ever mounted, the head among them, and a gesture too coarse to say whether the other+ twelve exist: not a finding, and not a pass.+ """+ rows, passed = _rows(+ tmp_path,+ _coverage(+ reached_target = True,+ ordinals_seen = [1, 2, 3, 16, 17, 18],+ ordinals_in_window_holes = [],+ sweep_continuous = False,+ traversal_stops = 2,+ ),+ )+ assert passed is False and rows[0]["passed"] is False+ assert rows[0]["detail"]["ordinal_coverage_state"] == COVERAGE_UNMEASURED+ assert [c["cell_id"] for c in excluded_from_rows(rows)] == [CELL.cell_id]+++def test_a_continuous_sweep_that_saw_every_ordinal_passes_the_gate(tmp_path):+ """The positive control for the test above: the same joining, on a sweep that did establish+ coverage. Without it, "not a pass" could be coming from a gate that passes nothing."""+ rows, passed = _rows(+ tmp_path,+ _coverage(+ reached_target = True,+ ordinals_seen = list(range(1, 19)),+ ordinals_in_window_holes = [],+ sweep_continuous = True,+ traversal_stops = 9,+ ),+ )+ assert passed is True and rows[0]["passed"] is True+ assert rows[0]["detail"]["ordinal_coverage_state"] == COVERAGE_COMPLETE+++def test_an_arm_that_publishes_no_ordinals_at_all_passes_the_gate(tmp_path):+ """The other positive control, and the reason a blanket "None fails" would be wrong: this is+ the shipped build, traversed to the top, publishing nothing for the sweep to count."""+ rows, passed = _rows(+ tmp_path,+ _coverage(+ reached_target = True,+ ordinals_seen = [],+ ordinals_in_window_holes = [],+ sweep_continuous = True,+ traversal_stops = 3,+ ),+ )+ assert passed is True and rows[0]["passed"] is True+ assert rows[0]["detail"]["ordinal_coverage_state"] == COVERAGE_NOT_APPLICABLE+++def test_a_head_that_never_mounted_still_fails_the_cell(tmp_path):+ """The original verdict, unchanged: the head marker not arriving is data loss on its own."""+ rows, passed = _rows(+ tmp_path,+ {"probe_attempted": True, "head_reached": False, "ordinal_coverage_complete": None},+ )+ assert passed is False and rows[0]["passed"] is False+ assert [c["cell_id"] for c in excluded_from_rows(rows)] == [CELL.cell_id]+++def test_a_probe_that_never_ran_fails_the_cell_rather_than_passing_it(tmp_path):+ """A probe that could not scroll the viewport returns neither verdict.++ It reports `probe_attempted: false` and nothing else, and the gate must not read a missing+ `head_reached` as a thread that was fine. This is the reading the harness has always taken and+ it is asserted here so the three-valued coverage rule above cannot quietly widen it.+ """+ rows, passed = _rows(+ tmp_path,+ {"probe_attempted": False, "reason": "the viewport could not be scrolled"},+ )+ assert passed is False and rows[0]["passed"] is False+ assert [c["cell_id"] for c in excluded_from_rows(rows)] == [CELL.cell_id]+++# ── every per-cell gate, not just the completeness one ──────────────+++def test_every_per_cell_gate_names_its_cell():+ """THE SAME DEFECT, IN FOUR MORE PLACES. `excluded_from_rows` reads+ `row.get("cell_id") or "run"`, so a per-cell gate emitted without one is attributed to the+ synthetic cell "run": a failure that says one arm at one rung lost the thread, or fell behind+ the stream, or had its timer clamped, is presented as a run-level self-check failure and the+ report cannot say which arm or which rung.++ Asserted against the source rather than a live session, because reaching these lines needs a+ browser, a backend and a seeded thread, and the property under test is simply that the call+ passes the identity it already has in scope.+ """+ import inspect++ from studiobench.runtime import session as S++ src = inspect.getsource(S)++ def _calls(text: str) -> list:+ # A PAREN COUNTER, not a regex. `rec.gate("follows_the_stream", bool(...), ...)` contains a+ # nested call, and a non-greedy regex stops at the inner closing paren -- reporting the+ # outer call as missing an argument that is two lines further down.+ out = []+ for marker in ("rec.gate(", "recorder.gate("):+ start = 0+ while True:+ i = text.find(marker, start)+ if i < 0:+ break+ j = i + len(marker)+ depth = 1+ while j < len(text) and depth:+ if text[j] == "(":+ depth += 1+ elif text[j] == ")":+ depth -= 1+ j += 1+ args = text[i + len(marker) : j - 1]+ # Skip prose. `session.py` carries a comment reading "WHY THIS IS NOT+ # `recorder.gate(...)`", and a scanner that counts it reports a defect in a+ # sentence.+ line_start = text.rfind("\n", 0, i) + 1+ is_comment = text[line_start:i].lstrip().startswith("#")+ if args.strip() != "..." and not is_comment:+ out.append(args)+ start = j+ return out++ calls = _calls(src)+ assert calls, "no gate calls found, so this test is asserting nothing"+ per_cell = [c for c in calls if "instrument_unavailable" not in c]+ missing = [c.strip()[:60] for c in per_cell if "cell_id" not in c]+ assert not missing, (+ "these per-cell gates do not name the cell they describe, so a failure in one arm at one "+ f"rung will be reported against the synthetic cell 'run': {missing}"+ )diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_copy_from_store_live.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_copy_from_store_live.pynew file mode 100644index 00000000000..816c2d50e14--- /dev/null+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_copy_from_store_live.py@@ -0,0 +1,231 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""SELECT-ALL COPY ON A WINDOWED THREAD, IN A REAL BROWSER, WITH A REAL CLIPBOARD.++The data-loss case, end to end. A windowed message list cannot SELECT what it has not mounted, so+`Selection.toString()` is short by design; whether the user loses their conversation depends+entirely on whether the app's copy handler serialises from the message store. Those two facts look+identical from the DOM and opposite from the clipboard, which is why `select_all_copy` now scores+itself on the clipboard.++The unit tests in the Studio worktree stub `containsNode`, so the rule "the selection spans the+whole mounted list" has never met a real `Selection` there. That is the part most likely to be+quietly wrong -- partial containment, text-node endpoints, whether a select-all over a scroll+container really reports the first and last rows as contained -- and it is what this exercises.++Three threads, one keystroke:++ full mount clipboard whole, selection whole. The shipping build.+ windowed, no handler clipboard SHORT. The regression, reproduced rather than described.+ windowed, handler clipboard whole, selection still short. The fix, and the only+ combination that distinguishes it from the other two.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++_HERE = Path(__file__).resolve()+_STUDIO_TESTS = _HERE.parents[3]+if str(_STUDIO_TESTS) not in sys.path:+ sys.path.insert(0, str(_STUDIO_TESTS))++TURNS = 9+MESSAGES = TURNS * 2+WINDOW = 6++_DOM_JS = _STUDIO_TESTS / "studiobench" / "scene" / "dom.js"+_FIXTURE_JS = _HERE.parent / "thread_fixture.js"+++def _skip_reason() -> str | None:+ try:+ from playwright.sync_api import sync_playwright # noqa: F401+ except Exception as exc: # noqa: BLE001+ return f"playwright is not installed: {exc}"+ return None+++pytestmark = pytest.mark.skipif(_skip_reason() is not None, reason = _skip_reason() or "")++[email protected](scope = "module")+def context():+ from playwright.sync_api import sync_playwright+ with sync_playwright() as p:+ try:+ b = p.chromium.launch(args = ["--no-sandbox"])+ except Exception as exc: # noqa: BLE001+ pytest.skip(f"chromium could not be launched: {exc}")+ # The real harness's browser factory requests the same two. Without them the clipboard+ # read-back throws and the reading is "could not be measured", which is exactly the+ # NOT COMPARABLE outcome the scoring layer now produces rather than a pass.+ ctx = b.new_context(permissions = ["clipboard-read", "clipboard-write"])+ # `navigator.clipboard` DOES NOT EXIST outside a secure context, and `set_content` leaves+ # the page on about:blank, which is not one. The reading came back as+ # "Cannot read properties of undefined" rather than as an empty clipboard, which would have+ # been easy to misread as "the copy did not work". Fulfilled from a route so no server is+ # needed and no network is touched.+ ctx.grant_permissions(["clipboard-read", "clipboard-write"], origin = ORIGIN)+ yield ctx+ ctx.close()+ b.close()+++ORIGIN = "https://studiobench.localhost"+++def _page(context, mode: str, copy_from_store: bool):+ page = context.new_page()+ page.route(+ "**/*",+ lambda route: route.fulfill(+ status = 200,+ content_type = "text/html; charset=utf-8",+ body = "<!doctype html><meta charset=utf-8><title>t</title><body></body>",+ ),+ )+ page.goto(ORIGIN + "/chat")+ page.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))+ page.add_script_tag(content = _FIXTURE_JS.read_text(encoding = "utf-8"))+ page.evaluate(+ "(o) => window.__fixture.build(o)",+ {+ "mode": mode,+ "turns": TURNS,+ "windowSize": WINDOW,+ "copyFromStore": copy_from_store,+ },+ )+ return page+++#: Exactly what scene/actions.select_all_copy does: focus the viewport, select its contents, then a+#: REAL Control+C so the app's own copy handler runs. Anything else would be testing a different+#: code path from the one the benchmark drives.+SELECT_JS = """+async () => {+ const v = window.__sb.dom.viewport();+ v.focus({ preventScroll: true });+ const sel = window.getSelection();+ sel.removeAllRanges();+ const range = document.createRange();+ range.selectNodeContents(v);+ sel.addRange(range);+ await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));+ return sel.toString().length;+}+"""+++def _select_all_copy(page) -> dict:+ selected = page.evaluate(SELECT_JS)+ page.keyboard.press("Control+C")+ page.wait_for_timeout(250)+ clip = page.evaluate("async () => await navigator.clipboard.readText()")+ return {+ "selected_chars": selected,+ "clipboard_chars": len(clip) if isinstance(clip, str) else None,+ "clipboard": clip,+ "mounted": page.evaluate("() => window.__sb.dom.messageCount()"),+ "total": page.evaluate("() => window.__sb.dom.threadTotal()"),+ }+++def _markers_present(clip: str) -> int:+ return sum(1 for i in range(TURNS) if f"studiobench turn {i}:" in clip)+++def test_a_full_mount_copies_the_whole_thread(context):+ page = _page(context, "full", copy_from_store = False)+ try:+ got = _select_all_copy(page)+ finally:+ page.close()+ assert got["mounted"] == got["total"] == MESSAGES+ assert _markers_present(got["clipboard"]) == TURNS+++def test_a_windowed_thread_without_the_handler_loses_most_of_the_conversation(context):+ """THE REGRESSION, REPRODUCED. Not described, not inferred from the mounted count: the+ clipboard is read back and most of the conversation is not in it."""+ page = _page(context, "windowed", copy_from_store = False)+ try:+ got = _select_all_copy(page)+ finally:+ page.close()+ assert got["mounted"] == WINDOW+ assert got["total"] == MESSAGES+ present = _markers_present(got["clipboard"])+ assert present < TURNS, "the windowed thread copied every turn, so there is nothing to fix"+ # Three of nine turns, which is the window. The user pressed Ctrl+A and got a third of it.+ assert present <= WINDOW // 2 + 1+++def test_the_handler_puts_the_whole_conversation_on_the_clipboard(context):+ """THE FIX. Same window, same short selection, whole clipboard.++ Both halves are asserted. A test that only checked the clipboard would pass just as well+ against a build that quietly stopped virtualising, and the entire question is whether the+ conversation survives WHILE the DOM is windowed.+ """+ page = _page(context, "windowed", copy_from_store = True)+ try:+ got = _select_all_copy(page)+ finally:+ page.close()+ assert got["mounted"] == WINDOW < got["total"] == MESSAGES+ assert _markers_present(got["clipboard"]) == TURNS, got["clipboard"][:400]+ # The selection is still short, and that is correct: it can only cover mounted nodes. This is+ # the reading the old alarm was wired to, and it is why the alarm had to be moved.+ assert got["selected_chars"] < got["clipboard_chars"]+++def test_a_partial_selection_is_not_replaced_by_the_whole_conversation(context):+ """The failure mode of the fix itself, which would be worse than the bug.++ Someone highlighting one message must not silently get forty turns of markdown.++ A SENTINEL IS WRITTEN FIRST, because the obvious version of this test is not deterministic. It+ asserted that the partial selection was non-empty, and under a loaded machine+ `Selection.toString()` came back empty for a row Chromium had not laid out -- passing when the+ file ran alone and failing in a full-suite run. Seeding the clipboard means both outcomes are+ still conclusive: either the copy happened and the clipboard holds one row, or it did not and+ the clipboard still holds the sentinel. Neither is the whole conversation, which is the claim.+ """+ page = _page(context, "windowed", copy_from_store = True)+ try:+ page.evaluate("async () => await navigator.clipboard.writeText('SENTINEL')")+ selected = page.evaluate("""+ async () => {+ const rows = document.querySelectorAll("[aria-posinset]");+ const target = rows[rows.length - 1];+ target.scrollIntoView();+ const sel = window.getSelection();+ sel.removeAllRanges();+ const range = document.createRange();+ range.selectNodeContents(target);+ sel.addRange(range);+ await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));+ return sel.toString().length;+ }+ """)+ page.keyboard.press("Control+C")+ page.wait_for_timeout(250)+ clip = page.evaluate("async () => await navigator.clipboard.readText()")+ finally:+ page.close()+ # THE CLAIM, and it holds either way.+ assert _markers_present(clip) <= 1, clip[:300]+ if selected > 0:+ # The copy really happened, so the clipboard is one row's worth and not the conversation.+ assert clip != "SENTINEL"+ assert len(clip) < 1000, clip[:300]+ else:+ # Chromium gave no selection for an off-screen row, so no copy was performed at all. Said+ # out loud rather than passed silently: this run did not exercise the substitution guard.+ assert clip == "SENTINEL"diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_follow_coverage_carveout.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_follow_coverage_carveout.pynew file mode 100644index 00000000000..327610089e0--- /dev/null+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_follow_coverage_carveout.py@@ -0,0 +1,388 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A STREAM-COVERAGE SHORTFALL IS NOT MEASURED; A PINNING FAILURE IS STILL FATAL.++`attached_fraction_of_stream` is set by the SCENE SCHEDULE, not by the build under test. The+shipped film scrolls away twice inside an ~18s opening stream and the app then correctly declines+to yank the reader back, so roughly half the streaming time is detached BY CONSTRUCTION. Measured+over 32 cells: 0.481 +/- 0.009, range 0.4625 to 0.5063 -- which put `FOLLOW_MIN_STREAM_COVERAGE`+of 0.50 above the mean of the quantity it was gating and turned the verdict into a coin flip.++The observed result was 32 of 32 pairs refused with `cell r100K.base.rep0 FAILED its stream-follow+gate`, exit 3, TOO LITTLE COMPARED -- and the NULL CONTROL, the same commit on both arms, refused+identically. A gate that fails its own null is not measuring the thing it names. The prose in+`scene/selftest/test_studiobench_follow_coverage_live.py` had already recorded the same shape at+the earlier 0.07-0.15 coverage ("failed every 100K cell of every run -- two copies of the shipped+build included") without the gate itself being changed.++Both arms run the same film, so the shortfall is symmetric and cancels in any comparison drawn+from these cells. It can only void a run, never discriminate between builds. Raising the constant+was the other option and is the same trap one turn later: it would need re-deriving every time the+film's scroll schedule moves.++So coverage is carved out of the two admission lists the way an absent instrument already is, and+BOTH REMAINING CONJUNCTS STAY FATAL. `pinned_fraction` and `ever_fell_behind` describe how the arm+behaved while it WAS attached and can genuinely differ between builds. This test exists because a+relaxation that cannot be shown to still bite is worthless.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[3]))+sys.path.insert(0, str(Path(__file__).resolve().parents[4]))++from studiobench.runtime.ab import failed_invalidating_gates # noqa: E402+from studiobench.runtime.session import ( # noqa: E402+ FOLLOW_MIN_STREAM_COVERAGE,+ follow_verdict,+)+from studiobench.sweep.ui_parity import incomplete_cells # noqa: E402++#: The coverage actually observed on the run this carve-out was derived from, not a round number.+OBSERVED_COVERAGE = 0.481+++def _records(detail: dict) -> list[dict]:+ return [+ {"row_type": "cell", "cell_id": "c1", "session_id": "s1", "completed": True},+ {+ "row_type": "gate",+ "name": "follows_the_stream",+ "passed": False,+ "cell_id": "c1",+ "session_id": "s1",+ "detail": detail,+ },+ ]+++def _refuses(tmp_path: Path, detail: dict) -> tuple[bool, bool]:+ """(does the A/B table drop this cell, does the UI parity job refuse its pair)."""++ records = _records(detail)+ tmp_path.mkdir(parents = True, exist_ok = True)+ path = tmp_path / "rows.jsonl"+ path.write_text("".join(json.dumps(r) + "\n" for r in records), encoding = "utf-8")+ return bool(failed_invalidating_gates(records)), bool(incomplete_cells([path]))+++def _coverage_short(coverage: float) -> dict:+ """What `session.py` writes when coverage is the ONLY thing that fell short."""++ return {+ "follow_attempted": True,+ "pinned_fraction": 1.0,+ "attached_fraction_of_stream": coverage,+ "ever_fell_behind": False,+ "stream_coverage": coverage,+ "stream_coverage_floor": 0.50,+ "stream_coverage_unmeasured": True,+ }+++def test_coverage_only_shortfall_is_carved_out(tmp_path) -> None:+ """0.481 is the film, not the build. Neither admission list may drop the cell for it."""++ dropped, refused = _refuses(tmp_path, _coverage_short(OBSERVED_COVERAGE))+ assert not dropped, "a coverage shortfall must not void the A/B table"+ assert not refused, "a coverage shortfall must not refuse the UI parity pair"+++def test_a_sliver_is_also_not_measured_rather_than_failed(tmp_path) -> None:+ """The 0.13 sampler-stranding case that motivated the original conjunct.++ It reaches the same destination by design. A verdict resting on 13% of the stream is NOT a+ reading, and "we have no reading" is what NOT MEASURED means -- so the cell is admitted to a+ comparison whose confounds are common to both arms, while the gate row stays `passed: False`+ so nobody can quote the follow verdict itself. The protection the conjunct was added for is+ that the gate refuses to CLAIM a pass, and that is still true; what it may no longer do is+ delete the cell's other, correctly measured columns.+ """++ dropped, refused = _refuses(tmp_path, _coverage_short(0.13))+ assert not dropped+ assert not refused+++def test_a_bad_pinned_fraction_still_bites(tmp_path) -> None:+ """Healthy coverage, genuinely bad pinning. Both lists must still drop the cell."""++ detail = {+ "follow_attempted": True,+ "pinned_fraction": 0.30,+ "attached_fraction_of_stream": 0.90,+ "ever_fell_behind": False,+ "stream_coverage": 0.90,+ "stream_coverage_unmeasured": False,+ "reason": "pinned for 30% of the attached samples",+ }+ dropped, refused = _refuses(tmp_path, detail)+ assert dropped, "a thread that stopped following must still void its cell"+ assert refused, "a thread that stopped following must still refuse its pair"+++def test_falling_behind_still_bites(tmp_path) -> None:+ """`ever_fell_behind` is a property of the arm and stays fatal on its own."""++ detail = {+ "follow_attempted": True,+ "pinned_fraction": 1.0,+ "attached_fraction_of_stream": 0.90,+ "ever_fell_behind": True,+ "stream_coverage": 0.90,+ "stream_coverage_unmeasured": False,+ "reason": "the thread fell behind the stream",+ }+ dropped, refused = _refuses(tmp_path, detail)+ assert dropped+ assert refused+++def test_low_coverage_does_not_launder_a_real_pinning_failure(tmp_path) -> None:+ """The regression that would make the carve-out worthless.++ A cell that failed BOTH must not ride out on the coverage allowance. `session.py` only sets+ `stream_coverage_unmeasured` when coverage was the sole shortfall, and this pins that: were it+ set whenever coverage was low, every genuine follow failure on a large rung -- where coverage+ is low by construction -- would be waived, which is the defect this whole carve-out exists to+ avoid re-introducing in the opposite direction.+ """++ detail = {+ "follow_attempted": True,+ "pinned_fraction": 0.30,+ "attached_fraction_of_stream": 0.20,+ "ever_fell_behind": False,+ "stream_coverage": 0.20,+ "stream_coverage_unmeasured": False,+ "reason": "pinned for 30% of the attached samples",+ }+ dropped, refused = _refuses(tmp_path, detail)+ assert dropped+ assert refused+++#: Every shape a failed `follows_the_stream` row can take, and whether it must still be fatal.+#: The two admission lists have to agree on all of them: `INVALIDATING_CELL_GATES` was centralised+#: so the scorers could not disagree about what invalidates a cell, and a predicate copied into+#: both consumers reintroduces exactly that drift one level down, where it is harder to see+#: because each copy reads correctly on its own.+_AGREEMENT_CASES: list[tuple[str, dict, bool]] = [+ ("coverage-only shortfall", _coverage_short(OBSERVED_COVERAGE), False),+ ("sliver", _coverage_short(0.13), False),+ (+ "bad pinned",+ {+ "follow_attempted": True,+ "pinned_fraction": 0.30,+ "attached_fraction_of_stream": 0.90,+ "ever_fell_behind": False,+ "stream_coverage_unmeasured": False,+ "reason": "pinned low",+ },+ True,+ ),+ (+ "fell behind",+ {+ "follow_attempted": True,+ "pinned_fraction": 1.0,+ "attached_fraction_of_stream": 0.90,+ "ever_fell_behind": True,+ "stream_coverage_unmeasured": False,+ "reason": "fell behind",+ },+ True,+ ),+ (+ "bad pinned AND low coverage",+ {+ "follow_attempted": True,+ "pinned_fraction": 0.30,+ "attached_fraction_of_stream": 0.20,+ "ever_fell_behind": False,+ "stream_coverage_unmeasured": False,+ "reason": "pinned low",+ },+ True,+ ),+ (+ "fell behind AND low coverage",+ {+ "follow_attempted": True,+ "pinned_fraction": 1.0,+ "attached_fraction_of_stream": 0.20,+ "ever_fell_behind": True,+ "stream_coverage_unmeasured": False,+ "reason": "fell behind",+ },+ True,+ ),+ (+ "no pinned reading, sampler present",+ {+ "follow_attempted": True,+ "pinned_fraction": None,+ "attached_fraction_of_stream": 0.90,+ "ever_fell_behind": False,+ "stream_coverage_unmeasured": False,+ "reason": "no pinned reading",+ },+ True,+ ),+ ("absent instrument", {"follow_attempted": False, "reason": "sampler is not installed"}, False),+ # The narrowing that must survive the refactor: `probe_attempted: False` has two producers and+ # only one is an absent instrument. A missing thread viewport is the ARM missing the surface+ # under test, and waiving it once let a real failure ride the instrument allowance.+ ("no thread viewport", {"probe_attempted": False, "reason": "no thread viewport"}, True),+]+++def test_both_admission_lists_agree_on_every_shape(tmp_path) -> None:+ """The property the copied predicate threatened, pinned directly."""++ disagreed: list[str] = []+ wrong: list[str] = []+ for index, (label, detail, want_fatal) in enumerate(_AGREEMENT_CASES):+ dropped, refused = _refuses(tmp_path / f"case{index}", detail)+ if dropped != refused:+ disagreed.append(f"{label}: ab={dropped} ui_parity={refused}")+ elif dropped != want_fatal:+ wrong.append(f"{label}: got {dropped}, wanted {want_fatal}")+ assert not disagreed, "the two admission lists disagree: " + "; ".join(disagreed)+ assert not wrong, "wrong verdict: " + "; ".join(wrong)+++# ---------------------------------------------------------------------------------------+# the WRITER. Everything above drives the two consumers with a hand-built gate detail, which+# cannot see a defect in the thing that PRODUCES that detail: a `follow_verdict` that set+# `stream_coverage_unmeasured` on every low reading would waive real follow failures and every+# consumer test would still pass. These drive the real writer.+# ---------------------------------------------------------------------------------------+++def _sampled(+ pinned,+ coverage,+ fell_behind = False,+ reattachments = 2,+) -> dict:+ """What `scene/dom.js::read()` returns. `reattachments` defaults to the film's own two.++ It is not decoration: the waiver's premise is that the detachment was the SCHEDULE's, and the+ sampler's proof of that is the arm coming back. A cell with 0 of them was detached for the rest+ of the film because the BUILD would not re-pin.+ """++ return {+ "follow_attempted": True,+ "pinned_fraction": pinned,+ "attached_fraction_of_stream": coverage,+ "ever_fell_behind": fell_behind,+ "reattachments": reattachments,+ }+++def test_writer_waives_only_a_lone_coverage_shortfall() -> None:+ """`stream_coverage_unmeasured` requires that NOTHING ELSE fell short.++ This is the conjunction that stops the carve-out laundering a real failure, and it is only+ visible here: a consumer test supplies the flag rather than deriving it.+ """++ passed, rec = follow_verdict(_sampled(1.0, OBSERVED_COVERAGE))+ assert passed is False, "the gate row must still read as failed"+ assert rec["stream_coverage_unmeasured"] is True++ # a bad pinned fraction alongside the same shortfall must NOT be waived+ _, rec = follow_verdict(_sampled(0.30, 0.20))+ assert rec["stream_coverage_unmeasured"] is False++ # nor may falling behind+ _, rec = follow_verdict(_sampled(1.0, 0.20, fell_behind = True))+ assert rec["stream_coverage_unmeasured"] is False++ # nor an absent pinned reading while the sampler was present+ _, rec = follow_verdict(_sampled(None, 0.20))+ assert rec["stream_coverage_unmeasured"] is False+++def test_an_arm_that_never_reattached_is_not_waived(tmp_path) -> None:+ """The half of the shortfall that IS the build, and the shape it wears.++ `scene/dom.js` clears `detached` only when a run that began after the harness's gesture is+ observed at the bottom, so an arm that stops re-pinning on a new turn stays detached for the+ rest of the film. The detached branch returns before the pinned and fell-behind accounting, so+ the opening stream's perfect `pinned_fraction` and `ever_fell_behind: False` survive while+ coverage collapses -- the exact shape of a lone coverage shortfall, produced by the one failure+ the gate exists to catch. Waived, the cell keeps its artificially cheap timings (an unmounted+ reply costs nothing to paint) and is compared against a healthy partner.+ """++ _, rec = follow_verdict(_sampled(1.0, 0.10, reattachments = 0))+ assert rec["stream_coverage_unmeasured"] is False++ detail = _sampled(1.0, 0.10, reattachments = 0)+ detail.update(rec)+ dropped, refused = _refuses(tmp_path, detail)+ assert dropped, "a build that never came back must still void its cell"+ assert refused, "a build that never came back must still refuse its pair"+++def test_the_schedules_own_shortfall_is_still_waived(tmp_path) -> None:+ """The control: same coverage story, but the arm DID come back, so 0.481 is the film."""++ _, rec = follow_verdict(_sampled(1.0, OBSERVED_COVERAGE, reattachments = 2))+ assert rec["stream_coverage_unmeasured"] is True+++def test_writer_records_the_coverage_as_a_number_either_way() -> None:+ """The quantity has to be legible as a quantity, whatever the verdict.++ It sat undetected precisely because it was only ever visible as a pass or a fail.+ """++ for coverage in (OBSERVED_COVERAGE, 0.13, 0.99):+ _, rec = follow_verdict(_sampled(1.0, coverage))+ assert rec["stream_coverage"] == coverage+ assert rec["stream_coverage_floor"] == FOLLOW_MIN_STREAM_COVERAGE+++def test_writer_passes_the_gate_when_the_film_does_cover_the_stream() -> None:+ """The carve-out must not make the gate unfailable OR unpassable."""++ passed, rec = follow_verdict(_sampled(1.0, 0.90))+ assert passed is True+ assert rec["stream_coverage_unmeasured"] is False+ assert "stream_coverage_reason" not in rec+++def test_writer_treats_an_absent_coverage_reading_as_short() -> None:+ """None is not a high number. A sampler that returned no coverage has not shown the film."""++ passed, rec = follow_verdict(_sampled(1.0, None))+ assert passed is False+ assert rec["stream_coverage"] is None+ assert "unknown share" in rec["stream_coverage_reason"]+++def test_not_measured_stays_distinguishable_from_a_pass(tmp_path) -> None:+ """Carving the cell out of the admission lists must not rewrite the gate row.++ "Not measured" and "compared and equal" are different claims and the payload has to keep them+ apart: the gate row still reads `passed: False`, and the coverage is still there AS A NUMBER+ rather than as the pass/fail it used to be visible only as. That is the whole reason 0.481 sat+ undetected long enough to void a campaign.+ """++ detail = _coverage_short(OBSERVED_COVERAGE)+ records = _records(detail)+ gate = [r for r in records if r["row_type"] == "gate"][0]+ assert gate["passed"] is False, "the carve-out must not manufacture a passing gate"+ assert gate["detail"]["stream_coverage"] == OBSERVED_COVERAGE+ assert isinstance(gate["detail"]["stream_coverage"], float)diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_probe_survives_failure.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_probe_survives_failure.pyindex 43e228fb6e4..46725965fff 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_probe_survives_failure.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_probe_survives_failure.py@@ -123,8 +123,17 @@ class _Seeder:auth = Nonedef seed(self, plan):- # No messages, so the mount wait is the selector and not a count that never arrives.- return types.SimpleNamespace(thread_id = "t-1", seconds = 0.0, messages = 0)+ # No messages, so the mount wait is the selector and not a count that never arrives, and+ # both markers `SeededThread` declares are present and `None` for the same reason:+ # `_wait_for_thread` reads `last_marker` unconditionally, and a stub that omits it fails on+ # the attribute rather than on the failure these tests are about.+ return types.SimpleNamespace(+ thread_id = "t-1",+ seconds = 0.0,+ messages = 0,+ first_marker = None,+ last_marker = None,+ )def _unit() -> Unit:diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_readiness_live.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_readiness_live.pynew file mode 100644index 00000000000..aa4b906154a--- /dev/null+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_readiness_live.py@@ -0,0 +1,928 @@+# 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 GATE, SHOWN PASSING AND SHOWN FAILING, in a real browser.++A gate nobody has watched refuse anything is not a gate, and the one this replaces was refusing+the wrong thing: it counted mounted `[data-role]` nodes, so a thread that mounts a window on+purpose could never satisfy it and the virtualization arm scored UNSCORED. The fix is only worth+having if it can be shown to admit the arm AND still refuse a thread that is not ready, so both+are constructed here rather than argued about.++Ten threads, one gate:++ full admitted in `full` mode. The shipped app.+ windowed admitted in `windowed` mode. A window at the end of the thread that+ publishes aria-setsize and aria-posinset, sits at the bottom, and+ materialises the head when you scroll to the top.+ mounting REFUSED in both modes. Nine of eighteen and climbing: the exact state the+ gate exists for, and the state the old gate did correctly catch.+ windowed_no_total REFUSED in `windowed` mode. A window that never says how long the thread is.+ windowed_at_top REFUSED in `windowed` mode. Settled, correct total, and showing the wrong+ end of the conversation.+ windowed_zero_ordinals+ windowed_duplicate_ordinals+ windowed_from_one REFUSED in `windowed` mode. All three publish aria-posinset on every mounted+ row, which is all the gate used to ask for, and none of the three publishes+ a POSITION: all zeros, all identical, and a window at the bottom of an+ eighteen-message thread numbered 1..6.+ windowed_lost_head ADMITTED by the readiness gate and REFUSED by the completeness probe. The+ honest split, and it is asserted in both directions: standing at the bottom+ of a thread there is no way to tell a virtualizer from a thread that has+ lost its history, so the probe walks to the top and looks.+ windowed_lost_middle+ ADMITTED by the readiness gate, ADMITTED by the head marker, and REFUSED on+ ordinal coverage. The head is there and the tail is there, so every check+ that looks at one end of the thread is satisfied; what is gone is the+ middle, and the only evidence is the ordinals of the mounted rows.++And the coverage verdict is asserted in its NOT MEASURED direction too, twice, because a probe+that reports what it did not look at as data loss is worse than no probe: an arm that publishes no+ordinals at all, and a gesture that never reached the top.++Everything under test is the production code path: the real `scene/dom.js`, the real `PROBE_JS`,+the real `wait_for_thread_ready` and `probe_thread_completeness`. The only synthetic part is the+page, which supplies the DOM contract the app publishes and nothing else.++Requires Playwright with Chromium. Skips cleanly without it, because a machine that cannot run a+browser should say so rather than fail.++ python -m pytest tests/studio/studiobench/runtime/selftest/test_studiobench_readiness_live.py -q+"""++from __future__ import annotations++import os+import sys+from pathlib import Path++import pytest++_HERE = Path(__file__).resolve()+_STUDIO_TESTS = _HERE.parents[3]+if str(_STUDIO_TESTS) not in sys.path:+ sys.path.insert(0, str(_STUDIO_TESTS))++from studiobench.runtime.readiness import ( # noqa: E402+ COVERAGE_COMPLETE,+ COVERAGE_INCOMPLETE,+ COVERAGE_NOT_APPLICABLE,+ COVERAGE_UNMEASURED,+ MODE_FULL,+ MODE_WINDOWED,+ ThreadNotReady,+ evaluate,+ ordinal_coverage,+ probe_thread_completeness,+ wait_for_thread_ready,+)+from studiobench.runtime.seeder import turn_marker # noqa: E402++TURNS = 9+MESSAGES = TURNS * 2 # 18, the number in the failure this work exists to fix+WINDOW = 6+#: The fixture's row height. The completeness tests step the traversal by two rows, because a+#: gesture whose stops do not overlap can only report NOT MEASURED, and a test that wants to see+#: coverage refuse something has to give the probe a sweep that actually covers the thread.+ROW_PX = 120++_DOM_JS = _STUDIO_TESTS / "studiobench" / "scene" / "dom.js"+_FIXTURE_JS = _HERE.parent / "thread_fixture.js"+++def _skip_reason() -> str | None:+ try:+ from playwright.sync_api import sync_playwright # noqa: F401+ except Exception as exc: # noqa: BLE001+ return f"playwright is not installed: {exc}"+ return None+++pytestmark = pytest.mark.skipif(_skip_reason() is not None, reason = _skip_reason() or "")++[email protected](scope = "module")+def browser():+ from playwright.sync_api import sync_playwright+ with sync_playwright() as p:+ try:+ b = p.chromium.launch(args = ["--no-sandbox"])+ except Exception as exc: # noqa: BLE001+ pytest.skip(f"chromium could not be launched: {exc}")+ yield b+ b.close()+++def _page(+ browser,+ mode: str,+ turns: int = TURNS,+):+ page = browser.new_page(viewport = {"width": 900, "height": 600})+ page.set_content("<!doctype html><meta charset=utf-8><body></body>")+ page.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))+ page.add_script_tag(content = _FIXTURE_JS.read_text(encoding = "utf-8"))+ built = page.evaluate(+ "(o) => window.__fixture.build(o)",+ {"mode": mode, "turns": turns, "windowSize": WINDOW},+ )+ assert built["total"] == turns * 2+ return page+++def _lines() -> tuple[list[str], callable]:+ got: list[str] = []+ return got, got.append+++# ── the fixture itself, before it is trusted to prove anything ──────+++def test_the_fixture_marker_matches_the_seeder_exactly(browser):+ """If these two ever drift, every gate below passes or fails for the wrong reason.++ The gate looks for a string the seeder wrote. A fixture that writes a slightly different one+ would make the negative cases pass for free and the positive ones fail mysteriously, so the+ agreement is asserted rather than assumed.+ """+ page = _page(browser, "full")+ try:+ assert page.evaluate("(i) => window.__fixture.marker(i)", 0) == turn_marker(0, 0)+ assert page.evaluate("(i) => window.__fixture.marker(i)", 8) == turn_marker(8, 8)+ finally:+ page.close()+++def test_the_fixture_really_mounts_what_each_mode_claims(browser):+ """The fixture is the instrument here, so its own readings are checked first."""+ expected = {+ "full": MESSAGES,+ "windowed": WINDOW,+ "windowed_no_total": WINDOW,+ "windowed_at_top": WINDOW,+ "windowed_lost_head": WINDOW,+ "windowed_lost_middle": WINDOW,+ "windowed_zero_ordinals": WINDOW,+ "windowed_duplicate_ordinals": WINDOW,+ "windowed_from_one": WINDOW,+ }+ for mode, want in expected.items():+ page = _page(browser, mode)+ try:+ got = page.evaluate("() => window.__sb.dom.messageCount()")+ assert got == want, f"{mode} mounted {got}, expected {want}"+ finally:+ page.close()+++def test_thread_total_reads_the_published_setsize_and_falls_back_to_the_count(browser):+ """`threadTotal()` is what every before/after assertion in actions.py now uses."""+ page = _page(browser, "full")+ try:+ # No aria-setsize anywhere: it must degrade to exactly today's messageCount().+ assert page.evaluate("() => window.__sb.dom.threadTotal()") == MESSAGES+ assert page.evaluate("() => window.__sb.dom.isWindowed()") is False+ finally:+ page.close()+ page = _page(browser, "windowed")+ try:+ assert page.evaluate("() => window.__sb.dom.threadTotal()") == MESSAGES+ assert page.evaluate("() => window.__sb.dom.messageCount()") == WINDOW+ assert page.evaluate("() => window.__sb.dom.isWindowed()") is True+ finally:+ page.close()+++# ── what the gate must ADMIT ────────────────────────────────────────+++def test_full_mount_is_admitted_in_full_mode(browser):+ page = _page(browser, "full")+ got, log = _lines()+ try:+ r = wait_for_thread_ready(+ page,+ MESSAGES,+ marker = turn_marker(TURNS - 1, TURNS - 1),+ mode = MODE_FULL,+ timeout_s = 20,+ log = log,+ )+ finally:+ page.close()+ assert r.ready+ assert r.conditions["all_messages_mounted"] is True+ assert r.conditions["end_present"] is True+ assert r.conditions["settled"] is True+ assert r.probe["mounted"] == MESSAGES+ # AND THE ORDINAL CONDITIONS ARE NOT APPLICABLE HERE, which is not the same as passing.+ # Studio publishes no aria-posinset anywhere, so a `full` arm has none to validate and must+ # never be gated on them; `None` is the value the parity layer and this gate both use for a+ # surface that was not measured rather than one that agreed.+ assert r.conditions["posinset_ordinals_valid"] is None+ assert r.conditions["posinset_reaches_end"] is None+ assert r.probe["posinset_count"] == 0+++def test_a_virtualised_thread_is_admitted_in_windowed_mode(browser):+ """THE WHOLE POINT. Six of eighteen mounted, and the gate says ready."""+ page = _page(browser, "windowed")+ got, log = _lines()+ try:+ r = wait_for_thread_ready(+ page,+ MESSAGES,+ marker = turn_marker(TURNS - 1, TURNS - 1),+ mode = MODE_WINDOWED,+ timeout_s = 20,+ log = log,+ )+ finally:+ page.close()+ assert r.ready, r.reason+ assert r.probe["mounted"] == WINDOW < MESSAGES+ assert r.conditions["total_matches_seeded"] is True+ assert r.conditions["posinset_on_every_row"] is True+ assert r.conditions["posinset_ordinals_valid"] is True+ assert r.conditions["posinset_reaches_end"] is True+ assert r.conditions["anchored_at_end"] is True+ assert r.conditions["end_present"] is True+ # The ordinals of a window at the END of an eighteen-message thread: 13..18, distinct, one per+ # mounted row. This is the shape the three malformed modes below fail to produce.+ assert (r.probe["min_posinset"], r.probe["max_posinset"]) == (MESSAGES - WINDOW + 1, MESSAGES)+ assert r.probe["posinset_distinct"] == WINDOW++[email protected]("mode", ["windowed", "windowed_flat"])+def test_the_ordinals_are_accepted_on_the_row_wrapper_or_on_the_message(browser, mode):+ """WHERE the attributes live must not decide whether the arm can be scored.++ `thread-message-virtualizer.tsx` renders an absolutely positioned wrapper per item and mounts+ the message inside it, so the element that is a member of the set is the wrapper. That is the+ correct place for `aria-posinset`, and a gate that only looked at `[data-role]` would refuse a+ correctly implemented arm for putting the attribute exactly where it belongs.+ """+ page = _page(browser, mode)+ got, log = _lines()+ try:+ assert page.evaluate("() => window.__sb.dom.threadTotal()") == MESSAGES+ r = wait_for_thread_ready(+ page,+ MESSAGES,+ marker = turn_marker(TURNS - 1, TURNS - 1),+ mode = MODE_WINDOWED,+ timeout_s = 20,+ log = log,+ )+ finally:+ page.close()+ assert r.ready, r.reason+ assert r.probe["setsize"] == MESSAGES+ assert r.conditions["posinset_on_every_row"] is True+++def _completeness(browser, mode: str, **kwargs) -> tuple[dict, list[str]]:+ """Bring `mode` up in windowed mode, then run the completeness probe over it."""+ page = _page(browser, mode)+ got, log = _lines()+ try:+ wait_for_thread_ready(+ page,+ MESSAGES,+ marker = turn_marker(TURNS - 1, TURNS - 1),+ mode = MODE_WINDOWED,+ timeout_s = 20,+ log = log,+ )+ out = probe_thread_completeness(+ page,+ first_marker = turn_marker(0, 0),+ expected_messages = MESSAGES,+ timeout_s = kwargs.pop("timeout_s", 15),+ log = log,+ **kwargs,+ )+ finally:+ page.close()+ return out, got+++def test_a_virtualised_thread_passes_the_completeness_probe(browser):+ out, _ = _completeness(browser, "windowed")+ assert out["head_reached"] is True, out+ # AND THE COVERAGE VERDICT IS NOT MEASURED AT THE DEFAULT STEP, which is the honest answer+ # rather than a flattering one. The gesture jumps 2,000px at a time and this fixture's whole+ # thread is 2,160px, so it lands at the bottom and then at the top and the rows between the+ # two stops were never in view. Nothing is known about them, so nothing is claimed.+ assert out["ordinal_coverage_complete"] is None, out+ assert out["sweep_continuous"] is False+ assert "never in view" in out["coverage_reason"]+ # WHICH KIND OF NOT MEASURED. The arm publishes ordinals, so the question applies and the+ # sweep failed to answer it, which `record_completeness_gate` refuses to score the cell on.+ # The remedy is the smaller step the next test uses, not a gate that accepts the unknown.+ assert out["ordinal_coverage_state"] == COVERAGE_UNMEASURED, out+++def test_a_virtualised_thread_covers_every_ordinal_when_the_sweep_is_continuous(browser):+ """The same correct thread, walked in steps small enough to overlap.++ This is what coverage looks like when it is actually measurable: every consecutive stop mounts+ a window overlapping the last, so the union is everything the thread can show, and it is all+ eighteen messages.+ """+ out, _ = _completeness(browser, "windowed", step_px = ROW_PX * 2)+ assert out["head_reached"] is True, out+ assert out["sweep_continuous"] is True+ assert out["ordinal_coverage_complete"] is True, out+ assert out["ordinal_coverage_state"] == COVERAGE_COMPLETE, out+ assert out["ordinals_seen_count"] == MESSAGES+ assert out["ordinals_missing"] == []+++def test_a_thread_that_lost_the_middle_passes_the_head_marker_and_fails_coverage(browser):+ """THE CASE THE MARKER CHECK ALONE CALLED COMPLETE.++ The store kept the first page and the last page. Standing at the bottom, every readiness+ condition holds -- the window is at the end, the total is right, the ordinals are positions.+ Scroll to the top and the first message of the conversation arrives, so `head_reached` is+ true. Twelve of the eighteen messages do not exist anywhere in the arm, and before this the+ cell was scoreable.++ What catches it does not depend on the step size: a virtualizer mounts a CONTIGUOUS run, so+ ordinals 4..15 missing from a single mounted window that spans 1..18 is the store, not the+ gesture. That is why this runs at the default step and still refuses.+ """+ out, got = _completeness(browser, "windowed_lost_middle")+ assert out["head_reached"] is True, out+ assert out["ordinal_coverage_complete"] is False, out+ assert out["ordinal_coverage_state"] == COVERAGE_INCOMPLETE, out+ assert out["ordinals_missing"] == list(range(4, MESSAGES - 2))+ assert out["ordinals_in_window_holes"] == list(range(4, MESSAGES - 2))+ assert "MIDDLE" in out["coverage_reason"]+ assert any("COMPLETENESS FAILED" in line for line in got)+++def test_coverage_does_not_apply_to_an_arm_that_publishes_no_ordinals(browser):+ """A fully mounted arm publishes no aria-posinset, and that is not eighteen lost messages.++ The probe can be pointed at a `full` arm (`--completeness-probe` is a per-runner flag, not a+ property of the mode), and there is nothing to count when it is. Reporting the seeded ordinals+ as missing there would turn the shipped build into the worst data-loss finding in the payload.++ NOT APPLICABLE rather than UNMEASURED, and the distinction is load-bearing: the gate declines+ to score a cell whose coverage was unmeasured, so calling this one unmeasured would fail the+ shipped build on every cell it is pointed at.+ """+ page = _page(browser, "full")+ got, log = _lines()+ try:+ wait_for_thread_ready(+ page,+ MESSAGES,+ marker = turn_marker(TURNS - 1, TURNS - 1),+ mode = MODE_FULL,+ timeout_s = 20,+ log = log,+ )+ out = probe_thread_completeness(+ page,+ first_marker = turn_marker(0, 0),+ expected_messages = MESSAGES,+ timeout_s = 10,+ log = log,+ )+ finally:+ page.close()+ assert out["head_reached"] is True, out+ assert out["ordinals_seen_count"] == 0+ assert out["ordinal_coverage_complete"] is None, out+ assert out["ordinal_coverage_state"] == COVERAGE_NOT_APPLICABLE, out+ assert "nothing to count" in out["coverage_reason"]+++def test_coverage_is_not_measured_when_the_gesture_never_reached_the_top(browser):+ """The rule `head_reached` already follows, applied to coverage.++ One step of two rows on a thread eighteen rows long: the viewport never gets near the top, so+ the head did not mount and most ordinals were never seen. Neither of those is a fact about the+ arm, and both used to be reportable as one.+ """+ out, got = _completeness(+ browser,+ "windowed",+ steps = 1,+ step_px = ROW_PX * 2,+ timeout_s = 2,+ )+ assert out["head_reached"] is None, out+ assert out["reached_top"] is False+ assert out["ordinal_coverage_complete"] is None, out+ assert out["ordinal_coverage_state"] == COVERAGE_UNMEASURED, out+ assert "never looked for" in out["coverage_reason"]+ assert any("NOT MEASURED" in line for line in got)+++def test_windowed_mode_also_admits_a_thread_short_enough_to_mount_whole(browser):+ """The same arm at a rung whose thread fits inside the window.++ A virtualised build mounts every message of a short thread, exactly like the shipped one, and+ then has nothing to publish a total ABOUT. If `windowed` refused that, the mode would only+ work at some rungs of the same arm and the ladder would have holes in it for a reason that has+ nothing to do with the app. The relaxation needs `mounted >= expected`, which IS the+ full-mount condition, so nothing half-built can reach it -- the test below proves that+ directly.+ """+ page = _page(browser, "full", turns = 2)+ got, log = _lines()+ try:+ r = wait_for_thread_ready(+ page,+ 4,+ marker = turn_marker(1, 1),+ mode = MODE_WINDOWED,+ timeout_s = 20,+ log = log,+ )+ finally:+ page.close()+ assert r.ready, r.reason+ assert r.probe["setsize"] is None+ assert r.conditions["total_declared"] is True+ # THE SAME WAIVER COVERS THE ORDINALS, and for the same reason: there are none to publish and+ # none to validate. It is waived on `mounted >= expected` AND on the absence of ordinals+ # together, so an arm that publishes malformed ones cannot buy its way out by also mounting+ # the whole thread.+ assert r.probe["posinset_count"] == 0+ assert r.conditions["posinset_ordinals_valid"] is True+ assert r.conditions["posinset_reaches_end"] is True+++# ── what the gate must REFUSE ───────────────────────────────────────+++def test_a_half_mounted_thread_is_refused_in_full_mode(browser):+ """The original failure, reproduced: mounting, not finished, and not admitted."""+ page = _page(browser, "mounting")+ got, log = _lines()+ try:+ with pytest.raises(ThreadNotReady) as caught:+ wait_for_thread_ready(+ page,+ MESSAGES,+ marker = turn_marker(TURNS - 1, TURNS - 1),+ mode = MODE_FULL,+ timeout_s = 4,+ log = log,+ )+ finally:+ page.close()+ detail = caught.value.detail+ assert detail["ready"] is False+ assert detail["conditions"]["all_messages_mounted"] is False+ # And the two NEW conditions caught it too, independently of the count. That matters: it is+ # what makes the windowed mode safe, because the windowed mode has no count to rely on.+ assert detail["conditions"]["end_present"] is False+ assert detail["probe"]["mounted"] < MESSAGES+++def test_a_half_mounted_thread_is_refused_in_windowed_mode_too(browser):+ """The one that decides whether `windowed` is a gate or a hole.++ A thread that is still mounting looks superficially like a windowed one: fewer messages are in+ the DOM than the thread contains. If `windowed` mode admitted it, the mode would be a way of+ switching the gate off, and every reading taken through it would be the flattering garbage the+ gate exists to prevent.+ """+ page = _page(browser, "mounting")+ got, log = _lines()+ try:+ with pytest.raises(ThreadNotReady) as caught:+ wait_for_thread_ready(+ page,+ MESSAGES,+ marker = turn_marker(TURNS - 1, TURNS - 1),+ mode = MODE_WINDOWED,+ timeout_s = 4,+ log = log,+ )+ finally:+ page.close()+ conditions = caught.value.detail["conditions"]+ # THREE independent refusals, not one. It is still growing, it has not reached the end of the+ # thread, and it publishes no total.+ assert conditions["settled"] is False+ assert conditions["end_present"] is False+ assert conditions["total_declared"] is False+++def test_a_window_that_publishes_no_total_is_refused(browser):+ page = _page(browser, "windowed_no_total")+ got, log = _lines()+ try:+ with pytest.raises(ThreadNotReady) as caught:+ wait_for_thread_ready(+ page,+ MESSAGES,+ marker = turn_marker(TURNS - 1, TURNS - 1),+ mode = MODE_WINDOWED,+ timeout_s = 4,+ log = log,+ )+ finally:+ page.close()+ conditions = caught.value.detail["conditions"]+ assert conditions["total_declared"] is False+ assert conditions["total_matches_seeded"] is False+ # Everything else about it was fine, which is the point: the refusal is specific.+ assert conditions["settled"] is True+ assert conditions["end_present"] is True+++def test_a_window_over_the_wrong_end_of_the_thread_is_refused(browser):+ page = _page(browser, "windowed_at_top")+ got, log = _lines()+ try:+ with pytest.raises(ThreadNotReady) as caught:+ wait_for_thread_ready(+ page,+ MESSAGES,+ marker = turn_marker(TURNS - 1, TURNS - 1),+ mode = MODE_WINDOWED,+ timeout_s = 4,+ log = log,+ )+ finally:+ page.close()+ conditions = caught.value.detail["conditions"]+ assert conditions["end_present"] is False+ assert conditions["anchored_at_end"] is False+ assert conditions["total_matches_seeded"] is True+++def _refused(browser, mode: str) -> dict:+ """Run the gate against `mode` in windowed mode and return the conditions it refused on."""+ page = _page(browser, mode)+ got, log = _lines()+ try:+ with pytest.raises(ThreadNotReady) as caught:+ wait_for_thread_ready(+ page,+ MESSAGES,+ marker = turn_marker(TURNS - 1, TURNS - 1),+ mode = MODE_WINDOWED,+ timeout_s = 4,+ log = log,+ )+ finally:+ page.close()+ return caught.value.detail+++def test_a_window_whose_rows_all_publish_a_zero_ordinal_is_refused(browser):+ """`aria-posinset` is 1-based, so 0 is not a position, it is the attribute being present.++ This is the first of the three shapes that passed the old condition: it asked whether every+ mounted row carried a finite number and every row here does. A window numbered 0,0,0,0,0,0+ tells a screen reader nothing about where it is in the thread, and told this gate nothing+ either while satisfying it.+ """+ detail = _refused(browser, "windowed_zero_ordinals")+ conditions = detail["conditions"]+ # The OLD condition still passes, which is exactly why it was not a check.+ assert conditions["posinset_on_every_row"] is True+ assert detail["probe"]["posinset_count"] == WINDOW+ assert conditions["posinset_ordinals_valid"] is False+ assert detail["probe"]["min_posinset"] == 0+ # And nothing else about the thread was wrong: the refusal is specific to the ordinals.+ assert conditions["settled"] is True+ assert conditions["end_present"] is True+ assert conditions["total_matches_seeded"] is True+++def test_a_window_whose_rows_all_claim_the_same_ordinal_is_refused(browser):+ """Six mounted rows and one position between them.++ Uniqueness is the property that makes the ordinals a MAP from row to place in the thread. Note+ what this mode gets right, so the refusal cannot be credited to anything else: the ordinal it+ publishes is the seeded total, so the window still reaches the end of the thread and+ `posinset_reaches_end` passes.+ """+ detail = _refused(browser, "windowed_duplicate_ordinals")+ conditions = detail["conditions"]+ assert conditions["posinset_on_every_row"] is True+ assert detail["probe"]["posinset_count"] == WINDOW+ assert detail["probe"]["posinset_distinct"] == 1+ assert conditions["posinset_ordinals_valid"] is False+ assert conditions["posinset_reaches_end"] is True+ assert conditions["end_present"] is True+++def test_a_bottom_window_numbered_from_one_is_refused(browser):+ """The likeliest of the three to be written by accident: the index WITHIN the window.++ Every ordinal here is a legal position -- 1..6, distinct, inside the declared set size -- so+ validity alone admits it. What refuses it is that a window sitting at the bottom of an+ eighteen-message thread claims to be its first six messages, which would make the mounted set+ unlocatable and would make a window at the end indistinguishable from one at the start.+ """+ detail = _refused(browser, "windowed_from_one")+ conditions = detail["conditions"]+ assert conditions["posinset_on_every_row"] is True+ assert conditions["posinset_ordinals_valid"] is True+ assert detail["probe"]["max_posinset"] == WINDOW+ assert conditions["posinset_reaches_end"] is False+ # The TEXT of the last message is mounted; only the numbering disagrees with it. That split is+ # the point: `end_present` reads the thread and this reads what the arm says about it.+ assert conditions["end_present"] is True+ assert conditions["anchored_at_end"] is True+++def test_a_thread_that_lost_its_head_passes_readiness_and_fails_completeness(browser):+ """THE HONEST SPLIT, asserted in both directions.++ From the bottom of the thread this is indistinguishable from a correct virtualizer: the same+ window, the same published total, the same anchor. The readiness gate therefore admits it, and+ saying otherwise would be claiming a power the reading does not have. What catches it is the+ completeness probe, which does the only thing a user could do -- scroll to the top and look for+ the beginning of the conversation.+ """+ page = _page(browser, "windowed_lost_head")+ got, log = _lines()+ try:+ r = wait_for_thread_ready(+ page,+ MESSAGES,+ marker = turn_marker(TURNS - 1, TURNS - 1),+ mode = MODE_WINDOWED,+ timeout_s = 20,+ log = log,+ )+ assert r.ready+ out = probe_thread_completeness(+ page,+ first_marker = turn_marker(0, 0),+ expected_messages = MESSAGES,+ timeout_s = 6,+ log = log,+ )+ finally:+ page.close()+ assert out["head_reached"] is False, out+ assert "not holding the whole conversation" in out["reason"]+ assert any("COMPLETENESS FAILED" in line for line in got)+++# ── the decision function, without a browser ────────────────────────+++def test_evaluate_never_reports_a_mode_inapplicable_condition_as_a_pass():+ """`None` is not `True`, and the difference is the whole design of the two modes."""+ probe = {+ "probe_attempted": True,+ "mounted": 6,+ "elements": 40,+ "composer": True,+ "setsize": None,+ "posinset_count": 0,+ "marker_found": True,+ "marker_from_end": 1,+ "scroll_height": 100,+ "from_bottom": 0,+ "app_says_at_bottom": True,+ "pinning": False,+ }+ full = evaluate(probe, probe, 18, MODE_FULL)+ assert full["total_declared"] is None+ assert full["all_messages_mounted"] is False+ windowed = evaluate(probe, probe, 18, MODE_WINDOWED)+ assert windowed["total_declared"] is False+ assert "all_messages_mounted" not in windowed+++def _windowed_probe(**changes) -> dict:+ """A settled window at the end of an 18-message thread, correct in every respect."""+ probe = {+ "probe_attempted": True,+ "mounted": 6,+ "elements": 40,+ "composer": True,+ "setsize": 18,+ "posinset_count": 6,+ "posinset_distinct": 6,+ "min_posinset": 13,+ "max_posinset": 18,+ "marker_found": True,+ "marker_from_end": 1,+ "scroll_height": 100,+ "from_bottom": 0,+ "app_says_at_bottom": True,+ "pinning": False,+ }+ probe.update(changes)+ return probe+++def test_evaluate_refuses_ordinals_that_are_not_positions():+ """The three malformed shapes, on the decision function itself.++ The live tests above put each of these in a real browser; this pins the rule they are being+ judged by, including which of the two conditions each one trips.+ """+ good = _windowed_probe()+ assert evaluate(good, good, 18, MODE_WINDOWED)["posinset_ordinals_valid"] is True+ zeros = _windowed_probe(posinset_distinct = 1, min_posinset = 0, max_posinset = 0)+ assert evaluate(zeros, zeros, 18, MODE_WINDOWED)["posinset_ordinals_valid"] is False+ duplicates = _windowed_probe(posinset_distinct = 1, min_posinset = 18)+ assert evaluate(duplicates, duplicates, 18, MODE_WINDOWED)["posinset_ordinals_valid"] is False+ from_one = _windowed_probe(min_posinset = 1, max_posinset = 6)+ conditions = evaluate(from_one, from_one, 18, MODE_WINDOWED)+ assert conditions["posinset_ordinals_valid"] is True+ assert conditions["posinset_reaches_end"] is False+ # PAST THE END OF THE SET THE SAME ROWS DECLARE. 19 of 18 is not a position either, and it is+ # what an off-by-one in a virtualizer's index-to-ordinal arithmetic produces.+ over = _windowed_probe(max_posinset = 19)+ assert evaluate(over, over, 18, MODE_WINDOWED)["posinset_ordinals_valid"] is False+ # And every one of them is NOT APPLICABLE in full mode, where nothing publishes ordinals.+ assert evaluate(zeros, zeros, 18, MODE_FULL)["posinset_ordinals_valid"] is None+++def test_evaluate_does_not_waive_malformed_ordinals_for_a_fully_mounted_thread():+ """The waiver is for a thread that publishes NO ordinals, not for one that publishes junk.++ A short thread mounted whole publishes nothing and is admitted, which is what keeps a windowed+ arm scoreable at the small rungs. An arm that publishes an ordinal of 0 on every row is broken+ for a screen reader whether or not the thread happened to fit in the window, and mounting+ everything must not be a way to skip the check.+ """+ silent = _windowed_probe(+ mounted = 18,+ setsize = None,+ posinset_count = 0,+ posinset_distinct = 0,+ min_posinset = None,+ max_posinset = None,+ )+ conditions = evaluate(silent, silent, 18, MODE_WINDOWED)+ assert conditions["posinset_ordinals_valid"] is True+ assert conditions["posinset_reaches_end"] is True+ junk = _windowed_probe(+ mounted = 18,+ posinset_count = 18,+ posinset_distinct = 1,+ min_posinset = 0,+ max_posinset = 0,+ )+ conditions = evaluate(junk, junk, 18, MODE_WINDOWED)+ assert conditions["posinset_ordinals_valid"] is False+ assert conditions["posinset_reaches_end"] is False+++# ── the coverage verdict, without a browser ─────────────────────────+++def test_ordinal_coverage_never_reports_a_gap_in_the_gesture_as_data_loss():+ """NOT MEASURED and MISSING are different answers, and the difference is the whole probe.++ Same missing ordinals, same reached top, and the only thing that changes is whether the stops+ of the traversal overlapped each other. When they did not, the rows between two stops were+ never mounted by anybody and the probe has nothing to say about them.+ """+ coarse = {+ "reached_target": True,+ "ordinals_seen": [1, 2, 3, 16, 17, 18],+ "ordinals_in_window_holes": [],+ "sweep_continuous": False,+ "traversal_stops": 2,+ }+ got_coarse = ordinal_coverage(coarse, 18)+ assert got_coarse["ordinal_coverage_complete"] is None+ # And it is the kind of None that is NOT a pass: the ordinals apply to this arm and the sweep+ # did not inspect them. `not_applicable` -- the other None -- is an arm publishing no ordinals+ # at all, which is the case below in `test_ordinal_coverage_separates_...`.+ assert got_coarse["ordinal_coverage_state"] == COVERAGE_UNMEASURED+ continuous = dict(coarse, sweep_continuous = True)+ got = ordinal_coverage(continuous, 18)+ assert got["ordinal_coverage_complete"] is False+ assert got["ordinal_coverage_state"] == COVERAGE_INCOMPLETE+ assert got["ordinals_missing"] == list(range(4, 16))+ assert got["ordinals_missing_count"] == 12+++def test_ordinal_coverage_reports_a_hole_inside_one_mounted_window_whatever_the_step():+ """The reading that does not depend on how coarsely the thread was walked.++ A virtualizer mounts a contiguous run, so an ordinal missing from between the smallest and the+ largest mounted at a single stop was not skipped by the gesture. It is intersected with "never+ seen anywhere", so a row that was still materialising at one stop and mounted at the next is+ not reported as lost.+ """+ lost_middle = {+ "reached_target": True,+ "ordinals_seen": [1, 2, 3, 16, 17, 18],+ "ordinals_in_window_holes": list(range(4, 16)),+ "sweep_continuous": False,+ "traversal_stops": 2,+ }+ got = ordinal_coverage(lost_middle, 18)+ assert got["ordinal_coverage_complete"] is False+ assert "MIDDLE" in got["coverage_reason"]+ late = {+ "reached_target": True,+ "ordinals_seen": list(range(1, 19)),+ "ordinals_in_window_holes": [7, 8],+ "sweep_continuous": True,+ "traversal_stops": 9,+ }+ assert ordinal_coverage(late, 18)["ordinal_coverage_complete"] is True+++def test_ordinal_coverage_is_unmeasured_when_the_traversal_never_reached_the_top():+ """Even a completely covered union proves nothing if the gesture stopped short: the rows it+ did not reach are rows it did not look at."""+ stopped = {+ "reached_target": False,+ "ordinals_seen": list(range(1, 19)),+ "ordinals_in_window_holes": [],+ "sweep_continuous": True,+ "traversal_stops": 3,+ }+ got = ordinal_coverage(stopped, 18)+ assert got["ordinal_coverage_complete"] is None+ assert got["ordinal_coverage_state"] == COVERAGE_UNMEASURED+ assert "never looked for" in got["coverage_reason"]+++def test_ordinal_coverage_separates_a_question_that_does_not_apply_from_one_it_could_not_answer():+ """THE TWO KINDS OF `None`, side by side, on traversals that differ in one thing.++ Both sweeps reached the top and both are too coarse to overlap. One is walking an arm that+ publishes ordinals and cannot say what happened to twelve of them; the other is walking an arm+ that publishes none at all, which is the shipped build, where there is nothing to say. The+ `thread_complete` gate refuses to score the first and passes the second, so a single `None`+ covering both is a gate that has to choose which mistake to make.+ """+ walked = {+ "reached_target": True,+ "ordinals_in_window_holes": [],+ "sweep_continuous": False,+ "traversal_stops": 2,+ }+ applies = ordinal_coverage(dict(walked, ordinals_seen = [1, 2, 3, 16, 17, 18]), 18)+ does_not = ordinal_coverage(dict(walked, ordinals_seen = []), 18)+ assert applies["ordinal_coverage_complete"] is does_not["ordinal_coverage_complete"] is None+ assert applies["ordinal_coverage_state"] == COVERAGE_UNMEASURED+ assert does_not["ordinal_coverage_state"] == COVERAGE_NOT_APPLICABLE+++def test_evaluate_cannot_settle_on_a_single_sample():+ """One reading is a snapshot, and a snapshot of a growing thread looks exactly like a settled+ one. The first sample can never report settled, whatever it contains."""+ probe = {"probe_attempted": True, "mounted": 18, "elements": 100, "scroll_height": 10}+ assert evaluate(probe, None, 18, MODE_FULL)["settled"] is False+ assert evaluate(probe, probe, 18, MODE_FULL)["settled"] is True+ grew = dict(probe, elements = 101)+ assert evaluate(grew, probe, 18, MODE_FULL)["settled"] is False+++# ── the viewport itself, asserted rather than inferred ────────────────────────+++def test_a_windowed_thread_with_no_viewport_is_refused(browser):+ """REGRESSION. Every other windowed condition degrades to a pass when the scroller is gone.++ `from_bottom` is null so the arithmetic is skipped, and the app's own answer is read off+ `.aui-thread-scroll-to-bottom`, which is a DESCENDANT of the viewport but is looked up at+ DOCUMENT scope. Renaming the viewport class therefore leaves that control reachable,+ `app_says_at_bottom` true and `anchored_at_end` true, and the cell was admitted with no+ viewport at all: the completeness probe then returns `probe_attempted: false`, the scroll+ actions return `not_run`, a not-run action blanks only its own timings, and the census viewport+ fields go null. Nothing refused, so the film was scored without the surface it was measuring.+ """+ page = _page(browser, "windowed")+ got, log = _lines()+ try:+ renamed = page.evaluate(+ """() => {+ const vp = document.querySelector(".aui-thread-viewport");+ if (!vp) return false;+ vp.classList.remove("aui-thread-viewport");+ vp.classList.add("aui-thread-scroller");+ return true;+ }"""+ )+ assert renamed, "the fixture has no viewport to rename"+ with pytest.raises(ThreadNotReady) as caught:+ wait_for_thread_ready(+ page,+ MESSAGES,+ marker = turn_marker(TURNS - 1, TURNS - 1),+ mode = MODE_WINDOWED,+ timeout_s = 3,+ log = log,+ )+ finally:+ page.close()++ # Named in the refusal, so the reader is told the surface is missing rather than left to infer+ # it from a condition that is really about something else.+ assert "viewport_present" in str(caught.value), str(caught.value)diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_drain.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_drain.pyindex ccc4fe90a9d..e8eaa73cf67 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_drain.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_drain.py@@ -197,9 +197,22 @@ class _SceneRunner:def _seed(plan):- """What `Seeder.seed` hands back. Zero messages, so the thread wait is the empty-page one."""+ """What `Seeder.seed` hands back. Zero messages, so the thread wait is the empty-page one.- return types.SimpleNamespace(thread_id = "t1", seconds = 0.5, messages = 0)+ The two markers are `None` for the same reason `messages` is 0: the readiness gate takes the+ empty-page path here, and a marker it never asserts on must not be invented. They are PRESENT+ rather than absent because `SeededThread` declares them and `_wait_for_thread` reads+ `last_marker` unconditionally; a stub without them fails on the attribute instead of on the+ behaviour these tests are about.+ """++ return types.SimpleNamespace(+ thread_id = "t1",+ seconds = 0.5,+ messages = 0,+ first_marker = None,+ last_marker = None,+ )@pytest.fixturediff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_stats.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_stats.pyindex b216fec78cd..0945f4b0418 100644--- a/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_stats.py+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_stats.py@@ -390,7 +390,16 @@ def cell_runner(monkeypatch, tmp_path):session = session,pacer = _RecordedPacer(streams),seeder = types.SimpleNamespace(- seed = lambda plan: types.SimpleNamespace(thread_id = "t1", seconds = 0.5, messages = 0),+ seed = lambda plan: types.SimpleNamespace(+ thread_id = "t1",+ seconds = 0.5,+ messages = 0,+ # Both markers `SeededThread` declares, present and None: the readiness gate+ # reads `last_marker` unconditionally, so a stub that omits it fails on the+ # attribute rather than on the stream accounting these tests are about.+ first_marker = None,+ last_marker = None,+ ),auth = None,),corpus = None,@@ -678,6 +687,13 @@ class _WirePage:return self.runningif "messageCount" in expr:return self.messages+ # THE THREAD'S LENGTH AS WELL AS THE MOUNTED COUNT. `send_turn` proves a send worked by+ # `threadTotal()` growing, not `messageCount()`, so that a windowed arm whose window slides+ # is not read as a send that did nothing. This page models a fully mounted arm, where the+ # two are the same number; without the second name the shipped action sees 0 both sides and+ # every follow-up reports that it never started a reply.+ if "threadTotal" in expr:+ return self.messagesif "assistantChars" in expr:return CENSUS["assistant_chars"]return 0@@ -756,7 +772,16 @@ def test_a_healthy_multi_turn_cell_passes_the_check_over_real_wire_bytes(monkeypsession = Session(ctx = ctx),pacer = pacer,seeder = types.SimpleNamespace(- seed = lambda plan: types.SimpleNamespace(thread_id = "t1", seconds = 0.5, messages = 0),+ seed = lambda plan: types.SimpleNamespace(+ thread_id = "t1",+ seconds = 0.5,+ messages = 0,+ # Both markers `SeededThread` declares, present and None: the readiness gate+ # reads `last_marker` unconditionally, so a stub that omits it fails on the+ # attribute rather than on the stream accounting these tests are about.+ first_marker = None,+ last_marker = None,+ ),auth = None,),corpus = None,diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_windowed_arm_names.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_windowed_arm_names.pynew file mode 100644index 00000000000..f72ef830f03--- /dev/null+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_windowed_arm_names.py@@ -0,0 +1,95 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A MISTYPED FLAG MUST NOT COST A BROWSER AND TWO STUDIO SERVERS.++`--windowed-arm` names the arm that is allowed the windowed readiness gate, and the name is checked+against the arms the run actually has. That check used to happen after both Studio installs had+been launched, the pacer bound and the browser opened, and the `SystemExit` it raises for+`--windowed-arm treatments` was raised from a place with no cleanup around it: the `finally` that+calls `bundle.close()`, `pacer.stop()`, `stop_studio()` and cancels the watchdog does not begin+until the cell loop far below. So the typo exited the process and left the heavy children running,+holding their ports.++It is a pure argument check -- it needs nothing that has been launched -- so it now runs before any+of it. These tests pin both halves: the check itself, and the fact that it happens FIRST.++ python -m pytest tests/studio/studiobench/runtime/selftest/test_studiobench_windowed_arm_names.py -q+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++_STUDIO_TESTS = Path(__file__).resolve().parents[3]+if str(_STUDIO_TESTS) not in sys.path:+ sys.path.insert(0, str(_STUDIO_TESTS))++from studiobench import __main__ as M # noqa: E402+++# ── the check itself ────────────────────────────────────────────────+++def test_the_arms_of_the_run_are_accepted():+ assert M._windowed_arms("treatment", ["base", "treatment"]) == {"treatment"}+ assert M._windowed_arms(" base , treatment ", ["base", "treatment"]) == {"base", "treatment"}+++def test_nothing_named_is_nothing_gated():+ assert M._windowed_arms("", ["base"]) == set()+ assert M._windowed_arms(None, ["base"]) == set()+++def test_a_typo_is_refused_and_says_which_arms_exist():+ with pytest.raises(SystemExit) as raised:+ M._windowed_arms("treatments", ["base", "treatment"])+ assert "['treatments']" in str(raised.value)+ assert "['base', 'treatment']" in str(raised.value)+++def test_naming_the_treatment_arm_of_a_run_that_has_no_treatment_is_refused():+ """Without `--ab` there is one arm. Naming the other one is not a harmless no-op: the caller+ believes a gate is in force that nothing in the run will ever apply."""+ with pytest.raises(SystemExit):+ M._windowed_arms("treatment", ["base"])+++# ── and it happens before anything is started ───────────────────────+++def test_a_bad_arm_name_is_refused_before_any_process_is_started(monkeypatch):+ """THE DEFECT. Every entry point that starts something is trapped here, so if the refusal moves+ back below any of them this fails with the trap's own error instead of the SystemExit.++ The watchdog is the first of them in `run`, then the Studio install or the health check on an+ attached one, then the pacer, then the browser. None of them is reached.+ """+ from studiobench import pacer as pacer_mod+ from studiobench.runtime import browser as browser_mod+ from studiobench.runtime import lifecycle++ started: list = []++ def _trap(name):+ def _boom(*_a, **_kw):+ started.append(name)+ raise AssertionError(f"{name} ran before the arm names were checked")++ return _boom++ monkeypatch.setattr(browser_mod, "install_wall_clock_watchdog", _trap("the watchdog"))+ monkeypatch.setattr(browser_mod, "launch", _trap("the browser"))+ monkeypatch.setattr(lifecycle, "install_studio", _trap("the Studio install"))+ monkeypatch.setattr(lifecycle, "launch_studio", _trap("the Studio launch"))+ monkeypatch.setattr(lifecycle, "wait_for_healthz", _trap("the health check"))+ monkeypatch.setattr(pacer_mod, "Pacer", _trap("the pacer"))++ with pytest.raises(SystemExit) as raised:+ M.main(["--windowed-arm", "treatments", "--attach", "http://127.0.0.1:1"])++ assert "--windowed-arm names ['treatments']" in str(raised.value), str(raised.value)+ assert started == [], starteddiff --git a/tests/studio/studiobench/runtime/selftest/thread_fixture.js b/tests/studio/studiobench/runtime/selftest/thread_fixture.jsnew file mode 100644index 00000000000..dc0e781dd5c--- /dev/null+++ b/tests/studio/studiobench/runtime/selftest/thread_fixture.js@@ -0,0 +1,272 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+//+// A SYNTHETIC THREAD, with a switch on how it mounts.+//+// This exists so the readiness gate can be shown PASSING on a correctly virtualised thread and+// FAILING on a broken one, in a real browser, against the real `scene/dom.js` adapter and the real+// `runtime/readiness.py` probe. A gate that has only ever been shown passing is not a gate, and+// neither is one that has only ever been shown against a mock of itself.+//+// It reproduces exactly the contract the shipping app publishes and the readiness gate reads --+// `.aui-thread-root`, `.aui-thread-viewport`, `[data-role]`, `.aui-thread-scroll-to-bottom` with+// its `invisible` toggle, the composer textarea -- and nothing else. It is not a replica of Studio+// and must never be mistaken for one: it cannot tell you anything about the app's own timing. What+// it can do is put the gate in front of each of the situations it has to tell apart.++(() => {+ const MODES = [+ // Everything mounted, the way the app ships today.+ "full",+ // Mounting is still in progress: the first K messages, growing. This is the state the gate+ // exists to refuse, and the state the old count-based gate DID correctly refuse.+ "mounting",+ // A correct window: the tail of the thread, aria-setsize/aria-posinset published, anchored at+ // the bottom, and the head materialises when you scroll to the top.+ "windowed",+ // A window with no aria-setsize. Nothing outside the app can learn how long this thread is.+ "windowed_no_total",+ // A window over the HEAD of the thread rather than its end: settled, correct total, but the+ // last message is nowhere.+ "windowed_at_top",+ // A window at the end, correct total published, and a store that only holds what is mounted.+ // Indistinguishable from `windowed` while you stand at the bottom of the thread, which is why+ // the completeness probe has to walk to the top.+ "windowed_lost_head",+ // A store that kept the first page AND the last page and lost the middle. The head marker+ // arrives when you scroll to the top, so the marker check alone calls it complete; the+ // ordinals of one mounted window run 1,2,3 then 16,17,18, which is the loss.+ "windowed_lost_middle",+ // The same correct window, but with the ordinals written directly on the [data-role] element+ // instead of on a row wrapper. Both placements must be accepted.+ "windowed_flat",+ // THE THREE MALFORMED ORDINAL CONTRACTS. Each publishes aria-posinset on every mounted row --+ // enough for a gate that only counts attributes -- and each publishes numbers that are not+ // positions in the thread, so nothing outside the app can locate the mounted window.+ //+ // Every row says 0. The attribute is there and it is out of range: aria-posinset is 1-based.+ "windowed_zero_ordinals",+ // Every row says the same number, so six mounted rows claim one position between them.+ "windowed_duplicate_ordinals",+ // A window at the BOTTOM of an 18-message thread numbered 1..6: the index within the window+ // published as though it were the position in the thread. The most likely of the three to be+ // written by accident, and the one that makes a window at the end look like a window at the+ // start.+ "windowed_from_one",+ ];++ function marker(i) {+ // Must match runtime/seeder.turn_marker exactly.+ return "studiobench turn " + i + ": continue with unit " + i;+ }++ window.__fixture = {+ MODES,+ marker,++ build(opts) {+ const mode = opts.mode;+ const turns = opts.turns; // user/assistant pairs+ const windowSize = opts.windowSize || 6;+ const total = turns * 2;+ document.body.innerHTML = "";++ const root = document.createElement("div");+ root.className = "aui-root aui-thread-root";+ const viewport = document.createElement("div");+ viewport.className = "aui-thread-viewport aui-stream-viewport";+ viewport.style.cssText = "height:400px;overflow-y:auto;position:relative;";+ root.appendChild(viewport);++ const topSpacer = document.createElement("div");+ const list = document.createElement("div");+ const bottomSpacer = document.createElement("div");+ topSpacer.setAttribute("aria-hidden", "true");+ bottomSpacer.setAttribute("aria-hidden", "true");+ viewport.appendChild(topSpacer);+ viewport.appendChild(list);+ viewport.appendChild(bottomSpacer);++ const jump = document.createElement("button");+ jump.className = "aui-thread-scroll-to-bottom";+ root.appendChild(jump);++ const composer = document.createElement("textarea");+ composer.setAttribute("aria-label", "Message input");+ root.appendChild(composer);+ document.body.appendChild(root);++ // Every message the "store" holds. `windowed_lost_head` throws most of them away, which is+ // the data loss the completeness probe is looking for.+ const ROW_PX = 120;+ let store = [];+ for (let i = 0; i < turns; i += 1) {+ store.push({ role: "user", text: marker(i), pos: i * 2 + 1 });+ store.push({ role: "assistant", text: "reply to turn " + i + " ".repeat(200), pos: i * 2 + 2 });+ }+ const declaredTotal = total;+ if (mode === "windowed_lost_head") store = store.slice(-windowSize);+ // THE HEAD AND THE TAIL, AND NOTHING BETWEEN THEM. Half a window at each end, so the store+ // is exactly one window long and every scroll position mounts all of it: the first message+ // is always there for the marker check, and the hole is always there for the ordinals.+ if (mode === "windowed_lost_middle") {+ const keep = Math.max(1, Math.floor(windowSize / 2));+ store = store.slice(0, keep).concat(store.slice(-keep));+ }++ const state = { mode, store, declaredTotal, windowSize, ROW_PX, total };++ // WHAT EACH ROW PUBLISHES AS ITS POSITION. Everything but the three malformed modes+ // publishes the message's real position in the thread, which is what aria-posinset means.+ // The malformed ones publish a number that is not one, each in a different way, so the gate+ // can be shown refusing each of them separately rather than refusing "something about the+ // ordinals".+ function publishedPos(message, indexInWindow) {+ if (mode === "windowed_zero_ordinals") return 0;+ if (mode === "windowed_duplicate_ordinals") return state.declaredTotal;+ if (mode === "windowed_from_one") return indexInWindow + 1;+ return message.pos;+ }++ function render(startIndex, count, publishTotals) {+ list.innerHTML = "";+ const slice = state.store.slice(startIndex, startIndex + count);+ for (let i = 0; i < slice.length; i += 1) {+ const m = slice[i];+ const pos = publishedPos(m, i);+ const el = document.createElement("div");+ el.setAttribute("data-role", m.role);+ el.style.cssText = "height:" + ROW_PX + "px;overflow:hidden;";+ el.textContent = m.text;+ // WHERE THE SHIPPING VIRTUALIZER PUTS THE ORDINALS: on the positioned row wrapper, not+ // on the message. `thread-message-virtualizer.tsx` renders an absolutely positioned div+ // per item and mounts `ThreadPrimitive.MessageByIndex` inside it, so the element that is+ // a member of the set is the wrapper. `wrapped` reproduces that shape exactly; the+ // unwrapped placement is kept too, because the gate must accept both.+ if (publishTotals && mode !== "windowed_flat") {+ const row = document.createElement("div");+ row.setAttribute("aria-setsize", String(state.declaredTotal));+ row.setAttribute("aria-posinset", String(pos));+ row.appendChild(el);+ list.appendChild(row);+ continue;+ }+ if (publishTotals) {+ el.setAttribute("aria-setsize", String(state.declaredTotal));+ el.setAttribute("aria-posinset", String(pos));+ }+ list.appendChild(el);+ }+ // Spacers, so the scroll extent describes the WHOLE thread even though only a window is+ // mounted. A virtualizer that omits these has a scrollbar that lies, which is one of the+ // behavioural invariants in analysis/behaviour.py.+ const above = mode === "full" || mode === "mounting" ? 0 : startIndex * ROW_PX;+ const below =+ mode === "full" || mode === "mounting"+ ? 0+ : Math.max(0, (state.declaredTotal - startIndex - slice.length) * ROW_PX);+ topSpacer.style.height = above + "px";+ bottomSpacer.style.height = below + "px";+ }++ function pin() {+ viewport.scrollTop = viewport.scrollHeight;+ jump.classList.add("invisible");+ }++ state.renderWindowAround = (scrollTop) => {+ // A store SHORTER than the thread it claims cannot be indexed by the thread's own+ // indices: `windowed_lost_middle` holds one window's worth of messages for an+ // eighteen-message thread, so every scroll position mounts the same rows and the ordinals+ // on them are the only thing that says which messages they are.+ if (mode === "windowed_lost_middle") {+ const start = Math.max(+ 0,+ Math.min(state.store.length - windowSize, Math.floor(scrollTop / ROW_PX)),+ );+ render(start, windowSize, true);+ return;+ }+ const first = Math.max(+ 0,+ Math.min(state.declaredTotal - windowSize, Math.floor(scrollTop / ROW_PX)),+ );+ // `windowed_lost_head` only has the tail in its store, so an index into the full thread+ // has to be translated. It will simply have nothing to show near the top.+ const offset = mode === "windowed_lost_head" ? state.declaredTotal - state.store.length : 0;+ render(Math.max(0, first - offset), windowSize, true);+ };++ if (mode === "full") {+ render(0, state.store.length, false);+ pin();+ } else if (mode === "mounting") {+ // GROWING. One message every 250ms, from the head, and it never finishes inside the+ // window any test here gives it. The count climbs, the element count climbs, the scroll+ // height climbs, and the last message is never reached.+ let n = 1;+ render(0, n, false);+ pin();+ state.timer = setInterval(() => {+ n += 1;+ if (n > state.store.length) { clearInterval(state.timer); return; }+ render(0, n, false);+ pin();+ }, 250);+ } else if (mode === "windowed_at_top") {+ render(0, windowSize, true);+ viewport.scrollTop = 0;+ jump.classList.remove("invisible");+ } else if (mode === "windowed_no_total") {+ render(state.store.length - windowSize, windowSize, false);+ pin();+ } else {+ // windowed, windowed_flat, windowed_lost_head, windowed_lost_middle and the three+ // malformed-ordinal modes: all of them are a window at the END of the thread, and they+ // differ only in what they publish about it.+ render(Math.max(0, state.store.length - windowSize), windowSize, true);+ pin();+ viewport.addEventListener("scroll", () => {+ state.renderWindowAround(viewport.scrollTop);+ jump.classList.toggle(+ "invisible",+ viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop < 8,+ );+ });+ }+ // COPY-FROM-STORE, the shipping fix, reproduced on the same contract.+ //+ // Mirrors `decideThreadCopy` in+ // studio/frontend/src/components/assistant-ui/thread-copy-from-store.ts: intervene only when+ // the selection spans the whole mounted list AND the store holds more than is mounted. The+ // unit tests over there stub `containsNode`; this is the only place the REAL Selection+ // semantics are exercised, which is the part that could actually be wrong.+ if (opts.copyFromStore) {+ viewport.addEventListener("copy", (event) => {+ const selection = window.getSelection();+ const nodes = Array.from(viewport.querySelectorAll("[aria-posinset]"));+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) return;+ if (nodes.length === 0 || state.store.length <= nodes.length) return;+ const first = nodes[0];+ const last = nodes[nodes.length - 1];+ if (!selection.containsNode(first, true) || !selection.containsNode(last, true)) return;+ const text = state.store.map((m) => "## " + m.role + "\n\n" + m.text).join("\n\n");+ event.clipboardData.setData("text/plain", text);+ event.preventDefault();+ });+ }++ window.__fixtureState = state;+ return { mode, total, mounted: list.children.length };+ },+ };++ // The two-rAF paint promise the real harness installs from instruments/frames.js. The+ // completeness probe awaits it.+ if (!window.__sbNextPaint) {+ window.__sbNextPaint = () =>+ new Promise((resolve) =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve(performance.now()))),+ );+ }+})();diff --git a/tests/studio/studiobench/runtime/session.py b/tests/studio/studiobench/runtime/session.pyindex efb0d06bfe1..a2286f49757 100644--- a/tests/studio/studiobench/runtime/session.py+++ b/tests/studio/studiobench/runtime/session.py@@ -28,6 +28,7 @@ import timeimport tracebackfrom dataclasses import dataclass, fieldfrom pathlib import Path+from collections.abc import Mappingfrom typing import Any, Callable, Optionalfrom ..fixture.corpus import PROVISIONAL_CHARS_PER_TOKEN, Corpus, RungPlan, plan_rung@@ -39,7 +40,17 @@ from ..scene.actions import paint_floor_msfrom ..scene.schedule import SceneRunnerfrom .browser import cdp_counters, cdp_metrics, dump_diagnosticsfrom .lifecycle import StudioAuth-from .seeder import Seeder, compare_signatures, dom_signature, measure_chars_per_token+from .readiness import (+ COVERAGE_STATES_SCOREABLE,+ MODE_FULL,+ MODE_WINDOWED,+ MODES,+ Readiness,+ ThreadNotReady,+ probe_thread_completeness,+ wait_for_thread_ready,+)+from .seeder import Seeder, SeededThread, compare_signatures, dom_signature, measure_chars_per_tokenfrom .types import BenchContext, Cell, Paths, Recorder, Window, make_cell_id, new_session_id# A 1x1 PNG, written to disk once per run so the image-upload action has a real file to attach.@@ -68,6 +79,113 @@ IDLE_CALIBRATION_MS = 1500EQUIVALENCE_RUNG = "10K"MOUNT_TIMEOUT_S = 180+#: How much of the streaming phase the thread must stay pinned for `follows_the_stream` to pass.+#: 0.95 rather than 1.0: the sampler ticks four times a second and a legitimate pin lands a tick+#: or two late after a large append, which is a rendering delay and not a failure to follow. It is+#: paired with `ever_fell_behind`, which is absolute -- a thread that drifted past the tolerance+#: even once fails, however quickly it was yanked back, because being yanked back is itself the+#: other half of the intent contract being broken.+FOLLOW_PINNED_MIN = 0.95++#: How much of the STREAMING TIME the attached phases must cover before `pinned_fraction` is+#: allowed to stand as a verdict.+#:+#: `pinned_fraction` is computed over attached samples only. With `detached` latching on the first+#: deliberate scroll and never clearing, the shipped film -- which scrolls 1.5s into an 18s opening+#: stream and then streams twice more -- produced a verdict from the first ~3s: 11 attached samples+#: against 72 detached, 13% coverage, reported as 100% pinned and read as "the thread follows the+#: stream". The latch is fixed, and this makes the coverage a condition rather than a footnote, so+#: a future regression that strands the sampler cannot produce a confident pass over a sliver.+FOLLOW_MIN_STREAM_COVERAGE = 0.50+++def follow_verdict(follow: Mapping[str, Any]) -> tuple[bool, dict[str, Any]]:+ """The `follows_the_stream` verdict, and the coverage fields recorded whatever it says.++ A module-level function rather than four lines inside the cell runner because the SPLIT it+ encodes is the whole point and has to be testable without a browser: which shortfalls are a+ reading of the BUILD and which are a property of the FILM.++ FATAL, because they describe how the arm behaved while it was attached and can genuinely+ differ between two builds:++ `pinned_fraction` below `FOLLOW_PINNED_MIN`, or absent while the sampler was present+ `ever_fell_behind` absolute; one drift past tolerance is a failure however fast the recovery++ NOT MEASURED, because it is set by the SCENE SCHEDULE and not by the build under test:++ `attached_fraction_of_stream` below `FOLLOW_MIN_STREAM_COVERAGE`, AND ONLY WHEN THE ARM+ re-attached at least once, so the shortfall is the schedule's+ and not this build's refusal to come back++ The film scrolls away twice inside an ~18s opening stream and the app then correctly declines+ to yank the reader back, so roughly half the streaming time is detached BY CONSTRUCTION.+ Measured over 32 cells it is 0.481 +/- 0.009, range 0.4625 to 0.5063 -- so a floor of 0.50 sat+ above the mean of the quantity it was gating and made the verdict a coin flip. It refused 32 of+ 32 pairs with `TOO LITTLE COMPARED`, exit 3, and the NULL CONTROL -- the same commit on both+ arms -- refused identically. A gate that fails its own null is not measuring what it names. It+ was blinding the null audit too, which could not establish its own noise floor: all 16 actions+ came back `undetermined`.++ Both arms run the same film, so the shortfall is symmetric by construction. It cannot+ discriminate between them; it can only void the run. It still qualifies an ABSOLUTE quote -- a+ thread that spent half the stream detached did render less -- which is why the coverage is+ RECORDED AS A NUMBER rather than dropped, and why this stays a failed gate row a reader has to+ step over. What it may no longer do is take the cell out of a COMPARISON, where the confound is+ common to both sides and cancels. Raising the constant instead would be the same trap one turn+ later: it would need re-deriving every time the film's scroll schedule moves.++ `pinned_ok and not fell_behind` in the `stream_coverage_unmeasured` conjunction is+ LOAD-BEARING. Without it a genuine follow failure on a large rung, where coverage is low+ anyway, would ride out on this allowance -- the same defect in the opposite direction.+ """++ pinned = follow.get("pinned_fraction")+ coverage = follow.get("attached_fraction_of_stream")+ pinned_ok = pinned is not None and pinned >= FOLLOW_PINNED_MIN+ fell_behind = bool(follow.get("ever_fell_behind"))+ coverage_short = coverage is None or coverage < FOLLOW_MIN_STREAM_COVERAGE+ # THE DETACHMENT HAS TO BE THE SCHEDULE'S, AND ONLY A RE-ATTACHMENT PROVES THAT IT WAS.+ #+ # The waiver's whole justification is that `attached_fraction_of_stream` is set by the film and+ # is therefore identical on both arms. Half of it is: the harness scrolls away on a fixed+ # schedule. The other half is the BUILD'S -- `scene/dom.js` clears `detached` only when a run+ # that began after the gesture is observed at the bottom, so an arm that stops re-pinning when+ # the user submits a new turn never re-attaches and every remaining sample lands in the+ # detached branch. That branch `return`s before the pinned and fell-behind accounting, so the+ # opening stream's `pinned_fraction: 1.0` and `ever_fell_behind: False` survive untouched while+ # coverage collapses -- exactly the shape this conjunction was about to waive, on the one+ # failure the gate exists to catch. A reply that leaves the viewport is unmounted and stops+ # costing anything to paint, so the cell is CHEAPER for the defect, and `readings_by_arm` would+ # have admitted it to the ratios against a healthy partner.+ #+ # `reattachments` is the sampler's own record of the app coming back, and it is >= 1 on every+ # cell the carve-out was derived from: the measured 0.481 coverage is unreachable without one,+ # since `detached` latches 1.5s into an 18s stream and only a re-attachment resumes counting+ # attached samples. Absent (an old payload, or a sampler that never ran) is not evidence of a+ # re-attachment, and the absent-instrument case is already waived by `follow_attempted`.+ reattached = bool(follow.get("reattachments"))+ # THE COVERAGE AS A NUMBER, WHATEVER THE VERDICT, next to the floor it is read against. It was+ # only ever visible as a pass or a fail, and that is why it took a campaign to notice the floor+ # sat above the film's ceiling: every reader saw "FAILED its stream-follow gate", nobody saw+ # 0.481. A quantity that decides whether a run is quotable has to be legible as a quantity.+ recorded: dict[str, Any] = {+ "stream_coverage": coverage,+ "stream_coverage_floor": FOLLOW_MIN_STREAM_COVERAGE,+ "stream_coverage_unmeasured": bool(+ coverage_short and pinned_ok and not fell_behind and reattached+ ),+ }+ if coverage_short:+ recorded["stream_coverage_reason"] = (+ "the thread was attached for "+ + ("an unknown share" if coverage is None else f"{coverage:.1%}")+ + f" of the streaming time, under the {FOLLOW_MIN_STREAM_COVERAGE:.0%} floor; "+ "the follow verdict is NOT MEASURED for this cell, not failed"+ )+ return bool(pinned_ok and not coverage_short and not fell_behind), recorded++# How long the composer may take to accept the click that starts the film. Not a performance# budget: the point is that the cell survives and the number gets recorded. See `_press_send`.# 90s because it has to be well clear of the worst real reading and still bounded, since a click@@ -82,6 +200,58 @@ class WindowInUse(RuntimeError):pass+def record_completeness_gate(recorder: Recorder, cell: Cell, completeness: dict) -> bool:+ """Write the completeness verdict as a gate row AGAINST THE CELL THAT PRODUCED IT.++ WHY THIS IS NOT `recorder.gate(...)`. `Recorder.gate` writes `{row_type, name, passed,+ detail}` and no cell_id, and `report/payload.py::excluded_from_rows` reads a failed gate as+ `row.get("cell_id") or "run"`. So a windowed cell that had really lost messages was excluded+ under the synthetic cell id "run": the report could say a self-check failed somewhere in the+ run and could not say which arm or which rung lost them, which is the one thing this probe+ exists to find out. `cell_id` is `r{rung}.{arm}.rep{rep}`, so attributing the row names all+ three. `Recorder.failure` already takes a cell_id for the same reason.++ THE VERDICT ITSELF is the head marker AND the ordinal coverage, and coverage is three-valued.+ `False` is a finding. `None` is two different answers wearing one value, and they are told+ apart by `ordinal_coverage_state`:++ not_applicable no row published an `aria-posinset` for the traversal to count. A fully+ mounted arm publishes none anywhere -- the shipped build publishes none --+ so the question does not arise, and failing on it would fail the shipped+ build's own completeness gate on every cell.+ unmeasured the question arises and the sweep could not answer it: the gesture stopped+ short of the top, or its consecutive stops did not overlap so the middle of+ the thread was never in view.++ Only the first is a pass. A store that retains the first page and the last one and has lost+ everything between them is the exact arm this probe was written to catch, and accepting+ `unmeasured` let it back in through the unknown state: the head marker arrives, the coverage+ sweep never looks, and the cell stays scoreable. "We could not tell" must not be recorded as+ "it was fine". The remedy for a coarse sweep is a smaller `step_px`, not a pass.++ A completeness dict carrying no state at all is treated the same way as `unmeasured`, because+ an undifferentiated `None` is precisely the ambiguity above and resolving it in favour of a+ pass is the defect.+ """+ coverage = completeness.get("ordinal_coverage_complete")+ state = completeness.get("ordinal_coverage_state")+ passed = (+ bool(completeness.get("head_reached"))+ and coverage is not False+ and state in COVERAGE_STATES_SCOREABLE+ )+ recorder.emit(+ {+ "row_type": "gate",+ "name": "thread_complete",+ "passed": passed,+ "detail": completeness,+ "cell_id": cell.cell_id,+ }+ )+ return passed++@dataclassclass Session:ctx: BenchContext@@ -190,6 +360,20 @@ class CellRunner:# of seconds at small rungs and a great deal at large ones, and it makes the cell's timings# incomparable with a cell that did not run it. See `_click_attribution`.click_probe: bool = False+ # WHICH READINESS GATE. `full` is the default and is what every normal arm runs: every seeded+ # message must be mounted, plus the settle and end-present conditions the gate gained. An arm+ # that mounts a WINDOW on purpose sets `windowed` and is then held to a different set of+ # conditions, none of them weaker. See runtime/readiness.py.+ #+ # It is a per-TARGET setting, so a base-versus-virtualised A/B runs the base arm on `full` and+ # only the treatment arm on `windowed`, and the base arm keeps the strict gate it always had.+ readiness_mode: str = MODE_FULL+ # Scroll a windowed thread to its top once per cell, before the measured window, to prove the+ # arm still holds the head of the conversation. Costs a full traversal, so it is off for+ # `full` (where the whole thread is mounted and there is nothing to prove) and on by default+ # for `windowed`, where it is the only check that separates a virtualised thread from one that+ # has lost most of its messages.+ completeness_probe: Optional[bool] = Nonedef run(self, cell: Cell, plan: RungPlan) -> dict:s = self.session@@ -227,6 +411,19 @@ class CellRunner:"message": str(exc),"traceback": traceback.format_exc()[-3000:],}+ if isinstance(exc, ThreadNotReady):+ # WHICH CONDITION, not just that it timed out. The old gate's message was "the+ # thread mounted 9 of 18 messages", which named a count and left the reader to+ # guess whether the app was slow, the thread was short or the arm mounts a window+ # on purpose. The verdict now carries every condition and the last probe reading.+ row["failure"]["readiness"] = exc.detail+ row["readiness"] = exc.detail+ rec.gate(+ f"thread_ready:{self.readiness_mode}",+ False,+ exc.detail,+ cell_id = cell.cell_id,+ )self.log(f" cell FAILED: {type(exc).__name__}: {exc}")rec.failure(cell.cell_id, type(exc).__name__, {"message": str(exc)})with contextlib.suppress(Exception):@@ -266,7 +463,39 @@ class CellRunner:wait_until = "domcontentloaded",timeout = 120_000,)- self._wait_for_thread(page, seeded.messages)+ if self.readiness_mode not in MODES:+ raise ValueError(f"unknown readiness mode {self.readiness_mode!r}")+ readiness = self._wait_for_thread(page, seeded)+ row["readiness"] = readiness.as_dict()+ # RECORDED AS A GATE, so no reader can pick up a windowed cell's frame rate without also+ # seeing that its readiness was established a different way.+ rec.gate(+ f"thread_ready:{self.readiness_mode}",+ True,+ readiness.as_dict(),+ cell_id = cell.cell_id,+ )++ # THE COMPLETENESS PROBE, before the idle window and therefore before anything is measured.+ # It scrolls the whole thread, which mounts rows and dirties the page, so it has to be+ # followed by the idle window rather than preceding a measurement directly.+ do_probe = (+ self.completeness_probe+ if self.completeness_probe is not None+ else self.readiness_mode == MODE_WINDOWED+ )+ if do_probe and seeded.first_marker and seeded.messages > 0:+ completeness = probe_thread_completeness(+ page,+ first_marker = seeded.first_marker,+ expected_messages = seeded.messages,+ log = self.log,+ )+ row["completeness"] = completeness+ record_completeness_gate(rec, cell, completeness)+ # Back to the resting state the gate described, or the idle calibration below runs+ # against a page that is still settling from the traversal.+ self._wait_for_thread(page, seeded)# ── the enforced idle window ────────────────────────────────frames = next((i for i in s.instruments if i.name == "frames"), None)@@ -283,12 +512,12 @@ class CellRunner:# so without it busy_pct is null with the reason attached and every other column# stands.self.log(f" timer clamp NOT established: {clamp.get('reason')}")- rec.gate("timer_clamp", False, clamp)+ rec.gate("timer_clamp", False, clamp, cell_id = cell.cell_id)else:self.log(f" timer clamp {clamp['clampMs']:.2f}ms " f"over {clamp.get('samples')} idle ticks")- rec.gate("timer_clamp", True, clamp)+ rec.gate("timer_clamp", True, clamp, cell_id = cell.cell_id)row["paint_floor_ms"] = paint_floor_ms(page)row["census_before"] = dom_signature(page)@@ -335,6 +564,16 @@ class CellRunner:f"content chars, cadence {self.cadence}, {expected_ms / 1000:.0f}s expected")+ # RESET THE FOLLOW SAMPLER FOR THIS CELL, immediately before the film starts.+ #+ # Necessary because the counters were just made to survive a navigation, by persisting to+ # sessionStorage -- and a cell boundary IS a navigation, to the next seeded thread on the+ # same origin. Without this, cell 2 reports cell 1's samples plus its own, cell 3 reports+ # all three, and a single bad cell early in a session poisons every reading after it while+ # each one still looks like a per-cell number.+ with contextlib.suppress(Exception):+ page.evaluate("() => window.__sb.follow && window.__sb.follow.reset()")+before_metrics = cdp_metrics(s.ctx.cdp)self._composer_click_ms = None# `click_attribution` is NOT filed here. It is filed in `run`'s `finally`, because a cell@@ -387,6 +626,74 @@ class CellRunner:drained = self._drain_stream(page, expected_ms)w.note("drained", drained)row["stream"] = drained+ # DID THE THREAD FOLLOW THE STREAM? Read once, here, after the last window of the film has+ # closed, so the reading is charged to nothing. See the sampler in scene/dom.js.+ #+ # This is a GATE, not a column, because of the specific way it fails. A thread that stops+ # following lets the streamed message leave the viewport; a windowed list then unmounts+ # it, and the streaming cost collapses because the renderer is no longer rendering the+ # thing being measured. The frame rate that comes out is excellent and is about nothing.+ # A number with a caveat attached is still a number people quote without the caveat, so+ # the caveat is a gate row that a reader has to step over.+ follow = self._read_follow(page)+ row["follow"] = follow+ pinned = follow.get("pinned_fraction")+ coverage = follow.get("attached_fraction_of_stream")+ passed, recorded = follow_verdict(follow)+ follow.update(recorded)+ rec.gate("follows_the_stream", passed, follow, cell_id = cell.cell_id)+ # THE OTHER HALF OF THE CONTRACT, RECORDED AND DELIBERATELY NOT GATED.+ #+ # It was a gate for one run and it failed on BOTH arms at nearly the same rate (32 of 79+ # on the base, 38 of 85 on the treatment), which is the signature of a reading about the+ # film rather than about the build. The film re-pins legitimately and often: `send_turn`+ # and `stop_generation` each START A RUN, and pinning to the bottom on run start is the+ # intended behaviour, not a violation; `scroll_after` ends its own gesture near the bottom+ # by design. Separating a legitimate re-pin from a yank requires knowing which pins the+ # app was ASKED for, which this sampler does not know.+ #+ # So it is reported as a per-arm figure to be compared BETWEEN arms, where the confounds+ # are common to both and cancel, and it carries the reason it is not a verdict. Gating on+ # it would have failed the shipped build.+ row["scroll_intent"] = {+ # THE ATTESTATION, without which this block fails the bare-zero ban and takes the whole+ # report with it. `yanked_back_samples: 0` beside a non-zero `detached_samples` is the+ # GOOD outcome -- the user scrolled away and the app left them there -- and the walker+ # in scoring/schema.py cannot tell that from a counter nobody wrote. `follow` itself+ # already carries `follow_attempted` and is covered by it; this block is derived from+ # the same read and had nothing, so a real CI session refused to render at all with+ # `bare zeros found: $.cells[0].scroll_intent.yanked_back_samples = 0`. False here+ # rather than absent: the sampler that was never installed reports None for both+ # counters, so "not measured" stays distinguishable from "measured zero".+ "follow_attempted": bool(follow.get("follow_attempted")),+ "detached_samples": follow.get("detached_samples"),+ "yanked_back_samples": follow.get("yanked_back_samples"),+ "gated": False,+ "reason": (+ "the film starts runs of its own (send_turn, stop_generation) and each start pins "+ "to the bottom by design, so this counts legitimate re-pins as well as yanks. "+ "Meaningful only as a difference between two arms of one session"+ ),+ }+ if pinned is None:+ self.log(f" follow: NOT MEASURED ({follow.get('pinned_fraction_reason')})")+ else:+ cov = follow.get("attached_fraction_of_stream")+ self.log(+ f" follow: pinned for {pinned:.0%} of the samples taken while attached and "+ f"streaming, over "+ + ("an unknown share" if cov is None else f"{cov:.0%}")+ + " of the streaming time"+ + f", worst drift {follow.get('max_distance_while_running')}px"+ + (", AND IT FELL BEHIND" if follow.get("ever_fell_behind") else "")+ )+ if follow.get("detached_samples"):+ self.log(+ f" scroll intent: {follow.get('yanked_back_samples')} of "+ f"{follow.get('detached_samples')} samples found the thread back at the bottom "+ f"after the user scrolled away"+ + (" -- THE USER WAS YANKED DOWN" if follow.get("yanked_after_scroll") else "")+ )# EVERY STREAM THE CELL SERVED, not just the last one. `last_stats()` describes whichever# turn finished last, so for a multi-turn cell it says nothing at all about the opening# reply -- and the opening reply is the one the rung is named for. Everything stays under@@ -504,7 +811,12 @@ class CellRunner:if cell.rung == EQUIVALENCE_RUNG and plan.streamed_unit is not None:eq = self._check_equivalence(plan, row)row["equivalence"] = eq- rec.gate("seeded_equals_streamed", bool(eq.get("equivalent")), eq)+ rec.gate(+ "seeded_equals_streamed",+ bool(eq.get("equivalent")),+ eq,+ cell_id = cell.cell_id,+ )if not eq.get("equivalent"):# A FINDING, printed, not a bug to hide. It says exactly which of this tool's# numbers are about the streaming path and which are about a thread that was put@@ -636,7 +948,7 @@ class CellRunner:wait_until = "domcontentloaded",timeout = 120_000,)- self._wait_for_thread(page, seeded_thread.messages)+ self._wait_for_thread(page, seeded_thread)# Let the highlighter finish, or the span count is a race rather than a comparison.page.wait_for_timeout(4000)seeded_sig = dom_signature(page)@@ -649,28 +961,52 @@ class CellRunner:out = compare_signatures(streamed, seeded_sig)out["streamed_census"] = streamedout["seeded_census"] = seeded_sig+ out["readiness_mode"] = self.readiness_mode+ if self.readiness_mode == MODE_WINDOWED:+ # SAID OUT LOUD RATHER THAN SCORED QUIETLY. Both sides of this check are loaded by the+ # SAME build, so under a windowed arm both censuses count the mounted window and not+ # the thread. The comparison is still like for like and its pass still means something+ # -- the two paths render the same window the same way -- but it is no longer evidence+ # that seeding reproduces the whole streamed thread, because neither side has the whole+ # thread in the DOM to compare.+ out["scope"] = "the mounted window only, not the whole thread"+ out["caveat"] = (+ "this arm mounts a window, so `assistant_messages`, `content_spans` and "+ "`content_code_blocks` are counts over what is mounted at the end of the thread. "+ "A pass is equivalence of the WINDOW, not of the thread."+ )# What the mirror was built from, so a drift can be read against the corpus it compared# rather than against an assumption about which turns were in the thread.out["mirrored_follow_ups"] = len(follow_ups)out["planned_follow_ups"] = len(plan.follow_up_units or [])return out- def _wait_for_thread(self, page, expected_messages: int) -> None:- if expected_messages <= 0:- page.wait_for_selector('textarea[aria-label="Message input"]', timeout = 60_000)- return- deadline = time.monotonic() + MOUNT_TIMEOUT_S- last = -1- while time.monotonic() < deadline:- got = page.evaluate("() => window.__sb.dom.messageCount()")- if got >= expected_messages:- return- if got != last:- last = got- self.log(f" mounting: {got}/{expected_messages} messages")- page.wait_for_timeout(500)- raise TimeoutError(- f"the thread mounted {last} of {expected_messages} messages in " f"{MOUNT_TIMEOUT_S}s"+ def _read_follow(self, page) -> dict:+ """Drain the page-side follow sampler. Never raises: a missing sampler is a reason, not+ a lost cell, and it must not read as a thread that followed."""+ try:+ got = page.evaluate("() => window.__sb.follow && window.__sb.follow.read()")+ except Exception as exc: # noqa: BLE001+ return {"follow_attempted": False, "reason": f"{type(exc).__name__}: {exc}"}+ if not isinstance(got, dict):+ return {"follow_attempted": False, "reason": "the follow sampler is not installed"}+ return got++ def _wait_for_thread(self, page, seeded: SeededThread) -> Readiness:+ """The readiness gate. See runtime/readiness.py for what it asserts and why.++ The mode is the CELL RUNNER's, not the thread's: an arm declares that it mounts a window+ and the whole run is then gated that way and labelled that way in every row it writes. A+ thread cannot be allowed to talk its way past the gate by looking virtualised, because+ "looks like it mounted fewer nodes on purpose" is indistinguishable from "did not finish".+ """+ return wait_for_thread_ready(+ page,+ seeded.messages,+ marker = seeded.last_marker,+ mode = self.readiness_mode,+ timeout_s = MOUNT_TIMEOUT_S,+ log = self.log,)def _click_attribution(self, page, selector: str) -> dict:diff --git a/tests/studio/studiobench/runtime/types.py b/tests/studio/studiobench/runtime/types.pyindex b5652e296ae..0f846d5abed 100644--- a/tests/studio/studiobench/runtime/types.py+++ b/tests/studio/studiobench/runtime/types.py@@ -370,10 +370,20 @@ class Recorder:name: str,passed: bool,detail: Optional[dict] = None,+ cell_id: Optional[str] = None,) -> None:- self.emit(- {"row_type": "gate", "name": name, "passed": bool(passed), "detail": detail or {}}- )+ """A pass/fail verdict row. `cell_id` NAMES THE CELL THE VERDICT IS ABOUT.++ Optional because a few gates really are run-level, but almost none are. `excluded_from_rows`+ reads `row.get("cell_id") or "run"`, so a per-cell gate emitted without one is attributed to+ the synthetic cell "run": a failure that says one arm at one rung lost messages is presented+ as a run-level self-check failure, and the report cannot say which arm or which rung. Pass+ it whenever the verdict is about a cell.+ """+ row = {"row_type": "gate", "name": name, "passed": bool(passed), "detail": detail or {}}+ if cell_id is not None:+ row["cell_id"] = cell_id+ self.emit(row)def failure(self,diff --git a/tests/studio/studiobench/scene/actions.py b/tests/studio/studiobench/scene/actions.pyindex 52c22b48f5f..d6070446ca9 100644--- a/tests/studio/studiobench/scene/actions.py+++ b/tests/studio/studiobench/scene/actions.py@@ -22,8 +22,15 @@ from __future__ import annotationsimport jsonimport time-from typing import Any-+from dataclasses import dataclass+from typing import Any, Optional++from ..runtime.readiness import (+ MODE_FULL,+ MODE_WINDOWED,+ ThreadNotReady,+ wait_for_thread_ready,+)from ..runtime.types import ActionContext, ActionResult, not_runfrom . import register_action@@ -63,6 +70,28 @@ def _ev(return {"__error": f"{type(exc).__name__}: {exc}"}+#: How much of an exception's message a refusal reason carries.+_EXC_CHARS = 160+++def _why(exc: BaseException) -> str:+ """An exception as a reason a person can act on: the class AND its first line.++ `type(exc).__name__` alone is worthless here and cost a full day of someone else's. Playwright's+ own exception class is named `Error`, so every clipboard refusal in two complete 100K payloads+ read "the clipboard could not be read back: Error" -- which names no cause, points at no engine+ and cannot be told apart from any other failure in the stack. The message is where the browser+ says `NotAllowedError: Document is not focused` or `TypeError: navigator.clipboard is+ undefined`, and it is the whole diagnosis.++ First line only, and truncated: Playwright appends the call log, which is dozens of lines and+ belongs in the log rather than in a row's `reason`.+ """+ first = str(exc).strip().splitlines()+ head = first[0][:_EXC_CHARS] if first else ""+ return f"{type(exc).__name__}: {head}" if head else type(exc).__name__++def _failed(raw: Any) -> str | None:if raw is None:return "the page returned nothing"@@ -293,7 +322,18 @@ def _scroll(ctx: ActionContext, label: str) -> ActionResult:steps = int(ctx.args.get("steps", 14))step_px = int(ctx.args.get("step_px", 420))settle_ms = int(ctx.args.get("settle_ms", 200))- raw = _ev(ctx, SCROLL_JS, [steps, step_px, settle_ms])+ # THE FOLLOW SAMPLER IS SUSPENDED FOR THE DURATION OF THIS GESTURE. This action drags the+ # viewport thousands of pixels off the bottom on purpose, twice, while the reply is still+ # streaming. Samples taken during it record a thread that is not pinned, which is true and is+ # the benchmark's own doing, and averaging them in makes `follows_the_stream` a reading about+ # the film rather than about the app. See the sampler in scene/dom.js.+ _ev(ctx, "() => window.__sb.follow && window.__sb.follow.suspend()")+ try:+ raw = _ev(ctx, SCROLL_JS, [steps, step_px, settle_ms])+ finally:+ # Resumed even when the gesture raised, or one failed scroll silences the sampler for the+ # rest of the cell and the arm reports a follow fraction built from nothing.+ _ev(ctx, "() => window.__sb.follow && window.__sb.follow.resume()")err = _failed(raw)if err:return not_run(err)@@ -404,7 +444,16 @@ def reasoning_toggle(ctx: ActionContext) -> ActionResult:ran = True,expect_ok = ok,expect = {+ # SCOPED TO WHAT IS MOUNTED, and always was. `reasoningTriggers()` is a+ # querySelectorAll, so on the shipped build it finds every pane in the thread and on a+ # windowed mount it finds the panes in the window. The assertion below stays+ # self-consistent either way (it opens N and expects N open), so the action still+ # passes -- but its COST silently stops being a function of thread length and becomes+ # a function of window size. That is the arm's point, and it is also the reason this+ # timing is not comparable between a windowed arm and a full one without the pane+ # count beside it."panes": raw["panes"],+ "panes_scope": "mounted","open_after_expand": raw["openCount"],"open_after_collapse": raw["afterClose"],"highlight_spans_while_open": raw["spansOpen"],@@ -417,6 +466,95 @@ def reasoning_toggle(ctx: ActionContext) -> ActionResult:)+#: THE SAME GESTURE A USER MAKES. `reasoning_toggle` above opens every pane in the thread at once,+#: which is a deliberate worst case and reads at 2.2 fps at the 100K rung. That number has been+#: quoted as though it described opening a reasoning pane, and it does not: a user opens ONE, and+#: almost always the newest one. This action measures that, so the two can be quoted apart.+#:+#: It is NOT in the standard film. The scene is a fixed-duration slot schedule, so adding a slot+#: shifts every window after it and voids comparability against every payload already on disk. Run+#: it in a purpose-built film until the next corpus or tier bump invalidates those payloads anyway.+REASONING_ONE_JS = """+async (timeoutMs) => {+ const D = window.__sb.dom;+ const triggers = D.reasoningTriggers();+ if (triggers.length === 0) return { ran: false, reason: "no reasoning pane in the thread" };+ const before = D.reasoningOpenCount();+ if (before !== 0) return { ran: false, reason: `${before} panes were already open` };+ // The LAST pane: the newest reply is the one a user reaches for, and it is also the only pane+ // whose position is the same on a windowed mount as on a full one.+ const target = triggers[triggers.length - 1];+ const settle = async (want) => {+ const started = performance.now();+ while (performance.now() - started < timeoutMs) {+ if (D.reasoningOpenCount() === want) return performance.now() - started;+ await window.__sbNextPaint();+ }+ return null;+ };+ const spansBefore = document.querySelectorAll("pre span").length;+ const openStart = performance.now();+ target.click();+ const openedIn = await settle(1);+ const openMs = openedIn === null ? null : performance.now() - openStart;+ const openCount = D.reasoningOpenCount();+ const spansOpen = document.querySelectorAll("pre span").length;+ const closeStart = performance.now();+ (D.reasoningTriggers()[triggers.length - 1] || target).click();+ const closedIn = await settle(0);+ const closeMs = closedIn === null ? null : performance.now() - closeStart;+ return {+ ran: true,+ panes: triggers.length,+ openCount,+ afterClose: D.reasoningOpenCount(),+ spansOpen,+ spansAdded: spansOpen - spansBefore,+ openMs: openMs === null ? null : Math.round(openMs * 10) / 10,+ closeMs: closeMs === null ? null : Math.round(closeMs * 10) / 10,+ };+}+"""+++@register_action(name = "reasoning_toggle_one", default_budget_ms = 12000)+def reasoning_toggle_one(ctx: ActionContext) -> ActionResult:+ raw = _ev(ctx, REASONING_ONE_JS, SETTLE_TIMEOUT_MS)+ err = _failed(raw)+ if err:+ return not_run(err)+ if not raw.get("ran"):+ return not_run(raw.get("reason", "the reasoning toggle did not run"))+ ok = (+ raw["openMs"] is not None+ and raw["closeMs"] is not None+ and raw["openCount"] == 1+ and raw["afterClose"] == 0+ )+ return ActionResult(+ ran = True,+ expect_ok = ok,+ expect = {+ # `panes` is context, not an assertion: this action opens one of them whatever the+ # thread holds, which is the whole point of it existing beside `reasoning_toggle`.+ "panes": raw["panes"],+ "panes_scope": "mounted",+ "panes_opened": 1,+ "open_after_expand": raw["openCount"],+ "open_after_collapse": raw["afterClose"],+ "highlight_spans_while_open": raw["spansOpen"],+ # The cost driver, so a reading can be normalised rather than compared across threads+ # whose newest reply happens to differ in size.+ "highlight_spans_added": raw["spansAdded"],+ },+ timings = {"open_ms": raw["openMs"], "close_ms": raw["closeMs"]},+ reason = None+ if ok+ else f"{raw['openCount']} panes were open after opening one and "+ f"{raw['afterClose']} were still open after collapsing",+ )++# ── 5. stop generation ──────────────────────────────────────────────#: What `stop_generation`'s throwaway turn costs in FIXED waits once it starts, on any machine: 80@@ -540,7 +678,9 @@ OWN_TURN_TEXT = "one more"STOP_CLEANUP_JS = """async (timeoutMs) => {const D = window.__sb.dom;- const before = D.messageCount();+ // threadTotal, not messageCount. Identical on the shipped build; under a windowed mount the+ // window refills as the message leaves it, so a cleanup that worked reports after == before.+ const before = D.threadTotal();const removeLast = async () => {const target = D.lastAssistantMessage();if (!target) return false;@@ -556,7 +696,7 @@ async (timeoutMs) => {return false;};const dropped = await removeLast();- const after = D.messageCount();+ const after = D.threadTotal();return {removed: dropped && after < before,before, after,@@ -582,7 +722,7 @@ def _own_turn_was_accepted(ctx: ActionContext, messages_before: Any) -> bool:"""if _ev(ctx, "() => window.__sb.dom.composerText()") != OWN_TURN_TEXT:return True- after = _ev(ctx, "() => window.__sb.dom.messageCount()")+ after = _ev(ctx, "() => window.__sb.dom.threadTotal()")return not (isinstance(messages_before, int) and isinstance(after, int) and after <= messages_before)@@ -610,7 +750,7 @@ def _reclaim_pending_turn(DELETES ONLY WHAT IT ADDED. `STOP_CLEANUP_JS` removes the LAST assistant message, so running itwhen the send was refused or when the app never rendered the turn would take a seeded reply outof 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.+ thread total 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")@@ -634,7 +774,7 @@ def _reclaim_pending_turn(# The chunks already in flight, as on the measured path.ctx.page.wait_for_timeout(400)- messages_after = _ev(ctx, "() => window.__sb.dom.messageCount()")+ messages_after = _ev(ctx, "() => window.__sb.dom.threadTotal()")grew = (isinstance(messages_before, int)and isinstance(messages_after, int)@@ -756,7 +896,14 @@ def stop_generation(ctx: ActionContext) -> ActionResult:# 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()")+ #+ # threadTotal, not messageCount, for the reason STOP_CLEANUP_JS gives above and in the same+ # direction: under a windowed mount the window refills as the thread grows, so a send that+ # WORKED reports after == before and the reclaim path then decides there is nothing to remove.+ # The turn it already sent is left in the thread with its stream still running, which is the+ # one outcome this whole path exists to prevent, and it contaminates every later action window+ # and the final census. Identical on the shipped build, where the two are the same number.+ messages_before = _ev(ctx, "() => window.__sb.dom.threadTotal()")ctx.page.fill('textarea[aria-label="Message input"]', OWN_TURN_TEXT)ctx.page.wait_for_timeout(80)ctx.page.keyboard.press("Enter")@@ -1128,7 +1275,7 @@ def copy_markdown(ctx: ActionContext) -> ActionResult:try:clip = ctx.page.evaluate("async () => await navigator.clipboard.readText()")except Exception as exc: # noqa: BLE001- reason = f"the clipboard could not be read back: {type(exc).__name__}"+ reason = f"the clipboard could not be read back: {_why(exc)}"chars = len(clip) if isinstance(clip, str) else Noneok = chars is not None and chars > 0return ActionResult(@@ -1232,16 +1379,154 @@ def select_all_copy(ctx: ActionContext) -> ActionResult:err = _failed(raw)if err:return not_run(err)+ # A SENTINEL ON THE CLIPBOARD BEFORE THE COPY, so "the copy happened" is OBSERVED rather than+ # assumed from the keystroke having been sent.+ #+ # THE FAILURE THIS EXISTS FOR, measured. Playwright's WebKit never performs a clipboard copy on+ # Control+C. The action pressed the key, slept 250ms for the copy to land, and reported the+ # sleep as `copy_ms`. In every WebKit payload on this machine that number is 258.5 ms at the 1K+ # rung, 258.8 ms at 10K and 263.9 ms at 100K: a hundredfold change in the quantity under study+ # moved the "measurement" by two percent, because it was measuring `wait_for_timeout(250)`.+ # Chromium reads about 1,538 ms at 100K for the same action. Forty-three rows across eleven+ # payloads reported a sleep as a result.+ #+ # A measurement that silently reports a sleep is the worst failure mode in this harness, so the+ # test is on the CLIPBOARD and not on the engine name: an engine that starts working, or a new+ # one, is admitted automatically, and an engine that stops working is refused automatically.+ #+ # WHAT THE CHECK NEEDS is a KNOWN PRE-COPY VALUE, and the sentinel is only the best way of+ # getting one. Writing it can fail on its own: `writeText` needs transient user activation or+ # the `clipboard-write` permission and throws `NotAllowedError` without either, while+ # `readText` is gated separately -- so the two are not granted or refused together, and+ # runtime/browser.py asks for the pair on Chromium and for neither on the other engines.+ #+ # Clearing the sentinel on that failure and carrying on is what re-admitted the exact defect+ # above: with no pre-copy value, `clip == sentinel` can never fire, and a Control+C that did+ # nothing leaves the clipboard holding whatever `copy_markdown` put there earlier in the same+ # film -- a plausible, non-empty string that is read back as a fresh copy of the whole thread,+ # with the 250 ms settle beside it as `copy_ms`.+ #+ # So a failed write falls back to SNAPSHOTTING what the clipboard already holds, which answers+ # the same question ("did this keystroke change the clipboard"), and when even that cannot be+ # established the action is NOT RUN. The residual, stated: if the clipboard already held+ # character-for-character what the copy would produce, an honest copy is refused as a+ # no-op. That direction is the safe one, it needs the write permission to be missing first,+ # and the film never copies the same thread twice.+ sentinel = f"__sb_clipboard_sentinel_{int(time.monotonic() * 1000)}__"+ sentinel_written = False+ #: What the clipboard held before Control+C, and where that value came from. `None` means no+ #: pre-copy value could be established at all, which is refused below.+ pre_copy: Optional[str] = None+ pre_copy_source = "sentinel"+ pre_copy_reason = None+ try:+ ctx.page.evaluate("async (s) => await navigator.clipboard.writeText(s)", sentinel)+ sentinel_written = True+ pre_copy = sentinel+ except Exception as write_exc: # noqa: BLE001+ sentinel = ""+ pre_copy_source = "snapshot"+ try:+ existing = ctx.page.evaluate("async () => await navigator.clipboard.readText()")+ except Exception as read_exc: # noqa: BLE001+ existing = None+ pre_copy_reason = (+ f"the sentinel could not be written ({_why(write_exc)}) and the clipboard could "+ f"not be read either ({_why(read_exc)})"+ )+ if isinstance(existing, str):+ pre_copy = existing+ elif pre_copy_reason is None:+ pre_copy_reason = (+ f"the sentinel could not be written ({_why(write_exc)}) and the clipboard handed "+ "back no string to snapshot in its place"+ )+copy_started = time.monotonic()ctx.page.keyboard.press("Control+C")ctx.page.wait_for_timeout(250)copy_ms = (time.monotonic() - copy_started) * 1000+ # THE CLIPBOARD, NOT THE SELECTION.+ #+ # This action used to score itself on `Selection.toString().length`, and that is not what a+ # user gets. The two came apart the moment an arm existed that unmounts messages AND handles+ # the copy event: the selection can only ever cover mounted nodes, while a copy handler that+ # reads the message store puts the whole conversation on the clipboard. Scored on the+ # selection, a build that had FIXED the data loss would still be reported as losing data --+ # the alarm would stay lit for a reason that no longer existed, which is the fastest way to+ # get an alarm switched off.+ #+ # Read back before the selection is cleared, and the failure to read it is reported rather+ # than treated as an empty clipboard: headless Chromium grants clipboard-read only with the+ # permission the browser factory requests.+ clip = None+ clip_reason = None+ try:+ clip = ctx.page.evaluate("async () => await navigator.clipboard.readText()")+ except Exception as exc: # noqa: BLE001+ clip_reason = f"the clipboard could not be read back: {_why(exc)}"+ clipboard_chars = len(clip) if isinstance(clip, str) else Nonectx.page.evaluate("() => window.getSelection().removeAllRanges()")++ # NO CONFIRMED COPY, NO TIMING. Reported NOT RUN rather than as a number, because a reader who+ # sees `copy_ms` has no way to tell a real copy from a keystroke that went nowhere, and the+ # engines that fail this do so silently and consistently enough to look like data.+ if pre_copy is not None and clip == pre_copy:+ held = (+ "it still holds the sentinel written before the keystroke"+ if sentinel_written+ else "it still holds, character for character, what it held before the keystroke "+ "(the sentinel could not be written, so the clipboard was snapshotted instead)"+ )+ return not_run(+ f"Control+C did not change the clipboard: {held}, so this engine did not perform the "+ f"copy and the elapsed time would be the harness's own {250}ms settle rather than a "+ "measurement of the app"+ )+ if pre_copy is None:+ return not_run(+ f"the copy could not be confirmed ({pre_copy_reason}), so nothing was known about the "+ "clipboard before Control+C and a keystroke that did nothing would be indistinguishable "+ "from a copy. A timing is only reported when the clipboard is known to have changed"+ )+ if clip_reason is not None:+ return not_run(+ f"the copy could not be confirmed ({clip_reason}), so there is no evidence that "+ "Control+C did anything and the elapsed time would be the harness's own settle. A "+ "timing is only reported when the clipboard can be read back and has changed"+ )+ total = _ev(ctx, "() => window.__sb.dom.threadTotal()")+ mounted = _ev(ctx, "() => window.__sb.dom.messageCount()")ok = raw["chars"] > 0return ActionResult(ran = True,expect_ok = ok,- expect = {"selected_chars": raw["chars"]},+ expect = {+ "selected_chars": raw["chars"],+ # WHAT ACTUALLY REACHED THE CLIPBOARD. The user-facing quantity, and the one the+ # truncation alarm is scored on. A windowed mount cannot SELECT what is not in the+ # DOM, but it can still COPY it, if the app's copy handler reads the message store --+ # which is the fix, and which this is the only reading able to see.+ "clipboard_chars": clipboard_chars,+ "clipboard_readable": clip_reason is None,+ "clipboard_note": clip_reason,+ # WHICH pre-copy value the change was confirmed against: the sentinel this action+ # wrote, or a snapshot of what the clipboard already held when the write was refused.+ # A snapshot is the weaker of the two -- see the note above the write -- and a reader+ # comparing rows has no other way to see which one a timing rests on.+ "copy_confirmed_against": pre_copy_source,+ # And the DOM coverage beside it, so the two can be told apart. Where+ # `mounted_fraction` is well below 1 and `clipboard_chars` is nonetheless whole, the+ # copy-from-store path is working; where both are short, the conversation is being+ # lost. That is a user-visible defect and must not be filed as a measurement problem.+ "messages_total": total,+ "messages_mounted": mounted,+ "mounted_fraction": (+ round(mounted / total, 3)+ if isinstance(total, int) and isinstance(mounted, int) and total+ else None+ ),+ },timings = {"select_all_ms": raw["selectMs"],"copy_ms": round(copy_ms, 1),@@ -1251,8 +1536,15 @@ def select_all_copy(ctx: ActionContext) -> ActionResult:# against: the selection is taken over the viewport's DOM, so if the DOM is windowed the# selection and every DOM-derived reference shrink together and agree with each other.# An absolute floor would need calibrating per rung and per platform, and would still be a- # guess. The count below is the real check, and it is paired against the other arm.- counts = {"selected_chars": raw["chars"]},+ # guess. The counts below are the real check, and they are paired against the other arm.+ #+ # `clipboard_chars` FIRST, because it is the one a user would notice. `selected_chars` is+ # kept beside it as the mechanism: if the clipboard held and the selection fell, the copy+ # handler is reading the store; if both fell, the conversation is being lost.+ counts = {+ "clipboard_chars": clipboard_chars,+ "selected_chars": raw["chars"],+ },reason = None if ok else "select-all selected nothing",)@@ -1317,7 +1609,12 @@ def send_turn(ctx: ActionContext) -> ActionResult:return not_run("no composer on the page")ctx.page.fill(selector, f"studiobench follow-up {index + 1}")ctx.page.wait_for_timeout(80)- before = _ev(ctx, "() => window.__sb.dom.messageCount()")+ # THE THREAD'S LENGTH, not the mounted count. "The thread grew" is a statement about the+ # conversation; a windowed mount answers it about the viewport, and the answer it gives is+ # `after == before` for a send that worked perfectly, because the new pair arrives at the+ # bottom while two messages leave the top of the window.+ before = _ev(ctx, "() => window.__sb.dom.threadTotal()")+ mounted_before = _ev(ctx, "() => window.__sb.dom.messageCount()")started = time.monotonic()ctx.page.keyboard.press("Enter")@@ -1328,7 +1625,8 @@ def send_turn(ctx: ActionContext) -> ActionResult:first_ms = (time.monotonic() - started) * 1000breakctx.page.wait_for_timeout(50)- after = _ev(ctx, "() => window.__sb.dom.messageCount()")+ after = _ev(ctx, "() => window.__sb.dom.threadTotal()")+ mounted_after = _ev(ctx, "() => window.__sb.dom.messageCount()")# A POSITIVE consequence: the turn actually started streaming AND the thread grew. A send that# silently failed leaves both unchanged and would otherwise read as an instant send.ok = (@@ -1343,6 +1641,11 @@ def send_turn(ctx: ActionContext) -> ActionResult:expect = {"messages_before": before,"messages_after": after,+ # What was MOUNTED either side, kept beside the thread totals. On the shipped build+ # these two pairs are identical; where they differ, the difference is the size of the+ # window and it is the reading the whole virtualization arm exists to produce.+ "mounted_before": mounted_before,+ "mounted_after": mounted_after,"turn_index": index + 1,"queued_turns": len(queue),"streamed_chars": len(unit["reasoning"]) + len(unit["content"]),@@ -1471,6 +1774,40 @@ def image_upload(ctx: ActionContext) -> ActionResult:# ── 13. thread reopen ───────────────────────────────────────────────+#: The end of the thread, as a plain string that can be looked for again after the rebuild.+#:+#: NOT the seeder's `last_marker`, even though that is the string the readiness gate uses at the+#: start of the cell. `send_turn` appends turns to the thread MID-FILM, twice in every scene, so by+#: the time this slot opens the seeded marker sits several messages from the end -- and+#: `end_present` requires the marker within two rows of the end, so it could never be satisfied.+#: Reading the last user turn out of the DOM immediately before leaving gives the marker for the+#: thread as it actually stands at this point in the film.+#:+#: `trim()` and then a prefix, never a whitespace-collapsing normalisation: readiness.PROBE_JS+#: matches with `textContent.includes(marker)` against RAW text, and trimming plus slicing from the+#: front leaves a genuine substring of that raw text while collapsing internal runs would not.+_LAST_USER_TEXT_JS = """+() => {+ const rows = Array.from(document.querySelectorAll('[data-role="user"]'));+ const last = rows.length ? rows[rows.length - 1] : null;+ if (!last) return null;+ const text = (last.textContent || "").trim();+ return text ? text.slice(0, 120) : null;+}+"""++#: How long the rebuilt thread is given to reach the readiness gate's definition of ready, in+#: seconds: what is left of the SLOT, floored and capped.+#:+#: Bounded by the slot because the condition below is now one a broken arm can fail to satisfy+#: forever -- a thread that never stops mutating never settles -- and the film's own last slot,+#: `delete_message`, is the one place an overrun has nowhere to go (see scene/schedule.py, which+#: records a sweep where exactly that lost delete on every base-arm cell). Floored at 10s so a+#: tight budget still gives a 1M-token thread a fair chance, and capped at the flat minute the+#: previous "declared its total" loop waited, so nothing waits longer than it used to.+_REOPEN_READY_FLOOR_S = 10.0+_REOPEN_READY_CEILING_S = 60.0+@register_action(name = "thread_reopen", default_budget_ms = 30000)def thread_reopen(ctx: ActionContext) -> ActionResult:@@ -1484,78 +1821,451 @@ def thread_reopen(ctx: ActionContext) -> ActionResult:thread_id = ctx.args.get("thread_id")if not thread_id:return not_run("no thread id was supplied to the action")- before = _ev(ctx, "() => window.__sb.dom.messageCount()")- if not before:+ # The THREAD's length, not the mounted count: a windowed arm that reopens with a different+ # scroll anchor mounts a different number of rows, and the exact-equality assertion at the end+ # of this action would then fail for a reason that has nothing to do with the rebuild.+ before = _ev(ctx, "() => window.__sb.dom.threadTotal()")+ mounted_before = _ev(ctx, "() => window.__sb.dom.messageCount()")+ # AN INTEGER, not merely truthy. `_ev` hands back `{"__error": ...}` when the page throws, and+ # a dict is truthy: it would reach the comparisons below and the readiness gate's own+ # `expected_messages` as a length, and raise there instead of being reported here.+ if not isinstance(before, int) or before <= 0:return not_run("the thread has no messages to rebuild")+ # WHICH READINESS MODE THIS ARM IS HELD TO, decided from the mount that is on screen now and+ # therefore before anything is torn down. A thread whose declared total is larger than what it+ # has mounted IS a windowed mount -- that is `isWindowed()` in scene/dom.js -- and it is the+ # same distinction runtime/readiness.py draws between its two modes. Read from the page rather+ # than taken from a session flag so both arms are judged by one rule.+ mode = (+ MODE_WINDOWED if isinstance(mounted_before, int) and mounted_before < before else MODE_FULL+ )+ marker = _ev(ctx, _LAST_USER_TEXT_JS)+ if not isinstance(marker, str) or not marker:+ # Refused HERE, before a single thing has been touched, so a thread this action cannot+ # verify is also a thread it has not disturbed. Without a string that identifies the end of+ # the conversation there is no way to tell a rebuilt thread from a half-rebuilt one, which+ # is the entire question the wait below exists to answer.+ return not_run(+ "the last user turn carried no text to identify the end of the thread with, so a "+ "finished rebuild could not have been told from a partial one"+ )started = time.monotonic()- # Click if the control is really clickable, otherwise NAVIGATE. The sidebar's sticky group- # label overlays the New chat button and intercepts the pointer, so the click retries until it- # times out on a button that is visible, enabled and stable -- and the action then reports a- # rebuild that never happened. `/chat?new=` is what the button itself does.- if not _click_or_navigate(- ctx, 'button[aria-label="New chat"]', f"{ctx.args['base_url']}/chat?new=studiobench"- ):- return not_run("the thread could not be left, by click or by navigation")+ # NO FALLBACK ON THE WAY OUT. Workspace task #102 and the defect it left behind.+ #+ # That task taught this action to REFUSE a substituted navigation, because a goto is a FULL+ # DOCUMENT NAVIGATION -- the SPA is torn down and reparsed, the bundle re-executes, the runtime+ # rehydrates -- while the click is a client-side route change that rebuilds one React subtree.+ # They are not the same operation and they do not cost the same thing; read as though it were+ # the click, the substitution produced thread_reopen at 6.0 fps, a number about a page load+ # quoted as a number about a thread.+ #+ # But it refused AFTER THE FACT, by inspecting `path` once `page.goto` had already run. The row+ # was then honest and the rest of the film was collateral damage: the scene carried on from an+ # empty new chat, and `delete_message` -- the last slot of every film, three slots later --+ # found no messages and went unexercised for a reason that had nothing to do with deleting.+ #+ # So the substitution is declined BEFORE it happens. Nothing is clicked, nothing is navigated,+ # the thread is still on screen, and the slots after this one still have the thread they were+ # written for.+ leave = _click_or_navigate(+ ctx,+ 'button[aria-label="New chat"]',+ f"{ctx.args['base_url']}/chat?new=studiobench",+ allow_navigate = False,+ )+ if not leave.ok:+ ctx.log(+ " thread_reopen NOT MEASURED: the New chat button could not be clicked "+ f"({leave.reason}), and the only substitute available is a full page navigation, "+ "which reloads the whole app and is not the operation this action exists to time. "+ "It was NOT performed: the thread is untouched and the slots that follow still have it."+ )+ return not_run(+ "the New chat control could not be clicked and the only available substitute is a full "+ "page navigation; a document reload is not a thread rebuild, so the action was not run "+ f"and no navigation was performed ({leave.reason})"+ )+ # BOTH CLOCKS START AT THE CLICK THAT WORKED, not at the first attempt on it.+ #+ # `_click_or_navigate` tries `handle.click` first, and Playwright's hit-target check retries+ # for its whole 2,000 ms timeout against a control whose centre does not hit-test to it. The+ # New chat button IS such a control by design -- `opacity-0 pointer-events-none` until its+ # header group is hovered -- so that timeout was paid on EVERY run and landed inside+ # `close_ms`, which sweep/floor_table.py harvests and quotes against the other arm. A metric+ # that is two seconds of harness retry plus the unmount is the same defect as reporting a+ # settle delay as `copy_ms`, one action along.+ #+ # The retry is not discarded, it is MOVED: `left_click_retry_ms` and `reopen_click_retry_ms`+ # below carry it as the harness's own cost, which is what it is. `started` still governs the+ # budget arithmetic, because the retry really did consume the slot's wall clock.+ click_left_at = leave.started_at if leave.started_at is not None else started# Unmount FIRST, or "already back" is indistinguishable from "never left".closed_ms = Nonedeadline = started + 15while time.monotonic() < deadline:if _ev(ctx, "() => window.__sb.dom.messageCount()") == 0:- closed_ms = (time.monotonic() - started) * 1000+ closed_ms = (time.monotonic() - click_left_at) * 1000breakctx.page.wait_for_timeout(50)if closed_ms is None:return not_run("the thread never unmounted, so the rebuild could not be timed")reopen_started = time.monotonic()- if not _click_or_navigate(+ # THE FALLBACK IS ALLOWED ON THE WAY BACK, and refused on the way out, for one reason: what it+ # does to the scene. From an empty new chat, a navigation to the thread's own URL is what puts+ # the thread back on screen for the slots that follow, so as a REPAIR it is the right tool --+ # where on the way out it was the thing that broke the scene. It is still not a measurement of+ # a rebuild, which is what the `not_run` below says, and no timing is reported for it.+ back = _click_or_navigate(ctx, f'[data-thread-id="{thread_id}"]', f"{ctx.args['base_url']}/chat?thread={thread_id}"- ):- return not_run("the thread could not be reopened, by click or by navigation")+ )+ if not back.ok:+ return not_run(f"the thread could not be reopened: {back.reason}")+ click_back_at = back.started_at if back.started_at is not None else reopen_started+ if back.navigated:+ ctx.log(+ " thread_reopen NOT MEASURED: the sidebar row for the thread could not be clicked, "+ f"so reopening fell back to a full page navigation ({back.reason}). The navigation "+ "was allowed to stand so the thread is back for the slots that follow, but a document "+ "reload is not a rebuild and no timing is reported for it."+ )+ return not_run(+ "the thread's sidebar row could not be clicked and a full page navigation was "+ f"substituted, so the rebuild was never timed ({back.reason})"+ )+ # WHEN IS THE REBUILD OVER?+ #+ # NOT when `threadTotal()` reaches the length it had. On a windowed arm `threadTotal()` reads+ # `aria-setsize`, which is the STORE'S CLAIM about how long the conversation is, and the very+ # first reopened row publishes it: the condition was satisfied while three of eighteen messages+ # were mounted, with no bottom window, no final assistant content and no syntax highlighting+ # yet. The action then reported that as `reopen_ms`, took its census and its parity digest off+ # a half-built DOM, and still passed its own assertion because `after == before` was a+ # statement about the same declared total. A declaration is not a rebuild.+ #+ # WHAT `reopen_ms` MEASURES NOW: from the click on the thread's sidebar row until the reopened+ # thread satisfies runtime/readiness.py's gate -- the composer is present, the END of the+ # conversation is mounted (the last user turn, found by the marker captured above), and the+ # mount has SETTLED, meaning two samples STABLE_GAP_MS apart agree on the mounted count, the+ # element count and the laid-out height. Plus, in `windowed` mode, that the thread declares the+ # right total on every row and is anchored at the end.+ #+ # THAT SAME FUNCTION, not a second definition of "ready" written here. Two disagreeing+ # definitions in one harness is a defect of its own, and this is the definition the cell was+ # already admitted under: the gate that let the cell start is the gate that decides the rebuild+ # is finished, so the number is the cost of getting back to the state the cell began in.+ #+ # COMPARABILITY: every condition gated in `full` mode is one a fully mounted thread reaches by+ # construction, and each arm is judged in the mode its own mount is in, exactly as the cell's+ # opening gate judged it. The extra `windowed` conditions are a contract that arm already had+ # to meet to be scored at all. What this costs is a floor of one STABLE_GAP_MS, paid equally by+ # both arms, because "settled" is a claim about two samples and cannot be made from one.+ left_ms = ctx.budget_ms - (time.monotonic() - started) * 1000+ timeout_s = min(_REOPEN_READY_CEILING_S, max(_REOPEN_READY_FLOOR_S, left_ms / 1000))reopen_ms = None- deadline = reopen_started + 60- while time.monotonic() < deadline:- if (_ev(ctx, "() => window.__sb.dom.messageCount()") or 0) >= before:- reopen_ms = (time.monotonic() - reopen_started) * 1000- break- ctx.page.wait_for_timeout(100)- after = _ev(ctx, "() => window.__sb.dom.messageCount()")+ try:+ ready = wait_for_thread_ready(+ ctx.page,+ before,+ marker = marker,+ mode = mode,+ timeout_s = timeout_s,+ log = ctx.log,+ )+ reopen_ms = (time.monotonic() - click_back_at) * 1000+ readiness = ready.as_dict()+ except ThreadNotReady as exc:+ # A REAL FINDING ABOUT THE ARM, and it keeps `ran = True` so the row carries which+ # conditions were still outstanding. `timings["reopen_ms"]` stays null, which the scoring+ # layer reads as "ran but recorded no reopen_ms" rather than as a fast rebuild.+ readiness = exc.detail+ except Exception as exc: # noqa: BLE001+ # The probe itself failed (a closed page, an uninstalled `window.__sb`). Nothing was+ # learned about the rebuild, so nothing is claimed about it.+ ctx.log(f" the readiness probe failed during the reopen: {type(exc).__name__}: {exc}")+ return not_run(+ f"the reopened thread could not be probed for readiness: {type(exc).__name__}: {exc}"+ )+ after = _ev(ctx, "() => window.__sb.dom.threadTotal()")+ mounted_after = _ev(ctx, "() => window.__sb.dom.messageCount()")spans = _ev(ctx, "() => document.querySelectorAll('pre span').length")ok = reopen_ms is not None and after == beforereturn ActionResult(ran = True,expect_ok = ok,- expect = {"messages_before": before, "messages_after": after, "highlight_spans_after": spans},+ expect = {+ "messages_before": before,+ "messages_after": after,+ "mounted_before": mounted_before,+ "mounted_after": mounted_after,+ "highlight_spans_after": spans,+ "left_via": leave.path,+ "reopened_via": back.path,+ # THE HARNESS'S OWN COST, named as such and kept OUT of the two timings above. This is+ # how long `_click_or_navigate` spent on attempts that failed before the one that+ # worked -- almost always Playwright's 2,000 ms hit-target retry against a control it+ # cannot hit at the centre. It belongs in the payload (a run where this grows is a run+ # whose controls have moved) and it does not belong in a rebuild timing.+ "left_click_retry_ms": round((click_left_at - started) * 1000, 1),+ "reopen_click_retry_ms": round((click_back_at - reopen_started) * 1000, 1),+ # WHICH GATE THE TIMING WAS TAKEN AGAINST, beside the timing itself. Two arms in+ # different readiness modes are answering slightly different questions, and a reader+ # comparing their `reopen_ms` has no other way to see that.+ "reopen_ready_mode": mode,+ # The gate's own verdict: every condition, the last probe reading and how many samples+ # it took. When the rebuild did not finish, this is what says which condition was still+ # outstanding -- "mounted 3 of 18, aria-setsize 18" is the difference between a slow+ # app and an arm that publishes a total it has not built.+ "reopen_readiness": readiness,+ },timings = {"close_ms": round(closed_ms, 1),"reopen_ms": None if reopen_ms is None else round(reopen_ms, 1),},- reason = None if ok else f"the thread came back with {after} of {before} messages",+ reason = None+ if ok+ else (+ f"the thread came back with {after} of {before} messages"+ if reopen_ms is not None+ else f"the reopened thread never reached a ready state: {readiness.get('reason')}"+ ),)-def _click_or_navigate(ctx: ActionContext, selector: str, url: str) -> bool:- """Click the control a user would click; fall back to the URL it would produce.+@dataclass+class Transition:+ """WHICH ROUTE a state change took, so a substitute can never be read as the original.++ `ok` alone was the whole return value of `_click_or_navigate`, and it collapsed three+ outcomes -- the control was clicked, the control failed and a page load was substituted, and+ nothing worked -- into two. The middle one is the dangerous one: it produces a row that looks+ like a measurement of a click and is a measurement of a document reload.+ """++ ok: bool+ path: str # "click", "navigate" or "failed"+ reason: str = ""+ #: The monotonic instant the interaction that SUCCEEDED was issued, so a caller timing "from+ #: the click" can start its clock at the click rather than at the first attempt. `None` when+ #: nothing succeeded.+ #:+ #: THE FAILED ATTEMPT IS NOT PART OF THE GESTURE. Playwright's hit-target check reads+ #: `elementFromPoint` at the control's centre and retries until the timeout, so a control that+ #: is laid out but not hit-testable at its centre -- the sidebar's `New chat`, which ships+ #: `opacity-0 pointer-events-none` until its group is hovered, and which therefore falls+ #: through to the group underneath on every hit test -- costs the full 2,000 ms before the+ #: reveal path below succeeds. Timed from the first attempt, `thread_reopen.close_ms` was+ #: two seconds of Playwright retry with the unmount somewhere inside it, on every run, and+ #: sweep/floor_table.py quotes it as a metric.+ started_at: Optional[float] = None++ @property+ def navigated(self) -> bool:+ return self.path == "navigate"+++#: Where on an element to look for a point a user could actually hit. Fractions of the box, centre+#: first (so a normal control behaves exactly as before), then the lower band, which is what stays+#: uncovered when a sticky header overlaps the top of a control.+_HIT_POINTS = (+ (0.5, 0.5),+ (0.5, 0.75),+ (0.25, 0.75),+ (0.75, 0.75),+ (0.5, 0.9),+ (0.15, 0.5),+ (0.85, 0.5),+ (0.5, 0.25),+)++#: EVERY match, not the first. `document.querySelector` returns the first element in DOCUMENT+#: ORDER, and this app renders "New chat" twice -- once in the sidebar header and once on the chat+#: page -- exactly as it renders the composer twice. When the sidebar is collapsed its button is+#: still in the tree at zero size, comes first, and is the one a plain query hands back: the probe+#: then reports "no point on the control hit-tests to it" about a button that is 34x34 and fully+#: clickable a few hundred pixels away. This is the same trap `image_upload` documents at length,+#: and it cost this action a second time.+_HIT_TEST_JS = """+([selector, points]) => {+ for (const el of document.querySelectorAll(selector)) {+ const r = el.getBoundingClientRect();+ if (r.width === 0 || r.height === 0) continue;+ for (const [fx, fy] of points) {+ const x = r.left + r.width * fx;+ const y = r.top + r.height * fy;+ if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;+ const top = document.elementFromPoint(x, y);+ // `contains`, not identity: the control's own icon or label is a child and hit-tests to+ // itself, which is still a click that reaches the control.+ if (top && (top === el || el.contains(top))) return { x, y };+ }+ }+ return null;+}+"""+++def _reachable_point(ctx: ActionContext, selector: str) -> tuple[float, float] | None:+ """A viewport point that hit-tests to `selector`, or None if no instance of it is reachable."""+ got = _ev(ctx, _HIT_TEST_JS, [selector, [list(p) for p in _HIT_POINTS]])+ if isinstance(got, dict) and "x" in got:+ return got["x"], got["y"]+ return None+++#: How long the reveal transition needs, and how many times to look. `.sidebar-header-action`+#: transitions opacity over 150ms. One sample after a fixed sleep is a race that this test suite+#: lost roughly one run in three on a loaded machine, so the hit test is retried instead.+_REVEAL_SETTLE_MS = 120+_REVEAL_ATTEMPTS = 5++#: The control's own box, whatever its computed style says. An earlier version only offered a+#: hover point for a control that LOOKED hidden, which made the reveal conditional on a style read+#: taken at exactly the wrong moment: mid-transition `getComputedStyle` reports the old opacity,+#: and after a failed Playwright click the element can read as already revealed while not yet+#: being hit-testable. Since this only runs when the control is already known to be unreachable,+#: there is nothing to gain by being clever about whether it deserves a hover.+_HOVER_TARGET_JS = """+(selector) => {+ for (const el of document.querySelectorAll(selector)) {+ const r = el.getBoundingClientRect();+ if (r.width === 0 || r.height === 0) continue;+ const x = r.left + r.width / 2, y = r.top + r.height / 2;+ if (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight) continue;+ return { x, y };+ }+ return null;+}+"""+++def _reveal_by_hover(ctx: ActionContext, selector: str) -> tuple[float, float] | None:+ """Hover a hover-revealed control into existence, then return a point on it.++ THE CONTROL WAS NEVER COVERED. The sidebar's New chat button is+ `.sidebar-header-action`, which ships `opacity-0 pointer-events-none` and is revealed only by+ `.group/sidebar-header:hover` (or `:focus-visible`). With no mouse over the header it is a+ 20x20 box that is laid out, reported `visible` by every check Playwright makes, and transparent+ to every hit test -- so `click()` waits out its whole timeout and the hit-test spread reports+ "no point on the control hit-tests to it". Both are accurate and both are the wrong conclusion:+ nothing is covering it and the sidebar is not collapsed. The harness simply never did the half+ of the gesture that makes the control exist, and then substituted a page reload for the click.++ Moving the mouse to where the button IS suffices, and is what a person does. `pointer-events:+ none` means the pointer falls through to the group underneath, the group's `:hover` matches,+ and the button becomes solid under a mouse that is already on it. So this deliberately does not+ walk ancestors looking for the reveal group: hovering the control's own centre finds it by+ construction, and cannot pick the wrong one.++ Called ONLY after the ordinary hit test has already failed, so a control that is reachable at+ rest is never hovered and no stray mouse movement enters a measured window. Returns None when+ hovering does not make the control hit-testable, which is a real finding and is reported as+ one rather than papered over with a page load.+ """+ target = _ev(ctx, _HOVER_TARGET_JS, selector)+ if not isinstance(target, dict) or "x" not in target:+ return None+ try:+ ctx.page.mouse.move(target["x"], target["y"])+ except Exception: # noqa: BLE001+ return None+ for _ in range(_REVEAL_ATTEMPTS):+ ctx.page.wait_for_timeout(_REVEAL_SETTLE_MS)+ point = _reachable_point(ctx, selector)+ if point is not None:+ ctx.log(" the control is hover-revealed; hovered it first, as a user would")+ return point+ return None+- A click is preferred because it exercises the app's own handler. But Playwright's- actionability retries do not give up on an element that is visible, enabled and stable and- merely covered by something else, which is the sidebar's sticky group label over the New chat- button -- so the click burns its whole timeout and the action reports a rebuild that never- happened. The navigation is the same state transition by the route the app's own control uses.+def _click_or_navigate(+ ctx: ActionContext,+ selector: str,+ url: str,+ *,+ allow_navigate: bool = True,+) -> Transition:+ """Click the control a user would click; fall back to the URL it would produce, and SAY SO.++ A click is preferred because it exercises the app's own handler. Playwright's actionability+ retries do not give up on an element that is visible, enabled and stable and merely covered by+ something else, so the click burns its whole timeout. The navigation reaches the same app+ state, and for getting the scene somewhere it is a perfectly good tool.++ WHAT IT IS NOT is the same operation, and the caller is now told which one it got. Every+ caller must decide for itself whether a navigation still answers its question. `thread_reopen`+ decides that it does not, because a document reload and a subtree rebuild are the two things+ that action exists to tell apart.++ `allow_navigate = False` lets a caller decide that BEFORE the substitution rather than after+ it. Reading `path == "navigate"` afterwards is enough to keep the ROW honest and not enough to+ keep the SCENE intact: by then the page has already left, and for the call that leaves the+ thread that means every later slot in the film runs against an empty one. Declining up front+ returns `path = "failed"` with the same explanation and leaves the page exactly where it was.+ The default is `True`, so a caller that has not thought about it keeps the behaviour every+ caller had."""handle = ctx.page.query_selector(selector)+ click_error = f"no element matched {selector}"if handle is not None:try:+ attempt_at = time.monotonic()handle.click(timeout = 2000)- return True- except Exception: # noqa: BLE001- ctx.log(f" {selector} was not clickable; navigating instead")+ return Transition(ok = True, path = "click", started_at = attempt_at)+ except Exception as exc: # noqa: BLE001+ click_error = f"{selector} was not clickable: {type(exc).__name__}"+ # THE CENTRE IS COVERED, BUT THE CONTROL IS NOT. Try the rest of it, the way a user would.+ #+ # Playwright clicks the centre of an element and refuses when something else hit-tests+ # there. The sidebar's sticky group label overlaps the top of the New chat button, so the+ # centre is taken and the click times out -- but most of the button is uncovered and a+ # person clicks it every day without noticing. Giving up at the centre and calling the+ # control unreachable is the harness being more fragile than a user, and it cost this+ # action on every CI run.+ #+ # So the element's own box is hit-tested at a spread of points and the first one that+ # resolves to the control is clicked with a real mouse event. If NO point on the control+ # is reachable then it genuinely cannot be clicked, which is a finding worth reporting+ # rather than a reason to substitute a page load.+ point = _reachable_point(ctx, selector) or _reveal_by_hover(ctx, selector)+ if point is not None:+ try:+ attempt_at = time.monotonic()+ ctx.page.mouse.click(point[0], point[1])+ return Transition(+ ok = True,+ path = "click",+ reason = "clicked off-centre",+ started_at = attempt_at,+ )+ except Exception as exc: # noqa: BLE001+ click_error += f"; the off-centre click also failed: {type(exc).__name__}"+ else:+ click_error += "; no point on the control hit-tests to it, even after hovering it"+ ctx.log(+ f" {click_error}; "+ + ("navigating instead" if allow_navigate else "NOT navigating, the caller refused it")+ )+ if not allow_navigate:+ return Transition(+ ok = False,+ path = "failed",+ reason = (+ f"{click_error}, and the caller does not accept a page navigation as a substitute, "+ "so none was performed and the page was left where it was"+ ),+ )try:+ attempt_at = time.monotonic()ctx.page.goto(url, wait_until = "domcontentloaded", timeout = 60_000)- return True+ return Transition(ok = True, path = "navigate", reason = click_error, started_at = attempt_at)except Exception as exc: # noqa: BLE001ctx.log(f" navigation to {url} failed: {type(exc).__name__}: {exc}")- return False+ return Transition(+ ok = False,+ path = "failed",+ reason = f"{click_error}, and the navigation failed too: {type(exc).__name__}",+ )# ── 14. message menu ────────────────────────────────────────────────@@ -1629,8 +2339,52 @@ async (opts) => {"""+#: How long an action that needs a message's ACTION BAR will wait for the reply to finish.+#:+#: Studio hides the action bar while a message is generating, so "no More button on the last+#: assistant message" and "no Delete button (a running message hides it)" are the same fact+#: reported by two actions. The film schedules `message_menu` about four seconds after a+#: `send_turn` whose reply runs for roughly fourteen, so the menu was being asked for on a message+#: that was still being written, and the action reported NOT RUN on every CI run.+#:+#: Waiting is what a USER does, and it is the only thing that makes the action measurable at all:+#: there is no menu to open until the reply lands. Bounded by the slot's own budget so a reply+#: that never finishes cannot swallow the rest of the film, and the wait happens BEFORE the+#: operation the action times, so `menu_open_ms` is unaffected.+_ACTION_BAR_WAIT_FRACTION = 0.6+_ACTION_BAR_POLL_MS = 100+++def _wait_for_the_reply_to_land(ctx: ActionContext) -> bool:+ """True once no reply is generating, False if one still is when the budget runs out."""+ budget_ms = max(0.0, float(ctx.budget_ms or 0)) * _ACTION_BAR_WAIT_FRACTION+ deadline = time.monotonic() + budget_ms / 1000.0+ running = bool(_ev(ctx, "() => window.__sb.dom.isRunning()"))+ if not running:+ return True+ ctx.log(" a reply is still generating; waiting for it before asking for the action bar")+ while time.monotonic() < deadline:+ ctx.page.wait_for_timeout(_ACTION_BAR_POLL_MS)+ if not _ev(ctx, "() => window.__sb.dom.isRunning()"):+ return True+ return False++@register_action(name = "message_menu", default_budget_ms = 12000)def message_menu(ctx: ActionContext) -> ActionResult:+ # TWO WAITS, AND THEY COVER DIFFERENT THINGS. This one waits for the STREAM to stop, bounded by+ # a fraction of the slot's own budget, because a follow-up reply runs for seconds and Studio+ # unmounts the whole action bar for its whole duration -- far longer than the page-side wait+ # below is allowed to sit. `waitForButtonMs` then waits for the BAR TO MOUNT, which happens a+ # few hundred milliseconds after the reply settles, and which this one cannot see because+ # `isRunning()` is already false by then. Dropping either leaves a real NOT RUN on the table:+ # without the first, a fourteen second reply outlasts a 1.5 s page-side wait; without the+ # second, the slot asks for a control that has not been mounted yet.+ if not _wait_for_the_reply_to_land(ctx):+ return not_run(+ "a reply was still generating when the slot's budget ran out, and Studio hides the "+ "action bar on a generating message, so there was no menu to open"+ )raw = _ev(ctx,MENU_JS,@@ -1703,18 +2457,31 @@ async (opts) => {};}const target = D.lastAssistantMessage();- const before = D.messageCount();+ const before = D.threadTotal();+ const mountedBefore = D.messageCount();const started = performance.now();button.click();let ms = null;// isConnected on the captured node is O(1). Re-counting [data-role] every frame would put an// O(messages) query INSIDE the window being timed, growing like the signal.+ //+ // THE LIMIT OF isConnected, recorded rather than worked around: it goes false when the node+ // leaves the document, and a virtualised list unmounts a node for scrolling as readily as for+ // deleting. Nothing scrolls during this action, so in this scene the two cannot be confused --+ // but the timing is only trustworthy when the thread total ALSO dropped, which is what+ // `expect_ok` requires below. A `ms` with an unchanged total is a node that was unmounted, not+ // a message that was deleted, and it must never be read as a fast delete.while (performance.now() - started < timeoutMs) {if (target === null || !target.isConnected) { ms = performance.now() - started; break; }await window.__sbNextPaint();}+ // `after` is the THREAD TOTAL, paired with the `before` above it, and the mounted counts ride+ // alongside rather than replacing it: on a windowed mount `messageCount()` is the size of the+ // window and a recycled node would read as a delete. `waitedMs` is how long the bar was waited+ // for, which the row reports so a slot that opened too early is visible.return { ran: true, waitedMs, ms: ms === null ? null : Math.round(ms * 10) / 10,- before, after: D.messageCount() };+ before, after: D.threadTotal(),+ mountedBefore, mountedAfter: D.messageCount() };}"""@@ -1731,8 +2498,9 @@ def delete_message(ctx: ActionContext) -> ActionResult:return not_run(err)if not raw.get("ran"):return not_run(raw.get("reason", "the delete action did not run"))- # The [data-role] count DROPPED. A delete that detached the node but left the count is a- # different bug and must not read as a successful delete.+ # The THREAD TOTAL dropped. A delete that detached the node but left the thread the same+ # length is a different bug -- or, on a windowed mount, a node the virtualizer recycled -- and+ # must not read as a successful delete.ok = raw["ms"] is not None and raw["after"] < raw["before"]return ActionResult(ran = True,@@ -1741,6 +2509,8 @@ def delete_message(ctx: ActionContext) -> ActionResult:"messages_before": raw["before"],"messages_after": raw["after"],"dropped": raw["before"] - raw["after"],+ "mounted_before": raw.get("mountedBefore"),+ "mounted_after": raw.get("mountedAfter"),"action_bar_wait_ms": raw.get("waitedMs"),},timings = {"delete_ms": raw["ms"]},diff --git a/tests/studio/studiobench/scene/dom.js b/tests/studio/studiobench/scene/dom.jsindex 74c1183ff51..e9a0e751581 100644--- a/tests/studio/studiobench/scene/dom.js+++ b/tests/studio/studiobench/scene/dom.js@@ -79,6 +79,38 @@messageCount() {return qa("[data-role]").length;},+ // HOW LONG THE THREAD IS, as opposed to how much of it is mounted.+ //+ // On the shipped build these are the same number and this returns exactly what+ // messageCount() does, so nothing about an existing run changes. They stop being the same+ // number the moment an arm mounts a window, and at that point every before/after assertion in+ // actions.py -- send_turn's "the thread grew", delete's "the count dropped", thread_reopen's+ // "it came back with the same messages" -- is asking about the THREAD and being answered+ // about the window. Under a windowed mount those three all read the wrong answer in the same+ // direction: the window refills as fast as it empties, so a delete that worked reports+ // `after == before` and fails, and a send that worked reports the same and fails.+ //+ // aria-setsize is where a windowed list is already required to publish this: WAI-ARIA says a+ // list whose items are not all in the DOM must carry aria-setsize and aria-posinset. So this+ // is not a private channel invented for the benchmark, it is the accessible name for the+ // quantity, and an arm that does not provide it is one a screen reader cannot navigate.+ threadTotal() {+ // On the message, or on the row wrapper a virtualizer positions it in. See the same walk in+ // runtime/readiness.py: the ordinal belongs on the element that is a member of the set, and+ // for a windowed list that is the positioned row rather than the message inside it.+ const first = q("[data-role]");+ const owner = first ? first.closest("[aria-setsize]") : q("[aria-setsize]");+ if (owner) {+ const n = Number(owner.getAttribute("aria-setsize"));+ if (Number.isFinite(n) && n >= 0) return n;+ }+ return qa("[data-role]").length;+ },+ // True when the thread is publishing a total that is larger than what it has mounted, i.e.+ // this really is a windowed mount and not merely a short thread.+ isWindowed() {+ return D.threadTotal() > qa("[data-role]").length;+ },assistantMessages() {return qa('[data-role="assistant"]');},@@ -87,6 +119,27 @@return all.length ? all[all.length - 1] : null;},+ // ── following the stream ─────────────────────────────────────+ //+ // The jump-to-bottom control, which thread.tsx renders permanently and hides with+ // `invisible` when the intent-aware autoscroll reports itself at the bottom. Reading the+ // app's own state rather than recomputing it means the harness and the app cannot disagree+ // about whether the thread is pinned, which is the whole question here.+ jumpToBottomButton() {+ return q(".aui-thread-scroll-to-bottom");+ },+ appSaysAtBottom() {+ const jump = D.jumpToBottomButton();+ // `null`, NOT `false`, when the control is absent. A build that does not render it has not+ // told us it is scrolled up; it has told us nothing, and the two must not be summed.+ return jump ? jump.classList.contains("invisible") : null;+ },+ distanceFromBottom() {+ const vp = D.viewport();+ if (!vp) return null;+ return Math.round(vp.scrollHeight - vp.clientHeight - vp.scrollTop);+ },+// ── reasoning ────────────────────────────────────────────────reasoningRoots() {return qa('[data-slot="reasoning-root"]');@@ -289,6 +342,27 @@assistant_chars: D.assistantChars(),viewport_scroll_height: (D.viewport() || {}).scrollHeight || null,viewport_client_height: (D.viewport() || {}).clientHeight || null,+ // ── DOES THE THREAD STILL FOLLOW THE STREAM? ──────────────+ //+ // Three readings, taken with every census, so the answer exists for every window of the+ // film rather than being reconstructed afterwards from timings.+ //+ // This is here because of a specific way a virtualized arm can produce a beautiful and+ // meaningless frame rate. If the thread stops following, the message being streamed+ // drifts out of the viewport; a windowed list then UNMOUNTS it, and the streaming cost+ // collapses to almost nothing. That is not a measurement of virtualization, it is a+ // measurement of not rendering the thing being measured, and it flatters the arm in+ // exactly the direction this campaign keeps having to catch. An fps number from such a+ // run must never be readable without this beside it.+ //+ // `app_at_bottom` is the app's OWN state, not arithmetic: thread.tsx renders the+ // scroll-to-bottom control permanently and hides it with `invisible` exactly when+ // use-intent-aware-autoscroll considers itself at the bottom. `distance_from_bottom` is+ // kept alongside because a virtualizer working from estimated row heights can sit a few+ // pixels off while the app is quite correctly pinned.+ viewport_scroll_top: (D.viewport() || {}).scrollTop || null,+ distance_from_bottom: D.distanceFromBottom(),+ app_at_bottom: D.appSaysAtBottom(),};out.census_cost_ms = Math.round((performance.now() - started) * 100) / 100;return out;@@ -304,4 +378,270 @@};window.__sb.dom = D;++ // ── the follow-the-stream sampler ──────────────────────────────────────────────────────────+ //+ // WHY THIS IS NOT DONE FROM THE DRIVER. The question is "while a reply was streaming, was the+ // thread pinned to the bottom", and the stream runs during the gap windows -- which are+ // measured windows whose whole purpose is to observe the page doing nothing but stream. A+ // `page.evaluate` per sample would put a CDP round trip and a forced style read inside exactly+ // those windows, four times a second, which is the same class of mistake as the census that+ // used to run inside the action windows.+ //+ // So it samples in the page and is READ ONCE PER CELL, outside every window. A 250ms timer,+ // four ticks a second: frames.js documents a 1ms timer as costing nothing at ~150 ticks a+ // second, so this is two orders of magnitude below that. It does no layout it has not already+ // caused -- `classList.contains` is free, and `distanceFromBottom` is only read when a run is+ // in progress.+ //+ // WHAT IT IS FOR. A thread that stops following unmounts the message being streamed, and the+ // streaming cost then collapses because the renderer is no longer rendering the thing under+ // measurement. That produces a superb frame rate and means nothing. `pinned_fraction` is the+ // reading that makes an fps number from a windowed arm readable at all.+ // THE COUNTERS SURVIVE A NAVIGATION, via sessionStorage.+ //+ // They did not, and the symptom was a confident "NOT MEASURED" on the arm that behaved best.+ // The film ends with `thread_reopen`, which falls back to `page.goto` when the New chat control+ // is covered; a full document navigation destroys the JS context and re-runs the init scripts,+ // so a sampler that lived only in memory came back at zero and the whole cell's streaming+ // phase was reported as never sampled. The treatment arm, whose thread_reopen did not run at+ // all, kept its counters and looked like the only arm with data.+ //+ // sessionStorage is per-origin and per-tab and outlives a same-origin navigation, which is+ // exactly the lifetime wanted: one cell, one page, however many documents it passes through.+ // Saved on pagehide rather than on every tick, so the cost is one serialisation per navigation+ // rather than four a second.+ const FOLLOW_KEY = "__sb_follow_v1";+ const restore = () => {+ try {+ const raw = window.sessionStorage.getItem(FOLLOW_KEY);+ return raw ? JSON.parse(raw) : null;+ } catch (e) {+ return null;+ }+ };+ const F = Object.assign({+ samples: 0,+ running_samples: 0,+ running_pinned: 0,+ running_unknown: 0,+ max_distance_while_running: 0,+ suspended_samples: 0,+ detached_samples: 0,+ yanked_back_samples: 0,+ stream_samples: 0,+ reattachments: 0,+ // Set once the thread is seen to fall behind while a run is in progress, and never cleared.+ // A thread that drifts away and is later yanked back to the bottom has still failed the+ // contract, and an end-of-cell reading would show it pinned.+ ever_fell_behind: false,+ }, restore() || {});+ window.addEventListener("pagehide", () => {+ try {+ window.sessionStorage.setItem(FOLLOW_KEY, JSON.stringify(F));+ } catch (e) {+ // A full sessionStorage is not worth losing the page over; the reading degrades to+ // "not measured", which is the honest outcome and is already handled.+ }+ });+ const FOLLOW_TICK_MS = 250;+ // How far from the bottom still counts as following. Generous on purpose: a virtualizer+ // working from estimated row heights corrects them as real rows are measured, so it can sit a+ // little short of the exact bottom while behaving perfectly. 64px is under two lines of text,+ // so it cannot hide a thread that has stopped following.+ const FOLLOW_TOLERANCE_PX = 64;+ // TWO PHASES, BECAUSE THE INTENT CONTRACT HAS TWO HALVES.+ //+ // The contract (plans/proud-wiggling-falcon.md): autoscroll follows a stream, AND a user who+ // has scrolled up is never yanked down. Those are opposite requirements about the same+ // scrollTop, so one number cannot score both -- and the first version of this sampler tried,+ // producing 47% to 50% pinned on BOTH arms with an identical 6,615px worst drift. That figure+ // is the film: `scroll_during_generation` drags the viewport thousands of pixels up, twice,+ // while the reply is still arriving, and the app then CORRECTLY declines to drag it back. The+ // sampler was recording the app honouring the second half of the contract and scoring it as a+ // failure of the first.+ //+ // ATTACHED (before the harness scrolls anywhere): the thread must stay pinned as content+ // arrives. This is "does it follow", and it is what the gate scores.+ // DETACHED (after the harness has deliberately scrolled): the thread must NOT come back to the+ // bottom on its own. Any sample that finds it pinned again while still streaming is the app+ // yanking the user down, which is the other half of the contract and is recorded as its own+ // finding rather than mixed into the fraction.+ let detached = false;+ let suspended = 0;+ // WHICH RUN THE USER SCROLLED AWAY FROM, and it is the difference between a yank and a return.+ //+ // `resume()` below clears `detached` only when the gesture itself ended at the bottom. On the+ // real films it never does: `SCROLL_JS` jumps to the bottom and then steps 14 x 420px away from+ // it, so at any rung whose thread is taller than 5,880px the gesture ends thousands of pixels+ // up and `detached` is latched for the rest of the cell. The film then starts TWO MORE RUNS of+ // its own -- `stop_generation` and `send_turn` both submit a turn -- and the app pins to the+ // bottom for them, which session.py already documents as intended behaviour rather than a+ // violation. Every one of those samples was landing in the detached branch, counted as a yank,+ // and excluded from `attached_fraction_of_stream`.+ //+ // Measured, at head, across every 100K payload in outputs/: attached_fraction 0.07 to 0.15 with+ // reattachments 0, on the BASE arm as well as the treatment and on pure null controls, so the+ // `follows_the_stream` gate failed every 100K cell of every run including two copies of the+ // shipped build. It passed only on the 1K smoke film, where the thread is short enough that the+ // gesture's reversal happens to land back at the bottom -- i.e. the verdict was a property of+ // the thread's height, not of the app.+ //+ // So a run the user STARTED is a fresh expression of intent to be at the end, exactly as+ // returning to the bottom is. Re-attachment is granted only when a run that began AFTER the+ // gesture is also OBSERVED at the bottom: an app that declines to pin stays detached and is+ // scored as before, and a pin during the SAME run the user scrolled away from is still a yank.+ let runSeq = 0;+ let wasRunning = false;+ let detachedAtRun = 0;+ setInterval(() => {+ F.samples += 1;+ // Read BEFORE the suspended early-return, or a run that starts and ends inside a deliberate+ // gesture is never seen and the run after it is mistaken for the one the user scrolled away+ // from.+ const running = D.isRunning();+ if (!running) wasRunning = false;+ else if (!wasRunning) { wasRunning = true; runSeq += 1; }+ if (suspended > 0) { F.suspended_samples += 1; return; }+ if (!running) return;+ const app = D.appSaysAtBottom();+ const distance = D.distanceFromBottom();+ // "At the bottom" by the app's own answer, with the geometry standing in only when the build+ // renders no jump control. `app === false` is the app saying no and is never overridden.+ const atBottom =+ app === true || (app === null && distance !== null && distance <= FOLLOW_TOLERANCE_PX);+ if (detached) {+ if (runSeq !== detachedAtRun && atBottom) {+ // A run the user started, found at the end: following again.+ detached = false;+ F.reattachments += 1;+ } else {+ F.detached_samples += 1;+ F.stream_samples += 1;+ // Pinned again, without anybody asking, inside the run they scrolled away from.+ if (atBottom) F.yanked_back_samples += 1;+ return;+ }+ }+ F.running_samples += 1;+ F.stream_samples += 1;+ if (distance !== null && distance > F.max_distance_while_running) {+ F.max_distance_while_running = distance;+ }+ if (app === null) {+ F.running_unknown += 1;+ if (distance !== null && distance > FOLLOW_TOLERANCE_PX) F.ever_fell_behind = true;+ return;+ }+ if (app) {+ F.running_pinned += 1;+ } else {+ F.ever_fell_behind = true;+ }+ }, FOLLOW_TICK_MS);++ window.__sb.follow = {+ // Called by any action that moves the viewport on purpose. Nested-safe, because more than one+ // scope may legitimately be open at once.+ // Called by any action that moves the viewport on purpose. Nested-safe. The FIRST suspend+ // also latches `detached`: from that moment the user has expressed an intent to be somewhere+ // other than the bottom, and everything after it is scored against the second half of the+ // contract instead of the first.+ // `detachedAtRun` is stamped on every suspend rather than only the first, so a second gesture+ // during a later run detaches from THAT run: without it, scrolling away during run 3 would be+ // compared against run 1 and the very next at-bottom sample would re-attach.+ suspend() { suspended += 1; detached = true; detachedAtRun = runSeq; },+ resume() {+ suspended = Math.max(0, suspended - 1);+ // RE-ATTACH IF THE GESTURE LEFT US AT THE END, and this is not a nicety.+ //+ // `detached` used to latch on the first suspend and never clear, so from the harness's+ // first deliberate scroll onwards every remaining sample went to the detached branch and+ // `running_samples` stopped growing. In the shipped film that scroll happens 1.5s into an+ // 18s opening stream and is followed by two more streamed turns, so the follow verdict was+ // computed from the first ~3s and covered 13% of the streaming time -- while reading, and+ // being reported as, "the thread follows the stream". Measured: running_samples 11,+ // detached_samples 72.+ //+ // The contract is about INTENT, and intent is re-expressed by coming back: a user who+ // scrolls up is detached until they return to the end, at which point they are following+ // again. That is the same re-attachment Studio's own intent-aware autoscroll implements.+ // Only checked here, on the way out of a deliberate gesture, so the app silently pulling+ // the viewport down on its own is still scored as a yank rather than laundered into a+ // re-attachment.+ if (suspended === 0 && detached) {+ const app = D.appSaysAtBottom();+ const distance = D.distanceFromBottom();+ // EITHER answer is enough, and the geometry is not merely a fallback for a build with no+ // jump control. The control's `invisible` class is updated from a scroll LISTENER, and+ // scroll events are dispatched asynchronously, so a gesture that has just returned the+ // viewport to the end can reach this line while the class still says otherwise. Reading+ // the class alone loses the re-attachment to a race and quietly restores the old+ // never-reattach behaviour on exactly the fast gestures the harness performs.+ // `distanceFromBottom()` is computed from scrollTop and cannot be stale.+ if (app === true || (distance !== null && distance <= FOLLOW_TOLERANCE_PX)) {+ detached = false;+ F.reattachments += 1;+ } else {+ // Still away from the end. Re-stamp against the run in flight NOW, not the one that was+ // in flight when the gesture began: a gesture long enough to span a run boundary would+ // otherwise look like a scroll away from the previous run and be re-attached by the very+ // first sample of the current one.+ detachedAtRun = runSeq;+ }+ }+ },+ read() {+ const measured = F.running_samples - F.running_unknown;+ return {+ follow_attempted: true,+ samples: F.samples,+ running_samples: F.running_samples,+ running_pinned: F.running_pinned,+ running_unknown: F.running_unknown,+ suspended_samples: F.suspended_samples,+ detached_samples: F.detached_samples,+ yanked_back_samples: F.yanked_back_samples,+ // The second half of the intent contract, as its own verdict.+ yanked_after_scroll: F.yanked_back_samples > 0,+ // null, not 1.0, when nothing was ever sampled mid-run. A cell whose stream finished+ // before the first tick has not demonstrated that the thread follows; it has+ // demonstrated nothing, and 1.0 would read as a pass.+ pinned_fraction: measured > 0 ? F.running_pinned / measured : null,+ pinned_fraction_reason:+ measured > 0 ? null : "no sample was taken while a reply was streaming",+ // HOW MUCH OF THE STREAM THIS VERDICT ACTUALLY COVERS. `pinned_fraction` is computed+ // over the attached phases only, so without this it can read 1.0 on a cell where the+ // thread was attached for three seconds of an eighteen-second stream. Reported beside it+ // so the one cannot be quoted without the other.+ stream_samples: F.stream_samples,+ attached_fraction_of_stream:+ F.stream_samples > 0 ? F.running_samples / F.stream_samples : null,+ reattachments: F.reattachments,+ max_distance_while_running: F.max_distance_while_running,+ ever_fell_behind: F.ever_fell_behind,+ tolerance_px: FOLLOW_TOLERANCE_PX,+ tick_ms: FOLLOW_TICK_MS,+ };+ },+ reset() {+ try { window.sessionStorage.removeItem(FOLLOW_KEY); } catch (e) {}+ F.samples = 0;+ F.running_samples = 0;+ F.running_pinned = 0;+ F.running_unknown = 0;+ F.max_distance_while_running = 0;+ F.suspended_samples = 0;+ F.detached_samples = 0;+ F.yanked_back_samples = 0;+ F.stream_samples = 0;+ F.reattachments = 0;+ F.ever_fell_behind = false;+ suspended = 0;+ detached = false;+ runSeq = 0;+ wasRunning = false;+ detachedAtRun = 0;+ },+ };})();diff --git a/tests/studio/studiobench/scene/parity.js b/tests/studio/studiobench/scene/parity.jsindex 32348702db6..bc497fbad19 100644--- a/tests/studio/studiobench/scene/parity.js+++ b/tests/studio/studiobench/scene/parity.js@@ -43,10 +43,38 @@// selection, scroll position (deliberately normalised), `<input>` live values typed by a user// (the DOM attribute is not the property), shadow DOM, and any state kept only in JS.//+// THAT LIST HAS NOW BEEN MEASURED RATHER THAN JUST ASSERTED, and the result is worse than the+// wording above suggests. A concurrent campaign measuring the sidebar drag ran this digest against+// a real, visible change and got 0 of 34 differing pairs -- and its null control also returned 0 of+// 34, so the instrument was not discriminating in either direction on that change. Three+// purpose-built captures (sidebar-inclusive structure, sidebar inline style, custom-property reach)+// each found the same change 34 of 34 with the null at zero. The two blind spots that mattered were+// the two named above: the sidebar is outside the root, and computed layout is never read.+//+// So a PARITY OK verdict from this file means NO THREAD-STRUCTURE CHANGE WAS DETECTED. It does not+// mean the UI is unchanged, and the two are far enough apart that the second should never be+// written down on the strength of the first.+//// Extending this into a real visual diff is the screenshot pair's job, not this one's. The point// of the digest is breadth at near-zero cost per action, and its limits are stated here so nobody// reads "18 actions, 0 differences" as "the UI is pixel-identical". It is not that claim.//+// ── AND A NOTE ON ANY SCAN THAT CAN RETURN ZERO ──────────────────────────────────────────────+//+// `styleProbe` below walks a hand-written selector list. If Studio renames a class the list goes+// quiet, matches nothing, and its digest becomes the hash of an empty string -- identical on both+// arms, reported as a MATCH. A scan of nothing must never be reported as agreement, so+// `compare_styles` refuses a zero-element probe instead of matching it, and `elements` travels+// with every reading so the count can be checked rather than assumed.+//+// The same team hit the general form of this and it is worth recording: their CSSOM scan returned+// a clean zero because CSS nesting gives every `CSSStyleRule` a truthy but empty `cssRules`, so+// code that treats a truthy `cssRules` as "this is a grouping rule, recurse" silently skips every+// declaration in the document. They caught it only because they had gated on a positive control.+// Nothing in this file walks the CSSOM today, so that specific bug is not present here -- but any+// scan added later that can legitimately return zero needs a positive control, and a zero without+// one should not be believed.+//// ── WHAT IS NORMALISED AWAY, and why each one has to be ──────────────────────────────────────//// A digest that trips on things that legally differ between two runs of the SAME build is worse@@ -92,6 +120,12 @@// Attributes that carry no rendered meaning at all.const IGNORED_ATTRS = new Set(["data-react-checksum", "data-reactroot"]);+ // VIRTUALIZATION BOOKKEEPING. Dropped -- name and value -- from the VISIBLE-REGION digest only,+ // and passed in by that caller rather than applied here, because the two comparisons want+ // different things from these two attributes. The whole argument is at the call site, in+ // `parityVisible.capture()`.+ const VIRTUALIZATION_ATTRS = new Set(["aria-posinset", "aria-setsize"]);+// Attributes whose value is a URL. The origin is stripped and the path kept, so a genuinely// different asset still moves the digest while the arm's own port does not.const URL_ATTRS = new Set(["src", "href", "srcset", "action", "poster", "data-src", "formaction"]);@@ -138,7 +172,11 @@return normText(raw);};- const signature = (root) => {+ // `dropAttrs`, when given, is a Set of attribute names this digest does not compare AT ALL --+ // neither presence nor value, unlike VOLATILE_ATTRS which keeps the presence. Optional and off+ // by default: every existing caller (the whole-thread digest, the per-message rows, the overlays+ // and the node-driven unit tests) passes nothing and gets exactly what it got before.+ const signature = (root, dropAttrs) => {if (!root) return "";const parts = [];const walk = (el, depth) => {@@ -150,6 +188,7 @@const names = [];for (const attr of el.attributes) {if (IGNORED_ATTRS.has(attr.name)) continue;+ if (dropAttrs && dropAttrs.has(attr.name)) continue;names.push(attr.name);}names.sort();@@ -245,6 +284,396 @@const D = () => (window.__sb.dom || {});+ // ── VISIBLE-REGION PARITY ────────────────────────────────────────────────────────────────────+ //+ // THE POLICY THIS SERVES. All changes must preserve UI and UX idempotency, with two exemptions:+ // a difference may be accepted deliberately when performance improves dramatically, and a+ // difference that exists only OFF SCREEN is fine by definition, because rendering only what is+ // visible is an accepted technique rather than a parity violation.+ //+ // The whole-document digest above cannot express the second exemption. It compares everything+ // that is in the DOM, so ANY deferred off-screen work fails it by construction -- virtualization,+ // deferred syntax highlighting, content-visibility, lazy images. Refusing such a pair as+ // NOT_APPLICABLE was the right instinct and it withholds a verdict. This supplies the verdict.+ //+ // THE CLAIM IT SUPPORTS, exactly: every message that was visible in the viewport at any point+ // during the action is present on both arms and identical between them, and every difference+ // lies outside the viewport.+ //+ // ── TWO BOUNDARY DECISIONS, MADE EXPLICITLY ──────────────────────────────────────────────────+ //+ // These are where a visible-region check goes wrong quietly, so they are decided here in the+ // open rather than left implicit in whatever the code happens to do.+ //+ // 1. PARTIAL INTERSECTION COUNTS AS VISIBLE, AND THE ELEMENT IS DIGESTED IN FULL.+ // A message one pixel into the viewport is visible to the user. The alternative -- digesting+ // only the part inside the viewport -- is not definable on a DOM subtree without reading+ // geometry per node, and reading geometry is the one thing this must not do (see below). So+ // the whole element is compared. The error this admits is a FALSE ALARM: a difference in the+ // off-screen tail of a partly-visible message is reported as a visible difference. The error+ // it refuses to admit is a false pass. Given a parity gate, that is the right way round.+ //+ // 2. ANYTHING VISIBLE AT ANY POINT DURING THE ACTION IS COMPARED, not just at the end.+ // An action that scrolls makes messages visible and then hides them again; a single sample at+ // the close of the window would compare the DOM the scroll happened to land on and silently+ // ignore everything the user actually saw on the way. So the observer is installed BEFORE the+ // window opens and the compared set is the UNION of everything that ever intersected. The+ // per-message digest is still the one taken at the close, which is a real limitation and is+ // named as such in `now_visible` versus `ever_visible`: a message that was visible mid-action+ // and has since changed is compared in its final state.+ //+ // ── WHY INTERSECTIONOBSERVER AND NOT GEOMETRY ────────────────────────────────────────────────+ //+ // `getBoundingClientRect()` / `getClientRects()` on content inside a `content-visibility` locked+ // subtree makes Chromium render that subtree in order to answer, so a geometry-based visibility+ // probe unlocks exactly what it came to observe and then reports that nothing was skipped. That+ // is measured, not theoretical: one session reported 0 off-screen unrendered roots while the+ // event counter recorded 22 simultaneously in the skipped state. See the content-visibility trap+ // section of CONTRIBUTING-perf.md.+ //+ // IntersectionObserver is the correct instrument and not merely a safe one: it is the same+ // mechanism Blink's own relevance machinery uses to decide whether a `content-visibility: auto`+ // subtree is skipped, so observing with it neither forces rendering nor perturbs the decision.+ // NOTHING in this section may call a geometry method on a candidate element.+ const VIS = {+ obs: null, mut: null, ever: new Set(), watching: false,+ // Nodes already counted in `unplaced`, so a row offered and refused several times before it+ // mounts does not inflate the diagnostic. NOT a "do not look at this again" set: placement is+ // re-read on every offer, because a recycled row changes position. See `observeOne`.+ unplacedSeen: new WeakSet(),+ // Rows that were observed and could NOT be placed in the thread at all: no `aria-posinset`+ // and not among the messages the DOM currently holds. Such a row is stamped with no ordinal,+ // so it is silently absent from `ever_visible`, and a silence that cannot be counted is the+ // failure this whole file is written against. Reported with the capture.+ unplaced: 0,+ // The batch-scoped position index. See `positionIndex`.+ index: null,+ };++ const ordinalOf = (el, position) => {+ // The message's position in the THREAD, not in the mounted list. This is what makes a windowed+ // arm comparable with a fully mounted one at all: mounted index 0 is message 10 on one arm and+ // message 1 on the other, so a per-index comparison compares different messages and reports+ // every row as changed. `aria-posinset` is the windowed arm's own claim about position; a+ // fully mounted thread does not publish it and does not need to, because there the DOM order+ // IS the thread order, which is what `position` carries.+ const owner = el.closest ? el.closest("[aria-posinset]") : null;+ if (owner) {+ const n = Number(owner.getAttribute("aria-posinset"));+ if (Number.isFinite(n)) return n;+ }+ return position;+ };++ // THE POSITION INDEX, AND WHY THE FALLBACK ORDINAL IS NOT A COUNTER.+ //+ // A row publishing no `aria-posinset` is stamped with its position among the thread's messages+ // in the DOM AS IT STANDS. That has to be resolved when the row is OBSERVED rather than when an+ // entry is delivered, which is the reason the ordinal is stamped onto the node in the first+ // place: by delivery time the row may have been unmounted and `closest()` would answer nothing.+ //+ // A LIFETIME COUNT OF OBSERVED NODES IS NOT THAT POSITION, and the gap between them was a+ // measured failure rather than a tidiness point. `thread_reopen` makes a fully mounted arm+ // remove and recreate every message row inside one document. Those rebuilt rows legitimately+ // publish no `aria-posinset` -- only a windowed arm publishes one -- so a counter that had+ // already seen the thread's N rows stamped the rebuilt ones N+1..2N, while the windowed arm on+ // the other side of the A/B stamped its real 1..N. `compare_visible` then saw two disjoint+ // visible sets and reported "the two arms put DIFFERENT MESSAGES on screen" for a rebuild that+ // was identical, failing thread_reopen on every base-versus-windowed pair.+ //+ // THE COST, WHICH IS WHY A COUNTER WAS TEMPTING. `observeAdded` runs inside the MEASURED action+ // window, so an O(document) lookup per mutation is workspace task #102 exactly: the instrument+ // charging its own walk to the action, on a DOM whose size is the quantity under investigation.+ // Three things keep that walk off the per-mutation path:+ //+ // 1. `aria-posinset` is read FIRST, so a windowed arm -- the only kind that mounts rows by the+ // hundred as it scrolls -- never builds an index at all.+ // 2. The index is built at most ONCE PER MUTATION BATCH, and only by a batch that actually+ // mounted a message element. A stream is text churn inside rows that are already mounted:+ // it adds no elements, so it builds nothing, which is what+ // `test_the_top_up_is_proportional_to_the_mutation_not_to_the_document` pins.+ // 3. It is read from the live DOM inside the callback, i.e. after every mutation in the batch+ // has been applied, so ONE read describes the batch's settled state rather than some+ // intermediate one. A rebuild that removes N rows and adds N rows in one commit is read+ // once, and reads N rows rather than 2N.+ //+ // What is left paying for it is an arm publishing no ordinals that mounts rows mid-action:+ // send_turn's one or two new messages, and thread_reopen's single rebuild. That is a handful of+ // document reads per action window, in exchange for the ordinals being right.+ const positionIndex = () => {+ if (VIS.index) return VIS.index;+ const nodes = (D().messages && D().messages()) || [];+ const map = new Map();+ for (let i = 0; i < nodes.length; i++) map.set(nodes[i], i + 1);+ VIS.index = map;+ return map;+ };++ //: `position` is the row's 1-based position among the thread's messages when the caller already+ //: knows it -- the full scan below holds the whole ordered list and needs no index. Left+ //: undefined, the position is resolved from the index, and only when no ordinal was published.+ const observeOne = (el, position) => {+ if (!VIS.obs) return;+ let ord = ordinalOf(el, typeof position === "number" ? position : null);+ if (ord === null) ord = positionIndex().get(el) || 0;+ // The ordinal is stamped on the node, because by the time an entry is delivered the node may+ // have been unmounted and `closest()` would return nothing.+ if (ord > 0) {+ // RE-READ RATHER THAN WRITE ONCE. A placed node used to be marked `seen` and skipped for the+ // rest of the window, which assumed a row's position in the thread cannot change while the+ // node lives. A virtualizer that RECYCLES rows breaks that assumption on purpose: it hands+ // the same node to another item and renumbers it. The stamp then stayed at the old ordinal+ // for the rest of the run, so the row's content was digested under a position it no longer+ // held, and the message it now showed was never reported visible at all.+ //+ // Re-reading is bounded work. The full scan runs once; every other call arrives from+ // `observeAdded`, which walks only what a mutation added, and `positionIndex` is built at+ // most once per batch.+ const had = el.__sbOrdinal;+ el.__sbOrdinal = ord;+ if (typeof had === "number" && had !== ord) {+ // A RENUMBERED ROW THAT NEVER STOPPED INTERSECTING REPORTS NOTHING. IntersectionObserver+ // delivers on a CHANGE of intersection, and this node's intersection did not change --+ // only its identity did -- so `ever` would never learn the new ordinal. Re-registering the+ // target makes the observer deliver an initial entry for it, which is the documented+ // behaviour of `observe()` and the only way to ask "is this thing on screen right now"+ // without calling a geometry method, which this section may not do.+ VIS.obs.unobserve(el);+ }+ } else {+ // NO ORDINAL RATHER THAN A MADE-UP ONE. A row that publishes nothing and is not in the+ // thread's message list has no position this instrument can honestly claim, and a guessed+ // one lands in `ever_visible` as a message the other arm never showed.+ //+ // NOT MARKED `seen`, WHICH IS THE WHOLE POINT. Marking it here is what made an unplaced row+ // able to hide a VISIBLE one. A row is unplaceable when it is observed while detached --+ // added and removed inside one task, so no paint could have shown it -- and a virtualizer+ // that RECYCLES DOM nodes hands that same node back on a later batch, mounted and about to+ // be shown. With the node already in `seen` the early return fired, it was never stamped,+ // and every intersection it went on to report was dropped for want of an ordinal: visible+ // on this arm, absent from `ever_visible`, and `compare_visible` free to call MATCH on the+ // strength of the rows that did place. Left out of `seen` it is simply placed on the batch+ // that mounts it, which is the batch that can place it.+ //+ // Counted once per node all the same. `unplacedSeen` is a separate WeakSet so a node that+ // is offered and refused several times before it mounts does not inflate the diagnostic+ // into a number nobody can interpret.+ if (!VIS.unplacedSeen.has(el)) {+ VIS.unplacedSeen.add(el);+ VIS.unplaced += 1;+ }+ }+ // Idempotent by specification: `observe()` on a target already being observed returns without+ // adding a second registration, so re-offering an unplaced row costs nothing.+ VIS.obs.observe(el);+ };++ //: The FULL scan. O(the document), so it runs exactly once, when the observer is installed --+ //: which happens before the measured window opens.+ const observeAll = () => {+ if (!VIS.obs) return;+ const nodes = (D().messages && D().messages()) || [];+ for (let i = 0; i < nodes.length; i++) observeOne(nodes[i], i + 1);+ };++ // THE TOP-UP, AND WHY IT IS NOT A RESCAN.+ //+ // A windowed list mounts rows as it scrolls, so rows appearing after the observer was installed+ // have to be picked up or a windowed arm is only ever asked about what it happened to have+ // mounted at the start. The obvious way to do that is to re-run the full scan from a+ // MutationObserver -- and the MutationObserver runs DURING the measured action window, so a+ // full `querySelectorAll` per mutation batch would charge an O(document) walk to the action,+ // once per batch, on a 64,000-element DOM, growing with exactly the quantity under+ // investigation. That is workspace task #102 verbatim: the census and the parity digest running+ // inside the window, which reported delete_message at 14.3 fps when it costs 49.0.+ //+ // So this walks only what was ADDED. `addedNodes` is small by construction -- a virtualizer+ // mounts one or two rows per scroll step -- and the cost is proportional to the mutation rather+ // than to the document. The one exception is stated in full at `positionIndex` above: an arm+ // that publishes no ordinals needs the thread's current message list to place a row it just+ // mounted, and that list is read ONCE for the whole batch and never once per row.+ const observeAdded = (records) => {+ // ONE INDEX PER BATCH AT MOST, and none at all for a batch that mounts nothing needing one.+ // Dropped again on the way out so the next batch cannot be answered from a stale list: rows+ // mount and unmount between batches, and a position read from the previous DOM is precisely+ // the wrong answer -- the same class of mistake as the lifetime counter this replaced.+ VIS.index = null;+ for (const rec of records) {+ // A RENUMBERED ROW ARRIVES AS ITS OWN TARGET, not in anybody's `addedNodes`. The ordinal+ // lives on `[aria-posinset]`, which `ordinalOf` reaches with `closest()`, so the row that+ // has to be re-placed is the target's message descendant, or the target itself when the+ // attribute is on the message.+ if (rec.type === "attributes") {+ const t = rec.target;+ if (!t || t.nodeType !== 1) continue;+ if (t.hasAttribute && t.hasAttribute("data-role")) observeOne(t);+ if (t.querySelectorAll) {+ for (const inner of t.querySelectorAll("[data-role]")) observeOne(inner);+ }+ continue;+ }+ const added = rec.addedNodes;+ for (let i = 0; i < added.length; i++) {+ const node = added[i];+ if (!node || node.nodeType !== 1) continue;+ if (node.hasAttribute && node.hasAttribute("data-role")) {+ observeOne(node);+ }+ // A row wrapper arrives with the message inside it, so the added node is the ancestor.+ // Bounded by the added subtree, never by the document.+ if (node.querySelectorAll) {+ for (const inner of node.querySelectorAll("[data-role]")) {+ observeOne(inner);+ }+ }+ }+ }+ VIS.index = null;+ };++ window.__sb.parityVisible = {+ watch() {+ try {+ const vp = D().viewport && D().viewport();+ if (!vp) return { visible_attempted: false, reason: "no thread viewport" };+ if (VIS.watching) return { visible_attempted: true, already: true };+ VIS.ever = new Set();+ VIS.unplacedSeen = new WeakSet();+ VIS.unplaced = 0;+ VIS.index = null;+ VIS.obs = new IntersectionObserver((entries) => {+ for (const entry of entries) {+ if (!entry.isIntersecting) continue;+ const ord = entry.target.__sbOrdinal;+ if (typeof ord === "number") VIS.ever.add(ord);+ }+ }, { root: vp, threshold: 0 });+ observeAll();+ // childList, plus ONE attribute by name, and no character-data records. A row ENTERING the+ // DOM is most of what needs observing, and a row leaving it has already contributed to+ // `ever`. Text changing inside a mounted row -- which is what a stream is -- must not+ // reach this callback at all, and with `attributeFilter` naming a single attribute it+ // cannot: a stream mutates text, not `aria-posinset`.+ //+ // `aria-posinset` is here because it is the one attribute whose change means the row is a+ // DIFFERENT MESSAGE. A virtualizer that recycles a still-connected row renumbers it in+ // place, which is not a childList mutation, so without this the renumbering is invisible+ // and the node keeps a stamp that now names the wrong message. Filtered to that name the+ // callback fires when a windowed arm re-uses a row and at no other time.+ VIS.mut = new MutationObserver(observeAdded);+ VIS.mut.observe(vp, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: ["aria-posinset"],+ });+ VIS.watching = true;+ return { visible_attempted: true, already: false };+ } catch (e) {+ return { visible_attempted: false, reason: String(e) };+ }+ },++ async capture() {+ try {+ if (!VIS.watching) {+ return { visible_attempted: false, reason: "the visibility observer was never installed" };+ }+ // WAIT FOR A FRAME FIRST, and this is not defensive padding.+ //+ // IntersectionObserver computes intersections as a step of the rendering lifecycle, so+ // with no frame between `observe()` and the read there is nothing to deliver and+ // `takeRecords()` returns an empty list. An action that scrolls produces frames and hides+ // this completely; a QUIET action -- open a menu, change a setting, type a character --+ // may not, and the capture then reports that the viewport showed nothing at all. The+ // analysis would correctly refuse such a pair as NOT_COMPARABLE, so it is not a false+ // pass, but it would silently strip visible-region coverage from exactly the actions that+ // are cheapest to get right. Observed directly: at rest, with no scroll, the observer+ // reported an empty set while message 1 filled the viewport.+ await new Promise((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(resolve));+ });+ // Then deliver anything still queued. Tearing down before this drops the last entries of+ // the action -- the ones most likely to describe what it just put on screen.+ const records = VIS.obs.takeRecords();+ for (const entry of records) {+ if (entry.isIntersecting && typeof entry.target.__sbOrdinal === "number") {+ VIS.ever.add(entry.target.__sbOrdinal);+ }+ }+ const nodes = (D().messages && D().messages()) || [];+ const byOrdinal = {};+ let mounted_ever_visible = 0;+ for (let i = 0; i < nodes.length; i++) {+ const el = nodes[i];+ const ord = typeof el.__sbOrdinal === "number" ? el.__sbOrdinal : ordinalOf(el, i + 1);+ if (!VIS.ever.has(ord)) continue;+ mounted_ever_visible += 1;+ // WITHOUT THE VIRTUALIZATION BOOKKEEPING, and the asymmetry is the reason.+ //+ // runtime/readiness.py deliberately accepts `aria-posinset` / `aria-setsize` either on+ // the `[data-role]` message or on an ancestor row wrapper -- it walks with `closest()`,+ // because the ordinal belongs on whichever element is the member of the set. An arm that+ // takes the first option therefore carries two attributes on EVERY message that the+ // fully mounted arm publishes on none, so the per-message digests differed on every+ // message while the rendered content was identical, and visible-region parity reported a+ // wall of differences for a DOM shape the gate explicitly permits. That makes auto-mode+ // parity unusable for the very arm it exists to score.+ //+ // NOT normalised in the whole-document structural digest, which is a separate decision+ // and a deliberate one. That digest is only ever applied to pairs where NEITHER arm is+ // windowing (see `decide_modes`), and between two fully mounted arms an ordinal that+ // appears, disappears or changes IS a change worth seeing. `signature` is shared with+ // the thread digest, the per-message rows, the overlays and the node-driven unit tests,+ // so the exclusion is passed in HERE by the one caller that wants it rather than baked+ // into the function every caller uses.+ //+ // What this gives up: a windowed arm publishing a WRONG ordinal on a message is no+ // longer visible in this digest. It is not unchecked -- runtime/readiness.py gates on+ // the ordinals being real positions (at least 1, distinct, no larger than the declared+ // set size, reaching the seeded total) and `probe_thread_completeness` walks them for+ // holes -- and those are the checks that can say what a right ordinal would be, which a+ // digest comparison against an arm that publishes none never could.+ const sig = signature(el, VIRTUALIZATION_ATTRS);+ byOrdinal[String(ord)] = {+ role: el.getAttribute("data-role") || "?",+ digest: hash(sig),+ chars: sig.length,+ };+ }+ const ever = [...VIS.ever].sort((a, b) => a - b);+ return {+ visible_attempted: true,+ // Every ordinal the viewport ever showed during the window, INCLUDING any that have+ // since been unmounted. The gap between this and `messages` is the honest measure of+ // what a windowed arm could not be asked about at capture time.+ ever_visible: ever,+ ever_visible_count: ever.length,+ mounted_ever_visible,+ unmounted_at_capture: ever.length - mounted_ever_visible,+ // Rows observed that this instrument could not place in the thread: no published+ // ordinal, and absent from the message list when they were observed. They carry no+ // ordinal and so appear nowhere above, which is a hole in the compared set rather than+ // agreement, and it is counted here so a reader can see it is zero.+ unplaced_rows: VIS.unplaced,+ messages: byOrdinal,+ };+ } catch (e) {+ return { visible_attempted: false, reason: String(e) };+ }+ },++ stop() {+ try {+ if (VIS.obs) VIS.obs.disconnect();+ if (VIS.mut) VIS.mut.disconnect();+ } catch (e) { /* nothing to do */ }+ VIS.obs = null;+ VIS.mut = null;+ VIS.watching = false;+ },+ };+window.__sb.parity = {// Exposed so the offline unit tests can drive the exact regexes that ship, rather than a// second copy of them that is free to drift.@@ -309,6 +738,19 @@messages,overlays,styles,+ // HOW MUCH OF THE THREAD THIS DIGEST COVERS.+ //+ // Every per-message row above is keyed by `i`, its position in the MOUNTED list. On the+ // shipped build that is also its position in the conversation, so the key is meaningful+ // and two arms can be compared row by row. On an arm that mounts a window it is not:+ // msg3 on one side and msg3 on the other are different messages, and comparing their+ // digests produces a wall of mismatches that says nothing about either build.+ //+ // Carrying the two numbers means the comparison layer can REFUSE rather than report+ // eighteen false differences. Identical on the shipped build, so nothing changes for a+ // normal pair.+ mounted_messages: messages.length,+ thread_total: (dom.threadTotal && dom.threadTotal()) || messages.length,};if (want_raw) out.raw = whole;return out;diff --git a/tests/studio/studiobench/scene/schedule.py b/tests/studio/studiobench/scene/schedule.pyindex 10a75bfcaa2..8a5399dba36 100644--- a/tests/studio/studiobench/scene/schedule.py+++ b/tests/studio/studiobench/scene/schedule.py@@ -280,6 +280,33 @@ class SceneRunner:except Exception as exc: # noqa: BLE001return {"census_attempted": False, "reason": f"{type(exc).__name__}: {exc}"}+ def _watch_visible(self) -> None:+ """Install the visible-region observer BEFORE the window opens.++ Before, not after, because the compared set is the union of everything the viewport showed+ during the action. An action that scrolls reveals messages and hides them again, and an+ observer installed at the close would compare only wherever the scroll happened to stop.+ """+ try:+ self.page.evaluate("() => window.__sb.parityVisible.watch()")+ except Exception: # noqa: BLE001+ # A page that cannot install it still gets a structural digest; the visible-region+ # capture reports itself absent rather than empty, which the analysis refuses.+ pass++ def _visible(self) -> dict:+ """The visible-region capture, taken at the close and BEFORE the census and the digest.++ It closes an accumulating observation rather than reading a static DOM, so it goes first;+ see the comment at the call site for what its tail costs when it does not.+ """+ try:+ got = self.page.evaluate("async () => await window.__sb.parityVisible.capture()")+ self.page.evaluate("() => window.__sb.parityVisible.stop()")+ return got+ except Exception as exc: # noqa: BLE001+ return {"visible_attempted": False, "reason": f"{type(exc).__name__}: {exc}"}+def _parity(self) -> dict:"""A structural digest of what is on screen, for the UI-parity check across arms.@@ -348,11 +375,21 @@ class SceneRunner:# 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.+ # THE CENSUS IS TAKEN BEFORE THE GAP WINDOW OPENS, not at its close. Same defect as the+ # action windows (workspace task #102) and the same fix, but the placement is different:+ # a gap window is the QUIET stretch, and its whole purpose is to measure the page doing+ # nothing but stream. Nineteen querySelectorAll passes over 195,000 elements at the end of+ # it is not nothing, and it landed on the frame-rate reading for the idle phase.+ #+ # Before rather than after, because the gap ends the instant the next slot is due: taking+ # it afterwards would push the action's start past its own slot and turn an instrument cost+ # into a missed slot, which is a worse failure than the one being fixed.+ census = self._census()with self.open_window(name, "gap") as window:+ window.note("census_before_gap", census)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)- window.note("census", self._census())def _run_slot(self, slot: Slot, t0: float) -> dict:entry = get_action(slot.action)@@ -388,6 +425,7 @@ class SceneRunner:expect = {"t_start_ms": slot.t_start_ms, "reached_at_ms": round(now_ms, 1)},).row(slot.action, window_name, self.cell.cell_id)+ self._watch_visible()with self.open_window(window_name, "action") as window:ctx = ActionContext(page = self.page,@@ -406,23 +444,79 @@ class SceneRunner:result = not_run(f"the action raised {type(exc).__name__}: {exc}")window.note("action", slot.action)window.note("ran", result.ran)- # A CENSUS PER ACTION, taken at the close of every window.- #- # Not a nicety. The end-of-cell census is taken after the film has finished, and the- # film ENDS with thread_reopen and delete_message -- so the "final" census of the- # first working run read 0 assistant messages and 0 characters, having faithfully- # measured a thread the benchmark had just deleted. A census per window gives the- # occupancy at the moment each action ran, which is the denominator every per-action- # cost needs anyway, and it makes the peak recoverable no matter what the last action- # did. Measured cost on a 1,500-element tree: 0.2ms.- window.note("census", self._census())- window.note("parity", self._parity())-- over_ms = ((time.monotonic() - t0) * 1000) - deadline_ms++ # THE CENSUS AND THE PARITY DIGEST ARE TAKEN OUTSIDE THE WINDOW. Workspace task #102.+ #+ # Both used to run inside the `with`, one line above this comment, on the strength of a+ # measurement -- "0.2ms on a 1,500-element tree" -- taken on a tree three orders of+ # magnitude smaller than the one this benchmark exists to study. At 100K+ tokens the+ # census walks nineteen querySelectorAll passes over ~195,000 elements and the parity+ # digest serialises 5.6 MB of structure, and every millisecond of it was being charged to+ # the action that happened to precede it. Measured cost of the mistake:+ #+ # delete_message reported 14.3 fps, true 49.0 fps+ # message_menu reported 17.1 fps, true 73.8 fps+ #+ # That is not a correction at the margin. It inverted the ranking of the actions this+ # campaign is about, and it did it in the direction that makes the standing DOM look like+ # a smaller problem than it is, because the instrument's own cost grows with exactly the+ # quantity under investigation.+ #+ # They still run at the same MOMENT -- immediately after the window closes, before the+ # scheduler starts waiting for the next slot -- so the digest and the occupancy still come+ # from one reading of one DOM taken at the end of the action. Only the accounting moved.+ #+ # The consequence, stated: the emitted `window` row no longer carries them in its notes,+ # because the row is emitted when the window closes. They live on the ACTION row, which is+ # where every consumer already reads them from.+ # THE DEADLINE IS SAMPLED HERE, BEFORE THE OBSERVATIONS. Moving the census and the digest+ # out of the measured window but leaving `over_ms` to be taken after them would have left+ # half the defect in place: an action that finished comfortably inside its budget would+ # still be flagged `over_budget` on the strength of a multi-megabyte serialisation that is+ # explicitly not its cost. Charging instrument time to the thing being measured is the+ # whole of task #102, and the budget flag is not exempt from it.+ window_closed_at = time.monotonic()+ over_ms = ((window_closed_at - t0) * 1000) - deadline_ms++ # THE VISIBLE CAPTURE GOES FIRST, AND THE ORDER IS THE MEASUREMENT. The other two read a+ # DOM that is sitting still; this one CLOSES an observation that has been accumulating+ # since `_watch_visible`, and every millisecond it stays open is another millisecond in+ # which a row can scroll into view and be counted as having been visible during the+ # action. Taken after the census and the digest, that tail was as long as those two probes+ # take -- and they are the one thing on this path whose cost is proportional to the arm.+ #+ # A fully mounted arm serialises the whole thread, a windowed arm serialises the dozen+ # rows it has mounted, so the two arms' observers stayed open for materially different+ # intervals: the numbers above this comment are 14.3 fps against 49.0, which is the same+ # asymmetry expressed as time. With streaming and autoscroll still running at the close of+ # `scroll_during_generation`, the mounted arm had the longer tail in which to admit an+ # ordinal the windowed arm never saw, and `compare_visible` has no tolerance for that --+ # it returns DIFFER on strict set inequality of `ever_visible`. The null control cannot+ # absorb it either, being same-build against same-build, where both sides pay the same+ # digest and the asymmetry does not exist.+ #+ # Taking it first does not make the tail zero: `capture()` still waits two frames, on+ # purpose, so a quiet action does not report an empty viewport. It makes the tail the SAME+ # ON BOTH ARMS, which is the property the comparison actually needs.+ visible = self._visible()+ census = self._census()+ parity = self._parity()+ # The observations DO consume wall clock before the next slot, so their cost is recorded+ # rather than dropped -- it is simply recorded as theirs.+ observation_ms = (time.monotonic() - window_closed_at) * 1000row = result.row(slot.action, window_name, self.cell.cell_id)row["window_ms"] = window.duration_ms- row["census"] = window.notes.get("census")- row["parity"] = window.notes.get("parity")+ # READ FROM THE LOCALS ABOVE, not from `window.notes`. The three observations were moved+ # out of the measured window, so by the time this row is built they are values this method+ # holds rather than notes the window carries.+ row["census"] = census+ row["parity"] = parity+ row["visible"] = visible+ # The observation cost itself, so it is never invisible again. `census_cost_ms` is the+ # page's own timing of the walk; if this pair ever comes to dominate the film's wall clock+ # the number is in the payload rather than in someone's hypothesis.+ row["observation_outside_window"] = True+ row["observation_ms"] = round(observation_ms, 1)# THE SCREENSHOT IS TAKEN OUTSIDE THE WINDOW, on purpose and not as a tidiness point.# The film runs on a wall clock and every slot has an absolute start, so an encode charged# to the measured window eats the gap before the next slot -- which is how an action comesdiff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_action_bar_wait.py b/tests/studio/studiobench/scene/selftest/test_studiobench_action_bar_wait.pyindex db3554527b9..63ee13d593c 100644--- a/tests/studio/studiobench/scene/selftest/test_studiobench_action_bar_wait.py+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_action_bar_wait.py@@ -179,6 +179,11 @@ const getComputedStyle = () => ({ pointerEvents: "auto" });const window = {};// The real one is frames.js's rAF promise. A timer is the same shape and does not need a compositor.window.__sbNextPaint = () => new Promise((r) => setTimeout(r, 16));+// dom.js's follow sampler survives a navigation by writing itself to sessionStorage on `pagehide`,+// so installing it REGISTERS a listener. Nothing here ever fires it -- the registration only has to+// not throw -- and the read side is already inside its own try/catch, which is why sessionStorage+// itself does not need shimming.+window.addEventListener = () => {};(new Function("window", "document", "PointerEvent", domSrc))(window, document, PointerEvent);diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_copy_confirmed_live.py b/tests/studio/studiobench/scene/selftest/test_studiobench_copy_confirmed_live.pynew file mode 100644index 00000000000..a54c30d1bcc--- /dev/null+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_copy_confirmed_live.py@@ -0,0 +1,233 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A KEYSTROKE THAT WENT NOWHERE WAS BEING REPORTED AS A MEASUREMENT.++`select_all_copy` pressed Control+C, slept 250ms for the copy to land, and reported the elapsed+time as `copy_ms`. On any engine that does not perform the copy, that number is the sleep.++Measured across the eleven WebKit payloads on this machine, 43 rows:++ r1K 258.5 ms+ r10K 258.8 ms+ r100K 263.9 ms++A hundredfold change in the quantity under study moved the "measurement" by two percent, because+it was measuring `wait_for_timeout(250)`. Chromium reads about 1,538 ms at the 100K rung for the+same action. Playwright's WebKit never performs a clipboard copy on Control+C, so every one of+those rows was a sleep wearing a timing's name -- and unlike a missing reading, it is perfectly+stable, so it looks like data.++The guard is on the CLIPBOARD and not on the engine name. A sentinel is written before the+keystroke; if it survives, nothing was copied. That admits an engine that starts working and+refuses one that stops, with no list to maintain.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++_HERE = Path(__file__).resolve()+_STUDIO_TESTS = _HERE.parents[3]+if str(_STUDIO_TESTS) not in sys.path:+ sys.path.insert(0, str(_STUDIO_TESTS))++from studiobench.runtime.types import ActionContext, Cell # noqa: E402+from studiobench.scene import actions as A # noqa: E402++_DOM_JS = _STUDIO_TESTS / "studiobench" / "scene" / "dom.js"++#: `navigator.clipboard` does not exist outside a secure context, and `set_content` leaves the page+#: on about:blank, which is not one. Served from a route so no server is needed.+ORIGIN = "https://studiobench.localhost"++BODY = """<!doctype html><meta charset=utf-8><title>t</title>+<style>.aui-thread-viewport { height: 300px; overflow-y: auto; }</style>+<div class="aui-thread-root"><div class="aui-thread-viewport" id="vp"></div></div>+<script>+ const vp = document.getElementById("vp");+ for (let i = 1; i <= 6; i++) {+ const m = document.createElement("div");+ m.setAttribute("data-role", i % 2 ? "user" : "assistant");+ m.textContent = "message " + i + " " + "x".repeat(400);+ vp.appendChild(m);+ }+ window.__sbNextPaint = () => new Promise(+ (r) => requestAnimationFrame(() => requestAnimationFrame(r)));+</script>+"""+++def _skip_reason() -> str | None:+ try:+ from playwright.sync_api import sync_playwright # noqa: F401+ except Exception as exc: # noqa: BLE001+ return f"playwright is not installed: {exc}"+ return None+++pytestmark = pytest.mark.skipif(_skip_reason() is not None, reason = _skip_reason() or "")++[email protected](scope = "module")+def context():+ from playwright.sync_api import sync_playwright+ with sync_playwright() as p:+ try:+ b = p.chromium.launch(args = ["--no-sandbox"])+ except Exception as exc: # noqa: BLE001+ pytest.skip(f"chromium could not be launched: {exc}")+ ctx = b.new_context(permissions = ["clipboard-read", "clipboard-write"])+ ctx.grant_permissions(["clipboard-read", "clipboard-write"], origin = ORIGIN)+ yield ctx+ ctx.close()+ b.close()+++def page(context):+ pg = context.new_page()+ pg.route(+ "**/*",+ lambda route: route.fulfill(status = 200, content_type = "text/html; charset=utf-8", body = BODY),+ )+ pg.goto(ORIGIN + "/chat")+ pg.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))+ yield pg+ pg.close()+++def _ctx(page, log = None) -> ActionContext:+ return ActionContext(+ page = page,+ cdp = None,+ cell = Cell(cell_id = "r100K.base.rep0", rung = "100K", rung_tokens = 100_000),+ window = None,+ args = {"thread_id": "t1", "base_url": ORIGIN},+ budget_ms = 30_000,+ dom = None,+ log = log or (lambda _m: None),+ )+++def _swallow_the_copy(page) -> None:+ """An engine that does not copy, reproduced faithfully: the keystroke is delivered, a `copy`+ event fires, and nothing reaches the clipboard."""+ page.evaluate("() => document.addEventListener('copy', (e) => { e.preventDefault(); }, true)")+++def test_a_real_copy_is_still_measured(page):+ """THE CONTROL. Without it the guard could refuse everything and the tests below would pass on+ an action that never reports a timing at all."""+ got = A.select_all_copy(_ctx(page))+ assert got.ran is True, got.reason+ assert got.timings.get("copy_ms") is not None+ assert (got.expect or {}).get("clipboard_chars", 0) > 0+++def test_an_engine_that_does_not_copy_is_NOT_RUN_rather_than_a_timing(page):+ """THE DEFECT. The keystroke is sent, 250ms passes, and before this the action returned that+ 250ms as `copy_ms` -- stable, plausible, and about nothing."""+ _swallow_the_copy(page)+ got = A.select_all_copy(_ctx(page))+ assert got.ran is False, got+ assert "did not change the clipboard" in (got.reason or "")+ assert "sentinel" in (got.reason or "")+ assert not got.timings.get("copy_ms")+++def test_the_refusal_says_the_number_would_have_been_the_harness_own_settle(page):+ """The reason has to name the failure, or the next person reads NOT RUN as a flaky run and adds+ the action to an allow-list."""+ _swallow_the_copy(page)+ said: list[str] = []+ got = A.select_all_copy(_ctx(page, said.append))+ assert "settle" in (got.reason or ""), got.reason+++def _refuse_the_sentinel_write(page) -> None:+ """Clipboard WRITE refused, clipboard READ still working.++ Not a hypothetical pairing. `writeText` needs transient user activation or the `clipboard-write`+ permission and throws `NotAllowedError` without either; `readText` is gated on a separate+ permission, and runtime/browser.py asks for the two only on Chromium. So the write can fail on+ its own, and the guard has to survive that rather than switch itself off.+ """+ page.evaluate(+ """() => {+ Object.defineProperty(navigator.clipboard, "writeText", {+ configurable: true,+ value: async () => { throw new DOMException("Write permission denied", "NotAllowedError"); },+ });+ }"""+ )+++def test_a_failed_sentinel_write_does_not_re_admit_the_unchanged_clipboard(page):+ """THE HOLE THIS CLOSES. When the sentinel could not be written, the action used to clear it and+ carry on -- and with no pre-copy value, `clip == sentinel` can never fire. A Control+C that did+ nothing then left the clipboard holding what the PREVIOUS action put there, which read back as a+ plausible non-empty copy of the whole thread with the 250ms settle beside it as `copy_ms`. That+ is the exact measurement the sentinel exists to refuse, re-admitted by its own fallback.+ """+ # Whatever an earlier action in the film left behind. Non-empty and plausible, which is what+ # makes it dangerous: an empty clipboard would have been caught by `clipboard_chars > 0`.+ page.evaluate("async () => await navigator.clipboard.writeText('x'.repeat(2400))")+ _refuse_the_sentinel_write(page)+ _swallow_the_copy(page)+ got = A.select_all_copy(_ctx(page))+ assert got.ran is False, got+ assert not got.timings.get("copy_ms")+ assert "did not change the clipboard" in (got.reason or ""), got.reason+ assert "snapshot" in (got.reason or ""), got.reason+++def test_a_real_copy_is_still_measured_when_the_sentinel_could_not_be_written(page):+ """THE CONTROL FOR THE ABOVE. The fallback must not turn a missing write permission into a dead+ action: a copy that really happened is still a measurement, and the row says which pre-copy+ value it was confirmed against."""+ page.evaluate("async () => await navigator.clipboard.writeText('stale')")+ _refuse_the_sentinel_write(page)+ got = A.select_all_copy(_ctx(page))+ assert got.ran is True, got.reason+ assert got.timings.get("copy_ms") is not None+ assert (got.expect or {}).get("clipboard_chars", 0) > 0+ assert (got.expect or {}).get("copy_confirmed_against") == "snapshot"+++def test_a_refusal_names_the_cause_and_not_just_the_exception_class(page):+ """`type(exc).__name__` is `Error` for every Playwright failure, and two complete 100K payloads+ refused this action with a reason that said exactly that and nothing else. The browser's own+ message is the diagnosis and has to travel with the row."""+ page.evaluate(+ """() => {+ for (const name of ["writeText", "readText"]) {+ Object.defineProperty(navigator.clipboard, name, {+ configurable: true,+ value: async () => { throw new DOMException("Document is not focused", "NotAllowedError"); },+ });+ }+ }"""+ )+ got = A.select_all_copy(_ctx(page))+ assert got.ran is False, got+ assert "Document is not focused" in (got.reason or ""), got.reason+++def test_the_guard_is_on_the_clipboard_and_not_on_the_engine_name():+ """No engine list to maintain. An engine that starts performing the copy is admitted with no+ change here, and one that stops is refused with no change here."""+ import inspect++ src = inspect.getsource(A.select_all_copy)+ assert "sentinel" in src+ # EXECUTABLE LINES ONLY. The engine names belong in the comment that explains which engine was+ # observed failing and with what numbers; what must not exist is a BRANCH on one.+ code = "\n".join(line for line in src.splitlines() if not line.lstrip().startswith("#"))+ # The word "engine" is allowed: it appears in the refusal MESSAGE, which is where it belongs.+ # A specific engine's NAME is not, because that is what a branch would need.+ for name in ("webkit", "WebKit", "firefox", "Firefox", "browser_name", "browser_type"):+ assert name not in code, f"the guard branches on {name!r} rather than on the clipboard"diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_follow_coverage_live.py b/tests/studio/studiobench/scene/selftest/test_studiobench_follow_coverage_live.pynew file mode 100644index 00000000000..bc3377ad92b--- /dev/null+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_follow_coverage_live.py@@ -0,0 +1,327 @@+# 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 FOLLOW VERDICT COVERED THIRTEEN PERCENT OF THE STREAM AND READ AS A PASS.++`follows_the_stream` exists to stop a windowed renderer producing a flattering streaming cost: if+the thread stops following, the streamed message leaves the viewport, a virtualizer unmounts it,+and the renderer is no longer rendering the thing being measured. The frame rate that comes out is+excellent and is about nothing.++The sampler splits its samples into two phases. ATTACHED, before the harness has scrolled+anywhere: the thread must stay pinned as content arrives, and this is what `pinned_fraction`+scores. DETACHED, after a deliberate scroll: the thread must NOT come back on its own.++`detached` latched on the FIRST `suspend()` and was never cleared. Every scene in the suite calls+`scroll_during_generation` about 1.5 seconds into an opening stream that runs for roughly 18+seconds, and two more streamed turns follow it. So from that first scroll onwards every sample+went to the detached branch, `running_samples` stopped growing, and the verdict was computed from+the first few seconds. Measured on a real 100K cell: `running_samples` 11, `detached_samples` 72.+Thirteen percent coverage, reported as 100% pinned, and quoted as evidence that the arm follows+the stream.++Two fixes, both pinned here. Coming back to the end RE-ATTACHES, because the contract is about+intent and intent is re-expressed by returning. And the coverage travels with the verdict, so the+fraction cannot be read without knowing how much of the stream it describes.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++_HERE = Path(__file__).resolve()+_STUDIO_TESTS = _HERE.parents[3]+if str(_STUDIO_TESTS) not in sys.path:+ sys.path.insert(0, str(_STUDIO_TESTS))++_DOM_JS = _STUDIO_TESTS / "studiobench" / "scene" / "dom.js"++#: A running thread: the stop button is what `isRunning()` looks for. The viewport is scrollable so+#: "at the bottom" is a real question.+#:+#: The jump-to-bottom control is present and its `invisible` class is kept in sync with the scroll+#: position by a listener, because that class IS the app's own answer to "are we at the bottom" and+#: `appSaysAtBottom()` reads nothing else. Omitting the control makes every sample `running_unknown`+#: and `pinned_fraction` null, which is correct behaviour on a build that renders no control and+#: useless as a fixture for scoring one.+FIXTURE = """+<!doctype html><meta charset="utf-8">+<style>+ body { margin: 0; }+ .aui-thread-viewport { height: 300px; overflow-y: auto; }+ .filler { height: 3000px; }+</style>+<div class="aui-thread-root">+ <div class="aui-thread-viewport" id="vp">+ <div class="filler"></div>+ <div data-role="assistant">last</div>+ </div>+ <button aria-label="Stop generating">stop</button>+ <div class="aui-thread-scroll-to-bottom invisible"></div>+</div>+<script>+ // The app's contract, modelled directly: the control's `invisible` class reflects whether the+ // viewport is at the end. Driven by an explicit call rather than a scroll listener, because a+ // programmatic `scrollTop` assignment does not reliably deliver a scroll event to a listener in+ // this fixture, and a test whose setup silently does not run is worse than no test.+ window.__syncJump = () => {+ const vp = document.getElementById("vp");+ const jump = document.querySelector(".aui-thread-scroll-to-bottom");+ const distance = vp.scrollHeight - vp.clientHeight - vp.scrollTop;+ jump.classList.toggle("invisible", distance <= 2);+ };+ window.__syncJump();+</script>+"""+++def _skip_reason() -> str | None:+ try:+ from playwright.sync_api import sync_playwright # noqa: F401+ except Exception as exc: # noqa: BLE001+ return f"playwright is not installed: {exc}"+ return None+++pytestmark = pytest.mark.skipif(_skip_reason() is not None, reason = _skip_reason() or "")++[email protected](scope = "module")+def browser():+ from playwright.sync_api import sync_playwright+ with sync_playwright() as p:+ try:+ b = p.chromium.launch(args = ["--no-sandbox"])+ except Exception as exc: # noqa: BLE001+ pytest.skip(f"chromium could not be launched: {exc}")+ yield b+ b.close()+++def page(browser):+ pg = browser.new_page(viewport = {"width": 800, "height": 600})+ pg.set_content(FIXTURE)+ pg.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))+ pg.evaluate("() => window.__sb.follow.reset()")+ yield pg+ pg.close()+++def _to_bottom(page) -> None:+ page.evaluate(+ "() => { const v = document.getElementById('vp'); v.scrollTop = v.scrollHeight;"+ " window.__syncJump(); }"+ )+++def _to_top(page) -> None:+ page.evaluate("() => { document.getElementById('vp').scrollTop = 0; window.__syncJump(); }")+++def _settle(page, ms: int = 700) -> None:+ """Long enough for several ticks at FOLLOW_TICK_MS (250ms)."""+ page.wait_for_timeout(ms)+++def _read(page) -> dict:+ return page.evaluate("() => window.__sb.follow.read()")+++def _start_at_bottom(page) -> None:+ """Position the viewport, THEN zero the counters.++ The sampler ticks every 250ms from the moment the script loads, so a test that scrolls after+ the first tick has already recorded a sample of the pre-scroll state and its `pinned_fraction`+ is 0.5 for reasons that have nothing to do with the code under test.+ """+ _to_bottom(page)+ page.wait_for_timeout(60)+ page.evaluate("() => window.__sb.follow.reset()")+++def test_the_sampler_scores_a_pinned_stream(page):+ """The control. Without it the tests below could pass on a sampler that never counts."""+ _start_at_bottom(page)+ _settle(page)+ got = _read(page)+ assert got["running_samples"] > 0, got+ assert got["pinned_fraction"] == 1, got+ assert got["attached_fraction_of_stream"] == 1, got+++def test_returning_to_the_end_reattaches_so_the_rest_of_the_stream_is_still_scored(page):+ """THE DEFECT. A deliberate scroll used to detach the sampler permanently, so every sample for+ the remainder of the stream -- and for every later stream in the cell -- was scored against the+ second half of the contract and contributed nothing to the verdict."""+ _start_at_bottom(page)+ _settle(page)+ before = _read(page)["running_samples"]++ # A deliberate gesture that ends back at the bottom, which is what `scroll_after` does and what+ # `scroll_during_generation` does when the user returns.+ page.evaluate("() => window.__sb.follow.suspend()")+ _to_top(page)+ _to_bottom(page)+ page.evaluate("() => window.__sb.follow.resume()")+ _settle(page)++ got = _read(page)+ assert got["reattachments"] == 1, got+ assert got["running_samples"] > before, (+ "the sampler stayed detached after a gesture that ended at the bottom, so the rest of the "+ "stream was never scored"+ )+ assert got["attached_fraction_of_stream"] > 0.5, got+++def test_a_gesture_that_ends_scrolled_up_does_NOT_reattach(page):+ """The other half of the contract has to survive the fix. A user who scrolled away and stayed+ away is detached, and any pin after that is the app yanking them down."""+ _start_at_bottom(page)+ _settle(page)+ page.evaluate("() => window.__sb.follow.suspend()")+ _to_top(page)+ page.evaluate("() => window.__sb.follow.resume()")+ _settle(page)+ got = _read(page)+ assert got["reattachments"] == 0, got+ assert got["detached_samples"] > 0, got+++def test_the_app_pulling_the_viewport_down_on_its_own_is_not_laundered_into_a_reattachment(page):+ """Re-attachment is only ever evaluated on the way out of a DELIBERATE gesture. If it were+ evaluated on every tick, an app that yanks a scrolled-up user back to the bottom would clear+ `detached` and the yank would be scored as the user following again -- the sampler would+ reward exactly the behaviour it exists to catch."""+ _start_at_bottom(page)+ _settle(page)+ page.evaluate("() => window.__sb.follow.suspend()")+ _to_top(page)+ page.evaluate("() => window.__sb.follow.resume()")+ _settle(page, 400)+ # The app, not the user, returns the viewport to the end.+ _to_bottom(page)+ _settle(page)+ got = _read(page)+ assert got["reattachments"] == 0, got+ assert got["yanked_back_samples"] > 0, got+ assert got["yanked_after_scroll"] is True, got+++def test_the_coverage_travels_with_the_verdict(page):+ """A fraction computed over the attached phases cannot be read without knowing how much of the+ streaming time those phases covered. Reported beside it so the one cannot be quoted alone."""+ _start_at_bottom(page)+ _settle(page, 400)+ page.evaluate("() => window.__sb.follow.suspend()")+ _to_top(page)+ page.evaluate("() => window.__sb.follow.resume()")+ _settle(page, 1200)+ got = _read(page)+ assert got["pinned_fraction"] == 1, got+ assert got["stream_samples"] == got["running_samples"] + got["detached_samples"], got+ assert got["attached_fraction_of_stream"] < 0.5, (+ got,+ "this cell was detached for most of its stream and the coverage must say so",+ )+++# ── the run the user started is a fresh intent to be at the end ─────+#+# THE GESTURE ON THE REAL FILM NEVER ENDS AT THE BOTTOM. `scene/actions.py::SCROLL_JS` jumps to+# the bottom and then steps 14 x 420px away from it, so on any thread taller than 5,880px the+# gesture ends thousands of pixels up and the `resume()` re-attachment above cannot fire. The film+# then starts two more runs of its own -- `stop_generation` and `send_turn` both submit a turn --+# and the app pins to the bottom for them, which `runtime/session.py` already documents as+# intended rather than a violation.+#+# Measured at head over every 100K payload in `outputs/`: attached_fraction_of_stream 0.07 to 0.15+# with reattachments 0, on the BASE arm as well as the treatment and on pure null controls, so the+# gate's FOLLOW_MIN_STREAM_COVERAGE of 0.50 failed every 100K cell of every run -- two copies of+# the shipped build included -- and a failed gate excludes the cell from scoring entirely. It+# passed only on the 1K smoke film, where the thread is short enough that the gesture's reversal+# lands back at the bottom by accident: a verdict about the thread's height, not about the app.+++def _end_run(page) -> None:+ """The reply finishes: the stop control goes, so `isRunning()` is false."""+ page.evaluate(+ "() => { const b = document.querySelector('button[aria-label=\"Stop generating\"]');"+ " if (b) b.setAttribute('aria-label', 'idle'); }"+ )+++def _start_run(page) -> None:+ """The user submits another turn: a NEW run, which the app pins to the bottom for."""+ page.evaluate(+ "() => { const b = document.querySelector('button[aria-label=\"idle\"]');"+ " if (b) b.setAttribute('aria-label', 'Stop generating'); }"+ )+++def test_a_run_the_user_started_reattaches_when_the_app_pins_for_it(page):+ """THE DEFECT. The verdict covered the first few seconds of the opening stream and nothing+ else, because every later turn of the film was scored against the yank half of the contract."""+ _start_at_bottom(page)+ _settle(page, 400)++ # The harness scrolls away mid-stream and stays away, exactly as SCROLL_JS leaves it.+ page.evaluate("() => window.__sb.follow.suspend()")+ _to_top(page)+ page.evaluate("() => window.__sb.follow.resume()")+ _settle(page, 500)+ assert _read(page)["reattachments"] == 0, _read(page)++ # That reply finishes; the user sends another turn and the app pins to the bottom for it.+ _end_run(page)+ _settle(page, 300)+ _start_run(page)+ _to_bottom(page)+ _settle(page, 800)++ got = _read(page)+ assert got["reattachments"] == 1, got+ assert got["attached_fraction_of_stream"] > 0.5, (+ got,+ "the follow-up turn streamed with the thread pinned at the bottom and none of it was "+ "scored, so the coverage gate fails a build that followed perfectly",+ )+++def test_a_pin_inside_the_SAME_run_is_still_a_yank_and_not_a_reattachment(page):+ """The other half has to survive. No new run started, so the app returning the viewport to the+ bottom on its own is the behaviour the sampler exists to catch, not the user coming back."""+ _start_at_bottom(page)+ _settle(page)+ page.evaluate("() => window.__sb.follow.suspend()")+ _to_top(page)+ page.evaluate("() => window.__sb.follow.resume()")+ _settle(page, 400)+ _to_bottom(page)+ _settle(page)+ got = _read(page)+ assert got["reattachments"] == 0, got+ assert got["yanked_back_samples"] > 0, got+ assert got["yanked_after_scroll"] is True, got+++def test_a_new_run_the_app_does_NOT_pin_for_leaves_the_sampler_detached(page):+ """A run start is not a free pass. The re-attachment needs the viewport to actually BE at the+ end, so an app that leaves a scrolled-up user where they are is scored exactly as before."""+ _start_at_bottom(page)+ _settle(page, 400)+ page.evaluate("() => window.__sb.follow.suspend()")+ _to_top(page)+ page.evaluate("() => window.__sb.follow.resume()")+ _settle(page, 400)+ _end_run(page)+ _settle(page, 300)+ _start_run(page)+ _settle(page, 800)+ got = _read(page)+ assert got["reattachments"] == 0, got+ assert got["attached_fraction_of_stream"] < 0.5, gotdiff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_hover_reveal_live.py b/tests/studio/studiobench/scene/selftest/test_studiobench_hover_reveal_live.pynew file mode 100644index 00000000000..47768b703de--- /dev/null+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_hover_reveal_live.py@@ -0,0 +1,221 @@+# 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 "NEW CHAT" CONTROL WAS NEVER COVERED. It was never HOVERED.++`thread_reopen` reported NOT RUN on every run, with two diagnostics that were both accurate and+both pointed the wrong way:++ button[aria-label="New chat"] was not clickable: TimeoutError;+ no point on the control hit-tests to it++That reads like an overlay, or a collapsed sidebar, or a zero-size button, and it was none of+them. Asking the live app directly returned a control that is 20x20 at (243, 319), `visibility:+visible`, `display: flex`, one instance, nothing drawn over it -- and `pointer-events: none` with+`opacity: 0`. Studio styles it as a hover-revealed action:++ .sidebar-header-action { opacity-0 pointer-events-none }+ .group\\/sidebar-header:hover .sidebar-header-action { opacity-100 pointer-events-auto }++With no mouse over the header the button is laid out, passes every actionability check Playwright+makes, and is transparent to every hit test. So `click()` waited out its timeout, the hit-test+spread found no reachable point, and the harness substituted `page.goto` -- timing a full document+navigation as though it were the client-side subtree rebuild the action exists to measure.++The fixture below is the app's rule, not an approximation of it. Both halves are asserted: that+the un-hovered control really is unreachable (otherwise the test proves nothing and would pass+without the fix), and that hovering makes it clickable through the production+`_click_or_navigate` path.++ python -m pytest tests/studio/studiobench/scene/selftest/test_studiobench_hover_reveal_live.py -q+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++_STUDIO_TESTS = Path(__file__).resolve().parents[3]+if str(_STUDIO_TESTS) not in sys.path:+ sys.path.insert(0, str(_STUDIO_TESTS))++from studiobench.runtime.types import ActionContext, Cell # noqa: E402+from studiobench.scene import actions as A # noqa: E402++#: Studio's own geometry: a 20x20 action inside a 279x49 sticky header row, at the same offset the+#: live probe measured. The numbers matter -- a control large enough to be hit by chance would let+#: the test pass for the wrong reason.+FIXTURE = """+<!doctype html><meta charset="utf-8">+<style>+ body { margin: 0; font: 12px sans-serif; }+ .sidebar { width: 280px; height: 900px; }+ .sidebar-header {+ display: flex; align-items: center; gap: 4px;+ width: 279px; height: 49px; padding: 0 4px; margin-top: 295px;+ }+ .sidebar-header-action {+ display: inline-flex; width: 20px; height: 20px;+ opacity: 0; pointer-events: none; transition: opacity 150ms;+ }+ .sidebar-header:hover .sidebar-header-action {+ opacity: 1; pointer-events: auto;+ }+</style>+<div class="sidebar">+ <div class="sidebar-header"><span>RECENTS</span>+ <button aria-label="New chat" class="sidebar-header-action">+</button>+ </div>+</div>+<script>+ window.__clicks = 0;+ document.querySelector('button[aria-label="New chat"]')+ .addEventListener("click", () => { window.__clicks += 1; });+</script>+"""++SELECTOR = 'button[aria-label="New chat"]'++#: A URL that actually loads. Pointing the fallback at a dead port exercises the "navigation+#: failed too" branch instead of the navigation branch under test.+FALLBACK_URL = "about:blank"+++def _skip_reason() -> str | None:+ try:+ from playwright.sync_api import sync_playwright # noqa: F401+ except Exception as exc: # noqa: BLE001+ return f"playwright is not installed: {exc}"+ return None+++pytestmark = pytest.mark.skipif(_skip_reason() is not None, reason = _skip_reason() or "")++[email protected](scope = "module")+def browser():+ from playwright.sync_api import sync_playwright+ with sync_playwright() as p:+ try:+ b = p.chromium.launch(args = ["--no-sandbox"])+ except Exception as exc: # noqa: BLE001+ pytest.skip(f"chromium could not be launched: {exc}")+ yield b+ b.close()+++def page(browser):+ # A PAGE PER TEST, because the mouse position is page state and a previous test's hover would+ # carry the control into the next one already revealed.+ pg = browser.new_page(viewport = {"width": 1280, "height": 900})+ pg.set_content(FIXTURE)+ yield pg+ pg.close()+++def _ctx(page, log = None) -> ActionContext:+ return ActionContext(+ page = page,+ cdp = None,+ cell = Cell(cell_id = "r100K.base.rep0", rung = "100K", rung_tokens = 100_000),+ window = None,+ args = {"thread_id": "t1", "base_url": "http://127.0.0.1:1"},+ budget_ms = 30_000,+ dom = None,+ log = log or (lambda _m: None),+ )+++# ── the condition, reproduced ───────────────────────────────────────+++def test_the_control_really_is_unreachable_until_it_is_hovered(page):+ """WITHOUT THIS THE REST PROVES NOTHING. If the fixture's button were hit-testable at rest,+ every assertion below would pass with or without the fix."""+ box = page.eval_on_selector(SELECTOR, "(el) => el.getBoundingClientRect().toJSON()")+ assert round(box["width"]) == 20 and round(box["height"]) == 20, "the fixture lost its geometry"+ style = page.eval_on_selector(+ SELECTOR,+ "(el) => { const s = getComputedStyle(el);"+ " return { pe: s.pointerEvents, op: s.opacity, vis: s.visibility }; }",+ )+ assert style == {"pe": "none", "op": "0", "vis": "visible"}, style+ assert (+ A._reachable_point(_ctx(page), SELECTOR) is None+ ), "the un-hovered control hit-tests to itself, so this fixture does not reproduce the failure"+++# ── the fix ─────────────────────────────────────────────────────────+++def test_hovering_reveals_the_control_and_returns_a_point_on_it(page):+ point = A._reveal_by_hover(_ctx(page), SELECTOR)+ assert point is not None, "hovering did not make the control hit-testable"+ x, y = point+ # Against the control's OWN box, read from the page. Hard-coding the live app's (243, 319)+ # asserted the fixture's layout rather than the behaviour, and failed on a fixture that was+ # working correctly.+ box = page.eval_on_selector(SELECTOR, "(el) => el.getBoundingClientRect().toJSON()")+ assert box["left"] <= x <= box["right"], (point, box)+ assert box["top"] <= y <= box["bottom"], (point, box)+++def test_the_action_clicks_the_control_instead_of_substituting_a_navigation(page):+ """THE BEHAVIOUR THAT CHANGED, end to end through the production path.++ Before the fix this returned `path == "navigate"`, and `thread_reopen` correctly refused to+ score it -- so the action reported NOT RUN on every single run.+ """+ got = A._click_or_navigate(_ctx(page), SELECTOR, FALLBACK_URL)+ assert got.path == "click", got.reason+ assert got.navigated is False+ assert page.evaluate("window.__clicks") == 1, "the app's own handler never fired"+++def test_the_hover_is_reported_so_the_gesture_is_not_silent(page):+ """A harness that quietly does something extra to make a control work is how the last defect+ got in. The reveal is logged."""+ said: list[str] = []+ A._click_or_navigate(_ctx(page, said.append), SELECTOR, FALLBACK_URL)+ assert any("hover-revealed" in m for m in said), said+++# ── and what it must NOT do ─────────────────────────────────────────+++def test_an_ordinary_control_is_not_hovered_first(page):+ """The reveal is a FALLBACK. A control that hit-tests at rest is clicked without any mouse+ movement being introduced into a measured window, which is checked here by its absence from+ the log rather than by asking `_reveal_by_hover` what it would have done."""+ page.eval_on_selector(+ SELECTOR,+ # `transition: none` as well: `opacity` is transitioned over 150ms, so `getComputedStyle`+ # sampled on the next tick still reports "0" and the control looks hidden to any check+ # that reads it. That is a real hazard for the production code too, and the reason the+ # reveal waits out `_REVEAL_SETTLE_MS` rather than sampling immediately.+ "(el) => { el.style.transition = 'none'; el.style.opacity = '1';"+ " el.style.pointerEvents = 'auto'; }",+ )+ assert A._reachable_point(_ctx(page), SELECTOR) is not None+ said: list[str] = []+ got = A._click_or_navigate(_ctx(page, said.append), SELECTOR, FALLBACK_URL)+ assert got.path == "click"+ assert not any("hover-revealed" in m for m in said), said+++def test_a_genuinely_unreachable_control_is_still_reported_unreachable(page):+ """The fix must not become a way of clicking things a user cannot click. A control covered by+ a real overlay stays unreachable after hovering, and the navigation fallback is taken with the+ reason saying so."""+ page.evaluate(+ "() => { const d = document.createElement('div');"+ " d.style.cssText = 'position:fixed;inset:0;z-index:9;background:#000';"+ " document.body.appendChild(d); }"+ )+ said: list[str] = []+ got = A._click_or_navigate(_ctx(page, said.append), SELECTOR, FALLBACK_URL)+ assert got.path == "navigate"+ assert "even after hovering it" in (got.reason or ""), got.reasondiff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_observation_cost.py b/tests/studio/studiobench/scene/selftest/test_studiobench_observation_cost.pynew file mode 100644index 00000000000..fa46185d3ed--- /dev/null+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_observation_cost.py@@ -0,0 +1,293 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The two harness defects recorded as workspace task #102, held closed.++DEFECT ONE: the census and the parity digest ran INSIDE the measured window. Nineteen+querySelectorAll passes over ~195,000 elements plus a 5.6 MB structural serialisation, charged to+whichever action they happened to follow. It reported `delete_message` at 14.3 fps when the action+costs 49.0, and `message_menu` at 17.1 when it costs 73.8 -- an instrument whose own cost grows+with exactly the quantity under investigation, biasing every reading in the direction that makes+the standing DOM look smaller than it is.++DEFECT TWO: the "New chat" click fell back to `page.goto` without telling anyone. A goto is a full+document navigation -- bundle re-execution, runtime rehydration -- and it was being timed as+though it were the client-side subtree rebuild `thread_reopen` exists to measure. That produced+thread_reopen at 6.0 fps, a number about a page load quoted as a number about a thread.++Both are ordering and reporting properties, so both are testable without a browser, which is why+they are asserted here rather than left to be noticed again in a payload.+"""++from __future__ import annotations++import sys+import time+from pathlib import Path++_STUDIO_TESTS = Path(__file__).resolve().parents[3]+if str(_STUDIO_TESTS) not in sys.path:+ sys.path.insert(0, str(_STUDIO_TESTS))++from studiobench.runtime.types import ActionContext, Cell, Slot # noqa: E402+from studiobench.scene import actions as A # noqa: E402+from studiobench.scene.schedule import Scene, SceneRunner # noqa: E402+++class _Recorder:+ def __init__(self):+ self.rows = []++ def emit(self, row):+ self.rows.append(row)+++class _Window:+ def __init__(self, log, name):+ self._log = log+ self.name = name+ self.notes = {}+ self.duration_ms = 1.0++ def __enter__(self):+ self._log.append(("open", self.name))+ return self++ def __exit__(self, *exc):+ self._log.append(("close", self.name))+ return False++ def note(self, key, value):+ self.notes[key] = value+++def _runner(order: list):+ cell = Cell(cell_id = "r10K.base.rep0", rung = "10K", rung_tokens = 10_000)++ def _open(name, kind):+ return _Window(order, name)++ runner = SceneRunner(+ cell = cell,+ page = None,+ cdp = None,+ dom = None,+ recorder = _Recorder(),+ open_window = _open,+ log = lambda _m: None,+ )+ runner._census = lambda: (order.append(("census", "")), {"elements": 195_631})[1]+ runner._parity = lambda: (order.append(("parity", "")), {"parity_attempted": True})[1]+ return runner+++# ── defect one: the observation is outside the window ───────────────+++def test_the_census_and_the_digest_are_taken_after_the_action_window_closes():+ """THE REGRESSION TEST FOR THE 14.3-vs-49.0 fps READING.++ Ordering, asserted directly: both observations must appear in the log AFTER the close of the+ window they describe. If either moves back inside, its cost lands on the action again.+ """+ order: list = []+ runner = _runner(order)+ scene = Scene(name = "one", slots = [Slot(action = "keystroke", t_start_ms = 0, budget_ms = 50)])+ runner.run(scene, time.monotonic())++ names = [kind for kind, _ in order]+ close_at = names.index("close")+ assert "census" in names and "parity" in names, "the observations were dropped entirely"+ assert names.index("census") > close_at, "the census is still inside the measured window"+ assert names.index("parity") > close_at, "the parity digest is still inside the window"+++def test_the_action_row_still_carries_both_observations():+ """Moving them out must not lose them. The row is where every consumer reads them from."""+ order: list = []+ runner = _runner(order)+ scene = Scene(name = "one", slots = [Slot(action = "keystroke", t_start_ms = 0, budget_ms = 50)])+ rows = runner.run(scene, time.monotonic())+ assert rows[0]["census"] == {"elements": 195_631}+ assert rows[0]["parity"] == {"parity_attempted": True}+ assert rows[0]["observation_outside_window"] is True+++def test_the_gap_windows_census_is_taken_before_the_gap_opens():+ """A gap window measures the page doing nothing but stream. A 195,000-element walk at the end+ of it is not nothing, and it cannot be moved to AFTER the close either: the gap ends exactly+ when the next slot is due, so a walk there would push the action past its own slot and turn an+ instrument cost into a missed slot."""+ order: list = []+ runner = _runner(order)+ runner._gap_window("stream:gap12", until_ms = 300, t0 = time.monotonic())+ names = [kind for kind, _ in order]+ assert names.index("census") < names.index("open")+++# ── defect two: the silent substitution ─────────────────────────────+++class _Page:+ """A page whose New chat button is present but refuses to be clicked, which is the real+ condition: the sidebar's sticky group label covers it, so Playwright's actionability retries+ burn their whole timeout on an element that is visible, enabled and stable."""++ def __init__(self, clickable: bool):+ self.clickable = clickable+ self.goto_calls: list[str] = []++ def query_selector(self, _selector):+ page = self++ class _Handle:+ def click(self, timeout = None):+ if not page.clickable:+ raise TimeoutError("element is covered by another element")++ return _Handle()++ def goto(self, url, **_kwargs):+ self.goto_calls.append(url)++ def evaluate(+ self,+ script = "",+ *_a,+ **_k,+ ):+ # The end of the thread, which `thread_reopen` reads out of the DOM before it touches+ # anything so that it has a string to recognise the rebuilt thread by. It has to be a+ # string here or the action refuses on that precondition and never reaches the transition+ # this file is about.+ if "data-role=" in script and "user" in script:+ return "studiobench turn 8: continue with unit 3"+ # Otherwise a thread with messages in it, so `thread_reopen` gets past its own precondition+ # and reaches the transition under test.+ return 18++ def wait_for_timeout(self, _ms):+ return None+++def _ctx(page) -> ActionContext:+ return ActionContext(+ page = page,+ cdp = None,+ cell = Cell(cell_id = "r10K.base.rep0", rung = "10K", rung_tokens = 10_000),+ window = None,+ args = {"thread_id": "t1", "base_url": "http://localhost:1"},+ budget_ms = 30_000,+ dom = None,+ log = lambda _m: None,+ )+++def test_a_clickable_control_reports_the_click_path():+ got = A._click_or_navigate(_ctx(_Page(True)), "button", "http://x/")+ assert got.ok is True+ assert got.path == "click"+ assert got.navigated is False+++def test_a_substituted_navigation_is_reported_as_a_navigation_not_as_a_click():+ """The whole defect in one assertion: the old function returned `True` here and the caller had+ no way to learn that a completely different operation had been performed."""+ page = _Page(False)+ got = A._click_or_navigate(_ctx(page), "button", "http://x/")+ assert got.ok is True+ assert got.path == "navigate"+ assert got.navigated is True+ assert got.reason, "the navigation carries no explanation of why the click failed"+ assert page.goto_calls == ["http://x/"]+++def test_thread_reopen_refuses_to_report_a_timing_for_a_page_navigation():+ """LOUD, AND NOT A MEASUREMENT. `ran = False` rather than a plausible-looking number.++ An `expect_ok = False` would have left the timing in the row, and a timing in a row is a+ number somebody eventually averages. The action did not happen, so it reports that it did not+ happen, and `ActionResult.__post_init__` empties `timings` for it.+ """+ page = _Page(False)+ result = A.thread_reopen(_ctx(page))+ assert result.ran is False+ assert result.timings == {}+ assert "not a thread rebuild" in (result.reason or "")+ assert "navigation" in (result.reason or "")+++def test_thread_reopen_says_so_in_the_log_as_well_as_in_the_row():+ """A payload nobody opens is not where this should first become visible."""+ lines: list[str] = []+ ctx = _ctx(_Page(False))+ ctx.log = lines.append+ A.thread_reopen(ctx)+ assert any("NOT MEASURED" in line for line in lines), lines+++# ── the action bar does not exist while a reply is being written ────+++class _RunningPage:+ """A page whose reply finishes after `runs_for` polls."""++ def __init__(self, runs_for: int):+ self.runs_for = runs_for+ self.polls = 0+ self.waits = 0++ def evaluate(self, script, *_a, **_k):+ if "isRunning" in script:+ self.polls += 1+ return self.polls <= self.runs_for+ return 18++ def wait_for_timeout(self, ms):+ # Actually sleeps, like Playwright's. A no-op here lets the bounded wait spin thousands of+ # times inside its deadline, which exhausted the scripted reply and made a test about a+ # reply that never lands pass for the opposite reason.+ self.waits += 1+ time.sleep(ms / 1000.0)+++def _running_ctx(page, budget_ms = 12000):+ return ActionContext(+ page = page,+ cdp = None,+ cell = Cell(cell_id = "r100K.A0.rep0", rung = "100K", rung_tokens = 100_000),+ window = None,+ args = {"thread_id": "t1", "base_url": "http://localhost:1"},+ budget_ms = budget_ms,+ dom = None,+ log = lambda _m: None,+ )+++def test_it_waits_for_a_generating_reply_instead_of_reporting_no_menu():+ """THE DEFECT, and it cost this action on every CI run since the branch opened.++ Studio hides a message's action bar while the message is generating, and the film schedules+ `message_menu` about four seconds after a `send_turn` whose reply runs for roughly fourteen.+ So the harness asked for a menu on a message that was still being written, got no More button,+ and reported NOT RUN -- an accurate observation of a question nobody should have asked yet.+ Waiting is what a user does, and it is the only thing that makes the action measurable.+ """+ page = _RunningPage(runs_for = 3)+ assert A._wait_for_the_reply_to_land(_running_ctx(page)) is True+ assert page.waits >= 1, "it returned without ever waiting"+++def test_a_reply_that_never_lands_is_reported_honestly_rather_than_waited_on_forever():+ """The wait is bounded by the slot's own budget: a reply that never finishes must not swallow+ the rest of the film."""+ page = _RunningPage(runs_for = 10_000)+ assert A._wait_for_the_reply_to_land(_running_ctx(page, budget_ms = 200)) is False+++def test_an_idle_thread_is_not_waited_on_at_all():+ """No stream, no wait: the action must not add latency to the common case, and a wait that+ always fires would change what every other reading is taken against."""+ page = _RunningPage(runs_for = 0)+ assert A._wait_for_the_reply_to_land(_running_ctx(page)) is True+ assert page.waits == 0diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_one_live.py b/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_one_live.pynew file mode 100644index 00000000000..7557cc10d09--- /dev/null+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_reasoning_one_live.py@@ -0,0 +1,180 @@+# 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 WORST NUMBER ON THE PAGE DESCRIBES A GESTURE NOBODY MAKES.++`reasoning_toggle` reads 2.2 fps at the 100K rung with a p95 frame of 2,084 ms. It gets there by+opening EVERY reasoning pane in the thread in one gesture: 10 panes, 74,917 highlight spans, 2,143+ms to open and 805 ms to close. That is a legitimate stress reading and it has been quoted as a+user-journey reading, which it is not -- a user expands one pane.++`reasoning_toggle_one` is that second number. These tests hold the property that makes the two worth+having side by side: the cost of the thread-wide action scales with thread length and the cost of+the single-pane one does not.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++_HERE = Path(__file__).resolve()+_STUDIO_TESTS = _HERE.parents[3]+if str(_STUDIO_TESTS) not in sys.path:+ sys.path.insert(0, str(_STUDIO_TESTS))++from studiobench.runtime.types import ActionContext, Cell # noqa: E402+from studiobench.scene import actions as A # noqa: E402++_DOM_JS = _STUDIO_TESTS / "studiobench" / "scene" / "dom.js"++#: A Radix Collapsible reduced to the two things `dom.js` reads: `data-state` on the ROOT, and a+#: trigger that flips it. The content stays mounted when collapsed, exactly as Radix leaves it, so a+#: presence check would read every pane as open and the assertion could never fail.+BODY_TEMPLATE = """<!doctype html><meta charset=utf-8><title>t</title>+<div class="aui-thread-root"><div class="aui-thread-viewport" id="vp"></div></div>+<script>+ const vp = document.getElementById("vp");+ const PANES = __PANES__;+ const SPANS = __SPANS__;+ for (let i = 0; i < PANES; i++) {+ const root = document.createElement("div");+ root.setAttribute("data-slot", "reasoning-root");+ root.setAttribute("data-state", "closed");+ const trigger = document.createElement("button");+ trigger.setAttribute("data-slot", "reasoning-trigger");+ trigger.textContent = "pane " + i;+ const content = document.createElement("pre");+ trigger.addEventListener("click", () => {+ const open = root.getAttribute("data-state") === "open";+ root.setAttribute("data-state", open ? "closed" : "open");+ // The CONTENT element stays mounted either way, as Radix leaves it for the animation, and+ // the highlight spans inside it do not: that is where the cost is, and it is why the action+ // counts `pre span` rather than trusting the pane count. `hidden` would not reproduce this,+ // because a hidden element still matches a selector.+ content.replaceChildren();+ if (!open) {+ for (let s = 0; s < SPANS; s++) {+ const span = document.createElement("span");+ span.textContent = "tok";+ content.appendChild(span);+ }+ }+ });+ root.appendChild(trigger);+ root.appendChild(content);+ vp.appendChild(root);+ }+ window.__sbNextPaint = () => new Promise(+ (r) => requestAnimationFrame(() => requestAnimationFrame(r)));+</script>+"""+++def _skip_reason() -> str | None:+ try:+ from playwright.sync_api import sync_playwright # noqa: F401+ except Exception as exc: # noqa: BLE001+ return f"playwright is not installed: {exc}"+ return None+++pytestmark = pytest.mark.skipif(_skip_reason() is not None, reason = _skip_reason() or "")++[email protected](scope = "module")+def browser():+ from playwright.sync_api import sync_playwright+ with sync_playwright() as p:+ try:+ b = p.chromium.launch(args = ["--no-sandbox"])+ except Exception as exc: # noqa: BLE001+ pytest.skip(f"chromium could not be launched: {exc}")+ yield b+ b.close()+++def make_page(browser):+ opened = []++ def _make(panes: int, spans_per_pane: int = 4):+ page = browser.new_page()+ body = BODY_TEMPLATE.replace("__PANES__", str(panes)).replace(+ "__SPANS__", str(spans_per_pane)+ )+ page.set_content(body)+ # `set_content` does not reliably run an init script, so the module is attached after.+ page.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))+ opened.append(page)+ return page++ yield _make+ for page in opened:+ page.close()+++def _ctx(page) -> ActionContext:+ return ActionContext(+ page = page,+ cdp = None,+ cell = Cell(cell_id = "r100K.base.rep0", rung = "100K", rung_tokens = 100_000),+ window = None,+ args = {"thread_id": "t1"},+ budget_ms = 30_000,+ dom = None,+ log = lambda _m: None,+ )+++def test_it_opens_exactly_one_pane_and_leaves_the_rest_shut(make_page):+ got = A.reasoning_toggle_one(_ctx(make_page(panes = 8)))+ assert got.ran is True, got.reason+ assert got.expect_ok is True, got.reason+ assert got.expect["open_after_expand"] == 1+ assert got.expect["open_after_collapse"] == 0+ # The thread's pane count is reported as CONTEXT beside a fixed gesture. Without it the reading+ # cannot be told apart from the thread-wide one in a payload.+ assert got.expect["panes"] == 8+ assert got.expect["panes_opened"] == 1+++def test_the_cost_does_not_scale_with_thread_length(make_page):+ """THE PROPERTY THAT MAKES IT A DIFFERENT NUMBER. `reasoning_toggle` materialises every pane's+ spans, so it grows with the thread. This one materialises one pane's, so it does not -- and a+ reading that quietly grew with thread length would be the thread-wide action under a new name.+ """+ small = A.reasoning_toggle_one(_ctx(make_page(panes = 2, spans_per_pane = 4)))+ large = A.reasoning_toggle_one(_ctx(make_page(panes = 40, spans_per_pane = 4)))+ assert small.ran and large.ran+ # Twentyfold the thread, the same number of spans revealed.+ assert small.expect["highlight_spans_added"] == large.expect["highlight_spans_added"] == 4+++def test_a_thread_with_no_reasoning_pane_is_NOT_RUN(make_page):+ got = A.reasoning_toggle_one(_ctx(make_page(panes = 0)))+ assert got.ran is False+ assert "no reasoning pane" in (got.reason or "")+++def test_it_refuses_a_thread_that_is_already_open(make_page):+ """A pane left open by an earlier action would make this measure a CLOSE and call it an open.+ Refusing is right: the number is the only reason the action exists."""+ page = make_page(panes = 3)+ page.evaluate("() => window.__sb.dom.reasoningTriggers()[0].click()")+ got = A.reasoning_toggle_one(_ctx(page))+ assert got.ran is False+ assert "already open" in (got.reason or "")+++def test_it_is_not_in_the_standard_film(make_page):+ """Adding a slot to a fixed-duration schedule shifts every window after it and voids+ comparability against every payload already on disk. The action exists so the number can be+ taken deliberately; it must not appear in the shipped scene until a corpus or tier bump is+ invalidating those payloads anyway."""+ schedule = (Path(_STUDIO_TESTS) / "studiobench" / "scene" / "schedule.py").read_text(+ encoding = "utf-8"+ )+ assert '"reasoning_toggle_one"' not in schedulediff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_stop_slot_budget.py b/tests/studio/studiobench/scene/selftest/test_studiobench_stop_slot_budget.pyindex a448586530a..3d09ca0f419 100644--- a/tests/studio/studiobench/scene/selftest/test_studiobench_stop_slot_budget.py+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_stop_slot_budget.py@@ -210,6 +210,12 @@ class _Page:return self.composerif "messageCount" in script:return self.messages+ # The thread's length as well as the mounted count. `stop_generation` proves its own turn+ # was added by `threadTotal()`, so that a windowed arm whose window refills is not read as+ # a send that added nothing and left with nothing to clean up. This page models a fully+ # mounted arm, where the two are the same number.+ if "threadTotal" in script:+ return self.messagesif "assistantChars" in script:return 9_200raise AssertionError(f"the page was asked something this shim does not model: {script}")@@ -586,3 +592,52 @@ def test_the_reserve_is_still_the_whole_of_what_its_two_halves_reserve():OWN_TURN_RESERVE_MS - 80 - OWN_TURN_FIXED_AFTER_SEND_MS - OWN_TURN_STOP_POLL_MS== OWN_TURN_START_POLL_MS)+++# ── the same give-up path, on an arm that mounts a window ────────────────────────────────────+++class _WindowedPage(_Page):+ """A thread whose MOUNTED count never moves because the window refills as it grows.++ `threadTotal()` is `aria-setsize`, the store's declaration of how long the thread is;+ `messageCount()` is how much of it is in the DOM. On the shipped build they are the same+ number and nothing here is visible. On an arm whose whole purpose is to mount less of the+ thread they are not, and a before/after taken on the mounted count answers "the thread did not+ grow" to a send that worked.+ """++ WINDOW = 2++ def evaluate(+ self,+ script,+ arg = None,+ ):+ if arg is None and "messageCount" in script:+ self.charge()+ return self.WINDOW+ return super().evaluate(script, arg)++[email protected]("scene", [FAST, QUICK, STANDARD], ids = lambda s: s.name)+def test_a_turn_given_up_on_is_taken_back_on_an_arm_that_mounts_a_window(monkeypatch, scene):+ """THE DEFECT. `STOP_CLEANUP_JS` already asks `threadTotal()`, but the guard deciding whether+ to RUN it compared `messageCount()` before the send with `messageCount()` after. A windowed+ mount holds that number still while the thread grows, so the cleanup was never called at all+ and the throwaway turn -- with its stream still running -- was handed to every later action+ window and to the final census."""++ stop, _nxt, _slack = _stop_slot(scene)+ settled = _thread_a_measured_turn_leaves(monkeypatch, stop.budget_ms)+ clock = _Clock()+ page = _WindowedPage(clock, 0.0, start_ms = stop.budget_ms - 1_000)+ result = _drive(page, monkeypatch, clock, stop.budget_ms)++ assert result.ran is False+ assert page.composer == "", "the send went through, so the box is empty"+ assert page.deleted == 1, "the turn it had already sent was never deleted"+ assert page.messages == settled, (+ f"{scene.name}: a give-up on a windowed arm left the thread at {page.messages} messages, "+ f"where a measured turn leaves it at {settled}"+ )diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_thread_reopen_gate.py b/tests/studio/studiobench/scene/selftest/test_studiobench_thread_reopen_gate.pynew file mode 100644index 00000000000..5d22d8749b4--- /dev/null+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_thread_reopen_gate.py@@ -0,0 +1,529 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The two `thread_reopen` defects left behind by workspace task #102, held closed.++DEFECT ONE: REFUSING THE READING BUT NOT THE DAMAGE. Task #102 taught the action to report NOT RUN+when the New chat control could not be clicked and `page.goto` was substituted, because a document+navigation is not the client-side subtree rebuild this action exists to time. It detected that+AFTER the fact, though, by reading `path == "navigate"` once the goto had already run -- so the row+was honest and the scene was wrecked: every slot after this one carried on from an empty new chat,+and `delete_message`, the last slot of every film, found no messages and went unexercised for a+reason that had nothing to do with deleting. The substitution is now declined BEFORE it happens.++DEFECT TWO: A DECLARATION READ AS A REBUILD. The completion condition was+`threadTotal() >= before`. On a windowed arm `threadTotal()` is `aria-setsize`, the store's claim+about how long the conversation is, and the FIRST reopened row publishes it -- so the condition was+satisfied with three of eighteen messages mounted, no final assistant content and no syntax+highlighting. The action recorded that as `reopen_ms`, took its census off a half-built DOM, and+passed its own assertion because `after == before` compared the same declared total with itself.+The wait is now runtime/readiness.py's own gate: the end of the conversation mounted, and the mount+settled.++Both are conditions on what the action DOES with what the page reports, so both are testable+against a scripted page and neither needs a browser.++ python -m pytest tests/studio/studiobench/scene/selftest/test_studiobench_thread_reopen_gate.py -q+"""++from __future__ import annotations++import sys+import time+from dataclasses import dataclass+from pathlib import Path++_STUDIO_TESTS = Path(__file__).resolve().parents[3]+if str(_STUDIO_TESTS) not in sys.path:+ sys.path.insert(0, str(_STUDIO_TESTS))++from studiobench.runtime.types import ActionContext, Cell # noqa: E402+from studiobench.scene import actions as A # noqa: E402++NEW_CHAT = 'button[aria-label="New chat"]'+SIDEBAR_ROW = '[data-thread-id="t1"]'+BASE_URL = "http://127.0.0.1:1"+THREAD_URL = f"{BASE_URL}/chat?thread=t1"+NEW_CHAT_URL = f"{BASE_URL}/chat?new=studiobench"++#: The length of the seeded thread, and the marker the seeder wrote into its last user turn.+TOTAL = 18+MARKER = "studiobench turn 8: continue with unit 3"+++@dataclass(frozen = True)+class _Frame:+ """One moment of the rebuilt thread, as the page would report it.++ A script of these IS the defect: `setsize` is the store's declared length and it is published+ on the very first frame, while `mounted`, `elements` and `spans` are what has actually been+ built and arrive over the following ones.+ """++ mounted: int+ elements: int+ scroll_height: int+ spans: int+ marker: bool+ setsize: int = TOTAL+++#: A rebuild that declares its full length immediately and then takes four more frames to become a+#: thread. Frame 3 has the whole conversation mounted but is still highlighting, so `elements` is+#: still moving and the mount is not settled until frame 4 repeats it.+REBUILD = (+ _Frame(mounted = 3, elements = 1_200, scroll_height = 2_000, spans = 0, marker = False),+ _Frame(mounted = 9, elements = 4_800, scroll_height = 6_400, spans = 120, marker = False),+ _Frame(mounted = 18, elements = 9_700, scroll_height = 12_000, spans = 4_210, marker = True),+ _Frame(mounted = 18, elements = 11_900, scroll_height = 12_400, spans = 8_940, marker = True),+ _Frame(mounted = 18, elements = 11_900, scroll_height = 12_400, spans = 8_940, marker = True),+)++#: A rebuild that never arrives: the store keeps declaring eighteen messages and the thread stops+#: at three of them, settled, with the end of the conversation nowhere on screen. The exact shape+#: the old condition scored as a fast, successful re-open.+STALLED = (_Frame(mounted = 3, elements = 1_200, scroll_height = 2_000, spans = 0, marker = False),)++#: A correctly windowed rebuild: a window of six rows out of eighteen, anchored at the end, with+#: the last user turn among them. `full` conditions would refuse this forever, which is why the+#: action picks its mode from the mount it left rather than assuming one.+WINDOWED = (+ _Frame(mounted = 2, elements = 900, scroll_height = 11_800, spans = 0, marker = False),+ _Frame(mounted = 6, elements = 3_400, scroll_height = 12_400, spans = 2_100, marker = True),+ _Frame(mounted = 6, elements = 3_400, scroll_height = 12_400, spans = 2_100, marker = True),+)+++class _ThreadPage:+ """A page with a thread on it that can be left and reopened, one frame per poll.++ Three phases, because the action's whole job is to tell them apart: `thread` (the seeded thread+ is on screen), `gone` (the New chat route, nothing mounted) and `rebuild` (walking `frames`).+ Every way of moving between them -- a click, or a `page.goto` -- is recorded, so a test can ask+ what the action DID to the scene and not only what it reported.+ """++ def __init__(+ self,+ *,+ frames = REBUILD,+ unclickable = (),+ mounted = TOTAL,+ total = TOTAL,+ ):+ self.frames = tuple(frames)+ self.unclickable = set(unclickable)+ self.mounted = mounted+ self.total = total+ self.phase = "thread"+ self.step = 0+ self.goto_calls: list[str] = []+ self.probes = 0++ # ── what the page would report ──────────────────────────────────++ @property+ def frame(self) -> _Frame:+ return self.frames[min(self.step, len(self.frames) - 1)]++ def thread_total(self) -> int:+ return {"thread": self.total, "gone": 0}.get(self.phase, self.frame.setsize)++ def message_count(self) -> int:+ return {"thread": self.mounted, "gone": 0}.get(self.phase, self.frame.mounted)++ def _probe(self) -> dict:+ """One reading in the shape runtime/readiness.py's PROBE_JS returns.++ The mounted rows are numbered as a window ANCHORED AT THE END of the conversation --+ `setsize - mounted + 1` through `setsize` -- because that is what the gate requires of a+ windowed arm, and numbering them any other way would be modelling a virtualizer bug rather+ than the thread this action leaves and comes back to.+ """+ self.probes += 1+ f = self.frame+ mounted = self.message_count()+ return {+ "probe_attempted": True,+ "mounted": mounted,+ "elements": f.elements,+ "composer": True,+ "running": False,+ "setsize": f.setsize,+ "setsize_values": [f.setsize],+ "posinset_count": mounted,+ "posinset_distinct": mounted,+ "min_posinset": max(1, f.setsize - mounted + 1) if mounted else None,+ "max_posinset": f.setsize if mounted else None,+ "marker_found": f.marker,+ "marker_from_end": 1 if f.marker else None,+ "last_role": "assistant",+ "last_tail": "...",+ "scroll_height": f.scroll_height,+ "client_height": 900,+ "scroll_top": f.scroll_height - 900,+ "from_bottom": 0,+ "viewport_present": True,+ "jump_button_present": True,+ "app_says_at_bottom": True,+ "pinning": False,+ }++ # ── the Playwright surface the action uses ──────────────────────++ def evaluate(+ self,+ script,+ arg = None,+ ):+ if "probe_attempted" in script: # readiness.PROBE_JS+ return self._probe()+ if "threadTotal" in script:+ return self.thread_total()+ if "messageCount" in script:+ return self.message_count()+ if '[data-role="user"]' in script:+ return MARKER if self.phase != "gone" else None+ if "pre span" in script:+ return self.frame.spans if self.phase == "rebuild" else 0+ # The hit-test spread and the hover target, both of which report "no reachable point" for+ # an unclickable control. Returning None here is what sends `_click_or_navigate` down the+ # branch under test rather than into an off-centre click.+ return None++ def query_selector(self, selector):+ page = self++ class _Handle:+ def click(self, timeout = None):+ if selector in page.unclickable:+ raise TimeoutError(f"{selector} is not clickable")+ page._route(selector)++ return _Handle()++ def goto(self, url, **_kwargs):+ self.goto_calls.append(url)+ self._route(url)++ def wait_for_timeout(self, _ms):+ # A REAL, TINY SLEEP. The readiness wait is bounded on the monotonic clock, so a poll that+ # returned instantly would spin thousands of times inside the timeout instead of walking+ # the scripted frames.+ time.sleep(0.002)+ if self.phase == "rebuild":+ self.step += 1++ # ── phases ──────────────────────────────────────────────────────++ def _route(self, target: str) -> None:+ if "New chat" in target or "new=" in target:+ self.phase = "gone"+ elif "thread-id" in target or "thread=" in target:+ self.phase = "rebuild"+ self.step = 0+++def _ctx(+ page,+ log = None,+ budget_ms = 30_000,+) -> ActionContext:+ return ActionContext(+ page = page,+ cdp = None,+ cell = Cell(cell_id = "r100K.base.rep0", rung = "100K", rung_tokens = 100_000),+ window = None,+ args = {"thread_id": "t1", "base_url": BASE_URL},+ budget_ms = budget_ms,+ dom = None,+ log = log or (lambda _m: None),+ )+++# ── defect one: the fallback is declined, not detected ──────────────+++def test_a_refused_reopen_leaves_the_thread_where_it_found_it():+ """THE COLLATERAL DAMAGE, asserted as damage rather than as a row.++ The action still reports NOT RUN, and the page must still be showing the thread afterwards.+ Before the fix `page.goto` had already run by the time the refusal was decided, so the scene+ continued from an empty new chat and every later slot measured that instead.+ """+ page = _ThreadPage(unclickable = {NEW_CHAT})+ result = A.thread_reopen(_ctx(page))++ assert result.ran is False+ assert result.timings == {}+ assert page.goto_calls == [], "the invalid fallback navigation was performed anyway"+ assert (+ page.phase == "thread"+ ), "the scene was left on the new-chat page for the slots that follow"+ assert page.message_count() == TOTAL, "the following slots inherited an empty thread"+++def test_the_refusal_still_says_why_in_the_row_and_in_the_log():+ """Declining the substitution must not make the refusal quieter than it was."""+ said: list[str] = []+ page = _ThreadPage(unclickable = {NEW_CHAT})+ result = A.thread_reopen(_ctx(page, said.append))++ assert "not a thread rebuild" in (result.reason or "")+ assert "no navigation was performed" in (result.reason or "")+ assert any("NOT MEASURED" in line for line in said), said+++def test_click_or_navigate_declines_the_substitute_when_the_caller_refuses_it():+ """The contract the caller relies on: no goto, `ok = False`, and the click failure explained."""+ page = _ThreadPage(unclickable = {NEW_CHAT})+ got = A._click_or_navigate(_ctx(page), NEW_CHAT, NEW_CHAT_URL, allow_navigate = False)++ assert got.ok is False+ assert got.path == "failed"+ assert got.navigated is False+ assert "not clickable" in (got.reason or "")+ assert page.goto_calls == []+++def test_refusing_the_substitute_does_not_refuse_the_click():+ """`allow_navigate` governs the FALLBACK only. A control that can be clicked is still clicked,+ which is the path every successful run takes."""+ page = _ThreadPage()+ got = A._click_or_navigate(_ctx(page), NEW_CHAT, NEW_CHAT_URL, allow_navigate = False)++ assert got.ok is True+ assert got.path == "click"+ assert page.phase == "gone", "the app's own route change never happened"+++def test_the_default_still_navigates_for_every_other_caller():+ """The signature gained a keyword and must not have changed what anyone else gets. The reopen+ half of `thread_reopen` depends on this: from an empty new chat the navigation is what puts the+ thread back for the slots that follow."""+ page = _ThreadPage(unclickable = {NEW_CHAT})+ got = A._click_or_navigate(_ctx(page), NEW_CHAT, NEW_CHAT_URL)++ assert got.ok is True+ assert got.path == "navigate"+ assert page.goto_calls == [NEW_CHAT_URL]+++def test_a_substituted_navigation_on_the_way_back_repairs_the_scene_but_is_not_timed():+ """THE DELIBERATE ASYMMETRY. Leaving, a navigation is the thing that breaks the scene and is+ refused. Returning, it is what puts the thread back on screen for the slots that follow, so it+ is allowed to stand -- and the action still reports NOT RUN, with no timing, because a document+ reload is still not a rebuild."""+ page = _ThreadPage(unclickable = {SIDEBAR_ROW})+ result = A.thread_reopen(_ctx(page))++ assert result.ran is False+ assert result.timings == {}+ assert "never timed" in (result.reason or "")+ assert page.goto_calls == [THREAD_URL]+ assert page.phase == "rebuild", "the thread was not put back for the slots that follow"+++# ── defect two: a declared total is not a finished rebuild ──────────+++def test_the_scripted_rebuild_declares_its_total_before_it_has_built_anything():+ """WITHOUT THIS THE TEST BELOW PROVES NOTHING. If the first frame did not already publish+ `aria-setsize = 18`, the old condition would have waited too and both would pass."""+ first = REBUILD[0]+ assert first.setsize == TOTAL+ assert first.mounted == 3+ assert first.marker is False and first.spans == 0+++def test_reopen_waits_for_the_thread_to_be_rebuilt_not_for_it_to_be_declared():+ """The reading the old condition produced came off frame 0: three of eighteen rows, no end of+ conversation, no highlighting. Every observation below is taken after the wait, so they are the+ assertion that the wait outlasted the declaration."""+ page = _ThreadPage()+ result = A.thread_reopen(_ctx(page))++ assert result.ran is True+ assert result.expect_ok is True+ assert result.expect["mounted_after"] == 18, "the census was taken off a partly built thread"+ assert result.expect["highlight_spans_after"] == 8_940, "the fences had not been highlighted"+ # Frame 4 is the earliest one that is both end-present and settled, so nothing short of five+ # probes can have satisfied the gate.+ assert page.probes >= 5, page.probes+ assert result.timings["reopen_ms"] is not None+++def test_the_row_carries_the_gate_the_timing_was_taken_against():+ """`reopen_ms` means "until ready", so the row has to say which definition of ready and how it+ was reached. Two arms in different modes are otherwise silently incomparable."""+ page = _ThreadPage()+ result = A.thread_reopen(_ctx(page))++ assert result.expect["reopen_ready_mode"] == "full"+ readiness = result.expect["reopen_readiness"]+ assert readiness["ready"] is True+ assert readiness["conditions"]["end_present"] is True+ assert readiness["conditions"]["settled"] is True+ assert readiness["conditions"]["all_messages_mounted"] is True+++def test_a_thread_that_declares_its_total_and_never_rebuilds_gets_no_timing(monkeypatch):+ """The old condition's worst case, and the one that made the defect invisible: the store+ publishes eighteen, three rows mount, nothing else ever arrives. That was scored as a fast+ re-open. It is now a run with no timing and the outstanding condition named."""+ monkeypatch.setattr(A, "_REOPEN_READY_CEILING_S", 0.4)+ page = _ThreadPage(frames = STALLED)+ result = A.thread_reopen(_ctx(page))++ assert result.ran is True+ assert result.timings["reopen_ms"] is None, "a half-built thread reported a rebuild time"+ assert result.expect_ok is False+ readiness = result.expect["reopen_readiness"]+ assert readiness["ready"] is False+ assert readiness["conditions"]["end_present"] is False+ assert readiness["conditions"]["all_messages_mounted"] is False+ assert "never reached a ready state" in (result.reason or "")+++def test_a_windowed_arm_is_held_to_the_windowed_gate_and_not_to_a_full_mount():+ """The other way this fix could have been wrong. A windowed arm never mounts every message, so+ waiting for a full mount would time out on the arm the whole comparison exists to score. The+ mode is read from the mount the action LEFT, exactly as the cell's opening gate read it."""+ page = _ThreadPage(frames = WINDOWED, mounted = 6, total = TOTAL)+ result = A.thread_reopen(_ctx(page))++ assert result.expect["reopen_ready_mode"] == "windowed"+ assert result.ran is True+ assert result.expect_ok is True+ assert result.expect["mounted_after"] == 6+ assert result.expect["messages_after"] == TOTAL+ conditions = result.expect["reopen_readiness"]["conditions"]+ assert conditions["end_present"] is True+ assert conditions["anchored_at_end"] is True+ assert conditions["total_matches_seeded"] is True+++def test_a_thread_whose_end_cannot_be_identified_is_refused_before_it_is_touched():+ """No marker, no way to tell a rebuilt thread from a half-rebuilt one -- so the action refuses,+ and refuses early enough that the thread it cannot verify is also one it has not disturbed."""++ class _NoMarker(_ThreadPage):+ def evaluate(+ self,+ script,+ arg = None,+ ):+ if '[data-role="user"]' in script:+ return None+ return super().evaluate(script, arg)++ page = _NoMarker()+ result = A.thread_reopen(_ctx(page))++ assert result.ran is False+ assert "identify the end of the thread" in (result.reason or "")+ assert page.phase == "thread" and page.goto_calls == []+++# ── defect three: the harness's own retry, billed to the rebuild ────++#: How long the centre click burns before it gives up. `_click_or_navigate` passes+#: `timeout = 2000` to Playwright, and the hit-target check retries for the whole of it against a+#: control it cannot hit at the centre. Scaled down here so the test is fast; what is asserted is+#: that the timings do not contain it, at whatever size it is.+RETRY_MS = 400+++class _HoverRevealedPage(_ThreadPage):+ """A page whose controls behave the way the sidebar's actually do.++ `.sidebar-header-action` ships `opacity-0 pointer-events-none` and is revealed by its group's+ `:hover`, so every hit test at rest falls through to the group underneath: `handle.click` waits+ out its whole actionability timeout, and the off-centre/hover path is the one that works. That+ is not an edge case, it is the documented behaviour of the New chat button on every run.+ """++ def __init__(+ self,+ *,+ slow = (),+ **kwargs,+ ):+ super().__init__(**kwargs)+ self.slow = set(slow)+ self.moves: list[tuple[float, float]] = []+ self._pending: str | None = None++ def evaluate(+ self,+ script,+ arg = None,+ ):+ if "elementFromPoint" in script or "getBoundingClientRect" in script:+ selector = arg[0] if isinstance(arg, list) else arg+ self._pending = selector+ return {"x": 12.0, "y": 34.0}+ return super().evaluate(script, arg)++ def query_selector(self, selector):+ page = self++ class _Handle:+ def click(self, timeout = None):+ if selector in page.slow:+ # The retry, faithfully: time passes and then it fails.+ time.sleep(RETRY_MS / 1000)+ raise TimeoutError(f"{selector} was not clickable in {timeout}ms")+ page._route(selector)++ return _Handle()++ @property+ def mouse(self):+ page = self++ class _Mouse:+ def move(self, x, y):+ page.moves.append((x, y))++ def click(self, x, y):+ page.moves.append((x, y))+ if page._pending is not None:+ page._route(page._pending)++ return _Mouse()+++def test_the_failed_click_retry_is_not_charged_to_the_close_or_the_rebuild():+ """THE DEFECT. `close_ms` and `reopen_ms` were clocked from before the FIRST click attempt, so+ Playwright's 2,000 ms hit-target retry against the hover-revealed New chat button landed inside+ them -- on every run, since that control is hover-revealed by design. sweep/floor_table.py+ harvests both as quotable metrics, so two seconds of harness retry was being compared against+ the other arm as though it were the cost of tearing down and rebuilding a thread.++ Both clocks now start at the click that WORKED. The retry is not thrown away, it is named.+ """+ page = _HoverRevealedPage(slow = {NEW_CHAT, SIDEBAR_ROW})+ result = A.thread_reopen(_ctx(page))++ assert result.ran is True, result.reason+ assert page.goto_calls == [], "the click path was available and should not have been replaced"+ close_ms = result.timings["close_ms"]+ reopen_ms = result.timings["reopen_ms"]+ assert close_ms < RETRY_MS, f"the retry is still inside close_ms ({close_ms}ms)"+ assert reopen_ms < RETRY_MS, f"the retry is still inside reopen_ms ({reopen_ms}ms)"+ # ...and it is still in the payload, as the harness's own cost rather than the app's.+ assert result.expect["left_click_retry_ms"] >= RETRY_MS+ assert result.expect["reopen_click_retry_ms"] >= RETRY_MS+++def test_a_control_that_clicks_first_time_reports_no_retry_at_all():+ """The control. Nothing about the ordinary path moves, and the new fields read zero rather than+ a small plausible number that a reader would have to interpret."""+ page = _HoverRevealedPage()+ result = A.thread_reopen(_ctx(page))++ assert result.ran is True, result.reason+ assert result.expect["left_click_retry_ms"] < 50+ assert result.expect["reopen_click_retry_ms"] < 50+ assert result.timings["reopen_ms"] > 0diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_visible_capture_live.py b/tests/studio/studiobench/scene/selftest/test_studiobench_visible_capture_live.pynew file mode 100644index 00000000000..42677022dc2--- /dev/null+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_visible_capture_live.py@@ -0,0 +1,729 @@+# 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 VISIBLE-REGION OBSERVER, in a real browser.++`compare_visible` is tested offline against hand-written captures, which proves the verdict logic+and proves nothing about whether the captures describe reality. Whether IntersectionObserver sees+what a user sees -- across a scroll, across mounting and unmounting, at the edge of the viewport --+is not a question a fixture dictionary can answer, so it is asked of Chromium here.++The three things that would make this instrument quietly wrong, each pinned:++ IT MUST SEE A PARTLY VISIBLE MESSAGE. One pixel into the viewport is visible to a user, and a+ threshold that rounded it away would exempt real differences at the top and bottom of the screen+ -- the two places a scroll spends most of its time.++ IT MUST ACCUMULATE ACROSS THE ACTION. An action that scrolls shows messages and hides them again.+ A single sample at the close of the window compares wherever the scroll happened to stop and+ silently ignores everything the user saw on the way. The compared set is the UNION.++ IT MUST NOT READ GEOMETRY. `getBoundingClientRect()` / `getClientRects()` on content inside a+ `content-visibility` locked subtree makes Chromium render that subtree to answer, so a+ geometry-based visibility probe unlocks exactly what it came to observe. One session reported 0+ off-screen unrendered roots while the event counter recorded 22 in the skipped state. This test+ installs a counting trap on both methods and fails if the capture touches either.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++_HERE = Path(__file__).resolve()+_STUDIO_TESTS = _HERE.parents[3]+if str(_STUDIO_TESTS) not in sys.path:+ sys.path.insert(0, str(_STUDIO_TESTS))++_DOM_JS = _STUDIO_TESTS / "studiobench" / "scene" / "dom.js"+_PARITY_JS = _STUDIO_TESTS / "studiobench" / "scene" / "parity.js"++#: A thread of tall messages in a short viewport, so only a few are ever on screen at once. Each+#: message publishes `aria-posinset`, which is how a windowed arm states thread position; the+#: capture keys on it so a window and a full mount are comparable.+FIXTURE = """+<!doctype html><meta charset="utf-8">+<style>+ body { margin: 0; }+ .aui-thread-viewport { height: 400px; overflow-y: auto; }+ /* The OBSERVED element is the tall one, as in the app: `[data-role]` is the message and the+ virtualizer's row wrapper around it carries aria-posinset. An earlier version of this fixture+ made the row tall and left `[data-role]` an 18px line of text inside it, so a scroll step+ jumped clean over the observed target and the union test failed for a reason that was entirely+ the fixture's. */+ [data-role] { height: 500px; }+</style>+<div class="aui-thread-root">+ <div class="aui-thread-viewport" id="vp"></div>+</div>+<script>+ window.__build = (count) => {+ const vp = document.getElementById("vp");+ vp.innerHTML = "";+ for (let i = 1; i <= count; i++) {+ const row = document.createElement("div");+ row.className = "row";+ row.setAttribute("aria-posinset", String(i));+ row.setAttribute("aria-setsize", String(count));+ const msg = document.createElement("div");+ msg.setAttribute("data-role", i % 2 ? "user" : "assistant");+ msg.textContent = "message " + i;+ row.appendChild(msg);+ vp.appendChild(row);+ }+ };+ window.__build(20);+</script>+"""+++def _skip_reason() -> str | None:+ try:+ from playwright.sync_api import sync_playwright # noqa: F401+ except Exception as exc: # noqa: BLE001+ return f"playwright is not installed: {exc}"+ return None+++pytestmark = pytest.mark.skipif(_skip_reason() is not None, reason = _skip_reason() or "")++[email protected](scope = "module")+def browser():+ from playwright.sync_api import sync_playwright+ with sync_playwright() as p:+ try:+ b = p.chromium.launch(args = ["--no-sandbox"])+ except Exception as exc: # noqa: BLE001+ pytest.skip(f"chromium could not be launched: {exc}")+ yield b+ b.close()+++def page(browser):+ pg = browser.new_page(viewport = {"width": 800, "height": 600})+ pg.set_content(FIXTURE)+ # `add_script_tag` after the content, not `add_init_script` before it: Playwright's+ # `set_content` does not always run init scripts, and the symptom is `window.__sb` simply not+ # existing, which reads like a broken instrument rather than a mis-ordered fixture.+ pg.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))+ pg.add_script_tag(content = _PARITY_JS.read_text(encoding = "utf-8"))+ yield pg+ pg.close()+++def _watch(page) -> None:+ got = page.evaluate("() => window.__sb.parityVisible.watch()")+ assert got.get("visible_attempted") is True, got+ # IntersectionObserver's first delivery is asynchronous, so give it a frame before anything+ # scrolls. Without this the initial viewport contents are attributed to whatever came next.+ page.wait_for_timeout(120)+++def _capture(page) -> dict:+ page.wait_for_timeout(120)+ return page.evaluate("async () => await window.__sb.parityVisible.capture()")+++# ── what the viewport actually showed ───────────────────────────────+++def test_it_reports_only_what_the_viewport_showed(page):+ _watch(page)+ got = _capture(page)+ assert got["visible_attempted"] is True+ # A 400px viewport over 500px rows: message 1 fills it, message 2 is not reached.+ assert got["ever_visible"] == [1], got["ever_visible"]+ assert set(got["messages"]) == {"1"}+++def test_a_partly_visible_message_counts_as_visible(page):+ """One pixel of message 2 inside the viewport. A threshold that rounded this away would exempt+ real differences at the top and bottom of the screen."""+ _watch(page)+ page.evaluate("() => { document.getElementById('vp').scrollTop = 101; }")+ got = _capture(page)+ assert got["ever_visible"] == [1, 2], got["ever_visible"]+++def test_the_compared_set_is_the_union_across_the_whole_action(page):+ """The scroll passes over messages 1 to 8 and lands showing 7 and 8. A single sample at the+ close would report two; the user saw eight."""+ _watch(page)+ for top in (0, 700, 1400, 2100, 2800, 3200):+ page.evaluate(f"() => {{ document.getElementById('vp').scrollTop = {top}; }}")+ page.wait_for_timeout(60)+ got = _capture(page)+ assert got["ever_visible"][0] == 1+ assert len(got["ever_visible"]) >= 7, got["ever_visible"]+ assert 7 in got["ever_visible"] and 8 in got["ever_visible"]+++def test_a_message_mounted_mid_action_is_observed_too(page):+ """A windowed list mounts rows as it scrolls. Rows that appear after the observer was installed+ have to be picked up, or a windowed arm reports only what it happened to have mounted at the+ start and the comparison silently shrinks to nothing."""+ page.evaluate("() => window.__build(2)")+ _watch(page)+ page.evaluate("() => window.__build(20)")+ page.wait_for_timeout(120)+ page.evaluate("() => { document.getElementById('vp').scrollTop = 1400; }")+ got = _capture(page)+ assert 3 in got["ever_visible"] or 4 in got["ever_visible"], got["ever_visible"]+++def test_an_unmounted_message_is_still_reported_as_having_been_visible(page):+ """The honest residue. It was on screen, so it belongs in `ever_visible`; it is gone, so it+ cannot be digested, and the gap is reported rather than quietly closed."""+ _watch(page)+ page.evaluate("() => { document.getElementById('vp').scrollTop = 2100; }")+ page.wait_for_timeout(120)+ page.evaluate("() => window.__build(0)")+ got = _capture(page)+ assert got["ever_visible_count"] > 0+ assert got["mounted_ever_visible"] == 0+ assert got["unmounted_at_capture"] == got["ever_visible_count"]+++# ── the trap ────────────────────────────────────────────────────────+++def test_the_capture_never_reads_geometry(page):+ """THE CONTENT-VISIBILITY TRAP, held closed by construction rather than by review.++ Reading a rect inside a `content-visibility` locked subtree makes Chromium render it, so a+ geometry-based visibility probe destroys the very state it is measuring and then reports that+ nothing was skipped. If anyone reaches for `getBoundingClientRect` in this path later, this+ fails.+ """+ page.evaluate(+ """() => {+ window.__geom = 0;+ for (const name of ["getBoundingClientRect", "getClientRects"]) {+ const original = Element.prototype[name];+ Element.prototype[name] = function () {+ window.__geom += 1;+ return original.apply(this, arguments);+ };+ }+ }"""+ )+ _watch(page)+ page.evaluate("() => { document.getElementById('vp').scrollTop = 1400; }")+ got = _capture(page)+ assert got["ever_visible"], "the capture returned nothing, so the trap proves nothing"+ assert page.evaluate("() => window.__geom") == 0, (+ "the visible-region capture read element geometry, which forces a content-visibility "+ "locked subtree to render and makes the probe change what it observes"+ )+++# ── refusals ────────────────────────────────────────────────────────+++def test_capturing_without_watching_is_refused_not_reported_empty(page):+ got = page.evaluate("async () => await window.__sb.parityVisible.capture()")+ assert got["visible_attempted"] is False+ assert "never installed" in got["reason"]+++def test_a_page_with_no_thread_viewport_is_refused(page):+ page.evaluate("() => { document.querySelector('.aui-thread-viewport').remove(); }")+ got = page.evaluate("() => window.__sb.parityVisible.watch()")+ assert got["visible_attempted"] is False, got+ assert "viewport" in got["reason"]+++# ── the instrument must not charge its own cost to the action ───────+++def test_the_top_up_is_proportional_to_the_mutation_not_to_the_document(page):+ """WORKSPACE TASK #102, WHICH THIS NEARLY REPEATED.++ The visibility observer's MutationObserver is the one part of this instrument that runs INSIDE+ the measured action window. The obvious implementation re-runs the full `querySelectorAll` scan+ on every mutation batch, which charges an O(document) walk to the action, once per batch, on a+ DOM whose size is the quantity under investigation. That is exactly the defect that reported+ `delete_message` at 14.3 fps when the action costs 49.0.++ So the top-up walks only `addedNodes`. This is asserted by counting `querySelectorAll` calls+ against the DOCUMENT while a stream-like mutation storm runs: text churning inside already+ mounted rows must produce none at all, because childList records do not fire for it.+ """+ page.evaluate(+ """() => {+ window.__docQsa = 0;+ const original = Document.prototype.querySelectorAll;+ Document.prototype.querySelectorAll = function () {+ window.__docQsa += 1;+ return original.apply(this, arguments);+ };+ }"""+ )+ _watch(page)+ # The handle is taken BEFORE the baseline, because looking the element up is itself a+ # document-wide query and would otherwise be counted against the instrument.+ page.evaluate(+ """() => {+ const rows = document.querySelectorAll("[data-role]");+ window.__last = rows[rows.length - 1];+ }"""+ )+ baseline = page.evaluate("() => window.__docQsa")+ # A stream: the last message's text changes many times, and nothing is added or removed.+ page.evaluate(+ "() => { for (let i = 0; i < 200; i++) window.__last.textContent = 'streaming ' + i; }"+ )+ page.wait_for_timeout(150)+ assert page.evaluate("() => window.__docQsa") == baseline, (+ "a text mutation inside a mounted row triggered a document-wide scan, so the instrument "+ "charges an O(document) walk to whatever action happens to be streaming"+ )+++def test_a_row_mounted_during_the_action_is_still_picked_up_cheaply(page):+ """The top-up has to actually work, or the previous test passes by doing nothing."""+ page.evaluate("() => window.__build(2)")+ _watch(page)+ page.evaluate(+ """() => {+ const vp = document.getElementById("vp");+ const row = document.createElement("div");+ row.setAttribute("aria-posinset", "3");+ const msg = document.createElement("div");+ msg.setAttribute("data-role", "assistant");+ msg.textContent = "late arrival";+ row.appendChild(msg);+ vp.appendChild(row);+ }"""+ )+ page.wait_for_timeout(120)+ page.evaluate("() => { document.getElementById('vp').scrollTop = 900; }")+ got = _capture(page)+ assert 3 in got["ever_visible"], got["ever_visible"]+++# ── where the virtualizer publishes its ordinals is not a UI change ──+#+# `runtime/readiness.py` accepts `aria-posinset` / `aria-setsize` on the `[data-role]` message OR on+# an ancestor row wrapper -- it walks with `closest()`, because the ordinal belongs on whichever+# element is the member of the set, and refusing the first option would refuse a correctly+# implemented arm for putting the attribute in a place the gate itself calls right.+#+# The visible-region digest then read every attribute on the message, so an arm that took that+# option differed from the fully mounted arm on EVERY message -- which publishes neither attribute+# anywhere -- while the rendered content was identical. Auto-mode parity was unusable for a DOM+# shape the gate explicitly permits, and a wall of differences that are all the same non-finding+# buries anything real underneath it.+++def _arm_html(ordinals: str, suffix: str = "") -> str:+ """One thread of twenty messages, with the virtualization ordinals published `on_the_message`,+ `on_the_row` wrapper, or `nowhere` -- which is what the shipped build does."""+ return """+<!doctype html><meta charset="utf-8">+<style>+ body { margin: 0; }+ .aui-thread-viewport { height: 400px; overflow-y: auto; }+ [data-role] { height: 500px; }+</style>+<div class="aui-thread-root">+ <div class="aui-thread-viewport" id="vp"></div>+</div>+<script>+ const WHERE = "__WHERE__";+ const vp = document.getElementById("vp");+ for (let i = 1; i <= 20; i++) {+ const row = document.createElement("div");+ row.className = "row";+ const msg = document.createElement("div");+ msg.setAttribute("data-role", i % 2 ? "user" : "assistant");+ msg.textContent = "message " + i + "__SUFFIX__";+ row.appendChild(msg);+ if (WHERE !== "nowhere") {+ const owner = WHERE === "on_the_message" ? msg : row;+ owner.setAttribute("aria-posinset", String(i));+ owner.setAttribute("aria-setsize", "20");+ }+ vp.appendChild(row);+ }+</script>+""".replace("__WHERE__", ordinals).replace("__SUFFIX__", suffix)+++def _capture_arm(+ browser,+ ordinals: str,+ suffix: str = "",+) -> dict:+ pg = browser.new_page(viewport = {"width": 800, "height": 600})+ pg.set_content(_arm_html(ordinals, suffix))+ pg.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))+ pg.add_script_tag(content = _PARITY_JS.read_text(encoding = "utf-8"))+ try:+ _watch(pg)+ return _capture(pg)+ finally:+ pg.close()+++def _thread_digests(browser, ordinals: str) -> dict:+ """The WHOLE-DOCUMENT structural digest of the same page, per message."""+ pg = browser.new_page(viewport = {"width": 800, "height": 600})+ pg.set_content(_arm_html(ordinals))+ pg.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))+ pg.add_script_tag(content = _PARITY_JS.read_text(encoding = "utf-8"))+ try:+ got = pg.evaluate("() => window.__sb.parity.capture()")+ return {row["i"]: row["digest"] for row in got["messages"]}+ finally:+ pg.close()+++def test_ordinals_on_the_message_do_not_make_every_message_differ(browser):+ """THE DEFECT. Same twenty messages, same text, same everything a user can see -- one arm+ publishing the ordinals the gate requires of it, the other publishing none."""+ from studiobench.analysis import parity as P++ windowed = _capture_arm(browser, "on_the_message")+ full = _capture_arm(browser, "nowhere")+ shared = sorted(set(windowed["messages"]) & set(full["messages"]))+ assert shared, (windowed["messages"], full["messages"])+ for key in shared:+ assert (+ windowed["messages"][key]["digest"] == full["messages"][key]["digest"]+ ), f"ordinal {key} differed on the virtualization bookkeeping alone"+ verdict = P.compare_visible(full, windowed)+ assert verdict["verdict"] == P.MATCH, verdict+++def test_ordinals_on_the_row_wrapper_are_unaffected_as_they_always_were(browser):+ """The other permitted placement, which was never inside the message's subtree and so was never+ part of the defect. It must stay comparable."""+ from studiobench.analysis import parity as P+ assert (+ P.compare_visible(_capture_arm(browser, "nowhere"), _capture_arm(browser, "on_the_row"))[+ "verdict"+ ]+ == P.MATCH+ )+++def test_a_real_rendering_difference_is_still_caught(browser):+ """THE POSITIVE CONTROL, without which the test above passes on a digest that stopped looking+ at anything. One arm renders different text; that is a visible difference and must still be."""+ from studiobench.analysis import parity as P++ verdict = P.compare_visible(+ _capture_arm(browser, "nowhere"), _capture_arm(browser, "on_the_message", suffix = " (v2)")+ )+ assert verdict["verdict"] == P.DIFFER, verdict+++# ── a rebuilt row is at its own position, not at the end of a lifetime count ──+#+# `thread_reopen` leaves the thread and comes back, and a FULLY MOUNTED arm answers that by+# removing every message row and creating a new one for every message inside the same document.+# Those rebuilt rows publish no `aria-posinset` -- only a windowed arm publishes one -- so their+# ordinal comes from the fallback, and the fallback used to be a LIFETIME counter of observed+# nodes. It already stood at N, so the rebuilt rows were stamped N+1..2N while the windowed arm on+# the other side of the A/B stamped its real 1..N. `compare_visible` compares the two sets of+# ordinals first, found them disjoint, and reported "the two arms put DIFFERENT MESSAGES on+# screen" -- a hard visible-difference verdict -- for a rebuild that was identical.+++#: The shipped shape: every message mounted, and NOTHING publishing a virtualization ordinal.+#: `__rebuild()` is the thread_reopen rebuild, in one commit, in the same document.+REBUILD_FIXTURE = """+<!doctype html><meta charset="utf-8">+<style>+ body { margin: 0; }+ .aui-thread-viewport { height: 400px; overflow-y: auto; }+ [data-role] { height: 500px; }+</style>+<div class="aui-thread-root">+ <div class="aui-thread-viewport" id="vp"></div>+</div>+<script>+ window.__rebuild = () => {+ const vp = document.getElementById("vp");+ vp.innerHTML = "";+ for (let i = 1; i <= 20; i++) {+ const row = document.createElement("div");+ row.className = "row";+ const msg = document.createElement("div");+ msg.setAttribute("data-role", i % 2 ? "user" : "assistant");+ msg.textContent = "message " + i;+ row.appendChild(msg);+ vp.appendChild(row);+ }+ };+ window.__rebuild();+</script>+"""+++def _rebuild_page(browser):+ pg = browser.new_page(viewport = {"width": 800, "height": 600})+ pg.set_content(REBUILD_FIXTURE)+ pg.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))+ pg.add_script_tag(content = _PARITY_JS.read_text(encoding = "utf-8"))+ return pg+++def _capture_after_rebuild(browser) -> dict:+ pg = _rebuild_page(browser)+ try:+ _watch(pg)+ pg.evaluate("() => window.__rebuild()")+ pg.wait_for_timeout(150)+ return _capture(pg)+ finally:+ pg.close()+++def test_a_rebuilt_row_carries_its_thread_position_not_a_lifetime_count(browser):+ """THE DEFECT. Twenty messages are observed, then all twenty rows are replaced. The viewport+ still shows message 1 and nothing else, so that is the only ordinal the capture may report."""+ got = _capture_after_rebuild(browser)+ assert got["ever_visible"] == [1], got["ever_visible"]+ assert set(got["messages"]) == {"1"}, got["messages"]+ # Every rebuilt row was placed, so nothing was dropped to buy the assertion above.+ assert got["unplaced_rows"] == 0, got+++def test_a_rebuilt_full_mount_still_matches_a_windowed_arm(browser):+ """THE SYMPTOM, end to end: the verdict `thread_reopen` was getting on every pair.++ The two arms render the same twenty messages and show the same one. One rebuilds its rows the+ way a fully mounted arm does on reopen; the other publishes the ordinals the readiness gate+ requires of a windowed arm. Nothing a user could see differs, and the pair must say so.+ """+ from studiobench.analysis import parity as P++ verdict = P.compare_visible(+ _capture_after_rebuild(browser), _capture_arm(browser, "on_the_row")+ )+ assert verdict["verdict"] == P.MATCH, verdict+++def test_a_real_difference_after_a_rebuild_is_still_caught(browser):+ """THE POSITIVE CONTROL for the two above, without which they pass on an instrument that+ stopped distinguishing anything. Same rebuild, different rendered text on the other arm."""+ from studiobench.analysis import parity as P++ verdict = P.compare_visible(+ _capture_after_rebuild(browser), _capture_arm(browser, "on_the_row", suffix = " (v2)")+ )+ assert verdict["verdict"] == P.DIFFER, verdict+++def _count_document_queries(pg) -> None:+ pg.evaluate(+ """() => {+ window.__docQsa = 0;+ const original = Document.prototype.querySelectorAll;+ Document.prototype.querySelectorAll = function () {+ window.__docQsa += 1;+ return original.apply(this, arguments);+ };+ }"""+ )+++def test_placing_a_batch_of_rebuilt_rows_costs_ONE_document_read_for_the_batch(browser):+ """THE PRICE OF GETTING THE ORDINAL RIGHT, and the reason a counter was tempting.++ Resolving a position needs the thread's current message list, and `observeAdded` runs inside+ the MEASURED action window. Read per row, a twenty-row rebuild would charge twenty O(document)+ walks to `thread_reopen` on a DOM whose size is the quantity under investigation -- workspace+ task #102 all over again. The index is therefore built once per mutation batch and shared by+ every row in it.++ Exactly one, in both directions: more than one means the lookup is back on the per-row path,+ and NONE means no position was resolved from the DOM at all, which is the lifetime counter+ this replaced.+ """+ pg = _rebuild_page(browser)+ try:+ _count_document_queries(pg)+ _watch(pg)+ baseline = pg.evaluate("() => window.__docQsa")+ pg.evaluate("() => window.__rebuild()")+ pg.wait_for_timeout(150)+ spent = pg.evaluate("() => window.__docQsa") - baseline+ finally:+ pg.close()+ assert spent == 1, f"a twenty-row rebuild in one batch cost {spent} document-wide queries"+++def test_a_row_that_publishes_its_ordinal_costs_no_document_read_at_all(browser):+ """A windowed arm mounts rows continuously as it scrolls, and it is the arm that would pay+ most for a document read per batch. It publishes `aria-posinset`, which is read first and+ answers the question outright, so it never reaches the position index."""+ pg = browser.new_page(viewport = {"width": 800, "height": 600})+ pg.set_content(FIXTURE)+ pg.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))+ pg.add_script_tag(content = _PARITY_JS.read_text(encoding = "utf-8"))+ try:+ _count_document_queries(pg)+ _watch(pg)+ baseline = pg.evaluate("() => window.__docQsa")+ # Ten more rows, each publishing its own position, in one batch.+ pg.evaluate(+ """() => {+ const vp = document.getElementById("vp");+ for (let i = 21; i <= 30; i++) {+ const row = document.createElement("div");+ row.setAttribute("aria-posinset", String(i));+ row.setAttribute("aria-setsize", "30");+ const msg = document.createElement("div");+ msg.setAttribute("data-role", "assistant");+ msg.textContent = "message " + i;+ row.appendChild(msg);+ vp.appendChild(row);+ }+ }"""+ )+ pg.wait_for_timeout(150)+ spent = pg.evaluate("() => window.__docQsa") - baseline+ finally:+ pg.close()+ assert spent == 0, f"a windowed arm's mounted rows cost {spent} document-wide queries"+++def test_the_structural_digest_still_sees_the_ordinals(browser):+ """THE SCOPING DECISION, in the browser. The exclusion is passed in by the visible-region+ caller and is NOT baked into the shared `signature`: the structural digest only ever scores+ pairs where neither arm is windowing, and there an ordinal appearing on every message is a real+ change that somebody should be shown."""+ numbered = _thread_digests(browser, "on_the_message")+ plain = _thread_digests(browser, "nowhere")+ assert set(numbered) == set(plain)+ assert all(numbered[i] != plain[i] for i in numbered), (numbered, plain)+++# ── a recycled node, and the ordinal it used to be denied ──────────────────+++#: An EMPTY viewport, so a row appended to it is on screen immediately. `__churn` mounts a row and+#: unmounts it inside ONE task, which is how a row comes to be observed while detached: the+#: MutationObserver batch runs after both operations, the node is in `addedNodes` and is no longer+#: among the document's messages, so it has no position the instrument can honestly claim.+#: `__remount` then hands THE SAME NODE back, which is what a virtualizer that recycles its rows+#: does on the next scroll step.+RECYCLE_FIXTURE = """+<!doctype html><meta charset="utf-8">+<style>+ body { margin: 0; }+ .aui-thread-viewport { height: 400px; overflow-y: auto; }+ [data-role] { height: 100px; }+</style>+<div class="aui-thread-root">+ <div class="aui-thread-viewport" id="vp"></div>+</div>+<script>+ window.__row = null;+ window.__churn = () => {+ const vp = document.getElementById("vp");+ const msg = document.createElement("div");+ msg.setAttribute("data-role", "assistant");+ msg.textContent = "recycled row";+ window.__row = msg;+ vp.appendChild(msg);+ vp.removeChild(msg);+ };+ window.__remount = () => {+ document.getElementById("vp").appendChild(window.__row);+ };+</script>+"""+++def test_a_recycled_row_is_placed_when_it_finally_mounts(browser):+ """REGRESSION. An unplaceable row must not be blacklisted from ever being placed.++ `observeOne` marked every node it looked at as `seen` BEFORE trying to place it, so a row+ observed while detached -- unplaceable, and correctly so -- could never be stamped afterwards.+ A virtualizer that recycles DOM nodes hands that same node back mounted and about to be shown;+ the early return fired, no ordinal was stamped, and every intersection it reported was dropped+ for want of one. The row was on screen and absent from `ever_visible`, which is exactly the+ silence `compare_visible` cannot see: with the other rows placed and matching, it returns+ MATCH while a visible row went uncompared.+ """++ pg = browser.new_page(viewport = {"width": 800, "height": 600})+ try:+ pg.set_content(RECYCLE_FIXTURE)+ pg.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))+ pg.add_script_tag(content = _PARITY_JS.read_text(encoding = "utf-8"))+ _watch(pg)+ pg.evaluate("() => window.__churn()")+ pg.wait_for_timeout(150)+ # It was refused a position, and that refusal is counted rather than silent.+ assert pg.evaluate("async () => (await window.__sb.parityVisible.capture()).unplaced_rows")+ pg.evaluate("() => window.__remount()")+ got = _capture(pg)+ finally:+ pg.close()++ # Mounted into an empty viewport, so it is message 1 and it is on screen.+ assert got["ever_visible"] == [1], got+++#: A row that is RENUMBERED IN PLACE. It stays connected, stays intersecting, and is handed to+#: another message -- which is what a virtualizer that recycles its row nodes does, and it is not a+#: childList mutation, so nothing about it reaches a childList-only observer.+RENUMBER_FIXTURE = """+<!doctype html><meta charset="utf-8">+<style>+ body { margin: 0; }+ .aui-thread-viewport { height: 400px; overflow-y: auto; }+ [data-role] { height: 100px; }+</style>+<div class="aui-thread-root">+ <div class="aui-thread-viewport" id="vp">+ <div aria-posinset="1"><div data-role="user" id="row">message 1</div></div>+ </div>+</div>+<script>+ window.__renumber = () => {+ const holder = document.getElementById("row").parentElement;+ holder.setAttribute("aria-posinset", "42");+ document.getElementById("row").textContent = "message 42";+ };+</script>+"""+++def test_a_row_renumbered_in_place_is_restamped_and_reported(browser):+ """REGRESSION. A placed row used to be marked `seen` and never looked at again, which assumed+ a row's position in the thread cannot change while the node lives. A recycling virtualizer+ breaks that on purpose.++ The node kept its original `__sbOrdinal`, so the message it now showed was never reported+ visible, and its content was digested under the position it no longer held: `ever_visible` said+ [1] and `messages["1"]` carried message 42's digest. Because the row never stopped intersecting+ the IntersectionObserver had no change to report, and because the mutation observer took+ childList records only, the renumbering was invisible to every path at once.+ """++ pg = browser.new_page(viewport = {"width": 800, "height": 600})+ try:+ pg.set_content(RENUMBER_FIXTURE)+ pg.add_script_tag(content = _DOM_JS.read_text(encoding = "utf-8"))+ pg.add_script_tag(content = _PARITY_JS.read_text(encoding = "utf-8"))+ _watch(pg)+ pg.evaluate("() => window.__renumber()")+ got = _capture(pg)+ finally:+ pg.close()++ # The row is still on screen, so BOTH the position it held and the one it holds now were shown.+ assert 42 in got["ever_visible"], got["ever_visible"]+ # And its content is filed under the position it actually holds.+ assert "42" in got["messages"], got["messages"]+ assert got["unplaced_rows"] == 0, gotdiff --git a/tests/studio/studiobench/scoring/from_payload.py b/tests/studio/studiobench/scoring/from_payload.pyindex 7c0549e98f5..e0ff367cc11 100644--- a/tests/studio/studiobench/scoring/from_payload.py+++ b/tests/studio/studiobench/scoring/from_payload.py@@ -328,6 +328,25 @@ def _stream_windows(windows: Sequence[Mapping[str, Any]]) -> tuple[list[Mapping[str(sc.get("reply_chars_delta_reason") or "the reply's growth was not measurable"))continue+ # THE INSTRUMENT'S OWN VERDICT ON ITS DENOMINATOR, and it is consulted here because this is+ # the only place that can act on it. `instruments/streamcost.py` marks a window unscoreable+ # when an SSE frame failed to parse inside it or an unterminated frame was still buffered+ # at its close -- and per the HTML standard an event is dispatched only at the blank line+ # that terminates it, so those characters have not been counted and cannot be recovered.+ # The delta is therefore short by an unknown amount, and every cost-per-character divided+ # by it comes out inflated. Publishing the flag and then summing the delta anyway left the+ # official metrics derived from a denominator the instrument had already disowned.+ #+ # `is False` and not falsiness: a payload recorded before the flag existed carries no key+ # at all, and those windows are admitted exactly as they were rather than voided wholesale.+ if sc.get("reply_chars_scoreable") is False:+ reject(+ str(+ sc.get("reply_chars_unscoreable_reason")+ or "the instrument marked this window's wire character count unscoreable"+ )+ )+ continueif int(delta) < MIN_STREAM_CHARS_PER_WINDOW:reject(f"the reply grew by fewer than {MIN_STREAM_CHARS_PER_WINDOW} characters")continuediff --git a/tests/studio/studiobench/scoring/schema.py b/tests/studio/studiobench/scoring/schema.pyindex 16301a298c2..56e51e008c8 100644--- a/tests/studio/studiobench/scoring/schema.py+++ b/tests/studio/studiobench/scoring/schema.py@@ -49,6 +49,32 @@ ZERO_OK_KEYS = frozenset(# an ordinal like every other name on this list, and rejecting it made `--report` fail# on any payload that carried parity rows at all."i",+ # ── the visible-region capture, whose zeros are all true statements ──+ #+ # NOT the whole `visible` subtree, deliberately. Exempting a subtree here once already+ # defeated a test that required a zero-length `chars` inside `parity` to stay a loud+ # failure, and the same argument applies with more force to this one: a visible message+ # whose signature is zero characters long is a broken capture and must stay loud. Only the+ # counters are named, and each is a fact rather than a measurement:+ # unmounted_at_capture: 0 every message the viewport showed was still mounted+ # mounted_ever_visible: 0 a windowed arm had unmounted them all again, which the+ # analysis reports as NOT COMPARABLE rather than as agreement+ # ever_visible_count: 0 the scan observed nothing, which the positive control in+ # compare_visible refuses; it is not scored anywhere+ # ── the SSE wire's integrity counters, whose zeros are the good outcome ──+ #+ # Again the scalars and not the `wire` subtree. "No frame failed to parse" and "no+ # unterminated frame was left buffered" are the statements that make the character count+ # trustworthy, and a run where they are zero is the run whose denominator can be scored.+ # `wireChars` itself is NOT on this list: a zero there means nothing was ever counted and+ # must stay loud.+ "wire_parse_failures",+ "wire_pending_chars",+ "wire_parse_failures_in_window",+ "wire_pending_chars_at_close",+ "ever_visible_count",+ "mounted_ever_visible",+ "unmounted_at_capture","rung_index","arm_index","window_index",@@ -125,6 +151,13 @@ EXEMPT_SUBTREE_KEYS = frozenset("streamed_census","seeded_census","expect",+ # The readiness gate's verdict and the completeness probe's, both written once per cell by+ # the session layer. Same rule as a census: `from_bottom: 0` is a true statement that the+ # viewport is exactly at the bottom, `waited_ms: 0` is a thread that was ready on the+ # first sample, and neither is a measurement of the app. Nothing here is scored; what the+ # gate produces for the report is a `gate` row, which carries a boolean.+ "readiness",+ "completeness","notes","scene","cell",diff --git a/tests/studio/studiobench/scoring/selftest/test_studiobench_from_payload.py b/tests/studio/studiobench/scoring/selftest/test_studiobench_from_payload.pyindex 5dc3f25c191..bc1aa8fca92 100644--- a/tests/studio/studiobench/scoring/selftest/test_studiobench_from_payload.py+++ b/tests/studio/studiobench/scoring/selftest/test_studiobench_from_payload.py@@ -301,6 +301,75 @@ def test_measures_by_cell_does_not_mix_readings_between_cells():assert by_cell[(10_000, 1)]["menu_open_ms"].value == pytest.approx(900.0)+def test_the_wire_integrity_counters_may_be_zero():+ """Zero here is the GOOD outcome and the one that makes the denominator trustworthy: no SSE+ frame failed to parse, and no unterminated frame was left buffered at the window's close. A+ clean run tripped the bare-zero ban and no report could be built from it at all."""+ validate_payload(+ {+ "excluded_cells": [],+ "blk": {+ "wire_parse_failures": 0,+ "wire_pending_chars": 0,+ "wire_parse_failures_in_window": 0,+ "wire_pending_chars_at_close": 0,+ },+ }+ )+++def test_a_wire_character_count_of_zero_is_still_a_failure():+ """The exemption is deliberately the counters and not the count. `wireChars` at zero means+ nothing was ever counted, which is a broken instrument rather than a clean stream, and it must+ stay loud."""+ with pytest.raises(PayloadSchemaError):+ validate_payload({"excluded_cells": [], "blk": {"wire_chars": 0}})+++def test_a_thread_that_was_not_yanked_back_can_still_be_reported():+ """The block `runtime/session.py` writes as `scroll_intent`, with the reading that broke CI.++ `detached_samples: 7, yanked_back_samples: 0` is the GOOD outcome -- the user scrolled away and+ the app left them there -- and it made the whole payload unrenderable: the real-path CI session+ ran every action, wrote its cell, and then `--report` refused with `bare zeros found:+ $.cells[0].scroll_intent.yanked_back_samples = 0`. The block is derived from the same page-side+ read as `follow`, which is covered by its own `follow_attempted`, so it carries the same+ attestation rather than a new exemption.+ """+ validate_payload(+ {+ "excluded_cells": [],+ "cells": [+ {+ "row_type": "cell",+ "completed": True,+ "scroll_intent": {+ "follow_attempted": True,+ "detached_samples": 7,+ "yanked_back_samples": 0,+ "gated": False,+ "reason": "counts legitimate re-pins as well as yanks",+ },+ }+ ],+ }+ )+++def test_the_scroll_intent_block_still_attests_in_the_session_layer():+ """The exemption is an attestation, so it lives with the writer and can be dropped there.++ Pinned at the source because the payload shape that fails is only produced by a live run: a+ `scroll_intent` block written without `follow_attempted` passes every unit test in this file+ and refuses the first real session that reaches the report step.+ """+ session = (Path(__file__).resolve().parents[2] / "runtime" / "session.py").read_text(+ encoding = "utf-8"+ )+ block = session[session.index('row["scroll_intent"] = {') :][:2_000]+ assert '"follow_attempted": bool(follow.get("follow_attempted"))' in block++# ── ran is not "did what it claimed" ────────────────────────────────────────────────────────diff --git a/tests/studio/studiobench/scoring/selftest/test_studiobench_stream_metrics.py b/tests/studio/studiobench/scoring/selftest/test_studiobench_stream_metrics.pyindex b6513785adf..b5328ee2e68 100644--- a/tests/studio/studiobench/scoring/selftest/test_studiobench_stream_metrics.py+++ b/tests/studio/studiobench/scoring/selftest/test_studiobench_stream_metrics.py@@ -230,6 +230,60 @@ def test_more_timer_ticks_than_the_clamp_allows_is_excluded():assert any("clamp is wrong" in reason for reason in rejected)+def _unscoreable(window: dict, reason: str = "") -> dict:+ """What `instruments/streamcost.py` writes when a frame failed to parse inside the window, or+ an unterminated one was still buffered at its close."""+ sc = window["instruments"]["stream_cost"]+ sc["reply_chars_scoreable"] = False+ sc["wire_parse_failures_in_window"] = 1+ sc["wire_pending_chars_at_close"] = 41+ sc["reply_chars_unscoreable_reason"] = (+ reason or "the wire character count is short by an unknown amount"+ )+ return window+++def test_a_window_the_instrument_marked_unscoreable_is_excluded_from_scoring():+ """THE DEFECT. The instrument publishes `reply_chars_scoreable: false` when it knows the wire+ count is short -- an SSE event is dispatched only at the blank line that terminates it, so an+ unterminated frame at the close is characters delivered and not counted -- and the scoring path+ summed the delta anyway. Every official cost-per-character was then divided by a denominator+ the instrument had already disowned, which inflates it by an unknown factor.+ """+ picked, rejected = _stream_windows([_unscoreable(_window("stream:gap1"))])+ assert picked == []+ assert any("short by an unknown amount" in reason for reason in rejected)+++def test_an_unscoreable_window_does_not_reach_the_cost_per_character():+ """The rate is not merely nudged by an unscoreable window: with nothing else in the cell there+ is no rate at all, and the reason travels instead of a number."""+ m = _stream_measures([_unscoreable(_window("stream:gap1"))])+ for key in STREAM_METRICS:+ assert m[key].value is None, (key, m[key])+ assert "short by an unknown amount" in (m["stream_delta_cost_ms_per_kchar"].note or "")+++def test_a_payload_recorded_before_the_flag_existed_is_scored_exactly_as_before():+ """`is False`, not falsiness. Rows written before the instrument published the flag carry no+ key at all, and voiding them would retro-actively delete every streaming metric this project+ has already recorded."""+ w = _window("stream:gap1")+ assert "reply_chars_scoreable" not in w["instruments"]["stream_cost"]+ picked, rejected = _stream_windows([w])+ assert len(picked) == 1+ assert rejected == {}+++def test_a_window_the_instrument_scored_is_still_admitted():+ """The control. A flag that is present and true changes nothing."""+ w = _window("stream:gap1")+ w["instruments"]["stream_cost"]["reply_chars_scoreable"] = True+ picked, rejected = _stream_windows([w])+ assert len(picked) == 1+ assert rejected == {}++def test_a_window_the_instrument_never_ran_in_is_refused():picked, rejected = _stream_windows([_window("stream:gap1", attempted = False)])assert picked == []diff --git a/tests/studio/studiobench/sweep/floor_table.py b/tests/studio/studiobench/sweep/floor_table.pyindex bb6bc2f692b..7bcde22278b 100644--- a/tests/studio/studiobench/sweep/floor_table.py+++ b/tests/studio/studiobench/sweep/floor_table.py@@ -40,6 +40,7 @@ if __package__ in (None, ""): # pragma: no cover# bad first minute.sys.path.insert(0, str(Path(__file__).resolve().parents[4]))+from tests.studio.studiobench.runtime.ab import failed_invalidating_gates # noqa: E402from tests.studio.studiobench.scoring.from_payload import ( # noqa: E402ACTION_SOURCES,FRAME_METRICS,@@ -48,6 +49,7 @@ from tests.studio.studiobench.scoring.from_payload import ( # noqa: E402_actions_for,_frame_measures,_stream_measures,+ latest_attempt_rows,refuse_if_probed,)@@ -131,10 +133,46 @@ def cell_metrics(records: list[dict]) -> dict[str, dict[str, float]]:frame metrics dilutes `time_in_jank_pct` and `jank_index` away from the film that was measured.A metric here has to be the same quantity the rest of the tool calls by that name."""+ # A CELL THAT FAILED AN INVALIDATING GATE IS NOT A READING, HERE EITHER. Both gates are+ # advisory where they are emitted, so such a cell arrives `completed=True` with a full set of+ # timings that are CHEAPER than a correct cell's, and this table is where a floor is built and+ # where a result is scored against it. `paired` divides treatment by base per pair, so a+ # one-sided failure is not cancelled by the null control being same-build: it lands in+ # `delta_pct` and `spread_pct` directly. On the result side it is worse, because a gate-failed+ # treatment cell pairs against a clean base cell and prints as `faster`.+ #+ # This is not hypothetical. The virtualization negative result recorded in CONTRIBUTING-perf.md+ # was measured through this workflow and contains both facts at once: the treatment arm's+ # census going from 12 mounted messages to 0 and never recovering, and a headline of 28.2%+ # faster weighted. Nothing between the two noticed.+ #+ # Read from the RAW stream, because `failed_invalidating_gates` scopes the gate to its own+ # attempt by hand -- a gate row is not one of the row types `latest_attempt_rows` covers -- and+ # it names the winning attempt from the last `cell` row of ANY completion state.+ gate_failures = failed_invalidating_gates(records)++ # A SUPERSEDED ATTEMPT'S COMPLETION IS NOT THIS CELL'S READING, and the session scoping below+ # cannot say so: it answers "which rows belong to this completed cell row", not "is this+ # completed cell row still the cell". `ab.skippable_cells` re-runs an A/B pair WHOLE, so a+ # resume with any work left re-attempts cells that had already completed, and a retry that+ # dies leaves the older completed row as the only one carrying a full set of timings.+ #+ # Left raw, that row is admitted -- and the guard above it disagrees about which attempt is+ # being scored. `failed_invalidating_gates` names the winner from the LAST cell row, so a+ # retry that crashed and wrote its `completed=False` row supersedes the dead attempt's FAILED+ # gate while this loop keeps that same attempt's numbers. A cell refused for losing its+ # thread's middle before the resume was published after it, pairing its cheaper timings+ # against a clean base arm and printing as `faster`: the 28.2% failure described above,+ # arriving through the resume. Same rows, same rule, one lens -- as `runtime/ab.readings_by_arm`+ # and `sweep/ui_parity.collect` already read them.+ records = latest_attempt_rows(records)+out: dict[str, dict[str, float]] = {}for row in records:if row.get("row_type") != "cell" or not row.get("completed"):continue+ if str(row.get("cell_id")) in gate_failures:+ continuecid = row["cell_id"]# Scoped to this cell's OWN attempt: `--resume` re-runs a died cell under a new# session_id into the same file, and pooling both attempts mixes two measurements.@@ -180,9 +218,13 @@ def cell_sessions(records: list[dict]) -> dict[str, str]:Same last-writer-wins rule as `cell_metrics`, so the session reported here is the session whosenumbers that function returned. Anything else would pair a reading against a session it did notcome from, which is the thing the caller is trying to stop.++ THROUGH `latest_attempt_rows`, because `cell_metrics` is. A superseded attempt it no longer+ returns must not still be able to name a session here, or this answers about one attempt while+ the numbers came from another -- the same lens split this pair of functions exists to close."""out: dict[str, str] = {}- for row in records:+ for row in latest_attempt_rows(records):if row.get("row_type") == "cell" and row.get("completed"):out[row["cell_id"]] = str(row.get("session_id") or "")return outdiff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_null_audit.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_null_audit.pyindex 0262dd8d741..befd05a265c 100644--- a/tests/studio/studiobench/sweep/selftest/test_studiobench_null_audit.py+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_null_audit.py@@ -830,6 +830,43 @@ def test_an_interrupted_retry_does_not_inherit_the_completion_it_superseded(tmp_assert ("r100K", "settings") not in unstable, unstable+# ── the audit has to run in the modes that ask for it ────────────────+#+# The audit block sat below the structural early return while reading nothing from the plan, so a+# payload with no structural entries returned first and the audit never ran. `--mode visible` and+# `--mode behaviour` hard-set `structural` to an empty set for every pattern, so those two could+# never audit at all: the command exited 0 out of the ordinary visible report having silently+# skipped the option whose promise is to FAIL unless the null decided what the result needs.+++def test_the_cli_audits_a_single_repetition_under_forced_visible_mode(tmp_path, capsys):+ """THE DEFECT. Same payload and same expectation as the auto-mode failure test above, with+ `--mode visible` added: the audit must still run and still fail."""+ null_run(tmp_path, "visaudit", [("r100K", "rep0", "settings", "SAME", "SAME")])+ rc = U.main(["--audit-null", str(tmp_path / "visaudit"), "--mode", "visible"])+ out = capsys.readouterr().out+ assert rc == 1, out+ assert "NULL CONTROL AUDIT: UNDECIDED" in out, out+++def test_the_cli_audits_a_single_repetition_under_forced_behaviour_mode(tmp_path, capsys):+ """The other forced mode, which reaches the same empty structural plan by the same line."""+ null_run(tmp_path, "behaudit", [("r100K", "rep0", "settings", "SAME", "SAME")])+ rc = U.main(["--audit-null", str(tmp_path / "behaudit"), "--mode", "behaviour"])+ out = capsys.readouterr().out+ assert rc == 1, out+ assert "NULL CONTROL AUDIT: UNDECIDED" in out, out+++def test_a_quiet_null_still_passes_the_audit_under_a_forced_mode(tmp_path, capsys):+ """The positive control: reaching the audit in these modes must not make it fail everything."""+ null_run(tmp_path, "visquiet", two_reps("settings", "SAME", "SAME"))+ rc = U.main(["--audit-null", str(tmp_path / "visquiet"), "--mode", "visible"])+ out = capsys.readouterr().out+ assert rc == 0, out+ assert "NULL CONTROL AUDIT: DECIDED" in out, out++# ── an exemption measured on another machine is not an exemption here ──diff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.pyindex fb55b167d43..235115a5fff 100644--- a/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.py+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_sweep.py@@ -880,11 +880,16 @@ def test_instability_measured_at_a_rung_still_silences_that_rung(tmp_path):def test_a_declared_unstable_action_still_holds_at_every_rung(tmp_path):# A declared entry carries a MECHANISM that is a property of the action, so it is not scoped# to a rung and a null control is not needed to honour it.+ #+ # NOT 1 is what this test is about: the difference is filed as expected variation rather than+ # as a stable difference. It is 2 and not 0 because the only pair in this payload landed in+ # that bucket, so nothing was compared at all -- see `report`'s `matched == 0` guard, which+ # refuses to exit 0 over a run where the digest never produced a verdict.rows = [{"row_type": "run_meta", "tier": "standard"}]rows.append(parity_action("r1K.base.rep0", "stop_generation", "A"))rows.append(parity_action("r1K.treatment.rep0", "stop_generation", "B"))path = write(tmp_path, "declared", rows)- assert U.report([path], "t", U.unstable_set(None)[0]) == 0+ assert U.report([path], "t", U.unstable_set(None)[0]) == 2# ── ui parity: the session is part of a pair's identity too ──────────@@ -943,7 +948,10 @@ def test_a_cross_session_pair_carries_no_verdict_in_either_direction(tmp_path):null = resumed_parity(tmp_path, "blind_resumed", "s2")verdicts = {r["verdict"] for _a, _s, _c, r in U.compare_all([null])[0]}assert verdicts == {U.P.NOT_COMPARABLE}- assert U.report([null], "t", U.UNSTABLE_ACTIONS) == 0+ # NOT 1, because a cross-session pair is not a stable difference, and NOT 0 either: every pair+ # here is NOT COMPARABLE, so the payload carries no verdict in either direction and `report`+ # says so with 2 rather than letting CI go green on a run that compared nothing.+ assert U.report([null], "t", U.UNSTABLE_ACTIONS) == 2def test_a_parity_arm_resumed_inside_the_same_session_still_pairs(tmp_path):@@ -1584,3 +1592,193 @@ def test_the_null_repetition_that_kept_its_reading_voids_the_same_result(tmp_patassert "30.1 VOID (under floor)" in tableassert "0 metric(s) cleared all three gates." in tableassert cli_main(["--assert-liveness", str(null)]) == 0+++# ── the attempt a gate is read through, and the cells a floor is derived from ──+++def test_a_gate_from_an_attempt_that_never_closed_still_refuses_its_cell(tmp_path):+ """The winning attempt is named by any attempt-stamped row, not by the terminal `cell` row.++ `CellRunner.run` writes that row from a `finally`, which a SIGKILL or an OOM kill never+ reaches, while the recorder has already flushed the action and gate rows before it. So a+ resume hard-killed inside a cell leaves the OLDER completed session as the only one holding a+ `cell` row. Named from terminal rows alone the winner was that dead-and-buried attempt, and+ the LIVE attempt's own failed gate was discarded as belonging to a superseded session --+ while `latest_attempt_rows` kept that same attempt's action rows, so `collect` scored a cell+ whose self-check had recorded conversation loss with no `_incomplete` stamp on it.+ """+ cid = "r100K.treatment.rep0"+ rows: list[dict] = [{"row_type": "run_meta", "tier": "standard", "session_id": "s1"}]+ # The first attempt completed cleanly and closed itself.+ rows.append(in_session(parity_action(cid, "settings", "STABLE"), "s1"))+ rows.append(parity_cell(cid, "treatment", "s1", "rep0", True))+ # The resume re-ran the same cell, lost messages, and was killed before its `cell` row.+ rows.append({"row_type": "run_meta", "tier": "standard", "session_id": "s2"})+ rows.append(in_session(parity_action(cid, "settings", "LOST"), "s2"))+ rows.append(+ {+ "row_type": "gate",+ "name": U.COMPLETENESS_GATE,+ "passed": False,+ "cell_id": cid,+ "session_id": "s2",+ "detail": {"reason": "the thread lost 3 messages"},+ }+ )+ path = write(tmp_path, "killed_retry", rows)++ refused = U.incomplete_cells([path])+ assert cid in refused, refused+ assert "lost 3 messages" in refused[cid]+++def gated_then_resumed(tmp_path: Path, name: str) -> Path:+ """A pair whose treatment arm FAILED `thread_complete`, re-run by `--resume`, retry crashed.++ `ab.skippable_cells` re-runs a pair WHOLE, so a resume with any work left re-attempts both+ arms of a repetition that had already completed. `CellRunner.run` writes its `cell` row from a+ `finally`, so a retry that raises still closes itself -- with `completed=False`.++ The payload then holds, under one cell id, a completed attempt carrying a FAILED gate row and+ a later, incomplete attempt carrying none.+ """+ rows = [+ {"row_type": "run_meta", "tier": "standard", "session_id": "s1"},+ {"row_type": "cell", "cell_id": "r100K.base.rep0", "session_id": "s1", "completed": True},+ timed_action("r100K.base.rep0", "s1", 100.0),+ # The treatment arm lost its thread's middle. It renders fewer rows, so its timing is+ # CHEAPER than a correct cell's, in the direction that flatters the arm.+ {+ "row_type": "cell",+ "cell_id": "r100K.treatment.rep0",+ "session_id": "s1",+ "completed": True,+ },+ timed_action("r100K.treatment.rep0", "s1", 50.0),+ {+ "row_type": "gate",+ "name": "thread_complete",+ "passed": False,+ "cell_id": "r100K.treatment.rep0",+ "session_id": "s1",+ "detail": {"reason": "the thread lost 3 messages"},+ },+ ]+ before = write(tmp_path, name + "_before", list(rows))+ rows += [+ {"row_type": "run_meta", "tier": "standard", "session_id": "s2"},+ timed_action("r100K.base.rep0", "s2", 101.0),+ {"row_type": "cell", "cell_id": "r100K.base.rep0", "session_id": "s2", "completed": False},+ timed_action("r100K.treatment.rep0", "s2", 199.0),+ {+ "row_type": "cell",+ "cell_id": "r100K.treatment.rep0",+ "session_id": "s2",+ "completed": False,+ },+ ]+ # The refusal has to hold on the payload BEFORE the resume, or the test below passes on a+ # payload that was never quotable for some other reason.+ assert F.paired(F.read_rows(before), shard = "b") == {}+ return write(tmp_path, name, rows)+++def test_a_superseded_cell_does_not_come_back_when_its_retry_crashes(tmp_path):+ """A resume must not resurrect the reading its own retry replaced.++ Two lenses on one cell id. `failed_invalidating_gates` names the winning attempt from the LAST+ `cell` row whatever its completion state, so the crashed retry supersedes the dead attempt's+ FAILED gate; `cell_metrics` kept the last COMPLETED cell row, which is that same dead+ attempt's. The guard therefore answered about `s2` while the numbers it was guarding came from+ `s1`, and a cell refused for losing its thread's middle before the resume was published after+ it -- pairing 50 ms of a broken thread against a clean 100 ms base arm and printing `faster`,+ which is the 28.2% failure `cell_metrics` documents, arriving through `--resume`.+ """+ path = gated_then_resumed(tmp_path, "gated_resume")+ rows = F.read_rows(path)++ assert F.cell_metrics(rows) == {}+ assert F.paired(rows, shard = "gated_resume") == {}+++def test_a_resumed_cell_that_is_not_superseded_still_reports_its_reading(tmp_path):+ """The control: superseding is keyed on a LATER attempt, not on the cell having a gate row.++ Without this, dropping every gate-adjacent or every twice-written cell would pass the test+ above by deleting readings the run legitimately earned.+ """+ rows = [+ {"row_type": "run_meta", "tier": "standard", "session_id": "s1"},+ {"row_type": "cell", "cell_id": "r100K.base.rep0", "session_id": "s1", "completed": True},+ timed_action("r100K.base.rep0", "s1", 100.0),+ {+ "row_type": "cell",+ "cell_id": "r100K.treatment.rep0",+ "session_id": "s1",+ "completed": True,+ },+ timed_action("r100K.treatment.rep0", "s1", 90.0),+ ]+ path = write(tmp_path, "unsuperseded", rows)+ assert F.paired(F.read_rows(path), shard = "unsuperseded") == {+ "message_menu.open_close_ms": [(100.0, 90.0)]+ }+++def test_the_visible_floor_is_derived_from_finished_cells_only(tmp_path):+ """An unfinished null-control cell is not an observation of stability.++ Action rows are written as the film runs and the `cell` row when it ends, so a null cell that+ died mid-film leaves a complete-looking set of captures that nothing owns. One DIFFERING+ unfinished observation plus one MATCHING finished one is exactly `min_observations`, which+ marked the action unstable and let `visible_report` file a real difference at the same key+ under "differ against an identical build". `unstable_set` already admits only finished cells+ on the structural side; the visible floor now reads through the same rule.+ """+ rows: list[dict] = [{"row_type": "run_meta", "tier": "standard", "session_id": "s1"}]+ for rep, (digest, completed) in enumerate((("X", False), ("same", True))):+ for arm in ("base", "treatment"):+ cid = f"r100K.{arm}.rep{rep}"+ rows.append(+ in_session(+ {+ "row_type": "action",+ "cell_id": cid,+ "action": "settings",+ "ran": True,+ "parity": _capture_for_visible(),+ "visible": _visible_capture(+ "X" if (digest == "X" and arm == "treatment") else "same"+ ),+ },+ "s1",+ )+ )+ rows.append(parity_cell(cid, arm, "s1", f"rep{rep}", completed))+ null = write(tmp_path, "null_unfinished", rows)++ assert U.visible_unstable_set([null]) == frozenset()+++def _capture_for_visible() -> dict:+ return {+ "parity_attempted": True,+ "root_kind": "thread",+ "chars": 10,+ "digest": "same",+ "messages": [{"i": 0, "role": "assistant", "chars": 10, "digest": "same"}],+ "overlays": [],+ "style": {"style_attempted": True, "capped": False, "nodes": []},+ }+++def _visible_capture(digest: str) -> dict:+ return {+ "visible_attempted": True,+ "ever_visible": [1],+ "ever_visible_count": 1,+ "mounted_ever_visible": 1,+ "unmounted_at_capture": 0,+ "messages": {"1": {"role": "assistant", "digest": digest, "chars": 10}},+ }diff --git a/tests/studio/studiobench/sweep/selftest/test_studiobench_windowed_parity.py b/tests/studio/studiobench/sweep/selftest/test_studiobench_windowed_parity.pynew file mode 100644index 00000000000..d0650d15eb7--- /dev/null+++ b/tests/studio/studiobench/sweep/selftest/test_studiobench_windowed_parity.py@@ -0,0 +1,1779 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""UI parity when one arm mounts a window, and the behavioural scoring that replaces it.++The structural digest asks "is the same DOM on screen". An arm whose entire purpose is to put less+DOM on screen answers no on every action, so the digest would print eighteen red rows that are all+the same non-finding and would bury anything real underneath them. These tests hold the line in+both directions: the digest must REFUSE such a pair rather than fail it, and the behavioural+scoring that stands in its place must still be able to fail.+"""++from __future__ import annotations++import sys+from pathlib import Path++_STUDIO_TESTS = Path(__file__).resolve().parents[3]+if str(_STUDIO_TESTS) not in sys.path:+ sys.path.insert(0, str(_STUDIO_TESTS))++from studiobench.analysis import behaviour as B # noqa: E402+from studiobench.analysis import parity as P # noqa: E402+++def _capture(+ mounted: int,+ total: int,+ digest: str = "d",+) -> dict:+ return {+ "parity_attempted": True,+ "root_kind": "thread",+ "digest": digest,+ "chars": 100,+ "messages": [+ {"i": i, "role": "assistant", "digest": f"{digest}{i}", "chars": 10}+ for i in range(mounted)+ ],+ "overlays": [],+ "styles": {"elements": mounted, "digest": "s", "capped": False},+ "mounted_messages": mounted,+ "thread_total": total,+ }+++def _row(action: str, capture: dict, **expect) -> dict:+ return {+ "row_type": "action",+ "action": action,+ "ran": True,+ "expect_ok": True,+ "expect": dict(expect),+ "timings": {},+ "parity": capture,+ "census": {"viewport_scroll_height": expect.pop("_scroll_height", 10_000)},+ }+++# ── the digest must refuse, not fail ────────────────────────────────+++def test_a_windowed_capture_is_detected_from_its_own_numbers():+ assert P.windowed_mount(_capture(6, 18)) is True+ assert P.windowed_mount(_capture(18, 18)) is False+ # An old payload carries neither number and is treated as the full mount it was.+ assert P.windowed_mount({"parity_attempted": True, "digest": "d"}) is False+++def test_the_digest_refuses_a_windowed_pair_rather_than_reporting_eighteen_differences():+ got = P.compare(_capture(18, 18, "base"), _capture(6, 18, "treat"))+ assert got["verdict"] == P.NOT_APPLICABLE+ assert got["verdict"] != P.DIFFER+ assert "mounts a WINDOW" in got["reason"]+ # And it localises nothing, because there is nothing here worth localising.+ assert got["moved"] == []+ assert got["style_verdict"] == P.NOT_APPLICABLE+++def test_not_applicable_is_not_folded_into_a_pass_or_a_fail():+ tally = P.summarise([P.compare(_capture(18, 18, "b"), _capture(6, 18, "t"))])+ assert tally == {P.NOT_APPLICABLE: 1}+ assert tally.get(P.MATCH, 0) == 0+ assert tally.get(P.DIFFER, 0) == 0+++def test_two_full_mounts_are_still_compared_exactly_as_before():+ """The refusal must not leak into a normal pair. Same digest is still MATCH, different is+ still DIFFER, and the windowed machinery is invisible to both."""+ same = P.compare(_capture(18, 18, "x"), _capture(18, 18, "x"))+ assert same["verdict"] == P.MATCH+ differ = P.compare(_capture(18, 18, "x"), _capture(18, 18, "y"))+ assert differ["verdict"] == P.DIFFER+ assert differ["moved"]+++def test_unequal_mounted_counts_are_reported_even_without_a_declared_total():+ """THIS TEST USED TO ASSERT THE OPPOSITE, and it was wrong in the way the whole gate is meant+ to be proof against: it treated "these rows cannot be lined up" as "there is nothing to say".++ The rows genuinely cannot be compared position by position, and that is a statement about the+ ROWS. Two arms that each mounted their whole thread and arrived at different lengths have a+ difference between them whatever the rows can support, and calling the pair inapplicable+ hides exactly the regression -- a treatment rendering fewer messages -- that a parity check+ exists to catch.+ """+ got = P.compare(_capture(18, 18, "b"), _capture(12, 12, "t"))+ assert got["verdict"] == P.DIFFER+ assert "different numbers of messages" in got["reason"]+ assert got["moved"] == [], "the positional rows would all read as moved and bury the finding"+++def test_a_refused_pair_is_not_evidence_of_stability_either():+ """`derive_unstable` counts observations. A pair the digest could not answer is not one."""+ derived = P.derive_unstable([("select_text", {"verdict": P.NOT_APPLICABLE})] * 4)+ assert derived["select_text"]["observations"] == 0+ assert derived["select_text"]["unstable"] is False+ assert derived["select_text"]["undetermined"] is True+ assert derived["select_text"]["not_comparable"] == 4+++# ── the behavioural scoring that replaces it ────────────────────────+++def test_the_scroll_extent_invariant_passes_a_virtualizer_that_sizes_its_spacers():+ base = _row("select_text", _capture(18, 18), selected_chars = 100, visible_chars = 100)+ treat = _row("select_text", _capture(6, 18), selected_chars = 100, visible_chars = 100)+ treat["census"]["viewport_scroll_height"] = 9_600 # 4% out, within the estimate tolerance+ got = B.compare_behaviour(base, treat)+ assert got["verdict"] == P.MATCH, got["reason"]+++def test_the_scroll_extent_invariant_fails_a_virtualizer_that_simply_drops_rows():+ """A scrollbar that says the thread is a third of its real length is a user-visible defect,+ and it is the failure mode a windowed mount invites first."""+ base = _row("select_text", _capture(18, 18), selected_chars = 100, visible_chars = 100)+ treat = _row("select_text", _capture(6, 18), selected_chars = 100, visible_chars = 100)+ treat["census"]["viewport_scroll_height"] = 3_300+ got = B.compare_behaviour(base, treat)+ assert got["verdict"] == B.BROKEN+ assert "scroll_extent" in got["reason"]+++def _copy_row(+ capture,+ *,+ clipboard,+ selected,+ mounted,+ readable = True,+):+ return _row(+ "select_all_copy",+ capture,+ selected_chars = selected,+ clipboard_chars = clipboard,+ clipboard_readable = readable,+ clipboard_note = None,+ messages_total = 18,+ messages_mounted = mounted,+ mounted_fraction = round(mounted / 18, 3),+ )+++def test_clipboard_truncation_is_reported_as_a_broken_invariant_not_as_noise():+ """A windowed thread whose copy path still reads the DOM loses conversation. That is data+ loss, and the report has to say so rather than file it under 'expected difference'."""+ base = _copy_row(_capture(18, 18), clipboard = 200_000, selected = 200_000, mounted = 18)+ treat = _copy_row(_capture(6, 18), clipboard = 66_000, selected = 66_000, mounted = 6)+ got = B.compare_behaviour(base, treat)+ assert got["verdict"] == B.BROKEN+ assert "clipboard_carries_the_whole_thread" in got["reason"]+++def test_the_alarm_goes_quiet_when_the_copy_reads_the_store_and_not_before():+ """THE FIX, AND THE REASON IT COUNTS AS ONE.++ Same windowed arm, same shrunken selection -- six of eighteen messages mounted, so Ctrl+A can+ only reach a third of the text. What changed is that the app's copy handler serialises from+ the message store, so the CLIPBOARD is whole. The alarm has to go quiet for that and for+ nothing else: an alarm still wired to `selected_chars` would stay lit on a build that had+ fixed the defect, and an alarm that ignored the selection entirely could not tell this apart+ from a build that never virtualised at all.+ """+ base = _copy_row(_capture(18, 18), clipboard = 200_000, selected = 200_000, mounted = 18)+ treat = _copy_row(_capture(6, 18), clipboard = 200_000, selected = 66_000, mounted = 6)+ got = B.compare_behaviour(base, treat)+ assert got["verdict"] == P.MATCH, got["reason"]+ checks = {c["invariant"]: c for c in got["checks"]}+ assert checks["clipboard_carries_the_whole_thread:base"]["ok"] is True+ assert checks["clipboard_carries_the_whole_thread:treatment"]["ok"] is True+ # And the shrunken selection is still on the record, as evidence rather than as a verdict.+ assert checks["selection_shrank_as_expected"]["ok"] is None+ assert "66000" in checks["selection_shrank_as_expected"]["detail"]+++def test_an_unreadable_clipboard_is_never_a_pass():+ """The one invariant where "we could not tell" must not look like "it was fine"."""+ base = _copy_row(_capture(18, 18), clipboard = 200_000, selected = 200_000, mounted = 18)+ treat = _copy_row(+ _capture(6, 18),+ clipboard = None,+ selected = 66_000,+ mounted = 6,+ readable = False,+ )+ got = B.compare_behaviour(base, treat)+ checks = {c["invariant"]: c for c in got["checks"]}+ assert checks["clipboard_readable:treatment"]["ok"] is None+ assert got["verdict"] != P.MATCH+++def test_a_reopen_that_loses_messages_is_broken():+ base = _row(+ "thread_reopen",+ _capture(18, 18),+ messages_before = 18,+ messages_after = 18,+ reopened_via = "click",+ )+ treat = _row(+ "thread_reopen",+ _capture(6, 18),+ messages_before = 18,+ messages_after = 6,+ reopened_via = "click",+ )+ got = B.compare_behaviour(base, treat)+ assert got["verdict"] == B.BROKEN+ assert "reopen_keeps_every_message:treatment" in got["reason"]+++def test_a_reopen_measured_through_a_page_navigation_is_broken():+ """A document reload is not a thread rebuild. See `_click_or_navigate`."""+ base = _row(+ "thread_reopen",+ _capture(18, 18),+ messages_before = 18,+ messages_after = 18,+ reopened_via = "click",+ )+ treat = _row(+ "thread_reopen",+ _capture(6, 18),+ messages_before = 18,+ messages_after = 18,+ reopened_via = "navigate",+ )+ got = B.compare_behaviour(base, treat)+ assert got["verdict"] == B.BROKEN+ assert "reopen_used_the_control:treatment" in got["reason"]+++# ── a rebuild that never finished is not a held invariant ───────────+++def _reopen_row(+ mounted,+ *,+ before = 18,+ after = 18,+ ready = True,+):+ """A `thread_reopen` row in the shape scene/actions.py writes one.++ `ready = False` is what a rebuild that timed out produces: `ran` stays TRUE so the outstanding+ conditions travel with the row, `expect_ok` is false, `reopen_ms` is null, and the two message+ counts are UNCHANGED -- because both of them are `threadTotal()`, which is the total the store+ DECLARED and which the first reopened row publishes.+ """+ row = _row(+ "thread_reopen",+ _capture(mounted, 18),+ messages_before = before,+ messages_after = after,+ reopened_via = "click",+ reopen_ready_mode = "windowed" if mounted < 18 else "full",+ reopen_readiness = {+ "ready": ready,+ "mode": "windowed" if mounted < 18 else "full",+ "expected_messages": before,+ "conditions": {"settled": True, "end_present": bool(ready)},+ "probe": {"mounted": mounted, "setsize": after},+ "reason": None if ready else "the thread was not ready: end_present",+ },+ )+ row["expect_ok"] = bool(ready) and before == after+ row["timings"] = {"close_ms": 120.0, "reopen_ms": 900.0 if ready else None}+ if not row["expect_ok"]:+ row["reason"] = "the reopened thread never reached a ready state"+ return row+++def test_a_reopen_that_never_became_ready_is_not_a_passed_invariant():+ """THE FALSE GREEN. The rebuild timed out at three of eighteen messages mounted, so the action+ reported `ran = True`, `expect_ok = False`, a null `reopen_ms` and the failed conditions -- and+ left `messages_before` and `messages_after` equal, because both are the total the store+ declared rather than a count of a rebuilt thread. Scored as equality that read as a held+ invariant, the route check passed because the sidebar click had worked, and the pair came out+ MATCH over a rebuild that never happened."""+ base = _reopen_row(18)+ treat = _reopen_row(3, ready = False)+ got = B.compare_behaviour(base, treat)+ assert got["verdict"] != P.MATCH, got+ assert got["verdict"] == P.NOT_COMPARABLE, got+ checks = {c["invariant"]: c for c in got["checks"]}+ assert checks["reopen_keeps_every_message:treatment"]["ok"] is None, checks+ assert checks["reopen_keeps_every_message:treatment"]["required"] is True+ assert "never reached a ready state" in got["reason"], got["reason"]+ assert "end_present" in got["reason"], got["reason"]+ # The route check still passed, which is exactly what used to carry the pair to a MATCH.+ assert checks["reopen_used_the_control:treatment"]["ok"] is True+++def test_a_reopen_that_lost_messages_is_still_broken_when_the_gate_also_refused_it():+ """The other half of the decision, and the reason it is not a blanket refusal. An arm whose+ store came back with six of eighteen messages FAILS the windowed readiness gate too -- its+ `aria-setsize` no longer matches the seeded count -- so a rule that voided every unready reopen+ would have turned the one finding this action exists for into "not comparable"."""+ base = _reopen_row(18)+ treat = _reopen_row(6, after = 6, ready = False)+ got = B.compare_behaviour(base, treat)+ assert got["verdict"] == B.BROKEN, got+ assert "reopen_keeps_every_message:treatment" in got["reason"]+++def test_a_finished_rebuild_with_matching_counts_still_holds():+ """The control. A check that never passes is as useless as one that never fails: a thread that+ really did come back, past the same readiness gate that admitted the cell, still counts."""+ got = B.compare_behaviour(_reopen_row(18), _reopen_row(6))+ assert got["verdict"] == P.MATCH, got+ checks = {c["invariant"]: c for c in got["checks"]}+ assert checks["reopen_keeps_every_message:treatment"]["ok"] is True+++def test_an_old_payload_that_records_no_rebuild_evidence_is_not_a_pass():+ """A row from a checkout that predates the readiness gate carries neither `reopen_readiness`+ nor a meaningful `expect_ok`. Back then `messages_after` was read the moment the store published+ its total, which is the reading the gate was added to refuse, so those rows cannot support this+ invariant either and must not be counted as having held it."""+ base = _reopen_row(18)+ treat = _reopen_row(6)+ for row in (base, treat):+ row["expect"].pop("reopen_readiness")+ row["expect_ok"] = None+ got = B.compare_behaviour(base, treat)+ assert got["verdict"] == P.NOT_COMPARABLE, got+++def test_a_timed_out_rebuild_leaves_the_behavioural_run_with_no_verdict(tmp_path, capsys):+ """THE CONSEQUENCE, through the command that reports it. This pair was the run's only one, so+ counting it as a held invariant produced `invariants held: 1` and exit 0 over a rebuild that+ never finished. It is now the third outcome, and a run that compared nothing exits 2."""+ import json++ from studiobench.sweep import ui_parity as U++ rows = []+ for side, row in (("base", _reopen_row(18)), ("treatment", _reopen_row(3, ready = False))):+ row["cell_id"] = f"r100K.{side}.rep0"+ rows.append(row)+ shard = tmp_path / "payload.jsonl"+ shard.write_text("\n".join(json.dumps(r) for r in rows), encoding = "utf-8")++ code = U.behaviour_report([shard], "UI PARITY: stalled reopen")+ out = capsys.readouterr().out+ assert "invariants held: 0" in out, out+ assert "NOT COMPARABLE: 1" in out, out+ assert "NOTHING WAS COMPARED" in out, out+ assert code == 2, out+++def test_an_action_with_no_declared_invariant_is_unchecked_and_not_a_pass():+ """The scroll extent is a property of the THREAD and holds identically on all eighteen+ actions. Letting it carry an action to a pass would report `model_change` as verified on a+ windowed arm when nothing about `model_change` was looked at."""+ base = _row("model_change", _capture(18, 18))+ treat = _row("model_change", _capture(6, 18))+ got = B.compare_behaviour(base, treat)+ assert got["verdict"] == P.NOT_APPLICABLE+ assert got["verdict"] != P.MATCH+ assert "UNCHECKED" in got["reason"]+ # The scroll extent still held, and is still reported. It just does not vote.+ assert {c["invariant"]: c["ok"] for c in got["checks"]}["scroll_extent"] is True+++def test_a_broken_scroll_extent_still_fails_an_action_with_no_invariant_of_its_own():+ """Not voting for a pass is not the same as not voting at all. A scrollbar that lies is a+ defect wherever it is observed."""+ base = _row("model_change", _capture(18, 18))+ treat = _row("model_change", _capture(6, 18))+ treat["census"]["viewport_scroll_height"] = 100+ got = B.compare_behaviour(base, treat)+ assert got["verdict"] == B.BROKEN+++def test_an_action_that_did_not_run_is_not_scored_at_all():+ base = _row("select_text", _capture(18, 18), selected_chars = 10, visible_chars = 10)+ treat = _row("select_text", _capture(6, 18))+ treat["ran"] = False+ treat["reason"] = "no assistant message"+ got = B.compare_behaviour(base, treat)+ assert got["verdict"] == P.NOT_EXERCISED+ assert got["checks"] == []+++def test_every_named_first_to_break_action_has_an_invariant():+ """The five the brief names as the ones that break first. An entry silently missing from the+ table would make that action UNCHECKED, which reads as clean."""+ for action in (+ "select_all_copy",+ "select_text",+ "copy_markdown",+ "thread_reopen",+ "scroll_after",+ ):+ assert action in B.INVARIANTS, f"{action} has no behavioural invariant declared"+++# ── the four false greens the first review round found ──────────────+#+# Every one of these returned SUCCESS before the fix, which is the only reason they are grouped:+# they are four different routes to a UI verdict of "fine" over a comparison that either found+# nothing or declined to look.+++def test_two_full_mounts_of_different_lengths_is_a_difference_not_an_excuse():+ """THE MOST SERIOUS ONE. Neither arm is windowing, so neither is holding anything back on+ purpose, and the treatment renders fewer messages than the base -- a user-visible loss of+ conversation. It used to be waved through as NOT_APPLICABLE on the argument that the+ per-message rows are keyed by position, which is true of the ROWS and says nothing about the+ finding."""+ base = _capture(mounted = 18, total = 18)+ treat = _capture(mounted = 17, total = 17)+ assert P.windowed_mount(base) is False and P.windowed_mount(treat) is False+ got = P.compare(base, treat)+ assert got["verdict"] == P.DIFFER, got+ assert "NEITHER arm is windowing" in got["reason"]+ # And the positional noise is withheld, so the one finding that matters is not buried.+ assert got["moved"] == []+++def test_a_windowed_pair_is_still_refused_rather_than_failed():+ """The fix must not turn the intended case red. A genuine window is still NOT_APPLICABLE."""+ got = P.compare(_capture(mounted = 18, total = 18), _capture(mounted = 9, total = 18))+ assert got["verdict"] == P.NOT_APPLICABLE, got+ assert "mounts a WINDOW" in got["reason"]+++def test_equal_full_mounts_are_compared_as_before():+ got = P.compare(_capture(mounted = 18, total = 18), _capture(mounted = 18, total = 18))+ assert got["verdict"] == P.MATCH, got+++def test_behavioural_scoring_that_validated_nothing_is_not_a_pass(tmp_path, capsys):+ """`broken` empty and `matched` zero used to return 0, under the heading "Every declared+ behavioural invariant held on both arms" -- a sentence that is true of an empty set and reads+ as a pass. On a windowed arm this is the ONLY UI verdict there is, so a silent no-op there+ leaves the arm with no verdict at all while appearing to have one."""+ from studiobench.sweep import ui_parity as U++ shard = tmp_path / "payload.jsonl"+ # Both arms recorded the action and NEITHER ran it: nothing to compare, nothing broken.+ import json++ rows = []+ for side in ("base", "treatment"):+ row = _row("thread_reopen", _capture(mounted = 9, total = 18))+ row["ran"] = False+ row["cell_id"] = f"r100K.{side}.rep0"+ rows.append(row)+ shard.write_text("\n".join(json.dumps(r) for r in rows), encoding = "utf-8")++ code = U.behaviour_report([shard], "UI PARITY: nothing")+ out = capsys.readouterr().out+ assert code == 2, out+ assert "NOTHING WAS COMPARED" in out+++def test_the_observation_cost_is_not_charged_to_the_action_budget():+ """`over_ms` used to be sampled AFTER the census and the multi-megabyte digest that this+ change had just moved outside the measured window, so an action that finished inside its+ budget was flagged `over_budget` for instrument time. The deadline is now read at the moment+ the window closes."""+ import inspect++ from studiobench.scene import schedule as S++ src = inspect.getsource(S.SceneRunner)+ close = src.index("window_closed_at = time.monotonic()")+ over = src.index("over_ms = ((window_closed_at - t0)", close)+ # The FIRST census taken after the deadline is read -- `_census` is called from more than one+ # place, so an unanchored search finds a gap window's copy and compares unrelated lines.+ census = src.index("census = self._census()", over)+ assert close < over < census, (+ "the deadline is sampled after the observations again, which charges instrument time to "+ "the action's budget"+ )+++# ── a scan of nothing is not agreement ──────────────────────────────+++def _styled(elements: int, digest: str = "s") -> dict:+ cap = _capture(mounted = 18, total = 18)+ cap["styles"] = {"elements": elements, "digest": digest, "capped": False}+ return cap+++def test_a_style_probe_that_matched_no_elements_does_not_report_a_match():+ """THE POSITIVE CONTROL. Two probes that matched nothing have equal counts and equal digests+ -- both the hash of an empty string -- so the strongest verdict the function can return was+ being issued on the strength of no observation at all.++ Not hypothetical: the probe walks a hand-written selector list written against Studio's+ markup, and a class rename anywhere in it empties the scan silently.+ """+ verdict, reason = P.compare_styles(_styled(0), _styled(0))+ assert verdict == P.NOT_COMPARABLE, (verdict, reason)+ assert "matched no elements" in reason+++def test_one_arm_scanning_nothing_is_also_not_a_difference_to_report():+ """It is a broken probe, not a finding about the build, and saying DIFFER here would send+ somebody looking for a UI change that nobody has evidence for."""+ verdict, _reason = P.compare_styles(_styled(0), _styled(12))+ assert verdict == P.NOT_COMPARABLE+++def test_a_probe_that_actually_looked_still_matches_and_still_differs():+ """The control must not swallow the readings it exists to protect."""+ assert P.compare_styles(_styled(12, "a"), _styled(12, "a"))[0] == P.MATCH+ assert P.compare_styles(_styled(12, "a"), _styled(12, "b"))[0] == P.DIFFER+++def test_the_passing_digest_verdict_states_what_it_did_not_look_at():+ """A PARITY OK line that reads as "the UI is unchanged" is a claim the instrument cannot+ support: run against a real sidebar-drag change the thread digest returned 0 of 34, and so did+ its null. The limitation is printed next to the verdict, not left in a source comment."""+ import inspect++ from studiobench.sweep import ui_parity as U++ src = inspect.getsource(U.report)+ assert "THREAD STRUCTURE" in src+ assert "sidebar-blind" in src and "layout-blind" in src+++# ── the clipboard is scored against the thread, in both directions ──+++def test_a_truncated_clipboard_still_fails():+ """The defect the invariant was written for. The windowed arm copies only what it mounted, so+ the clipboard is the visible fraction of the conversation and the rest is gone."""+ base = _copy_row(_capture(18, 18), clipboard = 200_000, selected = 200_000, mounted = 18)+ treat = _copy_row(_capture(6, 18), clipboard = 122_000, selected = 66_000, mounted = 6)+ got = B.compare_behaviour(base, treat)+ assert got["verdict"] == B.BROKEN, got+ checks = {c["invariant"]: c for c in got["checks"]}+ assert checks["clipboard_carries_the_whole_thread:treatment"]["ok"] is False+++def test_a_clipboard_that_carries_far_MORE_than_the_thread_also_fails():+ """THE DEFECT A FIX FOR THE FIRST ONE TURNS INTO. Serialising from the message store is the+ right repair, and the obvious serialiser is the "save this reply" one, which emits reasoning,+ tool-call arguments and tool results -- none of which a user can select, because the panes+ holding them are collapsed and a collapsed Radix Collapsible is not in the DOM at all.++ Measured on a real 100K arm: 420,911 characters against a 194,992-character thread, 2.16x.+ The truncation was fixed and the content was then wrong in the other direction. A check that+ only had a lower bound called that a pass.+ """+ base = _copy_row(_capture(18, 18), clipboard = 193_937, selected = 194_992, mounted = 18)+ treat = _copy_row(_capture(9, 18), clipboard = 420_911, selected = 118_089, mounted = 9)+ got = B.compare_behaviour(base, treat)+ assert got["verdict"] == B.BROKEN, got+ checks = {c["invariant"]: c for c in got["checks"]}+ assert checks["clipboard_carries_the_whole_thread:treatment"]["ok"] is False+ assert "2.159" in checks["clipboard_carries_the_whole_thread:treatment"]["detail"]+++def test_markdown_source_against_rendered_text_is_not_treated_as_a_difference():+ """The reason the two arms are NOT compared against each other. The base arm's clipboard is the+ DOM's rendered text and a store-based copy is markdown source, so fences, emphasis and LaTeX+ delimiters exist in one and not the other. A narrowed store serialiser measured about 1% over+ on a scale fixture. Comparing the two clipboards at a 2% tolerance fails a correct fix, and the+ only way to make it pass is to widen the tolerance until it tests nothing."""+ base = _copy_row(_capture(18, 18), clipboard = 193_937, selected = 194_992, mounted = 18)+ treat = _copy_row(_capture(9, 18), clipboard = 197_800, selected = 118_089, mounted = 9)+ got = B.compare_behaviour(base, treat)+ checks = {c["invariant"]: c for c in got["checks"]}+ assert checks["clipboard_carries_the_whole_thread:treatment"]["ok"] is True, checks+++def test_without_a_fully_mounted_arm_there_is_no_reference_and_no_verdict():+ """The reference is the thread's visible text as measured by an arm that has all of it. If+ neither arm mounts everything, nobody in this payload knows how long the conversation is, and+ that is reported rather than guessed."""+ base = _copy_row(_capture(9, 18), clipboard = 190_000, selected = 118_000, mounted = 9)+ treat = _copy_row(_capture(9, 18), clipboard = 190_000, selected = 118_000, mounted = 9)+ got = B.compare_behaviour(base, treat)+ checks = {c["invariant"]: c for c in got["checks"]}+ assert checks["clipboard_carries_the_whole_thread"]["ok"] is None+ assert got["verdict"] == P.NOT_COMPARABLE, got+++# ── visible-region parity needs a measured floor like everything else ──+++def _visible_shard(+ tmp_path,+ name,+ differ_actions,+ actions = ("a", "b", "c"),+ rung = "r100K",+ reps = 2,+):+ """A payload shard whose visible-region captures differ on `differ_actions` and match elsewhere.++ TWO REPS BY DEFAULT, and the rung is a parameter. Both are what the floor is keyed and counted+ by: an entry is derived from repeated readings at one rung, so a shard with a single rep is a+ shard that cannot produce a floor at all, and one recorded at a different rung produces a floor+ that does not apply here.+ """+ import json++ rows = []+ for action in actions:+ for rep in range(reps):+ for side in ("base", "treatment"):+ digest = "X" if (action in differ_actions and side == "treatment") else "same"+ rows.append(+ {+ "row_type": "action",+ "action": action,+ "ran": True,+ "cell_id": f"{rung}.{side}.rep{rep}",+ "parity": _capture(mounted = 18, total = 18),+ "visible": {+ "visible_attempted": True,+ "ever_visible": [1],+ "ever_visible_count": 1,+ "mounted_ever_visible": 1,+ "unmounted_at_capture": 0,+ "messages": {"1": {"role": "assistant", "digest": digest, "chars": 10}},+ },+ }+ )+ shard = tmp_path / name+ shard.mkdir()+ (shard / "payload.jsonl").write_text("\n".join(json.dumps(r) for r in rows), encoding = "utf-8")+ return shard / "payload.jsonl"+++def test_an_action_that_differs_against_an_identical_build_is_not_counted_against_the_arm(+ tmp_path, capsys+):+ """THE FLOOR, AND WHY IT IS NOT OPTIONAL.++ Measured on a real 100K run: the base-vs-base null control differed inside the viewport on 13+ of 64 action pairs, while the virtualization arm it was the control for differed on 5. Scored+ without the floor the arm ranks WORSE than two copies of the same build, so the verdict is not+ merely weak, it is backwards. The rows differ at identical character counts, which is a+ volatile attribute rather than changed content.+ """+ from studiobench.sweep import ui_parity as U++ null = _visible_shard(tmp_path, "null", differ_actions = {"a", "b"})+ arm = _visible_shard(tmp_path, "arm", differ_actions = {"a"})++ unstable = U.visible_unstable_set([null])+ assert unstable == frozenset({("r100K", "a"), ("r100K", "b")}), unstable++ # Unfloored: the arm's one difference is counted and the run fails.+ assert U.visible_report([arm], "unfloored") == 1+ # Floored by its own null: that action is known to differ against itself at this rung, so it+ # is reported and not counted.+ assert U.visible_report([arm], "floored", unstable) == 0+ out = capsys.readouterr().out+ assert "differ against an identical build" in out+++def test_a_real_visible_difference_outside_the_floor_still_fails(tmp_path):+ """The floor must not become a way of passing anything. An action the null never saw differ is+ still a failure."""+ from studiobench.sweep import ui_parity as U++ null = _visible_shard(tmp_path, "null2", differ_actions = {"b"})+ arm = _visible_shard(tmp_path, "arm2", differ_actions = {"a"})+ assert U.visible_report([arm], "floored", U.visible_unstable_set([null])) == 1+++def test_noise_at_one_rung_does_not_silence_a_regression_at_another(tmp_path, capsys):+ """THE FLOOR APPLIED WHERE IT WAS NEVER MEASURED.++ A payload holds several rungs -- the windowed readiness gate is written to permit an arm to+ mount everything at 1K and a window at 100K -- and the noise floor was a set of ACTION NAMES,+ so one differing null-control pair marked that action unstable everywhere. Here the null's+ 100K `model_change` differs for its own reasons and the arm's 1K `model_change` differs+ reproducibly. Keyed by name alone the second is filed as noise, the other pairs supply+ `matched > 0`, and the command exits 0 having silenced the one real finding in the run.++ The 1K rung is a different thread at a different size with the film's slots landing somewhere+ else entirely; the null measured nothing there and the floor may not speak for it.+ """+ from studiobench.sweep import ui_parity as U++ both = ("model_change", "keystroke")+ null = [+ _visible_shard(+ tmp_path, "null_rungs", differ_actions = {"model_change"}, actions = both, rung = "r100K"+ )+ ]+ big = _visible_shard(+ tmp_path, "arm_100k", differ_actions = {"model_change"}, actions = both, rung = "r100K"+ )+ small = _visible_shard(+ tmp_path, "arm_1k", differ_actions = {"model_change"}, actions = both, rung = "r1K"+ )+ unstable = U.visible_unstable_set(null)+ assert unstable == frozenset({("r100K", "model_change")}), unstable+ assert U.visible_report([big, small], "mixed rungs", unstable) == 1+ out = capsys.readouterr().out+ assert "DIFFERENCES INSIDE THE VIEWPORT" in out+ # And it is the 1K pair that is counted, with the 100K one still reported as floored noise.+ assert "r1K rep0" in out+ assert "differ against an identical build" in out+++def test_a_floor_derived_from_a_single_pair_is_not_a_floor(tmp_path):+ """ONE OCCURRENCE IS NOT EVIDENCE, which is the guard `derive_unstable` already applies to the+ structural set and this one had none of. A single flake in a null control would otherwise+ silence that action, at that rung, for every rep of every payload scored against it -- and the+ visible floor carries no declared mechanism behind it to justify the entry."""+ from studiobench.sweep import ui_parity as U++ thin = _visible_shard(tmp_path, "null_thin", differ_actions = {"a"}, reps = 1)+ assert U.visible_unstable_set([thin]) == frozenset()+ thick = _visible_shard(tmp_path, "null_thick", differ_actions = {"a"}, reps = 2)+ assert U.visible_unstable_set([thick]) == frozenset({("r100K", "a")})+++def test_an_unfloored_visible_run_says_so(tmp_path, capsys):+ from studiobench.sweep import ui_parity as U++ arm = _visible_shard(tmp_path, "arm3", differ_actions = set())+ U.visible_report([arm], "no floor")+ assert "NO FLOOR WAS MEASURED" in capsys.readouterr().out+++def test_the_noise_floor_cannot_silence_an_arm_that_lost_the_thread(tmp_path, capsys):+ """MEASURED. On the 100K run `model_change` is in the derived unstable set because the null+ control's copy of it differs on a volatile attribute at identical character counts -- AND it is+ the action on which the virtualization arm's thread went from 12 mounted messages to 0 and+ never came back. Routing the second finding into the floor because of the first suppresses a+ lost conversation on the strength of unrelated jitter."""+ import json++ from studiobench.sweep import ui_parity as U++ def _shard(name, treat_empty):+ rows = []+ for side in ("base", "treatment"):+ empty = treat_empty and side == "treatment"+ rows.append(+ {+ "row_type": "action",+ "action": "model_change",+ "ran": True,+ "cell_id": f"r100K.{side}.rep0",+ "parity": _capture(mounted = 18, total = 18),+ "visible": {+ "visible_attempted": True,+ "ever_visible": [14, 15],+ "ever_visible_count": 2,+ "mounted_ever_visible": 0 if empty else 2,+ "unmounted_at_capture": 2 if empty else 0,+ "messages": {}+ if empty+ else {+ str(o): {"role": "assistant", "digest": "same", "chars": 10}+ for o in (14, 15)+ },+ },+ }+ )+ shard = tmp_path / name+ shard.mkdir()+ (shard / "payload.jsonl").write_text(+ "\n".join(json.dumps(r) for r in rows), encoding = "utf-8"+ )+ return shard / "payload.jsonl"++ # The null differs on this action for its own reasons, so it lands in the unstable set...+ null = _visible_shard(+ tmp_path, "null_mc", differ_actions = {"model_change"}, actions = ("model_change",)+ )+ unstable = U.visible_unstable_set([null])+ assert ("r100K", "model_change") in unstable+ # ...and the arm that lost the thread on it is STILL a failure.+ assert U.visible_report([_shard("arm_mc", True)], "severe", unstable) == 1+ assert "one arm lost the thread" in capsys.readouterr().out+++# ── the residue of a windowed capture is printed, not swallowed ─────+++def _write(tmp_path, name, rows):+ import json++ shard = tmp_path / name+ shard.mkdir()+ (shard / "payload.jsonl").write_text("\n".join(json.dumps(r) for r in rows), encoding = "utf-8")+ return shard / "payload.jsonl"+++def _visible(+ ever,+ digested,+ digest = "same",+):+ """A visible-region capture that SAW `ever` and could still digest `digested` at capture time."""+ return {+ "visible_attempted": True,+ "ever_visible": sorted(ever),+ "ever_visible_count": len(ever),+ "mounted_ever_visible": len(digested),+ "unmounted_at_capture": len(ever) - len(digested),+ "messages": {+ str(o): {"role": "assistant", "digest": digest, "chars": 10} for o in sorted(digested)+ },+ }+++def _action(+ action,+ cell_id,+ *,+ parity = None,+ visible = None,+ ran = True,+ reason = None,+ expect = None,+):+ row = {+ "row_type": "action",+ "action": action,+ "ran": ran,+ "cell_id": cell_id,+ "parity": parity if parity is not None else _capture(mounted = 18, total = 18),+ "census": {"viewport_scroll_height": 10_000},+ "expect": dict(expect or {}),+ "expect_ok": True,+ "timings": {},+ }+ if visible is not None:+ row["visible"] = visible+ if reason is not None:+ row["reason"] = reason+ return row+++def test_a_visible_message_that_could_not_be_digested_is_printed_and_not_counted(tmp_path, capsys):+ """THE FALSE GREEN. `windowed` put ordinals 1 and 2 on screen during the action and had+ unmounted 2 again by the time the capture ran, so only ordinal 1 was ever compared. That pair+ used to return MATCH -- one mounted message is enough to carry it -- and `visible_report`+ never read `not_digested`, so a rendering difference in ordinal 2 exited 0 under a claim that+ every visible message was identical on both arms.++ It is now the third outcome, and the residue is on screen where a reader can see which message+ went uncompared."""+ from studiobench.sweep import ui_parity as U++ rows = []+ for side in ("base", "treatment"):+ rows.append(_action("settings", f"r100K.{side}.rep0", visible = _visible([1], [1])))+ rows.append(_action("scroll_after", f"r100K.{side}.rep0", visible = _visible([1, 2], [1])))+ shard = _write(tmp_path, "residue", rows)++ code = U.visible_report([shard], "residue")+ out = capsys.readouterr().out+ assert "VISIBLE BUT NOT DIGESTED" in out, out+ assert "ordinals [2]" in out, out+ # The fully digested pair still passes, so the refusal is scoped to the pair that earned it.+ assert "visible region matched: 1" in out, out+ assert "visible but NOT DIGESTED: 1" in out, out+ assert code == 0, out+++def test_a_run_where_nothing_could_be_digested_carries_no_visible_verdict(tmp_path, capsys):+ """Every pair carrying a residue means every pair was refused, and a mode that refused+ everything has no verdict to report. 2, not 0."""+ from studiobench.sweep import ui_parity as U++ rows = [+ _action("scroll_after", f"r100K.{side}.rep0", visible = _visible([1, 2], [1]))+ for side in ("base", "treatment")+ ]+ code = U.visible_report([_write(tmp_path, "all_residue", rows)], "all residue")+ out = capsys.readouterr().out+ assert code == 2, out+ assert "NOTHING WAS COMPARED" in out, out+++# ── an unmeasured windowed run cannot come out green ────────────────+++def _failed_parity(why = "the parity probe timed out"):+ return {"parity_attempted": False, "reason": why}+++def _declared_windowed_shard(+ tmp_path,+ name,+ *,+ arm = "treatment",+ parity = None,+):+ """A payload that DECLARES a windowed arm the way `__main__.py` records it, and measures nothing.++ Both records are written because both are read: the gate row `windowed_readiness:{arm}` that+ `--windowed-arm` produces, and `readiness.mode` on the cell row.+ """+ rows = [+ {+ "row_type": "gate",+ "name": f"windowed_readiness:{arm}",+ "passed": True,+ "detail": {"arm": arm, "reason": "declared on the command line with --windowed-arm"},+ }+ ]+ for side in ("base", "treatment"):+ rows.append(+ {+ "row_type": "cell",+ "cell_id": f"r100K.{side}.rep0",+ "readiness": {+ "ready": True,+ "mode": "windowed" if side == arm else "full",+ "expected_messages": 18,+ },+ }+ )+ rows.append(+ _action(+ "select_all_copy",+ f"r100K.{side}.rep0",+ parity = parity if parity is not None else _failed_parity(),+ ran = False,+ reason = "the slot was missed",+ )+ )+ return _write(tmp_path, name, rows)+++def test_a_declared_windowed_run_that_measured_nothing_is_still_windowed(tmp_path):+ """THE DETECTION HOLE. `any_windowed` scanned successful captures for+ `thread_total > mounted_messages`, so a run whose slots were all missed or whose parity probes+ all failed scanned exactly like a run that mounted its whole thread: no window found, `--mode+ auto` picks the digest, every pair comes out NOT_EXERCISED or NOT_COMPARABLE and the report+ exits 0. An entirely unmeasured windowed run produced a green structural result.++ The payload records the declaration independently of the measurement, so it decides when the+ measurement cannot."""+ from studiobench.sweep import ui_parity as U++ shard = _declared_windowed_shard(tmp_path, "declared")+ why = U.any_windowed([shard])+ assert why is not None, "a declared windowed run with no capture read as fully mounted"+ assert "DECLARED, not measured" in why, why+ assert all(mode == U.WINDOWED for mode, _why in U.decide_modes([shard]).values())+++def test_an_unmeasured_windowed_run_does_not_exit_zero(tmp_path, capsys):+ """The consequence, end to end through `main`. Nothing was measured, so no mode has a verdict+ and the run must say so rather than report a structural pass."""+ from studiobench.sweep import ui_parity as U++ _declared_windowed_shard(tmp_path, "declared_main")+ code = U.main([str(tmp_path / "declared_main")])+ out = capsys.readouterr().out+ assert code != 0, out+ assert code == 2, out+ assert "NOTHING WAS COMPARED" in out, out+++def test_a_payload_whose_captures_all_failed_is_not_a_structural_pass(tmp_path, capsys):+ """The same hole with no declaration to fall back on, at the report that would print the pass.+ Every pair is NOT COMPARABLE, so `stable_bad` is empty and `matched` is zero -- and the exit+ guard only refused this when the pairs were NOT APPLICABLE windowed mounts, so a payload whose+ parity probes all failed returned 0 under "No stable action rendered a different THREAD+ STRUCTURE"."""+ from studiobench.sweep import ui_parity as U++ rows = [+ _action("settings", f"r100K.{side}.rep0", parity = _failed_parity())+ for side in ("base", "treatment")+ ]+ code = U.report([_write(tmp_path, "all_failed", rows)], "all failed", frozenset())+ out = capsys.readouterr().out+ assert code == 2, out+ assert "NOTHING WAS COMPARED" in out, out+ assert "No stable action rendered a different THREAD STRUCTURE" not in out, out+++# ── the mode is decided per action pair, not per payload ────────────+++def _copy_expect(*, clipboard, selected, mounted):+ """The `select_all_copy` observations its behavioural invariant is scored on."""+ return {+ "selected_chars": selected,+ "clipboard_chars": clipboard,+ "clipboard_readable": True,+ "clipboard_note": None,+ "messages_total": 18,+ "messages_mounted": mounted,+ "mounted_fraction": round(mounted / 18, 3),+ }+++def _mixed_rung_shard(tmp_path, name):+ """One payload holding a fully mounted 1K rung and a windowed 100K rung, which is exactly what+ the windowed readiness gate permits an arm to do, plus a DOM regression at the 1K rung.++ The 100K rung is a CLEAN windowed pair: it holds its behavioural invariants (the clipboard+ still carries the whole thread) and its visible region matches, so the only thing left that can+ fail this payload is the digest at the rung where both arms mount everything.+ """+ rows = [+ {+ "row_type": "gate",+ "name": "windowed_readiness:treatment",+ "passed": True,+ "detail": {"arm": "treatment"},+ }+ ]+ for side in ("base", "treatment"):+ digest = "regressed" if side == "treatment" else "shipped"+ rows.append(+ _action(+ "select_all_copy",+ f"r1K.{side}.rep0",+ parity = _capture(mounted = 18, total = 18, digest = digest),+ visible = _visible([1], [1], digest = digest),+ expect = _copy_expect(clipboard = 200_000, selected = 200_000, mounted = 18),+ )+ )+ windowed = side == "treatment"+ rows.append(+ _action(+ "select_all_copy",+ f"r100K.{side}.rep0",+ parity = _capture(mounted = 9 if windowed else 18, total = 18, digest = "shipped"),+ visible = _visible([1], [1]),+ expect = _copy_expect(+ clipboard = 200_000,+ selected = 66_000 if windowed else 200_000,+ mounted = 9 if windowed else 18,+ ),+ )+ )+ return _write(tmp_path, name, rows)+++def test_two_rungs_of_one_payload_are_two_pairs_and_not_one(tmp_path):+ """`make_cell_id` writes `r{rung}.{arm}.rep{n}` and the pair key took only the last segment, so+ `r1K.base.rep0` and `r100K.base.rep0` were the same key: one rung's rows overwrote the other's+ and half the payload disappeared before anything was compared. The per-pair mode decision needs+ both rungs to exist before it can score them differently."""+ from studiobench.sweep import ui_parity as U++ shard = _mixed_rung_shard(tmp_path, "mixed_keys")+ pairs = U.collect([shard])["pairs"]+ assert len(pairs) == 2, sorted(pairs)+ cells = {f"{rung} {rep}" for _shard, rung, rep, _sid, _action in pairs}+ assert cells == {"r1K rep0", "r100K rep0"}, cells+ assert all(set(sides) == {"base", "treatment"} for sides in pairs.values())+++def test_the_windowed_large_rung_does_not_suppress_the_digest_on_the_mounted_small_one(+ tmp_path, capsys+):+ """THE FINDING. Deciding the mode per PAYLOAD meant one windowed 100K capture put every pair in+ that payload on the behavioural and visible-region scales -- including the 1K rung, where both+ arms mount their whole thread and the structural digest is exactly the right question. An+ ordinary DOM regression at that rung was then never looked for.++ Here the treatment's 1K digest differs and its 100K rung is a genuine window. The regression has+ to be found, by name, and the windowed rung has to stay out of the structural section."""+ from studiobench.sweep import ui_parity as U++ shard = _mixed_rung_shard(tmp_path, "mixed")+ modes = {+ f"{rung} {rep}": mode+ for (_s, rung, rep, _sid, _a), (mode, _why) in U.decide_modes([shard]).items()+ }+ assert modes == {"r1K rep0": U.STRUCTURAL, "r100K rep0": U.WINDOWED}, modes++ code = U.main([str(tmp_path / "mixed")])+ out = capsys.readouterr().out+ assert "MODE DECIDED PER ACTION PAIR: 1 of 2" in out, out+ assert "UI PARITY DIFFERENCES ON STABLE ACTIONS" in out, out+ assert "r1K rep0" in out.split("UI PARITY DIFFERENCES ON STABLE ACTIONS")[1], out+ # (1 fully mounted pair(s) of 2) in the heading: a structural section that silently covered+ # part of a payload would read as a verdict on all of it.+ assert "1 fully mounted pair(s) of 2" in out, out+ assert code == 1, out+++def test_the_exit_status_combines_every_mode_that_ran(tmp_path, capsys):+ """Any mode's failure fails the run. The windowed rung passes its own two modes here and the+ fully mounted rung fails the digest, so the combined status is the failure."""+ from studiobench.sweep import ui_parity as U++ _mixed_rung_shard(tmp_path, "combined")+ code = U.main([str(tmp_path / "combined")])+ out = capsys.readouterr().out+ assert "COMBINED EXIT STATUS 1" in out, out+ assert code == 1+++def test_an_arm_declared_windowed_is_still_digested_where_it_mounted_everything(tmp_path):+ """The declaration is a FALLBACK and never an override. `--windowed-arm treatment` is a+ statement about the arm, not about every rung it ran: at 1K it mounts the whole thread, the+ capture proves it, and that pair is owed a structural digest like any other."""+ from studiobench.sweep import ui_parity as U++ rows = [+ {+ "row_type": "gate",+ "name": "windowed_readiness:treatment",+ "passed": True,+ "detail": {"arm": "treatment"},+ }+ ]+ for side in ("base", "treatment"):+ rows.append(_action("settings", f"r1K.{side}.rep0", parity = _capture(mounted = 18, total = 18)))+ shard = _write(tmp_path, "declared_but_mounted", rows)+ assert all(mode == U.STRUCTURAL for mode, _why in U.decide_modes([shard]).values())+ assert U.any_windowed([shard]) is None+++# ── the declared arm that never produced a row at all ───────────────+++def _one_sided_shard(+ tmp_path,+ name,+ *,+ gate = True,+ cell_row = False,+):+ """A mixed-rung payload whose declared-windowed TREATMENT arm died at the large rung.++ The 1K rung is a clean, fully mounted pair that both arms recorded, so the structural report+ has something to pass on. At 100K only the base arm ever emitted an action row: `sides` holds+ one side, and the only thing left that can say the missing arm mounts a window is the run's own+ declaration -- the `--windowed-arm` gate row, or the cell row's `readiness.mode`.+ """+ rows = []+ if gate:+ rows.append(+ {+ "row_type": "gate",+ "name": "windowed_readiness:treatment",+ "passed": True,+ "detail": {"arm": "treatment"},+ }+ )+ if cell_row:+ rows.append(+ {+ "row_type": "cell",+ "cell_id": "r100K.treatment.rep0",+ "completed": False,+ "readiness": {"ready": True, "mode": "windowed", "expected_messages": 18},+ }+ )+ for side in ("base", "treatment"):+ rows.append(+ _action(+ "select_all_copy",+ f"r1K.{side}.rep0",+ parity = _capture(mounted = 18, total = 18),+ visible = _visible([1], [1]),+ expect = _copy_expect(clipboard = 200_000, selected = 200_000, mounted = 18),+ )+ )+ rows.append(+ _action(+ "select_all_copy",+ "r100K.base.rep0",+ parity = _capture(mounted = 18, total = 18),+ visible = _visible([1], [1]),+ expect = _copy_expect(clipboard = 200_000, selected = 200_000, mounted = 18),+ )+ )+ return _write(tmp_path, name, rows)+++def test_a_declared_windowed_arm_with_no_row_is_not_scored_structurally(tmp_path):+ """THE ONE-SIDED HOLE. The declaration fallback was read off the rows the pair HAS, so an arm+ that failed before emitting an action row was never asked about: the loop saw the base row,+ found no declaration for the base arm, and classified the pair structural."""+ from studiobench.sweep import ui_parity as U++ shard = _one_sided_shard(tmp_path, "one_sided")+ modes = {+ f"{rung} {rep}": (mode, why)+ for (_s, rung, rep, _sid, _a), (mode, why) in U.decide_modes([shard]).items()+ }+ assert modes["r100K rep0"][0] == U.WINDOWED, modes+ assert "DECLARED, not measured" in modes["r100K rep0"][1], modes+ # And the rung that really did mount everything on both arms is still owed its digest.+ assert modes["r1K rep0"][0] == U.STRUCTURAL, modes+++def test_a_windowed_cell_row_declares_the_arm_even_when_that_arm_has_no_action_row(tmp_path):+ """The other declaration, and the one that needs the missing arm's cell id to be derived at+ all: a run without `--windowed-arm` whose treatment cell was admitted by the WINDOWED readiness+ gate records that on the cell row, under a cell id no surviving row carries."""+ from studiobench.sweep import ui_parity as U++ shard = _one_sided_shard(tmp_path, "one_sided_cell", gate = False, cell_row = True)+ modes = {+ f"{rung} {rep}": mode+ for (_s, rung, rep, _sid, _a), (mode, _why) in U.decide_modes([shard]).items()+ }+ assert modes["r100K rep0"] == U.WINDOWED, modes+ assert modes["r1K rep0"] == U.STRUCTURAL, modes+++def test_a_missing_windowed_arm_does_not_exit_zero_on_the_strength_of_the_other_rung(+ tmp_path, capsys+):+ """THE CONSEQUENCE. The fully mounted 1K pair supplies `matched > 0`, the 100K pair is filed as+ structurally NOT COMPARABLE, and the command exits 0 -- having never run a windowed report for+ the rung whose treatment arm produced nothing at all."""+ from studiobench.sweep import ui_parity as U++ _one_sided_shard(tmp_path, "one_sided_main")+ code = U.main([str(tmp_path / "one_sided_main")])+ out = capsys.readouterr().out+ assert "windowed: " in out and "r100K rep0" in out, out+ assert "NOTHING WAS COMPARED" in out, out+ assert code == 2, out+++def test_a_pair_missing_an_arm_with_no_declaration_anywhere_is_still_structural(tmp_path):+ """The fallback must not become an override in the other direction: with nothing declaring a+ window, a pair one arm failed to record is the structural report's problem, and it refuses it+ there. Otherwise every crashed cell in an ordinary A/B would be routed to a mode that cannot+ say anything about it either."""+ from studiobench.sweep import ui_parity as U++ shard = _one_sided_shard(tmp_path, "one_sided_undeclared", gate = False)+ modes = {+ f"{rung} {rep}": mode+ for (_s, rung, rep, _sid, _a), (mode, _why) in U.decide_modes([shard]).items()+ }+ assert modes == {"r1K rep0": U.STRUCTURAL, "r100K rep0": U.STRUCTURAL}, modes+++def test_a_capture_that_saw_no_thread_at_all_falls_back_on_the_declaration(tmp_path):+ """MEASURED on the real 100K film: after `model_change` the treatment arm's captures read 0 of+ 0 messages for the rest of the film. `windowed_mount` answers False for 0 of 0 -- nothing is+ missing from a thread of nothing -- so that capture would score a declared windowed arm+ structurally on the strength of a probe that observed no messages."""+ from studiobench.sweep import ui_parity as U++ lost = {+ "parity_attempted": True,+ "root_kind": "thread",+ "digest": "d",+ "chars": 0,+ "messages": [],+ "overlays": [],+ "styles": {"elements": 0, "digest": "s", "capped": False},+ "mounted_messages": 0,+ "thread_total": 0,+ }+ shard = _declared_windowed_shard(tmp_path, "lost_thread", parity = lost)+ assert all(mode == U.WINDOWED for mode, _why in U.decide_modes([shard]).values())+++# ── a cell that failed its own completeness gate carries no UI verdict ──+#+# `probe_thread_completeness` runs before the film and `record_completeness_gate` writes the+# verdict against the cell, so a windowed arm that kept its first page and its last one and lost+# everything between them says so in its own payload. `report/payload.py::excluded_from_rows`+# drops that cell from the PERFORMANCE score. `ui_parity.py` read no gate row except the windowed+# declaration, so the same cell's eighteen action rows were still scored for UI parity -- and the+# visible region is a window on the END of the thread, which such a store still fills, so the+# pairs matched and `--mode auto` exited 0 over a payload that had already recorded the loss.+++def _completeness_gate(+ cell_id,+ passed,+ reason = "the head of the thread mounted, but 12 of 18 ordinals never mounted",+):+ return {+ "row_type": "gate",+ "name": "thread_complete",+ "passed": passed,+ "cell_id": cell_id,+ "detail": {"probe_attempted": True, "head_reached": True, "reason": reason},+ }+++def _matching_pair(cell_suffix = "rep0", ordinals = (17, 18)):+ """One action, both arms, identical inside the viewport: the pair that used to carry the run."""+ out = []+ for side in ("base", "treatment"):+ out.append(+ _action(+ "select_text",+ f"r100K.{side}.{cell_suffix}",+ parity = _capture(mounted = 6, total = 18),+ visible = _visible(ordinals, ordinals),+ )+ )+ return out+++def test_a_cell_that_lost_messages_gets_no_visible_pass(tmp_path, capsys):+ """THE FALSE GREEN. The arm's own gate says it is missing the middle of the conversation and+ the visible region matched anyway, because the visible region is the end of the thread."""+ from studiobench.sweep import ui_parity as U++ rows = [_completeness_gate("r100K.treatment.rep0", False)] + _matching_pair()+ shard = _write(tmp_path, "lost_middle", rows)+ code = U.visible_report([shard], "lost middle")+ out = capsys.readouterr().out+ assert code == 2, out+ assert "visible region matched: 0" in out, out+ assert "FAILED its completeness gate" in out, out+++def _held_invariant_pair(cell_suffix = "rep0"):+ """A `select_text` pair whose declared invariant HOLDS: the windowed arm selected the same+ characters and sized its spacers, so `compare_behaviour` returns MATCH. This is the shape a+ store that kept its first page and its last one still produces."""+ out = []+ for side, mounted in (("base", 18), ("treatment", 6)):+ row = _row(+ "select_text",+ _capture(mounted, 18),+ selected_chars = 100,+ visible_chars = 100,+ )+ row["cell_id"] = f"r100K.{side}.{cell_suffix}"+ out.append(row)+ return out+++def test_a_cell_that_lost_messages_gets_no_behavioural_pass_either(tmp_path, capsys):+ """The behavioural invariants are what REPLACE the digest on a windowed arm, so a pass here is+ the whole UI verdict for that pair."""+ from studiobench.sweep import ui_parity as U++ rows = [_completeness_gate("r100K.treatment.rep0", False)] + _held_invariant_pair()+ shard = _write(tmp_path, "lost_middle_b", rows)+ code = U.behaviour_report([shard], "lost middle")+ out = capsys.readouterr().out+ assert code == 2, out+ assert "invariants held: 0" in out, out+ assert "NOTHING WAS COMPARED" in out, out+++def _follow_gate(+ cell_id,+ passed,+ reason = "the thread fell behind the streamed reply for 38% of the streaming phase",+):+ return {+ "row_type": "gate",+ "name": "follows_the_stream",+ "passed": passed,+ "cell_id": cell_id,+ "detail": {"reason": reason},+ }+++def test_a_cell_that_stopped_following_the_stream_gets_no_behavioural_pass(tmp_path, capsys):+ """REGRESSION. `follows_the_stream` invalidates a pair for the same reason `thread_complete`+ does, and this file recognised only the latter.++ A reply that scrolled out of the viewport and was unmounted stops costing anything to render,+ so the arm was not showing the thing under test -- yet the invariants that do not depend on it+ still hold. A `select_text` pair matches, `invariants held` grows, and `--mode auto` exits 0+ over a payload that has already recorded the arm losing the stream.+ """+ from studiobench.sweep import ui_parity as U++ rows = [_follow_gate("r100K.treatment.rep0", False)] + _held_invariant_pair()+ shard = _write(tmp_path, "lost_stream", rows)+ code = U.behaviour_report([shard], "lost stream")+ out = capsys.readouterr().out+ assert code == 2, out+ assert "invariants held: 0" in out, out+ assert "FAILED its stream-follow gate" in out, out+++def test_a_cell_that_kept_following_the_stream_still_scores(tmp_path, capsys):+ """The positive control: the same pair, gate passed, is scored exactly as before."""+ from studiobench.sweep import ui_parity as U++ rows = [_follow_gate("r100K.treatment.rep0", True)] + _held_invariant_pair()+ shard = _write(tmp_path, "kept_stream", rows)+ code = U.behaviour_report([shard], "kept stream")+ out = capsys.readouterr().out+ assert code == 0, out+ assert "invariants held: 1" in out, out+++def test_a_complete_cell_still_earns_its_behavioural_pass(tmp_path, capsys):+ """The positive control for the test above: the same pair, gate passed, still scores."""+ from studiobench.sweep import ui_parity as U++ rows = [_completeness_gate("r100K.treatment.rep0", True)] + _held_invariant_pair()+ shard = _write(tmp_path, "complete_b", rows)+ code = U.behaviour_report([shard], "complete")+ out = capsys.readouterr().out+ assert code == 0, out+ assert "invariants held: 1" in out, out+++def test_a_cell_whose_completeness_gate_PASSED_is_scored_exactly_as_before(tmp_path, capsys):+ """The positive control. A refusal that fires on every cell measures nothing, and the shipped+ build passes this gate on every cell it runs."""+ from studiobench.sweep import ui_parity as U++ rows = [_completeness_gate("r100K.treatment.rep0", True)] + _matching_pair()+ shard = _write(tmp_path, "complete", rows)+ code = U.visible_report([shard], "complete")+ out = capsys.readouterr().out+ assert code == 0, out+ assert "visible region matched: 1" in out, out+++def test_only_the_cell_that_failed_is_refused(tmp_path, capsys):+ """Attribution. The gate names its cell, so a rep that lost messages must not silence the rep+ beside it -- that would be the mirror defect, a whole payload lost to one bad cell."""+ from studiobench.sweep import ui_parity as U++ rows = [_completeness_gate("r100K.treatment.rep0", False)]+ rows += _matching_pair("rep0")+ rows += _matching_pair("rep1")+ shard = _write(tmp_path, "one_bad_rep", rows)+ code = U.visible_report([shard], "one bad rep")+ out = capsys.readouterr().out+ assert code == 0, out+ assert "visible region matched: 1" in out, out+ assert "NOT COMPARABLE: 1" in out, out+++# ── one glob pools separate runs, and a declaration belongs to the run that made it ──+++def _legacy_capture(digest):+ """A capture from a checkout that predates `mounted_messages` / `thread_total`.++ `parity.windowed_mount` reads those two numbers and says of their absence: captures taken+ before they existed report neither and are treated as full-mount, which is what they were.+ Such a payload digests perfectly well and carries NO mount measurement, so every one of its+ pairs falls through to the declaration fallback.+ """+ return {+ "parity_attempted": True,+ "root_kind": "thread",+ "digest": digest,+ "chars": 100,+ "messages": [+ {"i": i, "role": "assistant", "digest": f"{digest}{i}", "chars": 10} for i in range(18)+ ],+ "overlays": [],+ "styles": {"elements": 18, "digest": "s", "capped": False},+ }+++def _two_run_glob(tmp_path):+ """Two SEPARATE runs under one glob: `sb_win` was launched with `--windowed-arm treatment`,+ `sb_old` was an ordinary A/B from an older checkout whose treatment arm has a DOM regression."""+ win = [+ {+ "row_type": "gate",+ "name": "windowed_readiness:treatment",+ "passed": True,+ "detail": {"arm": "treatment"},+ }+ ]+ for side in ("base", "treatment"):+ win.append(+ _action(+ "select_all_copy",+ f"r100K.{side}.rep0",+ parity = _capture(mounted = 9 if side == "treatment" else 18, total = 18),+ visible = _visible([1], [1]),+ expect = _copy_expect(+ clipboard = 200_000,+ selected = 66_000 if side == "treatment" else 200_000,+ mounted = 9 if side == "treatment" else 18,+ ),+ )+ )+ _write(tmp_path, "sb_win", win)+ old = [+ _action(+ "select_all_copy",+ f"r1K.{side}.rep0",+ parity = _legacy_capture("regressed" if side == "treatment" else "shipped"),+ visible = _visible([1], [1]),+ expect = _copy_expect(clipboard = 200_000, selected = 200_000, mounted = 18),+ )+ for side in ("base", "treatment")+ ]+ _write(tmp_path, "sb_old", old)+++def _modes_by_shard_action(decided):+ """{(shard, action): mode}, so an assertion does not have to spell the whole pair key."""+ return {(key[0], key[-1]): mode for key, (mode, _why) in decided.items()}+++def test_a_windowed_declaration_does_not_leak_into_another_run_under_one_glob(tmp_path, capsys):+ """DECLARATIONS ARE PER SHARD. `outputs/sbench_*` pools separate runs, and `cell_id` and arm+ label repeat identically in every one of them, so a `--windowed-arm treatment` gate row in one+ run became the fallback for every unmeasured pair in an ordinary run beside it. The ordinary+ run's pairs were scored on the visible region and on behavioural invariants instead, the+ structural digest they were owed never ran, and its DOM regression exited 0 because of a flag+ passed to a DIFFERENT run.+ """+ from studiobench.sweep import ui_parity as U++ _two_run_glob(tmp_path)+ modes = _modes_by_shard_action(U.decide_modes(U.shards_of(f"{tmp_path}/sb_*")))+ assert modes[("sb_old", "select_all_copy")] == U.STRUCTURAL, modes+ assert modes[("sb_win", "select_all_copy")] == U.WINDOWED, modes++ code = U.main([f"{tmp_path}/sb_*"])+ out = capsys.readouterr().out+ assert "UI PARITY DIFFERENCES ON STABLE ACTIONS" in out, out+ assert "sb_old" in out.split("UI PARITY DIFFERENCES ON STABLE ACTIONS")[1], out+ assert code == 1, out+++def test_the_declaration_still_decides_the_run_that_made_it(tmp_path):+ """The positive control for the scoping above: a run's own declaration must still reach its own+ unmeasured pairs, which is the whole reason the fallback exists."""+ from studiobench.sweep import ui_parity as U++ shard = _declared_windowed_shard(tmp_path, "still_declared")+ assert all(mode == U.WINDOWED for mode, _why in U.decide_modes([shard]).values())+ other = _write(+ tmp_path,+ "unrelated",+ [+ _action("settings", f"r1K.{side}.rep0", parity = _capture(mounted = 18, total = 18))+ for side in ("base", "treatment")+ ],+ )+ modes = _modes_by_shard_action(U.decide_modes([shard, other]))+ assert modes[("still_declared", "select_all_copy")] == U.WINDOWED, modes+ assert modes[("unrelated", "settings")] == U.STRUCTURAL, modes+++# ── a visible floor measured on another film tier is not this payload's floor ──+++def _tiered_visible_shard(+ tmp_path,+ name,+ tier,+ differ_actions,+ windowed,+ corpus = "",+):+ """A visible-region payload that records the FILM TIER it was shot on, as `run_meta` does.++ `corpus` is the `corpus_hash` of the thread the film drove, written by the same row. Left out+ by default: a payload recorded before corpus hashes existed declares none, and that is the+ shape the tier tests below are about.+ """+ import json++ rows = [{"row_type": "run_meta", "tier": tier}]+ if corpus:+ rows[0]["corpus_hash"] = corpus+ for action in ("copy_markdown", "select_text"):+ for rep in range(2):+ for side in ("base", "treatment"):+ digest = "X" if (action in differ_actions and side == "treatment") else "same"+ mounted = 9 if (windowed and side == "treatment") else 18+ rows.append(+ _action(+ action,+ f"r100K.{side}.rep{rep}",+ parity = _capture(mounted = mounted, total = 18),+ visible = _visible([1], [1], digest = digest),+ expect = {+ "clipboard_chars": 5000,+ "selected_chars": 100,+ "visible_chars": 100,+ },+ )+ )+ shard = tmp_path / name+ shard.mkdir()+ (shard / "payload.jsonl").write_text("\n".join(json.dumps(r) for r in rows), encoding = "utf-8")+ return shard+++def test_a_visible_floor_from_another_film_tier_is_not_applied(tmp_path, capsys):+ """THE INCOMPARABLE CONTROL. `tier_of` states the mechanism: on the fast film `copy_markdown`+ opens 2.7 s after a `send_turn` and lands inside that turn's stream, so it differs against+ itself; on the standard film it opens 26 s later against a finished reply. `--tier fast` then+ `--tier standard` is the documented way to work, so a stale fast null control on a standard+ run's command line is the ordinary mistake, not an exotic one.++ The floor derived from it was keyed by `(rung, action)` with no tier in it, so it silenced the+ standard payload's real visible difference, and an ALL-WINDOWED payload returns before the+ structural section that would have warned about the mismatch, so the command exited 0 without+ a word about the tier.+ """+ from studiobench.sweep import ui_parity as U++ null = _tiered_visible_shard(tmp_path, "null_fast", "fast", {"copy_markdown"}, windowed = False)+ arm = _tiered_visible_shard(+ tmp_path, "arm_standard", "standard", {"copy_markdown"}, windowed = True+ )+ assert U.visible_unstable_set(U.shards_of(str(null))) == frozenset({("r100K", "copy_markdown")})++ code = U.main([str(arm), "--null", str(null)])+ out = capsys.readouterr().out+ assert "FLOOR REFUSED" in out, out+ assert "DIFFERENCES INSIDE THE VIEWPORT" in out, out+ assert code == 1, out+++def test_a_visible_floor_from_the_SAME_tier_still_applies(tmp_path, capsys):+ """The positive control, and the verdict this must not change: a null control shot on the same+ film still silences the action it measured differing against itself."""+ from studiobench.sweep import ui_parity as U++ null = _tiered_visible_shard(+ tmp_path, "null_std", "standard", {"copy_markdown"}, windowed = False+ )+ arm = _tiered_visible_shard(tmp_path, "arm_std", "standard", {"copy_markdown"}, windowed = True)+ code = U.main([str(arm), "--null", str(null)])+ out = capsys.readouterr().out+ assert "FLOOR REFUSED" not in out, out+ assert "differ against an identical build" in out, out+ assert code == 0, out+++def test_a_visible_floor_from_another_corpus_is_not_applied(tmp_path, capsys):+ """THE OTHER AXIS OF THE SAME INCOMPARABLE CONTROL, and the quieter one. Which actions differ+ against an identical build is a property of the thread the film drove, not only of the film's+ spacing, so a null control recorded against corpus `c1` describes a thread a `c2` payload+ never rendered. The ordinary way in is a corpus revision landing while an older null control+ is still sitting in the directory the workflow globs.++ `cross_side_mismatch` already refuses this, but only in the structural section, and an+ ALL-WINDOWED payload -- which is every payload under `--mode visible` -- returns before it,+ so the wrong-corpus floor silenced the payload's real visible difference and the command+ exited 0 without a word about the corpus.+ """+ from studiobench.sweep import ui_parity as U++ null = _tiered_visible_shard(+ tmp_path, "null_c1", "standard", {"copy_markdown"}, windowed = False, corpus = "c1"+ )+ arm = _tiered_visible_shard(+ tmp_path, "arm_c2", "standard", {"copy_markdown"}, windowed = True, corpus = "c2"+ )+ assert U.visible_unstable_set(U.shards_of(str(null))) == frozenset({("r100K", "copy_markdown")})++ code = U.main([str(arm), "--null", str(null)])+ out = capsys.readouterr().out+ assert "FLOOR REFUSED" in out, out+ assert "corpus" in out, out+ assert "DIFFERENCES INSIDE THE VIEWPORT" in out, out+ assert code == 1, out+++def test_a_visible_floor_from_the_SAME_corpus_still_applies(tmp_path, capsys):+ """The positive control for the corpus axis: a null control recorded against the same thread+ still silences the action it measured differing against itself."""+ from studiobench.sweep import ui_parity as U++ null = _tiered_visible_shard(+ tmp_path, "null_same", "standard", {"copy_markdown"}, windowed = False, corpus = "c1"+ )+ arm = _tiered_visible_shard(+ tmp_path, "arm_same", "standard", {"copy_markdown"}, windowed = True, corpus = "c1"+ )+ code = U.main([str(arm), "--null", str(null)])+ out = capsys.readouterr().out+ assert "FLOOR REFUSED" not in out, out+ assert "differ against an identical build" in out, out+ assert code == 0, out+++# ── a resumed cell is judged on the attempt that survived, gates included ──+++def _resumed_completeness_shard(tmp_path, name, *, retry_passes):+ """A payload where attempt 1 of a cell FAILED `thread_complete` and `--resume` re-ran it.++ `make_cell_id` is deterministic, so the retry carries the SAME `cell_id` and is told apart+ only by `session_id`, exactly as `latest_attempt_rows` documents.+ """+ import json++ rows = [{"row_type": "run_meta", "tier": "standard", "session_id": "s1"}]+ for side in ("base", "treatment"):+ cid = f"r100K.{side}.rep0"+ rows.append({"row_type": "cell", "cell_id": cid, "session_id": "s1"})+ rows.append(+ {+ "row_type": "gate",+ "name": "thread_complete",+ "passed": False,+ "cell_id": cid,+ "session_id": "s1",+ "detail": {"reason": "the head marker never mounted"},+ }+ )+ for side in ("base", "treatment"):+ cid = f"r100K.{side}.rep0"+ rows.append({"row_type": "cell", "cell_id": cid, "session_id": "s2"})+ rows.append(+ {+ "row_type": "gate",+ "name": "thread_complete",+ "passed": bool(retry_passes),+ "cell_id": cid,+ "session_id": "s2",+ "detail": {"reason": "" if retry_passes else "still short"},+ }+ )+ act = _action(+ "select_text",+ cid,+ parity = _capture(mounted = 18, total = 18),+ visible = _visible([1], [1]),+ )+ act["session_id"] = "s2"+ rows.append(act)+ shard = tmp_path / name+ shard.mkdir()+ (shard / "payload.jsonl").write_text("\n".join(json.dumps(r) for r in rows), encoding = "utf-8")+ return shard+++def test_a_successful_resume_clears_the_dead_attempts_completeness_failure(tmp_path):+ """THE SUPERSEDED GATE MUST NOT OUTLIVE ITS ATTEMPT. `latest_attempt_rows` drops a dead+ attempt's rows everywhere else, but its ATTEMPT_ROW_TYPES is {cell, action, window} and a gate+ is none of those, so `incomplete_cells` scanned raw rows and kept the failure from the attempt+ that died. `collect` then stamped `_incomplete` on the RETRY's action rows and `_refused`+ withheld a verdict from a cell that had just been re-measured successfully.+ """+ from studiobench.sweep import ui_parity as U++ shard = _resumed_completeness_shard(tmp_path, "resumed_ok", retry_passes = True)+ assert U.incomplete_cells([shard / "payload.jsonl"]) == {}+++def test_a_resume_that_failed_again_is_still_refused(tmp_path):+ """The positive control: scoping the gate to the surviving attempt must not lose a real+ refusal when the retry failed too."""+ from studiobench.sweep import ui_parity as U++ shard = _resumed_completeness_shard(tmp_path, "resumed_bad", retry_passes = False)+ bad = U.incomplete_cells([shard / "payload.jsonl"])+ assert set(bad) == {"r100K.base.rep0", "r100K.treatment.rep0"}, bad+ assert "still short" in bad["r100K.base.rep0"], baddiff --git a/tests/studio/studiobench/sweep/ui_parity.py b/tests/studio/studiobench/sweep/ui_parity.pyindex b6d6b1055ab..c2475978b14 100644--- a/tests/studio/studiobench/sweep/ui_parity.py+++ b/tests/studio/studiobench/sweep/ui_parity.py@@ -49,13 +49,19 @@ import collectionsimport jsonimport sysfrom pathlib import Path+from typing import Any, Optionalif __package__ in (None, ""): # pragma: no cover# Running the file directly rather than as a module, which is the first thing anyone tries.sys.path.insert(0, str(Path(__file__).resolve().parents[4]))+from tests.studio.studiobench.analysis import behaviour as B # noqa: E402from tests.studio.studiobench.analysis import parity as P # noqa: E402-from tests.studio.studiobench.scoring.from_payload import latest_attempt_rows # noqa: E402+from tests.studio.studiobench.runtime.ab import gate_detail_is_unmeasured # noqa: E402+from tests.studio.studiobench.scoring.from_payload import ( # noqa: E402+ ATTEMPT_ROW_TYPES,+ latest_attempt_rows,+)# The DECLARED unstable set, each entry carrying its mechanism. It lives in the studiobench# package rather than here so that a test can require a mechanism for every entry, and so that@@ -67,6 +73,70 @@ from tests.studio.studiobench.scoring.from_payload import latest_attempt_rows ## audited rather than inherited.UNSTABLE_ACTIONS = frozenset(P.UNSTABLE_ACTIONS)+#: THE RUN'S OWN DECLARATION that an arm mounts a window, as `__main__.py` records it: the gate row+#: `windowed_readiness:{arm}` written when `--windowed-arm` names that side, and `readiness.mode` on+#: every cell row. Matched as literal strings rather than imported from `runtime/readiness.py`+#: because this script reads payloads written by other checkouts of the tool, where what has to be+#: matched is the string in the file and not the constant in this working tree.+WINDOWED_GATE = "windowed_readiness:"+MODE_WINDOWED = "windowed"++#: THE CELL'S OWN VERDICT THAT IT LOST MESSAGES. `runtime/session.py::record_completeness_gate`+#: writes this row, against the cell, when the traversal to the top of the thread could not+#: establish that the arm still holds the whole conversation -- the head marker never mounted, or+#: the ordinals recorded on the way up have a hole in them. `report/payload.py::excluded_from_rows`+#: reads it as a failed gate and drops the cell from the PERFORMANCE score; this file read no gate+#: rows at all except the windowed declaration, so the same cell's action rows were still scored+#: for UI parity. An arm that keeps the first page and the last one and has lost the middle then+#: retains its first and last visible windows, and its bottom rows, its scroll extent and an+#: action-specific invariant such as `select_text` can all match: `--mode auto` printed a visible+#: pass and a behavioural pass and exited 0 over a payload that already recorded the loss.+#: Matched as a literal string for the same reason `WINDOWED_GATE` is.+COMPLETENESS_GATE = "thread_complete"++#: THE CELL'S OWN VERDICT THAT IT STOPPED FOLLOWING THE REPLY IT WAS MEASURING. `runtime/session`+#: writes this row, against the cell, when the thread did not stay pinned for enough of the+#: streaming phase or too little of that phase had the stream attached at all. It belongs beside+#: the completeness gate rather than in a category of its own, because it invalidates the same+#: thing: a reply that scrolled out of the viewport and was unmounted by a windowed arm stops+#: costing anything to render, and the action rows measured around it are a reading of an arm that+#: was not showing the thing under test. `select_text` counts and bottom rows can still match+#: across such a pair, so `--mode auto` printed a behavioural pass and exited 0 over a payload+#: that had already recorded the arm losing the stream. Matched as a literal string for the same+#: reason the two gates above it are.+FOLLOW_GATE = "follows_the_stream"++#: The per-cell gates whose failure means this cell's action rows are not a reading of the build.+#: A gate that only qualifies one column -- `timer_clamp`, whose failure leaves every column but+#: `busy_pct` standing -- is deliberately NOT here; see `runtime/ab.py::INVALIDATING_CELL_GATES`,+#: which is the same list for the performance side.+INVALIDATING_GATES: tuple[str, ...] = (COMPLETENESS_GATE, FOLLOW_GATE)++#: How each is named and what its failure means, for the refusal a reader actually sees. The gate+#: is described rather than spelled with its row name, because this string is read by somebody+#: deciding whether a run is usable, not by a parser.+_GATE_LABEL: dict[str, str] = {+ COMPLETENESS_GATE: "completeness",+ FOLLOW_GATE: "stream-follow",+}+_GATE_REASON: dict[str, str] = {+ COMPLETENESS_GATE: "the arm is not holding the whole conversation",+ FOLLOW_GATE: "the arm stopped following the streamed reply",+}++#: How one action pair is scored. PER PAIR, never per payload: the readiness gate deliberately+#: permits a payload to hold fully mounted small rungs and windowed large ones, so a payload-wide+#: decision lets one windowed 100K capture suppress the structural digest on every fully mounted 1K+#: pair beside it, and an ordinary DOM regression at those rungs is then never looked for.+WINDOWED = "windowed"+STRUCTURAL = "structural"++#: The arms a pair is expected to have. Consulted BY NAME rather than by walking the rows that are+#: present, because the case that matters is the arm with NO row: an arm that died before it emitted+#: an action row leaves `sides` holding only the other one, and reading the declaration off the rows+#: present asks the surviving arm whether the missing one was windowed.+ARMS = ("base", "treatment")+def rows(path: Path) -> list[dict]:return [@@ -79,10 +149,107 @@ def arm_of(cell_id: str) -> str:def rung_of(cell_id: str) -> str:+ """The RUNG segment of a cell id: `r100K.base.rep0` -> `r100K`.++ THE SCOPE A MEASURED NOISE FLOOR IS ALLOWED TO BE APPLIED AT, and half of a pair's identity.+ Not the shard: a null control is its own output directory, so a shard-scoped floor would match+ nothing in the payload it was measured for. Not the rep either: reps are repetitions of one+ configuration, and pooling them is what turns a single flake into the several observations a+ floor has to be built from.+ """return cell_id.split(".", 1)[0]-def collect(paths: list[Path], require_complete: bool = False) -> dict:+def incomplete_cells(paths: list[Path]) -> dict[str, str]:+ """{cell_id: why} for every cell that FAILED one of the gates in `INVALIDATING_GATES`.++ THE PAYLOAD ALREADY KNOWS. `probe_thread_completeness` scrolls the whole thread before the+ film and `record_completeness_gate` writes the verdict against the cell, so a windowed arm+ that has really lost part of the conversation says so in its own payload. Nothing in this file+ read it, and the reports below then scored every action row of that cell: the visible region+ is a window on the end of the thread and a store that kept its first and last pages still+ fills it, so the pair matched, `matched` grew, and `--mode auto` exited 0 on a run whose own+ self-check had recorded conversation loss.++ A gate row with no `cell_id` is ignored here rather than applied run-wide. Only the per-cell+ writer emits this name, and attributing a nameless one to every cell would let one malformed+ row silence a whole payload -- the mirror of the defect being fixed.++ AND ONLY THE ATTEMPT THAT SURVIVED. `--resume` re-runs a cell that did not complete under the+ SAME `cell_id`, because `make_cell_id` is deterministic, so a payload can hold a failed gate+ from the attempt that died and a passing one from the retry that worked. `latest_attempt_rows`+ already drops the superseded attempt everywhere else, but its `ATTEMPT_ROW_TYPES` is+ `{cell, action, window}` and a gate is none of those, so scanning raw rows here kept the dead+ attempt's failure forever: `collect` then stamped `_incomplete` on the RETRY's action rows and+ `_refused` withheld a verdict from a cell that had been successfully re-measured. An attempt is+ `(cell_id, session_id)`, and the winner is named FROM THE SAME ATTEMPT-KEYED ROW TYPES+ `latest_attempt_rows` reads rather than from the terminal `cell` row alone. That row is written+ in `CellRunner.run`'s `finally`, which a SIGKILL or an OOM kill never reaches, while the+ Recorder has already fsynced every gate and action row before it. So a resume hard-killed+ inside a cell left the OLDER, completed session named as the winner: the new attempt's own+ failed gate was discarded here while `latest_attempt_rows` kept that same attempt's action+ rows, and `collect` scored a cell whose own self-check had recorded conversation loss with no+ `_incomplete` stamp on it -- a visible and behavioural pass, and exit 0, over exactly the+ payload this function exists to refuse. A gate with no session id is still honoured, for the+ same reason that function keeps unstamped rows: a payload written before the recorder stamped+ them cannot be split into attempts, and ignoring it would lose a real refusal.+ """+ out: dict[str, str] = {}+ for path in paths:+ payload = rows(path)+ winner: dict[str, Any] = {}+ for r in payload:+ if r.get("row_type") in ATTEMPT_ROW_TYPES and r.get("cell_id") is not None:+ winner[str(r.get("cell_id"))] = r.get("session_id")+ for r in payload:+ if r.get("row_type") != "gate" or r.get("passed") is not False:+ continue+ name = str(r.get("name") or "")+ if name not in INVALIDATING_GATES:+ continue+ cid = str(r.get("cell_id") or "")+ if not cid:+ continue+ keep = winner.get(cid)+ if keep is not None and r.get("session_id") not in (None, keep):+ continue+ detail = r.get("detail") if isinstance(r.get("detail"), dict) else {}+ # NOT MEASURED IS NOT FAILED, and this job draws the line in exactly the same place+ # the performance side does: `gate_detail_is_unmeasured` is THE definition, imported+ # rather than restated. The predicate had been copied here, which is the drift+ # `INVALIDATING_CELL_GATES` was centralised to prevent, arriving one level down.+ #+ # It matters most for the stream-coverage clause: that shortfall is a property of the+ # scene schedule, identical on both arms, and this job compares DOM digests the+ # shortfall does not touch at all. It refused 32 of 32 pairs here, the null control+ # included.+ if gate_detail_is_unmeasured(detail):+ continue+ # FIRST FAILURE WINS, so a cell that failed both is not relabelled by whichever row+ # happens to come second in the file.+ if cid in out:+ continue+ out[cid] = (+ f"cell {cid} FAILED its {_GATE_LABEL[name]} gate: "+ f"{detail.get('reason') or detail.get('coverage_reason') or _GATE_REASON[name]}"+ )+ return out+++def _refused(sides: dict) -> str:+ """Why this pair carries no UI verdict, or `""`. See `incomplete_cells`."""+ for _label, row in sorted(sides.items()):+ why = row.get("_incomplete")+ if why:+ return why+ return ""+++def collect(+ paths: list[Path],+ select: Optional[set] = None,+ require_complete: bool = False,+) -> dict:"""{(shard, rung, rep, session, action): {arm: action row}} plus a tally of what was captured.THE RUNG IS PART OF THE IDENTITY. A standard-tier run walks 1K, 10K and 100K inside one@@ -125,13 +292,23 @@ def collect(paths: list[Path], require_complete: bool = False) -> dict:The WHOLE ROW is carried, not just its digest, because `ran` is part of what the comparisonmeans: a matching digest on an action that never ran is not coverage of that action.++ `select`, when given, restricts the result to those pair keys. It is how one payload gets its+ windowed pairs scored on the visible region and its fully mounted pairs scored structurally in+ the same invocation, without either report seeing pairs the other one owns."""out: dict[tuple, dict] = collections.defaultdict(dict)attempted = missing = 0- incomplete = 0+ # TWO DIFFERENT "INCOMPLETE"S MEET HERE, and they are kept apart on purpose. `gate_failures`+ # is per cell and comes from a gate the payload FAILED, and those rows are stamped and kept.+ # `dropped_incomplete` counts action rows discarded because their cell never wrote a `cell`+ # row at all, which only happens under `require_complete`. Sharing one name between them+ # would make the first silently overwrite the second on the first shard scanned.+ dropped_incomplete = 0no_cell_rows = 0for path in paths:shard = path.parent.name+ gate_failures = incomplete_cells([path])raw_rows = rows(path)# A CELL THAT DID NOT FINISH IS NOT AN OBSERVATION -- ON THE NULL CONTROL ONLY, and the# asymmetry is the point rather than an omission.@@ -181,33 +358,593 @@ def collect(paths: list[Path], require_complete: bool = False) -> dict:for r in kept_rows:if r.get("row_type") != "action":continue+ cid = r.get("cell_id") or ""+ rep = cid.rsplit(".", 1)[-1]+ sid = str(r.get("session_id") or "")+ key = (shard, rung_of(cid), rep, sid, r.get("action"))+ # BEFORE the tally, so a selected report's counts are counts of the pairs it scored.+ if select is not None and key not in select:+ continue+ # And before the tally for the same reason, but after the selection: a row this+ # report never asked for is not an incomplete observation of it.if require_complete and has_cell_rows and r.get("cell_id") not in completed:- incomplete += 1+ dropped_incomplete += 1continueparity = r.get("parity")if isinstance(parity, dict) and parity.get("parity_attempted"):attempted += 1else:missing += 1- cid = r.get("cell_id") or ""- rep = cid.rsplit(".", 1)[-1]- sid = str(r.get("session_id") or "")- out[(shard, rung_of(cid), rep, sid, r.get("action"))][arm_of(cid)] = r+ # STAMPED, NOT DROPPED, for the same reason a failed capture is kept: the comparison+ # layer has to be able to say that this pair carries no verdict, and a row deleted here+ # would leave the pair looking like an action that simply never ran.+ if cid in gate_failures:+ r = dict(r)+ r["_incomplete"] = gate_failures[cid]+ out[key][arm_of(cid)] = rreturn {"pairs": out,"attempted": attempted,"missing": missing,- "incomplete": incomplete,+ "incomplete": dropped_incomplete,"shards_without_cell_rows": no_cell_rows,}-def compare_all(paths: list[Path], require_complete: bool = False) -> tuple[list[tuple], dict]:+def declared_windowed(+ paths: list[Path],+) -> tuple[dict[tuple[str, str], str], dict[tuple[str, str], str]]:+ """What the RUN SAID about windowing: ({(shard, cell_id): why}, {(shard, arm): why}).++ The declaration is the fallback for a pair the measurement cannot answer, and only that. It is+ never allowed to override a capture that did succeed, because the arm named by `--windowed-arm`+ still mounts its whole thread at the small rungs and those pairs are owed a structural digest.++ SCOPED TO THE SHARD THAT DECLARED IT, for the same reason `incomplete_cells` is read per path.+ One glob pools separate runs -- that is what `outputs/sbench_*` is for -- and `cell_id` and arm+ label repeat identically in every one of them, so keying on those alone let a+ `--windowed-arm treatment` declaration from one run become the fallback for an unmeasured pair+ in an ordinary run beside it. The ordinary run's pairs were then scored on the visible region+ and on behavioural invariants, the structural digest they were owed never ran, and a plain DOM+ regression in a payload that declared nothing exited 0 because of a flag passed to a different+ run. A payload recorded before `mounted_messages` existed carries no mount measurement at all,+ so every one of its pairs takes that fallback.+ """+ cells: dict[tuple[str, str], str] = {}+ arms: dict[tuple[str, str], str] = {}+ for path in paths:+ shard = path.parent.name+ for r in rows(path):+ kind = r.get("row_type")+ if kind == "gate":+ name = str(r.get("name") or "")+ if name.startswith(WINDOWED_GATE):+ arm = name[len(WINDOWED_GATE) :] or "?"+ arms[(shard, arm)] = (+ f"the run declared the {arm} arm windowed (gate row {name})"+ )+ elif kind == "cell":+ readiness = r.get("readiness")+ mode = readiness.get("mode") if isinstance(readiness, dict) else None+ if mode == MODE_WINDOWED:+ cid = str(r.get("cell_id") or "")+ cells[(shard, cid)] = f"cell {cid} was admitted by the WINDOWED readiness gate"+ return cells, arms+++def _mount_measured(parity: Optional[dict]) -> bool:+ """Did this capture actually MEASURE how much of the thread was mounted?++ `thread_total > 0` is part of it. A capture that reports 0 of 0 has not observed a thread at+ all -- on the real 100K film, 20 of the treatment arm's rows read 0 of 0 after `model_change`+ took the viewport to nothing -- and `windowed_mount` answers False for it, which would score a+ declared-windowed arm structurally on the strength of a capture that saw no messages.+ """+ if not isinstance(parity, dict) or not parity.get("parity_attempted"):+ return False+ mounted, total = parity.get("mounted_messages"), parity.get("thread_total")+ if not isinstance(mounted, int) or not isinstance(total, int):+ return False+ return total > 0+++def _cell_id_for(sides: dict, arm: str) -> str:+ """This pair's cell id ON `arm`, derived when that arm recorded no row.++ `make_cell_id` writes `r{rung}.{arm}.rep{n}`, so the counterpart of a row that IS present is+ the same id with the arm segment swapped. Without this an arm that never reached the film has+ no cell id to look up in the per-cell declarations, and the only declaration left is the+ run-wide one from `--windowed-arm`.+ """+ row = sides.get(arm)+ if isinstance(row, dict) and row.get("cell_id"):+ return str(row["cell_id"])+ for other in sides.values():+ parts = str(other.get("cell_id") or "").split(".")+ if len(parts) >= 3:+ parts[1] = arm+ return ".".join(parts)+ return ""+++def decide_modes(paths: list[Path]) -> dict[tuple, tuple[str, str]]:+ """{(shard, rung, rep, session, action): (mode, why)} -- how each pair is scored, and why.++ MEASURED FIRST, DECLARED ONLY AS A FALLBACK.++ measured windowed either arm's capture says it mounted fewer messages than the thread+ holds. This is the reading the tool has always used.+ measured full both arms measured their mount and neither is windowing, so the pair is+ owed the structural digest whatever the rest of the payload does.+ neither no usable mount measurement on this pair -- the slot was missed, or the+ parity probe failed, or the capture saw no thread at all -- so the run's+ own declaration decides it.++ THE FALLBACK IS THE POINT. A declared windowed run in which every capture failed used to scan+ clean, `--mode auto` picked the digest, every pair came out NOT_EXERCISED or NOT_COMPARABLE,+ and `report()` returned 0 because its no-result guard only covered NOT_APPLICABLE. An entirely+ unmeasured run reported a green structural result.+ """+ cells, arms = declared_windowed(paths)+ decided: dict[tuple, tuple[str, str]] = {}+ for key, sides in collect(paths)["pairs"].items():+ for _label, row in sorted(sides.items()):+ parity = row.get("parity")+ if P.windowed_mount(parity):+ decided[key] = (+ WINDOWED,+ f"{row.get('cell_id')} / {row.get('action')} mounted "+ f"{parity.get('mounted_messages')} of {parity.get('thread_total')} messages",+ )+ break+ if key in decided:+ continue+ if len(sides) == 2 and all(_mount_measured(r.get("parity")) for r in sides.values()):+ decided[key] = (STRUCTURAL, "")+ continue+ # EITHER EXPECTED ARM, INCLUDING ONE THAT HAS NO ROW AT ALL.+ #+ # The declaration fallback used to be read off the rows this pair actually has, which+ # covers a declared-windowed arm whose captures failed and misses the case one step worse:+ # the arm failed before it emitted an action row, so `sides` holds only the other side, the+ # loop never asks about the arm that is missing, and the pair is scored structurally. In a+ # mixed-rung payload the fully mounted pairs then supply `matched > 0`, the missing windowed+ # pair is filed as structurally NOT COMPARABLE, and the command exits 0 without ever running+ # a windowed report for the rung that has no verdict at all.+ #+ # AND ONLY THIS PAIR'S OWN SHARD DECLARES IT. See `declared_windowed`.+ why = ""+ shard = key[0]+ for label in ARMS:+ cid = _cell_id_for(sides, label)+ why = (cells.get((shard, cid)) if cid else "") or arms.get((shard, label)) or ""+ if why:+ break+ decided[key] = (+ (+ WINDOWED,+ f"DECLARED, not measured: {why}, and this pair carries no usable mount "+ "measurement on at least one arm",+ )+ if why+ else (STRUCTURAL, "")+ )+ return decided+++def any_windowed(paths: list[Path]) -> Optional[str]:+ """Did either arm of this payload mount a WINDOW of the thread rather than all of it?++ Measured from `mounted_messages` and `thread_total` where those exist, and falling back on the+ run's own declaration for pairs where they do not. Detection alone was not enough: it answers+ "no window here" identically for a payload that mounted everything and for one whose captures+ all failed, and the second of those is an unmeasured run being scored as a fully mounted one.+ """+ for _key, (mode, why) in sorted(decide_modes(paths).items()):+ if mode == WINDOWED:+ return why+ return None+++def behaviour_report(+ paths: list[Path],+ label: str,+ windowed: bool = True,+ select: Optional[set] = None,+) -> int:+ """The windowed arm's report: behavioural invariants instead of a structural digest.++ Printed with the reason it is being printed, every time. The one way this could mislead is by+ quietly replacing a strict check with a looser one, so the banner says outright which question+ is no longer being asked.++ `select` scores only those pair keys, which is how a payload's windowed pairs are reported here+ while its fully mounted ones go to the structural digest they are owed.+ """+ got = collect(paths, select)+ results = []+ for (shard, rung, rep, sid, action), sides in sorted(got["pairs"].items()):+ cell = f"{rung} {rep}"+ if "base" not in sides or "treatment" not in sides:+ results.append(+ (+ action,+ shard,+ cell,+ {+ "verdict": P.NOT_COMPARABLE,+ "reason": f"only the {next(iter(sides))} arm recorded this action",+ "checks": [],+ },+ )+ )+ continue+ why = _refused(sides)+ if why:+ results.append(+ (action, shard, cell, {"verdict": P.NOT_COMPARABLE, "reason": why, "checks": []})+ )+ continue+ results.append(+ (action, shard, cell, B.compare_behaviour(sides["base"], sides["treatment"]))+ )++ print(f"\n{label} (BEHAVIOURAL MODE)")+ print(f" CLAIM: {P.CLAIM_BEHAVIOURAL}.")+ print(f" POLICY: {P.POLICY_BY_MODE['behaviour']}.")+ # WHICH REASON, and only if it is true. Forced behavioural mode on a payload that mounts its+ # whole thread -- which is exactly how a NULL CONTROL is scored on the same scale as the+ # windowed arm it is the control for -- used to print "one arm of this payload mounts a window+ # of the thread" about a payload where neither arm does. A control that misdescribes itself in+ # its own heading is not a small thing when the heading is what gets read.+ if windowed:+ print(+ " One arm of this payload mounts a window of the thread, so the structural DOM digest"+ "\n is NOT APPLICABLE: it compares what is on screen, and this arm changes what is on"+ "\n screen by design. It would report a difference on every action and prove nothing."+ )+ else:+ print(+ " NEITHER arm of this payload mounts a window; behavioural mode was FORCED. The"+ "\n structural digest would have been applicable here and was not run, so nothing"+ "\n below says anything about whether the mounted messages render identically."+ )+ print(+ " What is scored is the scroll extent plus the behaviours a windowed mount breaks first.\n"+ " WHAT IS NOT BEING ASKED: whether the mounted messages render identically. An arm that\n"+ " passes everything below can still have changed how a message looks."+ )+ if not results:+ print(" NO ACTION DATA in this payload.")+ return 2++ broken, unchecked, idle, blind = [], [], [], []+ matched = 0+ for action, shard, cell, r in results:+ verdict = r["verdict"]+ if verdict == B.BROKEN:+ broken.append((action, shard, cell, r))+ elif verdict == P.MATCH:+ matched += 1+ elif verdict == P.NOT_EXERCISED:+ idle.append((action, shard, cell, r))+ elif verdict == P.NOT_COMPARABLE:+ blind.append((action, shard, cell, r))+ else:+ unchecked.append((action, shard, cell, r))++ print(f"\n {len(results)} action pairs across {len(paths)} shard(s)")+ print(f" invariants held: {matched}")+ print(f" INVARIANTS BROKEN: {len(broken)}")+ print(f" UNCHECKED: {len(unchecked)} (no invariant declared; not a pass)")+ print(f" NOT COMPARABLE: {len(blind)}")+ print(f" NOT EXERCISED: {len(idle)} (the action did not run; not coverage)")++ if broken:+ print("\n BEHAVIOURAL INVARIANTS BROKEN -- these are user-visible, not measurement noise:")+ for action, shard, cell, r in broken:+ print(f" {action:<26} {shard} {cell}: {r['reason']}")+ else:+ print("\n Every declared behavioural invariant held on both arms.")++ if unchecked:+ names = sorted({a for a, _s, _c, _v in unchecked})+ print(+ f"\n UNCHECKED -- {len(unchecked)} pair(s) over {len(names)} action(s) with no "+ f"declared invariant. These surfaces carry NO verdict on this arm:"+ )+ for name in names:+ print(f" {name}")+ if blind:+ print("\n NOT COMPARABLE:")+ for action, shard, cell, r in blind[:8]:+ print(f" {action:<26} {shard} {cell}: {r['reason']}")+ if idle:+ names = sorted({a for a, _s, _c, _v in idle})+ print(f"\n NOT EXERCISED: {', '.join(names)}")++ if broken:+ return 1+ if matched == 0:+ # NOTHING WAS VALIDATED, which is not the same as nothing being wrong. With every pair+ # unchecked, not comparable or never exercised, `broken` is empty and the block above has+ # just printed "Every declared behavioural invariant held on both arms" -- a sentence that+ # is technically true of an empty set and reads as a pass. This is the same false green+ # the digest path returns 2 for, and it is the more dangerous of the two here, because+ # behavioural mode is what REPLACES the digest on a windowed arm: if it silently validates+ # nothing then a windowed arm has no UI verdict at all while appearing to have passed one.+ print(+ "\n NOTHING WAS COMPARED. Not one behavioural invariant was evaluated on any pair, "+ "so this run carries no UI verdict -- neither a pass nor a failure. Treat it as an "+ "absent result and find out why the actions did not run."+ )+ return 2+ return 0+++def visible_unstable_set(null_paths: list[Path] | None) -> frozenset[tuple[str, str]]:+ """(rung, action) pairs whose VISIBLE REGION differs between two runs of the SAME build.++ A floor, measured rather than assumed, and it has to be measured separately from the digest's+ because the two ask different questions. Observed on a 100K base-vs-base control: 13 of 64+ action pairs differed inside the viewport, against 5 for the virtualization arm the control was+ run for. Without this the arm under test scores WORSE than an identical pair of builds and the+ verdict is not merely weak, it is backwards.++ The mechanism is the same one the digest already normalises around and does not fully catch:+ the rows differ at identical character counts (`7609->7609c`), which is a volatile attribute+ rather than changed content.++ KEYED BY RUNG AS WELL AS BY ACTION, AND EARNED AT THAT KEY. A bare action name was both too+ broad and too cheap: ONE differing null-control pair silenced that action for every cell and+ every rung. A payload legitimately holds several rungs -- the windowed readiness gate is+ written to permit an arm to mount everything at 1K and a window at 100K -- so transient visible+ noise on the null's 100K `model_change` pair suppressed a reproducible visible regression on+ the target's 1K `model_change` pair, and `visible_report` exited 0 over it.++ The rung is where the instability lives. How much thread there is, and where the film's slots+ land against it, is what makes an action differ against itself; that is the same argument+ `tier_of` already makes about the film's spacing, applied one level down. `P.derive_unstable`+ then supplies the observation count, so an entry needs more than one reading at the key it will+ be applied at.++ WHERE THIS DIVERGES FROM THE STRUCTURAL FLOOR, deliberately. `unstable_set` keys on the action+ alone -- but it is UNIONED with the declared `P.UNSTABLE_ACTIONS`, where every entry carries a+ written mechanism, and its derived half already refuses to call anything unstable on a single+ reading. The visible floor has no declared set behind it, so being derived is the only claim it+ can make, and a claim with no mechanism attached has to be earned at the scope it silences.++ None of this reaches the SEVERE verdicts: `visible_report` never routes an arm whose viewport+ ended empty into the floor, whatever the floor is keyed by.+ """+ if not null_paths:+ return frozenset()+ # AND ONLY FROM CELLS THAT FINISHED, which is the same admission rule `unstable_set` applies+ # to the structural floor and `audit_null` to the audit. `collect` states the asymmetry: action+ # rows are written as the film runs and the `cell` row when it ends, so a null-control cell+ # that died mid-film leaves a complete-looking set of captures that nothing owns, and they pair+ # and compare like real ones. Read raw here, one DIFFERING unfinished observation plus one+ # matching completed one is exactly `min_observations`, `derive_unstable` calls that (rung,+ # action) unstable, and `visible_report` then files a real visible difference at the same key+ # under "differ against an identical build" and exits 0. The floor is the one place an+ # under-observed action must read as undetermined rather than as an excuse.+ results, _got = compare_all_with(+ null_paths, P.compare_visible, "visible", require_complete = True+ )+ by_rung: dict[str, list[tuple[str, dict]]] = collections.defaultdict(list)+ for action, _shard, cell, r in results:+ # A pair whose action never ran on both arms is not an observation of anything, in either+ # direction. `derive_unstable` refuses to count a verdict it cannot read; this refuses to+ # hand it one it should not read.+ if r.get("_ran"):+ by_rung[rung_of_cell(cell)].append((action, r))+ out: set[tuple[str, str]] = set()+ for rung, pairs in by_rung.items():+ for action, row in P.derive_unstable(pairs).items():+ if row["unstable"]:+ out.add((rung, action))+ return frozenset(out)+++def visible_report(+ paths: list[Path],+ label: str,+ unstable: frozenset[tuple[str, str]] = frozenset(),+ select: Optional[set] = None,+) -> int:+ """VISIBLE-REGION PARITY. The verdict the off-screen exemption asks for.++ Policy: all changes preserve UI and UX idempotency, except that a difference may be accepted+ deliberately when performance improves dramatically, and a difference that exists only OFF+ SCREEN is fine by definition. The structural digest cannot express the second exemption -- it+ digests the thread on screen and off, so it fails every deferred-off-screen technique by+ construction -- so this scores the claim the policy actually cares about.++ `select` scores only those pair keys; see `decide_modes`.+ """+ results, _got = compare_all_with(paths, P.compare_visible, "visible", select)++ print(f"\n{label} (VISIBLE-REGION MODE)")+ print(f" CLAIM: {P.CLAIM_VISIBLE}.")+ print(f" POLICY: {P.POLICY_BY_MODE['visible']}.")+ print(+ " Off-screen differences are EXEMPT by policy and are not reported below. A message that\n"+ " was visible for any part of the action is compared, in full, even if only partly on\n"+ " screen. Messages are keyed by THREAD POSITION, so a windowed arm and a fully mounted\n"+ " one are comparable."+ )+ if not results:+ print(" NO ACTION DATA in this payload.")+ return 2++ differing, unstable_bad, blind, idle, matched = [], [], [], [], 0+ # THE RESIDUE, PRINTED. A message that was on screen during the action and had been unmounted+ # again by the time the capture ran cannot be digested, and `compare_visible` refuses the pair+ # for it. That refusal used to be invisible: the pair returned MATCH with the ordinals tucked+ # into `not_digested` and nothing here read the key, so a rendering difference in the missing+ # message left no trace anywhere in the output. It is collected across every verdict, because a+ # DIFFER pair with a residue is also a pair whose report is incomplete.+ residue = []+ for action, shard, cell, r in results:+ if r.get("not_digested"):+ residue.append((action, shard, cell, r))+ if not r.get("_ran"):+ idle.append((action, shard, cell, r))+ elif r["verdict"] == P.NOT_COMPARABLE:+ blind.append((action, shard, cell, r))+ elif r["verdict"] == P.DIFFER:+ # A SEVERE difference is never routed into the noise floor. See compare_visible: an+ # action can be in the derived unstable set for an unrelated attribute and still be+ # the action on which one arm lost the whole thread.+ #+ # AT THIS PAIR'S OWN RUNG. An action that differs against an identical build at 100K+ # says nothing about the same action at 1K, where the thread is a fraction of the size+ # and the film's slots land somewhere else entirely.+ noise = (rung_of_cell(cell), action) in unstable and not r.get("severe")+ (unstable_bad if noise else differing).append((action, shard, cell, r))+ else:+ matched += 1++ print(f"\n {len(results)} action pairs across {len(paths)} shard(s)")+ print(f" visible region matched: {matched}")+ print(f" VISIBLE DIFFERENCES: {len(differing)}")+ print(+ f" unstable actions differing: {len(unstable_bad)} (differ against an identical build; "+ "not a verdict)"+ )+ print(f" NOT COMPARABLE: {len(blind)} (never observed; not a pass)")+ print(f" NOT EXERCISED: {len(idle)} (the action did not run; not coverage)")+ print(+ f" visible but NOT DIGESTED: {len(residue)} (unmounted before the capture; no verdict "+ "covers them)"+ )++ if differing:+ print(+ "\n DIFFERENCES INSIDE THE VIEWPORT -- the off-screen exemption does not cover these:"+ )+ for action, shard, cell, r in differing:+ print(f" {action:<26} {shard} {cell}: {r['reason']}")+ for m in r.get("moved", [])[:4]:+ print(f" {m}")+ elif matched:+ print(+ "\n Every message that reached the viewport was identical on both arms.\n"+ " Differences outside the viewport are not reported here and are exempt by policy;\n"+ " run --mode digest for the thread-structure comparison, on screen and off, instead."+ )+ if blind:+ print("\n NOT COMPARABLE -- these carry no verdict in either direction:")+ for action, shard, cell, r in blind[:8]:+ print(f" {action:<26} {shard} {cell}: {r['reason']}")+ if residue:+ print(+ "\n VISIBLE BUT NOT DIGESTED -- these messages were on screen during the action and "+ "had\n been unmounted again before the capture, so nothing below covers them:"+ )+ for action, shard, cell, r in residue[:8]:+ print(f" {action:<26} {shard} {cell}: ordinals {r.get('not_digested')[:8]}")+ if unstable_bad:+ names = sorted({a for a, _s, _c, _v in unstable_bad})+ print(+ f"\n (reported, not counted) {len(unstable_bad)} pair(s) over {len(names)} action(s) "+ f"whose visible region differs between two runs of the SAME build: {', '.join(names)}"+ )+ if idle:+ names = sorted({a for a, _s, _c, _v in idle})+ print(f"\n NOT EXERCISED: {', '.join(names)}")+ if not unstable:+ print(+ "\n NO FLOOR WAS MEASURED. Pass --null OUTDIR of a base-vs-base run: an identical\n"+ " pair of builds has been observed differing on 13 of 64 pairs inside the viewport,\n"+ " so an unfloored count here can rank a real arm below two copies of the same build."+ )+ else:+ # WHICH RUNG EACH FLOOR ENTRY WAS MEASURED AT, printed, because it is also the only rung it+ # silences anything at. A floor that reads as a list of action names would look like it+ # covers the whole payload.+ keys = sorted(unstable)+ shown = ", ".join(f"{rung or '?'} {action}" for rung, action in keys[:12])+ print(+ f"\n FLOOR: {len(keys)} (rung, action) pair(s) measured differing against an "+ f"identical build,\n and silenced ONLY at the rung they were measured at: {shown}"+ + (f", and {len(keys) - 12} more" if len(keys) > 12 else "")+ )++ if differing:+ return 1+ if matched == 0:+ # The same false green every other mode here has already been fixed for: nothing compared+ # is not the same as nothing wrong, and it must not exit 0.+ print(+ "\n NOTHING WAS COMPARED. Not one action pair yielded a visible-region verdict, so\n"+ " this run carries no UI verdict at all -- neither a pass nor a failure."+ )+ return 2+ return 0+++def compare_all_with(+ paths: list[Path],+ compare,+ key: str,+ select: Optional[set] = None,+ require_complete: bool = False,+) -> tuple[list[tuple], dict]:+ """[(action, shard, cell, result)] using `compare` over payload sub-object `key`.++ `require_complete` drops the action rows of a cell that never wrote its terminal `cell` row;+ see `collect`, which states why that is right on a null control and wrong on a result.+ """+ got = collect(paths, select, require_complete = require_complete)+ results = []+ for (shard, rung, rep, sid, action), sides in sorted(got["pairs"].items()):+ cell = f"{rung} {rep}"+ if "base" not in sides or "treatment" not in sides:+ results.append(+ (+ action,+ shard,+ cell,+ {+ "verdict": P.NOT_COMPARABLE,+ "moved": [],+ "_ran": True,+ "reason": f"only the {next(iter(sides))} arm recorded this action",+ },+ )+ )+ continue+ why = _refused(sides)+ if why:+ results.append(+ (+ action,+ shard,+ cell,+ {"verdict": P.NOT_COMPARABLE, "moved": [], "_ran": True, "reason": why},+ )+ )+ continue+ ran = bool(sides["base"].get("ran")) and bool(sides["treatment"].get("ran"))+ out = compare(sides["base"].get(key), sides["treatment"].get(key))+ out["_ran"] = ran+ results.append((action, shard, cell, out))+ return results, got+++def compare_all(+ paths: list[Path],+ select: Optional[set] = None,+ require_complete: bool = False,+) -> tuple[list[tuple], dict]:"""[(action, shard, cell, compare-result)] over every base/treatment pair found.`cell` is `rung rep`, so the two rungs of one repetition stay two observations.++ `select` scores only those pair keys; see `decide_modes`."""- got = collect(paths, require_complete = require_complete)+ got = collect(paths, select, require_complete = require_complete)results = []for (shard, rung, rep, sid, action), sides in sorted(got["pairs"].items()):cell = f"{rung} {rep}"@@ -234,6 +971,23 @@ def compare_all(paths: list[Path], require_complete: bool = False) -> tuple[list))continue+ why = _refused(sides)+ if why:+ results.append(+ (+ action,+ shard,+ cell,+ {+ "verdict": P.NOT_COMPARABLE,+ "moved": [],+ "reason": why,+ "style_verdict": P.NOT_COMPARABLE,+ "style_reason": "",+ },+ )+ )+ continueresults.append((action, shard, cell, P.compare_rows(sides["base"], sides["treatment"])))return results, got@@ -688,10 +1442,20 @@ def report(paths: list[Path],label: str,unstable: frozenset,+ select: Optional[set] = None,min_reps: int = 1,min_compared: int = 0,) -> int:- results, got = compare_all(paths)+ """THREAD-STRUCTURE PARITY. `select` scores only those pair keys; see `decide_modes`.++ `unstable` holds both kinds of entry `is_unstable` reads: a bare action name, which is a+ declared entry and holds at every rung, and a `(rung, action)` tuple, which was measured and+ holds only at the rung it was measured at.++ `min_reps` is the corroboration threshold and `min_compared` the coverage floor; see+ `corroborated` and the coverage check below.+ """+ results, got = compare_all(paths, select)if not results:# An empty result is reported as an empty result. "No mismatches found" when nothing was# ever compared is the exact shape of a check that silently does nothing.@@ -703,6 +1467,7 @@ def report(return 2stable_bad, unstable_bad, blind, style_bad, idle = [], [], [], [], []+ inapplicable: list[tuple] = []one_sided, one_sided_unstable = [], []expect_bad = []matched = 0@@ -723,6 +1488,18 @@ def report(expect_bad.append((action, shard, cell, [r.get("expect_reason", "")], r["expect_regressed"]))+ if r["verdict"] == P.NOT_APPLICABLE:+ # NEITHER A PASS NOR A FAIL. The digest is the wrong question for this pair; see+ # analysis/parity.applicability. It is bucketed separately so it cannot be summed into+ # either column, and `--mode behaviour` is what answers it instead.+ #+ # BELOW the assertion collection above, and that ordering is the merge's one real+ # decision. This branch `continue`s, so putting it first would drop a failed assertion+ # whenever the pair also happened to be a windowed mount -- exactly what the comment+ # above means by collecting outside the verdict branches. A windowed arm that stops+ # stopping generation is the case that would have gone silent.+ inapplicable.append((action, shard, cell, [r.get("reason", "")]))+ continueif r["verdict"] == P.NOT_EXERCISED:# Same, for which arm stayed live: `one_sided` names the arm that DID run.entry = (action, shard, cell, [r.get("reason", "")], r.get("one_sided") or None)@@ -770,7 +1547,14 @@ def report(one_sided, one_sided_weak = corroborated(one_sided, min_reps)expect_bad, expect_weak = corroborated(expect_bad, min_reps)- print(f"\n{label}")+ print(f"\n{label} (STRUCTURAL MODE)")+ print(f" CLAIM: {P.CLAIM_STRUCTURAL}.")+ print(f" POLICY: {P.POLICY_BY_MODE['structural']}.")+ print(+ " Under the current policy an OFF-SCREEN-ONLY difference is exempt, and this mode cannot\n"+ " tell an off-screen difference from an on-screen one. Use --mode visible for a payload\n"+ " that defers off-screen work deliberately."+ )print(f" {len(results)} action pairs across {len(paths)} shard(s)")if got.get("incomplete"):print(@@ -803,6 +1587,13 @@ def report(print(f" unstable actions differing: {len(unstable_bad)} (expected to vary; not a verdict)")print(f" NOT COMPARABLE: {len(blind)} (never measured; not a pass)")print(f" NOT EXERCISED: {len(idle)} (the action did not run; not coverage)")+ if inapplicable:+ print(+ f" NOT APPLICABLE: {len(inapplicable)} (a windowed mount; the digest "+ f"cannot answer this)"+ )+ print(f" {inapplicable[0][3][0]}")+ print(" Re-run with --mode behaviour to score these on behavioural invariants.")print(f" style probe differing: {len(style_bad)} (advisory: display/visibility/"f"pointer-events)"@@ -864,12 +1655,45 @@ def report(for action, shard, cell, why, *_dir in one_sided_unstable[:8]:print(f" {action:<26} {shard} {cell}: {why[0]}")+ # A DEMOTED DIFFERENCE IS STILL A COMPARISON. `corroborated` moves a difference seen in fewer+ # than `min_reps` repetitions out of `stable_bad`, and that must not make the pair look like+ # one that never yielded a verdict: the digest was taken on both arms, it differed, and the+ # corroboration bar is the only reason it is not counted as a regression. Reading `matched`+ # alone, a payload whose every difference was uncorroborated exited 2 "NOTHING WAS COMPARED"+ # over a run that compared everything it had -- which is the opposite of the false green this+ # guard exists to catch, and would make `--min-reps 2` fail runs it was meant to quieten.+ decided = matched + len(uncorroborated) + len(one_sided_weak)if stable_bad:print("\n UI PARITY DIFFERENCES ON STABLE ACTIONS -- these need explaining:")for action, shard, cell, moved in stable_bad:print(f" {action:<26} {shard} {cell}: {', '.join(moved[:4])}")+ elif decided == 0:+ # NOT A PASS, and it must not print like one. Not one pair produced a digest verdict, so+ # "no stable action rendered differently" would be true, reassuring and about nothing --+ # the exact shape of a check that silently does nothing, which is what the NOT COMPARABLE+ # bucket exists to prevent elsewhere in this file.+ #+ # THE GUARD USED TO REQUIRE `inapplicable`, so it only caught the windowed-mount route to+ # an empty comparison. A run whose parity probes all failed, or whose slots were all+ # missed, produced nothing but NOT COMPARABLE and NOT EXERCISED rows, no inapplicable ones,+ # and exited 0 under a heading that reads as a clean structural pass.+ print(+ f"\n NOTHING WAS COMPARED. Not one of the {len(results)} pair(s) here yielded a "+ f"structural verdict ({len(inapplicable)} windowed, {len(blind)} not comparable, "+ f"{len(idle)} never exercised, {len(unstable_bad)} differing on actions that differ "+ "against themselves). This is not a pass."+ )+ if inapplicable:+ print(" Re-run with --mode behaviour to score the windowed pairs on invariants.")else:- print("\n No stable action rendered differently between the two arms.")+ print(+ "\n No stable action rendered a different THREAD STRUCTURE between the two arms.\n"+ " Read that literally. This digest walks the thread and nothing else: it is\n"+ " sidebar-blind and layout-blind by construction, and it never reads geometry or\n"+ " CSS custom properties. A change confined to the sidebar, or one that moves things\n"+ " without restructuring the thread, passes here while being invisible to it.\n"+ " This is not a statement that the UI is unchanged."+ )if uncorroborated:# Printed in full. A build renders the same way every time, so one repetition out of two@@ -908,7 +1732,23 @@ def report(print("\n (reported, not counted) actions that vary between runs of any build:")for action, shard, cell, moved in unstable_bad[:8]:print(f" {action:<26} {shard} {cell}: {', '.join(moved[:3])}")- return 1 if (stable_bad or one_sided or expect_bad) else 0+ # A one-sided action is a failure on the same footing as a differing digest: the two builds+ # behaved differently and the difference happens to leave no digest to compare. `expect_bad`+ # joins them for the reason given where it is collected: an assertion that failed on one arm+ # only is the two builds behaving differently, and it is the one shape a digest cannot show.+ if stable_bad or one_sided or expect_bad:+ return 1+ # 2, the same code the empty-payload path uses, and for the same reason: the tool was asked a+ # question it could not answer. Exiting 0 here would let CI go green on a run where the parity+ # check was structurally incapable of firing -- whether because every pair was a windowed mount+ # or because every capture failed. `decided`, not `matched`, for the reason given above it.+ #+ # AFTER the failure return, not before it: a run can find a real regression while deciding+ # nothing -- `expect_bad` is collected ahead of the verdict branches and survives a pair that+ # `continue`s -- and "it failed" is the more specific answer than "it could not tell".+ if decided == 0:+ return 2+ return 0def tier_of(paths: list[Path]) -> set[str]:@@ -1057,6 +1897,22 @@ def main(argv: list[str] | None = None) -> int:default = [],help = "a base-vs-base run to derive the unstable set from",)+ ap.add_argument(+ "--mode",+ # `structural` and `behavior` are ALIASES, not extra modes. The report header prints+ # "(STRUCTURAL MODE)" and the pull request template asks for "the structural digest", so+ # a reader who follows either and types `--mode structural` should not be told it is not+ # a choice. Same for the American spelling of behaviour.+ choices = ("auto", "digest", "structural", "visible", "behaviour", "behavior"),+ default = "auto",+ help = (+ "auto (default) decides per ACTION PAIR from the payload: a fully mounted pair is "+ "scored structurally, a windowed pair is scored on the VISIBLE REGION and then on "+ "behavioural invariants, and one payload can contain both; digest forces the "+ "thread-structure comparison on every pair; visible forces the visible-region one; "+ "behaviour forces the behavioural one. `structural` is an alias for `digest` and `behavior` for `behaviour`"+ ),+ )ap.add_argument("--min-reps",type = int,@@ -1105,7 +1961,166 @@ def main(argv: list[str] | None = None) -> int:"action the fixture genuinely cannot perform, and say which: every name here is a hole",)args = ap.parse_args(argv)+ args.mode = {"structural": "digest", "behavior": "behaviour"}.get(args.mode, args.mode)++ # THE MODE DECISION FIRST, before the unstable set is even derived. Deriving an unstable set+ # from a null control and then not using it because the payload is windowed would print a page+ # of scoring apparatus that has no bearing on the report underneath it.+ #+ # PER ACTION PAIR, and per payload and per invocation were both too coarse:+ #+ # per invocation `ui_parity normal_run windowed_run` scored the NORMAL run behaviourally+ # too, so an ordinary DOM regression in a fully mounted arm went unreported+ # because an unrelated payload on the same command line was windowed.+ # per payload one payload holds several rungs, and the readiness gate deliberately+ # permits an arm to mount everything at 1K and a window at 100K. One windowed+ # large-rung capture then suppressed the structural digest on every fully+ # mounted pair beside it, at the rungs where that digest is exactly the right+ # question.+ #+ # `--mode visible|behaviour|digest` still forces every pair, because that is what forcing means.+ plan: list[dict] = []+ for pattern in args.payloads:+ paths = shards_of(pattern)+ if not paths:+ # Kept with no pairs: the structural loop below is what reports a pattern that matched+ # no payload, and it exits 2 for it.+ plan.append({"pattern": pattern, "paths": [], "windowed": set(), "structural": None})+ continue+ if args.mode == "digest":+ plan.append({"pattern": pattern, "paths": paths, "windowed": set(), "structural": None})+ continue+ if args.mode in ("visible", "behaviour"):+ plan.append(+ {+ "pattern": pattern,+ "paths": paths,+ "windowed": set(collect(paths)["pairs"]),+ "structural": set(),+ "why": f"forced by --mode {args.mode}",+ "forced": True,+ }+ )+ continue+ decided = decide_modes(paths)+ windowed = {key for key, (mode, _why) in decided.items() if mode == WINDOWED}+ plan.append(+ {+ "pattern": pattern,+ "paths": paths,+ "windowed": windowed,+ # None, not an empty set, when the payload holds no action pairs at all: `report`+ # is what says NO PARITY DATA and exits 2, and it has to be reached to say it.+ "structural": (set(decided) - windowed) if decided else None,+ "why": next((w for _k, (m, w) in sorted(decided.items()) if m == WINDOWED), ""),+ }+ )+ worst = 0+ scored_windowed = 0+ vis_unstable: Optional[frozenset[tuple[str, str]]] = None+ vis_null_tiers: set[str] = set()+ vis_null_corpora: set[str] = set()+ for entry in plan:+ win, struct = entry["windowed"], entry["structural"] or set()+ if not win and not entry.get("forced"):+ continue+ pattern, paths = entry["pattern"], entry["paths"]+ print(f"\nWINDOWED PAIRS in {pattern}: {entry.get('why') or 'none measured or declared'}")+ if entry.get("forced"):+ print(+ f" FORCED: all {len(win)} pair(s) are scored by --mode {args.mode}, whatever the "+ "payload says about itself."+ )+ else:+ print(+ f" MODE DECIDED PER ACTION PAIR: {len(win)} of {len(win) + len(struct)} pair(s) "+ f"are scored on the visible region and on behavioural invariants here; "+ f"{len(struct)} fully mounted pair(s) are scored structurally further down."+ )+ for key in sorted(win)[:8]:+ # shard, rung, rep and the action. The session term of the key is left out of+ # the line: it is part of a pair's identity, not part of naming it to a reader.+ print(f" windowed: {key[0]} {key[1]} {key[2]} {key[4]}")+ if len(win) > 8:+ print(f" ... and {len(win) - 8} more windowed pair(s)")+ scored_windowed += len(win)+ # BOTH, and in this order. Visible-region parity is the verdict the off-screen exemption+ # asks for and it is the one that can FAIL a windowed arm for something a user would see.+ # The behavioural invariants are the complement: they catch what a viewport comparison+ # cannot, such as a clipboard that no longer carries the thread. Neither subsumes the other,+ # so a windowed pair gets both and the run fails if either does.+ if args.mode in ("auto", "visible"):+ if vis_unstable is None:+ # The floor, derived from the null control the caller passed. Without it an+ # identical pair of builds outscores the arm under test. Derived once: it is a+ # property of the null control, not of the payload being scored against it.+ vis_null: list[Path] = []+ for pat in args.null:+ vis_null.extend(shards_of(pat))+ vis_unstable = visible_unstable_set(vis_null)+ vis_null_tiers = one_tier(vis_null, "null control")+ vis_null_corpora = one_corpus(vis_null, "null control")+ # A FLOOR FROM ANOTHER FILM IS NOT THIS PAYLOAD'S FLOOR, ON EITHER AXIS. `tier_of`+ # states the mechanism for the film: the slot spacing decides which actions land+ # inside a live stream and so differ against themselves, and `--tier fast` then+ # `--tier standard` is the documented way to work, which is exactly how a stale fast+ # null control ends up on the command line of a standard run. `one_corpus` states the+ # same mechanism one level down for the thread the film drove, and that axis is the+ # quieter of the two: a corpus revision lands, the payload is re-recorded against it,+ # and an older null control is still sitting in the directory the workflow globs.+ # `one_tier` and `one_corpus` above refuse a null control that is internally mixed;+ # `cross_side_mismatch` refuses one that is internally consistent but belongs to a+ # different film or a different thread. The structural section further down says both+ # out loud, and an ALL-WINDOWED payload -- which is every payload under+ # `--mode visible` -- returns before it ever reaches that warning, so a floor measured+ # on the wrong film or the wrong corpus silenced a real visible difference and the+ # command exited 0 without a word about it. Refused rather than applied: an unfloored+ # report says what it is missing, a wrongly floored one does not.+ floor = vis_unstable+ mismatch = cross_side_mismatch(+ one_tier(paths, "payload"),+ vis_null_tiers,+ one_corpus(paths, "payload"),+ vis_null_corpora,+ )+ if floor and mismatch:+ print(+ f"\n FLOOR REFUSED: {mismatch} It is NOT applied, and the visible differences "+ f"below are unfloored: record a null control alongside this payload before "+ f"reading them as findings."+ )+ floor = frozenset()+ worst = max(+ worst,+ visible_report(paths, f"UI PARITY: {pattern}", floor, select = win),+ )+ if args.mode in ("auto", "behaviour"):+ worst = max(+ worst,+ behaviour_report(+ paths,+ f"UI PARITY: {pattern}",+ windowed = args.mode == "auto" or any_windowed(paths) is not None,+ select = win,+ ),+ )++ # AHEAD OF THE STRUCTURAL EARLY RETURN, because this mode does not read the plan at all.+ #+ # It takes its shards from `args.payloads` directly, audits each one AS a null control, resets+ # `worst` and returns unconditionally -- so it shares nothing with the windowed/structural+ # split it used to sit under. Below the return it was simply unreachable whenever `remaining`+ # came out empty, and that is not an exotic payload: `--mode visible` and `--mode behaviour`+ # both hard-set `structural` to an empty set for EVERY pattern, so `--audit-null` with either+ # of them could never run the audit at all, and auto mode joined them the moment every pair+ # classified as windowed. The command then exited 0 out of the ordinary visible report, having+ # silently skipped the audit the caller explicitly asked for and the `--compared-in`+ # enforcement that goes with it -- an option whose whole promise is to FAIL unless the null+ # decided the actions the result needs an excuse for.+ #+ # Moved here rather than duplicated above the return: one call site, and the auto-mode path+ # that already worked reaches it after exactly the same windowed reports as before.if args.audit_null:allow = frozenset(a.strip() for a in args.allow_undecided.split(",") if a.strip())scope = None@@ -1138,6 +2153,16 @@ def main(argv: list[str] | None = None) -> int:worst = max(worst, rc)return worst+ remaining = [e for e in plan if e["structural"] is None or e["structural"]]+ if not remaining:+ return worst+ if scored_windowed:+ # The rest still get the digest they were owed, in the same run.+ print(+ f"\n {len(remaining)} payload(s) still hold fully mounted pairs, which are scored "+ "structurally below and not behaviourally."+ )+null_paths: list[Path] = []for pattern in args.null:null_paths.extend(shards_of(pattern))@@ -1160,14 +2185,22 @@ def main(argv: list[str] | None = None) -> int:)print(" pass --null OUTDIR of a base-vs-base run to derive it instead.")- worst = 0- for pattern in args.payloads:- paths = shards_of(pattern)+ # `null_tiers` is the set `one_tier` already refused a mixed null control for, above. NOT+ # reassigned from `tier_of` here: that would be the same set without the refusal in front of it,+ # and `worst` is NOT reset either -- the windowed reports above have already run and a+ # behavioural or visible failure there may not be dropped by the structural pass below.+ scored_structural = 0+ for entry in remaining:+ pattern, paths, select = entry["pattern"], entry["paths"], entry["structural"]if not paths:print(f"\nno payload found for {pattern}")worst = max(worst, 2)continuetiers = one_tier(paths, "payload")+ # REFUSED, NOT WARNED. A tier or corpus the null control was not recorded against makes+ # its unstable set inapplicable to this payload, and a warning printed above a verdict is+ # read as a verdict. `cross_side_mismatch` covers the tier this used to warn about and the+ # corpus it did not check at all.corpora = one_corpus(paths, "payload")mismatch = cross_side_mismatch(tiers, null_tiers, corpora, null_corpora)if mismatch:@@ -1190,9 +2223,33 @@ def main(argv: list[str] | None = None) -> int:f"same DOM, so the null's race did not reproduce here: "f"{', '.join(unstable_label(e) for e in dropped)}")+ label = f"UI PARITY: {pattern}"+ if select is not None and entry["windowed"]:+ # WHICH PAIRS THESE ARE, in the heading. A structural section that silently covered+ # part of a payload would read as a verdict on all of it.+ label += (+ f" ({len(select)} fully mounted pair(s) of "+ f"{len(select) + len(entry['windowed'])})"+ )+ scored_structural += len(select) if select is not None else 0+ # BOTH SIDES OF THE MERGE, and the argument list is why this one had to be read rather+ # than chosen. `select` is the FOURTH positional here; the incoming call omitted it,+ # because on that branch this function had no windowed split to select from. Taken as+ # written it would have bound `args.min_reps` to `select` and `args.min_compared` to+ # `min_reps`, leaving the coverage floor at its default of 0 -- a silently disabled guard+ # and a structural pass scoring against an integer, with nothing failing to say so.worst = max(worst,- report(paths, f"UI PARITY: {pattern}", effective, args.min_reps, args.min_compared),+ report(paths, label, effective, select, args.min_reps, args.min_compared),+ )+ # COMBINED, and the worst outcome wins. A behavioural failure on one payload is not cancelled+ # by a structural pass on another, and a structural failure at the fully mounted rungs is not+ # cancelled by the windowed rungs passing their own two modes.+ if scored_windowed and scored_structural:+ print(+ f"\nCOMBINED EXIT STATUS {worst}: {scored_windowed} pair(s) scored on the visible "+ f"region and behavioural invariants, {scored_structural} scored structurally. Any "+ "mode's failure fails the run.")return worst