Skip to content

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

studiobench: a real-path performance benchmark and A/B simulator for Studio (#9296)

Daniel Han06e94e90ae8f
diff --git a/.github/workflows/studiobench-ci.yml b/.github/workflows/studiobench-ci.yml
new file mode 100644
index 00000000000..82c0978ec93
--- /dev/null
+++ b/.github/workflows/studiobench-ci.yml
@@ -0,0 +1,315 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+# Keep `studiobench` working, so that the day someone needs to measure a Studio
+# performance regression the tool is not itself the thing that needs fixing.
+#
+# WHAT THIS WORKFLOW DELIBERATELY DOES NOT DO: gate on a timing. A shared
+# two-core GitHub runner cannot resolve the effects studiobench measures. The
+# detection floors this tool derives on a quiet 100-core box are already wider
+# than most of the real effects found in a 40-PR audit, and a floor measured
+# under one contention level does not transfer to another. A workflow that
+# asserted "the message menu opens in under N ms" would be red on a noisy
+# runner and green on a quiet one, everyone would learn to re-run it, and the
+# signal would be worth less than nothing.
+#
+# So this gates on STRUCTURE, which is stable everywhere:
+#
+# selftests the package's own 338 tests, ruff, --doctor, and the single-file
+# zipapp build that external testers actually download
+# liveness a real session at the smallest rung, asserting that every
+# scheduled action RAN
+#
+# The second is the one that matters. Three separate times, in three separate
+# subsystems, this harness produced a confident "no effect" from code that could
+# never fire: four scene actions that recorded NOT RUN on 312 of 312 attempts
+# because their slots opened while a follow-up turn was still streaming; a
+# surface crawler that would have digested the same mounted root 53 times; an
+# overlay walk that could not fire at all. Every one of them exited 0. A gate on
+# the exit code catches none of them, and `--assert-liveness` catches all three
+# shapes.
+
+name: studiobench CI
+
+on:
+ pull_request:
+ paths:
+ - 'tests/studio/studiobench/**'
+ - '.github/workflows/studiobench-ci.yml'
+ # The harness drives the shipped frontend through the real backend, so a
+ # change to either can break it without touching a file under tests/.
+ - 'studio/frontend/**'
+ - 'studio/backend/**'
+ # The liveness job installs Unsloth to get a Studio to drive.
+ - 'install.sh'
+ - 'pyproject.toml'
+ - '.github/actions/install-unsloth-local/action.yml'
+ - '.github/scripts/boot-studio-api-only.sh'
+ - '.github/scripts/wait-for-health.sh'
+ # The Chromium install step shells out to this, so an edit to it changes what
+ # this workflow actually runs.
+ - '.github/scripts/retry-with-apt-lock.sh'
+ push:
+ branches: [main]
+ workflow_dispatch:
+
+concurrency:
+ # Unique per commit on main, so a merge burst cannot cancel a pending run
+ # before it starts. Matches studio-ui-smoke.yml, for the reasons documented there.
+ group: ${{ github.workflow }}-${{ github.ref }}-${{ github.ref == 'refs/heads/main' && github.sha || '' }}
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
+
+permissions:
+ contents: read
+
+jobs:
+ selftests:
+ name: Selftests, lint and the single-file build
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: '3.12'
+
+ # No browser engine here, on purpose. This job exists to be the fast one:
+ # it must stay runnable on a machine with no Chromium, because that is
+ # also the machine an external tester first runs `--doctor` on.
+ - name: Install the test dependencies only
+ run: pip install pytest ruff 'playwright<2' psutil
+
+ - name: Selftests
+ run: python -m pytest tests/studio/studiobench -q
+
+ - name: Lint
+ run: python -m ruff check tests/studio/studiobench
+
+ # --doctor is the first command in the README and the one an external
+ # tester runs before anything works. Every heavy import in the package is
+ # lazy precisely so this survives a bare machine; if that lazy-import
+ # discipline ever breaks, it breaks here rather than in someone's issue.
+ - name: Doctor reports rather than crashes
+ run: python -m tests.studio.studiobench --doctor
+
+ - name: The zipapp builds and the built artifact runs
+ run: |
+ python -m tests.studio.studiobench.build
+ test -f dist/studiobench.pyz
+ python dist/studiobench.pyz --doctor
+
+ liveness:
+ name: Real-path session, every action ran
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ env:
+ STUDIO_PORT: '18902'
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: '22'
+
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: '3.12'
+
+ - name: Install Unsloth
+ uses: ./.github/actions/install-unsloth-local
+ with:
+ gh-token: ${{ secrets.GITHUB_TOKEN }}
+ # Withheld on PR: this step runs checked-out PR code. studiobench needs
+ # no model at all, so nothing here depends on an authenticated fetch.
+ hf-token: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
+
+ - name: Pin the Playwright version so the browser cache has a key
+ id: pw
+ run: |
+ pip install 'playwright>=1.45,<2' psutil
+ echo "version=$(python -c 'import playwright; from importlib.metadata import version; print(version("playwright"))')" >> "$GITHUB_OUTPUT"
+
+ - name: Restore the Playwright browser cache
+ id: pw-cache
+ uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ continue-on-error: true
+ with:
+ path: ~/.cache/ms-playwright
+ key: ms-playwright-${{ runner.os }}-${{ steps.pw.outputs.version }}-sbench-v1
+
+ # Chromium alone. The other two engines are 470 MB each and this workflow
+ # never asks for them: studiobench's Linux default is WebKit as a proxy for
+ # WebKitGTK, but CI pins Chromium explicitly because the tracing and CDP
+ # instruments only exist there, and a liveness gate wants the richest
+ # instrumentation, not the most representative engine.
+ #
+ # Bounded and retried through the shared helper, and the CDN download is kept
+ # separate from the apt transaction because they are two different failures.
+ # `--with-deps` is deliberately absent: it makes playwright run its own
+ # `apt-get update`, which is the one apt call in this repo that cannot be
+ # restructured to try the image's lists first.
+ - name: Install the Chromium engine
+ id: pw-install
+ timeout-minutes: 15
+ env:
+ RETRY_ATTEMPTS: '2'
+ RETRY_ATTEMPT_TIMEOUT: '300'
+ # Zero hands resilience to the helper's own attempt loop, which reports which
+ # way each attempt went. apt's internal retries are invisible and are charged
+ # to the caller's budget.
+ APT_ACQUIRE_RETRIES: '0'
+ run: |
+ if [ "${{ steps.pw-cache.outputs.cache-hit }}" != "true" ]; then
+ bash .github/scripts/retry-with-apt-lock.sh \
+ python -m playwright install chromium
+ fi
+
+ # Ask whether the system libraries are actually missing rather than assuming
+ # it. ubuntu-latest is a browser-testing image and usually ships them, in
+ # which case install-deps is a full apt transaction to install nothing.
+ # Launching the engine is the honest test, and it is what the run does next.
+ probe() {
+ python - <<'PY'
+ import sys
+ from playwright.sync_api import sync_playwright
+ with sync_playwright() as p:
+ try:
+ browser = p.chromium.launch()
+ browser.close()
+ except Exception as exc:
+ print(f"chromium will not start: {type(exc).__name__}: {exc}")
+ sys.exit(1)
+ print("chromium launches; system libraries are present")
+ PY
+ }
+
+ if probe; then
+ echo "::notice::skipped playwright install-deps; the runner image already has the libraries"
+ else
+ echo "system libraries are missing, installing them"
+ bash .github/scripts/retry-with-apt-lock.sh \
+ python -m playwright install-deps chromium
+ # Fail loudly rather than proceeding into a session that cannot launch a
+ # browser, which would otherwise surface as an opaque timeout later.
+ probe
+ fi
+
+ - name: Save the Playwright browser cache
+ # main only, and only on a SUCCEEDING install. A partial download saved
+ # under an immutable version-pinned key is restored forever afterwards,
+ # reports cache-hit, skips the download, and leaves every later run with
+ # engines that are not there. Same reasoning as studio-ui-smoke.yml.
+ if: >-
+ always() && github.ref == 'refs/heads/main'
+ && steps.pw-cache.outputs.cache-hit != 'true'
+ && steps.pw-install.outcome == 'success'
+ uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ continue-on-error: true
+ with:
+ path: ~/.cache/ms-playwright
+ key: ms-playwright-${{ runner.os }}-${{ steps.pw.outputs.version }}-sbench-v1
+
+ # No --api-only: studiobench drives the real SPA, so the server has to be
+ # serving `studio/frontend/dist`. It needs no model, because the reply it
+ # measures comes from its own pacer over an external provider.
+ - name: Boot Studio
+ run: |
+ bash .github/scripts/boot-studio-api-only.sh \
+ --port "$STUDIO_PORT" --log logs/studio.log --pid-var STUDIO_PID
+
+ - name: Wait for health
+ run: bash .github/scripts/wait-for-health.sh --port "$STUDIO_PORT" --log logs/studio.log
+
+ # The smallest rung, and quick rather than fast: this job is asking whether
+ # every moving part still moves, not how fast anything is. 1K keeps it
+ # inside a runner's patience while still running the whole film.
+ # The password has to be handed over explicitly. Studio mints a bootstrap
+ # password on a boot with no auth directory, which is exactly what the boot
+ # script arranges by wiping rather than resetting. When studiobench installs
+ # its own Studio it reads that file itself; when it ATTACHES to one somebody
+ # else booted, it has no way to know where that Studio's home is, and the
+ # failure is a 401 that reads like a harness bug.
+ #
+ # It then rotates the password and clears `must_change_password`. That gate
+ # is not cosmetic: with it set, login succeeds, /healthz answers 200, and
+ # every route the harness needs answers 403, so the run reports an empty
+ # thread rather than an error.
+ #
+ # The 100K rung and the fast tier's 57.3 s film, because a liveness gate is
+ # only worth anything at a size that exercises the film.
+ #
+ # This was 1K on the reasoning that the smallest rung is the cheapest, and the
+ # first real run refuted it: NINE actions reported NOT RUN, every one of them
+ # for an honest reason the rung itself caused. The thread was shorter than the
+ # viewport, so neither scroll could travel. No follow-up turns were planned, so
+ # `send_turn` found an exhausted queue. The last assistant message carried no
+ # More, Copy or Delete button. Measured across real payloads afterwards: at 10K
+ # `message_menu` still drops out on some cells, and 100K is the first rung where
+ # everything except `image_upload` runs on every cell. That is the same 100K the
+ # README names as the smallest rung carrying real load, arrived at independently.
+ - name: Run a real-path session
+ run: |
+ python -m tests.studio.studiobench \
+ --tier fast --rungs 100K --reps 1 \
+ --attach "http://127.0.0.1:${STUDIO_PORT}" \
+ --password "$(cat ~/.unsloth/studio/auth/.bootstrap_password)" \
+ --engine chromium \
+ --out outputs/studiobench-ci
+
+ # THE GATE. Exits non-zero unless every scheduled action reports ran=true
+ # with no missed slot, and refuses a payload with no cell rows rather than
+ # passing over it vacuously.
+ #
+ # `image_upload` is excused, and it is the only one. It reports NOT RUN on
+ # every cell of every 100K run measured, always with the same evidence: the
+ # composer's attachments button is in the DOM with a zero box and
+ # `mounted: false`, alongside `model_loaded_hint: false`. This fixture drives
+ # an external provider and loads no model, so Studio does not mount the
+ # control. That is a property of the fixture rather than of any change under
+ # test, which is the only thing this flag is for. Every name here is a hole in
+ # the gate and this one is documented so it can be closed rather than inherited.
+ #
+ # If this step fails with `missed its slot` rather than NOT RUN, that is the
+ # runner failing to keep up with a fixed-duration film, not a defect in the
+ # code under test. The film is built so a slow machine misses a slot instead of
+ # quietly taking a different path through a shorter session.
+ - name: Every scheduled action ran
+ run: |
+ python -m tests.studio.studiobench \
+ --assert-liveness outputs/studiobench-ci/payload.jsonl \
+ --allow-not-run image_upload
+
+ # The step the documentation tells a reader to run, which until now CI never ran. That is
+ # exactly why the payload validator could reject the first parity message row, an ordinal
+ # that is legitimately 0, and go unnoticed: the session ran green while --report failed on
+ # every payload it produced. --report exits non-zero when it cannot score a payload, so
+ # running it here keeps the documented path honest.
+ - name: The payload renders as a report
+ run: |
+ python -m tests.studio.studiobench \
+ --report outputs/studiobench-ci/payload.jsonl \
+ --tier fast --rungs 100K
+ test -s outputs/studiobench-ci/summary.md
+
+ - name: Stop Studio
+ if: always()
+ run: kill "${STUDIO_PID:-0}" 2>/dev/null || true
+
+ # Uploaded on failure only. The payload is the whole diagnostic: it carries
+ # each action's reason for not running, which is the first thing anyone
+ # debugging this job wants and the last thing a step log preserves.
+ - name: Upload the payload and the Studio log
+ if: failure()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ with:
+ name: studiobench-ci-payload
+ path: |
+ outputs/studiobench-ci/**
+ logs/studio.log
+ retention-days: 7
+ if-no-files-found: warn
diff --git a/attribution/vite.studiobench.config.ts b/attribution/vite.studiobench.config.ts
new file mode 100644
index 00000000000..8d104c40703
--- /dev/null
+++ b/attribution/vite.studiobench.config.ts
@@ -0,0 +1,204 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// studiobench attribution build.
+//
+// Identical to `studio/frontend/vite.config.ts` in every respect that affects
+// what the app DOES, and different only in what it lets us SEE:
+//
+// 1. `react-dom/client` is aliased to `react-dom/profiling`, which is the
+// only build where React's `<Profiler>` `onRender` callback exists at all.
+// 2. Hidden sourcemaps, so our own frames get real names without shipping a
+// `//# sourceMappingURL` comment.
+// 3. Minifier name preservation, so our own functions and classes keep
+// their source names instead of being mangled to single letters.
+//
+// The resulting dist is injected into a REAL Studio install through the
+// existing `unsloth studio --frontend <dir>` flag (see `studio/backend/run.py`
+// around line 2820), so the backend, auth and storage stay real and only the
+// frontend bundle is swapped. That matters: the failure this whole tool exists
+// to correct was a fixture that did not run the real path.
+//
+// WHAT THIS BUILD DOES NOT FIX, and cannot. React's production and profiling
+// dists are minified by React's own release pipeline BEFORE Vite ever sees
+// them. Name preservation and sourcemaps therefore recover OUR names and
+// nothing whatsoever inside `react-dom`: the original identifier really is
+// `Zk`. Recovering react-dom names is the job of the symbol bridge in
+// `tests/studio/studiobench/analysis/symbols.py`, not of this config, and no
+// build flag here can do it.
+
+import { createRequire } from "node:module";
+import path from "node:path";
+
+const FRONTEND_ROOT = path.resolve(__dirname, "../studio/frontend");
+
+// The plugins are resolved from the FRONTEND package, not from this directory,
+// and that is not a stylistic preference. Vite bundles a `--config` file with
+// its bare imports left external (`bundleConfigFile` sets `root =
+// path.dirname(fileName)`) and then loads the bundle under the config file's
+// own path: CJS via `module._compile(code, <config path>)`, ESM via a temp file
+// in the nearest ancestor `node_modules`, of which this directory has none. So
+// Node starts its `node_modules` walk at `attribution/` and climbs to the
+// repository root, and NEITHER has a `node_modules` -- only
+// `studio/frontend/node_modules` does. Written with plain top-level imports
+// this config could not be loaded from any working directory, by any `vite`
+// binary: `Cannot find module '@tailwindcss/vite'`, and the same for the React
+// plugin and for `vite` itself. Anchoring the lookup at the frontend package's
+// `package.json` is the whole fix, and it points at the same installed copies
+// the shipping `studio/frontend/vite.config.ts` uses.
+const requireFromFrontend = createRequire(path.join(FRONTEND_ROOT, "package.json"));
+const tailwindcss = requireFromFrontend("@tailwindcss/vite").default;
+const react = requireFromFrontend("@vitejs/plugin-react").default;
+const { defineConfig } = requireFromFrontend("vite");
+
+export default defineConfig({
+ root: FRONTEND_ROOT,
+ plugins: [react(), tailwindcss()],
+ // Keep an unrelated PostCSS config in an ancestor directory from leaking
+ // into Studio installs. Tailwind is provided by its dedicated Vite plugin.
+ css: {
+ postcss: {
+ plugins: [],
+ },
+ },
+ optimizeDeps: {
+ include: ["@dagrejs/dagre", "@dagrejs/graphlib"],
+ },
+ server: {
+ host: "0.0.0.0",
+ allowedHosts: true,
+ proxy: {
+ "/api": {
+ target: "http://127.0.0.1:8888",
+ changeOrigin: true,
+ },
+ "/v1": {
+ target: "http://127.0.0.1:8888",
+ changeOrigin: true,
+ },
+ "/seed/inspect": {
+ target: "http://127.0.0.1:8004",
+ changeOrigin: true,
+ },
+ "/seed/preview": {
+ target: "http://127.0.0.1:8004",
+ changeOrigin: true,
+ },
+ "/preview": {
+ target: "http://127.0.0.1:8004",
+ changeOrigin: true,
+ },
+ "/validate": {
+ target: "http://127.0.0.1:8004",
+ changeOrigin: true,
+ },
+ "/tools": {
+ target: "http://127.0.0.1:8004",
+ changeOrigin: true,
+ },
+ },
+ },
+ resolve: {
+ // An ARRAY of regex aliases, not the object form, and the react-dom entry
+ // is deliberately anchored. Two traps, both of which produce a build that
+ // looks fine and is not:
+ //
+ // - Aliasing the bare specifier `react-dom` recurses forever. The
+ // profiling bundle's own first lines are
+ // `require("react"), require("react-dom")`, so rewriting `react-dom`
+ // points it at itself.
+ // - A plain string `find: "react-dom/client"` is prefix matching in
+ // Vite, so it would also rewrite `react-dom/profiling` and produce the
+ // same recursion by a different route.
+ //
+ // `/^react-dom\/client$/` matches exactly the specifier the app imports and
+ // nothing else. Bare `react-dom` is left alone on purpose: it is a small
+ // shim that dispatches through the injected internals object, so it drives
+ // whichever renderer actually loaded.
+ alias: [
+ { find: /^react-dom\/client$/, replacement: "react-dom/profiling" },
+ { find: /^@\//, replacement: `${path.resolve(FRONTEND_ROOT, "./src")}/` },
+ {
+ find: "@dagrejs/dagre",
+ replacement: path.resolve(
+ FRONTEND_ROOT,
+ "./node_modules/@dagrejs/dagre/dist/dagre.cjs.js",
+ ),
+ },
+ ],
+ },
+ build: {
+ outDir: path.resolve(__dirname, "dist"),
+ emptyOutDir: true,
+ // `hidden` emits the .map files but suppresses the sourceMappingURL
+ // comment, so the bundle is byte-comparable to a shipping one apart from
+ // the profiling renderer, and devtools does not silently start resolving
+ // maps mid-measurement.
+ sourcemap: "hidden",
+ // Vite 8 minifies with oxc by default, and without a name-preservation
+ // knob the minifier renames our own components too: the app-side frames
+ // become single letters, which would leave the symbol bridge with no
+ // anchors to validate against. Measured on this tree, of the 403
+ // `export function <Component>` names in `studio/frontend/src` only 37
+ // survive an unconfigured build, against 390 with the option below.
+ //
+ // The knob is the OXC MINIFIER's `mangle.keepNames`, reached through
+ // `output.minify`, and NOT the bundler-level `output.keepNames`. That
+ // distinction is the whole reason this block looks the way it does.
+ // `output.keepNames: true` on the rolldown that Vite 8.0.16 pins
+ // (`[email protected]`, an exact pin in Vite's own `dependencies`) fails the
+ // build outright:
+ //
+ // [MISSING_EXPORT] "toString" is not exported by
+ // "node_modules/underscore/modules/_setup.js"
+ //
+ // and 23 more like it. That is rolldown#9973: under `keepNames` the
+ // bundler splits a multi-declarator `export var a = 1, b = 2` into
+ // separate declarations and drops the `export` keyword while doing it, so
+ // every name after the split silently stops being exported. Underscore's
+ // `_setup.js` is written almost entirely in that style
+ // (`export var push = ..., slice = ..., toString = ...`) and we reach it
+ // through `@dagrejs/graphlib`, so the build aborts. Fixed upstream by
+ // rolldown#9974, first released in the 1.1.x line; unavailable to us
+ // without overriding the rolldown that Vite pins, which would change the
+ // bundler under the shipping UI and is not something an attribution-only
+ // config gets to do.
+ //
+ // `mangle.keepNames` is the option that actually matters here anyway.
+ // Bundler-level renaming only appends deconflicting suffixes and leaves
+ // names readable; it is the minifier's mangler that turns `AppSidebar`
+ // into a letter. `compress.keepNames` is set alongside it because oxc
+ // documents the pair as belonging together -- DCE has to stop treating
+ // the name-carrying binding as dead. Vite spreads the user `output` last
+ // (`buildOutputOptions`), so `minify` here replaces Vite's default
+ // `minify: true` rather than being clobbered by it; compression and
+ // mangling both stay on, and the bundle grows only ~3.9% from carrying
+ // the real names.
+ rolldownOptions: {
+ output: {
+ minify: {
+ compress: { keepNames: { function: true, class: true } },
+ mangle: { keepNames: { function: true, class: true } },
+ },
+ // Marks the bundle so the harness can prove it is measuring the
+ // attribution build and not a stale shipping dist left in the
+ // directory handed to `unsloth studio --frontend`. Read by
+ // `analysis/bridge_build.py:assert_attribution_build`.
+ //
+ // This is a BANNER and not a `define`, and the difference is not
+ // cosmetic. `define` performs identifier SUBSTITUTION in source: it
+ // rewrites occurrences of a token that already appear in the code. No
+ // Studio source file mentions `__STUDIOBENCH_ATTRIBUTION_BUILD__`, so
+ // a `define` entry substitutes nothing, emits nothing, and the marker
+ // is simply absent at runtime. Built that way first; the assertion
+ // could never pass and the bundle was byte-identical with and without
+ // the option. A banner is prepended unconditionally, so the global
+ // genuinely exists.
+ banner: "globalThis.__STUDIOBENCH_ATTRIBUTION_BUILD__ = true;",
+ },
+ },
+ commonjsOptions: {
+ include: [/node_modules/, /@dagrejs\/dagre/, /@dagrejs\/graphlib/],
+ },
+ },
+});
diff --git a/tests/studio/studiobench/CONTRIBUTING-perf.md b/tests/studio/studiobench/CONTRIBUTING-perf.md
new file mode 100644
index 00000000000..b4d601c9635
--- /dev/null
+++ b/tests/studio/studiobench/CONTRIBUTING-perf.md
@@ -0,0 +1,178 @@
+# Proving a Studio performance change
+
+This is the protocol for turning "it feels faster" into a number a reviewer can trust. It exists
+because an audit of 40 frontend pull requests found that **30 of them had no effect distinguishable
+from a null control**, and several of those had looked like clear wins right up until a detection
+floor was applied to them.
+
+Read this before you quote a result. It is short, and every rule in it was written after a wrong
+answer was produced by not having it.
+
+## The loop
+
+```
+1. Screen python -m tests.studio.studiobench --tier fast ~5 min, direction only
+2. Confirm python -m tests.studio.studiobench --tier standard --reps 4 ~1 h, ~2 h for an A/B
+3. Gate per-metric floor, sign consistency, stability
+4. Parity prove you did not change what is rendered
+5. Read python -m tests.studio.studiobench --report <out>/payload.jsonl --tier standard
+```
+
+Every step above except the last drives a real Studio and therefore needs credentials. The
+commands are written short here; see **"You need a Studio, and you need its password"** in
+[README.md](README.md) before you run the first one, because a missing `--password` fails as an
+HTTP 401 only after the browser has started, and `--doctor` reports PASS on that configuration.
+Step 5 needs neither Studio nor network.
+
+Steps 3 and 4 are not optional extras. A number that has not cleared them is not evidence.
+
+## 1. Screen on the fast tier
+
+`--tier fast` is one rung (100K), a 57.3 second film, about 5 minutes, or about 9 minutes for a full
+A/B wave. Its detection floor is wider than the standard tier's, so it can tell you a direction and
+it cannot tell you a magnitude.
+
+Use it to kill bad ideas cheaply. Do not use it to decide anything.
+
+## 2. Confirm on the standard tier
+
+`--tier standard --reps 4`. Three rungs, a 243 second film: twelve cells and about an hour against
+one build, twenty-four cells and about two hours for an A/B wave, before either install. Budget for
+that rather than for the tier's own 20 minute figure, which describes ONE walk of the ladder.
+
+**Use at least 4 repetitions.** At `--reps 2` the null control reported a 38.1% delta on
+`settings.open_ms`. At `--reps 4` the same metric collapsed to 1.2% with 48% spread. Two
+repetitions is not enough to separate a mean from an order effect, because the harness flips arm
+order on odd repetitions and a 1-rep or 2-rep session bakes in whichever order it happened to run.
+
+If you shard a run, shard into **2 shards of 2 repetitions, not 4 shards of 1**. A single-repetition
+session always runs base first.
+
+## 3. The three gates
+
+A result must clear all three. Failing any one makes it **void**, not "a small win".
+
+### Gate 1: its own per-metric detection floor
+
+You need a **null control**: the same build against itself, base versus base, producing a delta that
+you know is exactly zero in truth. Whatever it reports is your noise.
+
+Two rules about it, both learned the hard way:
+
+- **The floor is per metric, not global.** A single global floor derived from the frame tail says
+ nothing about whether `settings.open_ms` can resolve 5%. Each metric gets its own floor from the
+ null control.
+- **The floor must be measured in band**, concurrently with your A/B, under the same machine load.
+ A floor measured on a quiet machine does not transfer to a busy one. Session-to-session drift on
+ this metric set is about 8%, which is larger than most real effects, so a floor from yesterday's
+ run is not a floor.
+
+The floor for a metric is `max(|null delta|, spread)`. The null control's own systematic bias has to
+be cleared as well as its scatter.
+
+If you run waves, **each wave carries its own null control.** Wave 0's floor is not wave 1's floor.
+
+### Gate 2: sign consistency
+
+Every paired ratio must fall on the same side of 1.0. If three repetitions say faster and one says
+slower, you have scatter that happens to average in your favour, not an effect.
+
+### Gate 3: stability
+
+The effect must exceed its own scatter. This gate rejected 12 rows that had passed gates 1 and 2 and
+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
+on both arms and compares them.
+
+What the digest **can** see: tag structure, `data-slot`, `data-state`, `data-role`, classes, text.
+It normalises generated ids, rendered durations, relative times, scroll state, backend-minted record
+ids, absolute URLs and blob/data URLs, so those do not read as false differences.
+
+What it **cannot** see: stylesheet CSS, computed layout, colour, typography, or anything rastered.
+So a change to `content-visibility`, `contain-intrinsic-size`, transforms or paint can be perfectly
+parity-clean and still visibly wrong. **If you touched CSS, take screenshots as well.**
+
+`NOT EXERCISED` is not a pass. An action that never ran is not evidence that it is stable.
+
+## Before you trust any number at all
+
+### Check that the thing you measured actually ran
+
+The single most common way this harness has produced a wrong answer, three separate times in three
+separate subsystems, is code that could never fire reporting as "no effect":
+
+- Four scene actions recorded NOT RUN on 312 of 312 attempts, because their slots opened while a
+ follow-up turn was still streaming. They read as fast, stable and meaningless.
+- A surface crawler walked 53 surfaces that would all have digested the same persistently mounted
+ chat root.
+- An overlay walk was written in a way that could never fire at all.
+
+Check `ran` before you read a timing. Check that a potency counter moved before you believe an
+ablation.
+
+### Do not measure a stale branch against current main
+
+If your branch does not merge cleanly and the harness falls back to your raw head, your treatment
+arm predates every commit that landed since you branched, and you are measuring branch age. One
+pull request in the audit showed a +246% regression on the message menu that **vanished entirely**
+when the branch was rebased. The regression was another PR's improvement missing from the old side.
+
+For a change that has **already merged**, do not merge it onto main again: that is a no-op producing
+a byte-identical bundle and a void that looks exactly like "this changed nothing". Measure it as
+`merge commit` against `merge commit^1`.
+
+### Know what the rung ladder can and cannot see
+
+The rung varies the **seeded thread size**. The streamed reply is pinned at 6,000 characters on
+every rung on purpose. A mechanism whose cost scales with **reply length** is therefore held
+constant by this ladder and will read as a flat floor on it. If that is your mechanism, you need to
+build a reply-length axis rather than quote a rung comparison that cannot see your effect.
+
+Related: rank frames by **slope, not size**. `findNextMatchSync` is the second-largest frame at the
+100K 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.
+
+## Ablation: correlation to causation
+
+A hot frame with a steep slope is a lead. To make it a finding, remove the mechanism and watch the
+slope go with it. `arms/knobs.js` injects knobs into the shipped build through `add_init_script`, so
+no recompile is needed.
+
+Every arm reports two things or its reading is discarded:
+
+- **INVARIANCE**: evidence the rendered output is unchanged. An arm claiming exactness that drifts
+ is void, not quoted with a caveat.
+- **POTENCY**: evidence the knob fired, through a counter that must move. An arm that is exact but
+ whose potency counter did not move reads **NOT RUN**, never "no effect".
+
+Prefer a dose-response to an on/off arm where you can build one. Varying the dose and requiring a
+straight line makes a *null* informative, which an on/off arm cannot do.
+
+Which knob removes the slope names the fix. If none does, your hypothesis was wrong, and saying so
+is a better contribution than a fix aimed at the wrong mechanism.
+
+## If you have many cores
+
+Running several comparisons at once is fine and is how the 40-PR audit was done, but contention is a
+confound unless you contain it:
+
+- Pin **whole physical cores**. Never split SMT siblings across two jobs, or two jobs share an
+ execution unit and neither timing means anything.
+- Give each job **one NUMA node**, memory included.
+- Make the slices **equal**, sized by the most crowded node, and hold back about 20% for the kernel.
+- Read the topology from `/sys/devices/system/node` rather than hard-coding a CPU list.
+- Run the null control **as one of the parallel jobs**, so the floor sees the same contention the
+ results do.
+
+## What to put in your pull request
+
+- The metric, both arms' values, the ratio, the spread, and **the floor it cleared**.
+- Which tier, how many repetitions, and confirmation that a null control ran in the same session.
+- The parity result, plus screenshots if you touched CSS.
+- Anything that did not run, said plainly.
+
+A result quoted without its floor will be asked for its floor.
diff --git a/tests/studio/studiobench/INTERFACES.md b/tests/studio/studiobench/INTERFACES.md
new file mode 100644
index 00000000000..99ba92de792
--- /dev/null
+++ b/tests/studio/studiobench/INTERFACES.md
@@ -0,0 +1,300 @@
+# studiobench interfaces
+
+The contract between Layer 1 (real-path session), Layer 2 (tracing and analysis) and Layer 3
+(ablation arms and report). Layer 1 owns every name in this file. It is deliberately small: six
+concepts, all plain dataclasses and dicts, nothing that needs importing across layer boundaries at
+call time.
+
+Import everything from `tests.studio.studiobench.runtime.types`. Nothing else in `runtime/` is
+public.
+
+```python
+from tests.studio.studiobench.runtime.types import (
+ Cell, Window, Instrument, ActionContext, ActionResult, Slot, BenchContext, Recorder,
+)
+from tests.studio.studiobench.instruments import register_instrument
+from tests.studio.studiobench.scene import register_action
+```
+
+Rules that apply to every dict crossing these boundaries:
+
+- JSON-safe scalars only: `str`, `int`, `float`, `bool`, `None`, and lists/dicts of those.
+- **No bare zero.** A numeric key that can legitimately be zero carries a sibling
+ `<key>_attempted: bool`. A quantity that could not be measured is `None` with a sibling
+ `<key>_reason: str`. `0` means "measured, and it was zero"; it never means "did not run".
+- Durations are milliseconds, floats, suffixed `_ms`. Byte counts are suffixed `_bytes`,
+ megabytes `_mb`. Counts are integers with no suffix.
+- Keys are `snake_case`. An instrument namespaces nothing itself; the harness nests its dict under
+ its own name.
+
+---
+
+## 1. A cell
+
+A **cell** is one measured configuration: one rung, one arm, one repetition. It is the unit a row
+is keyed by and the unit a resume skips.
+
+```python
+@dataclass(frozen = True)
+class Cell:
+ cell_id: str # stable and filename-safe, e.g. "r10K.A0.rep0"
+ rung: str # "1K" | "10K" | "100K" | "500K" | "1M"
+ rung_tokens: int # nominal token target of the rung
+ arm: str # arm id; "A0" is the shipping build with no knob
+ rep: int # 0-based repetition index
+ tier: str # "quick" | "standard" | "full"
+ transport: str # "provider" (real SSE via the backend) | "direct" (ablation only)
+ instrument_level: int # 0..3; an instrument declaring a higher level stays dormant
+ seed: int # fixture seed; fixed per rung, not per cell
+ corpus_hash: str # sha256 of the frozen corpus shard this cell was built from
+ session_id: str # one browser session; ratios may only be taken WITHIN one of these
+ meta: dict # free-form, never read by Layer 1
+```
+
+`cell_id` is generated by Layer 1 and is the join key everywhere. Layer 3 constructs cells for its
+arms by `dataclasses.replace(base_cell, arm = ..., cell_id = ...)`.
+
+Two cells may only be compared if `session_id` matches. The report layer is expected to enforce
+that; Layer 1 guarantees the field is truthful.
+
+---
+
+## 2. A measurement window
+
+A **window** is a bracketed interval on the driver's monotonic clock during which instruments
+accumulate. Windows do not nest and do not overlap; opening one while another is open raises.
+
+```python
+@dataclass
+class Window:
+ name: str # "action:scroll_after", "stream:seg3", "idle:calibrate"
+ kind: str # "action" | "stream" | "idle" | "settle" | "teardown"
+ cell: Cell
+ t_open_ms: float # driver monotonic ms since session t0
+ t_close_ms: float | None
+ notes: dict # writer scratch, merged into the row under "notes"
+ instruments: dict # {instrument_name: dict}, filled on close
+```
+
+Opened as a context manager on the session:
+
+```python
+with session.window("action:jump", kind = "action") as w:
+ ...
+ w.note("travelled_px", 8400)
+row = w.row() # a report row, ready for Recorder.emit
+```
+
+Order on open, over instruments sorted by `name`: `instrument.open(window)`.
+Order on close, **reverse** order: `instrument.close(window) -> dict | None`. A non-None return is
+stored at `window.instruments[instrument.name]`. A raising instrument is caught, disabled for the
+rest of the cell, and recorded as
+`window.instruments[name] = {"error": "...", "disabled": True}`, so one broken instrument never
+loses the window.
+
+`window.duration_ms` is wall clock and is always present. It is not a metric; it is the denominator
+instruments divide by.
+
+---
+
+## 3. An instrument
+
+An instrument is any object satisfying this protocol. Every method is optional except `name` and
+`level`; the harness uses `getattr(inst, "open", None)`.
+
+```python
+class Instrument(Protocol):
+ name: str # unique, snake_case, becomes the key in window.instruments
+ level: int # minimum instrument_level at which this runs; 0 = always
+
+ def attach(self, ctx: BenchContext) -> None: ...
+ def start_cell(self, cell: Cell) -> None: ...
+ def open(self, window: Window) -> None: ...
+ def close(self, window: Window) -> dict | None: ...
+ def end_cell(self, cell: Cell) -> dict | None: ... # stored on the cell row
+ def detach(self) -> None: ...
+```
+
+Registration is by decorator on a zero-argument **factory**, so nothing is constructed (and no
+heavy module is imported) until the level actually selects it:
+
+```python
+# tests/studio/studiobench/instruments/tracing.py (Layer 2)
+from tests.studio.studiobench.instruments import register_instrument
+
+@register_instrument(name = "tracing", level = 2)
+def _make():
+ from .tracing_impl import TracingInstrument
+ return TracingInstrument()
+```
+
+`instruments/__init__.py` exposes `register_instrument(name, level)`, `available()` and
+`build(level) -> list[Instrument]`. Import of a Layer 2/3 instrument module is done by
+`instruments/__init__.py:load_all()`, which imports every sibling module by name and swallows
+`ImportError` into a recorded `instrument_unavailable` gate row. Adding a file is all that is
+needed to register.
+
+**Overhead declaration.** Any instrument at `level >= 1` must return, from `end_cell`, a key
+`overhead_ms` (its own best estimate of what it cost) and `overhead_attempted: bool`. Layer 1 does
+not use it; the report layer's `overhead_growth_with_length` gate does.
+
+Layer 1 ships `frames` (level 0), `input` (level 0), `glass` (level 0) and `rss` (level 0).
+
+---
+
+## 4. An action
+
+An action is a named thing a user does, run inside exactly one window, with a hard budget.
+
+```python
+@dataclass
+class ActionResult:
+ ran: bool # did the thing actually happen
+ expect_ok: bool | None # did the assertion prove it; None only if ran is False
+ expect: dict # the EVIDENCE, e.g. {"commanded_px": 4000, "travelled_px": 3980}
+ timings: dict # {"open_ms": 12.4, ...}; empty dict if ran is False
+ reason: str | None # required when ran is False or expect_ok is False
+ slot_missed: bool = False
+```
+
+An action that did not happen is `ran = False`. It is **never** reported as a fast timing, and
+`timings` must be empty in that case. An action that happened but whose assertion failed is
+`ran = True, expect_ok = False` with a reason, and its timings are recorded but the report layer is
+expected to refuse to quote them.
+
+Registration:
+
+```python
+from tests.studio.studiobench.scene import register_action
+
+@register_action(name = "scroll_after", default_budget_ms = 4000)
+def scroll_after(ctx: ActionContext) -> ActionResult: ...
+```
+
+```python
+@dataclass
+class ActionContext:
+ page: Any # Playwright sync Page
+ cdp: Any | None # CDPSession, or None off Chromium
+ cell: Cell
+ window: Window
+ args: dict # from the Slot
+ budget_ms: int # remaining budget at entry; the action must not exceed it
+ dom: "StudioDom" # selector adapter, see below
+ log: Callable[[str], None]
+```
+
+`StudioDom` is Layer 1's adapter over the real app's selectors. It exposes `viewport()`,
+`composer()`, `send_button()`, `stop_button()`, `messages()`, `last_assistant()`,
+`action_button(label)`, `reasoning_triggers()` and `js_api()` (the name of the in-page object,
+`window.__sb.dom`, that the salvaged action JS calls). Layer 3 should go through it rather than
+hard-coding selectors, so a selector change is one edit.
+
+---
+
+## 5. A scene slot
+
+The scene is a **film**, not a task list. Every action has a fixed start offset and a fixed budget
+on the session wall clock.
+
+```python
+@dataclass(frozen = True)
+class Slot:
+ action: str # a registered action name
+ t_start_ms: int # offset from the start of the measured window of the cell
+ budget_ms: int
+ args: dict = field(default_factory = dict)
+ required: bool = True # a missed required slot marks the cell degraded, not failed
+```
+
+If wall clock is already past `t_start_ms + budget_ms` when the scheduler reaches a slot, the slot
+is **not run**: it emits `ActionResult(ran = False, slot_missed = True, reason = "slot missed")`
+and the film rolls on. A slow machine therefore takes the SAME path through the SAME-length
+session as a fast one, which is the only way two machines are comparable.
+
+Layer 3 may supply its own slot list per arm via `Scene(slots = [...])`, but the total scene
+duration must be identical across arms in a batch or the ladder is not additive.
+
+---
+
+## 6. A report row
+
+One JSON object per line, appended to `report/payload.jsonl` as it is produced, so a renderer
+crash at rung 4 still ships rungs 1 to 3.
+
+```python
+recorder.emit({
+ "schema": "studiobench/1",
+ "row_type": "action", # run_meta | gate | cell | window | action | sample | failure
+ "ts_ms": 1234.5, # driver monotonic ms since session t0
+ "session_id": "...",
+ "cell_id": "r10K.A0.rep0", # absent only on run_meta and pre-cell gate rows
+ ... # row_type specific payload
+})
+```
+
+`Recorder` is:
+
+```python
+class Recorder:
+ def emit(self, row: dict) -> None: ... # validates, stamps, appends, flushes
+ def gate(self, name: str, passed: bool, detail: dict) -> None: ...
+ def failure(self, cell_id: str | None, kind: str, detail: dict) -> None: ...
+ def rows(self, row_type: str | None = None) -> Iterator[dict]: ... # re-reads the file
+```
+
+`emit` stamps `schema`, `ts_ms` and `session_id` if absent, rejects a row with no `row_type`, and
+`flush()`es plus `os.fsync`s every line. It is safe to call from the driver thread only.
+
+Row types and their required payload:
+
+| `row_type` | required keys |
+|---|---|
+| `run_meta` | `tier`, `tool_version`, `corpus_hash`, `studio_ref`, `bundle`, `platform`, `started_at` |
+| `gate` | `name`, `passed`, `detail` |
+| `cell` | `cell`, `completed` (bool), `fidelity`, `chars_per_token`, `instruments` |
+| `window` | `name`, `kind`, `t_open_ms`, `duration_ms`, `instruments`, `notes` |
+| `action` | `action`, `window`, `ran`, `expect_ok`, `expect`, `timings`, `reason`, `slot_missed` |
+| `sample` | `t_ms`, plus whatever the 1 Hz sampler produced |
+| `failure` | `kind`, `detail`; `cell_id` may be null |
+
+A cell that could not complete still emits a `cell` row with `completed: false`, its failure mode,
+its last `sample` row and `rss_at_death_mb`. That is a first-class result, not a gap.
+
+---
+
+## 7. BenchContext
+
+Handed to `Instrument.attach` and available to arms.
+
+```python
+@dataclass
+class BenchContext:
+ browser: Any # Playwright Browser
+ context: Any # BrowserContext
+ page: Any # the page under measurement
+ cdp: Any | None
+ base_url: str # the Studio the session is driving
+ session_id: str
+ tier: str
+ instrument_level: int
+ paths: "Paths" # .out, .payload_jsonl, .traces, .symbols, .corpus
+ recorder: Recorder
+ log: Callable[[str], None]
+ browser_procs: list # psutil.Process roots of the browser tree, possibly empty
+```
+
+`ctx.page` may be REPLACED between cells (a crashed renderer is recovered by opening a new page).
+An instrument that caches `page` must re-read it in `start_cell`, not in `attach`.
+
+---
+
+## 8. Stability
+
+This file is the contract. Layer 1 will not change any name above without editing this file in the
+same commit and saying so at the top. Additive changes (new optional key, new row type, new
+instrument level) are not breaking and will land without notice.
+
+Not part of the contract, and free to change without warning: everything under `runtime/` other
+than `types`, `pacer.py`'s internals, the fixture generator's internals, and the JS in
+`instruments/*.js`.
diff --git a/tests/studio/studiobench/README.md b/tests/studio/studiobench/README.md
new file mode 100644
index 00000000000..aa40ae9d288
--- /dev/null
+++ b/tests/studio/studiobench/README.md
@@ -0,0 +1,301 @@
+# studiobench
+
+A performance benchmark, profiler and A/B simulator for Unsloth Studio that runs the **real path**.
+
+## Run it yourself
+
+```
+pip install playwright psutil
+playwright install webkit # chromium on Windows; see "Which engine" below
+
+python -m tests.studio.studiobench --doctor
+```
+
+`--doctor` is always the first command. It works on a machine with nothing installed, because every
+heavy import is lazy, and it names what is missing and what each missing piece costs you. It does
+NOT check that it can log in to a Studio you point it at, so read the next section before you
+conclude that a `--doctor: PASS` means a run will start.
+
+### You need a Studio, and you need its password
+
+Every command below other than `--doctor` drives a real Studio, and Studio requires
+authentication. There are two ways to give it one.
+
+**Attach to a Studio you are already running.** This is the cheap path, and it needs the
+credentials, which are NOT optional and default to nothing:
+
+```
+python -m tests.studio.studiobench --tier fast \
+ --attach http://127.0.0.1:5401 \
+ --password "$(cat ~/.unsloth/studio/auth/.bootstrap_password)"
+```
+
+`--username` defaults to `unsloth`, `--password` defaults to empty. Without a correct password the
+run aborts with `HTTP 401 from .../api/auth/login` after the browser has already started. If you
+launched Studio with a non-default `UNSLOTH_STUDIO_HOME`, the password file is
+`$UNSLOTH_STUDIO_HOME/auth/.bootstrap_password`.
+
+Note that studiobench **rotates** the password to its own bench value on first login, so a second
+run against the same Studio does not need `--password` again.
+
+**Or let studiobench install and launch its own Studio** with `--branch REF`. No password needed,
+because it owns the instance, but the first run clones this repository and runs `install.sh`, which
+is a multi-gigabyte download budgeted at up to 45 minutes. The wall-clock figures in the table
+below are the measurement only and do not include that install.
+
+Then pick a path. There are two that matter:
+
+| path | tier | rungs | film | wall clock | what it is for |
+|---|---|---|---|---|---|
+| **fast** | `--tier fast` | 100K only | 57.3 s | about 5 min, or 9 min for an A/B wave | iteration. You are trying a fix and want direction. |
+| **slow** | `--tier standard` | 1K, 10K, 100K | 243 s | about 20 min | confirmation. You believe a number and want it to hold. |
+
+`--tier quick` (1K and 10K) is a wiring check, and `--tier full` adds the 500K and 1M rungs for a
+ceiling hunt. Neither is the loop you work in.
+
+```
+# iterate against a Studio you are already running (see the password note above)
+python -m tests.studio.studiobench --tier fast \
+ --attach http://127.0.0.1:5401 \
+ --password "$(cat ~/.unsloth/studio/auth/.bootstrap_password)" \
+ --out outputs/iterate
+
+# confirm, letting studiobench install and launch its own Studio from a ref
+python -m tests.studio.studiobench --tier standard --branch main --reps 4 --out outputs/confirm
+
+# read the payload back as a scored report; writes <out>/summary.md beside it
+python -m tests.studio.studiobench --report outputs/confirm/payload.jsonl --tier standard
+```
+
+Pass `--out` explicitly. Without it the run invents a `studiobench-<tier>-<timestamp>/` directory
+in whatever your working directory is, which for someone standing in a clone means an untracked
+directory in the repository root.
+
+**One `--out` holds one run.** A fresh run pointed at a directory that already has a
+`payload.jsonl` moves the old one aside to `payload-<timestamp>.jsonl` and starts its own, and says
+so. Nothing is deleted, and nothing is mixed: a cell id is the rung, the arm and the repetition, so
+two runs sharing one file are two builds under two films in one ladder with no way to tell them
+apart. `--resume` is the one reuse that appends, and it refuses a payload recorded under a
+different tier, cadence, browser engine, instrument level, corpus or ref rather than skipping cells
+that measured something else.
+
+**The fast tier is a screen, not a result.** One rung, a wider detection floor, direction only. It
+exists so that someone trying a fix does not wait 20 minutes to learn they were wrong. Nothing goes
+in a pull request until `--tier standard` agrees with it.
+
+### Why 100K, and why the fast tier has only that rung
+
+The 10K rung was run across six pull requests and could not separate any of them from a null
+control: at that size the UI work disappears underneath the scene's own scripted timings, and
+`copy_markdown` read 204 ms on all fourteen arms. 100K is the smallest rung that carries real load,
+with a jank index of 29 against 0.6 and a worst frame of 1,855 ms against 214. It is the only rung
+worth an iteration loop.
+
+### Proving a change actually did something
+
+A single number from a single build is not evidence. Read
+[CONTRIBUTING-perf.md](CONTRIBUTING-perf.md) before you quote a result. The short version: run a
+null control alongside your A/B, derive a per-metric detection floor from it, and clear all three
+verdict gates. In an audit of 40 frontend pull requests, 30 had no effect distinguishable from that
+null control, and several of those had looked like clear wins before the floor was applied.
+
+## Why this exists
+
+A full day of measurement failed to name what makes long generations slow, and the reason turned
+out to be the fixture rather than the analysis: **the old harness did not run the code that is
+slow.** It measured a backend-free smoke page driven by a local `ChatModelAdapter`, so two whole
+mechanisms never executed.
+
+1. **The cumulative `<think>` re-parse.** Real reasoning arrives as `delta.reasoning_content`, is
+ wrapped into `<think>...</think>`, appended to a single cumulative buffer, and then
+ `parseAssistantContent(cumulativeText)` re-parses **the whole growing buffer on every delta**.
+ O(n) per chunk, O(n^2) per reply. Not one line of it ran.
+2. **The autoscroll observer.** `use-intent-aware-autoscroll.tsx` installs a `MutationObserver`
+ with `subtree: true, characterData: true` over the entire viewport. Its callback synchronously
+ reads `scrollHeight`, writes an inherited CSS custom property on the scroll container
+ (invalidating style for every descendant), and calls `scrollTo`, on every streamed character, at
+ a cost proportional to the whole thread. `LayoutDuration` read as a flat floor, which is exactly
+ what you would see if this never ran.
+
+So Layer 1 runs the shipped app, through its own backend, over real SSE bytes.
+
+## How the real path is arranged
+
+```
+studiobench pacer --SSE--> Studio backend relay --SSE--> the SPA's own TextDecoder,
+(ThreadingHTTPServer) (external provider, SSE parser, delta accumulation,
+ provider_type "custom") parseAssistantContent, Streamdown,
+ the autoscroll observer
+```
+
+There is **no `page.route` on the primary transport** and no local adapter. A `--transport direct`
+mode is reserved purely as a cadence-fidelity ablation.
+
+### The pacer
+
+`pacer.py` is a stdlib `ThreadingHTTPServer` speaking OpenAI-compatible `text/event-stream`.
+
+- **Threaded**, not single-threaded: a single-threaded server previously lost 11 cells of a matrix
+ to `goto` timeouts, because the browser opens the SPA's own requests while a stream is in flight
+ and one blocked handler stalls all of them.
+- **The exact chunk shapes the app parses.** `delta.reasoning_content` carries `content: ""`
+ alongside, which is what the backend's own `_gguf_chat_delta_line` emits. The terminal chunk
+ carries `finish_reason: "stop"` **and** is followed by `data: [DONE]`: `streamChatCompletions`
+ throws `StreamInterruptedError` at EOF unless it saw one of them, so a harness that omits both
+ measures the error path. A usage chunk follows, because the app always sends
+ `stream_options: {include_usage: true}`.
+- **Chunked transfer encoding.** Verified: an HTTP/1.1 response with neither `Content-Length` nor
+ `Transfer-Encoding` is a keep-alive body of unknown length, and the reader blocks forever having
+ already received every byte.
+- **Deficit-scheduled cadence.** Each tick computes `floor((now - t0) / gap)` and sends the
+ shortfall in one burst, rather than sleeping a gap per chunk. Stream duration then depends on
+ wall clock alone, so a tier's time budget is honest on any machine, and a renderer that jams gets
+ a burst when it recovers, which is what a real backend does. Default cadence is the captured
+ reply's own: **24 characters every 73 ms**.
+
+`python -m tests.studio.studiobench.pacer` checks all of this on the wire with no browser.
+
+### The corpus
+
+`fixture/corpus/frozen/` **ships**. The text is generated once from a seed and frozen, with a
+sha256 per unit; a generator that drifts is refused rather than quietly measured. Every fence is
+unique, because Shiki caches highlighted output keyed on the source string and a repeated fence is
+free, which is how a harness measures a 300K-character thread and finds no highlighting cost in
+it. The escalating cycle is reasoning@10K, code@8K, reasoning@20K, code@16K, and so on.
+
+Rungs are **1K / 10K / 100K / 500K / 1M tokens**, and the characters-per-token ratio is
+**measured** per rung (tiktoken, else Studio's own counter, else a labelled estimate) rather than
+assumed at 4.0.
+
+Bulk thread mass is **seeded** over `PUT /api/chat/threads/{id}/messages`; only the last reply
+streams, because a million tokens at field cadence is three and a half hours. Seeded and streamed
+are not the same path, so the equivalence is **checked at the 10K rung** and higher rungs are
+labelled `fidelity: seeded_only` when it fails.
+
+The rung varies the **seeded thread**, and the streamed reply is held constant at
+`STREAM_TAIL_CHARS = 6_000` on every rung by design, so that the tail is comparable across rungs. A
+consequence worth knowing before you design an experiment: a mechanism whose cost scales with
+**reply length** rather than thread size is held constant by this ladder and will read as a flat
+floor on it. Measuring one of those needs an axis you build yourself.
+
+### The scene
+
+A **fixed-duration film**, not a task list. Every action has a fixed `(t_start_ms, budget_ms)` on
+wall clock. A machine too slow to reach a slot records `slot_missed: true` and the film rolls on.
+A sequential script would make a slow machine take a different path through a different-length
+session, and nothing would be comparable.
+
+Fifteen actions, each with an `expect` assertion that proves it happened:
+
+| action | what proves it |
+|---|---|
+| keystroke | the composer's controlled value grew by the characters typed |
+| scroll during generation / after | the viewport travelled at least 90% of what was commanded |
+| reasoning expand/collapse | every pane's `data-state` went open, then all closed |
+| stop generation | the run ended, and the character count stopped growing |
+| settings open/scroll/close | the dialog appeared, its body travelled, it closed |
+| model change | an option was clicked and the menu closed |
+| composer short/medium/very long | the composer held every length it was given |
+| copy markdown | the clipboard was non-empty afterwards |
+| select text | the selection covered at least half the **visible** characters |
+| select-all + copy | the selection was non-empty |
+| image upload | the composer's attachment count rose |
+| thread reopen | the thread came back with the same message count |
+| message menu | it opened **and** closed **and** had a non-zero item count |
+| delete | the `[data-role]` count dropped |
+
+**An action that did not happen is `ran: false`, never a fast timing.** The Radix menu trigger
+opens on `pointerdown`, so `element.click()` leaves it shut and the column reads a tidy small
+number. A jump scroll from the bottom is read by the intent-aware autoscroll as programmatic and
+snapped back, so the viewport lands where it started and the timing is precise and about nothing.
+
+This is the most common way this harness has produced a wrong answer, and it has happened three
+separate times in three separate subsystems. Each time the shape was identical: code that could
+never fire, reported as "no effect". Check `ran` before you read a timing.
+
+### The instruments
+
+| name | level | what it reads |
+|---|---|---|
+| `frames` | 0 | one self-rescheduling rAF loop, timer lag, long tasks, CDP presented frames |
+| `input` | 0 | keystroke-to-paint from the page side of a real key event |
+| `rss` | 0 | the whole browser tree's RSS, on a thread |
+| `glass` | 1 | `scrollHeight` reads, `scrollTop` writes, the stabilizer property, mutation records |
+
+Headline numbers come from level 0 only. Higher levels buy naming at the cost of overhead, and
+`overhead_growth_with_length` is a gate: overhead correlated with the treatment disqualifies that
+level for that comparison.
+
+The rAF loop **counts and does not pump**, and `requestAnimationFrame` is not wrapped as the frame
+counter: a wrapper counts the page's frame once for the loop and once more for every rAF the app
+scheduled in it, and reported **888 fps on a 60 Hz page**.
+
+The timer clamp is calibrated **inside an enforced idle window** before each measured window, not
+from the first ticks of a page that already has 31,637 elements standing. If the calibrated clamp
+exceeds 10 ms, `busy_pct` is `null` **with a reason**, never `0.2%`.
+
+## Gates
+
+- **A dev server is refused.** React's development build inflates the axis under investigation by
+ about 3.2x, so a measurement there would confirm any hypothesis. Two checks:
+ `/@vite/client` must not serve a JavaScript module, and `bundleType: 0` must appear in the same
+ chunk as `rendererPackageName: "react-dom"`.
+ - The `/@vite/client` probe checks **what came back**, not just the status: Studio serves its SPA
+ for any unknown path, so a production build answers 200 with `index.html`.
+ - The marker regex accepts **backticks**: the production bundle is minified with a pass that
+ rewrites short string literals as template literals.
+ - **`jsxDEV` is never grepped.** `hast-util-to-jsx-runtime`, which Streamdown pulls in, ships its
+ own option guard naming `jsxDEV`, so the grep fails a perfectly good production build.
+- **No bare zeros.** Every numeric key that can legitimately be zero carries a sibling
+ `<key>_attempted`. An unmeasurable quantity is `null` with a `<key>_reason`.
+- **Three clocks.** rAF, a 1 ms timer, and CDP presented frames. More than 20% disagreement marks
+ the window `clocks_agree: false` and the report layer excludes it from scoring.
+- **No cross-session comparison.** Every slope, ratio and A/B pair is read within one session, and
+ the report layer refuses anything else. Measured session-to-session drift on this metric set is
+ about 8%, which is larger than most real effects.
+
+## Ablation: proving a cause rather than correlating with one
+
+A hot frame with a steep slope is a lead, not a finding. `arms/knobs.js` carries runtime-injected
+knobs that are applied to the **shipped build** through `add_init_script`, so an ablation needs no
+recompile: hide content, undo a `content-visibility` override, detach the autoscroll observer,
+neutralise the scroll stabilizer property, freeze React while keeping the DOM.
+
+Every arm must declare and report two things or its reading is worthless:
+
+- **INVARIANCE**: evidence the rendered output is unchanged by the knob. An arm that claims
+ exactness and then drifts is **void**, not quoted with a caveat.
+- **POTENCY**: evidence the knob actually fired, through a counter that must move. An arm that is
+ exact but whose potency counter did not move reads **NOT RUN**, never "no effect".
+
+Which knob removes the slope names the fix. If no knob does, the hypothesis was wrong, and that
+negative result is worth more than a fix aimed at the wrong mechanism.
+
+## Output
+
+`<out>/payload.jsonl`, one JSON object per line, flushed and fsynced as it is produced, so a
+renderer crash at rung 4 still ships rungs 1 to 3 plus the crash record. A cell that could not
+complete emits a `cell` row with `completed: false`, its failure mode and its RSS at death.
+(`<out>` is the `--out` directory. `report/` is the source package that renders the payload, not
+an output path.)
+
+`--report <out>/payload.jsonl` scores that file and prints the summary, writing it to
+`<out>/summary.md` as well. It needs no browser, no Studio and no network, which is the point of
+shipping a single-file benchmark: the numbers come back as a file and the analysis happens
+wherever the analyst is. Pass the same `--tier` (or `--rungs`) the run used, or the ladder will
+report rungs you never declared as incomplete.
+
+## Portability
+
+`python -m tests.studio.studiobench.build` produces `dist/studiobench.pyz`, one file. The bootstrap
+is stdlib-only and Playwright is imported lazily, so `--help` and `--doctor` work on a machine with
+nothing installed, which is the machine where `--doctor` has to say what is missing.
+
+The default engine matches the tester's desktop webview family: Windows to Chromium via
+`channel=msedge` (WebView2), macOS to WebKit (WKWebView), Linux to WebKit, **labelled a proxy for
+WebKitGTK** rather than presented as the real thing.
+
+## Layers
+
+Layer 1 (this) owns the real-path session. Layer 2 owns tracing and analysis, Layer 3 owns the
+ablation arms and the report. `INTERFACES.md` is the contract between them.
diff --git a/tests/studio/studiobench/__init__.py b/tests/studio/studiobench/__init__.py
new file mode 100644
index 00000000000..bc562153d81
--- /dev/null
+++ b/tests/studio/studiobench/__init__.py
@@ -0,0 +1,10 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""studiobench: a real-path performance benchmark for Unsloth Studio.
+
+Layer 1 (this package's runtime, pacer, fixture and scene) drives the SHIPPED app through its own
+backend and its own SSE transport. See INTERFACES.md for the contract Layers 2 and 3 plug into.
+"""
+
+__version__ = "0.1.0"
diff --git a/tests/studio/studiobench/__main__.py b/tests/studio/studiobench/__main__.py
new file mode 100644
index 00000000000..d615dc48938
--- /dev/null
+++ b/tests/studio/studiobench/__main__.py
@@ -0,0 +1,1934 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""studiobench: the only thing a tester runs.
+
+ python -m tests.studio.studiobench --doctor
+ python -m tests.studio.studiobench --tier quick --attach http://127.0.0.1:5310
+ python -m tests.studio.studiobench --tier standard --branch main
+
+EVERY heavy import is lazy. `--help` and `--doctor` are the first two things an external tester
+runs and they must work on a machine with nothing installed -- a machine where `--doctor` exists
+precisely to say what is missing. An ImportError at the top of this file would make the tool
+unable to report its own missing dependencies, which is the one failure mode a doctor may not have.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import platform
+import sys
+import time
+from pathlib import Path
+from typing import Optional
+
+TOOL_VERSION = "0.1.0"
+TIERS = ("fast", "quick", "standard", "full")
+TIER_RUNGS = {
+ # One rung, and it is 100K on purpose. The 10K rung was measured across six PRs and could
+ # not separate any of them from the null control: at that size the UI work disappears
+ # underneath the scene's own scripted timings (copy_markdown read 204 ms on all fourteen
+ # arms). 100K is the smallest rung that carries real load -- jank index 29 against 0.6,
+ # worst frame 1,855 ms against 214 -- so it is the only rung worth an iteration loop.
+ "fast": ["100K"],
+ "quick": ["1K", "10K"],
+ "standard": ["1K", "10K", "100K"],
+ "full": ["1K", "10K", "100K", "500K", "1M"],
+}
+# Wall clock budgets, from the design. The deficit-scheduled pacer is what makes them honest: a
+# slow machine gets the same stream duration, so it misses SLOTS rather than overrunning the tier.
+TIER_BUDGET_S = {"fast": 5 * 60, "quick": 5 * 60, "standard": 20 * 60, "full": 60 * 60}
+
+
+def _log(msg: str = "") -> None:
+ print(msg, flush = True)
+
+
+def engines_installed(probe_text: str) -> list:
+ """The engines the doctor's probe reported as PRESENT, from its one-line answer.
+
+ The probe prints `chromium, webkit (not installed), firefox (unavailable)`; anything carrying a
+ parenthesised note is a name without an executable behind it.
+ """
+ out = []
+ for part in str(probe_text).split(","):
+ name = part.strip()
+ if name and "(" not in name:
+ out.append(name)
+ return out
+
+
+# ── doctor ──────────────────────────────────────────────────────────
+
+
+def doctor(args) -> int:
+ """What is here, what is missing, and what each missing thing costs. Never raises."""
+ ok = True
+ _log(f"studiobench {TOOL_VERSION}")
+ _log(f" python {sys.version.split()[0]} on {platform.system()} " f"{platform.machine()}")
+
+ def check(
+ label: str,
+ fn,
+ *,
+ fatal: bool = True,
+ cost: str = "",
+ ) -> bool:
+ nonlocal ok
+ try:
+ detail = fn()
+ _log(f" [ok] {label}: {detail}")
+ return True
+ except Exception as exc: # noqa: BLE001
+ mark = "FAIL" if fatal else "warn"
+ _log(f" [{mark}] {label}: {type(exc).__name__}: {exc}")
+ if cost:
+ _log(f" -> {cost}")
+ if fatal:
+ ok = False
+ return False
+
+ def _playwright():
+ import subprocess
+ import playwright # noqa: F401
+
+ # In a SUBPROCESS. Starting and stopping Playwright's node driver just to read the engine
+ # paths leaves asyncio tearing down a cancelled task, and it prints a TargetClosedError
+ # traceback to stderr after the check has already passed. A doctor that prints a
+ # traceback next to `[ok]` is a doctor nobody believes.
+ probe = (
+ "from playwright.sync_api import sync_playwright\n"
+ "with sync_playwright() as pw:\n"
+ " import pathlib\n"
+ " out = []\n"
+ " for n in ('chromium', 'webkit', 'firefox'):\n"
+ " try:\n"
+ " p = getattr(pw, n).executable_path\n"
+ " out.append(n if pathlib.Path(p).exists() else n + ' (not installed)')\n"
+ " except Exception:\n"
+ " out.append(n + ' (unavailable)')\n"
+ " print(', '.join(out))\n"
+ )
+ got = subprocess.run(
+ [sys.executable, "-c", probe], capture_output = True, text = True, timeout = 120
+ )
+ if got.returncode != 0:
+ raise RuntimeError((got.stderr or "the engine probe failed").strip().splitlines()[-1])
+ text = got.stdout.strip()
+ # THE PACKAGE IS NOT THE ENGINE. `pip install playwright` and `playwright install` are two
+ # steps and the README says so, so the machine with the package and no downloaded binary is
+ # the ordinary case rather than an exotic one. Say so in the line the reader sees, with the
+ # command that fixes it, rather than reporting a bare `[ok]` they will act on.
+ #
+ # REPORTED, NOT FATAL, and deliberately so. This doctor has to keep running on a machine
+ # with no engine at all, because that is exactly the machine an external tester points it
+ # at first; a non-zero exit there would turn the one command that explains the problem
+ # into another thing that fails without saying why.
+ if not engines_installed(text):
+ return (
+ f"{text}; no engine is downloaded. Run `playwright install webkit` "
+ "(chromium on Windows) before benchmarking"
+ )
+ return text
+
+ def _psutil():
+ import psutil
+ return f"{psutil.__version__}; RSS sampling available"
+
+ def _corpus():
+ from .fixture.corpus import Corpus, RUNGS, plan_rung
+
+ c = Corpus.load()
+ lines = []
+ for rung in RUNGS:
+ p = plan_rung(c, rung)
+ lines.append(f"{rung}={p.total_chars:,}c")
+ return (
+ f"corpus_hash {c.corpus_hash[:16]}, {len(c.manifest['units'])} units "
+ f"({' '.join(lines)})"
+ )
+
+ def _registries():
+ from .instruments import available, import_errors
+ from .scene import action_names
+
+ errs = import_errors()
+ note = "" if not errs else f"; {len(errs)} module(s) failed to import: {list(errs)}"
+ return f"{len(action_names())} actions, " f"instruments {[n for n, _ in available()]}{note}"
+
+ def _engine():
+ from .runtime.browser import default_engine
+ name, _, note = default_engine()
+ return f"{name} -- {note}"
+
+ check(
+ "playwright",
+ _playwright,
+ cost = "no browser can be driven; install with `pip install playwright` then "
+ "`playwright install`",
+ )
+ check(
+ "psutil",
+ _psutil,
+ fatal = False,
+ cost = "RSS is reported as null with a reason instead of a number; everything else runs",
+ )
+ check("frozen corpus", _corpus, cost = "the corpus cannot be loaded, so no cell can be built")
+ check("registries", _registries)
+ check("desktop webview proxy", _engine, fatal = False)
+
+ if args.attach:
+
+ def _studio():
+ from .runtime.bundle_guard import check_bundle
+ from .runtime.lifecycle import wait_for_healthz
+
+ if not wait_for_healthz(args.attach, 10):
+ raise RuntimeError(f"{args.attach}/healthz did not answer 200")
+ v = check_bundle(args.attach)
+ if not v.production:
+ raise RuntimeError(v.reason)
+ return f"production build, react-dom bundleType {v.bundle_type}"
+
+ check(f"studio at {args.attach}", _studio)
+
+ def _pacer():
+ from .pacer import Pacer
+ p = Pacer().start()
+ try:
+ return f"bound to {p.base_url}"
+ finally:
+ p.stop()
+
+ check("pacer", _pacer)
+ _log()
+ _log("doctor: PASS" if ok else "doctor: FAIL")
+ return 0 if ok else 1
+
+
+# ── the run ─────────────────────────────────────────────────────────
+
+
+def side_home(explicit, out, label: str, *, ab: bool) -> Path:
+ """`UNSLOTH_STUDIO_HOME` for one side. THE TWO A/B SIDES NEVER SHARE ONE.
+
+ With `--ab` and `--home` together, both iterations used to select the same directory, so the
+ treatment's `install.sh` ran into the base's home -- and into the base's clone, which is
+ derived from it -- while the base server was already running out of it. The two arms then
+ shared or overwrote each other's binaries, which is the one thing an A/B may not do: whatever
+ it reported afterwards was one build measured against itself, wearing two labels.
+ """
+ if not explicit:
+ return Path(out) / f"studio_home_{label}"
+ return Path(explicit) / label if ab else Path(explicit)
+
+
+def side_specs(args, ab_ref) -> list:
+ """`(label, ref, attach url, port, password)` per side. One without `--ab`, two with it.
+
+ EACH SIDE CARRIES ITS OWN PASSWORD. Studio mints a bootstrap password per home, so two Studios
+ the caller booted separately have two different ones; authenticating both with the single
+ `--password` meant the base logged in and the treatment answered 401 every time, which made the
+ advertised `--attach` + `--attach-b` A/B unusable unless both servers had been preconfigured
+ with the same secret. `--password-b` defaults to `--password`, so one Studio, one home or two
+ homes already rotated to the bench password all behave as before.
+ """
+ specs = [("base", args.branch, args.attach, args.port, args.password)]
+ if ab_ref:
+ specs.append(
+ (
+ "treatment",
+ ab_ref,
+ args.attach_b,
+ args.port + 1,
+ getattr(args, "password_b", "") or args.password,
+ )
+ )
+ return specs
+
+
+def planned_rungs(args) -> list:
+ """The ladder this run will actually walk: `--rungs` when given, else the tier's own.
+
+ NORMALISED AND CHECKED HERE, because a rung label that `RUNGS` does not carry is not merely a
+ late crash. `--rungs "1K, 10K"` split to `[\"1K\", \" 10K\"]`, and the first thing `run` does
+ with that list is record it: `run_meta` carries the rungs the run PROMISED, `plan_rung` does
+ not reach `RUNGS[rung]` until `build_cells` a hundred lines later, and `recorded_ladder` folds
+ every `run_meta` in the file. So a resumed run mistyped this way appended a rung nothing can
+ ever satisfy to a payload that was complete, and `--report` scored it INCOMPLETE from then on
+ -- the same permanent damage the ladder-ratio refusal had to learn to roll back, arriving
+ through the argument parser. The install and the browser sit between the two points as well,
+ so the check is worth minutes even when the payload is fresh.
+
+ Whitespace around a comma and a lowercase suffix are the two ways to type this that read as
+ correct, so both are accepted rather than rejected; anything else is named against the ladder
+ it was measured against.
+ """
+ if not args.rungs:
+ return list(TIER_RUNGS[args.tier])
+ # Imported here, not at module scope, on the same rule the rest of this file follows: `--help`
+ # has to answer on a machine with nothing installed.
+ from .fixture.corpus import RUNGS
+
+ rungs = [label.strip().upper() for label in args.rungs.split(",")]
+ rungs = [label for label in rungs if label]
+ unknown = [label for label in rungs if label not in RUNGS]
+ if not rungs or unknown:
+ named = ", ".join(repr(label) for label in unknown) or "nothing"
+ raise SystemExit(
+ f"--rungs {args.rungs!r} names {named}, which is not a rung. "
+ f"The ladder is {', '.join(RUNGS)}, comma-separated."
+ )
+ return rungs
+
+
+#: What a cell costs BESIDES its film, measured from the steps `CellRunner._run_inner` runs around
+#: it: seeding the thread and reading it back, the navigation and thread wait, the 1.5 s idle
+#: calibration, the chars-per-token measurement, the drain and the two censuses. Comfortably over
+#: what the small rungs cost and about what 1M costs.
+CELL_OVERHEAD_S = 60
+#: One optional `--surfaces` sweep per arm, before the cells.
+SURFACE_SWEEP_S = 120
+#: The same generosity the tier budget already carries, applied to the planned work.
+WATCHDOG_MARGIN = 3
+#: An absolute ceiling on the MEASUREMENT half of the deadline. The point of a watchdog is that a
+#: wedged run cannot outlive it, so scaling with the plan must not scale without limit: `--reps
+#: 1000` would otherwise arm a deadline measured in months and the watchdog would guarantee
+#: nothing at all. 24 hours is past any plan this tool supports and short of forever.
+WATCHDOG_MAX_MEASUREMENT_S = 24 * 60 * 60
+
+
+def planned_work_s(
+ tier: str,
+ rungs: list,
+ reps: int,
+ arms: int,
+ surfaces: bool = False,
+) -> float:
+ """The wall clock the CELLS THIS RUN PLANNED will take, from the plan itself.
+
+ The film is a fixed-duration one -- that is the whole design of `scene.schedule` -- so its
+ length is known before it runs: `SCENES[tier].duration_ms`, plus the per-cell work around it,
+ times one cell per (rung, rep, arm).
+ """
+ from .scene import schedule as scene_schedule
+
+ scene = scene_schedule.SCENES.get(tier, scene_schedule.QUICK)
+ cells = max(1, len(rungs)) * max(1, int(reps)) * max(1, int(arms))
+ return cells * (scene.duration_ms / 1000.0 + CELL_OVERHEAD_S) + (
+ SURFACE_SWEEP_S * max(1, int(arms)) if surfaces else 0
+ )
+
+
+def watchdog_deadline_s(
+ tier: str,
+ specs: list,
+ *,
+ rungs: Optional[list] = None,
+ reps: int = 1,
+ surfaces: bool = False,
+) -> float:
+ """The hard-exit deadline for a whole run: the measurement it PLANNED plus the setup it must
+ sit through.
+
+ THE MEASUREMENT BUDGET IS THE MEASUREMENT'S. `TIER_BUDGET_S` is the wall clock of the cells --
+ the README's table says so, and says the install is not in it -- and three times that is the
+ generous margin the watchdog wants around them. Arming it before `install_studio` charged a
+ multi-gigabyte clone and build, which this tool itself allows 45 minutes for, against a fast
+ tier's 15 minutes; an A/B does that twice, serially, before the first cell. The watchdog then
+ fired during setup on a perfectly healthy run, and it fires through `os._exit`, so the `finally`
+ that stops the Studios it started never ran either. Every side this run INSTALLS adds its own
+ documented budget; an attached side installs nothing and adds nothing.
+
+ AND THE TIER BUDGET IS NOT THE PLAN. It is one number per tier, and three things the caller
+ controls multiply the work underneath it: `--ab` runs every cell TWICE, `--reps N` runs the
+ whole ladder N times, and `--rungs` can name a ladder the tier never had. A standard A/B at
+ four repetitions -- three rungs, four reps, two arms -- is 24 cells of the 243 second standard
+ film, 5,832 seconds of film before a single thread is seeded, against a deadline of
+ `20 min * 3 = 3,600` seconds for an attached pair that adds no install budget. The watchdog
+ hard-exited a healthy run 40% of the way through it, through `os._exit`, taking the payload's
+ remaining rows and the `finally` that stops the Studios with it. Reps 2 clears it as well once
+ seeding is counted.
+
+ So the measurement half is the LARGER of the tier's own budget and the planned work with the
+ same 3x margin around it, which leaves every documented single-arm ladder exactly where it was
+ -- a fast tier is one 57 second film, nowhere near its 900 seconds -- and grows only when the
+ caller asks for more work than the tier describes. `WATCHDOG_MAX_MEASUREMENT_S` caps it, because
+ a deadline that scales without limit is not a deadline.
+ """
+ from .runtime.lifecycle import INSTALL_TIMEOUT_S
+
+ owned = sum(1 for spec in specs if not spec[2])
+ arms = max(1, len(specs))
+ planned = planned_work_s(
+ tier, list(rungs) if rungs else list(TIER_RUNGS[tier]), reps, arms, surfaces
+ )
+ measurement = max(TIER_BUDGET_S[tier] * WATCHDOG_MARGIN, planned * WATCHDOG_MARGIN)
+ return min(measurement, WATCHDOG_MAX_MEASUREMENT_S) + INSTALL_TIMEOUT_S * owned
+
+
+def completion_exit_code(rows: list, resumed: int = 0) -> int:
+ """0 when every cell this run asked for is complete, whether it ran them or found them.
+
+ A RUN WHOSE WORK WAS ALREADY DONE IS A SUCCESS. `--resume` against a finished output skips
+ every work item and leaves `rows` empty, and requiring at least one newly executed row then
+ reported the finished output as exit 1 -- which makes an idempotent retry fail in automation
+ after paying the whole install-and-launch cost. An EMPTY run with nothing resumed is still a
+ failure: a payload with no cells passing every check is the same false negative in a costume.
+ """
+ completed = sum(1 for r in rows if r.get("completed"))
+ if not rows and not resumed:
+ return 1
+ return 0 if completed == len(rows) else 1
+
+
+def is_null_control(sides: list) -> bool:
+ """Is this A/B the same build against itself?
+
+ DETECTED, NOT DECLARED, and detected by BUILD IDENTITY rather than by URL. A self-managed null
+ control -- `--branch main --ab main` -- installs the same ref twice and launches the two copies
+ on different ports, so their base URLs necessarily differ; keying on the URL classified the one
+ calibration run this tool exists to support as an ordinary A/B, skipped
+ `noise_floor_from_null_control()`, and printed "no null control ran" underneath a table
+ comparing a build with itself. Equal refs on two builds this run installed itself is a null
+ control whatever ports they landed on.
+
+ Two ATTACHED Studios are a different matter: the refs are whatever the caller typed and the
+ harness cannot see what is deployed at either URL, so those are only a null control when both
+ sides are the same URL.
+
+ WHICH IS WHY THE URL IS ASKED FIRST. That rule was stated here and then not applied: the ref
+ comparison ran ahead of it, so `--attach U --attach-b U --branch main --ab fix` -- one server,
+ two labels the harness cannot check -- returned False on the unequal labels before the equal
+ URL was ever looked at. One Studio measured against itself was then rendered as an ordinary
+ A/B, free to publish temporal noise as an improvement, and `noise_floor_from_null_control` was
+ skipped so nothing downstream had a floor to refuse it with. Two sides on one URL are one
+ build whatever they were called. The owned case is untouched: `side_specs` gives the second
+ side `port + 1`, so two Studios this run launched never share a URL and still fall through to
+ the commit comparison below.
+
+ AND A REF IS A POINTER, which is the rule `commit_problems` already states for `--resume` and
+ this decision did not apply. The two owned sides are cloned into separate repos and fetched one
+ after the other, with a whole clone, build and launch between them; `install_studio` alone
+ budgets 45 minutes. A push to `main` inside that window leaves `--branch main --ab main` with
+ two DIFFERENT builds under one ref name, and calling that a null control does not merely
+ mislabel it: `scoring.ab.compare` voids the run and empties `regressions`, and
+ `noise_floor_from_null_control` hands the delta back as THIS MACHINE'S NOISE FLOOR for the next
+ A/B to be judged against. Measured on a 12% regression between two commits: the regression is
+ erased and 12% is published as the floor, which would then hide every real effect under 12% on
+ that machine. That is a control that could not have detected the effect it was clearing.
+
+ So the BUILDS are compared, not their names. An empty commit on either side is not a
+ difference, the same rule `commit_problems` applies: an attached side has none to declare, and
+ neither does a payload written before commits were recorded.
+ """
+ if len(sides) < 2:
+ return False
+ base, treatment = sides[0], sides[1]
+ if base.get("base_url") == treatment.get("base_url"):
+ return True
+ if base.get("ref") != treatment.get("ref"):
+ return False
+ if not (base.get("owns") and treatment.get("owns")):
+ return False
+ base_commit = str(base.get("commit") or "")
+ treatment_commit = str(treatment.get("commit") or "")
+ if base_commit and treatment_commit:
+ return base_commit == treatment_commit
+ return True
+
+
+def _ab_label(sides: list, is_null: bool) -> str:
+ """The title on the A/B table, naming the BUILDS whenever the ref alone would mislead.
+
+ A null control states the commit it compared with itself, so a reader can tell which build the
+ machine's noise floor was measured on. And the case this exists for: two installs of one ref
+ that resolved to two different commits are NOT a null control, and printing "main -> main" over
+ them would read as one. Naming both commits is the only honest title for that table.
+ """
+ if len(sides) < 2:
+ return sides[0]["ref"] if sides else ""
+ base_commit = str(sides[0].get("commit") or "")
+ treatment_commit = str(sides[1].get("commit") or "")
+ if is_null:
+ at = f" @ {base_commit[:12]}" if base_commit else ""
+ return f"null control: {sides[0]['ref']}{at} vs itself"
+ if sides[0]["ref"] == sides[1]["ref"] and base_commit and treatment_commit:
+ return f"{sides[0]['ref']} {base_commit[:12]} -> {treatment_commit[:12]}"
+ return f"{sides[0]['ref']} -> {sides[1]['ref']}"
+
+
+def stop_owned_sides(
+ installs: list,
+ stop,
+ *,
+ keep: bool = False,
+) -> None:
+ """Stop every Studio THIS RUN launched. An attached one belongs to the caller and is left alone.
+
+ `installs` is the `(install, owns)` list the acquisition loop builds, so a side that has not
+ been reached yet is simply not in it. `keep` is `--keep-studio`, which asks for exactly this
+ leak.
+ """
+ if keep:
+ return
+ for side_install, side_owns in installs:
+ if side_owns and side_install is not None:
+ stop(side_install)
+
+
+def run(args, ab_ref = None) -> int:
+ from .fixture.corpus import Corpus
+ from .instruments import build as build_instruments # noqa: F401
+ from .pacer import Pacer
+ from .runtime import browser as browser_mod
+ from .runtime.bundle_guard import check_bundle
+ from .runtime.lifecycle import (
+ authenticate,
+ external_checkpoint_id,
+ install_studio,
+ launch_studio,
+ pacer_provider,
+ register_provider,
+ seed_init_script,
+ stop_studio,
+ wait_for_healthz,
+ )
+ from .runtime.seeder import Seeder
+ from .runtime.session import CellRunner, build_cells, ensure_probe_image, make_context
+ from .runtime import resources
+ from .runtime.types import Paths
+
+ out = Path(args.out or f"studiobench-{args.tier}-{int(time.time())}").resolve()
+ paths = Paths.under(out)
+ _log(f"studiobench {TOOL_VERSION} tier={args.tier} out={paths.out}")
+
+ corpus = Corpus.load()
+ _log(f" corpus_hash {corpus.corpus_hash}")
+
+ # BEFORE the first install, the first launch and the first recorded row. See `prepare_payload`:
+ # a refusal that arrives after two clones and two builds has cost the caller an hour to say
+ # something it could have said in a millisecond, and an archive that arrives after the Recorder
+ # has opened the file has already appended this run's header to the payload it was moving.
+ prepare_payload(
+ paths, requested_identity(args, ab_ref, corpus.corpus_hash), resume = bool(args.resume)
+ )
+
+ 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 = browser_mod.install_wall_clock_watchdog(
+ watchdog_deadline_s(
+ args.tier,
+ specs,
+ rungs = planned_rungs(args),
+ reps = args.reps,
+ surfaces = bool(args.surfaces),
+ ),
+ "studiobench",
+ _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
+ _log(f" A/B: base={args.branch} vs treatment={ab_ref}, interleaved in ONE session")
+
+ installs = []
+ sides = []
+ # EVERY SIDE THIS RUN LAUNCHED IS STOPPED WHEN THE SETUP AROUND IT FAILS. The sides are
+ # acquired one after another, so the base is already SERVING while the treatment clones and
+ # builds, and the cleanup that stops them both is the `finally` under the cells -- which a
+ # failure up here never reaches. The Studios are the resources that outlive this process:
+ # `launch_studio` detaches the server with `setsid -f`, so an abandoned one keeps its port.
+ # It is not idle there. Studio's own launcher ABORTS rather than binding when it finds one of
+ # its own servers on the requested port (`studio/backend/run.py`, `_resolve_port` with
+ # `avoid_own_studio`), so the next attempt's server exits and `wait_for_healthz` takes its 200
+ # from the STALE process: that run measures the build this one installed while `run_meta`
+ # records the ref it was asked for.
+ #
+ # A RETURN IS A FAILURE HERE TOO. The health check below and the development-build gate leave
+ # by returning, with both Studios up, which is the same abandoned server by a quieter route --
+ # so the guard is a `finally` on the whole of setup rather than an `except` on the install.
+ setup_complete = False
+ try:
+ for label, ref, attach, port, password in specs:
+ if attach:
+ side_url = attach.rstrip("/")
+ side_install, owns = None, False
+ _log(f" {label}: attaching to {side_url}")
+ else:
+ home = side_home(args.home, out, label, ab = bool(ab_ref))
+ _log(f" {label}: installing Studio from {ref} into {home} (this takes a while)")
+ side_install = install_studio(ref, home)
+ launch_studio(side_install, port, out / "logs" / f"studio_{label}.log")
+ side_url, owns = side_install.base_url, True
+ _log(f" {label}: Studio up at {side_url}")
+ installs.append((side_install, owns))
+ sides.append(
+ {
+ "label": label,
+ "ref": ref,
+ "base_url": side_url,
+ "owns": owns,
+ "password": password,
+ "commit": getattr(side_install, "commit", None) or "",
+ }
+ )
+
+ # THE BUILD, NOW THAT IT IS KNOWN. `prepare_payload` has already agreed the refs match,
+ # and a ref is a pointer: see `commit_problems`. This is the first moment the commit
+ # behind it exists, and it is still before the browser, the pacer and every cell, so a
+ # resume onto a moved branch costs the install it has already paid and nothing more.
+ if args.resume:
+ resolved = resolved_commits(sides)
+ commit_issues: list = []
+ for recorded in recorded_identities(paths.payload_jsonl):
+ for problem in commit_problems(recorded, resolved):
+ if problem not in commit_issues:
+ commit_issues.append(problem)
+ if commit_issues:
+ raise SystemExit(
+ f"refusing to resume {paths.payload_jsonl}: the ref matches but the build "
+ "does not.\n "
+ + "\n ".join(commit_issues)
+ + "\nThe cells already in this payload were measured on the commit it "
+ "records, and the rungs it still owes would be measured on the one installed "
+ "now, under one header naming one ref. Resume with the commit the payload "
+ "was recorded at, or re-run into a fresh --out."
+ )
+
+ base_url = sides[0]["base_url"]
+ install, owns_studio = installs[0]
+
+ for side in sides:
+ if not wait_for_healthz(side["base_url"], 60):
+ _log(f" FATAL: {side['base_url']}/healthz did not answer 200")
+ return 2
+
+ # ── THE GATE. Before anything else is measured. Both sides, because an A/B where one side
+ # is a development build is worse than no A/B: the 3.2x inflation lands entirely on one arm
+ # and reads as a colossal regression or win. ────────────────────
+ verdict = None
+ for side in sides:
+ side_verdict = check_bundle(side["base_url"])
+ _log(f" {side['label']} bundle: {side_verdict.reason}")
+ side["verdict"] = side_verdict
+ if verdict is None:
+ verdict = side_verdict
+ if not side_verdict.production and not args.allow_dev_server:
+ _log(
+ " REFUSING TO RUN. A development build inflates the very axis under "
+ "investigation"
+ )
+ _log(
+ " by about 3.2x, so a measurement here would confirm any hypothesis brought "
+ "to it."
+ )
+ _log(" Pass --allow-dev-server only to demonstrate that this gate matters.")
+ return 3
+
+ pacer = Pacer().start()
+ _log(f" pacer at {pacer.base_url}")
+ model_id = "studiobench-pacer"
+ pacer.state.model_ids = [model_id]
+
+ from .runtime.ab import origin_scoped
+
+ init_scripts = []
+ # ONE PROVIDER PER ORIGIN, because the provider lives in the BACKEND and localStorage is
+ # per-origin. An ATTACHED null control is `--attach U --attach-b U`, which `is_null_control`
+ # accepts on purpose: two sides, one Studio. Registering per SIDE there registers the pacer
+ # twice against the same backend, and `lifecycle.register_provider` is idempotent by DISPLAY
+ # NAME -- so the second registration DELETES the id the first side's seed script had already
+ # captured, and that script keeps selecting the dead id on every navigation it wins (the
+ # order init scripts run in is not defined, and `StudioAuth.rotate` re-adds them mid-run).
+ # A base cell that boots with a deleted provider selected renders "No longer offered" and
+ # throws `Connection not found` without ever asking for a completion.
+ registered: dict = {}
+ for index, side in enumerate(sides):
+ side_install = installs[index][0]
+ side_auth = authenticate(
+ side["base_url"],
+ args.username,
+ side["password"] or (side_install.bootstrap_password if side_install else ""),
+ )
+ _log(f" {side['label']}: authenticated as {side_auth.username}")
+
+ # BOTH sides register the SAME pacer, so the bytes on the wire are identical by
+ # construction rather than by two configurations that are meant to agree.
+ side_origin = side["base_url"].rstrip("/")
+ shared = registered.get(side_origin)
+ if shared is None:
+ side_provider = pacer_provider(pacer.base_url, [model_id])
+ # Registered in the BACKEND, and the id it assigns is what the selection names. See
+ # lifecycle.register_provider: a provider that exists only in localStorage renders
+ # in the picker as "No longer offered" and send throws `Connection not found`
+ # without ever asking for a completion.
+ register_provider(side["base_url"], side_auth, side_provider)
+ side_checkpoint = external_checkpoint_id(side_provider, model_id)
+ registered[side_origin] = (side_provider, side_checkpoint)
+ else:
+ side_provider, side_checkpoint = shared
+ _log(
+ f" {side['label']}: provider {side_provider.provider_type} -> "
+ f"{side_provider.base_url}, checkpoint {side_checkpoint}"
+ )
+ side["auth"] = side_auth
+
+ def _side_seed(
+ auth_now,
+ side = side,
+ provider = side_provider,
+ cp = side_checkpoint,
+ ):
+ return origin_scoped(
+ side["base_url"],
+ seed_init_script(
+ auth_now,
+ [provider],
+ extra_local_storage = {
+ # The SELECTION, without which nothing is ever generated. See
+ # lifecycle.external_checkpoint_id.
+ "unsloth_chat_last_external_checkpoint": cp,
+ "unsloth_chat_connections_enabled": "true",
+ },
+ ),
+ )
+
+ # Origin-gated even in the single-target case, so the one-build and two-build paths are
+ # the same code and the gate cannot rot while unused.
+ side["seed_script"] = _side_seed
+ init_scripts.append(_side_seed(side_auth))
+
+ auth = sides[0]["auth"]
+ init_scripts.append(resources.read_text("scene/dom.js"))
+ init_scripts.append(resources.read_text("scene/parity.js"))
+ # Loaded unconditionally, even without --surfaces. It defines selectors and reads dom.js and
+ # parity.js; it never runs on its own. Making the page's JS depend on a CLI flag would mean
+ # the flag changes what is on the page during the FILM as well, and the film's numbers must
+ # not depend on whether a later phase was asked for.
+ init_scripts.append(resources.read_text("scene/surfaces.js"))
+
+ procs_before = {}
+ try:
+ from .instruments.rss import new_roots, snapshot_children
+ procs_before = snapshot_children(os.getpid())
+ except Exception: # noqa: BLE001
+ new_roots = None # type: ignore[assignment]
+
+ bundle = browser_mod.launch(
+ args.engine, headless = not args.headed, init_scripts = init_scripts, log = _log
+ )
+ procs = []
+ if new_roots is not None:
+ time.sleep(1.0)
+ procs = new_roots(os.getpid(), procs_before)
+
+ # AN INIT SCRIPT IS A SNAPSHOT AND THE RUN OUTLIVES IT. The scripts above carry the access
+ # token this run logged in with, they re-run on EVERY navigation, and there is one
+ # navigation per cell -- so after `StudioAuth` re-mints a token, the next `page.goto` would
+ # write the DEAD one back over whatever the SPA had rotated to for itself, which is the
+ # failure this fixes wearing a different hat. Playwright has no way to replace an init
+ # script and does not define the order they run in, so the seed script decides for itself
+ # whether to write: it compares its token's `exp` against the one in storage and defers to
+ # the later one. See `seed_init_script`. At most one extra script per hour of run.
+ for side in sides:
+ side["auth"].on_rotate = lambda auth_now, side = side: bundle.context.add_init_script(
+ side["seed_script"](auth_now)
+ )
+
+ # WHAT WAS IN THE FILE BEFORE THIS SESSION COULD WRITE A BYTE. `make_context` opens the
+ # `Recorder` on the next line, and the only check left after that point -- the ladder ratio,
+ # which is not known until the corpus has been measured -- has to be able to put the payload
+ # back the way it found it. See `rollback_session_rows`.
+ mark = payload_mark(paths.payload_jsonl)
+ ctx, session = make_context(
+ bundle, base_url, args.tier, args.instrument_level, paths, _log, procs
+ )
+ rec = ctx.recorder
+ # The ladder this run PROMISED, resolved before it is announced. Recorded rather than
+ # left to be re-derived from the tier later: `--report` reads it back to decide which rungs
+ # a payload owes, and a `--rungs` override the payload did not carry made that answer wrong.
+ rungs = planned_rungs(args)
+ rec.emit(
+ {
+ "row_type": "run_meta",
+ "tier": args.tier,
+ "tool_version": TOOL_VERSION,
+ "corpus_hash": corpus.corpus_hash,
+ "studio_ref": args.branch if owns_studio else f"attached:{base_url}",
+ # WHICH COMMIT THAT REF NAMED, so a later `--resume` can tell a continuation from
+ # a branch that moved. Empty for an attached Studio, whose build is not visible
+ # from here. See `commit_problems`.
+ "studio_commit": sides[0].get("commit") or "",
+ "bundle": verdict.as_dict(),
+ "platform": {
+ "system": platform.system(),
+ "machine": platform.machine(),
+ "python": sys.version.split()[0],
+ "engine": bundle.engine,
+ "engine_note": bundle.engine_note,
+ },
+ "started_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
+ "pacer_base_url": pacer.base_url,
+ "cadence": args.cadence,
+ "rungs": rungs,
+ "tier_rungs": TIER_RUNGS[args.tier],
+ "reps": args.reps,
+ "instrument_level": args.instrument_level,
+ }
+ )
+ rec.gate("production_build", verdict.production, verdict.as_dict())
+
+ if args.tier == "fast":
+ # Said in the log AND recorded in the payload. A fast-tier reading is a DIRECTION, not
+ # a number: it runs one rung, a 47 s film and however few repetitions the caller asked
+ # for, so its detection floor is wider than the standard tier's and it has no null
+ # control of its own unless one is run alongside. The gate exists so the analysis layer
+ # can refuse to pool a fast payload with a standard one -- a fast reading quoted against
+ # a standard floor is the single most likely way this tier gets somebody a wrong answer.
+ _log("")
+ _log(" FAST TIER: for iteration while you are changing something, not for reporting.")
+ _log(
+ " One rung (100K), a 47s film. Use it to see whether a fix moved anything at all,"
+ )
+ _log(" then confirm with --tier standard and a null control before quoting a number.")
+ _log("")
+ rec.gate(
+ "reportable_tier",
+ args.tier != "fast",
+ {
+ "tier": args.tier,
+ "scene": TIER_RUNGS[args.tier],
+ "reason": (
+ "the fast tier is an iteration loop: one rung, a compressed film, and a "
+ "wider floor than the standard tier"
+ )
+ if args.tier == "fast"
+ else "standard measurement protocol",
+ },
+ )
+
+ image_path = ensure_probe_image(paths)
+ for side in sides:
+ side_seeder = Seeder(
+ base_url = side["base_url"], auth = side["auth"], model_id = model_id, log = _log
+ )
+ side["seeder"] = side_seeder
+ side["runner"] = CellRunner(
+ session = session,
+ pacer = pacer,
+ seeder = side_seeder,
+ corpus = corpus,
+ base_url = side["base_url"],
+ model_id = model_id,
+ tier = args.tier,
+ paths = paths,
+ log = _log,
+ cadence = args.cadence,
+ image_path = image_path,
+ )
+
+ seeder = sides[0]["seeder"]
+ runner = sides[0]["runner"]
+
+ if args.surfaces:
+ _sweep_surfaces(sides, ctx, paths)
+
+ # The ladder is sized by the ratio MEASURED on this corpus, not by the provisional 4.0.
+ # Measured here, before any cell is built, because a rung named in tokens is planned in
+ # characters and the ratio is what makes those the same claim.
+ cells = build_cells(
+ rungs,
+ corpus,
+ args.tier,
+ ctx.session_id,
+ args.instrument_level,
+ reps = args.reps,
+ base_url = sides[0]["base_url"],
+ auth = seeder.auth,
+ model_id = model_id,
+ log = _log,
+ )
+ if cells:
+ ladder_ratio = cells[0][0].meta["ladder_chars_per_token"]
+ rec.gate("ladder_ratio_measured", not ladder_ratio["provisional"], ladder_ratio)
+
+ # THE RATIO IS PART OF WHAT THE PAYLOAD MEASURED, and this is the first moment it is
+ # known -- the same shape as the commit check above, and for the same reason: the
+ # rungs already in the file were built at the ratio they record, the rungs still owed
+ # would be built at the one measured now, and one report prints both as one ladder.
+ if args.resume:
+ ratio_issues: list = []
+ for recorded in recorded_identities(paths.payload_jsonl):
+ for problem in ladder_ratio_problems(recorded, ladder_ratio["chars_per_token"]):
+ if problem not in ratio_issues:
+ ratio_issues.append(problem)
+ if ratio_issues:
+ # AND NOTHING THIS SESSION WROTE SURVIVES THE REFUSAL. Unlike the commit check
+ # above, this one runs after the `Recorder` has opened the payload, so refusing
+ # is not enough on its own: `run_meta` is already in the file and
+ # `recorded_ladder` folds every one of them, so a refused
+ # `--resume --rungs 1K,10K` would leave 10K promised and unrecorded in a
+ # payload that was complete. See `rollback_session_rows`.
+ rec.close()
+ rollback_session_rows(paths.payload_jsonl, mark)
+ raise SystemExit(
+ f"refusing to resume {paths.payload_jsonl}: the ladder is sized by a "
+ "different chars-per-token ratio than the cells already in it.\n "
+ + "\n ".join(ratio_issues)
+ + "\nA rung is named in tokens and built in characters, so the same rung "
+ "label would stand over two different character loads in one table. "
+ "Resume where the tokeniser answers as it did, or re-run into a fresh "
+ "--out."
+ )
+
+ done = _resume_set(paths) if args.resume else set()
+
+ if ab_ref:
+ from .runtime.ab import Target, interleave, order_is_balanced
+
+ targets = [
+ Target(
+ label = s["label"],
+ ref = s["ref"],
+ base_url = s["base_url"],
+ seeder = s["seeder"],
+ runner = s["runner"],
+ )
+ for s in sides
+ ]
+ work = interleave(cells, targets)
+ if not order_is_balanced(work):
+ # Said out loud rather than silently absorbed: with an odd number of reps one side
+ # always runs first, so anything drifting monotonically through the session lands on
+ # the other one instead of cancelling.
+ _log(
+ " WARNING: the run order is not balanced (use an even --reps). Linear drift "
+ "within the session is charged to whichever side runs second."
+ )
+ rec.emit(
+ {
+ "row_type": "ab_plan",
+ "base_ref": sides[0]["ref"],
+ "treatment_ref": sides[1]["ref"],
+ # WHICH SERVER THE TREATMENT WAS, when the caller attached one. `run_meta`
+ # already records the base that way in `studio_ref`; without the same for the
+ # treatment a resume can only compare the `--ab` label, which says nothing about
+ # the build that answered on the port. See `requested_identity`. Empty when this
+ # run installed the treatment itself: then the ref above is the identity.
+ "treatment_url": "" if sides[1]["owns"] else sides[1]["base_url"],
+ # The treatment's half of `studio_commit`. Same reason, same emptiness rule.
+ "treatment_commit": sides[1].get("commit") or "",
+ "balanced": order_is_balanced(work),
+ "order": [c.cell_id for _t, c, _p in work],
+ }
+ )
+ else:
+ work = [(None, cell, plan) for cell, plan in cells]
+
+ if done:
+ # AT PAIR GRANULARITY. An A/B pair whose two arms are not both recorded is re-run
+ # whole, so the resumed session never measures one arm on its own -- see
+ # `ab.skippable_cells`. For a run without --ab every pair holds one cell and this is the
+ # set it already was.
+ from .runtime.ab import skippable_cells
+ done = skippable_cells(work, done)
+ _log(f" resuming: {len(done)} cells already in {paths.payload_jsonl.name}")
+ setup_complete = True
+ finally:
+ if not setup_complete:
+ stop_owned_sides(installs, stop_studio, keep = args.keep_studio)
+
+ rows = []
+ resumed = 0
+ try:
+ for target, cell, plan in work:
+ if cell.cell_id in done:
+ _log(f" skipping {cell.cell_id} (already recorded)")
+ resumed += 1
+ continue
+ active = target.runner if target is not None else runner
+ if target is not None:
+ _log(f"\n### arm {target.label} ({target.ref}) at {target.base_url}")
+ rows.append(active.run(cell, plan))
+ finally:
+ for inst in session.instruments:
+ session._safe(inst, "detach")
+ try:
+ watchdog.cancel()
+ except Exception: # noqa: BLE001
+ pass
+ bundle.close()
+ pacer.stop()
+ stop_owned_sides(installs, stop_studio, keep = args.keep_studio)
+ rec.close()
+
+ if ab_ref:
+ # The cells THIS session was asked to measure. A resumed A/B skips whole pairs or none
+ # (`ab.skippable_cells`), so this is either every planned cell or none of them, and it is
+ # what `_render_ab` checks the payload against before it is allowed to print a verdict.
+ _render_ab(
+ paths,
+ sides,
+ ctx.session_id,
+ corpus.corpus_hash,
+ planned = [c.cell_id for _t, c, _p in work if c.cell_id not in done],
+ )
+
+ _summarise(rows, paths)
+ completed = sum(1 for r in rows if r.get("completed"))
+ _log(
+ f"\n{completed} of {len(rows)} cells completed"
+ + (f", {resumed} already complete in the payload" if resumed else "")
+ + f". payload: {paths.payload_jsonl}"
+ )
+ return completion_exit_code(rows, resumed)
+
+
+def _sweep_surfaces(sides: list, ctx, paths) -> None:
+ """The optional surface phase: one sweep per arm, BEFORE the cells.
+
+ Before, not after, and on an empty chat rather than a seeded one. Several surface roots
+ contain the keep-alive chat page, so a sweep taken after the film would carry that film's
+ thread -- and the two messages its last actions deleted -- into the digest of every route and
+ every menu. Running first makes the surface digests about the surfaces.
+
+ A failure here never costs the run. The sweep is additional evidence about the UI; the cells
+ are the measurement, and a broken selector in the registry must not stop them.
+ """
+ from .scene.surface_sweep import render_manifest, sweep
+ for side in sides:
+ label = side["label"]
+ _log(f"\n### surface sweep: {label} at {side['base_url']}")
+ try:
+ rows, manifest = sweep(
+ ctx.page,
+ side["base_url"],
+ log = _log,
+ cell_id = f"surfaces.{label}",
+ recorder = ctx.recorder,
+ )
+ except Exception as exc: # noqa: BLE001
+ # Recorded as a failed gate rather than swallowed. A sweep that raised and a sweep
+ # that found nothing look identical in a payload that only carries the rows.
+ _log(f" the surface sweep failed: {type(exc).__name__}: {exc}")
+ ctx.recorder.gate(
+ f"surface_sweep:{label}", False, {"error": f"{type(exc).__name__}: {exc}"}
+ )
+ continue
+ for row in rows:
+ row["arm"] = label
+ text = render_manifest(manifest)
+ print("\n" + text)
+ out = paths.out / f"surfaces_{label}.md"
+ out.write_text(text, encoding = "utf-8")
+ _log(f"surface coverage manifest written to {out}")
+ # PASSES only when every non-conditional surface was reached AND the digests were scoped.
+ # An unscoped sweep reports one page-wide digest per surface, which agrees everywhere for
+ # reasons that have nothing to do with the surfaces.
+ passed = manifest["not_reached_hard"] == 0 and manifest["digests_scoped"]
+ ctx.recorder.gate(f"surface_sweep:{label}", passed, manifest)
+
+
+def _render_ab(
+ paths,
+ sides,
+ session_id: str,
+ corpus_hash: str,
+ planned = (),
+) -> None:
+ """Render the A/B table from the payload the run just wrote.
+
+ Read back from disk rather than kept in memory on purpose: it is the same path a tester takes
+ with `--report`, so the table nobody checks and the table everybody reads are produced by one
+ piece of code.
+
+ NO VERDICT OVER A PLAN WITH A HOLE IN IT. `planned` is the cells this session was asked to
+ measure, and a failed cell does not stop the run -- `CellRunner.run` records the failure and
+ returns -- so without this check the comparison is rendered over whatever pairs survived. See
+ `ab.unmeasured_planned_cells`: the loss is not the failed cell but its healthy partner, which
+ the arm intersection removes silently.
+ """
+ from .report.render import render_ab_table
+ from .runtime.ab import compare_arms, unmeasured_planned_cells
+
+ records = []
+ with paths.payload_jsonl.open(encoding = "utf-8") as fh:
+ for line in fh:
+ try:
+ records.append(json.loads(line))
+ except ValueError:
+ continue
+
+ out = paths.out / "ab.md"
+ # A FULLY RESUMED A/B MEASURED NOTHING OF ITS OWN. `--resume` against a finished output skips
+ # every cell and is a success, but the ratio is scoped to THIS session, so re-rendering here
+ # replaced a real table with NO READING and exited 0 while doing it. The run that measured
+ # keeps its report; a run with no prior table still gets one, since there is nothing to lose.
+ if not any(r.get("row_type") == "cell" and r.get("session_id") == session_id for r in records):
+ if out.exists():
+ _log(f"\nno cell ran in this session; keeping the A/B table already at {out}")
+ return
+
+ # Detected, not declared. `--ab main` IS a null control whether or not the caller says so, and
+ # a null control that renders as an ordinary A/B invites somebody to quote "7.7% faster" from a
+ # build compared with itself. See `is_null_control`.
+ is_null = is_null_control(sides)
+ label = _ab_label(sides, is_null)
+
+ try:
+ result = compare_arms(
+ records,
+ sides[0]["label"],
+ sides[1]["label"],
+ bench_version = TOOL_VERSION,
+ corpus_hash = corpus_hash,
+ session_id = session_id,
+ label = label,
+ is_null_control = is_null,
+ )
+ except Exception as exc: # noqa: BLE001
+ _log(f"\nA/B table could not be built: {type(exc).__name__}: {exc}")
+ return
+
+ missing = unmeasured_planned_cells(records, planned, session_id = session_id)
+ if missing:
+ result.void = True
+ result.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)
+ )
+
+ text = render_ab_table(result)
+ print("\n" + text)
+ out.write_text(text, encoding = "utf-8")
+ _log(f"A/B table written to {out}")
+ if missing:
+ # A noise floor derived from a partial null control is a number about the cells that did
+ # not die, quoted afterwards at every real A/B on this machine.
+ _log("the plan did not complete, so no noise floor is derived from it")
+ return
+ if is_null:
+ from .scoring.ab import noise_floor_from_null_control
+ try:
+ floor, source = noise_floor_from_null_control(result)
+ _log(
+ f"THIS MACHINE'S NOISE FLOOR: {floor:.1f}% ({source}). Pass it to a real A/B; "
+ f"a difference smaller than this is not a difference."
+ )
+ except Exception as exc: # noqa: BLE001
+ _log(f"could not derive a noise floor from the null control: {exc}")
+ else:
+ _log(
+ "NOTE: no null control (base vs base) was run, so the noise floor here is the "
+ "declared default and not this machine's. A win inside that floor is not a win."
+ )
+
+
+#: THE PAYLOAD IDENTITY. The axes that decide whether a cell already in a payload measures the
+#: same thing a new invocation is asking for.
+#:
+#: `cell_id` is `r{rung}.{arm}.rep{rep}` and nothing else, so every one of these can change under a
+#: cell id that stays identical: the tier picks the FILM (the standard film runs 243 s, the quick
+#: one 77.5 s and the fast one 47 s, with different budgets), the cadence picks the rate the reply
+#: streams at, the instrument level decides how much of the number is the instrument, the corpus
+#: hash is the fixture, the engine is what rendered every frame, and the two refs are the builds
+#: under test.
+#:
+#: `rungs` and `reps` are deliberately NOT here. Resuming with more repetitions or another rung is
+#: a legitimate continuation -- it ADDS cells rather than reinterpreting the ones already recorded.
+IDENTITY_AXES = (
+ "tier",
+ "cadence",
+ "engine",
+ "instrument_level",
+ "corpus_hash",
+ "studio_ref",
+ "treatment_ref",
+ "treatment_url",
+)
+
+#: The axes that describe the SECOND side, which only exist when a run has one. See
+#: `identity_problems`: an A/B judged against a run that is not one may not differ on them.
+TREATMENT_AXES = ("treatment_ref", "treatment_url")
+
+#: THE RATIO THE LADDER WAS SIZED BY, carried on every cell's `meta` by `session.build_cells`.
+#: Not in `IDENTITY_AXES`: those are checked by `prepare_payload` before anything is installed,
+#: and this one is not known until `build_cells` has measured the corpus. Checked instead by
+#: `ladder_ratio_problems`, on the same footing as `COMMIT_AXES` -- late enough to have the answer,
+#: early enough that nothing has been measured under it.
+LADDER_RATIO_AXIS = "ladder_chars_per_token"
+
+#: How close two ratios must be to be the same ratio. `measure_chars_per_token` rounds its answer
+#: to three decimals and `PROVISIONAL_CHARS_PER_TOKEN` is exact, so every value that reaches a
+#: payload sits on a 0.001 grid: half a grid step separates "the same measurement, re-read through
+#: JSON" from "a different one". Wide enough that 5.0 never refuses 5.0 for a float's sake, narrow
+#: enough that the case this exists for -- a provisional 4.0 against tiktoken's 3.336 on this
+#: corpus, a fifth of the character load of every rung -- can never be inside it.
+LADDER_RATIO_TOLERANCE = 5e-4
+
+#: The arm a run without `--ab` records every cell under. `Cell.arm` in `runtime.types`; an A/B
+#: overwrites it with the target's label, `base` or `treatment`. Named here because it is what
+#: tells `recorded_identities` which of the two a session already in the payload was.
+SINGLE_ARM = "A0"
+
+#: THE BUILD, as opposed to the name it was asked for by. A ref is a POINTER: `main`, a topic
+#: branch and a movable tag all resolve afresh on every install, and `checkout_ref` is the only
+#: thing that ever knows which commit one named. So these are not in `IDENTITY_AXES` and are not
+#: checked by `prepare_payload`: that refusal is deliberately made BEFORE anything is installed,
+#: and a commit cannot be known before the fetch that resolves it. They are checked instead by
+#: `commit_problems`, once the sides are up and before the first cell -- late enough to have the
+#: answer, early enough that nothing has been measured under it. See `run`.
+COMMIT_AXES = ("studio_commit", "treatment_commit")
+
+
+def requested_identity(args, ab_ref, corpus_hash: str) -> dict:
+ """The payload identity THIS invocation is asking for.
+
+ `studio_ref` is spelled exactly as `run_meta` records it, so the requested value and the
+ recorded one are comparable without a second convention to keep in step.
+ """
+ from .runtime.browser import default_engine
+
+ base_ref = f"attached:{args.attach.rstrip('/')}" if args.attach else args.branch
+ attach_b = (getattr(args, "attach_b", "") or "").rstrip("/")
+ return {
+ "tier": args.tier,
+ "cadence": args.cadence,
+ # THE ENGINE THAT WILL RENDER, not the flag that asked for it. `--engine` defaults to
+ # nothing and `browser.launch` resolves the platform's desktop webview family, so the
+ # requested value has to be resolved the same way `launch` resolves it -- otherwise the
+ # commonest engine change of all, one run naming `--engine chromium` and the resume
+ # naming none, reads as no difference at all. Resolvable here, before anything is
+ # installed, because `default_engine` reads `platform.system()` and nothing else.
+ "engine": getattr(args, "engine", "") or default_engine()[0],
+ "instrument_level": args.instrument_level,
+ "corpus_hash": corpus_hash,
+ "studio_ref": base_ref,
+ "treatment_ref": ab_ref or "",
+ # THE ATTACHED TREATMENT IS THE SERVER, NOT THE LABEL. `studio_ref` folds an attached base
+ # down to its URL because that is the only thing about it this harness can see; the
+ # treatment carried nothing but the name typed after `--ab`, and that name is free. So
+ # `--attach A --attach-b B --ab fix --resume`, re-run later against `--attach-b C`, passed
+ # the identity check, skipped every completed treatment cell and reported B's measurements
+ # as C's result. Empty for a treatment this run installs itself, whose ref IS its identity.
+ "treatment_url": attach_b if (ab_ref and attach_b) else "",
+ }
+
+
+def recorded_identities(payload_path) -> list:
+ """One identity per session already in the payload, from the rows those sessions wrote.
+
+ Read out of `run_meta` (including its nested `platform.engine`), `ab_plan` and the cells
+ rather than out of a new field, so a payload written before this check existed is judged on
+ exactly the axes it DID record: an axis a row never declared cannot be a difference, and an
+ older output therefore still resumes.
+
+ `mode` is the one entry here that is not an axis of any single row. It is what the session's
+ cells were recorded under, which is the thing `identity_problems` has to compare and the only
+ thing the payload states about it. See `SINGLE_ARM`.
+ """
+ by_session: dict = {}
+ order: list = []
+ path = Path(payload_path)
+ if not path.exists():
+ return []
+ with path.open(encoding = "utf-8") as fh:
+ for line in fh:
+ try:
+ row = json.loads(line)
+ except ValueError:
+ continue
+ row_type = row.get("row_type")
+ if row_type not in ("run_meta", "ab_plan", "cell"):
+ continue
+ session = str(row.get("session_id"))
+ if session not in by_session:
+ by_session[session] = {}
+ order.append(session)
+ if row_type == "cell":
+ # THE MODE A SESSION MEASURED IN, declared by the cells it actually wrote rather
+ # than by a header it wrote before it measured anything. A run that died between
+ # `run_meta` and `ab_plan` recorded no cells and so declares no mode, and resuming
+ # it is not a transition; a session holding cells declares the mode those cells
+ # were recorded under, whichever row types the version that wrote them emitted.
+ arm = str((row.get("cell") or {}).get("arm") or row.get("arm") or "")
+ if arm:
+ by_session[session].setdefault("mode", "single" if arm == SINGLE_ARM else "ab")
+ # THE RATIO THE SESSION'S RUNGS WERE SIZED BY, on the same rule as the mode: read
+ # off a cell the session actually wrote, so a session that recorded none declares
+ # none. See `ladder_ratio_problems`.
+ sized = ((row.get("cell") or {}).get("meta") or {}).get("ladder_chars_per_token")
+ if isinstance(sized, dict) and sized.get("chars_per_token") is not None:
+ by_session[session].setdefault(
+ LADDER_RATIO_AXIS, float(sized["chars_per_token"])
+ )
+ continue
+ for axis in IDENTITY_AXES + COMMIT_AXES:
+ if axis in row:
+ by_session[session][axis] = row[axis]
+ # THE ENGINE IS NESTED, under `run_meta.platform`, so the loop above cannot see it.
+ # Read from there rather than from a new top-level field for the same reason as
+ # everything else here: a payload written before this check existed still declares
+ # what it rendered with, and is judged on it. `run_meta` is emitted AFTER
+ # `browser.launch` returns, so what is recorded is the RESOLVED engine and a session
+ # that never got a browser up declares none -- and an axis a row never declared
+ # cannot be a difference, so that session still resumes.
+ if row_type == "run_meta":
+ engine = str((row.get("platform") or {}).get("engine") or "")
+ if engine:
+ by_session[session]["engine"] = engine
+ # `ab_plan` is where the treatment ref is recorded; `run_meta` names only the base.
+ if row_type == "ab_plan" and row.get("treatment_ref") is not None:
+ by_session[session]["treatment_ref"] = row["treatment_ref"]
+ return [by_session[s] for s in order if by_session[s]]
+
+
+def identity_problems(recorded: dict, requested: dict) -> list:
+ """Every axis on which a recorded session and this invocation disagree."""
+ problems = []
+ # AN A/B AND A RUN THAT IS NOT ONE MAY NOT SHARE A PAYLOAD. The arm in the cell id ("A0"
+ # against "base"/"treatment") keeps the new cells from being SKIPPED, which is why this used
+ # to be waved through -- but it does not keep them out of each other's REPORT. `score_payload`
+ # hands every cell to `measures_from_records`, which keys by rung and keeps the first reading,
+ # and `_completion_by_rung` keeps a failure over a success at the same rung. So a single-build
+ # run that died at 10K, resumed as `--ab fix` and re-measured successfully on both arms, still
+ # printed `INCOMPLETE: the base died at 10K`, scored the rung 0 and reported ONSET RUNG: none,
+ # while the identical resume WITHOUT `--ab` -- same crash, same repair, same cell id, so the
+ # dead attempt is superseded -- scored it 82.2. The mode is part of what a payload measures,
+ # so a run that changes it resumes nothing: it starts a payload of its own.
+ requested_mode = "ab" if requested.get("treatment_ref") else "single"
+ recorded_mode = recorded.get("mode")
+ if recorded_mode is not None and recorded_mode != requested_mode:
+ names = {"ab": "an A/B (base against treatment)", "single": "one build on its own"}
+ problems.append(
+ f"mode: the payload was recorded by a run measuring {names[recorded_mode]}, "
+ f"this run measures {names[requested_mode]}"
+ )
+ # Is there a second side on BOTH sides of this comparison? When there is not, the treatment
+ # axes describe a side one of them does not have, and the mode difference above is the whole
+ # of what they disagree on. Decided from the ref, so that an A/B whose treatment this run
+ # installed -- which records no treatment URL -- is still judged against an attached one on
+ # the axis where the two of them do differ.
+ both_ab = bool(requested.get("treatment_ref")) and bool(recorded.get("treatment_ref"))
+ for axis in IDENTITY_AXES:
+ if axis not in recorded:
+ # An axis this payload never declared. See `recorded_identities`.
+ continue
+ if axis in TREATMENT_AXES and not both_ab:
+ continue
+ want, got = requested.get(axis), recorded[axis]
+ if str(want) != str(got):
+ problems.append(
+ f"{axis}: the payload was recorded with {got!r}, this run asks {want!r}"
+ )
+ return problems
+
+
+def resolved_commits(sides: list) -> dict:
+ """The commits the sides of THIS run were actually installed from. `""` when unknowable.
+
+ Unknowable for an attached Studio: the caller pointed this harness at a URL and nothing about
+ what is deployed behind it is visible from here, which is why `studio_ref` folds an attached
+ base down to that URL instead.
+ """
+ out = {axis: "" for axis in COMMIT_AXES}
+ for axis, side in zip(COMMIT_AXES, sides):
+ if side.get("owns"):
+ out[axis] = str(side.get("commit") or "")
+ return out
+
+
+def commit_problems(recorded: dict, resolved: dict) -> list:
+ """Every side on which a recorded session and this invocation installed a different BUILD.
+
+ `--resume` skips a completed `cell_id`, and a cell id is the rung, the arm and the repetition.
+ The identity check in `prepare_payload` keeps the REFS in step, and a ref is enough right up
+ until it moves: `--branch main --ab fix --resume` into a payload recorded yesterday passes
+ every axis while `main` has advanced, so the cells already in the file were measured on one
+ build and the rungs still owed are measured on another, and `report.assemble_rows` prints the
+ mixture under a single header naming one ref. Movable tags and any live topic branch do the
+ same thing; `unsloth/main` does it several times a day.
+
+ An empty commit on EITHER side is not a difference. A payload written before this was recorded
+ never declared it -- the same rule `recorded_identities` applies to every other axis -- and an
+ attached side has no commit to declare, so attaching does not start failing against a payload
+ that a self-managed run wrote.
+ """
+ problems = []
+ for axis in COMMIT_AXES:
+ want, got = str(resolved.get(axis) or ""), str(recorded.get(axis) or "")
+ if not want or not got or want == got:
+ continue
+ side = "the base" if axis == "studio_commit" else "the treatment"
+ problems.append(
+ f"{axis}: {side} was recorded at commit {got[:12]}, this run installed {want[:12]}"
+ )
+ return problems
+
+
+def ladder_ratio_problems(recorded: dict, measured: float) -> list:
+ """Whether the rungs this run is about to build carry the character load the payload's do.
+
+ A rung is NAMED in tokens and BUILT in characters, and the chars-per-token ratio is the only
+ thing that makes those the same claim. It is measured afresh on every invocation, `--resume`
+ included, and it is not fixed by anything the identity check already pins: `corpus_hash` is the
+ frozen fixture's own hash and says nothing about how many tokens a tokeniser reads out of it,
+ and `session.ladder_chars_per_token` falls back to `PROVISIONAL_CHARS_PER_TOKEN` whenever no
+ real tokeniser answers. tiktoken is not a dependency of this harness, and even where it is
+ installed `get_encoding` fetches `cl100k_base` over the network on first use, so "no tokeniser
+ answered" is one absent package or one unlucky minute, not a hypothetical.
+
+ So: a run on a machine with no tokeniser sizes every rung at 4.0 and dies at 100K; the resume
+ finds tiktoken and sizes at 3.336. `_resume_set` skips the completed cells by `cell_id`, which
+ is `r{rung}.{arm}.rep{rep}` and carries no ratio, so 1K and 10K stay at 4,000 and 40,000
+ characters while 100K and 1M are built at 333,600 and 3,336,000 -- a sixth less load per rung
+ on the second half of the ladder. Nothing downstream can see the mixture: `score_payload` keys
+ by rung, the report prints one ladder, and ONSET RUNG names a token label that means two
+ different amounts of work in the same table.
+
+ A ratio the payload never recorded is not a difference, the rule `recorded_identities` applies
+ to every other axis: a payload written before the ratio travelled on `meta` still resumes. See
+ `LADDER_RATIO_TOLERANCE` for what counts as the same ratio.
+ """
+ got = recorded.get(LADDER_RATIO_AXIS)
+ if got is None or measured is None:
+ return []
+ if abs(float(got) - float(measured)) <= LADDER_RATIO_TOLERANCE:
+ return []
+ return [
+ f"{LADDER_RATIO_AXIS}: the payload's rungs were sized at {float(got)!r} characters per "
+ f"token, this run measures {float(measured)!r}"
+ ]
+
+
+def archive_payload(paths, log = _log):
+ """Move an existing payload aside so a FRESH run starts a file of its own. `None` when empty.
+
+ APPEND MODE IS FOR VALIDATED RESUMES ONLY. `Recorder` opens the payload with `"a"`, so a second
+ invocation into the same `--out` used to write its rows behind the first run's. That is exactly
+ right for `--resume`, which re-runs the cells that died under the same deterministic `cell_id`
+ so `latest_attempt_rows` can supersede them -- and it is wrong for every other reuse, because
+ superseding only reaches the cell ids the new run REACHED. A fresh run that is interrupted
+ leaves the previous run's cells standing in the rungs it never got to, `report.assemble_rows`
+ takes its header from the FIRST `run_meta` in the file, and `--report` then scores one ladder
+ whose rungs came from two builds under two different films without a word about it.
+
+ Moved rather than truncated: the previous run's payload is the previous run's evidence, and the
+ fix for reporting a mixture may not be to delete half of it.
+ """
+ src = Path(paths.payload_jsonl)
+ try:
+ if not src.exists() or src.stat().st_size == 0:
+ return None
+ stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(src.stat().st_mtime))
+ except OSError:
+ return None
+ dest = src.with_name(f"{src.stem}-{stamp}{src.suffix}")
+ index = 1
+ while dest.exists():
+ dest = src.with_name(f"{src.stem}-{stamp}.{index}{src.suffix}")
+ index += 1
+ src.rename(dest)
+ log(f" a payload was already in this output directory; moved it to {dest.name}")
+ log(" (this run starts a payload of its own. Pass --resume to CONTINUE the previous one.)")
+ return dest
+
+
+def payload_mark(payload_path) -> int:
+ """How long the payload was BEFORE this session was allowed to append to it.
+
+ Taken before the `Recorder` opens the file, and paired with `rollback_session_rows`. See there
+ for what the pair is for; `0` for a payload that does not exist yet, which is the length it
+ has.
+ """
+ try:
+ return Path(payload_path).stat().st_size
+ except OSError:
+ return 0
+
+
+def rollback_session_rows(
+ payload_path,
+ mark: int,
+ log = _log,
+) -> int:
+ """Undo everything this session appended, back to `mark`. The bytes dropped.
+
+ THE RULE `prepare_payload` STATES: a refusal has to leave the payload it refused exactly as it
+ found it. `prepare_payload` and `commit_problems` keep it by running before the `Recorder`
+ exists -- the identity axes are known from the CLI, and the commit is known once the sides are
+ installed, both still before the first recorded row. `ladder_ratio_problems` cannot: the ratio
+ is not known until `build_cells` has measured the corpus, which is after `make_context` has
+ opened the file, written `run_meta` and possibly a failed `instrument_unavailable` gate, and
+ after an optional `--surfaces` sweep. So that check keeps the same rule from the other end.
+
+ What a refused resume costs if it does not. `recorded_ladder` folds the `rungs` of EVERY
+ `run_meta` in the file, deliberately -- a session killed after its header still owes what it
+ promised -- so a refused `--resume --rungs 1K,10K` over a finished 1K payload leaves 10K
+ promised and never recorded, and `--report` scores that payload INCOMPLETE from then on.
+ `excluded_from_rows` turns every failed gate into an excluded cell, so the refused session's
+ own `ladder_ratio_measured` gate is charged to the payload it never touched. Neither is
+ recoverable by re-running: the rows are in somebody else's evidence file.
+
+ TRUNCATED, NOT ARCHIVED, which is the opposite of `archive_payload` and for the reason that
+ makes it the opposite: an archive preserves a run's evidence, and a refused resume produced no
+ evidence. There is one writer -- `Recorder` is the only thing that opens this file, on the main
+ thread, and it is closed by the caller before this runs -- so the tail being dropped is this
+ session's rows and nothing else.
+ """
+ path = Path(payload_path)
+ try:
+ size = path.stat().st_size
+ except OSError:
+ return 0
+ if size <= mark:
+ return 0
+ try:
+ os.truncate(path, mark)
+ except OSError as exc:
+ log(f" could not roll back {path.name}: {exc}")
+ return 0
+ dropped = size - mark
+ log(f" rolled back {dropped} bytes this refused session had appended to {path.name}")
+ return dropped
+
+
+def prepare_payload(
+ paths,
+ requested: dict,
+ *,
+ resume: bool,
+ log = _log,
+):
+ """What happens to an `--out` that already holds a payload. Called BEFORE anything is installed.
+
+ Before, because both answers are worthless afterwards: the refusal below has to arrive before
+ the caller has paid for a clone and a build -- an A/B installs TWO -- and the archive has to
+ happen before this run's `Recorder` opens the file it would otherwise append to.
+
+ TWO REUSES, TWO ANSWERS.
+
+ A fresh run archives (see `archive_payload`).
+
+ A `--resume` continues, and is REFUSED when the payload was recorded under a different identity.
+ `--resume` skips every `cell_id` the payload already completed, and a cell id encodes the rung,
+ the arm and the repetition -- not the tier, the cadence, the instrument level, the corpus or
+ either ref. So resuming after changing one of those skips cells that measured something else:
+ at the extreme, `--branch main --ab other --resume` into a directory holding a finished
+ `main -> fix` run installs and launches two Studios, skips every cell, exits 0, and leaves the
+ OLD comparison standing in `ab.md` for somebody to read as the answer for `other`.
+ """
+ if not resume:
+ return archive_payload(paths, log = log)
+
+ problems: list = []
+ for recorded in recorded_identities(paths.payload_jsonl):
+ for problem in identity_problems(recorded, requested):
+ if problem not in problems:
+ problems.append(problem)
+ if problems:
+ raise SystemExit(
+ f"refusing to resume {paths.payload_jsonl}: it was not recorded by a run of this "
+ "configuration.\n "
+ + "\n ".join(problems)
+ + "\nA cell id is the rung, the arm and the repetition, so resuming here would skip "
+ "cells that measured something else and report the mixture as one run. Re-run into a "
+ "fresh --out, or resume with the configuration the payload was recorded under."
+ )
+ return None
+
+
+def _resume_set(paths) -> set:
+ """The cells `--resume` may skip: the ones whose LATEST attempt completed.
+
+ THE LATEST ATTEMPT DECIDES, which is the rule `latest_attempt_rows` already applies for the
+ score (`report.build.score_payload`), the ratio (`ab.readings_by_arm`), the surface parity
+ sweep and `--assert-liveness`. Read raw, this loop was the last reader in which a superseded
+ row still counted -- and it counted in the direction that skips work.
+
+ How that happens without anybody doing anything unusual: an A/B pair is re-run WHOLE
+ (`ab.skippable_cells`), so a resume re-runs an arm that had already succeeded. If that retry
+ fails while its partner succeeds, the payload holds a completed row and a LATER failed row
+ under the same deterministic `cell_id`. The next `--resume` found the old success, skipped the
+ whole pair and exited 0, while `--report` scored the failed retry INCOMPLETE and
+ `--assert-liveness` failed on it. A resume that can never re-run the cell that is broken is a
+ gate nobody can satisfy by fixing the run.
+ """
+ from .scoring.from_payload import latest_attempt_rows
+
+ done = set()
+ if not paths.payload_jsonl.exists():
+ return done
+ records = []
+ with paths.payload_jsonl.open(encoding = "utf-8") as fh:
+ for line in fh:
+ try:
+ records.append(json.loads(line))
+ except ValueError:
+ continue
+ for row in latest_attempt_rows(records):
+ # Only a COMPLETED cell is skipped. A cell that died is re-run, because its failure
+ # may have been the machine and not the build.
+ if row.get("row_type") == "cell" and row.get("completed"):
+ done.add(row.get("cell_id"))
+ return done
+
+
+def _summarise(rows: list, paths) -> None:
+ if not rows:
+ return
+ _log("\n" + "=" * 78)
+ _log(
+ f"{'cell':<16} {'chars':>10} {'elems':>8} {'spans':>8} {'c/span':>7} "
+ f"{'ran':>6} {'miss':>5} {'exp!':>5} {'busy%':>7}"
+ )
+ _log("-" * 78)
+ for r in rows:
+ actions = r.get("actions") or []
+ ran = sum(1 for a in actions if a.get("ran"))
+ # The PEAK, not the end state: the film's last two actions reopen the thread and delete
+ # a message, so an end-of-film census describes a thread that is no longer there.
+ census = r.get("census_peak") or r.get("census_after") or {}
+ _log(
+ f"{r['cell_id']:<16} {r.get('assistant_chars_in_dom') or 0:>10,} "
+ f"{census.get('elements') or 0:>8,} {census.get('highlight_spans') or 0:>8,} "
+ f"{str(r.get('chars_per_span') or '-'):>7} "
+ f"{ran}/{len(actions):>4} {r.get('slots_missed', 0):>5} "
+ f"{r.get('expect_failures', 0):>5} "
+ f"{'-' if not r.get('completed') else 'ok':>7}"
+ )
+ if not r.get("completed"):
+ f = r.get("failure") or {}
+ _log(f" FAILED: {f.get('kind')}: {str(f.get('message'))[:100]}")
+
+
+def _rung_tokens(labels: list) -> list:
+ """`1K` -> 1000. The scoring ladder is indexed by tokens; the CLI speaks in rung labels."""
+ mult = {"K": 1_000, "M": 1_000_000}
+ out = []
+ for label in labels:
+ text = str(label).strip().upper()
+ out.append(int(float(text[:-1]) * mult[text[-1]]) if text[-1] in mult else int(text))
+ return out
+
+
+def recorded_ladder(path) -> list:
+ """The rungs the RUN promised, folded over EVERY `run_meta` the payload carries. `[]` when it
+ never said.
+
+ A payload knows which ladder it was collecting; the CLI only knows which tier the caller
+ happened to type. Reporting a standard run that was killed before its top cell under the
+ default tier scored the surviving low rungs and never mentioned the missing one, which is the
+ crash-beats-limp failure `report/build.py` exists to refuse, arriving through the front door.
+
+ FOLDED, NOT THE FIRST HEADER, because a resume is allowed to ADD rungs -- `rungs` is
+ deliberately not a payload identity axis, and `--resume --rungs 1K,10K` over a finished 1K run
+ appends a second `run_meta` promising both. Reading the first one alone meant a continuation
+ killed after that header and before the 10K cell reported the 1K ladder it had already finished
+ and scored COMPLETE, which is the same truncated run passing as a whole one. Every rung any
+ session in this file promised is owed by it, and one it never reached is scored INCOMPLETE
+ rather than dropped.
+ """
+ ladder: list = []
+ try:
+ with Path(path).open(encoding = "utf-8") as fh:
+ for line in fh:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ row = json.loads(line)
+ except ValueError:
+ continue
+ if row.get("row_type") != "run_meta":
+ continue
+ rungs = row.get("rungs") or TIER_RUNGS.get(str(row.get("tier"))) or []
+ for rung in rungs:
+ if str(rung) not in ladder:
+ ladder.append(str(rung))
+ except OSError:
+ return []
+ return ladder
+
+
+def report_only(args) -> int:
+ """Score and render a payload that already exists. No browser, no Studio, no network.
+
+ Separate from `run` so a payload produced on somebody else's desktop reports identically here,
+ which is the whole point of shipping a single-file benchmark: the numbers come back as a file
+ and the analysis happens where the analyst is.
+ """
+ from .report.build import build_report
+
+ path = Path(args.report)
+ if not path.exists():
+ _log(f"no payload at {path}")
+ return 2
+
+ # `--rungs` first, then the payload's own ladder, then the tier. An explicit `--tier` still
+ # wins over the recording, so a reader can deliberately score a payload against another tier's
+ # ladder; what is gone is the DEFAULT tier silently shortening somebody else's run.
+ recorded = [] if getattr(args, "tier_explicit", True) else recorded_ladder(path)
+ if args.rungs:
+ declared = _rung_tokens(args.rungs.split(","))
+ elif recorded:
+ declared = _rung_tokens(recorded)
+ _log(f"scoring against the ladder this run recorded: {','.join(recorded)}")
+ else:
+ declared = _rung_tokens(TIER_RUNGS[args.tier])
+ try:
+ text, ladder, _payload = build_report(path, declared)
+ except Exception as exc: # noqa: BLE001
+ # A payload that cannot be scored is reported as such rather than half-rendered: a
+ # partial report is exactly the artefact that gets quoted without its caveats.
+ _log(f"could not build a report from {path}: {type(exc).__name__}: {exc}")
+ return 1
+
+ print(text)
+ out = path.parent / "summary.md"
+ out.write_text(text, encoding = "utf-8")
+ _log(f"summary written to {out}")
+ return 0
+
+
+def assert_liveness(args) -> int:
+ """Fail unless every scheduled action in a payload actually ran.
+
+ THE FAILURE THIS CATCHES. The most expensive wrong answers this harness has produced were not
+ wrong numbers, they were absent ones reported as "no effect": four scene actions recorded NOT
+ RUN on 312 of 312 attempts because their slots opened while a follow-up turn was still
+ streaming, and read as fast, stable and meaningless. A surface crawler walked 53 surfaces that
+ would all have digested the same mounted root. An overlay walk could never fire.
+
+ Every one of those is invisible to a test that only checks the run exited 0, and every one of
+ them is visible here, because `session.py` already counts `actions_not_run` and `slots_missed`
+ per cell. This turns the README's advice to check `ran` before reading a timing into something
+ a machine does, which is the only way it gets done every time.
+
+ Offline, so a payload from anyone's laptop or from CI checks identically.
+ """
+ path = Path(args.assert_liveness)
+ if not path.exists():
+ _log(f"no payload at {path}")
+ return 2
+
+ allowed = {a.strip() for a in (args.allow_not_run or "").split(",") if a.strip()}
+ rows, problems = [], []
+ for line in path.read_text(encoding = "utf-8").splitlines():
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ rows.append(json.loads(line))
+ except ValueError:
+ problems.append("a payload line is not valid JSON")
+
+ # A CELL THAT WAS RE-RUN IS JUDGED ON THE RUN THAT FINISHED IT, which is the same rule the
+ # report and the A/B already apply and the same helper that applies it. `--resume` appends to
+ # the payload it continues and re-runs the cells that died under the SAME deterministic
+ # `cell_id`, so the dead attempt's `completed: false` and its NOT RUN actions are still in the
+ # file after a resumed run has succeeded. Read raw, this loop found them forever: the resumed
+ # run exited 0 and `--report` scored the retry, while `--assert-liveness` on the same payload
+ # failed permanently on a cell that had already been re-run. A gate that cannot be satisfied
+ # by fixing the run is a gate people learn to pass with `--allow-not-run`.
+ from .scoring.from_payload import ATTEMPT_ROW_TYPES, latest_attempt_rows
+
+ # AN ATTEMPT THAT NEVER REACHED ITS CELL ROW IS A FAILURE, NOT AN ABSENCE. `latest_attempt_rows`
+ # names the latest attempt from ANY attempt-keyed row, because the Recorder flushes and fsyncs
+ # every action and window row while `CellRunner.run` writes the terminal `cell` row in a
+ # `finally` a SIGKILL, an OOM kill or a lost machine never reaches. So the killed attempt
+ # supersedes the completed one and then contributes no cell row of its own -- and this loop,
+ # reading cell rows only, dropped the cell out of the payload entirely. A resume killed inside a
+ # cell whose first attempt had already recorded `completed: false` with NOT RUN actions turned
+ # `1` into `0`: the gate stopped reporting a failure that is still written in the file.
+ attempted, recorded = set(), set()
+ kept = latest_attempt_rows(rows)
+ for row in kept:
+ if row.get("row_type") in ATTEMPT_ROW_TYPES and row.get("cell_id") is not None:
+ attempted.add(str(row.get("cell_id")))
+ if row.get("row_type") == "cell" and row.get("cell_id") is not None:
+ recorded.add(str(row.get("cell_id")))
+ truncated = sorted(attempted - recorded)
+ for where in truncated:
+ problems.append(f"{where}: an attempt wrote rows but never recorded a cell row")
+
+ cells = len(truncated)
+ for row in kept:
+ if row.get("row_type") != "cell":
+ continue
+ cells += 1
+ where = row.get("cell_id", "?")
+ if row.get("completed") is False:
+ problems.append(f"{where}: the cell did not complete")
+ for action in row.get("actions") or []:
+ name = action.get("action") or action.get("name") or "?"
+ if name in allowed:
+ continue
+ if not action.get("ran"):
+ problems.append(f"{where}: {name} NOT RUN ({action.get('reason') or 'no reason'})")
+ elif action.get("slot_missed"):
+ problems.append(f"{where}: {name} missed its slot")
+
+ if cells == 0:
+ # An empty payload passing every check is the same false negative in a different costume.
+ _log(f"REFUSING: {path} contains no cell rows, so there is nothing to assert about")
+ return 2
+ for line in problems:
+ _log(f" {line}")
+ _log(
+ f"{cells} cell(s), {len(problems)} liveness problem(s)"
+ + (f", {len(allowed)} action(s) allowed not to run" if allowed else "")
+ )
+ return 1 if problems else 0
+
+
+def parse_args(argv: list):
+ """The CLI surface, split out of `main` so the option contract can be asserted directly."""
+ ap = argparse.ArgumentParser(
+ prog = "studiobench", description = "A real-path performance benchmark for Unsloth Studio."
+ )
+ ap.add_argument(
+ "--tier",
+ choices = TIERS,
+ # No default here, and `quick` is applied below instead. `--report` needs to tell "the
+ # caller asked for this ladder" apart from "the caller said nothing", because a payload
+ # records the ladder its run promised and that answer beats a CLI default.
+ default = None,
+ help = (
+ "fast ~5min (100K only, the iteration loop), quick ~5min (1K,10K, a wiring check), "
+ "standard ~20min (1K,10K,100K), full ~60min (+500K,1M)"
+ ),
+ )
+ ap.add_argument(
+ "--doctor",
+ action = "store_true",
+ help = "report what is installed and what each missing piece costs",
+ )
+ ap.add_argument(
+ "--attach",
+ metavar = "URL",
+ help = "drive a Studio that is already running instead of installing one",
+ )
+ ap.add_argument(
+ "--resume", action = "store_true", help = "skip cells already completed in the output payload"
+ )
+ ap.add_argument(
+ "--ab",
+ metavar = "REF",
+ help = "A/B a second ref, interleaved within one session; with --attach also pass --attach-b",
+ )
+ ap.add_argument(
+ "--attach-b",
+ metavar = "URL",
+ dest = "attach_b",
+ help = "the treatment side's already-running Studio, when --ab is used "
+ "together with --attach",
+ )
+ ap.add_argument(
+ "--report",
+ metavar = "PAYLOAD",
+ help = "score and render an existing payload.jsonl, then exit. Runs offline, "
+ "so a payload mailed in from another machine reports here",
+ )
+ ap.add_argument(
+ "--assert-liveness",
+ metavar = "PAYLOAD",
+ dest = "assert_liveness",
+ help = "exit non-zero unless every scheduled action in an existing "
+ "payload.jsonl actually ran. Offline. This is the gate that catches an "
+ "action which never fired reporting as 'no effect'",
+ )
+ ap.add_argument(
+ "--allow-not-run",
+ metavar = "ACTIONS",
+ dest = "allow_not_run",
+ help = "comma-separated action names --assert-liveness may excuse. Use only "
+ "for an action a platform genuinely cannot perform, and say which in "
+ "the pull request: every name here is a hole in the gate",
+ )
+ ap.add_argument("--rungs", help = "comma-separated rung override, e.g. 1K,10K")
+ ap.add_argument("--reps", type = int, default = 1)
+ ap.add_argument(
+ "--instrument-level",
+ type = int,
+ default = 0,
+ choices = [0, 1, 2, 3],
+ help = "0 is the only level headline numbers may come from",
+ )
+ ap.add_argument(
+ "--cadence",
+ default = "field",
+ choices = ["field", "fast"],
+ help = "field is 24 chars every 73ms, the rate of the captured reply",
+ )
+ ap.add_argument(
+ "--engine",
+ choices = ["chromium", "webkit", "firefox"],
+ help = "default matches the platform's desktop webview family",
+ )
+ ap.add_argument("--branch", default = "main", help = "Studio ref to install when not attaching")
+ ap.add_argument("--home", help = "UNSLOTH_STUDIO_HOME for an install")
+ ap.add_argument("--port", type = int, default = 5399)
+ # `unsloth`, not `admin`. Studio's first run prints "DEFAULT ADMIN ACCOUNT CREATED / username:
+ # unsloth", and the wrong one answers 401 with a message about resetting the PASSWORD, which
+ # sends you looking in the wrong place.
+ ap.add_argument("--username", default = "unsloth")
+ ap.add_argument("--password", default = "")
+ ap.add_argument(
+ "--password-b",
+ dest = "password_b",
+ default = "",
+ help = "the treatment Studio's password, when --ab is used together with --attach-b. "
+ "Two Studios booted separately mint two different bootstrap passwords, so one "
+ "--password cannot authenticate both. Defaults to --password",
+ )
+ ap.add_argument("--out", help = "output directory")
+ ap.add_argument(
+ "--surfaces",
+ action = "store_true",
+ help = "additionally sweep every registered UI surface -- the other routes, "
+ "the settings tabs, the sidebar menus, the model picker -- and take a "
+ "parity digest of each. The film covers the chat thread; this covers "
+ "the rest of the app. Off by default: it costs about a minute per arm "
+ "and it does not measure performance",
+ )
+ ap.add_argument("--headed", action = "store_true")
+ ap.add_argument("--keep-studio", action = "store_true")
+ ap.add_argument(
+ "--allow-dev-server",
+ action = "store_true",
+ help = "run against a development build anyway. ONLY to demonstrate that the "
+ "production gate matters: React's dev build inflates the axis under "
+ "investigation by about 3.2x",
+ )
+ args = ap.parse_args(argv)
+ # Whether the ladder was ASKED FOR or merely defaulted. Only `--report` cares; everything else
+ # sees the tier it always saw.
+ args.tier_explicit = args.tier is not None
+ if args.tier is None:
+ args.tier = "quick"
+ return args
+
+
+def main(argv: list) -> int:
+ args = parse_args(argv)
+
+ if args.doctor:
+ return doctor(args)
+ if args.report:
+ return report_only(args)
+ if args.assert_liveness:
+ return assert_liveness(args)
+ if args.ab:
+ return run(args, ab_ref = args.ab)
+ return run(args)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/tests/studio/studiobench/analysis/__init__.py b/tests/studio/studiobench/analysis/__init__.py
new file mode 100644
index 00000000000..e3780ab8f08
--- /dev/null
+++ b/tests/studio/studiobench/analysis/__init__.py
@@ -0,0 +1,111 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""studiobench analysis: turn a captured trace into NAMED CALL FRAMES.
+
+Everything in this package is a pure function over a trace file. Nothing here
+launches a browser, so it can be unit tested against a checked-in trace and it
+keeps working when the harness layers change underneath it.
+
+The organising principle is that a RESIDUAL IS NOT A FINDING. A bucket sum the
+renderer computed for its own accounting ("36% of TaskDuration is unnamed
+script") is the shape of our ignorance, not a bottleneck. Every module here
+exists to replace one such bucket with a call frame, a count, and an exponent.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+__all__ = [
+ "CellFailure",
+ "classify",
+ "cpuprofile",
+ "fit",
+ "measured",
+ "merge",
+ "oracles",
+ "symbols",
+ "traceparse",
+ "unmeasured",
+]
+
+
+class CellFailure(RuntimeError):
+ """A measurement cell is unusable and must not be quoted.
+
+ Raised, never swallowed. A cell that fails an integrity gate is reported as
+ a failure with its reason; it is never silently downgraded into a smaller
+ number, because a silently truncated trace reads exactly like "the expensive
+ thing did not happen".
+ """
+
+ def __init__(self, gate: str, detail: str) -> None:
+ super().__init__(f"{gate}: {detail}")
+ self.gate = gate
+ self.detail = detail
+
+
+# ── the no-bare-zero convention (INTERFACES.md, "Rules that apply to every dict") ──
+#
+# `0` means "measured, and it was zero". It never means "did not run". Getting
+# this wrong is the single cheapest way to publish a false negative: a frame
+# budget of 0.00 ms reads as a fast app and is indistinguishable from an
+# instrument that never attached. Every numeric key these layers emit therefore
+# goes through one of the two helpers below, so the distinction is structural
+# rather than remembered.
+
+
+def measured(key: str, value: Any) -> dict:
+ """A value that WAS measured, even if it came out zero."""
+ return {key: value, f"{key}_attempted": True}
+
+
+def unmeasured(key: str, reason: str) -> dict:
+ """A value that could not be measured, and why.
+
+ Emits `None`, never `0`. The reason is required and is not optional
+ politeness: it is the only thing that tells a reader whether the number is
+ missing because the mechanism did not fire or because the instrument did not
+ run, and those imply opposite conclusions.
+ """
+ if not reason:
+ raise ValueError(f"unmeasured({key!r}) requires a reason")
+ return {key: None, f"{key}_attempted": False, f"{key}_reason": reason}
+
+
+def merge(*fragments: dict) -> dict:
+ """Combine helper fragments, refusing silent key collisions."""
+ out: dict = {}
+ for frag in fragments:
+ for k, v in frag.items():
+ if k in out and out[k] != v:
+ raise ValueError(f"conflicting values for {k!r}: {out[k]!r} then {v!r}")
+ out[k] = v
+ return out
+
+
+def assert_no_bare_zero(payload: dict, path: str = "payload") -> None:
+ """Check a dict obeys the convention before it crosses a layer boundary.
+
+ A numeric key equal to 0 (or a key set to None) must carry a sibling
+ `<key>_attempted`. Used in tests and cheap enough to call on real payloads.
+
+ Note the corollary for PROSE keys: a `reason` or `note` with nothing to say
+ must be OMITTED, not set to `None`. `None` is reserved for a quantity that
+ could not be measured, and overloading it for "no comment" makes the two
+ indistinguishable at exactly the point where the difference matters.
+ """
+ for k, v in payload.items():
+ if k.endswith(("_attempted", "_reason")):
+ continue
+ if isinstance(v, dict):
+ assert_no_bare_zero(v, f"{path}.{k}")
+ continue
+ is_zero = isinstance(v, (int, float)) and not isinstance(v, bool) and v == 0
+ if (is_zero or v is None) and f"{k}_attempted" not in payload:
+ raise CellFailure(
+ "bare_zero",
+ f"{path}.{k} is {v!r} with no sibling {k}_attempted. A bare zero cannot "
+ "be told apart from an instrument that never ran.",
+ )
diff --git a/tests/studio/studiobench/analysis/bridge_build.py b/tests/studio/studiobench/analysis/bridge_build.py
new file mode 100644
index 00000000000..66f2c027f19
--- /dev/null
+++ b/tests/studio/studiobench/analysis/bridge_build.py
@@ -0,0 +1,365 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Drive the two coverage runs that a symbol bridge is built from.
+
+The bridge needs the IDENTICAL fixture executed at the same small rungs against
+two different builds. That is the only requirement, and it is a strict one: if
+the two ladders differ in any way that changes how many times a function runs,
+the count vectors describe different experiments and every match is spurious.
+`build_bridge` cannot detect that, which is why the anchor check exists.
+
+Everything here is expressed against a `RungRunner` callable rather than against
+the session harness, so this module has no dependency on how a rung is actually
+driven. The caller supplies something that puts the page into rung state; this
+module owns only the coverage bracketing and the ordering guarantees.
+
+WHY THE RUNGS ARE SMALL. The bridge is a dictionary lookup, not a measurement,
+so it wants exactly enough dynamic range to make count vectors unique and not
+one rung more. Small rungs also keep the dev build, which is slow, from taking
+minutes. Two or three rungs spanning about a decade is plenty: three counts of
+a few thousand each collide far less often than one does.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Callable, Sequence
+
+from . import CellFailure
+from .symbols import FAILED, Bridge, build_bridge
+
+# A `RungRunner` puts the page into the state for one rung and returns when the
+# work for that rung is finished. It must be deterministic: the same rung must
+# do the same amount of work every time, or the count vectors are noise.
+RungRunner = Callable[[Any, str], None]
+
+DEFAULT_BRIDGE_RUNGS: tuple[str, ...] = ("bridge_s", "bridge_m", "bridge_l")
+
+
+@dataclass
+class BridgeArm:
+ """One build under test: how to reach it and what it is."""
+
+ build: str # "dev" or "prod"
+ cdp: Any
+ page: Any
+ react_version: str = ""
+ bundle_text: str = ""
+ snapshots: list[Any] = field(default_factory = list)
+
+
+def collect_arm(
+ arm: BridgeArm,
+ runner: RungRunner,
+ rungs: Sequence[str] = DEFAULT_BRIDGE_RUNGS,
+ *,
+ detailed: bool = False,
+) -> list[Any]:
+ """Run the ladder once under precise coverage, one snapshot per rung.
+
+ Coverage is started ONCE and snapshotted per rung, and each rung's counts are
+ the difference against the previous snapshot. Restarting coverage between
+ rungs would reset V8's counters and also re-run `DeoptimizeAll`, which
+ changes what gets compiled and therefore what gets counted.
+ """
+ from ..instruments.coverage import PreciseCoverage
+
+ cov = PreciseCoverage(arm.cdp, detailed = detailed)
+ cov.start()
+ try:
+ snapshots: list[Any] = []
+ for rung in rungs:
+ cov.mark()
+ runner(arm.page, rung)
+ snapshots.append(cov.window())
+ arm.snapshots = snapshots
+ return snapshots
+ finally:
+ cov.stop()
+
+
+def build(
+ dev_arm: BridgeArm,
+ prod_arm: BridgeArm,
+ runner: RungRunner,
+ *,
+ rungs: Sequence[str] = DEFAULT_BRIDGE_RUNGS,
+ anchor_names: Sequence[str],
+ react_url_filter: str | None = "react-dom",
+ anchor_url_filter: str | None = None,
+ symbols_dir: str | None = None,
+) -> Bridge:
+ """Collect both arms and build the bridge, persisting it if asked.
+
+ The two arms are collected in sequence rather than interleaved, because
+ interleaving would mean two coverage sessions alive at once and V8's
+ coverage mode is per isolate. Sequential collection is safe here precisely
+ because nothing timed is being compared: only integers cross out of this
+ function, and an integer does not drift between sessions.
+ """
+ if dev_arm.build != "dev" or prod_arm.build != "prod":
+ raise CellFailure(
+ "bridge_arms_mislabelled",
+ f"expected a dev arm and a prod arm, got {dev_arm.build!r} and {prod_arm.build!r}",
+ )
+ collect_arm(dev_arm, runner, rungs)
+ collect_arm(prod_arm, runner, rungs)
+
+ bridge = build_bridge(
+ dev_arm.snapshots,
+ prod_arm.snapshots,
+ rungs = rungs,
+ react_version = prod_arm.react_version or dev_arm.react_version,
+ bundle_source = prod_arm.bundle_text,
+ anchor_names = anchor_names,
+ react_url_filter = react_url_filter,
+ anchor_url_filter = anchor_url_filter,
+ )
+ if symbols_dir and bridge.status != FAILED:
+ bridge.save(symbols_dir)
+ return bridge
+
+
+def assert_profiling_build_loaded(page: Any) -> dict[str, Any]:
+ """Prove the profiling build is actually what the page loaded.
+
+ The check is that `<Profiler>`'s `onRender` FIRES NON-ZERO. `onRender` is
+ gated on React's `__PROFILE__` compile-time flag, so it does not exist in
+ the production build at all: `react-dom-client.production.js` contains zero
+ occurrences of the string `actualDuration`. A React stage that reads exactly
+ 0.00 is therefore not a fast app, it is a broken instrument, and it must
+ abort the run rather than pass as a clean result.
+
+ The page side is expected to have installed a recorder that pushes
+ `onRender` arguments into `window.__studiobench_profiler`, whose entries are
+ `[id, phase, actualDuration, baseDuration, startTime, commitTime]` in React
+ 19's six-argument order.
+ """
+ entries = page.evaluate("window.__studiobench_profiler || null")
+ if not entries:
+ raise CellFailure(
+ "profiling_build_not_loaded",
+ "no <Profiler> onRender callbacks were recorded. Either the profiling alias "
+ "did not take effect (react-dom/client was not rewritten to react-dom/profiling) "
+ "or the recorder was not installed. Either way the React stage would read 0.00, "
+ "which is a broken instrument and not a fast app.",
+ )
+ durations = [float(e[2]) for e in entries if isinstance(e, (list, tuple)) and len(e) >= 3]
+ total = sum(durations)
+ if total <= 0.0:
+ raise CellFailure(
+ "profiling_build_reads_zero",
+ f"{len(entries)} onRender callbacks fired but actualDuration summed to {total}. "
+ "A React stage reading exactly 0.00 is a broken instrument; aborting rather "
+ "than reporting it as a clean result.",
+ )
+ return {
+ "onRender_callbacks": len(entries),
+ "actual_duration_total_ms": total,
+ "phases": sorted({str(e[1]) for e in entries if len(e) >= 2}),
+ "profiling_build_verified": True,
+ }
+
+
+PROFILER_RECORDER_JS = """
+(() => {
+ // Installed via add_init_script BEFORE the app boots. Records every
+ // <Profiler> onRender call so the profiling alias can be verified by
+ // evidence rather than by trusting the build config.
+ window.__studiobench_profiler = [];
+ window.__studiobenchOnRender = function (id, phase, actualDuration,
+ baseDuration, startTime, commitTime) {
+ window.__studiobench_profiler.push(
+ [id, phase, actualDuration, baseDuration, startTime, commitTime]);
+ };
+})();
+"""
+
+
+# ═══════════════════════════════════════════════════════════════════════════
+# Build provenance: is the thing under measurement the thing we think it is?
+# ═══════════════════════════════════════════════════════════════════════════
+#
+# The worst output this layer can produce is a real number from the wrong
+# bundle under the right label. A dev server inflates React's own work several
+# fold and would MANUFACTURE the symptom we are hunting; a stale shipping dist
+# left in the output directory would silently measure code without the
+# profiling renderer. Both look like a clean run.
+#
+# Three independent checks, because each catches something the others cannot:
+#
+# 1. `/@vite/client` must not answer 200. That file exists only when a Vite
+# dev server is serving, and it is a fact about the SERVER.
+# 2. React must report `bundleType: 0` in the same renderer entry as
+# `rendererPackageName: "react-dom"`. That is a fact about the RENDERER
+# THAT ACTUALLY LOADED, which is the only thing that matters and the only
+# one of the three that a build-config mistake cannot fake.
+# 3. `__STUDIOBENCH_ATTRIBUTION_BUILD__` must be true. That is a fact about
+# WHICH dist is mounted, and it is what catches a stale shipping build
+# sitting in the directory passed to `--frontend`.
+#
+# DO NOT ADD A `jsxDEV` GREP. It false-positives: `hast-util-to-jsx-runtime`,
+# which Streamdown pulls in, references the dev JSX runtime in shipping code, so
+# a production bundle contains the string and the check condemns a correct
+# build.
+#
+# `bundleType` is read through the DevTools global hook. React only injects into
+# that hook if it already exists when the renderer initialises, so the stub must
+# be installed with `add_init_script` BEFORE the first `goto`, exactly like the
+# JWT seeding in `studio_test_kit.auth`. Installed after, the hook is empty and
+# the check reads as "React is missing" on a perfectly good page.
+
+DEVTOOLS_HOOK_STUB_JS = """
+(() => {
+ // Minimal __REACT_DEVTOOLS_GLOBAL_HOOK__. React calls `inject()` during
+ // renderer init and hands over an object carrying `bundleType` and
+ // `rendererPackageName`; everything else here exists only so React's
+ // instrumentation calls do not throw.
+ if (window.__REACT_DEVTOOLS_GLOBAL_HOOK__) return;
+ const renderers = new Map();
+ let uid = 0;
+ window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
+ renderers,
+ supportsFiber: true,
+ inject(renderer) {
+ const id = ++uid;
+ renderers.set(id, renderer);
+ (window.__studiobench_renderers = window.__studiobench_renderers || []).push({
+ bundleType: renderer && renderer.bundleType,
+ version: renderer && renderer.version,
+ rendererPackageName: renderer && renderer.rendererPackageName,
+ });
+ return id;
+ },
+ onCommitFiberRoot() {},
+ onCommitFiberUnmount() {},
+ onPostCommitFiberRoot() {},
+ onScheduleFiberRoot() {},
+ checkDCE() {},
+ };
+})();
+"""
+
+# React's `bundleType`: 0 is a production build, 1 is development. Confirmed on
+# a real pair: the dev server reported 1 and the profiling build reported 0.
+#
+# NOTE THAT 0 DOES NOT MEAN "profiling renderer is loaded". React's profiling
+# build is a production build, so it also reports 0, and `bundleType` alone
+# cannot tell the two apart. That is why `assert_profiling_build_loaded` is a
+# separate check on `onRender` actually firing, and why neither one substitutes
+# for the other.
+BUNDLE_TYPE_PRODUCTION = 0
+BUNDLE_TYPE_DEVELOPMENT = 1
+
+
+def assert_production_bundle(page: Any, *, base_url: str | None = None) -> dict[str, Any]:
+ """Refuse to measure a development build.
+
+ Raises `CellFailure` rather than warning. A dev-server run must be REFUSED,
+ not annotated, because the numbers it produces are wrong in the direction
+ that confirms the hypothesis: React's development build does several times
+ the work of the shipping one, so it would manufacture exactly the symptom
+ being investigated.
+ """
+ renderers = page.evaluate("window.__studiobench_renderers || null")
+ if not renderers:
+ raise CellFailure(
+ "no_react_renderer_seen",
+ "the React DevTools hook recorded no renderer. Either React never initialised, "
+ "or DEVTOOLS_HOOK_STUB_JS was installed after the first navigation instead of "
+ "through add_init_script before it, in which case React had nothing to inject into.",
+ )
+ # Match on the SAME entry, not across entries. A page can host more than one
+ # renderer (react-dom plus react-reconciler in a canvas library, say), and
+ # checking `bundleType` from one against `rendererPackageName` from another
+ # is how a development react-dom passes behind a production sibling.
+ dom = [r for r in renderers if str(r.get("rendererPackageName") or "") == "react-dom"]
+ if not dom:
+ raise CellFailure(
+ "no_react_dom_renderer",
+ f"no renderer identified itself as react-dom; saw "
+ f"{[r.get('rendererPackageName') for r in renderers]}",
+ )
+ dev = [r for r in dom if r.get("bundleType") == BUNDLE_TYPE_DEVELOPMENT]
+ if dev:
+ raise CellFailure(
+ "development_bundle",
+ f"react-dom reported bundleType {BUNDLE_TYPE_DEVELOPMENT} (development), version "
+ f"{dev[0].get('version')}. A development build does several times the work of the "
+ "shipping one and would manufacture the symptom under investigation. Refusing.",
+ )
+ out: dict[str, Any] = {
+ "react_dom_bundle_type": BUNDLE_TYPE_PRODUCTION,
+ "react_version": str(dom[0].get("version") or ""),
+ "renderers_seen": len(renderers),
+ "production_bundle_verified": True,
+ }
+ if base_url:
+ out.update(assert_not_dev_server(page, base_url))
+ return out
+
+
+def assert_not_dev_server(page: Any, base_url: str) -> dict[str, Any]:
+ """`/@vite/client` must not answer 200.
+
+ Checked from inside the page so it goes through the same origin and the same
+ server the app was actually loaded from, rather than from Python where a
+ proxy or a different host could answer.
+ """
+ url = base_url.rstrip("/") + "/@vite/client"
+ status = page.evaluate(
+ """async (u) => {
+ try {
+ const r = await fetch(u, { method: "GET", cache: "no-store" });
+ return r.status;
+ } catch (e) { return -1; }
+ }""",
+ url,
+ )
+ if status == 200:
+ raise CellFailure(
+ "vite_dev_server",
+ f"{url} answered 200, so this Studio is being served by a Vite dev server. "
+ "Every timing from it is inflated and the run must be refused.",
+ )
+ return {"vite_client_status": int(status), "dev_server_ruled_out": True}
+
+
+def assert_attribution_build(page: Any) -> dict[str, Any]:
+ """Confirm the dist under measurement is the studiobench attribution build.
+
+ Catches the staleness failure: a shipping dist left in the directory handed
+ to `unsloth studio --frontend <dir>` produces a perfectly healthy Studio
+ serving the WRONG bundle, with no profiling renderer and therefore a React
+ stage that reads 0.00. `attribution/vite.studiobench.config.ts` defines
+ `__STUDIOBENCH_ATTRIBUTION_BUILD__` for exactly this check.
+ """
+ marker = page.evaluate("globalThis.__STUDIOBENCH_ATTRIBUTION_BUILD__ === true")
+ if not marker:
+ raise CellFailure(
+ "not_the_attribution_build",
+ "__STUDIOBENCH_ATTRIBUTION_BUILD__ is not defined in the loaded bundle. The "
+ "directory passed to `unsloth studio --frontend` is serving some other dist, most "
+ "likely a stale shipping build. Rebuild with attribution/vite.studiobench.config.ts.",
+ )
+ return {"attribution_build_verified": True}
+
+
+def verify_build_provenance(
+ page: Any,
+ base_url: str,
+ *,
+ require_attribution: bool = True,
+) -> dict[str, Any]:
+ """All the provenance gates at once, for a Studio that is up and rendering.
+
+ Call this once per cell before any measurement. Every failure raises, and
+ that is deliberate: each of these conditions produces numbers that look
+ entirely reasonable and describe a different program.
+ """
+ out = assert_production_bundle(page, base_url = base_url)
+ if require_attribution:
+ out.update(assert_attribution_build(page))
+ out.update(assert_profiling_build_loaded(page))
+ return out
diff --git a/tests/studio/studiobench/analysis/classify.py b/tests/studio/studiobench/analysis/classify.py
new file mode 100644
index 00000000000..06bd975540f
--- /dev/null
+++ b/tests/studio/studiobench/analysis/classify.py
@@ -0,0 +1,521 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Classify every main-thread task by ORIGIN, read rather than inferred.
+
+"A scheduler task took 8 ms" is not a finding. "A `MessageChannel` port message
+posted from Blink's mojo connector ran 8 ms of page script, and there were 119
+of them" is. The difference is that the second one is read out of the trace.
+
+There is deliberately NO catch-all class. Buckets called "other" are exactly the
+failure this tool exists to remove, so a task that no rule explains is counted
+as `unclassified` and raises `unclassified_task_pct`; above the threshold the
+cell FAILS instead of quietly reporting a smaller, cleaner-looking table.
+
+Three evidence sources, in strict order of authority:
+
+1. **Blink's own task type**, from the `scheduler` trace category. That category
+ adds no events; it attaches TYPED ARGS to the `toplevel`
+ `ThreadControllerImpl::RunTask` slice:
+ `args.renderer_main_thread_task_execution.task_type` (a `TaskType` enum such
+ as `TASK_TYPE_JAVASCRIPT_TIMER_DELAYED_HIGH_NESTING` or
+ `TASK_TYPE_*POSTED_MESSAGE`) and `args.sequence_manager_task.queue_name`
+ (`FRAME_THROTTLEABLE_TQ`, `COMPOSITOR_TQ`, `INPUT_TQ`, `V8_TQ`, ...). This is
+ the scheduler stating what it thinks it is running. It is not an inference at
+ all, and it is why `scheduler` is in the category list.
+2. `src_file` / `src_func` on the same slice: the C++ that called `PostTask`.
+3. The `devtools.timeline` events nested inside the task (`TimerFire`,
+ `FireAnimationFrame`, `EventDispatch`, resource events), which say what the
+ task then DID.
+
+The ordering matters for the one class this tool most needs to get right.
+Blink implements `MessagePort` on top of a mojo message pipe, so a React
+scheduler callback and an inbound IPC arrive as the SAME
+`connector.cc / PostDispatchNextMessageFromPipe` task and `src_file` cannot
+separate them. The task type can: on a real capture, 120 `MessageChannel` round
+trips came back labelled as posted-message tasks, exactly 120 of them, while the
+`src_file` evidence lumped them in with unrelated IPC.
+
+Note that `sequence_manager` as a category does NOT carry queue names, which is
+the natural but wrong assumption; it contributes only the DoWork and DoIdleWork
+scoping slices.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Iterable
+
+from . import CellFailure
+from .traceparse import Task, Thread, Trace, join_posted_from, walk_within_task
+
+INPUT = "input"
+TIMER = "timer"
+MESSAGE_CHANNEL = "message_channel"
+NETWORK = "network"
+RAF = "raf"
+IDLE = "idle"
+GC = "gc"
+BROWSER_INTERNAL = "browser_internal"
+# Browser-to-renderer IPC that ran page script. In a harnessed run this is
+# dominated by the devtools pipe delivering `Runtime.evaluate`, which is to say
+# it is OUR OWN cost and it belongs in a column with its own name so that it can
+# be watched for growth with the treatment, not folded into a residual and not
+# hidden inside `browser_internal`.
+AGENT_IPC = "agent_ipc"
+UNCLASSIFIED = "unclassified"
+
+ORIGINS = (
+ INPUT,
+ TIMER,
+ MESSAGE_CHANNEL,
+ NETWORK,
+ RAF,
+ IDLE,
+ GC,
+ BROWSER_INTERNAL,
+ AGENT_IPC,
+ UNCLASSIFIED,
+)
+
+# Origins that are the harness observing, not the app working. Reported, never
+# subtracted: a correction you cannot see is a correction you cannot check.
+HARNESS_ORIGINS = (AGENT_IPC,)
+
+# Above this share of main-thread task time in the unclassified bucket, the cell
+# is not quotable. The point of the tool is that we can name things.
+UNCLASSIFIED_FAIL_PCT = 2.0
+
+_JS_EVENTS = frozenset(
+ {
+ "FunctionCall",
+ "v8.callFunction",
+ "EvaluateScript",
+ "v8.run",
+ "v8.compile",
+ "V8.Execute",
+ }
+)
+
+_RESOURCE_EVENTS = frozenset(
+ {
+ "ResourceSendRequest",
+ "ResourceReceiveResponse",
+ "ResourceReceivedData",
+ "ResourceFinish",
+ "ResourceMarkAsCached",
+ "XHRReadyStateChange",
+ "XHRLoad",
+ }
+)
+
+_RAF_EVENTS = frozenset(
+ {
+ "FireAnimationFrame",
+ "AnimationFrame::Render",
+ "AnimationFrame::StyleAndLayout",
+ "BeginMainThreadFrame",
+ }
+)
+
+_INPUT_EVENT_TYPES = frozenset(
+ {
+ "keydown",
+ "keyup",
+ "keypress",
+ "beforeinput",
+ "input",
+ "compositionstart",
+ "compositionupdate",
+ "compositionend",
+ "textInput",
+ "mousedown",
+ "mouseup",
+ "mousemove",
+ "click",
+ "dblclick",
+ "wheel",
+ "pointerdown",
+ "pointerup",
+ "pointermove",
+ "pointercancel",
+ "touchstart",
+ "touchend",
+ "touchmove",
+ "gesturescrollbegin",
+ "gesturescrollupdate",
+ }
+)
+
+# Network-ish streaming: an SSE frame arrives as a `message` event on an
+# EventSource, and a fetch-based stream as a resource event.
+_NETWORK_EVENT_TYPES = frozenset({"message", "readystatechange", "load", "error", "open"})
+
+_POSTED_FROM_RULES: tuple[tuple[str, str, str], ...] = (
+ # (src_file substring, src_func substring or "", origin)
+ ("core/scheduler/dom_timer.cc", "", TIMER),
+ ("blink/renderer/core/timing", "", TIMER),
+ ("widget/input/main_thread_event_queue.cc", "", INPUT),
+ ("blink/renderer/core/input", "", INPUT),
+ ("cc/trees/proxy_impl.cc", "ScheduledActionSendBeginMainFrame", RAF),
+ ("cc/trees/proxy_main.cc", "", RAF),
+ ("v8/src/heap/", "", GC),
+ ("blink/renderer/platform/heap/", "", GC),
+ ("v8/src/tasks/", "", GC),
+)
+
+# Tasks the browser posts to itself. Only ever applied to a task that ran NO
+# page script, so this can never swallow a JS bottleneck.
+_BROWSER_INTERNAL_FILES = (
+ "web_frame_widget_impl.cc",
+ "main_thread_scheduler_impl.cc",
+ "trace_session_observer.cc",
+ "ipc_mojo_bootstrap.cc",
+ "simple_watcher.cc",
+ "render_media_client.cc",
+ "sandboxed_process_thread_type_handler.cc",
+ "memory_usage_monitor.cc",
+ "gpu.cc",
+ "interface_endpoint_client.cc",
+ "paint_timing.cc",
+ "layout_shift_tracker.cc",
+ "cc/trees/",
+ "perfetto_task_runner.cc",
+ "compositor_frame_reporting_controller.cc",
+ "frame_scheduler_impl.cc",
+ "page_scheduler_impl.cc",
+)
+
+_IDLE_MARKERS = ("DoIdleWork", "RunIdleTask", "IdleTask", "ScheduleIdleTask")
+
+# Blink `TaskType` enum names as they appear in
+# `args.renderer_main_thread_task_execution.task_type`. Matched by SUBSTRING on
+# the part after `TASK_TYPE_`, so that both
+# `TASK_TYPE_JAVASCRIPT_TIMER_DELAYED_HIGH_NESTING` and
+# `TASK_TYPE_JAVASCRIPT_TIMER_IMMEDIATE` land on `timer` without enumerating
+# every nesting variant.
+_TASK_TYPE_RULES: tuple[tuple[str, str], ...] = (
+ ("JAVASCRIPT_TIMER", TIMER),
+ ("POSTED_MESSAGE", MESSAGE_CHANNEL),
+ ("UNSHIPPED_PORT_MESSAGE", MESSAGE_CHANNEL),
+ ("POST_MESSAGE_FORWARDING", MESSAGE_CHANNEL),
+ ("USER_INTERACTION", INPUT),
+ ("INPUT_BLOCKING", INPUT),
+ ("MAIN_THREAD_TASK_QUEUE_INPUT", INPUT),
+ ("NETWORKING", NETWORK),
+ ("WEB_SOCKET", NETWORK),
+ ("MAIN_THREAD_TASK_QUEUE_COMPOSITOR", RAF),
+ ("COMPOSITOR_THREAD_TASK_QUEUE", RAF),
+ ("IDLE_TASK", IDLE),
+ ("MAIN_THREAD_TASK_QUEUE_IDLE", IDLE),
+ ("MAIN_THREAD_TASK_QUEUE_V8", GC),
+ ("MICROTASK", MESSAGE_CHANNEL),
+)
+
+# `args.sequence_manager_task.queue_name`, used when the task type is absent.
+_QUEUE_NAME_RULES: tuple[tuple[str, str], ...] = (
+ ("INPUT_TQ", INPUT),
+ ("UI_USER_INPUT_TQ", INPUT),
+ ("COMPOSITOR_TQ", RAF),
+ ("FRAME_THROTTLEABLE_TQ", TIMER),
+ ("FRAME_LOADING_TQ", NETWORK),
+ ("FRAME_LOADING_CONTROL_TQ", NETWORK),
+ ("IDLE_TQ", IDLE),
+ ("V8_TQ", GC),
+ ("V8_USER_VISIBLE_TQ", GC),
+ ("V8_BEST_EFFORT_TQ", GC),
+)
+
+
+def scheduler_labels(task: Task) -> dict[str, str]:
+ """Read Blink's own labels for a task, if the `scheduler` category was on.
+
+ Returns `{}` when the category was absent, which is a legitimate state:
+ classification then falls back to `src_file` and nested evidence and the
+ result carries lower-authority evidence strings.
+ """
+ for t in walk_within_task(task):
+ if t.name != "ThreadControllerImpl::RunTask":
+ continue
+ a = t.args or {}
+ exec_args = a.get("renderer_main_thread_task_execution") or {}
+ sm_args = a.get("sequence_manager_task") or {}
+ out: dict[str, str] = {}
+ if isinstance(exec_args, dict) and exec_args.get("task_type"):
+ out["task_type"] = str(exec_args["task_type"])
+ if isinstance(sm_args, dict) and sm_args.get("queue_name"):
+ out["queue_name"] = str(sm_args["queue_name"])
+ if isinstance(sm_args, dict) and sm_args.get("priority"):
+ out["priority"] = str(sm_args["priority"])
+ if out:
+ return out
+ return {}
+
+
+@dataclass
+class ClassifiedTask:
+ task: Task
+ origin: str
+ evidence: str
+ src_file: str = ""
+ src_func: str = ""
+ ran_js: bool = False
+ task_type: str = ""
+ queue_name: str = ""
+
+ @property
+ def dur_us(self) -> int:
+ return self.task.dur
+
+ def as_row(self) -> dict[str, Any]:
+ return {
+ "ts": self.task.ts,
+ "dur_us": self.task.dur,
+ "origin": self.origin,
+ "evidence": self.evidence,
+ "src_file": self.src_file,
+ "src_func": self.src_func,
+ "ran_js": self.ran_js,
+ "task_type": self.task_type,
+ "queue_name": self.queue_name,
+ }
+
+
+@dataclass
+class Classification:
+ tasks: list[ClassifiedTask] = field(default_factory = list)
+ by_origin_us: dict[str, int] = field(default_factory = dict)
+ by_origin_count: dict[str, int] = field(default_factory = dict)
+ total_us: int = 0
+
+ @property
+ def unclassified_pct(self) -> float:
+ if self.total_us <= 0:
+ return 0.0
+ return 100.0 * self.by_origin_us.get(UNCLASSIFIED, 0) / self.total_us
+
+ def assert_named(self, threshold_pct: float = UNCLASSIFIED_FAIL_PCT) -> None:
+ pct = self.unclassified_pct
+ if pct > threshold_pct:
+ worst = sorted(
+ (c for c in self.tasks if c.origin == UNCLASSIFIED),
+ key = lambda c: -c.dur_us,
+ )[:5]
+ detail = "; ".join(
+ f"{c.dur_us / 1000:.1f}ms from {c.src_file or '?'}::{c.src_func or '?'}"
+ f" [task_type={c.task_type or 'absent'} queue={c.queue_name or 'absent'}]"
+ for c in worst
+ )
+ raise CellFailure(
+ "unclassified_task_pct",
+ f"{pct:.2f}% of main-thread task time has no known origin "
+ f"(limit {threshold_pct}%). Worst: {detail}",
+ )
+
+ def summary(self) -> dict[str, Any]:
+ return {
+ "total_task_ms": self.total_us / 1000.0,
+ "unclassified_task_pct": round(self.unclassified_pct, 4),
+ "by_origin_ms": {k: round(v / 1000.0, 3) for k, v in sorted(self.by_origin_us.items())},
+ "by_origin_count": dict(sorted(self.by_origin_count.items())),
+ }
+
+ def tasks_of(self, origin: str) -> list[ClassifiedTask]:
+ return [c for c in self.tasks if c.origin == origin]
+
+ def windows_of(self, origin: str) -> list[tuple[int, int]]:
+ """(start, end) microsecond windows, for slicing a CPU profile."""
+ return [(c.task.ts, c.task.end) for c in self.tasks_of(origin)]
+
+
+def _nested_names(task: Task) -> set[str]:
+ return {t.name for t in walk_within_task(task) if t is not task}
+
+
+def _event_dispatch_types(task: Task) -> set[str]:
+ out: set[str] = set()
+ for t in walk_within_task(task):
+ if t.name == "EventDispatch":
+ data = (t.args or {}).get("data") or {}
+ typ = data.get("type")
+ if isinstance(typ, str):
+ out.add(typ)
+ return out
+
+
+def classify_task(task: Task) -> ClassifiedTask:
+ posted = join_posted_from(task)
+ src_file = str(posted.get("src_file", "") or "")
+ src_func = str(posted.get("src_func", "") or "")
+ names = _nested_names(task)
+ types = _event_dispatch_types(task)
+ ran_js = bool(names & _JS_EVENTS)
+
+ labels = scheduler_labels(task)
+ task_type = labels.get("task_type", "")
+ queue_name = labels.get("queue_name", "")
+
+ def done(origin: str, evidence: str) -> ClassifiedTask:
+ return ClassifiedTask(
+ task = task,
+ origin = origin,
+ evidence = evidence,
+ src_file = src_file,
+ src_func = src_func,
+ ran_js = ran_js,
+ task_type = task_type,
+ queue_name = queue_name,
+ )
+
+ # 0. Blink's own label, when the `scheduler` category recorded one. This
+ # outranks everything below it because it is the scheduler stating what
+ # it dispatched rather than us reconstructing it. Two exceptions are
+ # handled first, both cases where the label is true but not what a reader
+ # wants attributed:
+ # - a V8 task queue that ran no JS is GC or compilation bookkeeping,
+ # but one that DID run JS is a real JS task and must not be filed
+ # under GC;
+ # - a compositor-queue task with a nested input dispatch is input.
+ if task_type:
+ if types & _INPUT_EVENT_TYPES:
+ return done(
+ INPUT,
+ f"task_type:{task_type}+EventDispatch:{sorted(types & _INPUT_EVENT_TYPES)[0]}",
+ )
+ for needle, origin in _TASK_TYPE_RULES:
+ if needle in task_type:
+ if origin == GC and ran_js:
+ continue
+ return done(origin, f"task_type:{task_type}")
+
+ # 1. Input first: a keystroke that also fires a timer is still a keystroke,
+ # and input latency is the metric a user actually feels.
+ if types & _INPUT_EVENT_TYPES:
+ return done(INPUT, f"EventDispatch:{sorted(types & _INPUT_EVENT_TYPES)[0]}")
+ if "main_thread_event_queue.cc" in src_file:
+ return done(INPUT, "posted_from:main_thread_event_queue")
+
+ # 2. GC before everything else that could contain it, because a major GC
+ # posted from the incremental marking job is not a timer task even when
+ # it happens to run inside one.
+ gc_names = {
+ n
+ for n in names
+ if n.startswith("V8.GC") or n in ("MajorGC", "MinorGC", "BlinkGC.AtomicPhase")
+ }
+ if any(marker in src_file for marker in ("v8/src/heap/", "platform/heap/")):
+ return done(GC, f"posted_from:{src_file.rsplit('/', 1)[-1]}")
+ if gc_names and not ran_js:
+ return done(GC, f"nested:{sorted(gc_names)[0]}")
+
+ # 3. Rendering lifecycle.
+ if names & _RAF_EVENTS or "ScheduledActionSendBeginMainFrame" in src_func:
+ return done(RAF, "frame_lifecycle")
+
+ # 4. Idle.
+ if any(m in src_func or m in task.name for m in _IDLE_MARKERS) or "RunIdleTask" in names:
+ return done(IDLE, "idle_queue")
+
+ # 5. Timers.
+ if "TimerFire" in names:
+ return done(TIMER, "nested:TimerFire")
+ if "dom_timer.cc" in src_file:
+ return done(TIMER, "posted_from:dom_timer")
+
+ # 6. Network / SSE. Checked before message-channel because both arrive over
+ # a mojo pipe and only the resource events tell them apart.
+ if names & _RESOURCE_EVENTS:
+ return done(NETWORK, f"nested:{sorted(names & _RESOURCE_EVENTS)[0]}")
+ if types & _NETWORK_EVENT_TYPES and "connector.cc" in src_file:
+ return done(NETWORK, f"EventDispatch:{sorted(types & _NETWORK_EVENT_TYPES)[0]}")
+
+ # 7. Message channel, that is, the React scheduler. Blink dispatches a
+ # `MessagePort` message as a mojo connector task, so the discriminator is
+ # that page script ran and nothing network-shaped happened.
+ if ran_js and (
+ "connector.cc" in src_file
+ or "message_port" in src_file
+ or "interface_endpoint_client.cc" in src_file
+ ):
+ return done(MESSAGE_CHANNEL, "mojo_pipe_running_page_script")
+
+ # 8. The devtools / browser IPC channel running page script. This is what
+ # `Runtime.evaluate` and `Page.*` look like from inside the renderer, so
+ # it is measurement cost. Named, so it can be watched for correlation
+ # with the treatment; never subtracted.
+ if ran_js and any(
+ f in src_file for f in ("ipc_mojo_bootstrap.cc", "simple_watcher.cc", "mojo_bootstrap")
+ ):
+ return done(AGENT_IPC, f"posted_from:{src_file.rsplit('/', 1)[-1]}")
+
+ # 9. Browser bookkeeping, and ONLY when no page script ran inside. This
+ # guard is what stops this class becoming the residual under a new name.
+ if not ran_js and any(f in src_file for f in _BROWSER_INTERNAL_FILES):
+ return done(BROWSER_INTERNAL, f"posted_from:{src_file.rsplit('/', 1)[-1]}")
+
+ for needle, func_needle, origin in _POSTED_FROM_RULES:
+ if needle in src_file and (not func_needle or func_needle in src_func):
+ return done(origin, f"posted_from:{needle}")
+
+ # 10. Last resort before giving up: the queue the task sat on. Weaker than
+ # the task type, because a queue carries a mix, but still read from the
+ # scheduler rather than guessed.
+ for needle, origin in _QUEUE_NAME_RULES:
+ if needle == queue_name:
+ if origin == GC and ran_js:
+ continue
+ return done(origin, f"queue_name:{queue_name}")
+
+ return done(
+ UNCLASSIFIED,
+ f"no rule for {src_file or 'unknown'}::{src_func or 'unknown'}"
+ + (" (ran JS)" if ran_js else ""),
+ )
+
+
+def classify_thread(trace: Trace, thread: Thread | None = None) -> Classification:
+ th = thread if thread is not None else trace.renderer_main()
+ result = Classification()
+ for task in trace.run_tasks(th):
+ c = classify_task(task)
+ result.tasks.append(c)
+ result.by_origin_us[c.origin] = result.by_origin_us.get(c.origin, 0) + c.dur_us
+ result.by_origin_count[c.origin] = result.by_origin_count.get(c.origin, 0) + 1
+ result.total_us += c.dur_us
+ return result
+
+
+def cross_check_task_duration(
+ classification: Classification,
+ cdp_task_duration_s: float,
+ tolerance: float = 0.05,
+) -> dict[str, Any]:
+ """Summed trace `RunTask` must agree with `Performance.getMetrics.TaskDuration`.
+
+ Two independent accountings of the same quantity. If they disagree the trace
+ is missing tasks or the metrics window did not line up with the trace
+ window, and either way nothing derived from either is safe to quote.
+ """
+ trace_s = classification.total_us / 1e6
+ if cdp_task_duration_s <= 0:
+ raise CellFailure("task_duration_zero", "Performance.getMetrics reported TaskDuration <= 0")
+ drift = abs(trace_s - cdp_task_duration_s) / cdp_task_duration_s
+ report = {
+ "trace_run_task_s": trace_s,
+ "cdp_task_duration_s": cdp_task_duration_s,
+ "drift": drift,
+ "tolerance": tolerance,
+ }
+ if drift > tolerance:
+ raise CellFailure(
+ "task_duration_mismatch",
+ f"trace RunTask total {trace_s * 1000:.1f} ms vs CDP TaskDuration "
+ f"{cdp_task_duration_s * 1000:.1f} ms = {drift * 100:.1f}% apart, "
+ f"above {tolerance * 100:.0f}%",
+ )
+ return report
+
+
+def origin_windows(classification: Classification, origins: Iterable[str]) -> list[tuple[int, int]]:
+ wanted = set(origins)
+ return [(c.task.ts, c.task.end) for c in classification.tasks if c.origin in wanted]
diff --git a/tests/studio/studiobench/analysis/cpuprofile.py b/tests/studio/studiobench/analysis/cpuprofile.py
new file mode 100644
index 00000000000..d7d1054fb25
--- /dev/null
+++ b/tests/studio/studiobench/analysis/cpuprofile.py
@@ -0,0 +1,495 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Turn `ProfileChunk` trace events into (timestamp, stack) pairs.
+
+This is the module that deletes the concept of a residual. A renderer bucket
+like `TaskOtherDuration` is a number the renderer computed for its own
+accounting and it has no stack; a V8 CPU sample has a stack, so every
+microsecond it covers resolves to a leaf call frame with an ancestry.
+
+Four properties of the real wire format, each confirmed against a captured
+trace rather than assumed, and each of which silently produces a wrong answer if
+you get it wrong:
+
+* `nodes` arrive INCREMENTALLY. In a real 118-chunk capture only 6 chunks
+ carried a `nodes` array at all. A parser that reads nodes per chunk and
+ discards them resolves almost every sample to "unknown node".
+* `timeDeltas` lives at `args.data.timeDeltas`, a SIBLING of `cpuProfile`, not
+ inside it. `samples` lives at `args.data.cpuProfile.samples`.
+* `ts`, `Profile.args.data.startTime` and every entry of `timeDeltas` are
+ MICROSECONDS on the same monotonic clock as the rest of the trace.
+* `timeDeltas` entries can be NEGATIVE. The V8 sampler timestamps samples on the
+ sampling thread and small reorderings happen. Summing is still correct;
+ clamping each delta at zero is not, because it inflates the total.
+
+The sum of `timeDeltas` over a window must equal the window wall duration.
+Assert it, and FAIL THE CELL when it does not, rather than rescaling: a scale
+factor that reconciles a broken profile with wall clock is a way of making every
+downstream number look plausible and be wrong.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Iterable, Sequence
+
+from . import CellFailure
+from .traceparse import Trace
+
+# V8 synthetic frames. They are real samples and their time is real, but they
+# are not call frames anyone can go and fix, so they are labelled and excluded
+# from frame ranking rather than silently dropped from totals.
+SYNTHETIC_FRAMES = frozenset({"(root)", "(program)", "(idle)", "(garbage collector)"})
+
+# How far the summed sample deltas may drift from the wall span of the chunks
+# before the cell is unusable.
+DELTA_WALL_TOLERANCE = 0.02
+
+# Below this many non-synthetic samples inside a window set, a leaf ranking is
+# not a ranking. At a ~150 us sampling interval a 40 us task contributes at most
+# one sample, so a set of short tasks can produce a confident-looking table
+# built on five data points. Reported as `underpowered`, never hidden.
+MIN_JS_SAMPLES_FOR_RANKING = 100
+
+
+@dataclass(frozen = True)
+class CallFrame:
+ function_name: str
+ script_id: str
+ url: str
+ line: int
+ column: int
+ code_type: str = ""
+
+ @property
+ def key(self) -> tuple[str, str, int, int]:
+ """Identity of a function, stable across chunks and across a session.
+
+ Keyed on script id and source position rather than on name, because the
+ name is very often the empty string for a module top level or an
+ anonymous callback, and because two different functions minified to the
+ same short name are different functions.
+ """
+ return (self.function_name, self.script_id, self.line, self.column)
+
+ @property
+ def is_synthetic(self) -> bool:
+ return self.function_name in SYNTHETIC_FRAMES
+
+ def label(self) -> str:
+ name = self.function_name or "(anonymous)"
+ where = self.url or f"script#{self.script_id}"
+ return f"{name} @ {where}:{self.line}:{self.column}"
+
+
+@dataclass
+class Sample:
+ ts: int # microseconds, monotonic, same clock as trace `ts`
+ node_id: int
+ delta: int # microseconds attributed to this sample
+
+
+@dataclass
+class CpuProfile:
+ """Accumulated V8 CPU profile for one profiled thread."""
+
+ pid: int
+ tid: int
+ start_time: int
+ nodes: dict[int, CallFrame] = field(default_factory = dict)
+ parents: dict[int, int] = field(default_factory = dict)
+ samples: list[Sample] = field(default_factory = list)
+ chunk_count: int = 0
+ chunk_ts_first: int = 0
+ chunk_ts_last: int = 0
+ negative_deltas: int = 0
+ # `Profile.args.data.startTime`, kept only so the clock skew against `ts`
+ # can be reported. Never used as an anchor.
+ declared_start_time: int = 0
+ source: str = ""
+ # `sampleTraceId` -> node id, accumulated from
+ # `ProfileChunk.args.data.cpuProfile.trace_ids`. This is an EXACT stack, not
+ # a sampled one: when the `disabled-by-default-devtools.timeline.stack`
+ # category is on, Blink calls `v8::CpuProfiler::CollectSample` with a tagged
+ # id at specific instrumentation points, so the stack recorded for that id
+ # is the real stack at that instant rather than whatever the 100 us sampler
+ # happened to catch.
+ trace_ids: dict[str, int] = field(default_factory = dict)
+
+ @property
+ def clock_skew_us(self) -> int:
+ if not self.declared_start_time:
+ return 0
+ return self.start_time - self.declared_start_time
+
+ def stack_for_sample_trace_id(self, sample_trace_id: int | str) -> list[CallFrame]:
+ """The EXACT stack recorded for a tagged instrumentation point.
+
+ Timeline events such as `EventDispatch`, `FunctionCall`,
+ `RequestAnimationFrame` and `TimerInstall` carry
+ `args.data.sampleTraceId` when the timeline.stack category is enabled.
+ Looking that id up here gives the true stack at that event, with none of
+ the sampling error that makes short windows unrankable.
+ """
+ node = self.trace_ids.get(str(sample_trace_id))
+ if node is None:
+ return []
+ return self.stack(node)
+
+ # ------------------------------------------------------------------ stacks
+
+ def stack(self, node_id: int) -> list[CallFrame]:
+ """Leaf-first ancestry of a sample node.
+
+ Guards against a cyclic `parent` chain, which a corrupt trace can
+ produce and which would otherwise hang the whole analysis.
+ """
+ out: list[CallFrame] = []
+ seen: set[int] = set()
+ cur: int | None = node_id
+ while cur is not None and cur not in seen:
+ seen.add(cur)
+ frame = self.nodes.get(cur)
+ if frame is None:
+ break
+ out.append(frame)
+ cur = self.parents.get(cur)
+ return out
+
+ def stacked_samples(
+ self,
+ t0: int | None = None,
+ t1: int | None = None,
+ ) -> list[tuple[int, list[CallFrame]]]:
+ """The deliverable: (timestamp, stack) pairs, leaf first."""
+ return [(s.ts, self.stack(s.node_id)) for s in self.window(t0, t1)]
+
+ def window(
+ self,
+ t0: int | None = None,
+ t1: int | None = None,
+ ) -> list[Sample]:
+ lo = t0 if t0 is not None else -(1 << 62)
+ hi = t1 if t1 is not None else (1 << 62)
+ return [s for s in self.samples if lo <= s.ts < hi]
+
+ # ------------------------------------------------------------- aggregation
+
+ def self_time_us(
+ self,
+ t0: int | None = None,
+ t1: int | None = None,
+ ) -> dict[tuple[str, str, int, int], int]:
+ """Microseconds where a frame was the LEAF of the stack, by frame key."""
+ out: dict[tuple[str, str, int, int], int] = {}
+ for s in self.window(t0, t1):
+ frame = self.nodes.get(s.node_id)
+ if frame is None:
+ continue
+ out[frame.key] = out.get(frame.key, 0) + s.delta
+ return out
+
+ def total_time_us(
+ self,
+ t0: int | None = None,
+ t1: int | None = None,
+ ) -> dict[tuple[str, str, int, int], int]:
+ """Microseconds where a frame appeared ANYWHERE on the stack."""
+ out: dict[tuple[str, str, int, int], int] = {}
+ for s in self.window(t0, t1):
+ for frame in dict.fromkeys(self.stack(s.node_id)):
+ out[frame.key] = out.get(frame.key, 0) + s.delta
+ return out
+
+ def frame_by_key(self, key: tuple[str, str, int, int]) -> CallFrame | None:
+ for f in self.nodes.values():
+ if f.key == key:
+ return f
+ return None
+
+ # ------------------------------------------------------------------- gates
+
+ def assert_deltas_match_wall(self, tolerance: float = DELTA_WALL_TOLERANCE) -> dict[str, Any]:
+ """Sum of deltas must equal the profiled wall span within `tolerance`.
+
+ A profile whose deltas do not add up to the wall clock is either
+ truncated or came from a different clock, and either way every self time
+ derived from it is wrong by an unknown factor.
+ """
+ if not self.samples:
+ raise CellFailure("cpuprofile_empty", "profile contained no samples")
+ delta_sum = sum(s.delta for s in self.samples)
+ wall = self.chunk_ts_last - self.chunk_ts_first
+ if wall <= 0:
+ raise CellFailure("cpuprofile_wall", f"non-positive chunk wall span {wall} us")
+ drift = abs(delta_sum - wall) / wall
+ report = {
+ "delta_sum_us": delta_sum,
+ "chunk_wall_us": wall,
+ "drift": drift,
+ "tolerance": tolerance,
+ "sample_count": len(self.samples),
+ "negative_deltas": self.negative_deltas,
+ }
+ if drift > tolerance:
+ raise CellFailure(
+ "cpuprofile_delta_wall_mismatch",
+ f"summed timeDeltas {delta_sum} us vs chunk wall {wall} us "
+ f"= {drift * 100:.2f}% drift, above {tolerance * 100:.0f}%",
+ )
+ return report
+
+ def sampling_interval_us(self) -> float:
+ if len(self.samples) < 2:
+ return 0.0
+ return (self.chunk_ts_last - self.chunk_ts_first) / max(1, len(self.samples))
+
+
+def _call_frame(raw: dict[str, Any]) -> CallFrame:
+ return CallFrame(
+ function_name = str(raw.get("functionName", "")),
+ script_id = str(raw.get("scriptId", "")),
+ url = str(raw.get("url", "")),
+ line = int(raw.get("lineNumber", -1)),
+ column = int(raw.get("columnNumber", -1)),
+ code_type = str(raw.get("codeType", "")),
+ )
+
+
+def parse_cpu_profiles(trace: Trace) -> dict[str, CpuProfile]:
+ """Build every CPU profile in a trace, keyed by the `Profile` event id.
+
+ The `Profile` event carries the pid/tid of the PROFILED thread and the
+ `startTime` anchor. `ProfileChunk` events carry the same `id` but are
+ emitted on the V8 profiler's own thread (`v8:ProfEvntProc`), so they are
+ correlated by `(pid, id)` and never by thread id. Filtering chunks by the
+ renderer main thread id returns zero samples, which is indistinguishable
+ from the CPU profiler having been left off.
+ """
+ profiles: dict[str, CpuProfile] = {}
+ for e in trace.events:
+ if e.get("name") != "Profile" or "cpu_profiler" not in str(e.get("cat", "")):
+ continue
+ data = (e.get("args") or {}).get("data") or {}
+ pid = int(e.get("pid", 0))
+ key = f"{pid}:{e.get('id')}"
+ profiles[key] = CpuProfile(
+ pid = pid,
+ tid = int(e.get("tid", 0)),
+ # ANCHOR ON `ts`, NOT ON `args.data.startTime`. V8 writes
+ # `startTime` straight from `base::TimeTicks` without converting it
+ # into the trace's clock domain, and both V8's own source comment
+ # and the DevTools frontend say to use the event timestamp instead.
+ # The two agree to within a few microseconds on a healthy capture,
+ # but the drift is unbounded in principle, and it would show up as
+ # every sample being attributed to the neighbouring task.
+ start_time = int(e.get("ts", data.get("startTime", 0))),
+ declared_start_time = int(data.get("startTime", 0)),
+ source = str(data.get("source", "")),
+ )
+
+ chunks = [
+ e
+ for e in trace.events
+ if e.get("name") == "ProfileChunk" and "cpu_profiler" in str(e.get("cat", ""))
+ ]
+ chunks.sort(key = lambda e: int(e.get("ts", 0)))
+
+ for e in chunks:
+ pid = int(e.get("pid", 0))
+ key = f"{pid}:{e.get('id')}"
+ prof = profiles.get(key)
+ if prof is None:
+ # A chunk with no matching Profile event cannot be anchored to a
+ # start time, so its sample timestamps would be meaningless.
+ continue
+ data = (e.get("args") or {}).get("data") or {}
+ cpu = data.get("cpuProfile") or {}
+
+ for raw in cpu.get("nodes") or ():
+ nid = int(raw["id"])
+ prof.nodes[nid] = _call_frame(raw.get("callFrame") or {})
+ parent = raw.get("parent")
+ if parent is not None:
+ prof.parents[nid] = int(parent)
+ # Some producers give `children` instead of `parent`; honour both so
+ # ancestry does not silently collapse to a forest of roots.
+ for child in raw.get("children") or ():
+ prof.parents.setdefault(int(child), nid)
+
+ for tid_key, node_id in (cpu.get("trace_ids") or {}).items():
+ prof.trace_ids[str(tid_key)] = int(node_id)
+
+ sample_ids = cpu.get("samples") or []
+ deltas = data.get("timeDeltas") or []
+ if len(sample_ids) != len(deltas):
+ raise CellFailure(
+ "cpuprofile_chunk_ragged",
+ f"chunk at ts={e.get('ts')} has {len(sample_ids)} samples and "
+ f"{len(deltas)} timeDeltas; they must be 1:1",
+ )
+ cursor = prof.samples[-1].ts if prof.samples else prof.start_time
+ for nid, delta in zip(sample_ids, deltas):
+ d = int(delta)
+ if d < 0:
+ prof.negative_deltas += 1
+ cursor += d
+ prof.samples.append(Sample(ts = cursor, node_id = int(nid), delta = d))
+
+ prof.chunk_count += 1
+ ts = int(e.get("ts", 0))
+ prof.chunk_ts_first = ts if prof.chunk_count == 1 else prof.chunk_ts_first
+ prof.chunk_ts_last = max(prof.chunk_ts_last, ts)
+
+ return profiles
+
+
+def main_thread_profile(trace: Trace) -> CpuProfile:
+ """The CPU profile for the thread the renderer runs its main loop on."""
+ pid, tid = trace.profiled_thread()
+ profiles = parse_cpu_profiles(trace)
+ for prof in profiles.values():
+ if prof.pid == pid and prof.tid == tid:
+ return prof
+ raise CellFailure(
+ "no_cpu_profile",
+ f"no v8 CPU profile for the profiled thread {pid}:{tid}; "
+ "was disabled-by-default-v8.cpu_profiler included in the categories?",
+ )
+
+
+def rank_self_time(
+ profile: CpuProfile,
+ t0: int | None = None,
+ t1: int | None = None,
+ *,
+ include_synthetic: bool = False,
+ limit: int = 40,
+) -> list[tuple[CallFrame, int]]:
+ """Leaf frames by self time, descending."""
+ by_key = profile.self_time_us(t0, t1)
+ frames: dict[tuple[str, str, int, int], CallFrame] = {}
+ for f in profile.nodes.values():
+ frames.setdefault(f.key, f)
+ rows = []
+ for key, us in by_key.items():
+ frame = frames.get(key)
+ if frame is None:
+ continue
+ if frame.is_synthetic and not include_synthetic:
+ continue
+ rows.append((frame, us))
+ rows.sort(key = lambda r: -r[1])
+ return rows[:limit]
+
+
+def self_time_in_windows(
+ profile: CpuProfile,
+ windows: Sequence[tuple[int, int]],
+ *,
+ include_synthetic: bool = False,
+ limit: int = 40,
+) -> tuple[list[tuple[CallFrame, int]], dict[str, Any]]:
+ """Rank leaf frames across a set of disjoint time windows.
+
+ This is how a task ORIGIN becomes a NAMED FRAME: take the windows of every
+ task classified as, say, message-channel, and rank the leaves sampled inside
+ them. Windows are half-open and assumed non-overlapping, which holds for
+ top-level `RunTask` intervals on one thread.
+
+ The returned diagnostics carry `js_sample_count`, and callers must look at
+ it. Synthetic V8 frames ((program), (idle), (garbage collector)) routinely
+ dominate short windows at a 150 us sampling interval, so a ranking built
+ from a handful of JS samples is noise wearing a function name. Dropping the
+ synthetic frames silently would hide exactly that.
+ """
+ totals: dict[tuple[str, str, int, int], int] = {}
+ frames: dict[tuple[str, str, int, int], CallFrame] = {}
+ js_samples = 0
+ synthetic_us = 0
+ js_us = 0
+ for lo, hi in windows:
+ for s in profile.window(lo, hi):
+ frame = profile.nodes.get(s.node_id)
+ if frame is None:
+ continue
+ if frame.is_synthetic:
+ synthetic_us += s.delta
+ if not include_synthetic:
+ continue
+ else:
+ js_samples += 1
+ js_us += s.delta
+ frames.setdefault(frame.key, frame)
+ totals[frame.key] = totals.get(frame.key, 0) + s.delta
+ rows = [(frames[k], v) for k, v in totals.items() if k in frames]
+ rows.sort(key = lambda r: -r[1])
+ diagnostics = {
+ "windows": len(windows),
+ "window_us": sum(max(0, hi - lo) for lo, hi in windows),
+ "js_sample_count": js_samples,
+ "js_us": js_us,
+ "synthetic_us": synthetic_us,
+ "underpowered": js_samples < MIN_JS_SAMPLES_FOR_RANKING,
+ "min_js_samples_for_ranking": MIN_JS_SAMPLES_FOR_RANKING,
+ }
+ return rows[:limit], diagnostics
+
+
+def stacks_under(
+ profile: CpuProfile,
+ predicate_function_name: str,
+ t0: int | None = None,
+ t1: int | None = None,
+) -> list[tuple[int, list[CallFrame]]]:
+ """Every sampled stack that contains a named function, leaf first."""
+ out = []
+ for ts, stack in profile.stacked_samples(t0, t1):
+ if any(f.function_name == predicate_function_name for f in stack):
+ out.append((ts, stack))
+ return out
+
+
+def summarise(
+ profile: CpuProfile,
+ t0: int | None = None,
+ t1: int | None = None,
+) -> dict[str, Any]:
+ win = profile.window(t0, t1)
+ total = sum(s.delta for s in win)
+ synthetic = 0
+ for s in win:
+ f = profile.nodes.get(s.node_id)
+ if f is not None and f.is_synthetic:
+ synthetic += s.delta
+ return {
+ "samples": len(win),
+ "sampled_us": total,
+ "synthetic_us": synthetic,
+ "js_us": total - synthetic,
+ "sampling_interval_us": profile.sampling_interval_us(),
+ "nodes_known": len(profile.nodes),
+ "chunks": profile.chunk_count,
+ "negative_deltas": profile.negative_deltas,
+ }
+
+
+def iter_leaf_frames(
+ profile: CpuProfile, samples: Iterable[Sample] | None = None
+) -> Iterable[tuple[Sample, CallFrame | None]]:
+ for s in samples if samples is not None else profile.samples:
+ yield s, profile.nodes.get(s.node_id)
+
+
+def frames_matching(profile: CpuProfile, needles: Sequence[str]) -> list[CallFrame]:
+ """Every known frame whose function name contains any of `needles`."""
+ out: list[CallFrame] = []
+ seen: set[tuple[str, str, int, int]] = set()
+ for f in profile.nodes.values():
+ if f.key in seen:
+ continue
+ if any(n in f.function_name for n in needles):
+ seen.add(f.key)
+ out.append(f)
+ return out
diff --git a/tests/studio/studiobench/analysis/fit.py b/tests/studio/studiobench/analysis/fit.py
new file mode 100644
index 00000000000..018f1c711d7
--- /dev/null
+++ b/tests/studio/studiobench/analysis/fit.py
@@ -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
+
+"""Growth exponents, fitted WITHIN ONE SESSION, and the severity ranking.
+
+`log(self_time_f) = a + b * log(L)` across the length ladder. The exponent `b`
+is what separates a frame that is merely expensive from a frame that is the
+reason long threads get worse: `b ~ 0` is a fixed cost, `b ~ 1` is linear in
+thread length, `b ~ 2` is the quadratic re-parse.
+
+CROSS-SESSION FITS ARE VOID AND THIS MODULE REFUSES TO PRODUCE ONE. The same
+cell drifts about 8% between sessions on the same machine. Two rungs measured in
+different sessions can therefore differ by 8% for no reason at all, and across a
+ladder spanning one decade of length that manufactures an exponent of roughly
+log(1.08)/log(10) = 0.03 out of pure drift, or far more when the ladder is
+short. Every point carries a `session` tag and `fit_loglog` raises if the tags
+are not all equal. This is not a warning that can be waved through, because a
+fit is exactly the kind of number that looks authoritative once it is in a
+table.
+
+Ranking is
+
+ severity = self_ms(L_max) * max(0, b_frame - b_task)
+
+Absolute cost at the top rung, weighted by how much FASTER the frame grows than
+total task time. The clamp at zero matters: a frame that grows more slowly than
+the total is getting relatively cheaper as threads lengthen, so however large it
+is, it is not the reason the curve bends. Multiplying rather than adding means a
+frame must be both big and steepening; either alone scores nothing.
+"""
+
+from __future__ import annotations
+
+import math
+import random
+from dataclasses import dataclass, field
+from typing import Any, Iterable, Sequence
+
+from . import CellFailure
+
+
+@dataclass(frozen = True)
+class Point:
+ """One rung of one series, tagged with the session that produced it."""
+
+ length: float # the treatment axis, e.g. thread tokens or characters
+ value: float # the measured quantity, e.g. self ms
+ session: str # opaque session identity; fits refuse to mix these
+ rung: str = ""
+
+
+@dataclass(frozen = True)
+class Fit:
+ a: float # intercept in log space
+ b: float # exponent
+ r2: float
+ n: int
+ session: str
+ b_ci: tuple[float, float] | None = None
+ x_min: float = 0.0
+ x_max: float = 0.0
+
+ def predict(self, length: float) -> float:
+ return math.exp(self.a + self.b * math.log(length))
+
+ def as_row(self) -> dict[str, Any]:
+ row: dict[str, Any] = {
+ "exponent_b": round(self.b, 4),
+ "intercept_a": round(self.a, 4),
+ "r2": round(self.r2, 4),
+ "points": self.n,
+ "session": self.session,
+ }
+ if self.b_ci is not None:
+ row["b_ci95"] = [round(self.b_ci[0], 4), round(self.b_ci[1], 4)]
+ return row
+
+
+def _ols(xs: Sequence[float], ys: Sequence[float]) -> tuple[float, float, float]:
+ n = len(xs)
+ mx = sum(xs) / n
+ my = sum(ys) / n
+ sxx = sum((x - mx) ** 2 for x in xs)
+ if sxx <= 0:
+ raise CellFailure("fit_degenerate", "every point sits at the same length; no slope exists")
+ sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
+ b = sxy / sxx
+ a = my - b * mx
+ ss_tot = sum((y - my) ** 2 for y in ys)
+ ss_res = sum((y - (a + b * x)) ** 2 for x, y in zip(xs, ys))
+ r2 = 1.0 - (ss_res / ss_tot) if ss_tot > 0 else 1.0
+ return a, b, r2
+
+
+def fit_loglog(
+ points: Sequence[Point],
+ *,
+ bootstrap: int = 2000,
+ seed: int = 20260819,
+ min_points: int = 3,
+) -> Fit:
+ """Fit `log(value) = a + b * log(length)` over one session's ladder.
+
+ Zero and negative values are DROPPED, not floored. A frame that did not run
+ at a rung has no logarithm, and substituting an epsilon would invent a data
+ point at whatever exponent the epsilon implies. The number of points
+ actually used is reported so a fit over two surviving rungs is visible as
+ such.
+ """
+ sessions = {p.session for p in points}
+ if len(sessions) > 1:
+ raise CellFailure(
+ "cross_session_fit",
+ f"points span {len(sessions)} sessions ({sorted(sessions)}). The same cell "
+ "drifts about 8% between sessions, which alone manufactures a nonzero "
+ "exponent, so a cross-session fit is void.",
+ )
+ usable = [p for p in points if p.length > 0 and p.value > 0]
+ if len(usable) < min_points:
+ raise CellFailure(
+ "fit_underpowered",
+ f"{len(usable)} usable points (need {min_points}); "
+ f"{len(points) - len(usable)} were dropped for non-positive length or value",
+ )
+ xs = [math.log(p.length) for p in usable]
+ ys = [math.log(p.value) for p in usable]
+ a, b, r2 = _ols(xs, ys)
+
+ ci: tuple[float, float] | None = None
+ if bootstrap and len(usable) >= 4:
+ rng = random.Random(seed)
+ slopes: list[float] = []
+ idx = range(len(usable))
+ for _ in range(bootstrap):
+ pick = [rng.choice(idx) for _ in idx]
+ bx = [xs[i] for i in pick]
+ by = [ys[i] for i in pick]
+ try:
+ slopes.append(_ols(bx, by)[1])
+ except CellFailure:
+ continue
+ if len(slopes) >= 100:
+ slopes.sort()
+ lo = slopes[int(0.025 * len(slopes))]
+ hi = slopes[min(len(slopes) - 1, int(0.975 * len(slopes)))]
+ ci = (lo, hi)
+
+ return Fit(
+ a = a,
+ b = b,
+ r2 = r2,
+ n = len(usable),
+ session = next(iter(sessions)) if sessions else "",
+ b_ci = ci,
+ x_min = min(p.length for p in usable),
+ x_max = max(p.length for p in usable),
+ )
+
+
+@dataclass
+class FrameGrowth:
+ """One call frame's cost and growth across a ladder, plus its severity."""
+
+ frame_label: str
+ frame_key: tuple[str, str, int, int]
+ points: list[Point] = field(default_factory = list)
+ fit: Fit | None = None
+ self_ms_at_max: float = 0.0
+ severity: float = 0.0
+ bridged_name: str | None = None
+ exact_call_count: int | None = None
+
+ def as_row(self) -> dict[str, Any]:
+ row: dict[str, Any] = {
+ "frame": self.bridged_name or self.frame_label,
+ "raw_frame": self.frame_label,
+ "self_ms_at_L_max": round(self.self_ms_at_max, 3),
+ "severity": round(self.severity, 4),
+ "bridged": self.bridged_name is not None,
+ }
+ if self.exact_call_count is not None:
+ row["exact_call_count"] = self.exact_call_count
+ if self.fit is not None:
+ row.update(self.fit.as_row())
+ return row
+
+
+def severity(self_ms_at_max: float, b_frame: float, b_task: float) -> float:
+ """Absolute cost weighted by how much faster the frame grows than the total.
+
+ Clamped at zero on the exponent difference: a frame growing more slowly than
+ total task time is becoming a smaller share of the problem as threads
+ lengthen, so it cannot be the reason the curve bends, no matter how many
+ milliseconds it costs today.
+ """
+ return self_ms_at_max * max(0.0, b_frame - b_task)
+
+
+def rank_frames(
+ series: dict[tuple[str, str, int, int], list[Point]],
+ labels: dict[tuple[str, str, int, int], str],
+ task_total_points: Sequence[Point],
+ *,
+ bootstrap: int = 2000,
+ min_points: int = 3,
+) -> tuple[list[FrameGrowth], dict[str, Any]]:
+ """Fit every frame, fit the task total, rank by severity.
+
+ Returns the ranking and a diagnostics block naming every frame that could
+ not be fitted and why. A frame dropped for having too few rungs is a fact
+ about coverage of the ladder, not a fact about the frame, and silently
+ omitting it would make the ranking look more complete than it is.
+ """
+ task_fit = fit_loglog(task_total_points, bootstrap = bootstrap, min_points = min_points)
+ rows: list[FrameGrowth] = []
+ skipped: dict[str, str] = {}
+ for key, pts in series.items():
+ label = labels.get(key, str(key))
+ try:
+ f = fit_loglog(pts, bootstrap = bootstrap, min_points = min_points)
+ except CellFailure as exc:
+ skipped[label] = exc.detail
+ continue
+ at_max = max(pts, key = lambda p: p.length)
+ g = FrameGrowth(
+ frame_label = label,
+ frame_key = key,
+ points = list(pts),
+ fit = f,
+ self_ms_at_max = at_max.value,
+ )
+ g.severity = severity(g.self_ms_at_max, f.b, task_fit.b)
+ rows.append(g)
+ rows.sort(key = lambda g: -g.severity)
+ diagnostics = {
+ "task_total_fit": task_fit.as_row(),
+ "frames_fitted": len(rows),
+ "frames_skipped": skipped,
+ "session": task_fit.session,
+ }
+ return rows, diagnostics
+
+
+def growth_is_superlinear(fit: Fit, *, margin: float = 0.15) -> bool:
+ """Is the exponent above 1 by more than the fit's own uncertainty?
+
+ Uses the bootstrap lower bound when there is one, because "b = 1.4" from
+ three noisy points is not evidence of superlinearity and reading it as such
+ is how an O(n) mechanism gets reported as O(n^2).
+ """
+ if fit.b_ci is not None:
+ return fit.b_ci[0] > 1.0
+ return fit.b > 1.0 + margin
+
+
+def collect_series(
+ per_rung: Iterable[tuple[str, float, dict[tuple[str, str, int, int], float]]], session: str
+) -> dict[tuple[str, str, int, int], list[Point]]:
+ """Reshape per-rung frame tables into per-frame ladders.
+
+ Input is (rung label, rung length, {frame key: self ms}). A frame absent at
+ a rung contributes no point rather than a zero, since a zero has no
+ logarithm and inventing one at the bottom of the ladder tilts every
+ exponent upward.
+ """
+ out: dict[tuple[str, str, int, int], list[Point]] = {}
+ for rung, length, table in per_rung:
+ for key, value in table.items():
+ out.setdefault(key, []).append(
+ Point(length = length, value = value, session = session, rung = rung)
+ )
+ return out
diff --git a/tests/studio/studiobench/analysis/oracles.py b/tests/studio/studiobench/analysis/oracles.py
new file mode 100644
index 00000000000..1b0afa43335
--- /dev/null
+++ b/tests/studio/studiobench/analysis/oracles.py
@@ -0,0 +1,511 @@
+# 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 line between a NAMING and an `unexplained_hot_frame`.
+
+A hot frame with a bridged name is not yet an explanation. `Zk` resolving to
+`cloneChildFibers` tells you what the code is called; it does not tell you why
+it ran 4,110 times, and without that the next step is guesswork.
+
+A NAMING requires the frame's EXACT invocation count, from precise coverage, to
+equal a STRUCTURAL quantity measured independently: blocks x renders,
+subscribers x notifies, siblings x updates. Independently means the structural
+quantity was counted from the DOM or from the app's own instrumentation, not
+derived from the same trace. When those two integers agree, the mechanism is
+identified, the fix is implied, and the prediction is falsifiable at the next
+rung.
+
+When nothing matches, the frame is emitted as `unexplained_hot_frame` carrying
+its bridged name, its exponent and its exact count. That is an honest partial
+result and it is enormously more than a residual: someone can read it, recognise
+the name, and know where to look. What it must never do is get quietly rounded
+into whichever oracle is closest.
+
+NEAR MISSES ARE REPORTED, NOT ACCEPTED. An exact 2x is the signature of React's
+StrictMode double invoke; an exact ratio of (n+1)/n is the signature of counting
+a root along with its children. Those are diagnoses in their own right, so the
+integer ratio is printed. It never promotes a match to a naming.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from fractions import Fraction
+from typing import Any, Callable, Sequence
+
+NAMING = "naming"
+NEAR_MISS = "near_miss"
+UNEXPLAINED = "unexplained_hot_frame"
+NOT_MEASURED = "not_measured"
+
+# Integer ratios worth naming when a count is off by a clean factor. Each has a
+# specific mechanical meaning, so reporting the ratio hands over a hypothesis
+# rather than a mystery.
+_KNOWN_RATIOS: dict[Fraction, str] = {
+ Fraction(
+ 2, 1
+ ): "exactly 2x predicted: React StrictMode double invoke, or the render ran twice per commit",
+ Fraction(
+ 1, 2
+ ): "exactly half predicted: the structural count is double counting, or only one of two passes is instrumented",
+ Fraction(3, 1): "exactly 3x predicted: three passes over the same structure",
+}
+
+
+@dataclass(frozen = True)
+class StructuralQuantity:
+ """A count measured from the app, independently of the profile.
+
+ `source` must say where the number came from. An oracle whose structural
+ side was derived from the same trace as the frame count proves nothing and
+ the field exists to make that visible in the report.
+ """
+
+ name: str
+ value: int
+ source: str
+ components: dict[str, int] = field(default_factory = dict)
+
+ def describe(self) -> str:
+ if self.components:
+ parts = " x ".join(f"{v} {k}" for k, v in self.components.items())
+ return f"{self.value} ({parts}, from {self.source})"
+ return f"{self.value} (from {self.source})"
+
+
+@dataclass
+class OracleVerdict:
+ frame: str
+ verdict: str
+ exact_call_count: int | None
+ quantity: StructuralQuantity | None
+ detail: str
+ ratio: str | None = None
+
+ def as_row(self) -> dict[str, Any]:
+ row: dict[str, Any] = {
+ "frame": self.frame,
+ "verdict": self.verdict,
+ "detail": self.detail,
+ }
+ if self.exact_call_count is not None:
+ row["exact_call_count"] = self.exact_call_count
+ if self.quantity is not None:
+ row["structural_quantity"] = self.quantity.describe()
+ row["structural_name"] = self.quantity.name
+ if self.ratio:
+ row["integer_ratio"] = self.ratio
+ return row
+
+ @property
+ def is_naming(self) -> bool:
+ return self.verdict == NAMING
+
+
+def blocks_times_renders(blocks: int, renders: int, source: str) -> StructuralQuantity:
+ """M1's prediction: one work-in-progress fiber cloned per sibling per render.
+
+ `memo` stops a child RENDERING but not React REACHING it.
+ `bailoutOnAlreadyFinishedWork` returns null only when `childLanes` is clear,
+ so an update anywhere in the subtree still walks every sibling and clones
+ one fiber each. With a flat, unvirtualised message list that is
+ blocks x renders clones per chunk, and it is invisible to `<Profiler>`
+ because it is fiber bookkeeping and not component render.
+
+ NAME THE RIGHT FUNCTION. `cloneChildFibers` DOES NOT EXIST IN REACT 19.2.
+ Grepping `[email protected]`'s development bundle finds zero occurrences of
+ it; it was inlined at some point before 19. The functions that do exist, and
+ that a symbol bridge built against a real 19.2.4 profiling bundle does
+ resolve, are `createWorkInProgress` (10 occurrences) and
+ `bailoutOnAlreadyFinishedWork` (10). Point this oracle at those. An oracle
+ aimed at a function that does not exist returns `not_measured` forever and
+ reads as "M1 is not happening", which is the wrong conclusion drawn from a
+ stale function name.
+ """
+ return StructuralQuantity(
+ name = "blocks_x_renders",
+ value = blocks * renders,
+ source = source,
+ components = {"blocks": blocks, "renders": renders},
+ )
+
+
+def subscribers_times_notifies(subscribers: int, notifies: int, source: str) -> StructuralQuantity:
+ """An external-store subscription fanout: every store notify hits every subscriber."""
+ return StructuralQuantity(
+ name = "subscribers_x_notifies",
+ value = subscribers * notifies,
+ source = source,
+ components = {"subscribers": subscribers, "notifies": notifies},
+ )
+
+
+def chars_times_deltas(chars: int, deltas: int, source: str) -> StructuralQuantity:
+ """M2's prediction: the cumulative buffer is re-parsed once per delta.
+
+ The count that matters for the re-parse is characters rescanned, so this is
+ a quantity to compare against a character counter rather than against a call
+ count; it is here so the M2 oracle has the same shape as the others.
+ """
+ return StructuralQuantity(
+ name = "chars_x_deltas",
+ value = chars * deltas,
+ source = source,
+ components = {"chars": chars, "deltas": deltas},
+ )
+
+
+def mutations_times_thread_nodes(mutations: int, nodes: int, source: str) -> StructuralQuantity:
+ """M3's prediction: one observer callback per mutation, each reading layout over the whole thread."""
+ return StructuralQuantity(
+ name = "mutations_x_thread_nodes",
+ value = mutations * nodes,
+ source = source,
+ components = {"mutations": mutations, "thread_nodes": nodes},
+ )
+
+
+def _ratio_note(measured: int, predicted: int) -> str | None:
+ if predicted <= 0 or measured <= 0:
+ return None
+ fr = Fraction(measured, predicted)
+ known = _KNOWN_RATIOS.get(fr)
+ if known:
+ return known
+ if fr.denominator == 1 and 1 < fr.numerator <= 16:
+ return f"exactly {fr.numerator}x predicted"
+ if fr.numerator == 1 and 1 < fr.denominator <= 16:
+ return f"exactly 1/{fr.denominator} of predicted"
+ # Off by one structural unit, e.g. counting a root alongside its children.
+ if abs(measured - predicted) <= 2:
+ return f"off by {measured - predicted:+d}, within one structural unit"
+ return None
+
+
+def check(
+ frame: str, exact_call_count: int | None, quantities: Sequence[StructuralQuantity]
+) -> OracleVerdict:
+ """Compare one frame's exact count against every candidate structural quantity.
+
+ EXACT equality is required for a naming. No tolerance, no rounding. The
+ whole value of an exact count is that it is exact; a count oracle with a 5%
+ tolerance is a correlation with extra steps, and it will match something
+ eventually.
+ """
+ if exact_call_count is None:
+ return OracleVerdict(
+ frame = frame,
+ verdict = NOT_MEASURED,
+ exact_call_count = None,
+ quantity = None,
+ detail = (
+ "no precise-coverage count for this frame. Without an exact integer "
+ "there is nothing to match against a structural quantity, so this "
+ "frame cannot be named however hot it is."
+ ),
+ )
+
+ for q in quantities:
+ if q.value == exact_call_count:
+ return OracleVerdict(
+ frame = frame,
+ verdict = NAMING,
+ exact_call_count = exact_call_count,
+ quantity = q,
+ detail = f"ran exactly {exact_call_count} times = {q.describe()}",
+ )
+
+ best: tuple[StructuralQuantity, str] | None = None
+ for q in quantities:
+ note = _ratio_note(exact_call_count, q.value)
+ if note is not None:
+ best = (q, note)
+ break
+
+ if best is not None:
+ q, note = best
+ return OracleVerdict(
+ frame = frame,
+ verdict = NEAR_MISS,
+ exact_call_count = exact_call_count,
+ quantity = q,
+ ratio = note,
+ detail = (
+ f"ran exactly {exact_call_count} times against a predicted {q.describe()}; "
+ f"{note}. A near miss is a hypothesis about the discrepancy, not a naming."
+ ),
+ )
+
+ return OracleVerdict(
+ frame = frame,
+ verdict = UNEXPLAINED,
+ exact_call_count = exact_call_count,
+ quantity = None,
+ detail = (
+ f"ran exactly {exact_call_count} times, matching none of "
+ f"{[q.describe() for q in quantities] or 'any supplied quantity'}. "
+ "Reported with its bridged name and exponent so it can be looked up; "
+ "this is a partial result, not a residual."
+ ),
+ )
+
+
+def check_all(
+ frames: Sequence[tuple[str, int | None]], quantities: Sequence[StructuralQuantity]
+) -> dict[str, Any]:
+ verdicts = [check(name, count, quantities) for name, count in frames]
+ namings = [v for v in verdicts if v.is_naming]
+ return {
+ "namings": [v.as_row() for v in namings],
+ "near_misses": [v.as_row() for v in verdicts if v.verdict == NEAR_MISS],
+ "unexplained_hot_frames": [v.as_row() for v in verdicts if v.verdict == UNEXPLAINED],
+ "not_measured": [v.as_row() for v in verdicts if v.verdict == NOT_MEASURED],
+ "named_at_least_one_frame": bool(namings),
+ }
+
+
+def predicted_next_rung(
+ quantity_fn: Callable[[int], StructuralQuantity], next_structural_input: int
+) -> int:
+ """The count a naming PREDICTS at the next rung.
+
+ A naming that cannot predict forward is a coincidence that has not been
+ caught yet. Emitting the prediction before the next rung runs is what makes
+ it falsifiable.
+ """
+ return quantity_fn(next_structural_input).value
+
+
+# ═══════════════════════════════════════════════════════════════════════════
+# M2 and M3: oracle shapes over PAGE-SIDE counters
+# ═══════════════════════════════════════════════════════════════════════════
+#
+# M1 is settled with a call count from precise coverage, because the mechanism
+# lives inside react-dom where we can count invocations. M2 and M3 do not work
+# that way: their cost is in how much text is rescanned and how much layout is
+# forced, and neither is an invocation count. Those must be counted IN THE PAGE.
+#
+# Layer 3 owns `instruments/layoutcost.js` and already counts `scrollHeight`
+# reads, `scrollTop` writes and MutationObserver callbacks. This section does
+# NOT duplicate that file. It fixes the KEY NAMES that file should emit and
+# supplies the oracles that consume them, so that the counting and the
+# interpretation are owned separately and neither has to guess at the other.
+#
+# ONE HONEST DIFFERENCE, stated plainly rather than buried. The M1 oracle is an
+# EXACT INTEGER MATCH and it either holds or it does not. The M2 oracle is a
+# REGIME TEST: SSE deltas do not arrive in equal sizes, so the quadratic
+# prediction is exact only for a uniform stream and must be compared as a ratio
+# with a refusal band. That is weaker evidence and it is labelled as such
+# everywhere it is emitted. Do not let a regime verdict sit in a table next to a
+# naming as though they were the same thing.
+
+REGIME_QUADRATIC = "cumulative_reparse_quadratic"
+REGIME_LINEAR = "incremental_parse_linear"
+REGIME_UNDECIDED = "undecided"
+
+# The counters Layer 3's page-side instrument should emit, per streamed reply.
+# Every one is an integer; none is a duration.
+PAGE_COUNTER_CONTRACT: dict[str, dict[str, str]] = {
+ "m2_reparse": {
+ "parse_calls": "invocations of parseAssistantContent during the reply",
+ "chars_rescanned": "SUM of the input length over those invocations; the whole point",
+ "deltas_received": "SSE delta events applied to the cumulative buffer",
+ "final_content_chars": "length of the cumulative buffer when the reply completed",
+ "think_tracker_calls": "invocations of createThinkTagTracker over the same window",
+ },
+ "m3_forced_layout": {
+ "observer_callbacks": "MutationObserver callback invocations on the viewport subtree",
+ "forced_layouts": "reads of scrollHeight/offsetHeight/getBoundingClientRect that flushed layout",
+ "scroll_writes": "scrollTo / scrollTop writes issued by the autoscroll path",
+ "stabilizer_writes": "writes of the --aui-scroll-stabilizer custom property",
+ "thread_nodes": "DOM node count inside the scroll container at the end of the window",
+ },
+}
+
+
+def cumulative_reparse_chars(
+ final_content_chars: int, deltas: int, source: str
+) -> StructuralQuantity:
+ """M2 under the CUMULATIVE hypothesis: the whole buffer is re-parsed per delta.
+
+ If `parseAssistantContent(cumulativeText)` runs on every delta, the i-th
+ delta rescans roughly `i * final/deltas` characters, so the total is
+
+ final * (deltas + 1) / 2
+
+ which is quadratic in reply length at fixed delta size. Exact only for a
+ uniform stream; see the module note about this being a regime test.
+ """
+ value = int(final_content_chars * (deltas + 1) / 2) if deltas > 0 else 0
+ return StructuralQuantity(
+ name = "cumulative_reparse_chars",
+ value = value,
+ source = source,
+ components = {"final_chars": final_content_chars, "deltas": deltas},
+ )
+
+
+def incremental_parse_chars(final_content_chars: int, source: str) -> StructuralQuantity:
+ """M2 under the NULL hypothesis: each delta is parsed once, so total = final length."""
+ return StructuralQuantity(
+ name = "incremental_parse_chars",
+ value = int(final_content_chars),
+ source = source,
+ components = {"final_chars": final_content_chars},
+ )
+
+
+def reparse_regime(
+ chars_rescanned: int,
+ final_content_chars: int,
+ deltas: int,
+ *,
+ refusal_band: float = 2.0,
+) -> dict[str, Any]:
+ """Which regime is the measured rescan count in?
+
+ Compares the measurement against the linear and quadratic predictions in log
+ space and refuses to call it when the two predictions are within
+ `refusal_band` of each other, which happens on short replies where a handful
+ of deltas makes the quadratic prediction indistinguishable from the linear
+ one. Refusing on a short reply is correct: the mechanism is real or not
+ regardless, but that reply cannot show it.
+ """
+ quad = cumulative_reparse_chars(final_content_chars, deltas, "prediction").value
+ lin = incremental_parse_chars(final_content_chars, "prediction").value
+ out: dict[str, Any] = {
+ "chars_rescanned": int(chars_rescanned),
+ "linear_prediction": lin,
+ "quadratic_prediction": quad,
+ "evidence_class": "regime_test",
+ "evidence_note": (
+ "a regime verdict is WEAKER evidence than a naming: it is a ratio "
+ "comparison with a refusal band, not an exact integer match"
+ ),
+ }
+ if lin <= 0 or quad <= 0 or chars_rescanned <= 0:
+ out["regime"] = REGIME_UNDECIDED
+ out["reason"] = "a prediction or the measurement was non-positive; nothing to compare"
+ return out
+ if quad < lin * refusal_band:
+ out["regime"] = REGIME_UNDECIDED
+ out["reason"] = (
+ f"the two predictions are only {quad / lin:.2f}x apart, below the {refusal_band}x "
+ "refusal band. This reply is too short to distinguish the regimes; use a longer rung."
+ )
+ return out
+ # Closer in log space wins; the ratio is reported either way so a reader can
+ # see how decisive the call was.
+ r_lin = chars_rescanned / lin
+ r_quad = chars_rescanned / quad
+ out["ratio_to_linear"] = round(r_lin, 3)
+ out["ratio_to_quadratic"] = round(r_quad, 3)
+ import math
+
+ if abs(math.log(r_quad)) < abs(math.log(r_lin)):
+ out["regime"] = REGIME_QUADRATIC
+ out["reason"] = (
+ f"rescanned {chars_rescanned} chars, {r_quad:.2f}x the cumulative-reparse "
+ f"prediction and {r_lin:.1f}x the incremental one"
+ )
+ else:
+ out["regime"] = REGIME_LINEAR
+ out["reason"] = (
+ f"rescanned {chars_rescanned} chars, {r_lin:.2f}x the incremental prediction; "
+ "the cumulative re-parse is NOT firing on this path"
+ )
+ return out
+
+
+def forced_layout_per_callback(
+ observer_callbacks: int, forced_layouts: int, source: str
+) -> OracleVerdict:
+ """M3's exact oracle: one forced layout per observer callback.
+
+ This one IS an exact integer match, unlike M2. `stabilize()` reads
+ `scrollHeight` synchronously inside the MutationObserver callback, so if the
+ mechanism is live the two counters are equal. A forced-layout count BELOW
+ the callback count means the read is being skipped or batched on some
+ callbacks, which is a different and much cheaper story; ABOVE means
+ something else is also forcing layout and M3 is not the whole cost.
+ """
+ return check(
+ "autoscroll MutationObserver forced layout",
+ forced_layouts,
+ [
+ StructuralQuantity(
+ name = "observer_callbacks",
+ value = observer_callbacks,
+ source = source,
+ components = {"observer_callbacks": observer_callbacks},
+ )
+ ],
+ )
+
+
+def forced_layout_cost_quantity(
+ forced_layouts: int, thread_nodes: int, source: str
+) -> StructuralQuantity:
+ """M3's cost shape: each forced layout is proportional to the whole thread.
+
+ The mechanism is invisible to a React Profiler, to markdown timing and to a
+ DOM census, and it grows with THREAD SIZE rather than with reply length,
+ which is what distinguishes it from M2. Compare against the growth exponent
+ of layout time, not against a call count.
+ """
+ return StructuralQuantity(
+ name = "forced_layouts_x_thread_nodes",
+ value = forced_layouts * thread_nodes,
+ source = source,
+ components = {"forced_layouts": forced_layouts, "thread_nodes": thread_nodes},
+ )
+
+
+def evaluate_page_counters(counters: dict[str, Any]) -> dict[str, Any]:
+ """Run the M2 and M3 oracles over one window's page-side counter block.
+
+ `counters` is the dict Layer 3's page instrument emits, keyed as in
+ `PAGE_COUNTER_CONTRACT`. Missing groups produce an explicit skip with a
+ reason, never a silent absence, because "M3 did not fire" and "nobody
+ counted" must not look the same in a report.
+ """
+ out: dict[str, Any] = {}
+
+ m2 = counters.get("m2_reparse")
+ if not isinstance(m2, dict):
+ out["m2"] = {"skipped": True, "reason": "no m2_reparse counter block was emitted"}
+ else:
+ missing = [
+ k for k in ("chars_rescanned", "final_content_chars", "deltas_received") if k not in m2
+ ]
+ if missing:
+ out["m2"] = {"skipped": True, "reason": f"m2_reparse is missing {missing}"}
+ else:
+ out["m2"] = reparse_regime(
+ int(m2["chars_rescanned"]),
+ int(m2["final_content_chars"]),
+ int(m2["deltas_received"]),
+ )
+
+ m3 = counters.get("m3_forced_layout")
+ if not isinstance(m3, dict):
+ out["m3"] = {"skipped": True, "reason": "no m3_forced_layout counter block was emitted"}
+ else:
+ missing = [k for k in ("observer_callbacks", "forced_layouts") if k not in m3]
+ if missing:
+ out["m3"] = {"skipped": True, "reason": f"m3_forced_layout is missing {missing}"}
+ else:
+ verdict = forced_layout_per_callback(
+ int(m3["observer_callbacks"]),
+ int(m3["forced_layouts"]),
+ source = "page counters",
+ )
+ block = verdict.as_row()
+ if "thread_nodes" in m3:
+ block["cost_quantity"] = forced_layout_cost_quantity(
+ int(m3["forced_layouts"]),
+ int(m3["thread_nodes"]),
+ source = "page counters",
+ ).describe()
+ out["m3"] = block
+ return out
diff --git a/tests/studio/studiobench/analysis/parity.py b/tests/studio/studiobench/analysis/parity.py
new file mode 100644
index 00000000000..56de8cd2cf8
--- /dev/null
+++ b/tests/studio/studiobench/analysis/parity.py
@@ -0,0 +1,343 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Comparing two parity captures, and deciding what the comparison is allowed to mean.
+
+`scene/parity.js` produces the reading; this decides what it says. The two are kept apart because
+the reading is taken inside a browser and the decision has to be unit-testable without one.
+
+THE RULE THIS FILE EXISTS TO ENFORCE. There are three outcomes of holding two captures side by
+side, not two, and collapsing the third into either of the others is how an instrument starts
+lying:
+
+ MATCH both arms were digested and the digests agree.
+ DIFFER both arms were digested and the digests disagree.
+ NOT COMPARABLE one arm has no digest, or the two were taken over different roots, or one
+ side's style probe was capped and the other's was not.
+
+`NOT COMPARABLE` is never folded into `MATCH`. A capture that failed and a capture that matched
+are the same absence of a complaint, and telling them apart is the entire difference between an
+instrument and a decoration.
+"""
+
+from __future__ import annotations
+
+import collections
+from typing import Any, Iterable, Optional
+
+# What a comparison concluded. Kept as plain strings so a payload row carries them verbatim.
+MATCH = "match"
+DIFFER = "differ"
+NOT_COMPARABLE = "not_comparable"
+NOT_EXERCISED = "not_exercised"
+
+# 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.
+#
+# A MECHANISM PER ENTRY, not a hunch, and the value is the mechanism rather than a comment beside
+# it so that a test can require one. An action silenced without a stated reason is a hole somebody
+# punched in the instrument and nobody can audit afterwards; the null control's empirically
+# derived set (`derive_unstable`) is the cross-check that each of these earns its place.
+UNSTABLE_ACTIONS: dict[str, str] = {
+ "stop_generation": "stops a live stream, so how many characters arrived before the stop is a race with the "
+ "network and differs run to run on one build. NOT reproduced by the 100K fast-tier null "
+ "control (0 of 4), so this entry rests on the mechanism rather than on a measurement",
+ "send_turn": "starts a new turn, so how far it has streamed when the digest is taken is wall clock. "
+ "Measured differing on 2 of 4 base-vs-base pairs, with assistant_chars differing too",
+ "scroll_during_generation": "the digest is taken after a scroll gesture against a growing thread; where it comes to "
+ "rest depends on the autoscroll observer, which is the mechanism under study. Measured "
+ "differing on 3 of 4 base-vs-base pairs",
+ "scroll_after": "same gesture against a settled thread; the resting offset still depends on the observer. "
+ "NOT reproduced by the 100K fast-tier null control (0 of 4); kept on the mechanism alone",
+ # The four below were NOT in the hand-written set and were found by the null control, each
+ # scoring as a hard UI-change signal on a build compared with itself. The mechanism for each
+ # was read out of the payload, not guessed.
+ "keystroke": "types characters into the composer over wall clock, and the composer's text is in the "
+ "DOM, so how many keystrokes had landed by the capture deadline is a race. Measured 4 of "
+ "4 differing, by 8 signature characters, with assistant_chars identical",
+ "composer_fill": "fills the composer with a fixed string, but whether the send button has re-enabled by "
+ "capture time is a race. A bare `disabled` serialises as exactly ten characters and the "
+ "observed delta was exactly ten, in both directions across repetitions",
+ "copy_markdown": "on the packed films this slot opens while the turn started by the preceding send_turn is "
+ "still streaming, so the last assistant message is mid-tail. Measured 3 of 4 differing, "
+ "with assistant_chars differing on every one",
+ "message_menu": "same cause as copy_markdown: the slot lands inside the previous send_turn's stream. "
+ "Measured 3 of 4 differing, with assistant_chars differing",
+ "select_text": "same cause again, and the worst of the three at 4 of 4 differing; the selection is taken "
+ "over a message whose tail is still arriving",
+}
+
+
+def _messages(capture: dict) -> dict[int, dict]:
+ return {m["i"]: m for m in (capture.get("messages") or []) if "i" in m}
+
+
+def _overlays(capture: dict) -> list[dict]:
+ return list(capture.get("overlays") or [])
+
+
+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)):
+ if not isinstance(side, dict):
+ return f"{label} recorded no parity capture at all"
+ if not side.get("parity_attempted"):
+ return (
+ f"{label} could not be captured: " f"{side.get('reason') or 'no reason recorded'}"
+ )
+ assert base is not None and treat is not None
+ # `root_kind` is absent in captures taken before it was recorded. Missing on BOTH sides is an
+ # old payload and is allowed through; missing on one side means the two runs were produced by
+ # two different versions of the instrument, which is not a comparison of two builds.
+ bk, tk = base.get("root_kind"), treat.get("root_kind")
+ if (bk is None) != (tk is None):
+ return (
+ "the two arms were captured by different versions of the parity instrument "
+ f"(root_kind base={bk!r} treatment={tk!r})"
+ )
+ if bk is not None and bk != tk:
+ return (
+ f"the arms digested different roots (base={bk}, treatment={tk}); a body-root "
+ "capture includes the sidebar and header and is not comparable with a thread one"
+ )
+ return None
+
+
+def localise(base: dict, treat: dict) -> list[str]:
+ """WHERE the two captures differ, as short human-readable claims.
+
+ A whole-thread digest that differs is a fact nobody can act on. The per-message and per-overlay
+ rows are what turn it into a bug report, and an unlocalised difference is reported as exactly
+ that rather than left to look like a localised one.
+ """
+ moved: list[str] = []
+ bm, tm = _messages(base), _messages(treat)
+ for i in sorted(set(bm) | set(tm)):
+ if i not in bm:
+ moved.append(f"msg{i}({tm[i].get('role', '?')}):only treatment")
+ elif i not in tm:
+ moved.append(f"msg{i}({bm[i].get('role', '?')}):only base")
+ elif bm[i].get("digest") != tm[i].get("digest"):
+ moved.append(
+ f"msg{i}({bm[i].get('role', '?')}):" f"{bm[i].get('chars')}->{tm[i].get('chars')}c"
+ )
+
+ bo, to = _overlays(base), _overlays(treat)
+ if len(bo) != len(to):
+ moved.append(f"overlays {len(bo)}->{len(to)}")
+ else:
+ for k, (b, t) in enumerate(zip(bo, to)):
+ if b.get("digest") != t.get("digest"):
+ moved.append(f"overlay{k}[{b.get('sel')}]:{b.get('chars')}->{t.get('chars')}c")
+
+ if not moved:
+ # The whole-thread digest moved but no message and no overlay did. That is the thread
+ # scaffolding itself -- the viewport, the composer, the empty-state -- and saying so is
+ # more useful than an empty list, which reads as "nothing differs".
+ moved.append(
+ f"thread scaffolding outside any message "
+ f"({base.get('chars')}->{treat.get('chars')}c)"
+ )
+ return moved
+
+
+def compare_styles(base: dict, treat: dict) -> tuple[str, str]:
+ """The bounded computed-style probe, as its own verdict.
+
+ Reported apart from the structural digest because it is the only reading here that can see a
+ stylesheet change and, for the same reason, the one most likely to be caught mid-transition.
+ """
+ bs, ts = base.get("styles"), treat.get("styles")
+ if not isinstance(bs, dict) or not isinstance(ts, dict):
+ return NOT_COMPARABLE, "one or both arms carry no style probe"
+ if bs.get("capped") or ts.get("capped"):
+ return NOT_COMPARABLE, (
+ f"the probe hit its element cap "
+ f"(base={bs.get('elements')}, treatment={ts.get('elements')})"
+ )
+ if bs.get("elements") != ts.get("elements"):
+ return DIFFER, (
+ f"the probe matched a different number of elements "
+ f"({bs.get('elements')} vs {ts.get('elements')})"
+ )
+ if bs.get("digest") == ts.get("digest"):
+ return MATCH, ""
+ return DIFFER, f"display/visibility/pointer-events differ over {bs.get('elements')} elements"
+
+
+def _any_moved(base: dict, treat: dict) -> bool:
+ """Did ANY digest in the capture move, not just the whole-thread one?
+
+ THE HOLE THIS CLOSES, found by the spike control and not by reading the code. An overlay --
+ an open menu, a dialog, the model picker -- lives OUTSIDE the thread root, so `parity.js`
+ walks it separately and reports it separately. The comparison used to test only the
+ whole-thread digest and then localise, which meant the overlay rows were unreachable: a menu
+ that mounted when it should not, or one whose contents were rewritten, left the thread digest
+ untouched and the check said MATCH. The overlay walk was carried in every payload and could
+ never fire. Injecting a `role="menu"` element and watching the digest report a clean pass is
+ what surfaced it.
+ """
+ if base.get("digest") != treat.get("digest"):
+ return True
+ bo, to = _overlays(base), _overlays(treat)
+ if [(o.get("sel"), o.get("digest")) for o in bo] != [
+ (o.get("sel"), o.get("digest")) for o in to
+ ]:
+ return True
+ bm, tm = _messages(base), _messages(treat)
+ if set(bm) != set(tm):
+ return True
+ return any(bm[i].get("digest") != tm[i].get("digest") for i in bm)
+
+
+def compare(base: Optional[dict], treat: Optional[dict]) -> dict:
+ """One base/treatment pair -> {verdict, reason, moved, style_verdict, style_reason}."""
+ why = comparability(base, treat)
+ if why is not None:
+ return {
+ "verdict": NOT_COMPARABLE,
+ "reason": why,
+ "moved": [],
+ "style_verdict": NOT_COMPARABLE,
+ "style_reason": why,
+ }
+ assert base is not None and treat is not None
+ style_verdict, style_reason = compare_styles(base, treat)
+ if not _any_moved(base, treat):
+ return {
+ "verdict": MATCH,
+ "reason": "",
+ "moved": [],
+ "style_verdict": style_verdict,
+ "style_reason": style_reason,
+ }
+ return {
+ "verdict": DIFFER,
+ "reason": "",
+ "moved": localise(base, treat),
+ "style_verdict": style_verdict,
+ "style_reason": style_reason,
+ }
+
+
+def compare_rows(base_row: Optional[dict], treat_row: Optional[dict]) -> dict:
+ """`compare()`, gated on whether the action actually RAN on both arms.
+
+ THE SECOND HOLE THE NULL CONTROL FOUND, and the more embarrassing one. Five of the eighteen
+ actions did not run at all on either arm of a 100K fast-tier null control -- `image_upload`
+ could not find a visible attachments button, `copy_markdown` found no Copy button, and so on.
+ The digest was captured anyway, because the action window closes whether or not the action
+ did anything, so the two arms agreed and `image_upload` was reported as a STABLE, MATCHING
+ surface. It reads as "the attachment flow renders identically on both builds". What actually
+ happened is that nobody opened it.
+
+ A comparison of two pages that no action touched is a comparison of the thread's resting
+ state. That is not worthless, but it is not coverage of the named action and must not be
+ counted as it. So it gets its own verdict, and an action that never ran on either arm can no
+ longer contribute a pass to anything.
+ """
+ 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",
+ "moved": [],
+ "style_verdict": NOT_COMPARABLE,
+ "style_reason": "",
+ }
+ if not row.get("ran"):
+ reason = row.get("reason") or "no reason recorded"
+ return {
+ "verdict": NOT_EXERCISED,
+ "moved": [],
+ "reason": f"the action did not run on the {label} arm ({reason}), so any "
+ "agreement here is about a surface nothing touched",
+ "style_verdict": NOT_EXERCISED,
+ "style_reason": "",
+ }
+ assert base_row is not None and treat_row is not None
+ return compare(base_row.get("parity"), treat_row.get("parity"))
+
+
+def derive_unstable(
+ pairs: Iterable[tuple[str, dict]], *, min_observations: int = 2
+) -> dict[str, dict]:
+ """Which actions differ against THEMSELVES, measured from a base-vs-base null control.
+
+ `pairs` is (action, compare() result) over a run whose two arms are the same build. Anything
+ that differs there differs for a reason that has nothing to do with any pull request, so this
+ is the empirical version of the hand-written UNSTABLE_ACTIONS list -- derived from a
+ measurement instead of declared from memory.
+
+ `min_observations` guards the obvious trap: one repetition of an action that happened to
+ differ once is not evidence that it is unstable, and treating it as evidence would let a
+ single flake permanently silence a real signal.
+ """
+ seen: dict[str, int] = collections.Counter()
+ differ: dict[str, int] = collections.Counter()
+ blind: dict[str, int] = collections.Counter()
+ for action, result in pairs:
+ if result.get("verdict") not in (MATCH, DIFFER):
+ # Not comparable and not exercised are both "no reading", and neither may be counted
+ # as an observation of stability. An action derived as stable from four pairs that
+ # never ran would be permanently trusted on the strength of nothing.
+ blind[action] += 1
+ continue
+ seen[action] += 1
+ if result.get("verdict") == DIFFER:
+ differ[action] += 1
+ out: dict[str, dict] = {}
+ for action in sorted(set(seen) | set(blind)):
+ n, d = seen[action], differ[action]
+ out[action] = {
+ "observations": n,
+ "differed": d,
+ "not_comparable": blind[action],
+ # Unstable only with enough observations to mean it. Below that the honest answer is
+ # "not enough evidence", which is not the same as "stable" and is not reported as it.
+ "unstable": bool(d and n >= min_observations),
+ "undetermined": n < min_observations,
+ }
+ return out
+
+
+def cross_check(derived: dict[str, dict], declared: Iterable[str]) -> dict[str, list[str]]:
+ """Where the empirical instability and the hand-written list disagree.
+
+ Both directions are findings and both are reported:
+ `declared_stable_in_practice` an action the list calls unstable that the null control never
+ saw differ. Its entry is costing real signal.
+ `unstable_but_not_declared` an action that differs against itself and is nonetheless being
+ scored as a hard signal. Every mismatch it produces is noise.
+ """
+ declared = set(declared)
+ unstable = {a for a, r in derived.items() if r["unstable"]}
+ undetermined = {a for a, r in derived.items() if r["undetermined"]}
+ return {
+ "declared_stable_in_practice": sorted(
+ a for a in declared if a in derived and a not in unstable and a not in undetermined
+ ),
+ "unstable_but_not_declared": sorted(unstable - declared),
+ "declared_but_never_observed": sorted(a for a in declared if a not in derived),
+ "undetermined": sorted(undetermined),
+ }
+
+
+def mutation_detected(before: dict, after: dict) -> dict:
+ """Did a deliberately injected DOM change move the digest, and where?
+
+ The spike control's decision function. Same shape as `compare`, and deliberately the SAME code
+ path: a mutation harness that used its own comparison would prove that its own comparison
+ works, which is not the question.
+ """
+ result = compare(before, after)
+ result["detected"] = result["verdict"] == DIFFER
+ return result
+
+
+def summarise(results: Iterable[dict[str, Any]]) -> dict[str, int]:
+ """Tally of verdicts, with NOT_COMPARABLE counted as its own outcome rather than as a pass."""
+ tally: dict[str, int] = collections.Counter()
+ for r in results:
+ tally[r.get("verdict", NOT_COMPARABLE)] += 1
+ return dict(tally)
diff --git a/tests/studio/studiobench/analysis/symbols.py b/tests/studio/studiobench/analysis/symbols.py
new file mode 100644
index 00000000000..63a8c24f2f7
--- /dev/null
+++ b/tests/studio/studiobench/analysis/symbols.py
@@ -0,0 +1,492 @@
+# 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 symbol bridge: recover react-dom function names without measuring a dev build.
+
+THE PROBLEM, stated exactly. React ships `cjs/react-dom-client.production.js`
+and `cjs/react-dom-profiling.profiling.js` ALREADY MINIFIED. Vite never sees the
+original identifiers, so `keep_fnames` has nothing to keep and a source map maps
+`Zk` to the character offset in react-dom's own pre-minified file where `Zk` is
+also what it is called. Source maps and `keep_fnames` recover OUR component
+names beautifully and recover nothing at all inside react-dom. The original name
+really is `Zk`. This is not a build misconfiguration and no build flag fixes it.
+
+THE SOLUTION. React's DEVELOPMENT build has real names. Use it strictly as a
+DICTIONARY and never as a measurement, because a dev build has different code,
+different fast paths, extra warnings and different allocation behaviour: a
+millisecond measured there describes a program nobody ships.
+
+The join key is the EXACT CALL-COUNT VECTOR. Run the identical fixture at two or
+three small rungs against both builds under precise coverage, and for each
+function record `(count at rung 1, count at rung 2, ...)`. Invocation counts are
+a semantic invariant across build modes: `cloneChildFibers` is called the same
+number of times whichever bundle you loaded, because it is called once per
+sibling per render either way, and that is a property of the algorithm rather
+than of the minifier. So a function with vector `(340, 3400, 34000)` in dev and
+a function with the same vector in prod are the same function.
+
+THE THREE WAYS THIS GOES WRONG, each closed by a rule below:
+
+1. **Collisions.** Many trivial functions share a vector, especially small
+ integers like `(1, 1, 1)`. A vector that is not UNIQUE WITHIN ITS OWN BUILD
+ is unusable, so it is recorded as ambiguous and never guessed. This is the
+ rule that keeps the bridge honest, and it discards a lot.
+2. **A bridge that is confidently wrong.** Validated against ANCHORS: our own
+ app components are independently named on BOTH sides through source maps, so
+ they must map to themselves. If any anchor maps to something else, the whole
+ bridge is discarded and the run degrades to unnamed frames with
+ `symbol_bridge: failed`. Not the bad anchor, the WHOLE bridge, because a
+ bridge that mislabels one function it can check will mislabel others it
+ cannot.
+3. **Dev timings leaking.** `assert_no_measurements` refuses any float in the
+ persisted artefact, and the artefact schema carries no duration fields at all.
+
+The result is persisted as `symbols/react-dom@<version>-<bundle-sha>.json`. The
+bundle SHA is part of the key because a bridge is only valid for the exact bytes
+it was built against; a new build renames everything.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+from dataclasses import dataclass, field
+from typing import Any, Iterable, Mapping, Sequence
+
+from . import CellFailure
+
+FAILED = "failed"
+OK = "ok"
+NOT_BUILT = "not_built"
+
+# A function whose counts are all this small carries almost no information and
+# collides with everything. Excluded from matching, and the exclusion is
+# reported so the coverage of the bridge is visible.
+MIN_INFORMATIVE_COUNT = 2
+
+# Above this share of resolved mappings being name-identical (`push` -> `push`),
+# the two arms are almost certainly the same build. Some identity is EXPECTED
+# and healthy: React's release minifier leaves scheduler entry points such as
+# `push`, `peek` and `performWorkUntilDeadline` alone, and `keepNames` preserves
+# others, so a genuine bridge measured on a real React 19.2.4 pair came in at
+# roughly 0.1. A same-build pair comes in at exactly 1.0, so the two regimes are
+# not close and this threshold is not delicate.
+MAX_IDENTITY_MAPPING_FRACTION = 0.5
+
+# NOTE FOR THE NEXT PERSON, because this is the obvious idea and it DOES NOT
+# WORK. You cannot detect "is this the development build?" by looking at how
+# long the function names are. Measured on the real pair: the development bundle
+# had a median react-dom function-name length of 19 with 97.6% of names at four
+# characters or more, and the PRODUCTION bundle had a median of 19 with 95.4%.
+# React's own minifier renames only part of react-dom, `keepNames` preserves the
+# rest, and V8 reports an inferred name for much of what is left. Name shape
+# tells you nothing. The checks below are structural instead.
+
+
+@dataclass(frozen = True)
+class FunctionVector:
+ """A function identified by its exact call counts across the rung ladder."""
+
+ build: str # "dev" or "prod"
+ url: str
+ function_name: str
+ script_id: str
+ start_offset: int
+ end_offset: int
+ counts: tuple[int, ...]
+
+ @property
+ def key(self) -> tuple[str, int, int]:
+ return (self.url, self.start_offset, self.end_offset)
+
+ @property
+ def informative(self) -> bool:
+ return max(self.counts, default = 0) >= MIN_INFORMATIVE_COUNT and any(self.counts)
+
+ def label(self) -> str:
+ return f"{self.function_name or '(anonymous)'}@{self.url}[{self.start_offset}:{self.end_offset}]"
+
+
+@dataclass
+class Bridge:
+ """A persisted prod-symbol to dev-name mapping, or an honest failure."""
+
+ status: str = NOT_BUILT
+ react_version: str = ""
+ bundle_sha: str = ""
+ rungs: tuple[str, ...] = ()
+ # prod function key -> dev function name
+ mapping: dict[str, str] = field(default_factory = dict)
+ # prod function key -> the count vector that matched it, for auditing
+ evidence: dict[str, list[int]] = field(default_factory = dict)
+ ambiguous_prod: list[str] = field(default_factory = list)
+ ambiguous_dev: list[str] = field(default_factory = list)
+ unmatched_prod: int = 0
+ # Resolved functions whose dev name equals their prod name. Expected to be
+ # small and non-zero; near 100% means both arms were the same build.
+ identity_mappings: int = 0
+ anchors_checked: int = 0
+ anchor_failures: list[str] = field(default_factory = list)
+ failure_reason: str = ""
+
+ @staticmethod
+ def prod_key(url: str, start_offset: int, end_offset: int) -> str:
+ # The URL is reduced to its basename because a Studio install serves the
+ # same bundle from a hashed path that changes per install, while the
+ # offsets inside the bundle do not.
+ return f"{os.path.basename(url)}:{start_offset}:{end_offset}"
+
+ def resolve(self, url: str, start_offset: int, end_offset: int) -> str | None:
+ if self.status != OK:
+ return None
+ return self.mapping.get(self.prod_key(url, start_offset, end_offset))
+
+ def resolve_frame_label(
+ self, url: str, start_offset: int, end_offset: int, fallback: str
+ ) -> str:
+ name = self.resolve(url, start_offset, end_offset)
+ return f"{name} (bridged)" if name else fallback
+
+ def summary(self) -> dict[str, Any]:
+ return {
+ "symbol_bridge": self.status,
+ "react_version": self.react_version,
+ "bundle_sha": self.bundle_sha[:12],
+ "rungs": list(self.rungs),
+ "resolved_functions": len(self.mapping),
+ "ambiguous_prod": len(self.ambiguous_prod),
+ "ambiguous_dev": len(self.ambiguous_dev),
+ "unmatched_prod": self.unmatched_prod,
+ "identity_mappings": self.identity_mappings,
+ "anchors_checked": self.anchors_checked,
+ "anchor_failures": self.anchor_failures,
+ "failure_reason": self.failure_reason,
+ }
+
+ def to_json(self) -> dict[str, Any]:
+ doc = {
+ "schema": "studiobench.symbols/1",
+ "status": self.status,
+ "react_version": self.react_version,
+ "bundle_sha": self.bundle_sha,
+ "rungs": list(self.rungs),
+ "mapping": dict(self.mapping),
+ "evidence": {k: list(v) for k, v in self.evidence.items()},
+ "ambiguous_prod": list(self.ambiguous_prod),
+ "ambiguous_dev": list(self.ambiguous_dev),
+ "unmatched_prod": self.unmatched_prod,
+ "identity_mappings": self.identity_mappings,
+ "anchors_checked": self.anchors_checked,
+ "anchor_failures": list(self.anchor_failures),
+ "failure_reason": self.failure_reason,
+ }
+ assert_no_measurements(doc)
+ return doc
+
+ @classmethod
+ def from_json(cls, doc: Mapping[str, Any]) -> "Bridge":
+ return cls(
+ status = str(doc.get("status", NOT_BUILT)),
+ react_version = str(doc.get("react_version", "")),
+ bundle_sha = str(doc.get("bundle_sha", "")),
+ rungs = tuple(doc.get("rungs") or ()),
+ mapping = dict(doc.get("mapping") or {}),
+ evidence = {k: list(v) for k, v in (doc.get("evidence") or {}).items()},
+ ambiguous_prod = list(doc.get("ambiguous_prod") or ()),
+ ambiguous_dev = list(doc.get("ambiguous_dev") or ()),
+ unmatched_prod = int(doc.get("unmatched_prod", 0)),
+ identity_mappings = int(doc.get("identity_mappings", 0)),
+ anchors_checked = int(doc.get("anchors_checked", 0)),
+ anchor_failures = list(doc.get("anchor_failures") or ()),
+ failure_reason = str(doc.get("failure_reason", "")),
+ )
+
+ def filename(self) -> str:
+ return f"react-dom@{self.react_version or 'unknown'}-{self.bundle_sha[:12] or 'nosha'}.json"
+
+ def save(self, directory: str) -> str:
+ os.makedirs(directory, exist_ok = True)
+ path = os.path.join(directory, self.filename())
+ with open(path, "w", encoding = "utf-8") as fh:
+ json.dump(self.to_json(), fh, indent = 2, sort_keys = True)
+ return path
+
+ @classmethod
+ def load(cls, path: str) -> "Bridge":
+ with open(path, "r", encoding = "utf-8") as fh:
+ return cls.from_json(json.load(fh))
+
+
+def assert_no_measurements(payload: Any, path: str = "bridge") -> None:
+ """Refuse any float anywhere in a bridge artefact.
+
+ The dev build is a dictionary, never a measurement. This is the mechanical
+ guarantee behind that sentence: the artefact can hold names and integers and
+ nothing else, so there is no field a duration could sit in even by accident.
+ """
+ if isinstance(payload, bool):
+ return
+ if isinstance(payload, float):
+ raise CellFailure(
+ "dev_measurement_leak",
+ f"{path} holds a float ({payload!r}). The development build is a "
+ "dictionary, not a measurement; no dev millisecond may enter a table.",
+ )
+ if isinstance(payload, Mapping):
+ for k, v in payload.items():
+ assert_no_measurements(v, f"{path}.{k}")
+ elif isinstance(payload, (list, tuple)):
+ for i, v in enumerate(payload):
+ assert_no_measurements(v, f"{path}[{i}]")
+
+
+def bundle_sha(source: str | bytes) -> str:
+ data = source.encode("utf-8") if isinstance(source, str) else source
+ return hashlib.sha256(data).hexdigest()
+
+
+def vectors_from_snapshots(
+ snapshots: Sequence[Any],
+ build: str,
+ *,
+ url_filter: str | None = None,
+) -> list[FunctionVector]:
+ """Turn one build's per-rung coverage snapshots into count vectors.
+
+ `snapshots` are `instruments.coverage.CoverageSnapshot` objects in RUNG
+ ORDER, and the order must be identical for both builds or the vectors
+ describe different experiments and every match is spurious.
+
+ A function missing from a rung contributes a 0 at that position rather than
+ being dropped, because "never called at the small rung" is itself part of
+ the signature.
+ """
+ if not snapshots:
+ return []
+ per_rung: list[dict[tuple[str, int, int], Any]] = []
+ for snap in snapshots:
+ table: dict[tuple[str, int, int], Any] = {}
+ for f in snap.functions:
+ if url_filter and url_filter not in f.url:
+ continue
+ table[(f.url, f.start_offset, f.end_offset)] = f
+ per_rung.append(table)
+
+ all_keys: set[tuple[str, int, int]] = set()
+ for table in per_rung:
+ all_keys |= set(table)
+
+ out: list[FunctionVector] = []
+ for key in sorted(all_keys):
+ counts = tuple(int(table[key].count) if key in table else 0 for table in per_rung)
+ sample = next(table[key] for table in per_rung if key in table)
+ out.append(
+ FunctionVector(
+ build = build,
+ url = key[0],
+ function_name = str(sample.function_name or ""),
+ script_id = str(sample.script_id),
+ start_offset = key[1],
+ end_offset = key[2],
+ counts = counts,
+ )
+ )
+ return out
+
+
+def _index_unique(
+ vectors: Iterable[FunctionVector],
+) -> tuple[dict[tuple[int, ...], FunctionVector], list[str]]:
+ """Index by count vector, keeping only vectors unique within this build."""
+ buckets: dict[tuple[int, ...], list[FunctionVector]] = {}
+ for v in vectors:
+ if not v.informative:
+ continue
+ buckets.setdefault(v.counts, []).append(v)
+ unique: dict[tuple[int, ...], FunctionVector] = {}
+ ambiguous: list[str] = []
+ for counts, group in buckets.items():
+ if len(group) == 1:
+ unique[counts] = group[0]
+ else:
+ ambiguous.append(
+ f"{list(counts)} shared by {len(group)}: " + ", ".join(g.label() for g in group[:4])
+ )
+ return unique, ambiguous
+
+
+def build_bridge(
+ dev_snapshots: Sequence[Any],
+ prod_snapshots: Sequence[Any],
+ *,
+ rungs: Sequence[str],
+ react_version: str,
+ bundle_source: str | bytes,
+ anchor_names: Sequence[str],
+ react_url_filter: str | None = None,
+ anchor_url_filter: str | None = None,
+) -> Bridge:
+ """Match prod functions to dev names by exact call-count vector equality.
+
+ `anchor_names` are functions that are independently named on BOTH sides,
+ which in practice means our own app components: source maps and `keep_fnames`
+ recover those in the production build, and the development build has them
+ too. They are the control. If an anchor does not map to itself the bridge is
+ discarded whole.
+ """
+ if len(dev_snapshots) != len(prod_snapshots):
+ return Bridge(
+ status = FAILED,
+ react_version = react_version,
+ bundle_sha = bundle_sha(bundle_source),
+ rungs = tuple(rungs),
+ failure_reason = (
+ f"{len(dev_snapshots)} dev rungs against {len(prod_snapshots)} prod rungs; "
+ "the two builds must run the identical ladder or the vectors describe "
+ "different experiments"
+ ),
+ )
+ if len(dev_snapshots) < 2:
+ return Bridge(
+ status = FAILED,
+ react_version = react_version,
+ bundle_sha = bundle_sha(bundle_source),
+ rungs = tuple(rungs),
+ failure_reason = (
+ f"{len(dev_snapshots)} rung(s); a single-rung vector is one integer and "
+ "collides with everything. Two or three rungs are the minimum."
+ ),
+ )
+
+ bridge = Bridge(
+ status = OK,
+ react_version = react_version,
+ bundle_sha = bundle_sha(bundle_source),
+ rungs = tuple(rungs),
+ )
+
+ # ---- anchor validation, on our own app code, both sides named ----------
+ dev_all = vectors_from_snapshots(dev_snapshots, "dev", url_filter = anchor_url_filter)
+ prod_all = vectors_from_snapshots(prod_snapshots, "prod", url_filter = anchor_url_filter)
+ dev_by_name: dict[str, list[FunctionVector]] = {}
+ for v in dev_all:
+ if v.function_name:
+ dev_by_name.setdefault(v.function_name, []).append(v)
+ prod_by_name: dict[str, list[FunctionVector]] = {}
+ for v in prod_all:
+ if v.function_name:
+ prod_by_name.setdefault(v.function_name, []).append(v)
+
+ for anchor in anchor_names:
+ dev_hits = [v for v in dev_by_name.get(anchor, []) if v.informative]
+ prod_hits = [v for v in prod_by_name.get(anchor, []) if v.informative]
+ if not dev_hits or not prod_hits:
+ bridge.anchor_failures.append(
+ f"{anchor}: present in dev={len(dev_hits)} prod={len(prod_hits)} with a usable "
+ "count vector; an anchor that does not run on both sides cannot validate anything"
+ )
+ continue
+ bridge.anchors_checked += 1
+ dev_counts = {v.counts for v in dev_hits}
+ prod_counts = {v.counts for v in prod_hits}
+ if not (dev_counts & prod_counts):
+ bridge.anchor_failures.append(
+ f"{anchor}: dev vectors {sorted(dev_counts)} vs prod vectors {sorted(prod_counts)} "
+ "do not intersect, so call counts are NOT invariant across these two builds and "
+ "the entire matching premise is false here"
+ )
+
+ if bridge.anchor_failures or bridge.anchors_checked == 0:
+ bridge.status = FAILED
+ bridge.mapping.clear()
+ bridge.evidence.clear()
+ bridge.failure_reason = (
+ "anchor validation failed; discarding the whole bridge rather than the bad anchors, "
+ "because a bridge that mislabels a function it can check will mislabel functions it cannot. "
+ + ("no anchors were usable" if bridge.anchors_checked == 0 else "")
+ )
+ return bridge
+
+ # ---- the two arms must actually be two different builds -----------------
+ #
+ # THE FAILURE THIS CLOSES. If both arms are pointed at the same server (a
+ # port collision, a reused base URL, a dev server that quietly served the
+ # production dist), every count vector matches trivially, EVERY ANCHOR
+ # PASSES because an anchor genuinely does map to itself, and the bridge
+ # reports `ok` with a mapping of `Zk` to `Zk`. That is a clean-looking run
+ # that proves nothing, and it would put "bridged" next to a minified name.
+ # The anchor check cannot catch it; it is the one thing anchors are blind
+ # to, because anchors test invariance and same-build is perfectly invariant.
+ dev_all_keys = {v.key for v in dev_all if v.informative}
+ prod_all_keys = {v.key for v in prod_all if v.informative}
+ if dev_all_keys and dev_all_keys == prod_all_keys:
+ bridge.status = FAILED
+ bridge.failure_reason = (
+ "both arms observed an IDENTICAL set of functions at identical byte offsets in "
+ "identically named scripts, so they were serving the same bundle. A bridge built "
+ "from one build maps minified names to themselves and reads as a success. Check "
+ "that the dev and prod arms are on different ports and different installs."
+ )
+ return bridge
+
+ # ---- the actual matching, restricted to react-dom ----------------------
+ dev_react = vectors_from_snapshots(dev_snapshots, "dev", url_filter = react_url_filter)
+ prod_react = vectors_from_snapshots(prod_snapshots, "prod", url_filter = react_url_filter)
+ dev_index, dev_ambiguous = _index_unique(dev_react)
+ prod_index, prod_ambiguous = _index_unique(prod_react)
+ bridge.ambiguous_dev = dev_ambiguous
+ bridge.ambiguous_prod = prod_ambiguous
+
+ matched = 0
+ identical_names = 0
+ for counts, prod_fn in prod_index.items():
+ dev_fn = dev_index.get(counts)
+ if dev_fn is None or not dev_fn.function_name:
+ continue
+ key = Bridge.prod_key(prod_fn.url, prod_fn.start_offset, prod_fn.end_offset)
+ bridge.mapping[key] = dev_fn.function_name
+ bridge.evidence[key] = list(counts)
+ if prod_fn.function_name == dev_fn.function_name:
+ identical_names += 1
+ matched += 1
+ bridge.unmatched_prod = len(prod_index) - matched
+ bridge.identity_mappings = identical_names
+
+ if matched == 0:
+ bridge.status = FAILED
+ bridge.failure_reason = (
+ "no prod function had a count vector that was unique in prod AND unique in dev AND "
+ "equal across the two. Widen the rung ladder so vectors carry more information."
+ )
+ return bridge
+
+ # Second guard on the same failure, for the case where the two arms differ
+ # in offsets but are still the same code (a rebuild of one tree, say). If
+ # nearly every resolved name maps to itself, no minification was undone and
+ # the bridge is not doing anything.
+ fraction = identical_names / matched
+ if fraction > MAX_IDENTITY_MAPPING_FRACTION:
+ bridge.status = FAILED
+ bridge.mapping.clear()
+ bridge.evidence.clear()
+ bridge.failure_reason = (
+ f"{identical_names} of {matched} resolved functions map to their own name "
+ f"({fraction * 100:.0f}%, limit {MAX_IDENTITY_MAPPING_FRACTION * 100:.0f}%). A bridge "
+ "that recovers the names it already had has undone no minification, which means both "
+ "arms were built the same way. A genuine dev-to-prod pair sits near 10%, because only "
+ "the scheduler entry points keep their names in both."
+ )
+ return bridge
+
+
+def apply_bridge(
+ bridge: Bridge, frames: Sequence[tuple[str, str, int, int]]
+) -> dict[tuple[str, str, int, int], str]:
+ """Resolve `(label, url, start, end)` tuples to bridged names where possible."""
+ out: dict[tuple[str, str, int, int], str] = {}
+ for label, url, start, end in frames:
+ name = bridge.resolve(url, start, end)
+ if name:
+ out[(label, url, start, end)] = name
+ return out
diff --git a/tests/studio/studiobench/analysis/test_analysis.py b/tests/studio/studiobench/analysis/test_analysis.py
new file mode 100644
index 00000000000..77e96cf5fed
--- /dev/null
+++ b/tests/studio/studiobench/analysis/test_analysis.py
@@ -0,0 +1,672 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Unit tests for the studiobench analysis layer, against a REAL captured trace.
+
+The fixture in `testdata/` is a genuine Chrome trace captured through
+`instruments/tracing.py`, trimmed to the renderer main thread plus the V8
+profiler events. The page it was captured from does three things with known
+counts, which is what makes the assertions below meaningful rather than
+self-referential:
+
+ * a `setInterval` loop, so there are timer tasks;
+ * a `MessageChannel` ping-pong of exactly 120 round trips, which is the shape
+ the React scheduler uses and the class this tool most needs to get right;
+ * a `requestAnimationFrame` loop, so there are frame tasks;
+ * real `page.keyboard` typing, so there are input tasks with `latencyInfo`.
+
+Run with `python -m pytest tests/studio/studiobench/analysis/test_analysis.py`,
+or standalone with `python tests/studio/studiobench/analysis/test_analysis.py`.
+No browser and no network required.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+
+_HERE = os.path.dirname(os.path.abspath(__file__))
+_STUDIO_TESTS = os.path.dirname(os.path.dirname(_HERE))
+if _STUDIO_TESTS not in sys.path:
+ sys.path.insert(0, _STUDIO_TESTS)
+
+from studiobench.analysis import CellFailure # noqa: E402
+from studiobench.analysis import assert_no_bare_zero, measured, merge, unmeasured # noqa: E402
+from studiobench.analysis import classify as K # noqa: E402
+from studiobench.analysis import cpuprofile as C # noqa: E402
+from studiobench.analysis import fit as F # noqa: E402
+from studiobench.analysis import oracles as O # noqa: E402
+from studiobench.analysis import symbols as S # noqa: E402
+from studiobench.analysis.traceparse import Trace, build_tree # noqa: E402
+
+TRACE = os.path.join(_HERE, "testdata", "probe_msgchan_timer_raf.json.gz")
+
+# Ground truth about the page the fixture was captured from.
+EXPECTED_MESSAGE_CHANNEL_TASKS = 120
+EXPECTED_RAF_ITERATIONS = 60
+
+
+def _trace() -> Trace:
+ return Trace.from_path(TRACE)
+
+
+# --------------------------------------------------------------- traceparse
+
+
+def test_loads_object_form_trace() -> None:
+ tr = _trace()
+ assert len(tr.events) > 1000
+ assert tr.metadata, "metadata block should survive the round trip"
+
+
+def test_truncated_trace_fails_the_cell_rather_than_parsing_short() -> None:
+ # A stream that was cut off mid-document must not degrade into "a shorter
+ # trace"; that reads exactly like the expensive work not happening.
+ try:
+ Trace.from_json_text('{"traceEvents":[{"ph":"X","ts":1,"dur":2,"name":"RunTask"')
+ except CellFailure as exc:
+ assert exc.gate == "trace_truncated"
+ else:
+ raise AssertionError("a truncated trace must raise CellFailure")
+
+
+def test_profiled_thread_is_the_renderer_main_not_the_profiler_thread() -> None:
+ tr = _trace()
+ pid, tid = tr.profiled_thread()
+ assert tr.thread_name(pid, tid) == "CrRendererMain"
+ # The chunks themselves live on a different thread; that is the trap.
+ chunk_tids = {e.get("tid") for e in tr.events if e.get("name") == "ProfileChunk"}
+ assert chunk_tids and chunk_tids != {tid}, (
+ "fixture should exercise the case where ProfileChunk is emitted on the "
+ "V8 profiler thread rather than the profiled thread"
+ )
+
+
+def test_tree_nests_and_self_time_never_goes_negative() -> None:
+ tr = _trace()
+ th = tr.renderer_main()
+ for task in tr.run_tasks(th):
+ for node in task.walk():
+ assert node.self_dur >= 0
+ assert sum(c.dur for c in node.children) <= node.dur + 1
+
+
+def test_overlapping_events_become_siblings_not_corrupt_parents() -> None:
+ # An event that starts inside another and ends after it is not nested.
+ events = [
+ {"ph": "X", "ts": 0, "dur": 100, "name": "outer", "cat": "c", "pid": 1, "tid": 1},
+ {"ph": "X", "ts": 50, "dur": 200, "name": "straddles", "cat": "c", "pid": 1, "tid": 1},
+ ]
+ roots = build_tree(events)
+ assert len(roots) == 2, "a straddling event must not be adopted as a child"
+
+
+def test_begin_end_pairs_fold_into_complete_events() -> None:
+ events = [
+ {"ph": "B", "ts": 10, "name": "x", "cat": "c", "pid": 1, "tid": 1, "args": {"a": 1}},
+ {"ph": "E", "ts": 40, "name": "x", "cat": "c", "pid": 1, "tid": 1, "args": {"b": 2}},
+ ]
+ roots = build_tree(events)
+ assert len(roots) == 1 and roots[0].dur == 30
+ assert roots[0].args == {"a": 1, "b": 2}
+
+
+def test_unmatched_begin_invents_no_duration() -> None:
+ roots = build_tree([{"ph": "B", "ts": 10, "name": "x", "cat": "c", "pid": 1, "tid": 1}])
+ assert roots == []
+
+
+# --------------------------------------------------------------- cpuprofile
+
+
+def test_profile_parses_and_deltas_match_wall_clock() -> None:
+ prof = C.main_thread_profile(_trace())
+ report = prof.assert_deltas_match_wall()
+ assert report["drift"] < C.DELTA_WALL_TOLERANCE
+ assert report["sample_count"] > 1000
+
+
+def test_nodes_accumulate_across_chunks() -> None:
+ # Only a handful of chunks carry a `nodes` array; a parser that reads nodes
+ # per chunk and forgets them resolves almost nothing.
+ tr = _trace()
+ chunks_with_nodes = sum(
+ 1
+ for e in tr.events
+ if e.get("name") == "ProfileChunk"
+ and ((e.get("args") or {}).get("data") or {}).get("cpuProfile", {}).get("nodes")
+ )
+ prof = C.main_thread_profile(tr)
+ assert chunks_with_nodes < prof.chunk_count, "fixture must exercise incremental nodes"
+ assert len(prof.nodes) > chunks_with_nodes
+ resolved = sum(1 for s in prof.samples if s.node_id in prof.nodes)
+ assert resolved == len(prof.samples), "every sample must resolve to a known node"
+
+
+def test_negative_time_deltas_are_summed_not_clamped() -> None:
+ prof = C.main_thread_profile(_trace())
+ assert prof.negative_deltas > 0, "fixture must exercise negative deltas"
+ # Clamping would inflate the total past wall clock and break the gate above.
+ naive = sum(max(0, s.delta) for s in prof.samples)
+ honest = sum(s.delta for s in prof.samples)
+ assert naive > honest
+
+
+def test_ragged_chunk_fails_the_cell() -> None:
+ tr = _trace()
+ for e in tr.events:
+ if e.get("name") == "ProfileChunk":
+ data = (e.get("args") or {}).get("data") or {}
+ if data.get("timeDeltas"):
+ data["timeDeltas"] = data["timeDeltas"][:-1]
+ break
+ try:
+ C.main_thread_profile(tr)
+ except CellFailure as exc:
+ assert exc.gate == "cpuprofile_chunk_ragged"
+ else:
+ raise AssertionError("samples and timeDeltas must be required to be 1:1")
+
+
+def test_stacks_have_ancestry() -> None:
+ prof = C.main_thread_profile(_trace())
+ stacks = C.stacks_under(prof, "hotLeafFrame")
+ assert stacks, "the known hot function must appear in sampled stacks"
+ names = [f.function_name for f in stacks[0][1]]
+ assert names[0] == "hotLeafFrame"
+ assert "middleFrame" in names, "the caller must be recoverable from the stack"
+
+
+def test_clock_anchor_is_the_event_timestamp() -> None:
+ # `args.data.startTime` is in a different clock domain and is kept only to
+ # report the skew, never used to anchor samples.
+ prof = C.main_thread_profile(_trace())
+ assert prof.declared_start_time
+ assert abs(prof.clock_skew_us) < 10_000
+
+
+def test_underpowered_windows_are_declared_not_hidden() -> None:
+ prof = C.main_thread_profile(_trace())
+ rows, diag = C.self_time_in_windows(prof, [(prof.samples[0].ts, prof.samples[0].ts + 50)])
+ assert diag["underpowered"] is True
+ assert diag["js_sample_count"] < C.MIN_JS_SAMPLES_FOR_RANKING
+ assert isinstance(rows, list)
+
+
+# ------------------------------------------------------------------ classify
+
+
+def test_every_task_gets_an_origin() -> None:
+ cls = K.classify_thread(_trace())
+ assert cls.total_us > 0
+ cls.assert_named() # raises if unclassified time exceeds the limit
+ assert cls.unclassified_pct == 0.0
+
+
+def test_message_channel_count_matches_the_page() -> None:
+ cls = K.classify_thread(_trace())
+ assert cls.by_origin_count[K.MESSAGE_CHANNEL] == EXPECTED_MESSAGE_CHANNEL_TASKS
+
+
+def test_origin_is_read_from_blinks_own_task_type() -> None:
+ cls = K.classify_thread(_trace())
+ evidence = {c.evidence for c in cls.tasks_of(K.MESSAGE_CHANNEL)}
+ assert any(e.startswith("task_type:") for e in evidence), (
+ "the scheduler category must be the authority for message-channel tasks, "
+ "not the mojo src_file heuristic"
+ )
+ for c in cls.tasks_of(K.MESSAGE_CHANNEL):
+ assert c.task_type, "task type should be recorded on the row"
+
+
+def test_timers_and_frames_and_input_are_all_present() -> None:
+ cls = K.classify_thread(_trace())
+ assert cls.by_origin_count.get(K.TIMER, 0) > 100
+ assert cls.by_origin_count.get(K.RAF, 0) >= EXPECTED_RAF_ITERATIONS
+ assert cls.by_origin_count.get(K.INPUT, 0) > 0
+
+
+def test_harness_cost_is_named_not_hidden() -> None:
+ cls = K.classify_thread(_trace())
+ # The devtools pipe running Runtime.evaluate is our own cost. It must have
+ # its own column so it can be watched, and must not be inside the app's.
+ assert K.AGENT_IPC in K.ORIGINS
+ assert K.AGENT_IPC in K.HARNESS_ORIGINS
+
+
+def test_unclassified_threshold_actually_fails() -> None:
+ cls = K.classify_thread(_trace())
+ for c in cls.tasks:
+ c.origin = K.UNCLASSIFIED
+ cls.by_origin_us = {K.UNCLASSIFIED: cls.total_us}
+ try:
+ cls.assert_named()
+ except CellFailure as exc:
+ assert exc.gate == "unclassified_task_pct"
+ else:
+ raise AssertionError("an all-unclassified run must fail the cell")
+
+
+def test_task_duration_cross_check_fails_on_disagreement() -> None:
+ cls = K.classify_thread(_trace())
+ good = cls.total_us / 1e6
+ K.cross_check_task_duration(cls, good * 1.02) # inside 5%
+ try:
+ K.cross_check_task_duration(cls, good * 1.5)
+ except CellFailure as exc:
+ assert exc.gate == "task_duration_mismatch"
+ else:
+ raise AssertionError("a 50% disagreement must fail the cell")
+
+
+# ---------------------------------------------------------------------- fit
+
+
+def _pts(session: str, pairs) -> list[F.Point]:
+ return [F.Point(length = x, value = y, session = session, rung = str(x)) for x, y in pairs]
+
+
+def test_loglog_recovers_a_known_exponent() -> None:
+ pairs = [(1000, 2.0), (10_000, 20.0), (100_000, 200.0), (1_000_000, 2000.0)]
+ f = F.fit_loglog(_pts("s1", pairs))
+ assert abs(f.b - 1.0) < 1e-6
+ assert f.r2 > 0.999
+
+
+def test_quadratic_growth_reads_as_two() -> None:
+ pairs = [(10, 1.0), (100, 100.0), (1000, 10_000.0)]
+ f = F.fit_loglog(_pts("s1", pairs), bootstrap = 0)
+ assert abs(f.b - 2.0) < 1e-6
+
+
+def test_cross_session_fit_is_refused() -> None:
+ pts = _pts("s1", [(1, 1.0), (10, 10.0)]) + _pts("s2", [(100, 100.0)])
+ try:
+ F.fit_loglog(pts)
+ except CellFailure as exc:
+ assert exc.gate == "cross_session_fit"
+ else:
+ raise AssertionError("mixing sessions in one fit must be refused")
+
+
+def test_zero_values_are_dropped_not_floored() -> None:
+ pts = _pts("s1", [(10, 0.0), (100, 100.0), (1000, 10_000.0), (10_000, 1_000_000.0)])
+ f = F.fit_loglog(pts, bootstrap = 0)
+ assert f.n == 3, "the zero point must be dropped, not replaced by an epsilon"
+
+
+def test_severity_is_zero_when_a_frame_grows_slower_than_the_total() -> None:
+ assert F.severity(1000.0, 0.5, 1.2) == 0.0
+ assert F.severity(100.0, 2.0, 1.0) == 100.0
+
+
+def test_ranking_reports_what_it_could_not_fit() -> None:
+ labels = {("a", "1", 0, 0): "steep", ("b", "2", 0, 0): "flat", ("c", "3", 0, 0): "sparse"}
+ series = {
+ ("a", "1", 0, 0): _pts("s", [(10, 1.0), (100, 100.0), (1000, 10_000.0)]),
+ ("b", "2", 0, 0): _pts("s", [(10, 5.0), (100, 5.0), (1000, 5.0)]),
+ ("c", "3", 0, 0): _pts("s", [(10, 1.0)]),
+ }
+ total = _pts("s", [(10, 10.0), (100, 100.0), (1000, 1000.0)])
+ rows, diag = F.rank_frames(series, labels, total, bootstrap = 0)
+ assert rows[0].frame_label == "steep"
+ assert "sparse" in diag["frames_skipped"]
+ assert rows[-1].severity == 0.0
+
+
+# ------------------------------------------------------------------ oracles
+
+
+def test_exact_match_is_a_naming() -> None:
+ q = O.blocks_times_renders(685, 6, source = "DOM census")
+ v = O.check("cloneChildFibers", 4110, [q])
+ assert v.is_naming
+ assert "4110" in v.detail and "685" in v.detail
+
+
+def test_off_by_a_hair_is_not_a_naming() -> None:
+ q = O.blocks_times_renders(685, 6, source = "DOM census")
+ v = O.check("cloneChildFibers", 4111, [q])
+ assert not v.is_naming
+ assert v.verdict == O.NEAR_MISS
+ assert "+1" in (v.ratio or "")
+
+
+def test_double_invoke_is_reported_as_a_diagnosis() -> None:
+ q = O.blocks_times_renders(100, 2, source = "DOM census")
+ v = O.check("f", 400, [q])
+ assert v.verdict == O.NEAR_MISS
+ assert "StrictMode" in (v.ratio or "")
+
+
+def test_a_frame_matching_nothing_is_unexplained_not_silent() -> None:
+ q = O.blocks_times_renders(685, 6, source = "DOM census")
+ v = O.check("Zk", 91_237, [q])
+ assert v.verdict == O.UNEXPLAINED
+ assert v.exact_call_count == 91_237
+
+
+def test_no_count_means_not_measured_rather_than_a_guess() -> None:
+ v = O.check("Zk", None, [O.blocks_times_renders(1, 1, source = "x")])
+ assert v.verdict == O.NOT_MEASURED
+
+
+def test_check_all_reports_every_bucket() -> None:
+ q = O.blocks_times_renders(685, 6, source = "DOM census")
+ out = O.check_all([("named", 4110), ("odd", 999_983), ("nocount", None)], [q])
+ assert out["named_at_least_one_frame"]
+ assert len(out["unexplained_hot_frames"]) == 1
+ assert len(out["not_measured"]) == 1
+
+
+# ------------------------------------------------------------------ symbols
+
+
+class _Fn:
+ def __init__(self, url, name, start, end, count):
+ self.url, self.function_name = url, name
+ self.start_offset, self.end_offset, self.count = start, end, count
+ self.script_id = "1"
+
+
+class _Snap:
+ def __init__(self, fns):
+ self.functions = fns
+
+
+def _arms(dev_counts, prod_counts, anchor_dev, anchor_prod):
+ """Two arms shaped like a REAL dev/prod pair.
+
+ The two sides deliberately differ in script URL and byte offset, because
+ that is what two different builds look like: a Vite dev server serves
+ `/node_modules/.vite/deps/react-dom_client.js` while a production build
+ inlines react-dom into a hashed app chunk at entirely different offsets. An
+ earlier version of this helper gave both sides identical URLs and offsets,
+ which is indistinguishable from pointing both arms at the same server, and
+ the same-build guard now correctly refuses it.
+ """
+ dev = [
+ _Snap(
+ [
+ _Fn("/deps/react-dom_client.js", n, i * 37 + 3, i * 37 + 21, c[r])
+ for i, (n, c) in enumerate(dev_counts.items())
+ ]
+ + [
+ _Fn("/src/app.jsx", n, 900 + i * 11, 930 + i * 11, c[r])
+ for i, (n, c) in enumerate(anchor_dev.items())
+ ]
+ )
+ for r in range(2)
+ ]
+ prod = [
+ _Snap(
+ [
+ _Fn("/assets/index-abc123.js", n, i * 10, i * 10 + 5, c[r])
+ for i, (n, c) in enumerate(prod_counts.items())
+ ]
+ + [
+ _Fn("/assets/index-abc123.js", n, 500 + i, 505 + i, c[r])
+ for i, (n, c) in enumerate(anchor_prod.items())
+ ]
+ )
+ for r in range(2)
+ ]
+ return dev, prod
+
+
+def test_bridge_resolves_a_minified_name_by_count_vector() -> None:
+ dev, prod = _arms(
+ {"cloneChildFibers": [340, 3400], "beginWork": [17, 170]},
+ {"Zk": [340, 3400], "qi": [17, 170]},
+ {"ThreadMessage": [50, 500]},
+ {"ThreadMessage": [50, 500]},
+ )
+ b = S.build_bridge(
+ dev,
+ prod,
+ rungs = ("s", "m"),
+ react_version = "19.2.4",
+ bundle_source = "x",
+ anchor_names = ["ThreadMessage"],
+ react_url_filter = None,
+ anchor_url_filter = None,
+ )
+ assert b.status == S.OK
+ assert b.resolve("/assets/index-abc123.js", 0, 5) == "cloneChildFibers"
+ assert b.resolve("/assets/index-abc123.js", 10, 15) == "beginWork"
+ # The anchor legitimately maps to itself, so some identity is expected. What
+ # must not happen is identity DOMINATING, which would mean no minification
+ # was undone.
+ assert b.identity_mappings / len(b.mapping) <= S.MAX_IDENTITY_MAPPING_FRACTION
+
+
+def test_bridge_refuses_to_guess_an_ambiguous_vector() -> None:
+ dev, prod = _arms(
+ {"alpha": [7, 7], "beta": [7, 7]},
+ {"Aa": [7, 7], "Bb": [7, 7]},
+ {"ThreadMessage": [50, 500]},
+ {"ThreadMessage": [50, 500]},
+ )
+ b = S.build_bridge(
+ dev,
+ prod,
+ rungs = ("s", "m"),
+ react_version = "19.2.4",
+ bundle_source = "x",
+ anchor_names = ["ThreadMessage"],
+ react_url_filter = None,
+ anchor_url_filter = None,
+ )
+ assert b.mapping == {}
+ assert b.ambiguous_prod and b.ambiguous_dev
+
+
+def test_anchor_mismatch_discards_the_whole_bridge() -> None:
+ dev, prod = _arms(
+ {"cloneChildFibers": [340, 3400]},
+ {"Zk": [340, 3400]},
+ {"ThreadMessage": [50, 500]},
+ {"ThreadMessage": [51, 500]}, # counts are NOT invariant here
+ )
+ b = S.build_bridge(
+ dev,
+ prod,
+ rungs = ("s", "m"),
+ react_version = "19.2.4",
+ bundle_source = "x",
+ anchor_names = ["ThreadMessage"],
+ react_url_filter = None,
+ anchor_url_filter = None,
+ )
+ assert b.status == S.FAILED
+ assert b.mapping == {}, "one bad anchor must discard every mapping, not just its own"
+ assert b.resolve("/react-dom.js", 0, 5) is None
+
+
+def test_same_build_on_both_arms_is_refused() -> None:
+ # The one failure anchors are structurally blind to. If both arms are the
+ # same build, every anchor maps to itself PERFECTLY, so anchor validation
+ # passes and the bridge reports ok while mapping minified names to
+ # themselves. Verified against the real implementation before this guard
+ # existed: it returned status ok with {"Zk": "Zk"}.
+ _, prod = _arms(
+ {"a": [1, 1]},
+ {"Zk": [340, 3400], "qi": [17, 170]},
+ {"x": [1, 1]},
+ {"ThreadMessage": [50, 500]},
+ )
+ b = S.build_bridge(
+ prod,
+ prod,
+ rungs = ("s", "m"),
+ react_version = "19.2.4",
+ bundle_source = "x",
+ anchor_names = ["ThreadMessage"],
+ react_url_filter = None,
+ anchor_url_filter = None,
+ )
+ assert b.status == S.FAILED
+ assert b.mapping == {}
+ assert "same bundle" in b.failure_reason
+ assert not b.anchor_failures, "anchors PASS here; that is exactly why this guard is needed"
+
+
+def test_an_all_identity_mapping_is_refused() -> None:
+ # Different scripts and offsets, but no minification was undone: every
+ # resolved name is its own name, so the bridge is doing nothing.
+ dev, prod = _arms(
+ {"Zk": [340, 3400], "qi": [17, 170]},
+ {"Zk": [340, 3400], "qi": [17, 170]},
+ {"ThreadMessage": [50, 500]},
+ {"ThreadMessage": [50, 500]},
+ )
+ b = S.build_bridge(
+ dev,
+ prod,
+ rungs = ("s", "m"),
+ react_version = "19.2.4",
+ bundle_source = "x",
+ anchor_names = ["ThreadMessage"],
+ react_url_filter = None,
+ anchor_url_filter = None,
+ )
+ assert b.status == S.FAILED
+ assert "map to their own name" in b.failure_reason
+
+
+def test_single_rung_bridge_is_refused() -> None:
+ b = S.build_bridge(
+ [_Snap([])],
+ [_Snap([])],
+ rungs = ("s",),
+ react_version = "19.2.4",
+ bundle_source = "x",
+ anchor_names = ["A"],
+ )
+ assert b.status == S.FAILED
+ assert "single-rung" in b.failure_reason or "rung" in b.failure_reason
+
+
+def test_no_dev_millisecond_can_enter_the_artefact() -> None:
+ b = S.Bridge(status = S.OK, react_version = "19.2.4", bundle_sha = "abc")
+ b.to_json() # integers only: fine
+ try:
+ S.assert_no_measurements({"mapping": {"a": "b"}, "dev_render_ms": 12.5})
+ except CellFailure as exc:
+ assert exc.gate == "dev_measurement_leak"
+ else:
+ raise AssertionError("a float in a bridge artefact must be refused")
+
+
+def test_bridge_round_trips_through_disk(tmpdir: str = "") -> None:
+ import tempfile
+
+ b = S.Bridge(status = S.OK, react_version = "19.2.4", bundle_sha = "deadbeefcafe0000")
+ b.mapping["react-dom.js:0:5"] = "cloneChildFibers"
+ b.evidence["react-dom.js:0:5"] = [340, 3400]
+ with tempfile.TemporaryDirectory() as d:
+ path = b.save(d)
+ assert os.path.basename(path) == "[email protected]"
+ again = S.Bridge.load(path)
+ assert again.resolve("/whatever/react-dom.js", 0, 5) == "cloneChildFibers"
+
+
+# ------------------------------------------------ the no-bare-zero convention
+
+
+def test_zero_is_distinguishable_from_did_not_run() -> None:
+ ran = measured("task_ms", 0.0)
+ didnt = unmeasured("task_ms", "tracing never started")
+ assert ran["task_ms"] == 0.0 and ran["task_ms_attempted"] is True
+ assert didnt["task_ms"] is None and didnt["task_ms_attempted"] is False
+ assert didnt["task_ms_reason"]
+ assert_no_bare_zero(ran)
+ assert_no_bare_zero(didnt)
+
+
+def test_a_bare_zero_is_refused() -> None:
+ try:
+ assert_no_bare_zero({"frames_dropped": 0})
+ except CellFailure as exc:
+ assert exc.gate == "bare_zero"
+ else:
+ raise AssertionError("a bare zero must be refused")
+
+
+def test_unmeasured_demands_a_reason() -> None:
+ try:
+ unmeasured("x", "")
+ except ValueError:
+ pass
+ else:
+ raise AssertionError("unmeasured without a reason must raise")
+
+
+def test_merge_refuses_conflicting_keys() -> None:
+ try:
+ merge(measured("a", 1), measured("a", 2))
+ except ValueError:
+ pass
+ else:
+ raise AssertionError("a silent key collision must raise")
+
+
+# ------------------------------------------------------------- M2/M3 oracles
+
+
+def test_cumulative_reparse_reads_as_quadratic() -> None:
+ out = O.reparse_regime(4_020_000, 40_000, 200)
+ assert out["regime"] == O.REGIME_QUADRATIC
+ assert out["evidence_class"] == "regime_test"
+
+
+def test_incremental_parse_reads_as_linear() -> None:
+ out = O.reparse_regime(40_000, 40_000, 200)
+ assert out["regime"] == O.REGIME_LINEAR
+
+
+def test_short_reply_refuses_to_call_the_regime() -> None:
+ out = O.reparse_regime(300, 100, 2)
+ assert out["regime"] == O.REGIME_UNDECIDED
+ assert "refusal band" in out["reason"]
+
+
+def test_m3_forced_layout_is_an_exact_oracle() -> None:
+ v = O.forced_layout_per_callback(4110, 4110, source = "page counters")
+ assert v.is_naming
+ v2 = O.forced_layout_per_callback(4110, 2055, source = "page counters")
+ assert not v2.is_naming
+
+
+def test_missing_page_counters_are_skipped_loudly() -> None:
+ out = O.evaluate_page_counters({})
+ assert out["m2"]["skipped"] and out["m2"]["reason"]
+ assert out["m3"]["skipped"] and out["m3"]["reason"]
+
+
+def test_page_counter_contract_is_documented() -> None:
+ # Layer 3 emits against these exact key names; a rename here is a contract
+ # change and must be agreed, not discovered at analysis time.
+ assert set(O.PAGE_COUNTER_CONTRACT) == {"m2_reparse", "m3_forced_layout"}
+ assert "chars_rescanned" in O.PAGE_COUNTER_CONTRACT["m2_reparse"]
+ assert "forced_layouts" in O.PAGE_COUNTER_CONTRACT["m3_forced_layout"]
+
+
+def _run_all() -> int:
+ failures = 0
+ for name, fn in sorted(globals().items()):
+ if not name.startswith("test_") or not callable(fn):
+ continue
+ try:
+ fn()
+ except Exception as exc: # noqa: BLE001
+ failures += 1
+ print(f"FAIL {name}: {type(exc).__name__}: {exc}")
+ else:
+ print(f"ok {name}")
+ print(f"\n{failures} failure(s)")
+ return 1 if failures else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(_run_all())
diff --git a/tests/studio/studiobench/analysis/test_instruments_live.py b/tests/studio/studiobench/analysis/test_instruments_live.py
new file mode 100644
index 00000000000..94b579c4526
--- /dev/null
+++ b/tests/studio/studiobench/analysis/test_instruments_live.py
@@ -0,0 +1,303 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Drive Layer 2's instruments through Layer 1's ACTUAL protocol, in a real browser.
+
+The unit tests next door prove the analysis is right about a trace. This proves
+the instruments are wired correctly into the harness contract, which is a
+different failure mode entirely and the one my own report flagged as untested:
+four modules that imported cleanly and registered nothing.
+
+It uses the real `Cell`, `Window`, `BenchContext` and `Paths` from
+`runtime.types`, the real `instruments.build(level)` registry, and calls
+`attach / start_cell / open / close / end_cell / detach` in the documented order
+with the documented reverse-order close. Nothing is mocked except the page,
+which is a local synthetic instead of a Studio install.
+
+Requires Playwright with Chromium. Skips cleanly without it, because a machine
+that cannot run a browser should report that rather than fail.
+
+ python tests/studio/studiobench/analysis/test_instruments_live.py
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+_HERE = os.path.dirname(os.path.abspath(__file__))
+_STUDIO_TESTS = os.path.dirname(os.path.dirname(_HERE))
+if _STUDIO_TESTS not in sys.path:
+ sys.path.insert(0, _STUDIO_TESTS)
+
+from studiobench.analysis import assert_no_bare_zero # noqa: E402
+from studiobench.instruments import available, build, import_errors # noqa: E402
+from studiobench.runtime.types import ( # noqa: E402
+ BenchContext,
+ Cell,
+ Paths,
+ Recorder,
+ Window,
+ make_cell_id,
+ new_session_id,
+)
+
+# A page with a known shape: a message-channel loop (the React scheduler's
+# mechanism), a timer loop, and a function whose call count is exactly known.
+PAGE = """<!doctype html><meta charset=utf-8><body><div id=o></div><script>
+window.__N = 0;
+window.__junk = [];
+function hotLeafFrame(x){ var s=0; for(var i=0;i<400;i++){ s+=Math.sqrt(i*x)|0; } window.__N++; return s; }
+function allocSiblings(n){ var out=[]; for(var i=0;i<n;i++) out.push({a:i,b:'sib'+i,c:[i,i,i]}); return out; }
+function middleFrame(k){ var t=0; for(var j=0;j<20;j++) t+=hotLeafFrame(j+k); window.__junk=allocSiblings(200); return t; }
+window.__runMsg = function(iters){ return new Promise(function(res){
+ var mc = new MessageChannel(); var n = 0;
+ mc.port1.onmessage = function(){ middleFrame(2); if(++n < iters) mc.port2.postMessage(0); else res(n); };
+ mc.port2.postMessage(0); }); };
+window.__runTimer = function(){ var id = setInterval(function(){ middleFrame(1); }, 4);
+ setTimeout(function(){ clearInterval(id); }, 300); };
+</script></body>"""
+
+MESSAGE_ITERATIONS = 150
+CALLS_PER_MESSAGE = 20 # middleFrame calls hotLeafFrame 20 times
+
+
+def _skip(reason: str) -> int:
+ print(f"SKIP: {reason}")
+ return 0
+
+
+def _drive(instruments, ctx, cell, page, window_names):
+ """Run the documented lifecycle over a list of windows.
+
+ Open is in `name` order, close is in REVERSE `name` order, exactly as
+ INTERFACES.md section 2 specifies. A raising instrument is caught and
+ disabled for the rest of the cell rather than losing the window.
+ """
+ ordered = sorted(instruments, key = lambda i: i.name)
+ for inst in ordered:
+ inst.attach(ctx)
+ for inst in ordered:
+ inst.start_cell(cell)
+
+ rows = {}
+ for wname in window_names:
+ w = Window(name = wname, kind = "action", cell = cell, t_open_ms = time.monotonic() * 1000)
+ for inst in ordered:
+ inst.open(w)
+ page.evaluate(f"__runTimer(); __runMsg({MESSAGE_ITERATIONS});")
+ page.wait_for_timeout(400)
+ w.t_close_ms = time.monotonic() * 1000
+ for inst in reversed(ordered):
+ out = inst.close(w)
+ if out is not None:
+ w.instruments[inst.name] = out
+ rows[wname] = w
+
+ cell_rows = {}
+ for inst in ordered:
+ out = inst.end_cell(cell)
+ if out is not None:
+ cell_rows[inst.name] = out
+ for inst in ordered:
+ inst.detach()
+ return rows, cell_rows
+
+
+def main() -> int:
+ try:
+ from playwright.sync_api import sync_playwright
+ except ImportError:
+ return _skip("playwright is not installed")
+
+ errs = import_errors()
+ if errs:
+ print(f"FAIL: instrument modules failed to import: {errs}")
+ return 1
+
+ names = dict(available())
+ expected = {"tracing": 1, "cpu_profile": 1, "coverage": 3, "heap": 3}
+ if names != expected:
+ print(f"FAIL: registry is {names}, expected {expected}")
+ return 1
+ print(f"ok registry: {sorted(names.items())}")
+
+ if build(0):
+ print("FAIL: build(0) must be empty so headline numbers can come from L0 only")
+ return 1
+ print("ok build(0) is empty; L0 attaches nothing")
+
+ failures = 0
+ with tempfile.TemporaryDirectory() as tmp:
+ paths = Paths.under(Path(tmp))
+ session_id = new_session_id()
+ recorder = Recorder(paths.payload_jsonl, session_id)
+
+ with sync_playwright() as pw:
+ browser = pw.chromium.launch(args = ["--no-sandbox"])
+ try:
+ for level in (1, 2, 3):
+ context = browser.new_context()
+ page = context.new_page()
+ page.set_content(PAGE)
+ cdp = context.new_cdp_session(page)
+
+ ctx = BenchContext(
+ browser = browser,
+ context = context,
+ page = page,
+ cdp = cdp,
+ base_url = "about:blank",
+ session_id = session_id,
+ tier = "quick",
+ instrument_level = level,
+ paths = paths,
+ recorder = recorder,
+ log = lambda m: None,
+ )
+ cell = Cell(
+ cell_id = make_cell_id("10K", "A0", 0),
+ rung = "10K",
+ rung_tokens = 10_000,
+ instrument_level = level,
+ session_id = session_id,
+ )
+ insts = build(level)
+ page.evaluate("window.__N = 0")
+ wrows, crows = _drive(insts, ctx, cell, page, ["action:stream"])
+ ground_truth = page.evaluate("window.__N")
+
+ failures += _check_level(level, wrows, crows, ground_truth)
+ context.close()
+ finally:
+ browser.close()
+ recorder.close()
+
+ print(f"\n{failures} failure(s)")
+ return 1 if failures else 0
+
+
+def _check_level(level, wrows, crows, ground_truth) -> int:
+ bad = 0
+ w = wrows["action:stream"]
+ tag = f"L{level}"
+
+ def fail(msg: str) -> None:
+ nonlocal bad
+ bad += 1
+ print(f"FAIL [{tag}] {msg}")
+
+ # Every payload must obey the no-bare-zero rule before it can be emitted.
+ for name, payload in list(w.instruments.items()) + list(crows.items()):
+ try:
+ assert_no_bare_zero(payload, f"{tag}.{name}")
+ except Exception as exc: # noqa: BLE001
+ fail(f"{name} violates the no-bare-zero rule: {exc}")
+
+ # The window row must be JSON-serialisable, since Recorder writes it.
+ import json
+
+ try:
+ json.dumps(w.row())
+ except Exception as exc: # noqa: BLE001
+ fail(f"window row is not JSON-safe: {exc}")
+
+ # Overhead is mandatory from every instrument at level >= 1, and it is what
+ # the report layer's overhead_growth_with_length gate consumes.
+ for name, payload in crows.items():
+ if "overhead_ms" not in payload or "overhead_ms_attempted" not in payload:
+ fail(f"{name}.end_cell has no overhead_ms/overhead_ms_attempted")
+
+ tracing = w.instruments.get("tracing", {})
+ if tracing.get("task_ms") is None:
+ fail(f"tracing reported no task_ms: {tracing.get('task_ms_reason')}")
+ elif tracing.get("unclassified_task_pct") is None:
+ fail("tracing reported no unclassified_task_pct")
+ else:
+ by_origin = tracing.get("task_count_by_origin") or {}
+ print(
+ f"ok [{tag}] tracing task_ms={tracing['task_ms']} "
+ f"unclassified={tracing['unclassified_task_pct']}% origins={by_origin}"
+ )
+ if by_origin.get("message_channel", 0) < MESSAGE_ITERATIONS * 0.8:
+ fail(f"expected ~{MESSAGE_ITERATIONS} message-channel tasks, got {by_origin}")
+
+ # THE LADDER. Naming requires the v8 profiler, which only L2+ turns on. At
+ # L1 that must be an explicit null with a reason, never an empty list.
+ if level == 1:
+ if tracing.get("named_frames") is not None:
+ fail("L1 must not report named frames; the profiler category is off")
+ elif not tracing.get("named_frames_reason"):
+ fail("L1 named_frames must carry a reason")
+ else:
+ print(f"ok [{tag}] named_frames is null with a reason, not an empty list")
+ cp = w.instruments.get("cpu_profile", {})
+ if not cp.get("active"):
+ fail(f"cpu_profile should be active at L1: {cp.get('self_ms_top_reason')}")
+ elif cp.get("self_ms_top") is None:
+ fail(f"cpu_profile ran but named nothing: {cp.get('self_ms_top_reason')}")
+ else:
+ top = [r["frame"].split(" @ ")[0] for r in cp["self_ms_top"][:3]]
+ print(f"ok [{tag}] standalone profiler named {top}")
+ else:
+ frames = tracing.get("named_frames")
+ if frames is None:
+ fail(f"L{level} must name frames: {tracing.get('named_frames_reason')}")
+ else:
+ top = [r["frame"].split(" @ ")[0] for r in frames[:3]]
+ print(f"ok [{tag}] tracing named {top}")
+ cp = w.instruments.get("cpu_profile", {})
+ if cp.get("active"):
+ fail("cpu_profile must stand down at L2+; V8 has one CpuProfiler")
+ elif not (crows.get("cpu_profile", {}).get("stand_down_reason")):
+ fail("cpu_profile stood down without saying why")
+ else:
+ print(
+ f"ok [{tag}] cpu_profile stood down: "
+ f"{crows['cpu_profile']['stand_down_reason'][:60]}..."
+ )
+
+ if level == 3:
+ cov = w.instruments.get("coverage", {})
+ if cov.get("total_calls") is None:
+ fail(f"coverage reported nothing: {cov.get('total_calls_reason')}")
+ else:
+ hits = [f for f in cov["top_functions"] if f["function"] == "hotLeafFrame"]
+ if not hits:
+ fail("coverage did not count the known hot function")
+ elif hits[0]["count"] != ground_truth:
+ fail(f"coverage counted {hits[0]['count']}, page counted {ground_truth}")
+ else:
+ mids = [f for f in cov["top_functions"] if f["function"] == "middleFrame"]
+ exact_oracle = mids and hits[0]["count"] == CALLS_PER_MESSAGE * mids[0]["count"]
+ print(
+ f"ok [{tag}] coverage counted hotLeafFrame exactly "
+ f"{hits[0]['count']} == page counter; structural oracle "
+ f"(hot == {CALLS_PER_MESSAGE} x middle) {'holds' if exact_oracle else 'MISSED'}"
+ )
+ if not exact_oracle:
+ fail("the structural count oracle did not hold")
+ if not cov.get("timings_void"):
+ fail("coverage must mark the cell timings_void")
+ else:
+ print(f"ok [{tag}] coverage marked timings_void")
+ heap = w.instruments.get("heap", {})
+ if heap.get("allocated_bytes") is None:
+ fail(f"heap reported nothing: {heap.get('allocated_bytes_reason')}")
+ elif not heap.get("included_objects_collected_by_major_gc"):
+ fail("heap must include objects collected by major GC")
+ else:
+ sites = [s["site"].split(" @ ")[0] for s in heap["top_sites"][:3]]
+ print(f"ok [{tag}] heap saw {heap['allocated_bytes']} bytes, top sites {sites}")
+ else:
+ if "coverage" in w.instruments or "heap" in w.instruments:
+ fail(f"coverage/heap must not run below L3, got {sorted(w.instruments)}")
+
+ return bad
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/studio/studiobench/analysis/testdata/probe_msgchan_timer_raf.json.gz b/tests/studio/studiobench/analysis/testdata/probe_msgchan_timer_raf.json.gz
new file mode 100644
index 00000000000..2c98cb7cd4a
Binary files /dev/null and b/tests/studio/studiobench/analysis/testdata/probe_msgchan_timer_raf.json.gz differ
diff --git a/tests/studio/studiobench/analysis/traceparse.py b/tests/studio/studiobench/analysis/traceparse.py
new file mode 100644
index 00000000000..e9a0a8e9d34
--- /dev/null
+++ b/tests/studio/studiobench/analysis/traceparse.py
@@ -0,0 +1,356 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Parse a Chrome trace into a per-thread task tree.
+
+All timestamps in a Chrome JSON trace are MICROSECONDS on the monotonic clock
+(`ts`), with `dur` also in microseconds for complete (`ph: "X"`) events. Nothing
+in this module rescales; if a caller wants milliseconds it divides, so that a
+unit mistake is a visible division and not a hidden constant.
+
+Two facts about real traces that this module encodes because both were observed
+in a captured trace rather than assumed:
+
+1. `RunTask` (category `disabled-by-default-devtools.timeline`) has EMPTY args.
+ It tells you a task ran and how long it took, and nothing whatsoever about
+ where it came from. The origin lives on a SIBLING event,
+ `ThreadControllerImpl::RunTask` (category `toplevel`), which carries
+ `src_file` / `src_func` / `src_line` naming the code that POSTED the task.
+ The two nest, they are 1:1 on a thread, and their `ts` values differ by a
+ microsecond or two, so they must be joined by interval containment and not by
+ timestamp equality. A naive equality join matched 79% of tasks on a real
+ capture, and the 21% it dropped is not a random sample.
+
+2. `ProfileChunk` events are emitted on the V8 profiler's own thread
+ (`v8:ProfEvntProc`), NOT on the thread being profiled. The profiled thread is
+ named by the `Profile` event's own `pid`/`tid`. Filtering chunks by the
+ renderer main thread id yields zero samples and looks exactly like "the CPU
+ profiler was not enabled".
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from dataclasses import dataclass, field
+from typing import Any, Iterable, Iterator, Sequence
+
+from . import CellFailure
+
+# Complete-duration events are the only phase that forms the task tree. Async
+# (`b`/`e`/`n`), flow (`s`/`t`/`f`), instant (`I`/`R`), sample (`P`), counter
+# (`C`) and metadata (`M`) events are carried alongside but never nested, since
+# their timestamps do not describe a stack.
+_PHASE_COMPLETE = "X"
+_PHASE_BEGIN = "B"
+_PHASE_END = "E"
+
+# When two events share both `ts` and `dur`, the trace gives no ordering. On the
+# main thread the devtools view (`RunTask`) is conceptually the outer frame and
+# the scheduler view (`ThreadControllerImpl::RunTask`) the inner one, so pin
+# that order rather than letting dict ordering decide which is the parent.
+_OUTERMOST_FIRST = {
+ "RunTask": 0,
+ "ThreadControllerImpl::RunTask": 1,
+}
+
+
+@dataclass
+class Task:
+ """One complete-duration trace event plus the events nested inside it."""
+
+ name: str
+ cat: str
+ ts: int
+ dur: int
+ pid: int
+ tid: int
+ args: dict[str, Any] = field(default_factory = dict)
+ children: list["Task"] = field(default_factory = list)
+ parent: "Task | None" = field(default = None, repr = False)
+
+ @property
+ def end(self) -> int:
+ return self.ts + self.dur
+
+ @property
+ def self_dur(self) -> int:
+ """Duration minus the time attributed to nested events.
+
+ Children of a complete event do not overlap each other in a well-formed
+ trace, so a plain sum is correct. Clamped at zero because a malformed
+ trace can report a child longer than its parent and a negative self time
+ would poison every downstream sum silently.
+ """
+ return max(0, self.dur - sum(c.dur for c in self.children))
+
+ def walk(self) -> Iterator["Task"]:
+ yield self
+ for c in self.children:
+ yield from c.walk()
+
+ def descendants_named(self, *names: str) -> list["Task"]:
+ wanted = set(names)
+ return [t for t in self.walk() if t is not self and t.name in wanted]
+
+ def find_child_task(self, name: str) -> "Task | None":
+ for t in self.walk():
+ if t is not self and t.name == name:
+ return t
+ return None
+
+
+@dataclass
+class Thread:
+ pid: int
+ tid: int
+ name: str
+ roots: list[Task] = field(default_factory = list)
+ # Every event on this thread, including phases that do not nest.
+ events: list[dict[str, Any]] = field(default_factory = list)
+
+ def tasks_named(self, name: str) -> list[Task]:
+ return [t for r in self.roots for t in r.walk() if t.name == name]
+
+ def wall_span_us(self) -> tuple[int, int]:
+ if not self.roots:
+ return (0, 0)
+ return (self.roots[0].ts, max(r.end for r in self.roots))
+
+
+class Trace:
+ """A loaded Chrome trace, indexed by thread."""
+
+ def __init__(
+ self,
+ events: Sequence[dict[str, Any]],
+ metadata: dict[str, Any] | None = None,
+ ) -> None:
+ self.events: list[dict[str, Any]] = list(events)
+ self.metadata: dict[str, Any] = dict(metadata or {})
+ self._thread_names: dict[tuple[int, int], str] = {}
+ for e in self.events:
+ if e.get("name") == "thread_name" and e.get("ph") == "M":
+ key = (e.get("pid"), e.get("tid"))
+ name = (e.get("args") or {}).get("name")
+ if isinstance(name, str) and None not in key:
+ self._thread_names[key] = name # type: ignore[index]
+ self._threads: dict[tuple[int, int], Thread] = {}
+
+ # ---------------------------------------------------------------- loading
+
+ @classmethod
+ def from_json_text(cls, text: str) -> "Trace":
+ """Load the exact wire format `Tracing` emits.
+
+ `transferMode: ReturnAsStream` with `streamFormat: json` produces an
+ OBJECT, `{"traceEvents": [...], "metadata": {...}}`, not the bare array
+ that the Trace Event Format also permits. Both are accepted here because
+ traces saved by the DevTools UI use the array form.
+ """
+ text = text.strip()
+ if not text:
+ raise CellFailure("trace_empty", "trace stream contained no bytes")
+ try:
+ doc = json.loads(text)
+ except json.JSONDecodeError as exc:
+ # A truncated JSON document is the signature of a drained stream that
+ # was cut short. That is a failed cell, never a short trace.
+ raise CellFailure(
+ "trace_truncated",
+ f"trace JSON did not parse ({exc}); {len(text)} bytes drained",
+ ) from exc
+ if isinstance(doc, list):
+ return cls(doc, {})
+ if isinstance(doc, dict) and isinstance(doc.get("traceEvents"), list):
+ return cls(doc["traceEvents"], doc.get("metadata") or {})
+ raise CellFailure(
+ "trace_shape",
+ f"unrecognised trace document keys: {sorted(doc)[:8] if isinstance(doc, dict) else type(doc)}",
+ )
+
+ @classmethod
+ def from_path(cls, path: str | os.PathLike[str]) -> "Trace":
+ """Load a trace from disk, transparently gunzipping a `.gz`.
+
+ Checked-in fixtures are gzipped because a trace of any useful length is
+ megabytes of highly repetitive JSON.
+ """
+ p = str(path)
+ if p.endswith(".gz"):
+ import gzip
+ with gzip.open(p, "rt", encoding = "utf-8") as fh:
+ return cls.from_json_text(fh.read())
+ with open(p, "r", encoding = "utf-8") as fh:
+ return cls.from_json_text(fh.read())
+
+ # ---------------------------------------------------------------- threads
+
+ def thread_name(self, pid: int, tid: int) -> str:
+ return self._thread_names.get((pid, tid), "")
+
+ def thread(self, pid: int, tid: int) -> Thread:
+ key = (pid, tid)
+ cached = self._threads.get(key)
+ if cached is not None:
+ return cached
+ own = [e for e in self.events if e.get("pid") == pid and e.get("tid") == tid]
+ th = Thread(pid = pid, tid = tid, name = self.thread_name(pid, tid), events = own)
+ th.roots = build_tree(own)
+ self._threads[key] = th
+ return th
+
+ def profiled_thread(self) -> tuple[int, int]:
+ """The thread the V8 CPU profiler attached to, read from `Profile`.
+
+ This is the correct anchor for the renderer main thread whenever the CPU
+ profiler category is on, because it is the thread whose stacks we have.
+ Falls back to the thread named `CrRendererMain`.
+ """
+ for e in self.events:
+ if e.get("name") == "Profile" and e.get("cat") == "disabled-by-default-v8.cpu_profiler":
+ return (int(e["pid"]), int(e["tid"]))
+ for (pid, tid), name in self._thread_names.items():
+ if name == "CrRendererMain":
+ return (pid, tid)
+ raise CellFailure(
+ "no_renderer_thread",
+ "trace has neither a v8 Profile event nor a CrRendererMain thread_name",
+ )
+
+ def renderer_main(self) -> Thread:
+ pid, tid = self.profiled_thread()
+ return self.thread(pid, tid)
+
+ # ------------------------------------------------------------------ joins
+
+ def run_tasks(self, thread: Thread | None = None) -> list[Task]:
+ """Top-level `RunTask` events on a thread, outermost only."""
+ th = thread if thread is not None else self.renderer_main()
+ out: list[Task] = []
+ for root in th.roots:
+ for t in root.walk():
+ if t.name == "RunTask" and not _has_runtask_ancestor(t):
+ out.append(t)
+ out.sort(key = lambda t: t.ts)
+ return out
+
+ def total_run_task_ms(self, thread: Thread | None = None) -> float:
+ return sum(t.dur for t in self.run_tasks(thread)) / 1000.0
+
+
+def _has_runtask_ancestor(task: Task) -> bool:
+ p = task.parent
+ while p is not None:
+ if p.name == "RunTask":
+ return True
+ p = p.parent
+ return False
+
+
+def build_tree(events: Iterable[dict[str, Any]]) -> list[Task]:
+ """Nest complete-duration events on ONE thread into a forest.
+
+ `B`/`E` pairs are folded into synthetic complete events first so that a
+ trace which uses the begin/end encoding parses identically. Unmatched `B`
+ events are dropped rather than guessed at, and an unmatched `E` is ignored,
+ because inventing an end timestamp would invent duration.
+ """
+ complete: list[Task] = []
+ open_stack: list[dict[str, Any]] = []
+ for e in events:
+ ph = e.get("ph")
+ if ph == _PHASE_COMPLETE:
+ dur = e.get("dur")
+ if dur is None:
+ # A complete event without `dur` is a zero-width marker.
+ dur = 0
+ complete.append(
+ Task(
+ name = str(e.get("name", "")),
+ cat = str(e.get("cat", "")),
+ ts = int(e["ts"]),
+ dur = int(dur),
+ pid = int(e.get("pid", 0)),
+ tid = int(e.get("tid", 0)),
+ args = dict(e.get("args") or {}),
+ )
+ )
+ elif ph == _PHASE_BEGIN:
+ open_stack.append(e)
+ elif ph == _PHASE_END:
+ if not open_stack:
+ continue
+ b = open_stack.pop()
+ args = dict(b.get("args") or {})
+ args.update(e.get("args") or {})
+ complete.append(
+ Task(
+ name = str(b.get("name", "")),
+ cat = str(b.get("cat", "")),
+ ts = int(b["ts"]),
+ dur = max(0, int(e["ts"]) - int(b["ts"])),
+ pid = int(b.get("pid", 0)),
+ tid = int(b.get("tid", 0)),
+ args = args,
+ )
+ )
+
+ complete.sort(key = lambda t: (t.ts, -t.dur, _OUTERMOST_FIRST.get(t.name, 50)))
+
+ roots: list[Task] = []
+ stack: list[Task] = []
+ for t in complete:
+ while stack and t.ts >= stack[-1].end:
+ stack.pop()
+ # An event that starts inside its would-be parent but ends after it is
+ # not nested; the trace is inconsistent there. Treat it as a sibling
+ # rather than corrupting self-time arithmetic for the whole subtree.
+ while stack and t.end > stack[-1].end:
+ stack.pop()
+ if stack:
+ t.parent = stack[-1]
+ stack[-1].children.append(t)
+ else:
+ roots.append(t)
+ stack.append(t)
+ return roots
+
+
+def join_posted_from(task: Task) -> dict[str, Any]:
+ """Return the `src_file`/`src_func`/`src_line` that POSTED this task.
+
+ Joined by interval containment against the nested
+ `ThreadControllerImpl::RunTask`, since the timestamps differ by a couple of
+ microseconds and an equality join loses a fifth of all tasks. Returns an
+ empty dict when the `toplevel` category was not recorded, which is a
+ legitimate state and not an error: the caller then classifies on nested
+ evidence alone and reports lower confidence.
+ """
+ for t in walk_within_task(task):
+ if t.name == "ThreadControllerImpl::RunTask":
+ a = t.args or {}
+ if "src_file" in a or "src_func" in a:
+ return {
+ "src_file": a.get("src_file", ""),
+ "src_func": a.get("src_func", ""),
+ "src_line": a.get("src_line"),
+ }
+ return {}
+
+
+def walk_within_task(task: Task) -> Iterator[Task]:
+ """Walk a task's subtree, stopping at any nested `RunTask` boundary.
+
+ Without the boundary a nested task's scheduler frame or its `TimerFire`
+ would be attributed to the outer task, which is how one long task swallows
+ the origin of every task it contains.
+ """
+ yield task
+ stack = list(task.children)
+ while stack:
+ node = stack.pop()
+ if node.name == "RunTask":
+ continue
+ yield node
+ stack.extend(node.children)
diff --git a/tests/studio/studiobench/arms/__init__.py b/tests/studio/studiobench/arms/__init__.py
new file mode 100644
index 00000000000..a9fa3ddf8fe
--- /dev/null
+++ b/tests/studio/studiobench/arms/__init__.py
@@ -0,0 +1,88 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Ablation arms: the layer that turns a correlation into a cause.
+
+Four pieces, in the order they constrain each other:
+
+ manifest.py what every arm must declare (INVARIANCE, POTENCY) and the verdict logic that
+ turns a run into QUOTED, BOUND, VOIDED, NOT RUN or UNAVAILABLE
+ knobs.py/.js the seven runtime-injected knobs on the shipped build, as a decision table
+ ladder.py the telescoping ladder, its adjacent differences, and the interaction term
+ between two routes to the same floor
+ calibration.py NULL and SPIKE, non-droppable, which decide whether the batch is quotable
+
+plus `bundle.py` for the arms that need an armed dist, `dose.py` for the dose-response that makes
+a null informative, and `recovery.py` for occupancy versus retention.
+"""
+
+from .batch import ( # noqa: F401
+ BatchPlanError,
+ BatchResult,
+ PlannedCell,
+ assert_equal_scene_duration,
+ judge_batch,
+ missing_cells,
+ plan_batch,
+)
+from .bundle import ( # noqa: F401
+ BANNER,
+ BUNDLE_ARMS,
+ ArmpackManifest,
+ ArmpackResolution,
+ ArmpackUnavailable,
+ discover_armpack,
+)
+from .calibration import ( # noqa: F401
+ CALIBRATION_ARM_IDS,
+ CalibrationMissing,
+ CalibrationVerdict,
+ SPIKE_SIZES_MS,
+ SpikeRecovery,
+ assert_batch_includes_calibration,
+ calibration_arms,
+ evaluate_batch,
+ null_arm,
+ null_delta_from_outcomes,
+ spike_arm,
+ spike_init_script,
+)
+from .dose import DOSES, DoseFit, DosePoint, fit_dose_response # noqa: F401
+from .knobs import ( # noqa: F401
+ ARM_BY_ID,
+ PREBOOT_ARM_IDS,
+ RUNTIME_ARM_IDS,
+ RUNTIME_ARMS,
+ arms_json,
+ config_init_script,
+ decision_table,
+ init_scripts_for,
+ load_knobs_js,
+ render_decision_table,
+ split_arms,
+)
+from .ladder import ( # noqa: F401
+ DECLARED_ROUTES,
+ MECHANISMS,
+ MECHANISM_FIX,
+ InteractionTerm,
+ LadderError,
+ LadderRoute,
+ RouteResult,
+ Step,
+ StepResult,
+ arms_key,
+ differences,
+ interaction_terms,
+ required_rungs,
+)
+from .manifest import ( # noqa: F401
+ Arm,
+ ArmOutcome,
+ ArmStatus,
+ DeclaredDiff,
+ Invariance,
+ PotencyCounter,
+ judge,
+)
+from .recovery import RECOVERY_TURNS, RecoveryResult, classify_recovery # noqa: F401
diff --git a/tests/studio/studiobench/arms/batch.py b/tests/studio/studiobench/arms/batch.py
new file mode 100644
index 00000000000..fb3c1e8d0b7
--- /dev/null
+++ b/tests/studio/studiobench/arms/batch.py
@@ -0,0 +1,213 @@
+# 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 batch: the unit that is planned, run, calibrated and then either quoted or not.
+
+A batch is every cell needed to answer one question at one rung: both ladder routes, their shared
+floor, the control, and the non-droppable calibration arms. It is the unit because calibration is
+the unit: the noise floor and the detection floor are properties of a machine at a moment, and
+carrying them across batches is how a number measured on a cold laptop gets quoted against one
+measured while a build was running.
+
+WHAT THIS MODULE ENFORCES, BEFORE ANYTHING RUNS:
+
+ * calibration arms are present. `assert_batch_includes_calibration` refuses a plan without them,
+ because "we will check afterwards whether that batch was resolvable" is not a thing that can
+ be done afterwards.
+ * every rung both declared routes need has a cell. A route with a hole cannot telescope, and
+ discovering that after an hour of measurement wastes the hour.
+ * the scene is the SAME LENGTH in every arm. This is the quiet one. The scene is a film on a
+ wall clock, so if one arm's film is 40 seconds and another's is 44, the two arms saw different
+ amounts of streaming and their difference includes that. Layer 1's contract allows an arm to
+ supply its own slot list; this check is what stops that freedom from silently breaking
+ additivity.
+
+WHAT IT DOES AFTER:
+ judges each arm against its manifest, computes both routes' adjacent differences, computes the
+ interaction terms between them, and hands the whole thing to the report layer. It does not
+ decide what is quotable; `CalibrationVerdict` does, and `BatchResult.quotable` just reads it.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Iterable, Mapping, Sequence
+
+from ..scoring.schema import Measure
+from .bundle import ArmpackResolution
+from .calibration import (
+ CALIBRATION_ARM_IDS,
+ CalibrationVerdict,
+ assert_batch_includes_calibration,
+)
+from .dose import DoseFit
+from .ladder import (
+ DECLARED_ROUTES,
+ InteractionTerm,
+ LadderError,
+ LadderRoute,
+ RouteResult,
+ arms_key,
+ differences,
+ interaction_terms,
+ required_rungs,
+)
+from .manifest import ArmOutcome, ArmStatus
+from .recovery import RecoveryResult
+
+
+class BatchPlanError(AssertionError):
+ """Raised when a batch plan cannot answer the question it is being run to answer."""
+
+
+@dataclass(frozen = True)
+class PlannedCell:
+ """One cell of a batch: which arms are applied, and what it is for."""
+
+ arms: frozenset[str]
+ role: str # "ladder" | "calibration" | "control" | "dose" | "recovery"
+ label: str = ""
+
+ @property
+ def key(self) -> str:
+ return arms_key(self.arms)
+
+ def to_json(self) -> dict[str, Any]:
+ return {"arms": sorted(self.arms), "key": self.key, "role": self.role, "label": self.label}
+
+
+def plan_batch(
+ routes: Sequence[LadderRoute] = DECLARED_ROUTES,
+ *,
+ calibration_arm_ids: Sequence[str] = CALIBRATION_ARM_IDS,
+) -> list[PlannedCell]:
+ """Every cell this batch must run, ladder rungs first, calibration always."""
+
+ cells = [PlannedCell(arms = rung, role = "ladder") for rung in required_rungs(routes)]
+ cells.extend(
+ PlannedCell(arms = frozenset({arm_id}), role = "calibration", label = arm_id)
+ for arm_id in calibration_arm_ids
+ )
+ planned_ids = {arm_id for cell in cells for arm_id in cell.arms}
+ assert_batch_includes_calibration(planned_ids)
+ return cells
+
+
+def assert_equal_scene_duration(
+ scene_durations_ms: Mapping[str, float], *, tolerance_ms: float = 1.0
+) -> None:
+ """Every arm in a batch must run a scene of the same length.
+
+ The scene is slot-scheduled on the wall clock, so its duration sets how much streaming each
+ arm saw. Two arms with different scene lengths differ by the treatment AND by the workload,
+ and no amount of care in the ladder recovers that. Layer 1 permits per-arm slot lists; this
+ is the check that keeps the permission from quietly breaking additivity.
+ """
+
+ if not scene_durations_ms:
+ raise BatchPlanError("no scene durations were supplied, so equality was never checked")
+ values = list(scene_durations_ms.values())
+ spread = max(values) - min(values)
+ if spread > tolerance_ms:
+ offenders = ", ".join(
+ f"{arm}={duration:.1f} ms" for arm, duration in sorted(scene_durations_ms.items())
+ )
+ raise BatchPlanError(
+ f"scene durations differ across arms by {spread:.1f} ms (tolerance {tolerance_ms:g} "
+ f"ms): {offenders}. Arms with different-length scenes saw different amounts of "
+ "streaming, so their difference is not the treatment"
+ )
+
+
+@dataclass
+class BatchResult:
+ """One batch, judged. Nothing in here is quotable unless `quotable` is true."""
+
+ rung_tokens: int
+ calibration: CalibrationVerdict
+ outcomes: dict[str, ArmOutcome] = field(default_factory = dict)
+ routes: list[RouteResult] = field(default_factory = list)
+ interactions: list[InteractionTerm] = field(default_factory = list)
+ armpack: ArmpackResolution | None = None
+ dose: DoseFit | None = None
+ recovery: RecoveryResult | None = None
+ plan_notes: list[str] = field(default_factory = list)
+
+ @property
+ def quotable(self) -> bool:
+ return self.calibration.quotable
+
+ @property
+ def detection_floor_ms(self) -> float | None:
+ floor = self.calibration.detection_floor_ms
+ return float(floor.value) if floor.has_reading else None
+
+ def voided_arms(self) -> list[ArmOutcome]:
+ return [o for o in self.outcomes.values() if o.status is ArmStatus.VOIDED]
+
+ def not_run_arms(self) -> list[ArmOutcome]:
+ return [o for o in self.outcomes.values() if o.status is ArmStatus.NOT_RUN]
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "rung_tokens": int(self.rung_tokens),
+ "quotable": self.quotable,
+ "calibration": self.calibration.to_json(),
+ "outcomes": {key: outcome.to_json() for key, outcome in self.outcomes.items()},
+ "routes": [route.to_json() for route in self.routes],
+ "interactions": [term.to_json() for term in self.interactions],
+ "armpack": self.armpack.to_json() if self.armpack else None,
+ "dose": self.dose.to_json() if self.dose else None,
+ "recovery": self.recovery.to_json() if self.recovery else None,
+ "plan_notes": list(self.plan_notes),
+ "voided_arms": [o.arm.arm_id for o in self.voided_arms()],
+ "not_run_arms": [o.arm.arm_id for o in self.not_run_arms()],
+ }
+
+
+def judge_batch(
+ *,
+ rung_tokens: int,
+ outcomes: Mapping[str, ArmOutcome],
+ calibration: CalibrationVerdict,
+ routes: Sequence[LadderRoute] = DECLARED_ROUTES,
+ armpack: ArmpackResolution | None = None,
+ dose: DoseFit | None = None,
+ recovery: RecoveryResult | None = None,
+) -> BatchResult:
+ """Turn a batch's raw arm outcomes into route differences and interaction terms.
+
+ The detection floor comes from the calibration arms of THIS batch and is threaded into every
+ difference, so a step below what this machine could resolve prints as a bound rather than as
+ a small number. That is the whole reason calibration is per batch.
+ """
+
+ result = BatchResult(
+ rung_tokens = int(rung_tokens),
+ calibration = calibration,
+ outcomes = dict(outcomes),
+ armpack = armpack,
+ dose = dose,
+ recovery = recovery,
+ )
+ floor = result.detection_floor_ms
+
+ for route in routes:
+ result.routes.append(differences(route, outcomes, detection_floor_ms = floor))
+
+ for index, left in enumerate(result.routes):
+ for right in result.routes[index + 1 :]:
+ try:
+ result.interactions.extend(interaction_terms(left, right, detection_floor_ms = floor))
+ except LadderError as error:
+ result.plan_notes.append(str(error))
+
+ if not result.quotable:
+ result.plan_notes.append("this batch is NOT quotable: " + calibration.reason)
+ return result
+
+
+def missing_cells(planned: Iterable[PlannedCell], outcomes: Mapping[str, ArmOutcome]) -> list[str]:
+ """Which planned cells produced no outcome. Checked before the report, not after."""
+
+ return [cell.key for cell in planned if cell.key not in outcomes]
diff --git a/tests/studio/studiobench/arms/bundle.py b/tests/studio/studiobench/arms/bundle.py
new file mode 100644
index 00000000000..39f98e80aeb
--- /dev/null
+++ b/tests/studio/studiobench/arms/bundle.py
@@ -0,0 +1,318 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Bundle-variant arms, and the refusal that keeps them from being skipped quietly.
+
+Three hypotheses cannot be tested by injecting script into a shipped build, because they are
+about what React does internally rather than about what the DOM does. They need a dist that was
+COMPILED differently, built once in CI and shipped as an ARMPACK next to the benchmark.
+
+ FROZEN ELEMENTS The retained prefix is re-emitted as the same element objects on every
+ render. If cost is driven by React allocating and cloning per child, this
+ removes the allocation while keeping the fibre count identical.
+ PREFIX FOLD The retained prefix is collapsed behind one memo boundary, so an update
+ anywhere below reaches one child instead of hundreds of siblings. This is
+ the closest thing to the proposed fix, measured before it is written.
+ FIBRE-FREE TWIN The retained prefix is re-emitted as IDENTICAL MARKUP through
+ `dangerouslySetInnerHTML`, so the DOM is unchanged and the fibres are gone.
+
+THE FIBRE-FREE TWIN IS NOT OPTIONAL AND IT IS NOT ONE ARM AMONG THREE. In the shipping build the
+number of fibres and the number of DOM nodes move together: every message is both. Every arm that
+removes messages removes both at once, so "cost proportional to fibres" and "cost proportional to
+DOM nodes" predict the identical result on every one of them. They are UNIDENTIFIABLE. The twin
+is the only arm in the whole design that moves one without the other: same nodes, same bytes, same
+pixels, no fibres. Without it, no amount of ablation can tell the two hypotheses apart, and a
+report that names one of them is guessing.
+
+WHY THE HARD REFUSAL. An armpack that does not match the install cannot be used: the arms are
+compiled against a specific dist, and running them against a different one measures the version
+difference. The tempting behaviour is to skip those arms and print the rest, which produces a
+report that looks complete and silently omits the only arm that could have distinguished the two
+live hypotheses. So this module prints ABLATION ARMS NOT AVAILABLE FOR THIS BUILD and exits that
+plane of the experiment. The runtime-knob plane still runs; it is the bundle plane that stops.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Iterable, Mapping, Sequence
+
+from .manifest import Arm, DeclaredDiff, Invariance, PotencyCounter
+
+BANNER = "ABLATION ARMS NOT AVAILABLE FOR THIS BUILD"
+
+
+class ArmpackUnavailable(RuntimeError):
+ """Raised to end the bundle-arm plane. Carries the banner as its message."""
+
+ def __init__(self, reason: str) -> None:
+ super().__init__(f"{BANNER}: {reason}")
+ self.reason = reason
+
+
+ARM_FROZEN_ELEMENTS = Arm(
+ arm_id = "BUNDLE_FROZEN_ELEMENTS",
+ title = "frozen elements for the retained prefix",
+ mechanism = (
+ "the prefix is re-emitted as the same element objects every render, so React allocates "
+ "nothing per child while the fibre count and the DOM stay identical"
+ ),
+ invariance = Invariance.EXACT,
+ potency = PotencyCounter(
+ name = "frozen_element_reuses",
+ min_delta = 1,
+ direction = "increase",
+ description = "element identity was reused for a prefix child at least once",
+ ),
+ implies_fix = (
+ "if this removes the slope, the cost is per-child ALLOCATION rather than the walk itself, "
+ "and the fix is to stop producing new element objects for unchanged prefix children"
+ ),
+ kind = "bundle",
+ requires_armpack = True,
+)
+
+ARM_PREFIX_FOLD = Arm(
+ arm_id = "BUNDLE_PREFIX_FOLD",
+ title = "fold the retained prefix behind one memo boundary",
+ mechanism = (
+ "the prefix becomes a single memoised child, so an update below it reaches one sibling "
+ "instead of every retained message"
+ ),
+ invariance = Invariance.EQUIVALENT,
+ declared_diff = DeclaredDiff(
+ normaliser = "strip_fold_wrapper",
+ keys = ("data-sb-fold-wrapper",),
+ rationale = (
+ "the fold introduces exactly one wrapper element carrying one marker attribute. The "
+ "normaliser removes that element from the canonical serialisation and nothing else; "
+ "if anything other than that attribute differs, the arm is voided, because the extra "
+ "difference is the one nobody reviewed"
+ ),
+ ),
+ potency = PotencyCounter(
+ name = "prefix_fold_children",
+ min_delta = 1,
+ direction = "increase",
+ description = "the number of prefix children collapsed behind the boundary",
+ ),
+ implies_fix = (
+ "if this removes the slope, the fix is structural: give the retained prefix its own memo "
+ "boundary, or virtualise the list so the prefix is not a sibling sequence at all"
+ ),
+ kind = "bundle",
+ requires_armpack = True,
+)
+
+ARM_FIBRE_FREE_TWIN = Arm(
+ arm_id = "BUNDLE_FIBRE_FREE_TWIN",
+ title = "fibre-free twin: identical markup, no fibres",
+ mechanism = (
+ "the retained prefix is re-emitted as identical markup via dangerouslySetInnerHTML. The "
+ "DOM nodes, bytes and pixels are the same; the fibres behind them are gone"
+ ),
+ invariance = Invariance.EXACT,
+ potency = PotencyCounter(
+ name = "twin_prefix_fibres",
+ min_delta = 1,
+ direction = "decrease",
+ description = (
+ "fibres behind the prefix must FALL while the DOM node count stays put; that "
+ "combination is the whole point of the arm"
+ ),
+ ),
+ implies_fix = (
+ "this arm does not imply a fix, it decides which of two fixes to look for. If the cost "
+ "goes with the fibres it is a React structure problem; if it stays with the DOM it is a "
+ "style, layout and paint problem, and no amount of memoisation will touch it"
+ ),
+ kind = "bundle",
+ requires_armpack = True,
+ notes = (
+ "the only arm that breaks fibre/DOM collinearity. Without it, cost proportional to fibres "
+ "and cost proportional to DOM are unidentifiable and the report cannot name either"
+ ),
+)
+
+BUNDLE_ARMS: tuple[Arm, ...] = (
+ ARM_FROZEN_ELEMENTS,
+ ARM_PREFIX_FOLD,
+ ARM_FIBRE_FREE_TWIN,
+)
+
+
+@dataclass(frozen = True)
+class ArmpackManifest:
+ """What an armpack claims about itself. Read from `armpack.json` inside the pack."""
+
+ armpack_version: str
+ built_from_sha: str
+ target_dist_digest: str
+ arms: Mapping[str, str] # arm_id -> relative dist directory inside the pack
+ root: Path
+
+ @classmethod
+ def load(cls, path: str | Path) -> "ArmpackManifest":
+ manifest_path = Path(path)
+ blob = json.loads(manifest_path.read_text(encoding = "utf-8"))
+ missing = [
+ key
+ for key in ("armpack_version", "built_from_sha", "target_dist_digest", "arms")
+ if key not in blob
+ ]
+ if missing:
+ raise ArmpackUnavailable(
+ f"{manifest_path} is missing required keys {missing}. An armpack that cannot say "
+ "which dist it was built against cannot be matched to one"
+ )
+ return cls(
+ armpack_version = str(blob["armpack_version"]),
+ built_from_sha = str(blob["built_from_sha"]),
+ target_dist_digest = str(blob["target_dist_digest"]),
+ arms = dict(blob["arms"]),
+ root = manifest_path.parent,
+ )
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "armpack_version": self.armpack_version,
+ "built_from_sha": self.built_from_sha,
+ "target_dist_digest": self.target_dist_digest,
+ "arms": dict(self.arms),
+ "root": str(self.root),
+ }
+
+
+@dataclass
+class ArmpackResolution:
+ """The outcome of looking for an armpack that matches this install."""
+
+ available: bool
+ reason: str
+ manifest: ArmpackManifest | None = None
+ arms: list[Arm] = field(default_factory = list)
+ searched: list[str] = field(default_factory = list)
+
+ def require(self) -> ArmpackManifest:
+ if not self.available or self.manifest is None:
+ raise ArmpackUnavailable(self.reason)
+ return self.manifest
+
+ def render(self) -> str:
+ if self.available and self.manifest is not None:
+ return (
+ f"armpack {self.manifest.armpack_version} matched "
+ f"(dist {self.manifest.target_dist_digest[:12]}, built from "
+ f"{self.manifest.built_from_sha[:12]}); bundle arms: "
+ + ", ".join(sorted(self.manifest.arms))
+ )
+ lines = [BANNER, f" {self.reason}"]
+ if self.searched:
+ lines.append(" searched:")
+ lines.extend(f" {path}" for path in self.searched)
+ lines.append(
+ " The bundle-arm plane of this experiment does not run. In particular the "
+ "fibre-free twin does not run, so this report cannot distinguish cost proportional "
+ "to fibres from cost proportional to DOM. The runtime-knob plane is unaffected."
+ )
+ return "\n".join(lines)
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "available": bool(self.available),
+ "reason": self.reason,
+ "banner": None if self.available else BANNER,
+ "manifest": self.manifest.to_json() if self.manifest else None,
+ "arms": [arm.arm_id for arm in self.arms],
+ "searched": list(self.searched),
+ }
+
+
+def discover_armpack(
+ search_paths: Iterable[str | Path],
+ install_dist_digest: str,
+ *,
+ required_arms: Sequence[Arm] = BUNDLE_ARMS,
+) -> ArmpackResolution:
+ """Find an armpack whose target digest matches this install, or refuse.
+
+ Matching is on the DIST DIGEST, not on a version string. Two installs claiming the same
+ Studio version can ship different dists (a local build, a patched install, a different
+ Node version producing a different chunk split), and an armpack built against one of them
+ measures the build difference when run against the other.
+ """
+
+ searched: list[str] = []
+ candidates: list[ArmpackManifest] = []
+ for base in search_paths:
+ base_path = Path(base)
+ searched.append(str(base_path))
+ manifest_path = (
+ base_path if base_path.name == "armpack.json" else base_path / "armpack.json"
+ )
+ if not manifest_path.is_file():
+ continue
+ try:
+ candidates.append(ArmpackManifest.load(manifest_path))
+ except ArmpackUnavailable:
+ continue
+ except (OSError, json.JSONDecodeError):
+ continue
+
+ if not candidates:
+ return ArmpackResolution(
+ available = False,
+ reason = "no armpack.json was found on any search path",
+ searched = searched,
+ )
+
+ matched = [m for m in candidates if m.target_dist_digest == install_dist_digest]
+ if not matched:
+ found = ", ".join(sorted({m.target_dist_digest[:12] for m in candidates}))
+ return ArmpackResolution(
+ available = False,
+ reason = (
+ f"no armpack targets this install's dist digest {install_dist_digest[:12]}; "
+ f"found packs for {found}. Running a mismatched pack would measure the build "
+ "difference and report it as a mechanism"
+ ),
+ searched = searched,
+ )
+
+ manifest = matched[0]
+ missing = [arm.arm_id for arm in required_arms if arm.arm_id not in manifest.arms]
+ if missing:
+ return ArmpackResolution(
+ available = False,
+ reason = (
+ f"the matching armpack is missing required arms {missing}. A partial pack is "
+ "refused rather than run: the arm most likely to be missing is the fibre-free "
+ "twin, and without it the remaining arms cannot identify what they appear to"
+ ),
+ manifest = manifest,
+ searched = searched,
+ )
+
+ absent_dirs = [
+ arm_id for arm_id, rel in manifest.arms.items() if not (manifest.root / rel).is_dir()
+ ]
+ if absent_dirs:
+ return ArmpackResolution(
+ available = False,
+ reason = (
+ f"the armpack manifest lists arms whose dist directories are absent: "
+ f"{sorted(absent_dirs)}"
+ ),
+ manifest = manifest,
+ searched = searched,
+ )
+
+ return ArmpackResolution(
+ available = True,
+ reason = "armpack matched this install",
+ manifest = manifest,
+ arms = list(required_arms),
+ searched = searched,
+ )
diff --git a/tests/studio/studiobench/arms/calibration.py b/tests/studio/studiobench/arms/calibration.py
new file mode 100644
index 00000000000..56efe748037
--- /dev/null
+++ b/tests/studio/studiobench/arms/calibration.py
@@ -0,0 +1,415 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""NULL and SPIKE: the two arms that decide whether any other arm in the batch may be quoted.
+
+An ablation harness has two failure modes that look exactly like results.
+
+ IDENTICAL WHERE IT SHOULD DIFFER. Every arm reads the same. That is reported as "no mechanism
+ dominates", when what actually happened is that the instrument cannot resolve anything at
+ this magnitude. The SPIKE arm settles it: a known d milliseconds of work is injected, and if
+ the instrument cannot see d, it could not have seen the mechanism either.
+
+ DIFFERENT WHERE IT SHOULD NOT. Two identical configurations read 12% apart, and every arm in
+ the batch inherits that 12% as apparent signal. The NULL arm settles it: the same build is
+ run twice under two different arm ids, and whatever spread that produces is the noise floor
+ for this batch on this machine.
+
+BOTH ARE NON-DROPPABLE, IN EVERY BATCH. Not once at the start of the session, not on the tester's
+machine last week. In every batch, because the thing they measure -- the machine's current
+ability to resolve a difference -- changes with thermal state, with background load, and with
+which browser build got installed this morning.
+
+THE RULE: one arm must read the SAME and one arm must read DIFFERENT, or nothing in that batch is
+quotable. Not "quotable with a caveat". A batch where the null control drifted and a batch where
+the spike went unseen are both batches in which the numbers are unrelated to the app.
+
+WHAT GETS PRINTED. The RECOVERY FRACTION (observed delta divided by the milliseconds actually
+burned, measured inside the page rather than assumed from the requested d) and the DETECTION
+FLOOR (the smallest injected cost this batch could actually see). A recovery fraction of 0.4 says
+the instrument sees 40% of what is there, which means every ablation number in the batch is an
+underestimate by a factor the reader can now apply. That is a far more useful thing to print than
+a confidence interval on a number whose scale is unverified.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Iterable, Mapping, Sequence
+
+from ..scoring.schema import Measure
+from .manifest import Arm, ArmOutcome, ArmStatus, Invariance, PotencyCounter
+
+#: The spike sizes every batch runs. 0.1 ms is below any plausible per-update mechanism and is
+#: expected to be INVISIBLE; it is included precisely so the detection floor has something to sit
+#: on. 2.0 ms is comfortably above, and must be seen or the instrument is broken.
+SPIKE_SIZES_MS: tuple[float, ...] = (0.1, 0.5, 2.0)
+
+#: A spike is considered recovered when the observed delta is this close to the burned cost.
+#: Wide on purpose: the point is "the instrument sees roughly the right amount", not calibration
+#: to three digits, and a tight band would fail on a machine that is merely noisy.
+RECOVERY_MIN = 0.5
+RECOVERY_MAX = 2.0
+
+
+SPIKE_INIT_JS = """
+// SPDX-License-Identifier: AGPL-3.0-only
+// Injected calibration spike. Burns a known amount of main-thread time per DOM update batch, so
+// the harness can check that it can see a cost it put there itself.
+//
+// The burn is a BUSY WAIT, not a sleep and not a setTimeout: the mechanisms under test occupy
+// the main thread, and a calibration that yields would be recovered by a different path through
+// the scheduler than the thing it is calibrating. `performance.now()` is read in a tight loop
+// and the ACTUAL elapsed time is accumulated, so the recovery fraction is computed against what
+// was really burned rather than against what was requested. On a machine under load those two
+// differ by more than the spike itself.
+(() => {
+ if (window.__sbSpike) { return; }
+ const requested = %(spike_ms)f;
+ const S = {
+ requestedMs: requested,
+ invocations: 0,
+ burnedMs: 0,
+ maxBurnMs: 0,
+ installed: false,
+ reason: "",
+ };
+ window.__sbSpike = S;
+ const burn = () => {
+ const started = performance.now();
+ // A tight read loop. Anything cheaper (a counter, a sum) gets optimised into nothing by the
+ // JIT and burns no time at all, which reads as an instrument that cannot see the spike.
+ while (performance.now() - started < requested) { /* spin */ }
+ const actual = performance.now() - started;
+ S.invocations += 1;
+ S.burnedMs += actual;
+ if (actual > S.maxBurnMs) { S.maxBurnMs = actual; }
+ };
+ const attach = () => {
+ const viewport = document.querySelector(".aui-thread-viewport.aui-stream-viewport");
+ if (!viewport) { return false; }
+ try {
+ const observer = new MutationObserver(burn);
+ observer.observe(viewport, { childList: true, subtree: true, characterData: true });
+ S.installed = true;
+ S.observer = observer;
+ return true;
+ } catch (e) {
+ S.reason = "MutationObserver refused: " + e;
+ return false;
+ }
+ };
+ const poll = setInterval(() => {
+ if (attach()) { clearInterval(poll); }
+ }, 50);
+ S.stop = () => {
+ clearInterval(poll);
+ if (S.observer) { S.observer.disconnect(); }
+ };
+})();
+"""
+
+
+def spike_init_script(spike_ms: float) -> str:
+ """Init script that burns `spike_ms` of main-thread time per DOM update batch."""
+
+ return SPIKE_INIT_JS % {"spike_ms": float(spike_ms)}
+
+
+def null_arm(arm_id: str = "NULL", *, reference_id: str = "shipping") -> Arm:
+ """A byte-identical rebuild under a different arm id. It must read EQUAL.
+
+ Nothing about the build changes. The arm exists so that the harness measures the same thing
+ twice under two labels and has to admit how far apart the two answers came out. Its potency
+ counter is deliberately trivial (the run happened at all), because there is no treatment to
+ detect: a NULL arm that "did not fire" is a NULL arm that did not run, which is caught by the
+ session count rather than by a knob.
+ """
+
+ return Arm(
+ arm_id = arm_id,
+ title = f"NULL calibration (byte-identical rebuild of {reference_id})",
+ mechanism = "none: the same build, the same config, a different arm id",
+ invariance = Invariance.EXACT,
+ potency = PotencyCounter(
+ name = "windows_measured",
+ min_delta = 1,
+ direction = "increase",
+ description = "the cell ran; there is no treatment to detect",
+ ),
+ implies_fix = (
+ "nothing. If this arm reads different from its reference, the batch is measuring the "
+ "machine and not the build"
+ ),
+ kind = "calibration",
+ notes = (
+ "non-droppable. A batch without a NULL arm has no measured noise floor, and every "
+ "difference in it is being compared against a number nobody checked"
+ ),
+ )
+
+
+def spike_arm(spike_ms: float) -> Arm:
+ """A known d ms of main-thread work per update. It must read +d."""
+
+ return Arm(
+ arm_id = f"SPIKE{spike_ms:g}",
+ title = f"SPIKE calibration ({spike_ms:g} ms burned per DOM update batch)",
+ mechanism = f"an injected busy wait of {spike_ms:g} ms per update batch",
+ invariance = Invariance.EXACT,
+ potency = PotencyCounter(
+ name = "spike_invocations",
+ min_delta = 1,
+ direction = "increase",
+ description = "the spike observer fired at least once",
+ ),
+ implies_fix = (
+ "nothing. This arm measures the instrument: if a known cost cannot be recovered, no "
+ "unknown cost in this batch can be either"
+ ),
+ kind = "calibration",
+ init_script = spike_init_script(spike_ms),
+ notes = (
+ "non-droppable. The 0.1 ms spike is expected to be invisible and is what the "
+ "detection floor rests on; the 2.0 ms spike must be seen"
+ ),
+ )
+
+
+CALIBRATION_ARM_IDS: tuple[str, ...] = ("NULL",) + tuple(f"SPIKE{d:g}" for d in SPIKE_SIZES_MS)
+
+
+def calibration_arms() -> list[Arm]:
+ return [null_arm()] + [spike_arm(d) for d in SPIKE_SIZES_MS]
+
+
+class CalibrationMissing(AssertionError):
+ """Raised when a batch plan tries to run without its calibration arms."""
+
+
+def assert_batch_includes_calibration(planned_arm_ids: Iterable[str]) -> None:
+ """Calibration arms are non-droppable. A plan that omits one is refused before it runs."""
+
+ planned = set(planned_arm_ids)
+ missing = [arm_id for arm_id in CALIBRATION_ARM_IDS if arm_id not in planned]
+ if missing:
+ raise CalibrationMissing(
+ "this batch omits non-droppable calibration arms: "
+ + ", ".join(missing)
+ + ". One arm must read the same and one must read different, or nothing in the batch "
+ "is quotable, and that cannot be established after the fact"
+ )
+
+
+@dataclass
+class SpikeRecovery:
+ """One spike arm's result: what was burned, what was seen, and the ratio."""
+
+ spike_ms: float
+ burned_ms_per_update: Measure
+ observed_delta: Measure
+ recovery_fraction: float | None
+ recovered: bool
+ note: str
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "spike_ms": float(self.spike_ms),
+ "burned_ms_per_update": self.burned_ms_per_update.to_json(),
+ "observed_delta": self.observed_delta.to_json(),
+ "recovery_fraction": self.recovery_fraction,
+ "recovered": bool(self.recovered),
+ "note": self.note,
+ }
+
+
+@dataclass
+class CalibrationVerdict:
+ """Whether anything in this batch may be quoted, and the two numbers that decide it."""
+
+ quotable: bool
+ reason: str
+ noise_floor_ms: Measure
+ detection_floor_ms: Measure
+ null_deltas: list[Measure] = field(default_factory = list)
+ spikes: list[SpikeRecovery] = field(default_factory = list)
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "quotable": bool(self.quotable),
+ "reason": self.reason,
+ "noise_floor_ms": self.noise_floor_ms.to_json(),
+ "detection_floor_ms": self.detection_floor_ms.to_json(),
+ "null_deltas": [m.to_json() for m in self.null_deltas],
+ "spikes": [s.to_json() for s in self.spikes],
+ }
+
+ def render(self) -> str:
+ lines = ["CALIBRATION (non-droppable, every batch)"]
+ lines.append(f" noise floor {self.noise_floor_ms.display()} (NULL arms)")
+ lines.append(f" detection floor {self.detection_floor_ms.display()} (SPIKE arms)")
+ for null_delta in self.null_deltas:
+ lines.append(f" NULL delta {null_delta.display()}")
+ for spike in self.spikes:
+ fraction = (
+ f"{spike.recovery_fraction:.2f}" if spike.recovery_fraction is not None else "n/a"
+ )
+ lines.append(
+ f" SPIKE {spike.spike_ms:>4g} ms burned {spike.burned_ms_per_update.display()}"
+ f", saw {spike.observed_delta.display()}, recovery {fraction}"
+ f" [{'recovered' if spike.recovered else 'not recovered'}]"
+ )
+ lines.append("")
+ lines.append(
+ f" VERDICT: {'quotable' if self.quotable else 'NOT QUOTABLE'} -- {self.reason}"
+ )
+ return "\n".join(lines)
+
+
+def evaluate_batch(
+ *, null_deltas: Sequence[Measure], spike_observations: Sequence[Mapping[str, Any]]
+) -> CalibrationVerdict:
+ """Decide whether this batch may be quoted at all.
+
+ `null_deltas` are the differences between each NULL arm and its reference, in ms per update.
+ `spike_observations` is one mapping per spike arm with keys `spike_ms`, `burned_ms_per_update`
+ (a Measure, read from inside the page) and `observed_delta` (a Measure).
+
+ The noise floor is the largest absolute NULL delta. The detection floor is the smallest spike
+ that was RECOVERED, where recovered means the observed delta both cleared the noise floor and
+ landed within a factor of two of what was actually burned. A batch where no spike was
+ recovered has no detection floor and is not quotable: the instrument is blind at every
+ magnitude tested, and an arm reading "no difference" in that batch is not evidence.
+ """
+
+ usable_nulls = [m for m in null_deltas if m.has_reading]
+ if not usable_nulls:
+ return CalibrationVerdict(
+ quotable = False,
+ reason = (
+ "no NULL arm produced a reading, so this batch has no measured noise floor and "
+ "every difference in it is being compared against nothing"
+ ),
+ noise_floor_ms = Measure.failed("ms/update", "no NULL arm produced a reading"),
+ detection_floor_ms = Measure.failed("ms/update", "not evaluated without a noise floor"),
+ null_deltas = list(null_deltas),
+ )
+
+ noise_floor_value = max(abs(float(m.value)) for m in usable_nulls)
+ noise_floor = Measure.read(noise_floor_value, "ms/update")
+
+ recoveries: list[SpikeRecovery] = []
+ for observation in spike_observations:
+ spike_ms = float(observation["spike_ms"])
+ burned: Measure = observation["burned_ms_per_update"]
+ observed: Measure = observation["observed_delta"]
+ if not (burned.has_reading and observed.has_reading) or float(burned.value) <= 0:
+ recoveries.append(
+ SpikeRecovery(
+ spike_ms = spike_ms,
+ burned_ms_per_update = burned,
+ observed_delta = observed,
+ recovery_fraction = None,
+ recovered = False,
+ note = (
+ "no usable reading. A spike that did not burn is a spike that did not "
+ "run, which says nothing about the instrument"
+ ),
+ )
+ )
+ continue
+ fraction = float(observed.value) / float(burned.value)
+ clears_noise = abs(float(observed.value)) > noise_floor_value
+ in_band = RECOVERY_MIN <= fraction <= RECOVERY_MAX
+ recovered = clears_noise and in_band
+ if recovered:
+ note = "recovered: the instrument saw what was burned, within a factor of two"
+ elif not clears_noise:
+ note = (
+ "below the noise floor of this batch. Expected for the smallest spike; that is "
+ "what the detection floor is made of"
+ )
+ else:
+ note = (
+ f"seen, but the recovery fraction is {fraction:.2f}, outside "
+ f"[{RECOVERY_MIN}, {RECOVERY_MAX}]. The instrument is reading a different "
+ "magnitude than was burned, so its scale is not trustworthy here"
+ )
+ recoveries.append(
+ SpikeRecovery(
+ spike_ms = spike_ms,
+ burned_ms_per_update = burned,
+ observed_delta = observed,
+ recovery_fraction = fraction,
+ recovered = recovered,
+ note = note,
+ )
+ )
+
+ recovered = [r for r in recoveries if r.recovered]
+ if not recovered:
+ return CalibrationVerdict(
+ quotable = False,
+ reason = (
+ "no SPIKE arm was recovered. The instrument could not see a cost it injected "
+ "itself at any magnitude tested, so an arm reading 'no difference' in this batch "
+ "is not evidence about the app"
+ ),
+ noise_floor_ms = noise_floor,
+ detection_floor_ms = Measure.failed(
+ "ms/update",
+ f"no spike up to {max(SPIKE_SIZES_MS):g} ms was recovered",
+ ),
+ null_deltas = list(null_deltas),
+ spikes = recoveries,
+ )
+
+ detection_floor_value = min(r.spike_ms for r in recovered)
+ detection_floor = Measure.read(detection_floor_value, "ms/update")
+
+ # The other half of the rule: one arm must read the SAME. A NULL arm whose delta exceeds the
+ # smallest thing the batch can detect is not reading the same.
+ worst_null = max(abs(float(m.value)) for m in usable_nulls)
+ if worst_null >= detection_floor_value:
+ return CalibrationVerdict(
+ quotable = False,
+ reason = (
+ f"the NULL arm moved by {worst_null:.3f} ms/update, which is at or above the "
+ f"detection floor of {detection_floor_value:g} ms/update. Two identical builds "
+ "read as different, so a difference between two different builds means nothing "
+ "in this batch"
+ ),
+ noise_floor_ms = noise_floor,
+ detection_floor_ms = detection_floor,
+ null_deltas = list(null_deltas),
+ spikes = recoveries,
+ )
+
+ return CalibrationVerdict(
+ quotable = True,
+ reason = (
+ f"the NULL arm read equal to within {worst_null:.3f} ms/update and the "
+ f"{detection_floor_value:g} ms spike was recovered. One arm read the same and one "
+ "read different, so differences in this batch are differences"
+ ),
+ noise_floor_ms = noise_floor,
+ detection_floor_ms = detection_floor,
+ null_deltas = list(null_deltas),
+ spikes = recoveries,
+ )
+
+
+def null_delta_from_outcomes(reference: ArmOutcome, null_outcome: ArmOutcome) -> Measure:
+ """The NULL arm's difference from its reference, or an explicit non-reading."""
+
+ if null_outcome.status is ArmStatus.VOIDED:
+ return Measure.failed("ms/update", f"NULL arm voided: {null_outcome.reason}")
+ if not (reference.cost.has_reading and null_outcome.cost.has_reading):
+ return Measure.failed(
+ "ms/update",
+ "the NULL arm or its reference produced no reading",
+ )
+ return Measure.read(
+ float(null_outcome.cost.value) - float(reference.cost.value),
+ reference.cost.unit,
+ )
diff --git a/tests/studio/studiobench/arms/dose.py b/tests/studio/studiobench/arms/dose.py
new file mode 100644
index 00000000000..892a3edf128
--- /dev/null
+++ b/tests/studio/studiobench/arms/dose.py
@@ -0,0 +1,285 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Dose-response: the only design in this file set that makes a NULL result informative.
+
+An on/off arm that reads "no difference" is almost worthless. It is consistent with the mechanism
+being absent, with the arm not firing, with the instrument being blind, and with the mechanism
+being real but smaller than the noise. Those four are not distinguishable from one number.
+
+A DOSE-RESPONSE is different. The same content is split across 4, 40, 400 and 4,000 memoised
+siblings. Content is held FIXED, so the amount of text laid out, highlighted and painted does not
+change; the only thing that changes is how many siblings React has to walk. If the cost is
+O(children) -- one cloned work-in-progress fibre per sibling per render, which is what
+`cloneChildFibers` does when `childLanes` is set and `bailoutOnAlreadyFinishedWork` cannot return
+null -- then the cost must be a STRAIGHT LINE THROUGH THE ORIGIN in the number of siblings.
+
+That makes both outcomes informative:
+
+ * a straight line through the origin, with a slope well above the minimum detectable slope, is
+ a positive identification of an O(children) term, and the slope is its per-child cost;
+ * a FLAT line is a real negative, and it comes with a number: "any O(children) term is below
+ X microseconds per child", where X is set by the detection floor and the largest dose. An
+ on/off arm can never produce that sentence.
+
+WHAT MAKES IT FAIL. A large intercept with a flat slope means the cost is there but is not
+proportional to children, so it belongs to some other mechanism. A curve (better fit with a
+quadratic than a line) means something superlinear, which at these sizes usually means the
+allocator or a cache boundary rather than the walk. Both are reported rather than forced into a
+line.
+
+MEMOISED IS LOAD-BEARING. The siblings must be `memo`-wrapped and not re-rendering, because the
+claim under test is that React reaches a child it does not render. If the children re-render, the
+slope measures rendering, which nobody doubts.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Mapping, Sequence
+
+from ..scoring.schema import Measure
+
+#: The declared doses. Four points spanning three orders of magnitude, because a two-point
+#: "line" cannot be distinguished from a step and a three-point one cannot show curvature.
+DOSES: tuple[int, ...] = (4, 40, 400, 4000)
+
+#: A fit this far from the through-origin model is called nonlinear rather than reported as a
+#: slope. Loose, because the question is "is this O(children)", not "what is the exact constant".
+MIN_R2_FOR_LINE = 0.90
+
+#: An intercept larger than this fraction of the largest-dose cost means most of the cost is not
+#: proportional to children, whatever the slope says.
+MAX_INTERCEPT_FRACTION = 0.35
+
+
+@dataclass
+class DosePoint:
+ """One dose and its measured cost, at fixed content."""
+
+ dose: int
+ cost: Measure
+ content_chars: int
+ memoised: bool = True
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "dose": int(self.dose),
+ "cost": self.cost.to_json(),
+ "content_chars": int(self.content_chars),
+ "memoised": bool(self.memoised),
+ }
+
+
+@dataclass
+class DoseFit:
+ """The two fits, the minimum detectable slope, and the verdict."""
+
+ slope_through_origin: float | None
+ r2_through_origin: float | None
+ slope_free: float | None
+ intercept_free: float | None
+ r2_free: float | None
+ min_detectable_slope: Measure
+ verdict: str
+ note: str
+ points: list[DosePoint] = field(default_factory = list)
+ content_varied: bool = False
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "slope_through_origin": self.slope_through_origin,
+ "r2_through_origin": self.r2_through_origin,
+ "slope_free": self.slope_free,
+ "intercept_free": self.intercept_free,
+ "r2_free": self.r2_free,
+ "min_detectable_slope": self.min_detectable_slope.to_json(),
+ "verdict": self.verdict,
+ "note": self.note,
+ "content_varied": bool(self.content_varied),
+ "points": [p.to_json() for p in self.points],
+ }
+
+ def render(self) -> str:
+ lines = ["DOSE-RESPONSE (memoised siblings at fixed content)"]
+ for point in self.points:
+ lines.append(
+ f" {point.dose:>6,} siblings {point.cost.display():>26} "
+ f"{point.content_chars:,} chars"
+ )
+ lines.append("")
+ if self.slope_through_origin is not None:
+ lines.append(
+ f" through-origin slope {self.slope_through_origin * 1000:.4f} us per child "
+ f"(R2 {self.r2_through_origin:.4f})"
+ )
+ if self.slope_free is not None:
+ lines.append(
+ f" free fit slope {self.slope_free * 1000:.4f} us per child, "
+ f"intercept {self.intercept_free:.4f} ms (R2 {self.r2_free:.4f})"
+ )
+ lines.append(f" minimum detectable slope {self.min_detectable_slope.display()}")
+ lines.append(f" VERDICT: {self.verdict} -- {self.note}")
+ return "\n".join(lines)
+
+
+def _r2(xs: Sequence[float], ys: Sequence[float], predict) -> float | None:
+ mean = sum(ys) / len(ys)
+ ss_tot = sum((y - mean) ** 2 for y in ys)
+ ss_res = sum((y - predict(x)) ** 2 for x, y in zip(xs, ys))
+ if ss_tot <= 0:
+ # Every reading identical. R2 is undefined, and reporting 1.0 (a perfect fit) for a flat
+ # line is exactly the wrong way round: this is the case with the least information.
+ return None
+ return 1.0 - (ss_res / ss_tot)
+
+
+def fit_dose_response(
+ points: Sequence[DosePoint], *, detection_floor_ms: float | None = None
+) -> DoseFit:
+ """Fit both models and decide what the shape says.
+
+ `detection_floor_ms` sets the minimum detectable slope: below `floor / max_dose` per child,
+ no arrangement of these doses could have seen the term, and a flat result is UNDERPOWERED
+ rather than a negative. Printing a null without that number is how a real O(children) term
+ gets declared absent.
+ """
+
+ usable = [p for p in points if p.cost.has_reading]
+ contents = {p.content_chars for p in points}
+ content_varied = len(contents) > 1
+
+ max_dose = max((p.dose for p in points), default = 0)
+ if detection_floor_ms is not None and max_dose > 0:
+ min_slope = Measure.read(detection_floor_ms / max_dose, "ms/child")
+ else:
+ min_slope = Measure.not_attempted(
+ "ms/child", "no detection floor was supplied, so a null result cannot be bounded"
+ )
+
+ if len(usable) < 3:
+ return DoseFit(
+ slope_through_origin = None,
+ r2_through_origin = None,
+ slope_free = None,
+ intercept_free = None,
+ r2_free = None,
+ min_detectable_slope = min_slope,
+ verdict = "NO FIT",
+ note = (
+ f"only {len(usable)} of {len(points)} doses produced a reading; three points is "
+ "the minimum that can distinguish a line from a step"
+ ),
+ points = list(points),
+ content_varied = content_varied,
+ )
+
+ if content_varied:
+ return DoseFit(
+ slope_through_origin = None,
+ r2_through_origin = None,
+ slope_free = None,
+ intercept_free = None,
+ r2_free = None,
+ min_detectable_slope = min_slope,
+ verdict = "INVALID",
+ note = (
+ "content length is not fixed across the doses "
+ f"({sorted(contents)}), so a slope in siblings is confounded with a slope in "
+ "content and the whole design is void"
+ ),
+ points = list(points),
+ content_varied = True,
+ )
+
+ xs = [float(p.dose) for p in usable]
+ ys = [float(p.cost.value) for p in usable]
+
+ sum_xy = sum(x * y for x, y in zip(xs, ys))
+ sum_xx = sum(x * x for x in xs)
+ slope_origin = sum_xy / sum_xx if sum_xx > 0 else None
+ r2_origin = _r2(xs, ys, lambda x: slope_origin * x) if slope_origin is not None else None
+
+ n = len(xs)
+ mean_x = sum(xs) / n
+ mean_y = sum(ys) / n
+ denominator = sum((x - mean_x) ** 2 for x in xs)
+ if denominator > 0:
+ slope_free = sum((x - mean_x) * (y - mean_y) for x, y in zip(xs, ys)) / denominator
+ intercept_free = mean_y - slope_free * mean_x
+ r2_free = _r2(xs, ys, lambda x: slope_free * x + intercept_free)
+ else:
+ slope_free = intercept_free = r2_free = None
+
+ largest_cost = max(ys)
+ floor = detection_floor_ms
+ # Detectability is judged on the FREE slope, not the through-origin one. A perfectly flat
+ # series still has a large through-origin slope, because forcing the line through zero makes
+ # the constant offset look like a per-child cost; judging detectability on that number turns
+ # every null result into a positive identification.
+ detectable = (
+ slope_free is not None
+ and floor is not None
+ and max_dose > 0
+ and abs(slope_free) > (floor / max_dose)
+ )
+
+ if slope_origin is None:
+ verdict, note = "NO FIT", "the doses carry no variation to fit"
+ elif not detectable and floor is not None:
+ verdict = "UNDERPOWERED NULL"
+ note = (
+ "the fitted slope is below the minimum this batch could detect. Any O(children) term "
+ f"is smaller than {min_slope.display()}, which is a real bound, but this is not "
+ "evidence that the term is absent"
+ )
+ elif not detectable:
+ verdict = "NULL, UNBOUNDED"
+ note = (
+ "the slope is indistinguishable from flat and no detection floor was supplied, so "
+ "the result cannot be turned into a bound. Run the calibration arms"
+ )
+ elif (
+ intercept_free is not None
+ and r2_free is not None
+ and r2_free >= MIN_R2_FOR_LINE
+ and largest_cost > 0
+ and abs(intercept_free) / largest_cost > MAX_INTERCEPT_FRACTION
+ ):
+ # Checked BEFORE the through-origin R2, because a straight line with a big offset fits a
+ # free line perfectly and a through-origin line badly. Reporting that as NONLINEAR would
+ # be exactly backwards: the data is as linear as data gets, it just does not pass through
+ # zero, and the offset is the finding.
+ verdict = "MOSTLY FIXED COST"
+ note = (
+ f"the free fit puts {abs(intercept_free) / largest_cost:.0%} of the largest-dose cost "
+ "in the intercept, at R2 "
+ f"{r2_free:.4f}. Most of what is being measured does not scale with children, "
+ "whatever the slope is"
+ )
+ elif r2_origin is not None and r2_origin < MIN_R2_FOR_LINE:
+ verdict = "NONLINEAR"
+ note = (
+ f"a line through the origin fits at R2 {r2_origin:.3f}, below {MIN_R2_FOR_LINE}. The "
+ "cost changes with sibling count but not proportionally, so it is not the simple "
+ "per-child walk"
+ )
+ else:
+ verdict = "LINEAR THROUGH ORIGIN"
+ note = (
+ f"cost is proportional to sibling count at {slope_origin * 1000:.3f} us per child "
+ f"(R2 {r2_origin:.4f}), which is the signature of a per-child walk at fixed content"
+ )
+
+ return DoseFit(
+ slope_through_origin = slope_origin,
+ r2_through_origin = r2_origin,
+ slope_free = slope_free,
+ intercept_free = intercept_free,
+ r2_free = r2_free,
+ min_detectable_slope = min_slope,
+ verdict = verdict,
+ note = note,
+ points = list(points),
+ content_varied = False,
+ )
diff --git a/tests/studio/studiobench/arms/knobs.js b/tests/studio/studiobench/arms/knobs.js
new file mode 100644
index 00000000000..6d4297dbc35
--- /dev/null
+++ b/tests/studio/studiobench/arms/knobs.js
@@ -0,0 +1,2767 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/*
+ * knobs.js -- runtime ablation knobs for the SHIPPED Unsloth Studio build.
+ *
+ * Injected with Playwright's context.add_init_script BEFORE the app boots, so it can patch
+ * browser APIs the app is about to use. It needs no compiler, no source edit and no rebuild: the
+ * point is that an external tester can run every ablation against the same production bundle the
+ * user gets, and that the ablated run and the control run are the same bytes of application code.
+ *
+ * WHAT AN ARM IS FOR
+ *
+ * Each arm removes one candidate mechanism and nothing else. If removing it makes the thread
+ * cheaper, that mechanism was the cost, and the arm names the fix. The arms:
+ *
+ * A visibility:hidden on completed messages.
+ * Removes paint and raster for the prefix. Keeps layout, keeps the DOM, keeps React.
+ * IF A IS THE WIN: the cost is paint/raster of off-screen content. The fix is to stop
+ * painting the prefix, not to stop building it.
+ *
+ * B content-visibility:auto plus contain-intrinsic-size on completed messages, and the undo
+ * of the index.css override that force-disables content-visibility on code blocks.
+ * Removes style, layout AND paint for anything off screen.
+ * IF B IS THE WIN: the cost is off-screen style plus layout plus paint, and the rule at
+ * studio/frontend/src/index.css:2537 is wrong -- it was kept for a flicker, and the comment
+ * above it asserts containment on message roots "was measured as no help", which is exactly
+ * the claim this arm re-tests. B beating A says the expensive part is not the pixels.
+ *
+ * C display:none on completed messages.
+ * Removes layout geometry and the sibling count as well as everything B removes.
+ * IF C IS THE WIN AND B IS NOT: the cost is layout geometry and the cost of having N
+ * siblings in one flow, not per-element style. That points at the thread container's layout
+ * mode (flex column over N children) rather than at the messages.
+ *
+ * D detach the autoscroll subtree MutationObserver.
+ * use-intent-aware-autoscroll.tsx:502 observes the viewport with subtree+characterData, and
+ * its callback reads el.scrollHeight, which forces synchronous style+layout of the WHOLE
+ * thread on every delivery. During streaming those deliveries arrive per streamed character.
+ * IF D IS THE WIN: the cost is forced synchronous layout inside the autoscroll observer.
+ * The fix is to stop reading scrollHeight per mutation (rAF-coalesce it, or switch to
+ * IntersectionObserver / overflow-anchor), not to touch the messages at all.
+ *
+ * E neutralise the --aui-scroll-stabilizer custom property write.
+ * That same callback writes a custom property on the viewport element. A custom property is
+ * inherited, so writing it on the scroll container invalidates inherited style for the whole
+ * subtree beneath it, which is every message.
+ * IF E IS THE WIN: the cost is inherited custom-property subtree style invalidation. The fix
+ * is to register the property with syntax and inherits:false via CSS.registerProperty, or to
+ * move the write off the ancestor of the thread.
+ *
+ * F freeze React's scheduler while leaving the DOM exactly as it is.
+ * React's browser scheduler drives work through a MessageChannel: port1.onmessage is
+ * performWorkUntilDeadline, and port2.postMessage schedules the next slice. Suppressing the
+ * delivery stops reconciliation, effects and store subscriptions without touching a node.
+ * IF F IS THE WIN: the cost is React subscriptions and reconciliation over the prefix, and
+ * the fix is memoisation / virtualisation / narrower context subscriptions, not CSS.
+ *
+ * G CONTROL. Identical DOM, no knob, thread scrolled so prior turns are actually IN the
+ * viewport. Every other arm removes work that only exists when the prefix is off screen and
+ * cheap; G is the run where the prefix is on screen and expensive. It is the calibration for
+ * "how much does this page cost when nothing is being skipped", and a G that is not slower
+ * than the untouched baseline means the baseline was never skipping anything, which would
+ * invalidate the whole comparison.
+ *
+ * THE TWO FAILURE MODES THIS FILE EXISTS TO PREVENT
+ *
+ * See arms/manifest.py. An ablation lies in exactly two ways and both are silent.
+ *
+ * 1. THE ARM CHANGED THE OUTPUT. The knob also removed some of the work, so the two sides did
+ * not render the same page. The dangerous case is the small invisible difference: an earlier
+ * stub fixture in this codebase produced 552 syntax-highlighted spans where the real page
+ * produces 2,561, and it read as a clean 4x win. It was not fast, it was rendering a fifth
+ * of the content. digest() and counts() exist for that: the canonical serialisation carries
+ * the code-block count and the span count per message, so a highlighting difference is
+ * caught even when every character of text is identical.
+ *
+ * TWO THINGS THE DIGEST CANNOT SEE, stated here because they cannot be stated in it. It
+ * walks `[data-message-id]` roots and serialises their attributes and text plus the count of
+ * code blocks and of spans inside them. It does NOT serialise the attributes of descendants,
+ * so an inline style written on a code block is invisible to it (arm B does exactly that,
+ * which is one reason B is EQUIVALENT and not EXACT). And it does not know about geometry,
+ * so a change that only moves pixels is invisible too. Neither gap is patched by making the
+ * digest bigger; they are declared, because a normaliser nobody wrote down is just a bug.
+ *
+ * Arms A and C therefore go out of their way to mutate NOTHING: they target the completed
+ * prefix with `:nth-child(-n+K)` against the viewport's direct children rather than by
+ * tagging elements, so the raw digest is byte-identical across the arm and EXACT is a claim
+ * they can actually make. When that is impossible they fall back to a marker attribute and
+ * say in the returned reason that they have dropped to EQUIVALENT.
+ *
+ * 2. THE ARM DID NOT FIRE. Selector matched nothing, patch failed to install, run completed,
+ * difference was zero, and "no effect" got written down as evidence against the mechanism.
+ * It is evidence of nothing. So every arm has a potency counter that the arm CAUSES: not
+ * "the stylesheet was appended" but "N elements actually compute to visibility:hidden".
+ * A patch that could not be installed lands in unavailable[] and never in available[], so
+ * UNAVAILABLE can never be misread as "had no effect".
+ *
+ * CASCADE FACTS THIS FILE DEPENDS ON, VERIFIED AGAINST THE SPEC
+ *
+ * The index.css override lives inside `@layer utilities { ... }` (Tailwind v4 emits native
+ * cascade layers). Per CSS Cascading and Inheritance Level 5 and MDN:
+ *
+ * - For IMPORTANT declarations the layer order is REVERSED, and important declarations in ANY
+ * layer beat important declarations outside every layer. So appending an unlayered
+ * `!important` rule, at any specificity, LOSES to the layered `!important` rule it is trying
+ * to undo. The obvious approach silently does nothing, which is failure mode 2.
+ * - Element-attached (inline) declarations are sorted BEFORE layers in the cascade, so an
+ * inline `!important` declaration beats every other author declaration whatever its layer.
+ *
+ * Therefore each CSS arm applies its stylesheet in two copies, one unlayered and one inside
+ * `@layer utilities` so it competes in the same layer as the rule it must beat (same layer, same
+ * importance, higher specificity, later order -> wins), THEN verifies with getComputedStyle, and
+ * only if the verification says the rule did not take effect does it escalate to inline
+ * !important, counting the escalation. The verification is the whole point: the stylesheet is a
+ * hypothesis about the cascade, the computed style is the observation.
+ *
+ * ARMS ARE APPLIED ONCE, OVER THE PREFIX THAT EXISTS AT THAT MOMENT
+ *
+ * apply() runs at the start of a measured window and never again. Messages created during the
+ * window are NOT ablated. That is deliberate and not a limitation:
+ *
+ * - the hypothesis is about the PREFIX (the N completed turns that are off screen), not about
+ * the turn being streamed, so ablating the in-flight message would change the thing under
+ * measurement rather than the thing under test;
+ * - a live MutationObserver re-applying the knob to each new message would add per-mutation
+ * work to the hot path, which is the exact category of cost the experiment is trying to
+ * remove. An ablation that installs its own observer to remove an observer measures itself.
+ *
+ * For the same reason arm B marks only code blocks inside COMPLETED messages: touching the code
+ * block that is still streaming would change how streamdown and shiki finalise it.
+ *
+ * PREBOOT VERSUS RUNTIME
+ *
+ * D, E and F patch APIs the app captures during boot, so they must be installed before the app
+ * runs and they are read from window.__sbArmConfig.preboot, set by an earlier init script. An arm
+ * that is not listed is NOT INSTALLED AT ALL. Installing a patch and leaving it inactive is not
+ * free: the wrapper costs a call frame on every MutationObserver.observe or setProperty in the
+ * process, and a control run carrying that overhead is not a control. So the preboot list decides
+ * per page load, and a run whose config did not arm D reports D as unavailable with a reason,
+ * never as an arm that ran and did nothing.
+ *
+ * D and E are ACTIVE FROM INJECTION when armed; there is no meaningful apply() for them, because
+ * the autoscroll observer is installed once during mount and the suppression has to be in place
+ * before that. apply("D") therefore reports the arm as already active and returns the suppression
+ * count so far. F is different: the port capture is preboot, the freeze is toggled by apply("F").
+ *
+ * ARM F IS DOM_CHANGING. Freezing React stops the stream from rendering, so the frozen run is not
+ * rendering the same page as the control -- it is rendering less of it. Its cost is therefore an
+ * upper bound on what React reconciliation costs and can never be quoted as a point estimate.
+ * manifest.py prints it as `<= x`. This is stated here as well because the arm is the one most
+ * likely to produce a spectacular number that somebody wants to quote.
+ *
+ * COUNTERS: EVENT COUNTERS VERSUS GAUGES
+ *
+ * potency() returns integers only, in two kinds, and the distinction is load-bearing:
+ *
+ * EVENT COUNTERS are monotonic and never decrease for the life of the page:
+ * suppressedViewportObserves, observeCallsTotal, observeCallsPassedThrough,
+ * suppressedStabilizerSets, customPropSets, setPropertyCallsTotal,
+ * suppressedSchedulerCallbacks, schedulerCallbacksDelivered, capturedSchedulerPorts, and the
+ * bookkeeping counters (armsApplied, inlineFallbacks, ...).
+ *
+ * GAUGES are point-in-time measurements of the live DOM, re-measured on every potency() call
+ * unless {live:false} is passed: visibilityHiddenConfirmed, cvAutoMessages, cvAutoCodeBlocks,
+ * contentVisibilityAutoConfirmed, displayNoneConfirmed, controlVisibleMessages,
+ * controlVisiblePriorMessages.
+ *
+ * Gauges are deliberately not monotonic. A stored 0 and a measured 0 are different facts, and
+ * this file exists to keep them different: measuring live means the "before" read is a real
+ * observation of the untouched page rather than a variable that has not been written yet, and it
+ * means arm G is checked against what the page looks like at the END of the window, after the
+ * app's own autoscroll has had every chance to undo the scroll position G set. Re-measuring calls
+ * getComputedStyle over every message root, which forces style recalc, so potency() must be
+ * called OUTSIDE the timed window; pass {live:false} to read the last stored values with no DOM
+ * access at all.
+ *
+ * HASHING
+ *
+ * FNV-1a, 32 bit, hex. NOT CRYPTOGRAPHIC and not a security boundary. It is a change detector
+ * against an adversary that does not exist, and 32 bits is small enough that a collision on a
+ * multi-megabyte canonical form is not impossible, so digest() also returns canonicalLength and
+ * rawLength. Compare the pair, not the hash alone.
+ */
+
+(function () {
+ "use strict";
+
+ if (typeof window === "undefined" || !window) {
+ return;
+ }
+
+ var W = window;
+
+ // Idempotence. add_init_script runs for every document including iframes, and a driver that
+ // reloads the page must not stack patches: a doubly wrapped observe() would double every
+ // count, and a doubly wrapped MessageChannel would make the freeze flag ambiguous.
+ if (W.__sbArmsInstalled) {
+ return;
+ }
+ W.__sbArmsInstalled = true;
+
+ var VERSION = "1.0.0";
+ var CANONICAL_FORMAT_VERSION = 1;
+
+ // Selectors. Every one of these is a verified fact about the shipped build, not a guess.
+ var VIEWPORT_SELECTOR = ".aui-thread-viewport.aui-stream-viewport";
+ var VIEWPORT_CLASS = "aui-stream-viewport";
+ var MESSAGE_SELECTOR = "[data-message-id]";
+ var CODE_BLOCK_SELECTOR = '[data-streamdown="code-block"]';
+ var RUNNING_SELECTOR = '[data-status="running"]';
+ var STABILIZER_PROP = "--aui-scroll-stabilizer";
+ var MARKER_ATTR = "data-sb-arm";
+
+ var ARM_IDS = ["A", "B", "C", "D", "E", "F", "G"];
+ var PREBOOT_ARMS = { D: true, E: true, F: true };
+
+ var MAX_RETAINED_SCHEDULER_EVENTS = 256;
+ var MAX_CAPTURED_CHANNELS = 64;
+ var DEFAULT_MAX_CANONICAL_CHARS = 4000000;
+ var DEFAULT_CONTROL_VISIBLE_TARGET = 3;
+ var MAX_STYLESHEET_DEPTH = 8;
+
+ // ------------------------------------------------------------------------------------
+ // Config
+ //
+ // Read defensively. A missing or malformed __sbArmConfig means no preboot arms, which is the
+ // correct default: no config is not permission to install patches into a control run.
+ // ------------------------------------------------------------------------------------
+
+ var cfg = {};
+ try {
+ if (W.__sbArmConfig && typeof W.__sbArmConfig === "object") {
+ cfg = W.__sbArmConfig;
+ }
+ } catch (e) {
+ cfg = {};
+ }
+
+ var debugOn = false;
+ try {
+ debugOn = cfg.debug === true;
+ } catch (e) {
+ debugOn = false;
+ }
+
+ function debug() {
+ if (!debugOn) {
+ return;
+ }
+ try {
+ var args = ["[sbArms]"];
+ for (var i = 0; i < arguments.length; i++) {
+ args.push(arguments[i]);
+ }
+ if (W.console && typeof W.console.debug === "function") {
+ W.console.debug.apply(W.console, args);
+ }
+ } catch (e) {
+ /* logging must never be the reason a run fails */
+ }
+ }
+
+ var armedPreboot = [];
+ try {
+ var rawPreboot = cfg.preboot;
+ if (rawPreboot && typeof rawPreboot.length === "number") {
+ for (var pi = 0; pi < rawPreboot.length; pi++) {
+ var pid = String(rawPreboot[pi]).toUpperCase();
+ if (PREBOOT_ARMS[pid] === true && armedPreboot.indexOf(pid) === -1) {
+ armedPreboot.push(pid);
+ }
+ }
+ }
+ } catch (e) {
+ armedPreboot = [];
+ }
+
+ var controlVisibleTarget = DEFAULT_CONTROL_VISIBLE_TARGET;
+ try {
+ var rawTarget = cfg.controlVisibleTarget;
+ if (typeof rawTarget === "number" && isFinite(rawTarget) && rawTarget > 0) {
+ controlVisibleTarget = Math.floor(rawTarget);
+ }
+ } catch (e) {
+ controlVisibleTarget = DEFAULT_CONTROL_VISIBLE_TARGET;
+ }
+
+ var redeliverOnUnfreeze = true;
+ try {
+ if (cfg.redeliverOnUnfreeze === false) {
+ redeliverOnUnfreeze = false;
+ }
+ } catch (e) {
+ redeliverOnUnfreeze = true;
+ }
+
+ var doc = null;
+ try {
+ doc = W.document || null;
+ } catch (e) {
+ doc = null;
+ }
+
+ // ------------------------------------------------------------------------------------
+ // State
+ // ------------------------------------------------------------------------------------
+
+ function freshEventCounters() {
+ return {
+ // D
+ observeCallsTotal: 0,
+ observeCallsPassedThrough: 0,
+ suppressedViewportObserves: 0,
+ // E
+ setPropertyCallsTotal: 0,
+ customPropSets: 0,
+ suppressedStabilizerSets: 0,
+ // F
+ capturedSchedulerPorts: 0,
+ schedulerCallbacksDelivered: 0,
+ suppressedSchedulerCallbacks: 0,
+ schedulerCallbacksRedelivered: 0,
+ schedulerResumeKicks: 0,
+ retainedSchedulerEvents: 0,
+ droppedSchedulerEvents: 0,
+ schedulerListenerAdds: 0,
+ schedulerCallbacksWithoutHandler: 0,
+ // bookkeeping
+ armsApplied: 0,
+ armsReverted: 0,
+ styleSheetsInstalled: 0,
+ markedElements: 0,
+ inlineFallbacks: 0,
+ inlinePropsSet: 0,
+ digestsTaken: 0
+ };
+ }
+
+ function freshGauges() {
+ return {
+ visibilityHiddenConfirmed: 0,
+ cvAutoMessages: 0,
+ cvAutoCodeBlocks: 0,
+ contentVisibilityAutoConfirmed: 0,
+ displayNoneConfirmed: 0,
+ controlVisibleMessages: 0,
+ controlVisiblePriorMessages: 0
+ };
+ }
+
+ var counters = freshEventCounters();
+ var gauges = freshGauges();
+
+ var state = {
+ applied: {}, // armId -> {at, affected, reason}
+ frozen: false,
+ markers: [], // {el, prev} for MARKER_ATTR restoration
+ inline: [], // {el, prop, prevValue, prevPriority, hadStyleAttr}
+ sheets: {}, // armId -> <style> element
+ channels: [], // captured MessageChannel records
+ scrollRestore: null, // arm G restoration record
+ originals: {
+ observe: null,
+ observeDescriptor: null,
+ setProperty: null,
+ setPropertyDescriptor: null,
+ MessageChannel: null
+ },
+ installed: { D: false, E: false, F: false }
+ };
+
+ var unavailable = {};
+
+ function markUnavailable(armId, reason) {
+ try {
+ if (!Object.prototype.hasOwnProperty.call(unavailable, armId)) {
+ unavailable[armId] = String(reason);
+ }
+ } catch (e) {
+ /* nothing sensible to do, and throwing here would take the app down */
+ }
+ }
+
+ function nowStamp() {
+ try {
+ return new Date().toISOString();
+ } catch (e) {
+ return null;
+ }
+ }
+
+ function result(applied, reason, affected) {
+ return {
+ applied: !!applied,
+ reason: String(reason || ""),
+ affected: typeof affected === "number" && isFinite(affected) ? Math.floor(affected) : 0
+ };
+ }
+
+ function revertResult(reverted, reason) {
+ return { reverted: !!reverted, reason: String(reason || "") };
+ }
+
+ // ------------------------------------------------------------------------------------
+ // DOM helpers
+ //
+ // All of them tolerate a missing document, a detached node and a selector that matches
+ // nothing, and none of them throw. A query that fails returns an empty array, and the caller
+ // turns that into a reason string rather than into a zero.
+ // ------------------------------------------------------------------------------------
+
+ function toArray(nodeList) {
+ var out = [];
+ try {
+ if (!nodeList) {
+ return out;
+ }
+ for (var i = 0; i < nodeList.length; i++) {
+ out.push(nodeList[i]);
+ }
+ } catch (e) {
+ /* partial list is better than none */
+ }
+ return out;
+ }
+
+ function queryAll(selector, root) {
+ try {
+ var scope = root || doc;
+ if (!scope || typeof scope.querySelectorAll !== "function") {
+ return [];
+ }
+ return toArray(scope.querySelectorAll(selector));
+ } catch (e) {
+ return [];
+ }
+ }
+
+ function queryOne(selector, root) {
+ try {
+ var scope = root || doc;
+ if (!scope || typeof scope.querySelector !== "function") {
+ return null;
+ }
+ return scope.querySelector(selector);
+ } catch (e) {
+ return null;
+ }
+ }
+
+ function messageRoots() {
+ return queryAll(MESSAGE_SELECTOR);
+ }
+
+ function isRunning(el) {
+ // The ONLY DOM signal of an in-flight message is a descendant (or the root itself)
+ // carrying [data-status="running"]; status.type from assistant-ui is one of
+ // running|complete|incomplete|requires-action.
+ try {
+ if (!el) {
+ return false;
+ }
+ if (typeof el.getAttribute === "function" && el.getAttribute("data-status") === "running") {
+ return true;
+ }
+ return queryOne(RUNNING_SELECTOR, el) !== null;
+ } catch (e) {
+ // Unknown status is treated as running, i.e. as NOT ablatable. Erring the other way
+ // would ablate the message being streamed and contaminate the measurement.
+ return true;
+ }
+ }
+
+ // The completed-message filter is done in JS, one querySelector per root, and NOT with a CSS
+ // `:has()` selector. `:has()` is unsupported on older engines and an unsupported compound
+ // selector makes the WHOLE selector list invalid, so the rule would be dropped at parse time,
+ // match nothing, and the arm would report a clean zero difference. That is precisely the
+ // did-not-fire failure this file is built to make impossible, and it is invisible in a
+ // screenshot, in a trace and in the console.
+ function completedMessageRoots() {
+ var roots = messageRoots();
+ var out = [];
+ for (var i = 0; i < roots.length; i++) {
+ if (!isRunning(roots[i])) {
+ out.push(roots[i]);
+ }
+ }
+ return out;
+ }
+
+ function runningMessageRoots() {
+ var roots = messageRoots();
+ var out = [];
+ for (var i = 0; i < roots.length; i++) {
+ if (isRunning(roots[i])) {
+ out.push(roots[i]);
+ }
+ }
+ return out;
+ }
+
+ function codeBlocksIn(root) {
+ return queryAll(CODE_BLOCK_SELECTOR, root);
+ }
+
+ function allCodeBlocks() {
+ return queryAll(CODE_BLOCK_SELECTOR);
+ }
+
+ function viewportEl() {
+ return queryOne(VIEWPORT_SELECTOR);
+ }
+
+ function rectOf(el) {
+ try {
+ if (!el || typeof el.getBoundingClientRect !== "function") {
+ return null;
+ }
+ return el.getBoundingClientRect();
+ } catch (e) {
+ return null;
+ }
+ }
+
+ function rectsIntersect(a, b) {
+ if (!a || !b) {
+ return false;
+ }
+ return a.bottom > b.top && a.top < b.bottom && a.right > b.left && a.left < b.right;
+ }
+
+ function computedValue(el, prop) {
+ try {
+ if (!el || typeof W.getComputedStyle !== "function") {
+ return "";
+ }
+ var cs = W.getComputedStyle(el);
+ if (!cs) {
+ return "";
+ }
+ if (typeof cs.getPropertyValue === "function") {
+ return String(cs.getPropertyValue(prop) || "");
+ }
+ return "";
+ } catch (e) {
+ return "";
+ }
+ }
+
+ function countComputed(els, prop, expected) {
+ var n = 0;
+ for (var i = 0; i < els.length; i++) {
+ var v = computedValue(els[i], prop);
+ if (v.trim() === expected) {
+ n += 1;
+ }
+ }
+ return n;
+ }
+
+ function supportsProp(prop, value) {
+ try {
+ if (W.CSS && typeof W.CSS.supports === "function") {
+ return W.CSS.supports(prop, value) === true;
+ }
+ } catch (e) {
+ /* fall through */
+ }
+ // No CSS.supports means we cannot prove support. Treat as supported and let the computed
+ // check decide: a false "unavailable" would hide an arm that works.
+ return true;
+ }
+
+ // ------------------------------------------------------------------------------------
+ // Markers and inline styles
+ //
+ // Arms A, B and C need a CSS hook on specific elements, and the only way to have a stylesheet
+ // address "these elements and no others" is an attribute the stylesheet can select. One
+ // attribute name is used for all arms, space separated, so [data-sb-arm~="A"] matches. That
+ // attribute IS a change to the DOM, so it shows up in digest().raw. It is meant to: an arm
+ // that mutates attributes is EQUIVALENT, not EXACT, and the Python side declares
+ // `attr:data-sb-arm` (plus `attr:style` when the inline escalation fires) as its allowed diff.
+ // Pretending otherwise by hiding the marker from the raw digest would defeat the check.
+ // ------------------------------------------------------------------------------------
+
+ function markElement(el, armId) {
+ try {
+ if (!el || typeof el.getAttribute !== "function") {
+ return false;
+ }
+ var prev = el.getAttribute(MARKER_ATTR);
+ var tokens = prev ? String(prev).split(/\s+/) : [];
+ var seen = false;
+ var clean = [];
+ for (var i = 0; i < tokens.length; i++) {
+ if (!tokens[i]) {
+ continue;
+ }
+ clean.push(tokens[i]);
+ if (tokens[i] === armId) {
+ seen = true;
+ }
+ }
+ if (!seen) {
+ clean.push(armId);
+ }
+ state.markers.push({ el: el, prev: prev });
+ el.setAttribute(MARKER_ATTR, clean.join(" "));
+ counters.markedElements += 1;
+ return true;
+ } catch (e) {
+ return false;
+ }
+ }
+
+ function markAll(els, armId) {
+ var n = 0;
+ for (var i = 0; i < els.length; i++) {
+ if (markElement(els[i], armId)) {
+ n += 1;
+ }
+ }
+ return n;
+ }
+
+ function unmarkAll() {
+ for (var i = state.markers.length - 1; i >= 0; i--) {
+ var rec = state.markers[i];
+ try {
+ if (rec.prev === null || rec.prev === undefined) {
+ rec.el.removeAttribute(MARKER_ATTR);
+ } else {
+ rec.el.setAttribute(MARKER_ATTR, rec.prev);
+ }
+ } catch (e) {
+ /* best effort: a detached node cannot be restored and does not matter */
+ }
+ }
+ state.markers = [];
+ }
+
+ function setInline(el, prop, value, priority) {
+ try {
+ if (!el || !el.style || typeof el.style.setProperty !== "function") {
+ return false;
+ }
+ var prevValue = "";
+ var prevPriority = "";
+ try {
+ prevValue = el.style.getPropertyValue(prop) || "";
+ prevPriority = el.style.getPropertyPriority(prop) || "";
+ } catch (e) {
+ prevValue = "";
+ prevPriority = "";
+ }
+ var hadStyleAttr = false;
+ try {
+ hadStyleAttr =
+ typeof el.hasAttribute === "function" ? el.hasAttribute("style") : true;
+ } catch (e) {
+ hadStyleAttr = true;
+ }
+ state.inline.push({
+ el: el,
+ prop: prop,
+ prevValue: prevValue,
+ prevPriority: prevPriority,
+ hadStyleAttr: hadStyleAttr
+ });
+ el.style.setProperty(prop, value, priority || "");
+ counters.inlinePropsSet += 1;
+ return true;
+ } catch (e) {
+ return false;
+ }
+ }
+
+ function restoreInline() {
+ for (var i = state.inline.length - 1; i >= 0; i--) {
+ var rec = state.inline[i];
+ try {
+ if (rec.prevValue === "") {
+ rec.el.style.removeProperty(rec.prop);
+ } else {
+ rec.el.style.setProperty(rec.prop, rec.prevValue, rec.prevPriority);
+ }
+ if (!rec.hadStyleAttr) {
+ var left = "";
+ try {
+ left = String(rec.el.getAttribute("style") || "").trim();
+ } catch (e2) {
+ left = "x";
+ }
+ if (left === "") {
+ // Leaving style="" behind would be a permanent, invisible difference in
+ // every future digest of this page.
+ rec.el.removeAttribute("style");
+ }
+ }
+ } catch (e) {
+ /* best effort */
+ }
+ }
+ state.inline = [];
+ }
+
+ // ------------------------------------------------------------------------------------
+ // Stylesheets
+ //
+ // Every arm sheet is emitted TWICE: once unlayered, once inside `@layer utilities`.
+ //
+ // The rule that has to be beaten (index.css:2536-2538) is inside `@layer utilities`, and for
+ // important declarations layered beats unlayered no matter the specificity. The layered copy
+ // therefore competes in the same layer as its target, where the ordinary rules apply again:
+ // same layer, same importance, higher specificity, later in document order, so it wins. The
+ // unlayered copy covers the case where the build has no layers at all (then there is nothing
+ // layered to lose to, and the unlayered copy is the one that applies). Emitting both is safe
+ // because the two copies carry identical declarations, so whichever wins produces the same
+ // computed value.
+ //
+ // Appending to <head> puts the sheet last among same-layer rules, which settles order of
+ // appearance. None of this is trusted: applyX() checks getComputedStyle afterwards.
+ // ------------------------------------------------------------------------------------
+
+ function ensureStyleSheet(armId, cssBody) {
+ try {
+ if (state.sheets[armId]) {
+ return true;
+ }
+ if (!doc || typeof doc.createElement !== "function") {
+ return false;
+ }
+ var parent = doc.head || doc.documentElement || doc.body;
+ if (!parent || typeof parent.appendChild !== "function") {
+ return false;
+ }
+ var el = doc.createElement("style");
+ el.setAttribute("data-sb-arm-sheet", armId);
+ el.textContent = cssBody + "\n@layer utilities {\n" + cssBody + "\n}\n";
+ parent.appendChild(el);
+ state.sheets[armId] = el;
+ counters.styleSheetsInstalled += 1;
+ return true;
+ } catch (e) {
+ return false;
+ }
+ }
+
+ function removeStyleSheet(armId) {
+ try {
+ var el = state.sheets[armId];
+ if (!el) {
+ return false;
+ }
+ if (el.parentNode && typeof el.parentNode.removeChild === "function") {
+ el.parentNode.removeChild(el);
+ }
+ delete state.sheets[armId];
+ return true;
+ } catch (e) {
+ return false;
+ }
+ }
+
+ // ------------------------------------------------------------------------------------
+ // Two ways to address "the completed messages" from a stylesheet, and why the first one is
+ // worth the extra code.
+ //
+ // PREFIX PATH (preferred). Messages are DIRECT CHILDREN of the viewport; there is no
+ // message-list wrapper element. The message being streamed is the last one. So the completed
+ // messages are a leading run of the viewport's children and
+ //
+ // .aui-thread-viewport.aui-stream-viewport > [data-message-id]:nth-child(-n+K)
+ //
+ // selects exactly them, with K computed in JS as the child index of the first running message
+ // root. This mutates NOTHING. No attribute is added, no inline style is written, and the raw
+ // digest of the thread is byte-identical before and after, so arms A and C can honestly claim
+ // EXACT invariance. The `[data-message-id]` part is not redundant: nth-child alone would also
+ // match spacers, sentinels and buttons that share the viewport, and hiding one of those is a
+ // change to the rendered page that the digest cannot see because the digest only walks
+ // message roots.
+ //
+ // MARKER PATH (fallback). If the completed set is not a leading prefix (a message somewhere
+ // in the middle is still running, which assistant-ui allows in principle), or the viewport
+ // cannot be found, the arm falls back to a `data-sb-arm` attribute on each completed root.
+ // That is a real DOM mutation, so the arm drops from EXACT to EQUIVALENT and the returned
+ // reason string says so in as many words. It is reported rather than hidden because a
+ // silently-EQUIVALENT arm quoted as EXACT is a false number, while a loudly-EQUIVALENT one is
+ // just a number with a declared diff.
+ // ------------------------------------------------------------------------------------
+
+ function cssPrefixA(k) {
+ return (
+ VIEWPORT_SELECTOR + " > [data-message-id]:nth-child(-n+" + k + ") {\n" +
+ "\tvisibility: hidden !important;\n" +
+ "}\n"
+ );
+ }
+
+ function cssPrefixB(k) {
+ return (
+ "html body " + VIEWPORT_SELECTOR + " > [data-message-id]:nth-child(-n+" + k + ") " +
+ '[data-streamdown="code-block"] {\n' +
+ "\tcontent-visibility: auto !important;\n" +
+ "}\n"
+ );
+ }
+
+ function cssPrefixC(k) {
+ return (
+ VIEWPORT_SELECTOR + " > [data-message-id]:nth-child(-n+" + k + ") {\n" +
+ "\tdisplay: none !important;\n" +
+ "}\n"
+ );
+ }
+
+ var CSS_A =
+ "body [data-message-id][" + MARKER_ATTR + '~="A"],\n' +
+ "[data-message-id][" + MARKER_ATTR + '~="A"] {\n' +
+ "\tvisibility: hidden !important;\n" +
+ "}\n";
+
+ var CSS_B =
+ "html body .aui-thread-root [data-streamdown=\"code-block\"][" + MARKER_ATTR + '~="B"],\n' +
+ "html body [data-streamdown=\"code-block\"][" + MARKER_ATTR + '~="B"] {\n' +
+ "\tcontent-visibility: auto !important;\n" +
+ "}\n";
+
+ var CSS_C =
+ "body [data-message-id][" + MARKER_ATTR + '~="C"],\n' +
+ "[data-message-id][" + MARKER_ATTR + '~="C"] {\n' +
+ "\tdisplay: none !important;\n" +
+ "}\n";
+
+ // Returns the leading run of viewport children that contains no running message, or null when
+ // the prefix path is not usable. `k` is a 1-based nth-child bound; `roots` are the message
+ // roots inside it, all of them completed by construction.
+ function prefixInfo() {
+ try {
+ var vp = viewportEl();
+ if (!vp) {
+ return null;
+ }
+ var kids = [];
+ try {
+ kids = toArray(vp.children);
+ } catch (e) {
+ kids = [];
+ }
+ if (kids.length === 0) {
+ return null;
+ }
+ var firstRunning = -1;
+ var i;
+ for (i = 0; i < kids.length; i++) {
+ var kid = kids[i];
+ var isMessage = false;
+ try {
+ isMessage =
+ typeof kid.getAttribute === "function" &&
+ kid.getAttribute("data-message-id") !== null;
+ } catch (e2) {
+ isMessage = false;
+ }
+ if (isMessage && isRunning(kid)) {
+ firstRunning = i;
+ break;
+ }
+ }
+ var k = firstRunning === -1 ? kids.length : firstRunning;
+ if (k <= 0) {
+ return null;
+ }
+ var roots = [];
+ for (i = 0; i < k; i++) {
+ try {
+ if (
+ typeof kids[i].getAttribute === "function" &&
+ kids[i].getAttribute("data-message-id") !== null
+ ) {
+ roots.push(kids[i]);
+ }
+ } catch (e3) {
+ /* a child we cannot read is a child we do not ablate */
+ }
+ }
+ if (roots.length === 0) {
+ return null;
+ }
+ var skipped = completedMessageRoots().length - roots.length;
+ return { vp: vp, k: k, roots: roots, skipped: skipped > 0 ? skipped : 0 };
+ } catch (e) {
+ return null;
+ }
+ }
+
+ // ------------------------------------------------------------------------------------
+ // Hashing and canonical serialisation
+ // ------------------------------------------------------------------------------------
+
+ var imul =
+ typeof Math.imul === "function"
+ ? Math.imul
+ : function (a, b) {
+ var ah = (a >>> 16) & 0xffff;
+ var al = a & 0xffff;
+ var bh = (b >>> 16) & 0xffff;
+ var bl = b & 0xffff;
+ return ((al * bl + (((ah * bl + al * bh) << 16) >>> 0)) | 0);
+ };
+
+ // FNV-1a, 32 bit, over UTF-16 code units taken low byte first. Non-cryptographic: this is a
+ // change detector, not a security boundary. Compare it together with canonicalLength.
+ function fnv1a32(str) {
+ var h = 0x811c9dc5;
+ for (var i = 0; i < str.length; i++) {
+ var c = str.charCodeAt(i);
+ h ^= c & 0xff;
+ h = imul(h, 16777619);
+ h ^= (c >>> 8) & 0xff;
+ h = imul(h, 16777619);
+ }
+ return ("0000000" + (h >>> 0).toString(16)).slice(-8);
+ }
+
+ // Field encoding. JSON escapes quotes, backslashes, newlines and control characters; the pipe
+ // is escaped on top of that so no encoded field can ever contain the field separator, which
+ // makes the canonical form parseable by a plain split() in diffKeys().
+ function enc(s) {
+ try {
+ return JSON.stringify(String(s === null || s === undefined ? "" : s))
+ .slice(1, -1)
+ .replace(/\|/g, "\\u007c");
+ } catch (e) {
+ return "";
+ }
+ }
+
+ function dec(f) {
+ try {
+ return JSON.parse('"' + f + '"');
+ } catch (e) {
+ return "";
+ }
+ }
+
+ function normaliseStyleValue(value, skipStyleProps) {
+ if (!skipStyleProps || !skipStyleProps.length) {
+ return value;
+ }
+ // Parse with the browser's own CSS parser on a detached element rather than by splitting
+ // on ";" and ":", which breaks on url(data:...) and on any value containing a semicolon.
+ try {
+ if (doc && typeof doc.createElement === "function") {
+ var scratch = doc.createElement("div");
+ scratch.style.cssText = String(value);
+ for (var i = 0; i < skipStyleProps.length; i++) {
+ scratch.style.removeProperty(String(skipStyleProps[i]));
+ }
+ return String(scratch.style.cssText || "");
+ }
+ } catch (e) {
+ /* fall through to the textual fallback */
+ }
+ var parts = String(value).split(";");
+ var kept = [];
+ for (var j = 0; j < parts.length; j++) {
+ var seg = parts[j];
+ var colon = seg.indexOf(":");
+ if (colon < 0) {
+ continue;
+ }
+ var name = seg.slice(0, colon).trim().toLowerCase();
+ var drop = false;
+ for (var k = 0; k < skipStyleProps.length; k++) {
+ if (String(skipStyleProps[k]).trim().toLowerCase() === name) {
+ drop = true;
+ break;
+ }
+ }
+ if (!drop) {
+ kept.push(seg.trim());
+ }
+ }
+ return kept.join("; ");
+ }
+
+ // One DOM walk, reused for both serialisations. Walking twice would be slower and, worse,
+ // would let the page change between the raw pass and the normalised pass, producing a "raw
+ // differs, normalised does not" that is an artefact of the instrument.
+ function collectRecords() {
+ var roots = messageRoots();
+ var records = [];
+ var totalCodeBlocks = 0;
+ var totalCodeSpans = 0;
+ for (var i = 0; i < roots.length; i++) {
+ var el = roots[i];
+ var rec = {
+ tag: "",
+ id: "",
+ attrs: [],
+ text: "",
+ codeBlocks: 0,
+ codeSpans: 0
+ };
+ try {
+ rec.tag = String(el.tagName || el.nodeName || "?").toLowerCase();
+ } catch (e) {
+ rec.tag = "?";
+ }
+ try {
+ rec.id = String(el.getAttribute("data-message-id") || "");
+ } catch (e) {
+ rec.id = "";
+ }
+ try {
+ var attrs = el.attributes;
+ var list = [];
+ for (var a = 0; a < attrs.length; a++) {
+ list.push({
+ name: String(attrs[a].name),
+ value: String(attrs[a].value === undefined ? "" : attrs[a].value)
+ });
+ }
+ list.sort(function (x, y) {
+ return x.name < y.name ? -1 : x.name > y.name ? 1 : 0;
+ });
+ rec.attrs = list;
+ } catch (e) {
+ rec.attrs = [];
+ }
+ try {
+ rec.text = String(el.textContent === null || el.textContent === undefined ? "" : el.textContent);
+ } catch (e) {
+ rec.text = "";
+ }
+ var blocks = codeBlocksIn(el);
+ rec.codeBlocks = blocks.length;
+ var spans = 0;
+ for (var b = 0; b < blocks.length; b++) {
+ spans += queryAll("span", blocks[b]).length;
+ }
+ rec.codeSpans = spans;
+ totalCodeBlocks += rec.codeBlocks;
+ totalCodeSpans += rec.codeSpans;
+ records.push(rec);
+ }
+ return {
+ records: records,
+ messages: roots.length,
+ codeBlocks: totalCodeBlocks,
+ codeSpans: totalCodeSpans
+ };
+ }
+
+ function serialise(collected, skipAttributes, skipStyleProps, observedKeys) {
+ var lines = [];
+ lines.push("V|" + CANONICAL_FORMAT_VERSION);
+ lines.push("S|messages|" + collected.messages);
+ lines.push("S|codeBlocks|" + collected.codeBlocks);
+ lines.push("S|codeSpans|" + collected.codeSpans);
+ observedKeys["structure:messages"] = true;
+ observedKeys["structure:codeBlocks"] = true;
+ observedKeys["structure:codeSpans"] = true;
+ observedKeys["structure:order"] = true;
+ observedKeys.tag = true;
+ observedKeys.text = true;
+
+ var skip = {};
+ for (var s = 0; s < skipAttributes.length; s++) {
+ skip[String(skipAttributes[s]).toLowerCase()] = true;
+ }
+
+ for (var i = 0; i < collected.records.length; i++) {
+ var rec = collected.records[i];
+ lines.push("M|" + i + "|" + enc(rec.tag) + "|" + enc(rec.id));
+ for (var a = 0; a < rec.attrs.length; a++) {
+ var name = rec.attrs[a].name;
+ var lower = String(name).toLowerCase();
+ if (skip[lower] === true) {
+ continue;
+ }
+ var value = rec.attrs[a].value;
+ if (lower === "style") {
+ value = normaliseStyleValue(value, skipStyleProps);
+ }
+ observedKeys["attr:" + lower] = true;
+ lines.push("A|" + i + "|" + enc(name) + "|" + enc(value));
+ }
+ lines.push("T|" + i + "|" + enc(rec.text));
+ lines.push("B|" + i + "|" + rec.codeBlocks + "|" + rec.codeSpans);
+ }
+ return lines.join("\n");
+ }
+
+ function digest(options) {
+ var opts = options && typeof options === "object" ? options : {};
+ var skipAttributes = ["style"];
+ try {
+ if (opts.skipAttributes && typeof opts.skipAttributes.length === "number") {
+ skipAttributes = [];
+ for (var i = 0; i < opts.skipAttributes.length; i++) {
+ skipAttributes.push(String(opts.skipAttributes[i]));
+ }
+ }
+ } catch (e) {
+ skipAttributes = ["style"];
+ }
+ var skipStyleProps = [];
+ try {
+ if (opts.skipStyleProps && typeof opts.skipStyleProps.length === "number") {
+ for (var j = 0; j < opts.skipStyleProps.length; j++) {
+ skipStyleProps.push(String(opts.skipStyleProps[j]));
+ }
+ }
+ } catch (e) {
+ skipStyleProps = [];
+ }
+ var keepCanonical = opts.keepCanonical === true;
+ var maxCanonicalChars = DEFAULT_MAX_CANONICAL_CHARS;
+ try {
+ if (typeof opts.maxCanonicalChars === "number" && isFinite(opts.maxCanonicalChars) && opts.maxCanonicalChars >= 0) {
+ maxCanonicalChars = Math.floor(opts.maxCanonicalChars);
+ }
+ } catch (e) {
+ maxCanonicalChars = DEFAULT_MAX_CANONICAL_CHARS;
+ }
+
+ var out = {
+ raw: null,
+ normalised: null,
+ canonicalLength: 0,
+ rawLength: 0,
+ observedKeys: [],
+ canonical: null,
+ canonicalRaw: null,
+ truncated: false,
+ skipAttributes: skipAttributes.slice(0),
+ skipStyleProps: skipStyleProps.slice(0),
+ formatVersion: CANONICAL_FORMAT_VERSION,
+ hash: "fnv1a32",
+ messages: 0,
+ codeBlocks: 0,
+ codeSpans: 0,
+ error: null
+ };
+
+ try {
+ var collected = collectRecords();
+ out.messages = collected.messages;
+ out.codeBlocks = collected.codeBlocks;
+ out.codeSpans = collected.codeSpans;
+
+ var rawKeys = {};
+ // `raw` skips nothing at all: it is the answer to "did anything about the rendered
+ // output change", including the arm's own marker attribute. An EXACT arm that touches
+ // an attribute is not an EXACT arm, and this is where that gets caught.
+ var rawCanonical = serialise(collected, [], [], rawKeys);
+
+ var normKeys = {};
+ var normCanonical = serialise(collected, skipAttributes, skipStyleProps, normKeys);
+
+ out.raw = fnv1a32(rawCanonical);
+ out.normalised = fnv1a32(normCanonical);
+ out.rawLength = rawCanonical.length;
+ out.canonicalLength = normCanonical.length;
+
+ var keys = [];
+ for (var k in rawKeys) {
+ if (Object.prototype.hasOwnProperty.call(rawKeys, k)) {
+ keys.push(k);
+ }
+ }
+ keys.sort();
+ out.observedKeys = keys;
+
+ if (keepCanonical) {
+ if (rawCanonical.length > maxCanonicalChars || normCanonical.length > maxCanonicalChars) {
+ // A prefix is retained because it is useful when debugging, but `truncated`
+ // is set and diffKeys() refuses to answer from a truncated pair. A quiet cut
+ // would turn "we did not look at the rest" into "the rest was identical".
+ out.truncated = true;
+ }
+ out.canonicalRaw = rawCanonical.slice(0, maxCanonicalChars);
+ out.canonical = normCanonical.slice(0, maxCanonicalChars);
+ }
+ counters.digestsTaken += 1;
+ } catch (e) {
+ out.error = String((e && e.message) || e);
+ }
+ return out;
+ }
+
+ // ------------------------------------------------------------------------------------
+ // diffKeys
+ //
+ // Compares the RAW canonical forms, not the normalised ones. The normalised hashes already
+ // answer "are these equivalent"; what manifest.py needs from here is the other question,
+ // "what actually differs", so it can check the observed diff against the diff the arm
+ // DECLARED it would produce. An arm that declares one difference and produces two is voided,
+ // and comparing normalised forms would hide the second one, since the normaliser is exactly
+ // the thing that removes the declared difference.
+ //
+ // Keys are collapsed to a stable vocabulary (`attr:<name>`, `text`, `tag`,
+ // `structure:<what>`) rather than per-message paths, because a declared diff has to be
+ // writable in advance and `#msg-8fc2.attr.style` is not knowable in advance.
+ //
+ // Fails closed: if the canonical form was not retained, or was truncated, or cannot be
+ // parsed, the returned array contains a key beginning with `__unavailable:` which can never
+ // appear in a declared diff, so the arm is voided instead of silently passing.
+ // ------------------------------------------------------------------------------------
+
+ function parseCanonical(text) {
+ var entries = {}; // entryId -> {key: value}
+ var indexToId = {};
+ var lines = String(text).split("\n");
+ for (var i = 0; i < lines.length; i++) {
+ var line = lines[i];
+ if (!line) {
+ continue;
+ }
+ var f = line.split("|");
+ var kind = f[0];
+ if (kind === "V") {
+ continue;
+ }
+ if (kind === "S") {
+ if (!entries["#global"]) {
+ entries["#global"] = {};
+ }
+ entries["#global"]["structure:" + f[1]] = f[2];
+ continue;
+ }
+ var idx = f[1];
+ if (kind === "M") {
+ var id = dec(f[3] === undefined ? "" : f[3]);
+ var entryId = id ? "id:" + id : "idx:" + idx;
+ indexToId[idx] = entryId;
+ if (!entries[entryId]) {
+ entries[entryId] = {};
+ }
+ entries[entryId].tag = dec(f[2] === undefined ? "" : f[2]);
+ entries[entryId]["structure:order"] = String(idx);
+ continue;
+ }
+ var owner = indexToId[idx];
+ if (!owner || !entries[owner]) {
+ continue;
+ }
+ if (kind === "A") {
+ entries[owner]["attr:" + dec(f[2] === undefined ? "" : f[2]).toLowerCase()] =
+ dec(f.slice(3).join("|"));
+ } else if (kind === "T") {
+ entries[owner].text = dec(f.slice(2).join("|"));
+ } else if (kind === "B") {
+ entries[owner]["structure:codeBlocks"] = f[2];
+ entries[owner]["structure:codeSpans"] = f[3];
+ }
+ }
+ return entries;
+ }
+
+ function diffKeys(a, b) {
+ try {
+ if (!a || !b || typeof a !== "object" || typeof b !== "object") {
+ return ["__unavailable:digest-missing__"];
+ }
+ if (a.truncated === true || b.truncated === true) {
+ return ["__unavailable:canonical-truncated__"];
+ }
+ var ca = a.canonicalRaw;
+ var cb = b.canonicalRaw;
+ if (typeof ca !== "string" || typeof cb !== "string") {
+ return ["__unavailable:canonical-not-retained__"];
+ }
+ if (ca === cb) {
+ return [];
+ }
+ var ea = parseCanonical(ca);
+ var eb = parseCanonical(cb);
+ var found = {};
+ var ids = {};
+ var id;
+ for (id in ea) {
+ if (Object.prototype.hasOwnProperty.call(ea, id)) {
+ ids[id] = true;
+ }
+ }
+ for (id in eb) {
+ if (Object.prototype.hasOwnProperty.call(eb, id)) {
+ ids[id] = true;
+ }
+ }
+ for (id in ids) {
+ if (!Object.prototype.hasOwnProperty.call(ids, id)) {
+ continue;
+ }
+ var ra = ea[id];
+ var rb = eb[id];
+ if (!ra || !rb) {
+ found["structure:messagePresence"] = true;
+ continue;
+ }
+ var keys = {};
+ var key;
+ for (key in ra) {
+ if (Object.prototype.hasOwnProperty.call(ra, key)) {
+ keys[key] = true;
+ }
+ }
+ for (key in rb) {
+ if (Object.prototype.hasOwnProperty.call(rb, key)) {
+ keys[key] = true;
+ }
+ }
+ for (key in keys) {
+ if (!Object.prototype.hasOwnProperty.call(keys, key)) {
+ continue;
+ }
+ if (ra[key] !== rb[key]) {
+ found[key] = true;
+ }
+ }
+ }
+ var out = [];
+ for (var k in found) {
+ if (Object.prototype.hasOwnProperty.call(found, k)) {
+ out.push(k);
+ }
+ }
+ out.sort();
+ return out;
+ } catch (e) {
+ return ["__unavailable:diff-failed__"];
+ }
+ }
+
+ // Beyond the required API: the same comparison with examples, for a human reading a VOIDED
+ // verdict who needs to know WHICH message drifted and by how much.
+ function diffDetail(a, b, limit) {
+ var cap = typeof limit === "number" && limit > 0 ? Math.floor(limit) : 20;
+ var out = [];
+ try {
+ if (!a || !b || typeof a.canonicalRaw !== "string" || typeof b.canonicalRaw !== "string") {
+ return out;
+ }
+ var ea = parseCanonical(a.canonicalRaw);
+ var eb = parseCanonical(b.canonicalRaw);
+ var ids = {};
+ var id;
+ for (id in ea) {
+ if (Object.prototype.hasOwnProperty.call(ea, id)) {
+ ids[id] = true;
+ }
+ }
+ for (id in eb) {
+ if (Object.prototype.hasOwnProperty.call(eb, id)) {
+ ids[id] = true;
+ }
+ }
+ for (id in ids) {
+ if (!Object.prototype.hasOwnProperty.call(ids, id) || out.length >= cap) {
+ continue;
+ }
+ var ra = ea[id] || {};
+ var rb = eb[id] || {};
+ var keys = {};
+ var key;
+ for (key in ra) {
+ if (Object.prototype.hasOwnProperty.call(ra, key)) {
+ keys[key] = true;
+ }
+ }
+ for (key in rb) {
+ if (Object.prototype.hasOwnProperty.call(rb, key)) {
+ keys[key] = true;
+ }
+ }
+ for (key in keys) {
+ if (!Object.prototype.hasOwnProperty.call(keys, key) || out.length >= cap) {
+ continue;
+ }
+ if (ra[key] !== rb[key]) {
+ out.push({
+ entry: id,
+ key: key,
+ before: String(ra[key] === undefined ? "" : ra[key]).slice(0, 200),
+ after: String(rb[key] === undefined ? "" : rb[key]).slice(0, 200)
+ });
+ }
+ }
+ }
+ } catch (e) {
+ /* a partial detail list is still useful and must not throw */
+ }
+ return out;
+ }
+
+ // ------------------------------------------------------------------------------------
+ // counts()
+ // ------------------------------------------------------------------------------------
+
+ function counts() {
+ var out = {
+ messages: 0,
+ assistantMessages: 0,
+ userMessages: 0,
+ completedMessages: 0,
+ runningMessages: 0,
+ codeBlocks: 0,
+ codeSpans: 0,
+ highlightedTokens: 0,
+ chars: 0,
+ domNodes: 0,
+ visibleMessages: 0,
+ // Beyond the required keys, and required by the zero discipline: visibleMessages == 0
+ // because the thread viewport was not found is a different fact from
+ // visibleMessages == 0 because nothing is on screen, and the two must not print the
+ // same.
+ viewportFound: false
+ };
+ try {
+ var roots = messageRoots();
+ out.messages = roots.length;
+ var vp = viewportEl();
+ out.viewportFound = !!vp;
+ var vpRect = vp ? rectOf(vp) : null;
+ for (var i = 0; i < roots.length; i++) {
+ var el = roots[i];
+ var role = "";
+ try {
+ role = String(el.getAttribute("data-role") || "");
+ } catch (e) {
+ role = "";
+ }
+ if (role === "assistant") {
+ out.assistantMessages += 1;
+ } else if (role === "user") {
+ out.userMessages += 1;
+ }
+ if (isRunning(el)) {
+ out.runningMessages += 1;
+ } else {
+ out.completedMessages += 1;
+ }
+ try {
+ out.chars += String(el.textContent || "").length;
+ } catch (e2) {
+ /* a node that cannot be read contributes nothing */
+ }
+ if (vpRect) {
+ var r = rectOf(el);
+ if (rectsIntersect(r, vpRect)) {
+ out.visibleMessages += 1;
+ }
+ }
+ }
+ var blocks = allCodeBlocks();
+ out.codeBlocks = blocks.length;
+ for (var b = 0; b < blocks.length; b++) {
+ var spans = queryAll("span", blocks[b]);
+ out.codeSpans += spans.length;
+ for (var s = 0; s < spans.length; s++) {
+ // A shiki token is a leaf span with text. Both numbers are reported: a
+ // fixture that renders a fifth of the highlighting moves both, and a change
+ // in span NESTING moves only codeSpans, so keeping them separate says which
+ // of the two happened.
+ var sp = spans[s];
+ var hasElementChild = false;
+ try {
+ hasElementChild = !!(sp.children && sp.children.length > 0);
+ } catch (e3) {
+ hasElementChild = false;
+ }
+ if (hasElementChild) {
+ continue;
+ }
+ var txt = "";
+ try {
+ txt = String(sp.textContent || "");
+ } catch (e4) {
+ txt = "";
+ }
+ if (txt.length > 0) {
+ out.highlightedTokens += 1;
+ }
+ }
+ }
+ try {
+ out.domNodes = doc && typeof doc.getElementsByTagName === "function"
+ ? doc.getElementsByTagName("*").length
+ : 0;
+ } catch (e5) {
+ out.domNodes = 0;
+ }
+ } catch (e) {
+ /* whatever was counted before the failure is still returned */
+ }
+ return out;
+ }
+
+ // ------------------------------------------------------------------------------------
+ // potency()
+ // ------------------------------------------------------------------------------------
+
+ function measureGauges() {
+ try {
+ var roots = messageRoots();
+ gauges.visibilityHiddenConfirmed = countComputed(roots, "visibility", "hidden");
+ gauges.displayNoneConfirmed = countComputed(roots, "display", "none");
+ gauges.cvAutoMessages = countComputed(roots, "content-visibility", "auto");
+ gauges.cvAutoCodeBlocks = countComputed(allCodeBlocks(), "content-visibility", "auto");
+ gauges.contentVisibilityAutoConfirmed = gauges.cvAutoMessages + gauges.cvAutoCodeBlocks;
+
+ var vp = viewportEl();
+ var vpRect = vp ? rectOf(vp) : null;
+ var visible = 0;
+ var visiblePrior = 0;
+ if (vpRect) {
+ for (var i = 0; i < roots.length; i++) {
+ if (rectsIntersect(rectOf(roots[i]), vpRect)) {
+ visible += 1;
+ if (i < roots.length - 1) {
+ visiblePrior += 1;
+ }
+ }
+ }
+ }
+ gauges.controlVisibleMessages = visible;
+ gauges.controlVisiblePriorMessages = visiblePrior;
+ } catch (e) {
+ /* keep the last measurement rather than zeroing it, and never throw */
+ }
+ }
+
+ function potency(options) {
+ var opts = options && typeof options === "object" ? options : {};
+ try {
+ if (opts.live !== false) {
+ measureGauges();
+ }
+ } catch (e) {
+ /* fall through and return the stored values */
+ }
+ var out = {};
+ var k;
+ for (k in counters) {
+ if (Object.prototype.hasOwnProperty.call(counters, k)) {
+ out[k] = Math.floor(counters[k]);
+ }
+ }
+ for (k in gauges) {
+ if (Object.prototype.hasOwnProperty.call(gauges, k)) {
+ out[k] = Math.floor(gauges[k]);
+ }
+ }
+ out.frozen = state.frozen ? 1 : 0;
+ out.armsAppliedNow = 0;
+ for (var id in state.applied) {
+ if (Object.prototype.hasOwnProperty.call(state.applied, id)) {
+ out.armsAppliedNow += 1;
+ }
+ }
+ return out;
+ }
+
+ // ------------------------------------------------------------------------------------
+ // Arm A -- visibility:hidden on completed messages
+ // ------------------------------------------------------------------------------------
+
+ function applyA() {
+ var info = prefixInfo();
+ var roots;
+ var via;
+ if (info) {
+ roots = info.roots;
+ ensureStyleSheet("A", cssPrefixA(info.k));
+ via =
+ ":nth-child(-n+" + info.k + ") prefix stylesheet, no DOM mutation (EXACT)" +
+ (info.skipped > 0
+ ? "; " + info.skipped + " completed root(s) after the first running message " +
+ "were left alone"
+ : "");
+ } else {
+ roots = completedMessageRoots();
+ if (roots.length === 0) {
+ return result(
+ false,
+ "no completed message roots matched " + MESSAGE_SELECTOR + " (found " +
+ messageRoots().length + " message roots, " + runningMessageRoots().length +
+ " of them running); nothing was ablated",
+ 0
+ );
+ }
+ ensureStyleSheet("A", CSS_A);
+ markAll(roots, "A");
+ via =
+ "marker-attribute stylesheet: the completed set is not a leading prefix of the " +
+ "viewport's children, so " + MARKER_ATTR + " was added and this arm is " +
+ "EQUIVALENT, not EXACT";
+ }
+ var confirmed = countComputed(roots, "visibility", "hidden");
+ if (confirmed === 0) {
+ // The stylesheet lost the cascade. Inline important is sorted before layers and beats
+ // every author rule, so this is the escalation that cannot lose.
+ counters.inlineFallbacks += 1;
+ for (var i = 0; i < roots.length; i++) {
+ setInline(roots[i], "visibility", "hidden", "important");
+ }
+ confirmed = countComputed(roots, "visibility", "hidden");
+ via =
+ "inline !important, escalated because the stylesheet lost the cascade (this " +
+ "writes the style attribute, so the arm is EQUIVALENT, not EXACT)";
+ }
+ gauges.visibilityHiddenConfirmed = confirmed;
+ if (confirmed === 0) {
+ return result(
+ false,
+ "targeted " + roots.length + " completed message roots but none of them compute " +
+ "to visibility:hidden; the arm did not fire and must not be read as no effect",
+ 0
+ );
+ }
+ return result(
+ true,
+ "visibility:hidden via " + via + " on " + confirmed + " of " + roots.length +
+ " completed message roots",
+ confirmed
+ );
+ }
+
+ // ------------------------------------------------------------------------------------
+ // Arm B -- content-visibility:auto plus contain-intrinsic-size
+ //
+ // Part (i) restores content-visibility on code blocks, undoing index.css:2536-2538.
+ // Part (ii) puts content-visibility:auto and contain-intrinsic-size:auto <measured>px inline
+ // on each completed message root.
+ //
+ // THE ORDERING BUG THIS FUNCTION IS SHAPED TO AVOID: content-visibility:auto makes an
+ // off-screen element skip its contents, so the moment it is set, offsetHeight collapses to the
+ // contain-intrinsic-size placeholder. Reading offsetHeight after setting the property captures
+ // the placeholder, which is then fed back as the intrinsic size, and every element ends up
+ // claiming to be 200px (or 0) tall. The thread's scroll height collapses, the scrollbar jumps,
+ // the autoscroll observer fires on the reflow, and the run measures a page that is not the
+ // page. So the heights are all read in one pass FIRST and only then written in a second pass.
+ // Two passes also avoid read/write layout thrash, but that is a bonus, not the reason.
+ // ------------------------------------------------------------------------------------
+
+ function readHeights(els) {
+ var heights = [];
+ for (var i = 0; i < els.length; i++) {
+ var h = 0;
+ try {
+ h = Number(els[i].offsetHeight) || 0;
+ } catch (e) {
+ h = 0;
+ }
+ heights.push(h);
+ }
+ return heights;
+ }
+
+ function applyB() {
+ var info = prefixInfo();
+ var roots = info ? info.roots : completedMessageRoots();
+ if (roots.length === 0) {
+ return result(
+ false,
+ "no completed message roots matched " + MESSAGE_SELECTOR + "; nothing was ablated",
+ 0
+ );
+ }
+
+ // Only code blocks inside COMPLETED messages. The block that is still streaming must not
+ // be touched: changing containment on it would change how streamdown and shiki finalise
+ // it, which is a change to the output, not an ablation of cost.
+ var blocks = [];
+ for (var r = 0; r < roots.length; r++) {
+ var bs = codeBlocksIn(roots[r]);
+ for (var b = 0; b < bs.length; b++) {
+ blocks.push(bs[b]);
+ }
+ }
+
+ // READ PASS. Every height is captured before any property is written.
+ var blockHeights = readHeights(blocks);
+ var rootHeights = readHeights(roots);
+
+ // WRITE PASS. B writes inline styles on the roots either way, so it is EQUIVALENT
+ // whatever happens here; the prefix selector is still preferred because it keeps the
+ // code blocks free of a marker attribute that the digest cannot see (the canonical form
+ // serialises message-root attributes and DESCENDANT COUNTS, not descendant attributes).
+ if (info) {
+ ensureStyleSheet("B", cssPrefixB(info.k));
+ } else {
+ ensureStyleSheet("B", CSS_B);
+ markAll(blocks, "B");
+ }
+ var i;
+ for (i = 0; i < blocks.length; i++) {
+ // contain-intrinsic-size has to be inline anyway because it is per element, and the
+ // stylesheet only carries content-visibility.
+ setInline(
+ blocks[i],
+ "contain-intrinsic-size",
+ "auto " + Math.max(0, Math.round(blockHeights[i])) + "px",
+ "important"
+ );
+ }
+
+ var cvBlocks = countComputed(blocks, "content-visibility", "auto");
+ if (blocks.length > 0 && cvBlocks === 0) {
+ // Expected on this build: index.css:2537 sets content-visibility:visible !important
+ // from inside @layer utilities, and for important declarations a layered rule beats
+ // an unlayered one at any specificity. The layered copy of CSS_B should win; if it
+ // did not, inline important is the escalation that the cascade guarantees.
+ counters.inlineFallbacks += 1;
+ for (i = 0; i < blocks.length; i++) {
+ setInline(blocks[i], "content-visibility", "auto", "important");
+ }
+ cvBlocks = countComputed(blocks, "content-visibility", "auto");
+ }
+
+ for (i = 0; i < roots.length; i++) {
+ setInline(roots[i], "content-visibility", "auto", "important");
+ setInline(
+ roots[i],
+ "contain-intrinsic-size",
+ "auto " + Math.max(0, Math.round(rootHeights[i])) + "px",
+ "important"
+ );
+ }
+ var cvRoots = countComputed(roots, "content-visibility", "auto");
+
+ gauges.cvAutoCodeBlocks = cvBlocks;
+ gauges.cvAutoMessages = cvRoots;
+ gauges.contentVisibilityAutoConfirmed = cvBlocks + cvRoots;
+
+ if (cvBlocks + cvRoots === 0) {
+ return result(
+ false,
+ "touched " + roots.length + " message roots and " + blocks.length + " code blocks " +
+ "and none of them compute to content-visibility:auto; the arm did not fire",
+ 0
+ );
+ }
+ return result(
+ true,
+ "content-visibility:auto on " + cvRoots + "/" + roots.length + " message roots and " +
+ cvBlocks + "/" + blocks.length + " code blocks; contain-intrinsic-size seeded from " +
+ "heights measured before the property was set",
+ cvBlocks + cvRoots
+ );
+ }
+
+ // ------------------------------------------------------------------------------------
+ // Arm C -- display:none on completed messages
+ // ------------------------------------------------------------------------------------
+
+ function applyC() {
+ var info = prefixInfo();
+ var roots;
+ var via;
+ if (info) {
+ roots = info.roots;
+ ensureStyleSheet("C", cssPrefixC(info.k));
+ via =
+ ":nth-child(-n+" + info.k + ") prefix stylesheet, no DOM mutation (EXACT)" +
+ (info.skipped > 0
+ ? "; " + info.skipped + " completed root(s) after the first running message " +
+ "were left alone"
+ : "");
+ } else {
+ roots = completedMessageRoots();
+ if (roots.length === 0) {
+ return result(
+ false,
+ "no completed message roots matched " + MESSAGE_SELECTOR + "; nothing was ablated",
+ 0
+ );
+ }
+ ensureStyleSheet("C", CSS_C);
+ markAll(roots, "C");
+ via =
+ "marker-attribute stylesheet: the completed set is not a leading prefix of the " +
+ "viewport's children, so " + MARKER_ATTR + " was added and this arm is " +
+ "EQUIVALENT, not EXACT";
+ }
+ var confirmed = countComputed(roots, "display", "none");
+ if (confirmed === 0) {
+ counters.inlineFallbacks += 1;
+ for (var i = 0; i < roots.length; i++) {
+ setInline(roots[i], "display", "none", "important");
+ }
+ confirmed = countComputed(roots, "display", "none");
+ via =
+ "inline !important, escalated because the stylesheet lost the cascade (this " +
+ "writes the style attribute, so the arm is EQUIVALENT, not EXACT)";
+ }
+ gauges.displayNoneConfirmed = confirmed;
+ if (confirmed === 0) {
+ return result(
+ false,
+ "targeted " + roots.length + " completed message roots but none compute to " +
+ "display:none; the arm did not fire",
+ 0
+ );
+ }
+ return result(
+ true,
+ "display:none via " + via + " on " + confirmed + " of " + roots.length +
+ " completed message roots",
+ confirmed
+ );
+ }
+
+ // ------------------------------------------------------------------------------------
+ // Arm D -- detach the autoscroll subtree observer (PREBOOT)
+ //
+ // Two discriminators identify the autoscroll observer, and both come from
+ // use-intent-aware-autoscroll.tsx:502: the target carries the aui-stream-viewport class, and
+ // the options carry "aria-expanded" in attributeFilter. Nothing else in the app observes with
+ // aria-expanded, and .aui-stream-viewport marks only real streaming-thread viewports.
+ //
+ // EVERY OTHER observe() CALL MUST PASS THROUGH UNCHANGED. reasoning.tsx,
+ // research-activity-panel.tsx, animated-theme-toggler.tsx, tooltip-modal-layer.ts (twice),
+ // settings-dialog.tsx, monitor-frame-store.ts and use-composer-pill-fit.ts all install
+ // observers, and breaking any of them would change what the app renders, which converts an
+ // ablation into a different page.
+ //
+ // The wrapper forwards `arguments` verbatim to the original, so calls with missing or invalid
+ // arguments throw the same TypeError from the same function they always did. The matching
+ // logic cannot throw: if reading options.attributeFilter fails for any reason, the call is
+ // treated as not-matching and passes through, because passing an observe() through is always
+ // safe and suppressing one that should not have been suppressed is not.
+ // ------------------------------------------------------------------------------------
+
+ function targetIsStreamViewport(target) {
+ try {
+ if (!target || target.nodeType !== 1) {
+ return false;
+ }
+ var list = target.classList;
+ if (list && typeof list.contains === "function") {
+ return list.contains(VIEWPORT_CLASS) === true;
+ }
+ var cn = String(target.className || "");
+ return (" " + cn + " ").indexOf(" " + VIEWPORT_CLASS + " ") >= 0;
+ } catch (e) {
+ return false;
+ }
+ }
+
+ function optionsHaveAriaExpanded(options) {
+ try {
+ if (!options || typeof options !== "object") {
+ return false;
+ }
+ var filter = options.attributeFilter;
+ if (!filter || typeof filter.length !== "number") {
+ return false;
+ }
+ for (var i = 0; i < filter.length; i++) {
+ if (String(filter[i]) === "aria-expanded") {
+ return true;
+ }
+ }
+ return false;
+ } catch (e) {
+ return false;
+ }
+ }
+
+ function installD() {
+ var proto = null;
+ try {
+ proto = W.MutationObserver && W.MutationObserver.prototype;
+ } catch (e) {
+ proto = null;
+ }
+ if (!proto) {
+ markUnavailable("D", "window.MutationObserver is missing in this browser");
+ return false;
+ }
+ var descriptor = null;
+ try {
+ descriptor = Object.getOwnPropertyDescriptor(proto, "observe");
+ } catch (e) {
+ descriptor = null;
+ }
+ if (!descriptor || typeof descriptor.value !== "function") {
+ markUnavailable("D", "MutationObserver.prototype.observe is not a data property");
+ return false;
+ }
+ if (descriptor.configurable !== true && descriptor.writable !== true) {
+ markUnavailable(
+ "D",
+ "MutationObserver.prototype.observe is neither configurable nor writable, so the " +
+ "patch cannot be installed on this engine"
+ );
+ return false;
+ }
+ var original = descriptor.value;
+
+ function observe(target, options) {
+ counters.observeCallsTotal += 1;
+ var matched = false;
+ try {
+ matched = targetIsStreamViewport(target) || optionsHaveAriaExpanded(options);
+ } catch (e) {
+ matched = false;
+ }
+ if (matched && state.installed.D) {
+ counters.suppressedViewportObserves += 1;
+ debug("suppressed autoscroll observe()", target);
+ return undefined;
+ }
+ counters.observeCallsPassedThrough += 1;
+ return original.apply(this, arguments);
+ }
+
+ try {
+ Object.defineProperty(observe, "name", { value: "observe", configurable: true });
+ Object.defineProperty(observe, "length", { value: original.length, configurable: true });
+ } catch (e) {
+ /* cosmetic only */
+ }
+
+ try {
+ Object.defineProperty(proto, "observe", {
+ value: observe,
+ writable: descriptor.writable !== false,
+ enumerable: descriptor.enumerable === true,
+ configurable: true
+ });
+ } catch (e) {
+ markUnavailable("D", "defineProperty on MutationObserver.prototype.observe threw: " + e);
+ return false;
+ }
+
+ state.originals.observe = original;
+ state.originals.observeDescriptor = descriptor;
+ state.installed.D = true;
+ return true;
+ }
+
+ // ------------------------------------------------------------------------------------
+ // Arm E -- neutralise the --aui-scroll-stabilizer write (PREBOOT)
+ //
+ // One custom property, by exact name. Every other setProperty call, custom property or not,
+ // passes through with its arguments forwarded verbatim so that coercion and throwing are
+ // unchanged. customPropSets counts every custom property write including the suppressed ones,
+ // which is the context that tells a reader whether the stabilizer was one write in ten or one
+ // in ten thousand.
+ // ------------------------------------------------------------------------------------
+
+ function installE() {
+ var proto = null;
+ try {
+ proto = W.CSSStyleDeclaration && W.CSSStyleDeclaration.prototype;
+ } catch (e) {
+ proto = null;
+ }
+ if (!proto) {
+ markUnavailable("E", "window.CSSStyleDeclaration is missing in this browser");
+ return false;
+ }
+ var descriptor = null;
+ try {
+ descriptor = Object.getOwnPropertyDescriptor(proto, "setProperty");
+ } catch (e) {
+ descriptor = null;
+ }
+ if (!descriptor || typeof descriptor.value !== "function") {
+ markUnavailable("E", "CSSStyleDeclaration.prototype.setProperty is not a data property");
+ return false;
+ }
+ if (descriptor.configurable !== true && descriptor.writable !== true) {
+ markUnavailable(
+ "E",
+ "CSSStyleDeclaration.prototype.setProperty is neither configurable nor writable"
+ );
+ return false;
+ }
+ var original = descriptor.value;
+
+ function setProperty(property, value, priority) {
+ counters.setPropertyCallsTotal += 1;
+ var name = null;
+ try {
+ // A Symbol argument makes String() throw. In that case name stays null, the call
+ // passes through, and the original throws exactly the TypeError it would have.
+ name = typeof property === "string" ? property : String(property);
+ } catch (e) {
+ name = null;
+ }
+ if (name !== null && name.charCodeAt(0) === 45 && name.charCodeAt(1) === 45) {
+ counters.customPropSets += 1;
+ }
+ if (name === STABILIZER_PROP && state.installed.E) {
+ counters.suppressedStabilizerSets += 1;
+ return undefined;
+ }
+ return original.apply(this, arguments);
+ }
+
+ try {
+ Object.defineProperty(setProperty, "name", { value: "setProperty", configurable: true });
+ Object.defineProperty(setProperty, "length", {
+ value: original.length,
+ configurable: true
+ });
+ } catch (e) {
+ /* cosmetic only */
+ }
+
+ try {
+ Object.defineProperty(proto, "setProperty", {
+ value: setProperty,
+ writable: descriptor.writable !== false,
+ enumerable: descriptor.enumerable === true,
+ configurable: true
+ });
+ } catch (e) {
+ markUnavailable("E", "defineProperty on CSSStyleDeclaration.prototype.setProperty threw: " + e);
+ return false;
+ }
+
+ state.originals.setProperty = original;
+ state.originals.setPropertyDescriptor = descriptor;
+ state.installed.E = true;
+ return true;
+ }
+
+ // ------------------------------------------------------------------------------------
+ // Arm F -- freeze the React scheduler, keep the DOM (PREBOOT capture, apply() freezes)
+ //
+ // THIS ARM IS DOM_CHANGING. While frozen, React renders nothing, so the stream stops
+ // appearing on screen and the frozen side is not rendering the same page as the control. Its
+ // cost is an UPPER BOUND on what React reconciliation costs and can never be quoted as a point
+ // estimate; manifest.py prints it as `<= x`. It is here because a bound on React is still
+ // worth having when the alternative is guessing, not because the number is clean.
+ //
+ // React's browser scheduler is the only runtime handle available. The ReactDOMRoot object is
+ // not exposed on window, so root.unmount() is not reachable, and #root is just an element.
+ // The scheduler does: const channel = new MessageChannel(); channel.port1.onmessage =
+ // performWorkUntilDeadline; ... port2.postMessage(null). Intercepting the assignment to
+ // port1.onmessage puts a dispatcher in front of performWorkUntilDeadline, and the freeze flag
+ // decides whether the dispatcher forwards.
+ //
+ // capturedSchedulerPorts is what separates "React never used MessageChannel on this build"
+ // (0 ports: NOT RUN, the treatment never happened) from "we froze it and nothing changed"
+ // (ports captured, callbacks suppressed).
+ //
+ // SUPPRESSING SCHEDULER MESSAGES CAN WEDGE REACT PERMANENTLY. The message loop only posts the
+ // next message from inside the handler it just ran, so a swallowed delivery ends the loop and
+ // unfreezing alone does not restart it. revert() therefore posts one fresh message per
+ // channel that had suppressions (schedulerResumeKicks) unless config.redeliverOnUnfreeze is
+ // false, and says so in the returned reason. The suppressed events themselves are NOT
+ // replayed: React's performWorkUntilDeadline ignores the event object and reads its own
+ // queue, so one kick resumes exactly the work the swallowed messages would have done, and
+ // replaying N events would run N slices that no longer correspond to anything.
+ // ------------------------------------------------------------------------------------
+
+ function instrumentSchedulerPort(channel) {
+ var port = channel.port1;
+ var stored = null;
+ var record = { channel: channel, pendingSuppressed: 0 };
+
+ function dispatch(event) {
+ var fn = stored;
+ if (typeof fn !== "function") {
+ counters.schedulerCallbacksWithoutHandler += 1;
+ return undefined;
+ }
+ if (state.frozen) {
+ counters.suppressedSchedulerCallbacks += 1;
+ record.pendingSuppressed += 1;
+ if (counters.retainedSchedulerEvents < MAX_RETAINED_SCHEDULER_EVENTS) {
+ counters.retainedSchedulerEvents += 1;
+ } else {
+ counters.droppedSchedulerEvents += 1;
+ }
+ return undefined;
+ }
+ counters.schedulerCallbacksDelivered += 1;
+ // Called without a try/catch on purpose: an exception thrown by React must propagate
+ // exactly as it would have. Swallowing it here would make the frozen run behave
+ // differently from the control in a way that has nothing to do with the ablation.
+ return fn.call(port, event);
+ }
+
+ // Assigning through the prototype accessor first, so the real port ends up calling the
+ // dispatcher. This implicitly starts port1, which the scheduler does a moment later
+ // anyway when it assigns its own handler.
+ port.onmessage = dispatch;
+
+ Object.defineProperty(port, "onmessage", {
+ configurable: true,
+ enumerable: true,
+ get: function () {
+ return stored;
+ },
+ set: function (fn) {
+ stored = fn;
+ }
+ });
+
+ // Some builds attach with addEventListener instead of onmessage. Without this, such a
+ // build would report captured ports and zero suppressions, which reads as "we froze it
+ // and React did not care" when the truth is that the freeze never reached the handler.
+ try {
+ var origAdd = port.addEventListener;
+ var origRemove = port.removeEventListener;
+ var wrappedByOriginal = typeof WeakMap === "function" ? new WeakMap() : null;
+ if (typeof origAdd === "function") {
+ Object.defineProperty(port, "addEventListener", {
+ configurable: true,
+ writable: true,
+ enumerable: false,
+ value: function (type, listener, opts) {
+ if (type === "message" && typeof listener === "function") {
+ counters.schedulerListenerAdds += 1;
+ var wrapped = function (event) {
+ if (state.frozen) {
+ counters.suppressedSchedulerCallbacks += 1;
+ record.pendingSuppressed += 1;
+ if (counters.retainedSchedulerEvents < MAX_RETAINED_SCHEDULER_EVENTS) {
+ counters.retainedSchedulerEvents += 1;
+ } else {
+ counters.droppedSchedulerEvents += 1;
+ }
+ return undefined;
+ }
+ counters.schedulerCallbacksDelivered += 1;
+ return listener.call(this, event);
+ };
+ if (wrappedByOriginal) {
+ wrappedByOriginal.set(listener, wrapped);
+ }
+ return origAdd.call(this, type, wrapped, opts);
+ }
+ return origAdd.apply(this, arguments);
+ }
+ });
+ }
+ if (typeof origRemove === "function") {
+ Object.defineProperty(port, "removeEventListener", {
+ configurable: true,
+ writable: true,
+ enumerable: false,
+ value: function (type, listener, opts) {
+ if (type === "message" && typeof listener === "function" && wrappedByOriginal) {
+ var wrapped = wrappedByOriginal.get(listener);
+ if (wrapped) {
+ return origRemove.call(this, type, wrapped, opts);
+ }
+ }
+ return origRemove.apply(this, arguments);
+ }
+ });
+ }
+ } catch (e) {
+ debug("could not wrap port addEventListener", e);
+ }
+
+ if (state.channels.length < MAX_CAPTURED_CHANNELS) {
+ state.channels.push(record);
+ }
+ counters.capturedSchedulerPorts += 1;
+ }
+
+ function installF() {
+ var Original = null;
+ try {
+ Original = W.MessageChannel;
+ } catch (e) {
+ Original = null;
+ }
+ if (typeof Original !== "function") {
+ markUnavailable("F", "window.MessageChannel is missing, so React's scheduler cannot be intercepted");
+ return false;
+ }
+
+ // Probe before committing: if the port instance refuses a redefined onmessage there is no
+ // way to intercept, and the arm must read UNAVAILABLE rather than run and suppress
+ // nothing.
+ try {
+ var probe = new Original();
+ Object.defineProperty(probe.port1, "onmessage", {
+ configurable: true,
+ enumerable: true,
+ get: function () {
+ return null;
+ },
+ set: function () {}
+ });
+ try {
+ probe.port1.close();
+ probe.port2.close();
+ } catch (e2) {
+ /* closing is hygiene, not correctness */
+ }
+ } catch (e) {
+ markUnavailable("F", "MessagePort.onmessage cannot be redefined on this engine: " + e);
+ return false;
+ }
+
+ function WrappedMessageChannel() {
+ var channel = new Original();
+ try {
+ instrumentSchedulerPort(channel);
+ } catch (e) {
+ // A channel we failed to instrument is still a working channel. The app must not
+ // notice, and capturedSchedulerPorts simply does not count it.
+ debug("could not instrument a MessageChannel", e);
+ }
+ return channel;
+ }
+
+ try {
+ WrappedMessageChannel.prototype = Original.prototype;
+ Object.defineProperty(WrappedMessageChannel, "name", {
+ value: "MessageChannel",
+ configurable: true
+ });
+ } catch (e) {
+ /* cosmetic only */
+ }
+
+ try {
+ W.MessageChannel = WrappedMessageChannel;
+ } catch (e) {
+ markUnavailable("F", "window.MessageChannel is not writable: " + e);
+ return false;
+ }
+
+ state.originals.MessageChannel = Original;
+ state.installed.F = true;
+ return true;
+ }
+
+ function applyF() {
+ if (!state.installed.F) {
+ return result(false, unavailable.F || "arm F was not armed at injection time", 0);
+ }
+ if (state.frozen) {
+ return result(false, "already frozen", counters.capturedSchedulerPorts);
+ }
+ state.frozen = true;
+ if (counters.capturedSchedulerPorts === 0) {
+ // Not an error yet: React may create its channel later. It is recorded in the reason
+ // so that a run which ends with zero captured ports is read as NOT RUN.
+ return result(
+ true,
+ "freeze flag set, but no MessageChannel has been created yet; if " +
+ "capturedSchedulerPorts is still 0 at the end of the window then React never " +
+ "used MessageChannel on this build and the arm did NOT run",
+ 0
+ );
+ }
+ return result(
+ true,
+ "scheduler frozen across " + counters.capturedSchedulerPorts + " captured port(s); " +
+ "this arm is DOM_CHANGING and its cost is an upper bound only",
+ counters.capturedSchedulerPorts
+ );
+ }
+
+ function revertF() {
+ if (!state.installed.F) {
+ return revertResult(false, "arm F was never installed");
+ }
+ if (!state.frozen) {
+ return revertResult(true, "not frozen");
+ }
+ state.frozen = false;
+ var kicks = 0;
+ var suppressed = 0;
+ for (var i = 0; i < state.channels.length; i++) {
+ var rec = state.channels[i];
+ if (rec.pendingSuppressed <= 0) {
+ continue;
+ }
+ suppressed += rec.pendingSuppressed;
+ rec.pendingSuppressed = 0;
+ if (!redeliverOnUnfreeze) {
+ continue;
+ }
+ try {
+ rec.channel.port2.postMessage(null);
+ kicks += 1;
+ counters.schedulerResumeKicks += 1;
+ counters.schedulerCallbacksRedelivered += 1;
+ } catch (e) {
+ debug("could not kick a frozen scheduler channel", e);
+ }
+ }
+ if (!redeliverOnUnfreeze) {
+ return revertResult(
+ true,
+ "unfrozen; " + suppressed + " suppressed delivery/deliveries were NOT redelivered " +
+ "(config.redeliverOnUnfreeze is false), so React's message loop may stay " +
+ "stopped until something else schedules work"
+ );
+ }
+ return revertResult(
+ true,
+ "unfrozen; " + suppressed + " suppressed delivery/deliveries were not replayed, and " +
+ kicks + " fresh scheduler message(s) were posted instead to restart the message " +
+ "loop. Anything rendered after this point was rendered late"
+ );
+ }
+
+ // ------------------------------------------------------------------------------------
+ // Arm G -- control: identical DOM, prior turns in the viewport
+ //
+ // The viewport carries the `scroll-smooth` class (thread.tsx:1728), so a scrollTop assignment
+ // would animate. An animated scroll would still be running when the measured window starts,
+ // which would put scroll animation cost inside the control and make the control the most
+ // expensive arm. scrollBehavior is forced to auto for the assignment and restored afterwards.
+ //
+ // The app's own autoscroll may pull the thread back to the bottom at any time, which is why
+ // controlVisibleMessages is a gauge that is re-measured on every potency() call rather than a
+ // number recorded once at apply time: the honest question is whether the prior turns were
+ // visible for the WINDOW, not whether they were visible for an instant.
+ // ------------------------------------------------------------------------------------
+
+ function applyG() {
+ var vp = viewportEl();
+ if (!vp) {
+ return result(false, "no element matched " + VIEWPORT_SELECTOR + "; nothing to scroll", 0);
+ }
+ var roots = messageRoots();
+ if (roots.length === 0) {
+ return result(false, "no message roots to bring into view", 0);
+ }
+
+ var prevBehavior = "";
+ var prevBehaviorPriority = "";
+ var hadStyleAttr = true;
+ try {
+ prevBehavior = vp.style.getPropertyValue("scroll-behavior") || "";
+ prevBehaviorPriority = vp.style.getPropertyPriority("scroll-behavior") || "";
+ hadStyleAttr = typeof vp.hasAttribute === "function" ? vp.hasAttribute("style") : true;
+ } catch (e) {
+ prevBehavior = "";
+ prevBehaviorPriority = "";
+ }
+ var prevScrollTop = 0;
+ try {
+ prevScrollTop = Number(vp.scrollTop) || 0;
+ } catch (e) {
+ prevScrollTop = 0;
+ }
+ state.scrollRestore = {
+ el: vp,
+ scrollTop: prevScrollTop,
+ behavior: prevBehavior,
+ behaviorPriority: prevBehaviorPriority,
+ hadStyleAttr: hadStyleAttr
+ };
+
+ try {
+ vp.style.setProperty("scroll-behavior", "auto", "important");
+ } catch (e) {
+ debug("could not force scroll-behavior:auto", e);
+ }
+
+ var target = Math.min(controlVisibleTarget, Math.max(1, roots.length - 1));
+ var anchorIndex = Math.max(0, roots.length - 1 - target);
+
+ function visibleCounts() {
+ var vpRect = rectOf(vp);
+ var visible = 0;
+ var prior = 0;
+ if (vpRect) {
+ for (var i = 0; i < roots.length; i++) {
+ if (rectsIntersect(rectOf(roots[i]), vpRect)) {
+ visible += 1;
+ if (i < roots.length - 1) {
+ prior += 1;
+ }
+ }
+ }
+ }
+ return { visible: visible, prior: prior };
+ }
+
+ var attempts = 0;
+ var seen = visibleCounts();
+ try {
+ var vpRect0 = rectOf(vp);
+ var anchorRect = rectOf(roots[anchorIndex]);
+ if (vpRect0 && anchorRect) {
+ vp.scrollTop = Number(vp.scrollTop) + (anchorRect.top - vpRect0.top);
+ }
+ } catch (e) {
+ debug("initial scroll assignment failed", e);
+ }
+ seen = visibleCounts();
+
+ // Walk upwards until enough prior turns are on screen or the top is reached. Bounded
+ // iterations: a loop that cannot terminate would hang the measured window, and reporting
+ // "could not reach the target" is a usable result while a hang is not.
+ while (seen.prior < target && attempts < 16) {
+ attempts += 1;
+ var before = 0;
+ try {
+ before = Number(vp.scrollTop) || 0;
+ var step = Math.max(64, Math.floor((Number(vp.clientHeight) || 400) / 2));
+ vp.scrollTop = Math.max(0, before - step);
+ } catch (e) {
+ break;
+ }
+ var after = 0;
+ try {
+ after = Number(vp.scrollTop) || 0;
+ } catch (e) {
+ after = before;
+ }
+ seen = visibleCounts();
+ if (after === before) {
+ break; // already at the top
+ }
+ }
+
+ try {
+ if (prevBehavior === "") {
+ vp.style.removeProperty("scroll-behavior");
+ } else {
+ vp.style.setProperty("scroll-behavior", prevBehavior, prevBehaviorPriority);
+ }
+ if (!hadStyleAttr) {
+ var left = String(vp.getAttribute("style") || "").trim();
+ if (left === "") {
+ vp.removeAttribute("style");
+ }
+ }
+ } catch (e) {
+ debug("could not restore scroll-behavior", e);
+ }
+
+ gauges.controlVisibleMessages = seen.visible;
+ gauges.controlVisiblePriorMessages = seen.prior;
+
+ if (seen.prior < target) {
+ return result(
+ false,
+ "scrolled to the top of the thread and only " + seen.prior + " prior message " +
+ "root(s) intersect the viewport, target was " + target + "; the control is not " +
+ "in the state it claims",
+ seen.visible
+ );
+ }
+ return result(
+ true,
+ seen.visible + " message root(s) intersect the viewport, " + seen.prior + " of them " +
+ "prior turns (target " + target + "); DOM unchanged, scroll position changed",
+ seen.visible
+ );
+ }
+
+ function revertG() {
+ var rec = state.scrollRestore;
+ if (!rec) {
+ return revertResult(true, "arm G was never applied");
+ }
+ state.scrollRestore = null;
+ try {
+ rec.el.style.setProperty("scroll-behavior", "auto", "important");
+ rec.el.scrollTop = rec.scrollTop;
+ if (rec.behavior === "") {
+ rec.el.style.removeProperty("scroll-behavior");
+ } else {
+ rec.el.style.setProperty("scroll-behavior", rec.behavior, rec.behaviorPriority);
+ }
+ if (!rec.hadStyleAttr) {
+ var left = String(rec.el.getAttribute("style") || "").trim();
+ if (left === "") {
+ rec.el.removeAttribute("style");
+ }
+ }
+ return revertResult(true, "scroll position restored to " + rec.scrollTop + "px");
+ } catch (e) {
+ return revertResult(false, "could not restore the scroll position: " + e);
+ }
+ }
+
+ // ------------------------------------------------------------------------------------
+ // apply / revert
+ // ------------------------------------------------------------------------------------
+
+ function apply(armId) {
+ var id;
+ try {
+ id = String(armId).toUpperCase();
+ } catch (e) {
+ return result(false, "arm id is not a string", 0);
+ }
+ if (ARM_IDS.indexOf(id) === -1) {
+ return result(false, "unknown arm id " + JSON.stringify(id), 0);
+ }
+ if (Object.prototype.hasOwnProperty.call(unavailable, id)) {
+ return result(false, unavailable[id], 0);
+ }
+ if (Object.prototype.hasOwnProperty.call(state.applied, id) && id !== "F") {
+ // `applied` means "this call applied it". Arms are applied once per measured window
+ // by design, so a second call is a no-op and says so rather than re-marking elements
+ // and inflating the counters.
+ return result(
+ false,
+ "arm " + id + " was already applied at " + state.applied[id].at +
+ "; arms are applied once per measured window by design",
+ state.applied[id].affected
+ );
+ }
+
+ var out;
+ try {
+ if (id === "A") {
+ out = applyA();
+ } else if (id === "B") {
+ out = applyB();
+ } else if (id === "C") {
+ out = applyC();
+ } else if (id === "D") {
+ out = result(
+ true,
+ "arm D is a preboot arm and has been active since injection; " +
+ counters.suppressedViewportObserves + " viewport observe call(s) suppressed " +
+ "so far out of " + counters.observeCallsTotal + " total",
+ counters.suppressedViewportObserves
+ );
+ } else if (id === "E") {
+ out = result(
+ true,
+ "arm E is a preboot arm and has been active since injection; " +
+ counters.suppressedStabilizerSets + " stabilizer write(s) suppressed so far " +
+ "out of " + counters.customPropSets + " custom property writes",
+ counters.suppressedStabilizerSets
+ );
+ } else if (id === "F") {
+ out = applyF();
+ } else {
+ out = applyG();
+ }
+ } catch (e) {
+ // An arm that throws has to be reported, not propagated: the app is mid-stream and an
+ // exception here would end the run with no data at all.
+ return result(false, "arm " + id + " threw while applying: " + e, 0);
+ }
+
+ if (out.applied) {
+ counters.armsApplied += 1;
+ state.applied[id] = { at: nowStamp(), affected: out.affected, reason: out.reason };
+ }
+ debug("apply", id, out);
+ return out;
+ }
+
+ function revert(armId) {
+ var id;
+ try {
+ id = String(armId).toUpperCase();
+ } catch (e) {
+ return revertResult(false, "arm id is not a string");
+ }
+ if (ARM_IDS.indexOf(id) === -1) {
+ return revertResult(false, "unknown arm id " + JSON.stringify(id));
+ }
+
+ var out;
+ try {
+ if (id === "A" || id === "B" || id === "C") {
+ removeStyleSheet(id);
+ // The inline and marker ledgers are global rather than per arm: a run applies one
+ // arm, and unwinding everything is the behaviour least likely to leave a stray
+ // !important behind on a page that is about to be measured again.
+ restoreInline();
+ unmarkAll();
+ out = revertResult(true, "stylesheet removed, inline properties and markers restored");
+ } else if (id === "D") {
+ var hadSuppressed = counters.suppressedViewportObserves > 0;
+ if (state.originals.observe && W.MutationObserver) {
+ try {
+ Object.defineProperty(W.MutationObserver.prototype, "observe", {
+ value: state.originals.observe,
+ writable: true,
+ enumerable: false,
+ configurable: true
+ });
+ state.installed.D = false;
+ } catch (e2) {
+ /* leave it patched rather than throw */
+ }
+ }
+ out = hadSuppressed
+ ? revertResult(
+ false,
+ "the original observe() is restored for FUTURE calls, but the " +
+ counters.suppressedViewportObserves + " already-suppressed observe " +
+ "call(s) cannot be installed retroactively; the autoscroll observer " +
+ "for this thread stays detached for the life of the page"
+ )
+ : revertResult(true, "original observe() restored; nothing had been suppressed");
+ } else if (id === "E") {
+ if (state.originals.setProperty && W.CSSStyleDeclaration) {
+ try {
+ Object.defineProperty(W.CSSStyleDeclaration.prototype, "setProperty", {
+ value: state.originals.setProperty,
+ writable: true,
+ enumerable: false,
+ configurable: true
+ });
+ state.installed.E = false;
+ } catch (e3) {
+ /* leave it patched rather than throw */
+ }
+ }
+ out = revertResult(
+ true,
+ "original setProperty() restored; the " + counters.suppressedStabilizerSets +
+ " suppressed write(s) are lost, and " + STABILIZER_PROP + " stays unset " +
+ "until the app writes it again"
+ );
+ } else if (id === "F") {
+ out = revertF();
+ } else {
+ out = revertG();
+ }
+ } catch (e) {
+ return revertResult(false, "arm " + id + " threw while reverting: " + e);
+ }
+
+ if (out.reverted) {
+ counters.armsReverted += 1;
+ try {
+ delete state.applied[id];
+ } catch (e4) {
+ /* nothing to do */
+ }
+ }
+ debug("revert", id, out);
+ return out;
+ }
+
+ // ------------------------------------------------------------------------------------
+ // Install the preboot arms, then publish
+ // ------------------------------------------------------------------------------------
+
+ if (armedPreboot.indexOf("D") !== -1) {
+ installD();
+ } else {
+ markUnavailable(
+ "D",
+ "not armed at injection time: D is a preboot arm and must be listed in " +
+ "__sbArmConfig.preboot. It is deliberately NOT installed, because an inactive " +
+ "wrapper on MutationObserver.prototype.observe still costs a call frame per " +
+ "observe and would perturb the control run"
+ );
+ }
+
+ if (armedPreboot.indexOf("E") !== -1) {
+ installE();
+ } else {
+ markUnavailable(
+ "E",
+ "not armed at injection time: E is a preboot arm and must be listed in " +
+ "__sbArmConfig.preboot. It is deliberately NOT installed, because an inactive " +
+ "wrapper on CSSStyleDeclaration.prototype.setProperty would cost a call frame on " +
+ "every style write in the control run"
+ );
+ }
+
+ if (armedPreboot.indexOf("F") !== -1) {
+ installF();
+ } else {
+ markUnavailable(
+ "F",
+ "not armed at injection time: F is a preboot arm and must be listed in " +
+ "__sbArmConfig.preboot. It is deliberately NOT installed, because wrapping " +
+ "MessageChannel changes React's scheduler path even when the freeze is off"
+ );
+ }
+
+ // Feature checks for the runtime arms. These are capability questions about the browser, not
+ // about the page, so a false here is UNAVAILABLE and never a zero difference.
+ if (!doc) {
+ markUnavailable("A", "no document");
+ markUnavailable("B", "no document");
+ markUnavailable("C", "no document");
+ markUnavailable("G", "no document");
+ } else {
+ if (!supportsProp("content-visibility", "auto")) {
+ markUnavailable(
+ "B",
+ "this browser does not support content-visibility:auto, so the arm cannot be run " +
+ "here at all"
+ );
+ } else if (!supportsProp("contain-intrinsic-size", "auto 200px")) {
+ markUnavailable(
+ "B",
+ "this browser does not support contain-intrinsic-size with the auto keyword; " +
+ "running content-visibility:auto without it would collapse the thread height " +
+ "and change the page instead of ablating it"
+ );
+ }
+ }
+
+ var available = [];
+ for (var ai = 0; ai < ARM_IDS.length; ai++) {
+ if (!Object.prototype.hasOwnProperty.call(unavailable, ARM_IDS[ai])) {
+ available.push(ARM_IDS[ai]);
+ }
+ }
+
+ var api = {
+ version: VERSION,
+ available: available,
+ unavailable: unavailable,
+ armedPreboot: armedPreboot,
+ apply: apply,
+ revert: revert,
+ potency: potency,
+ counts: counts,
+ digest: digest,
+ diffKeys: diffKeys,
+ // Beyond the required API, additive and safe to ignore.
+ diffDetail: diffDetail,
+ armIds: ARM_IDS.slice(0),
+ prebootArmIds: ["D", "E", "F"],
+ domChangingArmIds: ["F"],
+ markerAttribute: MARKER_ATTR,
+ canonicalFormatVersion: CANONICAL_FORMAT_VERSION,
+ hashAlgorithm: "fnv1a32 (non-cryptographic change detector, not a security boundary)",
+ installedAt: nowStamp(),
+ controlVisibleTarget: controlVisibleTarget,
+ selectors: {
+ viewport: VIEWPORT_SELECTOR,
+ message: MESSAGE_SELECTOR,
+ codeBlock: CODE_BLOCK_SELECTOR,
+ running: RUNNING_SELECTOR,
+ stabilizerProperty: STABILIZER_PROP
+ },
+ appliedArms: function () {
+ var out = [];
+ for (var id in state.applied) {
+ if (Object.prototype.hasOwnProperty.call(state.applied, id)) {
+ out.push(id);
+ }
+ }
+ out.sort();
+ return out;
+ }
+ };
+
+ try {
+ W.__sbArms = api;
+ } catch (e) {
+ /* if we cannot publish, the driver will see __sbArms undefined, which is the honest
+ signal that no arm can be run on this page */
+ }
+
+ debug("installed", VERSION, "available:", available, "unavailable:", unavailable);
+})();
diff --git a/tests/studio/studiobench/arms/knobs.py b/tests/studio/studiobench/arms/knobs.py
new file mode 100644
index 00000000000..b4cae7f04f1
--- /dev/null
+++ b/tests/studio/studiobench/arms/knobs.py
@@ -0,0 +1,362 @@
+# 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 seven runtime-injected knobs, as a decision table: which knob removes the slope names the fix.
+
+Every arm here runs on the SHIPPED PRODUCTION BUILD through `add_init_script`. Nothing is
+compiled, nothing is patched on disk, and an external tester with a laptop and a Studio install
+can run the whole ablation plane. That constraint is not a convenience. An ablation that requires
+a custom build is an ablation that will be run once, by the person who wrote it, on the machine
+where the problem does not reproduce.
+
+THE DECISION TABLE. These are not seven ways of saying "it got faster". Each knob removes a
+different layer of the pipeline, and the FIRST one that removes the slope names the layer the
+cost lives in:
+
+ A visibility:hidden on completed messages
+ removes paint and raster, keeps layout, DOM and React
+ -> if the slope goes: the cost is painting retained messages
+ B content-visibility:auto + contain-intrinsic-size (undoing the shipped
+ `.aui-thread-root [data-streamdown="code-block"]` override in index.css, which forces
+ `content-visibility: visible !important`)
+ removes off-screen style, layout and paint
+ -> if the slope goes: the cost is off-screen style and layout. Note what the shipped comment
+ above that rule now says: the "thread length is bounded" justification has already been
+ disproved by #8977, the rule is kept for a height flicker and a WebKit find-in-page
+ hazard, and containment on the message roots was measured as no help, with the claim that
+ what grows with thread length is inherited-property style recalc rather than layout. That
+ last sentence is arm E's hypothesis, already asserted upstream. This ladder is what
+ confirms or refutes it, and a positive B is not permission to delete the rule
+ C display:none on completed messages
+ also removes layout geometry and the sibling from the layout sequence
+ -> if the slope goes here but not at A or B: the cost is layout geometry, and the fix is to
+ virtualise the list
+ D detach the autoscroll subtree observer
+ removes forced synchronous layout per mutation
+ -> if the slope goes: the cost is the observer reading scrollHeight on every streamed
+ character, at a price proportional to the whole thread
+ E neutralise --aui-scroll-stabilizer
+ removes inherited-custom-property subtree style invalidation
+ -> if the slope goes: writing one inherited custom property on the scroll container is
+ invalidating style for every descendant, per mutation
+ F freeze React but keep the DOM
+ removes React subscriptions and reconciliation
+ -> if the slope goes: the cost is fibre bookkeeping, not DOM. Note this arm is DOM-CHANGING
+ (the stream stops rendering while frozen) so it is only ever an upper bound
+ G CONTROL: identical DOM, thread scrolled so prior turns are IN the viewport
+ -> if the slope is the SAME as the unscrolled case, off-screen occupancy is not the
+ mechanism, and A, B and C should all have read null. If G disagrees with them, one of
+ them did not fire
+
+G is the arm that catches the harness rather than the app, which is why it is in the list rather
+than in a comment. A, B and C all rest on the assumption that the retained messages are OFF
+screen; if the thread is not actually scrolled where the harness thinks it is, all three read
+null for a reason that has nothing to do with rendering.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Iterable, Mapping, Sequence
+
+from .manifest import Arm, DeclaredDiff, Invariance, PotencyCounter
+
+KNOBS_JS_PATH = Path(__file__).with_name("knobs.js")
+
+#: Knobs that must be installed BEFORE the app boots, because they patch a prototype the app is
+#: about to use. Installing one of these after boot measures nothing: React has already captured
+#: its scheduler port and the autoscroll hook has already called observe().
+PREBOOT_ARM_IDS: frozenset[str] = frozenset({"D", "E", "F"})
+
+#: Knobs applied at the start of a measured window, over the messages that exist then.
+RUNTIME_ARM_IDS: frozenset[str] = frozenset({"A", "B", "C", "G"})
+
+
+ARM_A = Arm(
+ arm_id = "A",
+ title = "visibility:hidden on completed messages",
+ mechanism = "paint and raster of retained messages",
+ invariance = Invariance.EXACT,
+ potency = PotencyCounter(
+ name = "visibilityHiddenConfirmed",
+ min_delta = 1,
+ direction = "increase",
+ description = (
+ "message roots whose COMPUTED visibility is hidden. Computed, not the rule we "
+ "injected: a rule that lost the cascade is a knob that did not fire, and counting our "
+ "own stylesheet would report it as fired"
+ ),
+ ),
+ implies_fix = (
+ "the cost is painting and rasterising retained messages. Fix by not painting what is off "
+ "screen: containment, or a virtualised list"
+ ),
+ notes = (
+ "the DOM is untouched (one injected stylesheet, no element attributes change), so this "
+ "arm claims EXACT and its cost is a point estimate of paint"
+ ),
+)
+
+ARM_B = Arm(
+ arm_id = "B",
+ title = "content-visibility:auto with contain-intrinsic-size",
+ mechanism = "off-screen style, layout and paint",
+ invariance = Invariance.EQUIVALENT,
+ declared_diff = DeclaredDiff(
+ normaliser = "skip_style_attribute",
+ keys = ("attr:style",),
+ rationale = (
+ "this arm writes content-visibility and contain-intrinsic-size INLINE on each "
+ "completed message root, because the intrinsic size has to be that element's own "
+ "measured height. The style attribute is therefore expected to differ and nothing "
+ "else is. If any other attribute or any text differs, the arm is voided. The key is "
+ "`attr:style` and not `style` because knobs.js namespaces attribute keys against the "
+ "structural ones, so an attribute literally named `text` cannot collide with the "
+ "text key. Getting this string wrong voids the arm on every run, which is the "
+ "correct failure direction but an expensive one to debug"
+ ),
+ ),
+ potency = PotencyCounter(
+ name = "contentVisibilityAutoConfirmed",
+ min_delta = 1,
+ direction = "increase",
+ description = (
+ "elements whose computed content-visibility is auto. index.css:2537 sets `visible` "
+ "with !important, so this counter is also the check that the undo actually won"
+ ),
+ ),
+ implies_fix = (
+ "the cost is style and layout of off-screen content. This does NOT license removing the "
+ "shipped override. Read the comment above the rule in index.css before acting on a "
+ "positive result here: the original justification (thread length is bounded) has already "
+ "been disproved by #8977, and the rule is now kept for a visible height flicker during "
+ "stream finalisation plus a WebKit find-in-page hazard (webkit.org/b/283846, no in-thread "
+ "search to fall back on). A win from this arm means the cost is real and needs a "
+ "DIFFERENT mechanism to remove it"
+ ),
+ notes = (
+ "two things this arm cannot see, both stated here because they cannot be stated in the "
+ "digest. First, the canonical serialisation walks message roots and records descendant "
+ "code-block and span COUNTS, not descendant attributes, so the inline style this arm "
+ "writes on code blocks is invisible to the invariance check and only the message-root "
+ "style is actually policed. Second, the shipped override lives inside `@layer utilities`, "
+ "and an important declaration in a layer beats an important unlayered one at any "
+ "specificity, so the undo has to be emitted into the same layer (or inline) and then "
+ "VERIFIED with getComputedStyle. The potency counter is that verification"
+ ),
+)
+
+ARM_C = Arm(
+ arm_id = "C",
+ title = "display:none on completed messages",
+ mechanism = "layout geometry and the sibling's place in the layout sequence",
+ invariance = Invariance.EXACT,
+ potency = PotencyCounter(
+ name = "displayNoneConfirmed",
+ min_delta = 1,
+ direction = "increase",
+ description = "message roots whose computed display is none",
+ ),
+ implies_fix = (
+ "the cost is layout geometry of retained messages. Fix by virtualising the message list; "
+ "thread.tsx:1741 renders a bare ThreadPrimitive.Messages and nothing in the thread is "
+ "virtualised, although the app already depends on @tanstack/react-virtual"
+ ),
+ notes = (
+ "C subsumes A and B for completed messages, which is why the ladder places it after both "
+ "rather than treating the three as independent"
+ ),
+)
+
+ARM_D = Arm(
+ arm_id = "D",
+ title = "detach the autoscroll subtree observer",
+ mechanism = "forced synchronous layout inside the autoscroll MutationObserver",
+ invariance = Invariance.EXACT,
+ potency = PotencyCounter(
+ name = "suppressedViewportObserves",
+ min_delta = 1,
+ direction = "increase",
+ description = (
+ "observe() calls no-opped. Matched on the target carrying aui-stream-viewport OR an "
+ "attributeFilter containing aria-expanded, which is unique to this observer among the "
+ "nine in the app"
+ ),
+ ),
+ implies_fix = (
+ "the cost is the autoscroll observer: it reads scrollHeight, writes an inherited custom "
+ "property and calls scrollTo on every streamed character, at a price proportional to the "
+ "whole thread. Fix at use-intent-aware-autoscroll.tsx:435,466,487"
+ ),
+ notes = (
+ "pre-boot: the hook calls observe() during mount, so a patch installed after boot "
+ "suppresses nothing and reads as NOT RUN, correctly"
+ ),
+)
+
+ARM_E = Arm(
+ arm_id = "E",
+ title = "neutralise --aui-scroll-stabilizer",
+ mechanism = "subtree style invalidation from writing an inherited custom property",
+ invariance = Invariance.EXACT,
+ potency = PotencyCounter(
+ name = "suppressedStabilizerSets",
+ min_delta = 1,
+ direction = "increase",
+ description = "setProperty calls for --aui-scroll-stabilizer that were skipped",
+ ),
+ implies_fix = (
+ "the cost is style invalidation of every descendant caused by writing one inherited "
+ "custom property on the scroll container per mutation. Fix at "
+ "use-intent-aware-autoscroll.tsx:466, or stop the property being inherited"
+ ),
+ notes = (
+ "E is a strict subset of D: D removes the callback that does this write, among other "
+ "things. That is why the ladder puts E after D and never quotes the two together"
+ ),
+)
+
+ARM_F = Arm(
+ arm_id = "F",
+ title = "freeze React, keep the DOM",
+ mechanism = "React subscriptions and reconciliation",
+ invariance = Invariance.DOM_CHANGING,
+ potency = PotencyCounter(
+ name = "suppressedSchedulerCallbacks",
+ min_delta = 1,
+ direction = "increase",
+ description = (
+ "scheduler callbacks not delivered. If React never used MessageChannel on this "
+ "engine, capturedSchedulerPorts is 0 and the arm reads NOT RUN rather than no effect"
+ ),
+ ),
+ implies_fix = (
+ "the cost is React fibre bookkeeping rather than DOM. Fix by cutting the number of fibres "
+ "reached per update, which memo does not do: bailoutOnAlreadyFinishedWork returns null "
+ "only when childLanes is clear, so an update anywhere in the subtree still clones one "
+ "work-in-progress fibre per sibling"
+ ),
+ notes = (
+ "DOM-CHANGING by construction: while React is frozen the stream stops rendering, so the "
+ "two sides are not showing the same content and this arm can only ever bound the "
+ "mechanism from above. That is still worth having, because a small bound is a strong "
+ "negative result"
+ ),
+)
+
+ARM_G = Arm(
+ arm_id = "G",
+ title = "CONTROL: identical DOM, prior turns scrolled INTO the viewport",
+ mechanism = "none; this arm changes only the scroll position",
+ invariance = Invariance.EXACT,
+ potency = PotencyCounter(
+ name = "controlVisibleMessages",
+ min_delta = 1,
+ direction = "increase",
+ description = "message roots intersecting the viewport rect after the scroll",
+ ),
+ implies_fix = (
+ "not a fix, a check on the other arms. If bringing the retained turns ON screen does not "
+ "change the cost, then off-screen occupancy was never the mechanism and A, B and C should "
+ "all read null. If G disagrees with them, one of them did not fire"
+ ),
+ kind = "control",
+)
+
+RUNTIME_ARMS: tuple[Arm, ...] = (ARM_A, ARM_B, ARM_C, ARM_D, ARM_E, ARM_F, ARM_G)
+ARM_BY_ID: Mapping[str, Arm] = {arm.arm_id: arm for arm in RUNTIME_ARMS}
+
+
+def load_knobs_js() -> str:
+ """Read the injected knob implementation from disk."""
+
+ return KNOBS_JS_PATH.read_text(encoding = "utf-8")
+
+
+def config_init_script(
+ arm_ids: Iterable[str],
+ *,
+ debug: bool = False,
+ control_visible_target: int = 3,
+) -> str:
+ """The config script that must be injected BEFORE knobs.js.
+
+ Only the pre-boot arms named here get their prototype patches installed. An installed but
+ inactive patch is not free: it adds a call frame to `observe`, to `setProperty` and to every
+ scheduler delivery, and it would sit in the control cell too, which is precisely the kind of
+ quiet, treatment-correlated overhead this whole design exists to keep out.
+ """
+
+ requested = sorted(set(arm_ids))
+ unknown = [arm_id for arm_id in requested if arm_id not in ARM_BY_ID]
+ if unknown:
+ raise KeyError(f"unknown arm ids {unknown}; known ids are {sorted(ARM_BY_ID)}")
+ preboot = [arm_id for arm_id in requested if arm_id in PREBOOT_ARM_IDS]
+ config = {
+ "preboot": preboot,
+ "requested": requested,
+ "debug": bool(debug),
+ "controlVisibleTarget": int(control_visible_target),
+ }
+ return f"window.__sbArmConfig = {json.dumps(config, sort_keys = True)};"
+
+
+def init_scripts_for(
+ arm_ids: Iterable[str],
+ *,
+ debug: bool = False,
+ control_visible_target: int = 3,
+ extra_scripts: Sequence[str] = (),
+) -> list[str]:
+ """The ordered list of init scripts for one cell. Order is load-bearing.
+
+ The config must exist before knobs.js reads it, and knobs.js must be installed before the app
+ bundle runs. `add_init_script` preserves insertion order, so this list is handed over as-is.
+ """
+
+ return [
+ config_init_script(arm_ids, debug = debug, control_visible_target = control_visible_target),
+ load_knobs_js(),
+ *extra_scripts,
+ ]
+
+
+def split_arms(arm_ids: Iterable[str]) -> tuple[list[str], list[str]]:
+ """Split a rung's arms into (pre-boot, apply-at-window-start)."""
+
+ requested = sorted(set(arm_ids))
+ return (
+ [a for a in requested if a in PREBOOT_ARM_IDS],
+ [a for a in requested if a in RUNTIME_ARM_IDS],
+ )
+
+
+@dataclass(frozen = True)
+class DecisionRow:
+ arm_id: str
+ removes: str
+ if_slope_goes: str
+
+
+def decision_table() -> list[DecisionRow]:
+ """The table the report prints. One row per knob, read as a diagnosis."""
+
+ return [DecisionRow(arm.arm_id, arm.mechanism, arm.implies_fix) for arm in RUNTIME_ARMS]
+
+
+def render_decision_table() -> str:
+ lines = [
+ "ABLATION DECISION TABLE (which knob removes the slope names the fix)",
+ "",
+ ]
+ for row in decision_table():
+ lines.append(f" {row.arm_id} removes: {row.removes}")
+ lines.append(f" if the slope goes here: {row.if_slope_goes}")
+ lines.append("")
+ return "\n".join(lines).rstrip() + "\n"
+
+
+def arms_json() -> list[dict[str, Any]]:
+ return [arm.to_json() for arm in RUNTIME_ARMS]
diff --git a/tests/studio/studiobench/arms/ladder.py b/tests/studio/studiobench/arms/ladder.py
new file mode 100644
index 00000000000..8fbed1c2868
--- /dev/null
+++ b/tests/studio/studiobench/arms/ladder.py
@@ -0,0 +1,605 @@
+# 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 telescoping ladder: how a correlation becomes a cause, and where the risk goes.
+
+A set of independent on/off ablations produces a set of differences that do not add up to the
+total, and the gap between them is a residual. A residual is not a measurement of anything. It is
+the part nobody can name, and it grows every time an arm is added, because overlapping arms
+double-count the same work.
+
+A TELESCOPING LADDER removes the residual by construction. Arms are nested,
+
+ A0 (shipping) superset A1 superset ... superset An (floor)
+
+with adjacent pairs differing by exactly one mechanism. Then
+
+ cost(A0) - cost(An) = sum of the adjacent differences
+
+IDENTICALLY. Not approximately, not up to a residual: the interior terms cancel algebraically, so
+the identity is a property of the arithmetic and any failure of it is a failure of MEASUREMENT
+(a missing cell, a voided arm) that the code reports rather than absorbs.
+
+THE RISK DOES NOT VANISH, IT MOVES. What was "an unnamed remainder" becomes "a possibly
+mislabelled step". That is a strict improvement for one reason: a step is testable. If step 3 is
+labelled "layout geometry" and someone doubts it, they can attack step 3 directly with a
+different knob. Nobody can attack a residual.
+
+TWO RULES, ENFORCED IN CODE:
+
+ 1. NO ARM IS EVER QUOTED ALONE. `LadderRoute.quote_arm()` raises. A single arm's absolute cost
+ is not a measurement of a mechanism; it is a measurement of that arm's whole configuration
+ against nothing. Only adjacent differences are quotable.
+ 2. TWO LADDERS MUST REACH THE SAME FLOOR BY DIFFERENT ROUTES. Where they disagree about the
+ same mechanism, that disagreement is the INTERACTION TERM and it is reported as such. It is
+ never averaged away: two routes disagreeing by 3 ms means the mechanisms are not additive,
+ which is a finding, and the mean of the two hides exactly that finding.
+
+FUSED STEPS. Some mechanisms cannot be separated by any knob available at runtime: `display:none`
+removes layout geometry AND sibling count in one move, and there is no knob that removes one
+without the other. A step may therefore declare more than one mechanism ONLY when it is marked
+`fused` with a reason, and the report prints it as fused. That is honest; pretending it is one
+mechanism is how a step gets mislabelled, which is the one risk this design accepts.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Iterable, Mapping, Sequence
+
+from ..scoring.schema import Measure
+from .manifest import ArmOutcome, ArmStatus
+
+#: The named mechanisms this ladder can remove. A step must name mechanisms from this set, so a
+#: typo becomes an error rather than a new, unexplained row in the report.
+MECHANISMS: tuple[str, ...] = (
+ "paint_raster",
+ "offscreen_style_layout",
+ "layout_geometry",
+ "sibling_count",
+ "autoscroll_forced_layout",
+ "stabilizer_style_invalidation",
+ "react_reconciliation",
+)
+
+MECHANISM_FIX: Mapping[str, str] = {
+ "paint_raster": (
+ "the cost is painting and rasterising completed messages. Fix: stop painting what is not "
+ "on screen (containment, or a virtualised list)"
+ ),
+ "offscreen_style_layout": (
+ "the cost is style and layout of off-screen content. The obvious fix, content-visibility: "
+ "auto, is NOT available: the shipped override that disables it is kept for a height "
+ "flicker during stream finalisation and because WebKit below Safari 26 cannot find "
+ "skipped content with find-in-page and Studio has no in-thread search. So a win here "
+ "names the cost and still needs a different mechanism to remove it"
+ ),
+ "layout_geometry": (
+ "the cost is layout geometry of retained messages. Fix: virtualise the message list; "
+ "thread.tsx:1741 renders a bare ThreadPrimitive.Messages and nothing is virtualised"
+ ),
+ "sibling_count": (
+ "the cost is proportional to the number of siblings React must walk. Fix: reduce the flat "
+ "sibling count (grouping, windowing) or stop the parent update that forces the walk"
+ ),
+ "autoscroll_forced_layout": (
+ "the cost is forced synchronous layout inside the autoscroll MutationObserver. Fix: stop "
+ "reading scrollHeight in the observer callback, or scope the observer off the subtree"
+ ),
+ "stabilizer_style_invalidation": (
+ "the cost is style invalidation of the whole subtree from writing an inherited custom "
+ "property. Fix: stop writing --aui-scroll-stabilizer on the scroll container per "
+ "mutation. Note this is the mechanism the shipped index.css comment ALREADY names -- it "
+ "says what grows with thread length is inherited-property style recalc, not layout -- so "
+ "a large step here confirms a claim that is currently asserted without a number next to "
+ "it, and a small one contradicts it"
+ ),
+ "react_reconciliation": (
+ "the cost is React subscriptions and reconciliation, not DOM. Fix: cut the update rate or "
+ "the fibre count reached per update; memo does not help, because bailout still clones one "
+ "work-in-progress fibre per sibling when childLanes is set"
+ ),
+}
+
+
+class LadderError(AssertionError):
+ """Raised when a ladder is malformed or used in a way the design forbids."""
+
+
+def arms_key(arms: Iterable[str]) -> str:
+ """Canonical key for a set of simultaneously applied arms."""
+
+ ordered = sorted(set(arms))
+ return "+".join(ordered) if ordered else "shipping"
+
+
+@dataclass(frozen = True)
+class Step:
+ """One rung-to-rung transition: which arms are added, which mechanisms that removes."""
+
+ arms_before: frozenset[str]
+ arms_after: frozenset[str]
+ mechanisms: tuple[str, ...]
+ fused: bool = False
+ fused_reason: str = ""
+
+ def __post_init__(self) -> None:
+ unknown = [m for m in self.mechanisms if m not in MECHANISMS]
+ if unknown:
+ raise LadderError(f"unknown mechanisms {unknown}; add them to MECHANISMS")
+ if not self.mechanisms:
+ raise LadderError("a step must remove at least one named mechanism")
+ if len(self.mechanisms) > 1 and not self.fused:
+ raise LadderError(
+ f"step {arms_key(self.arms_before)} -> {arms_key(self.arms_after)} removes "
+ f"{len(self.mechanisms)} mechanisms but is not marked fused. Adjacent pairs "
+ "differ by exactly one mechanism unless no available knob can separate them, in "
+ "which case say so explicitly"
+ )
+ if self.fused and not self.fused_reason:
+ raise LadderError("a fused step must say why the mechanisms cannot be separated")
+ if not self.arms_before < self.arms_after:
+ raise LadderError(
+ f"a ladder step must ADD arms: {arms_key(self.arms_before)} is not a strict "
+ f"subset of {arms_key(self.arms_after)}. A telescoping ladder is nested; two "
+ "arms that merely differ are two experiments, not a ladder"
+ )
+
+ @property
+ def label(self) -> str:
+ return f"{arms_key(self.arms_before)} -> {arms_key(self.arms_after)}"
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "arms_before": sorted(self.arms_before),
+ "arms_after": sorted(self.arms_after),
+ "label": self.label,
+ "mechanisms": list(self.mechanisms),
+ "fused": bool(self.fused),
+ "fused_reason": self.fused_reason,
+ }
+
+
+@dataclass
+class StepResult:
+ """One adjacent difference, which is the only kind of number a ladder may quote."""
+
+ step: Step
+ difference: Measure
+ quotable: bool
+ reason: str
+ bound_only: bool = False
+
+ def quote(self) -> str:
+ if not self.quotable:
+ return f"NOT QUOTABLE ({self.reason})"
+ prefix = "<= " if self.bound_only else ""
+ return f"{prefix}{self.difference.display()}"
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "step": self.step.to_json(),
+ "difference": self.difference.to_json(),
+ "quotable": bool(self.quotable),
+ "bound_only": bool(self.bound_only),
+ "reason": self.reason,
+ "quote": self.quote(),
+ "implies_fix": [MECHANISM_FIX[m] for m in self.step.mechanisms],
+ }
+
+
+@dataclass
+class LadderRoute:
+ """One nested route from the shipping build down to the floor."""
+
+ route_id: str
+ name: str
+ steps: tuple[Step, ...]
+
+ def __post_init__(self) -> None:
+ if not self.steps:
+ raise LadderError(f"{self.route_id}: a route needs at least one step")
+ for earlier, later in zip(self.steps, self.steps[1:]):
+ if earlier.arms_after != later.arms_before:
+ raise LadderError(
+ f"{self.route_id}: steps are not contiguous; "
+ f"{arms_key(earlier.arms_after)} != {arms_key(later.arms_before)}. A gap in "
+ "the chain reintroduces the residual this design exists to remove"
+ )
+ seen: list[str] = []
+ for step in self.steps:
+ for mechanism in step.mechanisms:
+ if mechanism in seen:
+ raise LadderError(
+ f"{self.route_id}: mechanism {mechanism!r} is removed twice. A mechanism "
+ "removed twice is counted twice, which is the residual wearing a hat"
+ )
+ seen.append(mechanism)
+
+ @property
+ def top(self) -> frozenset[str]:
+ return self.steps[0].arms_before
+
+ @property
+ def floor(self) -> frozenset[str]:
+ return self.steps[-1].arms_after
+
+ @property
+ def mechanisms(self) -> tuple[str, ...]:
+ return tuple(m for step in self.steps for m in step.mechanisms)
+
+ def quote_arm(self, arms: Iterable[str]) -> str:
+ """Refuse. An arm's absolute cost is not a measurement of a mechanism."""
+
+ raise LadderError(
+ f"refusing to quote arm {arms_key(arms)} on its own. A single arm's cost is the cost "
+ "of its whole configuration against nothing; only adjacent differences on this "
+ "ladder isolate a mechanism. Use differences()"
+ )
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "route_id": self.route_id,
+ "name": self.name,
+ "top": sorted(self.top),
+ "floor": sorted(self.floor),
+ "steps": [s.to_json() for s in self.steps],
+ }
+
+
+@dataclass
+class RouteResult:
+ """A whole route's differences, plus the telescoping identity check."""
+
+ route: LadderRoute
+ steps: list[StepResult] = field(default_factory = list)
+ total: Measure | None = None
+ sum_of_steps: Measure | None = None
+ residual_ms: float = 0.0
+ identity_holds: bool = False
+ identity_note: str = ""
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "route": self.route.to_json(),
+ "steps": [s.to_json() for s in self.steps],
+ "total": self.total.to_json() if self.total else None,
+ "sum_of_steps": self.sum_of_steps.to_json() if self.sum_of_steps else None,
+ "residual_ms": float(self.residual_ms),
+ "identity_holds": bool(self.identity_holds),
+ "identity_note": self.identity_note,
+ }
+
+
+def _cost_of(
+ outcomes: Mapping[str, ArmOutcome], arms: frozenset[str]
+) -> tuple[Measure | None, str, bool]:
+ """Look up one rung's cost, returning (measure, reason, bound_only)."""
+
+ key = arms_key(arms)
+ outcome = outcomes.get(key)
+ if outcome is None:
+ return None, f"no cell was recorded for rung {key}", False
+ if outcome.status is ArmStatus.VOIDED:
+ return None, f"rung {key} is VOIDED: {outcome.reason}", False
+ if outcome.status is ArmStatus.NOT_RUN:
+ return None, f"rung {key} reads NOT RUN: {outcome.reason}", False
+ if outcome.status is ArmStatus.UNAVAILABLE:
+ return None, f"rung {key} is unavailable: {outcome.reason}", False
+ if not outcome.cost.has_reading:
+ return None, f"rung {key} produced no reading: {outcome.cost.note}", False
+ return outcome.cost, "", outcome.status is ArmStatus.BOUND
+
+
+def differences(
+ route: LadderRoute,
+ outcomes: Mapping[str, ArmOutcome],
+ *,
+ detection_floor_ms: float | None = None,
+) -> RouteResult:
+ """Compute every adjacent difference on a route and check the telescoping identity.
+
+ `outcomes` is keyed by `arms_key(...)`, so the shipping rung is `"shipping"` and a rung with
+ arms C and D applied is `"C+D"`.
+
+ The identity is checked only when EVERY rung on the route produced a reading. A route with a
+ voided or missing rung has no identity to check, and reporting `residual = 0` for it would be
+ a claim about arithmetic that was never performed.
+ """
+
+ result = RouteResult(route = route)
+ all_readable = True
+
+ for step in route.steps:
+ before, before_reason, before_bound = _cost_of(outcomes, step.arms_before)
+ after, after_reason, after_bound = _cost_of(outcomes, step.arms_after)
+ if before is None or after is None:
+ all_readable = False
+ result.steps.append(
+ StepResult(
+ step = step,
+ difference = Measure.failed("ms", before_reason or after_reason),
+ quotable = False,
+ reason = before_reason or after_reason,
+ )
+ )
+ continue
+ delta = float(before.value) - float(after.value)
+ measure = Measure.read(delta, before.unit, floor = detection_floor_ms)
+ bound_only = before_bound or after_bound
+ result.steps.append(
+ StepResult(
+ step = step,
+ difference = measure,
+ quotable = True,
+ bound_only = bound_only,
+ reason = (
+ "one or both rungs are DOM-changing, so this difference bounds the mechanism"
+ if bound_only
+ else "both rungs held their invariance and fired"
+ ),
+ )
+ )
+
+ top, top_reason, _ = _cost_of(outcomes, route.top)
+ floor, floor_reason, _ = _cost_of(outcomes, route.floor)
+ if top is not None and floor is not None:
+ result.total = Measure.read(
+ float(top.value) - float(floor.value), top.unit, floor = detection_floor_ms
+ )
+ else:
+ result.total = Measure.failed("ms", top_reason or floor_reason)
+
+ readable_steps = [s for s in result.steps if s.quotable]
+ if readable_steps:
+ result.sum_of_steps = Measure.read(
+ sum(float(s.difference.value) for s in readable_steps),
+ readable_steps[0].difference.unit,
+ floor = detection_floor_ms,
+ )
+
+ if (
+ all_readable
+ and result.total is not None
+ and result.total.has_reading
+ and result.sum_of_steps
+ ):
+ result.residual_ms = float(result.total.value) - float(result.sum_of_steps.value)
+ # This is an arithmetic identity, not an empirical claim: the interior terms cancel. A
+ # non-zero residual here means a bug in this function, not a finding about the app.
+ result.identity_holds = abs(result.residual_ms) < 1e-9
+ result.identity_note = (
+ "top minus floor equals the sum of the adjacent differences, identically, because the "
+ "interior terms cancel. There is no residual to attribute"
+ if result.identity_holds
+ else (
+ f"residual {result.residual_ms:.9f} ms. This is an arithmetic identity, so a "
+ "non-zero value is a bug in the ladder code, not a property of the app"
+ )
+ )
+ else:
+ result.identity_holds = False
+ result.identity_note = (
+ "the identity was not checked: at least one rung on this route produced no usable "
+ "reading, so there is no complete chain to telescope"
+ )
+ return result
+
+
+@dataclass
+class InteractionTerm:
+ """One mechanism, measured on two routes, and how much they disagree."""
+
+ mechanism: str
+ route_a: str
+ route_b: str
+ value_a: Measure
+ value_b: Measure
+ disagreement_ms: float | None
+ disagreement_pct: float | None
+ note: str
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "mechanism": self.mechanism,
+ "route_a": self.route_a,
+ "route_b": self.route_b,
+ "value_a": self.value_a.to_json(),
+ "value_b": self.value_b.to_json(),
+ "disagreement_ms": self.disagreement_ms,
+ "disagreement_pct": self.disagreement_pct,
+ "note": self.note,
+ }
+
+
+def interaction_terms(
+ result_a: RouteResult,
+ result_b: RouteResult,
+ *,
+ detection_floor_ms: float | None = None,
+) -> list[InteractionTerm]:
+ """Compare two routes mechanism by mechanism. Disagreement is reported, never averaged.
+
+ Two routes reaching the same floor must agree about each mechanism if the mechanisms are
+ additive. Where they do not, the mechanisms interact: removing the autoscroll observer first
+ makes the paint step look cheaper, because some of that paint was being forced by the
+ observer. That is a real property of the system and it is the most interesting thing a
+ two-route ladder can find. Averaging the two numbers produces one that describes neither
+ route and hides the finding completely.
+ """
+
+ if result_a.route.floor != result_b.route.floor:
+ raise LadderError(
+ "the two routes do not reach the same floor: "
+ f"{arms_key(result_a.route.floor)} vs {arms_key(result_b.route.floor)}. Two ladders "
+ "that end somewhere different are not two routes to one answer"
+ )
+
+ def by_mechanism(result: RouteResult) -> dict[str, StepResult]:
+ out: dict[str, StepResult] = {}
+ for step_result in result.steps:
+ for mechanism in step_result.step.mechanisms:
+ out[mechanism] = step_result
+ return out
+
+ a_map, b_map = by_mechanism(result_a), by_mechanism(result_b)
+ terms: list[InteractionTerm] = []
+ for mechanism in sorted(set(a_map) & set(b_map)):
+ step_a, step_b = a_map[mechanism], b_map[mechanism]
+ value_a, value_b = step_a.difference, step_b.difference
+ if not (value_a.has_reading and value_b.has_reading):
+ terms.append(
+ InteractionTerm(
+ mechanism = mechanism,
+ route_a = result_a.route.route_id,
+ route_b = result_b.route.route_id,
+ value_a = value_a,
+ value_b = value_b,
+ disagreement_ms = None,
+ disagreement_pct = None,
+ note = "one route produced no reading for this mechanism",
+ )
+ )
+ continue
+ delta = float(value_a.value) - float(value_b.value)
+ base = max(abs(float(value_a.value)), abs(float(value_b.value)))
+ pct = (abs(delta) / base * 100.0) if base > 0 else None
+ if detection_floor_ms is not None and abs(delta) < detection_floor_ms:
+ note = (
+ "the two routes agree to within the detection floor, so the mechanisms are "
+ "additive as far as this instrument can tell"
+ )
+ elif step_a.step.fused or step_b.step.fused:
+ note = (
+ "the routes disagree and at least one side measures this mechanism inside a "
+ "fused step, so part of the disagreement may be the fusion rather than an "
+ "interaction"
+ )
+ else:
+ note = (
+ "the routes disagree beyond the detection floor: these mechanisms are not "
+ "additive. Reported as an interaction term, not averaged"
+ )
+ terms.append(
+ InteractionTerm(
+ mechanism = mechanism,
+ route_a = result_a.route.route_id,
+ route_b = result_b.route.route_id,
+ value_a = value_a,
+ value_b = value_b,
+ disagreement_ms = delta,
+ disagreement_pct = pct,
+ note = note,
+ )
+ )
+ return terms
+
+
+# ---------------------------------------------------------------------------------------
+# the two declared routes
+# ---------------------------------------------------------------------------------------
+
+_SHIPPING: frozenset[str] = frozenset()
+
+#: Route 1 walks down the rendering pipeline first: stop painting, then stop laying out
+#: off-screen, then stop occupying layout at all, and only then touch the observers and React.
+ROUTE_VISUAL_FIRST = LadderRoute(
+ route_id = "visual_first",
+ name = "paint, then off-screen layout, then geometry, then observers, then React",
+ steps = (
+ Step(
+ arms_before = _SHIPPING,
+ arms_after = frozenset({"A"}),
+ mechanisms = ("paint_raster",),
+ ),
+ Step(
+ arms_before = frozenset({"A"}),
+ arms_after = frozenset({"A", "B"}),
+ mechanisms = ("offscreen_style_layout",),
+ ),
+ Step(
+ arms_before = frozenset({"A", "B"}),
+ arms_after = frozenset({"A", "B", "C"}),
+ mechanisms = ("layout_geometry", "sibling_count"),
+ fused = True,
+ fused_reason = (
+ "display:none removes the element from layout AND from the sibling sequence React "
+ "walks. No runtime knob removes one without the other, so the step is quoted as "
+ "the pair rather than mislabelled as either one"
+ ),
+ ),
+ Step(
+ arms_before = frozenset({"A", "B", "C"}),
+ arms_after = frozenset({"A", "B", "C", "D"}),
+ mechanisms = ("autoscroll_forced_layout",),
+ ),
+ Step(
+ arms_before = frozenset({"A", "B", "C", "D"}),
+ arms_after = frozenset({"A", "B", "C", "D", "E"}),
+ mechanisms = ("stabilizer_style_invalidation",),
+ ),
+ Step(
+ arms_before = frozenset({"A", "B", "C", "D", "E"}),
+ arms_after = frozenset({"A", "B", "C", "D", "E", "F"}),
+ mechanisms = ("react_reconciliation",),
+ ),
+ ),
+)
+
+#: Route 2 reaches the identical floor from the other end: kill the observers and React first,
+#: then walk down the rendering pipeline. If the mechanisms are additive both routes report the
+#: same per-mechanism numbers. Where they do not, that gap is the interaction term.
+ROUTE_SCHEDULER_FIRST = LadderRoute(
+ route_id = "scheduler_first",
+ name = "observers, then React, then paint, then off-screen layout, then geometry",
+ steps = (
+ Step(
+ arms_before = _SHIPPING,
+ arms_after = frozenset({"D"}),
+ mechanisms = ("autoscroll_forced_layout",),
+ ),
+ Step(
+ arms_before = frozenset({"D"}),
+ arms_after = frozenset({"D", "E"}),
+ mechanisms = ("stabilizer_style_invalidation",),
+ ),
+ Step(
+ arms_before = frozenset({"D", "E"}),
+ arms_after = frozenset({"D", "E", "F"}),
+ mechanisms = ("react_reconciliation",),
+ ),
+ Step(
+ arms_before = frozenset({"D", "E", "F"}),
+ arms_after = frozenset({"A", "D", "E", "F"}),
+ mechanisms = ("paint_raster",),
+ ),
+ Step(
+ arms_before = frozenset({"A", "D", "E", "F"}),
+ arms_after = frozenset({"A", "B", "D", "E", "F"}),
+ mechanisms = ("offscreen_style_layout",),
+ ),
+ Step(
+ arms_before = frozenset({"A", "B", "D", "E", "F"}),
+ arms_after = frozenset({"A", "B", "C", "D", "E", "F"}),
+ mechanisms = ("layout_geometry", "sibling_count"),
+ fused = True,
+ fused_reason = (
+ "same fusion as the other route: display:none is the only knob that removes "
+ "layout geometry, and it removes the sibling from the sequence at the same time"
+ ),
+ ),
+ ),
+)
+
+DECLARED_ROUTES: tuple[LadderRoute, ...] = (ROUTE_VISUAL_FIRST, ROUTE_SCHEDULER_FIRST)
+
+
+def required_rungs(routes: Sequence[LadderRoute] = DECLARED_ROUTES) -> list[frozenset[str]]:
+ """Every distinct arm-combination the declared routes need a cell for."""
+
+ seen: dict[str, frozenset[str]] = {}
+ for route in routes:
+ for step in route.steps:
+ seen[arms_key(step.arms_before)] = step.arms_before
+ seen[arms_key(step.arms_after)] = step.arms_after
+ return [seen[key] for key in sorted(seen)]
diff --git a/tests/studio/studiobench/arms/layoutcost.py b/tests/studio/studiobench/arms/layoutcost.py
new file mode 100644
index 00000000000..918d1be003a
--- /dev/null
+++ b/tests/studio/studiobench/arms/layoutcost.py
@@ -0,0 +1,255 @@
+# 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 Python side of `instruments/layoutcost.js`: an instrument that measures its own cost.
+
+WHY THIS FILE LIVES UNDER `arms/`. `instruments/layoutcost.js` is the browser half; the harness
+layer owns `instruments/` as a package and its registration machinery. This is the ablation
+layer's adapter over it, and it exists for the ablation plane: the counters it reads
+(`scrollHeight` reads, `scrollTop` writes, MutationObserver callbacks and records, custom
+property writes) are the potency evidence for arms D and E, and the thing they instrument is the
+mechanism those arms remove.
+
+WHY IT IS OFF BY DEFAULT AND WHY IT RUNS TWICE. Wrapping the `scrollHeight` getter to time it
+adds a call frame and two `performance.now()` reads to the very operation under suspicion. That
+is not a small effect on a counter that fires per streamed character. So:
+
+ * the instrument declares level 3, and never runs at the levels the headline numbers come from;
+ * the deep tier runs the SAME CELL twice, once with it and once without, and reports the
+ difference as the instrument's in-situ cost.
+
+The second point is the one that matters. `selfCostEstimate()` inside the JS measures the wrapper
+against a detached, clean element, which is a lower bound and a fair one; the paired cell measures
+what it actually cost in the page, with a dirty layout tree and a real observer running. Those two
+numbers are usually different, and quoting the cheap one because it is easier to obtain is how an
+instrument's cost gets assumed rather than known.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Mapping
+
+from ..scoring.schema import Measure
+
+LAYOUTCOST_JS_PATH = Path(__file__).resolve().parents[1] / "instruments" / "layoutcost.js"
+
+#: The instrument level at which this may run. Headline numbers come from level 0 only.
+LAYOUTCOST_LEVEL = 3
+
+#: Counter families the browser side reports, each with its own `attempted` flag.
+COUNTER_FAMILIES = (
+ "scrollHeightReads",
+ "scrollTopWrites",
+ "scrollToCalls",
+ "moCallbacks",
+ "moRecords",
+ "customPropSets",
+)
+
+
+def load_layoutcost_js() -> str:
+ return LAYOUTCOST_JS_PATH.read_text(encoding = "utf-8")
+
+
+@dataclass
+class LayoutCostReading:
+ """One window's layout-cost counters, as Measures rather than bare integers."""
+
+ counters: dict[str, Measure] = field(default_factory = dict)
+ timings: dict[str, Measure] = field(default_factory = dict)
+ unavailable: list[str] = field(default_factory = list)
+ self_cost_ms_per_call: Measure = field(
+ default_factory = lambda: Measure.not_attempted("ms", "self cost not estimated")
+ )
+ stabilizer_sets: Measure = field(
+ default_factory = lambda: Measure.not_attempted("count", "not read")
+ )
+ viewport_observer_callbacks: Measure = field(
+ default_factory = lambda: Measure.not_attempted("count", "not read")
+ )
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "counters": {k: v.to_json() for k, v in self.counters.items()},
+ "timings": {k: v.to_json() for k, v in self.timings.items()},
+ "unavailable": list(self.unavailable),
+ "self_cost_ms_per_call": self.self_cost_ms_per_call.to_json(),
+ "stabilizer_sets": self.stabilizer_sets.to_json(),
+ "viewport_observer_callbacks": self.viewport_observer_callbacks.to_json(),
+ }
+
+
+def reading_from_snapshot(snapshot: Mapping[str, Any] | None) -> LayoutCostReading:
+ """Turn the browser snapshot into Measures, preserving `attempted` per family.
+
+ A patch the engine refused (a non-configurable descriptor on some WebKit builds) comes back
+ in `unavailable`, and every counter under it becomes NOT ATTEMPTED rather than zero. That
+ distinction is the whole reason this adapter exists instead of the raw dict being written
+ straight into the payload: a WebKit run that could not install the getter patch would
+ otherwise report zero forced layouts, which is the most confident possible way to be wrong.
+ """
+
+ if not snapshot:
+ return LayoutCostReading(
+ unavailable = list(COUNTER_FAMILIES),
+ counters = {
+ name: Measure.not_attempted("count", "layoutcost produced no snapshot")
+ for name in COUNTER_FAMILIES
+ },
+ )
+
+ unavailable = list(snapshot.get("unavailable") or [])
+ raw_counters = dict(snapshot.get("counters") or {})
+ raw_timings = dict(snapshot.get("timings") or {})
+ attempted_map = dict(snapshot.get("attempted") or {})
+
+ reading = LayoutCostReading(unavailable = unavailable)
+ for name in COUNTER_FAMILIES:
+ family_ok = attempted_map.get(name, name not in unavailable)
+ if not family_ok:
+ reading.counters[name] = Measure.not_attempted(
+ "count", f"{name}: the patch could not be installed on this engine"
+ )
+ continue
+ value = raw_counters.get(name)
+ if value is None:
+ reading.counters[name] = Measure.failed("count", f"{name} missing from the snapshot")
+ else:
+ reading.counters[name] = Measure.read(float(value), "count")
+
+ for name, value in raw_timings.items():
+ if value is None:
+ reading.timings[name] = Measure.failed("ms", f"{name} missing from the snapshot")
+ else:
+ reading.timings[name] = Measure.read(float(value), "ms")
+
+ self_cost = snapshot.get("overheadMsPerCall")
+ if self_cost is not None:
+ reading.self_cost_ms_per_call = Measure.read(
+ float(self_cost),
+ "ms/call",
+ note = (
+ "measured against a detached clean element, so this is a LOWER BOUND on the "
+ "in-page cost; the paired with/without cell is the real number"
+ ),
+ )
+
+ mo = dict(snapshot.get("mo") or {})
+ if "viewportCallbacks" in mo:
+ reading.viewport_observer_callbacks = Measure.read(float(mo["viewportCallbacks"]), "count")
+ if "stabilizerSets" in raw_counters:
+ reading.stabilizer_sets = Measure.read(float(raw_counters["stabilizerSets"]), "count")
+ return reading
+
+
+def in_situ_overhead(with_instrument_ms: Measure, without_instrument_ms: Measure) -> Measure:
+ """The instrument's real cost, from the paired cell. Not its own estimate of itself.
+
+ Positive means the instrumented cell was slower, which is the expected direction. A negative
+ result larger than the noise means the pair is not measuring what it thinks it is, and it is
+ reported as a reading rather than clamped to zero, because a clamp would turn a broken pair
+ into a plausible one.
+ """
+
+ if not (with_instrument_ms.has_reading and without_instrument_ms.has_reading):
+ return Measure.failed(
+ with_instrument_ms.unit,
+ "the with/without pair is incomplete, so the instrument's cost is unknown rather "
+ "than zero",
+ )
+ return Measure.read(
+ float(with_instrument_ms.value) - float(without_instrument_ms.value),
+ with_instrument_ms.unit,
+ )
+
+
+class LayoutCostInstrument:
+ """Adapter satisfying the harness layer's `Instrument` protocol.
+
+ Registration is deliberately not done at import time here: `instruments/__init__.py` and its
+ `register_instrument` decorator belong to the harness layer, and importing them from this
+ layer would make the ablation package fail to import whenever the harness package is being
+ edited. `register()` below is called by whoever wires the two together.
+ """
+
+ name = "layoutcost"
+ level = LAYOUTCOST_LEVEL
+
+ def __init__(self) -> None:
+ self._ctx: Any = None
+ self._page: Any = None
+ self._installed = False
+ self._error: str | None = None
+
+ def attach(self, ctx: Any) -> None:
+ self._ctx = ctx
+
+ def start_cell(self, cell: Any) -> None:
+ # `ctx.page` may be replaced between cells when a crashed renderer is recovered, so the
+ # page is re-read here rather than cached in attach().
+ self._page = getattr(self._ctx, "page", None)
+
+ def open(self, window: Any) -> None:
+ if self._page is None:
+ return
+ try:
+ self._page.evaluate(
+ "() => { if (window.__sbLayoutCost) { window.__sbLayoutCost.reset(); } }"
+ )
+ self._installed = True
+ except Exception as error: # pragma: no cover - browser-side failure path
+ self._error = str(error)
+
+ def close(self, window: Any) -> dict[str, Any] | None:
+ if self._page is None:
+ return None
+ try:
+ snapshot = self._page.evaluate(
+ "() => (window.__sbLayoutCost ? window.__sbLayoutCost.snapshot() : null)"
+ )
+ except Exception as error: # pragma: no cover - browser-side failure path
+ return {"error": str(error), "attempted": True}
+ return reading_from_snapshot(snapshot).to_json()
+
+ def end_cell(self, cell: Any) -> dict[str, Any] | None:
+ # The harness contract requires every instrument at level >= 1 to declare its own cost.
+ # This one declares the LOWER BOUND it can measure itself, and says so, because the real
+ # number comes from the paired with/without cell that only the deep tier runs.
+ if self._page is None:
+ return {"overhead_ms": None, "overhead_attempted": False}
+ try:
+ estimate = self._page.evaluate(
+ "() => (window.__sbLayoutCost ? window.__sbLayoutCost.selfCostEstimate() : null)"
+ )
+ except Exception: # pragma: no cover - browser-side failure path
+ estimate = None
+ if not estimate:
+ return {"overhead_ms": None, "overhead_attempted": False}
+ return {
+ "overhead_ms": estimate.get("overheadMsPerCall"),
+ "overhead_attempted": True,
+ "overhead_is_lower_bound": True,
+ "overhead_note": (
+ "per-call wrapper cost against a detached clean element; the in-page cost is "
+ "measured by the paired with/without cell"
+ ),
+ }
+
+ def detach(self) -> None:
+ self._page = None
+
+
+def register(register_instrument: Any) -> Any:
+ """Wire this instrument into the harness layer's registry.
+
+ Takes the decorator rather than importing it, so this module has no import-time dependency on
+ a package another layer is still building.
+ """
+
+ @register_instrument(name = LayoutCostInstrument.name, level = LAYOUTCOST_LEVEL)
+ def _make() -> LayoutCostInstrument:
+ return LayoutCostInstrument()
+
+ return _make
diff --git a/tests/studio/studiobench/arms/manifest.py b/tests/studio/studiobench/arms/manifest.py
new file mode 100644
index 00000000000..4ae9f4c5198
--- /dev/null
+++ b/tests/studio/studiobench/arms/manifest.py
@@ -0,0 +1,345 @@
+# 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 every ablation arm must declare before it is allowed to produce a number.
+
+An ablation is a claim of the form "removing X made it faster, therefore X was the cost". That
+claim has exactly two ways of being false, and both of them are silent:
+
+ 1. THE ARM CHANGED THE OUTPUT. Turning off the thing also turned off some of the work, so the
+ two sides are not rendering the same page and the difference is not attributable to X. The
+ worst case is not a visible difference; it is a small invisible one. An earlier stub arm in
+ this codebase produced 552 syntax-highlighted spans where the real page produces 2,561, and
+ it read as a clean 4x win. The arm was not fast. It was rendering a fifth of the content.
+ 2. THE ARM DID NOT FIRE. The knob was injected, the selector matched nothing, the run completed
+ and the difference was zero. Reported as "no effect", that is evidence AGAINST the mechanism.
+ It is not evidence of anything; the treatment was never applied. Four instrument defects
+ found in a single day were all this shape, which is why the inversion is enforced here:
+ an arm whose potency counter did not move reads NOT RUN, never "no effect".
+
+So every arm declares:
+
+ INVARIANCE -- what proves the rendered output did not change, in one of three classes:
+ EXACT the output digest is byte-identical. Anything else voids the arm.
+ EQUIVALENT identical after a declared, reviewed normaliser, AND the observed diff is
+ EXACTLY the declared diff. An extra difference, however small, voids it.
+ DOM_CHANGING the output legitimately differs. Usable only as a BOUND, printed as `<= x`,
+ never as a point estimate.
+ POTENCY -- a counter, read before and after, that proves the arm actually fired, with the
+ minimum movement that counts as fired. The counter must be something the arm CAUSES, not
+ something correlated with it.
+
+The distinction between VOIDED and NOT RUN matters more than either of them: VOIDED means we
+measured something real and cannot attribute it, NOT RUN means we measured nothing. Reporting
+both as "no effect" is how a whole day of work concluded that nothing was slow.
+"""
+
+from __future__ import annotations
+
+import enum
+from dataclasses import dataclass, field
+from typing import Any, Callable, Mapping, Sequence
+
+from ..scoring.schema import Measure
+
+
+class Invariance(enum.Enum):
+ """How strongly an arm claims the rendered output is unchanged."""
+
+ EXACT = "EXACT"
+ EQUIVALENT = "EQUIVALENT"
+ DOM_CHANGING = "DOM_CHANGING"
+
+
+class ArmStatus(enum.Enum):
+ """The five things an arm run can be. Only two of them produce a number."""
+
+ QUOTED = "QUOTED" # invariance held, potency fired: a point estimate
+ BOUND = "BOUND" # DOM-changing but potent: an upper bound, printed as `<= x`
+ VOIDED = "VOIDED" # claimed invariance and drifted: measured, unattributable, not quoted
+ NOT_RUN = "NOT_RUN" # potency counter did not move: the treatment never happened
+ UNAVAILABLE = "UNAVAILABLE" # the arm needs a build that this install is not
+
+
+@dataclass(frozen = True)
+class PotencyCounter:
+ """The proof that the arm fired, and the minimum movement that counts.
+
+ `direction` is `"increase"`, `"decrease"` or `"any"`. A knob that is supposed to REMOVE work
+ usually proves itself by a counter going DOWN, and accepting movement in either direction
+ would let an unrelated regression pass as potency.
+ """
+
+ name: str
+ min_delta: float
+ direction: str = "any"
+ description: str = ""
+
+ def fired(self, before: float | None, after: float | None) -> bool:
+ if before is None or after is None:
+ return False
+ delta = float(after) - float(before)
+ if self.direction == "increase":
+ return delta >= self.min_delta
+ if self.direction == "decrease":
+ return -delta >= self.min_delta
+ return abs(delta) >= self.min_delta
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "name": self.name,
+ "min_delta": float(self.min_delta),
+ "direction": self.direction,
+ "description": self.description,
+ }
+
+
+@dataclass(frozen = True)
+class DeclaredDiff:
+ """For EQUIVALENT arms: exactly what is allowed to differ, and nothing else.
+
+ `keys` are the normaliser-visible fields permitted to change. The verification is an equality
+ check against the OBSERVED set, not a subset check: an arm that declares one difference and
+ produces two is voided, because the second one is precisely the thing nobody looked at.
+ """
+
+ normaliser: str
+ keys: tuple[str, ...]
+ rationale: str = ""
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "normaliser": self.normaliser,
+ "keys": list(self.keys),
+ "rationale": self.rationale,
+ }
+
+
+@dataclass(frozen = True)
+class Arm:
+ """One ablation arm: what it does, what it claims, and how it proves it fired."""
+
+ arm_id: str
+ title: str
+ mechanism: str
+ invariance: Invariance
+ potency: PotencyCounter
+ implies_fix: str
+ kind: str = "runtime" # "runtime" | "bundle" | "calibration" | "control" | "dose"
+ declared_diff: DeclaredDiff | None = None
+ init_script: str | None = None
+ requires_armpack: bool = False
+ notes: str = ""
+
+ def __post_init__(self) -> None:
+ if self.invariance is Invariance.EQUIVALENT and self.declared_diff is None:
+ raise ValueError(
+ f"{self.arm_id}: an EQUIVALENT arm must declare its normaliser and the exact "
+ "diff it is allowed to produce"
+ )
+ if self.invariance is not Invariance.EQUIVALENT and self.declared_diff is not None:
+ raise ValueError(
+ f"{self.arm_id}: only an EQUIVALENT arm may declare a diff; an EXACT arm that "
+ "needs one is an EQUIVALENT arm that has not admitted it"
+ )
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "arm_id": self.arm_id,
+ "title": self.title,
+ "mechanism": self.mechanism,
+ "invariance": self.invariance.value,
+ "kind": self.kind,
+ "implies_fix": self.implies_fix,
+ "requires_armpack": bool(self.requires_armpack),
+ "potency": self.potency.to_json(),
+ "declared_diff": self.declared_diff.to_json() if self.declared_diff else None,
+ "notes": self.notes,
+ }
+
+
+@dataclass
+class ArmOutcome:
+ """One arm, run once, with its verdict and the evidence behind it."""
+
+ arm: Arm
+ cost: Measure
+ status: ArmStatus
+ reason: str
+ digest_before: str | None = None
+ digest_after: str | None = None
+ normalised_before: str | None = None
+ normalised_after: str | None = None
+ observed_diff_keys: tuple[str, ...] = ()
+ potency_before: float | None = None
+ potency_after: float | None = None
+ potency_counters: dict[str, Any] = field(default_factory = dict)
+
+ @property
+ def quotable(self) -> bool:
+ return self.status in (ArmStatus.QUOTED, ArmStatus.BOUND)
+
+ def quote(self) -> str:
+ """Render this arm's cost with the qualifier its status demands.
+
+ A DOM-changing arm is printed as a bound and cannot be printed any other way; that is the
+ entire difference between "this mechanism costs 40 ms" and "this mechanism plus whatever
+ else changed costs at most 40 ms".
+ """
+
+ if self.status is ArmStatus.QUOTED:
+ return self.cost.display()
+ if self.status is ArmStatus.BOUND:
+ return f"<= {self.cost.display()}"
+ if self.status is ArmStatus.NOT_RUN:
+ return f"NOT RUN ({self.reason})"
+ if self.status is ArmStatus.VOIDED:
+ return f"VOIDED ({self.reason})"
+ return f"UNAVAILABLE ({self.reason})"
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "arm": self.arm.to_json(),
+ "status": self.status.value,
+ "reason": self.reason,
+ "quote": self.quote(),
+ "quotable": self.quotable,
+ "cost": self.cost.to_json(),
+ "invariance_evidence": {
+ "digest_before": self.digest_before,
+ "digest_after": self.digest_after,
+ "normalised_before": self.normalised_before,
+ "normalised_after": self.normalised_after,
+ "observed_diff_keys": list(self.observed_diff_keys),
+ },
+ "potency_evidence": {
+ "counter": self.arm.potency.name,
+ "before": self.potency_before,
+ "after": self.potency_after,
+ "fired": self.arm.potency.fired(self.potency_before, self.potency_after),
+ "potency_counters": dict(self.potency_counters),
+ },
+ }
+
+
+def judge(
+ arm: Arm,
+ *,
+ cost: Measure,
+ digest_before: str | None,
+ digest_after: str | None,
+ normalised_before: str | None = None,
+ normalised_after: str | None = None,
+ observed_diff_keys: Sequence[str] = (),
+ potency_before: float | None = None,
+ potency_after: float | None = None,
+ potency_counters: Mapping[str, Any] | None = None,
+ available: bool = True,
+ unavailable_reason: str = "",
+) -> ArmOutcome:
+ """Apply the manifest to one run of one arm and produce its verdict.
+
+ ORDER MATTERS AND IS DELIBERATE.
+
+ Availability is checked first: an arm that needs an armed bundle and did not get one has no
+ evidence of any kind. Invariance is checked SECOND, before potency, because a voided arm has
+ already produced a number that must not be quoted, and letting a NOT RUN verdict pre-empt it
+ would hide a real drift behind a benign-sounding label. Potency is checked LAST, so the only
+ way to reach QUOTED is: available, invariance held, and the counter moved.
+ """
+
+ counters = dict(potency_counters or {})
+
+ if not available:
+ return ArmOutcome(
+ arm = arm,
+ cost = Measure.not_attempted(cost.unit, unavailable_reason or "arm unavailable"),
+ status = ArmStatus.UNAVAILABLE,
+ reason = unavailable_reason or "arm unavailable for this build",
+ potency_counters = counters,
+ )
+
+ outcome = ArmOutcome(
+ arm = arm,
+ cost = cost,
+ status = ArmStatus.QUOTED,
+ reason = "",
+ digest_before = digest_before,
+ digest_after = digest_after,
+ normalised_before = normalised_before,
+ normalised_after = normalised_after,
+ observed_diff_keys = tuple(observed_diff_keys),
+ potency_before = potency_before,
+ potency_after = potency_after,
+ potency_counters = counters,
+ )
+
+ if arm.invariance is Invariance.EXACT:
+ if digest_before is None or digest_after is None:
+ outcome.status = ArmStatus.VOIDED
+ outcome.reason = (
+ "this arm claims EXACT invariance but no output digest was captured, so the "
+ "claim was never checked"
+ )
+ return outcome
+ if digest_before != digest_after:
+ outcome.status = ArmStatus.VOIDED
+ outcome.reason = (
+ f"claims EXACT invariance and the output digest changed "
+ f"({digest_before[:12]} -> {digest_after[:12]}). The two sides did not render "
+ "the same thing, so the difference cannot be attributed to the mechanism"
+ )
+ return outcome
+ elif arm.invariance is Invariance.EQUIVALENT:
+ declared = arm.declared_diff
+ assert declared is not None # enforced in Arm.__post_init__
+ if normalised_before is None or normalised_after is None:
+ outcome.status = ArmStatus.VOIDED
+ outcome.reason = (
+ "claims EQUIVALENT invariance but the normaliser produced no output, so the "
+ "equivalence was never checked"
+ )
+ return outcome
+ if normalised_before != normalised_after:
+ outcome.status = ArmStatus.VOIDED
+ outcome.reason = (
+ f"claims EQUIVALENT under normaliser {declared.normaliser!r} and the normalised "
+ "digests still differ"
+ )
+ return outcome
+ observed = tuple(sorted(set(observed_diff_keys)))
+ expected = tuple(sorted(set(declared.keys)))
+ if observed != expected:
+ extra = sorted(set(observed) - set(expected))
+ missing = sorted(set(expected) - set(observed))
+ outcome.status = ArmStatus.VOIDED
+ outcome.reason = (
+ "the observed diff is not exactly the declared diff"
+ + (f"; undeclared: {extra}" if extra else "")
+ + (f"; declared but absent: {missing}" if missing else "")
+ + ". An undeclared difference is the one nobody looked at."
+ )
+ return outcome
+
+ if not arm.potency.fired(potency_before, potency_after):
+ outcome.status = ArmStatus.NOT_RUN
+ outcome.reason = (
+ f"potency counter {arm.potency.name!r} did not move "
+ f"({potency_before} -> {potency_after}, needs {arm.potency.direction} of at least "
+ f"{arm.potency.min_delta}). The treatment was not applied, so this is not a "
+ "measurement of no effect"
+ )
+ outcome.cost = Measure.not_attempted(cost.unit, "arm did not fire")
+ return outcome
+
+ if arm.invariance is Invariance.DOM_CHANGING:
+ outcome.status = ArmStatus.BOUND
+ outcome.reason = (
+ "the arm legitimately changes the rendered output, so its cost is an upper bound on "
+ "the mechanism and not a point estimate"
+ )
+ return outcome
+
+ outcome.status = ArmStatus.QUOTED
+ outcome.reason = "invariance held and the potency counter moved"
+ return outcome
diff --git a/tests/studio/studiobench/arms/recovery.py b/tests/studio/studiobench/arms/recovery.py
new file mode 100644
index 00000000000..fbfbd95076a
--- /dev/null
+++ b/tests/studio/studiobench/arms/recovery.py
@@ -0,0 +1,212 @@
+# 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 recovery test: does deleting the thread give the performance back?
+
+Ninety seconds, never run before, and it separates three fix classes that every other measurement
+in this tool conflates.
+
+ seed 512 turns -> measure -> delete back to zero -> measure again
+
+The user report is "it gets worse the longer you use it". That sentence has two completely
+different causes and they need different fixes:
+
+ OCCUPANCY the cost is proportional to what is currently on the page. Delete the turns and the
+ cost goes away. The fix is to stop keeping them present: virtualise, contain, or
+ unmount. This is the comfortable case and it is what everyone assumes.
+ RETAINED the cost does not come back down. Something survives the delete: a detached DOM
+ tree still referenced by a closure, an observer never disconnected, a growing map
+ in a store, a Shiki cache keyed per block. The fix is to release it, and no amount
+ of virtualisation will help, because the structure is not on screen in the first
+ place.
+ HYSTERETIC partial recovery. Both mechanisms are present, and fixing only the visible one
+ leaves a slow drift that reappears in a support ticket six weeks later.
+
+The test is worth its ninety seconds because those three imply different work, and nothing else
+in this tool can tell them apart: every other measurement is taken at a fixed thread size, where
+occupancy and retention are perfectly correlated.
+
+A FOURTH OUTCOME MATTERS AND IS EASY TO MISREAD. If the loaded measurement is not meaningfully
+worse than the baseline, there is nothing to recover, and the recovery fraction is undefined
+rather than 100%. Printing "fully recovered" for a load that never cost anything would be the
+same defect as printing zero for an instrument that never ran.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+from ..scoring.schema import Measure
+
+#: Seeded turns for the loaded phase. 512 is chosen to be well past the point where the reported
+#: symptom appears while still seeding in under a minute through the messages API.
+RECOVERY_TURNS = 512
+
+FULL_RECOVERY = 0.90
+NO_RECOVERY = 0.10
+
+
+@dataclass
+class RecoveryResult:
+ """Baseline, loaded, and post-delete, plus which of the three classes this is."""
+
+ baseline: Measure
+ loaded: Measure
+ after_delete: Measure
+ turns: int
+ noise_floor_ms: float
+ recovered_fraction: float | None
+ classification: str
+ implies_fix: str
+ note: str
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "baseline": self.baseline.to_json(),
+ "loaded": self.loaded.to_json(),
+ "after_delete": self.after_delete.to_json(),
+ "turns": int(self.turns),
+ "noise_floor_ms": float(self.noise_floor_ms),
+ "recovered_fraction": self.recovered_fraction,
+ "classification": self.classification,
+ "implies_fix": self.implies_fix,
+ "note": self.note,
+ }
+
+ def render(self) -> str:
+ fraction = (
+ f"{self.recovered_fraction:.0%}" if self.recovered_fraction is not None else "undefined"
+ )
+ return "\n".join(
+ [
+ f"RECOVERY TEST ({self.turns} turns seeded, then deleted back to zero)",
+ f" baseline {self.baseline.display()}",
+ f" loaded {self.loaded.display()}",
+ f" after delete {self.after_delete.display()}",
+ f" recovered {fraction}",
+ f" CLASSIFICATION: {self.classification}",
+ f" {self.note}",
+ f" implies: {self.implies_fix}",
+ ]
+ )
+
+
+def classify_recovery(
+ *,
+ baseline: Measure,
+ loaded: Measure,
+ after_delete: Measure,
+ noise_floor_ms: float,
+ turns: int = RECOVERY_TURNS,
+) -> RecoveryResult:
+ """Turn three readings into one of four classes, or an explicit refusal to classify."""
+
+ def refuse(reason: str) -> RecoveryResult:
+ return RecoveryResult(
+ baseline = baseline,
+ loaded = loaded,
+ after_delete = after_delete,
+ turns = turns,
+ noise_floor_ms = float(noise_floor_ms),
+ recovered_fraction = None,
+ classification = "NOT CLASSIFIED",
+ implies_fix = "none: this run cannot distinguish the cases",
+ note = reason,
+ )
+
+ if not (baseline.has_reading and loaded.has_reading and after_delete.has_reading):
+ return refuse(
+ "one of the three phases produced no reading, so there is no recovery to compute"
+ )
+
+ base_v = float(baseline.value)
+ loaded_v = float(loaded.value)
+ after_v = float(after_delete.value)
+ load_cost = loaded_v - base_v
+
+ if load_cost <= noise_floor_ms:
+ return RecoveryResult(
+ baseline = baseline,
+ loaded = loaded,
+ after_delete = after_delete,
+ turns = turns,
+ noise_floor_ms = float(noise_floor_ms),
+ recovered_fraction = None,
+ classification = "NOTHING TO RECOVER",
+ implies_fix = (
+ "none from this test. Seeding the thread did not make it measurably slower on "
+ "this machine, so the recovery question does not arise here"
+ ),
+ note = (
+ f"the loaded phase is only {load_cost:.3f} ms above baseline, at or below the "
+ f"noise floor of {noise_floor_ms:.3f} ms. The recovery fraction is UNDEFINED, "
+ "not 100%: there was no cost to give back"
+ ),
+ )
+
+ fraction = (loaded_v - after_v) / load_cost
+
+ if after_v > loaded_v + noise_floor_ms:
+ return RecoveryResult(
+ baseline = baseline,
+ loaded = loaded,
+ after_delete = after_delete,
+ turns = turns,
+ noise_floor_ms = float(noise_floor_ms),
+ recovered_fraction = fraction,
+ classification = "WORSE AFTER DELETE",
+ implies_fix = (
+ "look at the delete path itself. Something about removing the turns costs more "
+ "than keeping them, which usually means detached subtrees still observed, or "
+ "state rebuilt on every removal"
+ ),
+ note = (
+ "the post-delete reading is worse than the loaded one. This is not recovery "
+ "failing, it is the deletion adding cost of its own"
+ ),
+ )
+
+ if fraction >= FULL_RECOVERY:
+ classification = "OCCUPANCY"
+ implies = (
+ "the cost is proportional to what is currently present. Virtualise, contain or "
+ "unmount the retained messages and the cost goes with them"
+ )
+ note = (
+ f"{fraction:.0%} of the loaded cost came back on delete, so nothing meaningful "
+ "survives the removal"
+ )
+ elif fraction <= NO_RECOVERY:
+ classification = "RETAINED STRUCTURE"
+ implies = (
+ "something survives the delete: a detached tree still referenced, an observer never "
+ "disconnected, a cache keyed per block, a store that only grows. Virtualisation will "
+ "not touch this, because the structure is not on screen to begin with"
+ )
+ note = (
+ f"only {fraction:.0%} of the loaded cost came back. This is the literal shape of "
+ "'gets worse the longer you use it and stays worse'"
+ )
+ else:
+ classification = "HYSTERETIC"
+ implies = (
+ "both mechanisms are present. Fixing the visible one leaves a residual drift that "
+ "will come back as a separate report later"
+ )
+ note = (
+ f"{fraction:.0%} of the loaded cost came back, which is neither full recovery nor "
+ "none. Do not round it to whichever is more convenient"
+ )
+
+ return RecoveryResult(
+ baseline = baseline,
+ loaded = loaded,
+ after_delete = after_delete,
+ turns = turns,
+ noise_floor_ms = float(noise_floor_ms),
+ recovered_fraction = fraction,
+ classification = classification,
+ implies_fix = implies,
+ note = note,
+ )
diff --git a/tests/studio/studiobench/arms/selftest/test_studiobench_arms.py b/tests/studio/studiobench/arms/selftest/test_studiobench_arms.py
new file mode 100644
index 00000000000..66d5099e242
--- /dev/null
+++ b/tests/studio/studiobench/arms/selftest/test_studiobench_arms.py
@@ -0,0 +1,705 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Unit tests for the ablation layer.
+
+The arms layer is where a wrong answer is most expensive, because its output is a CAUSAL claim.
+Everything here is a test of a refusal: an arm that drifted must not be quoted, an arm that did
+not fire must not read as no effect, a ladder must not quote a rung on its own, a batch without
+calibration must not run at all, and an armpack that does not match must stop its plane of the
+experiment rather than be skipped quietly.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.arms import ( # noqa: E402
+ BANNER,
+ Arm,
+ ArmStatus,
+ DeclaredDiff,
+ Invariance,
+ LadderError,
+ PotencyCounter,
+ Step,
+ arms_key,
+ assert_batch_includes_calibration,
+ classify_recovery,
+ config_init_script,
+ differences,
+ discover_armpack,
+ evaluate_batch,
+ fit_dose_response,
+ interaction_terms,
+ judge,
+ render_decision_table,
+ required_rungs,
+ split_arms,
+)
+from studiobench.arms.bundle import ARM_FIBRE_FREE_TWIN, BUNDLE_ARMS # noqa: E402
+from studiobench.arms.calibration import CalibrationMissing # noqa: E402
+from studiobench.arms.dose import DosePoint # noqa: E402
+from studiobench.arms.knobs import PREBOOT_ARM_IDS, RUNTIME_ARMS # noqa: E402
+from studiobench.arms.ladder import ( # noqa: E402
+ ROUTE_SCHEDULER_FIRST,
+ ROUTE_VISUAL_FIRST,
+ LadderRoute,
+)
+from studiobench.arms.manifest import ArmOutcome # noqa: E402
+from studiobench.scoring import Measure # noqa: E402
+
+
+def _arm(
+ arm_id: str = "X",
+ invariance: Invariance = Invariance.EXACT,
+ declared_diff: DeclaredDiff | None = None,
+) -> Arm:
+ return Arm(
+ arm_id = arm_id,
+ title = arm_id,
+ mechanism = "test mechanism",
+ invariance = invariance,
+ declared_diff = declared_diff,
+ potency = PotencyCounter(name = "fired", min_delta = 1, direction = "increase"),
+ implies_fix = "test",
+ )
+
+
+# ---------------------------------------------------------------------------------------
+# manifest: invariance and potency
+# ---------------------------------------------------------------------------------------
+
+
+def test_an_exact_arm_that_drifts_is_voided_not_quoted():
+ outcome = judge(
+ _arm(),
+ cost = Measure.read(4.0, "ms/update"),
+ digest_before = "aaaa1111",
+ digest_after = "bbbb2222",
+ potency_before = 0,
+ potency_after = 700,
+ )
+ assert outcome.status is ArmStatus.VOIDED
+ assert outcome.quotable is False
+ assert "VOIDED" in outcome.quote()
+ assert "did not render the same thing" in outcome.reason
+
+
+def test_an_exact_arm_whose_potency_did_not_move_reads_not_run_never_no_effect():
+ outcome = judge(
+ _arm(),
+ cost = Measure.read(0.001, "ms/update"),
+ digest_before = "same",
+ digest_after = "same",
+ potency_before = 0,
+ potency_after = 0,
+ )
+ assert outcome.status is ArmStatus.NOT_RUN
+ assert "NOT RUN" in outcome.quote()
+ assert outcome.cost.attempted is False
+ assert "not a measurement of no effect" in outcome.reason
+
+
+def test_drift_is_reported_ahead_of_a_dead_potency_counter():
+ """A voided arm has already produced a number; NOT RUN would make that sound harmless."""
+
+ outcome = judge(
+ _arm(),
+ cost = Measure.read(4.0, "ms/update"),
+ digest_before = "aaaa",
+ digest_after = "bbbb",
+ potency_before = 0,
+ potency_after = 0,
+ )
+ assert outcome.status is ArmStatus.VOIDED
+
+
+def test_a_dom_changing_arm_is_quoted_only_as_a_bound():
+ outcome = judge(
+ _arm(invariance = Invariance.DOM_CHANGING),
+ cost = Measure.read(12.5, "ms/update"),
+ digest_before = "a",
+ digest_after = "b",
+ potency_before = 0,
+ potency_after = 44,
+ )
+ assert outcome.status is ArmStatus.BOUND
+ assert outcome.quote().startswith("<= ")
+
+
+def test_an_equivalent_arm_must_produce_exactly_the_declared_diff():
+ arm = _arm(
+ invariance = Invariance.EQUIVALENT,
+ declared_diff = DeclaredDiff(normaliser = "skip_style_attribute", keys = ("style",)),
+ )
+ good = judge(
+ arm,
+ cost = Measure.read(3.0, "ms/update"),
+ digest_before = "raw-a",
+ digest_after = "raw-b",
+ normalised_before = "norm",
+ normalised_after = "norm",
+ observed_diff_keys = ("style",),
+ potency_before = 0,
+ potency_after = 685,
+ )
+ assert good.status is ArmStatus.QUOTED
+
+ extra = judge(
+ arm,
+ cost = Measure.read(3.0, "ms/update"),
+ digest_before = "raw-a",
+ digest_after = "raw-b",
+ normalised_before = "norm",
+ normalised_after = "norm",
+ observed_diff_keys = ("style", "data-status"),
+ potency_before = 0,
+ potency_after = 685,
+ )
+ assert extra.status is ArmStatus.VOIDED
+ assert "undeclared" in extra.reason
+
+
+def test_an_exact_arm_with_no_digest_is_voided_rather_than_believed():
+ outcome = judge(
+ _arm(),
+ cost = Measure.read(3.0, "ms/update"),
+ digest_before = None,
+ digest_after = None,
+ potency_before = 0,
+ potency_after = 99,
+ )
+ assert outcome.status is ArmStatus.VOIDED
+ assert "never checked" in outcome.reason
+
+
+def test_an_unavailable_arm_is_not_a_zero():
+ outcome = judge(
+ _arm(),
+ cost = Measure.read(0.0, "ms/update"),
+ digest_before = "a",
+ digest_after = "a",
+ available = False,
+ unavailable_reason = "no armpack for this dist",
+ )
+ assert outcome.status is ArmStatus.UNAVAILABLE
+ assert outcome.cost.attempted is False
+
+
+def test_an_equivalent_arm_must_declare_its_diff_and_an_exact_one_may_not():
+ with pytest.raises(ValueError):
+ _arm(invariance = Invariance.EQUIVALENT)
+ with pytest.raises(ValueError):
+ _arm(declared_diff = DeclaredDiff(normaliser = "n", keys = ("style",)))
+
+
+# ---------------------------------------------------------------------------------------
+# ladder
+# ---------------------------------------------------------------------------------------
+
+
+def test_a_step_removing_two_mechanisms_must_admit_it_is_fused():
+ with pytest.raises(LadderError):
+ Step(
+ arms_before = frozenset(),
+ arms_after = frozenset({"C"}),
+ mechanisms = ("layout_geometry", "sibling_count"),
+ )
+ Step(
+ arms_before = frozenset(),
+ arms_after = frozenset({"C"}),
+ mechanisms = ("layout_geometry", "sibling_count"),
+ fused = True,
+ fused_reason = "no knob separates them",
+ )
+
+
+def test_a_step_must_be_nested_not_merely_different():
+ with pytest.raises(LadderError):
+ Step(
+ arms_before = frozenset({"A"}),
+ arms_after = frozenset({"B"}),
+ mechanisms = ("paint_raster",),
+ )
+
+
+def test_a_route_may_not_remove_the_same_mechanism_twice():
+ with pytest.raises(LadderError):
+ LadderRoute(
+ route_id = "bad",
+ name = "bad",
+ steps = (
+ Step(frozenset(), frozenset({"A"}), ("paint_raster",)),
+ Step(frozenset({"A"}), frozenset({"A", "B"}), ("paint_raster",)),
+ ),
+ )
+
+
+def test_a_route_with_a_gap_is_refused():
+ with pytest.raises(LadderError):
+ LadderRoute(
+ route_id = "gap",
+ name = "gap",
+ steps = (
+ Step(frozenset(), frozenset({"A"}), ("paint_raster",)),
+ Step(
+ frozenset({"A", "B"}),
+ frozenset({"A", "B", "C"}),
+ ("layout_geometry", "sibling_count"),
+ fused = True,
+ fused_reason = "x",
+ ),
+ ),
+ )
+
+
+def _outcomes(costs: dict[str, float]) -> dict[str, ArmOutcome]:
+ out: dict[str, ArmOutcome] = {}
+ for key, value in costs.items():
+ out[key] = ArmOutcome(
+ arm = _arm(key),
+ cost = Measure.read(value, "ms/update"),
+ status = ArmStatus.QUOTED,
+ reason = "synthetic",
+ potency_before = 0,
+ potency_after = 100,
+ )
+ return out
+
+
+_VISUAL_COSTS = {
+ "shipping": 40.0,
+ "A": 34.0,
+ "A+B": 26.0,
+ "A+B+C": 18.0,
+ "A+B+C+D": 9.0,
+ "A+B+C+D+E": 7.0,
+ "A+B+C+D+E+F": 2.0,
+}
+
+
+def test_the_telescoping_identity_holds_exactly_with_no_residual():
+ result = differences(ROUTE_VISUAL_FIRST, _outcomes(_VISUAL_COSTS), detection_floor_ms = 0.5)
+ assert result.identity_holds is True
+ assert result.residual_ms == pytest.approx(0.0, abs = 1e-12)
+ assert result.total.value == pytest.approx(38.0)
+ assert result.sum_of_steps.value == pytest.approx(38.0)
+ assert "no residual to attribute" in result.identity_note
+
+
+def test_a_missing_rung_means_the_identity_is_not_claimed():
+ costs = dict(_VISUAL_COSTS)
+ del costs["A+B"]
+ result = differences(ROUTE_VISUAL_FIRST, _outcomes(costs), detection_floor_ms = 0.5)
+ assert result.identity_holds is False
+ assert "no complete chain" in result.identity_note
+ assert any(not step.quotable for step in result.steps)
+
+
+def test_a_voided_rung_poisons_only_its_own_steps():
+ outcomes = _outcomes(_VISUAL_COSTS)
+ outcomes["A+B"] = ArmOutcome(
+ arm = _arm("A+B"),
+ cost = Measure.read(26.0, "ms/update"),
+ status = ArmStatus.VOIDED,
+ reason = "digest drifted",
+ )
+ result = differences(ROUTE_VISUAL_FIRST, outcomes, detection_floor_ms = 0.5)
+ quotable = [s for s in result.steps if s.quotable]
+ assert len(quotable) == len(ROUTE_VISUAL_FIRST.steps) - 2
+ assert result.identity_holds is False
+
+
+def test_a_bound_rung_makes_its_adjacent_difference_a_bound():
+ outcomes = _outcomes(_VISUAL_COSTS)
+ outcomes["A+B+C+D+E+F"] = ArmOutcome(
+ arm = _arm("A+B+C+D+E+F"),
+ cost = Measure.read(2.0, "ms/update"),
+ status = ArmStatus.BOUND,
+ reason = "DOM changing",
+ potency_after = 10,
+ )
+ result = differences(ROUTE_VISUAL_FIRST, outcomes, detection_floor_ms = 0.5)
+ react_step = result.steps[-1]
+ assert react_step.bound_only is True
+ assert react_step.quote().startswith("<= ")
+
+
+def test_no_arm_may_be_quoted_alone():
+ with pytest.raises(LadderError) as caught:
+ ROUTE_VISUAL_FIRST.quote_arm({"A", "B"})
+ assert "only adjacent differences" in str(caught.value)
+
+
+def test_the_two_declared_routes_reach_the_same_floor_by_different_orders():
+ assert ROUTE_VISUAL_FIRST.floor == ROUTE_SCHEDULER_FIRST.floor
+ assert ROUTE_VISUAL_FIRST.mechanisms != ROUTE_SCHEDULER_FIRST.mechanisms
+ assert sorted(ROUTE_VISUAL_FIRST.mechanisms) == sorted(ROUTE_SCHEDULER_FIRST.mechanisms)
+
+
+def test_route_disagreement_is_reported_as_an_interaction_not_averaged():
+ scheduler_costs = {
+ "shipping": 40.0,
+ "D": 22.0, # removing the observer first is worth much more on this route
+ "D+E": 20.0,
+ "D+E+F": 15.0,
+ "A+D+E+F": 12.0,
+ "A+B+D+E+F": 8.0,
+ "A+B+C+D+E+F": 2.0,
+ }
+ visual = differences(ROUTE_VISUAL_FIRST, _outcomes(_VISUAL_COSTS), detection_floor_ms = 0.5)
+ scheduler = differences(
+ ROUTE_SCHEDULER_FIRST, _outcomes(scheduler_costs), detection_floor_ms = 0.5
+ )
+ terms = {t.mechanism: t for t in interaction_terms(visual, scheduler, detection_floor_ms = 0.5)}
+ assert terms["autoscroll_forced_layout"].disagreement_ms == pytest.approx(9.0 - 18.0)
+ assert "not additive" in terms["autoscroll_forced_layout"].note
+ # nothing anywhere produced a mean of the two
+ assert terms["autoscroll_forced_layout"].value_a.value == pytest.approx(9.0)
+ assert terms["autoscroll_forced_layout"].value_b.value == pytest.approx(18.0)
+
+
+def test_routes_with_different_floors_cannot_be_compared():
+ other = LadderRoute(
+ route_id = "short",
+ name = "short",
+ steps = (Step(frozenset(), frozenset({"A"}), ("paint_raster",)),),
+ )
+ left = differences(ROUTE_VISUAL_FIRST, _outcomes(_VISUAL_COSTS))
+ right = differences(other, _outcomes({"shipping": 40.0, "A": 34.0}))
+ with pytest.raises(LadderError):
+ interaction_terms(left, right)
+
+
+def test_required_rungs_covers_both_routes():
+ keys = {arms_key(r) for r in required_rungs()}
+ assert "shipping" in keys
+ assert "A+B+C+D+E+F" in keys
+ assert "D" in keys and "A" in keys
+
+
+# ---------------------------------------------------------------------------------------
+# calibration
+# ---------------------------------------------------------------------------------------
+
+
+def test_a_batch_without_calibration_arms_is_refused_before_it_runs():
+ with pytest.raises(CalibrationMissing) as caught:
+ assert_batch_includes_calibration(["A", "B", "C"])
+ assert "NULL" in str(caught.value)
+ assert_batch_includes_calibration(["A", "NULL", "SPIKE0.1", "SPIKE0.5", "SPIKE2"])
+
+
+def _spike(spike_ms: float, burned: float, observed: float) -> dict:
+ return {
+ "spike_ms": spike_ms,
+ "burned_ms_per_update": Measure.read(burned, "ms/update"),
+ "observed_delta": Measure.read(observed, "ms/update"),
+ }
+
+
+def test_a_well_behaved_batch_is_quotable_and_prints_both_floors():
+ verdict = evaluate_batch(
+ null_deltas = [Measure.read(0.03, "ms/update")],
+ spike_observations = [
+ _spike(0.1, 0.11, 0.02),
+ _spike(0.5, 0.52, 0.49),
+ _spike(2.0, 2.05, 1.98),
+ ],
+ )
+ assert verdict.quotable is True
+ assert verdict.noise_floor_ms.value == pytest.approx(0.03)
+ assert verdict.detection_floor_ms.value == pytest.approx(0.5)
+ assert [s.recovered for s in verdict.spikes] == [False, True, True]
+ assert "recovery" in verdict.render()
+
+
+def test_a_batch_where_no_spike_is_recovered_is_not_quotable():
+ verdict = evaluate_batch(
+ null_deltas = [Measure.read(0.01, "ms/update")],
+ spike_observations = [
+ _spike(0.1, 0.11, 0.001),
+ _spike(0.5, 0.52, 0.004),
+ _spike(2.0, 2.05, 0.01),
+ ],
+ )
+ assert verdict.quotable is False
+ assert "could not see a cost it injected itself" in verdict.reason
+
+
+def test_a_batch_whose_null_arm_drifted_past_the_detection_floor_is_not_quotable():
+ verdict = evaluate_batch(
+ null_deltas = [Measure.read(0.6, "ms/update")],
+ spike_observations = [_spike(0.5, 0.5, 0.62), _spike(2.0, 2.0, 1.95)],
+ )
+ assert verdict.quotable is False
+ assert "read as different" in verdict.reason
+
+
+def test_a_noisy_batch_stays_quotable_but_only_at_a_coarser_floor():
+ """A noisy machine is not automatically a broken one; it is a machine with a blunt floor.
+
+ The null moves 0.9 ms/update, which swallows the 0.1 and 0.5 spikes entirely. The 2.0 spike
+ still comes back cleanly, so the batch can resolve differences above 2.0 ms/update and
+ nothing below it. Voiding this batch would throw away a usable, coarse measurement; quoting
+ a 0.3 ms difference from it would be inventing one. The detection floor is what keeps the
+ two apart, and every difference is rendered against it.
+ """
+
+ verdict = evaluate_batch(
+ null_deltas = [Measure.read(0.9, "ms/update")],
+ spike_observations = [
+ _spike(0.1, 0.1, 0.02),
+ _spike(0.5, 0.5, 0.49),
+ _spike(2.0, 2.0, 1.99),
+ ],
+ )
+ assert verdict.quotable is True
+ assert verdict.detection_floor_ms.value == pytest.approx(2.0)
+ assert Measure.read(0.3, "ms/update", floor = 2.0).display().startswith("< 2")
+
+
+def test_a_spike_read_at_the_wrong_magnitude_is_not_recovered():
+ verdict = evaluate_batch(
+ null_deltas = [Measure.read(0.02, "ms/update")],
+ spike_observations = [_spike(2.0, 2.0, 8.0)],
+ )
+ assert verdict.spikes[0].recovered is False
+ assert "outside" in verdict.spikes[0].note
+ assert verdict.quotable is False
+
+
+def test_a_batch_with_no_null_reading_has_no_noise_floor():
+ verdict = evaluate_batch(
+ null_deltas = [Measure.failed("ms/update", "the NULL cell crashed")],
+ spike_observations = [_spike(2.0, 2.0, 1.9)],
+ )
+ assert verdict.quotable is False
+ assert "no measured noise floor" in verdict.reason
+
+
+# ---------------------------------------------------------------------------------------
+# dose-response
+# ---------------------------------------------------------------------------------------
+
+
+def _dose_points(
+ per_child_ms: float,
+ intercept: float = 0.0,
+ chars: int = 50_000,
+):
+ return [
+ DosePoint(
+ dose = d, cost = Measure.read(intercept + per_child_ms * d, "ms"), content_chars = chars
+ )
+ for d in (4, 40, 400, 4000)
+ ]
+
+
+def test_a_line_through_the_origin_is_identified_as_o_children():
+ fit = fit_dose_response(_dose_points(0.002), detection_floor_ms = 0.5)
+ assert fit.verdict == "LINEAR THROUGH ORIGIN"
+ assert fit.slope_through_origin == pytest.approx(0.002, rel = 1e-6)
+
+
+def test_a_flat_result_is_an_informative_null_with_a_bound():
+ points = [
+ DosePoint(dose = d, cost = Measure.read(3.0, "ms"), content_chars = 50_000)
+ for d in (4, 40, 400, 4000)
+ ]
+ fit = fit_dose_response(points, detection_floor_ms = 0.5)
+ assert fit.verdict == "UNDERPOWERED NULL"
+ assert fit.min_detectable_slope.value == pytest.approx(0.5 / 4000)
+ assert "real bound" in fit.note
+
+
+def test_a_flat_result_without_a_detection_floor_cannot_be_turned_into_a_bound():
+ points = [
+ DosePoint(dose = d, cost = Measure.read(3.0, "ms"), content_chars = 50_000)
+ for d in (4, 40, 400, 4000)
+ ]
+ fit = fit_dose_response(points)
+ assert fit.verdict == "NULL, UNBOUNDED"
+ assert fit.min_detectable_slope.attempted is False
+
+
+def test_a_large_intercept_is_called_out_rather_than_reported_as_a_slope():
+ fit = fit_dose_response(_dose_points(0.0005, intercept = 6.0), detection_floor_ms = 0.1)
+ assert fit.verdict == "MOSTLY FIXED COST"
+
+
+def test_varying_content_across_doses_voids_the_design():
+ points = _dose_points(0.002)
+ points[-1] = DosePoint(dose = 4000, cost = Measure.read(9.0, "ms"), content_chars = 90_000)
+ fit = fit_dose_response(points, detection_floor_ms = 0.5)
+ assert fit.verdict == "INVALID"
+ assert "confounded" in fit.note
+
+
+def test_two_points_do_not_make_a_line():
+ points = _dose_points(0.002)[:2]
+ fit = fit_dose_response(points, detection_floor_ms = 0.5)
+ assert fit.verdict == "NO FIT"
+
+
+# ---------------------------------------------------------------------------------------
+# armpack
+# ---------------------------------------------------------------------------------------
+
+
+def _write_armpack(
+ root: Path,
+ digest: str,
+ arms = None,
+) -> Path:
+ arms = arms if arms is not None else {arm.arm_id: arm.arm_id.lower() for arm in BUNDLE_ARMS}
+ root.mkdir(parents = True, exist_ok = True)
+ for rel in arms.values():
+ (root / rel).mkdir(parents = True, exist_ok = True)
+ (root / "armpack.json").write_text(
+ json.dumps(
+ {
+ "armpack_version": "1",
+ "built_from_sha": "deadbeefcafe",
+ "target_dist_digest": digest,
+ "arms": arms,
+ }
+ ),
+ encoding = "utf-8",
+ )
+ return root
+
+
+def test_no_armpack_prints_the_banner_and_stops_that_plane(tmp_path: Path):
+ resolution = discover_armpack([tmp_path / "nowhere"], "digest-1")
+ assert resolution.available is False
+ assert BANNER in resolution.render()
+ assert "fibre-free twin does not run" in resolution.render()
+ with pytest.raises(Exception):
+ resolution.require()
+
+
+def test_a_mismatched_armpack_is_refused_rather_than_used(tmp_path: Path):
+ _write_armpack(tmp_path / "pack", "digest-other")
+ resolution = discover_armpack([tmp_path / "pack"], "digest-1")
+ assert resolution.available is False
+ assert "measure the build difference" in resolution.reason
+
+
+def test_a_partial_armpack_missing_the_twin_is_refused(tmp_path: Path):
+ arms = {
+ arm.arm_id: arm.arm_id.lower()
+ for arm in BUNDLE_ARMS
+ if arm.arm_id != ARM_FIBRE_FREE_TWIN.arm_id
+ }
+ _write_armpack(tmp_path / "pack", "digest-1", arms = arms)
+ resolution = discover_armpack([tmp_path / "pack"], "digest-1")
+ assert resolution.available is False
+ assert ARM_FIBRE_FREE_TWIN.arm_id in resolution.reason
+
+
+def test_a_matching_armpack_resolves(tmp_path: Path):
+ _write_armpack(tmp_path / "pack", "digest-1")
+ resolution = discover_armpack([tmp_path / "pack"], "digest-1")
+ assert resolution.available is True
+ assert resolution.require().target_dist_digest == "digest-1"
+
+
+# ---------------------------------------------------------------------------------------
+# recovery
+# ---------------------------------------------------------------------------------------
+
+
+def test_full_recovery_is_occupancy():
+ result = classify_recovery(
+ baseline = Measure.read(2.0, "ms/update"),
+ loaded = Measure.read(20.0, "ms/update"),
+ after_delete = Measure.read(2.4, "ms/update"),
+ noise_floor_ms = 0.5,
+ )
+ assert result.classification == "OCCUPANCY"
+
+
+def test_no_recovery_is_retained_structure():
+ result = classify_recovery(
+ baseline = Measure.read(2.0, "ms/update"),
+ loaded = Measure.read(20.0, "ms/update"),
+ after_delete = Measure.read(19.5, "ms/update"),
+ noise_floor_ms = 0.5,
+ )
+ assert result.classification == "RETAINED STRUCTURE"
+ assert "stays worse" in result.note
+
+
+def test_partial_recovery_is_not_rounded_to_whichever_is_convenient():
+ result = classify_recovery(
+ baseline = Measure.read(2.0, "ms/update"),
+ loaded = Measure.read(20.0, "ms/update"),
+ after_delete = Measure.read(11.0, "ms/update"),
+ noise_floor_ms = 0.5,
+ )
+ assert result.classification == "HYSTERETIC"
+ assert result.recovered_fraction == pytest.approx(0.5)
+
+
+def test_a_load_that_cost_nothing_has_an_undefined_recovery_not_a_perfect_one():
+ result = classify_recovery(
+ baseline = Measure.read(2.0, "ms/update"),
+ loaded = Measure.read(2.2, "ms/update"),
+ after_delete = Measure.read(2.1, "ms/update"),
+ noise_floor_ms = 0.5,
+ )
+ assert result.classification == "NOTHING TO RECOVER"
+ assert result.recovered_fraction is None
+ assert "UNDEFINED" in result.note
+
+
+def test_worse_after_delete_points_at_the_delete_path():
+ result = classify_recovery(
+ baseline = Measure.read(2.0, "ms/update"),
+ loaded = Measure.read(20.0, "ms/update"),
+ after_delete = Measure.read(26.0, "ms/update"),
+ noise_floor_ms = 0.5,
+ )
+ assert result.classification == "WORSE AFTER DELETE"
+
+
+# ---------------------------------------------------------------------------------------
+# knobs
+# ---------------------------------------------------------------------------------------
+
+
+def test_only_requested_preboot_arms_are_installed():
+ config = json.loads(config_init_script(["A", "D"]).split("=", 1)[1].strip().rstrip(";"))
+ assert config["preboot"] == ["D"]
+ assert config["requested"] == ["A", "D"]
+
+
+def test_an_unknown_arm_id_is_a_hard_error():
+ with pytest.raises(KeyError):
+ config_init_script(["A", "Z"])
+
+
+def test_split_arms_separates_preboot_from_apply_time():
+ preboot, runtime = split_arms(["A", "B", "C", "D", "E", "F", "G"])
+ assert set(preboot) == set(PREBOOT_ARM_IDS)
+ assert set(runtime) == {"A", "B", "C", "G"}
+
+
+def test_every_knob_declares_which_fix_its_outcome_implies():
+ table = render_decision_table()
+ for arm in RUNTIME_ARMS:
+ assert f" {arm.arm_id} removes:" in table
+ assert arm.implies_fix in table
+
+
+def test_the_control_arm_exists_and_is_not_a_treatment():
+ control = [arm for arm in RUNTIME_ARMS if arm.kind == "control"]
+ assert [arm.arm_id for arm in control] == ["G"]
diff --git a/tests/studio/studiobench/arms/selftest/test_studiobench_end_to_end.py b/tests/studio/studiobench/arms/selftest/test_studiobench_end_to_end.py
new file mode 100644
index 00000000000..f5601f162af
--- /dev/null
+++ b/tests/studio/studiobench/arms/selftest/test_studiobench_end_to_end.py
@@ -0,0 +1,371 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""End to end over synthetic data: plan a batch, judge it, render it, read it back.
+
+The unit tests check each rule in isolation. This file checks that the rules still hold once
+they are composed, which is where they usually stop holding: a `VOIDED` arm that gets rendered
+anyway because the renderer walks a different list, a not-quotable batch whose numbers appear in
+a summary assembled by a different function, a payload that validates on its own and fails once
+the harness layer's rows are in it.
+
+It also runs the two renderers for real and asserts on their OUTPUT, because a renderer that
+raises is a bug anyone finds and a renderer that prints the wrong thing is a bug nobody does.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.arms import ( # noqa: E402
+ ArmStatus,
+ BatchPlanError,
+ Invariance,
+ PlannedCell,
+ PotencyCounter,
+ arms_key,
+ assert_equal_scene_duration,
+ classify_recovery,
+ discover_armpack,
+ evaluate_batch,
+ fit_dose_response,
+ judge_batch,
+ missing_cells,
+ plan_batch,
+)
+from studiobench.arms.dose import DosePoint # noqa: E402
+from studiobench.arms.manifest import Arm, ArmOutcome # noqa: E402
+from studiobench.report import ( # noqa: E402
+ PayloadWriter,
+ assemble,
+ assemble_rows,
+ render_batch,
+ render_fix_implications,
+)
+from studiobench.scoring import Measure # noqa: E402
+
+
+def _arm(arm_id: str) -> Arm:
+ return Arm(
+ arm_id = arm_id,
+ title = arm_id,
+ mechanism = "synthetic",
+ invariance = Invariance.EXACT,
+ potency = PotencyCounter(name = "fired", min_delta = 1, direction = "increase"),
+ implies_fix = "synthetic",
+ )
+
+
+def _outcome(
+ key: str,
+ cost: float,
+ status: ArmStatus = ArmStatus.QUOTED,
+) -> ArmOutcome:
+ return ArmOutcome(
+ arm = _arm(key),
+ cost = Measure.read(cost, "ms/update"),
+ status = status,
+ reason = "synthetic",
+ potency_before = 0,
+ potency_after = 500,
+ )
+
+
+#: One coherent synthetic world: the autoscroll observer is the dominant cost on both routes,
+#: and the two routes disagree about it, which is the interaction the design exists to surface.
+_VISUAL = {
+ "shipping": 40.0,
+ "A": 34.0,
+ "A+B": 26.0,
+ "A+B+C": 18.0,
+ "A+B+C+D": 9.0,
+ "A+B+C+D+E": 7.0,
+ "A+B+C+D+E+F": 2.0,
+}
+_SCHEDULER = {
+ "shipping": 40.0,
+ "D": 22.0,
+ "D+E": 20.0,
+ "D+E+F": 15.0,
+ "A+D+E+F": 12.0,
+ "A+B+D+E+F": 8.0,
+ "A+B+C+D+E+F": 2.0,
+}
+
+
+def _all_outcomes() -> dict[str, ArmOutcome]:
+ merged = dict(_VISUAL)
+ merged.update(_SCHEDULER)
+ return {key: _outcome(key, cost) for key, cost in merged.items()}
+
+
+def _good_calibration():
+ return evaluate_batch(
+ null_deltas = [Measure.read(0.04, "ms/update")],
+ spike_observations = [
+ {
+ "spike_ms": 0.1,
+ "burned_ms_per_update": Measure.read(0.1, "ms/update"),
+ "observed_delta": Measure.read(0.02, "ms/update"),
+ },
+ {
+ "spike_ms": 0.5,
+ "burned_ms_per_update": Measure.read(0.5, "ms/update"),
+ "observed_delta": Measure.read(0.48, "ms/update"),
+ },
+ {
+ "spike_ms": 2.0,
+ "burned_ms_per_update": Measure.read(2.0, "ms/update"),
+ "observed_delta": Measure.read(1.97, "ms/update"),
+ },
+ ],
+ )
+
+
+def _blind_calibration():
+ return evaluate_batch(
+ null_deltas = [Measure.read(0.04, "ms/update")],
+ spike_observations = [
+ {
+ "spike_ms": 2.0,
+ "burned_ms_per_update": Measure.read(2.0, "ms/update"),
+ "observed_delta": Measure.read(0.005, "ms/update"),
+ }
+ ],
+ )
+
+
+# ---------------------------------------------------------------------------------------
+# planning
+# ---------------------------------------------------------------------------------------
+
+
+def test_a_planned_batch_covers_both_routes_and_the_calibration_arms():
+ planned = plan_batch()
+ keys = {cell.key for cell in planned}
+ assert "shipping" in keys
+ assert "A+B+C+D+E+F" in keys # the shared floor
+ assert {"NULL", "SPIKE0.1", "SPIKE0.5", "SPIKE2"} <= keys
+ assert missing_cells(planned, _all_outcomes()) # calibration cells are still to be run
+
+
+def test_arms_with_different_scene_lengths_are_refused_before_the_run():
+ assert_equal_scene_duration({"shipping": 40_000.0, "A": 40_000.5})
+ with pytest.raises(BatchPlanError) as caught:
+ assert_equal_scene_duration({"shipping": 40_000.0, "A": 44_000.0})
+ assert "saw different amounts of streaming" in str(caught.value)
+
+
+def test_no_scene_durations_at_all_is_a_refusal_not_a_pass():
+ with pytest.raises(BatchPlanError):
+ assert_equal_scene_duration({})
+
+
+# ---------------------------------------------------------------------------------------
+# judging and rendering
+# ---------------------------------------------------------------------------------------
+
+
+def test_a_quotable_batch_renders_steps_interactions_and_verdicts():
+ result = judge_batch(
+ rung_tokens = 100_000,
+ outcomes = _all_outcomes(),
+ calibration = _good_calibration(),
+ )
+ assert result.quotable is True
+ assert result.detection_floor_ms == pytest.approx(0.5)
+ assert len(result.routes) == 2
+ assert all(route.identity_holds for route in result.routes)
+
+ rendered = render_batch(result)
+ assert "ROUTE visual_first" in rendered
+ assert "ROUTE scheduler_first" in rendered
+ assert "INTERACTION TERMS" in rendered
+ assert "[FUSED]" in rendered
+ assert "Nothing here is averaged" in rendered
+ assert "ABLATION DECISION TABLE" in rendered
+ # the identity is stated and holds on both routes
+ assert rendered.count("no residual to attribute") == 2
+
+
+def test_no_absolute_arm_cost_appears_anywhere_in_the_rendered_batch():
+ """The rule that no arm is quoted alone has to survive rendering, not just the API."""
+
+ result = judge_batch(
+ rung_tokens = 100_000,
+ outcomes = _all_outcomes(),
+ calibration = _good_calibration(),
+ )
+ rendered = render_batch(result)
+ # 34.0 and 26.0 are arm costs; 8.00 and 6.00 are adjacent differences
+ assert "34.0 ms/update" not in rendered
+ assert "26.0 ms/update" not in rendered
+ assert "6.00 ms/update" in rendered # shipping -> A
+ assert "8.00 ms/update" in rendered # A -> A+B
+
+
+def test_a_not_quotable_batch_prints_no_ablation_numbers():
+ result = judge_batch(
+ rung_tokens = 100_000,
+ outcomes = _all_outcomes(),
+ calibration = _blind_calibration(),
+ )
+ assert result.quotable is False
+ rendered = render_batch(result)
+ assert "NO ABLATION NUMBERS ARE PRINTED" in rendered
+ assert "ROUTE visual_first" not in rendered
+ assert "6.00 ms/update" not in rendered
+ # the verdicts still print: a reader needs to know the arms ran
+ assert "ARM VERDICTS" in rendered
+
+
+def test_voided_and_not_run_arms_are_named_in_the_render():
+ outcomes = _all_outcomes()
+ outcomes["A+B"] = _outcome("A+B", 26.0, ArmStatus.VOIDED)
+ outcomes["A+B+C"] = ArmOutcome(
+ arm = _arm("A+B+C"),
+ cost = Measure.not_attempted("ms/update", "arm did not fire"),
+ status = ArmStatus.NOT_RUN,
+ reason = "potency counter did not move",
+ potency_before = 0,
+ potency_after = 0,
+ )
+ result = judge_batch(rung_tokens = 100_000, outcomes = outcomes, calibration = _good_calibration())
+ rendered = render_batch(result)
+ assert "VOIDED" in rendered
+ assert "NOT RUN arms are not evidence of no effect" in rendered
+ assert result.routes[0].identity_holds is False
+
+
+def test_fix_implications_rank_the_largest_step_and_name_its_fix():
+ result = judge_batch(
+ rung_tokens = 100_000,
+ outcomes = _all_outcomes(),
+ calibration = _good_calibration(),
+ )
+ rendered = render_fix_implications(result)
+ top = rendered.splitlines()[1].strip()
+ # the two routes disagree about the autoscroll observer, so the headline is a RANGE and both
+ # routes are named; quoting only the larger would let a reader pick the flattering route
+ assert top.startswith("9.000 to 18.000 ms")
+ assert "autoscroll_forced_layout" in top
+ assert "routes disagree: scheduler_first 18.000, visual_first 9.000" in rendered
+ assert "scrollHeight" in rendered
+
+
+def test_a_batch_with_a_dose_fit_an_armpack_refusal_and_a_recovery_renders_all_three(tmp_path):
+ dose = fit_dose_response(
+ [
+ DosePoint(dose = d, cost = Measure.read(0.002 * d, "ms"), content_chars = 50_000)
+ for d in (4, 40, 400, 4000)
+ ],
+ detection_floor_ms = 0.5,
+ )
+ recovery = classify_recovery(
+ baseline = Measure.read(2.0, "ms/update"),
+ loaded = Measure.read(20.0, "ms/update"),
+ after_delete = Measure.read(19.0, "ms/update"),
+ noise_floor_ms = 0.5,
+ )
+ armpack = discover_armpack([tmp_path / "absent"], "digest-1")
+ result = judge_batch(
+ rung_tokens = 100_000,
+ outcomes = _all_outcomes(),
+ calibration = _good_calibration(),
+ armpack = armpack,
+ dose = dose,
+ recovery = recovery,
+ )
+ rendered = render_batch(result)
+ assert "ABLATION ARMS NOT AVAILABLE FOR THIS BUILD" in rendered
+ assert "fibre-free twin does not run" in rendered
+ assert "LINEAR THROUGH ORIGIN" in rendered
+ assert "RETAINED STRUCTURE" in rendered
+
+
+# ---------------------------------------------------------------------------------------
+# the harness layer's row stream
+# ---------------------------------------------------------------------------------------
+
+
+def test_harness_rows_assemble_and_their_attested_zeros_survive(tmp_path: Path):
+ path = tmp_path / "payload.jsonl"
+ writer = PayloadWriter(path)
+ # written by hand rather than through PayloadWriter.write, because these are Layer 1's rows
+ with path.open("w", encoding = "utf-8") as handle:
+ rows = [
+ '{"row_type":"run_meta","tier":"quick","tool_version":"1","corpus_hash":"c",'
+ '"studio_ref":"main","bundle":"prod","platform":"linux","started_at":"now"}',
+ '{"row_type":"gate","name":"bundle_is_production","passed":true,"detail":{}}',
+ '{"row_type":"cell","cell_id":"r10K.A0.rep0","completed":true,"fidelity":"real"}',
+ '{"row_type":"window","cell_id":"r10K.A0.rep0","name":"action:scroll",'
+ '"kind":"action","t_open_ms":10.0,"duration_ms":4000.0,'
+ '"long_task_ms":0,"long_task_ms_attempted":true,'
+ '"react_stage_ms":null,"react_stage_ms_reason":"profiling alias not verified"}',
+ '{"row_type":"action","cell_id":"r10K.A0.rep0","action":"scroll","ran":true,'
+ '"expect_ok":false,"expect":{},"timings":{"gesture_ms":120.0},'
+ '"reason":"travelled 0 px","slot_missed":false}',
+ ]
+ handle.write("\n".join(rows) + "\n")
+ writer.close()
+
+ payload = assemble_rows(path)
+ assert payload["complete"] is True
+ assert len(payload["windows"]) == 1
+ # an attested zero survives validation; an action that failed its own assertion is excluded
+ assert payload["excluded_cells"][0]["reason"] == "slot_missed"
+ assert "must not be quoted" in payload["excluded_cells"][0]["detail"]
+
+ window = payload["windows"][0]
+ long_task = Measure.from_row(window, "long_task_ms")
+ assert long_task.has_reading and long_task.value == 0.0
+ react = Measure.from_row(window, "react_stage_ms")
+ assert react.has_reading is False
+ assert "profiling alias" in react.display()
+
+
+def test_a_run_with_no_completed_cell_is_not_complete(tmp_path: Path):
+ path = tmp_path / "payload.jsonl"
+ path.write_text(
+ '{"row_type":"run_meta","tier":"quick"}\n'
+ '{"row_type":"cell","cell_id":"r1M.A0.rep0","completed":false,'
+ '"failure_mode":"renderer crashed","fidelity":"real"}\n',
+ encoding = "utf-8",
+ )
+ payload = assemble_rows(path)
+ assert payload["complete"] is False
+ assert payload["excluded_cells"][0]["reason"] == "rung_incomplete"
+ assert "renderer crashed" in payload["excluded_cells"][0]["detail"]
+
+
+def test_the_two_writers_produce_the_same_assembled_shape(tmp_path: Path):
+ own = tmp_path / "own.jsonl"
+ writer = PayloadWriter(own)
+ writer.write("header", info = {"tier": "quick"})
+ writer.write("window", cell_id = "r1K.A0.rep0", metrics = {})
+ writer.write("footer", info = {"exit": "ok"})
+ writer.close()
+
+ rows = tmp_path / "rows.jsonl"
+ rows.write_text(
+ '{"row_type":"run_meta","tier":"quick"}\n'
+ '{"row_type":"window","cell_id":"r1K.A0.rep0"}\n'
+ '{"row_type":"cell","cell_id":"r1K.A0.rep0","completed":true}\n',
+ encoding = "utf-8",
+ )
+
+ left, right = assemble(own), assemble_rows(rows)
+ for key in ("schema", "complete", "excluded_cells", "windows", "crashes"):
+ assert key in left and key in right
+ assert left["complete"] is True and right["complete"] is True
+
+
+def test_missing_cells_is_computed_not_assumed():
+ planned = [PlannedCell(arms = frozenset({"A"}), role = "ladder")]
+ assert missing_cells(planned, {}) == [arms_key({"A"})]
+ assert missing_cells(planned, {"A": _outcome("A", 1.0)}) == []
diff --git a/tests/studio/studiobench/arms/selftest/test_studiobench_knobs_contract.py b/tests/studio/studiobench/arms/selftest/test_studiobench_knobs_contract.py
new file mode 100644
index 00000000000..cb5d88b4a11
--- /dev/null
+++ b/tests/studio/studiobench/arms/selftest/test_studiobench_knobs_contract.py
@@ -0,0 +1,134 @@
+# 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 contract between `knobs.py` and `knobs.js`, pinned so it cannot drift silently.
+
+Every arm's manifest names two strings that live on the other side of a language boundary: a
+potency counter and, for an EQUIVALENT arm, the diff keys it is allowed to produce. Neither is
+checked by any compiler, and both fail in the worst possible direction.
+
+A misspelled potency counter reads as `NOT RUN` for an arm that fired perfectly. A mismatched diff
+key reads as `VOIDED` for an arm whose output never changed. Both are conservative, so neither
+produces a wrong NUMBER, and that is exactly why they can survive for weeks: the report simply
+says less than it could, forever, and nobody can tell the difference between a knob that is
+broken and a mechanism that is not there.
+
+This was not hypothetical. Arm B declared its allowed diff as `style` while the browser side
+emits `attr:style` (namespaced so that an attribute called `text` cannot collide with the
+structural text key). B would have been voided on every run of every batch.
+"""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.arms.knobs import ( # noqa: E402
+ KNOBS_JS_PATH,
+ PREBOOT_ARM_IDS,
+ RUNTIME_ARMS,
+ init_scripts_for,
+ load_knobs_js,
+)
+
+
[email protected](scope = "module")
+def knobs_js() -> str:
+ return load_knobs_js()
+
+
+def test_the_injected_file_exists_and_is_not_a_stub(knobs_js: str):
+ assert KNOBS_JS_PATH.is_file()
+ assert len(knobs_js) > 10_000
+
+
+def test_every_potency_counter_name_exists_on_the_browser_side(knobs_js: str):
+ """A counter the browser never writes reads as NOT RUN for an arm that fired."""
+
+ for arm in RUNTIME_ARMS:
+ assert arm.potency.name in knobs_js, (
+ f"arm {arm.arm_id} declares potency counter {arm.potency.name!r}, which does not "
+ "appear in knobs.js. That arm will read NOT RUN on every run"
+ )
+
+
+def test_every_declared_diff_key_exists_on_the_browser_side(knobs_js: str):
+ """A key the browser never emits voids the arm on every run."""
+
+ for arm in RUNTIME_ARMS:
+ if arm.declared_diff is None:
+ continue
+ for key in arm.declared_diff.keys:
+ assert key in knobs_js, (
+ f"arm {arm.arm_id} declares diff key {key!r}, which knobs.js never emits. That "
+ "arm will be VOIDED on every run"
+ )
+
+
+def test_the_public_api_the_python_side_calls_is_present(knobs_js: str):
+ for symbol in (
+ "__sbArms",
+ "__sbArmConfig",
+ "apply",
+ "revert",
+ "potency",
+ "counts",
+ "digest",
+ "diffKeys",
+ "available",
+ "unavailable",
+ ):
+ assert symbol in knobs_js, f"knobs.js does not expose {symbol}"
+
+
+def test_the_selectors_the_arms_depend_on_are_the_shipped_ones(knobs_js: str):
+ for selector in (
+ "aui-stream-viewport",
+ "data-message-id",
+ 'data-status="running"',
+ 'data-streamdown="code-block"',
+ "--aui-scroll-stabilizer",
+ "aria-expanded",
+ ):
+ assert selector in knobs_js, f"knobs.js does not reference {selector}"
+
+
+def test_every_arm_id_is_reachable_from_the_browser_side(knobs_js: str):
+ for arm in RUNTIME_ARMS:
+ assert f'"{arm.arm_id}"' in knobs_js or f"'{arm.arm_id}'" in knobs_js
+
+
+def test_init_scripts_are_ordered_config_then_knobs():
+ scripts = init_scripts_for(["A", "D"])
+ assert scripts[0].startswith("window.__sbArmConfig")
+ assert "__sbArms" in scripts[1]
+ assert len(scripts) == 2
+
+
+def test_preboot_arms_are_the_ones_that_patch_a_prototype(knobs_js: str):
+ """D, E and F patch something the app captures during boot; the rest do not."""
+
+ assert PREBOOT_ARM_IDS == frozenset({"D", "E", "F"})
+ for needle in (
+ "MutationObserver.prototype",
+ "CSSStyleDeclaration.prototype",
+ "MessageChannel",
+ ):
+ assert needle in knobs_js
+
+
[email protected](shutil.which("node") is None, reason = "node is not installed")
+def test_knobs_js_parses():
+ result = subprocess.run(
+ ["node", "--check", str(KNOBS_JS_PATH)],
+ capture_output = True,
+ text = True,
+ check = False,
+ )
+ assert result.returncode == 0, result.stderr
diff --git a/tests/studio/studiobench/arms/selftest/test_studiobench_selfcheck.py b/tests/studio/studiobench/arms/selftest/test_studiobench_selfcheck.py
new file mode 100644
index 00000000000..9874210a3d3
--- /dev/null
+++ b/tests/studio/studiobench/arms/selftest/test_studiobench_selfcheck.py
@@ -0,0 +1,232 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Unit tests for the integrity gates in `instruments/selfcheck.py`.
+
+These live under `arms/selftest/` rather than beside the module because `instruments/` is shared
+with the layer that owns the frame recorder, and this layer owns only `selfcheck.py` inside it.
+
+Every gate is tested in BOTH directions. The passing direction is the easy half and the one that
+gets written; the failing direction is the half that matters, because a gate that cannot fail is
+decoration, and the whole point of this file is that a failure ABORTS the run rather than
+appearing as a caveat under a table.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.instruments.selfcheck import ( # noqa: E402
+ SelfCheckFailure,
+ evaluate_clock_pair,
+ evaluate_input_delay_gate,
+ evaluate_longtask_support,
+ evaluate_scene_contrast_gate,
+ evaluate_stall_gate,
+ evaluate_tri_clock,
+ guard,
+ run_gates,
+)
+from studiobench.scoring.schema import EXCLUSION_REASONS, check_exclusion_reasons # noqa: E402
+
+
+# ---------------------------------------------------------------------------------------
+# the injected stall
+# ---------------------------------------------------------------------------------------
+
+
+def test_a_120ms_stall_seen_within_tolerance_passes():
+ assert evaluate_stall_gate(121.0).passed is True
+ assert evaluate_stall_gate(139.0).passed is True
+
+
+def test_a_stall_the_recorder_missed_fails_the_run():
+ gate = evaluate_stall_gate(12.0)
+ assert gate.passed is False
+ assert "mis-attributing" in gate.detail
+
+
+def test_no_stall_reading_at_all_is_a_failure_not_a_pass():
+ gate = evaluate_stall_gate(None)
+ assert gate.passed is False
+ assert gate.measured.attempted is True
+ assert gate.measured.has_reading is False
+
+
+# ---------------------------------------------------------------------------------------
+# the injected input delay
+# ---------------------------------------------------------------------------------------
+
+
+def test_a_400ms_input_delay_must_move_p95_by_350ms():
+ assert evaluate_input_delay_gate(20.0, 415.0).passed is True
+
+
+def test_an_input_path_that_does_not_move_is_not_measuring_input():
+ gate = evaluate_input_delay_gate(20.0, 24.0)
+ assert gate.passed is False
+ assert "will not move when the app gets slower" in gate.detail
+
+
+# ---------------------------------------------------------------------------------------
+# scene contrast: the blindness check
+# ---------------------------------------------------------------------------------------
+
+
+def test_a_heavy_and_a_trivial_scene_must_differ():
+ assert evaluate_scene_contrast_gate(300.0, 100.0).passed is True
+
+
+def test_an_instrument_that_cannot_tell_heavy_from_trivial_is_blind():
+ gate = evaluate_scene_contrast_gate(104.0, 100.0)
+ assert gate.passed is False
+ assert "BLIND" in gate.detail
+
+
+# ---------------------------------------------------------------------------------------
+# longtask support
+# ---------------------------------------------------------------------------------------
+
+
+def test_longtask_support_is_read_from_supported_entry_types():
+ supported = evaluate_longtask_support(["mark", "measure", "longtask"])
+ assert "available on this engine" in supported.detail
+ unsupported = evaluate_longtask_support(["mark", "measure"])
+ assert "NOT ATTEMPTED rather than as zero" in unsupported.detail
+ # not supporting longtask is a fact about the engine, not a reason to abort
+ assert unsupported.fatal is False
+ assert unsupported.passed is True
+
+
+def test_an_unreadable_support_list_is_recorded_and_not_guessed():
+ gate = evaluate_longtask_support(None)
+ assert gate.passed is False
+ assert gate.fatal is False
+
+
+# ---------------------------------------------------------------------------------------
+# the clock-pair control ratio
+# ---------------------------------------------------------------------------------------
+
+
+def test_a_flat_control_ratio_passes():
+ assert evaluate_clock_pair(10_000.0, 10_020.0).passed is True
+
+
+def test_a_moving_control_ratio_means_the_measurement_moved():
+ gate = evaluate_clock_pair(10_000.0, 8_000.0)
+ assert gate.passed is False
+ assert "the MEASUREMENT moved, not the page" in gate.detail
+
+
+# ---------------------------------------------------------------------------------------
+# three-clock agreement
+# ---------------------------------------------------------------------------------------
+
+
+def test_three_agreeing_clocks_keep_the_window():
+ verdict = evaluate_tri_clock(
+ wall_ms = 10_000.0,
+ raf_span_ms = 9_900.0,
+ screencast_span_ms = 9_850.0,
+ timer_span_ms = 10_010.0,
+ raf_frames = 600,
+ )
+ assert verdict.agreed is True
+ assert verdict.excluded_cell("r3.w1") is None
+
+
+def test_an_unscheduled_raf_loop_reads_as_no_measurement_not_as_no_dropped_frames():
+ """The trap this gate exists for: no frames looks exactly like a perfectly smooth window."""
+
+ verdict = evaluate_tri_clock(
+ wall_ms = 10_000.0,
+ raf_span_ms = 0.0,
+ screencast_span_ms = 9_900.0,
+ timer_span_ms = 10_000.0,
+ raf_frames = 0,
+ )
+ assert verdict.agreed is False
+ assert "unmeasured one" in verdict.reason
+ cell = verdict.excluded_cell("r4.w2")
+ assert cell is not None
+ assert cell.reason == "clock_disagreement"
+ check_exclusion_reasons([cell])
+
+
+def test_a_clock_more_than_twenty_percent_off_excludes_the_window():
+ verdict = evaluate_tri_clock(
+ wall_ms = 10_000.0,
+ raf_span_ms = 6_000.0,
+ screencast_span_ms = 9_900.0,
+ timer_span_ms = 10_000.0,
+ raf_frames = 120,
+ )
+ assert verdict.agreed is False
+ assert verdict.worst_clock == "raf"
+ assert verdict.worst_disagreement_pct == pytest.approx(40.0)
+
+
+def test_agreement_between_fewer_than_two_clocks_is_not_agreement():
+ verdict = evaluate_tri_clock(
+ wall_ms = 10_000.0,
+ raf_span_ms = 9_900.0,
+ screencast_span_ms = None,
+ timer_span_ms = None,
+ raf_frames = 600,
+ )
+ assert verdict.agreed is False
+ assert "fewer than two clocks" in verdict.reason
+
+
+def test_clock_disagreement_is_a_declared_exclusion_reason():
+ assert "clock_disagreement" in EXCLUSION_REASONS
+
+
+# ---------------------------------------------------------------------------------------
+# the whole gate set
+# ---------------------------------------------------------------------------------------
+
+
+def _healthy(**overrides):
+ args = {
+ "stall_observed_ms": 122.0,
+ "keystroke_p95_baseline_ms": 22.0,
+ "keystroke_p95_delayed_ms": 430.0,
+ "heavy_scene_ms": 380.0,
+ "trivial_scene_ms": 100.0,
+ "supported_entry_types": ["longtask"],
+ "clock_pair_page_ms": 10_000.0,
+ "clock_pair_driver_ms": 10_010.0,
+ }
+ args.update(overrides)
+ return args
+
+
+def test_a_healthy_instrument_passes_every_gate():
+ report = run_gates(**_healthy())
+ assert report.ok is True
+ assert "all gates held" in report.render()
+ guard(report) # does not raise
+
+
+def test_one_failed_gate_aborts_the_run_before_any_numbers():
+ report = run_gates(**_healthy(stall_observed_ms = 5.0))
+ assert report.ok is False
+ messages = []
+ with pytest.raises(SelfCheckFailure) as caught:
+ guard(report, on_abort = messages.append)
+ assert messages and "ABORT" in messages[0]
+ assert "no cells will be measured" in str(caught.value)
+
+
+def test_the_abort_message_says_why_reporting_nothing_is_better():
+ report = run_gates(**_healthy(heavy_scene_ms = 101.0))
+ with pytest.raises(SelfCheckFailure) as caught:
+ report.raise_if_failed()
+ assert "the numbers get quoted and the blindness does not" in str(caught.value)
diff --git a/tests/studio/studiobench/build.py b/tests/studio/studiobench/build.py
new file mode 100644
index 00000000000..5000b67d166
--- /dev/null
+++ b/tests/studio/studiobench/build.py
@@ -0,0 +1,126 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Build `dist/studiobench.pyz`: ONE file an external tester runs.
+
+ python -m tests.studio.studiobench.build
+ python dist/studiobench.pyz --doctor
+
+WHY ONE FILE. The people whose machines matter most are the ones who will not clone a monorepo,
+create a virtualenv and read a README to find out that their laptop drops frames at 90K characters.
+A zipapp is `python studiobench.pyz --doctor`, and the doctor then says in one screen what is
+missing and what each missing piece costs.
+
+WHAT GOES IN. The package, the frozen corpus, and the pieces of `tests/studio/_playwright_robust.py`
+that the runtime asks for by name. What does NOT go in is anything from `pip`: a zipapp cannot
+carry Playwright, which ships a node driver and a browser, so the bootstrap is stdlib-only and
+`--doctor` is what tells a tester to `pip install playwright && playwright install`.
+
+WHAT IS DELIBERATELY NOT COMPRESSED AWAY. `fixture/corpus/frozen/units.jsonl` is most of the
+artifact's size and all of its meaning: it is the frozen text, and shipping the generator instead
+of the text would make every tester's corpus a function of their own copy of the generator. The
+manifest's per-unit digests are checked at load, so a corpus that drifted refuses to run rather
+than quietly measuring something else.
+"""
+
+from __future__ import annotations
+
+import shutil
+import zipapp
+from pathlib import Path
+
+PKG = Path(__file__).resolve().parent
+REPO = PKG.parents[2]
+DEFAULT_OUT = REPO / "dist" / "studiobench.pyz"
+
+# Everything under the package except caches and the build's own scratch.
+EXCLUDE_DIRS = {"__pycache__", ".pytest_cache", "dist", "build"}
+EXCLUDE_SUFFIXES = {".pyc", ".pyo"}
+
+MAIN = "tests.studio.studiobench.__main__:main_argv"
+
+
+def _copy_package(staging: Path) -> None:
+ target = staging / "tests" / "studio" / "studiobench"
+ target.parent.mkdir(parents = True, exist_ok = True)
+ shutil.copytree(PKG, target, ignore = shutil.ignore_patterns(*EXCLUDE_DIRS, "*.pyc", "*.pyo"))
+ # `tests` and `tests/studio` must be importable packages inside the archive, and they are not
+ # packages in the repository -- the harnesses there are standalone scripts.
+ for pkg_dir in (staging / "tests", staging / "tests" / "studio"):
+ init = pkg_dir / "__init__.py"
+ if not init.exists():
+ init.write_text("# generated by studiobench.build\n", encoding = "utf-8")
+
+
+def _copy_robust(staging: Path) -> bool:
+ """`_playwright_robust.py` if it is there.
+
+ Vendored rather than imported, for the same reason lifecycle is: the artifact runs on a
+ machine with no checkout. `runtime/browser.py` imports it by either name and survives its
+ absence, so a build without it is degraded rather than broken -- it loses the maintained
+ Chromium flags, the view-transition killer and `dump_diagnostics`.
+ """
+ src = REPO / "tests" / "studio" / "_playwright_robust.py"
+ if not src.exists():
+ return False
+ shutil.copy2(src, staging / "tests" / "studio" / "_playwright_robust.py")
+ return True
+
+
+def build(out: Path = DEFAULT_OUT, compressed: bool = True) -> Path:
+ out = Path(out).resolve()
+ out.parent.mkdir(parents = True, exist_ok = True)
+ staging = out.parent / "_studiobench_staging"
+ if staging.exists():
+ shutil.rmtree(staging)
+ staging.mkdir(parents = True)
+
+ _copy_package(staging)
+ had_robust = _copy_robust(staging)
+
+ frozen = staging / "tests" / "studio" / "studiobench" / "fixture" / "corpus" / "frozen"
+ if not (frozen / "manifest.json").exists():
+ raise FileNotFoundError(
+ "the frozen corpus is not in the tree. Run "
+ "`python -m tests.studio.studiobench.fixture.corpus --freeze` before building, or the "
+ "artifact ships a benchmark with no content."
+ )
+
+ # A __main__.py at the archive root is what `python foo.pyz` executes. It re-exports the
+ # package's CLI rather than duplicating it.
+ (staging / "__main__.py").write_text(
+ "import sys\n"
+ "from tests.studio.studiobench.__main__ import main\n"
+ "raise SystemExit(main(sys.argv[1:]))\n",
+ encoding = "utf-8",
+ )
+
+ zipapp.create_archive(
+ staging, target = out, interpreter = "/usr/bin/env python3", compressed = compressed
+ )
+ shutil.rmtree(staging)
+ size_mb = out.stat().st_size / 1048576
+ print(f"built {out} ({size_mb:.1f} MB)")
+ if not had_robust:
+ print(
+ " NOTE: _playwright_robust.py was not found, so the artifact falls back to its own "
+ "Chromium flags and diagnostics"
+ )
+ print(f" run it with: python {out.name} --doctor")
+ return out
+
+
+def _main(argv: list) -> int:
+ import argparse
+
+ ap = argparse.ArgumentParser(description = "Build the studiobench zipapp.")
+ ap.add_argument("--out", default = str(DEFAULT_OUT))
+ ap.add_argument("--no-compress", action = "store_true")
+ args = ap.parse_args(argv)
+ build(Path(args.out), compressed = not args.no_compress)
+ return 0
+
+
+if __name__ == "__main__":
+ import sys
+ raise SystemExit(_main(sys.argv[1:]))
diff --git a/tests/studio/studiobench/fixture/__init__.py b/tests/studio/studiobench/fixture/__init__.py
new file mode 100644
index 00000000000..b1eaa3dbad2
--- /dev/null
+++ b/tests/studio/studiobench/fixture/__init__.py
@@ -0,0 +1,4 @@
+# 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 frozen deterministic corpus and the thread seeder."""
diff --git a/tests/studio/studiobench/fixture/corpus.py b/tests/studio/studiobench/fixture/corpus.py
new file mode 100644
index 00000000000..439bceb990f
--- /dev/null
+++ b/tests/studio/studiobench/fixture/corpus.py
@@ -0,0 +1,964 @@
+# 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 deterministic, frozen benchmark corpus.
+
+THREE properties, and each of them was a bug in an earlier fixture:
+
+1. **Frozen.** The text is generated once from a seed and written to `corpus/frozen/units.jsonl`,
+ which SHIPS. A benchmark whose content is regenerated by whatever version of the generator the
+ tester happens to have is not a benchmark, it is two different measurements with one name. The
+ generator stays in the tree so the corpus can be rebuilt deliberately, and `manifest.json`
+ carries a sha256 per unit so a rebuild that changes a single character is refused rather than
+ quietly measured.
+
+2. **Every unit unique.** Shiki caches highlighted output keyed on the SOURCE STRING. A fixture
+ that repeats one fence pays the highlight cost exactly once and reports the other 99 as free,
+ which is how a harness measures a 300K-character thread and finds no highlighting cost in it.
+ Every fence here carries its unit index in its identifiers, so no two fences in the whole corpus
+ are byte-identical and the cache never hits. Unique units are only half of it: a PLAN that hands
+ one unit to more than one turn restores the caching without changing a byte of the corpus, which
+ is what an index clamp in `plan_rung` used to do at the top rung. `check_streamed_units_are_new`
+ states that half, and the manifest is sized from the ladder so no rung can reach it.
+
+3. **The field's own span density.** The captured 90,262-character reply carried 16,186 highlight
+ spans, i.e. 5.6 characters per span, which only happens if the content is nearly all fenced
+ code. 1,250 characters of prose against an 1,800-character fence lands on that; an all-fence
+ fixture measures 3.47, half again as much work per character as real content. Plus a fence-free
+ PREAMBLE: the capture held a flat 60 fps and exactly zero spans for its first 33,348 characters
+ and started dropping frames at the first CLOSED fence, so a fixture with no such stretch cannot
+ show where the onset is, only that there is one.
+
+The escalating cycle -- reasoning@10K, code@8K, reasoning@20K, code@16K, ... -- exists because a
+thread of identical turns is not what gets slow. Each cycle doubles until the cap, so a long thread
+is a few enormous replies among many small ones, which is the shape of a real session.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import random
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Iterator, Optional
+
+FROZEN_DIR = Path(__file__).resolve().parent / "corpus" / "frozen"
+UNITS_JSONL = FROZEN_DIR / "units.jsonl"
+MANIFEST_JSON = FROZEN_DIR / "manifest.json"
+
+CORPUS_SEED = 20260819
+CORPUS_VERSION = 1
+
+# Span density, calibrated against the field capture. See the module docstring. These are now the
+# MEANS of a jittered distribution rather than fixed sizes -- see `_jitter`.
+PROSE_CHARS = 1250
+FENCE_CHARS = 1800
+PREAMBLE_FRACTION = 0.25
+
+# How far each block's size may wander from its mean, as a fraction. Real replies do not emit
+# identically sized paragraphs and fences, and a fixture that does lets a cost that is really
+# per-block masquerade as per-character (and vice versa): with every block the same size the two
+# are perfectly collinear and no measurement can separate them. Jitter breaks that.
+#
+# Applied through the PER-UNIT rng, so unit 40 is still the same text whether it was reached by
+# generating 41 units or by asking for that one. Randomised is not the same as nondeterministic:
+# the corpus hash still pins every byte.
+BLOCK_JITTER = 0.55
+
+# Unit sizes wander too, around the escalating nominal. Same reason at the turn level: a thread of
+# turns that are all exactly 10,000 characters is not the shape of a real session, and the rung
+# planner then has no short turns to land its target on.
+UNIT_JITTER = 0.35
+
+# Tool calls per unit, as a range. The thread renders a tool group for each, which is a component
+# with its own mount and update cost and which nothing in the corpus previously exercised.
+TOOL_CALLS_PER_UNIT = (0, 3)
+
+#: The stored part shape that actually renders a tool block. VERIFIED, not assumed: seeding a flat
+#: `{"type": "tool-call", ...}` and an assistant-ui style `{"type": "tool-invocation", ...}` both
+#: rendered their sibling text and NO tool UI, while this shape produced a "Used tool" group. A
+#: corpus full of parts the app ignores looks richer and measures nothing.
+TOOL_NAMES = ("web_search", "code_execution", "python", "terminal", "search_knowledge_base")
+
+# The escalating cycle. Reasoning first because a turn's reasoning is what the pane holds open.
+CYCLE_BASE = ((("reasoning", 10_000), ("code", 8_000)),)
+# Doubling stops here. Without a cap the eighth cycle is a single 2.5M-character reply, which is
+# not a thread, it is one document -- and it makes the 1M rung one turn deep, where every
+# per-message cost this tool exists to measure is multiplied by one.
+MAX_UNIT_CHARS = 320_000
+
+# Text below `units.jsonl` ships for every rung up to and including this many characters. Beyond
+# it the units are regenerated on the tester's machine and checked against the manifest hash, so
+# drift is still impossible; only the bytes are not carried in the artifact.
+SHIPPED_CHARS_BUDGET = 460_000
+
+
+# ── the vocabulary ──────────────────────────────────────────────────
+#
+# Deliberately mundane. The point of the corpus is span density and uniqueness, not realism of
+# meaning, and a vocabulary a reader can skim is a vocabulary a reader can spot a bug in.
+
+_NOUNS = (
+ "buffer",
+ "scheduler",
+ "fibre",
+ "observer",
+ "commit",
+ "layout",
+ "token",
+ "shard",
+ "lane",
+ "chunk",
+ "boundary",
+ "descriptor",
+ "checkpoint",
+ "gradient",
+ "kernel",
+ "adapter",
+ "window",
+ "residual",
+ "quantiser",
+ "allocator",
+ "transcript",
+ "viewport",
+ "sentinel",
+ "digest",
+)
+_VERBS = (
+ "reparses",
+ "flushes",
+ "clones",
+ "invalidates",
+ "schedules",
+ "accumulates",
+ "walks",
+ "coalesces",
+ "materialises",
+ "spills",
+ "reconciles",
+ "hoists",
+ "pins",
+ "drains",
+)
+_ADJS = (
+ "cumulative",
+ "monotonic",
+ "deferred",
+ "synchronous",
+ "transient",
+ "bounded",
+ "retained",
+ "speculative",
+ "interleaved",
+ "hysteretic",
+ "collinear",
+ "saturating",
+)
+_CONNECTIVES = (
+ "which means",
+ "so in practice",
+ "and therefore",
+ "but only when",
+ "except that",
+ "as long as",
+ "provided that",
+ "which is why",
+)
+_LANGS = ("python", "typescript", "rust", "go", "c")
+# Short names for code. See _fence: span density is per TOKEN, so long names dilute it.
+_SHORT = (
+ "a",
+ "b",
+ "c",
+ "d",
+ "e",
+ "f",
+ "g",
+ "h",
+ "i",
+ "j",
+ "k",
+ "n",
+ "p",
+ "q",
+ "s",
+ "t",
+ "u",
+ "v",
+ "w",
+ "x",
+ "y",
+ "z",
+ "acc",
+ "buf",
+ "idx",
+ "key",
+ "len",
+ "map",
+ "ptr",
+ "res",
+ "tmp",
+)
+
+
+@dataclass(frozen = True)
+class Unit:
+ """One assistant turn's worth of content."""
+
+ index: int
+ kind: str # "reasoning" | "code"
+ reasoning: str # goes out as delta.reasoning_content
+ content: str # goes out as delta.content
+ chars: int
+ sha256: str
+ #: Stored tool-call parts for this turn, in the shape the app renders. Not counted in `chars`:
+ #: `chars` is the rung's size axis and must stay comparable with every earlier measurement,
+ #: while a tool call's cost is a mount, not a character count. Reported separately.
+ tool_calls: tuple = ()
+
+ @property
+ def tool_call_count(self) -> int:
+ return len(self.tool_calls)
+
+ def as_row(self) -> dict:
+ return {
+ "index": self.index,
+ "kind": self.kind,
+ "chars": self.chars,
+ "sha256": self.sha256,
+ "reasoning": self.reasoning,
+ "content": self.content,
+ "tool_calls": list(self.tool_calls),
+ }
+
+ def clipped_to(self, chars: int) -> "Unit":
+ """A prefix of this unit at WHOLE BLOCK boundaries, for a rung smaller than one turn.
+
+ The smallest rung is 1K tokens, about 4,000 characters, and the escalating cycle's first
+ turn is 10,000. Something has to give, and clipping the first turn is the only option that
+ leaves the cycle itself intact for every rung above.
+
+ Blocks, not characters, and the reason is a rendering path rather than tidiness: the parts
+ are separated by blank lines and every fence is one whole part, so a block-aligned prefix
+ can never end inside a fence. A character-aligned one can, and an unclosed fence is a
+ DIFFERENT Streamdown path (the incomplete-fence branch) with a different cost, so the
+ smallest rung would have been measuring something no other rung measures.
+ """
+ if chars >= self.chars:
+ return self
+
+ def take(text: str, budget: int) -> str:
+ blocks = text.split("\n\n")
+ out: list[str] = []
+ size = 0
+ for b in blocks:
+ if out and size + len(b) + 2 > budget:
+ break
+ out.append(b)
+ size += len(b) + 2
+ return "\n\n".join(out)
+
+ # Keep the unit's own reasoning/content split, so a clipped turn has the same shape as a
+ # whole one and the smallest rung is not accidentally all-visible or all-reasoning.
+ reasoning_budget = max(1, int(chars * (len(self.reasoning) / self.chars)))
+ reasoning = take(self.reasoning, reasoning_budget)
+ content = take(self.content, max(1, chars - len(reasoning)))
+ text = reasoning + content
+ return Unit(
+ index = self.index,
+ kind = self.kind,
+ reasoning = reasoning,
+ content = content,
+ chars = len(text),
+ # A DIFFERENT digest, deliberately. A clipped unit is not the frozen unit and must not
+ # be checked against its hash or reported under it.
+ sha256 = "clip:"
+ + hashlib.sha256(f"{self.sha256}\x00{chars}".encode("utf-8")).hexdigest(),
+ # Tool calls survive clipping. They carry no `chars` weight, so dropping them would
+ # silently remove a whole component from exactly the rung -- the smallest -- that every
+ # growth ratio is taken against.
+ tool_calls = self.tool_calls,
+ )
+
+ @classmethod
+ def from_row(cls, row: dict) -> "Unit":
+ return cls(
+ index = row["index"],
+ kind = row["kind"],
+ reasoning = row["reasoning"],
+ content = row["content"],
+ chars = row["chars"],
+ sha256 = row["sha256"],
+ tool_calls = tuple(row.get("tool_calls") or ()),
+ )
+
+
+# ── generation ──────────────────────────────────────────────────────
+
+
+def _sentence(rng: random.Random, salt: str) -> str:
+ return (
+ f"The {rng.choice(_ADJS)} {rng.choice(_NOUNS)} {rng.choice(_VERBS)} the "
+ f"{rng.choice(_ADJS)} {rng.choice(_NOUNS)}_{salt}, {rng.choice(_CONNECTIVES)} the "
+ f"{rng.choice(_NOUNS)} stays {rng.choice(_ADJS)}."
+ )
+
+
+def _prose(rng: random.Random, target: int, salt: str) -> str:
+ """`target` characters of fence-free prose. No span will ever be built over any of it."""
+ out: list[str] = []
+ size = 0
+ while size < target:
+ para: list[str] = []
+ for _ in range(rng.randint(3, 6)):
+ s = _sentence(rng, salt)
+ para.append(s)
+ size += len(s) + 1
+ out.append(" ".join(para))
+ size += 2
+ if size >= target:
+ break
+ return "\n\n".join(out)
+
+
+def _fence(
+ rng: random.Random,
+ target: int,
+ salt: str,
+ lang: Optional[str] = None,
+) -> str:
+ """`target` characters of fenced code, unique to `salt`.
+
+ The salt is in every identifier, not just in a comment. Shiki keys its cache on the whole
+ source string, so a comment would be enough to miss the cache -- but a highlighter that ever
+ learns to normalise comments would silently restore the caching and halve the measured cost
+ without changing a number in the report. Identifiers cannot be normalised away.
+ """
+ lang = lang or rng.choice(_LANGS)
+ lines = [f"```{lang}"]
+ size = len(lines[0]) + 1
+ i = 0
+ # SHORT identifiers and dense punctuation, because the density target is a SPAN count, not a
+ # character count. Long descriptive names are cheap to highlight per character: the field
+ # capture ran at 5.6 characters per span, and a first version of this generator with
+ # `cumulative_buffer_0007_12`-style names measured 10.1, i.e. half the highlighter work per
+ # character of the content it is standing in for. Real code is mostly operators.
+ r = rng.randint
+
+ def v() -> str:
+ # A MIX of short and long names. All-short measured 3.95 characters per span against the
+ # field's 5.6 and all-long measured 10.1, so neither extreme stands in for real code. The
+ # mix is the tuning knob for the offline proxy; the number that actually gets reported is
+ # the span density MEASURED in the DOM at run time, because Shiki merges adjacent
+ # same-scope tokens and no offline count can predict that exactly.
+ return rng.choice(_SHORT) if rng.random() < 0.55 else rng.choice(_NOUNS)
+
+ while size < target:
+ # ONE salted identifier per line is all the uniqueness Shiki's source-keyed cache needs,
+ # and it leaves the rest of the line free to be dense.
+ u = f"{rng.choice(_SHORT)}{salt}{i}"
+ if lang == "python":
+ line = (
+ f" {u}={v()}[{r(0,9)}]*{r(2,99)}-{v()}({v()},{v()})+{v()}[{r(0,9)}:{r(1,9)}]"
+ f";{v()}={v()}%{r(2,9)} if {v()}>{r(1,99)} else {v()}|{r(1,7)}"
+ )
+ elif lang == "typescript":
+ line = (
+ f" const {u}={{a:{v()}[{r(0,9)}],b:{v()}({v()},{r(1,99)}),c:{v()}?{v()}:"
+ f"{r(0,9)}}};{v()}={v()}&{r(1,7)}|{v()}<<{r(1,7)};"
+ )
+ elif lang == "rust":
+ line = (
+ f" let {u}:u64={v()}[{r(0,9)}]^{v()}({v()},{r(1,99)})&{r(1,255)};"
+ f"{v()}={v()}.iter().map(|x|x*{r(2,99)}).sum::<u64>();"
+ )
+ elif lang == "go":
+ line = (
+ f"\t{u}:={v()}[{r(0,9)}]+{v()}({v()},{r(1,99)})*{r(2,99)};"
+ f"{v()},{v()}={v()}%{r(2,9)},{v()}>>{r(1,7)}"
+ )
+ else:
+ line = (
+ f" uint64_t {u}={v()}[{r(0,9)}]|({v()}({v()},{r(1,99)})&0x{r(16,255):02x})"
+ f";{v()}=*{v()}++^{r(1,255)};"
+ )
+ lines.append(line)
+ size += len(line) + 1
+ i += 1
+ lines.append("```")
+ return "\n".join(lines)
+
+
+def _jitter(
+ rng: random.Random,
+ mean: int,
+ spread: float = BLOCK_JITTER,
+ floor: int = 80,
+) -> int:
+ """A size around `mean`, never below `floor`.
+
+ Uniform on [1-spread, 1+spread] rather than lognormal: the point is to decorrelate block size
+ from block count, and a symmetric spread does that while keeping the MEAN exactly where the
+ span-density calibration put it. A skewed distribution would quietly move the mean and with it
+ the characters-per-span figure the whole corpus is tuned to.
+ """
+ return max(floor, int(mean * (1.0 + rng.uniform(-spread, spread))))
+
+
+def _body(rng: random.Random, target: int, salt: str, *, preamble: bool) -> str:
+ """Preamble, then a jittered prose/fence alternation, to `target` characters."""
+ parts: list[str] = []
+ size = 0
+ if preamble:
+ want = int(target * PREAMBLE_FRACTION)
+ head = _prose(rng, want, f"{salt}p")
+ parts.append(head)
+ size += len(head) + 2
+ while size < target:
+ p = _prose(rng, _jitter(rng, PROSE_CHARS), f"{salt}{len(parts)}")
+ parts.append(p)
+ size += len(p) + 2
+ if size >= target:
+ break
+ f = _fence(rng, _jitter(rng, FENCE_CHARS), f"{salt}{len(parts)}")
+ parts.append(f)
+ size += len(f) + 2
+ return "\n\n".join(parts)
+
+
+def _tool_calls(rng: random.Random, salt: str) -> list[dict]:
+ """Zero to three tool calls for one turn, in the part shape the app actually renders."""
+ low, high = TOOL_CALLS_PER_UNIT
+ out: list[dict] = []
+ for i in range(rng.randint(low, high)):
+ name = rng.choice(TOOL_NAMES)
+ query = _prose(rng, _jitter(rng, 220, floor = 40), f"{salt}t{i}q").replace("\n", " ")
+ result = _prose(rng, _jitter(rng, 900, floor = 120), f"{salt}t{i}r")
+ args = (
+ {"query": query} if name in ("web_search", "search_knowledge_base") else {"code": query}
+ )
+ out.append(
+ {
+ "type": "tool-call",
+ "toolCallId": f"call_{salt}_{i}",
+ "toolName": name,
+ "argsText": json.dumps(args),
+ "args": args,
+ "state": "result",
+ "result": result,
+ }
+ )
+ return out
+
+
+def _unit_targets(index: int) -> tuple[str, int]:
+ """(kind, target chars) for unit `index` of the escalating cycle."""
+ cycle = index // 2
+ slot = index % 2
+ base = 10_000 if slot == 0 else 8_000
+ kind = "reasoning" if slot == 0 else "code"
+ nominal = min(MAX_UNIT_CHARS, base * (2**cycle))
+ # Jittered around the nominal, deterministic in `index` alone so the escalating shape survives
+ # while no two turns are the same size. A separate RNG from the body's, so changing block
+ # jitter does not reshuffle which turns are large.
+ rng = random.Random((index * 6_364_136_223_846_793_005) ^ 0x5DEECE66D)
+ return kind, max(1_500, min(MAX_UNIT_CHARS, _jitter(rng, nominal, UNIT_JITTER, floor = 1_500)))
+
+
+def generate_unit(index: int, seed: int = CORPUS_SEED) -> Unit:
+ """Unit `index`, deterministic in (seed, index) alone.
+
+ Seeded per unit and not per corpus, so unit 40 is the same text whether it was reached by
+ generating 41 units or by asking for that one. A corpus-level RNG would make the 1M rung's
+ early turns differ from the 1K rung's, and then two rungs would not share a prefix and the
+ growth curve would be over two different corpora.
+ """
+ rng = random.Random((seed * 1_000_003) ^ (index * 2_654_435_761))
+ kind, target = _unit_targets(index)
+ salt = f"{index:04d}"
+ if kind == "reasoning":
+ # A reasoning turn: most of the mass arrives as delta.reasoning_content, so the cumulative
+ # <think> re-parse in the chat adapter is what pays for it.
+ reasoning = _body(rng, int(target * 0.8), f"r{salt}", preamble = True)
+ content = _body(rng, int(target * 0.2), f"a{salt}", preamble = False)
+ else:
+ # A code turn: the mass is visible content, so the cost lands on Streamdown and Shiki.
+ reasoning = _prose(rng, 1_200, f"r{salt}")
+ content = _body(rng, target, f"a{salt}", preamble = False)
+ tools = tuple(_tool_calls(rng, salt))
+ chars = len(reasoning) + len(content)
+ digest = hashlib.sha256(
+ (
+ f"{index}\x00{kind}\x00{reasoning}\x00{content}\x00" + json.dumps(tools, sort_keys = True)
+ ).encode("utf-8")
+ ).hexdigest()
+ return Unit(
+ index = index,
+ kind = kind,
+ reasoning = reasoning,
+ content = content,
+ chars = chars,
+ sha256 = digest,
+ tool_calls = tools,
+ )
+
+
+def units_for_chars(total_chars: int, seed: int = CORPUS_SEED) -> list[Unit]:
+ """The shortest prefix of the cycle whose characters reach `total_chars`."""
+ out: list[Unit] = []
+ size = 0
+ index = 0
+ while size < total_chars:
+ u = generate_unit(index, seed)
+ out.append(u)
+ size += u.chars
+ index += 1
+ if index > 4096:
+ raise RuntimeError("corpus cycle did not reach the requested size")
+ return out
+
+
+# ── freezing and loading ────────────────────────────────────────────
+
+
+def freeze(
+ max_chars: int = SHIPPED_CHARS_BUDGET,
+ seed: int = CORPUS_SEED,
+ out_dir: Path = FROZEN_DIR,
+) -> dict:
+ """Write `units.jsonl` and `manifest.json`. Run deliberately; never on a benchmark run."""
+ out_dir.mkdir(parents = True, exist_ok = True)
+ shipped = units_for_chars(max_chars, seed)
+ # The manifest covers every unit any rung can reach, including the ones whose text is not
+ # shipped, so a regenerated unit at the 1M rung is still checked byte for byte. SIZED FROM THE
+ # LADDER, by `manifest_unit_count`, rather than from a bare character budget: the streamed turn
+ # and its follow-ups live PAST the seeded prefix, and a manifest that stops where the prefix
+ # stops leaves them nothing to point at.
+ all_units = [generate_unit(i, seed) for i in range(manifest_unit_count(seed))]
+ with (out_dir / "units.jsonl").open("w", encoding = "utf-8") as fh:
+ for u in shipped:
+ fh.write(json.dumps(u.as_row(), ensure_ascii = False) + "\n")
+ manifest = {
+ "corpus_version": CORPUS_VERSION,
+ "seed": seed,
+ "prose_chars": PROSE_CHARS,
+ "fence_chars": FENCE_CHARS,
+ "preamble_fraction": PREAMBLE_FRACTION,
+ "max_unit_chars": MAX_UNIT_CHARS,
+ "shipped_units": len(shipped),
+ "shipped_chars": sum(u.chars for u in shipped),
+ "units": [
+ {"index": u.index, "kind": u.kind, "chars": u.chars, "sha256": u.sha256}
+ for u in all_units
+ ],
+ }
+ manifest["corpus_hash"] = corpus_hash(manifest)
+ (out_dir / "manifest.json").write_text(
+ json.dumps(manifest, indent = 2, ensure_ascii = False) + "\n", encoding = "utf-8"
+ )
+ return manifest
+
+
+def corpus_hash(manifest: dict) -> str:
+ """One hash over the generator's parameters and every unit digest.
+
+ Includes the parameters, not only the unit hashes, because two corpora with the same text and
+ different declared densities would otherwise compare as identical.
+ """
+ h = hashlib.sha256()
+ for key in (
+ "corpus_version",
+ "seed",
+ "prose_chars",
+ "fence_chars",
+ "preamble_fraction",
+ "max_unit_chars",
+ ):
+ h.update(f"{key}={manifest[key]}\x00".encode("utf-8"))
+ for u in manifest["units"]:
+ h.update(f"{u['index']}:{u['sha256']}\x00".encode("utf-8"))
+ return h.hexdigest()
+
+
+class Corpus:
+ """The frozen corpus, with every unit checked against the manifest before it is used."""
+
+ def __init__(self, manifest: dict, shipped: dict[int, Unit], seed: int) -> None:
+ self.manifest = manifest
+ self.seed = seed
+ self._shipped = shipped
+ self._expected = {u["index"]: u["sha256"] for u in manifest["units"]}
+ self.corpus_hash = manifest["corpus_hash"]
+ self.regenerated: list[int] = []
+
+ @classmethod
+ def load(cls, frozen_dir: Optional[Path] = None) -> "Corpus":
+ # Through the resource loader, NOT a filesystem path. Inside `studiobench.pyz` the frozen
+ # corpus is a zip member and every Path built from __file__ points at something that
+ # cannot exist; the built artifact's own --doctor is what caught it.
+ from ..runtime import resources
+
+ if frozen_dir is not None:
+ manifest_path = Path(frozen_dir) / "manifest.json"
+ if not manifest_path.exists():
+ raise FileNotFoundError(f"no frozen manifest at {manifest_path}")
+ raw_manifest = manifest_path.read_text(encoding = "utf-8")
+ raw_units = ""
+ units_path = Path(frozen_dir) / "units.jsonl"
+ if units_path.exists():
+ raw_units = units_path.read_text(encoding = "utf-8")
+ else:
+ try:
+ raw_manifest = resources.read_text("fixture/corpus/frozen/manifest.json")
+ except (FileNotFoundError, OSError) as exc:
+ raise FileNotFoundError(
+ "the frozen corpus is not in this build. Run "
+ "`python -m tests.studio.studiobench.fixture.corpus --freeze` to build it."
+ ) from exc
+ try:
+ raw_units = resources.read_text("fixture/corpus/frozen/units.jsonl")
+ except (FileNotFoundError, OSError):
+ raw_units = ""
+ manifest = json.loads(raw_manifest)
+ recomputed = corpus_hash(manifest)
+ if recomputed != manifest.get("corpus_hash"):
+ raise ValueError(
+ f"the frozen manifest's own corpus_hash does not match its contents "
+ f"({manifest.get('corpus_hash')} declared, {recomputed} recomputed). The corpus "
+ "has been edited by hand; rebuild it with --freeze."
+ )
+ shipped: dict[int, Unit] = {}
+ for line in raw_units.splitlines():
+ line = line.strip()
+ if line:
+ u = Unit.from_row(json.loads(line))
+ shipped[u.index] = u
+ return cls(manifest, shipped, manifest["seed"])
+
+ def unit(self, index: int) -> Unit:
+ """Unit `index`, from the shipped text if it is there and regenerated if it is not.
+
+ EITHER WAY it is checked against the manifest digest. A regenerated unit that does not
+ match is a hard failure: it means the generator in this tree does not produce the corpus
+ this artifact claims to measure, and every number after it would be from a different
+ fixture with the same name.
+ """
+ u = self._shipped.get(index)
+ if u is None:
+ u = generate_unit(index, self.seed)
+ self.regenerated.append(index)
+ expected = self._expected.get(index)
+ if expected is None:
+ raise KeyError(f"unit {index} is outside the frozen manifest")
+ if u.sha256 != expected:
+ raise ValueError(
+ f"corpus unit {index} does not match the frozen manifest "
+ f"(expected {expected[:16]}, got {u.sha256[:16]}). The generator has drifted; "
+ "this tree cannot reproduce the shipped corpus."
+ )
+ return u
+
+ def units_for_chars(self, total_chars: int) -> list[Unit]:
+ out: list[Unit] = []
+ size = 0
+ index = 0
+ while size < total_chars:
+ u = self.unit(index)
+ out.append(u)
+ size += u.chars
+ index += 1
+ return out
+
+ def iter_units(self) -> Iterator[Unit]:
+ for entry in self.manifest["units"]:
+ yield self.unit(entry["index"])
+
+
+# ── rungs ───────────────────────────────────────────────────────────
+
+RUNGS: dict[str, int] = {
+ "1K": 1_000,
+ "10K": 10_000,
+ "100K": 100_000,
+ "500K": 500_000,
+ "1M": 1_000_000,
+}
+
+# The PROVISIONAL ratio used to size the corpus before anything has been tokenised. It is never
+# reported: `chars_per_token` in every row is the MEASURED one, and it is measured per rung.
+PROVISIONAL_CHARS_PER_TOKEN = 4.0
+
+# How much of the last turn STREAMS, at every rung. See the long note in `plan_rung`.
+#
+# Sized from the film, not chosen round: the quick scene's during-generation slots occupy the
+# first 16 s and the first after-generation slot opens at 22.5 s, so the stream has to finish
+# inside roughly 20 s. At the field cadence of 24 characters every 73 ms -- 328.8 chars/s -- that
+# is about 6,500 characters. Rounded DOWN so the stream reliably drains before the first action
+# that claims the reply is complete, rather than finishing exactly as it starts.
+STREAM_TAIL_CHARS = 6_000
+
+# How many turns actually stream per cell: the opening one plus the follow-ups the `send_turn`
+# action sends mid-film. They SHARE the budget above rather than each getting it, so three turns
+# and one turn take the same wall clock. Three because the corpus alternates reasoning-heavy and
+# code-heavy units, so three consecutive turns are guaranteed to cover both kinds.
+STREAM_TURNS = 3
+
+# Each follow-up's size. Small on purpose: the follow-ups exist to sample "what does a chunk cost
+# given what is already on screen" at two more points inside the cell, not to add mass.
+FOLLOW_UP_CHARS = 1_500
+
+# Below this the rung streams ONCE. Three turns need about 9,000 characters of budget and the 1K
+# rung is 4,000 characters in total, so splitting it three ways produced an opening stream that
+# drained in four seconds -- shorter than the during-generation slots timed against it -- and a
+# rung 40% over its own target. A small rung is allowed to be a single exchange, which is also
+# what a 1K-token conversation actually is.
+MULTI_TURN_MIN_CHARS = 20_000
+
+# The largest characters-per-token the FROZEN CORPUS is sized for, which is not the same number as
+# the provisional ratio used to plan a rung. `plan_rung` takes a measured ratio, and a corpus sized
+# at exactly the provisional 4.0 has no material left the moment a machine measures 4.1. A quarter
+# of headroom costs a handful of extra manifest entries -- the text of an unshipped unit is
+# regenerated only when a rung actually reaches it -- and buys every ratio the seeder can plausibly
+# report. Past it `plan_rung` refuses rather than degrades.
+MANIFEST_CHARS_PER_TOKEN = 5.0
+
+
+def manifest_unit_count(
+ seed: int = CORPUS_SEED, chars_per_token: float = MANIFEST_CHARS_PER_TOKEN
+) -> int:
+ """How many units the frozen manifest must carry, DERIVED FROM THE LADDER.
+
+ The corpus used to be sized by a bare `RUNGS["1M"] * 4` character budget, which is exactly the
+ largest rung's seeded target and therefore one unit short of what the largest rung needs. The
+ streamed turn is the unit AFTER the seeded prefix and each follow-up is one after that, so the
+ top rung's stream ran off the end of the manifest and a `min(index, last_index)` clamp folded
+ all three onto the final unit: the opening stream re-sent text already seeded, both follow-ups
+ were byte-identical, and every fence in them hit Shiki's source-keyed cache instead of missing
+ it. The rung that exists to be the most expensive one on the ladder was measured as the
+ cheapest per character, and nothing failed.
+
+ So the ladder sizes the corpus and not the reverse: the longest seeded prefix any rung can ask
+ for, plus one unit per streamed turn beyond it.
+ """
+ prefix = len(units_for_chars(int(max(RUNGS.values()) * chars_per_token), seed))
+ return prefix + STREAM_TURNS
+
+
+@dataclass
+class RungPlan:
+ """What a rung is made of, and how much of it streams rather than being seeded."""
+
+ rung: str
+ target_tokens: int
+ target_chars: int
+ seeded_units: list[Unit] = field(default_factory = list)
+ streamed_unit: Optional[Unit] = None
+ #: Further turns streamed DURING the film by the `send_turn` action. They come out of the same
+ #: fixed streaming budget as the first, split between them, so more turns cost no wall clock.
+ follow_up_units: list[Unit] = field(default_factory = list)
+
+ @property
+ def seeded_chars(self) -> int:
+ return sum(u.chars for u in self.seeded_units)
+
+ @property
+ def streamed_chars(self) -> int:
+ return self.streamed_unit.chars if self.streamed_unit else 0
+
+ @property
+ def follow_up_chars(self) -> int:
+ return sum(u.chars for u in self.follow_up_units)
+
+ @property
+ def total_chars(self) -> int:
+ # The follow-ups are part of the rung's mass: they are streamed INTO the thread during the
+ # film and are on screen for most of it. Leaving them out understated every rung by the
+ # follow-up budget, which at the 1K rung is most of the rung.
+ return self.seeded_chars + self.streamed_chars + self.follow_up_chars
+
+
+def _too_small(rung: str, chars_per_token: float, last_index: int, what: str) -> ValueError:
+ """The one message for every way a rung can outgrow the frozen corpus.
+
+ Deliberately an ERROR and not a clamp. The clamp it replaces is how a 1M rung came to stream
+ the same unit three times and report the cheapest per-character cost on the ladder, and a
+ benchmark that quietly measures something smaller than it says is worse than one that stops.
+ """
+ return ValueError(
+ f"the frozen corpus is too small for the {rung} rung at {chars_per_token} chars per "
+ f"token: {what} runs past the manifest, which ends at index {last_index}. Re-freeze with "
+ "`python -m tests.studio.studiobench.fixture.corpus --freeze` after raising "
+ "MANIFEST_CHARS_PER_TOKEN, and note that a re-freeze changes corpus_hash and so ends "
+ "comparability with everything measured before it."
+ )
+
+
+def unit_text(unit: Unit) -> str:
+ """Everything a unit puts on screen, in the order it arrives."""
+ return unit.reasoning + unit.content
+
+
+def check_streamed_units_are_new(plan: RungPlan) -> None:
+ """Every streamed turn must be material the thread has not seen. Raises when it is not.
+
+ This is the corpus's whole reason for existing, restated at the level of a rung plan. Shiki
+ caches highlighted output keyed on the SOURCE STRING, so a fence that has already been rendered
+ once in this thread costs nothing the second time. Property 2 in the module docstring keeps
+ every unit in the corpus distinct; it says nothing about a PLAN that hands the same unit to
+ three turns, which is exactly what the index clamp used to do at the top rung.
+
+ Checked as a PREFIX relation and not equality, because the streamed turns are clipped and a
+ clipped unit is a prefix of the unit it came from. Two turns clipped from one unit are not
+ equal and would pass an equality check while sharing every fence they have.
+
+ Run on every plan rather than only in a test: this is not a property to discover afterwards
+ from a table of numbers that came out lower than they should have.
+ """
+ streamed: list[tuple[str, str]] = []
+ if plan.streamed_unit is not None:
+ streamed.append(("streamed", unit_text(plan.streamed_unit)))
+ for i, unit in enumerate(plan.follow_up_units):
+ streamed.append((f"follow_up[{i}]", unit_text(unit)))
+
+ def fail(what: str, a: str, b: str) -> None:
+ raise ValueError(
+ f"rung {plan.rung}: {a} and {b} {what}. A streamed turn that repeats material already "
+ "on screen hits Shiki's source-keyed cache instead of missing it, so the rung reports "
+ "less work per character than it does. The corpus is too small for this ladder; "
+ "re-freeze it with `--freeze`."
+ )
+
+ seeded = [(f"seeded unit {u.index}", unit_text(u)) for u in plan.seeded_units]
+ for i, (label, text) in enumerate(streamed):
+ if not text:
+ raise ValueError(f"rung {plan.rung}: {label} is empty")
+ for other_label, other in streamed[i + 1 :] + seeded:
+ if text.startswith(other) or other.startswith(text):
+ fail("share a prefix", label, other_label)
+
+
+def plan_rung(
+ corpus: Corpus,
+ rung: str,
+ chars_per_token: float = PROVISIONAL_CHARS_PER_TOKEN,
+) -> RungPlan:
+ """Which units are SEEDED and which one STREAMS.
+
+ Only the last reply streams. At the field's own cadence, 24 characters every 73ms, a million
+ tokens is three and a half hours of streaming; a benchmark nobody can run measures nothing.
+ The seeded/streamed equivalence is CHECKED at the 10K rung rather than assumed, and rungs
+ above it are labelled `fidelity: seeded_only` when that check fails.
+ """
+ tokens = RUNGS[rung]
+ target_chars = int(tokens * chars_per_token)
+
+ # THE STREAMED TAIL IS THE SAME SIZE AT EVERY RUNG, and the whole size ladder lives in the
+ # seeded prefix. This is not tidiness, it is what makes the film mean anything above 10K.
+ #
+ # The scene is a FIXED-DURATION film whose slots are wall-clock times: three actions run
+ # "during generation" and ten run "after the reply is complete". At the field's own cadence
+ # of 24 characters every 73 ms, a streamed tail that grows with the rung takes 11 s at 1K,
+ # 54 s at 10K, 354 s at 100K and 811 s at 1M -- against a film 135 s long. Above 10K the
+ # stream outlasts the entire film, so every action labelled "after the reply is complete"
+ # runs mid-generation. The run still completes and still prints a full table; the labels are
+ # simply false, which is worse than a crash.
+ #
+ # Holding the tail constant also isolates the variable under investigation. The question is
+ # what a streamed chunk costs AS A FUNCTION OF THE THREAD ALREADY ON SCREEN, and that needs
+ # the chunk workload held fixed while the thread grows, not both moving together.
+ turns = STREAM_TURNS if target_chars >= MULTI_TURN_MIN_CHARS else 1
+ tail_target = min(STREAM_TAIL_CHARS, target_chars)
+ follow_budget = FOLLOW_UP_CHARS * (turns - 1)
+ seed_target = max(0, target_chars - tail_target - follow_budget)
+
+ # Size the SEEDED PREFIX to the remainder, then trim its last unit to land on the target.
+ # Growing it a whole unit at a time instead overshoots by up to one turn, which at the 1K
+ # rung means 13,333 characters against a 4,000-character budget.
+ last_index = max(e["index"] for e in corpus.manifest["units"])
+ try:
+ seeded = corpus.units_for_chars(seed_target) if seed_target > 0 else []
+ except KeyError as exc:
+ # The prefix alone outgrew the manifest, before any streamed turn was even asked for.
+ raise _too_small(rung, chars_per_token, last_index, "its seeded prefix alone") from exc
+ if seeded:
+ overshoot = sum(u.chars for u in seeded) - seed_target
+ if overshoot > 0:
+ seeded[-1] = seeded[-1].clipped_to(max(1, seeded[-1].chars - overshoot))
+
+ # The streamed turn is the next one after the prefix, clipped to the fixed tail, and each
+ # follow-up is the one after that.
+ #
+ # NO CLAMP HERE, deliberately. This used to be `min(index, last_index)`, so a rung whose prefix
+ # reached the end of the manifest silently got the final unit three times over: the opening
+ # stream re-sent text the seeded prefix already held, both follow-ups were byte-identical, and
+ # every fence in all three hit Shiki's source-keyed cache. Running off the end is a corpus that
+ # is too small for the ladder, and the only honest answer is to say so and stop. `--freeze`
+ # sizes the manifest from the ladder (`manifest_unit_count`) precisely so this cannot be
+ # reached by any supported configuration.
+ needed = len(seeded) + turns - 1
+ if needed > last_index:
+ raise _too_small(
+ rung,
+ chars_per_token,
+ last_index,
+ f"its {len(seeded)}-unit seeded prefix plus {turns} streamed turns need units up to "
+ f"index {needed}, which",
+ )
+
+ # The streaming budget is SPLIT across the opening turn and the follow-ups, so a cell that
+ # streams three times takes the same wall clock as one that streams once. Turns are taken from
+ # consecutive corpus units, which alternate reasoning-heavy and code-heavy, so the follow-ups
+ # exercise the `<think>` re-parse and the Streamdown path rather than repeating one of them.
+ # The opening turn keeps the FULL tail budget and the follow-ups are extra. The three
+ # during-generation slots are timed against the opening stream, so it has to outlast them;
+ # splitting the budget between turns left it draining in four seconds and those slots then ran
+ # against a finished reply while still being labelled "during generation".
+ streamed = corpus.unit(len(seeded)).clipped_to(tail_target)
+ follow_ups = [corpus.unit(len(seeded) + i).clipped_to(FOLLOW_UP_CHARS) for i in range(1, turns)]
+
+ plan = RungPlan(
+ rung = rung,
+ target_tokens = tokens,
+ target_chars = target_chars,
+ seeded_units = seeded,
+ streamed_unit = streamed,
+ follow_up_units = follow_ups,
+ )
+ check_streamed_units_are_new(plan)
+ return plan
+
+
+def _main(argv: list[str]) -> int:
+ import argparse
+
+ ap = argparse.ArgumentParser(description = "Build or verify the frozen studiobench corpus.")
+ ap.add_argument("--freeze", action = "store_true", help = "regenerate frozen/*.jsonl")
+ ap.add_argument("--verify", action = "store_true", help = "check the tree against the freeze")
+ args = ap.parse_args(argv)
+ if args.freeze:
+ m = freeze()
+ print(
+ f"froze {m['shipped_units']} units, {m['shipped_chars']:,} chars, "
+ f"{len(m['units'])} manifest entries"
+ )
+ print(f"corpus_hash {m['corpus_hash']}")
+ return 0
+ c = Corpus.load()
+ n = 0
+ for _ in c.iter_units():
+ n += 1
+ print(f"verified {n} units against corpus_hash {c.corpus_hash}")
+ print(f"regenerated (not shipped as text): {len(c.regenerated)} units")
+ for rung in RUNGS:
+ p = plan_rung(c, rung)
+ print(
+ f" {rung:>5}: {len(p.seeded_units):>4} seeded units, "
+ f"{p.seeded_chars:>10,} seeded chars, {p.streamed_chars:>9,} streamed chars"
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ import sys
+ raise SystemExit(_main(sys.argv[1:]))
diff --git a/tests/studio/studiobench/fixture/corpus/frozen/manifest.json b/tests/studio/studiobench/fixture/corpus/frozen/manifest.json
new file mode 100644
index 00000000000..988b2f6d3ef
--- /dev/null
+++ b/tests/studio/studiobench/fixture/corpus/frozen/manifest.json
@@ -0,0 +1,187 @@
+{
+ "corpus_version": 1,
+ "seed": 20260819,
+ "prose_chars": 1250,
+ "fence_chars": 1800,
+ "preamble_fraction": 0.25,
+ "max_unit_chars": 320000,
+ "shipped_units": 10,
+ "shipped_chars": 519859,
+ "units": [
+ {
+ "index": 0,
+ "kind": "reasoning",
+ "chars": 14330,
+ "sha256": "34b38c7ba1d699be6720d5109d8c6733872b3de825a2fe698bcdbe27f3f70a1a"
+ },
+ {
+ "index": 1,
+ "kind": "code",
+ "chars": 12764,
+ "sha256": "43fc94336bcbb4cfc08ecb5aee51b5b0ce38a260133dc1c5d53ba94eb6232b88"
+ },
+ {
+ "index": 2,
+ "kind": "reasoning",
+ "chars": 17023,
+ "sha256": "9bdc426b3119b8a6c895b1d003dd7fc5f59d416879376b7c2fea44e65947e613"
+ },
+ {
+ "index": 3,
+ "kind": "code",
+ "chars": 13360,
+ "sha256": "a3871d6c4f07d5f4bdcb8e6a2f6723f5410d4c26bf183fd217f3e8be2282835d"
+ },
+ {
+ "index": 4,
+ "kind": "reasoning",
+ "chars": 37342,
+ "sha256": "ba3163bb88e62d0771b7a4279e856d6ed9454852a3e85ba6f34cf48cfe24bc5c"
+ },
+ {
+ "index": 5,
+ "kind": "code",
+ "chars": 38493,
+ "sha256": "02f5aecb56006e344b48378f0798f78f8ee99edcb7c7e9c12dd82a23170e8ad7"
+ },
+ {
+ "index": 6,
+ "kind": "reasoning",
+ "chars": 60234,
+ "sha256": "7886a0579e049655c0b62bfcf14fa1aaeb8dcf4bc67bc3349e631a4c31308762"
+ },
+ {
+ "index": 7,
+ "kind": "code",
+ "chars": 72699,
+ "sha256": "5b50618cefbaec3c272966181fff3e020371b13e0d73789abbdb83048f58b4b6"
+ },
+ {
+ "index": 8,
+ "kind": "reasoning",
+ "chars": 134652,
+ "sha256": "c4a673b33a53412589a1b0e07ad2f6accdee8b1cd1dda664498f7bd0c313f752"
+ },
+ {
+ "index": 9,
+ "kind": "code",
+ "chars": 118962,
+ "sha256": "02c8f74850a8a084346b302fecd84311c6ed9497ae67df6c895372fbef2321ee"
+ },
+ {
+ "index": 10,
+ "kind": "reasoning",
+ "chars": 322573,
+ "sha256": "3fcb5742b92126db74ac6164c9c562e78ecfc5bdccd13351a0f90b8218a1e365"
+ },
+ {
+ "index": 11,
+ "kind": "code",
+ "chars": 321517,
+ "sha256": "81d705a0bff4fd797afe162d0f6808197ef68a4adc6afb3635ca473c48691573"
+ },
+ {
+ "index": 12,
+ "kind": "reasoning",
+ "chars": 293631,
+ "sha256": "6773835c83f01881e541d998180f9655ae58e17bc06dad3a7290d3e78e585a11"
+ },
+ {
+ "index": 13,
+ "kind": "code",
+ "chars": 322362,
+ "sha256": "3ab482461e43d4cb7c5e6e5f7d3af0413818e81938ac9453c9b753c1c5bae0ca"
+ },
+ {
+ "index": 14,
+ "kind": "reasoning",
+ "chars": 306095,
+ "sha256": "d76e971b0f1a860065a03747062d747138770dc6eb6e688f9f6bfeb555bdd8a8"
+ },
+ {
+ "index": 15,
+ "kind": "code",
+ "chars": 322406,
+ "sha256": "538d8c1684d1bb0a1be1f9c51928f87aac2cd93076e90d3d74f1a0424637d7ed"
+ },
+ {
+ "index": 16,
+ "kind": "reasoning",
+ "chars": 323391,
+ "sha256": "9ee00ce6b25d83bc4708324ea1d4321d8117bee427fce95c46f448b000e127fd"
+ },
+ {
+ "index": 17,
+ "kind": "code",
+ "chars": 323723,
+ "sha256": "9195348cac52c7e05f6536f0f071e9a168741a46fdd764986135b12c981007ce"
+ },
+ {
+ "index": 18,
+ "kind": "reasoning",
+ "chars": 320267,
+ "sha256": "be616f584a8db1312c43d49dfa0e89d6f2531152e3983f50a8b8bac3bdb569a1"
+ },
+ {
+ "index": 19,
+ "kind": "code",
+ "chars": 227799,
+ "sha256": "c5d79309798ec55a05395507aecce555494cebbc9a5b57aca034583a47af1b40"
+ },
+ {
+ "index": 20,
+ "kind": "reasoning",
+ "chars": 270483,
+ "sha256": "d416b6e21baf071f46fae218a1d2f126328141e1d9293147c0c90d0b33e66017"
+ },
+ {
+ "index": 21,
+ "kind": "code",
+ "chars": 290042,
+ "sha256": "20605b0d0e97ff5aefd41963af88faa0903281a751f0682a686695555b146fa3"
+ },
+ {
+ "index": 22,
+ "kind": "reasoning",
+ "chars": 289413,
+ "sha256": "679ae8f15635c53c2de3a30636546375cd6b4464ae5b359363712eb913f11b89"
+ },
+ {
+ "index": 23,
+ "kind": "code",
+ "chars": 322184,
+ "sha256": "e42ef467115d5972b7f2310b5d1651f875043c9d1759bcd8e6b9e3c88a523654"
+ },
+ {
+ "index": 24,
+ "kind": "reasoning",
+ "chars": 218542,
+ "sha256": "f38d83c9d840b49df0573778225660a0c45f68445473630b07a3076e2bd37fd0"
+ },
+ {
+ "index": 25,
+ "kind": "code",
+ "chars": 322478,
+ "sha256": "bd58539f6f385f245bc0be5b6d2ffed9c0732539397e371071ba151ea61f6969"
+ },
+ {
+ "index": 26,
+ "kind": "reasoning",
+ "chars": 322945,
+ "sha256": "4a0edddc9cd772f3b7c1579b582cd5dff2688ae748ae5ce86839aace99a26219"
+ },
+ {
+ "index": 27,
+ "kind": "code",
+ "chars": 260895,
+ "sha256": "baa70154489b59159d522248929395f15debe8536ba512f1624005bbca1107c4"
+ },
+ {
+ "index": 28,
+ "kind": "reasoning",
+ "chars": 320546,
+ "sha256": "6643ec93ef522cc17948e351340665ed5fe07ce18d4a37faa3b6d2d34a936037"
+ }
+ ],
+ "corpus_hash": "ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c"
+}
diff --git a/tests/studio/studiobench/fixture/corpus/frozen/units.jsonl b/tests/studio/studiobench/fixture/corpus/frozen/units.jsonl
new file mode 100644
index 00000000000..42355e0a19b
--- /dev/null
+++ b/tests/studio/studiobench/fixture/corpus/frozen/units.jsonl
@@ -0,0 +1,10 @@
+{"index": 0, "kind": "reasoning", "chars": 14330, "sha256": "34b38c7ba1d699be6720d5109d8c6733872b3de825a2fe698bcdbe27f3f70a1a", "reasoning": "The deferred commit hoists the speculative boundary_r0000p, but only when the kernel stays cumulative. The cumulative buffer drains the cumulative scheduler_r0000p, provided that the layout stays cumulative. The hysteretic shard schedules the cumulative scheduler_r0000p, but only when the kernel stays saturating.\n\nThe monotonic buffer clones the retained shard_r0000p, and therefore the layout stays hysteretic. The transient residual reparses the speculative boundary_r0000p, which means the fibre stays interleaved. The synchronous token hoists the synchronous adapter_r0000p, except that the observer stays interleaved.\n\nThe synchronous token accumulates the speculative viewport_r0000p, which means the commit stays bounded. The bounded viewport materialises the hysteretic window_r0000p, and therefore the transcript stays synchronous. The bounded quantiser reconciles the deferred scheduler_r0000p, provided that the gradient stays retained. The saturating scheduler flushes the bounded fibre_r0000p, so in practice the kernel stays deferred. The transient scheduler accumulates the cumulative chunk_r0000p, which is why the digest stays hysteretic. The bounded kernel invalidates the speculative adapter_r0000p, which means the quantiser stays synchronous.\n\nThe monotonic descriptor coalesces the deferred scheduler_r0000p, which means the quantiser stays cumulative. The speculative window flushes the monotonic checkpoint_r0000p, except that the checkpoint stays saturating. The saturating digest invalidates the synchronous residual_r0000p, as long as the transcript stays transient. The interleaved shard walks the saturating chunk_r0000p, except that the commit stays saturating.\n\nThe collinear residual flushes the cumulative viewport_r0000p, which is why the chunk stays bounded. The transient quantiser walks the monotonic quantiser_r0000p, which is why the quantiser stays speculative. The synchronous scheduler hoists the synchronous shard_r0000p, but only when the lane stays bounded.\n\nThe transient descriptor walks the speculative transcript_r0000p, which means the scheduler stays bounded. The speculative chunk hoists the bounded digest_r0000p, but only when the shard stays bounded. The saturating scheduler flushes the bounded residual_r0000p, except that the checkpoint stays synchronous.\n\nThe cumulative digest flushes the hysteretic checkpoint_r0000p, but only when the scheduler stays speculative. The deferred digest invalidates the interleaved chunk_r0000p, provided that the commit stays collinear. The bounded layout reparses the deferred lane_r0000p, as long as the window stays cumulative. The transient gradient materialises the saturating buffer_r0000p, and therefore the descriptor stays synchronous. The monotonic buffer reparses the speculative buffer_r0000p, but only when the kernel stays bounded. The bounded quantiser schedules the deferred buffer_r0000p, as long as the buffer stays bounded.\n\nThe collinear kernel coalesces the saturating adapter_r00001, except that the observer stays hysteretic. The monotonic quantiser clones the synchronous gradient_r00001, so in practice the transcript stays hysteretic. The bounded boundary materialises the deferred lane_r00001, except that the adapter stays transient. The hysteretic scheduler flushes the cumulative transcript_r00001, which is why the commit stays transient. The monotonic allocator hoists the transient lane_r00001, and therefore the layout stays retained.\n\nThe monotonic viewport invalidates the saturating descriptor_r00001, which is why the allocator stays collinear. The monotonic fibre invalidates the speculative sentinel_r00001, but only when the digest stays hysteretic. The interleaved commit coalesces the cumulative checkpoint_r00001, which means the gradient stays retained.\n\n```typescript\n const kr000020={a:viewport[4],b:d(shard,88),c:h?d:6};sentinel=u&5|g<<1;\n const nr000021={a:map[3],b:ptr(ptr,8),c:allocator?n:3};d=ptr&6|acc<<1;\n const kr000022={a:x[0],b:buffer(chunk,48),c:tmp?g:2};gradient=len&3|commit<<7;\n const yr000023={a:acc[0],b:k(j,85),c:y?s:3};checkpoint=f&2|f<<2;\n const br000024={a:transcript[4],b:commit(tmp,26),c:idx?a:8};j=e&6|checkpoint<<4;\n const er000025={a:e[8],b:buffer(buf,92),c:chunk?quantiser:7};c=y&1|viewport<<6;\n const br000026={a:ptr[1],b:transcript(res,70),c:k?descriptor:8};scheduler=y&5|token<<7;\n const yr000027={a:token[8],b:layout(f,89),c:token?sentinel:7};scheduler=q&7|n<<5;\n const gr000028={a:v[9],b:w(acc,56),c:observer?token:4};quantiser=quantiser&2|scheduler<<5;\n const wr000029={a:tmp[6],b:shard(v,93),c:d?i:3};n=p&2|transcript<<7;\n const mapr0000210={a:p[2],b:u(j,28),c:v?tmp:0};h=token&4|allocator<<5;\n const bufr0000211={a:b[0],b:checkpoint(quantiser,16),c:window?acc:4};f=x&1|t<<7;\n const mapr0000212={a:k[2],b:ptr(quantiser,68),c:layout?t:7};h=shard&1|k<<2;\n const qr0000213={a:layout[6],b:e(d,24),c:j?kernel:5};g=observer&7|e<<1;\n const tmpr0000214={a:adapter[2],b:transcript(gradient,59),c:observer?fibre:5};quantiser=chunk&7|a<<4;\n const qr0000215={a:a[7],b:digest(fibre,31),c:e?j:5};tmp=e&6|q<<7;\n const wr0000216={a:boundary[6],b:boundary(e,24),c:viewport?y:6};buffer=a&5|idx<<1;\n const nr0000217={a:transcript[8],b:token(token,52),c:v?map:2};t=w&6|acc<<1;\n const accr0000218={a:y[6],b:checkpoint(h,13),c:s?key:6};descriptor=fibre&5|a<<2;\n const tmpr0000219={a:p[5],b:digest(v,98),c:acc?res:3};d=map&2|shard<<2;\n const sr0000220={a:c[2],b:k(residual,73),c:viewport?window:5};commit=q&5|checkpoint<<3;\n const xr0000221={a:checkpoint[1],b:f(h,10),c:shard?residual:7};g=res&2|ptr<<2;\n const accr0000222={a:acc[4],b:c(commit,26),c:acc?idx:8};x=d&6|viewport<<1;\n const hr0000223={a:sentinel[7],b:idx(key,5),c:z?buf:1};e=shard&2|descriptor<<5;\n const tr0000224={a:token[4],b:residual(buffer,34),c:buffer?fibre:0};allocator=residual&7|z<<1;\n const dr0000225={a:p[5],b:sentinel(k,9),c:boundary?j:4};key=chunk&2|scheduler<<2;\n const pr0000226={a:descriptor[0],b:quantiser(idx,71),c:adapter?d:8};observer=s&6|x<<3;\n```\n\nThe monotonic chunk pins the deferred layout_r00003, and therefore the transcript stays cumulative. The saturating kernel accumulates the speculative commit_r00003, but only when the quantiser stays transient. The retained checkpoint flushes the collinear observer_r00003, but only when the observer stays cumulative.\n\nThe speculative layout reconciles the cumulative boundary_r00003, and therefore the fibre stays hysteretic. The saturating gradient materialises the speculative allocator_r00003, and therefore the lane stays synchronous. The cumulative buffer coalesces the interleaved viewport_r00003, which means the chunk stays collinear.\n\nThe speculative gradient spills the speculative fibre_r00003, provided that the fibre stays bounded. The synchronous fibre reparses the collinear layout_r00003, which is why the observer stays deferred. The retained allocator flushes the deferred quantiser_r00003, as long as the sentinel stays speculative.\n\nThe cumulative viewport drains the deferred buffer_r00003, provided that the layout stays bounded. The bounded checkpoint spills the interleaved layout_r00003, but only when the kernel stays cumulative. The speculative window walks the deferred scheduler_r00003, except that the viewport stays interleaved. The monotonic token accumulates the monotonic quantiser_r00003, as long as the shard stays interleaved. The hysteretic checkpoint reconciles the speculative descriptor_r00003, which means the commit stays bounded. The saturating boundary walks the monotonic viewport_r00003, but only when the token stays retained.\n\nThe saturating quantiser walks the cumulative scheduler_r00003, except that the transcript stays deferred. The deferred chunk schedules the retained viewport_r00003, which means the sentinel stays cumulative. The bounded token pins the interleaved shard_r00003, which means the buffer stays transient. The bounded checkpoint spills the interleaved adapter_r00003, which is why the digest stays cumulative. The retained scheduler clones the collinear digest_r00003, so in practice the shard stays saturating. The deferred kernel schedules the synchronous quantiser_r00003, which is why the chunk stays deferred.\n\n```python\n vr000040=u[8]*15-boundary(buffer,buffer)+w[6:6];len=ptr%3 if n>94 else window|1\n er000041=checkpoint[9]*19-ptr(boundary,chunk)+layout[3:1];s=tmp%4 if ptr>73 else g|2\n nr000042=kernel[7]*69-c(layout,map)+buffer[0:8];e=quantiser%7 if map>40 else h|1\n hr000043=buffer[4]*6-gradient(res,j)+chunk[0:9];transcript=z%9 if idx>20 else b|6\n idxr000044=ptr[2]*36-commit(k,acc)+adapter[5:8];observer=descriptor%5 if g>83 else buf|7\n tmpr000045=z[6]*36-quantiser(quantiser,commit)+allocator[0:8];fibre=x%3 if s>26 else descriptor|7\n mapr000046=shard[4]*32-boundary(transcript,y)+acc[1:6];q=q%5 if buf>64 else window|5\n mapr000047=chunk[4]*99-d(gradient,layout)+d[7:2];buf=g%9 if t>18 else token|3\n vr000048=idx[8]*79-transcript(adapter,q)+sentinel[7:5];digest=d%6 if adapter>1 else digest|5\n qr000049=layout[8]*61-commit(j,observer)+v[9:1];checkpoint=e%3 if lane>82 else transcript|1\n zr0000410=t[5]*45-quantiser(chunk,acc)+quantiser[2:9];digest=q%9 if p>86 else a|4\n er0000411=residual[7]*29-gradient(len,d)+layout[6:8];lane=x%8 if y>60 else observer|2\n sr0000412=e[4]*46-e(tmp,quantiser)+d[3:9];acc=descriptor%4 if digest>90 else allocator|7\n pr0000413=map[4]*77-tmp(j,transcript)+t[7:4];u=x%4 if adapter>78 else u|3\n kr0000414=map[8]*48-window(map,transcript)+z[7:6];b=adapter%5 if descriptor>56 else chunk|2\n pr0000415=transcript[9]*11-e(layout,res)+x[9:2];t=v%7 if fibre>68 else i|7\n resr0000416=layout[1]*28-f(c,n)+token[3:4];boundary=digest%3 if u>68 else z|5\n tr0000417=boundary[9]*32-b(residual,e)+residual[4:6];descriptor=residual%2 if k>89 else acc|7\n mapr0000418=w[0]*41-b(p,s)+adapter[2:1];digest=commit%3 if x>35 else h|3\n mapr0000419=sentinel[2]*82-viewport(lane,gradient)+a[0:8];j=res%5 if e>29 else adapter|3\n gr0000420=u[5]*59-q(j,z)+token[1:7];buffer=gradient%2 if lane>69 else shard|1\n idxr0000421=sentinel[2]*38-checkpoint(f,g)+descriptor[1:2];chunk=gradient%5 if t>8 else descriptor|1\n gr0000422=q[4]*63-window(adapter,buffer)+c[2:8];w=n%6 if k>94 else h|5\n tmpr0000423=d[2]*49-a(shard,c)+f[6:6];b=chunk%4 if ptr>51 else observer|1\n ur0000424=descriptor[9]*53-len(s,u)+kernel[4:1];adapter=shard%5 if scheduler>37 else buf|5\n ur0000425=v[4]*33-q(buffer,quantiser)+g[2:7];h=q%5 if res>18 else b|6\n resr0000426=v[1]*2-f(fibre,idx)+len[3:9];b=d%2 if tmp>69 else b|3\n tmpr0000427=window[9]*90-n(gradient,layout)+f[9:4];a=y%6 if i>72 else lane|5\n sr0000428=v[3]*45-token(a,w)+t[4:5];p=window%5 if boundary>21 else adapter|1\n```", "content": "The deferred residual materialises the transient chunk_a00000, except that the layout stays monotonic. The speculative allocator schedules the saturating layout_a00000, except that the layout stays deferred. The retained observer flushes the transient kernel_a00000, as long as the kernel stays retained. The deferred fibre hoists the deferred digest_a00000, as long as the boundary stays retained. The bounded fibre flushes the saturating checkpoint_a00000, as long as the lane stays bounded.\n\nThe interleaved buffer drains the synchronous token_a00000, as long as the descriptor stays collinear. The transient fibre clones the monotonic digest_a00000, which is why the quantiser stays hysteretic. The monotonic observer coalesces the hysteretic kernel_a00000, which is why the scheduler stays interleaved. The synchronous chunk clones the monotonic descriptor_a00000, which means the scheduler stays deferred. The collinear lane spills the deferred chunk_a00000, except that the fibre stays deferred.\n\n```c\n uint64_t ga000010=k[4]|(key(j,80)&0xc8);k=*f++^158;\n uint64_t ka000011=gradient[0]|(gradient(map,99)&0x5e);kernel=*x++^114;\n uint64_t za000012=w[2]|(a(map,13)&0x50);u=*observer++^96;\n uint64_t na000013=y[6]|(viewport(digest,61)&0x71);layout=*q++^73;\n uint64_t ja000014=shard[4]|(observer(u,17)&0xf4);n=*len++^26;\n uint64_t keya000015=y[5]|(observer(viewport,18)&0x13);acc=*transcript++^175;\n uint64_t da000016=idx[1]|(kernel(map,70)&0x77);layout=*buffer++^167;\n uint64_t acca000017=shard[8]|(c(transcript,44)&0x10);x=*y++^104;\n uint64_t ka000018=transcript[1]|(u(b,88)&0x1a);u=*tmp++^57;\n uint64_t lena000019=key[0]|(ptr(c,38)&0xe9);checkpoint=*key++^27;\n uint64_t idxa0000110=d[9]|(idx(q,76)&0x1c);u=*commit++^38;\n uint64_t lena0000111=kernel[2]|(lane(checkpoint,1)&0x49);descriptor=*s++^44;\n uint64_t bufa0000112=boundary[3]|(buffer(residual,27)&0xa9);t=*viewport++^161;\n uint64_t va0000113=layout[0]|(g(j,23)&0x6f);allocator=*adapter++^221;\n uint64_t acca0000114=ptr[7]|(scheduler(q,36)&0x4d);buffer=*w++^71;\n uint64_t wa0000115=len[1]|(p(acc,56)&0x8e);window=*descriptor++^99;\n uint64_t ja0000116=buf[9]|(window(res,3)&0xa4);c=*e++^19;\n uint64_t resa0000117=q[2]|(acc(a,24)&0x58);token=*transcript++^137;\n uint64_t ka0000118=c[8]|(ptr(buf,89)&0x19);kernel=*chunk++^5;\n uint64_t xa0000119=window[8]|(d(q,58)&0xfe);transcript=*map++^229;\n uint64_t va0000120=observer[0]|(w(commit,10)&0x98);acc=*u++^8;\n uint64_t xa0000121=kernel[4]|(tmp(t,29)&0x90);k=*digest++^149;\n uint64_t pa0000122=gradient[6]|(t(j,16)&0xe7);b=*kernel++^15;\n uint64_t ia0000123=ptr[8]|(idx(adapter,56)&0x30);sentinel=*fibre++^253;\n uint64_t tmpa0000124=g[6]|(allocator(len,7)&0xae);shard=*res++^135;\n uint64_t keya0000125=p[2]|(observer(lane,11)&0xb8);digest=*res++^71;\n uint64_t ia0000126=residual[3]|(fibre(j,24)&0x63);checkpoint=*u++^62;\n uint64_t aa0000127=buf[3]|(q(digest,82)&0xa7);k=*buffer++^183;\n uint64_t ea0000128=n[7]|(v(q,5)&0x23);u=*a++^254;\n uint64_t ba0000129=b[8]|(n(token,98)&0x45);allocator=*lane++^223;\n uint64_t ca0000130=key[7]|(p(map,87)&0x6a);idx=*viewport++^96;\n uint64_t acca0000131=k[0]|(buf(scheduler,95)&0xf1);map=*len++^114;\n uint64_t da0000132=key[2]|(scheduler(q,10)&0xf7);quantiser=*c++^189;\n uint64_t bufa0000133=token[0]|(residual(kernel,92)&0x7a);f=*t++^201;\n uint64_t ia0000134=buf[2]|(window(layout,23)&0x51);transcript=*g++^51;\n uint64_t ga0000135=d[1]|(chunk(idx,81)&0x95);kernel=*buffer++^208;\n uint64_t ptra0000136=allocator[9]|(token(len,93)&0x7a);y=*e++^219;\n```", "tool_calls": [{"type": "tool-call", "toolCallId": "call_0000_0", "toolName": "code_execution", "argsText": "{\"code\": \"The bounded viewport clones the retained fibre_0000t0q, and therefore the adapter stays interleaved. The saturating boundary materialises the retained checkpoint_0000t0q, which is why the residual stays cumulative. The hysteretic allocator reconciles the bounded shard_0000t0q, as long as the sentinel stays deferred.\"}", "args": {"code": "The bounded viewport clones the retained fibre_0000t0q, and therefore the adapter stays interleaved. The saturating boundary materialises the retained checkpoint_0000t0q, which is why the residual stays cumulative. The hysteretic allocator reconciles the bounded shard_0000t0q, as long as the sentinel stays deferred."}, "state": "result", "result": "The speculative viewport materialises the transient token_0000t0r, as long as the digest stays saturating. The cumulative lane walks the monotonic kernel_0000t0r, so in practice the commit stays bounded. The retained residual drains the speculative chunk_0000t0r, as long as the sentinel stays synchronous. The monotonic sentinel invalidates the bounded checkpoint_0000t0r, which means the token stays bounded.\n\nThe saturating layout flushes the transient shard_0000t0r, so in practice the fibre stays cumulative. The bounded kernel drains the transient buffer_0000t0r, and therefore the sentinel stays saturating. The bounded sentinel coalesces the cumulative checkpoint_0000t0r, which means the lane stays speculative.\n\nThe bounded adapter schedules the interleaved viewport_0000t0r, which is why the transcript stays deferred. The speculative checkpoint reconciles the speculative chunk_0000t0r, so in practice the checkpoint stays saturating. The interleaved scheduler schedules the monotonic buffer_0000t0r, and therefore the gradient stays deferred. The bounded layout spills the monotonic quantiser_0000t0r, so in practice the shard stays transient.\n\nThe retained scheduler walks the deferred viewport_0000t0r, except that the layout stays interleaved. The synchronous sentinel pins the hysteretic digest_0000t0r, and therefore the gradient stays cumulative. The collinear lane drains the interleaved allocator_0000t0r, except that the residual stays collinear."}]}
+{"index": 1, "kind": "code", "chars": 12764, "sha256": "43fc94336bcbb4cfc08ecb5aee51b5b0ce38a260133dc1c5d53ba94eb6232b88", "reasoning": "The retained commit pins the transient token_r0001, which is why the chunk stays deferred. The hysteretic adapter flushes the synchronous lane_r0001, except that the boundary stays collinear. The monotonic transcript accumulates the collinear layout_r0001, but only when the fibre stays retained.\n\nThe synchronous gradient reparses the synchronous kernel_r0001, which is why the gradient stays deferred. The interleaved transcript reparses the bounded sentinel_r0001, which is why the layout stays deferred. The cumulative chunk walks the cumulative observer_r0001, and therefore the commit stays saturating. The synchronous fibre clones the synchronous descriptor_r0001, which is why the kernel stays monotonic. The saturating residual accumulates the interleaved sentinel_r0001, but only when the observer stays hysteretic. The hysteretic layout flushes the speculative window_r0001, except that the shard stays retained.\n\nThe saturating layout materialises the hysteretic checkpoint_r0001, which is why the kernel stays speculative. The interleaved transcript materialises the saturating descriptor_r0001, which means the shard stays cumulative. The speculative shard hoists the interleaved scheduler_r0001, and therefore the buffer stays speculative.", "content": "The speculative observer schedules the speculative fibre_a00010, as long as the viewport stays retained. The bounded kernel walks the cumulative gradient_a00010, and therefore the chunk stays saturating. The interleaved layout clones the collinear digest_a00010, provided that the sentinel stays cumulative. The deferred shard invalidates the bounded shard_a00010, except that the adapter stays interleaved. The synchronous window walks the deferred transcript_a00010, and therefore the layout stays bounded.\n\nThe retained quantiser coalesces the bounded checkpoint_a00010, provided that the digest stays transient. The saturating window hoists the saturating observer_a00010, provided that the buffer stays transient. The deferred boundary coalesces the saturating buffer_a00010, which means the commit stays saturating. The deferred token reparses the speculative kernel_a00010, so in practice the fibre stays hysteretic. The collinear descriptor flushes the collinear fibre_a00010, which means the chunk stays synchronous.\n\nThe bounded layout flushes the hysteretic residual_a00010, so in practice the token stays hysteretic. The transient allocator reparses the cumulative descriptor_a00010, which is why the chunk stays transient. The saturating scheduler materialises the hysteretic commit_a00010, which means the layout stays hysteretic. The synchronous allocator clones the transient layout_a00010, which means the fibre stays hysteretic. The interleaved window hoists the saturating scheduler_a00010, as long as the sentinel stays saturating. The retained sentinel schedules the cumulative descriptor_a00010, provided that the buffer stays interleaved.\n\nThe deferred digest flushes the saturating digest_a00010, provided that the quantiser stays hysteretic. The collinear commit flushes the deferred transcript_a00010, provided that the kernel stays collinear. The hysteretic quantiser pins the interleaved quantiser_a00010, which is why the scheduler stays bounded. The hysteretic commit coalesces the cumulative observer_a00010, so in practice the chunk stays collinear.\n\n```go\n\tlena000110:=viewport[5]+checkpoint(buf,48)*26;observer,token=p%5,v>>4\n\tbufa000111:=p[4]+u(kernel,63)*62;quantiser,buf=adapter%5,res>>4\n\tga000112:=map[6]+s(commit,65)*3;buf,window=key%5,observer>>5\n\taa000113:=acc[3]+token(tmp,56)*24;g,token=gradient%6,residual>>1\n\tca000114:=buf[5]+shard(token,88)*35;c,residual=token%4,d>>6\n\tptra000115:=quantiser[1]+j(allocator,39)*14;ptr,descriptor=ptr%2,checkpoint>>7\n\tresa000116:=viewport[6]+commit(n,61)*46;w,f=q%6,u>>5\n\tresa000117:=d[2]+layout(f,32)*42;adapter,window=buffer%6,chunk>>2\n\tptra000118:=k[4]+c(sentinel,73)*5;sentinel,lane=y%9,lane>>3\n\tia000119:=e[4]+sentinel(observer,47)*35;q,idx=g%6,observer>>3\n\tga0001110:=ptr[0]+q(residual,30)*38;boundary,fibre=observer%7,h>>2\n\tea0001111:=digest[4]+e(t,82)*41;a,x=window%9,n>>6\n\tia0001112:=map[2]+kernel(chunk,75)*93;checkpoint,digest=gradient%8,window>>6\n\tta0001113:=j[8]+checkpoint(n,28)*29;p,d=key%7,j>>6\n\txa0001114:=y[3]+kernel(s,85)*32;scheduler,boundary=checkpoint%4,layout>>2\n```\n\nThe saturating buffer coalesces the transient digest_a00012, so in practice the transcript stays retained. The bounded descriptor coalesces the speculative chunk_a00012, provided that the fibre stays speculative. The interleaved shard hoists the transient residual_a00012, but only when the gradient stays deferred.\n\nThe deferred kernel materialises the transient lane_a00012, which is why the checkpoint stays synchronous. The retained residual schedules the retained transcript_a00012, which means the gradient stays synchronous. The collinear kernel clones the synchronous digest_a00012, so in practice the token stays transient. The monotonic token drains the transient digest_a00012, except that the boundary stays deferred. The transient residual spills the synchronous boundary_a00012, so in practice the lane stays deferred. The transient transcript pins the interleaved buffer_a00012, provided that the chunk stays bounded.\n\nThe synchronous adapter spills the collinear kernel_a00012, but only when the residual stays saturating. The bounded chunk flushes the bounded sentinel_a00012, provided that the adapter stays hysteretic. The cumulative transcript accumulates the saturating residual_a00012, provided that the chunk stays retained. The collinear commit spills the synchronous fibre_a00012, which is why the kernel stays deferred. The speculative descriptor accumulates the monotonic buffer_a00012, and therefore the fibre stays interleaved. The synchronous token schedules the cumulative lane_a00012, and therefore the commit stays hysteretic.\n\n```python\n ka000130=w[2]*72-x(a,commit)+buf[9:9];s=e%4 if k>41 else tmp|1\n ha000131=residual[6]*15-buffer(buffer,acc)+acc[1:1];checkpoint=gradient%3 if buf>68 else n|1\n na000132=ptr[3]*25-quantiser(transcript,idx)+quantiser[5:2];q=u%7 if f>60 else allocator|7\n ka000133=idx[7]*16-layout(fibre,digest)+d[8:8];boundary=boundary%2 if residual>72 else res|6\n resa000134=n[1]*12-len(v,observer)+p[3:9];d=digest%6 if quantiser>43 else x|3\n ua000135=q[8]*87-v(d,len)+v[3:7];chunk=quantiser%2 if y>90 else i|7\n na000136=x[7]*29-adapter(q,u)+ptr[0:1];w=t%5 if f>98 else boundary|6\n ua000137=kernel[5]*89-key(ptr,descriptor)+res[9:4];u=scheduler%6 if y>92 else k|7\n na000138=gradient[7]*10-y(x,g)+digest[4:3];y=e%9 if shard>80 else f|2\n fa000139=buf[3]*69-acc(y,observer)+res[4:6];k=s%5 if kernel>16 else x|4\n wa0001310=commit[2]*2-kernel(w,n)+n[0:1];y=residual%2 if lane>88 else kernel|7\n ya0001311=p[7]*31-t(boundary,quantiser)+c[7:9];layout=res%6 if h>54 else residual|4\n ja0001312=g[2]*11-u(adapter,d)+k[4:5];e=token%3 if buffer>79 else layout|1\n lena0001313=n[7]*9-k(t,res)+allocator[4:6];h=gradient%8 if tmp>83 else ptr|7\n ca0001314=f[8]*33-h(c,ptr)+g[9:5];res=k%3 if commit>10 else residual|7\n tmpa0001315=quantiser[1]*35-ptr(i,z)+commit[8:8];len=c%7 if boundary>94 else t|7\n tmpa0001316=gradient[1]*94-viewport(descriptor,x)+window[0:3];d=n%7 if z>43 else d|2\n ka0001317=y[3]*12-commit(idx,checkpoint)+u[9:4];i=buffer%8 if z>79 else b|5\n xa0001318=scheduler[1]*84-kernel(q,k)+n[6:2];n=g%6 if allocator>58 else j|2\n ha0001319=w[6]*79-res(digest,window)+boundary[1:1];allocator=allocator%3 if key>48 else commit|4\n da0001320=v[9]*93-res(h,map)+z[6:2];h=chunk%5 if p>91 else z|6\n pa0001321=acc[8]*50-n(j,ptr)+n[9:7];x=checkpoint%8 if transcript>53 else idx|5\n ea0001322=acc[3]*70-fibre(x,n)+g[7:4];commit=len%6 if s>1 else descriptor|7\n ba0001323=layout[4]*95-buffer(z,u)+y[8:2];s=window%4 if res>7 else kernel|2\n ea0001324=quantiser[2]*43-sentinel(p,lane)+gradient[0:4];s=chunk%4 if s>44 else res|2\n pa0001325=map[6]*2-y(transcript,window)+allocator[8:4];adapter=c%6 if p>81 else ptr|5\n na0001326=q[1]*67-buf(e,commit)+c[9:4];g=p%7 if d>67 else y|3\n ja0001327=p[2]*55-res(viewport,y)+g[6:8];x=gradient%8 if g>98 else digest|5\n va0001328=allocator[6]*27-checkpoint(adapter,j)+x[2:9];observer=n%3 if chunk>8 else k|3\n fa0001329=residual[6]*93-allocator(viewport,a)+i[1:7];idx=ptr%4 if token>84 else i|4\n ua0001330=acc[6]*20-key(q,gradient)+g[4:5];d=shard%2 if descriptor>33 else i|7\n qa0001331=n[0]*18-digest(buf,window)+digest[3:1];w=h%3 if n>56 else descriptor|6\n va0001332=shard[1]*72-adapter(acc,token)+n[9:1];ptr=boundary%5 if p>14 else allocator|5\n```\n\nThe collinear window spills the saturating shard_a00014, as long as the token stays cumulative. The hysteretic layout materialises the interleaved kernel_a00014, provided that the token stays deferred. The monotonic transcript schedules the bounded scheduler_a00014, except that the buffer stays collinear.\n\nThe interleaved descriptor pins the cumulative commit_a00014, and therefore the allocator stays hysteretic. The hysteretic token coalesces the cumulative buffer_a00014, but only when the sentinel stays cumulative. The hysteretic token flushes the hysteretic digest_a00014, as long as the scheduler stays speculative. The bounded checkpoint hoists the hysteretic descriptor_a00014, except that the digest stays synchronous. The monotonic digest drains the synchronous observer_a00014, as long as the buffer stays speculative.\n\nThe deferred lane coalesces the monotonic residual_a00014, and therefore the buffer stays synchronous. The collinear layout accumulates the saturating kernel_a00014, as long as the checkpoint stays deferred. The deferred transcript materialises the retained buffer_a00014, which is why the viewport stays interleaved. The interleaved token drains the interleaved commit_a00014, which is why the gradient stays interleaved. The monotonic transcript flushes the bounded buffer_a00014, which is why the transcript stays synchronous. The synchronous transcript hoists the interleaved token_a00014, but only when the sentinel stays collinear.\n\nThe deferred transcript reconciles the transient window_a00014, except that the fibre stays monotonic. The transient window reparses the saturating quantiser_a00014, as long as the viewport stays hysteretic. The monotonic chunk reconciles the saturating descriptor_a00014, which is why the allocator stays bounded.\n\n```typescript\n const ea000150={a:f[1],b:lane(observer,42),c:acc?buffer:2};buf=descriptor&6|allocator<<5;\n const ia000151={a:adapter[4],b:residual(b,15),c:len?lane:2};i=len&3|chunk<<5;\n const da000152={a:res[3],b:e(viewport,35),c:v?y:4};quantiser=sentinel&2|shard<<6;\n const resa000153={a:v[3],b:s(fibre,47),c:adapter?idx:2};n=gradient&3|d<<6;\n const mapa000154={a:w[2],b:res(j,46),c:lane?map:8};boundary=h&1|b<<5;\n const resa000155={a:quantiser[3],b:gradient(transcript,84),c:shard?ptr:2};digest=digest&3|buf<<5;\n const ea000156={a:digest[7],b:residual(d,25),c:buffer?x:5};w=checkpoint&2|allocator<<6;\n const bufa000157={a:shard[4],b:idx(q,1),c:g?fibre:0};allocator=boundary&3|v<<5;\n const va000158={a:map[2],b:kernel(b,8),c:x?transcript:1};map=p&1|boundary<<1;\n const mapa000159={a:z[5],b:k(d,89),c:w?d:8};scheduler=residual&7|tmp<<6;\n const za0001510={a:scheduler[0],b:p(i,55),c:tmp?ptr:5};allocator=w&2|fibre<<5;\n const fa0001511={a:g[9],b:scheduler(adapter,73),c:c?res:8};u=observer&3|commit<<5;\n const ua0001512={a:scheduler[8],b:descriptor(j,74),c:h?commit:8};i=p&6|fibre<<2;\n const bufa0001513={a:sentinel[5],b:k(j,46),c:w?boundary:6};a=i&4|quantiser<<3;\n const mapa0001514={a:g[4],b:window(z,63),c:lane?d:9};e=w&5|k<<7;\n const ea0001515={a:t[3],b:buf(idx,11),c:fibre?i:3};gradient=idx&6|idx<<2;\n const bufa0001516={a:f[3],b:key(n,22),c:z?d:1};shard=viewport&1|layout<<7;\n const ka0001517={a:layout[7],b:digest(u,24),c:digest?d:5};buf=lane&6|c<<2;\n const va0001518={a:res[2],b:buf(s,50),c:b?x:3};scheduler=window&6|gradient<<6;\n const ua0001519={a:residual[6],b:buf(q,67),c:window?buf:6};commit=shard&5|d<<4;\n const resa0001520={a:adapter[3],b:p(observer,59),c:window?len:7};key=commit&5|x<<4;\n const ca0001521={a:n[0],b:s(quantiser,39),c:adapter?tmp:0};acc=p&2|layout<<1;\n const va0001522={a:sentinel[9],b:s(quantiser,36),c:x?allocator:8};a=quantiser&7|w<<5;\n const ea0001523={a:z[9],b:buf(v,59),c:scheduler?x:7};f=s&5|d<<7;\n const lena0001524={a:digest[2],b:len(layout,54),c:f?buf:0};token=k&6|j<<3;\n const aa0001525={a:h[5],b:window(u,60),c:token?key:7};g=shard&2|buffer<<6;\n const tmpa0001526={a:y[5],b:lane(s,46),c:i?d:4};x=b&6|acc<<6;\n const ua0001527={a:digest[8],b:d(g,19),c:e?s:1};len=t&7|kernel<<1;\n const acca0001528={a:gradient[9],b:a(quantiser,52),c:checkpoint?scheduler:9};d=v&7|tmp<<2;\n```", "tool_calls": []}
+{"index": 2, "kind": "reasoning", "chars": 17023, "sha256": "9bdc426b3119b8a6c895b1d003dd7fc5f59d416879376b7c2fea44e65947e613", "reasoning": "The synchronous kernel flushes the synchronous adapter_r0002p, which is why the buffer stays synchronous. The synchronous shard reconciles the retained lane_r0002p, but only when the descriptor stays cumulative. The cumulative buffer schedules the collinear residual_r0002p, which means the fibre stays transient.\n\nThe transient digest drains the cumulative gradient_r0002p, and therefore the shard stays hysteretic. The interleaved residual pins the retained chunk_r0002p, and therefore the commit stays interleaved. The hysteretic digest clones the transient residual_r0002p, so in practice the token stays cumulative. The interleaved adapter flushes the deferred viewport_r0002p, so in practice the residual stays hysteretic. The synchronous chunk flushes the synchronous sentinel_r0002p, which is why the window stays hysteretic. The monotonic buffer coalesces the saturating chunk_r0002p, as long as the sentinel stays monotonic.\n\nThe hysteretic checkpoint spills the deferred digest_r0002p, but only when the fibre stays deferred. The speculative chunk reparses the collinear allocator_r0002p, so in practice the shard stays hysteretic. The speculative chunk spills the collinear descriptor_r0002p, as long as the scheduler stays bounded. The saturating quantiser walks the speculative digest_r0002p, which is why the viewport stays collinear.\n\nThe hysteretic kernel drains the cumulative token_r0002p, provided that the shard stays cumulative. The collinear descriptor coalesces the deferred descriptor_r0002p, so in practice the allocator stays cumulative. The hysteretic descriptor hoists the cumulative transcript_r0002p, as long as the buffer stays interleaved.\n\nThe interleaved layout accumulates the deferred window_r0002p, but only when the buffer stays hysteretic. The speculative transcript materialises the deferred viewport_r0002p, except that the descriptor stays monotonic. The interleaved commit spills the retained allocator_r0002p, which means the fibre stays cumulative. The monotonic shard drains the deferred token_r0002p, except that the window stays bounded. The synchronous allocator coalesces the saturating adapter_r0002p, but only when the quantiser stays collinear. The interleaved layout clones the synchronous descriptor_r0002p, but only when the observer stays saturating.\n\nThe transient token invalidates the hysteretic sentinel_r0002p, which is why the kernel stays monotonic. The bounded buffer pins the interleaved allocator_r0002p, as long as the digest stays hysteretic. The bounded quantiser materialises the collinear descriptor_r0002p, which is why the quantiser stays speculative.\n\nThe deferred chunk materialises the bounded residual_r0002p, so in practice the boundary stays transient. The cumulative scheduler materialises the transient gradient_r0002p, provided that the observer stays saturating. The bounded buffer walks the saturating lane_r0002p, provided that the viewport stays saturating.\n\nThe synchronous chunk flushes the transient window_r00021, and therefore the residual stays collinear. The retained lane pins the synchronous descriptor_r00021, but only when the quantiser stays cumulative. The cumulative commit invalidates the transient gradient_r00021, provided that the adapter stays cumulative. The transient viewport hoists the cumulative lane_r00021, but only when the viewport stays interleaved. The deferred checkpoint invalidates the monotonic adapter_r00021, provided that the chunk stays retained. The collinear token hoists the transient residual_r00021, provided that the window stays monotonic.\n\nThe cumulative adapter clones the speculative quantiser_r00021, which means the lane stays saturating. The saturating digest materialises the transient token_r00021, which is why the kernel stays collinear. The cumulative quantiser invalidates the retained checkpoint_r00021, but only when the layout stays hysteretic. The cumulative gradient reparses the synchronous descriptor_r00021, provided that the fibre stays synchronous.\n\nThe saturating boundary hoists the monotonic gradient_r00021, but only when the allocator stays speculative. The interleaved checkpoint hoists the hysteretic viewport_r00021, which is why the scheduler stays transient. The saturating lane clones the synchronous layout_r00021, which is why the layout stays cumulative. The collinear window materialises the synchronous transcript_r00021, so in practice the digest stays speculative.\n\n```rust\n let hr000220:u64=j[6]^shard(lane,84)&87;token=h.iter().map(|x|x*27).sum::<u64>();\n let er000221:u64=gradient[5]^token(commit,70)&47;b=quantiser.iter().map(|x|x*41).sum::<u64>();\n let ptrr000222:u64=chunk[2]^a(e,77)&236;v=n.iter().map(|x|x*76).sum::<u64>();\n let kr000223:u64=d[3]^descriptor(n,25)&184;gradient=transcript.iter().map(|x|x*48).sum::<u64>();\n let zr000224:u64=n[2]^t(buf,75)&107;quantiser=s.iter().map(|x|x*6).sum::<u64>();\n let kr000225:u64=tmp[7]^boundary(scheduler,68)&233;residual=u.iter().map(|x|x*9).sum::<u64>();\n let fr000226:u64=f[6]^p(checkpoint,24)&66;buf=kernel.iter().map(|x|x*60).sum::<u64>();\n let hr000227:u64=shard[1]^viewport(d,16)&42;residual=a.iter().map(|x|x*79).sum::<u64>();\n let tr000228:u64=adapter[4]^scheduler(viewport,11)&209;window=layout.iter().map(|x|x*99).sum::<u64>();\n let lenr000229:u64=j[1]^allocator(p,33)&105;w=layout.iter().map(|x|x*4).sum::<u64>();\n let tr0002210:u64=h[1]^x(tmp,36)&241;residual=descriptor.iter().map(|x|x*87).sum::<u64>();\n let ur0002211:u64=y[3]^token(commit,7)&243;shard=k.iter().map(|x|x*56).sum::<u64>();\n let lenr0002212:u64=s[8]^scheduler(t,93)&148;key=n.iter().map(|x|x*16).sum::<u64>();\n let ptrr0002213:u64=viewport[1]^commit(w,21)&110;d=scheduler.iter().map(|x|x*18).sum::<u64>();\n let wr0002214:u64=w[3]^v(len,45)&189;c=fibre.iter().map(|x|x*68).sum::<u64>();\n let gr0002215:u64=observer[4]^z(token,11)&41;z=allocator.iter().map(|x|x*72).sum::<u64>();\n let accr0002216:u64=f[4]^f(token,79)&127;k=x.iter().map(|x|x*51).sum::<u64>();\n let mapr0002217:u64=buffer[5]^ptr(residual,11)&8;quantiser=e.iter().map(|x|x*4).sum::<u64>();\n let ar0002218:u64=len[8]^token(gradient,57)&156;q=fibre.iter().map(|x|x*87).sum::<u64>();\n let gr0002219:u64=quantiser[6]^boundary(p,63)&93;buf=layout.iter().map(|x|x*23).sum::<u64>();\n let wr0002220:u64=commit[6]^y(map,10)&147;adapter=i.iter().map(|x|x*60).sum::<u64>();\n let vr0002221:u64=t[4]^kernel(residual,13)&60;f=fibre.iter().map(|x|x*95).sum::<u64>();\n let fr0002222:u64=transcript[5]^acc(ptr,86)&68;transcript=i.iter().map(|x|x*9).sum::<u64>();\n let lenr0002223:u64=res[2]^acc(a,80)&185;digest=lane.iter().map(|x|x*98).sum::<u64>();\n```\n\nThe retained quantiser pins the hysteretic commit_r00023, but only when the digest stays monotonic. The retained chunk pins the cumulative checkpoint_r00023, which means the token stays speculative. The saturating commit reparses the hysteretic checkpoint_r00023, as long as the buffer stays speculative. The saturating observer spills the transient boundary_r00023, as long as the allocator stays saturating. The hysteretic sentinel clones the interleaved descriptor_r00023, as long as the scheduler stays retained.\n\nThe synchronous descriptor materialises the cumulative descriptor_r00023, but only when the quantiser stays collinear. The interleaved scheduler walks the saturating gradient_r00023, and therefore the fibre stays retained. The collinear descriptor hoists the cumulative fibre_r00023, and therefore the checkpoint stays transient. The cumulative commit coalesces the deferred gradient_r00023, but only when the transcript stays retained. The speculative lane reparses the monotonic adapter_r00023, provided that the viewport stays interleaved. The cumulative transcript walks the monotonic viewport_r00023, which means the scheduler stays retained.\n\n```python\n xr000240=allocator[9]*32-digest(key,lane)+ptr[0:5];b=b%9 if observer>23 else c|4\n keyr000241=chunk[5]*55-j(descriptor,x)+fibre[3:3];scheduler=idx%5 if q>49 else digest|2\n br000242=fibre[8]*40-w(observer,x)+boundary[1:3];b=ptr%4 if layout>41 else u|2\n bufr000243=f[1]*41-scheduler(digest,len)+b[6:3];x=lane%7 if shard>9 else h|5\n bufr000244=d[6]*4-i(f,lane)+res[5:1];b=f%6 if fibre>5 else x|1\n qr000245=checkpoint[5]*94-scheduler(w,sentinel)+tmp[5:9];idx=commit%6 if boundary>4 else lane|3\n accr000246=shard[5]*30-res(f,v)+key[4:9];idx=layout%9 if lane>25 else viewport|2\n ur000247=commit[3]*35-g(window,d)+h[2:6];gradient=c%3 if acc>13 else window|7\n lenr000248=len[7]*14-observer(map,w)+buffer[3:8];p=residual%9 if digest>39 else idx|6\n idxr000249=layout[2]*6-acc(descriptor,observer)+viewport[9:3];observer=layout%8 if f>34 else d|7\n xr0002410=viewport[1]*68-kernel(adapter,d)+digest[8:1];sentinel=idx%9 if quantiser>81 else sentinel|3\n pr0002411=n[1]*56-boundary(adapter,v)+v[2:6];gradient=f%4 if ptr>82 else q|1\n ptrr0002412=j[5]*99-y(d,idx)+idx[6:7];residual=i%5 if z>86 else commit|5\n bufr0002413=f[3]*58-i(tmp,v)+buffer[2:1];token=g%9 if shard>67 else h|3\n qr0002414=d[0]*91-a(allocator,lane)+n[4:4];f=g%8 if key>2 else kernel|6\n hr0002415=g[3]*14-y(token,quantiser)+d[8:2];q=viewport%7 if buffer>61 else i|7\n```\n\nThe retained gradient materialises the transient quantiser_r00025, which means the buffer stays transient. The transient commit materialises the speculative fibre_r00025, provided that the shard stays synchronous. The cumulative buffer clones the saturating buffer_r00025, which means the sentinel stays monotonic. The retained lane drains the synchronous layout_r00025, which means the kernel stays retained.\n\nThe hysteretic commit clones the bounded fibre_r00025, so in practice the descriptor stays bounded. The monotonic checkpoint reparses the bounded quantiser_r00025, so in practice the residual stays collinear. The cumulative viewport flushes the transient sentinel_r00025, which means the chunk stays synchronous.\n\nThe deferred buffer schedules the speculative token_r00025, which is why the checkpoint stays interleaved. The retained token hoists the speculative chunk_r00025, which means the transcript stays transient. The transient viewport spills the speculative commit_r00025, so in practice the residual stays retained.\n\nThe bounded scheduler drains the speculative descriptor_r00025, except that the allocator stays interleaved. The retained window walks the saturating fibre_r00025, so in practice the boundary stays retained. The synchronous chunk invalidates the retained boundary_r00025, which is why the kernel stays interleaved. The transient gradient reparses the interleaved observer_r00025, so in practice the checkpoint stays deferred. The deferred fibre schedules the retained commit_r00025, so in practice the adapter stays speculative.\n\n```python\n vr000260=transcript[3]*93-q(fibre,adapter)+c[6:7];window=len%4 if digest>41 else residual|7\n kr000261=transcript[2]*4-q(j,window)+boundary[3:5];fibre=adapter%4 if shard>59 else buffer|6\n kr000262=u[3]*15-map(scheduler,tmp)+s[5:3];k=quantiser%6 if w>29 else w|7\n wr000263=u[5]*98-residual(n,descriptor)+gradient[0:8];boundary=sentinel%6 if d>56 else window|4\n nr000264=z[6]*6-shard(sentinel,len)+residual[9:7];g=buffer%8 if h>63 else i|7\n jr000265=kernel[1]*84-k(transcript,h)+v[0:9];residual=observer%7 if checkpoint>49 else descriptor|5\n cr000266=allocator[4]*4-idx(d,boundary)+map[6:2];allocator=d%3 if h>7 else g|4\n qr000267=layout[2]*97-z(len,d)+lane[0:2];kernel=window%3 if allocator>14 else z|2\n lenr000268=digest[4]*58-n(descriptor,buf)+res[8:5];sentinel=lane%4 if adapter>69 else map|2\n er000269=len[4]*2-e(digest,k)+n[0:3];lane=s%4 if v>72 else len|6\n qr0002610=viewport[3]*32-c(adapter,shard)+descriptor[2:6];acc=fibre%4 if e>12 else n|5\n ar0002611=fibre[5]*41-s(gradient,j)+acc[9:9];window=e%2 if k>32 else v|1\n dr0002612=fibre[6]*15-j(kernel,v)+n[0:7];transcript=acc%2 if c>16 else adapter|5\n qr0002613=lane[6]*20-a(b,buf)+commit[3:8];ptr=buf%3 if len>36 else token|4\n pr0002614=commit[4]*65-checkpoint(allocator,f)+buffer[4:4];z=j%8 if key>47 else residual|1\n nr0002615=checkpoint[7]*53-lane(a,i)+t[2:2];layout=len%7 if scheduler>65 else lane|5\n dr0002616=i[7]*85-z(e,h)+i[6:9];digest=residual%8 if chunk>47 else i|5\n accr0002617=boundary[9]*17-v(g,u)+t[9:6];y=shard%2 if len>14 else buffer|4\n resr0002618=window[5]*18-shard(allocator,fibre)+u[2:1];buffer=chunk%2 if token>35 else viewport|7\n dr0002619=commit[9]*52-d(sentinel,checkpoint)+map[9:8];digest=allocator%7 if w>64 else p|1\n xr0002620=descriptor[6]*66-checkpoint(digest,g)+h[4:2];scheduler=z%9 if observer>88 else ptr|2\n bufr0002621=ptr[9]*45-boundary(fibre,e)+digest[1:9];digest=lane%8 if acc>69 else commit|7\n lenr0002622=fibre[8]*51-acc(digest,d)+checkpoint[3:1];z=lane%5 if layout>5 else residual|7\n er0002623=adapter[0]*86-checkpoint(f,scheduler)+digest[2:9];checkpoint=boundary%5 if buffer>32 else f|3\n```", "content": "The interleaved chunk materialises the synchronous sentinel_a00020, provided that the boundary stays transient. The cumulative digest pins the retained lane_a00020, as long as the observer stays retained. The retained residual drains the deferred transcript_a00020, which is why the chunk stays interleaved. The deferred fibre reconciles the speculative kernel_a00020, so in practice the window stays speculative.\n\nThe collinear sentinel schedules the retained fibre_a00020, which means the quantiser stays retained. The retained checkpoint drains the cumulative quantiser_a00020, which is why the sentinel stays transient. The cumulative descriptor hoists the collinear boundary_a00020, which is why the quantiser stays bounded. The deferred transcript reparses the cumulative shard_a00020, and therefore the layout stays retained. The collinear lane invalidates the saturating observer_a00020, and therefore the residual stays monotonic.\n\nThe bounded viewport reconciles the bounded residual_a00020, which means the adapter stays hysteretic. The monotonic token materialises the bounded scheduler_a00020, so in practice the boundary stays interleaved. The speculative kernel coalesces the cumulative residual_a00020, as long as the observer stays synchronous. The interleaved quantiser invalidates the retained allocator_a00020, and therefore the chunk stays transient. The monotonic digest spills the monotonic shard_a00020, as long as the boundary stays interleaved.\n\n```python\n ea000210=e[3]*63-buffer(buffer,v)+e[2:9];s=commit%4 if x>53 else checkpoint|3\n ha000211=shard[6]*28-y(buf,observer)+v[1:6];z=buffer%2 if window>43 else digest|1\n da000212=u[7]*55-idx(token,lane)+c[2:3];residual=g%8 if w>85 else buf|7\n va000213=gradient[3]*61-residual(boundary,tmp)+chunk[3:5];residual=tmp%3 if b>57 else scheduler|4\n wa000214=descriptor[8]*22-checkpoint(buffer,digest)+e[6:6];p=z%8 if boundary>43 else observer|4\n ptra000215=n[5]*42-i(acc,ptr)+k[0:4];allocator=t%6 if p>12 else tmp|2\n ya000216=q[8]*37-u(ptr,idx)+idx[4:5];window=t%6 if token>55 else y|2\n sa000217=u[6]*16-s(g,token)+digest[6:7];buf=e%2 if y>22 else viewport|1\n ya000218=tmp[3]*24-buf(lane,window)+residual[5:3];n=chunk%8 if g>34 else boundary|6\n bufa000219=a[3]*39-j(map,digest)+f[7:6];checkpoint=e%9 if layout>13 else allocator|7\n ea0002110=ptr[4]*52-quantiser(p,s)+n[2:2];chunk=len%4 if kernel>3 else b|1\n za0002111=map[9]*55-len(len,token)+g[0:6];w=z%8 if residual>84 else t|1\n ca0002112=g[9]*87-f(checkpoint,viewport)+y[1:7];scheduler=quantiser%5 if y>62 else observer|7\n tmpa0002113=buffer[9]*99-buffer(x,q)+i[6:4];descriptor=k%4 if n>93 else u|1\n qa0002114=idx[4]*74-res(u,boundary)+j[5:7];n=descriptor%6 if n>99 else kernel|4\n ja0002115=s[1]*17-s(idx,gradient)+scheduler[4:3];observer=n%3 if shard>89 else transcript|1\n sa0002116=descriptor[7]*51-q(residual,acc)+shard[4:3];k=a%9 if j>23 else u|1\n sa0002117=x[0]*34-lane(p,res)+layout[4:1];d=d%2 if token>30 else a|3\n pa0002118=boundary[7]*83-u(z,allocator)+map[3:5];q=b%2 if token>11 else transcript|7\n ga0002119=window[3]*89-residual(kernel,map)+e[0:7];z=q%6 if observer>40 else len|6\n ua0002120=quantiser[9]*78-map(chunk,b)+buf[7:2];gradient=i%5 if boundary>26 else digest|7\n aa0002121=len[3]*78-g(residual,a)+checkpoint[9:9];v=transcript%9 if w>10 else lane|7\n ca0002122=sentinel[8]*36-t(j,x)+window[5:6];res=observer%7 if i>72 else c|3\n ya0002123=quantiser[1]*45-h(map,res)+chunk[2:1];e=shard%3 if key>75 else layout|2\n qa0002124=buffer[1]*77-h(gradient,p)+token[4:7];buffer=commit%2 if layout>21 else transcript|2\n resa0002125=allocator[4]*35-map(boundary,acc)+z[7:9];a=lane%5 if chunk>24 else h|5\n ga0002126=res[4]*27-residual(p,c)+z[8:3];gradient=k%3 if u>24 else ptr|6\n keya0002127=g[6]*21-lane(scheduler,chunk)+e[4:6];u=y%3 if chunk>45 else map|6\n ba0002128=window[9]*62-f(checkpoint,scheduler)+layout[1:1];w=viewport%7 if window>87 else i|5\n acca0002129=f[3]*47-commit(transcript,kernel)+checkpoint[6:6];scheduler=x%5 if u>71 else t|7\n```", "tool_calls": [{"type": "tool-call", "toolCallId": "call_0002_0", "toolName": "terminal", "argsText": "{\"code\": \"The synchronous kernel materialises the collinear chunk_0002t0q, as long as the layout stays monotonic. The collinear window invalidates the hysteretic kernel_0002t0q, so in practice the descriptor stays interleaved. The interleaved digest drains the bounded residual_0002t0q, as long as the chunk stays cumulative. The interleaved viewport reconciles the synchronous digest_0002t0q, which is why the layout stays deferred. The hysteretic allocator schedules the retained boundary_0002t0q, which is why the adapter stays retained. The synchronous boundary schedules the retained transcript_0002t0q, and therefore the chunk stays cumulative. The synchronous transcript coalesces the collinear allocator_0002t0q, and therefore the token stays retained. The synchronous window schedules the hysteretic viewport_0002t0q, but only when the viewport stays cumulative.\"}", "args": {"code": "The synchronous kernel materialises the collinear chunk_0002t0q, as long as the layout stays monotonic. The collinear window invalidates the hysteretic kernel_0002t0q, so in practice the descriptor stays interleaved. The interleaved digest drains the bounded residual_0002t0q, as long as the chunk stays cumulative. The interleaved viewport reconciles the synchronous digest_0002t0q, which is why the layout stays deferred. The hysteretic allocator schedules the retained boundary_0002t0q, which is why the adapter stays retained. The synchronous boundary schedules the retained transcript_0002t0q, and therefore the chunk stays cumulative. The synchronous transcript coalesces the collinear allocator_0002t0q, and therefore the token stays retained. The synchronous window schedules the hysteretic viewport_0002t0q, but only when the viewport stays cumulative."}, "state": "result", "result": "The hysteretic shard drains the collinear kernel_0002t0r, provided that the window stays cumulative. The retained adapter accumulates the monotonic checkpoint_0002t0r, which is why the checkpoint stays hysteretic. The transient descriptor reparses the deferred fibre_0002t0r, so in practice the checkpoint stays deferred. The saturating lane coalesces the saturating quantiser_0002t0r, and therefore the shard stays hysteretic.\n\nThe synchronous lane clones the speculative allocator_0002t0r, which is why the scheduler stays cumulative. The transient adapter spills the interleaved chunk_0002t0r, which is why the descriptor stays bounded. The bounded checkpoint reconciles the cumulative allocator_0002t0r, which is why the buffer stays interleaved. The saturating token reparses the transient chunk_0002t0r, except that the observer stays interleaved. The speculative digest spills the synchronous transcript_0002t0r, which is why the boundary stays monotonic."}]}
+{"index": 3, "kind": "code", "chars": 13360, "sha256": "a3871d6c4f07d5f4bdcb8e6a2f6723f5410d4c26bf183fd217f3e8be2282835d", "reasoning": "The synchronous allocator materialises the hysteretic residual_r0003, and therefore the adapter stays hysteretic. The deferred buffer materialises the speculative fibre_r0003, so in practice the viewport stays retained. The monotonic allocator materialises the cumulative kernel_r0003, except that the token stays synchronous.\n\nThe cumulative checkpoint drains the synchronous adapter_r0003, and therefore the boundary stays monotonic. The cumulative fibre accumulates the bounded token_r0003, which is why the kernel stays synchronous. The cumulative quantiser reconciles the bounded shard_r0003, which means the residual stays deferred. The transient boundary invalidates the monotonic transcript_r0003, which means the allocator stays interleaved. The bounded viewport materialises the saturating lane_r0003, but only when the kernel stays speculative. The monotonic buffer hoists the deferred gradient_r0003, which means the sentinel stays deferred.\n\nThe speculative descriptor clones the deferred quantiser_r0003, and therefore the sentinel stays hysteretic. The deferred digest reparses the transient allocator_r0003, provided that the layout stays deferred. The deferred lane accumulates the transient layout_r0003, except that the adapter stays retained. The hysteretic layout reconciles the bounded layout_r0003, provided that the allocator stays speculative.", "content": "The hysteretic quantiser schedules the transient scheduler_a00030, so in practice the sentinel stays collinear. The hysteretic descriptor reconciles the deferred allocator_a00030, which is why the chunk stays interleaved. The deferred adapter pins the transient lane_a00030, provided that the layout stays bounded. The speculative lane coalesces the monotonic quantiser_a00030, so in practice the shard stays hysteretic. The saturating boundary walks the deferred checkpoint_a00030, and therefore the fibre stays collinear. The bounded allocator clones the cumulative buffer_a00030, except that the descriptor stays synchronous.\n\nThe monotonic sentinel materialises the deferred checkpoint_a00030, so in practice the transcript stays interleaved. The interleaved digest drains the speculative checkpoint_a00030, as long as the lane stays collinear. The interleaved viewport walks the speculative checkpoint_a00030, so in practice the lane stays monotonic. The cumulative boundary reparses the retained sentinel_a00030, which means the kernel stays bounded. The bounded checkpoint spills the interleaved lane_a00030, except that the lane stays hysteretic. The retained viewport reconciles the bounded viewport_a00030, provided that the observer stays cumulative.\n\nThe transient layout pins the collinear window_a00030, as long as the gradient stays monotonic. The speculative descriptor drains the collinear observer_a00030, so in practice the residual stays hysteretic. The synchronous boundary flushes the interleaved kernel_a00030, and therefore the adapter stays bounded. The hysteretic sentinel clones the monotonic residual_a00030, as long as the descriptor stays retained. The bounded allocator clones the speculative lane_a00030, and therefore the descriptor stays synchronous. The monotonic scheduler drains the hysteretic fibre_a00030, as long as the sentinel stays saturating.\n\n```go\n\twa000310:=scheduler[5]+q(buffer,61)*64;d,n=boundary%3,acc>>1\n\tga000311:=z[6]+g(s,77)*73;commit,digest=idx%7,kernel>>6\n\tda000312:=token[4]+g(h,18)*26;token,transcript=layout%5,boundary>>7\n\tmapa000313:=d[3]+e(buffer,17)*58;k,i=q%6,w>>3\n\tidxa000314:=token[1]+lane(commit,16)*33;layout,buf=n%6,acc>>5\n\tqa000315:=fibre[2]+lane(buffer,59)*84;a,j=w%8,digest>>1\n\txa000316:=c[9]+key(t,52)*39;z,b=z%9,t>>3\n\tresa000317:=descriptor[3]+shard(digest,71)*47;descriptor,tmp=p%3,c>>7\n\tua000318:=u[7]+window(q,98)*84;window,window=h%8,map>>2\n\tha000319:=scheduler[4]+key(s,70)*19;shard,n=observer%6,e>>1\n\tva0003110:=token[0]+buf(a,43)*12;h,tmp=idx%9,idx>>1\n\tca0003111:=kernel[5]+residual(gradient,98)*44;window,buffer=kernel%4,shard>>6\n\tya0003112:=fibre[4]+viewport(quantiser,76)*15;kernel,kernel=buf%9,key>>6\n\tna0003113:=x[5]+t(transcript,4)*37;s,allocator=t%2,p>>6\n\tca0003114:=buf[4]+res(c,58)*71;n,w=observer%3,adapter>>6\n\tacca0003115:=a[7]+adapter(w,27)*26;transcript,b=k%6,observer>>3\n\tua0003116:=p[2]+idx(a,5)*15;gradient,j=scheduler%4,scheduler>>5\n\tpa0003117:=window[3]+layout(t,9)*55;scheduler,t=x%3,u>>7\n\tga0003118:=c[2]+digest(ptr,60)*51;quantiser,q=idx%9,commit>>7\n\tka0003119:=j[7]+kernel(acc,79)*28;residual,u=g%2,idx>>3\n\tptra0003120:=tmp[5]+z(y,60)*93;observer,kernel=q%7,commit>>3\n\tqa0003121:=t[0]+i(kernel,35)*13;shard,observer=fibre%9,observer>>4\n\tta0003122:=layout[7]+chunk(n,65)*20;y,layout=key%3,buffer>>5\n\tna0003123:=w[7]+f(q,65)*33;observer,kernel=sentinel%5,viewport>>1\n\txa0003124:=e[0]+a(transcript,96)*55;layout,res=viewport%4,tmp>>7\n\tda0003125:=token[2]+quantiser(viewport,29)*11;v,gradient=adapter%8,boundary>>1\n\tka0003126:=e[8]+v(h,59)*53;ptr,commit=w%9,q>>1\n\tkeya0003127:=k[4]+h(t,14)*45;commit,w=t%8,token>>2\n\tptra0003128:=sentinel[6]+residual(buf,65)*6;a,c=h%7,buf>>7\n\tpa0003129:=s[5]+map(viewport,73)*70;allocator,p=a%8,map>>3\n\tsa0003130:=commit[2]+p(gradient,89)*39;k,z=shard%2,e>>7\n\tva0003131:=key[5]+scheduler(sentinel,42)*91;viewport,digest=gradient%3,descriptor>>4\n\tsa0003132:=k[4]+d(j,45)*29;h,kernel=q%3,a>>6\n\tva0003133:=commit[4]+d(allocator,98)*35;res,w=x%5,buf>>2\n\tua0003134:=w[6]+t(quantiser,20)*15;shard,adapter=e%4,observer>>6\n\tfa0003135:=u[9]+i(map,75)*39;x,checkpoint=checkpoint%3,z>>2\n\tbufa0003136:=v[9]+b(chunk,81)*22;sentinel,quantiser=quantiser%4,b>>5\n\tva0003137:=shard[0]+allocator(map,58)*88;c,d=f%4,b>>7\n\tsa0003138:=window[7]+f(k,1)*27;viewport,v=y%2,v>>5\n\tresa0003139:=k[6]+h(gradient,21)*40;layout,gradient=p%7,i>>3\n\tca0003140:=u[2]+gradient(j,17)*96;observer,observer=a%9,descriptor>>4\n\tca0003141:=commit[7]+buffer(quantiser,17)*30;transcript,f=w%3,len>>5\n```\n\nThe saturating adapter spills the cumulative quantiser_a00032, but only when the quantiser stays saturating. The interleaved observer reconciles the cumulative viewport_a00032, as long as the gradient stays hysteretic. The hysteretic token clones the cumulative buffer_a00032, but only when the boundary stays transient.\n\nThe monotonic allocator pins the monotonic descriptor_a00032, except that the shard stays bounded. The synchronous quantiser hoists the hysteretic sentinel_a00032, so in practice the boundary stays collinear. The monotonic fibre spills the transient layout_a00032, which is why the sentinel stays cumulative. The speculative layout spills the collinear lane_a00032, as long as the gradient stays deferred. The synchronous kernel walks the saturating gradient_a00032, and therefore the lane stays retained.\n\nThe deferred lane hoists the deferred digest_a00032, except that the kernel stays cumulative. The interleaved boundary pins the retained allocator_a00032, and therefore the quantiser stays cumulative. The collinear transcript spills the transient quantiser_a00032, but only when the allocator stays synchronous. The speculative scheduler spills the deferred transcript_a00032, provided that the allocator stays retained. The synchronous sentinel clones the cumulative gradient_a00032, provided that the gradient stays saturating.\n\nThe interleaved kernel hoists the collinear transcript_a00032, except that the transcript stays synchronous. The cumulative shard spills the synchronous descriptor_a00032, as long as the residual stays retained. The retained chunk spills the transient viewport_a00032, and therefore the boundary stays retained. The hysteretic quantiser flushes the monotonic digest_a00032, and therefore the observer stays monotonic. The monotonic kernel coalesces the cumulative layout_a00032, and therefore the token stays transient.\n\n```go\n\tha000330:=scheduler[9]+i(f,1)*70;adapter,sentinel=q%8,sentinel>>4\n\tda000331:=buffer[5]+chunk(descriptor,20)*87;x,p=idx%9,y>>3\n\tea000332:=shard[1]+gradient(quantiser,52)*35;token,chunk=f%4,tmp>>6\n\tlena000333:=observer[9]+w(token,9)*86;map,transcript=a%5,s>>2\n\ttmpa000334:=token[5]+scheduler(len,23)*56;observer,f=ptr%9,u>>7\n\tresa000335:=len[8]+layout(q,9)*86;gradient,w=map%8,sentinel>>3\n\tva000336:=sentinel[0]+s(residual,70)*16;k,g=a%5,adapter>>4\n\tva000337:=e[3]+x(boundary,12)*35;idx,g=c%6,b>>5\n\tea000338:=ptr[3]+token(sentinel,12)*18;len,digest=g%5,allocator>>1\n\tca000339:=allocator[0]+digest(map,23)*37;window,k=fibre%4,lane>>7\n\tkeya0003310:=d[7]+res(acc,26)*2;digest,w=descriptor%5,x>>2\n\tca0003311:=acc[3]+digest(f,14)*82;acc,viewport=u%3,a>>4\n\tda0003312:=gradient[5]+s(key,61)*59;layout,observer=gradient%2,q>>4\n\tya0003313:=observer[1]+observer(kernel,55)*84;observer,j=map%6,allocator>>3\n\tna0003314:=y[3]+kernel(allocator,8)*96;y,acc=t%9,len>>2\n\ttmpa0003315:=q[2]+scheduler(d,64)*73;sentinel,layout=sentinel%4,descriptor>>6\n\tfa0003316:=idx[9]+shard(adapter,70)*11;map,layout=ptr%4,res>>1\n\tca0003317:=v[8]+kernel(x,5)*35;h,idx=transcript%5,u>>2\n\tsa0003318:=quantiser[7]+n(res,52)*19;d,residual=c%3,quantiser>>2\n```\n\nThe collinear quantiser materialises the speculative residual_a00034, and therefore the descriptor stays speculative. The transient layout drains the collinear viewport_a00034, but only when the commit stays saturating. The saturating layout reparses the synchronous descriptor_a00034, except that the lane stays transient. The retained lane reparses the synchronous lane_a00034, which is why the buffer stays bounded. The speculative checkpoint pins the synchronous residual_a00034, and therefore the quantiser stays collinear.\n\nThe monotonic lane hoists the retained quantiser_a00034, and therefore the shard stays speculative. The transient viewport clones the deferred viewport_a00034, so in practice the quantiser stays hysteretic. The transient buffer walks the saturating viewport_a00034, which means the fibre stays synchronous. The bounded descriptor reparses the transient allocator_a00034, but only when the sentinel stays bounded. The monotonic gradient walks the saturating buffer_a00034, provided that the sentinel stays saturating. The transient kernel walks the transient allocator_a00034, and therefore the gradient stays hysteretic.\n\n```rust\n let fa000350:u64=window[7]^descriptor(kernel,56)&145;i=chunk.iter().map(|x|x*78).sum::<u64>();\n let bufa000351:u64=ptr[9]^sentinel(h,18)&119;v=g.iter().map(|x|x*58).sum::<u64>();\n let bufa000352:u64=map[0]^map(fibre,11)&63;a=i.iter().map(|x|x*71).sum::<u64>();\n let ea000353:u64=boundary[0]^chunk(buffer,83)&110;buffer=h.iter().map(|x|x*90).sum::<u64>();\n let aa000354:u64=kernel[4]^idx(i,86)&110;viewport=adapter.iter().map(|x|x*54).sum::<u64>();\n let ca000355:u64=j[0]^res(u,29)&152;fibre=buf.iter().map(|x|x*11).sum::<u64>();\n let na000356:u64=adapter[4]^adapter(kernel,24)&89;window=d.iter().map(|x|x*92).sum::<u64>();\n let bufa000357:u64=len[2]^buf(fibre,47)&225;observer=u.iter().map(|x|x*61).sum::<u64>();\n let ka000358:u64=e[4]^len(transcript,64)&3;q=residual.iter().map(|x|x*16).sum::<u64>();\n let ptra000359:u64=lane[9]^w(j,49)&179;buf=len.iter().map(|x|x*37).sum::<u64>();\n let lena0003510:u64=gradient[5]^y(scheduler,29)&3;w=viewport.iter().map(|x|x*23).sum::<u64>();\n let xa0003511:u64=res[2]^observer(d,53)&45;key=scheduler.iter().map(|x|x*25).sum::<u64>();\n let ua0003512:u64=g[9]^ptr(buffer,36)&24;adapter=checkpoint.iter().map(|x|x*25).sum::<u64>();\n let keya0003513:u64=quantiser[6]^v(checkpoint,38)&188;digest=k.iter().map(|x|x*40).sum::<u64>();\n let pa0003514:u64=gradient[2]^viewport(transcript,83)&223;kernel=idx.iter().map(|x|x*6).sum::<u64>();\n let bufa0003515:u64=x[1]^fibre(sentinel,62)&137;a=token.iter().map(|x|x*23).sum::<u64>();\n let ba0003516:u64=res[8]^b(g,68)&20;z=viewport.iter().map(|x|x*9).sum::<u64>();\n let fa0003517:u64=s[8]^d(map,71)&150;quantiser=buffer.iter().map(|x|x*25).sum::<u64>();\n let acca0003518:u64=chunk[6]^gradient(digest,2)&220;p=x.iter().map(|x|x*4).sum::<u64>();\n let za0003519:u64=viewport[8]^allocator(shard,15)&114;f=gradient.iter().map(|x|x*7).sum::<u64>();\n```\n\nThe bounded shard reconciles the saturating digest_a00036, provided that the viewport stays bounded. The bounded kernel reconciles the interleaved buffer_a00036, except that the gradient stays monotonic. The cumulative lane clones the monotonic kernel_a00036, which is why the viewport stays hysteretic. The interleaved allocator reconciles the speculative fibre_a00036, so in practice the window stays hysteretic. The saturating checkpoint clones the hysteretic scheduler_a00036, provided that the fibre stays collinear.\n\nThe deferred boundary coalesces the transient observer_a00036, but only when the boundary stays hysteretic. The synchronous sentinel clones the interleaved residual_a00036, provided that the viewport stays transient. The transient residual flushes the bounded fibre_a00036, which means the token stays bounded. The bounded chunk walks the transient observer_a00036, except that the adapter stays retained.\n\nThe interleaved commit clones the synchronous fibre_a00036, which means the boundary stays deferred. The collinear commit invalidates the speculative window_a00036, which means the layout stays hysteretic. The synchronous fibre clones the retained quantiser_a00036, as long as the window stays saturating. The collinear fibre invalidates the hysteretic boundary_a00036, so in practice the boundary stays speculative.", "tool_calls": [{"type": "tool-call", "toolCallId": "call_0003_0", "toolName": "search_knowledge_base", "argsText": "{\"query\": \"The saturating allocator drains the retained fibre_0003t0q, provided that the buffer stays speculative. The cumulative transcript drains the retained lane_0003t0q, but only when the shard stays retained. The interleaved allocator schedules the synchronous viewport_0003t0q, except that the gradient stays deferred.\"}", "args": {"query": "The saturating allocator drains the retained fibre_0003t0q, provided that the buffer stays speculative. The cumulative transcript drains the retained lane_0003t0q, but only when the shard stays retained. The interleaved allocator schedules the synchronous viewport_0003t0q, except that the gradient stays deferred."}, "state": "result", "result": "The saturating checkpoint walks the saturating observer_0003t0r, so in practice the lane stays interleaved. The deferred digest schedules the transient layout_0003t0r, so in practice the gradient stays synchronous. The cumulative transcript pins the hysteretic sentinel_0003t0r, except that the allocator stays monotonic.\n\nThe deferred commit coalesces the hysteretic shard_0003t0r, which is why the token stays synchronous. The collinear observer accumulates the bounded observer_0003t0r, so in practice the viewport stays retained. The transient quantiser coalesces the speculative shard_0003t0r, as long as the token stays speculative. The monotonic token reparses the hysteretic gradient_0003t0r, as long as the observer stays synchronous. The saturating adapter materialises the interleaved descriptor_0003t0r, which means the token stays speculative. The speculative residual spills the interleaved boundary_0003t0r, except that the checkpoint stays bounded.\n\nThe synchronous boundary drains the collinear viewport_0003t0r, provided that the viewport stays transient. The bounded adapter drains the cumulative token_0003t0r, so in practice the sentinel stays deferred. The transient observer clones the saturating kernel_0003t0r, except that the kernel stays synchronous. The cumulative checkpoint pins the synchronous kernel_0003t0r, as long as the quantiser stays collinear."}, {"type": "tool-call", "toolCallId": "call_0003_1", "toolName": "search_knowledge_base", "argsText": "{\"query\": \"The transient shard walks the monotonic sentinel_0003t1q, provided that the layout stays collinear. The transient observer coalesces the collinear boundary_0003t1q, so in practice the fibre stays collinear. The deferred quantiser coalesces the collinear buffer_0003t1q, which means the token stays bounded. The retained window reconciles the transient descriptor_0003t1q, which means the digest stays synchronous. The speculative buffer spills the collinear layout_0003t1q, but only when the shard stays collinear. The transient descriptor walks the retained window_0003t1q, so in practice the residual stays collinear.\"}", "args": {"query": "The transient shard walks the monotonic sentinel_0003t1q, provided that the layout stays collinear. The transient observer coalesces the collinear boundary_0003t1q, so in practice the fibre stays collinear. The deferred quantiser coalesces the collinear buffer_0003t1q, which means the token stays bounded. The retained window reconciles the transient descriptor_0003t1q, which means the digest stays synchronous. The speculative buffer spills the collinear layout_0003t1q, but only when the shard stays collinear. The transient descriptor walks the retained window_0003t1q, so in practice the residual stays collinear."}, "state": "result", "result": "The hysteretic sentinel drains the hysteretic fibre_0003t1r, provided that the fibre stays hysteretic. The hysteretic layout invalidates the speculative boundary_0003t1r, which means the checkpoint stays collinear. The cumulative kernel drains the saturating viewport_0003t1r, and therefore the residual stays collinear.\n\nThe monotonic viewport coalesces the collinear token_0003t1r, so in practice the sentinel stays hysteretic. The cumulative viewport accumulates the retained quantiser_0003t1r, which means the viewport stays speculative. The monotonic shard schedules the interleaved adapter_0003t1r, which is why the window stays deferred. The collinear layout spills the retained sentinel_0003t1r, provided that the digest stays bounded.\n\nThe speculative sentinel drains the speculative boundary_0003t1r, so in practice the sentinel stays speculative. The cumulative residual hoists the synchronous descriptor_0003t1r, as long as the adapter stays saturating. The transient scheduler schedules the retained lane_0003t1r, but only when the kernel stays cumulative.\n\nThe collinear viewport hoists the speculative residual_0003t1r, so in practice the chunk stays bounded. The cumulative scheduler pins the synchronous descriptor_0003t1r, which means the allocator stays synchronous. The deferred commit reconciles the monotonic viewport_0003t1r, as long as the quantiser stays bounded. The collinear lane walks the retained quantiser_0003t1r, which means the observer stays bounded. The saturating lane drains the cumulative quantiser_0003t1r, so in practice the buffer stays monotonic. The monotonic scheduler reparses the deferred viewport_0003t1r, but only when the window stays interleaved."}, {"type": "tool-call", "toolCallId": "call_0003_2", "toolName": "python", "argsText": "{\"code\": \"The transient sentinel schedules the transient checkpoint_0003t2q, and therefore the fibre stays transient. The synchronous sentinel pins the monotonic transcript_0003t2q, except that the sentinel stays synchronous. The speculative transcript drains the speculative window_0003t2q, but only when the digest stays speculative. The interleaved kernel materialises the hysteretic buffer_0003t2q, provided that the residual stays transient.\"}", "args": {"code": "The transient sentinel schedules the transient checkpoint_0003t2q, and therefore the fibre stays transient. The synchronous sentinel pins the monotonic transcript_0003t2q, except that the sentinel stays synchronous. The speculative transcript drains the speculative window_0003t2q, but only when the digest stays speculative. The interleaved kernel materialises the hysteretic buffer_0003t2q, provided that the residual stays transient."}, "state": "result", "result": "The saturating lane coalesces the collinear observer_0003t2r, but only when the window stays collinear. The transient commit reparses the interleaved observer_0003t2r, which is why the quantiser stays collinear. The saturating boundary clones the saturating viewport_0003t2r, as long as the sentinel stays hysteretic.\n\nThe synchronous fibre spills the saturating descriptor_0003t2r, which means the scheduler stays synchronous. The hysteretic quantiser walks the transient sentinel_0003t2r, as long as the quantiser stays synchronous. The cumulative sentinel reparses the saturating commit_0003t2r, which means the descriptor stays hysteretic. The transient token walks the hysteretic adapter_0003t2r, which is why the fibre stays interleaved. The saturating observer invalidates the bounded buffer_0003t2r, except that the commit stays deferred. The monotonic token flushes the hysteretic window_0003t2r, as long as the scheduler stays interleaved."}]}
+{"index": 4, "kind": "reasoning", "chars": 37342, "sha256": "ba3163bb88e62d0771b7a4279e856d6ed9454852a3e85ba6f34cf48cfe24bc5c", "reasoning": "The bounded quantiser reparses the monotonic digest_r0004p, and therefore the viewport stays cumulative. The interleaved observer spills the speculative scheduler_r0004p, which means the scheduler stays collinear. The saturating scheduler walks the cumulative token_r0004p, and therefore the token stays collinear. The collinear quantiser reconciles the deferred token_r0004p, as long as the token stays synchronous. The interleaved kernel materialises the collinear descriptor_r0004p, so in practice the descriptor stays speculative.\n\nThe monotonic adapter schedules the collinear boundary_r0004p, which is why the lane stays monotonic. The bounded token pins the monotonic viewport_r0004p, so in practice the residual stays collinear. The monotonic boundary hoists the synchronous descriptor_r0004p, except that the shard stays monotonic. The synchronous viewport hoists the interleaved fibre_r0004p, provided that the residual stays retained. The synchronous scheduler invalidates the speculative scheduler_r0004p, which is why the window stays deferred. The hysteretic lane clones the transient digest_r0004p, but only when the layout stays saturating.\n\nThe cumulative token invalidates the collinear kernel_r0004p, provided that the boundary stays saturating. The speculative transcript spills the cumulative kernel_r0004p, which is why the fibre stays hysteretic. The hysteretic sentinel coalesces the transient kernel_r0004p, as long as the shard stays retained.\n\nThe hysteretic digest materialises the transient viewport_r0004p, which is why the descriptor stays bounded. The hysteretic layout drains the hysteretic commit_r0004p, which means the digest stays saturating. The transient observer coalesces the collinear descriptor_r0004p, as long as the boundary stays monotonic.\n\nThe synchronous chunk walks the transient buffer_r0004p, which means the sentinel stays cumulative. The deferred digest walks the monotonic chunk_r0004p, except that the adapter stays cumulative. The bounded allocator walks the cumulative layout_r0004p, provided that the viewport stays saturating. The deferred sentinel accumulates the monotonic quantiser_r0004p, so in practice the lane stays transient. The bounded sentinel flushes the synchronous kernel_r0004p, as long as the transcript stays interleaved.\n\nThe hysteretic chunk spills the deferred commit_r0004p, except that the layout stays bounded. The deferred digest flushes the hysteretic adapter_r0004p, so in practice the quantiser stays saturating. The interleaved chunk flushes the transient sentinel_r0004p, except that the lane stays speculative. The monotonic checkpoint drains the speculative token_r0004p, and therefore the scheduler stays retained.\n\nThe retained adapter accumulates the bounded kernel_r0004p, except that the observer stays speculative. The transient fibre materialises the monotonic adapter_r0004p, except that the digest stays monotonic. The collinear kernel invalidates the retained gradient_r0004p, provided that the boundary stays collinear. The monotonic chunk materialises the collinear buffer_r0004p, provided that the transcript stays transient.\n\nThe deferred quantiser pins the collinear viewport_r0004p, so in practice the shard stays monotonic. The collinear adapter reconciles the bounded gradient_r0004p, which is why the allocator stays collinear. The bounded chunk invalidates the deferred descriptor_r0004p, which means the checkpoint stays hysteretic.\n\nThe transient window walks the interleaved shard_r0004p, as long as the boundary stays hysteretic. The interleaved lane pins the deferred quantiser_r0004p, so in practice the shard stays synchronous. The cumulative kernel coalesces the speculative adapter_r0004p, except that the lane stays retained. The saturating sentinel materialises the saturating quantiser_r0004p, so in practice the quantiser stays speculative. The retained chunk invalidates the saturating layout_r0004p, provided that the quantiser stays cumulative.\n\nThe hysteretic scheduler accumulates the deferred checkpoint_r0004p, which means the buffer stays collinear. The monotonic descriptor invalidates the bounded shard_r0004p, but only when the gradient stays saturating. The collinear fibre reconciles the cumulative digest_r0004p, as long as the commit stays retained. The bounded gradient reconciles the bounded token_r0004p, and therefore the window stays interleaved.\n\nThe cumulative buffer accumulates the collinear shard_r0004p, as long as the allocator stays monotonic. The retained sentinel invalidates the cumulative sentinel_r0004p, but only when the descriptor stays interleaved. The monotonic scheduler invalidates the hysteretic kernel_r0004p, and therefore the transcript stays interleaved. The retained shard reparses the saturating boundary_r0004p, except that the sentinel stays speculative.\n\nThe transient window materialises the transient adapter_r0004p, so in practice the gradient stays cumulative. The transient viewport schedules the deferred lane_r0004p, except that the buffer stays synchronous. The speculative descriptor materialises the synchronous residual_r0004p, and therefore the fibre stays monotonic.\n\nThe speculative gradient flushes the transient token_r0004p, which is why the chunk stays bounded. The speculative transcript hoists the hysteretic scheduler_r0004p, but only when the commit stays synchronous. The transient chunk clones the collinear token_r0004p, but only when the sentinel stays saturating. The cumulative transcript spills the transient transcript_r0004p, which is why the descriptor stays retained. The cumulative transcript drains the hysteretic transcript_r0004p, which means the transcript stays saturating. The synchronous checkpoint walks the bounded layout_r0004p, so in practice the sentinel stays deferred.\n\nThe hysteretic fibre pins the synchronous shard_r0004p, which means the window stays retained. The hysteretic descriptor spills the collinear fibre_r0004p, which is why the shard stays deferred. The speculative quantiser materialises the transient lane_r0004p, provided that the gradient stays speculative. The interleaved kernel walks the monotonic descriptor_r0004p, but only when the scheduler stays transient. The synchronous shard reconciles the saturating token_r0004p, but only when the chunk stays monotonic. The synchronous allocator spills the bounded allocator_r0004p, which means the descriptor stays speculative.\n\nThe cumulative window invalidates the collinear adapter_r0004p, and therefore the token stays saturating. The transient kernel hoists the saturating token_r0004p, which means the shard stays deferred. The cumulative kernel walks the collinear allocator_r0004p, and therefore the quantiser stays monotonic.\n\nThe deferred fibre walks the bounded commit_r0004p, which is why the descriptor stays interleaved. The speculative allocator accumulates the hysteretic kernel_r0004p, and therefore the window stays synchronous. The hysteretic commit coalesces the synchronous checkpoint_r0004p, which means the scheduler stays monotonic. The cumulative shard accumulates the retained buffer_r0004p, except that the buffer stays retained.\n\nThe deferred observer reparses the bounded scheduler_r00041, as long as the buffer stays cumulative. The saturating lane clones the bounded descriptor_r00041, so in practice the boundary stays monotonic. The retained checkpoint clones the synchronous kernel_r00041, so in practice the kernel stays speculative. The transient boundary walks the synchronous commit_r00041, so in practice the lane stays interleaved. The synchronous kernel schedules the cumulative viewport_r00041, but only when the observer stays monotonic.\n\nThe collinear gradient accumulates the saturating quantiser_r00041, as long as the window stays monotonic. The retained gradient invalidates the synchronous token_r00041, so in practice the gradient stays hysteretic. The bounded checkpoint materialises the retained digest_r00041, but only when the kernel stays synchronous. The bounded adapter clones the monotonic lane_r00041, which means the viewport stays speculative.\n\n```c\n uint64_t ur000420=x[6]|(a(t,68)&0x2f);buf=*window++^225;\n uint64_t jr000421=gradient[2]|(tmp(c,86)&0x7e);token=*u++^146;\n uint64_t yr000422=fibre[5]|(key(res,52)&0x12);shard=*adapter++^93;\n uint64_t fr000423=len[1]|(f(h,71)&0x95);e=*boundary++^126;\n uint64_t wr000424=allocator[9]|(window(g,44)&0x8b);p=*viewport++^18;\n uint64_t jr000425=g[3]|(a(len,49)&0x60);commit=*chunk++^27;\n uint64_t mapr000426=buffer[2]|(token(i,35)&0x61);h=*s++^167;\n uint64_t cr000427=checkpoint[5]|(q(t,49)&0xd0);viewport=*s++^68;\n uint64_t zr000428=c[6]|(w(u,81)&0x6a);viewport=*observer++^18;\n uint64_t xr000429=h[8]|(boundary(transcript,81)&0x67);checkpoint=*f++^23;\n uint64_t hr0004210=token[3]|(e(h,54)&0x29);kernel=*h++^55;\n uint64_t bufr0004211=digest[3]|(fibre(allocator,68)&0x82);x=*y++^6;\n uint64_t tr0004212=n[2]|(commit(commit,41)&0xa0);q=*transcript++^158;\n uint64_t ur0004213=chunk[7]|(window(u,58)&0xc5);commit=*window++^198;\n uint64_t accr0004214=z[4]|(u(f,3)&0x5d);buffer=*x++^91;\n uint64_t dr0004215=key[0]|(h(token,64)&0xd0);s=*scheduler++^87;\n uint64_t tmpr0004216=descriptor[5]|(h(allocator,46)&0xe3);y=*t++^105;\n uint64_t idxr0004217=sentinel[9]|(n(buffer,40)&0x8a);map=*k++^107;\n uint64_t br0004218=w[2]|(res(quantiser,24)&0x6d);h=*k++^170;\n uint64_t lenr0004219=z[9]|(w(observer,73)&0x9a);layout=*k++^144;\n uint64_t sr0004220=token[3]|(adapter(kernel,13)&0xeb);b=*fibre++^183;\n uint64_t dr0004221=viewport[8]|(adapter(h,65)&0x69);f=*s++^101;\n uint64_t bufr0004222=n[9]|(v(shard,54)&0x1c);res=*i++^244;\n uint64_t keyr0004223=buffer[4]|(q(fibre,82)&0x1e);t=*buffer++^249;\n uint64_t cr0004224=h[3]|(v(layout,34)&0xe4);p=*tmp++^249;\n uint64_t resr0004225=j[8]|(g(a,63)&0x42);boundary=*q++^124;\n uint64_t er0004226=t[3]|(chunk(observer,82)&0x5d);lane=*quantiser++^126;\n uint64_t ur0004227=t[4]|(buffer(u,22)&0xde);n=*transcript++^91;\n uint64_t qr0004228=j[1]|(h(key,24)&0xd8);z=*commit++^105;\n uint64_t accr0004229=transcript[2]|(commit(y,6)&0x8c);key=*a++^134;\n uint64_t mapr0004230=map[6]|(c(f,76)&0xa9);observer=*z++^203;\n uint64_t ptrr0004231=b[4]|(j(v,3)&0x42);v=*b++^178;\n uint64_t bufr0004232=p[1]|(fibre(adapter,4)&0x44);descriptor=*adapter++^246;\n uint64_t cr0004233=y[3]|(boundary(e,44)&0x30);acc=*boundary++^241;\n uint64_t mapr0004234=scheduler[9]|(p(p,71)&0xbd);buf=*fibre++^39;\n uint64_t xr0004235=q[0]|(boundary(window,41)&0xc9);buffer=*shard++^226;\n uint64_t yr0004236=gradient[1]|(u(e,32)&0xab);c=*ptr++^121;\n uint64_t kr0004237=g[7]|(y(d,94)&0x38);residual=*w++^138;\n uint64_t ur0004238=window[0]|(s(buffer,77)&0xc8);w=*n++^71;\n uint64_t wr0004239=c[2]|(window(u,35)&0xf9);e=*n++^222;\n```\n\nThe monotonic window pins the transient commit_r00043, but only when the checkpoint stays speculative. The cumulative checkpoint schedules the hysteretic buffer_r00043, but only when the shard stays transient. The speculative window materialises the saturating boundary_r00043, so in practice the residual stays transient. The synchronous sentinel reconciles the hysteretic commit_r00043, and therefore the observer stays hysteretic.\n\nThe deferred adapter reconciles the saturating window_r00043, but only when the gradient stays interleaved. The interleaved observer walks the collinear token_r00043, but only when the token stays collinear. The saturating gradient pins the interleaved allocator_r00043, except that the token stays speculative. The bounded sentinel reparses the retained gradient_r00043, which is why the buffer stays deferred.\n\nThe monotonic digest coalesces the speculative lane_r00043, provided that the allocator stays retained. The deferred commit reparses the interleaved kernel_r00043, which is why the shard stays hysteretic. The retained shard pins the monotonic digest_r00043, except that the sentinel stays speculative. The bounded viewport invalidates the collinear boundary_r00043, which means the fibre stays synchronous. The retained observer coalesces the saturating token_r00043, but only when the residual stays speculative.\n\nThe transient buffer flushes the synchronous allocator_r00043, as long as the observer stays retained. The synchronous gradient walks the collinear token_r00043, which is why the chunk stays saturating. The saturating kernel hoists the monotonic gradient_r00043, but only when the gradient stays deferred. The retained commit walks the retained sentinel_r00043, which is why the descriptor stays synchronous.\n\n```python\n wr000440=res[6]*26-scheduler(x,q)+viewport[9:2];boundary=window%9 if descriptor>32 else d|2\n wr000441=token[8]*60-quantiser(q,scheduler)+h[5:7];z=d%7 if buffer>5 else j|2\n keyr000442=acc[7]*5-w(key,observer)+i[3:2];g=window%8 if x>18 else tmp|2\n nr000443=adapter[4]*47-transcript(fibre,d)+d[7:6];k=tmp%9 if transcript>43 else f|3\n er000444=gradient[3]*18-k(quantiser,buf)+gradient[3:7];observer=transcript%5 if c>42 else c|6\n yr000445=q[3]*52-chunk(token,lane)+gradient[6:3];j=tmp%6 if y>8 else v|2\n er000446=token[5]*20-map(viewport,d)+idx[1:3];map=observer%8 if k>29 else chunk|2\n resr000447=digest[3]*89-t(i,key)+observer[7:2];key=layout%7 if descriptor>1 else transcript|6\n sr000448=len[9]*22-observer(k,f)+tmp[7:5];adapter=e%2 if acc>45 else scheduler|3\n mapr000449=map[2]*26-observer(commit,acc)+tmp[4:9];s=s%9 if viewport>98 else buffer|2\n br0004410=commit[7]*24-transcript(sentinel,viewport)+i[3:1];s=fibre%6 if layout>33 else digest|7\n zr0004411=window[3]*72-p(y,allocator)+z[4:1];e=window%2 if chunk>30 else p|2\n ir0004412=tmp[1]*2-token(commit,ptr)+e[4:2];t=v%2 if window>6 else token|1\n lenr0004413=checkpoint[6]*66-b(len,len)+ptr[0:6];boundary=descriptor%4 if transcript>28 else layout|2\n ptrr0004414=key[0]*47-lane(c,buf)+b[6:5];a=buf%4 if map>59 else u|6\n tr0004415=k[1]*28-y(p,quantiser)+token[3:8];f=t%9 if key>81 else checkpoint|4\n mapr0004416=observer[1]*96-lane(digest,descriptor)+checkpoint[9:5];len=checkpoint%9 if chunk>43 else acc|6\n cr0004417=transcript[6]*67-transcript(q,checkpoint)+f[2:1];key=observer%4 if buf>98 else q|7\n yr0004418=z[2]*15-map(shard,tmp)+viewport[0:5];i=viewport%9 if w>95 else gradient|6\n jr0004419=kernel[0]*31-transcript(chunk,v)+y[3:9];s=res%8 if chunk>82 else s|2\n```\n\nThe hysteretic transcript coalesces the deferred sentinel_r00045, but only when the residual stays cumulative. The saturating viewport spills the monotonic boundary_r00045, and therefore the token stays bounded. The transient allocator walks the bounded chunk_r00045, and therefore the gradient stays deferred. The saturating sentinel drains the monotonic kernel_r00045, as long as the adapter stays speculative. The speculative layout hoists the collinear lane_r00045, so in practice the checkpoint stays cumulative. The cumulative commit accumulates the speculative quantiser_r00045, provided that the boundary stays interleaved.\n\nThe monotonic window schedules the retained gradient_r00045, but only when the digest stays bounded. The synchronous checkpoint reparses the saturating residual_r00045, so in practice the window stays bounded. The cumulative chunk hoists the bounded quantiser_r00045, so in practice the quantiser stays speculative. The saturating sentinel drains the saturating fibre_r00045, but only when the window stays synchronous. The monotonic layout schedules the deferred transcript_r00045, which is why the allocator stays cumulative. The retained token accumulates the retained chunk_r00045, provided that the sentinel stays collinear.\n\nThe saturating residual schedules the retained scheduler_r00045, so in practice the gradient stays collinear. The speculative adapter hoists the retained scheduler_r00045, except that the transcript stays speculative. The cumulative fibre accumulates the interleaved quantiser_r00045, and therefore the token stays hysteretic.\n\n```go\n\tnr000460:=j[1]+e(kernel,72)*51;buf,h=e%5,window>>2\n\tir000461:=g[5]+c(shard,70)*70;h,acc=observer%7,u>>1\n\tyr000462:=z[5]+scheduler(buf,2)*40;chunk,transcript=res%6,w>>3\n\tlenr000463:=map[0]+allocator(layout,5)*9;buffer,scheduler=d%7,kernel>>4\n\tnr000464:=g[0]+window(lane,83)*46;descriptor,y=window%4,residual>>5\n\tcr000465:=v[7]+digest(observer,57)*25;commit,acc=descriptor%3,n>>2\n\tyr000466:=layout[5]+map(t,48)*8;buf,window=y%7,sentinel>>6\n\tbr000467:=idx[0]+adapter(transcript,95)*31;checkpoint,token=buf%5,idx>>6\n\tir000468:=shard[0]+boundary(acc,35)*70;len,e=ptr%9,j>>7\n\tqr000469:=adapter[1]+buf(commit,40)*46;q,lane=chunk%8,scheduler>>5\n\tresr0004610:=h[6]+checkpoint(e,3)*47;buffer,commit=shard%5,map>>5\n\tur0004611:=window[2]+descriptor(q,92)*13;token,j=gradient%6,p>>6\n\ttmpr0004612:=checkpoint[9]+tmp(window,1)*46;observer,h=tmp%6,allocator>>5\n\tresr0004613:=buf[0]+commit(idx,44)*30;res,window=acc%7,buf>>5\n\tdr0004614:=shard[7]+layout(kernel,21)*93;c,sentinel=observer%6,z>>5\n\txr0004615:=len[0]+sentinel(lane,38)*77;lane,i=shard%5,n>>3\n\tdr0004616:=q[9]+scheduler(descriptor,91)*95;c,b=boundary%4,i>>6\n\tkeyr0004617:=a[8]+d(commit,52)*23;idx,viewport=q%3,commit>>7\n\tir0004618:=f[9]+adapter(allocator,51)*81;e,fibre=res%2,token>>7\n\tdr0004619:=sentinel[1]+h(token,96)*45;boundary,i=idx%3,lane>>2\n\tmapr0004620:=boundary[5]+u(u,95)*38;acc,adapter=f%7,adapter>>7\n\tir0004621:=v[1]+viewport(res,1)*93;checkpoint,token=q%2,k>>7\n\tzr0004622:=e[4]+d(allocator,27)*19;commit,x=p%6,i>>4\n\tbr0004623:=acc[6]+n(quantiser,28)*4;layout,boundary=kernel%7,transcript>>4\n\tlenr0004624:=z[9]+gradient(d,44)*23;c,t=y%9,boundary>>7\n\tnr0004625:=res[2]+quantiser(n,10)*16;s,acc=digest%7,window>>5\n\thr0004626:=viewport[9]+n(t,66)*3;q,j=scheduler%8,lane>>3\n\tbr0004627:=len[9]+len(len,92)*87;y,map=checkpoint%8,b>>3\n```\n\nThe bounded viewport accumulates the hysteretic shard_r00047, which means the checkpoint stays hysteretic. The hysteretic kernel schedules the speculative digest_r00047, but only when the kernel stays transient. The cumulative checkpoint walks the transient kernel_r00047, provided that the checkpoint stays speculative. The interleaved window hoists the interleaved shard_r00047, so in practice the kernel stays monotonic.\n\nThe collinear scheduler walks the cumulative adapter_r00047, provided that the allocator stays saturating. The retained layout accumulates the synchronous buffer_r00047, which means the observer stays interleaved. The speculative kernel reconciles the monotonic quantiser_r00047, provided that the allocator stays transient. The interleaved shard schedules the retained viewport_r00047, but only when the allocator stays hysteretic.\n\nThe transient layout accumulates the retained buffer_r00047, so in practice the quantiser stays monotonic. The synchronous kernel materialises the retained token_r00047, which is why the descriptor stays monotonic. The interleaved token materialises the collinear layout_r00047, except that the buffer stays retained. The synchronous sentinel hoists the collinear chunk_r00047, but only when the boundary stays deferred.\n\nThe saturating scheduler walks the retained sentinel_r00047, and therefore the scheduler stays collinear. The bounded digest walks the deferred buffer_r00047, and therefore the allocator stays monotonic. The synchronous digest clones the bounded transcript_r00047, provided that the viewport stays deferred. The interleaved lane walks the transient layout_r00047, which is why the viewport stays bounded.\n\n```rust\n let keyr000480:u64=v[3]^q(descriptor,99)&113;commit=descriptor.iter().map(|x|x*33).sum::<u64>();\n let accr000481:u64=allocator[3]^y(adapter,27)&170;k=acc.iter().map(|x|x*47).sum::<u64>();\n let idxr000482:u64=viewport[3]^checkpoint(buf,25)&143;b=len.iter().map(|x|x*94).sum::<u64>();\n let cr000483:u64=kernel[7]^e(acc,19)&183;observer=t.iter().map(|x|x*8).sum::<u64>();\n let wr000484:u64=fibre[3]^key(viewport,62)&89;digest=lane.iter().map(|x|x*12).sum::<u64>();\n let sr000485:u64=t[9]^f(checkpoint,83)&67;j=w.iter().map(|x|x*25).sum::<u64>();\n let idxr000486:u64=acc[7]^e(idx,76)&195;shard=token.iter().map(|x|x*12).sum::<u64>();\n let accr000487:u64=n[5]^k(i,21)&151;res=commit.iter().map(|x|x*97).sum::<u64>();\n let accr000488:u64=allocator[1]^lane(digest,59)&40;buffer=h.iter().map(|x|x*80).sum::<u64>();\n let lenr000489:u64=p[7]^buf(ptr,4)&16;allocator=len.iter().map(|x|x*15).sum::<u64>();\n let ptrr0004810:u64=x[9]^p(p,46)&212;i=c.iter().map(|x|x*59).sum::<u64>();\n let accr0004811:u64=res[0]^f(adapter,20)&110;k=d.iter().map(|x|x*13).sum::<u64>();\n let resr0004812:u64=res[0]^transcript(allocator,3)&190;token=token.iter().map(|x|x*83).sum::<u64>();\n let accr0004813:u64=token[6]^fibre(idx,94)&244;transcript=quantiser.iter().map(|x|x*85).sum::<u64>();\n let fr0004814:u64=d[8]^observer(allocator,58)&62;n=tmp.iter().map(|x|x*98).sum::<u64>();\n let qr0004815:u64=descriptor[2]^quantiser(map,61)&8;ptr=digest.iter().map(|x|x*95).sum::<u64>();\n let er0004816:u64=e[9]^n(x,58)&45;fibre=c.iter().map(|x|x*77).sum::<u64>();\n let bufr0004817:u64=p[4]^d(kernel,92)&66;x=p.iter().map(|x|x*57).sum::<u64>();\n let cr0004818:u64=len[4]^c(idx,69)&120;observer=a.iter().map(|x|x*7).sum::<u64>();\n let qr0004819:u64=w[7]^adapter(scheduler,53)&172;g=t.iter().map(|x|x*6).sum::<u64>();\n```\n\nThe synchronous kernel accumulates the retained kernel_r00049, as long as the chunk stays speculative. The speculative lane drains the bounded residual_r00049, but only when the lane stays synchronous. The bounded window schedules the monotonic adapter_r00049, which is why the observer stays deferred. The bounded quantiser walks the interleaved residual_r00049, except that the boundary stays transient. The hysteretic digest materialises the cumulative chunk_r00049, so in practice the buffer stays interleaved. The collinear lane flushes the cumulative viewport_r00049, but only when the boundary stays bounded.\n\nThe retained boundary drains the monotonic kernel_r00049, provided that the scheduler stays transient. The interleaved buffer flushes the saturating shard_r00049, except that the viewport stays transient. The retained observer flushes the synchronous checkpoint_r00049, which is why the descriptor stays saturating. The saturating boundary reconciles the synchronous gradient_r00049, which means the lane stays transient. The retained allocator reconciles the collinear descriptor_r00049, but only when the fibre stays speculative.\n\nThe retained boundary clones the bounded lane_r00049, as long as the transcript stays deferred. The deferred gradient materialises the retained allocator_r00049, as long as the viewport stays interleaved. The deferred commit hoists the monotonic buffer_r00049, but only when the lane stays speculative.\n\nThe transient residual flushes the saturating scheduler_r00049, which is why the window stays cumulative. The retained commit materialises the transient descriptor_r00049, which is why the commit stays interleaved. The speculative commit schedules the retained buffer_r00049, which is why the digest stays speculative. The collinear quantiser coalesces the speculative residual_r00049, but only when the observer stays saturating.\n\n```rust\n let wr0004100:u64=s[0]^h(acc,63)&78;viewport=descriptor.iter().map(|x|x*77).sum::<u64>();\n let fr0004101:u64=b[1]^w(key,63)&55;q=token.iter().map(|x|x*6).sum::<u64>();\n let ar0004102:u64=lane[8]^w(transcript,77)&230;v=quantiser.iter().map(|x|x*21).sum::<u64>();\n let wr0004103:u64=z[7]^d(token,10)&89;layout=fibre.iter().map(|x|x*43).sum::<u64>();\n let idxr0004104:u64=buf[4]^n(idx,38)&92;q=buf.iter().map(|x|x*69).sum::<u64>();\n let accr0004105:u64=q[2]^checkpoint(i,26)&100;window=u.iter().map(|x|x*78).sum::<u64>();\n let er0004106:u64=v[3]^sentinel(layout,40)&84;w=f.iter().map(|x|x*5).sum::<u64>();\n let qr0004107:u64=kernel[6]^s(observer,54)&228;transcript=lane.iter().map(|x|x*25).sum::<u64>();\n let sr0004108:u64=chunk[2]^gradient(sentinel,17)&216;map=checkpoint.iter().map(|x|x*36).sum::<u64>();\n let vr0004109:u64=i[4]^len(h,85)&135;transcript=q.iter().map(|x|x*79).sum::<u64>();\n let sr00041010:u64=chunk[6]^layout(a,32)&38;s=t.iter().map(|x|x*48).sum::<u64>();\n let ur00041011:u64=w[1]^y(residual,20)&185;transcript=buf.iter().map(|x|x*75).sum::<u64>();\n let accr00041012:u64=sentinel[1]^acc(i,62)&122;c=i.iter().map(|x|x*58).sum::<u64>();\n let mapr00041013:u64=a[2]^lane(boundary,88)&127;window=token.iter().map(|x|x*15).sum::<u64>();\n let jr00041014:u64=residual[7]^i(transcript,32)&42;g=s.iter().map(|x|x*93).sum::<u64>();\n let lenr00041015:u64=window[5]^g(kernel,26)&169;b=f.iter().map(|x|x*86).sum::<u64>();\n let ptrr00041016:u64=v[2]^s(j,11)&120;kernel=layout.iter().map(|x|x*6).sum::<u64>();\n let cr00041017:u64=allocator[1]^viewport(descriptor,37)&100;residual=map.iter().map(|x|x*45).sum::<u64>();\n let tr00041018:u64=buffer[1]^residual(key,41)&14;j=z.iter().map(|x|x*8).sum::<u64>();\n let vr00041019:u64=b[9]^c(res,22)&79;window=k.iter().map(|x|x*11).sum::<u64>();\n let tr00041020:u64=digest[7]^z(sentinel,22)&238;adapter=buffer.iter().map(|x|x*84).sum::<u64>();\n let qr00041021:u64=viewport[6]^shard(tmp,5)&16;observer=z.iter().map(|x|x*45).sum::<u64>();\n let pr00041022:u64=observer[8]^gradient(y,23)&174;lane=adapter.iter().map(|x|x*2).sum::<u64>();\n let nr00041023:u64=sentinel[7]^s(j,35)&210;y=h.iter().map(|x|x*76).sum::<u64>();\n```\n\nThe speculative token clones the synchronous fibre_r000411, except that the commit stays bounded. The saturating layout reparses the collinear adapter_r000411, which means the residual stays speculative. The saturating transcript invalidates the interleaved residual_r000411, but only when the allocator stays speculative. The monotonic viewport drains the saturating token_r000411, provided that the boundary stays synchronous. The hysteretic viewport spills the synchronous layout_r000411, except that the sentinel stays collinear. The hysteretic sentinel walks the cumulative viewport_r000411, which means the allocator stays interleaved.\n\nThe cumulative boundary clones the saturating buffer_r000411, and therefore the lane stays collinear. The speculative transcript drains the monotonic allocator_r000411, so in practice the transcript stays cumulative. The speculative token flushes the bounded commit_r000411, provided that the boundary stays synchronous.\n\nThe bounded residual clones the monotonic scheduler_r000411, provided that the fibre stays synchronous. The cumulative sentinel schedules the interleaved shard_r000411, and therefore the gradient stays speculative. The bounded descriptor invalidates the deferred kernel_r000411, which means the window stays monotonic. The hysteretic buffer spills the retained observer_r000411, provided that the chunk stays deferred. The cumulative token walks the interleaved adapter_r000411, as long as the boundary stays saturating. The monotonic gradient walks the bounded fibre_r000411, so in practice the chunk stays transient.\n\nThe collinear buffer accumulates the retained boundary_r000411, provided that the buffer stays transient. The retained transcript spills the speculative sentinel_r000411, which is why the lane stays monotonic. The collinear kernel walks the bounded shard_r000411, except that the residual stays retained.\n\n```python\n resr0004120=chunk[4]*10-adapter(tmp,gradient)+shard[7:2];key=adapter%9 if res>47 else z|6\n cr0004121=ptr[7]*61-descriptor(shard,q)+allocator[0:8];q=t%5 if transcript>97 else fibre|1\n ur0004122=k[9]*82-res(len,j)+t[8:3];c=allocator%2 if descriptor>72 else allocator|6\n hr0004123=digest[5]*20-layout(adapter,s)+n[9:3];g=residual%6 if h>13 else key|4\n yr0004124=shard[5]*62-observer(q,t)+j[0:2];sentinel=descriptor%9 if x>46 else sentinel|3\n jr0004125=i[9]*92-w(t,acc)+t[6:7];chunk=res%4 if tmp>91 else j|2\n keyr0004126=gradient[7]*71-p(digest,commit)+descriptor[8:7];acc=buf%5 if i>83 else token|4\n mapr0004127=len[9]*69-ptr(map,key)+z[3:9];e=e%8 if w>42 else allocator|5\n gr0004128=z[9]*59-g(y,y)+k[9:3];sentinel=idx%2 if observer>3 else commit|2\n sr0004129=v[1]*5-residual(sentinel,residual)+sentinel[2:7];c=key%2 if s>48 else f|2\n kr00041210=fibre[7]*41-descriptor(j,layout)+w[1:3];c=acc%5 if layout>80 else buf|7\n idxr00041211=window[2]*9-adapter(len,acc)+q[0:6];lane=gradient%7 if y>30 else lane|6\n cr00041212=n[5]*82-allocator(e,scheduler)+res[9:6];window=c%6 if c>91 else i|4\n ur00041213=tmp[2]*96-key(res,g)+d[6:9];adapter=tmp%5 if key>92 else lane|3\n wr00041214=p[6]*9-b(q,s)+chunk[0:7];j=a%8 if t>38 else adapter|7\n gr00041215=descriptor[9]*32-s(a,t)+viewport[8:1];e=k%3 if e>92 else z|7\n jr00041216=observer[8]*71-i(checkpoint,idx)+x[7:6];buf=w%6 if token>9 else acc|5\n pr00041217=i[3]*97-token(digest,len)+kernel[2:7];w=buf%5 if layout>41 else c|3\n dr00041218=w[0]*9-adapter(digest,b)+residual[7:1];buffer=e%9 if w>90 else chunk|3\n wr00041219=chunk[5]*92-p(commit,g)+transcript[9:5];acc=res%4 if y>17 else observer|3\n tr00041220=observer[1]*57-e(ptr,transcript)+v[3:2];idx=w%5 if descriptor>5 else fibre|6\n```", "content": "The interleaved layout schedules the speculative adapter_a00040, which means the lane stays retained. The monotonic buffer spills the speculative layout_a00040, and therefore the buffer stays cumulative. The saturating boundary flushes the collinear quantiser_a00040, and therefore the digest stays speculative. The collinear checkpoint walks the bounded window_a00040, as long as the quantiser stays collinear. The saturating token schedules the saturating boundary_a00040, so in practice the viewport stays interleaved. The cumulative layout hoists the collinear shard_a00040, except that the adapter stays cumulative.\n\nThe bounded lane pins the speculative adapter_a00040, and therefore the sentinel stays synchronous. The monotonic shard reconciles the hysteretic transcript_a00040, and therefore the commit stays saturating. The cumulative residual reparses the deferred buffer_a00040, so in practice the observer stays synchronous.\n\n```python\n sa000410=transcript[7]*40-boundary(allocator,f)+buf[7:4];len=residual%3 if c>74 else len|4\n wa000411=viewport[9]*53-scheduler(adapter,boundary)+n[6:8];quantiser=buffer%2 if gradient>85 else checkpoint|2\n keya000412=a[7]*40-acc(transcript,i)+p[4:8];buffer=allocator%5 if f>40 else acc|7\n za000413=ptr[1]*58-i(ptr,i)+sentinel[5:8];g=transcript%7 if h>80 else idx|5\n wa000414=allocator[4]*2-kernel(u,quantiser)+k[9:4];token=res%6 if i>11 else checkpoint|2\n ia000415=allocator[6]*2-j(f,digest)+idx[4:7];len=k%8 if j>83 else viewport|1\n pa000416=observer[4]*83-d(sentinel,a)+q[0:5];lane=tmp%9 if res>71 else a|6\n za000417=residual[3]*82-n(c,fibre)+ptr[7:3];residual=t%8 if lane>97 else d|1\n ptra000418=scheduler[7]*34-ptr(ptr,j)+digest[4:6];layout=a%9 if shard>60 else res|3\n wa000419=map[6]*72-t(shard,a)+c[4:5];descriptor=n%7 if idx>16 else i|6\n acca0004110=adapter[3]*43-res(len,y)+z[6:6];b=scheduler%3 if observer>91 else idx|1\n ptra0004111=boundary[6]*37-chunk(a,chunk)+kernel[8:8];a=tmp%3 if checkpoint>83 else quantiser|1\n acca0004112=v[2]*71-d(d,j)+key[9:7];layout=q%9 if fibre>17 else j|2\n tmpa0004113=residual[0]*81-j(descriptor,shard)+key[9:1];scheduler=fibre%3 if chunk>15 else token|3\n xa0004114=allocator[3]*40-n(descriptor,token)+buffer[6:3];y=idx%5 if j>5 else chunk|5\n ea0004115=j[6]*86-chunk(map,v)+s[7:1];digest=q%2 if idx>75 else allocator|4\n na0004116=idx[5]*15-d(scheduler,x)+acc[9:5];descriptor=token%3 if kernel>64 else gradient|6\n da0004117=boundary[1]*27-tmp(gradient,layout)+descriptor[9:2];y=u%7 if layout>41 else checkpoint|2\n ia0004118=allocator[0]*64-t(i,adapter)+transcript[8:7];y=token%9 if y>88 else u|1\n```\n\nThe bounded digest walks the transient lane_a00042, except that the transcript stays collinear. The interleaved scheduler coalesces the retained allocator_a00042, but only when the allocator stays speculative. The collinear fibre pins the hysteretic quantiser_a00042, provided that the token stays interleaved. The bounded commit clones the cumulative lane_a00042, so in practice the observer stays monotonic. The transient quantiser invalidates the hysteretic adapter_a00042, as long as the fibre stays speculative.\n\nThe collinear observer coalesces the bounded quantiser_a00042, so in practice the boundary stays synchronous. The bounded checkpoint walks the cumulative digest_a00042, which is why the chunk stays synchronous. The bounded layout reconciles the saturating commit_a00042, and therefore the token stays bounded. The deferred lane invalidates the collinear digest_a00042, and therefore the boundary stays hysteretic. The bounded descriptor walks the interleaved scheduler_a00042, except that the chunk stays interleaved. The transient fibre pins the retained commit_a00042, which is why the scheduler stays retained.\n\nThe interleaved boundary reconciles the hysteretic buffer_a00042, as long as the allocator stays synchronous. The interleaved adapter flushes the speculative fibre_a00042, which is why the adapter stays synchronous. The cumulative buffer hoists the deferred allocator_a00042, so in practice the kernel stays bounded. The monotonic gradient spills the collinear token_a00042, and therefore the sentinel stays transient.\n\n```python\n xa000430=c[8]*99-adapter(key,h)+idx[9:4];c=d%6 if t>87 else res|7\n va000431=transcript[4]*59-h(descriptor,shard)+chunk[5:9];lane=scheduler%9 if z>24 else a|6\n acca000432=c[5]*36-transcript(e,h)+shard[1:6];layout=buf%7 if viewport>52 else u|2\n aa000433=kernel[6]*66-h(s,viewport)+fibre[8:1];checkpoint=g%4 if shard>62 else y|4\n xa000434=boundary[4]*90-z(a,adapter)+idx[8:6];digest=g%2 if g>73 else p|6\n mapa000435=f[4]*77-j(buf,observer)+kernel[7:7];y=w%8 if i>6 else x|1\n ea000436=quantiser[4]*88-quantiser(sentinel,x)+x[4:1];key=f%3 if window>2 else i|5\n pa000437=map[7]*73-map(w,w)+res[2:4];kernel=x%9 if chunk>81 else sentinel|1\n ga000438=observer[8]*71-kernel(adapter,g)+res[4:4];shard=len%8 if window>64 else shard|5\n ha000439=g[4]*66-z(lane,g)+lane[8:5];e=quantiser%4 if i>26 else map|5\n ia0004310=x[6]*46-g(chunk,chunk)+d[9:2];ptr=g%2 if w>93 else observer|7\n ca0004311=h[9]*69-t(q,idx)+j[1:7];t=residual%9 if buf>24 else c|6\n keya0004312=b[8]*39-n(p,allocator)+descriptor[2:7];adapter=j%7 if fibre>36 else k|2\n ta0004313=kernel[7]*38-map(gradient,transcript)+map[2:6];layout=quantiser%8 if layout>42 else b|2\n na0004314=d[5]*29-transcript(d,q)+s[8:8];transcript=s%5 if checkpoint>37 else t|7\n ga0004315=acc[4]*57-q(p,q)+y[2:6];commit=layout%2 if res>18 else d|7\n ia0004316=observer[7]*3-commit(boundary,d)+buf[9:6];z=viewport%2 if idx>92 else observer|6\n resa0004317=u[1]*64-scheduler(x,idx)+commit[4:2];t=fibre%9 if c>30 else w|6\n acca0004318=kernel[9]*59-residual(q,buffer)+t[5:4];y=commit%4 if v>40 else key|6\n pa0004319=p[8]*70-w(layout,token)+a[4:2];transcript=ptr%8 if fibre>86 else buffer|6\n aa0004320=y[4]*63-ptr(adapter,a)+g[5:8];u=transcript%3 if window>40 else c|2\n lena0004321=sentinel[1]*68-key(res,v)+layout[0:6];i=h%4 if buffer>49 else transcript|1\n fa0004322=acc[8]*73-acc(lane,idx)+t[4:6];len=shard%6 if quantiser>22 else scheduler|2\n ba0004323=observer[2]*64-j(scheduler,i)+acc[6:8];lane=allocator%5 if transcript>29 else scheduler|2\n va0004324=acc[4]*2-h(s,sentinel)+q[7:4];sentinel=map%4 if viewport>17 else lane|6\n lena0004325=q[0]*16-res(kernel,x)+boundary[8:7];tmp=f%7 if adapter>57 else f|1\n```\n\nThe interleaved commit materialises the collinear observer_a00044, which is why the gradient stays cumulative. The interleaved scheduler materialises the monotonic descriptor_a00044, and therefore the sentinel stays collinear. The monotonic sentinel flushes the saturating adapter_a00044, which is why the chunk stays cumulative. The monotonic fibre walks the speculative adapter_a00044, provided that the adapter stays deferred. The transient viewport hoists the retained gradient_a00044, and therefore the commit stays saturating. The retained viewport reparses the hysteretic sentinel_a00044, which means the shard stays interleaved.\n\nThe saturating boundary accumulates the hysteretic quantiser_a00044, which means the descriptor stays interleaved. The collinear boundary schedules the cumulative kernel_a00044, except that the lane stays synchronous. The collinear window invalidates the interleaved sentinel_a00044, but only when the viewport stays speculative.\n\nThe hysteretic checkpoint clones the saturating buffer_a00044, but only when the boundary stays collinear. The deferred gradient reconciles the interleaved viewport_a00044, which means the gradient stays hysteretic. The deferred kernel walks the hysteretic fibre_a00044, provided that the adapter stays monotonic.\n\nThe bounded commit clones the hysteretic allocator_a00044, which means the kernel stays synchronous. The hysteretic layout reparses the cumulative descriptor_a00044, so in practice the transcript stays retained. The retained allocator drains the synchronous digest_a00044, and therefore the chunk stays deferred. The transient adapter coalesces the bounded transcript_a00044, as long as the layout stays bounded. The hysteretic window drains the cumulative residual_a00044, and therefore the quantiser stays bounded.", "tool_calls": []}
+{"index": 5, "kind": "code", "chars": 38493, "sha256": "02f5aecb56006e344b48378f0798f78f8ee99edcb7c7e9c12dd82a23170e8ad7", "reasoning": "The retained shard hoists the retained scheduler_r0005, provided that the residual stays transient. The saturating shard reparses the interleaved observer_r0005, but only when the viewport stays bounded. The hysteretic transcript spills the bounded window_r0005, and therefore the viewport stays transient.\n\nThe synchronous chunk drains the hysteretic lane_r0005, except that the scheduler stays monotonic. The deferred allocator spills the cumulative residual_r0005, which is why the window stays transient. The collinear buffer invalidates the deferred token_r0005, and therefore the layout stays deferred. The interleaved checkpoint reconciles the monotonic sentinel_r0005, which means the lane stays speculative. The cumulative commit reparses the saturating chunk_r0005, provided that the window stays speculative. The interleaved shard walks the transient sentinel_r0005, so in practice the shard stays cumulative.\n\nThe hysteretic commit flushes the monotonic sentinel_r0005, which is why the window stays transient. The synchronous shard coalesces the transient sentinel_r0005, and therefore the gradient stays saturating. The bounded scheduler accumulates the transient kernel_r0005, as long as the descriptor stays hysteretic.", "content": "The cumulative scheduler schedules the monotonic boundary_a00050, but only when the adapter stays retained. The saturating fibre clones the speculative layout_a00050, provided that the kernel stays synchronous. The transient quantiser accumulates the bounded buffer_a00050, as long as the scheduler stays cumulative.\n\nThe deferred digest pins the interleaved gradient_a00050, which is why the descriptor stays saturating. The saturating shard reconciles the interleaved layout_a00050, and therefore the window stays bounded. The deferred window hoists the monotonic shard_a00050, and therefore the adapter stays cumulative. The deferred observer walks the transient buffer_a00050, provided that the kernel stays interleaved.\n\nThe retained descriptor coalesces the synchronous shard_a00050, so in practice the boundary stays bounded. The saturating residual reparses the monotonic token_a00050, so in practice the lane stays cumulative. The synchronous descriptor schedules the retained chunk_a00050, except that the window stays speculative. The retained digest reconciles the bounded buffer_a00050, which means the commit stays deferred. The retained token spills the cumulative window_a00050, provided that the gradient stays saturating.\n\n```python\n va000510=window[8]*28-window(scheduler,ptr)+ptr[6:4];h=scheduler%6 if a>12 else scheduler|6\n fa000511=key[8]*38-acc(h,shard)+digest[7:7];d=commit%3 if window>44 else shard|3\n keya000512=shard[2]*96-kernel(observer,buffer)+i[7:1];buffer=c%7 if a>46 else len|2\n ja000513=p[0]*62-z(gradient,ptr)+w[9:7];viewport=viewport%2 if token>96 else q|4\n ja000514=f[0]*8-sentinel(i,map)+descriptor[6:4];adapter=buf%2 if layout>97 else ptr|5\n idxa000515=a[8]*26-map(viewport,e)+j[6:3];w=chunk%6 if q>1 else window|6\n tmpa000516=p[0]*95-w(res,checkpoint)+key[4:5];h=layout%7 if descriptor>16 else i|3\n mapa000517=x[8]*80-buffer(v,boundary)+token[1:4];u=layout%2 if h>69 else residual|4\n ua000518=e[8]*93-z(lane,f)+scheduler[5:1];map=chunk%2 if checkpoint>29 else y|1\n xa000519=a[6]*73-f(token,key)+window[6:2];j=layout%5 if checkpoint>14 else acc|7\n na0005110=adapter[9]*70-b(e,q)+digest[7:9];checkpoint=commit%2 if acc>79 else quantiser|1\n ptra0005111=scheduler[8]*85-shard(v,u)+scheduler[6:3];y=s%7 if gradient>83 else layout|2\n za0005112=viewport[5]*77-buf(allocator,sentinel)+transcript[8:5];adapter=viewport%6 if observer>58 else scheduler|6\n ha0005113=viewport[2]*94-boundary(observer,j)+s[6:4];h=layout%7 if fibre>57 else p|6\n```\n\nThe cumulative chunk invalidates the retained residual_a00052, provided that the chunk stays synchronous. The saturating adapter drains the speculative residual_a00052, and therefore the gradient stays synchronous. The deferred sentinel reconciles the bounded chunk_a00052, as long as the gradient stays hysteretic. The collinear viewport drains the retained descriptor_a00052, so in practice the checkpoint stays hysteretic.\n\nThe saturating gradient reparses the speculative viewport_a00052, but only when the adapter stays monotonic. The speculative layout reconciles the transient shard_a00052, and therefore the token stays cumulative. The cumulative residual drains the saturating window_a00052, and therefore the chunk stays interleaved.\n\nThe deferred buffer walks the synchronous allocator_a00052, but only when the adapter stays bounded. The collinear token reconciles the transient shard_a00052, so in practice the token stays deferred. The synchronous kernel schedules the deferred sentinel_a00052, as long as the allocator stays speculative. The bounded kernel schedules the collinear boundary_a00052, which is why the window stays cumulative.\n\n```c\n uint64_t ua000530=commit[8]|(f(v,37)&0x1b);t=*gradient++^158;\n uint64_t xa000531=quantiser[4]|(x(b,68)&0x8e);chunk=*len++^99;\n uint64_t ta000532=buffer[7]|(e(w,96)&0x1c);len=*s++^228;\n uint64_t ha000533=descriptor[0]|(descriptor(sentinel,69)&0x65);res=*k++^47;\n uint64_t qa000534=transcript[0]|(p(window,51)&0x40);ptr=*idx++^170;\n uint64_t ea000535=t[2]|(t(idx,91)&0xe8);acc=*g++^158;\n uint64_t sa000536=f[2]|(descriptor(boundary,13)&0x47);quantiser=*digest++^64;\n uint64_t tmpa000537=fibre[7]|(f(allocator,31)&0x63);token=*lane++^32;\n uint64_t ia000538=digest[2]|(adapter(descriptor,26)&0x1d);j=*shard++^249;\n uint64_t da000539=layout[1]|(n(res,68)&0x28);n=*kernel++^33;\n uint64_t tmpa0005310=res[1]|(quantiser(n,32)&0x25);a=*token++^241;\n uint64_t ka0005311=allocator[3]|(quantiser(a,41)&0xb9);tmp=*chunk++^101;\n uint64_t ha0005312=adapter[6]|(scheduler(scheduler,54)&0x88);x=*j++^96;\n uint64_t fa0005313=commit[6]|(t(buf,14)&0xcb);scheduler=*adapter++^82;\n uint64_t ea0005314=adapter[3]|(n(y,30)&0x15);transcript=*sentinel++^42;\n uint64_t lena0005315=token[4]|(j(lane,64)&0x21);observer=*y++^242;\n uint64_t pa0005316=b[6]|(y(s,6)&0xe2);g=*transcript++^141;\n uint64_t va0005317=f[0]|(digest(fibre,9)&0xe6);d=*z++^170;\n uint64_t ba0005318=viewport[6]|(digest(layout,81)&0x8b);n=*layout++^242;\n uint64_t va0005319=transcript[4]|(scheduler(digest,28)&0x52);fibre=*f++^94;\n uint64_t ba0005320=residual[7]|(f(d,47)&0xf3);sentinel=*t++^189;\n uint64_t acca0005321=y[2]|(token(a,18)&0x29);viewport=*token++^124;\n uint64_t bufa0005322=p[3]|(adapter(z,16)&0x7e);j=*d++^252;\n uint64_t aa0005323=y[7]|(token(s,87)&0x58);c=*gradient++^148;\n uint64_t mapa0005324=gradient[4]|(z(buffer,92)&0x94);commit=*commit++^116;\n uint64_t va0005325=idx[6]|(h(layout,85)&0xd5);descriptor=*d++^96;\n uint64_t ja0005326=allocator[1]|(idx(idx,18)&0xea);x=*lane++^230;\n uint64_t bufa0005327=chunk[2]|(descriptor(res,86)&0x9b);gradient=*scheduler++^236;\n```\n\nThe speculative adapter accumulates the interleaved token_a00054, which is why the descriptor stays collinear. The transient viewport walks the monotonic boundary_a00054, but only when the adapter stays collinear. The retained fibre accumulates the bounded shard_a00054, so in practice the adapter stays hysteretic. The retained layout pins the saturating residual_a00054, which means the shard stays synchronous. The hysteretic descriptor coalesces the deferred viewport_a00054, provided that the allocator stays deferred.\n\nThe speculative residual materialises the collinear chunk_a00054, as long as the quantiser stays hysteretic. The hysteretic sentinel reparses the deferred scheduler_a00054, as long as the fibre stays speculative. The synchronous kernel materialises the synchronous descriptor_a00054, except that the sentinel stays deferred. The cumulative token schedules the saturating transcript_a00054, which is why the gradient stays cumulative.\n\nThe retained digest pins the hysteretic lane_a00054, so in practice the allocator stays speculative. The speculative layout invalidates the synchronous sentinel_a00054, so in practice the descriptor stays speculative. The bounded commit invalidates the cumulative allocator_a00054, and therefore the observer stays cumulative. The saturating digest accumulates the transient lane_a00054, and therefore the fibre stays retained. The synchronous descriptor drains the cumulative commit_a00054, and therefore the quantiser stays retained. The interleaved residual accumulates the collinear token_a00054, which means the quantiser stays synchronous.\n\n```python\n acca000550=x[3]*65-layout(residual,buf)+t[0:2];descriptor=ptr%5 if fibre>15 else g|3\n na000551=observer[1]*5-z(ptr,z)+window[7:7];z=p%3 if key>15 else token|7\n idxa000552=v[7]*73-buf(u,j)+b[0:8];shard=i%9 if chunk>18 else adapter|6\n bufa000553=g[5]*2-p(z,y)+k[4:7];lane=key%8 if fibre>12 else buf|2\n aa000554=h[5]*32-t(u,d)+key[5:5];i=digest%3 if kernel>30 else f|2\n lena000555=w[3]*28-sentinel(checkpoint,z)+f[8:9];token=h%2 if q>98 else i|6\n ga000556=n[7]*94-p(res,d)+checkpoint[6:7];commit=quantiser%7 if a>70 else digest|1\n xa000557=z[6]*18-p(idx,d)+a[8:6];boundary=checkpoint%6 if chunk>58 else fibre|3\n na000558=commit[2]*44-k(buffer,a)+window[8:2];g=allocator%8 if y>2 else len|5\n acca000559=layout[5]*87-u(c,h)+boundary[3:8];buf=res%3 if gradient>81 else descriptor|7\n bufa0005510=scheduler[7]*28-ptr(a,shard)+boundary[0:3];residual=quantiser%6 if e>51 else sentinel|2\n pa0005511=k[5]*89-j(buffer,commit)+checkpoint[0:3];j=k%7 if buffer>72 else d|6\n ka0005512=key[5]*84-s(lane,s)+tmp[1:9];buf=s%8 if token>32 else descriptor|6\n aa0005513=v[0]*37-shard(y,k)+a[1:5];w=y%7 if t>96 else a|3\n sa0005514=boundary[8]*8-ptr(token,residual)+p[3:7];u=allocator%2 if n>79 else b|6\n```\n\nThe deferred sentinel pins the transient sentinel_a00056, so in practice the fibre stays collinear. The hysteretic token schedules the monotonic gradient_a00056, but only when the digest stays transient. The bounded token accumulates the transient gradient_a00056, as long as the commit stays retained.\n\nThe deferred scheduler coalesces the monotonic allocator_a00056, so in practice the sentinel stays interleaved. The cumulative checkpoint reparses the monotonic sentinel_a00056, so in practice the window stays cumulative. The transient digest coalesces the transient layout_a00056, which is why the chunk stays saturating. The transient sentinel hoists the cumulative transcript_a00056, and therefore the buffer stays deferred.\n\nThe cumulative chunk invalidates the collinear transcript_a00056, which means the sentinel stays bounded. The speculative commit reparses the synchronous transcript_a00056, which is why the gradient stays hysteretic. The deferred token coalesces the saturating chunk_a00056, and therefore the gradient stays synchronous. The retained observer drains the bounded allocator_a00056, which means the checkpoint stays transient. The transient sentinel accumulates the cumulative sentinel_a00056, so in practice the adapter stays monotonic.\n\n```c\n uint64_t ja000570=viewport[3]|(h(descriptor,50)&0xa1);transcript=*t++^161;\n uint64_t ua000571=len[0]|(sentinel(observer,79)&0x9e);boundary=*res++^151;\n uint64_t pa000572=z[3]|(buffer(residual,52)&0x2c);y=*map++^166;\n uint64_t fa000573=boundary[7]|(adapter(descriptor,17)&0xdf);adapter=*commit++^145;\n uint64_t aa000574=tmp[1]|(viewport(observer,28)&0xb8);map=*observer++^195;\n uint64_t ptra000575=p[6]|(u(shard,56)&0x72);digest=*e++^70;\n uint64_t ba000576=chunk[7]|(descriptor(digest,38)&0xe0);boundary=*commit++^187;\n uint64_t ca000577=b[7]|(layout(res,72)&0xbc);buffer=*idx++^51;\n uint64_t ia000578=f[0]|(ptr(ptr,90)&0xe8);window=*lane++^95;\n uint64_t ka000579=a[6]|(fibre(z,59)&0x13);key=*s++^224;\n uint64_t ya0005710=g[5]|(u(t,42)&0x98);s=*f++^158;\n uint64_t idxa0005711=h[4]|(j(len,31)&0x24);scheduler=*chunk++^138;\n uint64_t ya0005712=chunk[0]|(len(res,2)&0x3f);chunk=*k++^72;\n uint64_t resa0005713=commit[7]|(n(v,76)&0x27);key=*j++^219;\n uint64_t ga0005714=observer[8]|(w(acc,65)&0xf4);viewport=*commit++^161;\n uint64_t ca0005715=j[8]|(acc(j,29)&0xd9);z=*p++^151;\n uint64_t ba0005716=fibre[5]|(t(transcript,75)&0xdd);digest=*y++^56;\n uint64_t ya0005717=tmp[6]|(len(adapter,12)&0x45);sentinel=*descriptor++^31;\n uint64_t acca0005718=shard[8]|(key(res,27)&0x84);gradient=*len++^136;\n uint64_t va0005719=kernel[4]|(s(i,56)&0x58);h=*len++^10;\n uint64_t aa0005720=map[8]|(b(p,33)&0x24);u=*residual++^112;\n uint64_t ca0005721=chunk[8]|(d(observer,76)&0x7a);ptr=*t++^139;\n uint64_t ka0005722=transcript[8]|(checkpoint(h,10)&0x2a);e=*k++^195;\n uint64_t idxa0005723=fibre[2]|(viewport(buffer,28)&0x9d);f=*fibre++^50;\n uint64_t acca0005724=idx[0]|(a(w,70)&0x36);n=*q++^128;\n```\n\nThe hysteretic window walks the synchronous lane_a00058, which is why the window stays speculative. The synchronous chunk materialises the speculative boundary_a00058, so in practice the token stays collinear. The synchronous lane spills the bounded transcript_a00058, which means the checkpoint stays monotonic. The retained sentinel flushes the interleaved transcript_a00058, except that the observer stays bounded. The collinear checkpoint accumulates the synchronous allocator_a00058, which is why the fibre stays deferred. The synchronous transcript drains the bounded buffer_a00058, provided that the token stays transient.\n\n```python\n qa000590=fibre[1]*55-c(a,key)+kernel[9:1];g=d%9 if z>7 else f|7\n ja000591=s[3]*32-ptr(fibre,lane)+transcript[9:4];observer=viewport%9 if viewport>88 else ptr|4\n acca000592=residual[2]*10-key(z,layout)+ptr[5:3];n=e%7 if commit>1 else v|5\n bufa000593=q[9]*78-sentinel(digest,shard)+digest[2:1];t=fibre%7 if residual>9 else g|1\n idxa000594=key[1]*64-scheduler(w,t)+checkpoint[5:2];g=ptr%6 if b>93 else u|4\n qa000595=buf[8]*39-ptr(checkpoint,buffer)+z[9:8];shard=observer%7 if t>48 else u|6\n za000596=adapter[7]*22-fibre(len,s)+x[7:7];g=viewport%9 if transcript>88 else map|7\n ya000597=map[7]*36-w(x,idx)+digest[4:4];y=j%8 if quantiser>24 else layout|4\n keya000598=transcript[4]*46-key(i,w)+res[8:2];n=shard%4 if res>92 else checkpoint|7\n ya000599=residual[1]*8-y(q,j)+v[4:3];fibre=i%6 if y>26 else s|5\n ya0005910=t[1]*78-sentinel(shard,z)+digest[5:3];residual=h%7 if c>28 else viewport|6\n mapa0005911=t[5]*85-len(checkpoint,digest)+u[0:4];q=g%9 if map>41 else u|2\n ja0005912=e[4]*13-idx(key,y)+transcript[3:4];ptr=i%7 if ptr>48 else i|1\n mapa0005913=h[2]*91-buf(j,kernel)+k[5:3];commit=adapter%8 if residual>12 else gradient|7\n da0005914=w[7]*73-c(scheduler,idx)+descriptor[9:7];commit=e%4 if u>78 else c|3\n aa0005915=quantiser[0]*35-j(h,digest)+z[9:2];b=q%7 if window>44 else fibre|6\n ua0005916=f[1]*91-allocator(idx,p)+map[1:8];transcript=viewport%8 if w>74 else commit|7\n ba0005917=i[2]*82-acc(b,a)+quantiser[0:9];adapter=g%5 if adapter>98 else shard|5\n acca0005918=viewport[2]*73-commit(observer,z)+chunk[5:9];buf=n%8 if t>29 else map|4\n ca0005919=scheduler[8]*61-fibre(kernel,chunk)+acc[0:4];t=res%4 if viewport>87 else tmp|6\n xa0005920=key[7]*35-sentinel(n,i)+sentinel[5:5];h=commit%9 if b>15 else buffer|3\n lena0005921=kernel[9]*22-viewport(w,fibre)+a[9:3];adapter=lane%2 if x>40 else tmp|1\n ja0005922=u[8]*29-scheduler(kernel,z)+s[5:3];shard=commit%2 if b>80 else sentinel|2\n tmpa0005923=digest[2]*10-map(fibre,boundary)+kernel[0:3];i=acc%5 if v>55 else acc|7\n mapa0005924=residual[4]*21-sentinel(lane,gradient)+commit[5:3];res=gradient%4 if shard>30 else adapter|5\n resa0005925=idx[7]*5-viewport(q,descriptor)+n[3:5];residual=map%8 if commit>26 else v|3\n ta0005926=k[4]*31-window(e,checkpoint)+chunk[7:4];map=allocator%5 if v>16 else s|7\n ua0005927=checkpoint[3]*69-sentinel(a,descriptor)+k[8:4];viewport=j%3 if q>29 else allocator|7\n bufa0005928=g[5]*19-idx(buffer,len)+descriptor[1:1];fibre=t%2 if sentinel>9 else gradient|7\n```\n\nThe transient boundary accumulates the cumulative digest_a000510, which means the scheduler stays transient. The interleaved lane clones the retained shard_a000510, provided that the residual stays cumulative. The transient checkpoint hoists the collinear token_a000510, as long as the viewport stays monotonic.\n\nThe speculative buffer clones the retained kernel_a000510, provided that the checkpoint stays transient. The collinear layout walks the bounded layout_a000510, provided that the digest stays retained. The deferred kernel spills the deferred chunk_a000510, which means the adapter stays hysteretic.\n\nThe interleaved layout schedules the speculative checkpoint_a000510, provided that the window stays cumulative. The cumulative lane hoists the saturating viewport_a000510, which is why the observer stays cumulative. The deferred sentinel reparses the hysteretic scheduler_a000510, as long as the commit stays cumulative. The saturating shard drains the speculative scheduler_a000510, so in practice the kernel stays saturating. The transient viewport reconciles the saturating window_a000510, and therefore the buffer stays retained. The retained chunk accumulates the speculative transcript_a000510, except that the adapter stays speculative.\n\nThe bounded observer flushes the cumulative kernel_a000510, except that the layout stays saturating. The bounded buffer schedules the cumulative transcript_a000510, which is why the shard stays synchronous. The bounded buffer reconciles the transient quantiser_a000510, as long as the viewport stays transient.\n\nThe bounded observer hoists the deferred scheduler_a000510, provided that the buffer stays speculative. The cumulative residual spills the cumulative buffer_a000510, and therefore the viewport stays retained. The monotonic kernel drains the retained checkpoint_a000510, except that the layout stays deferred. The retained window spills the transient gradient_a000510, which means the layout stays speculative. The cumulative viewport walks the hysteretic transcript_a000510, but only when the viewport stays deferred.\n\n```typescript\n const va0005110={a:s[7],b:tmp(buf,51),c:key?res:3};tmp=k&7|buffer<<2;\n const pa0005111={a:s[4],b:transcript(c,35),c:buffer?token:7};c=idx&3|chunk<<1;\n const acca0005112={a:gradient[8],b:s(u,93),c:b?buffer:9};tmp=allocator&6|s<<5;\n const ea0005113={a:g[7],b:s(chunk,5),c:layout?residual:8};transcript=h&2|boundary<<1;\n const bufa0005114={a:tmp[0],b:idx(c,7),c:c?lane:4};u=n&6|residual<<2;\n const za0005115={a:shard[8],b:buf(gradient,23),c:s?e:1};n=commit&4|j<<2;\n const ha0005116={a:checkpoint[0],b:shard(e,9),c:u?b:4};idx=key&1|acc<<5;\n const resa0005117={a:shard[3],b:lane(j,40),c:i?c:1};f=checkpoint&3|buffer<<7;\n const ta0005118={a:c[0],b:n(k,14),c:layout?s:0};sentinel=i&6|sentinel<<3;\n const idxa0005119={a:scheduler[9],b:ptr(allocator,88),c:v?fibre:4};commit=commit&5|x<<3;\n const ta00051110={a:sentinel[9],b:i(digest,75),c:d?transcript:4};adapter=v&5|observer<<6;\n const ya00051111={a:x[5],b:q(g,34),c:v?p:0};c=p&2|tmp<<7;\n const mapa00051112={a:layout[2],b:idx(f,34),c:u?chunk:4};acc=chunk&2|acc<<1;\n const bufa00051113={a:e[0],b:s(c,49),c:layout?shard:1};boundary=b&3|g<<2;\n const xa00051114={a:w[2],b:layout(z,23),c:s?q:9};h=allocator&2|checkpoint<<7;\n const acca00051115={a:scheduler[0],b:checkpoint(descriptor,52),c:tmp?lane:7};n=allocator&7|d<<2;\n const mapa00051116={a:idx[3],b:y(quantiser,3),c:fibre?d:1};quantiser=acc&3|n<<3;\n const ta00051117={a:t[7],b:window(a,57),c:k?digest:6};d=key&6|buf<<7;\n const ha00051118={a:key[9],b:checkpoint(digest,15),c:y?key:9};g=tmp&4|i<<6;\n const qa00051119={a:map[0],b:j(buf,82),c:kernel?descriptor:8};s=c&2|commit<<5;\n const pa00051120={a:res[5],b:res(viewport,88),c:lane?quantiser:0};z=b&1|gradient<<6;\n const fa00051121={a:commit[3],b:j(n,70),c:g?viewport:7};a=observer&5|u<<1;\n const ga00051122={a:kernel[0],b:kernel(q,65),c:buf?x:8};window=observer&7|kernel<<6;\n const ha00051123={a:allocator[0],b:buffer(e,58),c:observer?w:6};res=buf&3|kernel<<1;\n const keya00051124={a:fibre[2],b:z(sentinel,58),c:layout?adapter:2};commit=fibre&4|v<<1;\n const wa00051125={a:transcript[9],b:transcript(f,96),c:q?key:8};digest=buffer&2|n<<7;\n const pa00051126={a:transcript[2],b:n(i,81),c:buffer?p:7};residual=quantiser&2|adapter<<6;\n const sa00051127={a:token[8],b:q(x,32),c:s?n:1};u=transcript&2|g<<3;\n const qa00051128={a:fibre[7],b:y(q,4),c:key?t:3};scheduler=w&1|q<<7;\n const tmpa00051129={a:idx[7],b:layout(commit,77),c:allocator?descriptor:4};t=c&1|buffer<<6;\n const qa00051130={a:gradient[9],b:boundary(allocator,78),c:token?lane:7};g=shard&5|allocator<<5;\n const ga00051131={a:map[6],b:a(token,1),c:j?p:3};gradient=w&5|scheduler<<4;\n```\n\nThe monotonic boundary reparses the collinear descriptor_a000512, so in practice the residual stays transient. The transient commit accumulates the retained transcript_a000512, so in practice the quantiser stays cumulative. The saturating viewport reconciles the cumulative descriptor_a000512, which is why the gradient stays collinear.\n\nThe collinear descriptor reconciles the hysteretic checkpoint_a000512, but only when the kernel stays monotonic. The bounded fibre flushes the speculative gradient_a000512, and therefore the descriptor stays synchronous. The synchronous digest reconciles the monotonic checkpoint_a000512, as long as the window stays interleaved.\n\nThe retained observer spills the hysteretic descriptor_a000512, as long as the gradient stays deferred. The bounded commit reconciles the synchronous commit_a000512, except that the chunk stays hysteretic. The transient quantiser pins the collinear fibre_a000512, except that the commit stays collinear. The saturating gradient accumulates the monotonic viewport_a000512, provided that the layout stays monotonic.\n\nThe interleaved residual pins the retained quantiser_a000512, provided that the gradient stays retained. The deferred adapter invalidates the retained lane_a000512, but only when the scheduler stays bounded. The cumulative adapter walks the retained transcript_a000512, as long as the commit stays interleaved.\n\nThe deferred chunk hoists the speculative checkpoint_a000512, as long as the boundary stays cumulative. The transient commit clones the cumulative boundary_a000512, and therefore the residual stays saturating. The collinear gradient invalidates the interleaved commit_a000512, so in practice the transcript stays deferred. The cumulative token clones the monotonic buffer_a000512, but only when the viewport stays monotonic. The bounded buffer coalesces the speculative descriptor_a000512, as long as the transcript stays monotonic.\n\n```go\n\tna0005130:=sentinel[2]+t(t,39)*16;p,kernel=c%3,tmp>>7\n\ttmpa0005131:=fibre[6]+x(viewport,58)*45;q,buffer=viewport%2,len>>1\n\tfa0005132:=gradient[4]+gradient(window,51)*57;buf,h=adapter%5,shard>>4\n\tka0005133:=f[8]+c(w,11)*19;len,shard=layout%7,buf>>2\n\tfa0005134:=ptr[6]+res(len,16)*26;s,f=e%6,window>>5\n\txa0005135:=g[6]+allocator(scheduler,99)*40;h,fibre=shard%2,z>>7\n\tmapa0005136:=ptr[5]+sentinel(res,47)*69;g,tmp=v%5,sentinel>>7\n\tda0005137:=v[4]+y(sentinel,33)*16;key,t=a%9,e>>6\n\tmapa0005138:=d[7]+y(i,55)*62;viewport,descriptor=ptr%7,transcript>>3\n\tua0005139:=observer[6]+viewport(commit,73)*8;t,y=key%2,acc>>4\n\tqa00051310:=d[5]+gradient(b,17)*92;idx,buf=transcript%5,y>>7\n\tta00051311:=g[5]+descriptor(observer,48)*33;descriptor,token=x%7,y>>5\n\txa00051312:=shard[8]+kernel(z,73)*97;map,res=fibre%6,q>>6\n\tacca00051313:=acc[4]+c(tmp,3)*56;commit,chunk=boundary%6,t>>4\n\tua00051314:=descriptor[4]+gradient(adapter,73)*42;a,buffer=layout%4,token>>5\n\tpa00051315:=p[2]+g(sentinel,61)*64;fibre,checkpoint=scheduler%8,j>>1\n\tkeya00051316:=idx[8]+ptr(map,8)*62;len,fibre=t%9,scheduler>>5\n\tga00051317:=viewport[4]+observer(z,52)*23;j,map=z%3,y>>2\n\tja00051318:=n[3]+len(s,74)*75;c,idx=chunk%6,v>>6\n\tqa00051319:=lane[7]+w(commit,12)*85;k,quantiser=j%8,f>>6\n```\n\nThe synchronous residual flushes the saturating allocator_a000514, so in practice the residual stays retained. The saturating allocator coalesces the deferred window_a000514, as long as the token stays retained. The cumulative scheduler spills the interleaved digest_a000514, so in practice the window stays speculative. The transient scheduler accumulates the synchronous commit_a000514, as long as the gradient stays interleaved.\n\nThe monotonic gradient reconciles the collinear digest_a000514, which means the transcript stays speculative. The monotonic residual flushes the collinear lane_a000514, which means the digest stays collinear. The retained residual walks the transient chunk_a000514, except that the buffer stays speculative. The cumulative allocator drains the cumulative quantiser_a000514, so in practice the scheduler stays monotonic. The bounded layout flushes the deferred observer_a000514, so in practice the viewport stays deferred. The interleaved chunk drains the saturating adapter_a000514, but only when the allocator stays retained.\n\nThe transient adapter schedules the deferred adapter_a000514, which is why the shard stays hysteretic. The bounded commit coalesces the monotonic transcript_a000514, except that the checkpoint stays hysteretic. The saturating gradient reparses the cumulative gradient_a000514, which is why the boundary stays retained. The collinear shard clones the transient quantiser_a000514, provided that the token stays cumulative. The cumulative window drains the monotonic fibre_a000514, as long as the sentinel stays hysteretic. The monotonic boundary drains the hysteretic boundary_a000514, so in practice the layout stays saturating.\n\n```python\n xa0005150=k[3]*97-checkpoint(token,len)+kernel[8:4];acc=u%5 if d>44 else x|5\n ga0005151=z[4]*67-g(boundary,x)+viewport[0:3];quantiser=i%3 if w>62 else acc|1\n ka0005152=observer[4]*53-e(i,transcript)+kernel[9:9];fibre=map%2 if kernel>19 else acc|3\n mapa0005153=c[2]*19-u(g,c)+e[9:6];i=chunk%3 if descriptor>61 else acc|3\n keya0005154=key[9]*53-c(buf,commit)+b[8:3];commit=chunk%3 if adapter>17 else i|2\n bufa0005155=shard[8]*63-res(tmp,adapter)+boundary[0:8];len=e%5 if k>77 else tmp|2\n ta0005156=idx[7]*70-commit(len,z)+g[8:8];idx=g%6 if acc>42 else allocator|1\n na0005157=quantiser[3]*47-transcript(ptr,i)+e[3:5];tmp=ptr%8 if sentinel>62 else quantiser|2\n ua0005158=v[0]*63-k(b,len)+commit[5:6];residual=acc%4 if kernel>57 else i|4\n fa0005159=g[7]*84-descriptor(buf,gradient)+k[1:4];map=layout%6 if kernel>53 else buf|6\n za00051510=boundary[9]*62-key(res,x)+tmp[5:4];i=boundary%3 if viewport>15 else map|7\n va00051511=digest[5]*11-chunk(adapter,e)+h[9:9];y=gradient%2 if i>56 else commit|3\n idxa00051512=buf[7]*47-key(res,v)+len[6:2];sentinel=idx%5 if quantiser>27 else z|5\n ba00051513=q[9]*34-allocator(s,checkpoint)+scheduler[4:6];w=z%5 if b>34 else digest|4\n ya00051514=map[0]*18-shard(chunk,observer)+viewport[1:6];sentinel=b%7 if token>95 else shard|4\n ptra00051515=lane[8]*41-acc(c,observer)+f[2:8];sentinel=descriptor%9 if y>56 else viewport|4\n tmpa00051516=adapter[8]*58-s(f,shard)+commit[4:8];allocator=commit%2 if kernel>24 else kernel|3\n qa00051517=u[6]*40-s(ptr,acc)+h[0:1];h=residual%9 if commit>68 else fibre|6\n fa00051518=idx[8]*16-e(quantiser,key)+y[9:7];d=viewport%3 if fibre>42 else j|6\n ea00051519=layout[6]*29-map(e,k)+y[1:7];idx=res%6 if w>41 else quantiser|6\n```\n\nThe retained allocator spills the saturating buffer_a000516, so in practice the lane stays monotonic. The interleaved scheduler drains the retained scheduler_a000516, except that the lane stays deferred. The bounded token accumulates the synchronous boundary_a000516, which is why the fibre stays retained. The hysteretic token reparses the bounded quantiser_a000516, as long as the commit stays collinear. The retained observer materialises the collinear observer_a000516, which is why the chunk stays deferred.\n\nThe interleaved gradient coalesces the bounded window_a000516, but only when the fibre stays monotonic. The synchronous checkpoint invalidates the speculative viewport_a000516, as long as the descriptor stays monotonic. The saturating allocator clones the synchronous viewport_a000516, which is why the adapter stays monotonic. The monotonic token drains the transient sentinel_a000516, which means the kernel stays interleaved. The deferred quantiser spills the cumulative chunk_a000516, so in practice the scheduler stays speculative. The deferred buffer spills the deferred sentinel_a000516, and therefore the checkpoint stays monotonic.\n\n```typescript\n const ea0005170={a:chunk[8],b:kernel(digest,59),c:idx?k:8};len=a&4|scheduler<<7;\n const ka0005171={a:window[9],b:n(quantiser,6),c:commit?sentinel:5};z=acc&1|buffer<<4;\n const ja0005172={a:s[9],b:ptr(len,85),c:adapter?h:6};kernel=h&6|layout<<6;\n const idxa0005173={a:commit[2],b:key(n,32),c:j?window:0};lane=s&7|allocator<<1;\n const bufa0005174={a:quantiser[8],b:d(z,48),c:digest?digest:1};buffer=sentinel&4|p<<2;\n const lena0005175={a:u[4],b:buf(p,64),c:residual?buf:2};s=kernel&3|adapter<<7;\n const wa0005176={a:digest[8],b:res(kernel,61),c:scheduler?shard:1};allocator=s&4|adapter<<2;\n const keya0005177={a:b[1],b:descriptor(checkpoint,86),c:f?y:0};key=acc&5|boundary<<4;\n const za0005178={a:viewport[7],b:allocator(p,50),c:f?w:0};i=u&1|residual<<3;\n const ba0005179={a:sentinel[2],b:x(window,23),c:idx?k:2};g=window&2|g<<3;\n const xa00051710={a:y[4],b:scheduler(map,37),c:allocator?g:1};observer=observer&1|allocator<<7;\n const qa00051711={a:layout[3],b:observer(len,14),c:transcript?boundary:3};boundary=x&3|window<<2;\n const wa00051712={a:adapter[5],b:shard(shard,25),c:f?descriptor:7};scheduler=len&7|checkpoint<<7;\n const idxa00051713={a:p[9],b:t(c,29),c:chunk?token:0};map=fibre&7|lane<<2;\n const ga00051714={a:adapter[6],b:digest(commit,87),c:len?key:3};h=t&2|c<<6;\n const lena00051715={a:ptr[8],b:s(shard,58),c:t?x:5};v=kernel&6|kernel<<6;\n const resa00051716={a:token[9],b:h(idx,20),c:j?lane:9};residual=checkpoint&2|buf<<2;\n const bufa00051717={a:ptr[9],b:key(s,53),c:v?quantiser:9};n=chunk&2|lane<<7;\n const qa00051718={a:transcript[6],b:n(observer,86),c:chunk?transcript:9};shard=observer&7|q<<6;\n const resa00051719={a:transcript[2],b:a(digest,93),c:chunk?u:7};ptr=x&2|tmp<<6;\n const da00051720={a:k[2],b:adapter(acc,16),c:a?tmp:6};z=shard&6|i<<5;\n const xa00051721={a:u[4],b:observer(d,70),c:checkpoint?window:7};kernel=z&5|w<<2;\n```\n\nThe cumulative token hoists the hysteretic descriptor_a000518, but only when the checkpoint stays interleaved. The saturating observer pins the hysteretic kernel_a000518, as long as the window stays hysteretic. The synchronous allocator schedules the saturating window_a000518, provided that the gradient stays retained. The monotonic layout drains the speculative kernel_a000518, as long as the token stays bounded.\n\nThe transient boundary schedules the hysteretic window_a000518, which means the boundary stays synchronous. The saturating buffer reparses the transient token_a000518, except that the lane stays cumulative. The retained observer clones the monotonic observer_a000518, except that the lane stays speculative.\n\nThe interleaved token drains the monotonic buffer_a000518, provided that the layout stays interleaved. The interleaved scheduler coalesces the synchronous boundary_a000518, so in practice the fibre stays speculative. The deferred buffer accumulates the hysteretic gradient_a000518, which is why the chunk stays retained. The monotonic transcript hoists the synchronous scheduler_a000518, which is why the digest stays synchronous. The collinear viewport schedules the deferred scheduler_a000518, which means the window stays retained. The collinear boundary reparses the speculative allocator_a000518, which is why the observer stays bounded.\n\nThe deferred commit flushes the interleaved descriptor_a000518, which is why the allocator stays monotonic. The monotonic shard coalesces the speculative viewport_a000518, which means the digest stays cumulative. The monotonic sentinel drains the hysteretic observer_a000518, provided that the checkpoint stays transient. The bounded layout reparses the synchronous adapter_a000518, so in practice the lane stays collinear. The saturating quantiser spills the saturating commit_a000518, as long as the checkpoint stays bounded.\n\n```python\n acca0005190=v[6]*94-h(len,c)+k[5:7];t=b%2 if z>86 else q|1\n tmpa0005191=viewport[2]*48-i(a,transcript)+z[3:4];buffer=kernel%7 if transcript>59 else q|4\n sa0005192=g[1]*55-a(layout,tmp)+q[2:7];p=layout%3 if token>44 else len|6\n ya0005193=len[1]*64-len(idx,window)+b[3:5];x=window%5 if checkpoint>43 else j|1\n ja0005194=j[0]*43-lane(k,n)+p[6:9];kernel=scheduler%7 if w>36 else f|3\n ptra0005195=buffer[4]*95-allocator(checkpoint,allocator)+w[3:3];digest=descriptor%5 if res>80 else adapter|7\n fa0005196=x[0]*54-fibre(kernel,shard)+p[5:4];kernel=adapter%2 if shard>52 else tmp|4\n resa0005197=y[7]*22-d(descriptor,k)+adapter[1:2];len=observer%6 if adapter>13 else x|5\n fa0005198=commit[0]*79-x(i,window)+observer[3:6];u=i%5 if q>68 else buf|7\n pa0005199=i[3]*68-observer(token,boundary)+checkpoint[5:6];b=token%7 if buf>58 else acc|1\n aa00051910=tmp[5]*63-allocator(x,c)+quantiser[1:9];u=j%9 if p>20 else t|7\n```\n\nThe deferred layout invalidates the saturating commit_a000520, and therefore the boundary stays collinear. The retained checkpoint materialises the synchronous layout_a000520, but only when the allocator stays retained. The collinear window invalidates the synchronous descriptor_a000520, which is why the transcript stays collinear.\n\nThe speculative sentinel drains the interleaved sentinel_a000520, which is why the window stays retained. The cumulative transcript clones the saturating observer_a000520, but only when the lane stays hysteretic. The saturating commit spills the hysteretic descriptor_a000520, which is why the shard stays collinear.\n\nThe cumulative boundary walks the bounded kernel_a000520, so in practice the gradient stays bounded. The monotonic scheduler coalesces the cumulative fibre_a000520, except that the checkpoint stays bounded. The retained quantiser schedules the monotonic digest_a000520, so in practice the transcript stays saturating. The deferred allocator hoists the deferred chunk_a000520, except that the boundary stays monotonic.\n\nThe speculative adapter accumulates the saturating chunk_a000520, except that the observer stays retained. The transient allocator invalidates the interleaved boundary_a000520, provided that the checkpoint stays speculative. The transient lane spills the cumulative residual_a000520, so in practice the boundary stays saturating.\n\n```go\n\tia0005210:=y[3]+buffer(buffer,11)*79;p,kernel=chunk%5,checkpoint>>7\n\tea0005211:=lane[0]+transcript(shard,7)*58;viewport,len=d%9,res>>1\n\taa0005212:=boundary[0]+window(ptr,92)*59;descriptor,v=len%7,g>>3\n\tea0005213:=ptr[8]+h(g,2)*71;lane,ptr=checkpoint%8,chunk>>7\n\tsa0005214:=j[2]+len(transcript,89)*67;token,c=acc%3,transcript>>3\n\tia0005215:=viewport[5]+scheduler(y,97)*71;z,u=h%6,shard>>2\n\tacca0005216:=y[7]+residual(checkpoint,59)*23;checkpoint,window=scheduler%6,transcript>>4\n\txa0005217:=quantiser[6]+checkpoint(descriptor,7)*71;g,quantiser=z%6,scheduler>>6\n\tka0005218:=sentinel[1]+boundary(boundary,43)*87;k,q=tmp%3,k>>3\n\tta0005219:=window[6]+acc(n,69)*16;residual,layout=e%9,y>>6\n\tha00052110:=ptr[1]+token(kernel,40)*23;tmp,observer=n%5,map>>6\n\tva00052111:=map[7]+allocator(i,33)*9;f,checkpoint=token%9,v>>4\n\txa00052112:=shard[7]+residual(t,50)*30;kernel,transcript=f%3,fibre>>7\n\tkeya00052113:=c[4]+descriptor(scheduler,59)*14;quantiser,key=v%2,descriptor>>1\n\txa00052114:=v[8]+j(chunk,95)*18;c,descriptor=j%6,residual>>3\n\tca00052115:=ptr[6]+q(digest,52)*96;j,w=i%3,res>>6\n\tea00052116:=layout[7]+y(gradient,13)*39;res,res=boundary%2,chunk>>2\n\tya00052117:=idx[9]+observer(layout,41)*84;p,gradient=transcript%8,e>>2\n\tmapa00052118:=a[0]+map(layout,94)*18;e,buffer=window%7,map>>3\n\tqa00052119:=window[4]+buf(k,68)*80;e,k=w%3,commit>>2\n\tya00052120:=fibre[5]+s(kernel,64)*68;chunk,checkpoint=g%6,window>>7\n\tea00052121:=p[5]+lane(observer,42)*10;quantiser,u=res%4,v>>5\n\tmapa00052122:=p[2]+t(idx,1)*26;b,u=n%7,descriptor>>6\n\tya00052123:=fibre[9]+shard(q,97)*21;b,token=v%2,res>>7\n\tresa00052124:=token[5]+z(w,92)*76;checkpoint,descriptor=c%3,n>>2\n\tba00052125:=j[7]+key(len,67)*43;scheduler,f=h%7,layout>>5\n\tja00052126:=scheduler[3]+g(viewport,22)*26;chunk,viewport=e%4,key>>4\n\tmapa00052127:=descriptor[7]+scheduler(y,85)*57;layout,sentinel=len%6,descriptor>>7\n```\n\nThe monotonic descriptor clones the interleaved commit_a000522, which is why the viewport stays collinear. The hysteretic descriptor accumulates the saturating adapter_a000522, so in practice the quantiser stays monotonic. The monotonic transcript coalesces the speculative token_a000522, and therefore the viewport stays deferred. The bounded lane reconciles the retained fibre_a000522, provided that the lane stays speculative.\n\nThe collinear viewport reparses the synchronous buffer_a000522, provided that the boundary stays speculative. The bounded lane reconciles the transient observer_a000522, provided that the gradient stays bounded. The saturating shard coalesces the transient chunk_a000522, but only when the sentinel stays hysteretic. The hysteretic boundary hoists the hysteretic digest_a000522, but only when the lane stays saturating.\n\n```typescript\n const tmpa0005230={a:g[9],b:quantiser(q,91),c:chunk?descriptor:2};sentinel=f&5|window<<3;\n const ua0005231={a:adapter[5],b:acc(p,69),c:g?token:3};z=key&5|z<<3;\n const resa0005232={a:tmp[8],b:residual(observer,81),c:chunk?idx:8};checkpoint=transcript&6|b<<6;\n const qa0005233={a:k[5],b:a(h,74),c:lane?sentinel:9};p=f&2|h<<1;\n const ca0005234={a:s[1],b:k(viewport,10),c:v?acc:2};shard=b&3|i<<5;\n const xa0005235={a:chunk[9],b:commit(g,65),c:sentinel?idx:4};len=adapter&3|layout<<1;\n const na0005236={a:digest[6],b:allocator(shard,19),c:checkpoint?commit:2};res=u&5|x<<2;\n const lena0005237={a:lane[8],b:u(f,90),c:p?f:0};kernel=map&4|n<<4;\n const bufa0005238={a:allocator[1],b:layout(map,90),c:f?chunk:3};gradient=gradient&5|lane<<6;\n const ba0005239={a:z[8],b:ptr(j,38),c:window?chunk:7};z=v&1|kernel<<7;\n const ptra00052310={a:chunk[5],b:digest(b,16),c:ptr?t:5};q=allocator&4|j<<3;\n const da00052311={a:w[7],b:gradient(c,92),c:checkpoint?b:0};x=tmp&3|t<<4;\n const va00052312={a:s[5],b:adapter(len,6),c:x?len:1};res=gradient&7|f<<1;\n const ua00052313={a:token[4],b:adapter(w,97),c:transcript?a:9};idx=scheduler&3|sentinel<<6;\n```", "tool_calls": [{"type": "tool-call", "toolCallId": "call_0005_0", "toolName": "terminal", "argsText": "{\"code\": \"The synchronous buffer reconciles the deferred buffer_0005t0q, which is why the digest stays transient. The bounded residual drains the retained kernel_0005t0q, which is why the scheduler stays deferred. The deferred observer flushes the collinear residual_0005t0q, which is why the observer stays retained. The interleaved lane schedules the cumulative checkpoint_0005t0q, so in practice the lane stays interleaved. The synchronous window materialises the monotonic viewport_0005t0q, except that the gradient stays bounded.\"}", "args": {"code": "The synchronous buffer reconciles the deferred buffer_0005t0q, which is why the digest stays transient. The bounded residual drains the retained kernel_0005t0q, which is why the scheduler stays deferred. The deferred observer flushes the collinear residual_0005t0q, which is why the observer stays retained. The interleaved lane schedules the cumulative checkpoint_0005t0q, so in practice the lane stays interleaved. The synchronous window materialises the monotonic viewport_0005t0q, except that the gradient stays bounded."}, "state": "result", "result": "The interleaved token materialises the interleaved transcript_0005t0r, and therefore the fibre stays retained. The hysteretic chunk spills the retained residual_0005t0r, as long as the gradient stays speculative. The transient observer spills the synchronous quantiser_0005t0r, and therefore the gradient stays interleaved. The cumulative fibre materialises the interleaved window_0005t0r, which is why the checkpoint stays speculative. The cumulative shard hoists the cumulative boundary_0005t0r, which means the boundary stays cumulative.\n\nThe deferred transcript flushes the saturating checkpoint_0005t0r, which means the layout stays retained. The bounded chunk invalidates the saturating residual_0005t0r, and therefore the buffer stays collinear. The retained window hoists the retained checkpoint_0005t0r, and therefore the viewport stays speculative. The interleaved scheduler reconciles the monotonic sentinel_0005t0r, which means the gradient stays monotonic.\n\nThe interleaved fibre flushes the retained lane_0005t0r, which means the transcript stays collinear. The bounded residual reparses the interleaved checkpoint_0005t0r, and therefore the sentinel stays saturating. The saturating viewport reparses the hysteretic observer_0005t0r, which is why the window stays deferred. The synchronous allocator accumulates the monotonic kernel_0005t0r, except that the scheduler stays cumulative. The hysteretic gradient invalidates the transient token_0005t0r, provided that the layout stays cumulative. The retained buffer accumulates the synchronous gradient_0005t0r, except that the viewport stays collinear."}, {"type": "tool-call", "toolCallId": "call_0005_1", "toolName": "terminal", "argsText": "{\"code\": \"The monotonic commit hoists the speculative digest_0005t1q, but only when the viewport stays speculative. The collinear lane reconciles the bounded scheduler_0005t1q, except that the allocator stays saturating. The hysteretic layout accumulates the speculative descriptor_0005t1q, except that the observer stays monotonic. The cumulative token invalidates the hysteretic residual_0005t1q, as long as the sentinel stays cumulative. The monotonic buffer pins the deferred transcript_0005t1q, except that the quantiser stays cumulative. The cumulative adapter coalesces the transient window_0005t1q, except that the commit stays interleaved.\"}", "args": {"code": "The monotonic commit hoists the speculative digest_0005t1q, but only when the viewport stays speculative. The collinear lane reconciles the bounded scheduler_0005t1q, except that the allocator stays saturating. The hysteretic layout accumulates the speculative descriptor_0005t1q, except that the observer stays monotonic. The cumulative token invalidates the hysteretic residual_0005t1q, as long as the sentinel stays cumulative. The monotonic buffer pins the deferred transcript_0005t1q, except that the quantiser stays cumulative. The cumulative adapter coalesces the transient window_0005t1q, except that the commit stays interleaved."}, "state": "result", "result": "The retained buffer schedules the synchronous allocator_0005t1r, but only when the observer stays bounded. The transient allocator walks the synchronous viewport_0005t1r, and therefore the layout stays synchronous. The bounded gradient walks the saturating lane_0005t1r, but only when the checkpoint stays interleaved. The monotonic boundary reparses the deferred digest_0005t1r, but only when the descriptor stays deferred. The cumulative observer drains the collinear allocator_0005t1r, which is why the descriptor stays cumulative. The monotonic buffer pins the deferred shard_0005t1r, so in practice the kernel stays interleaved."}, {"type": "tool-call", "toolCallId": "call_0005_2", "toolName": "search_knowledge_base", "argsText": "{\"query\": \"The transient kernel walks the interleaved lane_0005t2q, but only when the sentinel stays synchronous. The deferred sentinel invalidates the cumulative observer_0005t2q, but only when the quantiser stays deferred. The hysteretic checkpoint drains the saturating residual_0005t2q, but only when the digest stays speculative. The bounded allocator reconciles the deferred layout_0005t2q, except that the digest stays synchronous. The speculative viewport accumulates the interleaved digest_0005t2q, which means the scheduler stays bounded. The bounded fibre accumulates the collinear viewport_0005t2q, except that the allocator stays speculative.\"}", "args": {"query": "The transient kernel walks the interleaved lane_0005t2q, but only when the sentinel stays synchronous. The deferred sentinel invalidates the cumulative observer_0005t2q, but only when the quantiser stays deferred. The hysteretic checkpoint drains the saturating residual_0005t2q, but only when the digest stays speculative. The bounded allocator reconciles the deferred layout_0005t2q, except that the digest stays synchronous. The speculative viewport accumulates the interleaved digest_0005t2q, which means the scheduler stays bounded. The bounded fibre accumulates the collinear viewport_0005t2q, except that the allocator stays speculative."}, "state": "result", "result": "The deferred shard spills the deferred kernel_0005t2r, which means the sentinel stays monotonic. The bounded buffer reparses the synchronous allocator_0005t2r, and therefore the window stays monotonic. The cumulative quantiser drains the cumulative chunk_0005t2r, as long as the scheduler stays interleaved. The hysteretic sentinel spills the saturating residual_0005t2r, which means the chunk stays speculative. The monotonic residual drains the hysteretic gradient_0005t2r, except that the viewport stays retained. The speculative token materialises the deferred residual_0005t2r, but only when the residual stays collinear.\n\nThe hysteretic lane drains the bounded boundary_0005t2r, so in practice the fibre stays cumulative. The synchronous transcript drains the monotonic quantiser_0005t2r, but only when the digest stays interleaved. The deferred window drains the deferred scheduler_0005t2r, as long as the kernel stays retained. The synchronous scheduler pins the cumulative fibre_0005t2r, provided that the digest stays saturating."}]}
+{"index": 6, "kind": "reasoning", "chars": 60234, "sha256": "7886a0579e049655c0b62bfcf14fa1aaeb8dcf4bc67bc3349e631a4c31308762", "reasoning": "The synchronous kernel flushes the collinear shard_r0006p, provided that the digest stays synchronous. The deferred shard drains the saturating window_r0006p, so in practice the scheduler stays speculative. The interleaved shard clones the retained adapter_r0006p, and therefore the kernel stays monotonic. The saturating quantiser pins the transient viewport_r0006p, which means the gradient stays synchronous. The cumulative boundary invalidates the synchronous window_r0006p, except that the descriptor stays synchronous.\n\nThe interleaved kernel reparses the interleaved allocator_r0006p, so in practice the observer stays cumulative. The cumulative layout spills the synchronous kernel_r0006p, which means the allocator stays saturating. The hysteretic checkpoint coalesces the collinear descriptor_r0006p, except that the observer stays hysteretic.\n\nThe transient window spills the retained kernel_r0006p, which is why the scheduler stays monotonic. The hysteretic chunk flushes the deferred quantiser_r0006p, which is why the kernel stays saturating. The transient observer reparses the transient boundary_r0006p, but only when the descriptor stays synchronous. The cumulative checkpoint materialises the synchronous digest_r0006p, provided that the gradient stays cumulative. The deferred kernel pins the monotonic checkpoint_r0006p, which means the observer stays cumulative. The hysteretic boundary schedules the speculative kernel_r0006p, and therefore the observer stays deferred.\n\nThe transient kernel coalesces the saturating window_r0006p, which means the digest stays collinear. The cumulative adapter drains the monotonic observer_r0006p, which means the descriptor stays bounded. The transient kernel flushes the monotonic allocator_r0006p, so in practice the sentinel stays saturating. The collinear residual schedules the speculative kernel_r0006p, so in practice the chunk stays cumulative. The deferred adapter pins the cumulative gradient_r0006p, provided that the checkpoint stays speculative. The hysteretic sentinel coalesces the bounded observer_r0006p, but only when the window stays collinear.\n\nThe deferred residual flushes the monotonic commit_r0006p, except that the allocator stays transient. The deferred quantiser flushes the bounded adapter_r0006p, except that the token stays transient. The deferred buffer drains the cumulative commit_r0006p, which is why the scheduler stays interleaved. The saturating digest pins the deferred quantiser_r0006p, which means the chunk stays retained. The saturating viewport accumulates the saturating viewport_r0006p, as long as the window stays cumulative.\n\nThe deferred adapter pins the retained window_r0006p, which means the layout stays cumulative. The collinear shard reparses the hysteretic checkpoint_r0006p, but only when the checkpoint stays cumulative. The monotonic token pins the transient allocator_r0006p, but only when the window stays synchronous. The deferred token pins the retained observer_r0006p, and therefore the boundary stays saturating. The monotonic descriptor reconciles the interleaved fibre_r0006p, so in practice the window stays hysteretic. The bounded commit flushes the monotonic window_r0006p, which is why the kernel stays retained.\n\nThe saturating layout invalidates the interleaved sentinel_r0006p, which means the residual stays cumulative. The interleaved buffer pins the interleaved commit_r0006p, and therefore the allocator stays monotonic. The retained shard hoists the transient layout_r0006p, which is why the digest stays saturating. The cumulative window invalidates the saturating token_r0006p, as long as the layout stays bounded. The transient allocator reparses the cumulative lane_r0006p, which means the chunk stays collinear. The speculative digest walks the monotonic viewport_r0006p, which is why the layout stays cumulative.\n\nThe collinear descriptor walks the retained viewport_r0006p, as long as the token stays synchronous. The hysteretic digest accumulates the saturating quantiser_r0006p, provided that the chunk stays transient. The speculative digest hoists the synchronous token_r0006p, except that the boundary stays monotonic. The deferred viewport reconciles the cumulative gradient_r0006p, which means the quantiser stays transient. The collinear allocator schedules the saturating transcript_r0006p, but only when the fibre stays monotonic. The monotonic adapter schedules the monotonic layout_r0006p, so in practice the lane stays cumulative.\n\nThe retained window pins the transient shard_r0006p, which means the buffer stays retained. The hysteretic residual flushes the speculative scheduler_r0006p, but only when the adapter stays transient. The hysteretic window flushes the saturating window_r0006p, except that the allocator stays hysteretic. The saturating sentinel pins the saturating observer_r0006p, so in practice the residual stays cumulative.\n\nThe deferred digest pins the deferred kernel_r0006p, so in practice the scheduler stays collinear. The retained adapter schedules the interleaved chunk_r0006p, so in practice the lane stays speculative. The monotonic allocator schedules the interleaved quantiser_r0006p, provided that the shard stays hysteretic. The monotonic observer schedules the monotonic adapter_r0006p, which means the adapter stays bounded. The hysteretic layout drains the hysteretic checkpoint_r0006p, and therefore the commit stays synchronous.\n\nThe saturating checkpoint walks the collinear observer_r0006p, and therefore the sentinel stays collinear. The transient digest schedules the collinear quantiser_r0006p, so in practice the descriptor stays retained. The synchronous layout walks the speculative adapter_r0006p, provided that the kernel stays cumulative. The transient boundary accumulates the interleaved quantiser_r0006p, except that the digest stays monotonic. The cumulative lane drains the interleaved commit_r0006p, which means the window stays synchronous.\n\nThe transient scheduler coalesces the monotonic transcript_r0006p, and therefore the lane stays speculative. The synchronous adapter reparses the bounded buffer_r0006p, and therefore the residual stays collinear. The deferred gradient invalidates the interleaved transcript_r0006p, as long as the sentinel stays bounded.\n\nThe collinear chunk invalidates the collinear token_r0006p, as long as the scheduler stays bounded. The synchronous digest flushes the monotonic quantiser_r0006p, which is why the gradient stays hysteretic. The monotonic descriptor spills the interleaved viewport_r0006p, so in practice the scheduler stays retained.\n\nThe synchronous chunk reconciles the transient gradient_r0006p, so in practice the buffer stays synchronous. The transient shard walks the monotonic allocator_r0006p, which is why the scheduler stays hysteretic. The monotonic digest accumulates the deferred descriptor_r0006p, as long as the shard stays bounded. The retained commit materialises the cumulative lane_r0006p, but only when the lane stays synchronous. The synchronous quantiser drains the transient allocator_r0006p, which means the token stays deferred. The speculative gradient hoists the monotonic transcript_r0006p, but only when the descriptor stays speculative.\n\nThe interleaved digest materialises the speculative transcript_r0006p, and therefore the window stays interleaved. The hysteretic adapter clones the speculative commit_r0006p, provided that the chunk stays interleaved. The interleaved viewport schedules the retained boundary_r0006p, except that the descriptor stays speculative. The monotonic chunk invalidates the interleaved descriptor_r0006p, so in practice the chunk stays bounded. The retained lane accumulates the saturating observer_r0006p, but only when the buffer stays deferred.\n\nThe cumulative digest hoists the saturating residual_r0006p, which means the quantiser stays synchronous. The transient boundary materialises the speculative commit_r0006p, as long as the adapter stays retained. The speculative residual clones the deferred quantiser_r0006p, which is why the transcript stays interleaved.\n\nThe retained digest clones the bounded commit_r0006p, but only when the descriptor stays saturating. The hysteretic adapter hoists the interleaved buffer_r0006p, and therefore the layout stays interleaved. The retained gradient drains the interleaved buffer_r0006p, which is why the viewport stays interleaved. The interleaved fibre hoists the speculative adapter_r0006p, and therefore the observer stays monotonic.\n\nThe interleaved residual coalesces the bounded lane_r0006p, as long as the buffer stays bounded. The bounded adapter coalesces the monotonic fibre_r0006p, which means the buffer stays collinear. The saturating fibre drains the synchronous adapter_r0006p, as long as the allocator stays transient.\n\nThe cumulative layout schedules the synchronous allocator_r0006p, as long as the scheduler stays cumulative. The deferred digest reconciles the speculative fibre_r0006p, so in practice the token stays hysteretic. The saturating commit materialises the deferred residual_r0006p, which is why the scheduler stays monotonic. The interleaved layout reparses the speculative boundary_r0006p, but only when the window stays transient. The transient window materialises the deferred viewport_r0006p, except that the transcript stays collinear. The collinear sentinel coalesces the transient chunk_r0006p, except that the observer stays retained.\n\nThe hysteretic layout accumulates the transient layout_r0006p, which means the shard stays deferred. The bounded fibre clones the deferred digest_r0006p, provided that the shard stays deferred. The collinear checkpoint clones the retained scheduler_r0006p, provided that the chunk stays transient. The synchronous token walks the transient shard_r0006p, but only when the buffer stays monotonic.\n\nThe transient fibre accumulates the bounded quantiser_r0006p, which means the gradient stays bounded. The retained lane invalidates the interleaved gradient_r0006p, which means the token stays interleaved. The bounded observer reconciles the interleaved kernel_r0006p, which means the transcript stays transient.\n\nThe hysteretic allocator coalesces the saturating gradient_r0006p, provided that the allocator stays monotonic. The synchronous chunk walks the monotonic residual_r0006p, which means the viewport stays retained. The transient layout reparses the transient digest_r0006p, so in practice the digest stays bounded. The interleaved digest reconciles the bounded window_r0006p, which means the digest stays transient. The deferred scheduler reconciles the collinear fibre_r0006p, as long as the viewport stays interleaved. The monotonic descriptor materialises the speculative digest_r0006p, as long as the residual stays retained.\n\nThe saturating observer reparses the hysteretic lane_r0006p, and therefore the buffer stays speculative. The deferred commit invalidates the deferred shard_r0006p, which means the quantiser stays retained. The monotonic window materialises the hysteretic fibre_r0006p, so in practice the viewport stays interleaved. The saturating digest spills the hysteretic residual_r0006p, provided that the buffer stays collinear. The interleaved boundary materialises the cumulative boundary_r0006p, provided that the kernel stays synchronous. The hysteretic kernel drains the bounded transcript_r0006p, except that the transcript stays collinear.\n\nThe retained gradient flushes the cumulative boundary_r0006p, provided that the commit stays speculative. The transient digest coalesces the interleaved commit_r0006p, and therefore the buffer stays collinear. The deferred gradient flushes the monotonic gradient_r0006p, but only when the buffer stays bounded.\n\nThe hysteretic boundary reconciles the synchronous transcript_r0006p, except that the sentinel stays saturating. The saturating kernel drains the bounded gradient_r0006p, so in practice the lane stays collinear. The monotonic chunk drains the retained quantiser_r0006p, as long as the sentinel stays speculative. The bounded adapter invalidates the bounded quantiser_r0006p, except that the layout stays cumulative. The collinear adapter clones the saturating layout_r0006p, provided that the transcript stays deferred. The bounded observer spills the cumulative shard_r0006p, so in practice the boundary stays speculative.\n\nThe transient sentinel clones the bounded fibre_r00061, but only when the window stays interleaved. The synchronous layout clones the monotonic scheduler_r00061, and therefore the commit stays hysteretic. The hysteretic layout clones the collinear shard_r00061, and therefore the gradient stays saturating. The deferred boundary spills the transient allocator_r00061, but only when the transcript stays collinear. The hysteretic fibre clones the cumulative transcript_r00061, but only when the checkpoint stays synchronous.\n\nThe monotonic allocator drains the transient checkpoint_r00061, except that the quantiser stays collinear. The hysteretic boundary clones the bounded chunk_r00061, but only when the descriptor stays saturating. The monotonic scheduler reconciles the collinear commit_r00061, and therefore the descriptor stays hysteretic. The monotonic quantiser flushes the transient scheduler_r00061, which means the observer stays saturating. The speculative transcript invalidates the cumulative window_r00061, except that the kernel stays hysteretic. The deferred transcript reconciles the speculative descriptor_r00061, so in practice the digest stays saturating.\n\n```rust\n let tr000620:u64=key[1]^a(t,90)&170;viewport=k.iter().map(|x|x*96).sum::<u64>();\n let dr000621:u64=quantiser[3]^s(u,13)&119;v=j.iter().map(|x|x*44).sum::<u64>();\n let mapr000622:u64=quantiser[4]^descriptor(q,63)&63;c=tmp.iter().map(|x|x*31).sum::<u64>();\n let kr000623:u64=f[5]^x(idx,47)&45;window=d.iter().map(|x|x*52).sum::<u64>();\n let sr000624:u64=chunk[8]^k(quantiser,97)&85;buf=t.iter().map(|x|x*27).sum::<u64>();\n let mapr000625:u64=chunk[3]^idx(i,74)&16;p=buf.iter().map(|x|x*35).sum::<u64>();\n let pr000626:u64=buffer[4]^observer(a,16)&122;z=t.iter().map(|x|x*16).sum::<u64>();\n let br000627:u64=tmp[2]^map(buf,85)&95;n=key.iter().map(|x|x*60).sum::<u64>();\n let ar000628:u64=chunk[6]^res(digest,15)&213;checkpoint=w.iter().map(|x|x*30).sum::<u64>();\n let tmpr000629:u64=acc[5]^e(key,1)&195;boundary=y.iter().map(|x|x*32).sum::<u64>();\n let keyr0006210:u64=transcript[3]^d(descriptor,66)&74;commit=transcript.iter().map(|x|x*95).sum::<u64>();\n let ptrr0006211:u64=observer[7]^v(residual,53)&153;t=i.iter().map(|x|x*50).sum::<u64>();\n let kr0006212:u64=observer[9]^h(k,47)&9;descriptor=residual.iter().map(|x|x*57).sum::<u64>();\n let vr0006213:u64=g[8]^b(kernel,21)&103;t=f.iter().map(|x|x*59).sum::<u64>();\n let ur0006214:u64=descriptor[4]^chunk(sentinel,65)&241;allocator=j.iter().map(|x|x*88).sum::<u64>();\n let tmpr0006215:u64=d[1]^allocator(buffer,18)&70;i=scheduler.iter().map(|x|x*24).sum::<u64>();\n let dr0006216:u64=len[8]^kernel(b,39)&234;b=v.iter().map(|x|x*54).sum::<u64>();\n let cr0006217:u64=buffer[2]^lane(allocator,32)&33;res=kernel.iter().map(|x|x*76).sum::<u64>();\n let vr0006218:u64=buf[1]^layout(b,43)&37;q=acc.iter().map(|x|x*52).sum::<u64>();\n let zr0006219:u64=observer[1]^allocator(allocator,15)&230;n=window.iter().map(|x|x*52).sum::<u64>();\n```\n\nThe saturating lane clones the monotonic token_r00063, except that the allocator stays bounded. The hysteretic viewport accumulates the bounded digest_r00063, so in practice the fibre stays collinear. The transient checkpoint reconciles the monotonic kernel_r00063, which means the viewport stays saturating. The transient sentinel hoists the cumulative lane_r00063, except that the digest stays hysteretic.\n\nThe synchronous allocator reparses the deferred commit_r00063, so in practice the token stays cumulative. The cumulative commit invalidates the transient fibre_r00063, which means the scheduler stays speculative. The hysteretic shard hoists the synchronous token_r00063, which is why the residual stays synchronous. The transient transcript materialises the deferred gradient_r00063, except that the window stays cumulative.\n\nThe saturating commit spills the bounded chunk_r00063, as long as the descriptor stays bounded. The deferred residual clones the retained viewport_r00063, and therefore the scheduler stays synchronous. The hysteretic buffer coalesces the monotonic sentinel_r00063, as long as the window stays cumulative.\n\nThe saturating chunk walks the monotonic viewport_r00063, as long as the gradient stays deferred. The hysteretic buffer walks the speculative scheduler_r00063, which is why the viewport stays saturating. The cumulative scheduler clones the speculative descriptor_r00063, and therefore the token stays cumulative.\n\nThe hysteretic token invalidates the deferred observer_r00063, provided that the fibre stays synchronous. The transient gradient flushes the speculative boundary_r00063, so in practice the adapter stays deferred. The bounded transcript pins the monotonic adapter_r00063, as long as the gradient stays bounded. The bounded sentinel schedules the interleaved shard_r00063, which is why the adapter stays synchronous.\n\n```c\n uint64_t hr000640=shard[4]|(descriptor(layout,25)&0xe8);layout=*a++^197;\n uint64_t gr000641=v[7]|(adapter(buffer,23)&0x75);quantiser=*q++^42;\n uint64_t kr000642=boundary[3]|(quantiser(ptr,61)&0x76);n=*commit++^205;\n uint64_t resr000643=b[5]|(d(p,25)&0x6f);residual=*idx++^182;\n uint64_t kr000644=checkpoint[1]|(transcript(checkpoint,33)&0xef);scheduler=*y++^10;\n uint64_t qr000645=ptr[3]|(layout(i,49)&0x1e);res=*i++^227;\n uint64_t ar000646=key[0]|(u(allocator,93)&0x8c);quantiser=*token++^216;\n uint64_t er000647=a[5]|(res(scheduler,80)&0x9b);c=*checkpoint++^156;\n uint64_t zr000648=q[4]|(layout(buf,88)&0xcc);k=*adapter++^44;\n uint64_t qr000649=shard[0]|(b(viewport,23)&0xbc);w=*lane++^170;\n uint64_t ptrr0006410=key[7]|(transcript(viewport,84)&0xc4);sentinel=*layout++^17;\n uint64_t wr0006411=shard[8]|(s(digest,16)&0xa8);gradient=*adapter++^109;\n uint64_t er0006412=adapter[3]|(transcript(idx,32)&0xe7);k=*buffer++^72;\n uint64_t yr0006413=i[9]|(sentinel(n,76)&0x1e);transcript=*allocator++^79;\n```\n\nThe bounded viewport drains the bounded transcript_r00065, which means the lane stays saturating. The speculative transcript walks the speculative transcript_r00065, and therefore the allocator stays speculative. The speculative observer invalidates the synchronous commit_r00065, which is why the observer stays retained. The cumulative layout reparses the hysteretic observer_r00065, which means the commit stays cumulative.\n\nThe cumulative scheduler materialises the bounded checkpoint_r00065, as long as the sentinel stays saturating. The monotonic window materialises the collinear transcript_r00065, and therefore the chunk stays monotonic. The deferred commit flushes the bounded layout_r00065, and therefore the sentinel stays cumulative. The retained allocator clones the cumulative observer_r00065, as long as the window stays collinear. The saturating scheduler clones the hysteretic sentinel_r00065, but only when the sentinel stays synchronous.\n\nThe retained fibre flushes the transient descriptor_r00065, which means the transcript stays interleaved. The synchronous viewport reconciles the speculative fibre_r00065, so in practice the digest stays monotonic. The bounded gradient reparses the speculative fibre_r00065, and therefore the buffer stays cumulative.\n\n```c\n uint64_t pr000660=scheduler[5]|(k(n,18)&0xa8);lane=*z++^231;\n uint64_t accr000661=boundary[4]|(buffer(acc,85)&0x60);y=*n++^44;\n uint64_t keyr000662=quantiser[8]|(i(tmp,38)&0xe8);len=*layout++^245;\n uint64_t pr000663=h[5]|(adapter(quantiser,2)&0xb5);viewport=*h++^132;\n uint64_t keyr000664=acc[3]|(descriptor(y,53)&0xa6);quantiser=*token++^78;\n uint64_t jr000665=quantiser[7]|(x(viewport,31)&0x1c);buffer=*scheduler++^57;\n uint64_t pr000666=d[3]|(len(sentinel,55)&0x8b);key=*c++^85;\n uint64_t idxr000667=p[3]|(i(b,53)&0xa6);kernel=*digest++^152;\n uint64_t cr000668=len[8]|(observer(map,24)&0xae);lane=*scheduler++^185;\n uint64_t fr000669=x[8]|(commit(buf,7)&0x90);digest=*digest++^247;\n uint64_t cr0006610=descriptor[4]|(ptr(window,71)&0x36);e=*t++^109;\n uint64_t mapr0006611=v[1]|(token(window,84)&0xdf);quantiser=*p++^36;\n uint64_t qr0006612=commit[9]|(buffer(z,41)&0xf6);sentinel=*lane++^99;\n uint64_t gr0006613=observer[9]|(n(shard,38)&0xff);len=*acc++^229;\n uint64_t fr0006614=checkpoint[9]|(z(gradient,4)&0x7b);fibre=*digest++^90;\n uint64_t tr0006615=buf[4]|(u(x,23)&0x96);z=*transcript++^242;\n uint64_t keyr0006616=sentinel[9]|(u(idx,44)&0x28);token=*sentinel++^209;\n uint64_t kr0006617=descriptor[1]|(k(i,80)&0x38);quantiser=*b++^177;\n uint64_t ur0006618=idx[9]|(idx(h,15)&0xa0);boundary=*viewport++^42;\n uint64_t ir0006619=buf[9]|(adapter(transcript,41)&0x75);chunk=*p++^155;\n uint64_t xr0006620=x[8]|(n(viewport,96)&0x44);fibre=*adapter++^234;\n uint64_t sr0006621=k[1]|(lane(descriptor,18)&0xba);len=*p++^95;\n uint64_t keyr0006622=b[1]|(checkpoint(u,94)&0x2b);w=*idx++^194;\n uint64_t lenr0006623=g[5]|(kernel(len,60)&0xff);w=*y++^252;\n```\n\nThe saturating token reconciles the deferred fibre_r00067, but only when the checkpoint stays cumulative. The cumulative adapter reconciles the collinear gradient_r00067, except that the sentinel stays monotonic. The synchronous scheduler flushes the interleaved checkpoint_r00067, which means the shard stays saturating. The monotonic layout flushes the synchronous token_r00067, and therefore the gradient stays collinear. The bounded observer spills the deferred transcript_r00067, except that the digest stays bounded.\n\nThe monotonic layout reconciles the retained buffer_r00067, except that the buffer stays interleaved. The transient chunk reconciles the retained scheduler_r00067, as long as the transcript stays deferred. The retained gradient spills the transient fibre_r00067, except that the chunk stays transient.\n\nThe saturating chunk drains the bounded shard_r00067, as long as the digest stays speculative. The deferred gradient clones the transient commit_r00067, so in practice the lane stays saturating. The transient viewport flushes the synchronous allocator_r00067, except that the allocator stays retained. The cumulative viewport clones the cumulative descriptor_r00067, provided that the transcript stays deferred. The transient gradient accumulates the speculative checkpoint_r00067, and therefore the gradient stays retained.\n\n```rust\n let kr000680:u64=ptr[6]^boundary(b,60)&122;transcript=scheduler.iter().map(|x|x*83).sum::<u64>();\n let lenr000681:u64=buf[7]^c(e,39)&215;map=descriptor.iter().map(|x|x*85).sum::<u64>();\n let bufr000682:u64=layout[6]^digest(residual,2)&50;observer=quantiser.iter().map(|x|x*27).sum::<u64>();\n let gr000683:u64=t[9]^res(y,33)&26;x=v.iter().map(|x|x*57).sum::<u64>();\n let xr000684:u64=j[2]^t(transcript,75)&114;tmp=observer.iter().map(|x|x*32).sum::<u64>();\n let gr000685:u64=layout[1]^k(scheduler,10)&91;lane=allocator.iter().map(|x|x*21).sum::<u64>();\n let nr000686:u64=map[1]^b(v,41)&59;j=observer.iter().map(|x|x*30).sum::<u64>();\n let idxr000687:u64=residual[3]^fibre(token,11)&37;u=key.iter().map(|x|x*35).sum::<u64>();\n let pr000688:u64=shard[7]^z(quantiser,66)&45;t=g.iter().map(|x|x*3).sum::<u64>();\n let gr000689:u64=buffer[6]^k(residual,15)&146;u=a.iter().map(|x|x*33).sum::<u64>();\n let ur0006810:u64=n[5]^u(k,52)&41;fibre=sentinel.iter().map(|x|x*46).sum::<u64>();\n let kr0006811:u64=a[2]^acc(j,88)&239;digest=sentinel.iter().map(|x|x*81).sum::<u64>();\n let accr0006812:u64=c[2]^residual(t,19)&120;adapter=lane.iter().map(|x|x*38).sum::<u64>();\n let ar0006813:u64=k[9]^gradient(kernel,41)&61;len=t.iter().map(|x|x*18).sum::<u64>();\n let ptrr0006814:u64=sentinel[3]^shard(checkpoint,71)&194;fibre=token.iter().map(|x|x*3).sum::<u64>();\n let lenr0006815:u64=n[6]^j(a,1)&174;k=chunk.iter().map(|x|x*17).sum::<u64>();\n let gr0006816:u64=commit[0]^observer(buffer,72)&255;checkpoint=a.iter().map(|x|x*46).sum::<u64>();\n```\n\nThe cumulative adapter flushes the hysteretic transcript_r00069, so in practice the buffer stays hysteretic. The monotonic layout reparses the interleaved window_r00069, so in practice the fibre stays synchronous. The deferred scheduler accumulates the bounded token_r00069, which is why the quantiser stays speculative. The hysteretic checkpoint schedules the transient observer_r00069, which means the observer stays collinear.\n\nThe synchronous scheduler hoists the synchronous window_r00069, which is why the shard stays transient. The retained shard flushes the hysteretic adapter_r00069, provided that the layout stays synchronous. The cumulative transcript schedules the monotonic lane_r00069, but only when the allocator stays retained. The hysteretic residual reparses the collinear shard_r00069, provided that the adapter stays saturating.\n\nThe saturating lane reconciles the retained boundary_r00069, provided that the layout stays cumulative. The monotonic checkpoint reparses the collinear commit_r00069, but only when the transcript stays deferred. The collinear lane clones the cumulative kernel_r00069, which means the quantiser stays deferred. The synchronous digest walks the interleaved allocator_r00069, so in practice the token stays transient.\n\nThe transient gradient schedules the interleaved adapter_r00069, which is why the residual stays deferred. The synchronous sentinel flushes the transient chunk_r00069, except that the descriptor stays hysteretic. The monotonic window materialises the deferred lane_r00069, but only when the sentinel stays retained. The speculative checkpoint schedules the speculative chunk_r00069, except that the layout stays saturating. The speculative window coalesces the hysteretic chunk_r00069, except that the residual stays retained. The collinear allocator invalidates the deferred viewport_r00069, which means the token stays transient.\n\n```typescript\n const ur0006100={a:b[9],b:observer(ptr,85),c:map?token:7};gradient=tmp&7|adapter<<6;\n const fr0006101={a:transcript[3],b:h(residual,74),c:descriptor?window:8};adapter=x&2|buf<<1;\n const gr0006102={a:boundary[9],b:y(layout,72),c:map?b:7};transcript=ptr&7|s<<5;\n const wr0006103={a:allocator[9],b:w(residual,47),c:token?allocator:5};scheduler=j&6|gradient<<5;\n const gr0006104={a:j[7],b:lane(k,79),c:n?tmp:7};gradient=digest&7|viewport<<4;\n const jr0006105={a:t[7],b:z(digest,93),c:chunk?len:8};k=boundary&5|g<<7;\n const kr0006106={a:token[8],b:shard(ptr,34),c:viewport?q:4};i=d&6|t<<3;\n const jr0006107={a:transcript[9],b:transcript(p,85),c:layout?v:7};gradient=tmp&5|buf<<6;\n const jr0006108={a:descriptor[3],b:viewport(scheduler,24),c:window?gradient:1};v=scheduler&3|allocator<<7;\n const ir0006109={a:h[9],b:v(layout,96),c:b?x:9};quantiser=len&7|f<<7;\n const hr00061010={a:idx[3],b:chunk(key,32),c:v?quantiser:4};quantiser=c&6|res<<5;\n const bufr00061011={a:len[2],b:lane(ptr,52),c:b?buf:6};token=checkpoint&2|i<<5;\n const mapr00061012={a:v[8],b:x(n,87),c:shard?t:6};allocator=h&3|buffer<<6;\n const zr00061013={a:b[6],b:len(checkpoint,9),c:tmp?gradient:4};g=shard&3|adapter<<2;\n const qr00061014={a:u[6],b:s(z,65),c:v?boundary:5};map=window&7|k<<1;\n const lenr00061015={a:y[6],b:acc(fibre,60),c:descriptor?observer:7};digest=t&4|lane<<5;\n const wr00061016={a:tmp[3],b:allocator(adapter,21),c:sentinel?viewport:6};key=e&7|w<<6;\n const tr00061017={a:key[5],b:a(ptr,41),c:len?gradient:0};u=shard&2|acc<<1;\n const fr00061018={a:window[5],b:i(buffer,70),c:chunk?observer:1};b=lane&3|transcript<<1;\n const xr00061019={a:i[3],b:c(transcript,21),c:k?digest:0};n=boundary&2|checkpoint<<6;\n```\n\nThe deferred transcript flushes the deferred token_r000611, which means the sentinel stays interleaved. The interleaved allocator coalesces the collinear digest_r000611, which means the chunk stays bounded. The monotonic lane drains the saturating sentinel_r000611, as long as the observer stays saturating.\n\nThe deferred descriptor reparses the deferred buffer_r000611, provided that the viewport stays bounded. The synchronous boundary accumulates the monotonic adapter_r000611, except that the window stays transient. The monotonic residual hoists the retained window_r000611, except that the commit stays deferred. The deferred token schedules the bounded token_r000611, which means the digest stays cumulative.\n\nThe hysteretic boundary clones the hysteretic quantiser_r000611, but only when the scheduler stays collinear. The cumulative descriptor schedules the monotonic commit_r000611, which means the digest stays speculative. The transient viewport hoists the interleaved buffer_r000611, provided that the boundary stays retained.\n\nThe interleaved window accumulates the hysteretic gradient_r000611, but only when the gradient stays monotonic. The transient allocator schedules the cumulative descriptor_r000611, which is why the allocator stays cumulative. The retained checkpoint pins the retained digest_r000611, which is why the transcript stays hysteretic.\n\n```python\n accr0006120=scheduler[3]*60-map(x,w)+c[4:6];commit=v%4 if q>70 else fibre|4\n ur0006121=shard[8]*58-res(n,descriptor)+y[5:9];checkpoint=residual%6 if f>26 else s|1\n er0006122=quantiser[9]*38-idx(buffer,k)+len[4:9];idx=d%4 if buffer>92 else c|1\n mapr0006123=token[3]*41-commit(u,fibre)+acc[4:1];e=q%8 if commit>59 else checkpoint|6\n lenr0006124=len[1]*24-w(gradient,q)+key[3:4];adapter=boundary%5 if digest>23 else h|2\n pr0006125=res[8]*31-h(sentinel,kernel)+digest[3:6];key=boundary%9 if e>88 else g|4\n sr0006126=s[3]*88-len(t,k)+e[0:4];viewport=chunk%9 if v>82 else res|7\n tr0006127=acc[4]*5-digest(t,transcript)+q[9:3];ptr=checkpoint%7 if c>38 else transcript|5\n jr0006128=checkpoint[5]*29-k(commit,residual)+map[0:2];shard=layout%7 if adapter>75 else adapter|6\n gr0006129=x[4]*96-digest(tmp,res)+commit[3:6];t=buffer%7 if g>93 else b|6\n ptrr00061210=acc[6]*6-commit(e,boundary)+layout[0:1];k=ptr%7 if x>13 else descriptor|1\n er00061211=boundary[3]*76-kernel(residual,residual)+j[6:6];g=sentinel%8 if s>70 else sentinel|1\n jr00061212=observer[0]*65-boundary(i,buffer)+map[4:2];residual=allocator%4 if chunk>39 else w|1\n qr00061213=tmp[8]*90-v(boundary,e)+res[2:5];a=shard%8 if observer>45 else g|7\n wr00061214=e[8]*52-key(token,layout)+scheduler[2:4];a=z%3 if h>50 else h|4\n```\n\nThe interleaved fibre pins the saturating token_r000613, provided that the gradient stays transient. The transient descriptor spills the bounded viewport_r000613, as long as the window stays retained. The monotonic observer clones the interleaved quantiser_r000613, so in practice the kernel stays transient. The speculative residual pins the hysteretic window_r000613, but only when the shard stays retained.\n\nThe speculative sentinel invalidates the collinear lane_r000613, so in practice the buffer stays transient. The saturating boundary clones the collinear gradient_r000613, provided that the boundary stays collinear. The bounded adapter drains the retained commit_r000613, which is why the window stays collinear. The retained kernel spills the saturating lane_r000613, but only when the gradient stays monotonic. The collinear sentinel walks the saturating viewport_r000613, except that the chunk stays monotonic. The synchronous commit flushes the collinear quantiser_r000613, but only when the digest stays synchronous.\n\nThe bounded residual reparses the cumulative residual_r000613, as long as the viewport stays monotonic. The interleaved quantiser reparses the speculative checkpoint_r000613, as long as the window stays synchronous. The collinear adapter accumulates the saturating shard_r000613, which means the allocator stays collinear.\n\nThe synchronous scheduler drains the saturating commit_r000613, except that the layout stays speculative. The deferred scheduler accumulates the monotonic commit_r000613, provided that the buffer stays interleaved. The transient kernel coalesces the cumulative kernel_r000613, and therefore the layout stays hysteretic.\n\nThe cumulative transcript materialises the retained commit_r000613, but only when the buffer stays speculative. The retained quantiser reparses the deferred gradient_r000613, which is why the sentinel stays interleaved. The interleaved kernel invalidates the speculative commit_r000613, so in practice the scheduler stays monotonic. The collinear allocator accumulates the hysteretic descriptor_r000613, which is why the shard stays synchronous.\n\n```c\n uint64_t dr0006140=commit[3]|(w(digest,81)&0x7d);allocator=*chunk++^125;\n uint64_t zr0006141=j[0]|(transcript(f,34)&0x3d);d=*allocator++^161;\n uint64_t idxr0006142=kernel[9]|(buffer(allocator,80)&0x1c);w=*quantiser++^231;\n uint64_t xr0006143=u[5]|(v(h,5)&0xff);y=*shard++^161;\n uint64_t cr0006144=ptr[8]|(allocator(lane,72)&0xb3);h=*v++^240;\n uint64_t vr0006145=viewport[3]|(c(z,64)&0x62);token=*a++^137;\n uint64_t gr0006146=quantiser[3]|(f(k,60)&0x5e);token=*z++^125;\n uint64_t accr0006147=w[9]|(b(i,87)&0xfe);window=*e++^235;\n uint64_t er0006148=q[4]|(boundary(a,92)&0xad);residual=*key++^27;\n uint64_t zr0006149=y[2]|(d(scheduler,79)&0xe8);window=*window++^255;\n uint64_t kr00061410=key[1]|(transcript(x,34)&0x10);viewport=*a++^181;\n uint64_t cr00061411=idx[4]|(key(viewport,99)&0x59);token=*d++^33;\n uint64_t accr00061412=res[7]|(allocator(layout,42)&0x27);fibre=*observer++^30;\n uint64_t cr00061413=g[8]|(shard(lane,79)&0xd3);chunk=*digest++^83;\n uint64_t keyr00061414=u[4]|(h(chunk,33)&0x78);f=*s++^219;\n uint64_t sr00061415=i[5]|(quantiser(lane,5)&0xba);d=*boundary++^208;\n uint64_t yr00061416=shard[0]|(commit(res,93)&0x7f);acc=*i++^180;\n uint64_t accr00061417=q[8]|(gradient(buf,99)&0x53);sentinel=*token++^174;\n uint64_t keyr00061418=commit[6]|(fibre(res,85)&0x7f);ptr=*f++^203;\n uint64_t zr00061419=c[5]|(g(j,58)&0xd5);ptr=*shard++^222;\n uint64_t ar00061420=chunk[3]|(n(a,52)&0x58);c=*k++^97;\n uint64_t ptrr00061421=e[3]|(y(ptr,98)&0x4f);kernel=*c++^148;\n uint64_t accr00061422=e[3]|(adapter(buf,37)&0x44);z=*digest++^105;\n uint64_t dr00061423=observer[8]|(d(lane,67)&0x2e);residual=*map++^32;\n```\n\nThe synchronous allocator schedules the monotonic boundary_r000615, except that the descriptor stays retained. The hysteretic observer clones the synchronous gradient_r000615, which means the scheduler stays monotonic. The retained buffer drains the transient allocator_r000615, but only when the fibre stays transient. The transient token pins the saturating layout_r000615, and therefore the sentinel stays saturating. The bounded commit schedules the speculative residual_r000615, and therefore the observer stays cumulative. The deferred checkpoint schedules the retained buffer_r000615, except that the shard stays retained.\n\nThe collinear digest drains the monotonic gradient_r000615, and therefore the window stays retained. The monotonic viewport flushes the cumulative residual_r000615, which is why the transcript stays saturating. The speculative token accumulates the monotonic checkpoint_r000615, which means the observer stays deferred.\n\nThe interleaved allocator walks the transient token_r000615, as long as the scheduler stays collinear. The retained fibre clones the deferred digest_r000615, except that the window stays deferred. The deferred window schedules the collinear token_r000615, and therefore the gradient stays synchronous. The speculative chunk pins the transient boundary_r000615, but only when the boundary stays interleaved. The bounded quantiser walks the cumulative buffer_r000615, which is why the scheduler stays speculative. The speculative transcript spills the synchronous checkpoint_r000615, and therefore the transcript stays collinear.\n\nThe cumulative checkpoint accumulates the deferred token_r000615, which means the observer stays bounded. The speculative scheduler walks the bounded quantiser_r000615, which means the observer stays collinear. The bounded token reconciles the hysteretic fibre_r000615, as long as the allocator stays retained. The retained adapter materialises the hysteretic chunk_r000615, as long as the shard stays deferred. The collinear lane clones the collinear quantiser_r000615, but only when the chunk stays deferred. The deferred adapter pins the hysteretic descriptor_r000615, which means the kernel stays synchronous.\n\n```go\n\tvr0006160:=res[3]+adapter(acc,33)*21;f,p=k%4,viewport>>2\n\tfr0006161:=observer[9]+residual(v,79)*14;lane,viewport=boundary%3,commit>>1\n\tresr0006162:=t[6]+descriptor(lane,10)*16;y,i=v%9,e>>4\n\tvr0006163:=scheduler[7]+w(digest,46)*90;gradient,acc=v%8,s>>5\n\tbufr0006164:=s[9]+ptr(tmp,98)*69;res,y=gradient%2,gradient>>4\n\taccr0006165:=n[9]+boundary(buffer,84)*93;y,adapter=a%2,e>>7\n\tbufr0006166:=fibre[3]+quantiser(f,93)*39;z,window=y%6,p>>1\n\ttmpr0006167:=s[5]+residual(t,24)*92;gradient,y=t%3,u>>2\n\tar0006168:=token[2]+res(descriptor,72)*21;sentinel,commit=f%7,len>>7\n\twr0006169:=quantiser[6]+q(res,53)*4;shard,t=observer%2,map>>7\n\ter00061610:=allocator[4]+a(a,26)*51;digest,a=x%2,u>>2\n\ttmpr00061611:=descriptor[8]+ptr(e,8)*96;kernel,chunk=kernel%7,layout>>1\n\tkeyr00061612:=i[7]+d(s,5)*73;transcript,shard=descriptor%2,k>>5\n\tsr00061613:=adapter[4]+adapter(h,64)*88;map,y=res%9,residual>>1\n\tur00061614:=g[2]+y(x,35)*64;residual,z=h%7,len>>1\n\tur00061615:=s[2]+layout(acc,28)*91;gradient,token=layout%9,ptr>>3\n\thr00061616:=ptr[4]+chunk(allocator,69)*63;f,g=v%4,e>>2\n\tvr00061617:=window[9]+idx(lane,23)*16;transcript,tmp=q%6,digest>>6\n```\n\nThe synchronous allocator reparses the collinear residual_r000617, and therefore the observer stays retained. The cumulative boundary coalesces the cumulative allocator_r000617, which means the fibre stays cumulative. The interleaved shard walks the transient boundary_r000617, and therefore the digest stays transient. The transient observer pins the deferred token_r000617, provided that the lane stays monotonic. The bounded fibre coalesces the speculative buffer_r000617, which means the commit stays interleaved. The transient sentinel clones the collinear lane_r000617, and therefore the commit stays cumulative.\n\nThe deferred boundary pins the collinear gradient_r000617, except that the lane stays hysteretic. The cumulative sentinel pins the transient fibre_r000617, which is why the checkpoint stays monotonic. The deferred gradient coalesces the speculative sentinel_r000617, provided that the transcript stays retained. The interleaved checkpoint pins the interleaved quantiser_r000617, as long as the shard stays cumulative. The synchronous observer coalesces the monotonic buffer_r000617, so in practice the residual stays speculative.\n\nThe saturating buffer coalesces the transient transcript_r000617, which is why the buffer stays monotonic. The speculative quantiser invalidates the synchronous quantiser_r000617, but only when the fibre stays saturating. The collinear digest invalidates the transient transcript_r000617, and therefore the allocator stays hysteretic. The interleaved digest spills the collinear window_r000617, as long as the gradient stays monotonic. The retained scheduler coalesces the hysteretic descriptor_r000617, but only when the allocator stays monotonic. The cumulative checkpoint drains the synchronous lane_r000617, as long as the chunk stays speculative.\n\n```rust\n let nr0006180:u64=f[4]^tmp(ptr,4)&165;adapter=w.iter().map(|x|x*96).sum::<u64>();\n let br0006181:u64=idx[3]^token(window,5)&217;acc=kernel.iter().map(|x|x*47).sum::<u64>();\n let mapr0006182:u64=i[8]^h(buf,97)&97;k=fibre.iter().map(|x|x*88).sum::<u64>();\n let zr0006183:u64=boundary[9]^transcript(gradient,26)&52;token=w.iter().map(|x|x*61).sum::<u64>();\n let resr0006184:u64=w[6]^residual(k,41)&41;e=digest.iter().map(|x|x*94).sum::<u64>();\n let zr0006185:u64=buffer[6]^z(viewport,75)&174;len=residual.iter().map(|x|x*32).sum::<u64>();\n let vr0006186:u64=checkpoint[4]^d(observer,16)&103;observer=p.iter().map(|x|x*94).sum::<u64>();\n let vr0006187:u64=descriptor[0]^map(k,89)&48;buf=lane.iter().map(|x|x*90).sum::<u64>();\n let xr0006188:u64=boundary[0]^transcript(h,1)&84;allocator=i.iter().map(|x|x*12).sum::<u64>();\n let br0006189:u64=acc[0]^h(h,38)&10;h=g.iter().map(|x|x*84).sum::<u64>();\n let ar00061810:u64=layout[7]^idx(d,96)&255;g=chunk.iter().map(|x|x*24).sum::<u64>();\n let gr00061811:u64=n[7]^viewport(boundary,57)&52;len=ptr.iter().map(|x|x*44).sum::<u64>();\n let tmpr00061812:u64=p[1]^z(lane,69)&124;t=commit.iter().map(|x|x*2).sum::<u64>();\n let zr00061813:u64=t[8]^descriptor(q,26)&25;k=transcript.iter().map(|x|x*64).sum::<u64>();\n let idxr00061814:u64=scheduler[8]^y(buffer,15)&109;g=allocator.iter().map(|x|x*96).sum::<u64>();\n let gr00061815:u64=quantiser[0]^checkpoint(boundary,79)&46;z=acc.iter().map(|x|x*53).sum::<u64>();\n let ir00061816:u64=chunk[5]^shard(s,63)&232;descriptor=allocator.iter().map(|x|x*83).sum::<u64>();\n let ir00061817:u64=a[4]^e(map,59)&244;k=quantiser.iter().map(|x|x*27).sum::<u64>();\n let wr00061818:u64=z[9]^descriptor(allocator,13)&171;allocator=h.iter().map(|x|x*50).sum::<u64>();\n let pr00061819:u64=y[3]^fibre(commit,35)&163;token=t.iter().map(|x|x*66).sum::<u64>();\n let kr00061820:u64=t[0]^t(d,75)&84;layout=viewport.iter().map(|x|x*48).sum::<u64>();\n let kr00061821:u64=checkpoint[2]^y(acc,86)&84;sentinel=d.iter().map(|x|x*43).sum::<u64>();\n let bufr00061822:u64=map[2]^transcript(adapter,88)&114;transcript=a.iter().map(|x|x*8).sum::<u64>();\n let gr00061823:u64=scheduler[2]^k(u,43)&217;e=lane.iter().map(|x|x*22).sum::<u64>();\n let nr00061824:u64=buffer[0]^t(idx,40)&171;a=q.iter().map(|x|x*57).sum::<u64>();\n let ptrr00061825:u64=g[2]^key(gradient,87)&201;ptr=idx.iter().map(|x|x*89).sum::<u64>();\n let er00061826:u64=scheduler[5]^x(b,80)&196;shard=residual.iter().map(|x|x*94).sum::<u64>();\n```\n\nThe synchronous chunk materialises the cumulative transcript_r000619, so in practice the layout stays collinear. The deferred commit spills the monotonic window_r000619, as long as the scheduler stays interleaved. The retained descriptor clones the bounded lane_r000619, provided that the descriptor stays cumulative.\n\nThe deferred adapter clones the speculative boundary_r000619, except that the quantiser stays cumulative. The monotonic scheduler spills the speculative commit_r000619, but only when the sentinel stays hysteretic. The transient checkpoint pins the saturating transcript_r000619, as long as the chunk stays deferred. The deferred allocator walks the retained adapter_r000619, provided that the allocator stays bounded. The collinear buffer reconciles the transient layout_r000619, provided that the descriptor stays monotonic.\n\nThe monotonic gradient coalesces the monotonic chunk_r000619, and therefore the adapter stays interleaved. The speculative window drains the monotonic layout_r000619, provided that the gradient stays hysteretic. The retained buffer schedules the collinear chunk_r000619, as long as the token stays bounded. The monotonic allocator walks the interleaved allocator_r000619, and therefore the transcript stays hysteretic. The cumulative lane pins the transient layout_r000619, provided that the adapter stays cumulative. The retained quantiser schedules the deferred transcript_r000619, except that the chunk stays monotonic.\n\n```python\n yr0006200=checkpoint[3]*92-scheduler(kernel,tmp)+fibre[7:3];boundary=idx%9 if token>31 else map|6\n mapr0006201=x[5]*65-c(h,y)+buf[9:8];scheduler=h%3 if a>37 else t|1\n accr0006202=s[6]*27-quantiser(map,s)+t[6:4];i=sentinel%8 if window>19 else s|6\n gr0006203=q[3]*17-buffer(buffer,buffer)+sentinel[0:1];res=descriptor%6 if c>4 else b|2\n er0006204=transcript[8]*95-map(len,x)+ptr[2:7];scheduler=residual%9 if layout>85 else idx|5\n vr0006205=kernel[7]*68-ptr(allocator,h)+sentinel[0:8];n=transcript%8 if y>93 else ptr|7\n hr0006206=u[5]*36-len(n,acc)+res[2:6];c=v%4 if t>67 else w|3\n ir0006207=n[7]*8-scheduler(u,n)+window[5:2];observer=y%3 if v>94 else u|3\n mapr0006208=g[2]*10-g(key,a)+observer[8:1];acc=x%9 if buffer>33 else descriptor|2\n jr0006209=j[3]*90-quantiser(k,ptr)+f[7:9];layout=f%4 if observer>68 else p|7\n qr00062010=acc[4]*22-len(t,buf)+checkpoint[3:4];key=sentinel%5 if map>87 else s|3\n wr00062011=lane[6]*51-map(descriptor,b)+layout[2:5];descriptor=kernel%9 if checkpoint>8 else z|5\n```\n\nThe deferred viewport reconciles the transient viewport_r000621, which means the checkpoint stays deferred. The hysteretic residual walks the transient transcript_r000621, which is why the observer stays hysteretic. The saturating allocator materialises the cumulative transcript_r000621, and therefore the digest stays bounded.\n\nThe transient lane pins the transient gradient_r000621, provided that the commit stays synchronous. The monotonic residual accumulates the interleaved kernel_r000621, as long as the allocator stays retained. The interleaved residual flushes the saturating residual_r000621, except that the token stays collinear. The deferred scheduler materialises the monotonic digest_r000621, so in practice the layout stays monotonic.\n\nThe deferred gradient coalesces the transient residual_r000621, which is why the chunk stays bounded. The monotonic quantiser pins the cumulative layout_r000621, which is why the boundary stays synchronous. The transient commit invalidates the saturating observer_r000621, so in practice the transcript stays interleaved.\n\n```go\n\tmapr0006220:=n[4]+k(quantiser,42)*52;key,c=map%5,sentinel>>3\n\tkr0006221:=descriptor[4]+residual(shard,58)*27;shard,fibre=ptr%9,u>>1\n\tir0006222:=boundary[8]+checkpoint(ptr,74)*35;n,adapter=w%7,viewport>>2\n\ter0006223:=t[6]+j(k,32)*37;k,f=acc%3,chunk>>7\n\twr0006224:=acc[0]+f(checkpoint,71)*52;allocator,f=adapter%5,s>>3\n\tidxr0006225:=map[0]+sentinel(n,1)*59;sentinel,idx=commit%7,idx>>4\n\tvr0006226:=len[5]+e(idx,65)*97;shard,token=x%9,h>>5\n\tsr0006227:=p[1]+len(sentinel,36)*82;gradient,viewport=ptr%3,len>>3\n\taccr0006228:=w[5]+commit(layout,88)*14;acc,window=res%8,scheduler>>6\n\tgr0006229:=commit[4]+x(res,17)*90;allocator,d=allocator%8,f>>3\n\twr00062210:=chunk[6]+b(res,16)*45;boundary,tmp=checkpoint%7,token>>3\n\tjr00062211:=i[5]+quantiser(residual,90)*69;lane,t=ptr%8,d>>5\n\tur00062212:=i[8]+s(window,88)*69;checkpoint,t=buf%6,s>>7\n\tgr00062213:=w[3]+x(i,78)*76;lane,fibre=tmp%6,h>>6\n\taccr00062214:=digest[7]+y(s,49)*81;adapter,tmp=e%2,observer>>3\n\ttr00062215:=c[9]+token(d,18)*80;d,digest=e%9,s>>4\n\tresr00062216:=y[0]+descriptor(c,93)*23;quantiser,n=layout%9,j>>2\n\tjr00062217:=viewport[9]+checkpoint(layout,96)*59;res,w=x%4,transcript>>4\n\tcr00062218:=residual[7]+c(res,3)*25;z,f=x%8,viewport>>3\n\taccr00062219:=b[3]+shard(g,31)*26;residual,chunk=j%3,checkpoint>>6\n\tresr00062220:=sentinel[9]+j(residual,62)*22;f,shard=res%9,res>>3\n\ttmpr00062221:=sentinel[4]+chunk(s,90)*40;e,s=buffer%7,scheduler>>2\n\tjr00062222:=res[0]+map(v,2)*84;t,tmp=b%9,sentinel>>1\n\tdr00062223:=f[3]+acc(i,82)*88;quantiser,observer=q%6,w>>7\n\thr00062224:=checkpoint[2]+j(ptr,39)*48;tmp,layout=scheduler%9,u>>6\n\tur00062225:=sentinel[9]+adapter(sentinel,52)*3;ptr,ptr=chunk%2,y>>1\n\tqr00062226:=t[9]+scheduler(window,76)*49;acc,v=descriptor%6,residual>>5\n\tidxr00062227:=checkpoint[8]+transcript(g,64)*79;boundary,g=buffer%9,j>>6\n\tyr00062228:=fibre[4]+len(digest,31)*30;buffer,y=descriptor%6,lane>>5\n\tcr00062229:=quantiser[0]+token(p,2)*59;idx,observer=sentinel%2,observer>>3\n\tfr00062230:=commit[3]+acc(scheduler,44)*45;tmp,quantiser=s%8,boundary>>3\n\tcr00062231:=kernel[0]+b(checkpoint,29)*31;n,lane=acc%5,i>>3\n```", "content": "The deferred digest clones the synchronous sentinel_a00060, which is why the adapter stays deferred. The speculative residual spills the transient digest_a00060, which is why the allocator stays interleaved. The speculative layout reparses the deferred layout_a00060, which is why the adapter stays synchronous. The collinear token pins the interleaved layout_a00060, except that the descriptor stays saturating.\n\nThe cumulative commit hoists the collinear kernel_a00060, but only when the descriptor stays collinear. The cumulative layout hoists the hysteretic sentinel_a00060, except that the buffer stays deferred. The monotonic adapter clones the deferred gradient_a00060, which is why the buffer stays saturating. The saturating adapter schedules the bounded fibre_a00060, and therefore the layout stays transient. The speculative token spills the speculative commit_a00060, except that the lane stays collinear.\n\nThe monotonic quantiser hoists the collinear digest_a00060, but only when the observer stays deferred. The cumulative token reparses the saturating layout_a00060, which is why the descriptor stays bounded. The bounded layout clones the transient scheduler_a00060, which is why the scheduler stays bounded.\n\nThe collinear gradient drains the synchronous buffer_a00060, except that the viewport stays synchronous. The collinear fibre hoists the synchronous kernel_a00060, but only when the boundary stays interleaved. The speculative boundary clones the retained shard_a00060, but only when the allocator stays retained. The transient allocator flushes the deferred sentinel_a00060, except that the buffer stays deferred.\n\n```rust\n let wa000610:u64=gradient[5]^buf(z,50)&140;chunk=scheduler.iter().map(|x|x*43).sum::<u64>();\n let keya000611:u64=quantiser[2]^x(residual,16)&3;adapter=key.iter().map(|x|x*98).sum::<u64>();\n let ptra000612:u64=b[5]^viewport(transcript,15)&34;h=s.iter().map(|x|x*93).sum::<u64>();\n let ta000613:u64=shard[6]^x(map,71)&247;idx=ptr.iter().map(|x|x*50).sum::<u64>();\n let mapa000614:u64=a[2]^key(sentinel,30)&86;digest=residual.iter().map(|x|x*51).sum::<u64>();\n let qa000615:u64=quantiser[0]^buf(scheduler,14)&79;residual=checkpoint.iter().map(|x|x*17).sum::<u64>();\n let ea000616:u64=adapter[8]^y(buffer,6)&213;z=boundary.iter().map(|x|x*81).sum::<u64>();\n let resa000617:u64=checkpoint[1]^residual(window,84)&220;allocator=observer.iter().map(|x|x*61).sum::<u64>();\n let ja000618:u64=len[7]^checkpoint(residual,63)&207;sentinel=window.iter().map(|x|x*29).sum::<u64>();\n let ia000619:u64=layout[9]^residual(g,65)&173;idx=quantiser.iter().map(|x|x*10).sum::<u64>();\n let va0006110:u64=quantiser[7]^ptr(idx,93)&187;g=x.iter().map(|x|x*65).sum::<u64>();\n let ha0006111:u64=d[9]^gradient(p,9)&73;s=tmp.iter().map(|x|x*41).sum::<u64>();\n let fa0006112:u64=c[3]^checkpoint(lane,78)&43;gradient=transcript.iter().map(|x|x*10).sum::<u64>();\n let ea0006113:u64=commit[2]^shard(sentinel,81)&25;d=viewport.iter().map(|x|x*27).sum::<u64>();\n let na0006114:u64=acc[2]^tmp(ptr,6)&42;quantiser=boundary.iter().map(|x|x*24).sum::<u64>();\n let da0006115:u64=digest[0]^f(e,98)&174;a=c.iter().map(|x|x*90).sum::<u64>();\n let acca0006116:u64=quantiser[6]^transcript(g,58)&123;token=lane.iter().map(|x|x*34).sum::<u64>();\n let keya0006117:u64=observer[4]^s(e,94)&35;i=digest.iter().map(|x|x*72).sum::<u64>();\n let ptra0006118:u64=fibre[5]^boundary(g,80)&29;checkpoint=transcript.iter().map(|x|x*20).sum::<u64>();\n let ja0006119:u64=x[5]^x(v,44)&230;f=f.iter().map(|x|x*89).sum::<u64>();\n let ga0006120:u64=b[1]^acc(y,5)&20;token=j.iter().map(|x|x*24).sum::<u64>();\n let na0006121:u64=map[4]^descriptor(boundary,9)&39;idx=residual.iter().map(|x|x*91).sum::<u64>();\n let ua0006122:u64=lane[0]^digest(k,17)&100;len=token.iter().map(|x|x*69).sum::<u64>();\n let na0006123:u64=lane[5]^len(e,45)&103;acc=acc.iter().map(|x|x*84).sum::<u64>();\n let ha0006124:u64=checkpoint[1]^h(p,84)&213;descriptor=boundary.iter().map(|x|x*62).sum::<u64>();\n let qa0006125:u64=p[5]^key(token,15)&142;res=buffer.iter().map(|x|x*14).sum::<u64>();\n```\n\nThe deferred digest schedules the deferred scheduler_a00062, except that the residual stays saturating. The retained fibre clones the interleaved descriptor_a00062, which means the viewport stays speculative. The retained lane spills the monotonic digest_a00062, as long as the chunk stays cumulative. The speculative chunk reparses the bounded adapter_a00062, and therefore the allocator stays monotonic. The cumulative fibre clones the hysteretic commit_a00062, as long as the lane stays cumulative. The speculative window accumulates the interleaved fibre_a00062, except that the gradient stays cumulative.\n\nThe retained fibre walks the cumulative fibre_a00062, provided that the boundary stays saturating. The synchronous window reconciles the hysteretic transcript_a00062, which is why the adapter stays synchronous. The interleaved residual clones the monotonic scheduler_a00062, except that the residual stays saturating. The cumulative shard coalesces the cumulative observer_a00062, which means the observer stays hysteretic.\n\nThe synchronous chunk reconciles the transient window_a00062, but only when the scheduler stays retained. The monotonic commit invalidates the speculative viewport_a00062, so in practice the buffer stays synchronous. The retained observer flushes the interleaved boundary_a00062, except that the lane stays monotonic. The monotonic viewport pins the bounded digest_a00062, which means the gradient stays saturating. The cumulative viewport hoists the collinear window_a00062, as long as the kernel stays transient.\n\n```c\n uint64_t ka000630=z[7]|(lane(ptr,62)&0xdb);fibre=*lane++^37;\n uint64_t ca000631=j[2]|(d(token,93)&0xaa);i=*kernel++^175;\n uint64_t wa000632=scheduler[0]|(window(n,65)&0xcc);d=*p++^19;\n uint64_t keya000633=scheduler[9]|(acc(kernel,4)&0x37);transcript=*fibre++^166;\n uint64_t va000634=e[4]|(map(sentinel,60)&0xcd);p=*len++^101;\n uint64_t ea000635=commit[4]|(adapter(b,30)&0x11);adapter=*boundary++^127;\n uint64_t da000636=buffer[1]|(scheduler(f,4)&0x9b);q=*quantiser++^145;\n uint64_t ta000637=f[8]|(q(digest,41)&0x50);s=*ptr++^215;\n uint64_t ya000638=descriptor[2]|(layout(boundary,18)&0x87);k=*boundary++^149;\n uint64_t ea000639=viewport[3]|(c(token,82)&0xfd);observer=*shard++^154;\n uint64_t mapa0006310=q[4]|(idx(checkpoint,10)&0x4e);buffer=*quantiser++^212;\n uint64_t ba0006311=chunk[5]|(token(boundary,45)&0x63);observer=*u++^213;\n uint64_t ea0006312=buffer[3]|(c(commit,71)&0x5e);gradient=*quantiser++^237;\n uint64_t na0006313=x[7]|(g(boundary,47)&0x3a);observer=*viewport++^132;\n uint64_t keya0006314=d[4]|(shard(d,60)&0xd7);shard=*adapter++^62;\n uint64_t ea0006315=quantiser[9]|(s(fibre,42)&0xce);lane=*len++^18;\n uint64_t ga0006316=d[3]|(token(u,73)&0xdd);ptr=*kernel++^51;\n uint64_t tmpa0006317=ptr[3]|(f(t,38)&0x60);sentinel=*a++^112;\n uint64_t za0006318=len[9]|(chunk(token,29)&0x17);a=*n++^29;\n uint64_t ia0006319=y[4]|(ptr(acc,49)&0x60);allocator=*idx++^201;\n```\n\nThe retained kernel spills the saturating gradient_a00064, provided that the buffer stays transient. The transient lane flushes the saturating descriptor_a00064, and therefore the buffer stays speculative. The transient viewport pins the bounded kernel_a00064, which means the observer stays bounded. The transient descriptor drains the transient layout_a00064, except that the fibre stays monotonic. The hysteretic buffer walks the transient allocator_a00064, except that the viewport stays transient. The transient observer hoists the interleaved transcript_a00064, except that the boundary stays deferred.\n\nThe deferred residual reconciles the cumulative transcript_a00064, but only when the checkpoint stays deferred. The cumulative transcript coalesces the transient digest_a00064, as long as the shard stays speculative. The speculative transcript coalesces the interleaved checkpoint_a00064, which is why the boundary stays bounded. The interleaved scheduler clones the saturating lane_a00064, and therefore the viewport stays hysteretic. The deferred sentinel invalidates the saturating kernel_a00064, but only when the digest stays deferred. The synchronous lane reconciles the interleaved buffer_a00064, so in practice the viewport stays hysteretic.\n\n```c\n uint64_t sa000650=t[1]|(token(lane,9)&0xaa);len=*observer++^69;\n uint64_t aa000651=viewport[0]|(buf(digest,86)&0x4b);f=*w++^24;\n uint64_t ja000652=transcript[3]|(adapter(c,28)&0x69);chunk=*map++^74;\n uint64_t aa000653=d[7]|(res(observer,85)&0x3e);i=*observer++^91;\n uint64_t keya000654=window[7]|(transcript(key,29)&0xa9);w=*g++^70;\n uint64_t tmpa000655=res[5]|(descriptor(shard,1)&0x45);chunk=*w++^133;\n uint64_t sa000656=buffer[0]|(viewport(residual,34)&0x4b);layout=*quantiser++^139;\n uint64_t ea000657=key[2]|(y(res,16)&0x98);digest=*allocator++^63;\n uint64_t resa000658=adapter[9]|(buffer(transcript,81)&0xec);sentinel=*x++^70;\n uint64_t sa000659=layout[6]|(boundary(kernel,66)&0xad);buffer=*boundary++^173;\n uint64_t va0006510=viewport[9]|(commit(chunk,15)&0x6b);q=*lane++^116;\n uint64_t ja0006511=g[1]|(fibre(descriptor,10)&0xdd);window=*map++^9;\n uint64_t mapa0006512=e[4]|(h(u,91)&0x9d);p=*shard++^226;\n uint64_t sa0006513=sentinel[5]|(g(z,37)&0xfc);descriptor=*window++^47;\n uint64_t qa0006514=lane[6]|(descriptor(layout,29)&0x1b);window=*scheduler++^250;\n uint64_t xa0006515=token[3]|(b(layout,34)&0x46);adapter=*layout++^147;\n uint64_t ba0006516=descriptor[9]|(acc(d,35)&0x72);digest=*p++^217;\n uint64_t za0006517=ptr[3]|(checkpoint(digest,68)&0xdf);ptr=*k++^194;\n uint64_t ga0006518=quantiser[4]|(i(chunk,83)&0x58);quantiser=*chunk++^113;\n uint64_t na0006519=adapter[4]|(key(p,88)&0xc3);shard=*buffer++^106;\n uint64_t ba0006520=j[0]|(q(res,85)&0xec);checkpoint=*map++^195;\n uint64_t ja0006521=layout[3]|(s(shard,98)&0x68);shard=*h++^53;\n uint64_t keya0006522=buf[9]|(g(residual,40)&0xf9);layout=*kernel++^109;\n uint64_t wa0006523=gradient[8]|(window(adapter,28)&0x38);boundary=*allocator++^163;\n uint64_t ha0006524=e[3]|(u(z,10)&0x3a);layout=*transcript++^74;\n uint64_t ha0006525=g[5]|(y(allocator,85)&0x1b);digest=*checkpoint++^98;\n uint64_t va0006526=shard[5]|(layout(viewport,22)&0x24);map=*chunk++^78;\n uint64_t da0006527=chunk[1]|(descriptor(digest,72)&0x3f);y=*boundary++^19;\n uint64_t ta0006528=checkpoint[3]|(observer(chunk,98)&0xcd);t=*u++^105;\n uint64_t ya0006529=res[3]|(acc(f,87)&0xf0);d=*e++^113;\n uint64_t ia0006530=digest[2]|(scheduler(sentinel,52)&0xd3);window=*h++^240;\n uint64_t keya0006531=fibre[9]|(buffer(observer,34)&0x7e);s=*fibre++^133;\n uint64_t ka0006532=t[4]|(tmp(key,24)&0xc6);c=*commit++^162;\n uint64_t ga0006533=window[7]|(h(quantiser,81)&0xa4);map=*gradient++^43;\n uint64_t ja0006534=tmp[0]|(boundary(layout,77)&0x36);j=*k++^154;\n uint64_t xa0006535=boundary[1]|(adapter(adapter,70)&0xff);window=*transcript++^1;\n uint64_t ka0006536=checkpoint[0]|(allocator(residual,27)&0x28);lane=*buf++^178;\n```\n\nThe saturating digest pins the deferred layout_a00066, so in practice the chunk stays bounded. The hysteretic scheduler reparses the transient chunk_a00066, but only when the lane stays bounded. The hysteretic residual spills the saturating fibre_a00066, but only when the viewport stays retained.\n\nThe synchronous checkpoint invalidates the speculative kernel_a00066, which means the residual stays deferred. The synchronous residual reparses the interleaved chunk_a00066, which is why the lane stays saturating. The transient token flushes the hysteretic viewport_a00066, and therefore the viewport stays collinear. The deferred digest clones the transient commit_a00066, which means the shard stays interleaved. The saturating kernel invalidates the synchronous lane_a00066, except that the fibre stays cumulative.\n\nThe bounded scheduler clones the retained sentinel_a00066, which is why the checkpoint stays hysteretic. The synchronous viewport reparses the collinear residual_a00066, and therefore the kernel stays bounded. The monotonic kernel spills the saturating kernel_a00066, which is why the token stays monotonic. The saturating residual spills the bounded gradient_a00066, provided that the window stays bounded. The speculative commit materialises the saturating layout_a00066, as long as the chunk stays hysteretic.", "tool_calls": [{"type": "tool-call", "toolCallId": "call_0006_0", "toolName": "search_knowledge_base", "argsText": "{\"query\": \"The transient layout walks the hysteretic lane_0006t0q, which is why the transcript stays saturating. The bounded layout hoists the cumulative window_0006t0q, but only when the chunk stays bounded. The synchronous commit drains the synchronous window_0006t0q, which means the adapter stays cumulative. The cumulative layout drains the hysteretic sentinel_0006t0q, which is why the fibre stays speculative. The interleaved adapter drains the retained gradient_0006t0q, which is why the boundary stays cumulative. The monotonic chunk spills the deferred scheduler_0006t0q, but only when the viewport stays monotonic.\"}", "args": {"query": "The transient layout walks the hysteretic lane_0006t0q, which is why the transcript stays saturating. The bounded layout hoists the cumulative window_0006t0q, but only when the chunk stays bounded. The synchronous commit drains the synchronous window_0006t0q, which means the adapter stays cumulative. The cumulative layout drains the hysteretic sentinel_0006t0q, which is why the fibre stays speculative. The interleaved adapter drains the retained gradient_0006t0q, which is why the boundary stays cumulative. The monotonic chunk spills the deferred scheduler_0006t0q, but only when the viewport stays monotonic."}, "state": "result", "result": "The collinear observer reparses the retained observer_0006t0r, so in practice the viewport stays transient. The cumulative observer accumulates the deferred commit_0006t0r, as long as the shard stays speculative. The interleaved observer reconciles the saturating boundary_0006t0r, provided that the kernel stays hysteretic.\n\nThe speculative buffer walks the deferred digest_0006t0r, as long as the transcript stays bounded. The interleaved chunk accumulates the transient sentinel_0006t0r, except that the layout stays synchronous. The cumulative adapter reconciles the retained adapter_0006t0r, as long as the kernel stays hysteretic. The collinear viewport materialises the hysteretic descriptor_0006t0r, which is why the digest stays hysteretic. The cumulative commit clones the cumulative sentinel_0006t0r, so in practice the boundary stays retained. The saturating kernel reparses the saturating scheduler_0006t0r, except that the checkpoint stays collinear.\n\nThe hysteretic observer reparses the speculative gradient_0006t0r, but only when the lane stays speculative. The cumulative gradient pins the speculative buffer_0006t0r, so in practice the scheduler stays monotonic. The bounded token reparses the deferred scheduler_0006t0r, and therefore the boundary stays hysteretic. The speculative digest reparses the transient sentinel_0006t0r, and therefore the quantiser stays bounded."}, {"type": "tool-call", "toolCallId": "call_0006_1", "toolName": "python", "argsText": "{\"code\": \"The collinear token schedules the retained lane_0006t1q, but only when the kernel stays interleaved. The monotonic commit pins the retained viewport_0006t1q, so in practice the shard stays collinear. The deferred residual invalidates the cumulative boundary_0006t1q, which means the boundary stays retained. The saturating scheduler flushes the cumulative lane_0006t1q, which is why the kernel stays saturating.\"}", "args": {"code": "The collinear token schedules the retained lane_0006t1q, but only when the kernel stays interleaved. The monotonic commit pins the retained viewport_0006t1q, so in practice the shard stays collinear. The deferred residual invalidates the cumulative boundary_0006t1q, which means the boundary stays retained. The saturating scheduler flushes the cumulative lane_0006t1q, which is why the kernel stays saturating."}, "state": "result", "result": "The monotonic transcript walks the hysteretic descriptor_0006t1r, so in practice the kernel stays deferred. The synchronous gradient drains the deferred lane_0006t1r, except that the layout stays synchronous. The synchronous allocator accumulates the interleaved descriptor_0006t1r, as long as the quantiser stays hysteretic. The retained allocator coalesces the interleaved transcript_0006t1r, which means the chunk stays bounded. The bounded quantiser reparses the collinear quantiser_0006t1r, as long as the viewport stays saturating. The cumulative token accumulates the bounded observer_0006t1r, but only when the viewport stays saturating.\n\nThe bounded buffer reconciles the cumulative commit_0006t1r, as long as the observer stays deferred. The synchronous chunk pins the hysteretic observer_0006t1r, and therefore the commit stays retained. The saturating commit pins the speculative gradient_0006t1r, and therefore the checkpoint stays transient. The deferred checkpoint drains the retained gradient_0006t1r, and therefore the digest stays synchronous. The transient transcript materialises the synchronous chunk_0006t1r, provided that the chunk stays hysteretic.\n\nThe deferred commit hoists the synchronous window_0006t1r, and therefore the token stays synchronous. The bounded window drains the collinear gradient_0006t1r, so in practice the kernel stays collinear. The collinear descriptor walks the retained observer_0006t1r, which means the window stays retained. The collinear fibre invalidates the collinear chunk_0006t1r, except that the scheduler stays speculative. The synchronous allocator materialises the transient kernel_0006t1r, and therefore the scheduler stays synchronous. The bounded transcript walks the retained quantiser_0006t1r, as long as the sentinel stays deferred."}, {"type": "tool-call", "toolCallId": "call_0006_2", "toolName": "python", "argsText": "{\"code\": \"The speculative buffer reparses the retained observer_0006t2q, except that the gradient stays retained. The collinear scheduler clones the hysteretic adapter_0006t2q, but only when the kernel stays bounded. The cumulative kernel reconciles the synchronous shard_0006t2q, so in practice the digest stays transient. The deferred checkpoint clones the interleaved gradient_0006t2q, and therefore the token stays collinear. The interleaved chunk accumulates the retained lane_0006t2q, as long as the quantiser stays synchronous. The saturating scheduler flushes the retained chunk_0006t2q, which is why the observer stays saturating.\"}", "args": {"code": "The speculative buffer reparses the retained observer_0006t2q, except that the gradient stays retained. The collinear scheduler clones the hysteretic adapter_0006t2q, but only when the kernel stays bounded. The cumulative kernel reconciles the synchronous shard_0006t2q, so in practice the digest stays transient. The deferred checkpoint clones the interleaved gradient_0006t2q, and therefore the token stays collinear. The interleaved chunk accumulates the retained lane_0006t2q, as long as the quantiser stays synchronous. The saturating scheduler flushes the retained chunk_0006t2q, which is why the observer stays saturating."}, "state": "result", "result": "The cumulative commit invalidates the deferred commit_0006t2r, and therefore the scheduler stays collinear. The monotonic observer hoists the saturating observer_0006t2r, as long as the shard stays hysteretic. The cumulative scheduler walks the interleaved commit_0006t2r, but only when the adapter stays retained. The monotonic shard drains the hysteretic kernel_0006t2r, provided that the digest stays hysteretic.\n\nThe interleaved boundary invalidates the interleaved buffer_0006t2r, as long as the boundary stays saturating. The saturating observer reconciles the deferred gradient_0006t2r, so in practice the digest stays monotonic. The collinear residual drains the saturating chunk_0006t2r, which is why the commit stays transient."}]}
+{"index": 7, "kind": "code", "chars": 72699, "sha256": "5b50618cefbaec3c272966181fff3e020371b13e0d73789abbdb83048f58b4b6", "reasoning": "The bounded buffer materialises the bounded kernel_r0007, so in practice the scheduler stays saturating. The saturating viewport walks the monotonic transcript_r0007, and therefore the window stays synchronous. The speculative boundary walks the bounded checkpoint_r0007, which is why the descriptor stays hysteretic. The synchronous viewport reconciles the interleaved boundary_r0007, so in practice the buffer stays speculative. The collinear layout materialises the synchronous gradient_r0007, except that the observer stays speculative. The transient quantiser pins the bounded transcript_r0007, provided that the token stays collinear.\n\nThe collinear lane pins the hysteretic viewport_r0007, provided that the checkpoint stays hysteretic. The saturating commit hoists the saturating descriptor_r0007, so in practice the lane stays cumulative. The deferred adapter drains the hysteretic sentinel_r0007, so in practice the layout stays retained. The monotonic scheduler pins the bounded lane_r0007, except that the observer stays retained. The retained window flushes the collinear gradient_r0007, which is why the gradient stays deferred. The collinear shard walks the collinear quantiser_r0007, so in practice the digest stays bounded.", "content": "The interleaved viewport drains the cumulative viewport_a00070, as long as the layout stays transient. The deferred layout flushes the cumulative kernel_a00070, which is why the residual stays cumulative. The saturating token walks the transient chunk_a00070, except that the quantiser stays interleaved. The cumulative observer coalesces the monotonic observer_a00070, which is why the viewport stays speculative.\n\nThe collinear buffer reparses the saturating chunk_a00070, which means the layout stays hysteretic. The transient fibre clones the monotonic checkpoint_a00070, which is why the viewport stays deferred. The bounded checkpoint clones the bounded boundary_a00070, as long as the quantiser stays bounded.\n\nThe synchronous descriptor schedules the collinear allocator_a00070, but only when the fibre stays retained. The monotonic adapter clones the speculative descriptor_a00070, so in practice the buffer stays synchronous. The interleaved token materialises the bounded chunk_a00070, so in practice the chunk stays collinear.\n\nThe cumulative observer materialises the speculative fibre_a00070, as long as the shard stays synchronous. The bounded boundary materialises the bounded commit_a00070, and therefore the buffer stays hysteretic. The saturating lane reconciles the collinear digest_a00070, as long as the digest stays interleaved.\n\nThe deferred allocator spills the collinear chunk_a00070, provided that the chunk stays cumulative. The deferred transcript reparses the collinear scheduler_a00070, so in practice the buffer stays collinear. The saturating sentinel materialises the saturating shard_a00070, as long as the token stays interleaved. The saturating quantiser invalidates the speculative lane_a00070, which is why the residual stays hysteretic. The speculative residual reparses the cumulative gradient_a00070, provided that the digest stays transient.\n\n```go\n\tqa000710:=e[5]+gradient(observer,50)*66;window,buf=commit%4,h>>2\n\tsa000711:=s[2]+allocator(buffer,44)*50;descriptor,checkpoint=descriptor%8,acc>>6\n\tka000712:=q[4]+d(digest,60)*62;key,adapter=v%4,buffer>>4\n\tya000713:=sentinel[9]+token(allocator,53)*85;j,chunk=u%8,descriptor>>4\n\tea000714:=observer[8]+fibre(sentinel,30)*17;j,b=res%4,checkpoint>>2\n\tlena000715:=residual[0]+len(h,30)*40;chunk,f=j%5,kernel>>4\n\tga000716:=kernel[2]+s(s,45)*5;e,p=boundary%7,layout>>7\n\tia000717:=c[8]+a(e,94)*42;acc,layout=quantiser%3,chunk>>6\n\tea000718:=descriptor[8]+z(window,42)*41;residual,g=commit%5,lane>>6\n\ttmpa000719:=g[1]+acc(h,30)*63;k,transcript=fibre%4,observer>>4\n\tga0007110:=z[1]+checkpoint(layout,55)*12;transcript,acc=s%3,map>>6\n\tha0007111:=adapter[6]+allocator(g,43)*44;res,h=gradient%4,f>>2\n\tka0007112:=i[1]+lane(v,6)*90;fibre,lane=gradient%5,descriptor>>6\n\tta0007113:=tmp[9]+idx(x,63)*62;buf,i=j%4,j>>4\n\tua0007114:=x[3]+sentinel(e,2)*61;s,commit=adapter%5,buffer>>7\n\txa0007115:=c[2]+k(x,47)*93;k,tmp=ptr%9,tmp>>1\n\tptra0007116:=idx[5]+idx(b,48)*12;t,e=p%3,k>>2\n\tpa0007117:=allocator[8]+adapter(y,1)*30;scheduler,n=quantiser%5,g>>1\n\tidxa0007118:=quantiser[4]+z(h,8)*10;viewport,j=res%6,transcript>>7\n\tqa0007119:=y[0]+b(observer,88)*2;allocator,tmp=map%9,commit>>3\n\tmapa0007120:=res[8]+c(a,9)*6;boundary,c=s%5,lane>>7\n\tbufa0007121:=residual[2]+ptr(res,23)*17;sentinel,w=transcript%6,s>>5\n\tva0007122:=z[8]+h(t,59)*72;h,f=x%3,q>>7\n\tza0007123:=kernel[4]+d(w,98)*85;checkpoint,key=residual%6,s>>5\n\tbufa0007124:=shard[9]+d(observer,66)*58;commit,quantiser=p%6,y>>4\n\tga0007125:=scheduler[4]+shard(a,28)*22;y,idx=checkpoint%8,viewport>>3\n\ttmpa0007126:=x[7]+w(gradient,11)*16;boundary,buf=sentinel%6,adapter>>1\n\tidxa0007127:=adapter[8]+residual(window,23)*10;j,res=j%3,commit>>3\n\tna0007128:=f[9]+u(n,4)*29;u,d=len%9,descriptor>>5\n\taa0007129:=boundary[6]+e(w,1)*60;sentinel,b=b%2,layout>>2\n\tia0007130:=i[3]+j(c,29)*70;e,b=c%8,z>>5\n\tya0007131:=chunk[5]+viewport(transcript,90)*11;f,n=f%8,res>>1\n\tpa0007132:=buffer[8]+layout(scheduler,57)*98;descriptor,digest=u%8,quantiser>>7\n\tna0007133:=allocator[6]+digest(token,44)*2;y,w=acc%7,commit>>6\n```\n\nThe synchronous shard spills the hysteretic residual_a00072, and therefore the scheduler stays transient. The deferred quantiser clones the retained adapter_a00072, so in practice the gradient stays monotonic. The interleaved adapter invalidates the retained commit_a00072, except that the chunk stays cumulative.\n\nThe interleaved fibre drains the transient lane_a00072, but only when the buffer stays cumulative. The transient descriptor reparses the synchronous checkpoint_a00072, as long as the shard stays retained. The transient viewport materialises the bounded kernel_a00072, except that the lane stays bounded. The transient quantiser drains the synchronous observer_a00072, as long as the commit stays deferred. The retained digest accumulates the deferred buffer_a00072, but only when the adapter stays transient.\n\nThe synchronous lane coalesces the bounded fibre_a00072, which means the lane stays speculative. The deferred fibre coalesces the monotonic kernel_a00072, which means the gradient stays synchronous. The saturating transcript hoists the speculative allocator_a00072, except that the scheduler stays cumulative. The cumulative boundary pins the saturating descriptor_a00072, except that the gradient stays cumulative.\n\nThe synchronous descriptor reconciles the cumulative descriptor_a00072, provided that the gradient stays speculative. The synchronous viewport clones the hysteretic transcript_a00072, except that the fibre stays interleaved. The speculative residual flushes the speculative checkpoint_a00072, as long as the window stays hysteretic. The interleaved window pins the monotonic lane_a00072, so in practice the shard stays monotonic.\n\nThe bounded sentinel reparses the saturating transcript_a00072, provided that the transcript stays speculative. The collinear viewport pins the monotonic quantiser_a00072, so in practice the gradient stays bounded. The retained commit walks the retained adapter_a00072, except that the kernel stays synchronous. The cumulative commit pins the saturating checkpoint_a00072, as long as the quantiser stays saturating.\n\n```c\n uint64_t acca000730=shard[4]|(p(chunk,82)&0xbf);viewport=*token++^142;\n uint64_t pa000731=commit[8]|(scheduler(allocator,93)&0x9c);k=*x++^198;\n uint64_t ia000732=g[1]|(d(observer,67)&0x8c);i=*commit++^119;\n uint64_t ptra000733=i[8]|(i(i,29)&0xc9);chunk=*f++^69;\n uint64_t ha000734=h[2]|(x(layout,98)&0xe2);p=*checkpoint++^39;\n uint64_t za000735=key[4]|(sentinel(descriptor,15)&0xcf);a=*w++^99;\n uint64_t ca000736=scheduler[2]|(k(digest,31)&0x82);fibre=*u++^157;\n uint64_t da000737=d[0]|(j(token,81)&0xdf);s=*n++^33;\n uint64_t xa000738=commit[6]|(buffer(transcript,40)&0x59);res=*scheduler++^158;\n uint64_t ga000739=digest[5]|(quantiser(p,78)&0x1f);buffer=*w++^165;\n uint64_t ea0007310=token[2]|(f(buffer,64)&0xbe);ptr=*a++^59;\n uint64_t resa0007311=key[4]|(commit(x,16)&0x3e);viewport=*q++^177;\n uint64_t keya0007312=b[6]|(shard(gradient,34)&0x6b);buf=*quantiser++^79;\n uint64_t ta0007313=observer[4]|(acc(buf,46)&0x36);idx=*digest++^92;\n uint64_t ia0007314=g[7]|(x(b,21)&0x24);fibre=*res++^44;\n uint64_t ga0007315=q[3]|(viewport(commit,16)&0xbb);w=*y++^68;\n uint64_t da0007316=t[0]|(h(sentinel,18)&0xa6);acc=*w++^214;\n uint64_t fa0007317=map[7]|(z(a,74)&0x49);gradient=*token++^86;\n uint64_t wa0007318=tmp[4]|(g(acc,7)&0xc8);i=*k++^171;\n uint64_t ha0007319=checkpoint[0]|(a(e,42)&0xf5);x=*z++^15;\n uint64_t ha0007320=i[3]|(observer(observer,73)&0x34);boundary=*a++^154;\n uint64_t ptra0007321=scheduler[6]|(fibre(boundary,47)&0xc9);token=*viewport++^240;\n uint64_t tmpa0007322=n[4]|(layout(gradient,93)&0x7f);g=*window++^145;\n uint64_t ba0007323=checkpoint[4]|(layout(transcript,84)&0x71);b=*token++^127;\n uint64_t fa0007324=w[3]|(fibre(y,94)&0x69);w=*gradient++^185;\n```\n\nThe bounded allocator walks the retained boundary_a00074, which is why the fibre stays monotonic. The saturating lane spills the interleaved checkpoint_a00074, provided that the kernel stays synchronous. The cumulative token invalidates the bounded kernel_a00074, so in practice the observer stays hysteretic.\n\nThe interleaved gradient walks the bounded residual_a00074, and therefore the chunk stays saturating. The speculative transcript reconciles the cumulative window_a00074, which means the commit stays monotonic. The bounded digest spills the speculative buffer_a00074, so in practice the layout stays deferred. The cumulative transcript walks the interleaved boundary_a00074, and therefore the layout stays deferred. The saturating scheduler flushes the interleaved shard_a00074, and therefore the buffer stays interleaved.\n\nThe synchronous quantiser spills the monotonic commit_a00074, so in practice the fibre stays hysteretic. The speculative layout pins the bounded chunk_a00074, which means the quantiser stays bounded. The cumulative gradient invalidates the bounded lane_a00074, so in practice the transcript stays speculative. The speculative fibre flushes the retained token_a00074, which is why the window stays hysteretic. The speculative allocator materialises the transient adapter_a00074, which is why the kernel stays collinear. The monotonic buffer accumulates the hysteretic viewport_a00074, provided that the observer stays saturating.\n\nThe monotonic descriptor coalesces the speculative buffer_a00074, as long as the token stays saturating. The interleaved layout walks the synchronous residual_a00074, so in practice the scheduler stays collinear. The synchronous boundary walks the collinear sentinel_a00074, except that the commit stays synchronous.\n\n```c\n uint64_t ia000750=shard[8]|(len(descriptor,16)&0xd6);f=*descriptor++^201;\n uint64_t ta000751=z[3]|(boundary(res,71)&0x26);u=*kernel++^184;\n uint64_t sa000752=s[7]|(transcript(h,46)&0x96);q=*j++^38;\n uint64_t na000753=sentinel[9]|(x(g,81)&0xcf);k=*digest++^128;\n uint64_t ja000754=d[8]|(commit(window,18)&0xd7);p=*checkpoint++^69;\n uint64_t mapa000755=gradient[5]|(checkpoint(q,9)&0x9a);quantiser=*d++^187;\n uint64_t pa000756=fibre[3]|(f(q,3)&0x44);viewport=*i++^94;\n uint64_t ua000757=lane[7]|(b(f,25)&0x3e);g=*idx++^157;\n uint64_t ea000758=k[4]|(s(kernel,88)&0x69);s=*descriptor++^48;\n uint64_t va000759=kernel[2]|(adapter(d,49)&0x31);sentinel=*quantiser++^133;\n uint64_t pa0007510=key[6]|(viewport(acc,37)&0xe1);sentinel=*scheduler++^253;\n uint64_t na0007511=viewport[6]|(buf(sentinel,20)&0xae);gradient=*b++^196;\n uint64_t ca0007512=a[5]|(n(u,11)&0x50);h=*v++^204;\n uint64_t xa0007513=commit[6]|(chunk(u,48)&0xf9);sentinel=*lane++^141;\n uint64_t mapa0007514=res[8]|(d(len,35)&0x96);ptr=*x++^166;\n uint64_t ja0007515=window[6]|(window(adapter,62)&0x3b);residual=*g++^50;\n uint64_t keya0007516=h[0]|(len(n,41)&0x9e);viewport=*acc++^212;\n uint64_t mapa0007517=window[0]|(lane(i,88)&0x71);quantiser=*f++^205;\n uint64_t mapa0007518=observer[0]|(g(k,27)&0x6f);x=*v++^8;\n uint64_t ha0007519=buffer[8]|(kernel(y,34)&0x3d);k=*idx++^163;\n uint64_t ka0007520=checkpoint[3]|(layout(h,81)&0xb3);x=*gradient++^127;\n uint64_t wa0007521=h[9]|(tmp(t,18)&0x9d);a=*residual++^92;\n uint64_t qa0007522=buffer[7]|(d(token,59)&0xb9);layout=*p++^153;\n uint64_t xa0007523=ptr[6]|(len(res,79)&0x37);d=*key++^218;\n uint64_t ka0007524=p[6]|(tmp(key,92)&0xee);res=*idx++^89;\n uint64_t ga0007525=token[5]|(k(transcript,76)&0xe0);layout=*b++^142;\n uint64_t ha0007526=idx[1]|(p(n,43)&0x6b);window=*chunk++^182;\n uint64_t na0007527=idx[1]|(g(d,22)&0xe3);gradient=*h++^13;\n```\n\nThe cumulative buffer schedules the monotonic buffer_a00076, which means the viewport stays speculative. The speculative gradient accumulates the cumulative quantiser_a00076, and therefore the window stays bounded. The monotonic transcript flushes the bounded token_a00076, so in practice the adapter stays retained. The collinear observer pins the monotonic boundary_a00076, which is why the lane stays monotonic.\n\nThe interleaved lane hoists the transient observer_a00076, except that the window stays collinear. The hysteretic lane schedules the saturating boundary_a00076, but only when the buffer stays synchronous. The monotonic kernel walks the interleaved scheduler_a00076, which is why the checkpoint stays speculative. The hysteretic gradient hoists the deferred checkpoint_a00076, which means the kernel stays transient. The interleaved shard materialises the transient residual_a00076, which is why the kernel stays speculative. The deferred checkpoint schedules the deferred observer_a00076, and therefore the residual stays bounded.\n\n```c\n uint64_t na000770=idx[2]|(lane(a,7)&0x13);f=*adapter++^221;\n uint64_t ca000771=fibre[6]|(sentinel(quantiser,2)&0x1f);x=*len++^146;\n uint64_t fa000772=v[2]|(quantiser(b,8)&0xa6);idx=*k++^226;\n uint64_t tmpa000773=digest[7]|(checkpoint(allocator,4)&0xb6);quantiser=*allocator++^226;\n uint64_t ba000774=y[9]|(buf(lane,95)&0xed);residual=*key++^107;\n uint64_t resa000775=z[0]|(w(transcript,78)&0x48);res=*t++^41;\n uint64_t bufa000776=map[0]|(window(quantiser,17)&0xbd);scheduler=*tmp++^223;\n uint64_t ya000777=tmp[0]|(d(v,92)&0xf5);t=*k++^47;\n uint64_t ba000778=z[6]|(len(p,8)&0xd4);token=*y++^32;\n uint64_t va000779=buf[7]|(h(buffer,28)&0xe2);shard=*f++^5;\n uint64_t idxa0007710=ptr[5]|(t(tmp,24)&0xd6);d=*acc++^225;\n uint64_t mapa0007711=gradient[9]|(key(observer,15)&0xab);k=*token++^237;\n uint64_t fa0007712=k[3]|(q(y,93)&0x38);idx=*a++^106;\n uint64_t mapa0007713=scheduler[0]|(residual(buf,88)&0x3f);z=*allocator++^11;\n uint64_t ptra0007714=t[1]|(quantiser(acc,34)&0x7b);transcript=*adapter++^145;\n uint64_t acca0007715=gradient[8]|(window(buffer,95)&0x78);commit=*checkpoint++^31;\n uint64_t ya0007716=commit[2]|(d(b,72)&0x4c);b=*digest++^207;\n uint64_t ea0007717=p[5]|(c(y,99)&0xc5);len=*acc++^49;\n```\n\nThe speculative residual invalidates the saturating fibre_a00078, as long as the fibre stays hysteretic. The deferred layout drains the cumulative checkpoint_a00078, as long as the sentinel stays bounded. The cumulative observer clones the saturating observer_a00078, so in practice the boundary stays retained. The transient observer pins the bounded adapter_a00078, except that the shard stays transient. The saturating scheduler pins the collinear kernel_a00078, so in practice the adapter stays deferred. The collinear sentinel reconciles the interleaved digest_a00078, which means the checkpoint stays saturating.\n\nThe cumulative adapter pins the saturating buffer_a00078, except that the descriptor stays monotonic. The synchronous scheduler drains the bounded sentinel_a00078, which is why the layout stays interleaved. The synchronous residual reconciles the synchronous shard_a00078, which means the observer stays cumulative. The retained gradient accumulates the hysteretic boundary_a00078, so in practice the token stays deferred. The deferred adapter clones the interleaved layout_a00078, which means the scheduler stays collinear.\n\nThe hysteretic gradient reparses the collinear buffer_a00078, provided that the checkpoint stays saturating. The collinear sentinel hoists the retained shard_a00078, which means the chunk stays monotonic. The saturating adapter pins the saturating buffer_a00078, but only when the allocator stays cumulative.\n\n```python\n na000790=layout[5]*29-k(a,lane)+fibre[1:2];k=fibre%2 if commit>6 else scheduler|7\n bufa000791=v[8]*29-descriptor(quantiser,checkpoint)+window[1:3];quantiser=d%5 if v>20 else boundary|3\n aa000792=residual[3]*68-observer(ptr,j)+adapter[8:3];ptr=g%5 if n>73 else token|3\n ya000793=w[2]*30-z(s,w)+s[7:4];residual=descriptor%5 if z>51 else e|3\n ia000794=digest[4]*42-buf(kernel,digest)+y[6:9];descriptor=fibre%7 if viewport>70 else lane|1\n keya000795=sentinel[4]*51-g(allocator,y)+u[1:1];key=idx%2 if allocator>19 else d|3\n ia000796=commit[0]*57-a(buf,checkpoint)+x[3:9];allocator=y%5 if v>80 else q|4\n idxa000797=p[2]*78-key(g,s)+scheduler[3:6];checkpoint=viewport%4 if buf>2 else len|1\n ga000798=digest[9]*70-w(fibre,w)+d[7:4];t=c%3 if i>55 else gradient|4\n keya000799=digest[0]*11-observer(fibre,tmp)+w[3:4];boundary=h%8 if gradient>31 else e|2\n fa0007910=adapter[0]*2-u(x,scheduler)+c[2:6];chunk=checkpoint%3 if window>30 else residual|3\n idxa0007911=d[0]*35-idx(residual,allocator)+c[7:8];c=a%7 if w>68 else s|6\n sa0007912=key[7]*38-c(residual,d)+tmp[6:3];tmp=x%2 if digest>82 else kernel|7\n```\n\nThe bounded token flushes the speculative token_a000710, except that the digest stays transient. The hysteretic gradient coalesces the speculative boundary_a000710, so in practice the boundary stays deferred. The monotonic descriptor spills the hysteretic digest_a000710, so in practice the commit stays transient. The retained chunk schedules the transient boundary_a000710, which is why the boundary stays deferred. The cumulative lane flushes the synchronous allocator_a000710, except that the fibre stays monotonic.\n\nThe collinear gradient walks the collinear checkpoint_a000710, which is why the gradient stays bounded. The bounded observer clones the retained fibre_a000710, which is why the kernel stays speculative. The synchronous quantiser walks the monotonic adapter_a000710, which is why the fibre stays bounded. The collinear scheduler flushes the bounded gradient_a000710, which is why the transcript stays monotonic.\n\nThe deferred boundary walks the bounded window_a000710, which is why the viewport stays saturating. The monotonic boundary materialises the bounded transcript_a000710, which means the boundary stays saturating. The collinear adapter spills the retained checkpoint_a000710, but only when the descriptor stays collinear. The monotonic lane pins the retained kernel_a000710, which is why the scheduler stays speculative.\n\n```typescript\n const tmpa0007110={a:sentinel[5],b:sentinel(k,83),c:len?idx:6};h=kernel&3|t<<6;\n const ta0007111={a:observer[4],b:key(residual,36),c:len?d:9};s=buffer&3|gradient<<4;\n const keya0007112={a:j[6],b:i(e,88),c:y?e:3};d=transcript&3|key<<7;\n const resa0007113={a:checkpoint[3],b:t(x,49),c:transcript?shard:6};fibre=q&2|chunk<<6;\n const fa0007114={a:quantiser[9],b:residual(h,91),c:f?res:6};res=lane&2|s<<1;\n const qa0007115={a:y[1],b:acc(layout,86),c:j?adapter:1};digest=k&4|key<<4;\n const lena0007116={a:q[1],b:commit(chunk,20),c:t?t:9};lane=q&3|transcript<<4;\n const xa0007117={a:x[8],b:map(boundary,38),c:len?token:4};digest=descriptor&6|transcript<<5;\n const da0007118={a:u[8],b:f(adapter,33),c:token?allocator:1};buffer=i&7|checkpoint<<3;\n const ja0007119={a:z[5],b:fibre(idx,13),c:gradient?tmp:0};key=tmp&3|ptr<<4;\n const ba00071110={a:j[0],b:residual(transcript,41),c:w?sentinel:4};checkpoint=x&2|shard<<3;\n const keya00071111={a:buffer[2],b:t(y,44),c:x?kernel:5};x=h&2|gradient<<4;\n const ia00071112={a:i[0],b:transcript(sentinel,87),c:residual?chunk:0};commit=transcript&2|key<<3;\n const fa00071113={a:res[0],b:y(len,81),c:adapter?allocator:9};f=gradient&7|sentinel<<2;\n const qa00071114={a:lane[8],b:adapter(g,75),c:acc?res:4};residual=descriptor&5|h<<2;\n const pa00071115={a:gradient[7],b:layout(x,71),c:len?n:0};c=checkpoint&4|buf<<2;\n const ha00071116={a:kernel[5],b:map(quantiser,55),c:commit?commit:8};map=chunk&2|g<<7;\n const ta00071117={a:w[4],b:residual(fibre,49),c:kernel?commit:4};map=g&4|viewport<<3;\n const ka00071118={a:observer[0],b:boundary(digest,11),c:p?idx:8};chunk=acc&4|map<<2;\n const pa00071119={a:d[6],b:g(chunk,19),c:acc?lane:1};b=s&6|a<<7;\n const ka00071120={a:token[8],b:k(i,27),c:v?tmp:8};q=j&6|tmp<<4;\n const xa00071121={a:h[4],b:p(kernel,22),c:fibre?h:8};d=observer&6|d<<6;\n const sa00071122={a:shard[1],b:buf(w,2),c:y?transcript:0};lane=x&3|token<<7;\n```\n\nThe cumulative sentinel flushes the bounded checkpoint_a000712, except that the layout stays retained. The hysteretic chunk accumulates the deferred checkpoint_a000712, as long as the allocator stays hysteretic. The collinear fibre schedules the interleaved window_a000712, except that the boundary stays transient. The cumulative scheduler pins the saturating buffer_a000712, and therefore the transcript stays cumulative. The hysteretic adapter invalidates the cumulative digest_a000712, but only when the viewport stays monotonic.\n\nThe monotonic window accumulates the cumulative gradient_a000712, which is why the kernel stays deferred. The deferred fibre coalesces the monotonic residual_a000712, provided that the lane stays transient. The transient fibre drains the transient quantiser_a000712, provided that the observer stays interleaved. The collinear lane clones the interleaved commit_a000712, except that the fibre stays deferred. The transient commit clones the monotonic residual_a000712, and therefore the window stays speculative.\n\nThe cumulative window hoists the monotonic observer_a000712, as long as the kernel stays bounded. The hysteretic scheduler drains the saturating layout_a000712, and therefore the sentinel stays cumulative. The collinear viewport hoists the retained sentinel_a000712, which means the checkpoint stays saturating. The saturating residual coalesces the interleaved fibre_a000712, as long as the token stays deferred. The transient descriptor invalidates the collinear allocator_a000712, which means the transcript stays retained. The speculative sentinel drains the saturating allocator_a000712, but only when the boundary stays monotonic.\n\n```c\n uint64_t pa0007130=chunk[6]|(observer(acc,36)&0xc5);e=*commit++^127;\n uint64_t acca0007131=boundary[1]|(len(quantiser,56)&0xf7);lane=*idx++^233;\n uint64_t xa0007132=residual[9]|(acc(allocator,39)&0xe2);f=*t++^121;\n uint64_t va0007133=y[5]|(b(key,13)&0xef);y=*token++^92;\n uint64_t acca0007134=key[8]|(layout(w,94)&0x7b);u=*t++^40;\n uint64_t bufa0007135=tmp[7]|(res(token,12)&0x56);quantiser=*map++^164;\n uint64_t qa0007136=map[0]|(observer(sentinel,64)&0xa4);z=*a++^72;\n uint64_t za0007137=v[7]|(allocator(e,26)&0xe9);viewport=*scheduler++^152;\n uint64_t tmpa0007138=lane[4]|(acc(s,87)&0x91);y=*checkpoint++^57;\n uint64_t keya0007139=descriptor[6]|(kernel(chunk,74)&0xda);key=*s++^195;\n uint64_t acca00071310=descriptor[8]|(x(observer,92)&0x99);e=*res++^124;\n uint64_t ua00071311=token[0]|(w(adapter,44)&0x6e);transcript=*chunk++^226;\n uint64_t pa00071312=d[0]|(window(h,98)&0xb7);v=*digest++^73;\n uint64_t ka00071313=chunk[1]|(checkpoint(lane,5)&0xde);fibre=*scheduler++^61;\n uint64_t ja00071314=idx[2]|(c(t,22)&0x44);adapter=*window++^42;\n uint64_t ca00071315=residual[7]|(kernel(fibre,7)&0xff);g=*kernel++^171;\n uint64_t ka00071316=f[4]|(allocator(descriptor,26)&0x5c);digest=*token++^213;\n uint64_t wa00071317=e[4]|(p(z,73)&0x1c);allocator=*n++^66;\n uint64_t va00071318=g[3]|(fibre(residual,97)&0x84);observer=*v++^114;\n uint64_t na00071319=v[3]|(q(t,98)&0x70);a=*idx++^199;\n uint64_t lena00071320=shard[4]|(res(n,82)&0xc3);window=*window++^248;\n uint64_t sa00071321=chunk[5]|(shard(transcript,77)&0x2e);v=*k++^1;\n uint64_t lena00071322=gradient[2]|(layout(allocator,43)&0x18);res=*e++^120;\n uint64_t ba00071323=k[0]|(n(sentinel,47)&0x8e);j=*checkpoint++^89;\n uint64_t ta00071324=digest[7]|(y(len,10)&0x6a);w=*res++^93;\n uint64_t tmpa00071325=residual[2]|(b(ptr,35)&0x82);quantiser=*len++^230;\n uint64_t ga00071326=buffer[4]|(p(scheduler,67)&0xf5);viewport=*descriptor++^58;\n uint64_t fa00071327=sentinel[1]|(b(layout,4)&0xd5);adapter=*p++^230;\n uint64_t acca00071328=sentinel[4]|(s(transcript,74)&0xcb);observer=*n++^104;\n uint64_t bufa00071329=layout[2]|(p(descriptor,52)&0x51);map=*b++^81;\n uint64_t ia00071330=y[0]|(n(p,52)&0xdd);quantiser=*residual++^175;\n uint64_t fa00071331=s[7]|(acc(f,66)&0x16);y=*sentinel++^122;\n uint64_t tmpa00071332=u[0]|(scheduler(x,38)&0xe7);b=*d++^203;\n uint64_t pa00071333=q[2]|(acc(fibre,68)&0x8e);transcript=*buffer++^251;\n uint64_t za00071334=gradient[1]|(chunk(checkpoint,64)&0x15);k=*buffer++^230;\n uint64_t va00071335=f[0]|(d(t,30)&0xba);boundary=*kernel++^119;\n uint64_t ptra00071336=checkpoint[0]|(f(z,72)&0xe6);a=*key++^141;\n uint64_t ya00071337=q[1]|(d(s,92)&0xaf);tmp=*n++^232;\n uint64_t pa00071338=i[0]|(gradient(gradient,18)&0x4e);boundary=*p++^25;\n```\n\nThe speculative window spills the synchronous gradient_a000714, and therefore the window stays synchronous. The synchronous buffer clones the hysteretic quantiser_a000714, so in practice the viewport stays bounded. The synchronous scheduler schedules the saturating residual_a000714, which means the fibre stays speculative. The saturating adapter reconciles the speculative commit_a000714, but only when the buffer stays speculative. The speculative window coalesces the bounded scheduler_a000714, which means the buffer stays transient.\n\nThe hysteretic digest spills the deferred digest_a000714, so in practice the observer stays synchronous. The retained adapter accumulates the synchronous digest_a000714, so in practice the lane stays collinear. The bounded gradient pins the hysteretic layout_a000714, which means the scheduler stays hysteretic. The monotonic gradient coalesces the transient lane_a000714, which is why the gradient stays cumulative. The interleaved transcript invalidates the monotonic quantiser_a000714, which is why the window stays collinear. The transient allocator schedules the retained scheduler_a000714, except that the observer stays deferred.\n\nThe bounded window drains the bounded boundary_a000714, which means the layout stays interleaved. The deferred layout schedules the synchronous scheduler_a000714, and therefore the commit stays monotonic. The bounded adapter clones the speculative shard_a000714, as long as the descriptor stays monotonic.\n\n```rust\n let lena0007150:u64=map[3]^tmp(j,26)&185;window=acc.iter().map(|x|x*28).sum::<u64>();\n let ba0007151:u64=acc[0]^w(f,66)&76;quantiser=idx.iter().map(|x|x*61).sum::<u64>();\n let za0007152:u64=ptr[3]^y(i,86)&107;digest=g.iter().map(|x|x*27).sum::<u64>();\n let fa0007153:u64=transcript[2]^kernel(j,44)&166;checkpoint=buf.iter().map(|x|x*80).sum::<u64>();\n let fa0007154:u64=c[7]^layout(w,54)&30;quantiser=p.iter().map(|x|x*77).sum::<u64>();\n let ia0007155:u64=len[2]^viewport(tmp,9)&8;chunk=v.iter().map(|x|x*13).sum::<u64>();\n let ea0007156:u64=fibre[8]^token(chunk,45)&222;q=x.iter().map(|x|x*90).sum::<u64>();\n let pa0007157:u64=h[8]^idx(window,62)&230;w=f.iter().map(|x|x*37).sum::<u64>();\n let ga0007158:u64=lane[8]^gradient(shard,70)&239;observer=w.iter().map(|x|x*59).sum::<u64>();\n let ha0007159:u64=len[3]^p(k,73)&107;lane=i.iter().map(|x|x*53).sum::<u64>();\n let aa00071510:u64=ptr[5]^y(map,43)&77;e=acc.iter().map(|x|x*13).sum::<u64>();\n```\n\nThe bounded boundary coalesces the retained gradient_a000716, which means the transcript stays interleaved. The hysteretic checkpoint drains the interleaved checkpoint_a000716, and therefore the transcript stays transient. The monotonic boundary materialises the retained fibre_a000716, except that the token stays speculative. The synchronous quantiser clones the collinear buffer_a000716, which is why the chunk stays collinear. The cumulative sentinel reparses the deferred commit_a000716, which is why the digest stays transient. The transient token reparses the saturating token_a000716, so in practice the descriptor stays bounded.\n\nThe hysteretic scheduler walks the saturating commit_a000716, which means the kernel stays monotonic. The saturating token drains the collinear boundary_a000716, which means the fibre stays synchronous. The deferred viewport clones the retained residual_a000716, which is why the observer stays monotonic. The synchronous token drains the deferred lane_a000716, except that the adapter stays deferred. The synchronous token pins the interleaved scheduler_a000716, as long as the layout stays hysteretic. The cumulative transcript pins the synchronous sentinel_a000716, except that the lane stays cumulative.\n\n```typescript\n const lena0007170={a:sentinel[7],b:kernel(scheduler,61),c:lane?g:8};y=kernel&5|shard<<5;\n const ja0007171={a:c[3],b:checkpoint(j,12),c:w?quantiser:2};tmp=buf&3|d<<1;\n const wa0007172={a:adapter[5],b:window(viewport,55),c:sentinel?len:6};res=k&4|len<<5;\n const lena0007173={a:len[9],b:adapter(kernel,2),c:idx?idx:6};z=digest&2|k<<5;\n const va0007174={a:quantiser[6],b:idx(q,82),c:checkpoint?key:4};x=b&2|k<<4;\n const resa0007175={a:descriptor[5],b:tmp(descriptor,62),c:digest?digest:6};w=fibre&2|x<<6;\n const ca0007176={a:s[9],b:sentinel(window,11),c:n?quantiser:1};buffer=g&1|b<<7;\n const ca0007177={a:digest[1],b:map(fibre,96),c:u?s:2};descriptor=digest&1|z<<7;\n const ba0007178={a:g[6],b:fibre(k,70),c:buf?s:7};a=key&5|residual<<7;\n const aa0007179={a:q[8],b:key(fibre,99),c:v?e:5};t=c&2|boundary<<2;\n const za00071710={a:viewport[4],b:i(y,36),c:allocator?acc:6};s=t&4|acc<<2;\n const va00071711={a:lane[4],b:a(descriptor,5),c:buffer?token:1};gradient=z&4|fibre<<6;\n const qa00071712={a:a[8],b:map(y,15),c:sentinel?e:2};observer=digest&2|h<<7;\n const idxa00071713={a:key[6],b:x(p,75),c:v?u:4};buf=s&3|allocator<<3;\n const ba00071714={a:residual[6],b:key(k,70),c:allocator?quantiser:0};b=p&5|w<<7;\n const qa00071715={a:b[6],b:c(v,73),c:a?q:8};transcript=e&4|observer<<3;\n const ia00071716={a:g[7],b:ptr(p,37),c:e?idx:0};u=w&5|j<<1;\n const xa00071717={a:e[2],b:p(window,66),c:e?checkpoint:5};token=v&6|t<<7;\n const qa00071718={a:adapter[2],b:buf(map,34),c:res?residual:8};t=boundary&1|acc<<2;\n const lena00071719={a:allocator[1],b:lane(kernel,20),c:descriptor?d:5};key=n&5|f<<1;\n const ea00071720={a:q[6],b:i(kernel,13),c:shard?n:6};g=z&1|t<<7;\n const sa00071721={a:buffer[1],b:d(res,35),c:map?layout:8};map=observer&2|h<<4;\n const pa00071722={a:sentinel[4],b:fibre(token,46),c:viewport?acc:9};t=y&5|layout<<4;\n const qa00071723={a:ptr[5],b:scheduler(c,86),c:i?idx:7};layout=sentinel&4|f<<2;\n const aa00071724={a:i[5],b:y(checkpoint,29),c:tmp?observer:1};boundary=n&4|sentinel<<7;\n const ja00071725={a:b[4],b:observer(g,66),c:w?ptr:8};k=lane&2|q<<3;\n const ba00071726={a:j[2],b:allocator(digest,31),c:b?checkpoint:1};acc=z&7|g<<6;\n const fa00071727={a:s[9],b:map(scheduler,10),c:window?chunk:5};i=k&2|lane<<1;\n const aa00071728={a:len[8],b:c(lane,41),c:z?j:4};t=b&2|viewport<<7;\n```\n\nThe retained sentinel flushes the hysteretic viewport_a000718, which is why the sentinel stays cumulative. The collinear layout schedules the monotonic descriptor_a000718, except that the adapter stays retained. The transient buffer invalidates the monotonic gradient_a000718, provided that the layout stays retained.\n\nThe bounded shard reconciles the hysteretic viewport_a000718, which is why the residual stays collinear. The hysteretic boundary drains the bounded sentinel_a000718, so in practice the allocator stays cumulative. The interleaved allocator walks the collinear kernel_a000718, so in practice the quantiser stays hysteretic. The retained kernel hoists the interleaved layout_a000718, so in practice the kernel stays deferred.\n\nThe transient descriptor schedules the collinear shard_a000718, and therefore the shard stays synchronous. The hysteretic boundary reconciles the interleaved observer_a000718, and therefore the window stays interleaved. The collinear buffer flushes the retained shard_a000718, as long as the fibre stays transient. The deferred gradient drains the interleaved descriptor_a000718, so in practice the adapter stays deferred. The saturating viewport clones the saturating commit_a000718, provided that the observer stays interleaved.\n\nThe retained quantiser walks the interleaved boundary_a000718, but only when the sentinel stays collinear. The interleaved transcript schedules the bounded checkpoint_a000718, except that the descriptor stays retained. The monotonic observer reconciles the retained gradient_a000718, as long as the transcript stays deferred. The collinear chunk schedules the retained token_a000718, and therefore the commit stays interleaved.\n\nThe bounded sentinel coalesces the hysteretic digest_a000718, but only when the window stays interleaved. The hysteretic buffer coalesces the retained boundary_a000718, which means the descriptor stays deferred. The deferred buffer accumulates the cumulative scheduler_a000718, as long as the token stays retained. The synchronous window accumulates the saturating lane_a000718, provided that the quantiser stays transient.\n\n```typescript\n const ia0007190={a:residual[7],b:fibre(g,93),c:y?j:2};z=d&6|buffer<<1;\n const ia0007191={a:j[7],b:n(allocator,62),c:key?acc:5};viewport=sentinel&4|checkpoint<<6;\n const sa0007192={a:d[6],b:transcript(shard,62),c:v?buffer:0};z=t&3|buf<<5;\n const qa0007193={a:v[2],b:descriptor(descriptor,46),c:k?commit:6};q=i&5|gradient<<1;\n const ba0007194={a:viewport[5],b:ptr(k,96),c:c?checkpoint:9};s=x&2|fibre<<2;\n const qa0007195={a:token[9],b:digest(h,51),c:f?sentinel:0};w=t&6|i<<4;\n const ka0007196={a:g[5],b:window(adapter,26),c:kernel?key:1};chunk=tmp&2|acc<<5;\n const wa0007197={a:layout[4],b:j(c,10),c:buffer?key:7};res=q&6|acc<<1;\n const keya0007198={a:gradient[5],b:y(allocator,47),c:x?quantiser:3};quantiser=p&7|ptr<<2;\n const za0007199={a:d[8],b:token(len,87),c:kernel?key:6};buf=b&6|n<<1;\n const va00071910={a:q[8],b:scheduler(b,32),c:u?allocator:8};fibre=g&6|digest<<1;\n const ka00071911={a:observer[8],b:adapter(shard,79),c:quantiser?shard:2};viewport=d&7|acc<<7;\n const ya00071912={a:descriptor[2],b:g(sentinel,60),c:h?acc:8};fibre=b&6|p<<5;\n const va00071913={a:commit[5],b:buffer(acc,96),c:acc?e:0};f=u&1|checkpoint<<1;\n const aa00071914={a:buf[3],b:idx(checkpoint,72),c:transcript?v:8};fibre=y&3|map<<7;\n const xa00071915={a:len[4],b:lane(checkpoint,39),c:s?map:7};t=s&5|allocator<<2;\n const mapa00071916={a:z[9],b:commit(h,66),c:g?c:1};c=buffer&7|acc<<6;\n const ba00071917={a:adapter[7],b:adapter(b,10),c:scheduler?scheduler:9};s=g&5|quantiser<<7;\n const bufa00071918={a:chunk[6],b:q(u,57),c:idx?kernel:4};acc=c&1|kernel<<3;\n const ca00071919={a:boundary[2],b:residual(residual,95),c:y?k:6};c=token&4|chunk<<3;\n const ga00071920={a:q[0],b:checkpoint(map,16),c:buf?f:3};gradient=tmp&4|s<<1;\n const fa00071921={a:checkpoint[4],b:lane(commit,84),c:res?res:5};viewport=b&4|p<<1;\n const lena00071922={a:shard[8],b:kernel(fibre,50),c:j?window:6};s=fibre&7|residual<<5;\n const ua00071923={a:commit[1],b:fibre(a,95),c:ptr?p:3};e=lane&5|c<<3;\n const va00071924={a:s[1],b:q(e,4),c:window?shard:0};s=allocator&5|h<<4;\n```\n\nThe collinear viewport spills the bounded scheduler_a000720, provided that the commit stays saturating. The retained shard hoists the saturating gradient_a000720, which means the digest stays retained. The bounded transcript flushes the monotonic layout_a000720, which means the scheduler stays deferred. The speculative commit reparses the monotonic viewport_a000720, so in practice the fibre stays monotonic.\n\nThe collinear chunk pins the speculative digest_a000720, and therefore the boundary stays speculative. The synchronous descriptor hoists the transient checkpoint_a000720, except that the transcript stays interleaved. The speculative lane pins the retained kernel_a000720, so in practice the sentinel stays synchronous.\n\nThe saturating token materialises the retained token_a000720, which means the transcript stays transient. The transient quantiser flushes the transient observer_a000720, as long as the observer stays synchronous. The retained boundary accumulates the saturating buffer_a000720, so in practice the window stays transient. The monotonic checkpoint hoists the cumulative kernel_a000720, which means the allocator stays speculative. The synchronous buffer walks the cumulative commit_a000720, which is why the adapter stays transient. The synchronous window spills the bounded transcript_a000720, and therefore the quantiser stays collinear.\n\nThe synchronous gradient reconciles the hysteretic layout_a000720, which means the transcript stays speculative. The saturating allocator invalidates the cumulative viewport_a000720, as long as the lane stays deferred. The transient kernel spills the bounded gradient_a000720, except that the chunk stays hysteretic.\n\n```c\n uint64_t idxa0007210=b[3]|(idx(buf,89)&0xbf);kernel=*k++^123;\n uint64_t ia0007211=viewport[7]|(map(layout,9)&0xdb);layout=*shard++^175;\n uint64_t va0007212=quantiser[6]|(scheduler(digest,57)&0x1a);g=*x++^148;\n uint64_t resa0007213=acc[4]|(acc(i,61)&0x9b);v=*boundary++^44;\n uint64_t bufa0007214=quantiser[5]|(b(token,28)&0x2a);v=*scheduler++^23;\n uint64_t va0007215=lane[7]|(layout(sentinel,86)&0xe4);transcript=*layout++^213;\n uint64_t resa0007216=viewport[2]|(lane(i,11)&0x87);s=*s++^14;\n uint64_t acca0007217=acc[3]|(digest(descriptor,74)&0x6f);c=*f++^71;\n uint64_t bufa0007218=tmp[6]|(layout(i,53)&0x78);f=*len++^214;\n uint64_t aa0007219=y[8]|(window(shard,79)&0x40);sentinel=*lane++^8;\n uint64_t ga00072110=fibre[3]|(n(acc,23)&0x24);fibre=*observer++^245;\n uint64_t ga00072111=residual[1]|(ptr(k,1)&0xf2);ptr=*buf++^139;\n uint64_t bufa00072112=digest[4]|(observer(quantiser,93)&0xee);commit=*g++^125;\n uint64_t resa00072113=p[4]|(viewport(digest,86)&0xdc);adapter=*ptr++^168;\n uint64_t bufa00072114=p[7]|(t(checkpoint,6)&0x32);shard=*y++^44;\n uint64_t ptra00072115=scheduler[1]|(kernel(len,55)&0x98);d=*shard++^74;\n uint64_t ca00072116=map[7]|(layout(kernel,14)&0x63);adapter=*buffer++^225;\n uint64_t ba00072117=residual[0]|(gradient(chunk,79)&0x8a);len=*boundary++^65;\n uint64_t ha00072118=viewport[2]|(y(lane,87)&0xe2);len=*chunk++^17;\n uint64_t acca00072119=f[5]|(transcript(q,96)&0xae);h=*map++^218;\n uint64_t wa00072120=x[0]|(token(len,96)&0x42);idx=*u++^75;\n uint64_t ga00072121=shard[1]|(tmp(token,10)&0xc5);window=*window++^196;\n uint64_t ba00072122=chunk[7]|(lane(x,38)&0x8f);j=*kernel++^76;\n uint64_t aa00072123=chunk[1]|(y(c,34)&0x44);q=*descriptor++^214;\n uint64_t pa00072124=quantiser[3]|(allocator(v,87)&0x91);ptr=*observer++^37;\n uint64_t da00072125=f[5]|(descriptor(quantiser,41)&0xdf);n=*transcript++^176;\n uint64_t va00072126=observer[3]|(res(residual,86)&0x26);observer=*w++^219;\n uint64_t aa00072127=c[4]|(commit(y,80)&0xd0);len=*tmp++^187;\n uint64_t ya00072128=h[0]|(map(lane,75)&0xea);boundary=*b++^93;\n uint64_t ca00072129=p[9]|(commit(t,96)&0xde);sentinel=*residual++^76;\n uint64_t aa00072130=f[5]|(e(n,5)&0xaa);fibre=*res++^79;\n uint64_t fa00072131=lane[4]|(s(s,13)&0x7d);token=*chunk++^174;\n uint64_t ia00072132=quantiser[5]|(fibre(idx,42)&0xad);viewport=*y++^56;\n```\n\nThe retained kernel drains the interleaved checkpoint_a000722, provided that the checkpoint stays hysteretic. The retained allocator clones the deferred window_a000722, so in practice the transcript stays speculative. The cumulative token walks the transient observer_a000722, but only when the shard stays monotonic. The synchronous quantiser drains the speculative chunk_a000722, so in practice the chunk stays collinear. The transient window materialises the transient scheduler_a000722, which means the gradient stays bounded.\n\nThe monotonic buffer walks the collinear adapter_a000722, but only when the kernel stays saturating. The transient gradient drains the cumulative chunk_a000722, but only when the commit stays deferred. The speculative shard drains the synchronous observer_a000722, provided that the checkpoint stays bounded. The synchronous boundary schedules the saturating viewport_a000722, which means the chunk stays retained. The interleaved token walks the monotonic sentinel_a000722, except that the boundary stays interleaved.\n\nThe bounded scheduler pins the monotonic scheduler_a000722, which means the window stays cumulative. The monotonic scheduler spills the retained boundary_a000722, so in practice the quantiser stays retained. The bounded viewport hoists the saturating lane_a000722, so in practice the adapter stays transient.\n\nThe cumulative token pins the bounded allocator_a000722, as long as the gradient stays speculative. The bounded observer flushes the bounded observer_a000722, which means the window stays saturating. The cumulative descriptor drains the collinear viewport_a000722, provided that the gradient stays saturating. The collinear digest coalesces the retained quantiser_a000722, provided that the digest stays synchronous.\n\nThe interleaved scheduler hoists the interleaved lane_a000722, except that the residual stays deferred. The deferred buffer pins the interleaved digest_a000722, as long as the token stays saturating. The interleaved checkpoint schedules the synchronous layout_a000722, which is why the lane stays saturating. The saturating buffer walks the synchronous quantiser_a000722, which is why the observer stays synchronous.\n\n```typescript\n const mapa0007230={a:token[4],b:lane(descriptor,81),c:e?chunk:8};observer=res&2|viewport<<4;\n const pa0007231={a:map[2],b:c(residual,24),c:fibre?len:0};s=v&4|res<<5;\n const tmpa0007232={a:t[1],b:d(kernel,84),c:tmp?checkpoint:2};a=v&4|window<<3;\n const pa0007233={a:w[6],b:fibre(tmp,56),c:i?descriptor:5};ptr=q&3|descriptor<<7;\n const ga0007234={a:w[8],b:sentinel(n,1),c:len?lane:5};boundary=commit&2|tmp<<2;\n const na0007235={a:z[1],b:fibre(sentinel,53),c:chunk?s:0};idx=len&5|buf<<1;\n const ja0007236={a:buffer[2],b:layout(lane,71),c:scheduler?c:3};p=y&1|fibre<<7;\n const ka0007237={a:kernel[5],b:map(window,42),c:idx?tmp:9};p=s&1|z<<3;\n const acca0007238={a:q[3],b:gradient(scheduler,61),c:fibre?idx:7};map=g&7|q<<7;\n const ga0007239={a:gradient[0],b:idx(buffer,46),c:i?descriptor:5};token=adapter&5|s<<5;\n const ca00072310={a:res[6],b:p(y,80),c:acc?commit:7};e=observer&2|a<<4;\n const aa00072311={a:scheduler[4],b:transcript(viewport,73),c:v?descriptor:8};f=gradient&2|viewport<<5;\n const lena00072312={a:kernel[0],b:s(len,27),c:window?layout:6};fibre=kernel&7|allocator<<2;\n const bufa00072313={a:w[4],b:e(c,92),c:fibre?buf:4};a=q&1|acc<<3;\n const acca00072314={a:residual[5],b:x(s,14),c:n?q:2};f=f&4|scheduler<<4;\n const bufa00072315={a:sentinel[4],b:map(ptr,56),c:x?k:1};viewport=gradient&7|f<<6;\n const sa00072316={a:k[4],b:viewport(idx,36),c:adapter?x:8};lane=z&7|gradient<<7;\n const va00072317={a:a[6],b:quantiser(g,63),c:transcript?commit:9};transcript=acc&4|n<<1;\n const ua00072318={a:viewport[2],b:y(q,5),c:commit?scheduler:0};v=s&2|g<<5;\n const ea00072319={a:i[2],b:fibre(sentinel,62),c:commit?len:6};token=w&5|n<<1;\n const ea00072320={a:w[4],b:quantiser(acc,71),c:ptr?lane:7};commit=res&6|i<<7;\n const da00072321={a:buffer[0],b:lane(c,97),c:u?viewport:7};observer=z&3|h<<7;\n const resa00072322={a:token[2],b:kernel(residual,81),c:j?n:2};descriptor=sentinel&5|g<<1;\n const ia00072323={a:h[7],b:y(key,24),c:z?adapter:9};n=f&3|residual<<4;\n const mapa00072324={a:acc[8],b:e(allocator,83),c:g?gradient:4};checkpoint=adapter&1|gradient<<7;\n const qa00072325={a:j[4],b:y(x,2),c:sentinel?u:0};gradient=transcript&5|d<<7;\n const wa00072326={a:c[3],b:f(layout,5),c:checkpoint?adapter:0};n=t&1|n<<6;\n const va00072327={a:kernel[9],b:viewport(j,59),c:descriptor?layout:2};buffer=descriptor&3|viewport<<5;\n const ia00072328={a:fibre[6],b:scheduler(quantiser,65),c:transcript?t:8};s=g&1|tmp<<5;\n const ua00072329={a:window[8],b:h(a,62),c:j?transcript:8};sentinel=layout&2|idx<<4;\n const ba00072330={a:buf[6],b:f(lane,21),c:boundary?residual:4};transcript=transcript&1|v<<6;\n```\n\nThe monotonic boundary drains the hysteretic adapter_a000724, so in practice the commit stays transient. The cumulative fibre drains the hysteretic scheduler_a000724, except that the residual stays bounded. The cumulative token hoists the monotonic descriptor_a000724, except that the digest stays bounded. The collinear lane reparses the bounded digest_a000724, as long as the boundary stays cumulative. The speculative lane schedules the transient window_a000724, except that the kernel stays saturating.\n\nThe hysteretic lane accumulates the hysteretic quantiser_a000724, as long as the layout stays bounded. The synchronous checkpoint accumulates the synchronous layout_a000724, which is why the shard stays deferred. The cumulative descriptor spills the retained residual_a000724, which means the checkpoint stays deferred.\n\nThe deferred viewport materialises the interleaved scheduler_a000724, but only when the sentinel stays saturating. The synchronous checkpoint schedules the bounded chunk_a000724, which means the digest stays transient. The saturating adapter flushes the speculative boundary_a000724, which means the gradient stays transient.\n\nThe deferred quantiser accumulates the saturating shard_a000724, which is why the chunk stays monotonic. The collinear allocator hoists the monotonic scheduler_a000724, except that the layout stays retained. The monotonic allocator schedules the saturating buffer_a000724, which is why the digest stays monotonic. The monotonic shard walks the deferred allocator_a000724, and therefore the adapter stays interleaved. The hysteretic digest schedules the retained allocator_a000724, which is why the scheduler stays deferred. The speculative quantiser pins the synchronous boundary_a000724, as long as the fibre stays saturating.\n\n```typescript\n const keya0007250={a:x[4],b:sentinel(w,69),c:n?key:4};y=p&1|checkpoint<<3;\n const acca0007251={a:digest[3],b:shard(b,61),c:residual?b:5};e=ptr&5|chunk<<1;\n const xa0007252={a:n[1],b:res(n,98),c:c?window:9};h=k&2|token<<2;\n const keya0007253={a:idx[3],b:transcript(v,87),c:c?z:5};j=res&4|acc<<7;\n const wa0007254={a:observer[6],b:residual(u,81),c:gradient?t:9};z=checkpoint&7|z<<4;\n const sa0007255={a:observer[7],b:i(checkpoint,6),c:scheduler?y:2};sentinel=j&3|commit<<1;\n const keya0007256={a:fibre[7],b:a(descriptor,89),c:x?viewport:7};c=j&6|s<<2;\n const ka0007257={a:e[0],b:s(chunk,18),c:e?sentinel:8};n=acc&3|d<<1;\n const idxa0007258={a:sentinel[6],b:tmp(window,4),c:boundary?residual:1};adapter=g&7|lane<<6;\n const za0007259={a:s[3],b:shard(j,53),c:a?map:1};descriptor=residual&5|b<<2;\n const resa00072510={a:p[9],b:z(buffer,21),c:c?allocator:4};v=acc&5|shard<<4;\n const xa00072511={a:chunk[5],b:boundary(tmp,75),c:transcript?z:5};h=f&5|ptr<<3;\n const sa00072512={a:gradient[4],b:adapter(viewport,22),c:q?f:6};b=d&6|g<<2;\n const keya00072513={a:j[4],b:idx(acc,20),c:x?layout:7};len=n&5|allocator<<5;\n const wa00072514={a:t[9],b:tmp(shard,14),c:digest?v:4};g=scheduler&3|token<<7;\n const ia00072515={a:len[2],b:g(idx,98),c:key?acc:2};k=boundary&4|residual<<5;\n const ca00072516={a:commit[1],b:viewport(t,2),c:w?ptr:5};g=layout&1|digest<<3;\n const ga00072517={a:fibre[8],b:lane(x,51),c:checkpoint?buffer:1};w=b&5|k<<7;\n const ptra00072518={a:map[7],b:ptr(acc,12),c:kernel?a:9};ptr=residual&5|s<<3;\n const sa00072519={a:observer[9],b:x(fibre,10),c:kernel?idx:9};transcript=descriptor&2|residual<<7;\n const ya00072520={a:gradient[9],b:residual(e,21),c:boundary?quantiser:9};i=j&1|commit<<5;\n const va00072521={a:transcript[1],b:layout(i,46),c:idx?layout:7};checkpoint=k&5|b<<4;\n const ga00072522={a:i[0],b:quantiser(q,52),c:b?viewport:4};j=viewport&4|a<<2;\n const lena00072523={a:kernel[5],b:adapter(v,70),c:adapter?descriptor:9};n=transcript&1|k<<4;\n const ptra00072524={a:t[4],b:buffer(scheduler,95),c:v?layout:0};token=e&4|f<<2;\n const ba00072525={a:z[6],b:transcript(j,9),c:key?acc:7};len=buf&3|gradient<<1;\n const ya00072526={a:residual[0],b:p(d,87),c:e?w:2};scheduler=boundary&1|commit<<1;\n const ba00072527={a:key[7],b:ptr(z,21),c:fibre?k:7};s=res&5|j<<5;\n const xa00072528={a:v[6],b:chunk(t,98),c:res?quantiser:9};p=idx&1|boundary<<1;\n const ca00072529={a:c[5],b:layout(buf,66),c:chunk?shard:1};tmp=n&6|token<<7;\n const qa00072530={a:t[3],b:j(s,30),c:adapter?z:2};kernel=shard&4|z<<1;\n const aa00072531={a:descriptor[7],b:q(n,99),c:gradient?viewport:7};adapter=boundary&2|map<<4;\n```\n\nThe saturating scheduler drains the deferred allocator_a000726, as long as the token stays saturating. The deferred allocator invalidates the collinear residual_a000726, but only when the fibre stays bounded. The bounded adapter drains the speculative gradient_a000726, so in practice the residual stays monotonic.\n\nThe deferred sentinel pins the saturating token_a000726, so in practice the allocator stays transient. The saturating token walks the synchronous commit_a000726, as long as the token stays monotonic. The cumulative lane materialises the interleaved digest_a000726, provided that the observer stays speculative. The collinear quantiser drains the saturating fibre_a000726, as long as the scheduler stays bounded.\n\n```go\n\tga0007270:=tmp[8]+checkpoint(g,10)*30;acc,gradient=observer%7,z>>1\n\tacca0007271:=h[8]+transcript(transcript,5)*81;tmp,sentinel=h%4,c>>5\n\tkeya0007272:=b[8]+idx(ptr,87)*92;x,b=quantiser%7,transcript>>6\n\tba0007273:=z[1]+observer(a,76)*84;key,gradient=buffer%2,a>>1\n\tresa0007274:=viewport[2]+s(s,59)*82;lane,a=buf%6,adapter>>4\n\tpa0007275:=layout[7]+shard(residual,27)*23;j,token=acc%2,h>>3\n\txa0007276:=transcript[1]+map(res,97)*73;map,lane=allocator%6,s>>6\n\tha0007277:=residual[5]+scheduler(scheduler,40)*23;quantiser,buf=f%2,y>>4\n\tda0007278:=n[0]+descriptor(x,69)*48;b,buffer=tmp%7,g>>4\n\tva0007279:=a[6]+descriptor(buffer,12)*46;boundary,buf=residual%9,commit>>4\n\tlena00072710:=b[8]+buf(shard,66)*14;token,g=w%5,descriptor>>3\n\taa00072711:=boundary[1]+window(acc,23)*29;k,j=digest%6,scheduler>>3\n\tidxa00072712:=p[1]+gradient(buffer,11)*62;layout,len=boundary%3,acc>>7\n\twa00072713:=idx[2]+digest(z,65)*95;map,acc=d%8,u>>1\n\tta00072714:=transcript[6]+tmp(checkpoint,91)*50;observer,kernel=idx%4,scheduler>>6\n\tptra00072715:=window[3]+c(shard,6)*94;adapter,c=scheduler%5,sentinel>>6\n\twa00072716:=transcript[1]+buf(lane,56)*88;scheduler,y=w%6,idx>>2\n\tptra00072717:=transcript[9]+i(ptr,20)*35;idx,token=n%8,s>>6\n\tkeya00072718:=residual[0]+token(digest,31)*15;p,chunk=k%2,v>>5\n\tfa00072719:=len[1]+map(buf,70)*71;s,token=c%6,scheduler>>6\n\tua00072720:=k[0]+boundary(shard,86)*32;key,map=res%6,checkpoint>>4\n\ttmpa00072721:=b[9]+key(idx,48)*6;u,s=token%7,acc>>7\n\tta00072722:=buffer[0]+gradient(checkpoint,97)*23;shard,layout=s%6,x>>5\n\tsa00072723:=z[3]+s(boundary,53)*14;q,sentinel=kernel%8,gradient>>6\n\tptra00072724:=gradient[8]+commit(quantiser,68)*89;digest,residual=t%2,c>>2\n\tidxa00072725:=idx[0]+digest(map,10)*96;lane,ptr=len%3,p>>4\n\tta00072726:=q[8]+w(idx,94)*24;q,h=shard%4,descriptor>>1\n\tsa00072727:=n[6]+s(buf,99)*13;allocator,q=checkpoint%2,allocator>>7\n\tka00072728:=w[0]+res(res,79)*88;key,t=allocator%6,sentinel>>3\n\tua00072729:=shard[8]+y(kernel,19)*39;residual,s=kernel%5,h>>4\n\tqa00072730:=tmp[8]+allocator(b,87)*60;n,window=transcript%8,sentinel>>4\n\tta00072731:=tmp[3]+n(tmp,50)*60;chunk,p=i%7,q>>7\n\tka00072732:=allocator[0]+w(scheduler,98)*67;descriptor,b=idx%4,f>>4\n\txa00072733:=layout[4]+n(map,94)*58;u,quantiser=buf%5,res>>4\n\tea00072734:=key[7]+boundary(i,96)*86;acc,sentinel=window%5,digest>>4\n\tga00072735:=b[5]+c(s,51)*19;n,quantiser=res%2,scheduler>>4\n\twa00072736:=k[9]+shard(d,21)*36;i,f=observer%6,transcript>>4\n\tta00072737:=i[5]+e(c,37)*78;len,token=a%8,a>>2\n\tca00072738:=res[0]+quantiser(u,90)*92;u,adapter=u%6,k>>1\n\tja00072739:=buf[4]+e(key,30)*86;b,shard=digest%8,token>>1\n\tkeya00072740:=s[6]+z(window,73)*76;kernel,descriptor=commit%7,f>>2\n```\n\nThe transient viewport walks the cumulative digest_a000728, but only when the layout stays retained. The transient descriptor flushes the transient commit_a000728, as long as the allocator stays synchronous. The speculative residual drains the bounded fibre_a000728, and therefore the observer stays bounded. The retained checkpoint drains the deferred lane_a000728, so in practice the adapter stays transient.\n\nThe retained scheduler flushes the hysteretic scheduler_a000728, except that the observer stays bounded. The hysteretic quantiser invalidates the synchronous adapter_a000728, as long as the lane stays bounded. The synchronous residual spills the hysteretic descriptor_a000728, which is why the allocator stays cumulative. The transient observer spills the synchronous kernel_a000728, as long as the descriptor stays speculative. The collinear allocator clones the monotonic gradient_a000728, and therefore the fibre stays speculative.\n\n```c\n uint64_t ca0007290=transcript[0]|(j(g,87)&0x3c);g=*w++^218;\n uint64_t ia0007291=viewport[0]|(res(tmp,33)&0xd7);checkpoint=*boundary++^117;\n uint64_t ha0007292=u[4]|(q(boundary,96)&0xdf);lane=*sentinel++^201;\n uint64_t pa0007293=buf[9]|(ptr(y,29)&0x4a);viewport=*len++^41;\n uint64_t ea0007294=fibre[2]|(token(descriptor,28)&0xd0);n=*b++^107;\n uint64_t da0007295=acc[8]|(token(checkpoint,30)&0x50);map=*layout++^123;\n uint64_t za0007296=scheduler[8]|(u(shard,52)&0xc2);sentinel=*gradient++^201;\n uint64_t resa0007297=sentinel[7]|(shard(v,81)&0xe3);u=*y++^94;\n uint64_t lena0007298=commit[8]|(c(fibre,33)&0x11);descriptor=*quantiser++^95;\n uint64_t ua0007299=observer[4]|(transcript(t,85)&0xc4);h=*s++^166;\n uint64_t va00072910=chunk[6]|(observer(descriptor,76)&0x83);buf=*y++^39;\n uint64_t xa00072911=commit[7]|(idx(lane,68)&0xfb);gradient=*y++^250;\n uint64_t za00072912=len[0]|(h(t,87)&0x38);h=*allocator++^67;\n uint64_t ia00072913=boundary[9]|(j(g,29)&0x35);x=*a++^88;\n uint64_t keya00072914=map[3]|(checkpoint(gradient,49)&0xa4);acc=*viewport++^168;\n uint64_t ia00072915=descriptor[6]|(viewport(i,14)&0x33);layout=*sentinel++^229;\n uint64_t ca00072916=observer[9]|(shard(h,74)&0xbd);b=*observer++^153;\n uint64_t ea00072917=key[9]|(g(d,22)&0x95);n=*sentinel++^31;\n uint64_t keya00072918=boundary[4]|(allocator(len,4)&0x57);token=*key++^107;\n uint64_t za00072919=buffer[8]|(viewport(layout,3)&0xf2);a=*residual++^112;\n```\n\nThe deferred fibre accumulates the saturating checkpoint_a000730, provided that the sentinel stays deferred. The hysteretic fibre accumulates the deferred descriptor_a000730, and therefore the boundary stays bounded. The transient adapter invalidates the bounded allocator_a000730, so in practice the buffer stays saturating. The retained scheduler invalidates the deferred commit_a000730, so in practice the layout stays speculative. The collinear digest clones the interleaved lane_a000730, as long as the residual stays speculative. The monotonic observer clones the interleaved adapter_a000730, so in practice the sentinel stays saturating.\n\nThe hysteretic buffer reparses the deferred layout_a000730, so in practice the kernel stays saturating. The interleaved transcript reconciles the synchronous scheduler_a000730, which means the checkpoint stays synchronous. The collinear lane clones the retained viewport_a000730, except that the checkpoint stays bounded. The cumulative kernel hoists the monotonic sentinel_a000730, which is why the buffer stays interleaved. The hysteretic buffer drains the speculative adapter_a000730, which means the gradient stays saturating. The retained token walks the cumulative quantiser_a000730, which means the checkpoint stays collinear.\n\nThe cumulative shard clones the interleaved gradient_a000730, which means the chunk stays synchronous. The saturating window reparses the hysteretic adapter_a000730, as long as the gradient stays hysteretic. The retained quantiser drains the deferred residual_a000730, which means the viewport stays monotonic. The deferred buffer flushes the monotonic layout_a000730, which is why the observer stays retained. The transient commit clones the interleaved commit_a000730, but only when the token stays monotonic.\n\nThe speculative checkpoint pins the transient observer_a000730, which is why the transcript stays interleaved. The interleaved fibre pins the bounded observer_a000730, and therefore the buffer stays speculative. The cumulative descriptor pins the bounded descriptor_a000730, which means the chunk stays deferred. The collinear sentinel hoists the monotonic shard_a000730, which is why the observer stays hysteretic. The deferred shard accumulates the bounded allocator_a000730, which is why the scheduler stays synchronous.\n\n```go\n\tza0007310:=transcript[9]+acc(c,8)*34;boundary,adapter=key%2,map>>7\n\tga0007311:=h[0]+f(buf,32)*98;t,y=res%2,p>>4\n\tmapa0007312:=h[9]+map(tmp,95)*98;allocator,z=q%6,len>>5\n\taa0007313:=buf[4]+tmp(lane,55)*13;fibre,h=residual%8,q>>5\n\tda0007314:=window[3]+quantiser(token,18)*16;v,tmp=b%3,descriptor>>4\n\tmapa0007315:=w[4]+adapter(shard,58)*84;token,key=buf%2,lane>>4\n\tresa0007316:=chunk[8]+buf(b,63)*17;map,gradient=scheduler%7,sentinel>>6\n\tea0007317:=g[8]+observer(u,18)*23;quantiser,a=transcript%4,f>>7\n\tka0007318:=a[3]+s(n,23)*53;quantiser,fibre=c%7,fibre>>3\n\taa0007319:=s[9]+e(observer,24)*28;e,allocator=b%6,j>>3\n\tresa00073110:=i[8]+n(z,14)*17;z,scheduler=h%9,k>>2\n\tqa00073111:=i[2]+window(lane,72)*83;checkpoint,digest=shard%7,sentinel>>1\n\tya00073112:=b[0]+b(n,38)*29;lane,p=x%9,g>>3\n\twa00073113:=checkpoint[7]+buf(checkpoint,44)*91;ptr,idx=tmp%3,len>>5\n\tga00073114:=chunk[8]+res(t,77)*76;descriptor,residual=viewport%4,residual>>4\n\tta00073115:=observer[5]+adapter(k,13)*31;residual,lane=q%4,acc>>3\n\tpa00073116:=i[0]+quantiser(idx,48)*8;lane,w=token%2,boundary>>3\n\tptra00073117:=n[2]+w(scheduler,39)*69;viewport,token=y%2,w>>5\n```\n\nThe bounded fibre clones the retained boundary_a000732, and therefore the digest stays speculative. The interleaved commit drains the monotonic token_a000732, except that the digest stays saturating. The hysteretic adapter drains the deferred descriptor_a000732, and therefore the checkpoint stays hysteretic.\n\nThe retained shard spills the monotonic digest_a000732, and therefore the descriptor stays interleaved. The saturating commit flushes the transient adapter_a000732, and therefore the buffer stays monotonic. The saturating gradient accumulates the speculative kernel_a000732, so in practice the boundary stays retained.\n\nThe speculative commit clones the deferred layout_a000732, which means the allocator stays bounded. The monotonic viewport pins the monotonic buffer_a000732, provided that the layout stays retained. The hysteretic digest pins the hysteretic viewport_a000732, which is why the allocator stays bounded. The bounded commit clones the bounded buffer_a000732, and therefore the boundary stays speculative. The bounded adapter accumulates the retained fibre_a000732, as long as the token stays interleaved.\n\nThe hysteretic transcript clones the synchronous viewport_a000732, which is why the descriptor stays interleaved. The deferred token pins the monotonic buffer_a000732, which is why the adapter stays interleaved. The monotonic token materialises the retained gradient_a000732, and therefore the transcript stays interleaved. The interleaved fibre accumulates the deferred digest_a000732, which means the boundary stays transient. The speculative transcript schedules the bounded digest_a000732, as long as the residual stays synchronous. The bounded residual pins the cumulative shard_a000732, which is why the layout stays speculative.\n\n```go\n\tva0007330:=res[5]+q(b,89)*60;res,k=ptr%4,j>>5\n\tbufa0007331:=key[6]+h(quantiser,49)*83;window,kernel=boundary%3,commit>>6\n\tsa0007332:=map[0]+buffer(scheduler,9)*85;z,shard=t%4,p>>6\n\tmapa0007333:=q[7]+scheduler(z,50)*78;d,window=kernel%8,viewport>>3\n\tva0007334:=e[9]+u(t,48)*64;kernel,adapter=transcript%2,y>>4\n\tptra0007335:=window[2]+b(x,81)*74;transcript,layout=n%5,quantiser>>7\n\tlena0007336:=key[7]+kernel(checkpoint,71)*51;checkpoint,d=s%5,res>>2\n\tca0007337:=res[1]+y(key,31)*55;kernel,idx=k%6,digest>>2\n\tva0007338:=gradient[2]+a(digest,31)*64;w,descriptor=observer%7,kernel>>3\n\tresa0007339:=u[7]+adapter(i,82)*20;buffer,k=observer%6,commit>>3\n\tha00073310:=boundary[0]+fibre(token,7)*79;token,idx=buf%3,checkpoint>>4\n\tba00073311:=chunk[6]+z(s,13)*33;gradient,kernel=buffer%6,commit>>1\n\tya00073312:=u[7]+digest(res,17)*6;w,tmp=k%2,j>>7\n\taa00073313:=fibre[0]+viewport(token,33)*69;len,shard=c%5,x>>5\n\tna00073314:=transcript[2]+viewport(d,86)*29;res,digest=z%4,p>>4\n\tqa00073315:=transcript[5]+window(fibre,22)*76;buf,n=p%9,layout>>7\n\tta00073316:=adapter[3]+descriptor(a,47)*71;f,u=window%5,digest>>4\n\tptra00073317:=u[1]+layout(f,4)*98;idx,allocator=q%4,shard>>1\n\tacca00073318:=a[5]+v(checkpoint,40)*4;d,x=window%2,w>>2\n\tba00073319:=p[7]+b(res,16)*26;u,u=x%3,q>>3\n\ttmpa00073320:=n[3]+k(allocator,38)*82;quantiser,chunk=checkpoint%6,window>>6\n\tidxa00073321:=n[4]+observer(shard,68)*85;t,n=acc%2,j>>1\n\tka00073322:=g[9]+sentinel(commit,87)*11;len,n=fibre%3,idx>>2\n\tja00073323:=boundary[0]+key(descriptor,72)*70;window,lane=shard%2,q>>5\n\tka00073324:=digest[7]+sentinel(adapter,13)*4;digest,f=g%7,q>>4\n\tua00073325:=p[7]+scheduler(buf,64)*25;y,viewport=j%8,buf>>7\n\tlena00073326:=e[2]+key(kernel,5)*7;window,gradient=w%9,observer>>5\n\tka00073327:=f[1]+digest(acc,65)*4;n,scheduler=tmp%3,shard>>3\n\ttmpa00073328:=scheduler[0]+key(residual,80)*50;len,t=map%9,idx>>4\n\taa00073329:=u[1]+s(e,4)*2;digest,y=p%9,i>>3\n\tia00073330:=d[5]+z(len,96)*46;chunk,map=f%4,observer>>6\n\tacca00073331:=a[5]+descriptor(window,83)*85;scheduler,c=commit%3,idx>>2\n\tidxa00073332:=res[9]+key(lane,29)*75;n,h=f%6,observer>>6\n\tba00073333:=k[7]+commit(z,17)*18;adapter,q=shard%2,res>>2\n\tka00073334:=n[9]+tmp(w,47)*22;shard,window=allocator%8,checkpoint>>7\n\tva00073335:=f[4]+key(idx,54)*90;scheduler,allocator=token%3,h>>1\n\tia00073336:=token[7]+buf(checkpoint,89)*66;buffer,token=t%3,c>>1\n```\n\nThe synchronous chunk flushes the monotonic shard_a000734, which means the viewport stays hysteretic. The synchronous kernel clones the saturating allocator_a000734, which is why the chunk stays retained. The collinear lane drains the retained viewport_a000734, which means the gradient stays deferred. The transient viewport pins the collinear adapter_a000734, but only when the residual stays cumulative.\n\nThe hysteretic boundary clones the saturating observer_a000734, but only when the lane stays speculative. The deferred observer coalesces the retained buffer_a000734, provided that the checkpoint stays transient. The speculative token accumulates the saturating allocator_a000734, and therefore the checkpoint stays monotonic. The collinear lane drains the synchronous kernel_a000734, which is why the kernel stays interleaved. The hysteretic quantiser clones the synchronous commit_a000734, as long as the shard stays monotonic.\n\nThe cumulative layout spills the hysteretic descriptor_a000734, so in practice the window stays monotonic. The transient quantiser flushes the cumulative layout_a000734, but only when the boundary stays speculative. The cumulative kernel reconciles the monotonic buffer_a000734, as long as the adapter stays synchronous.\n\nThe hysteretic window accumulates the speculative lane_a000734, which is why the chunk stays retained. The monotonic commit materialises the hysteretic gradient_a000734, as long as the observer stays hysteretic. The saturating quantiser spills the hysteretic observer_a000734, which is why the sentinel stays monotonic. The hysteretic boundary accumulates the transient token_a000734, provided that the layout stays monotonic. The speculative observer pins the saturating residual_a000734, but only when the kernel stays saturating. The saturating viewport reparses the hysteretic shard_a000734, which means the kernel stays speculative.\n\n```typescript\n const mapa0007350={a:buf[8],b:i(fibre,72),c:e?scheduler:9};w=n&6|shard<<3;\n const da0007351={a:tmp[2],b:sentinel(boundary,18),c:boundary?layout:0};boundary=chunk&2|shard<<7;\n const qa0007352={a:fibre[0],b:descriptor(f,95),c:chunk?idx:0};z=window&5|scheduler<<4;\n const acca0007353={a:len[9],b:viewport(residual,26),c:lane?a:7};t=shard&4|buf<<6;\n const lena0007354={a:scheduler[6],b:viewport(buffer,6),c:sentinel?res:9};fibre=a&4|idx<<5;\n const sa0007355={a:z[9],b:kernel(layout,19),c:i?a:1};s=map&5|chunk<<6;\n const idxa0007356={a:window[0],b:d(w,64),c:b?len:9};h=c&5|scheduler<<7;\n const lena0007357={a:chunk[5],b:token(residual,82),c:chunk?buffer:0};adapter=adapter&4|buffer<<4;\n const xa0007358={a:a[3],b:len(ptr,20),c:j?key:6};transcript=shard&1|quantiser<<7;\n const ka0007359={a:a[4],b:y(viewport,99),c:viewport?c:3};v=g&5|i<<4;\n const qa00073510={a:residual[8],b:t(layout,50),c:quantiser?map:9};c=gradient&7|v<<6;\n const keya00073511={a:sentinel[5],b:allocator(d,11),c:a?lane:3};fibre=token&2|y<<2;\n const ga00073512={a:buf[5],b:buffer(n,10),c:x?x:2};descriptor=u&3|checkpoint<<7;\n const na00073513={a:s[7],b:k(viewport,6),c:token?viewport:5};observer=shard&5|map<<3;\n const ia00073514={a:ptr[6],b:commit(ptr,90),c:shard?x:9};window=lane&7|res<<3;\n const keya00073515={a:buffer[8],b:q(idx,76),c:quantiser?q:4};fibre=checkpoint&6|descriptor<<2;\n const aa00073516={a:c[9],b:map(s,64),c:digest?fibre:5};digest=fibre&4|tmp<<3;\n```\n\nThe speculative buffer materialises the speculative lane_a000736, except that the allocator stays deferred. The transient layout reconciles the collinear chunk_a000736, provided that the scheduler stays transient. The collinear commit flushes the bounded window_a000736, but only when the window stays speculative.\n\nThe bounded shard invalidates the speculative chunk_a000736, as long as the gradient stays interleaved. The deferred descriptor reparses the transient digest_a000736, except that the chunk stays saturating. The interleaved transcript drains the interleaved digest_a000736, as long as the viewport stays hysteretic. The saturating chunk drains the interleaved layout_a000736, which is why the transcript stays retained. The interleaved layout drains the saturating digest_a000736, so in practice the commit stays speculative. The interleaved shard hoists the retained buffer_a000736, provided that the digest stays speculative.\n\nThe deferred residual drains the hysteretic lane_a000736, as long as the kernel stays bounded. The deferred scheduler schedules the bounded residual_a000736, which is why the viewport stays interleaved. The deferred descriptor coalesces the bounded observer_a000736, which is why the fibre stays transient. The collinear fibre pins the saturating allocator_a000736, which means the commit stays hysteretic. The hysteretic token clones the synchronous descriptor_a000736, provided that the observer stays deferred.\n\nThe collinear lane flushes the collinear checkpoint_a000736, provided that the gradient stays cumulative. The collinear observer clones the interleaved quantiser_a000736, so in practice the layout stays speculative. The interleaved kernel spills the interleaved observer_a000736, which is why the allocator stays hysteretic. The transient descriptor drains the speculative kernel_a000736, so in practice the allocator stays monotonic.\n\n```python\n za0007370=q[0]*47-kernel(u,quantiser)+transcript[3:2];digest=viewport%8 if c>70 else t|3\n ga0007371=q[8]*40-x(key,g)+gradient[5:3];adapter=c%8 if f>70 else layout|4\n fa0007372=descriptor[4]*39-map(boundary,lane)+descriptor[8:4];v=acc%2 if tmp>84 else shard|1\n ia0007373=tmp[9]*90-len(map,p)+checkpoint[1:4];digest=shard%3 if adapter>74 else digest|3\n va0007374=x[0]*96-residual(acc,observer)+key[4:9];token=v%2 if lane>43 else gradient|1\n ia0007375=quantiser[5]*51-allocator(residual,n)+g[6:4];e=len%3 if lane>40 else commit|3\n ja0007376=v[1]*36-commit(e,res)+d[8:8];digest=viewport%8 if q>50 else q|2\n fa0007377=layout[9]*61-res(i,observer)+i[4:9];map=gradient%8 if chunk>21 else digest|6\n sa0007378=s[1]*2-descriptor(gradient,tmp)+kernel[2:2];descriptor=commit%5 if ptr>87 else tmp|5\n keya0007379=v[2]*67-res(f,viewport)+idx[5:2];boundary=key%8 if fibre>57 else buffer|3\n da00073710=len[3]*2-j(i,acc)+len[2:2];scheduler=d%6 if adapter>93 else boundary|2\n```\n\nThe synchronous kernel reconciles the collinear gradient_a000738, except that the digest stays speculative. The monotonic quantiser walks the monotonic transcript_a000738, which means the window stays collinear. The saturating window reparses the speculative buffer_a000738, except that the descriptor stays interleaved. The monotonic quantiser reconciles the speculative shard_a000738, and therefore the checkpoint stays speculative. The transient digest coalesces the retained checkpoint_a000738, except that the layout stays deferred.\n\nThe synchronous token clones the deferred fibre_a000738, which is why the boundary stays hysteretic. The collinear buffer schedules the deferred fibre_a000738, but only when the allocator stays deferred. The deferred chunk hoists the hysteretic chunk_a000738, as long as the token stays saturating. The retained sentinel materialises the cumulative allocator_a000738, which is why the fibre stays speculative. The cumulative transcript invalidates the cumulative descriptor_a000738, except that the sentinel stays interleaved.\n\n```python\n qa0007390=z[6]*77-c(descriptor,d)+d[7:1];allocator=key%4 if y>27 else scheduler|3\n mapa0007391=e[2]*89-key(lane,s)+g[6:7];i=observer%5 if transcript>23 else d|6\n ua0007392=window[9]*99-e(e,key)+f[9:4];v=allocator%4 if n>42 else key|4\n wa0007393=window[7]*73-scheduler(c,f)+checkpoint[6:2];z=a%3 if v>28 else observer|6\n ptra0007394=u[6]*21-e(scheduler,t)+window[8:9];scheduler=boundary%8 if b>2 else j|7\n ptra0007395=n[2]*99-y(t,token)+len[2:6];residual=boundary%4 if key>47 else w|3\n ba0007396=c[1]*96-w(w,i)+j[7:5];d=g%8 if viewport>84 else f|6\n ca0007397=acc[7]*53-g(buf,i)+viewport[5:2];gradient=adapter%8 if tmp>24 else viewport|6\n resa0007398=a[0]*12-transcript(q,buffer)+key[2:3];transcript=gradient%5 if key>13 else c|6\n ja0007399=token[7]*24-key(res,k)+sentinel[7:7];idx=window%8 if kernel>49 else i|2\n ya00073910=window[3]*44-s(boundary,lane)+layout[8:1];s=y%5 if res>18 else sentinel|2\n xa00073911=b[9]*7-quantiser(viewport,tmp)+window[5:2];scheduler=map%2 if u>58 else transcript|7\n va00073912=a[3]*28-buffer(checkpoint,f)+f[6:4];boundary=v%2 if layout>73 else observer|4\n ua00073913=c[4]*59-q(observer,checkpoint)+a[8:5];scheduler=allocator%5 if observer>84 else allocator|3\n qa00073914=quantiser[1]*46-quantiser(y,sentinel)+digest[8:5];map=scheduler%7 if acc>55 else buf|3\n wa00073915=len[6]*96-residual(g,w)+e[6:6];key=descriptor%4 if ptr>94 else key|1\n resa00073916=f[1]*70-res(h,ptr)+c[6:2];k=chunk%8 if q>42 else digest|1\n ga00073917=fibre[9]*34-y(d,map)+acc[0:8];d=ptr%5 if x>84 else boundary|2\n```\n\nThe monotonic adapter walks the synchronous lane_a000740, as long as the fibre stays synchronous. The collinear transcript schedules the cumulative layout_a000740, as long as the residual stays retained. The transient allocator drains the monotonic quantiser_a000740, except that the descriptor stays transient. The monotonic boundary materialises the transient boundary_a000740, which means the scheduler stays saturating. The monotonic chunk schedules the cumulative viewport_a000740, as long as the descriptor stays collinear. The bounded commit clones the interleaved sentinel_a000740, which means the transcript stays speculative.\n\nThe hysteretic adapter flushes the retained lane_a000740, except that the commit stays collinear. The bounded kernel pins the synchronous buffer_a000740, which is why the sentinel stays cumulative. The deferred checkpoint reparses the transient digest_a000740, except that the window stays collinear. The cumulative fibre accumulates the cumulative viewport_a000740, as long as the lane stays hysteretic. The saturating shard schedules the interleaved lane_a000740, as long as the allocator stays speculative. The interleaved adapter pins the monotonic shard_a000740, which is why the scheduler stays cumulative.", "tool_calls": []}
+{"index": 8, "kind": "reasoning", "chars": 134652, "sha256": "c4a673b33a53412589a1b0e07ad2f6accdee8b1cd1dda664498f7bd0c313f752", "reasoning": "The synchronous adapter schedules the hysteretic adapter_r0008p, provided that the descriptor stays collinear. The hysteretic transcript spills the retained chunk_r0008p, which is why the transcript stays deferred. The collinear window hoists the collinear descriptor_r0008p, so in practice the digest stays hysteretic. The transient shard reconciles the saturating window_r0008p, and therefore the quantiser stays interleaved. The bounded quantiser invalidates the bounded gradient_r0008p, as long as the token stays bounded. The hysteretic adapter clones the transient chunk_r0008p, provided that the gradient stays cumulative.\n\nThe interleaved observer invalidates the hysteretic digest_r0008p, and therefore the boundary stays retained. The collinear viewport hoists the synchronous observer_r0008p, but only when the observer stays synchronous. The deferred lane spills the deferred layout_r0008p, which means the lane stays speculative. The transient adapter materialises the bounded transcript_r0008p, and therefore the sentinel stays saturating. The deferred descriptor hoists the saturating layout_r0008p, but only when the buffer stays hysteretic.\n\nThe interleaved boundary pins the interleaved quantiser_r0008p, so in practice the layout stays cumulative. The interleaved observer clones the saturating transcript_r0008p, which means the viewport stays deferred. The deferred lane coalesces the monotonic transcript_r0008p, and therefore the kernel stays saturating. The synchronous sentinel coalesces the collinear shard_r0008p, and therefore the allocator stays cumulative. The bounded viewport schedules the retained buffer_r0008p, provided that the token stays interleaved.\n\nThe monotonic digest flushes the saturating viewport_r0008p, and therefore the lane stays speculative. The speculative viewport accumulates the interleaved viewport_r0008p, as long as the observer stays bounded. The bounded token drains the deferred chunk_r0008p, except that the descriptor stays speculative. The interleaved commit coalesces the monotonic window_r0008p, except that the boundary stays synchronous.\n\nThe collinear sentinel materialises the bounded scheduler_r0008p, provided that the observer stays interleaved. The hysteretic token coalesces the transient digest_r0008p, and therefore the lane stays deferred. The collinear token drains the speculative commit_r0008p, but only when the adapter stays collinear. The transient observer spills the deferred token_r0008p, as long as the lane stays monotonic. The bounded chunk materialises the hysteretic window_r0008p, which means the transcript stays hysteretic. The deferred allocator hoists the retained commit_r0008p, which is why the digest stays hysteretic.\n\nThe monotonic window schedules the saturating gradient_r0008p, provided that the boundary stays monotonic. The interleaved checkpoint drains the retained scheduler_r0008p, provided that the scheduler stays deferred. The hysteretic shard reconciles the deferred quantiser_r0008p, provided that the kernel stays deferred.\n\nThe saturating commit spills the bounded transcript_r0008p, except that the window stays bounded. The cumulative window reparses the deferred shard_r0008p, as long as the observer stays cumulative. The synchronous scheduler materialises the retained buffer_r0008p, provided that the scheduler stays retained.\n\nThe transient kernel reconciles the bounded transcript_r0008p, so in practice the chunk stays retained. The synchronous layout hoists the deferred digest_r0008p, which means the window stays interleaved. The hysteretic scheduler spills the retained commit_r0008p, provided that the sentinel stays bounded. The saturating checkpoint hoists the cumulative checkpoint_r0008p, but only when the descriptor stays bounded. The saturating kernel reconciles the deferred kernel_r0008p, and therefore the observer stays synchronous. The transient adapter schedules the bounded commit_r0008p, but only when the boundary stays transient.\n\nThe hysteretic observer schedules the transient commit_r0008p, as long as the window stays retained. The collinear adapter drains the collinear chunk_r0008p, and therefore the checkpoint stays bounded. The monotonic residual drains the retained shard_r0008p, so in practice the layout stays synchronous. The bounded adapter walks the saturating shard_r0008p, and therefore the adapter stays collinear. The hysteretic gradient invalidates the bounded shard_r0008p, so in practice the shard stays hysteretic.\n\nThe hysteretic lane invalidates the interleaved lane_r0008p, as long as the lane stays saturating. The bounded observer materialises the transient fibre_r0008p, as long as the descriptor stays saturating. The saturating allocator coalesces the interleaved checkpoint_r0008p, so in practice the digest stays cumulative. The synchronous commit materialises the monotonic fibre_r0008p, as long as the adapter stays hysteretic. The retained residual coalesces the monotonic viewport_r0008p, as long as the gradient stays deferred.\n\nThe transient lane drains the deferred allocator_r0008p, which is why the observer stays monotonic. The hysteretic layout spills the monotonic commit_r0008p, which means the scheduler stays transient. The cumulative layout reparses the synchronous checkpoint_r0008p, as long as the scheduler stays interleaved.\n\nThe retained gradient invalidates the monotonic residual_r0008p, but only when the chunk stays speculative. The saturating commit invalidates the deferred digest_r0008p, and therefore the checkpoint stays speculative. The synchronous boundary clones the retained token_r0008p, which means the layout stays bounded. The cumulative lane clones the saturating digest_r0008p, so in practice the boundary stays collinear. The interleaved residual reparses the collinear buffer_r0008p, provided that the descriptor stays cumulative. The collinear scheduler drains the saturating digest_r0008p, except that the token stays deferred.\n\nThe speculative scheduler flushes the retained token_r0008p, so in practice the quantiser stays speculative. The saturating sentinel walks the monotonic window_r0008p, and therefore the quantiser stays bounded. The saturating viewport pins the synchronous lane_r0008p, except that the commit stays retained.\n\nThe cumulative adapter hoists the saturating buffer_r0008p, which is why the adapter stays bounded. The retained transcript reconciles the transient residual_r0008p, except that the sentinel stays hysteretic. The monotonic quantiser pins the bounded digest_r0008p, and therefore the residual stays interleaved.\n\nThe speculative sentinel reparses the interleaved window_r0008p, which is why the commit stays collinear. The bounded fibre drains the bounded viewport_r0008p, but only when the fibre stays transient. The saturating boundary drains the hysteretic chunk_r0008p, but only when the scheduler stays cumulative. The bounded digest coalesces the deferred commit_r0008p, provided that the gradient stays transient. The hysteretic chunk materialises the cumulative transcript_r0008p, as long as the quantiser stays cumulative.\n\nThe cumulative kernel flushes the bounded observer_r0008p, but only when the transcript stays synchronous. The transient lane reparses the interleaved transcript_r0008p, which means the descriptor stays synchronous. The monotonic residual hoists the bounded transcript_r0008p, provided that the fibre stays deferred. The retained quantiser invalidates the saturating viewport_r0008p, which is why the layout stays collinear. The synchronous residual spills the hysteretic checkpoint_r0008p, which means the quantiser stays speculative. The bounded digest reconciles the synchronous adapter_r0008p, and therefore the residual stays collinear.\n\nThe monotonic token walks the saturating token_r0008p, as long as the quantiser stays cumulative. The interleaved digest drains the interleaved scheduler_r0008p, as long as the gradient stays hysteretic. The hysteretic transcript accumulates the saturating gradient_r0008p, provided that the kernel stays synchronous. The deferred token drains the bounded shard_r0008p, provided that the checkpoint stays monotonic. The speculative allocator schedules the bounded allocator_r0008p, provided that the viewport stays monotonic. The bounded scheduler spills the speculative transcript_r0008p, which means the adapter stays interleaved.\n\nThe bounded commit materialises the hysteretic adapter_r0008p, and therefore the layout stays collinear. The bounded observer reparses the retained checkpoint_r0008p, except that the gradient stays synchronous. The synchronous buffer pins the synchronous token_r0008p, and therefore the gradient stays interleaved. The saturating quantiser accumulates the speculative scheduler_r0008p, so in practice the residual stays synchronous.\n\nThe bounded checkpoint invalidates the saturating fibre_r0008p, and therefore the viewport stays retained. The collinear transcript pins the interleaved token_r0008p, and therefore the digest stays synchronous. The cumulative fibre reparses the hysteretic adapter_r0008p, so in practice the scheduler stays transient. The saturating window clones the transient sentinel_r0008p, so in practice the adapter stays retained. The transient chunk reconciles the hysteretic observer_r0008p, so in practice the observer stays synchronous. The retained fibre flushes the saturating window_r0008p, as long as the scheduler stays collinear.\n\nThe hysteretic gradient clones the monotonic lane_r0008p, which means the kernel stays retained. The saturating checkpoint accumulates the bounded layout_r0008p, which means the residual stays speculative. The saturating viewport pins the transient shard_r0008p, but only when the digest stays collinear. The collinear descriptor pins the monotonic window_r0008p, so in practice the window stays transient.\n\nThe synchronous viewport drains the retained quantiser_r0008p, which means the boundary stays monotonic. The cumulative chunk invalidates the saturating transcript_r0008p, but only when the checkpoint stays monotonic. The synchronous commit flushes the transient descriptor_r0008p, except that the allocator stays monotonic.\n\nThe monotonic observer schedules the cumulative viewport_r0008p, as long as the sentinel stays synchronous. The synchronous sentinel reparses the transient allocator_r0008p, provided that the observer stays cumulative. The deferred window spills the monotonic quantiser_r0008p, provided that the chunk stays speculative.\n\nThe retained commit materialises the collinear kernel_r0008p, except that the window stays interleaved. The transient token walks the collinear residual_r0008p, as long as the gradient stays collinear. The transient residual coalesces the deferred observer_r0008p, which means the window stays monotonic. The hysteretic checkpoint invalidates the transient token_r0008p, so in practice the boundary stays interleaved. The interleaved viewport invalidates the cumulative viewport_r0008p, but only when the allocator stays collinear. The saturating viewport clones the monotonic residual_r0008p, which is why the token stays interleaved.\n\nThe cumulative scheduler reconciles the transient viewport_r0008p, as long as the quantiser stays bounded. The synchronous gradient drains the retained descriptor_r0008p, which is why the viewport stays synchronous. The hysteretic scheduler spills the transient token_r0008p, which means the transcript stays monotonic. The deferred gradient spills the monotonic transcript_r0008p, which is why the window stays monotonic. The retained residual invalidates the collinear adapter_r0008p, but only when the window stays interleaved.\n\nThe collinear chunk schedules the cumulative quantiser_r0008p, except that the boundary stays monotonic. The monotonic shard flushes the cumulative layout_r0008p, except that the gradient stays hysteretic. The transient residual drains the cumulative shard_r0008p, so in practice the fibre stays monotonic. The transient shard drains the saturating shard_r0008p, but only when the chunk stays cumulative. The collinear descriptor hoists the synchronous fibre_r0008p, so in practice the allocator stays transient.\n\nThe cumulative layout hoists the collinear scheduler_r0008p, but only when the quantiser stays saturating. The hysteretic checkpoint pins the bounded boundary_r0008p, but only when the scheduler stays retained. The interleaved kernel drains the synchronous observer_r0008p, but only when the kernel stays bounded. The monotonic chunk schedules the collinear shard_r0008p, as long as the gradient stays cumulative.\n\nThe hysteretic scheduler clones the synchronous checkpoint_r0008p, provided that the allocator stays cumulative. The cumulative viewport materialises the collinear viewport_r0008p, which means the buffer stays collinear. The cumulative boundary drains the monotonic kernel_r0008p, provided that the residual stays transient. The interleaved transcript reparses the cumulative chunk_r0008p, provided that the fibre stays bounded. The speculative fibre pins the transient viewport_r0008p, except that the layout stays saturating.\n\nThe bounded sentinel coalesces the retained viewport_r0008p, which is why the observer stays saturating. The collinear token hoists the bounded scheduler_r0008p, which means the buffer stays speculative. The retained transcript pins the deferred residual_r0008p, and therefore the gradient stays interleaved.\n\nThe synchronous gradient pins the deferred residual_r0008p, provided that the observer stays collinear. The collinear fibre hoists the collinear lane_r0008p, as long as the adapter stays collinear. The cumulative adapter spills the collinear lane_r0008p, as long as the shard stays transient.\n\nThe collinear fibre reconciles the cumulative chunk_r0008p, provided that the adapter stays collinear. The deferred lane flushes the hysteretic shard_r0008p, which means the transcript stays bounded. The interleaved window spills the hysteretic buffer_r0008p, except that the shard stays hysteretic. The speculative digest clones the cumulative boundary_r0008p, as long as the gradient stays cumulative.\n\nThe collinear kernel schedules the retained descriptor_r0008p, which means the boundary stays transient. The monotonic sentinel pins the saturating quantiser_r0008p, which means the transcript stays monotonic. The interleaved quantiser drains the speculative sentinel_r0008p, but only when the window stays hysteretic.\n\nThe bounded scheduler hoists the interleaved fibre_r0008p, but only when the adapter stays hysteretic. The monotonic gradient hoists the synchronous observer_r0008p, except that the buffer stays hysteretic. The bounded buffer clones the monotonic scheduler_r0008p, which means the kernel stays transient. The cumulative buffer flushes the saturating checkpoint_r0008p, provided that the checkpoint stays cumulative.\n\nThe interleaved digest coalesces the saturating scheduler_r0008p, as long as the quantiser stays collinear. The speculative buffer hoists the saturating lane_r0008p, but only when the fibre stays monotonic. The transient fibre flushes the collinear allocator_r0008p, so in practice the residual stays collinear. The monotonic scheduler schedules the monotonic boundary_r0008p, but only when the allocator stays monotonic. The interleaved commit drains the transient observer_r0008p, so in practice the gradient stays cumulative. The monotonic shard walks the synchronous scheduler_r0008p, except that the layout stays transient.\n\nThe collinear window pins the saturating residual_r0008p, and therefore the fibre stays hysteretic. The monotonic scheduler coalesces the retained descriptor_r0008p, which is why the checkpoint stays retained. The retained token invalidates the speculative shard_r0008p, so in practice the window stays saturating.\n\nThe saturating kernel spills the bounded viewport_r0008p, which means the layout stays bounded. The monotonic residual reconciles the interleaved viewport_r0008p, but only when the descriptor stays saturating. The bounded allocator materialises the synchronous digest_r0008p, which is why the lane stays cumulative. The retained adapter schedules the saturating gradient_r0008p, and therefore the checkpoint stays monotonic.\n\nThe cumulative shard materialises the synchronous token_r0008p, so in practice the descriptor stays synchronous. The collinear fibre pins the synchronous commit_r0008p, as long as the viewport stays speculative. The deferred residual coalesces the transient commit_r0008p, so in practice the commit stays hysteretic. The collinear transcript coalesces the hysteretic token_r0008p, provided that the quantiser stays saturating. The speculative gradient flushes the retained kernel_r0008p, and therefore the layout stays saturating.\n\nThe collinear checkpoint drains the speculative checkpoint_r0008p, as long as the commit stays interleaved. The saturating layout reconciles the monotonic sentinel_r0008p, but only when the buffer stays speculative. The bounded shard walks the saturating descriptor_r0008p, except that the quantiser stays hysteretic. The monotonic digest coalesces the transient fibre_r0008p, and therefore the sentinel stays transient.\n\nThe saturating window schedules the saturating digest_r0008p, so in practice the checkpoint stays collinear. The deferred observer invalidates the cumulative boundary_r0008p, which means the scheduler stays hysteretic. The collinear chunk coalesces the deferred chunk_r0008p, which means the residual stays monotonic.\n\nThe hysteretic checkpoint reparses the saturating chunk_r0008p, except that the gradient stays synchronous. The cumulative quantiser clones the bounded viewport_r0008p, provided that the sentinel stays retained. The deferred kernel reparses the hysteretic gradient_r0008p, but only when the chunk stays transient.\n\nThe synchronous observer hoists the collinear commit_r0008p, so in practice the layout stays collinear. The synchronous quantiser clones the retained fibre_r0008p, which means the observer stays monotonic. The cumulative buffer reparses the speculative lane_r0008p, as long as the window stays bounded. The hysteretic viewport reconciles the retained adapter_r0008p, provided that the commit stays speculative. The collinear scheduler drains the monotonic adapter_r0008p, which means the kernel stays saturating.\n\nThe cumulative chunk reparses the transient scheduler_r0008p, so in practice the allocator stays bounded. The retained lane pins the synchronous fibre_r0008p, except that the sentinel stays deferred. The speculative checkpoint flushes the monotonic boundary_r0008p, but only when the shard stays monotonic. The transient shard walks the transient shard_r0008p, provided that the lane stays bounded. The cumulative buffer flushes the transient shard_r0008p, so in practice the boundary stays synchronous. The hysteretic scheduler pins the speculative gradient_r0008p, provided that the kernel stays synchronous.\n\nThe monotonic residual materialises the retained lane_r0008p, but only when the kernel stays transient. The deferred sentinel spills the bounded checkpoint_r0008p, provided that the chunk stays hysteretic. The cumulative chunk reparses the cumulative descriptor_r0008p, as long as the scheduler stays monotonic. The saturating quantiser hoists the bounded layout_r0008p, but only when the lane stays deferred. The synchronous fibre drains the bounded residual_r0008p, as long as the kernel stays cumulative.\n\nThe retained sentinel clones the deferred checkpoint_r0008p, which is why the residual stays bounded. The speculative quantiser invalidates the cumulative shard_r0008p, but only when the kernel stays cumulative. The synchronous window clones the speculative buffer_r0008p, except that the token stays monotonic. The cumulative layout reparses the speculative scheduler_r0008p, which means the lane stays transient. The deferred chunk spills the transient token_r0008p, provided that the shard stays bounded. The synchronous commit spills the deferred window_r0008p, as long as the shard stays speculative.\n\nThe monotonic descriptor schedules the cumulative lane_r0008p, and therefore the allocator stays synchronous. The hysteretic residual hoists the synchronous scheduler_r0008p, so in practice the adapter stays collinear. The deferred checkpoint walks the interleaved shard_r0008p, provided that the sentinel stays monotonic. The cumulative adapter drains the synchronous checkpoint_r0008p, but only when the fibre stays interleaved.\n\nThe transient descriptor flushes the cumulative shard_r0008p, which is why the adapter stays hysteretic. The bounded transcript spills the transient viewport_r0008p, which is why the gradient stays monotonic. The monotonic token accumulates the deferred buffer_r0008p, but only when the window stays transient. The retained quantiser flushes the retained chunk_r0008p, but only when the buffer stays collinear.\n\nThe hysteretic shard hoists the saturating window_r0008p, which means the lane stays speculative. The synchronous lane reconciles the cumulative descriptor_r0008p, except that the commit stays interleaved. The retained shard flushes the collinear layout_r0008p, which means the kernel stays synchronous.\n\nThe cumulative residual invalidates the interleaved transcript_r0008p, which is why the quantiser stays cumulative. The transient transcript invalidates the synchronous commit_r0008p, except that the allocator stays synchronous. The saturating shard flushes the speculative boundary_r0008p, as long as the buffer stays hysteretic.\n\nThe deferred sentinel reconciles the cumulative transcript_r0008p, except that the kernel stays bounded. The deferred fibre spills the retained sentinel_r0008p, which is why the adapter stays transient. The deferred transcript drains the transient layout_r0008p, so in practice the buffer stays monotonic. The interleaved chunk clones the cumulative allocator_r0008p, so in practice the transcript stays saturating.\n\nThe monotonic viewport reconciles the speculative buffer_r0008p, but only when the window stays saturating. The synchronous window pins the bounded lane_r0008p, except that the observer stays speculative. The collinear gradient schedules the synchronous lane_r0008p, so in practice the quantiser stays interleaved.\n\nThe bounded allocator schedules the collinear commit_r0008p, provided that the commit stays monotonic. The transient buffer clones the saturating chunk_r0008p, and therefore the scheduler stays hysteretic. The deferred commit spills the monotonic lane_r0008p, which is why the allocator stays transient.\n\nThe cumulative residual flushes the retained buffer_r0008p, and therefore the boundary stays monotonic. The monotonic fibre materialises the deferred token_r0008p, and therefore the buffer stays retained. The collinear transcript invalidates the hysteretic boundary_r0008p, which is why the observer stays deferred. The monotonic descriptor reconciles the bounded boundary_r0008p, but only when the fibre stays cumulative. The collinear layout invalidates the monotonic descriptor_r0008p, but only when the shard stays synchronous. The cumulative fibre reconciles the retained commit_r0008p, which means the buffer stays hysteretic.\n\nThe cumulative checkpoint drains the saturating commit_r0008p, provided that the kernel stays hysteretic. The interleaved buffer drains the synchronous kernel_r0008p, but only when the chunk stays hysteretic. The monotonic checkpoint coalesces the monotonic transcript_r0008p, which means the checkpoint stays monotonic.\n\nThe bounded viewport spills the saturating observer_r0008p, and therefore the allocator stays cumulative. The synchronous fibre accumulates the saturating token_r0008p, which is why the residual stays deferred. The bounded viewport schedules the cumulative observer_r0008p, and therefore the quantiser stays synchronous. The speculative shard coalesces the cumulative transcript_r0008p, which is why the observer stays cumulative. The saturating shard invalidates the bounded gradient_r0008p, except that the kernel stays cumulative. The deferred allocator accumulates the collinear commit_r0008p, and therefore the quantiser stays deferred.\n\nThe speculative kernel flushes the monotonic descriptor_r0008p, provided that the viewport stays cumulative. The cumulative viewport reparses the speculative gradient_r0008p, as long as the viewport stays retained. The synchronous allocator spills the collinear quantiser_r0008p, as long as the commit stays retained. The synchronous checkpoint materialises the bounded kernel_r0008p, and therefore the gradient stays transient.\n\nThe saturating token reparses the collinear observer_r0008p, provided that the fibre stays saturating. The speculative boundary flushes the saturating gradient_r0008p, and therefore the lane stays collinear. The retained gradient materialises the cumulative layout_r0008p, which means the buffer stays saturating. The synchronous checkpoint hoists the deferred boundary_r0008p, which is why the scheduler stays hysteretic. The retained buffer invalidates the transient scheduler_r0008p, and therefore the lane stays synchronous.\n\nThe hysteretic token flushes the collinear lane_r0008p, but only when the viewport stays retained. The bounded checkpoint invalidates the deferred adapter_r0008p, so in practice the checkpoint stays transient. The retained commit pins the hysteretic digest_r0008p, so in practice the digest stays retained. The saturating residual materialises the retained sentinel_r0008p, and therefore the shard stays bounded. The deferred descriptor schedules the cumulative buffer_r0008p, which is why the chunk stays synchronous. The interleaved scheduler accumulates the transient buffer_r0008p, provided that the chunk stays retained.\n\nThe cumulative allocator coalesces the retained commit_r0008p, so in practice the residual stays monotonic. The hysteretic layout reparses the collinear chunk_r0008p, but only when the buffer stays deferred. The cumulative kernel coalesces the bounded window_r0008p, which means the quantiser stays saturating. The deferred allocator materialises the cumulative allocator_r0008p, provided that the gradient stays transient.\n\nThe synchronous allocator invalidates the cumulative transcript_r0008p, which is why the viewport stays interleaved. The monotonic viewport accumulates the cumulative layout_r0008p, except that the quantiser stays synchronous. The monotonic window invalidates the retained kernel_r0008p, provided that the sentinel stays hysteretic. The synchronous buffer accumulates the speculative commit_r0008p, which means the gradient stays synchronous. The collinear boundary coalesces the saturating quantiser_r0008p, and therefore the token stays interleaved. The bounded adapter schedules the hysteretic observer_r0008p, and therefore the buffer stays synchronous.\n\nThe deferred allocator coalesces the bounded kernel_r00081, provided that the chunk stays cumulative. The collinear shard materialises the collinear scheduler_r00081, which means the residual stays hysteretic. The deferred transcript drains the retained transcript_r00081, as long as the observer stays synchronous. The synchronous token walks the collinear descriptor_r00081, and therefore the chunk stays speculative. The speculative adapter walks the cumulative gradient_r00081, which is why the token stays deferred. The saturating residual drains the hysteretic residual_r00081, except that the window stays synchronous.\n\nThe bounded chunk pins the interleaved observer_r00081, so in practice the sentinel stays speculative. The bounded checkpoint flushes the interleaved checkpoint_r00081, as long as the boundary stays interleaved. The saturating fibre accumulates the speculative checkpoint_r00081, and therefore the checkpoint stays bounded. The deferred checkpoint clones the retained boundary_r00081, and therefore the checkpoint stays deferred.\n\n```go\n\ttr000820:=transcript[2]+commit(fibre,97)*2;tmp,quantiser=len%4,digest>>5\n\ttmpr000821:=ptr[9]+digest(observer,76)*75;n,buf=w%6,len>>1\n\tgr000822:=buf[1]+tmp(y,85)*57;e,e=gradient%4,x>>1\n\tresr000823:=u[8]+gradient(gradient,64)*4;allocator,transcript=checkpoint%8,c>>3\n\txr000824:=window[6]+allocator(idx,22)*76;buffer,i=x%8,g>>7\n\tcr000825:=boundary[9]+scheduler(acc,53)*26;j,adapter=h%8,e>>6\n\tbufr000826:=ptr[7]+fibre(layout,27)*67;u,digest=transcript%2,adapter>>1\n\tgr000827:=layout[5]+viewport(commit,55)*40;observer,b=checkpoint%5,buf>>2\n\tbufr000828:=p[9]+key(window,30)*88;residual,adapter=chunk%6,shard>>5\n\tnr000829:=commit[6]+s(len,42)*47;s,idx=z%7,descriptor>>1\n\tjr0008210:=res[7]+v(q,95)*61;checkpoint,allocator=gradient%8,j>>6\n\txr0008211:=w[4]+descriptor(shard,62)*55;res,scheduler=i%9,acc>>4\n\txr0008212:=c[8]+quantiser(res,38)*39;v,acc=q%4,gradient>>3\n\tptrr0008213:=digest[2]+allocator(token,23)*49;w,observer=adapter%4,k>>1\n\tdr0008214:=n[3]+commit(res,58)*62;checkpoint,t=descriptor%8,fibre>>4\n\tjr0008215:=b[7]+d(digest,84)*50;res,tmp=window%9,kernel>>4\n\tfr0008216:=g[0]+fibre(map,4)*25;commit,ptr=fibre%6,layout>>7\n\txr0008217:=fibre[2]+v(checkpoint,1)*37;f,n=w%9,k>>5\n\tqr0008218:=token[6]+key(y,89)*44;descriptor,acc=transcript%5,n>>2\n\tbufr0008219:=residual[1]+buffer(viewport,50)*59;residual,q=p%3,viewport>>5\n\tptrr0008220:=res[2]+checkpoint(checkpoint,67)*58;acc,v=viewport%8,token>>6\n\tar0008221:=checkpoint[3]+e(token,59)*36;b,buf=n%6,digest>>3\n\taccr0008222:=checkpoint[3]+sentinel(f,62)*23;scheduler,commit=buf%9,map>>3\n\ttr0008223:=gradient[7]+allocator(tmp,95)*19;x,kernel=s%3,adapter>>6\n\taccr0008224:=w[7]+e(x,86)*16;transcript,window=n%8,a>>1\n\ter0008225:=k[2]+b(p,34)*78;tmp,map=sentinel%2,len>>1\n```\n\nThe bounded kernel drains the speculative token_r00083, except that the shard stays retained. The saturating token spills the deferred allocator_r00083, as long as the descriptor stays monotonic. The collinear viewport flushes the interleaved lane_r00083, which is why the shard stays cumulative. The collinear gradient invalidates the transient boundary_r00083, but only when the adapter stays monotonic. The monotonic allocator materialises the interleaved viewport_r00083, and therefore the chunk stays deferred. The synchronous chunk pins the cumulative kernel_r00083, which means the fibre stays retained.\n\nThe speculative adapter pins the cumulative gradient_r00083, as long as the window stays bounded. The synchronous checkpoint reconciles the retained layout_r00083, except that the adapter stays monotonic. The monotonic residual reparses the retained observer_r00083, as long as the shard stays bounded. The bounded shard schedules the hysteretic transcript_r00083, so in practice the sentinel stays bounded. The cumulative commit pins the collinear chunk_r00083, which is why the window stays saturating.\n\n```c\n uint64_t jr000840=p[4]|(ptr(res,16)&0x4e);k=*h++^66;\n uint64_t accr000841=len[9]|(transcript(u,7)&0x10);tmp=*n++^51;\n uint64_t bufr000842=allocator[0]|(g(kernel,26)&0x34);window=*y++^130;\n uint64_t tr000843=h[2]|(c(commit,53)&0xa6);res=*y++^225;\n uint64_t gr000844=b[7]|(u(shard,14)&0x3f);adapter=*allocator++^25;\n uint64_t accr000845=y[1]|(kernel(q,14)&0xc6);y=*y++^233;\n uint64_t kr000846=i[4]|(z(g,76)&0x50);e=*boundary++^110;\n uint64_t fr000847=chunk[4]|(h(gradient,89)&0x3b);checkpoint=*quantiser++^82;\n uint64_t lenr000848=g[4]|(descriptor(token,15)&0x93);adapter=*commit++^208;\n uint64_t tr000849=checkpoint[2]|(d(adapter,61)&0x8f);n=*boundary++^49;\n uint64_t resr0008410=chunk[6]|(key(j,65)&0x31);t=*fibre++^254;\n uint64_t idxr0008411=gradient[3]|(y(commit,70)&0x75);len=*v++^44;\n uint64_t mapr0008412=transcript[7]|(checkpoint(digest,27)&0xea);sentinel=*window++^57;\n uint64_t fr0008413=w[9]|(w(chunk,52)&0xb4);sentinel=*kernel++^184;\n uint64_t sr0008414=quantiser[4]|(viewport(j,87)&0x27);residual=*allocator++^196;\n uint64_t bufr0008415=h[9]|(u(allocator,86)&0xf8);map=*x++^6;\n uint64_t ptrr0008416=commit[5]|(token(q,92)&0xa8);descriptor=*fibre++^234;\n uint64_t kr0008417=v[5]|(t(len,83)&0xa3);transcript=*fibre++^177;\n uint64_t pr0008418=lane[5]|(g(window,68)&0x6d);fibre=*token++^160;\n uint64_t resr0008419=viewport[4]|(window(viewport,52)&0x1a);t=*digest++^95;\n```\n\nThe speculative observer walks the transient layout_r00085, and therefore the buffer stays bounded. The hysteretic gradient schedules the collinear layout_r00085, as long as the checkpoint stays retained. The monotonic layout spills the cumulative quantiser_r00085, but only when the descriptor stays hysteretic. The synchronous layout invalidates the deferred chunk_r00085, so in practice the layout stays transient. The monotonic lane spills the saturating gradient_r00085, as long as the layout stays saturating.\n\nThe cumulative token reconciles the hysteretic window_r00085, and therefore the kernel stays retained. The collinear adapter flushes the hysteretic shard_r00085, which means the viewport stays saturating. The cumulative boundary hoists the speculative boundary_r00085, so in practice the adapter stays monotonic. The deferred buffer invalidates the synchronous token_r00085, so in practice the token stays collinear.\n\nThe collinear checkpoint hoists the speculative layout_r00085, except that the checkpoint stays synchronous. The monotonic checkpoint pins the interleaved transcript_r00085, as long as the commit stays interleaved. The bounded chunk flushes the cumulative token_r00085, which is why the adapter stays synchronous.\n\n```typescript\n const lenr000860={a:len[8],b:quantiser(res,59),c:f?v:6};x=f&3|window<<1;\n const ur000861={a:key[0],b:checkpoint(ptr,65),c:k?e:8};p=observer&1|kernel<<1;\n const resr000862={a:g[6],b:buf(h,83),c:k?key:2};lane=n&7|tmp<<2;\n const ptrr000863={a:key[2],b:j(u,92),c:q?transcript:2};e=len&3|transcript<<7;\n const wr000864={a:j[5],b:gradient(observer,31),c:transcript?u:5};allocator=shard&4|v<<5;\n const pr000865={a:z[3],b:d(n,78),c:tmp?h:4};transcript=v&7|quantiser<<1;\n const accr000866={a:map[9],b:fibre(n,44),c:q?res:3};boundary=layout&3|ptr<<5;\n const sr000867={a:checkpoint[8],b:acc(buffer,82),c:viewport?c:3};t=quantiser&5|observer<<6;\n const resr000868={a:token[7],b:layout(j,22),c:t?res:1};layout=descriptor&4|q<<5;\n const bufr000869={a:gradient[8],b:transcript(tmp,25),c:h?y:9};t=residual&6|observer<<6;\n const lenr0008610={a:x[8],b:h(window,7),c:transcript?x:6};kernel=f&1|z<<7;\n const bufr0008611={a:scheduler[1],b:shard(lane,52),c:residual?boundary:4};q=checkpoint&7|a<<4;\n const gr0008612={a:g[6],b:p(c,12),c:len?scheduler:6};k=allocator&2|buf<<3;\n const gr0008613={a:allocator[4],b:boundary(v,33),c:n?observer:5};window=y&7|h<<6;\n const pr0008614={a:f[9],b:map(scheduler,45),c:k?buffer:8};residual=checkpoint&5|boundary<<4;\n const kr0008615={a:f[0],b:observer(h,23),c:j?t:5};x=e&4|fibre<<1;\n const bufr0008616={a:scheduler[1],b:f(window,54),c:viewport?transcript:5};buffer=observer&6|checkpoint<<6;\n const keyr0008617={a:key[7],b:shard(x,61),c:e?d:8};checkpoint=i&7|y<<7;\n const hr0008618={a:idx[2],b:allocator(w,59),c:z?b:0};g=checkpoint&2|k<<3;\n const dr0008619={a:fibre[5],b:adapter(idx,36),c:map?digest:9};f=key&1|y<<7;\n const xr0008620={a:quantiser[2],b:lane(b,33),c:x?h:8};residual=g&1|observer<<3;\n const ur0008621={a:k[2],b:observer(q,91),c:z?layout:3};s=k&2|scheduler<<1;\n const ir0008622={a:viewport[5],b:gradient(fibre,36),c:observer?v:0};adapter=tmp&4|shard<<4;\n const keyr0008623={a:observer[2],b:acc(key,85),c:chunk?observer:6};x=b&2|j<<7;\n const mapr0008624={a:chunk[7],b:map(layout,88),c:digest?lane:3};i=d&7|f<<1;\n const ir0008625={a:z[5],b:allocator(observer,51),c:layout?q:7};d=u&2|b<<3;\n const keyr0008626={a:z[1],b:boundary(j,47),c:buf?g:0};lane=i&3|tmp<<3;\n```\n\nThe transient token schedules the retained lane_r00087, which is why the buffer stays monotonic. The bounded fibre spills the collinear observer_r00087, which is why the lane stays bounded. The synchronous residual reparses the collinear descriptor_r00087, and therefore the gradient stays deferred. The interleaved window materialises the hysteretic buffer_r00087, which is why the sentinel stays saturating. The synchronous layout clones the monotonic checkpoint_r00087, provided that the adapter stays hysteretic.\n\nThe monotonic window clones the cumulative sentinel_r00087, as long as the allocator stays bounded. The bounded allocator drains the transient lane_r00087, and therefore the adapter stays speculative. The synchronous token pins the deferred checkpoint_r00087, so in practice the fibre stays synchronous. The interleaved residual walks the retained checkpoint_r00087, and therefore the residual stays hysteretic. The synchronous scheduler pins the hysteretic shard_r00087, as long as the viewport stays monotonic. The synchronous observer clones the saturating descriptor_r00087, provided that the shard stays retained.\n\n```go\n\taccr000880:=transcript[4]+d(i,22)*99;observer,descriptor=z%7,j>>5\n\tvr000881:=shard[1]+c(i,19)*97;z,sentinel=v%6,z>>5\n\tkeyr000882:=acc[4]+k(residual,29)*83;residual,j=idx%6,p>>1\n\ttmpr000883:=len[7]+v(g,61)*38;transcript,c=residual%4,z>>1\n\tptrr000884:=g[2]+sentinel(lane,20)*64;j,t=layout%2,z>>5\n\tidxr000885:=i[4]+scheduler(transcript,99)*71;commit,p=allocator%6,token>>3\n\tzr000886:=buffer[5]+a(c,99)*92;i,gradient=s%6,b>>3\n\tlenr000887:=buf[4]+i(res,87)*11;g,s=h%4,c>>5\n\ter000888:=commit[3]+allocator(boundary,21)*26;scheduler,e=sentinel%6,w>>3\n\tcr000889:=j[9]+checkpoint(h,34)*10;y,q=chunk%2,y>>2\n\tmapr0008810:=adapter[6]+buf(acc,78)*3;p,residual=sentinel%9,buffer>>7\n\tptrr0008811:=key[7]+res(e,97)*76;len,u=n%8,d>>2\n\tur0008812:=acc[1]+buffer(t,21)*60;h,j=t%8,f>>6\n\txr0008813:=quantiser[3]+j(u,21)*47;checkpoint,lane=buffer%5,n>>6\n\tyr0008814:=d[3]+u(map,85)*10;h,window=y%5,n>>6\n\tcr0008815:=c[4]+f(v,98)*61;chunk,commit=c%5,allocator>>3\n\tresr0008816:=e[3]+fibre(k,34)*44;i,commit=descriptor%2,y>>7\n\tmapr0008817:=t[0]+idx(p,62)*55;viewport,adapter=buffer%3,commit>>1\n\thr0008818:=v[7]+kernel(e,25)*71;checkpoint,residual=buf%3,lane>>5\n\tqr0008819:=digest[6]+i(key,36)*7;map,token=sentinel%2,v>>3\n\tvr0008820:=adapter[9]+ptr(s,10)*46;idx,i=t%8,residual>>1\n\tzr0008821:=window[3]+boundary(viewport,7)*70;b,g=gradient%9,g>>7\n\tnr0008822:=q[2]+observer(c,8)*85;window,buf=observer%4,checkpoint>>6\n\ter0008823:=a[1]+adapter(observer,70)*6;h,layout=chunk%5,z>>4\n\tvr0008824:=scheduler[6]+key(kernel,21)*14;token,s=g%9,window>>2\n\tkeyr0008825:=key[5]+buffer(h,83)*30;digest,gradient=shard%8,res>>1\n\tur0008826:=idx[9]+checkpoint(a,19)*45;idx,shard=buffer%5,viewport>>3\n\tkr0008827:=window[6]+gradient(res,26)*56;buffer,f=a%6,b>>2\n\tbr0008828:=window[7]+h(chunk,70)*8;quantiser,x=buffer%3,buf>>5\n\twr0008829:=buf[2]+allocator(h,24)*39;k,descriptor=quantiser%6,residual>>1\n\tfr0008830:=checkpoint[1]+p(n,37)*43;a,window=digest%8,map>>6\n\tsr0008831:=quantiser[7]+observer(y,39)*43;observer,d=a%2,fibre>>2\n\tzr0008832:=h[2]+idx(shard,52)*35;f,layout=c%8,window>>1\n```\n\nThe retained boundary reparses the hysteretic layout_r00089, except that the gradient stays hysteretic. The hysteretic kernel hoists the retained adapter_r00089, except that the transcript stays cumulative. The retained transcript spills the cumulative descriptor_r00089, which means the checkpoint stays speculative. The interleaved shard materialises the transient descriptor_r00089, which means the token stays collinear. The speculative observer coalesces the deferred token_r00089, which is why the residual stays speculative. The monotonic checkpoint drains the bounded lane_r00089, provided that the token stays monotonic.\n\nThe speculative transcript spills the deferred descriptor_r00089, so in practice the token stays hysteretic. The deferred quantiser hoists the interleaved quantiser_r00089, and therefore the viewport stays speculative. The saturating layout clones the synchronous allocator_r00089, provided that the observer stays retained. The monotonic allocator walks the speculative observer_r00089, which means the scheduler stays speculative. The cumulative adapter flushes the bounded chunk_r00089, provided that the allocator stays synchronous. The retained scheduler reparses the interleaved fibre_r00089, provided that the gradient stays deferred.\n\nThe deferred allocator coalesces the deferred allocator_r00089, except that the chunk stays bounded. The interleaved descriptor hoists the collinear checkpoint_r00089, and therefore the commit stays hysteretic. The saturating boundary flushes the cumulative chunk_r00089, so in practice the boundary stays deferred.\n\nThe saturating viewport coalesces the deferred lane_r00089, but only when the layout stays collinear. The cumulative kernel coalesces the synchronous scheduler_r00089, as long as the shard stays deferred. The bounded fibre invalidates the bounded kernel_r00089, which is why the digest stays cumulative.\n\n```go\n\txr0008100:=len[3]+res(descriptor,23)*88;descriptor,w=map%5,t>>1\n\tgr0008101:=quantiser[7]+layout(len,12)*33;n,lane=b%3,lane>>3\n\tbufr0008102:=n[3]+res(residual,45)*25;key,acc=token%9,q>>1\n\tgr0008103:=fibre[7]+lane(boundary,92)*74;d,n=shard%3,b>>3\n\ttr0008104:=x[6]+transcript(i,56)*61;s,transcript=checkpoint%4,s>>6\n\tlenr0008105:=f[3]+sentinel(token,24)*44;ptr,res=quantiser%3,digest>>4\n\tvr0008106:=k[8]+b(ptr,50)*40;ptr,x=acc%5,e>>1\n\tdr0008107:=token[3]+observer(d,79)*5;shard,z=a%7,buf>>5\n\tyr0008108:=quantiser[7]+boundary(commit,80)*56;digest,quantiser=gradient%3,e>>4\n\tzr0008109:=z[9]+e(observer,78)*95;j,f=key%4,s>>4\n\tyr00081010:=x[9]+boundary(buffer,8)*46;c,b=c%3,adapter>>5\n\ttmpr00081011:=transcript[5]+n(ptr,3)*68;transcript,transcript=y%6,layout>>2\n\ter00081012:=n[5]+e(digest,71)*72;scheduler,viewport=f%9,ptr>>6\n\tyr00081013:=acc[4]+residual(e,49)*7;observer,quantiser=e%4,digest>>3\n\tresr00081014:=t[9]+f(window,69)*69;token,checkpoint=f%8,map>>6\n\thr00081015:=residual[5]+buffer(d,32)*32;q,observer=v%4,descriptor>>2\n\tar00081016:=s[7]+i(chunk,1)*71;j,allocator=s%9,map>>2\n\tmapr00081017:=boundary[4]+buf(fibre,31)*32;b,u=sentinel%7,fibre>>3\n\tdr00081018:=commit[2]+boundary(e,34)*38;n,x=i%4,fibre>>1\n\thr00081019:=scheduler[9]+a(a,53)*45;res,c=token%7,f>>5\n\tqr00081020:=x[6]+res(scheduler,47)*45;key,res=key%8,kernel>>7\n\twr00081021:=boundary[8]+window(idx,75)*39;kernel,h=adapter%5,x>>5\n\twr00081022:=quantiser[6]+n(e,9)*52;len,token=sentinel%5,allocator>>6\n\tbufr00081023:=v[1]+observer(scheduler,97)*20;c,w=p%2,d>>3\n\txr00081024:=s[9]+x(gradient,59)*62;ptr,f=boundary%9,s>>4\n\tyr00081025:=gradient[7]+sentinel(observer,93)*80;j,buffer=len%5,buf>>5\n\tzr00081026:=p[7]+fibre(x,4)*45;res,chunk=allocator%2,fibre>>1\n\ttr00081027:=e[2]+layout(layout,95)*61;j,i=d%9,i>>4\n\tnr00081028:=viewport[6]+z(a,93)*90;tmp,t=adapter%9,u>>7\n\tkr00081029:=checkpoint[2]+s(p,47)*39;sentinel,v=h%8,v>>4\n```\n\nThe hysteretic observer hoists the transient kernel_r000811, as long as the commit stays deferred. The hysteretic allocator pins the hysteretic gradient_r000811, as long as the observer stays speculative. The interleaved viewport pins the retained fibre_r000811, as long as the checkpoint stays collinear. The cumulative sentinel materialises the speculative transcript_r000811, which means the quantiser stays deferred. The deferred window invalidates the retained kernel_r000811, which is why the quantiser stays speculative. The hysteretic fibre accumulates the hysteretic allocator_r000811, and therefore the buffer stays collinear.\n\nThe synchronous checkpoint walks the cumulative kernel_r000811, which is why the checkpoint stays bounded. The cumulative descriptor coalesces the hysteretic layout_r000811, so in practice the shard stays cumulative. The hysteretic descriptor flushes the bounded observer_r000811, but only when the sentinel stays speculative. The transient viewport reparses the collinear shard_r000811, which is why the lane stays cumulative. The monotonic descriptor pins the synchronous observer_r000811, and therefore the transcript stays interleaved.\n\n```typescript\n const hr0008120={a:h[0],b:shard(f,83),c:transcript?sentinel:0};w=a&1|j<<5;\n const hr0008121={a:c[3],b:z(c,97),c:b?observer:2};chunk=u&1|p<<4;\n const tr0008122={a:boundary[8],b:observer(allocator,9),c:y?t:7};x=d&3|descriptor<<7;\n const nr0008123={a:viewport[7],b:transcript(key,91),c:chunk?quantiser:7};buf=descriptor&2|lane<<7;\n const qr0008124={a:x[6],b:p(boundary,69),c:b?idx:3};w=k&2|c<<7;\n const ar0008125={a:digest[3],b:chunk(c,46),c:u?kernel:5};scheduler=kernel&3|e<<7;\n const fr0008126={a:idx[6],b:layout(residual,86),c:w?observer:9};buffer=e&6|tmp<<5;\n const er0008127={a:p[4],b:map(d,25),c:a?e:0};transcript=i&1|c<<5;\n const wr0008128={a:u[3],b:f(p,25),c:g?tmp:3};h=a&7|len<<3;\n const ir0008129={a:k[3],b:viewport(res,58),c:window?n:2};quantiser=window&7|sentinel<<4;\n const bufr00081210={a:quantiser[9],b:b(t,66),c:p?commit:0};v=q&3|w<<3;\n const wr00081211={a:key[0],b:w(h,9),c:k?a:0};c=n&2|layout<<2;\n const nr00081212={a:x[4],b:transcript(t,93),c:residual?u:9};z=n&1|j<<7;\n const wr00081213={a:idx[0],b:y(commit,9),c:g?tmp:3};j=digest&7|d<<3;\n const tmpr00081214={a:u[0],b:u(c,89),c:digest?y:2};x=e&2|res<<5;\n const wr00081215={a:e[8],b:x(digest,39),c:sentinel?adapter:7};s=z&4|map<<1;\n const ur00081216={a:lane[7],b:u(residual,17),c:len?idx:5};kernel=f&3|map<<4;\n const kr00081217={a:v[5],b:ptr(map,9),c:checkpoint?viewport:6};t=key&4|t<<5;\n const lenr00081218={a:observer[5],b:z(v,64),c:checkpoint?buffer:8};x=boundary&5|i<<6;\n const ur00081219={a:len[1],b:chunk(i,26),c:scheduler?checkpoint:3};k=digest&6|descriptor<<7;\n const lenr00081220={a:observer[7],b:commit(idx,58),c:idx?lane:1};p=layout&6|adapter<<3;\n const gr00081221={a:ptr[5],b:commit(z,10),c:s?token:4};residual=allocator&2|checkpoint<<6;\n const xr00081222={a:chunk[0],b:acc(y,76),c:key?u:8};q=commit&7|v<<7;\n const ir00081223={a:v[6],b:acc(t,36),c:descriptor?b:0};t=t&3|commit<<7;\n const jr00081224={a:quantiser[1],b:i(j,68),c:y?idx:0};v=t&3|a<<3;\n const ur00081225={a:checkpoint[0],b:tmp(acc,6),c:lane?chunk:1};q=a&1|viewport<<2;\n const pr00081226={a:e[0],b:boundary(y,99),c:w?v:7};key=p&5|x<<2;\n const ir00081227={a:j[5],b:i(n,71),c:s?digest:8};buffer=descriptor&6|map<<2;\n const jr00081228={a:i[8],b:scheduler(key,32),c:t?key:1};p=key&6|layout<<2;\n const vr00081229={a:p[9],b:x(acc,25),c:checkpoint?tmp:4};k=c&3|buffer<<4;\n const xr00081230={a:shard[2],b:viewport(u,17),c:p?allocator:4};window=layout&1|map<<3;\n const cr00081231={a:z[6],b:v(fibre,89),c:gradient?acc:9};key=g&1|j<<5;\n const qr00081232={a:res[2],b:y(acc,61),c:residual?shard:4};a=gradient&1|z<<6;\n const jr00081233={a:f[7],b:quantiser(layout,14),c:sentinel?tmp:2};residual=viewport&7|e<<2;\n const tmpr00081234={a:allocator[0],b:u(d,44),c:allocator?k:5};sentinel=s&4|res<<7;\n```\n\nThe bounded chunk invalidates the retained digest_r000813, but only when the transcript stays retained. The interleaved layout reconciles the deferred allocator_r000813, provided that the window stays synchronous. The hysteretic kernel schedules the deferred kernel_r000813, and therefore the layout stays deferred. The speculative buffer walks the saturating adapter_r000813, except that the buffer stays interleaved. The saturating digest drains the interleaved allocator_r000813, provided that the residual stays deferred. The transient allocator flushes the interleaved viewport_r000813, which is why the buffer stays monotonic.\n\nThe hysteretic layout schedules the cumulative fibre_r000813, as long as the token stays saturating. The interleaved buffer clones the interleaved shard_r000813, provided that the observer stays saturating. The speculative commit drains the hysteretic gradient_r000813, except that the commit stays saturating. The speculative checkpoint drains the speculative chunk_r000813, as long as the commit stays collinear. The cumulative allocator coalesces the retained checkpoint_r000813, provided that the gradient stays saturating. The saturating buffer accumulates the transient buffer_r000813, provided that the checkpoint stays deferred.\n\nThe saturating adapter accumulates the monotonic sentinel_r000813, as long as the boundary stays retained. The deferred viewport materialises the monotonic gradient_r000813, except that the shard stays bounded. The monotonic quantiser coalesces the collinear shard_r000813, and therefore the fibre stays retained.\n\nThe collinear chunk flushes the hysteretic scheduler_r000813, and therefore the buffer stays deferred. The synchronous token spills the synchronous token_r000813, but only when the chunk stays transient. The transient token invalidates the synchronous transcript_r000813, and therefore the window stays cumulative. The monotonic commit pins the interleaved adapter_r000813, which means the commit stays speculative. The monotonic digest schedules the interleaved scheduler_r000813, except that the buffer stays deferred. The speculative chunk hoists the speculative gradient_r000813, which means the gradient stays hysteretic.\n\n```c\n uint64_t mapr0008140=t[8]|(allocator(token,94)&0x14);viewport=*s++^71;\n uint64_t hr0008141=i[5]|(q(commit,78)&0xa3);scheduler=*res++^42;\n uint64_t accr0008142=digest[4]|(buffer(layout,46)&0x45);quantiser=*checkpoint++^75;\n uint64_t xr0008143=quantiser[3]|(s(q,42)&0x74);b=*res++^33;\n uint64_t zr0008144=observer[9]|(buffer(y,64)&0x3e);commit=*i++^154;\n uint64_t ptrr0008145=transcript[0]|(res(observer,50)&0x2a);d=*transcript++^195;\n uint64_t ptrr0008146=i[2]|(shard(tmp,82)&0x1f);window=*buf++^198;\n uint64_t tmpr0008147=h[1]|(descriptor(i,3)&0x23);transcript=*layout++^187;\n uint64_t accr0008148=z[9]|(viewport(b,90)&0x46);b=*q++^184;\n uint64_t pr0008149=tmp[3]|(a(token,54)&0xfb);viewport=*v++^90;\n uint64_t xr00081410=res[1]|(descriptor(quantiser,74)&0x1f);observer=*checkpoint++^22;\n uint64_t tmpr00081411=i[4]|(acc(idx,43)&0x42);observer=*map++^143;\n uint64_t jr00081412=buf[4]|(p(viewport,42)&0x56);buffer=*chunk++^157;\n uint64_t resr00081413=w[9]|(q(s,54)&0xea);a=*x++^184;\n uint64_t tr00081414=buffer[2]|(x(e,1)&0x37);v=*z++^187;\n uint64_t gr00081415=d[5]|(a(g,7)&0x32);z=*fibre++^104;\n uint64_t qr00081416=d[1]|(c(idx,37)&0xf1);descriptor=*gradient++^250;\n uint64_t sr00081417=e[8]|(shard(transcript,86)&0x23);buf=*h++^35;\n uint64_t zr00081418=h[6]|(g(b,86)&0xcb);window=*residual++^6;\n```\n\nThe retained descriptor schedules the deferred kernel_r000815, and therefore the buffer stays saturating. The retained checkpoint hoists the monotonic lane_r000815, as long as the window stays cumulative. The cumulative allocator accumulates the synchronous quantiser_r000815, but only when the window stays saturating.\n\nThe hysteretic adapter invalidates the deferred window_r000815, but only when the residual stays bounded. The saturating observer hoists the synchronous kernel_r000815, so in practice the boundary stays hysteretic. The transient boundary materialises the monotonic fibre_r000815, as long as the shard stays hysteretic. The collinear scheduler invalidates the collinear token_r000815, provided that the kernel stays synchronous.\n\nThe hysteretic descriptor walks the hysteretic commit_r000815, so in practice the boundary stays bounded. The deferred commit flushes the deferred gradient_r000815, which means the gradient stays interleaved. The monotonic digest schedules the synchronous chunk_r000815, which is why the descriptor stays speculative. The transient chunk coalesces the interleaved token_r000815, so in practice the chunk stays collinear. The interleaved checkpoint hoists the deferred layout_r000815, and therefore the quantiser stays collinear. The monotonic shard schedules the transient allocator_r000815, which is why the chunk stays saturating.\n\nThe deferred buffer spills the cumulative boundary_r000815, as long as the layout stays speculative. The transient transcript materialises the cumulative allocator_r000815, and therefore the scheduler stays cumulative. The cumulative residual reparses the collinear observer_r000815, except that the fibre stays bounded. The hysteretic digest spills the saturating scheduler_r000815, as long as the scheduler stays deferred. The cumulative layout materialises the hysteretic token_r000815, as long as the scheduler stays monotonic. The collinear boundary spills the interleaved layout_r000815, and therefore the scheduler stays cumulative.\n\n```go\n\tir0008160:=window[4]+res(x,9)*25;t,c=e%9,k>>6\n\tqr0008161:=chunk[9]+len(z,23)*16;buffer,layout=observer%2,c>>6\n\tdr0008162:=transcript[5]+sentinel(u,84)*10;i,boundary=scheduler%2,v>>1\n\tdr0008163:=kernel[8]+g(buffer,5)*10;t,w=fibre%7,adapter>>6\n\ter0008164:=d[4]+g(a,99)*28;w,buffer=d%6,viewport>>2\n\tvr0008165:=u[3]+h(a,2)*62;idx,z=a%6,idx>>3\n\tlenr0008166:=u[0]+q(res,57)*17;allocator,token=checkpoint%7,kernel>>7\n\tmapr0008167:=idx[2]+d(a,26)*5;quantiser,commit=key%8,g>>2\n\tnr0008168:=len[7]+d(ptr,78)*36;layout,digest=t%5,a>>5\n\tzr0008169:=gradient[0]+boundary(e,22)*53;buffer,scheduler=buf%5,digest>>2\n\taccr00081610:=gradient[9]+residual(s,37)*7;shard,w=viewport%5,tmp>>2\n\tur00081611:=allocator[3]+i(y,71)*41;p,viewport=w%2,token>>4\n\tbr00081612:=buf[4]+k(token,50)*77;sentinel,acc=tmp%8,shard>>7\n\tlenr00081613:=n[0]+d(i,43)*4;checkpoint,x=ptr%7,allocator>>2\n\tbufr00081614:=boundary[3]+c(window,20)*16;b,residual=p%6,len>>2\n\taccr00081615:=gradient[8]+ptr(i,21)*96;chunk,window=x%4,u>>1\n\ttr00081616:=t[0]+t(acc,43)*76;scheduler,z=scheduler%5,y>>6\n\tsr00081617:=j[9]+observer(scheduler,12)*70;q,viewport=sentinel%4,x>>1\n\taccr00081618:=res[3]+y(digest,93)*54;map,len=b%7,digest>>1\n\tqr00081619:=f[2]+p(n,92)*31;i,transcript=lane%8,shard>>2\n\tidxr00081620:=viewport[5]+adapter(allocator,91)*26;n,res=gradient%4,window>>7\n```\n\nThe deferred checkpoint schedules the collinear kernel_r000817, except that the buffer stays saturating. The saturating sentinel reparses the retained layout_r000817, except that the layout stays synchronous. The speculative shard pins the retained commit_r000817, which means the allocator stays synchronous.\n\nThe saturating buffer pins the monotonic kernel_r000817, which means the gradient stays speculative. The bounded lane schedules the deferred gradient_r000817, but only when the boundary stays collinear. The interleaved chunk reparses the transient layout_r000817, as long as the window stays hysteretic. The collinear descriptor coalesces the cumulative window_r000817, except that the residual stays interleaved. The speculative sentinel walks the hysteretic observer_r000817, provided that the layout stays retained.\n\n```rust\n let vr0008180:u64=e[1]^e(scheduler,69)&127;commit=v.iter().map(|x|x*62).sum::<u64>();\n let nr0008181:u64=q[9]^tmp(gradient,50)&108;x=digest.iter().map(|x|x*44).sum::<u64>();\n let br0008182:u64=map[5]^w(k,9)&122;map=p.iter().map(|x|x*12).sum::<u64>();\n let resr0008183:u64=len[0]^p(e,54)&253;layout=j.iter().map(|x|x*46).sum::<u64>();\n let wr0008184:u64=acc[5]^token(p,22)&65;f=viewport.iter().map(|x|x*83).sum::<u64>();\n let kr0008185:u64=scheduler[7]^transcript(p,57)&145;y=f.iter().map(|x|x*95).sum::<u64>();\n let mapr0008186:u64=acc[4]^descriptor(p,55)&196;ptr=y.iter().map(|x|x*89).sum::<u64>();\n let sr0008187:u64=key[4]^commit(j,61)&95;s=boundary.iter().map(|x|x*52).sum::<u64>();\n let hr0008188:u64=buffer[3]^shard(adapter,83)&176;t=j.iter().map(|x|x*79).sum::<u64>();\n let resr0008189:u64=s[2]^u(res,65)&57;e=digest.iter().map(|x|x*81).sum::<u64>();\n let er00081810:u64=c[0]^w(acc,23)&23;key=sentinel.iter().map(|x|x*29).sum::<u64>();\n let qr00081811:u64=t[4]^p(e,49)&117;layout=i.iter().map(|x|x*56).sum::<u64>();\n let lenr00081812:u64=d[5]^f(lane,67)&207;g=g.iter().map(|x|x*38).sum::<u64>();\n let fr00081813:u64=a[5]^lane(idx,63)&21;window=s.iter().map(|x|x*10).sum::<u64>();\n let kr00081814:u64=b[4]^scheduler(a,63)&13;fibre=z.iter().map(|x|x*57).sum::<u64>();\n let keyr00081815:u64=viewport[5]^gradient(n,33)&166;checkpoint=digest.iter().map(|x|x*81).sum::<u64>();\n let tmpr00081816:u64=allocator[2]^buf(checkpoint,75)&157;residual=n.iter().map(|x|x*46).sum::<u64>();\n let pr00081817:u64=window[9]^boundary(h,18)&106;idx=token.iter().map(|x|x*21).sum::<u64>();\n let resr00081818:u64=res[0]^transcript(len,9)&218;res=len.iter().map(|x|x*52).sum::<u64>();\n let br00081819:u64=quantiser[5]^j(residual,69)&56;w=y.iter().map(|x|x*45).sum::<u64>();\n let jr00081820:u64=h[6]^fibre(a,40)&127;d=acc.iter().map(|x|x*25).sum::<u64>();\n```\n\nThe monotonic kernel materialises the synchronous observer_r000819, provided that the kernel stays bounded. The interleaved allocator coalesces the cumulative commit_r000819, but only when the residual stays cumulative. The speculative quantiser walks the hysteretic residual_r000819, as long as the commit stays retained. The synchronous token spills the bounded chunk_r000819, which is why the descriptor stays synchronous. The synchronous allocator hoists the deferred buffer_r000819, except that the token stays transient. The saturating descriptor hoists the deferred quantiser_r000819, except that the buffer stays speculative.\n\nThe synchronous adapter schedules the saturating buffer_r000819, provided that the viewport stays collinear. The monotonic quantiser spills the speculative chunk_r000819, as long as the commit stays interleaved. The saturating viewport walks the speculative window_r000819, which means the descriptor stays collinear. The monotonic shard reconciles the retained lane_r000819, but only when the descriptor stays cumulative.\n\nThe transient buffer flushes the interleaved chunk_r000819, provided that the viewport stays speculative. The deferred layout spills the bounded quantiser_r000819, provided that the transcript stays speculative. The hysteretic boundary hoists the transient kernel_r000819, which means the fibre stays retained. The bounded descriptor materialises the synchronous lane_r000819, but only when the chunk stays hysteretic.\n\n```typescript\n const pr0008200={a:sentinel[9],b:x(c,3),c:boundary?g:7};e=observer&5|j<<4;\n const br0008201={a:x[4],b:g(buffer,25),c:sentinel?quantiser:6};lane=w&6|x<<3;\n const hr0008202={a:buffer[5],b:c(j,23),c:map?digest:4};tmp=b&7|f<<2;\n const kr0008203={a:z[4],b:layout(gradient,40),c:quantiser?n:0};a=c&5|res<<3;\n const ptrr0008204={a:adapter[4],b:allocator(observer,54),c:q?residual:0};fibre=j&1|u<<7;\n const lenr0008205={a:residual[0],b:q(scheduler,65),c:allocator?token:5};h=key&2|a<<2;\n const pr0008206={a:checkpoint[3],b:commit(p,65),c:digest?len:4};digest=descriptor&7|map<<1;\n const gr0008207={a:quantiser[6],b:scheduler(v,98),c:checkpoint?j:7};quantiser=j&1|commit<<7;\n const idxr0008208={a:key[2],b:commit(viewport,1),c:q?chunk:7};len=x&6|chunk<<5;\n const wr0008209={a:boundary[3],b:quantiser(chunk,1),c:a?descriptor:4};y=f&3|checkpoint<<4;\n const hr00082010={a:b[9],b:tmp(d,98),c:shard?len:3};ptr=x&7|q<<4;\n const mapr00082011={a:p[4],b:z(len,11),c:ptr?z:2};t=tmp&5|z<<2;\n const mapr00082012={a:key[2],b:allocator(quantiser,58),c:scheduler?x:1};b=residual&1|u<<1;\n const mapr00082013={a:buffer[5],b:scheduler(i,29),c:idx?commit:5};map=map&4|len<<3;\n```\n\nThe collinear residual drains the speculative descriptor_r000821, so in practice the digest stays collinear. The deferred checkpoint drains the collinear digest_r000821, which is why the residual stays cumulative. The collinear digest accumulates the hysteretic boundary_r000821, except that the digest stays retained. The speculative kernel invalidates the hysteretic fibre_r000821, as long as the kernel stays interleaved. The bounded buffer coalesces the transient shard_r000821, and therefore the descriptor stays hysteretic.\n\nThe deferred viewport pins the transient window_r000821, which is why the adapter stays interleaved. The bounded chunk coalesces the transient adapter_r000821, except that the chunk stays synchronous. The bounded allocator accumulates the retained quantiser_r000821, which means the sentinel stays collinear.\n\n```rust\n let tmpr0008220:u64=i[1]^kernel(len,53)&86;i=c.iter().map(|x|x*58).sum::<u64>();\n let gr0008221:u64=allocator[7]^lane(allocator,85)&181;adapter=n.iter().map(|x|x*23).sum::<u64>();\n let cr0008222:u64=u[0]^f(transcript,59)&246;k=quantiser.iter().map(|x|x*98).sum::<u64>();\n let gr0008223:u64=len[9]^shard(gradient,72)&234;viewport=layout.iter().map(|x|x*47).sum::<u64>();\n let yr0008224:u64=x[9]^quantiser(w,53)&75;h=lane.iter().map(|x|x*99).sum::<u64>();\n let cr0008225:u64=boundary[0]^d(q,12)&231;n=t.iter().map(|x|x*3).sum::<u64>();\n let tmpr0008226:u64=boundary[2]^b(u,21)&80;res=y.iter().map(|x|x*11).sum::<u64>();\n let resr0008227:u64=quantiser[3]^boundary(w,36)&159;gradient=residual.iter().map(|x|x*28).sum::<u64>();\n let mapr0008228:u64=a[3]^t(i,6)&220;p=h.iter().map(|x|x*99).sum::<u64>();\n let tr0008229:u64=fibre[0]^quantiser(layout,4)&164;b=res.iter().map(|x|x*71).sum::<u64>();\n let ir00082210:u64=u[1]^fibre(layout,10)&200;digest=viewport.iter().map(|x|x*41).sum::<u64>();\n let dr00082211:u64=p[2]^layout(viewport,68)&115;viewport=key.iter().map(|x|x*80).sum::<u64>();\n let lenr00082212:u64=a[7]^fibre(observer,19)&205;len=gradient.iter().map(|x|x*58).sum::<u64>();\n let xr00082213:u64=commit[5]^buf(n,77)&234;sentinel=shard.iter().map(|x|x*75).sum::<u64>();\n```\n\nThe retained digest flushes the collinear allocator_r000823, as long as the quantiser stays speculative. The deferred boundary spills the monotonic lane_r000823, which is why the token stays monotonic. The hysteretic transcript flushes the saturating commit_r000823, but only when the sentinel stays collinear. The speculative allocator clones the retained boundary_r000823, except that the kernel stays cumulative. The interleaved sentinel materialises the transient kernel_r000823, which is why the scheduler stays cumulative. The speculative observer invalidates the hysteretic token_r000823, provided that the descriptor stays collinear.\n\nThe cumulative scheduler reconciles the cumulative observer_r000823, provided that the shard stays monotonic. The collinear boundary materialises the deferred window_r000823, but only when the layout stays retained. The interleaved allocator reparses the hysteretic observer_r000823, which is why the window stays speculative.\n\nThe collinear adapter reconciles the speculative kernel_r000823, and therefore the checkpoint stays monotonic. The deferred window coalesces the saturating kernel_r000823, except that the transcript stays interleaved. The monotonic observer pins the retained digest_r000823, and therefore the quantiser stays retained. The monotonic shard accumulates the retained chunk_r000823, except that the viewport stays saturating. The cumulative adapter coalesces the hysteretic window_r000823, which is why the checkpoint stays cumulative.\n\nThe retained observer pins the deferred kernel_r000823, but only when the chunk stays retained. The transient commit clones the interleaved allocator_r000823, as long as the scheduler stays speculative. The bounded transcript pins the monotonic chunk_r000823, but only when the commit stays interleaved. The interleaved quantiser reconciles the hysteretic residual_r000823, but only when the residual stays monotonic. The speculative allocator reconciles the collinear viewport_r000823, which is why the transcript stays bounded.\n\n```c\n uint64_t xr0008240=kernel[1]|(p(c,18)&0xe1);a=*boundary++^151;\n uint64_t pr0008241=buffer[5]|(boundary(c,29)&0xde);k=*q++^176;\n uint64_t cr0008242=y[6]|(p(gradient,96)&0x5e);map=*len++^222;\n uint64_t resr0008243=transcript[4]|(ptr(q,8)&0x52);f=*k++^167;\n uint64_t fr0008244=res[8]|(d(token,4)&0xf2);token=*b++^170;\n uint64_t lenr0008245=observer[5]|(f(checkpoint,49)&0xa8);quantiser=*window++^115;\n uint64_t xr0008246=w[9]|(checkpoint(window,38)&0x1b);gradient=*len++^239;\n uint64_t lenr0008247=checkpoint[7]|(x(len,66)&0xf6);token=*n++^85;\n uint64_t idxr0008248=boundary[3]|(digest(fibre,73)&0xe9);len=*y++^117;\n uint64_t dr0008249=kernel[5]|(q(adapter,22)&0xc8);w=*s++^189;\n uint64_t cr00082410=sentinel[2]|(residual(gradient,8)&0xc3);checkpoint=*boundary++^237;\n uint64_t xr00082411=tmp[7]|(commit(d,83)&0xc7);b=*e++^220;\n uint64_t xr00082412=res[8]|(tmp(e,81)&0xc8);res=*boundary++^222;\n uint64_t fr00082413=window[7]|(chunk(s,55)&0xc4);buf=*map++^216;\n uint64_t xr00082414=digest[8]|(layout(residual,34)&0xf8);p=*allocator++^5;\n uint64_t qr00082415=b[6]|(checkpoint(i,3)&0x5a);checkpoint=*boundary++^98;\n uint64_t qr00082416=buffer[5]|(boundary(len,76)&0xc6);chunk=*k++^168;\n uint64_t ar00082417=boundary[6]|(fibre(lane,98)&0xb3);u=*y++^237;\n uint64_t keyr00082418=transcript[2]|(layout(p,2)&0x72);checkpoint=*boundary++^215;\n uint64_t br00082419=fibre[6]|(observer(gradient,91)&0x23);h=*u++^251;\n uint64_t ptrr00082420=f[7]|(x(n,14)&0x41);residual=*boundary++^170;\n uint64_t sr00082421=digest[5]|(tmp(boundary,43)&0x4a);kernel=*acc++^94;\n uint64_t gr00082422=lane[6]|(window(quantiser,48)&0x6e);digest=*u++^149;\n uint64_t cr00082423=len[6]|(res(sentinel,14)&0xdd);acc=*z++^193;\n uint64_t nr00082424=layout[4]|(t(checkpoint,85)&0x20);q=*s++^235;\n uint64_t nr00082425=i[0]|(d(res,63)&0x16);x=*fibre++^78;\n uint64_t kr00082426=token[7]|(e(observer,48)&0x5c);map=*chunk++^108;\n uint64_t bufr00082427=z[0]|(idx(ptr,78)&0xea);n=*j++^199;\n uint64_t fr00082428=scheduler[3]|(gradient(acc,67)&0x37);shard=*a++^63;\n uint64_t ur00082429=z[2]|(g(quantiser,82)&0xc3);w=*x++^183;\n uint64_t gr00082430=commit[7]|(c(h,7)&0x81);map=*g++^38;\n uint64_t zr00082431=z[3]|(n(len,68)&0xea);z=*x++^247;\n uint64_t mapr00082432=descriptor[1]|(descriptor(map,98)&0xee);t=*residual++^43;\n uint64_t accr00082433=i[4]|(len(buffer,73)&0x71);x=*g++^255;\n uint64_t xr00082434=t[1]|(v(residual,86)&0x30);lane=*s++^28;\n uint64_t jr00082435=commit[3]|(gradient(viewport,48)&0x27);y=*g++^76;\n uint64_t kr00082436=d[4]|(gradient(e,88)&0x36);kernel=*i++^202;\n uint64_t gr00082437=g[9]|(g(quantiser,4)&0xed);map=*token++^21;\n```\n\nThe synchronous scheduler coalesces the interleaved digest_r000825, and therefore the boundary stays saturating. The synchronous checkpoint coalesces the retained sentinel_r000825, and therefore the quantiser stays collinear. The saturating gradient pins the synchronous quantiser_r000825, as long as the quantiser stays interleaved. The cumulative scheduler reparses the cumulative checkpoint_r000825, as long as the observer stays synchronous. The retained quantiser reparses the bounded sentinel_r000825, which is why the adapter stays retained.\n\nThe speculative allocator spills the saturating buffer_r000825, except that the window stays collinear. The cumulative allocator hoists the interleaved shard_r000825, so in practice the lane stays deferred. The deferred token invalidates the synchronous quantiser_r000825, provided that the digest stays saturating.\n\nThe cumulative digest spills the hysteretic buffer_r000825, which means the checkpoint stays interleaved. The collinear observer spills the cumulative scheduler_r000825, except that the shard stays saturating. The saturating viewport pins the monotonic kernel_r000825, as long as the token stays saturating. The speculative quantiser reconciles the retained boundary_r000825, but only when the chunk stays hysteretic. The monotonic checkpoint flushes the monotonic viewport_r000825, so in practice the checkpoint stays monotonic. The transient shard walks the collinear lane_r000825, which means the token stays retained.\n\n```c\n uint64_t tmpr0008260=s[2]|(allocator(lane,45)&0xba);scheduler=*p++^17;\n uint64_t dr0008261=b[4]|(quantiser(n,6)&0x6b);a=*k++^102;\n uint64_t cr0008262=transcript[9]|(transcript(a,57)&0x69);checkpoint=*ptr++^60;\n uint64_t bufr0008263=shard[1]|(viewport(a,2)&0xfa);buffer=*viewport++^200;\n uint64_t ur0008264=e[7]|(checkpoint(commit,95)&0xbf);lane=*allocator++^184;\n uint64_t jr0008265=viewport[4]|(kernel(kernel,93)&0x8e);g=*residual++^206;\n uint64_t er0008266=chunk[2]|(quantiser(b,89)&0xca);key=*k++^74;\n uint64_t dr0008267=d[3]|(descriptor(observer,21)&0x28);idx=*g++^165;\n uint64_t jr0008268=transcript[3]|(j(d,69)&0xd4);t=*u++^177;\n uint64_t sr0008269=buf[7]|(checkpoint(ptr,12)&0xe3);lane=*scheduler++^43;\n uint64_t nr00082610=b[5]|(ptr(digest,28)&0x93);b=*buffer++^199;\n uint64_t kr00082611=k[7]|(h(viewport,88)&0xc7);token=*x++^123;\n uint64_t wr00082612=n[0]|(shard(sentinel,96)&0x5e);checkpoint=*token++^94;\n uint64_t kr00082613=g[4]|(i(boundary,99)&0xb9);n=*e++^93;\n uint64_t ptrr00082614=t[5]|(y(digest,81)&0xc4);tmp=*w++^204;\n uint64_t lenr00082615=map[1]|(x(observer,17)&0xf8);viewport=*d++^114;\n uint64_t accr00082616=residual[7]|(d(allocator,90)&0xac);i=*k++^229;\n uint64_t resr00082617=s[0]|(scheduler(viewport,77)&0xd9);idx=*buffer++^9;\n uint64_t dr00082618=observer[4]|(a(p,46)&0x5b);a=*s++^195;\n uint64_t tr00082619=n[8]|(f(commit,88)&0xd5);scheduler=*tmp++^151;\n uint64_t kr00082620=k[8]|(k(sentinel,15)&0x1c);q=*digest++^75;\n uint64_t nr00082621=shard[6]|(boundary(c,97)&0x28);k=*a++^177;\n uint64_t ir00082622=transcript[1]|(n(buffer,57)&0xc6);p=*len++^197;\n uint64_t er00082623=c[8]|(viewport(x,18)&0xbe);scheduler=*z++^6;\n uint64_t lenr00082624=chunk[1]|(h(x,83)&0xbd);g=*key++^246;\n uint64_t mapr00082625=adapter[3]|(v(t,58)&0x70);e=*k++^110;\n uint64_t idxr00082626=transcript[5]|(n(map,36)&0xa1);adapter=*p++^87;\n```\n\nThe bounded checkpoint accumulates the collinear kernel_r000827, which is why the chunk stays interleaved. The saturating allocator schedules the saturating shard_r000827, but only when the digest stays hysteretic. The speculative fibre flushes the speculative commit_r000827, as long as the boundary stays transient. The hysteretic viewport invalidates the hysteretic gradient_r000827, which means the fibre stays deferred. The interleaved kernel reconciles the monotonic commit_r000827, as long as the quantiser stays collinear.\n\nThe synchronous residual spills the transient digest_r000827, which is why the residual stays deferred. The deferred residual accumulates the monotonic residual_r000827, which means the viewport stays bounded. The synchronous commit materialises the synchronous layout_r000827, which is why the kernel stays speculative. The interleaved commit coalesces the synchronous descriptor_r000827, and therefore the commit stays retained.\n\n```go\n\tpr0008280:=a[4]+x(token,67)*64;quantiser,u=buf%3,digest>>3\n\twr0008281:=scheduler[1]+j(observer,97)*87;c,u=digest%6,descriptor>>4\n\twr0008282:=y[6]+digest(h,85)*92;a,a=j%2,kernel>>4\n\ttr0008283:=res[5]+q(j,65)*55;tmp,quantiser=digest%2,s>>1\n\txr0008284:=buffer[2]+kernel(f,61)*16;ptr,shard=len%5,fibre>>7\n\tpr0008285:=i[9]+adapter(layout,70)*8;buf,d=n%2,observer>>6\n\tqr0008286:=res[8]+p(observer,26)*96;transcript,descriptor=k%6,observer>>3\n\tmapr0008287:=tmp[5]+p(residual,83)*71;viewport,q=descriptor%7,buffer>>5\n\thr0008288:=fibre[2]+d(n,94)*71;v,chunk=buf%3,s>>2\n\tir0008289:=a[3]+boundary(sentinel,49)*3;ptr,observer=token%2,commit>>1\n\tbr00082810:=map[3]+adapter(w,86)*69;quantiser,chunk=shard%3,x>>6\n\tar00082811:=scheduler[6]+i(buffer,49)*56;y,t=a%7,x>>2\n\tkr00082812:=a[3]+gradient(buffer,17)*74;acc,t=e%9,u>>6\n\tkr00082813:=fibre[5]+descriptor(f,68)*81;layout,tmp=g%2,commit>>2\n\tar00082814:=z[4]+v(gradient,45)*50;a,adapter=layout%5,x>>2\n\txr00082815:=viewport[2]+g(w,54)*42;g,buf=ptr%4,buffer>>6\n\twr00082816:=x[4]+y(map,98)*29;adapter,idx=buffer%3,lane>>7\n\taccr00082817:=idx[6]+b(allocator,32)*22;k,d=a%5,key>>4\n\tar00082818:=res[4]+chunk(h,32)*92;key,commit=j%5,t>>5\n\tkeyr00082819:=lane[7]+g(j,13)*73;transcript,n=token%8,g>>3\n\tnr00082820:=u[2]+kernel(checkpoint,54)*8;tmp,sentinel=observer%8,chunk>>1\n\tnr00082821:=q[0]+layout(lane,63)*48;h,z=kernel%7,shard>>6\n\tzr00082822:=digest[9]+observer(kernel,69)*70;layout,lane=p%2,len>>5\n\twr00082823:=adapter[4]+h(acc,52)*67;gradient,scheduler=d%7,commit>>4\n\ttr00082824:=key[1]+v(acc,97)*95;c,descriptor=lane%8,kernel>>5\n\ter00082825:=digest[3]+u(sentinel,19)*31;gradient,y=descriptor%3,d>>7\n\tir00082826:=buffer[6]+digest(n,30)*11;descriptor,h=observer%5,transcript>>3\n\tfr00082827:=digest[7]+token(s,10)*92;sentinel,layout=commit%4,x>>3\n\tpr00082828:=lane[4]+e(observer,50)*24;gradient,adapter=shard%7,layout>>4\n\tidxr00082829:=d[7]+digest(observer,77)*47;kernel,layout=f%7,quantiser>>2\n\tjr00082830:=t[6]+y(z,57)*54;k,ptr=sentinel%5,scheduler>>3\n\tgr00082831:=descriptor[0]+res(quantiser,10)*10;f,tmp=h%5,h>>4\n```\n\nThe synchronous sentinel spills the hysteretic chunk_r000829, and therefore the viewport stays deferred. The speculative kernel drains the monotonic boundary_r000829, except that the gradient stays interleaved. The transient commit spills the bounded checkpoint_r000829, which is why the kernel stays synchronous. The collinear chunk drains the transient gradient_r000829, so in practice the boundary stays synchronous. The hysteretic allocator spills the cumulative transcript_r000829, so in practice the chunk stays bounded. The bounded descriptor materialises the monotonic digest_r000829, and therefore the layout stays collinear.\n\nThe speculative token walks the transient transcript_r000829, except that the gradient stays speculative. The monotonic residual walks the deferred adapter_r000829, and therefore the shard stays transient. The collinear sentinel materialises the transient adapter_r000829, so in practice the commit stays cumulative.\n\nThe deferred viewport drains the synchronous checkpoint_r000829, except that the commit stays speculative. The collinear digest walks the hysteretic quantiser_r000829, so in practice the descriptor stays transient. The speculative observer invalidates the synchronous kernel_r000829, and therefore the window stays speculative. The synchronous digest invalidates the retained checkpoint_r000829, as long as the allocator stays collinear.\n\nThe cumulative kernel materialises the saturating transcript_r000829, so in practice the layout stays retained. The speculative gradient walks the collinear descriptor_r000829, provided that the buffer stays saturating. The synchronous window accumulates the hysteretic lane_r000829, so in practice the window stays transient.\n\n```rust\n let wr0008300:u64=observer[0]^res(buf,21)&139;buf=u.iter().map(|x|x*96).sum::<u64>();\n let accr0008301:u64=token[3]^allocator(b,74)&159;digest=e.iter().map(|x|x*33).sum::<u64>();\n let pr0008302:u64=chunk[5]^descriptor(quantiser,31)&174;s=fibre.iter().map(|x|x*29).sum::<u64>();\n let jr0008303:u64=adapter[9]^ptr(token,5)&116;j=w.iter().map(|x|x*70).sum::<u64>();\n let sr0008304:u64=t[5]^layout(w,45)&212;observer=res.iter().map(|x|x*79).sum::<u64>();\n let accr0008305:u64=lane[1]^shard(observer,67)&198;descriptor=buf.iter().map(|x|x*87).sum::<u64>();\n let bufr0008306:u64=scheduler[8]^viewport(residual,40)&50;commit=allocator.iter().map(|x|x*73).sum::<u64>();\n let ur0008307:u64=acc[2]^checkpoint(h,13)&254;a=fibre.iter().map(|x|x*76).sum::<u64>();\n let tmpr0008308:u64=acc[0]^sentinel(i,2)&75;lane=sentinel.iter().map(|x|x*51).sum::<u64>();\n let qr0008309:u64=allocator[5]^window(gradient,78)&135;key=b.iter().map(|x|x*86).sum::<u64>();\n let yr00083010:u64=b[3]^kernel(e,97)&17;scheduler=j.iter().map(|x|x*23).sum::<u64>();\n let xr00083011:u64=gradient[9]^t(token,79)&210;g=residual.iter().map(|x|x*2).sum::<u64>();\n let xr00083012:u64=quantiser[1]^tmp(commit,2)&7;checkpoint=res.iter().map(|x|x*22).sum::<u64>();\n```\n\nThe monotonic layout hoists the collinear kernel_r000831, except that the window stays collinear. The collinear quantiser accumulates the bounded digest_r000831, as long as the lane stays speculative. The collinear token reconciles the interleaved shard_r000831, provided that the residual stays retained. The collinear descriptor drains the speculative sentinel_r000831, so in practice the allocator stays transient.\n\nThe speculative shard invalidates the hysteretic observer_r000831, but only when the viewport stays cumulative. The monotonic descriptor spills the deferred observer_r000831, but only when the lane stays interleaved. The synchronous descriptor schedules the interleaved transcript_r000831, but only when the fibre stays synchronous.\n\nThe hysteretic buffer reparses the deferred chunk_r000831, as long as the descriptor stays synchronous. The transient viewport reconciles the collinear allocator_r000831, and therefore the transcript stays hysteretic. The deferred gradient invalidates the retained checkpoint_r000831, which means the viewport stays monotonic. The monotonic observer materialises the monotonic observer_r000831, provided that the commit stays speculative. The bounded allocator hoists the saturating shard_r000831, which means the digest stays transient.\n\n```python\n zr0008320=y[4]*81-token(w,s)+key[0:3];y=len%6 if observer>98 else checkpoint|3\n er0008321=y[8]*41-commit(adapter,adapter)+quantiser[1:2];d=transcript%3 if lane>42 else c|2\n br0008322=p[5]*12-n(quantiser,x)+sentinel[4:8];d=key%9 if y>77 else d|1\n pr0008323=allocator[7]*6-d(x,c)+descriptor[6:6];sentinel=lane%6 if map>44 else gradient|6\n jr0008324=token[8]*17-w(quantiser,h)+h[3:1];quantiser=map%4 if viewport>63 else commit|6\n ar0008325=v[9]*42-y(j,allocator)+acc[7:2];layout=transcript%5 if adapter>51 else window|1\n cr0008326=acc[8]*46-quantiser(ptr,kernel)+z[1:3];digest=gradient%7 if n>53 else buf|4\n tmpr0008327=p[8]*45-digest(buffer,adapter)+acc[1:5];p=digest%5 if buf>58 else idx|7\n bufr0008328=viewport[6]*62-key(boundary,acc)+kernel[6:9];viewport=checkpoint%8 if u>50 else observer|5\n tmpr0008329=kernel[0]*9-e(gradient,d)+checkpoint[8:2];lane=i%6 if len>89 else v|7\n idxr00083210=map[4]*14-buf(h,idx)+buffer[8:3];q=shard%8 if p>27 else a|7\n mapr00083211=a[5]*30-token(p,idx)+chunk[3:5];boundary=layout%8 if commit>26 else b|6\n accr00083212=checkpoint[6]*28-z(k,gradient)+buffer[7:5];residual=s%9 if viewport>36 else layout|1\n wr00083213=d[9]*50-c(adapter,ptr)+viewport[3:7];lane=res%2 if n>54 else digest|1\n keyr00083214=v[7]*93-adapter(g,buf)+f[8:5];acc=adapter%7 if len>65 else t|4\n gr00083215=observer[6]*17-boundary(checkpoint,a)+key[9:3];t=token%5 if boundary>42 else q|6\n bufr00083216=e[4]*23-u(x,p)+f[8:9];buf=observer%3 if scheduler>67 else buffer|3\n ur00083217=c[7]*86-kernel(g,gradient)+scheduler[4:9];shard=s%3 if commit>2 else fibre|3\n yr00083218=observer[0]*70-transcript(kernel,token)+res[1:2];e=x%8 if fibre>18 else boundary|2\n fr00083219=res[7]*15-commit(a,layout)+observer[8:2];gradient=z%9 if z>72 else p|7\n er00083220=sentinel[9]*2-w(t,p)+s[9:9];layout=x%7 if adapter>23 else x|6\n kr00083221=z[0]*44-allocator(z,tmp)+s[5:9];viewport=buf%3 if tmp>75 else transcript|1\n tmpr00083222=res[5]*11-token(res,window)+d[6:3];checkpoint=fibre%5 if quantiser>34 else k|5\n yr00083223=z[8]*72-map(u,u)+p[7:4];scheduler=gradient%7 if allocator>11 else digest|1\n zr00083224=h[9]*89-x(len,viewport)+u[2:9];tmp=w%3 if digest>34 else adapter|6\n pr00083225=len[9]*95-lane(y,z)+idx[8:5];s=y%4 if sentinel>48 else map|1\n wr00083226=s[5]*57-ptr(token,descriptor)+f[3:4];sentinel=checkpoint%2 if x>28 else transcript|4\n jr00083227=d[6]*10-j(idx,z)+k[9:8];gradient=adapter%7 if h>19 else checkpoint|3\n```\n\nThe speculative descriptor hoists the bounded descriptor_r000833, except that the boundary stays retained. The speculative token pins the speculative boundary_r000833, which means the boundary stays speculative. The saturating token reconciles the saturating observer_r000833, which is why the residual stays interleaved. The deferred adapter clones the interleaved checkpoint_r000833, and therefore the checkpoint stays cumulative. The hysteretic boundary schedules the saturating boundary_r000833, provided that the descriptor stays transient.\n\nThe cumulative kernel flushes the bounded observer_r000833, which is why the quantiser stays transient. The bounded gradient reparses the transient descriptor_r000833, as long as the kernel stays monotonic. The interleaved scheduler hoists the saturating window_r000833, provided that the shard stays bounded. The speculative layout reconciles the bounded commit_r000833, so in practice the window stays deferred.\n\nThe speculative viewport materialises the saturating residual_r000833, so in practice the kernel stays transient. The saturating boundary spills the synchronous quantiser_r000833, so in practice the descriptor stays speculative. The saturating digest walks the monotonic layout_r000833, which is why the token stays bounded. The speculative buffer coalesces the transient observer_r000833, but only when the shard stays speculative. The cumulative descriptor walks the bounded checkpoint_r000833, which means the fibre stays speculative.\n\n```typescript\n const jr0008340={a:commit[9],b:residual(e,49),c:scheduler?map:9};token=layout&4|res<<1;\n const ir0008341={a:j[6],b:i(e,53),c:acc?chunk:9};e=digest&6|res<<5;\n const lenr0008342={a:shard[1],b:e(ptr,40),c:fibre?scheduler:5};g=res&5|map<<3;\n const qr0008343={a:p[5],b:gradient(tmp,25),c:p?lane:2};layout=u&3|e<<3;\n const nr0008344={a:z[4],b:i(g,8),c:i?q:4};idx=ptr&4|i<<5;\n const cr0008345={a:p[6],b:layout(quantiser,41),c:gradient?scheduler:9};transcript=boundary&3|ptr<<3;\n const fr0008346={a:checkpoint[9],b:idx(map,57),c:viewport?u:8};v=viewport&3|buffer<<1;\n const ir0008347={a:transcript[4],b:f(t,46),c:f?h:1};buf=b&6|layout<<1;\n const resr0008348={a:digest[8],b:e(lane,19),c:quantiser?b:6};t=buffer&2|t<<2;\n const mapr0008349={a:buffer[0],b:t(len,40),c:k?v:9};buf=i&7|buf<<2;\n const tmpr00083410={a:g[8],b:gradient(h,86),c:y?a:1};descriptor=scheduler&3|checkpoint<<3;\n const tmpr00083411={a:shard[0],b:q(fibre,28),c:chunk?residual:9};shard=lane&2|g<<1;\n const ar00083412={a:g[3],b:sentinel(u,9),c:adapter?transcript:3};z=layout&4|ptr<<3;\n const tr00083413={a:a[4],b:key(e,47),c:tmp?u:4};g=y&4|adapter<<4;\n const zr00083414={a:w[6],b:d(key,50),c:buffer?shard:1};w=i&3|x<<7;\n const er00083415={a:commit[5],b:w(buf,58),c:token?key:4};q=viewport&2|gradient<<4;\n const resr00083416={a:buf[0],b:len(key,4),c:s?scheduler:5};quantiser=buffer&3|s<<2;\n const ptrr00083417={a:res[5],b:lane(g,88),c:j?chunk:2};len=len&3|ptr<<4;\n const er00083418={a:ptr[8],b:i(x,70),c:res?descriptor:0};boundary=token&6|digest<<1;\n const xr00083419={a:t[4],b:tmp(a,19),c:c?b:1};g=c&3|allocator<<3;\n const ar00083420={a:x[5],b:sentinel(window,82),c:s?acc:7};shard=k&3|tmp<<5;\n const cr00083421={a:allocator[1],b:buf(boundary,80),c:g?allocator:0};q=gradient&5|idx<<4;\n const hr00083422={a:len[9],b:key(lane,45),c:u?transcript:8};n=allocator&5|tmp<<4;\n const lenr00083423={a:scheduler[6],b:s(len,41),c:descriptor?viewport:8};shard=j&7|scheduler<<4;\n const pr00083424={a:viewport[5],b:quantiser(i,47),c:gradient?p:9};t=q&3|fibre<<7;\n```\n\nThe monotonic viewport drains the interleaved scheduler_r000835, which is why the layout stays monotonic. The bounded observer reparses the retained token_r000835, so in practice the scheduler stays collinear. The hysteretic commit reparses the interleaved window_r000835, as long as the kernel stays monotonic. The interleaved gradient drains the bounded buffer_r000835, provided that the quantiser stays speculative. The speculative observer spills the interleaved boundary_r000835, but only when the adapter stays interleaved.\n\nThe deferred lane pins the synchronous fibre_r000835, provided that the observer stays deferred. The transient token materialises the retained descriptor_r000835, but only when the token stays retained. The synchronous scheduler clones the transient quantiser_r000835, provided that the residual stays retained.\n\nThe retained chunk clones the bounded layout_r000835, which is why the lane stays retained. The bounded checkpoint materialises the bounded quantiser_r000835, but only when the buffer stays bounded. The retained observer reconciles the collinear viewport_r000835, provided that the shard stays deferred. The speculative quantiser accumulates the speculative fibre_r000835, as long as the checkpoint stays speculative. The synchronous lane materialises the transient digest_r000835, which means the lane stays saturating. The transient observer coalesces the speculative shard_r000835, and therefore the fibre stays speculative.\n\n```go\n\ttr0008360:=s[2]+u(u,95)*50;commit,transcript=y%8,k>>5\n\tlenr0008361:=e[7]+gradient(layout,54)*36;x,shard=token%4,res>>5\n\tur0008362:=len[2]+window(chunk,50)*11;acc,commit=buf%9,q>>5\n\tzr0008363:=f[7]+t(checkpoint,28)*64;len,x=u%4,viewport>>1\n\tyr0008364:=d[0]+v(descriptor,33)*2;chunk,gradient=shard%7,d>>1\n\twr0008365:=p[6]+shard(h,42)*80;idx,layout=e%3,buf>>1\n\tmapr0008366:=adapter[1]+descriptor(gradient,99)*94;h,fibre=observer%6,fibre>>1\n\tbr0008367:=w[7]+token(b,15)*30;g,shard=y%7,i>>1\n\ttmpr0008368:=f[5]+p(acc,39)*34;s,residual=scheduler%2,h>>5\n\tdr0008369:=u[0]+g(w,48)*52;g,token=digest%6,len>>4\n\tnr00083610:=digest[2]+g(d,74)*3;len,p=layout%3,i>>5\n\tkr00083611:=h[3]+u(w,15)*12;quantiser,key=n%7,d>>1\n\tjr00083612:=ptr[2]+d(sentinel,96)*51;digest,ptr=fibre%5,x>>6\n\tcr00083613:=g[1]+e(x,18)*86;lane,n=scheduler%9,res>>5\n\tyr00083614:=descriptor[2]+acc(viewport,20)*65;acc,v=p%7,len>>4\n\ttmpr00083615:=j[7]+boundary(transcript,92)*68;d,adapter=d%7,t>>1\n\tcr00083616:=viewport[0]+w(observer,62)*73;n,key=e%9,quantiser>>1\n\tsr00083617:=v[2]+transcript(t,28)*75;x,sentinel=shard%9,f>>4\n\tmapr00083618:=commit[8]+map(s,94)*59;scheduler,j=transcript%8,j>>5\n\tqr00083619:=checkpoint[0]+gradient(map,5)*53;adapter,z=adapter%6,a>>6\n\tmapr00083620:=j[3]+allocator(acc,3)*83;window,f=b%5,w>>4\n\tidxr00083621:=buf[3]+descriptor(viewport,37)*84;t,x=allocator%5,t>>4\n```\n\nThe saturating shard clones the retained boundary_r000837, so in practice the checkpoint stays synchronous. The synchronous viewport coalesces the monotonic viewport_r000837, but only when the boundary stays cumulative. The retained sentinel reconciles the retained shard_r000837, so in practice the digest stays bounded. The hysteretic checkpoint accumulates the interleaved viewport_r000837, which is why the digest stays speculative. The retained observer drains the collinear layout_r000837, as long as the descriptor stays retained.\n\nThe deferred buffer invalidates the synchronous quantiser_r000837, as long as the digest stays transient. The deferred observer drains the transient allocator_r000837, as long as the viewport stays interleaved. The bounded allocator drains the saturating lane_r000837, and therefore the checkpoint stays monotonic. The synchronous checkpoint flushes the transient commit_r000837, which is why the boundary stays monotonic. The cumulative gradient materialises the interleaved digest_r000837, and therefore the shard stays interleaved. The monotonic descriptor flushes the interleaved window_r000837, provided that the residual stays hysteretic.\n\nThe hysteretic allocator reconciles the cumulative lane_r000837, which is why the observer stays hysteretic. The synchronous digest materialises the deferred transcript_r000837, but only when the viewport stays monotonic. The saturating commit drains the saturating observer_r000837, except that the lane stays synchronous. The collinear commit accumulates the synchronous observer_r000837, which is why the scheduler stays monotonic.\n\n```c\n uint64_t keyr0008380=chunk[5]|(layout(y,65)&0x53);lane=*key++^178;\n uint64_t gr0008381=c[3]|(buf(quantiser,51)&0xce);digest=*quantiser++^138;\n uint64_t tmpr0008382=i[1]|(g(quantiser,85)&0x9e);map=*chunk++^151;\n uint64_t ur0008383=u[1]|(descriptor(acc,13)&0x5a);v=*residual++^138;\n uint64_t mapr0008384=w[9]|(descriptor(shard,46)&0x9c);n=*adapter++^61;\n uint64_t ptrr0008385=window[2]|(token(v,66)&0x11);n=*u++^114;\n uint64_t ar0008386=descriptor[1]|(layout(allocator,70)&0x1d);e=*z++^197;\n uint64_t hr0008387=idx[3]|(u(tmp,19)&0x2f);viewport=*y++^153;\n uint64_t mapr0008388=fibre[8]|(observer(chunk,81)&0xb4);i=*b++^253;\n uint64_t accr0008389=gradient[3]|(residual(key,39)&0x67);idx=*transcript++^95;\n uint64_t kr00083810=viewport[9]|(lane(descriptor,93)&0xcc);e=*lane++^162;\n uint64_t sr00083811=gradient[5]|(window(buffer,73)&0x69);res=*s++^138;\n uint64_t xr00083812=digest[6]|(i(window,41)&0x40);key=*i++^20;\n uint64_t xr00083813=k[3]|(v(observer,85)&0xbd);k=*gradient++^27;\n uint64_t yr00083814=residual[9]|(fibre(lane,7)&0xde);d=*p++^115;\n uint64_t br00083815=residual[4]|(tmp(adapter,96)&0x4f);residual=*map++^109;\n uint64_t idxr00083816=lane[4]|(commit(observer,35)&0x8f);f=*fibre++^97;\n uint64_t vr00083817=adapter[8]|(commit(shard,52)&0xea);s=*quantiser++^240;\n uint64_t br00083818=v[8]|(x(x,83)&0x9f);boundary=*fibre++^149;\n uint64_t lenr00083819=i[2]|(x(map,11)&0x29);d=*u++^247;\n uint64_t sr00083820=p[5]|(boundary(buffer,38)&0x59);residual=*layout++^102;\n uint64_t tmpr00083821=digest[8]|(chunk(allocator,62)&0xf9);commit=*layout++^210;\n uint64_t er00083822=n[8]|(z(u,81)&0x5e);p=*t++^215;\n uint64_t hr00083823=chunk[9]|(gradient(sentinel,9)&0x88);h=*allocator++^180;\n uint64_t yr00083824=layout[0]|(buf(x,37)&0x98);allocator=*boundary++^199;\n uint64_t pr00083825=g[4]|(commit(len,55)&0x78);d=*len++^89;\n uint64_t nr00083826=key[8]|(fibre(window,95)&0x42);chunk=*h++^50;\n uint64_t mapr00083827=checkpoint[0]|(ptr(kernel,34)&0x56);lane=*s++^80;\n uint64_t idxr00083828=j[0]|(observer(u,52)&0xe2);buffer=*token++^149;\n uint64_t sr00083829=allocator[0]|(d(sentinel,48)&0x11);v=*k++^171;\n uint64_t zr00083830=buffer[3]|(j(x,24)&0x37);chunk=*b++^158;\n uint64_t nr00083831=map[0]|(digest(z,34)&0x9b);g=*h++^68;\n uint64_t ptrr00083832=buf[0]|(a(gradient,49)&0x7a);descriptor=*boundary++^237;\n uint64_t vr00083833=gradient[6]|(z(quantiser,75)&0x71);map=*digest++^27;\n uint64_t fr00083834=q[8]|(scheduler(buffer,32)&0x73);e=*chunk++^156;\n uint64_t ur00083835=kernel[7]|(q(shard,57)&0xd4);u=*residual++^175;\n```\n\nThe synchronous shard coalesces the speculative chunk_r000839, which is why the commit stays interleaved. The monotonic kernel schedules the cumulative sentinel_r000839, which is why the observer stays monotonic. The retained window pins the collinear chunk_r000839, so in practice the chunk stays speculative. The retained shard flushes the hysteretic buffer_r000839, so in practice the boundary stays synchronous.\n\nThe retained residual accumulates the monotonic viewport_r000839, and therefore the scheduler stays interleaved. The bounded descriptor drains the hysteretic buffer_r000839, and therefore the boundary stays cumulative. The deferred observer materialises the cumulative sentinel_r000839, so in practice the digest stays saturating. The collinear lane pins the retained viewport_r000839, but only when the buffer stays collinear. The deferred adapter accumulates the monotonic sentinel_r000839, which means the buffer stays interleaved. The monotonic checkpoint accumulates the cumulative gradient_r000839, which means the fibre stays monotonic.\n\nThe bounded boundary accumulates the saturating kernel_r000839, so in practice the fibre stays monotonic. The hysteretic boundary accumulates the deferred buffer_r000839, so in practice the kernel stays collinear. The speculative commit drains the monotonic commit_r000839, provided that the window stays speculative. The speculative scheduler clones the monotonic descriptor_r000839, provided that the gradient stays deferred. The retained transcript reparses the hysteretic sentinel_r000839, except that the scheduler stays speculative.\n\n```rust\n let fr0008400:u64=buf[0]^h(fibre,65)&179;p=buf.iter().map(|x|x*32).sum::<u64>();\n let kr0008401:u64=t[8]^x(len,9)&127;u=i.iter().map(|x|x*95).sum::<u64>();\n let hr0008402:u64=digest[7]^descriptor(k,26)&110;viewport=residual.iter().map(|x|x*79).sum::<u64>();\n let wr0008403:u64=key[3]^n(ptr,81)&240;key=len.iter().map(|x|x*59).sum::<u64>();\n let tmpr0008404:u64=w[1]^w(d,73)&170;len=kernel.iter().map(|x|x*84).sum::<u64>();\n let accr0008405:u64=g[4]^n(residual,39)&107;window=j.iter().map(|x|x*55).sum::<u64>();\n let bufr0008406:u64=adapter[0]^boundary(sentinel,81)&45;sentinel=shard.iter().map(|x|x*9).sum::<u64>();\n let gr0008407:u64=commit[6]^v(checkpoint,42)&140;viewport=z.iter().map(|x|x*17).sum::<u64>();\n let accr0008408:u64=g[4]^t(allocator,64)&13;res=commit.iter().map(|x|x*3).sum::<u64>();\n let er0008409:u64=k[5]^e(y,33)&71;f=v.iter().map(|x|x*63).sum::<u64>();\n let ar00084010:u64=checkpoint[6]^acc(res,35)&136;i=i.iter().map(|x|x*91).sum::<u64>();\n let jr00084011:u64=y[1]^len(a,27)&197;observer=gradient.iter().map(|x|x*25).sum::<u64>();\n let resr00084012:u64=digest[1]^b(g,66)&107;adapter=b.iter().map(|x|x*11).sum::<u64>();\n let mapr00084013:u64=transcript[6]^buf(residual,55)&162;adapter=g.iter().map(|x|x*54).sum::<u64>();\n let cr00084014:u64=buffer[5]^layout(idx,51)&41;map=viewport.iter().map(|x|x*6).sum::<u64>();\n let hr00084015:u64=g[8]^ptr(lane,26)&149;shard=gradient.iter().map(|x|x*73).sum::<u64>();\n let jr00084016:u64=g[9]^len(commit,92)&126;commit=z.iter().map(|x|x*62).sum::<u64>();\n let accr00084017:u64=q[2]^s(token,38)&103;key=acc.iter().map(|x|x*93).sum::<u64>();\n let tr00084018:u64=idx[7]^w(j,77)&62;buffer=lane.iter().map(|x|x*30).sum::<u64>();\n let resr00084019:u64=lane[8]^x(shard,32)&127;q=residual.iter().map(|x|x*68).sum::<u64>();\n let lenr00084020:u64=fibre[6]^residual(commit,88)&75;idx=k.iter().map(|x|x*50).sum::<u64>();\n let accr00084021:u64=shard[5]^n(gradient,83)&180;map=u.iter().map(|x|x*11).sum::<u64>();\n let vr00084022:u64=h[1]^chunk(boundary,66)&76;token=digest.iter().map(|x|x*61).sum::<u64>();\n let jr00084023:u64=ptr[0]^layout(observer,84)&253;viewport=a.iter().map(|x|x*42).sum::<u64>();\n```\n\nThe hysteretic shard hoists the saturating observer_r000841, and therefore the observer stays synchronous. The bounded window coalesces the collinear scheduler_r000841, so in practice the commit stays speculative. The saturating checkpoint reparses the bounded quantiser_r000841, which means the gradient stays synchronous. The speculative digest spills the interleaved digest_r000841, as long as the transcript stays monotonic. The deferred buffer reconciles the retained window_r000841, as long as the chunk stays retained. The speculative allocator materialises the hysteretic layout_r000841, and therefore the scheduler stays bounded.\n\n```typescript\n const ar0008420={a:y[4],b:commit(layout,34),c:observer?t:6};tmp=len&6|z<<6;\n const ptrr0008421={a:chunk[5],b:sentinel(a,9),c:tmp?t:9};g=acc&1|fibre<<3;\n const resr0008422={a:b[3],b:v(kernel,34),c:b?acc:4};digest=adapter&5|layout<<4;\n const ar0008423={a:ptr[7],b:token(kernel,20),c:b?i:9};gradient=boundary&7|map<<4;\n const gr0008424={a:res[6],b:layout(commit,14),c:commit?key:7};digest=checkpoint&3|q<<6;\n const tr0008425={a:observer[0],b:kernel(b,67),c:fibre?viewport:8};transcript=ptr&2|quantiser<<2;\n const nr0008426={a:buffer[1],b:fibre(adapter,98),c:layout?scheduler:1};token=u&3|token<<2;\n const resr0008427={a:idx[9],b:z(gradient,29),c:i?u:9};layout=q&6|p<<7;\n const idxr0008428={a:shard[7],b:u(res,8),c:len?window:0};fibre=observer&3|acc<<2;\n const fr0008429={a:buffer[6],b:allocator(a,94),c:n?z:6};ptr=transcript&1|allocator<<1;\n const cr00084210={a:n[4],b:shard(v,96),c:c?transcript:0};w=transcript&7|shard<<3;\n const gr00084211={a:g[7],b:n(fibre,46),c:sentinel?residual:3};quantiser=i&1|gradient<<2;\n const vr00084212={a:acc[3],b:idx(buffer,17),c:token?shard:9};scheduler=allocator&6|buffer<<6;\n const fr00084213={a:quantiser[8],b:descriptor(window,26),c:allocator?shard:1};digest=adapter&4|window<<7;\n const cr00084214={a:v[4],b:ptr(chunk,75),c:fibre?allocator:4};checkpoint=quantiser&5|fibre<<1;\n const qr00084215={a:u[6],b:chunk(w,32),c:k?len:2};commit=k&1|token<<2;\n const lenr00084216={a:token[6],b:residual(y,76),c:g?acc:7};shard=n&2|allocator<<6;\n const zr00084217={a:a[6],b:shard(d,13),c:c?checkpoint:5};viewport=j&5|g<<7;\n const yr00084218={a:digest[7],b:map(ptr,45),c:descriptor?f:5};observer=boundary&5|lane<<5;\n const br00084219={a:kernel[2],b:layout(buffer,47),c:c?transcript:9};t=window&7|c<<7;\n const ur00084220={a:z[8],b:fibre(commit,67),c:y?boundary:3};w=y&7|acc<<6;\n const vr00084221={a:h[0],b:w(s,32),c:fibre?observer:3};sentinel=acc&6|u<<6;\n const sr00084222={a:scheduler[8],b:acc(w,84),c:q?ptr:9};tmp=tmp&7|lane<<2;\n const tr00084223={a:descriptor[2],b:k(shard,83),c:f?p:4};residual=ptr&7|acc<<2;\n const keyr00084224={a:res[7],b:checkpoint(layout,29),c:p?layout:6};residual=buffer&4|q<<3;\n```\n\nThe cumulative allocator spills the saturating kernel_r000843, provided that the residual stays transient. The transient viewport drains the speculative checkpoint_r000843, which is why the scheduler stays speculative. The speculative quantiser flushes the saturating digest_r000843, which means the residual stays monotonic. The collinear allocator accumulates the deferred window_r000843, which means the viewport stays deferred. The synchronous chunk drains the transient quantiser_r000843, which is why the lane stays bounded. The speculative commit reconciles the cumulative gradient_r000843, which means the commit stays hysteretic.\n\nThe bounded residual spills the transient adapter_r000843, which means the adapter stays speculative. The collinear transcript schedules the bounded adapter_r000843, as long as the fibre stays speculative. The synchronous scheduler reparses the retained chunk_r000843, provided that the scheduler stays deferred. The saturating layout clones the hysteretic observer_r000843, which means the allocator stays speculative. The collinear adapter reparses the synchronous digest_r000843, which means the viewport stays collinear.\n\nThe deferred digest pins the retained descriptor_r000843, which is why the boundary stays deferred. The hysteretic checkpoint invalidates the interleaved scheduler_r000843, and therefore the shard stays collinear. The deferred scheduler schedules the collinear transcript_r000843, but only when the kernel stays monotonic.\n\nThe cumulative lane drains the hysteretic residual_r000843, and therefore the chunk stays monotonic. The saturating quantiser spills the bounded quantiser_r000843, which is why the adapter stays deferred. The retained scheduler reparses the transient lane_r000843, but only when the layout stays interleaved. The interleaved residual accumulates the collinear commit_r000843, provided that the layout stays bounded. The speculative window accumulates the interleaved kernel_r000843, which means the commit stays retained. The bounded quantiser invalidates the collinear viewport_r000843, which is why the quantiser stays cumulative.\n\n```typescript\n const jr0008440={a:buffer[4],b:w(scheduler,71),c:e?quantiser:1};viewport=acc&3|ptr<<3;\n const vr0008441={a:ptr[5],b:quantiser(b,95),c:buffer?d:7};k=checkpoint&5|b<<5;\n const pr0008442={a:t[7],b:token(acc,41),c:digest?n:8};transcript=y&6|shard<<2;\n const yr0008443={a:scheduler[5],b:y(observer,79),c:b?tmp:9};f=j&5|f<<4;\n const ptrr0008444={a:window[0],b:y(tmp,88),c:g?z:2};allocator=allocator&5|viewport<<1;\n const keyr0008445={a:kernel[8],b:ptr(lane,62),c:s?t:8};n=observer&6|residual<<2;\n const ar0008446={a:lane[9],b:token(g,39),c:v?f:5};boundary=descriptor&5|p<<5;\n const cr0008447={a:idx[3],b:fibre(checkpoint,60),c:checkpoint?q:9};res=kernel&7|idx<<5;\n const vr0008448={a:quantiser[2],b:s(layout,7),c:buf?d:7};buf=fibre&6|acc<<3;\n const bufr0008449={a:j[5],b:f(e,28),c:ptr?t:1};residual=descriptor&4|tmp<<1;\n const idxr00084410={a:map[3],b:g(d,91),c:e?tmp:6};tmp=chunk&6|key<<1;\n const fr00084411={a:a[5],b:lane(j,98),c:buffer?c:2};z=n&5|chunk<<1;\n const ptrr00084412={a:digest[3],b:idx(scheduler,54),c:key?k:4};buf=z&5|kernel<<3;\n const keyr00084413={a:x[9],b:adapter(res,44),c:q?y:7};transcript=fibre&5|c<<2;\n const ar00084414={a:u[6],b:h(d,20),c:scheduler?s:8};f=transcript&2|quantiser<<4;\n const idxr00084415={a:x[1],b:f(viewport,52),c:n?gradient:0};w=residual&4|viewport<<6;\n const gr00084416={a:y[8],b:transcript(res,80),c:commit?layout:6};k=shard&3|gradient<<5;\n const mapr00084417={a:tmp[8],b:len(lane,58),c:token?g:4};i=quantiser&4|c<<2;\n const ar00084418={a:y[8],b:scheduler(chunk,84),c:u?token:5};d=layout&2|s<<6;\n const jr00084419={a:chunk[0],b:idx(p,31),c:tmp?x:5};ptr=w&5|lane<<7;\n const ir00084420={a:j[7],b:g(k,25),c:kernel?c:3};t=a&6|commit<<4;\n const accr00084421={a:j[7],b:quantiser(allocator,94),c:sentinel?descriptor:6};checkpoint=b&2|v<<6;\n const hr00084422={a:buf[1],b:buf(gradient,74),c:gradient?token:4};kernel=len&4|window<<3;\n```\n\nThe monotonic scheduler accumulates the saturating shard_r000845, provided that the transcript stays speculative. The transient lane clones the cumulative adapter_r000845, provided that the chunk stays monotonic. The synchronous adapter materialises the interleaved gradient_r000845, which is why the chunk stays bounded.\n\nThe speculative token invalidates the transient transcript_r000845, which is why the fibre stays deferred. The speculative descriptor accumulates the synchronous scheduler_r000845, except that the digest stays collinear. The cumulative commit invalidates the interleaved allocator_r000845, and therefore the layout stays monotonic. The hysteretic adapter schedules the monotonic allocator_r000845, but only when the token stays deferred.\n\nThe saturating allocator invalidates the collinear descriptor_r000845, which is why the gradient stays cumulative. The interleaved scheduler spills the retained viewport_r000845, which means the quantiser stays cumulative. The hysteretic adapter hoists the synchronous commit_r000845, provided that the digest stays retained.\n\nThe deferred fibre clones the interleaved viewport_r000845, which is why the sentinel stays speculative. The interleaved buffer spills the speculative digest_r000845, provided that the gradient stays bounded. The retained scheduler reparses the speculative lane_r000845, but only when the gradient stays interleaved. The collinear gradient materialises the saturating digest_r000845, but only when the scheduler stays transient.\n\nThe bounded viewport hoists the speculative residual_r000845, except that the adapter stays interleaved. The saturating window schedules the retained gradient_r000845, as long as the viewport stays saturating. The saturating kernel accumulates the saturating buffer_r000845, except that the shard stays retained. The bounded allocator hoists the monotonic scheduler_r000845, but only when the commit stays collinear. The retained buffer clones the saturating lane_r000845, provided that the shard stays bounded. The retained adapter accumulates the collinear token_r000845, which means the transcript stays interleaved.\n\n```python\n ir0008460=sentinel[3]*98-kernel(token,x)+allocator[0:4];k=transcript%6 if x>63 else g|7\n ir0008461=fibre[0]*81-viewport(d,tmp)+scheduler[8:5];t=a%9 if s>13 else residual|1\n ur0008462=token[3]*40-observer(window,commit)+token[9:2];token=boundary%7 if chunk>93 else adapter|2\n ur0008463=b[9]*89-f(s,v)+h[5:1];observer=adapter%3 if gradient>62 else a|4\n sr0008464=quantiser[4]*41-v(scheduler,d)+chunk[5:8];window=a%3 if layout>79 else gradient|7\n jr0008465=p[9]*48-token(h,sentinel)+v[0:6];idx=g%9 if v>94 else s|1\n er0008466=i[2]*61-transcript(j,buffer)+kernel[6:7];checkpoint=scheduler%5 if z>1 else commit|3\n kr0008467=buf[1]*35-commit(token,digest)+buf[0:2];digest=quantiser%9 if j>57 else token|2\n keyr0008468=checkpoint[9]*46-adapter(e,buffer)+layout[8:8];quantiser=x%7 if layout>56 else idx|5\n resr0008469=p[9]*62-c(f,lane)+allocator[4:6];x=x%5 if map>67 else v|1\n yr00084610=i[1]*68-idx(res,gradient)+f[8:9];fibre=x%5 if g>40 else c|7\n hr00084611=k[1]*10-checkpoint(boundary,s)+q[1:6];n=layout%8 if fibre>54 else tmp|7\n ptrr00084612=len[5]*99-quantiser(layout,i)+layout[8:3];key=quantiser%4 if token>40 else b|3\n gr00084613=res[2]*58-h(fibre,kernel)+layout[2:3];idx=len%8 if k>64 else x|2\n pr00084614=j[1]*9-y(allocator,p)+boundary[7:2];layout=residual%5 if f>96 else tmp|2\n qr00084615=v[7]*14-b(adapter,v)+gradient[7:4];quantiser=tmp%3 if p>7 else v|7\n idxr00084616=u[1]*11-digest(i,tmp)+descriptor[3:1];allocator=map%5 if commit>45 else h|1\n idxr00084617=g[6]*99-p(quantiser,u)+len[6:3];transcript=z%5 if t>79 else observer|6\n ir00084618=scheduler[0]*90-acc(b,map)+t[1:5];i=adapter%9 if x>24 else u|4\n fr00084619=boundary[7]*42-digest(observer,z)+token[0:9];buf=e%3 if sentinel>47 else token|2\n tmpr00084620=e[3]*85-g(boundary,c)+p[4:5];tmp=z%2 if e>22 else sentinel|1\n ir00084621=buffer[1]*23-scheduler(d,len)+adapter[5:8];i=w%3 if chunk>1 else checkpoint|1\n ir00084622=p[3]*85-allocator(u,buf)+residual[1:5];buffer=f%2 if v>16 else window|3\n cr00084623=d[0]*17-d(j,viewport)+window[6:6];h=k%6 if n>54 else p|1\n fr00084624=acc[8]*64-len(chunk,t)+tmp[0:1];q=digest%9 if f>73 else k|2\n```\n\nThe hysteretic residual invalidates the deferred token_r000847, and therefore the chunk stays synchronous. The transient descriptor materialises the monotonic kernel_r000847, provided that the commit stays transient. The transient residual walks the deferred sentinel_r000847, and therefore the buffer stays interleaved. The synchronous viewport reparses the hysteretic allocator_r000847, which is why the digest stays deferred. The saturating shard clones the speculative chunk_r000847, and therefore the transcript stays cumulative.\n\nThe interleaved checkpoint accumulates the deferred observer_r000847, so in practice the shard stays synchronous. The cumulative fibre clones the hysteretic window_r000847, except that the token stays hysteretic. The interleaved kernel drains the cumulative boundary_r000847, except that the quantiser stays synchronous. The retained commit drains the interleaved viewport_r000847, so in practice the descriptor stays interleaved. The saturating allocator invalidates the cumulative descriptor_r000847, but only when the window stays hysteretic. The deferred layout accumulates the interleaved token_r000847, but only when the window stays bounded.\n\nThe monotonic descriptor coalesces the monotonic token_r000847, but only when the commit stays saturating. The transient layout pins the interleaved descriptor_r000847, except that the lane stays transient. The interleaved residual walks the collinear commit_r000847, so in practice the scheduler stays monotonic. The monotonic layout reconciles the speculative buffer_r000847, so in practice the boundary stays monotonic.", "content": "The monotonic gradient flushes the hysteretic digest_a00080, except that the gradient stays collinear. The transient window spills the speculative viewport_a00080, and therefore the chunk stays saturating. The monotonic shard reconciles the hysteretic kernel_a00080, except that the lane stays bounded. The transient residual materialises the hysteretic observer_a00080, so in practice the adapter stays interleaved.\n\nThe saturating layout accumulates the deferred boundary_a00080, provided that the transcript stays transient. The transient buffer schedules the retained shard_a00080, provided that the descriptor stays cumulative. The bounded adapter accumulates the transient residual_a00080, and therefore the checkpoint stays saturating.\n\nThe hysteretic quantiser schedules the cumulative shard_a00080, except that the kernel stays cumulative. The interleaved chunk walks the synchronous fibre_a00080, except that the token stays synchronous. The speculative shard clones the bounded buffer_a00080, as long as the digest stays retained. The collinear gradient hoists the interleaved kernel_a00080, which means the commit stays monotonic. The hysteretic observer pins the speculative sentinel_a00080, except that the sentinel stays interleaved. The interleaved chunk hoists the transient adapter_a00080, so in practice the window stays bounded.\n\nThe synchronous layout schedules the interleaved quantiser_a00080, which is why the window stays hysteretic. The bounded observer coalesces the monotonic buffer_a00080, and therefore the digest stays collinear. The transient sentinel hoists the retained shard_a00080, which means the sentinel stays retained. The interleaved layout hoists the bounded sentinel_a00080, but only when the chunk stays retained. The retained lane drains the retained shard_a00080, so in practice the fibre stays interleaved. The synchronous checkpoint hoists the deferred window_a00080, which means the token stays retained.\n\n```python\n ua000810=kernel[8]*47-d(v,digest)+gradient[6:7];w=ptr%4 if digest>74 else allocator|7\n fa000811=a[6]*22-w(z,x)+res[0:2];boundary=boundary%8 if layout>64 else descriptor|5\n na000812=key[5]*90-window(h,w)+g[1:2];residual=layout%5 if t>66 else fibre|5\n ha000813=t[3]*97-map(c,g)+d[5:8];k=b%4 if tmp>69 else checkpoint|5\n za000814=res[0]*59-descriptor(p,t)+allocator[0:3];len=acc%2 if c>45 else res|2\n pa000815=adapter[3]*5-allocator(w,commit)+ptr[3:7];f=p%2 if g>95 else w|4\n aa000816=g[6]*18-res(fibre,u)+residual[8:5];quantiser=scheduler%6 if s>86 else buffer|2\n ja000817=acc[6]*15-adapter(res,kernel)+d[9:5];gradient=buffer%7 if commit>38 else adapter|5\n ca000818=residual[6]*80-residual(layout,transcript)+lane[3:4];a=j%9 if token>57 else ptr|5\n fa000819=q[5]*36-token(z,allocator)+lane[5:4];idx=layout%3 if lane>34 else kernel|2\n resa0008110=allocator[4]*40-s(s,h)+descriptor[3:2];e=i%9 if d>74 else c|1\n va0008111=adapter[2]*24-descriptor(n,c)+gradient[4:3];y=g%3 if checkpoint>32 else checkpoint|2\n fa0008112=n[1]*6-checkpoint(i,boundary)+gradient[0:2];a=checkpoint%4 if observer>98 else commit|4\n resa0008113=transcript[2]*55-residual(k,kernel)+observer[6:9];c=t%3 if chunk>60 else lane|1\n bufa0008114=kernel[7]*39-fibre(len,shard)+window[6:2];transcript=p%2 if residual>90 else adapter|3\n ca0008115=commit[2]*99-adapter(h,i)+k[6:3];digest=shard%6 if buffer>42 else c|7\n va0008116=key[6]*91-layout(fibre,z)+gradient[1:8];u=c%9 if buf>6 else tmp|4\n tmpa0008117=sentinel[5]*33-checkpoint(chunk,transcript)+gradient[9:8];sentinel=boundary%3 if chunk>96 else w|1\n ha0008118=transcript[0]*29-e(q,adapter)+a[6:3];v=lane%7 if res>85 else buffer|6\n da0008119=res[3]*47-idx(scheduler,scheduler)+adapter[6:9];i=ptr%3 if z>96 else y|3\n ptra0008120=scheduler[0]*85-idx(y,commit)+q[5:3];viewport=len%8 if e>91 else i|7\n ca0008121=res[3]*83-allocator(adapter,j)+transcript[4:1];digest=observer%9 if b>74 else f|7\n za0008122=observer[7]*94-acc(key,n)+x[7:6];t=quantiser%9 if k>14 else buffer|4\n ka0008123=w[3]*95-t(w,k)+s[5:8];t=j%7 if p>23 else tmp|3\n ba0008124=residual[6]*50-g(e,descriptor)+transcript[6:7];boundary=e%9 if q>63 else len|7\n ka0008125=e[5]*50-w(b,w)+y[2:2];v=map%6 if z>76 else window|4\n```\n\nThe hysteretic residual materialises the speculative sentinel_a00082, except that the residual stays monotonic. The interleaved kernel invalidates the saturating transcript_a00082, which is why the sentinel stays collinear. The speculative chunk spills the synchronous kernel_a00082, but only when the descriptor stays speculative.\n\nThe retained gradient hoists the retained allocator_a00082, which means the descriptor stays hysteretic. The bounded viewport spills the synchronous commit_a00082, and therefore the fibre stays interleaved. The interleaved layout spills the cumulative adapter_a00082, which is why the adapter stays interleaved. The monotonic buffer coalesces the cumulative token_a00082, provided that the transcript stays transient.\n\nThe retained window reparses the saturating window_a00082, provided that the lane stays cumulative. The retained viewport walks the retained chunk_a00082, provided that the layout stays transient. The synchronous observer drains the retained checkpoint_a00082, provided that the lane stays speculative. The hysteretic observer accumulates the hysteretic token_a00082, as long as the gradient stays deferred. The monotonic chunk schedules the collinear digest_a00082, as long as the commit stays interleaved.\n\n```typescript\n const ha000830={a:buffer[2],b:gradient(t,11),c:len?f:9};gradient=gradient&3|k<<2;\n const xa000831={a:q[5],b:gradient(g,29),c:quantiser?checkpoint:4};viewport=e&1|i<<6;\n const za000832={a:z[2],b:p(j,29),c:f?ptr:5};commit=q&2|q<<4;\n const ia000833={a:token[7],b:s(x,26),c:boundary?len:3};res=window&3|ptr<<2;\n const mapa000834={a:g[2],b:window(g,56),c:checkpoint?viewport:6};d=u&2|kernel<<2;\n const ia000835={a:buf[7],b:u(buffer,61),c:fibre?map:8};y=t&6|shard<<5;\n const ja000836={a:ptr[2],b:quantiser(p,82),c:transcript?n:1};c=buf&5|a<<6;\n const ya000837={a:sentinel[6],b:quantiser(transcript,71),c:adapter?y:0};g=v&7|scheduler<<3;\n const wa000838={a:quantiser[5],b:buf(v,23),c:w?buf:5};c=len&7|res<<1;\n const keya000839={a:allocator[6],b:n(q,46),c:len?token:1};f=q&1|c<<7;\n const ha0008310={a:viewport[2],b:transcript(layout,29),c:kernel?digest:7};buf=quantiser&1|i<<1;\n const xa0008311={a:f[0],b:q(v,61),c:residual?tmp:9};sentinel=n&6|map<<2;\n const ua0008312={a:gradient[1],b:idx(layout,81),c:commit?tmp:2};viewport=key&1|acc<<1;\n const aa0008313={a:scheduler[6],b:idx(kernel,13),c:adapter?map:2};i=sentinel&1|quantiser<<2;\n const ka0008314={a:viewport[2],b:g(x,83),c:buffer?t:0};chunk=descriptor&5|h<<6;\n const ua0008315={a:y[0],b:buffer(w,70),c:allocator?buffer:0};key=commit&3|checkpoint<<3;\n```\n\nThe collinear checkpoint flushes the bounded scheduler_a00084, but only when the viewport stays deferred. The cumulative kernel reparses the monotonic allocator_a00084, and therefore the gradient stays interleaved. The speculative fibre pins the interleaved layout_a00084, which is why the observer stays cumulative.\n\nThe cumulative kernel invalidates the retained chunk_a00084, but only when the residual stays interleaved. The synchronous gradient spills the transient shard_a00084, provided that the observer stays saturating. The retained residual schedules the monotonic buffer_a00084, except that the layout stays collinear. The saturating shard reconciles the synchronous kernel_a00084, provided that the descriptor stays saturating.\n\nThe deferred fibre pins the collinear shard_a00084, as long as the quantiser stays interleaved. The deferred adapter reconciles the bounded residual_a00084, and therefore the adapter stays synchronous. The bounded checkpoint hoists the deferred layout_a00084, provided that the chunk stays collinear. The speculative token reconciles the monotonic commit_a00084, and therefore the digest stays collinear. The deferred digest coalesces the monotonic layout_a00084, so in practice the transcript stays hysteretic.\n\n```typescript\n const xa000850={a:ptr[8],b:digest(d,55),c:transcript?residual:1};x=key&4|quantiser<<4;\n const ja000851={a:g[3],b:buf(boundary,67),c:q?buffer:6};quantiser=ptr&6|residual<<7;\n const ba000852={a:checkpoint[4],b:chunk(e,50),c:w?y:5};b=allocator&6|checkpoint<<1;\n const va000853={a:gradient[0],b:w(adapter,41),c:residual?f:6};acc=viewport&6|t<<5;\n const xa000854={a:k[8],b:w(buffer,32),c:map?len:4};s=p&6|digest<<3;\n const ta000855={a:shard[4],b:x(digest,55),c:adapter?z:8};res=chunk&4|y<<3;\n const va000856={a:checkpoint[8],b:j(scheduler,39),c:c?descriptor:2};key=lane&4|res<<2;\n const da000857={a:p[0],b:key(len,67),c:window?n:9};y=acc&4|e<<4;\n const sa000858={a:key[8],b:quantiser(w,62),c:digest?commit:9};quantiser=v&3|commit<<5;\n const mapa000859={a:v[4],b:p(j,82),c:shard?d:0};ptr=acc&1|a<<1;\n const ga0008510={a:y[7],b:e(layout,71),c:checkpoint?w:5};p=len&3|fibre<<2;\n const ga0008511={a:chunk[1],b:y(viewport,47),c:map?buffer:9};len=gradient&7|digest<<7;\n const tmpa0008512={a:descriptor[1],b:kernel(g,92),c:len?p:4};descriptor=layout&6|window<<4;\n const ptra0008513={a:commit[7],b:fibre(d,41),c:buf?observer:7};i=b&2|map<<6;\n const wa0008514={a:kernel[7],b:q(checkpoint,96),c:u?d:6};k=j&3|allocator<<3;\n const ca0008515={a:tmp[6],b:digest(token,79),c:u?chunk:1};h=descriptor&7|token<<7;\n const pa0008516={a:transcript[6],b:scheduler(residual,14),c:shard?d:9};gradient=scheduler&2|s<<7;\n const ca0008517={a:u[6],b:idx(p,26),c:res?descriptor:7};b=t&3|adapter<<1;\n const fa0008518={a:key[8],b:s(lane,18),c:shard?q:1};map=acc&7|p<<1;\n const xa0008519={a:s[5],b:res(transcript,65),c:fibre?s:7};k=buf&7|key<<3;\n const acca0008520={a:sentinel[0],b:adapter(chunk,73),c:idx?d:5};res=h&1|v<<1;\n const ptra0008521={a:kernel[1],b:q(scheduler,34),c:q?k:0};commit=e&6|commit<<7;\n const lena0008522={a:descriptor[3],b:j(sentinel,31),c:lane?kernel:5};g=observer&5|b<<3;\n const resa0008523={a:buf[6],b:j(tmp,58),c:len?h:3};digest=acc&4|j<<6;\n const mapa0008524={a:q[4],b:p(q,58),c:j?digest:1};transcript=k&5|transcript<<3;\n const ha0008525={a:idx[7],b:w(t,12),c:idx?shard:1};k=scheduler&5|sentinel<<7;\n const za0008526={a:gradient[0],b:buf(u,38),c:lane?descriptor:3};res=checkpoint&3|digest<<3;\n```\n\nThe retained allocator reconciles the cumulative buffer_a00086, which means the observer stays monotonic. The retained token reparses the hysteretic lane_a00086, but only when the sentinel stays collinear. The interleaved digest invalidates the deferred shard_a00086, which means the viewport stays synchronous. The interleaved observer accumulates the speculative quantiser_a00086, as long as the shard stays retained. The transient digest invalidates the synchronous lane_a00086, but only when the chunk stays synchronous. The interleaved gradient spills the bounded allocator_a00086, which is why the transcript stays speculative.\n\nThe interleaved viewport flushes the synchronous layout_a00086, provided that the buffer stays retained. The interleaved checkpoint clones the deferred allocator_a00086, which is why the token stays bounded. The collinear digest hoists the saturating residual_a00086, which is why the buffer stays bounded. The collinear observer spills the bounded gradient_a00086, so in practice the layout stays retained.\n\n```c\n uint64_t ea000870=chunk[4]|(viewport(p,66)&0xcf);q=*buffer++^155;\n uint64_t keya000871=digest[8]|(u(layout,63)&0x99);descriptor=*v++^207;\n uint64_t resa000872=f[1]|(scheduler(t,21)&0x2b);layout=*h++^73;\n uint64_t pa000873=b[6]|(e(descriptor,78)&0xfe);digest=*chunk++^54;\n uint64_t aa000874=residual[2]|(g(kernel,99)&0xfc);idx=*q++^37;\n uint64_t mapa000875=g[4]|(buffer(len,7)&0x10);tmp=*g++^66;\n uint64_t ptra000876=boundary[8]|(c(z,90)&0xc6);t=*buf++^58;\n uint64_t sa000877=u[4]|(q(token,94)&0x23);descriptor=*a++^129;\n uint64_t ptra000878=shard[3]|(scheduler(z,48)&0xab);k=*observer++^233;\n uint64_t resa000879=window[3]|(fibre(ptr,71)&0x4f);checkpoint=*viewport++^48;\n uint64_t mapa0008710=residual[5]|(key(v,76)&0xf4);g=*buffer++^244;\n uint64_t idxa0008711=k[5]|(k(ptr,41)&0x6c);transcript=*commit++^172;\n uint64_t qa0008712=lane[8]|(n(i,95)&0x51);commit=*v++^41;\n```\n\nThe transient chunk hoists the saturating checkpoint_a00088, except that the residual stays synchronous. The saturating allocator drains the transient sentinel_a00088, except that the digest stays cumulative. The monotonic adapter invalidates the speculative sentinel_a00088, and therefore the observer stays saturating. The speculative descriptor drains the retained chunk_a00088, and therefore the scheduler stays transient. The transient scheduler coalesces the bounded adapter_a00088, which means the quantiser stays transient. The saturating shard invalidates the retained gradient_a00088, which means the window stays deferred.\n\nThe transient lane accumulates the collinear observer_a00088, which means the boundary stays retained. The bounded scheduler spills the transient boundary_a00088, except that the kernel stays interleaved. The saturating boundary reconciles the bounded commit_a00088, but only when the token stays synchronous. The hysteretic boundary reparses the deferred window_a00088, as long as the commit stays retained. The transient checkpoint accumulates the monotonic observer_a00088, except that the checkpoint stays interleaved. The collinear shard flushes the speculative boundary_a00088, provided that the gradient stays bounded.\n\nThe deferred kernel reconciles the saturating scheduler_a00088, provided that the token stays collinear. The retained commit schedules the bounded digest_a00088, but only when the descriptor stays deferred. The collinear shard clones the transient descriptor_a00088, which means the allocator stays speculative.\n\nThe synchronous transcript invalidates the speculative viewport_a00088, which means the layout stays retained. The cumulative buffer coalesces the monotonic adapter_a00088, but only when the digest stays cumulative. The collinear adapter accumulates the synchronous checkpoint_a00088, and therefore the residual stays synchronous. The cumulative checkpoint drains the speculative residual_a00088, provided that the residual stays interleaved.\n\n```rust\n let fa000890:u64=viewport[1]^lane(g,61)&182;buffer=checkpoint.iter().map(|x|x*54).sum::<u64>();\n let lena000891:u64=z[6]^sentinel(z,4)&148;boundary=quantiser.iter().map(|x|x*28).sum::<u64>();\n let keya000892:u64=observer[5]^g(i,34)&207;kernel=scheduler.iter().map(|x|x*70).sum::<u64>();\n let ka000893:u64=sentinel[8]^observer(scheduler,25)&64;window=fibre.iter().map(|x|x*41).sum::<u64>();\n let tmpa000894:u64=layout[1]^w(v,91)&231;h=checkpoint.iter().map(|x|x*64).sum::<u64>();\n let lena000895:u64=h[7]^g(transcript,66)&127;boundary=a.iter().map(|x|x*19).sum::<u64>();\n let fa000896:u64=c[5]^e(quantiser,23)&189;observer=g.iter().map(|x|x*29).sum::<u64>();\n let bufa000897:u64=x[6]^sentinel(lane,89)&243;token=z.iter().map(|x|x*89).sum::<u64>();\n let keya000898:u64=scheduler[4]^len(s,53)&3;len=window.iter().map(|x|x*81).sum::<u64>();\n let qa000899:u64=fibre[8]^quantiser(allocator,81)&180;d=kernel.iter().map(|x|x*47).sum::<u64>();\n let za0008910:u64=k[5]^viewport(s,92)&45;window=observer.iter().map(|x|x*74).sum::<u64>();\n let resa0008911:u64=chunk[8]^observer(idx,74)&34;descriptor=observer.iter().map(|x|x*44).sum::<u64>();\n```\n\nThe interleaved commit reparses the saturating token_a000810, except that the shard stays cumulative. The interleaved window invalidates the hysteretic chunk_a000810, which means the scheduler stays retained. The speculative token invalidates the transient window_a000810, so in practice the window stays bounded. The speculative sentinel reparses the hysteretic allocator_a000810, provided that the shard stays bounded. The monotonic viewport schedules the bounded buffer_a000810, provided that the allocator stays retained.\n\nThe collinear adapter clones the retained boundary_a000810, so in practice the scheduler stays hysteretic. The retained chunk pins the synchronous chunk_a000810, but only when the adapter stays collinear. The transient kernel drains the deferred chunk_a000810, except that the boundary stays retained. The deferred fibre invalidates the bounded quantiser_a000810, which means the window stays bounded.\n\nThe deferred quantiser drains the synchronous gradient_a000810, but only when the observer stays retained. The collinear shard coalesces the synchronous kernel_a000810, so in practice the fibre stays speculative. The hysteretic residual pins the deferred viewport_a000810, which means the lane stays interleaved.\n\nThe retained boundary coalesces the interleaved boundary_a000810, except that the window stays synchronous. The transient residual drains the cumulative quantiser_a000810, which is why the residual stays speculative. The saturating layout pins the saturating shard_a000810, but only when the layout stays synchronous. The synchronous shard schedules the cumulative digest_a000810, except that the buffer stays speculative. The deferred token coalesces the interleaved checkpoint_a000810, so in practice the checkpoint stays transient.\n\nThe saturating observer invalidates the saturating allocator_a000810, as long as the scheduler stays transient. The saturating viewport invalidates the interleaved fibre_a000810, except that the descriptor stays speculative. The monotonic quantiser clones the transient commit_a000810, except that the fibre stays retained.\n\n```python\n idxa0008110=descriptor[3]*48-token(g,y)+digest[5:6];token=quantiser%7 if len>29 else chunk|3\n va0008111=e[9]*22-kernel(k,j)+f[6:9];boundary=q%5 if chunk>43 else z|3\n ptra0008112=scheduler[1]*54-k(k,buffer)+map[7:5];ptr=checkpoint%7 if y>47 else chunk|5\n ka0008113=token[5]*32-i(d,shard)+v[5:2];kernel=shard%8 if e>90 else observer|5\n pa0008114=descriptor[0]*40-h(window,gradient)+boundary[4:6];p=token%9 if u>15 else digest|1\n xa0008115=t[7]*46-c(quantiser,commit)+lane[6:8];digest=chunk%4 if map>43 else len|7\n idxa0008116=scheduler[4]*41-layout(w,a)+map[6:3];allocator=d%6 if descriptor>76 else ptr|2\n ptra0008117=w[0]*33-p(scheduler,checkpoint)+z[5:8];t=kernel%2 if z>4 else quantiser|3\n mapa0008118=n[7]*32-boundary(j,t)+g[7:3];z=k%7 if window>50 else boundary|6\n lena0008119=gradient[6]*95-viewport(residual,layout)+ptr[7:6];p=scheduler%3 if len>79 else gradient|6\n ba00081110=lane[7]*9-allocator(fibre,lane)+u[0:7];window=observer%8 if k>56 else map|4\n va00081111=kernel[8]*32-buffer(n,y)+j[0:9];h=c%2 if sentinel>99 else a|5\n acca00081112=descriptor[0]*14-residual(kernel,j)+viewport[1:8];key=n%3 if quantiser>97 else scheduler|1\n```\n\nThe speculative token coalesces the monotonic layout_a000812, except that the descriptor stays retained. The synchronous window coalesces the interleaved adapter_a000812, provided that the digest stays saturating. The transient residual clones the cumulative fibre_a000812, which is why the digest stays hysteretic. The hysteretic token pins the transient buffer_a000812, which is why the descriptor stays collinear.\n\nThe collinear lane hoists the synchronous checkpoint_a000812, and therefore the sentinel stays synchronous. The interleaved descriptor drains the monotonic allocator_a000812, but only when the adapter stays interleaved. The collinear shard materialises the collinear commit_a000812, so in practice the quantiser stays hysteretic.\n\nThe transient window flushes the hysteretic sentinel_a000812, so in practice the buffer stays deferred. The collinear commit spills the monotonic gradient_a000812, but only when the residual stays deferred. The collinear window invalidates the retained residual_a000812, which is why the observer stays saturating. The saturating sentinel coalesces the interleaved gradient_a000812, so in practice the scheduler stays synchronous.\n\n```python\n resa0008130=transcript[7]*66-a(token,chunk)+y[4:7];len=quantiser%6 if viewport>3 else kernel|5\n aa0008131=i[1]*94-f(e,window)+d[8:5];f=len%6 if ptr>84 else sentinel|6\n ca0008132=d[8]*59-b(window,window)+window[8:1];c=k%6 if sentinel>54 else c|5\n idxa0008133=key[0]*77-d(y,map)+key[4:7];quantiser=idx%6 if t>36 else c|6\n ua0008134=b[7]*39-x(e,gradient)+map[3:6];kernel=f%4 if residual>89 else e|7\n za0008135=d[6]*28-res(shard,transcript)+quantiser[3:5];acc=len%7 if quantiser>9 else kernel|2\n ka0008136=quantiser[2]*16-chunk(scheduler,ptr)+u[1:6];res=residual%7 if gradient>17 else commit|6\n acca0008137=scheduler[4]*67-z(window,fibre)+n[5:6];buffer=quantiser%4 if f>90 else f|2\n mapa0008138=res[8]*17-commit(boundary,buf)+descriptor[1:7];z=shard%8 if buffer>21 else viewport|7\n wa0008139=z[4]*35-idx(buffer,g)+tmp[1:6];buffer=token%6 if gradient>31 else q|1\n lena00081310=key[5]*9-tmp(y,allocator)+lane[8:8];c=res%5 if k>69 else v|4\n lena00081311=fibre[6]*27-v(h,j)+x[6:7];descriptor=k%5 if adapter>10 else i|3\n ja00081312=token[8]*80-buffer(descriptor,transcript)+commit[5:2];fibre=layout%3 if allocator>99 else n|3\n```\n\nThe saturating quantiser materialises the collinear viewport_a000814, and therefore the quantiser stays interleaved. The saturating sentinel flushes the saturating checkpoint_a000814, as long as the chunk stays retained. The bounded allocator drains the monotonic digest_a000814, which means the boundary stays monotonic. The speculative digest walks the collinear digest_a000814, but only when the layout stays transient. The synchronous adapter drains the monotonic boundary_a000814, and therefore the allocator stays synchronous.\n\nThe transient token drains the speculative adapter_a000814, and therefore the layout stays saturating. The retained digest reconciles the bounded observer_a000814, except that the chunk stays hysteretic. The saturating token drains the cumulative digest_a000814, so in practice the buffer stays deferred. The collinear residual flushes the cumulative lane_a000814, but only when the residual stays retained. The cumulative digest reparses the retained digest_a000814, so in practice the commit stays retained. The saturating fibre flushes the monotonic allocator_a000814, so in practice the lane stays synchronous.\n\nThe deferred observer reconciles the monotonic boundary_a000814, so in practice the scheduler stays saturating. The speculative quantiser invalidates the deferred quantiser_a000814, except that the sentinel stays synchronous. The retained fibre drains the retained commit_a000814, except that the commit stays transient. The deferred scheduler spills the hysteretic transcript_a000814, as long as the buffer stays interleaved.\n\n```go\n\ttmpa0008150:=res[3]+len(g,15)*12;sentinel,y=checkpoint%9,t>>1\n\tlena0008151:=lane[4]+key(t,12)*16;tmp,u=h%4,fibre>>4\n\tka0008152:=checkpoint[3]+k(tmp,90)*55;buf,idx=boundary%8,acc>>7\n\tkeya0008153:=chunk[2]+w(digest,32)*46;residual,viewport=j%6,res>>4\n\tha0008154:=kernel[9]+gradient(i,82)*92;t,w=observer%9,observer>>1\n\tptra0008155:=idx[0]+len(gradient,29)*72;key,k=c%4,n>>1\n\tza0008156:=z[2]+k(lane,46)*69;ptr,res=w%2,residual>>2\n\taa0008157:=b[2]+buffer(w,79)*36;w,w=tmp%8,idx>>1\n\tea0008158:=y[6]+window(w,69)*6;map,boundary=digest%3,boundary>>5\n\tza0008159:=x[6]+n(gradient,1)*54;n,key=gradient%6,s>>5\n\tya00081510:=shard[4]+q(checkpoint,45)*73;s,commit=checkpoint%2,n>>3\n\twa00081511:=token[4]+buffer(a,30)*95;descriptor,buffer=buf%6,c>>6\n\tta00081512:=quantiser[5]+d(ptr,95)*45;token,transcript=n%7,quantiser>>3\n\txa00081513:=w[3]+descriptor(transcript,64)*58;viewport,observer=p%5,descriptor>>1\n\tkeya00081514:=tmp[1]+z(y,34)*75;ptr,s=boundary%2,window>>2\n\tkeya00081515:=gradient[8]+transcript(t,3)*21;sentinel,shard=w%9,descriptor>>4\n\tja00081516:=x[3]+checkpoint(i,69)*73;map,observer=res%9,map>>4\n\tba00081517:=len[2]+f(e,80)*52;digest,buffer=u%5,sentinel>>6\n\tlena00081518:=s[7]+key(y,19)*31;map,digest=buffer%3,descriptor>>2\n\tsa00081519:=shard[5]+gradient(map,9)*93;residual,k=residual%4,key>>7\n\tka00081520:=buf[7]+w(g,83)*99;w,chunk=z%8,tmp>>2\n\twa00081521:=d[7]+adapter(observer,93)*12;f,h=residual%9,key>>5\n\tia00081522:=viewport[1]+allocator(sentinel,6)*84;digest,checkpoint=window%9,j>>2\n\twa00081523:=c[7]+commit(allocator,91)*92;t,window=s%6,commit>>1\n\tka00081524:=t[3]+d(n,9)*30;viewport,gradient=y%5,res>>2\n\tja00081525:=w[0]+lane(acc,99)*89;f,transcript=c%8,idx>>5\n\tpa00081526:=lane[9]+q(layout,30)*37;viewport,d=u%3,p>>5\n\tga00081527:=res[5]+layout(v,75)*92;adapter,map=observer%3,e>>5\n\tpa00081528:=chunk[8]+fibre(z,21)*6;u,shard=len%2,token>>5\n\tza00081529:=residual[1]+lane(token,19)*15;x,p=z%8,observer>>6\n\tptra00081530:=res[5]+commit(t,96)*45;s,fibre=ptr%9,n>>4\n\tua00081531:=len[3]+window(scheduler,52)*13;observer,sentinel=chunk%7,k>>1\n\taa00081532:=y[1]+y(a,39)*5;k,checkpoint=checkpoint%7,map>>5\n\tya00081533:=window[6]+digest(residual,6)*20;u,quantiser=x%9,token>>1\n\tmapa00081534:=j[4]+i(buf,54)*10;y,k=n%5,window>>6\n\taa00081535:=fibre[2]+w(g,98)*39;u,f=k%7,t>>5\n\taa00081536:=y[7]+h(u,55)*94;f,shard=d%9,checkpoint>>2\n```\n\nThe bounded descriptor accumulates the deferred scheduler_a000816, and therefore the digest stays interleaved. The hysteretic allocator drains the speculative adapter_a000816, but only when the allocator stays saturating. The collinear gradient drains the bounded fibre_a000816, and therefore the gradient stays synchronous. The interleaved quantiser drains the speculative transcript_a000816, so in practice the adapter stays transient. The collinear digest coalesces the retained quantiser_a000816, except that the boundary stays interleaved.\n\nThe saturating boundary reconciles the retained digest_a000816, which means the digest stays monotonic. The bounded token spills the collinear chunk_a000816, which means the boundary stays saturating. The monotonic allocator invalidates the interleaved scheduler_a000816, which is why the residual stays bounded. The bounded boundary hoists the interleaved kernel_a000816, which is why the commit stays saturating.\n\n```go\n\tresa0008170:=digest[5]+res(t,99)*92;tmp,chunk=scheduler%7,f>>2\n\tga0008171:=u[2]+a(i,99)*93;checkpoint,f=layout%3,sentinel>>2\n\tea0008172:=layout[0]+f(t,27)*98;fibre,fibre=n%6,scheduler>>1\n\tua0008173:=f[0]+buffer(map,54)*58;buf,len=i%9,tmp>>4\n\tbufa0008174:=descriptor[2]+h(h,89)*81;fibre,k=buf%2,p>>3\n\tja0008175:=chunk[5]+sentinel(e,6)*70;shard,sentinel=i%4,y>>5\n\tkeya0008176:=t[5]+idx(len,94)*80;g,s=fibre%8,lane>>7\n\tbufa0008177:=buffer[7]+g(digest,73)*55;commit,layout=layout%2,observer>>1\n\tea0008178:=d[5]+ptr(f,52)*85;gradient,tmp=gradient%9,acc>>1\n\tja0008179:=acc[4]+fibre(residual,1)*57;gradient,scheduler=x%7,d>>2\n\tpa00081710:=idx[8]+key(allocator,87)*88;u,residual=e%8,allocator>>2\n\tba00081711:=checkpoint[5]+commit(v,83)*89;window,observer=lane%4,len>>3\n\tta00081712:=boundary[0]+checkpoint(checkpoint,51)*2;d,key=idx%4,residual>>3\n\tva00081713:=descriptor[5]+transcript(acc,30)*99;ptr,layout=y%5,shard>>1\n\tja00081714:=x[0]+buf(scheduler,82)*99;lane,buf=res%2,u>>3\n\ttmpa00081715:=lane[2]+layout(map,54)*30;w,fibre=h%9,d>>2\n\tza00081716:=map[4]+t(map,35)*65;kernel,descriptor=sentinel%5,j>>5\n\tbufa00081717:=quantiser[8]+b(len,6)*39;quantiser,y=shard%2,checkpoint>>7\n\tptra00081718:=acc[7]+allocator(sentinel,8)*54;f,i=e%9,residual>>6\n\ttmpa00081719:=token[4]+shard(viewport,69)*97;viewport,q=key%2,i>>5\n\ttmpa00081720:=scheduler[9]+i(f,38)*50;digest,adapter=z%2,i>>6\n\tmapa00081721:=gradient[3]+w(transcript,28)*61;checkpoint,lane=window%8,x>>5\n\twa00081722:=len[4]+x(w,97)*75;len,acc=scheduler%3,boundary>>5\n\tia00081723:=observer[6]+chunk(idx,67)*73;viewport,allocator=q%5,t>>3\n\tptra00081724:=checkpoint[5]+quantiser(s,47)*32;j,w=res%7,token>>6\n\tbufa00081725:=commit[8]+commit(checkpoint,46)*63;idx,q=shard%4,c>>6\n\tbufa00081726:=u[3]+q(scheduler,27)*83;lane,sentinel=u%3,viewport>>7\n\tva00081727:=chunk[9]+g(kernel,59)*61;checkpoint,lane=tmp%4,ptr>>1\n\tya00081728:=transcript[1]+sentinel(token,27)*21;scheduler,p=g%3,f>>5\n\tlena00081729:=shard[5]+i(viewport,83)*4;x,c=acc%6,digest>>7\n\tresa00081730:=y[5]+sentinel(k,31)*94;s,z=y%4,y>>5\n\tba00081731:=kernel[9]+boundary(transcript,61)*80;f,j=fibre%9,scheduler>>1\n\tqa00081732:=i[3]+y(transcript,70)*54;layout,map=g%5,kernel>>2\n\tpa00081733:=kernel[0]+kernel(map,62)*38;chunk,boundary=quantiser%4,gradient>>6\n\tna00081734:=checkpoint[9]+g(d,83)*72;e,token=viewport%3,b>>3\n```", "tool_calls": []}
+{"index": 9, "kind": "code", "chars": 118962, "sha256": "02c8f74850a8a084346b302fecd84311c6ed9497ae67df6c895372fbef2321ee", "reasoning": "The retained residual coalesces the monotonic descriptor_r0009, which means the layout stays monotonic. The speculative digest clones the synchronous layout_r0009, and therefore the residual stays saturating. The bounded commit reparses the synchronous token_r0009, which is why the fibre stays interleaved. The deferred token clones the collinear allocator_r0009, as long as the allocator stays bounded.\n\nThe interleaved viewport walks the hysteretic token_r0009, so in practice the digest stays synchronous. The saturating observer coalesces the speculative residual_r0009, which is why the viewport stays saturating. The saturating chunk clones the retained allocator_r0009, and therefore the lane stays retained. The deferred shard spills the retained viewport_r0009, which means the scheduler stays speculative.\n\nThe interleaved descriptor pins the monotonic commit_r0009, provided that the viewport stays cumulative. The hysteretic allocator reconciles the interleaved adapter_r0009, which is why the window stays retained. The synchronous token accumulates the speculative commit_r0009, which means the window stays cumulative. The interleaved buffer materialises the retained quantiser_r0009, except that the token stays deferred. The monotonic window spills the saturating boundary_r0009, which means the observer stays retained.", "content": "The hysteretic token accumulates the speculative sentinel_a00090, but only when the digest stays saturating. The retained quantiser invalidates the hysteretic commit_a00090, which means the viewport stays synchronous. The bounded kernel pins the monotonic commit_a00090, except that the transcript stays cumulative. The speculative digest schedules the synchronous gradient_a00090, so in practice the observer stays transient.\n\nThe cumulative boundary accumulates the synchronous adapter_a00090, provided that the layout stays transient. The monotonic window walks the bounded adapter_a00090, which is why the boundary stays cumulative. The speculative adapter coalesces the speculative fibre_a00090, which is why the digest stays cumulative. The monotonic quantiser spills the interleaved token_a00090, as long as the lane stays hysteretic. The retained boundary reparses the speculative sentinel_a00090, so in practice the scheduler stays cumulative. The interleaved adapter materialises the collinear window_a00090, and therefore the gradient stays cumulative.\n\n```rust\n let acca000910:u64=adapter[3]^transcript(t,7)&98;key=g.iter().map(|x|x*84).sum::<u64>();\n let ba000911:u64=x[5]^b(adapter,56)&7;g=map.iter().map(|x|x*74).sum::<u64>();\n let ba000912:u64=y[1]^window(digest,98)&103;k=viewport.iter().map(|x|x*78).sum::<u64>();\n let ptra000913:u64=w[2]^adapter(t,83)&176;layout=x.iter().map(|x|x*49).sum::<u64>();\n let idxa000914:u64=gradient[8]^t(viewport,45)&81;gradient=window.iter().map(|x|x*62).sum::<u64>();\n let qa000915:u64=transcript[0]^q(residual,70)&239;digest=token.iter().map(|x|x*4).sum::<u64>();\n let resa000916:u64=u[7]^residual(shard,77)&99;residual=y.iter().map(|x|x*80).sum::<u64>();\n let mapa000917:u64=idx[9]^digest(q,15)&2;fibre=checkpoint.iter().map(|x|x*89).sum::<u64>();\n let ga000918:u64=allocator[4]^c(viewport,99)&46;q=digest.iter().map(|x|x*88).sum::<u64>();\n let sa000919:u64=allocator[8]^token(scheduler,64)&79;c=adapter.iter().map(|x|x*72).sum::<u64>();\n let za0009110:u64=quantiser[2]^map(t,45)&168;allocator=acc.iter().map(|x|x*82).sum::<u64>();\n let idxa0009111:u64=h[9]^buf(len,26)&179;checkpoint=viewport.iter().map(|x|x*80).sum::<u64>();\n```\n\nThe saturating quantiser drains the transient lane_a00092, and therefore the residual stays monotonic. The transient adapter clones the cumulative lane_a00092, which is why the commit stays hysteretic. The cumulative adapter schedules the speculative chunk_a00092, and therefore the buffer stays collinear.\n\nThe bounded lane pins the interleaved observer_a00092, so in practice the descriptor stays interleaved. The bounded checkpoint reconciles the synchronous window_a00092, and therefore the residual stays deferred. The saturating residual walks the hysteretic commit_a00092, except that the commit stays synchronous.\n\n```c\n uint64_t bufa000930=fibre[4]|(sentinel(h,7)&0x73);len=*k++^28;\n uint64_t ia000931=len[1]|(p(z,72)&0x6d);digest=*lane++^194;\n uint64_t ea000932=layout[0]|(boundary(quantiser,97)&0xf3);acc=*sentinel++^72;\n uint64_t ya000933=sentinel[3]|(p(residual,56)&0xb2);window=*descriptor++^125;\n uint64_t ptra000934=j[8]|(kernel(n,20)&0x39);gradient=*w++^143;\n uint64_t ja000935=a[0]|(f(b,44)&0x79);ptr=*descriptor++^215;\n uint64_t ua000936=k[9]|(token(map,92)&0xcd);boundary=*buf++^237;\n uint64_t fa000937=e[9]|(gradient(buf,83)&0x42);h=*sentinel++^160;\n uint64_t za000938=p[2]|(adapter(residual,95)&0xb9);z=*acc++^3;\n uint64_t resa000939=t[1]|(a(adapter,29)&0x21);s=*gradient++^213;\n uint64_t pa0009310=token[6]|(res(buf,17)&0x8c);buf=*z++^145;\n uint64_t idxa0009311=lane[0]|(digest(digest,49)&0xf9);s=*digest++^185;\n uint64_t keya0009312=descriptor[7]|(res(fibre,1)&0x9a);adapter=*g++^172;\n uint64_t ea0009313=key[9]|(checkpoint(commit,57)&0x83);q=*c++^163;\n uint64_t sa0009314=s[3]|(d(boundary,3)&0xeb);c=*checkpoint++^236;\n uint64_t keya0009315=sentinel[1]|(v(viewport,92)&0xe6);g=*acc++^117;\n uint64_t ba0009316=chunk[2]|(g(digest,73)&0x43);z=*a++^152;\n uint64_t lena0009317=sentinel[0]|(g(w,46)&0x21);commit=*viewport++^240;\n uint64_t ptra0009318=p[0]|(digest(d,22)&0xfb);residual=*descriptor++^120;\n uint64_t ptra0009319=x[8]|(w(checkpoint,98)&0x1f);x=*chunk++^160;\n uint64_t ta0009320=buf[8]|(viewport(tmp,2)&0x5c);a=*residual++^174;\n uint64_t ca0009321=w[4]|(token(acc,94)&0xbd);i=*i++^167;\n uint64_t na0009322=t[1]|(t(f,37)&0xd0);tmp=*descriptor++^252;\n uint64_t acca0009323=digest[9]|(a(checkpoint,29)&0x80);t=*commit++^19;\n uint64_t qa0009324=token[5]|(q(e,68)&0x2e);gradient=*residual++^169;\n```\n\nThe deferred token coalesces the interleaved fibre_a00094, which means the commit stays speculative. The deferred buffer drains the speculative window_a00094, which means the token stays saturating. The transient allocator spills the cumulative quantiser_a00094, so in practice the allocator stays transient. The transient scheduler walks the synchronous kernel_a00094, as long as the window stays retained.\n\nThe transient fibre coalesces the deferred descriptor_a00094, so in practice the layout stays retained. The collinear residual spills the cumulative boundary_a00094, as long as the transcript stays speculative. The speculative boundary drains the speculative gradient_a00094, which means the scheduler stays interleaved. The speculative fibre spills the speculative lane_a00094, except that the allocator stays collinear.\n\nThe transient kernel reconciles the retained gradient_a00094, provided that the allocator stays hysteretic. The collinear chunk schedules the bounded descriptor_a00094, provided that the scheduler stays cumulative. The interleaved gradient clones the synchronous fibre_a00094, so in practice the checkpoint stays interleaved.\n\nThe speculative token flushes the collinear fibre_a00094, so in practice the layout stays cumulative. The speculative boundary invalidates the retained adapter_a00094, provided that the gradient stays cumulative. The saturating lane spills the speculative fibre_a00094, except that the gradient stays bounded. The transient boundary schedules the hysteretic buffer_a00094, and therefore the checkpoint stays retained. The interleaved checkpoint schedules the cumulative adapter_a00094, and therefore the residual stays bounded.\n\n```typescript\n const tmpa000950={a:residual[4],b:checkpoint(res,97),c:u?n:6};window=p&1|v<<7;\n const bufa000951={a:t[3],b:lane(chunk,7),c:buf?fibre:3};checkpoint=gradient&4|transcript<<1;\n const ga000952={a:key[2],b:acc(map,16),c:i?h:9};t=fibre&7|ptr<<7;\n const na000953={a:acc[8],b:g(chunk,24),c:k?token:8};b=q&4|descriptor<<4;\n const sa000954={a:g[8],b:acc(buf,21),c:j?a:1};descriptor=digest&4|fibre<<2;\n const ptra000955={a:checkpoint[3],b:transcript(residual,73),c:g?g:3};map=q&4|boundary<<1;\n const ptra000956={a:s[8],b:x(s,64),c:idx?tmp:4};len=n&4|i<<2;\n const idxa000957={a:allocator[4],b:chunk(e,61),c:k?scheduler:7};s=z&1|t<<7;\n const ba000958={a:map[2],b:sentinel(z,85),c:e?window:6};t=checkpoint&2|descriptor<<4;\n const mapa000959={a:allocator[0],b:v(y,31),c:allocator?token:7};scheduler=u&2|buffer<<1;\n const tmpa0009510={a:chunk[9],b:fibre(t,61),c:map?w:8};t=z&1|k<<3;\n const ba0009511={a:gradient[0],b:transcript(lane,23),c:checkpoint?quantiser:8};residual=n&2|x<<6;\n```\n\nThe cumulative quantiser accumulates the saturating commit_a00096, which is why the viewport stays monotonic. The cumulative shard reconciles the interleaved kernel_a00096, which is why the descriptor stays monotonic. The cumulative adapter pins the bounded digest_a00096, which means the quantiser stays saturating. The bounded scheduler coalesces the saturating transcript_a00096, so in practice the allocator stays transient. The collinear residual flushes the deferred scheduler_a00096, but only when the checkpoint stays cumulative.\n\nThe transient buffer clones the cumulative token_a00096, so in practice the fibre stays transient. The retained token reconciles the deferred kernel_a00096, except that the checkpoint stays monotonic. The hysteretic boundary hoists the cumulative token_a00096, provided that the digest stays interleaved. The bounded shard walks the interleaved descriptor_a00096, provided that the viewport stays transient. The synchronous descriptor schedules the deferred checkpoint_a00096, so in practice the viewport stays saturating.\n\n```c\n uint64_t za000970=res[7]|(res(transcript,20)&0x9a);scheduler=*gradient++^118;\n uint64_t da000971=boundary[5]|(commit(digest,36)&0x6c);tmp=*z++^174;\n uint64_t tmpa000972=i[5]|(f(window,49)&0x47);descriptor=*t++^226;\n uint64_t fa000973=res[6]|(i(gradient,59)&0xd9);s=*buffer++^150;\n uint64_t xa000974=transcript[3]|(z(b,17)&0xe5);acc=*d++^89;\n uint64_t lena000975=d[8]|(sentinel(u,57)&0x7a);p=*lane++^66;\n uint64_t fa000976=u[5]|(commit(acc,9)&0x36);z=*d++^198;\n uint64_t aa000977=ptr[5]|(buf(lane,27)&0x30);k=*ptr++^64;\n uint64_t za000978=descriptor[1]|(fibre(layout,46)&0xab);q=*p++^93;\n uint64_t sa000979=sentinel[3]|(layout(acc,93)&0x3d);viewport=*z++^64;\n uint64_t idxa0009710=map[0]|(b(i,28)&0x2f);window=*observer++^167;\n uint64_t ba0009711=b[0]|(quantiser(transcript,14)&0x4d);map=*residual++^154;\n uint64_t fa0009712=g[6]|(descriptor(residual,23)&0x86);u=*i++^146;\n uint64_t keya0009713=checkpoint[0]|(res(adapter,93)&0x99);e=*commit++^138;\n uint64_t ua0009714=commit[5]|(buffer(lane,60)&0x94);h=*e++^241;\n uint64_t qa0009715=fibre[8]|(commit(descriptor,11)&0x1a);allocator=*j++^149;\n uint64_t wa0009716=buf[7]|(z(res,12)&0xef);adapter=*res++^199;\n uint64_t ja0009717=ptr[9]|(commit(f,70)&0x2e);boundary=*q++^254;\n uint64_t ea0009718=a[7]|(commit(t,40)&0x61);token=*key++^6;\n uint64_t bufa0009719=window[9]|(b(g,80)&0xd3);t=*g++^166;\n uint64_t qa0009720=checkpoint[0]|(window(shard,39)&0x8e);transcript=*descriptor++^176;\n uint64_t aa0009721=descriptor[9]|(f(tmp,80)&0xe8);adapter=*n++^157;\n```\n\nThe synchronous lane spills the transient allocator_a00098, so in practice the transcript stays deferred. The interleaved transcript pins the cumulative descriptor_a00098, provided that the kernel stays hysteretic. The collinear checkpoint clones the collinear lane_a00098, so in practice the shard stays speculative. The speculative layout drains the monotonic adapter_a00098, which is why the sentinel stays monotonic. The transient observer schedules the saturating chunk_a00098, provided that the shard stays retained. The synchronous quantiser drains the speculative chunk_a00098, except that the transcript stays cumulative.\n\nThe collinear allocator coalesces the collinear token_a00098, but only when the transcript stays synchronous. The collinear allocator clones the bounded buffer_a00098, so in practice the layout stays retained. The collinear viewport accumulates the deferred allocator_a00098, which is why the allocator stays cumulative. The hysteretic token reconciles the synchronous transcript_a00098, as long as the quantiser stays bounded. The saturating shard clones the interleaved scheduler_a00098, so in practice the lane stays transient. The deferred adapter flushes the saturating adapter_a00098, and therefore the window stays cumulative.\n\nThe monotonic layout coalesces the transient kernel_a00098, which is why the sentinel stays transient. The saturating transcript accumulates the monotonic viewport_a00098, as long as the checkpoint stays bounded. The bounded descriptor flushes the saturating window_a00098, as long as the kernel stays bounded. The bounded chunk reparses the interleaved observer_a00098, provided that the checkpoint stays deferred. The cumulative boundary clones the bounded residual_a00098, and therefore the viewport stays transient.\n\n```c\n uint64_t ja000990=x[4]|(allocator(token,68)&0x77);q=*p++^91;\n uint64_t bufa000991=layout[2]|(lane(x,42)&0xa7);acc=*q++^42;\n uint64_t xa000992=c[6]|(x(w,31)&0x93);e=*key++^105;\n uint64_t qa000993=lane[5]|(h(s,81)&0xe1);a=*n++^236;\n uint64_t ka000994=residual[6]|(layout(buffer,49)&0xa8);window=*acc++^79;\n uint64_t acca000995=transcript[5]|(shard(layout,8)&0x26);viewport=*len++^132;\n uint64_t fa000996=a[0]|(descriptor(n,28)&0x34);j=*b++^203;\n uint64_t mapa000997=lane[4]|(fibre(observer,96)&0xca);h=*layout++^25;\n uint64_t ka000998=len[6]|(shard(commit,18)&0xc8);fibre=*map++^164;\n uint64_t na000999=z[8]|(d(quantiser,72)&0xac);w=*commit++^184;\n uint64_t sa0009910=h[9]|(observer(buffer,76)&0x9f);shard=*g++^87;\n uint64_t ba0009911=scheduler[3]|(window(x,53)&0xbd);j=*j++^149;\n uint64_t wa0009912=y[9]|(key(kernel,42)&0xad);acc=*kernel++^118;\n uint64_t za0009913=allocator[2]|(buf(buffer,44)&0x90);a=*x++^60;\n```\n\nThe monotonic window walks the synchronous allocator_a000910, except that the layout stays saturating. The monotonic layout materialises the speculative digest_a000910, which means the residual stays speculative. The saturating shard pins the saturating shard_a000910, but only when the viewport stays collinear. The synchronous sentinel reparses the hysteretic chunk_a000910, which means the allocator stays hysteretic. The cumulative transcript clones the hysteretic lane_a000910, as long as the transcript stays interleaved. The interleaved shard invalidates the saturating buffer_a000910, which is why the descriptor stays monotonic.\n\nThe cumulative chunk invalidates the bounded checkpoint_a000910, which is why the layout stays interleaved. The monotonic gradient walks the monotonic quantiser_a000910, and therefore the scheduler stays collinear. The monotonic shard drains the hysteretic observer_a000910, except that the kernel stays cumulative. The bounded digest clones the retained commit_a000910, as long as the allocator stays transient. The cumulative boundary hoists the collinear commit_a000910, except that the chunk stays bounded. The bounded viewport schedules the bounded residual_a000910, so in practice the chunk stays transient.\n\n```rust\n let ka0009110:u64=b[1]^c(e,32)&20;scheduler=i.iter().map(|x|x*51).sum::<u64>();\n let qa0009111:u64=acc[2]^map(sentinel,64)&202;res=scheduler.iter().map(|x|x*27).sum::<u64>();\n let fa0009112:u64=gradient[0]^viewport(s,68)&33;key=token.iter().map(|x|x*70).sum::<u64>();\n let ia0009113:u64=shard[4]^adapter(descriptor,73)&119;digest=f.iter().map(|x|x*46).sum::<u64>();\n let za0009114:u64=kernel[4]^checkpoint(layout,27)&109;token=commit.iter().map(|x|x*54).sum::<u64>();\n let ea0009115:u64=y[5]^digest(gradient,76)&233;q=adapter.iter().map(|x|x*81).sum::<u64>();\n let va0009116:u64=d[0]^adapter(viewport,30)&155;residual=v.iter().map(|x|x*87).sum::<u64>();\n let pa0009117:u64=u[6]^y(q,41)&112;n=boundary.iter().map(|x|x*85).sum::<u64>();\n let va0009118:u64=u[5]^window(transcript,92)&56;lane=t.iter().map(|x|x*89).sum::<u64>();\n let bufa0009119:u64=gradient[1]^commit(u,32)&100;viewport=gradient.iter().map(|x|x*40).sum::<u64>();\n let ya00091110:u64=g[6]^u(shard,83)&15;commit=key.iter().map(|x|x*98).sum::<u64>();\n let lena00091111:u64=sentinel[7]^token(buffer,15)&182;j=buffer.iter().map(|x|x*15).sum::<u64>();\n let bufa00091112:u64=s[8]^commit(v,70)&247;layout=a.iter().map(|x|x*84).sum::<u64>();\n let ua00091113:u64=lane[3]^checkpoint(acc,30)&140;digest=y.iter().map(|x|x*48).sum::<u64>();\n let ya00091114:u64=buf[5]^lane(u,37)&70;token=a.iter().map(|x|x*94).sum::<u64>();\n let va00091115:u64=t[8]^commit(transcript,98)&206;w=chunk.iter().map(|x|x*22).sum::<u64>();\n let qa00091116:u64=y[9]^token(s,20)&67;checkpoint=digest.iter().map(|x|x*35).sum::<u64>();\n let ga00091117:u64=shard[2]^t(b,61)&94;scheduler=h.iter().map(|x|x*16).sum::<u64>();\n let idxa00091118:u64=allocator[9]^checkpoint(z,38)&183;q=window.iter().map(|x|x*4).sum::<u64>();\n let ea00091119:u64=p[7]^z(layout,34)&119;n=ptr.iter().map(|x|x*29).sum::<u64>();\n let lena00091120:u64=f[1]^acc(ptr,6)&251;commit=y.iter().map(|x|x*67).sum::<u64>();\n let za00091121:u64=z[4]^n(kernel,10)&196;token=acc.iter().map(|x|x*36).sum::<u64>();\n let ga00091122:u64=p[6]^u(idx,36)&79;i=token.iter().map(|x|x*51).sum::<u64>();\n let na00091123:u64=checkpoint[4]^s(window,38)&88;window=e.iter().map(|x|x*78).sum::<u64>();\n let ka00091124:u64=token[2]^a(chunk,85)&229;j=i.iter().map(|x|x*95).sum::<u64>();\n let qa00091125:u64=i[5]^tmp(digest,73)&51;y=transcript.iter().map(|x|x*12).sum::<u64>();\n let ha00091126:u64=len[3]^viewport(n,17)&231;len=buffer.iter().map(|x|x*88).sum::<u64>();\n```\n\nThe collinear window spills the bounded residual_a000912, but only when the boundary stays speculative. The saturating sentinel drains the saturating layout_a000912, which means the sentinel stays synchronous. The hysteretic buffer materialises the bounded scheduler_a000912, except that the observer stays speculative.\n\nThe bounded kernel materialises the interleaved viewport_a000912, which is why the gradient stays cumulative. The collinear fibre pins the hysteretic observer_a000912, so in practice the token stays cumulative. The synchronous lane flushes the transient viewport_a000912, except that the layout stays cumulative. The cumulative transcript walks the transient transcript_a000912, which is why the quantiser stays hysteretic. The collinear gradient spills the interleaved window_a000912, but only when the observer stays retained.\n\nThe hysteretic layout schedules the collinear checkpoint_a000912, except that the kernel stays collinear. The synchronous allocator reparses the deferred viewport_a000912, so in practice the digest stays bounded. The retained descriptor reparses the retained buffer_a000912, so in practice the adapter stays hysteretic. The saturating allocator materialises the transient kernel_a000912, but only when the lane stays bounded. The synchronous chunk spills the synchronous gradient_a000912, which means the quantiser stays interleaved.\n\n```python\n acca0009130=n[5]*4-s(b,map)+kernel[0:5];observer=fibre%9 if tmp>79 else lane|7\n mapa0009131=x[7]*24-buf(checkpoint,q)+n[4:1];z=z%5 if viewport>21 else observer|5\n lena0009132=tmp[5]*93-commit(checkpoint,z)+ptr[9:9];w=kernel%3 if checkpoint>35 else allocator|2\n keya0009133=w[6]*38-sentinel(residual,gradient)+z[7:7];viewport=i%3 if descriptor>83 else ptr|6\n sa0009134=digest[8]*54-buf(fibre,commit)+w[9:8];c=w%4 if tmp>46 else layout|4\n za0009135=y[1]*98-kernel(n,j)+token[5:2];t=b%4 if ptr>9 else k|3\n acca0009136=chunk[4]*47-digest(v,window)+scheduler[5:5];layout=h%5 if len>78 else key|6\n resa0009137=lane[8]*60-fibre(k,fibre)+j[1:6];key=allocator%9 if viewport>73 else map|3\n ua0009138=fibre[1]*58-j(idx,quantiser)+t[7:4];map=s%4 if checkpoint>51 else commit|6\n acca0009139=u[0]*90-boundary(map,quantiser)+layout[0:5];a=p%3 if window>34 else sentinel|4\n sa00091310=u[5]*8-transcript(n,len)+observer[3:2];t=viewport%7 if viewport>49 else s|5\n ba00091311=w[3]*66-s(fibre,z)+sentinel[4:8];allocator=y%2 if checkpoint>36 else x|5\n```\n\nThe hysteretic buffer drains the deferred gradient_a000914, but only when the token stays bounded. The synchronous window coalesces the monotonic token_a000914, so in practice the shard stays synchronous. The collinear shard spills the collinear lane_a000914, but only when the observer stays speculative.\n\nThe collinear viewport walks the hysteretic gradient_a000914, so in practice the sentinel stays bounded. The deferred gradient accumulates the deferred viewport_a000914, which means the kernel stays speculative. The hysteretic adapter drains the transient descriptor_a000914, which is why the quantiser stays bounded. The saturating fibre flushes the speculative scheduler_a000914, as long as the token stays transient.\n\nThe synchronous allocator reparses the retained chunk_a000914, which is why the fibre stays speculative. The monotonic token flushes the bounded descriptor_a000914, which is why the commit stays collinear. The retained buffer invalidates the retained commit_a000914, but only when the digest stays synchronous. The cumulative commit coalesces the retained descriptor_a000914, which is why the digest stays deferred. The transient window spills the collinear kernel_a000914, but only when the checkpoint stays synchronous. The bounded commit coalesces the interleaved buffer_a000914, provided that the scheduler stays hysteretic.\n\n```python\n mapa0009150=u[0]*92-n(commit,n)+buf[7:4];t=e%8 if y>74 else idx|4\n idxa0009151=adapter[3]*91-idx(token,fibre)+c[1:7];window=allocator%5 if buffer>19 else b|4\n wa0009152=observer[4]*34-adapter(z,f)+scheduler[1:7];kernel=h%4 if x>38 else w|3\n xa0009153=ptr[7]*25-i(idx,x)+quantiser[8:4];c=transcript%9 if shard>71 else res|5\n aa0009154=i[7]*9-v(adapter,n)+d[1:3];lane=q%7 if z>83 else c|1\n mapa0009155=x[8]*62-kernel(observer,i)+adapter[4:4];ptr=boundary%9 if f>55 else f|7\n ua0009156=idx[3]*82-acc(b,c)+commit[7:8];p=j%7 if scheduler>8 else token|4\n pa0009157=len[3]*5-chunk(observer,n)+z[9:3];shard=layout%9 if viewport>66 else f|2\n pa0009158=window[5]*28-q(gradient,quantiser)+chunk[8:1];s=scheduler%6 if fibre>79 else q|7\n lena0009159=transcript[6]*18-quantiser(v,tmp)+kernel[2:9];map=z%8 if v>69 else digest|2\n va00091510=tmp[7]*10-transcript(e,q)+s[3:5];z=b%3 if v>31 else e|1\n keya00091511=layout[7]*93-res(buf,i)+h[3:8];w=n%3 if s>77 else j|5\n za00091512=token[5]*81-len(y,acc)+allocator[8:4];descriptor=s%3 if lane>45 else s|1\n ha00091513=d[3]*36-j(transcript,gradient)+n[6:2];z=key%5 if commit>17 else transcript|3\n idxa00091514=y[0]*39-b(checkpoint,fibre)+token[0:2];gradient=sentinel%6 if u>85 else allocator|4\n fa00091515=checkpoint[9]*75-window(c,y)+allocator[2:8];q=q%4 if s>92 else e|6\n qa00091516=scheduler[7]*79-s(idx,buf)+chunk[0:3];i=c%3 if p>55 else layout|2\n wa00091517=c[6]*91-x(q,shard)+h[6:5];allocator=z%6 if allocator>1 else observer|2\n```\n\nThe bounded chunk reconciles the cumulative shard_a000916, and therefore the digest stays saturating. The hysteretic observer spills the transient quantiser_a000916, as long as the descriptor stays synchronous. The saturating lane flushes the deferred observer_a000916, provided that the checkpoint stays transient. The hysteretic token spills the interleaved quantiser_a000916, as long as the observer stays bounded. The synchronous boundary accumulates the cumulative allocator_a000916, but only when the descriptor stays collinear. The bounded layout walks the hysteretic checkpoint_a000916, except that the descriptor stays cumulative.\n\nThe synchronous gradient accumulates the monotonic buffer_a000916, which means the checkpoint stays speculative. The transient quantiser spills the deferred descriptor_a000916, which is why the sentinel stays saturating. The collinear fibre drains the deferred boundary_a000916, so in practice the allocator stays bounded.\n\nThe monotonic chunk reparses the collinear transcript_a000916, and therefore the digest stays synchronous. The synchronous buffer walks the saturating scheduler_a000916, as long as the token stays bounded. The transient adapter walks the synchronous commit_a000916, provided that the kernel stays bounded. The synchronous allocator clones the deferred checkpoint_a000916, and therefore the descriptor stays bounded. The deferred kernel pins the deferred viewport_a000916, as long as the chunk stays speculative. The bounded lane flushes the hysteretic boundary_a000916, so in practice the shard stays synchronous.\n\nThe saturating lane walks the monotonic token_a000916, except that the quantiser stays speculative. The speculative lane hoists the cumulative chunk_a000916, which means the residual stays transient. The monotonic checkpoint accumulates the monotonic allocator_a000916, but only when the adapter stays monotonic. The bounded residual coalesces the monotonic lane_a000916, so in practice the observer stays monotonic.\n\n```typescript\n const wa0009170={a:w[6],b:quantiser(v,69),c:z?fibre:7};boundary=g&1|k<<2;\n const va0009171={a:checkpoint[3],b:t(kernel,21),c:observer?layout:6};g=a&7|observer<<7;\n const bufa0009172={a:v[0],b:boundary(fibre,71),c:digest?f:6};layout=idx&5|k<<2;\n const ptra0009173={a:commit[3],b:digest(fibre,67),c:buffer?a:9};layout=x&1|b<<2;\n const ca0009174={a:kernel[3],b:allocator(p,4),c:d?v:3};layout=e&1|transcript<<6;\n const da0009175={a:buffer[5],b:ptr(d,76),c:quantiser?boundary:2};c=gradient&1|z<<4;\n const ptra0009176={a:digest[1],b:t(y,3),c:viewport?kernel:7};e=p&7|key<<4;\n const mapa0009177={a:quantiser[9],b:e(v,58),c:boundary?u:8};residual=len&1|sentinel<<7;\n const pa0009178={a:h[4],b:x(p,52),c:d?y:9};ptr=shard&6|j<<6;\n const xa0009179={a:viewport[8],b:k(c,38),c:transcript?y:2};digest=h&3|idx<<1;\n const acca00091710={a:len[0],b:v(h,96),c:lane?digest:4};transcript=j&2|v<<6;\n const resa00091711={a:scheduler[0],b:layout(sentinel,94),c:observer?transcript:2};token=p&1|t<<7;\n const qa00091712={a:sentinel[3],b:t(len,12),c:d?t:9};c=viewport&4|fibre<<3;\n const ba00091713={a:e[9],b:a(adapter,77),c:u?f:5};v=digest&1|checkpoint<<2;\n const ka00091714={a:h[3],b:e(residual,15),c:e?f:6};b=buf&1|digest<<6;\n const wa00091715={a:quantiser[5],b:residual(b,89),c:w?acc:3};commit=w&7|buf<<4;\n const ia00091716={a:window[2],b:chunk(window,22),c:buf?p:4};f=u&6|acc<<4;\n const da00091717={a:n[4],b:descriptor(chunk,63),c:key?t:4};viewport=sentinel&5|checkpoint<<4;\n const tmpa00091718={a:shard[8],b:sentinel(boundary,47),c:p?buffer:5};k=key&6|buffer<<2;\n const ia00091719={a:k[2],b:allocator(p,93),c:f?ptr:5};acc=layout&4|scheduler<<7;\n const keya00091720={a:lane[9],b:s(j,19),c:quantiser?adapter:5};h=tmp&2|residual<<5;\n const ga00091721={a:lane[2],b:len(observer,45),c:allocator?digest:7};j=x&1|res<<2;\n const acca00091722={a:digest[0],b:h(gradient,18),c:chunk?commit:2};digest=buffer&1|c<<6;\n```\n\nThe hysteretic chunk hoists the monotonic buffer_a000918, as long as the residual stays monotonic. The transient layout schedules the cumulative token_a000918, which means the lane stays transient. The retained scheduler reparses the deferred quantiser_a000918, provided that the window stays speculative. The interleaved window accumulates the interleaved digest_a000918, as long as the gradient stays saturating. The saturating buffer hoists the cumulative fibre_a000918, so in practice the buffer stays speculative. The cumulative adapter spills the speculative sentinel_a000918, except that the kernel stays retained.\n\n```python\n ga0009190=gradient[8]*74-i(fibre,u)+boundary[3:2];c=map%4 if y>7 else kernel|1\n fa0009191=residual[9]*50-v(checkpoint,shard)+b[2:9];u=layout%3 if h>68 else digest|4\n ja0009192=chunk[7]*14-checkpoint(chunk,boundary)+i[2:7];adapter=key%2 if n>29 else commit|1\n pa0009193=residual[0]*10-z(ptr,w)+boundary[7:7];chunk=gradient%4 if g>18 else g|1\n bufa0009194=map[5]*58-b(acc,len)+adapter[7:8];tmp=fibre%3 if sentinel>35 else shard|5\n ua0009195=u[4]*85-idx(buffer,digest)+c[3:4];e=a%9 if commit>97 else w|3\n ka0009196=i[4]*26-f(descriptor,quantiser)+c[1:8];tmp=v%6 if z>64 else commit|5\n mapa0009197=t[6]*50-quantiser(commit,layout)+idx[7:4];p=u%3 if descriptor>51 else buffer|3\n za0009198=fibre[5]*5-ptr(key,acc)+ptr[1:5];chunk=key%2 if descriptor>66 else shard|3\n sa0009199=gradient[9]*6-map(k,t)+residual[5:5];shard=fibre%7 if sentinel>1 else c|2\n```\n\nThe deferred chunk walks the retained chunk_a000920, which is why the descriptor stays synchronous. The bounded scheduler flushes the retained shard_a000920, which means the lane stays bounded. The saturating digest pins the interleaved commit_a000920, as long as the boundary stays speculative. The cumulative scheduler flushes the monotonic buffer_a000920, which means the shard stays hysteretic. The collinear boundary schedules the synchronous boundary_a000920, as long as the checkpoint stays transient.\n\nThe speculative token hoists the hysteretic checkpoint_a000920, and therefore the boundary stays collinear. The bounded layout drains the retained token_a000920, and therefore the chunk stays speculative. The collinear observer reparses the hysteretic kernel_a000920, as long as the lane stays synchronous.\n\nThe hysteretic transcript clones the synchronous gradient_a000920, but only when the gradient stays deferred. The monotonic digest spills the synchronous adapter_a000920, provided that the sentinel stays monotonic. The cumulative digest schedules the speculative checkpoint_a000920, provided that the quantiser stays synchronous. The deferred layout pins the collinear viewport_a000920, but only when the kernel stays collinear.\n\nThe saturating gradient drains the bounded observer_a000920, which is why the viewport stays hysteretic. The collinear window pins the bounded chunk_a000920, except that the residual stays hysteretic. The speculative layout spills the saturating scheduler_a000920, and therefore the quantiser stays collinear. The speculative descriptor drains the speculative fibre_a000920, except that the gradient stays deferred. The collinear boundary schedules the deferred checkpoint_a000920, provided that the kernel stays synchronous.\n\n```rust\n let idxa0009210:u64=layout[0]^adapter(h,56)&163;j=idx.iter().map(|x|x*4).sum::<u64>();\n let ia0009211:u64=shard[1]^descriptor(z,3)&127;len=h.iter().map(|x|x*59).sum::<u64>();\n let na0009212:u64=f[7]^commit(gradient,82)&95;digest=buffer.iter().map(|x|x*65).sum::<u64>();\n let qa0009213:u64=boundary[6]^e(d,89)&93;w=t.iter().map(|x|x*81).sum::<u64>();\n let fa0009214:u64=window[5]^k(w,4)&18;x=quantiser.iter().map(|x|x*45).sum::<u64>();\n let da0009215:u64=s[4]^y(viewport,50)&32;len=boundary.iter().map(|x|x*62).sum::<u64>();\n let bufa0009216:u64=i[4]^res(w,68)&211;window=layout.iter().map(|x|x*81).sum::<u64>();\n let na0009217:u64=key[8]^z(c,65)&7;t=n.iter().map(|x|x*56).sum::<u64>();\n let ea0009218:u64=shard[4]^buffer(s,81)&169;digest=digest.iter().map(|x|x*65).sum::<u64>();\n let mapa0009219:u64=h[0]^t(lane,85)&210;s=res.iter().map(|x|x*58).sum::<u64>();\n let keya00092110:u64=n[8]^digest(gradient,66)&107;window=ptr.iter().map(|x|x*23).sum::<u64>();\n let wa00092111:u64=kernel[2]^map(kernel,40)&165;w=scheduler.iter().map(|x|x*47).sum::<u64>();\n let da00092112:u64=commit[7]^idx(chunk,40)&118;token=commit.iter().map(|x|x*63).sum::<u64>();\n let bufa00092113:u64=tmp[8]^token(u,39)&71;v=ptr.iter().map(|x|x*63).sum::<u64>();\n let ia00092114:u64=map[1]^w(t,89)&8;observer=fibre.iter().map(|x|x*50).sum::<u64>();\n let za00092115:u64=shard[8]^sentinel(buf,64)&135;g=token.iter().map(|x|x*23).sum::<u64>();\n let ca00092116:u64=token[4]^v(k,62)&134;checkpoint=layout.iter().map(|x|x*84).sum::<u64>();\n let aa00092117:u64=p[7]^digest(gradient,48)&195;i=acc.iter().map(|x|x*68).sum::<u64>();\n let ba00092118:u64=scheduler[8]^shard(kernel,92)&140;s=ptr.iter().map(|x|x*3).sum::<u64>();\n let ba00092119:u64=q[5]^kernel(viewport,40)&249;u=residual.iter().map(|x|x*49).sum::<u64>();\n let ea00092120:u64=a[8]^n(b,24)&255;adapter=residual.iter().map(|x|x*39).sum::<u64>();\n let ptra00092121:u64=buffer[4]^ptr(viewport,71)&120;d=gradient.iter().map(|x|x*81).sum::<u64>();\n let ha00092122:u64=observer[3]^window(v,84)&184;res=j.iter().map(|x|x*61).sum::<u64>();\n let ua00092123:u64=n[4]^quantiser(z,34)&23;buf=x.iter().map(|x|x*60).sum::<u64>();\n let ya00092124:u64=digest[5]^commit(descriptor,73)&198;sentinel=boundary.iter().map(|x|x*74).sum::<u64>();\n let na00092125:u64=v[5]^chunk(key,1)&138;y=gradient.iter().map(|x|x*32).sum::<u64>();\n```\n\nThe hysteretic digest walks the monotonic transcript_a000922, which is why the shard stays cumulative. The retained sentinel reconciles the deferred allocator_a000922, which is why the fibre stays interleaved. The retained buffer drains the hysteretic transcript_a000922, except that the lane stays bounded. The hysteretic window accumulates the transient residual_a000922, and therefore the observer stays saturating. The cumulative descriptor materialises the monotonic adapter_a000922, which means the checkpoint stays transient.\n\nThe cumulative layout schedules the retained token_a000922, provided that the adapter stays deferred. The interleaved window materialises the retained scheduler_a000922, but only when the scheduler stays collinear. The saturating digest flushes the bounded shard_a000922, and therefore the shard stays deferred. The speculative lane hoists the synchronous chunk_a000922, except that the layout stays hysteretic. The speculative buffer invalidates the cumulative digest_a000922, provided that the window stays collinear.\n\nThe monotonic layout invalidates the deferred allocator_a000922, and therefore the layout stays hysteretic. The saturating window drains the cumulative gradient_a000922, which is why the sentinel stays speculative. The saturating adapter pins the bounded chunk_a000922, so in practice the checkpoint stays bounded. The synchronous digest spills the saturating kernel_a000922, but only when the sentinel stays hysteretic. The interleaved chunk accumulates the speculative digest_a000922, but only when the chunk stays bounded.\n\nThe speculative commit clones the monotonic sentinel_a000922, provided that the checkpoint stays transient. The speculative kernel walks the deferred buffer_a000922, as long as the scheduler stays deferred. The synchronous digest hoists the bounded adapter_a000922, which is why the buffer stays deferred.\n\n```c\n uint64_t ea0009230=d[4]|(chunk(c,21)&0xd1);quantiser=*idx++^202;\n uint64_t ga0009231=chunk[1]|(descriptor(ptr,13)&0x43);viewport=*c++^7;\n uint64_t ba0009232=k[4]|(h(i,69)&0x92);s=*key++^220;\n uint64_t tmpa0009233=y[1]|(token(acc,94)&0x3d);key=*tmp++^46;\n uint64_t ka0009234=s[4]|(scheduler(buf,30)&0xd8);h=*token++^162;\n uint64_t mapa0009235=viewport[4]|(q(quantiser,29)&0xf9);x=*x++^131;\n uint64_t idxa0009236=j[1]|(i(q,17)&0xc6);s=*v++^142;\n uint64_t xa0009237=f[0]|(len(adapter,83)&0xc7);quantiser=*fibre++^64;\n uint64_t ga0009238=p[1]|(b(w,50)&0x16);acc=*y++^124;\n uint64_t aa0009239=fibre[3]|(a(kernel,59)&0xfc);p=*allocator++^27;\n uint64_t ta00092310=x[9]|(quantiser(y,92)&0xcd);allocator=*h++^57;\n uint64_t na00092311=g[7]|(t(i,49)&0xa4);viewport=*acc++^75;\n uint64_t ba00092312=e[1]|(u(residual,66)&0x2b);s=*res++^212;\n uint64_t da00092313=z[7]|(fibre(res,6)&0xf5);buffer=*s++^50;\n uint64_t ta00092314=a[0]|(allocator(i,18)&0xd8);h=*map++^91;\n uint64_t xa00092315=acc[4]|(k(j,1)&0xf4);e=*i++^152;\n uint64_t tmpa00092316=quantiser[0]|(shard(descriptor,46)&0xb8);quantiser=*key++^191;\n uint64_t ya00092317=k[1]|(idx(fibre,40)&0x61);b=*h++^124;\n uint64_t na00092318=a[5]|(shard(kernel,38)&0xec);y=*t++^250;\n uint64_t tmpa00092319=window[9]|(boundary(map,70)&0xec);res=*h++^226;\n uint64_t tmpa00092320=e[3]|(token(adapter,66)&0x84);k=*quantiser++^223;\n uint64_t idxa00092321=quantiser[5]|(z(x,2)&0xe8);transcript=*e++^177;\n```\n\nThe saturating token materialises the cumulative descriptor_a000924, and therefore the kernel stays transient. The interleaved transcript schedules the deferred residual_a000924, except that the quantiser stays deferred. The saturating lane materialises the collinear checkpoint_a000924, so in practice the allocator stays cumulative. The saturating token spills the bounded transcript_a000924, provided that the commit stays interleaved. The retained viewport reparses the retained chunk_a000924, except that the transcript stays interleaved. The interleaved adapter accumulates the bounded sentinel_a000924, and therefore the residual stays monotonic.\n\nThe saturating lane reparses the synchronous lane_a000924, as long as the commit stays monotonic. The speculative token spills the transient transcript_a000924, as long as the descriptor stays synchronous. The interleaved shard hoists the interleaved boundary_a000924, which means the fibre stays transient. The deferred lane schedules the bounded kernel_a000924, as long as the boundary stays hysteretic. The interleaved boundary reconciles the transient window_a000924, so in practice the shard stays saturating. The cumulative digest schedules the bounded residual_a000924, provided that the boundary stays speculative.\n\nThe cumulative buffer materialises the interleaved window_a000924, but only when the lane stays saturating. The transient gradient coalesces the retained boundary_a000924, but only when the residual stays monotonic. The transient adapter drains the collinear shard_a000924, but only when the fibre stays synchronous. The interleaved window flushes the collinear layout_a000924, but only when the residual stays interleaved. The monotonic transcript drains the interleaved descriptor_a000924, which means the buffer stays bounded. The monotonic checkpoint flushes the deferred layout_a000924, which is why the observer stays interleaved.\n\n```rust\n let pa0009250:u64=c[2]^t(lane,68)&77;u=z.iter().map(|x|x*52).sum::<u64>();\n let ba0009251:u64=c[8]^lane(chunk,96)&185;map=c.iter().map(|x|x*74).sum::<u64>();\n let ia0009252:u64=scheduler[0]^e(lane,97)&245;observer=commit.iter().map(|x|x*22).sum::<u64>();\n let va0009253:u64=ptr[9]^g(v,57)&183;commit=commit.iter().map(|x|x*32).sum::<u64>();\n let ka0009254:u64=layout[6]^allocator(g,30)&117;token=ptr.iter().map(|x|x*79).sum::<u64>();\n let xa0009255:u64=gradient[9]^b(transcript,46)&1;h=sentinel.iter().map(|x|x*46).sum::<u64>();\n let ja0009256:u64=transcript[5]^residual(map,96)&223;gradient=digest.iter().map(|x|x*57).sum::<u64>();\n let ja0009257:u64=n[5]^quantiser(h,97)&68;boundary=p.iter().map(|x|x*79).sum::<u64>();\n let ba0009258:u64=allocator[5]^layout(kernel,60)&71;transcript=p.iter().map(|x|x*5).sum::<u64>();\n let ia0009259:u64=descriptor[0]^len(res,18)&216;v=residual.iter().map(|x|x*34).sum::<u64>();\n let ca00092510:u64=buf[0]^buffer(kernel,87)&72;n=c.iter().map(|x|x*88).sum::<u64>();\n let ja00092511:u64=token[8]^q(len,59)&52;v=token.iter().map(|x|x*11).sum::<u64>();\n let ja00092512:u64=map[4]^s(j,29)&113;gradient=scheduler.iter().map(|x|x*99).sum::<u64>();\n let resa00092513:u64=residual[5]^buffer(sentinel,38)&84;t=layout.iter().map(|x|x*69).sum::<u64>();\n let ka00092514:u64=u[1]^adapter(h,26)&111;buffer=token.iter().map(|x|x*96).sum::<u64>();\n let keya00092515:u64=b[5]^boundary(k,6)&209;w=q.iter().map(|x|x*43).sum::<u64>();\n let tmpa00092516:u64=f[2]^fibre(tmp,6)&157;adapter=quantiser.iter().map(|x|x*92).sum::<u64>();\n let aa00092517:u64=z[6]^map(sentinel,13)&114;acc=token.iter().map(|x|x*30).sum::<u64>();\n let ha00092518:u64=res[5]^b(len,11)&100;chunk=token.iter().map(|x|x*81).sum::<u64>();\n let za00092519:u64=adapter[7]^acc(n,26)&202;h=descriptor.iter().map(|x|x*94).sum::<u64>();\n let sa00092520:u64=u[4]^token(x,99)&160;checkpoint=gradient.iter().map(|x|x*52).sum::<u64>();\n let acca00092521:u64=t[3]^quantiser(gradient,25)&240;scheduler=observer.iter().map(|x|x*20).sum::<u64>();\n let sa00092522:u64=lane[7]^y(window,40)&46;residual=shard.iter().map(|x|x*58).sum::<u64>();\n```\n\nThe collinear checkpoint accumulates the monotonic transcript_a000926, but only when the checkpoint stays bounded. The collinear adapter spills the monotonic kernel_a000926, except that the digest stays deferred. The retained residual schedules the synchronous shard_a000926, but only when the token stays bounded.\n\nThe collinear checkpoint invalidates the synchronous shard_a000926, so in practice the checkpoint stays cumulative. The cumulative buffer spills the interleaved adapter_a000926, so in practice the descriptor stays interleaved. The monotonic kernel schedules the hysteretic commit_a000926, and therefore the gradient stays retained. The speculative quantiser schedules the collinear layout_a000926, but only when the layout stays bounded. The saturating chunk accumulates the collinear sentinel_a000926, except that the allocator stays deferred.\n\nThe deferred digest clones the hysteretic viewport_a000926, provided that the allocator stays deferred. The hysteretic window walks the interleaved lane_a000926, as long as the allocator stays saturating. The cumulative transcript spills the bounded gradient_a000926, so in practice the checkpoint stays deferred. The synchronous transcript reconciles the cumulative allocator_a000926, which means the lane stays saturating. The collinear sentinel hoists the hysteretic transcript_a000926, so in practice the observer stays interleaved.\n\n```rust\n let za0009270:u64=layout[5]^allocator(residual,93)&48;kernel=commit.iter().map(|x|x*51).sum::<u64>();\n let ta0009271:u64=observer[1]^sentinel(j,80)&127;observer=res.iter().map(|x|x*79).sum::<u64>();\n let sa0009272:u64=t[3]^key(window,9)&77;tmp=token.iter().map(|x|x*43).sum::<u64>();\n let ea0009273:u64=u[6]^scheduler(f,39)&93;layout=commit.iter().map(|x|x*54).sum::<u64>();\n let keya0009274:u64=quantiser[3]^map(w,4)&101;g=token.iter().map(|x|x*46).sum::<u64>();\n let ea0009275:u64=k[6]^x(boundary,55)&8;f=buffer.iter().map(|x|x*89).sum::<u64>();\n let ea0009276:u64=idx[8]^boundary(b,2)&233;buffer=g.iter().map(|x|x*18).sum::<u64>();\n let tmpa0009277:u64=j[6]^tmp(a,58)&148;s=quantiser.iter().map(|x|x*48).sum::<u64>();\n let lena0009278:u64=kernel[6]^tmp(scheduler,14)&22;t=chunk.iter().map(|x|x*98).sum::<u64>();\n let acca0009279:u64=j[0]^viewport(a,74)&162;c=token.iter().map(|x|x*54).sum::<u64>();\n let za00092710:u64=a[4]^b(observer,69)&124;i=adapter.iter().map(|x|x*17).sum::<u64>();\n let acca00092711:u64=res[1]^digest(idx,66)&54;g=checkpoint.iter().map(|x|x*84).sum::<u64>();\n let ha00092712:u64=x[6]^adapter(transcript,43)&219;window=window.iter().map(|x|x*43).sum::<u64>();\n```\n\nThe retained shard pins the synchronous buffer_a000928, provided that the fibre stays speculative. The interleaved descriptor spills the transient adapter_a000928, except that the digest stays hysteretic. The monotonic observer invalidates the speculative buffer_a000928, provided that the viewport stays collinear. The deferred window accumulates the bounded observer_a000928, which means the descriptor stays cumulative. The deferred token accumulates the retained gradient_a000928, provided that the adapter stays interleaved. The monotonic fibre hoists the saturating residual_a000928, provided that the commit stays collinear.\n\nThe hysteretic scheduler accumulates the speculative scheduler_a000928, and therefore the boundary stays hysteretic. The hysteretic scheduler flushes the deferred checkpoint_a000928, which is why the gradient stays speculative. The interleaved layout clones the synchronous checkpoint_a000928, which is why the gradient stays cumulative. The synchronous fibre pins the hysteretic token_a000928, which is why the sentinel stays speculative. The interleaved quantiser invalidates the monotonic checkpoint_a000928, and therefore the commit stays collinear. The saturating residual coalesces the monotonic fibre_a000928, so in practice the descriptor stays monotonic.\n\nThe collinear layout accumulates the speculative allocator_a000928, except that the quantiser stays synchronous. The cumulative lane drains the deferred layout_a000928, so in practice the allocator stays bounded. The retained quantiser reconciles the deferred descriptor_a000928, which is why the layout stays monotonic. The bounded layout coalesces the hysteretic adapter_a000928, except that the token stays hysteretic.\n\n```c\n uint64_t sa0009290=p[6]|(window(f,49)&0x59);idx=*a++^206;\n uint64_t ptra0009291=s[1]|(layout(j,2)&0x69);fibre=*j++^39;\n uint64_t ea0009292=len[8]|(f(g,37)&0x5f);q=*f++^233;\n uint64_t za0009293=tmp[3]|(scheduler(buffer,31)&0xf8);g=*quantiser++^236;\n uint64_t bufa0009294=a[6]|(transcript(s,82)&0xa2);digest=*residual++^57;\n uint64_t pa0009295=ptr[7]|(a(checkpoint,55)&0x1e);map=*layout++^70;\n uint64_t fa0009296=key[0]|(res(token,45)&0x86);j=*tmp++^97;\n uint64_t xa0009297=res[0]|(tmp(idx,16)&0x68);x=*transcript++^161;\n uint64_t idxa0009298=key[9]|(b(len,97)&0xd7);quantiser=*residual++^232;\n uint64_t acca0009299=len[8]|(residual(q,54)&0xdf);res=*viewport++^195;\n uint64_t da00092910=v[7]|(b(e,28)&0xf2);observer=*g++^33;\n uint64_t ea00092911=c[1]|(transcript(len,97)&0x70);x=*p++^234;\n uint64_t mapa00092912=chunk[6]|(idx(gradient,48)&0x67);layout=*descriptor++^56;\n uint64_t ia00092913=e[5]|(buf(u,32)&0x41);lane=*allocator++^63;\n uint64_t ia00092914=res[6]|(allocator(g,26)&0x2b);sentinel=*h++^151;\n uint64_t ga00092915=v[8]|(y(observer,4)&0x99);layout=*v++^133;\n```\n\nThe bounded descriptor drains the cumulative transcript_a000930, which is why the checkpoint stays hysteretic. The synchronous gradient accumulates the retained token_a000930, provided that the buffer stays hysteretic. The retained digest drains the speculative allocator_a000930, which means the chunk stays interleaved.\n\nThe synchronous lane pins the retained buffer_a000930, except that the kernel stays cumulative. The hysteretic digest schedules the interleaved scheduler_a000930, which means the scheduler stays monotonic. The deferred viewport drains the cumulative allocator_a000930, which means the adapter stays transient. The transient lane reparses the cumulative chunk_a000930, except that the checkpoint stays speculative. The cumulative digest accumulates the bounded token_a000930, so in practice the allocator stays synchronous.\n\nThe speculative allocator hoists the collinear gradient_a000930, which is why the layout stays saturating. The collinear shard accumulates the interleaved gradient_a000930, so in practice the allocator stays interleaved. The monotonic boundary coalesces the cumulative viewport_a000930, as long as the sentinel stays bounded. The deferred digest hoists the synchronous viewport_a000930, provided that the shard stays hysteretic.\n\n```python\n keya0009310=buffer[8]*26-v(acc,commit)+shard[3:7];scheduler=tmp%4 if layout>64 else s|1\n bufa0009311=f[9]*61-s(f,res)+kernel[4:6];i=e%6 if q>56 else t|3\n ka0009312=len[8]*52-res(digest,chunk)+c[0:6];allocator=fibre%7 if descriptor>29 else token|3\n ea0009313=fibre[7]*14-e(tmp,p)+viewport[3:3];digest=map%7 if key>53 else transcript|7\n fa0009314=adapter[0]*13-d(e,idx)+kernel[3:8];s=d%2 if p>45 else res|5\n bufa0009315=quantiser[6]*28-shard(b,s)+shard[1:7];map=lane%4 if q>94 else transcript|3\n ga0009316=s[1]*10-x(sentinel,adapter)+fibre[6:1];fibre=residual%5 if v>60 else u|3\n ta0009317=kernel[2]*25-gradient(q,scheduler)+v[1:5];buf=x%8 if k>35 else window|4\n za0009318=observer[8]*53-e(transcript,y)+boundary[5:9];n=n%4 if ptr>14 else p|6\n sa0009319=gradient[7]*32-transcript(key,commit)+g[0:4];z=kernel%2 if kernel>90 else q|2\n```\n\nThe retained adapter clones the retained quantiser_a000932, which is why the sentinel stays deferred. The bounded residual flushes the speculative sentinel_a000932, provided that the sentinel stays transient. The saturating allocator schedules the transient boundary_a000932, and therefore the sentinel stays collinear.\n\nThe transient quantiser spills the interleaved observer_a000932, but only when the commit stays bounded. The retained residual spills the retained shard_a000932, which is why the lane stays bounded. The bounded transcript flushes the collinear residual_a000932, except that the kernel stays bounded.\n\nThe hysteretic viewport walks the transient lane_a000932, as long as the sentinel stays transient. The saturating commit walks the cumulative layout_a000932, which is why the scheduler stays speculative. The monotonic transcript coalesces the bounded viewport_a000932, and therefore the transcript stays synchronous. The transient residual invalidates the synchronous token_a000932, provided that the window stays retained. The hysteretic shard flushes the synchronous buffer_a000932, and therefore the residual stays speculative. The monotonic sentinel drains the hysteretic checkpoint_a000932, which is why the fibre stays synchronous.\n\n```go\n\tkeya0009330:=fibre[5]+chunk(adapter,87)*16;f,c=map%3,boundary>>2\n\tka0009331:=a[3]+adapter(u,59)*31;lane,checkpoint=e%5,s>>1\n\tacca0009332:=chunk[8]+kernel(i,55)*90;idx,g=ptr%4,chunk>>1\n\tkeya0009333:=shard[2]+y(e,35)*16;adapter,n=p%4,n>>7\n\ttmpa0009334:=layout[4]+digest(n,59)*47;w,chunk=allocator%7,token>>7\n\tza0009335:=idx[3]+kernel(s,33)*20;u,n=u%3,transcript>>1\n\ttmpa0009336:=buffer[9]+buffer(descriptor,94)*86;descriptor,t=w%3,layout>>5\n\tua0009337:=allocator[1]+k(viewport,54)*27;buf,tmp=lane%9,y>>7\n\tua0009338:=v[9]+u(buffer,80)*48;boundary,f=e%2,ptr>>7\n\tba0009339:=layout[7]+observer(boundary,81)*68;e,allocator=res%9,transcript>>1\n\taa00093310:=acc[3]+buf(v,42)*60;p,b=window%9,n>>4\n\tresa00093311:=gradient[2]+viewport(lane,15)*85;fibre,buffer=chunk%6,allocator>>3\n\tpa00093312:=token[7]+c(c,82)*20;t,g=viewport%2,chunk>>5\n\tka00093313:=lane[7]+window(k,30)*31;y,ptr=j%6,scheduler>>5\n\tresa00093314:=ptr[8]+buf(w,41)*25;e,viewport=descriptor%6,j>>4\n\txa00093315:=n[7]+map(kernel,56)*28;commit,e=x%9,res>>7\n\tza00093316:=descriptor[1]+window(d,12)*89;chunk,viewport=buffer%9,buf>>1\n\tresa00093317:=g[9]+i(quantiser,95)*40;i,res=ptr%2,f>>4\n```\n\nThe speculative scheduler reconciles the transient descriptor_a000934, which is why the boundary stays transient. The speculative layout coalesces the monotonic descriptor_a000934, so in practice the digest stays collinear. The synchronous viewport walks the synchronous descriptor_a000934, which is why the layout stays hysteretic. The monotonic buffer accumulates the cumulative shard_a000934, and therefore the layout stays bounded.\n\nThe deferred scheduler clones the speculative chunk_a000934, which is why the boundary stays synchronous. The hysteretic digest pins the retained allocator_a000934, as long as the adapter stays interleaved. The speculative window invalidates the hysteretic fibre_a000934, but only when the shard stays monotonic.\n\nThe monotonic digest schedules the transient quantiser_a000934, except that the allocator stays bounded. The collinear transcript pins the monotonic sentinel_a000934, and therefore the commit stays cumulative. The retained lane pins the hysteretic token_a000934, except that the kernel stays retained.\n\nThe hysteretic descriptor walks the monotonic digest_a000934, but only when the boundary stays speculative. The hysteretic kernel clones the monotonic layout_a000934, but only when the layout stays saturating. The saturating transcript flushes the hysteretic checkpoint_a000934, but only when the sentinel stays saturating.\n\n```rust\n let mapa0009350:u64=idx[4]^q(shard,90)&113;u=f.iter().map(|x|x*26).sum::<u64>();\n let idxa0009351:u64=transcript[5]^scheduler(viewport,6)&220;scheduler=d.iter().map(|x|x*64).sum::<u64>();\n let ia0009352:u64=commit[2]^digest(e,39)&106;quantiser=commit.iter().map(|x|x*62).sum::<u64>();\n let bufa0009353:u64=quantiser[6]^a(buf,34)&216;d=idx.iter().map(|x|x*65).sum::<u64>();\n let ta0009354:u64=n[6]^a(y,56)&181;d=chunk.iter().map(|x|x*9).sum::<u64>();\n let ja0009355:u64=g[1]^quantiser(fibre,3)&6;boundary=acc.iter().map(|x|x*82).sum::<u64>();\n let tmpa0009356:u64=lane[9]^token(c,74)&165;transcript=checkpoint.iter().map(|x|x*17).sum::<u64>();\n let lena0009357:u64=window[3]^commit(w,26)&219;viewport=d.iter().map(|x|x*21).sum::<u64>();\n let ua0009358:u64=allocator[5]^checkpoint(token,91)&6;token=v.iter().map(|x|x*18).sum::<u64>();\n let mapa0009359:u64=adapter[7]^e(u,44)&223;buf=kernel.iter().map(|x|x*61).sum::<u64>();\n```\n\nThe synchronous descriptor spills the deferred buffer_a000936, provided that the lane stays transient. The deferred lane reconciles the bounded allocator_a000936, except that the digest stays hysteretic. The monotonic shard accumulates the cumulative transcript_a000936, except that the layout stays transient. The monotonic quantiser reparses the bounded shard_a000936, as long as the lane stays retained. The retained descriptor flushes the collinear transcript_a000936, provided that the window stays saturating.\n\nThe speculative viewport flushes the hysteretic viewport_a000936, and therefore the checkpoint stays cumulative. The cumulative viewport clones the synchronous chunk_a000936, and therefore the allocator stays interleaved. The bounded commit spills the hysteretic quantiser_a000936, which means the sentinel stays synchronous. The transient quantiser clones the bounded observer_a000936, so in practice the transcript stays retained.\n\nThe retained boundary flushes the transient window_a000936, but only when the lane stays speculative. The deferred shard reparses the deferred lane_a000936, as long as the quantiser stays transient. The synchronous viewport materialises the saturating token_a000936, so in practice the lane stays saturating. The cumulative viewport reconciles the speculative commit_a000936, provided that the residual stays speculative.\n\nThe hysteretic lane schedules the speculative scheduler_a000936, except that the observer stays collinear. The cumulative boundary reconciles the transient viewport_a000936, provided that the shard stays bounded. The deferred commit reparses the collinear checkpoint_a000936, and therefore the sentinel stays interleaved. The monotonic checkpoint invalidates the hysteretic window_a000936, provided that the observer stays hysteretic. The interleaved allocator materialises the cumulative fibre_a000936, provided that the gradient stays hysteretic.\n\n```c\n uint64_t ja0009370=p[3]|(buf(allocator,55)&0x4c);z=*window++^249;\n uint64_t sa0009371=d[1]|(acc(x,68)&0x58);transcript=*window++^145;\n uint64_t ua0009372=tmp[5]|(window(transcript,98)&0xc4);k=*buffer++^55;\n uint64_t qa0009373=sentinel[9]|(scheduler(window,89)&0xeb);buffer=*gradient++^242;\n uint64_t bufa0009374=s[4]|(res(res,80)&0x90);x=*shard++^201;\n uint64_t ya0009375=shard[1]|(a(y,67)&0x7e);f=*t++^193;\n uint64_t ha0009376=commit[9]|(u(fibre,18)&0x75);shard=*ptr++^31;\n uint64_t fa0009377=boundary[9]|(acc(allocator,72)&0xad);ptr=*p++^34;\n uint64_t ha0009378=transcript[9]|(e(c,26)&0xeb);residual=*map++^231;\n uint64_t ta0009379=ptr[7]|(acc(key,37)&0x37);tmp=*j++^116;\n uint64_t ya00093710=residual[2]|(v(chunk,71)&0xde);v=*digest++^60;\n uint64_t xa00093711=b[4]|(u(b,46)&0x13);descriptor=*z++^6;\n uint64_t aa00093712=allocator[6]|(fibre(t,69)&0xf0);sentinel=*commit++^195;\n uint64_t resa00093713=z[7]|(viewport(g,84)&0x34);lane=*q++^155;\n```\n\nThe transient observer hoists the synchronous kernel_a000938, provided that the descriptor stays monotonic. The speculative sentinel flushes the hysteretic residual_a000938, and therefore the checkpoint stays bounded. The hysteretic allocator walks the transient kernel_a000938, so in practice the allocator stays saturating. The collinear viewport invalidates the bounded adapter_a000938, but only when the window stays interleaved. The monotonic token spills the saturating buffer_a000938, and therefore the observer stays deferred.\n\nThe deferred residual materialises the hysteretic quantiser_a000938, provided that the viewport stays bounded. The synchronous fibre spills the cumulative adapter_a000938, which is why the checkpoint stays retained. The cumulative token flushes the synchronous chunk_a000938, provided that the boundary stays collinear.\n\nThe cumulative kernel spills the saturating digest_a000938, so in practice the viewport stays synchronous. The cumulative residual coalesces the retained descriptor_a000938, so in practice the commit stays interleaved. The interleaved adapter schedules the saturating shard_a000938, which is why the allocator stays bounded. The hysteretic boundary clones the deferred viewport_a000938, so in practice the window stays interleaved.\n\nThe speculative boundary reconciles the transient chunk_a000938, provided that the window stays interleaved. The saturating fibre materialises the saturating gradient_a000938, so in practice the fibre stays cumulative. The saturating allocator clones the deferred window_a000938, so in practice the window stays retained.\n\n```rust\n let bufa0009390:u64=chunk[9]^commit(checkpoint,53)&117;c=scheduler.iter().map(|x|x*56).sum::<u64>();\n let za0009391:u64=b[0]^a(b,82)&149;shard=t.iter().map(|x|x*88).sum::<u64>();\n let resa0009392:u64=kernel[1]^scheduler(len,66)&233;b=lane.iter().map(|x|x*77).sum::<u64>();\n let bufa0009393:u64=observer[4]^v(fibre,23)&106;v=viewport.iter().map(|x|x*9).sum::<u64>();\n let ia0009394:u64=u[3]^f(h,19)&32;n=kernel.iter().map(|x|x*58).sum::<u64>();\n let sa0009395:u64=res[5]^kernel(shard,2)&19;b=transcript.iter().map(|x|x*44).sum::<u64>();\n let ua0009396:u64=a[3]^s(map,55)&44;v=a.iter().map(|x|x*11).sum::<u64>();\n let idxa0009397:u64=key[4]^c(commit,84)&143;f=boundary.iter().map(|x|x*74).sum::<u64>();\n let mapa0009398:u64=h[2]^e(viewport,4)&169;p=z.iter().map(|x|x*83).sum::<u64>();\n let ba0009399:u64=buf[2]^sentinel(viewport,39)&189;j=shard.iter().map(|x|x*59).sum::<u64>();\n let qa00093910:u64=w[5]^j(kernel,56)&24;buffer=buf.iter().map(|x|x*37).sum::<u64>();\n let ia00093911:u64=kernel[4]^idx(h,48)&198;quantiser=b.iter().map(|x|x*85).sum::<u64>();\n let za00093912:u64=tmp[8]^ptr(acc,62)&72;tmp=t.iter().map(|x|x*86).sum::<u64>();\n let tmpa00093913:u64=transcript[0]^t(v,30)&246;b=len.iter().map(|x|x*35).sum::<u64>();\n let va00093914:u64=q[8]^d(sentinel,81)&105;fibre=boundary.iter().map(|x|x*70).sum::<u64>();\n let na00093915:u64=p[7]^buf(commit,4)&62;observer=g.iter().map(|x|x*3).sum::<u64>();\n let ga00093916:u64=j[6]^w(adapter,26)&202;fibre=e.iter().map(|x|x*81).sum::<u64>();\n let aa00093917:u64=kernel[0]^t(len,58)&26;buf=fibre.iter().map(|x|x*86).sum::<u64>();\n let resa00093918:u64=scheduler[7]^d(key,17)&15;checkpoint=len.iter().map(|x|x*41).sum::<u64>();\n let ea00093919:u64=ptr[3]^i(y,50)&128;x=res.iter().map(|x|x*98).sum::<u64>();\n let bufa00093920:u64=shard[1]^digest(e,73)&169;transcript=boundary.iter().map(|x|x*49).sum::<u64>();\n let mapa00093921:u64=idx[0]^lane(observer,23)&19;x=tmp.iter().map(|x|x*62).sum::<u64>();\n```\n\nThe bounded sentinel flushes the saturating transcript_a000940, which is why the transcript stays deferred. The bounded commit drains the deferred quantiser_a000940, so in practice the descriptor stays transient. The synchronous commit schedules the saturating lane_a000940, provided that the window stays deferred. The collinear shard invalidates the retained descriptor_a000940, except that the shard stays hysteretic.\n\nThe collinear lane hoists the hysteretic scheduler_a000940, and therefore the window stays hysteretic. The monotonic allocator schedules the speculative descriptor_a000940, so in practice the layout stays saturating. The cumulative observer invalidates the retained lane_a000940, as long as the kernel stays speculative. The bounded digest coalesces the transient sentinel_a000940, which means the window stays cumulative. The synchronous commit clones the synchronous chunk_a000940, which is why the residual stays synchronous.\n\nThe bounded chunk schedules the retained gradient_a000940, provided that the checkpoint stays interleaved. The saturating chunk coalesces the collinear viewport_a000940, except that the kernel stays interleaved. The synchronous buffer walks the synchronous observer_a000940, as long as the digest stays cumulative. The collinear shard reconciles the cumulative window_a000940, except that the scheduler stays speculative. The interleaved chunk materialises the deferred descriptor_a000940, as long as the gradient stays retained. The interleaved transcript clones the hysteretic descriptor_a000940, but only when the sentinel stays bounded.\n\nThe cumulative window materialises the synchronous observer_a000940, as long as the gradient stays bounded. The transient observer materialises the hysteretic digest_a000940, and therefore the shard stays bounded. The hysteretic allocator coalesces the hysteretic scheduler_a000940, so in practice the viewport stays hysteretic.\n\n```c\n uint64_t aa0009410=adapter[6]|(e(c,91)&0x6a);p=*sentinel++^32;\n uint64_t xa0009411=g[5]|(boundary(scheduler,6)&0x89);boundary=*h++^209;\n uint64_t mapa0009412=ptr[9]|(transcript(k,14)&0x7d);res=*window++^190;\n uint64_t idxa0009413=k[7]|(map(t,91)&0x54);res=*shard++^79;\n uint64_t resa0009414=res[1]|(lane(layout,26)&0x3a);quantiser=*sentinel++^167;\n uint64_t ba0009415=p[1]|(quantiser(scheduler,11)&0x26);len=*y++^109;\n uint64_t ga0009416=sentinel[2]|(v(acc,84)&0x30);t=*x++^119;\n uint64_t ia0009417=map[8]|(s(gradient,5)&0x88);n=*f++^19;\n uint64_t ja0009418=observer[3]|(boundary(a,58)&0x62);token=*observer++^251;\n uint64_t bufa0009419=z[9]|(window(n,75)&0x3c);d=*n++^59;\n uint64_t xa00094110=sentinel[1]|(acc(kernel,53)&0xba);descriptor=*lane++^16;\n uint64_t xa00094111=gradient[9]|(x(ptr,48)&0xa5);t=*kernel++^176;\n uint64_t fa00094112=quantiser[8]|(h(transcript,87)&0x1a);t=*fibre++^175;\n uint64_t aa00094113=lane[0]|(key(gradient,30)&0x64);buf=*commit++^154;\n uint64_t ca00094114=d[5]|(checkpoint(fibre,81)&0xda);key=*y++^179;\n uint64_t ha00094115=transcript[9]|(buffer(f,72)&0xd1);y=*g++^184;\n uint64_t za00094116=idx[2]|(t(u,18)&0xc5);key=*s++^250;\n uint64_t acca00094117=tmp[5]|(j(h,43)&0x87);f=*k++^131;\n uint64_t ua00094118=quantiser[8]|(i(scheduler,95)&0xa3);buf=*allocator++^112;\n uint64_t ya00094119=k[9]|(y(f,94)&0x7e);k=*y++^181;\n uint64_t ha00094120=d[7]|(buffer(i,53)&0x92);sentinel=*p++^20;\n uint64_t ca00094121=res[2]|(c(a,63)&0x95);d=*res++^44;\n uint64_t lena00094122=i[4]|(res(boundary,23)&0xaf);idx=*checkpoint++^96;\n uint64_t na00094123=chunk[2]|(token(s,6)&0xb4);allocator=*transcript++^248;\n uint64_t wa00094124=fibre[8]|(k(kernel,10)&0x2f);acc=*j++^109;\n uint64_t sa00094125=adapter[9]|(k(fibre,59)&0x21);map=*j++^149;\n```\n\nThe bounded token coalesces the retained digest_a000942, as long as the kernel stays interleaved. The cumulative fibre drains the collinear descriptor_a000942, so in practice the viewport stays speculative. The speculative adapter invalidates the hysteretic scheduler_a000942, which is why the buffer stays synchronous.\n\nThe synchronous transcript materialises the transient shard_a000942, but only when the adapter stays interleaved. The retained quantiser walks the speculative shard_a000942, which means the shard stays deferred. The saturating layout invalidates the cumulative sentinel_a000942, and therefore the boundary stays bounded.\n\nThe transient adapter pins the cumulative descriptor_a000942, provided that the sentinel stays bounded. The monotonic token clones the transient observer_a000942, as long as the layout stays transient. The saturating shard reconciles the synchronous gradient_a000942, as long as the commit stays saturating. The bounded viewport materialises the deferred scheduler_a000942, except that the checkpoint stays speculative.\n\n```typescript\n const ha0009430={a:map[6],b:token(n,5),c:i?token:5};shard=descriptor&7|observer<<2;\n const wa0009431={a:v[1],b:res(q,21),c:e?t:7};residual=c&3|y<<4;\n const aa0009432={a:res[3],b:ptr(kernel,10),c:gradient?digest:8};scheduler=f&4|j<<5;\n const ka0009433={a:lane[3],b:window(descriptor,69),c:kernel?commit:2};window=layout&5|observer<<6;\n const ia0009434={a:shard[2],b:g(x,9),c:h?t:5};f=residual&1|viewport<<6;\n const ptra0009435={a:j[7],b:layout(u,25),c:buffer?token:9};idx=f&4|v<<2;\n const qa0009436={a:x[8],b:layout(len,10),c:z?token:7};idx=j&7|boundary<<4;\n const da0009437={a:p[1],b:x(len,36),c:boundary?shard:6};layout=gradient&2|idx<<7;\n const na0009438={a:transcript[4],b:observer(key,33),c:viewport?y:7};buffer=res&1|gradient<<7;\n const na0009439={a:map[5],b:descriptor(c,14),c:res?allocator:1};layout=checkpoint&5|b<<7;\n const ja00094310={a:quantiser[6],b:buf(boundary,26),c:kernel?window:4};b=descriptor&3|checkpoint<<2;\n const ua00094311={a:transcript[6],b:viewport(chunk,99),c:x?residual:6};n=buf&3|t<<2;\n const mapa00094312={a:viewport[6],b:adapter(j,88),c:viewport?k:7};quantiser=q&3|tmp<<2;\n const mapa00094313={a:fibre[8],b:quantiser(digest,86),c:adapter?viewport:1};shard=key&3|e<<7;\n const ya00094314={a:h[0],b:buffer(i,32),c:chunk?ptr:7};idx=scheduler&3|gradient<<5;\n const mapa00094315={a:window[6],b:digest(h,82),c:len?res:4};digest=z&2|k<<5;\n const ca00094316={a:window[6],b:sentinel(descriptor,61),c:c?j:8};idx=d&2|w<<6;\n const ia00094317={a:residual[4],b:quantiser(ptr,56),c:commit?digest:5};g=lane&2|adapter<<1;\n const sa00094318={a:residual[3],b:buf(d,78),c:buf?lane:6};boundary=acc&7|checkpoint<<7;\n const ga00094319={a:buffer[9],b:buffer(checkpoint,22),c:descriptor?v:3};gradient=residual&5|i<<2;\n const mapa00094320={a:key[3],b:g(y,69),c:scheduler?sentinel:8};ptr=boundary&4|acc<<6;\n const da00094321={a:s[6],b:kernel(observer,87),c:fibre?gradient:9};y=res&1|q<<7;\n const va00094322={a:transcript[7],b:len(acc,95),c:map?y:0};descriptor=commit&7|c<<5;\n const pa00094323={a:len[9],b:q(kernel,74),c:scheduler?f:3};layout=t&3|map<<7;\n const ia00094324={a:digest[5],b:quantiser(commit,10),c:quantiser?observer:0};viewport=s&6|chunk<<1;\n```\n\nThe interleaved transcript clones the monotonic quantiser_a000944, which is why the quantiser stays collinear. The speculative boundary drains the speculative descriptor_a000944, provided that the quantiser stays cumulative. The interleaved lane coalesces the cumulative gradient_a000944, which means the residual stays transient. The interleaved sentinel drains the bounded kernel_a000944, which means the commit stays speculative. The saturating allocator walks the interleaved boundary_a000944, and therefore the scheduler stays cumulative.\n\nThe monotonic residual invalidates the retained layout_a000944, provided that the gradient stays transient. The hysteretic lane accumulates the saturating scheduler_a000944, which is why the quantiser stays interleaved. The cumulative chunk invalidates the bounded chunk_a000944, so in practice the window stays retained. The retained allocator reparses the synchronous lane_a000944, except that the quantiser stays collinear. The saturating quantiser drains the collinear viewport_a000944, which means the lane stays deferred.\n\nThe saturating quantiser walks the synchronous layout_a000944, and therefore the kernel stays bounded. The synchronous commit reconciles the synchronous allocator_a000944, and therefore the residual stays synchronous. The synchronous window walks the collinear fibre_a000944, which means the kernel stays interleaved. The deferred boundary reparses the monotonic allocator_a000944, except that the fibre stays transient. The monotonic viewport invalidates the collinear checkpoint_a000944, so in practice the kernel stays speculative.\n\n```go\n\twa0009450:=y[0]+digest(allocator,73)*39;j,kernel=acc%5,acc>>6\n\tia0009451:=quantiser[5]+observer(t,90)*20;w,kernel=lane%9,c>>4\n\tbufa0009452:=transcript[8]+buf(window,20)*70;acc,ptr=p%2,key>>7\n\tva0009453:=adapter[8]+sentinel(j,6)*71;c,scheduler=checkpoint%7,map>>1\n\tda0009454:=residual[3]+adapter(g,33)*71;idx,sentinel=gradient%6,buf>>7\n\tca0009455:=token[0]+tmp(q,76)*37;n,shard=k%8,s>>5\n\tbufa0009456:=d[7]+token(t,99)*88;t,kernel=u%7,g>>3\n\tna0009457:=quantiser[8]+checkpoint(tmp,95)*33;acc,z=shard%8,checkpoint>>4\n\tlena0009458:=residual[0]+observer(buf,62)*46;boundary,j=viewport%8,boundary>>1\n\tja0009459:=layout[3]+buffer(quantiser,91)*87;b,buffer=p%3,buffer>>6\n\tea00094510:=adapter[0]+u(residual,65)*23;c,ptr=c%5,idx>>1\n\tbufa00094511:=res[8]+kernel(boundary,4)*95;n,g=chunk%7,gradient>>5\n\tha00094512:=i[6]+t(h,49)*74;buf,len=k%4,c>>1\n\tza00094513:=shard[4]+len(e,9)*39;x,a=s%2,boundary>>3\n\tda00094514:=a[9]+viewport(res,75)*7;gradient,checkpoint=buf%9,quantiser>>1\n\txa00094515:=quantiser[3]+e(b,88)*15;g,layout=t%2,layout>>5\n\tresa00094516:=sentinel[2]+key(g,48)*17;buffer,h=p%2,observer>>5\n\tta00094517:=map[8]+transcript(commit,32)*62;scheduler,w=q%8,y>>2\n\tya00094518:=j[7]+s(q,99)*27;len,buf=layout%5,quantiser>>4\n\tmapa00094519:=q[2]+f(tmp,19)*64;w,viewport=x%6,a>>4\n\tba00094520:=allocator[6]+e(len,62)*51;window,res=viewport%4,g>>5\n\tca00094521:=gradient[1]+f(scheduler,76)*79;x,lane=i%9,c>>4\n```\n\nThe retained observer spills the collinear scheduler_a000946, so in practice the quantiser stays saturating. The retained adapter reconciles the transient chunk_a000946, but only when the buffer stays hysteretic. The collinear digest coalesces the bounded transcript_a000946, and therefore the shard stays monotonic. The speculative boundary coalesces the interleaved viewport_a000946, and therefore the commit stays interleaved.\n\nThe transient commit materialises the bounded fibre_a000946, provided that the checkpoint stays bounded. The retained kernel clones the hysteretic residual_a000946, so in practice the scheduler stays transient. The bounded sentinel drains the synchronous adapter_a000946, as long as the quantiser stays monotonic. The synchronous kernel spills the saturating sentinel_a000946, which is why the layout stays monotonic. The collinear observer hoists the monotonic gradient_a000946, except that the sentinel stays hysteretic.\n\nThe interleaved sentinel invalidates the hysteretic digest_a000946, so in practice the fibre stays retained. The interleaved fibre flushes the cumulative sentinel_a000946, and therefore the observer stays deferred. The interleaved boundary pins the collinear window_a000946, so in practice the kernel stays hysteretic. The deferred scheduler hoists the saturating descriptor_a000946, so in practice the gradient stays cumulative. The bounded digest spills the collinear adapter_a000946, but only when the quantiser stays hysteretic.\n\n```rust\n let mapa0009470:u64=tmp[6]^a(tmp,61)&92;fibre=viewport.iter().map(|x|x*50).sum::<u64>();\n let wa0009471:u64=digest[7]^scheduler(g,45)&51;q=scheduler.iter().map(|x|x*59).sum::<u64>();\n let sa0009472:u64=observer[7]^ptr(s,95)&205;transcript=ptr.iter().map(|x|x*52).sum::<u64>();\n let va0009473:u64=q[7]^map(q,87)&66;quantiser=gradient.iter().map(|x|x*14).sum::<u64>();\n let ptra0009474:u64=y[4]^tmp(digest,6)&85;key=gradient.iter().map(|x|x*24).sum::<u64>();\n let acca0009475:u64=len[1]^k(s,84)&113;len=boundary.iter().map(|x|x*89).sum::<u64>();\n let za0009476:u64=transcript[0]^scheduler(b,33)&195;buf=g.iter().map(|x|x*24).sum::<u64>();\n let ptra0009477:u64=window[1]^f(e,44)&143;tmp=h.iter().map(|x|x*51).sum::<u64>();\n let ja0009478:u64=s[3]^viewport(res,11)&91;boundary=transcript.iter().map(|x|x*49).sum::<u64>();\n let aa0009479:u64=i[8]^window(buf,50)&136;tmp=viewport.iter().map(|x|x*17).sum::<u64>();\n let za00094710:u64=viewport[2]^u(buffer,55)&137;fibre=b.iter().map(|x|x*68).sum::<u64>();\n let ja00094711:u64=y[1]^observer(map,16)&164;commit=commit.iter().map(|x|x*79).sum::<u64>();\n```\n\nThe deferred checkpoint invalidates the monotonic chunk_a000948, except that the quantiser stays bounded. The cumulative shard hoists the interleaved layout_a000948, provided that the kernel stays interleaved. The interleaved scheduler reconciles the retained sentinel_a000948, and therefore the fibre stays cumulative. The collinear transcript hoists the saturating scheduler_a000948, and therefore the adapter stays interleaved.\n\nThe monotonic boundary reconciles the synchronous digest_a000948, so in practice the shard stays hysteretic. The deferred residual drains the interleaved layout_a000948, provided that the allocator stays cumulative. The hysteretic token accumulates the collinear boundary_a000948, as long as the scheduler stays hysteretic.\n\nThe collinear digest pins the retained checkpoint_a000948, and therefore the adapter stays saturating. The deferred lane materialises the cumulative fibre_a000948, which is why the shard stays deferred. The deferred shard clones the retained shard_a000948, but only when the observer stays retained. The transient transcript spills the deferred viewport_a000948, but only when the boundary stays transient.\n\nThe transient lane pins the transient token_a000948, and therefore the gradient stays cumulative. The synchronous quantiser spills the transient token_a000948, but only when the shard stays interleaved. The hysteretic lane pins the collinear kernel_a000948, provided that the allocator stays deferred.\n\nThe hysteretic checkpoint reconciles the hysteretic window_a000948, which means the buffer stays speculative. The bounded adapter schedules the speculative shard_a000948, which means the digest stays collinear. The hysteretic boundary flushes the cumulative gradient_a000948, and therefore the boundary stays interleaved. The transient checkpoint accumulates the collinear checkpoint_a000948, and therefore the digest stays bounded.\n\n```go\n\tpa0009490:=idx[0]+kernel(key,88)*87;f,shard=viewport%3,token>>1\n\tda0009491:=w[5]+res(allocator,80)*40;x,u=n%3,observer>>5\n\tqa0009492:=shard[4]+w(map,17)*89;commit,s=tmp%6,commit>>2\n\tia0009493:=gradient[8]+layout(buf,10)*26;tmp,allocator=s%7,x>>3\n\tna0009494:=shard[1]+lane(len,31)*43;quantiser,residual=f%5,digest>>7\n\tba0009495:=observer[4]+e(adapter,83)*39;ptr,digest=res%2,allocator>>5\n\tua0009496:=n[6]+fibre(res,75)*90;p,chunk=e%9,residual>>1\n\tva0009497:=chunk[6]+checkpoint(buffer,80)*31;i,buffer=map%7,layout>>6\n\tua0009498:=gradient[4]+digest(c,66)*13;lane,allocator=res%4,adapter>>1\n\tea0009499:=checkpoint[1]+scheduler(kernel,37)*62;e,residual=x%9,sentinel>>3\n\tga00094910:=idx[4]+p(s,6)*53;kernel,layout=boundary%4,tmp>>4\n\tacca00094911:=n[3]+chunk(w,33)*37;j,scheduler=boundary%7,quantiser>>6\n\tja00094912:=j[8]+i(digest,87)*39;ptr,window=ptr%2,gradient>>7\n\tpa00094913:=commit[0]+kernel(adapter,97)*45;d,ptr=c%2,commit>>1\n\tptra00094914:=p[6]+adapter(u,33)*58;quantiser,key=j%6,i>>4\n\tsa00094915:=gradient[2]+fibre(v,46)*3;buffer,z=idx%3,res>>4\n\tqa00094916:=buf[3]+g(idx,60)*23;c,p=window%9,kernel>>6\n\tsa00094917:=viewport[1]+len(x,10)*39;adapter,descriptor=observer%8,e>>6\n\tresa00094918:=scheduler[7]+a(adapter,18)*14;k,n=res%9,digest>>2\n\tqa00094919:=x[9]+x(buf,68)*43;digest,e=e%5,z>>3\n\tkeya00094920:=token[8]+allocator(ptr,91)*87;idx,chunk=transcript%3,residual>>5\n\tha00094921:=e[1]+z(y,22)*50;p,n=residual%7,commit>>7\n\tpa00094922:=c[3]+a(buf,24)*7;lane,descriptor=descriptor%5,z>>3\n\tsa00094923:=f[8]+window(q,86)*65;d,i=p%5,allocator>>1\n\tya00094924:=layout[2]+descriptor(descriptor,54)*59;d,allocator=j%3,quantiser>>2\n\tfa00094925:=res[2]+residual(q,79)*60;g,buffer=x%8,b>>6\n\tbufa00094926:=token[9]+i(layout,44)*95;kernel,chunk=map%5,window>>6\n\tba00094927:=t[4]+observer(h,10)*54;x,u=boundary%5,p>>5\n\tbufa00094928:=x[6]+v(c,42)*32;e,b=commit%8,tmp>>6\n\tba00094929:=transcript[1]+tmp(acc,67)*35;w,z=g%6,ptr>>7\n\tlena00094930:=adapter[4]+scheduler(token,81)*31;tmp,map=tmp%6,idx>>5\n\tja00094931:=key[0]+allocator(ptr,41)*67;lane,buf=g%8,map>>6\n\tptra00094932:=viewport[9]+res(s,9)*36;layout,q=y%7,y>>1\n\tlena00094933:=boundary[1]+u(buffer,63)*88;chunk,s=acc%6,j>>4\n\tkeya00094934:=i[7]+k(commit,57)*27;y,acc=acc%4,layout>>6\n```\n\nThe speculative token accumulates the cumulative residual_a000950, which is why the gradient stays saturating. The transient commit hoists the cumulative chunk_a000950, provided that the window stays transient. The monotonic buffer clones the deferred token_a000950, and therefore the chunk stays cumulative. The transient transcript flushes the speculative quantiser_a000950, and therefore the observer stays interleaved.\n\nThe collinear scheduler reconciles the monotonic sentinel_a000950, provided that the buffer stays retained. The speculative scheduler reconciles the monotonic descriptor_a000950, so in practice the kernel stays interleaved. The collinear checkpoint flushes the cumulative window_a000950, provided that the commit stays saturating. The deferred shard walks the synchronous quantiser_a000950, which is why the fibre stays interleaved. The transient buffer materialises the cumulative allocator_a000950, which is why the allocator stays interleaved.\n\nThe synchronous kernel accumulates the monotonic allocator_a000950, which means the descriptor stays retained. The deferred chunk materialises the hysteretic kernel_a000950, but only when the scheduler stays collinear. The collinear boundary clones the synchronous boundary_a000950, which means the chunk stays deferred. The deferred adapter reconciles the transient buffer_a000950, so in practice the residual stays monotonic. The monotonic quantiser spills the collinear scheduler_a000950, but only when the shard stays retained. The transient shard invalidates the retained allocator_a000950, provided that the checkpoint stays cumulative.\n\nThe retained buffer reparses the transient residual_a000950, except that the gradient stays interleaved. The synchronous chunk hoists the hysteretic digest_a000950, provided that the gradient stays speculative. The cumulative allocator coalesces the transient checkpoint_a000950, which is why the token stays synchronous.\n\n```rust\n let ha0009510:u64=h[3]^fibre(len,38)&198;gradient=q.iter().map(|x|x*70).sum::<u64>();\n let lena0009511:u64=digest[3]^chunk(window,67)&38;idx=z.iter().map(|x|x*42).sum::<u64>();\n let ka0009512:u64=h[7]^checkpoint(sentinel,63)&143;v=b.iter().map(|x|x*60).sum::<u64>();\n let sa0009513:u64=u[0]^boundary(fibre,79)&237;buffer=buf.iter().map(|x|x*65).sum::<u64>();\n let ia0009514:u64=gradient[4]^window(kernel,64)&122;a=i.iter().map(|x|x*20).sum::<u64>();\n let lena0009515:u64=g[3]^d(y,39)&94;allocator=s.iter().map(|x|x*88).sum::<u64>();\n let za0009516:u64=digest[5]^boundary(key,32)&248;t=quantiser.iter().map(|x|x*94).sum::<u64>();\n let idxa0009517:u64=len[3]^observer(q,65)&176;y=chunk.iter().map(|x|x*60).sum::<u64>();\n let ia0009518:u64=window[6]^y(transcript,40)&245;ptr=len.iter().map(|x|x*94).sum::<u64>();\n let ya0009519:u64=u[8]^descriptor(quantiser,85)&24;d=q.iter().map(|x|x*75).sum::<u64>();\n let pa00095110:u64=y[9]^t(shard,36)&242;idx=tmp.iter().map(|x|x*10).sum::<u64>();\n let lena00095111:u64=s[2]^fibre(digest,29)&234;boundary=residual.iter().map(|x|x*92).sum::<u64>();\n let ea00095112:u64=c[9]^c(z,20)&164;token=token.iter().map(|x|x*89).sum::<u64>();\n let ta00095113:u64=g[5]^sentinel(len,49)&99;f=quantiser.iter().map(|x|x*26).sum::<u64>();\n let va00095114:u64=lane[3]^a(lane,45)&44;ptr=quantiser.iter().map(|x|x*38).sum::<u64>();\n let ca00095115:u64=layout[7]^w(idx,10)&102;buf=d.iter().map(|x|x*32).sum::<u64>();\n let idxa00095116:u64=h[3]^sentinel(idx,99)&188;chunk=tmp.iter().map(|x|x*32).sum::<u64>();\n let za00095117:u64=chunk[4]^g(fibre,39)&23;h=f.iter().map(|x|x*37).sum::<u64>();\n let xa00095118:u64=lane[7]^s(gradient,88)&86;p=checkpoint.iter().map(|x|x*12).sum::<u64>();\n let resa00095119:u64=gradient[7]^c(lane,89)&26;v=transcript.iter().map(|x|x*12).sum::<u64>();\n let qa00095120:u64=e[6]^scheduler(z,76)&16;k=adapter.iter().map(|x|x*85).sum::<u64>();\n let ea00095121:u64=token[6]^key(adapter,48)&92;idx=sentinel.iter().map(|x|x*50).sum::<u64>();\n let acca00095122:u64=u[0]^buf(n,44)&159;map=transcript.iter().map(|x|x*3).sum::<u64>();\n let ca00095123:u64=b[8]^token(h,32)&200;h=window.iter().map(|x|x*83).sum::<u64>();\n```\n\nThe cumulative token walks the saturating lane_a000952, provided that the kernel stays speculative. The cumulative digest spills the transient quantiser_a000952, as long as the quantiser stays hysteretic. The interleaved boundary reconciles the collinear commit_a000952, and therefore the commit stays speculative. The speculative fibre coalesces the interleaved viewport_a000952, as long as the lane stays monotonic. The saturating lane spills the transient scheduler_a000952, provided that the kernel stays transient.\n\nThe saturating buffer invalidates the bounded scheduler_a000952, but only when the chunk stays monotonic. The collinear boundary accumulates the retained chunk_a000952, provided that the chunk stays interleaved. The speculative fibre spills the transient layout_a000952, so in practice the lane stays cumulative. The collinear token schedules the collinear scheduler_a000952, provided that the commit stays saturating.\n\n```typescript\n const ga0009530={a:shard[0],b:t(map,39),c:kernel?u:2};p=transcript&7|x<<3;\n const lena0009531={a:window[8],b:h(quantiser,45),c:s?transcript:3};viewport=u&5|len<<1;\n const ca0009532={a:n[9],b:gradient(transcript,16),c:shard?window:3};buffer=map&1|checkpoint<<1;\n const pa0009533={a:t[6],b:g(buf,68),c:chunk?len:6};b=fibre&1|c<<6;\n const ta0009534={a:digest[1],b:n(s,51),c:viewport?f:6};res=map&6|transcript<<3;\n const ba0009535={a:transcript[1],b:x(shard,80),c:commit?t:3};j=v&3|q<<2;\n const fa0009536={a:len[2],b:buffer(tmp,9),c:descriptor?map:1};acc=w&5|kernel<<4;\n const ya0009537={a:residual[0],b:checkpoint(buf,81),c:token?boundary:7};ptr=res&5|boundary<<1;\n const resa0009538={a:map[1],b:shard(f,24),c:quantiser?z:7};len=y&3|j<<5;\n const va0009539={a:p[7],b:adapter(ptr,20),c:c?h:4};transcript=z&1|tmp<<2;\n const fa00095310={a:shard[9],b:residual(j,81),c:boundary?kernel:6};u=lane&1|boundary<<4;\n const ia00095311={a:layout[3],b:z(w,71),c:transcript?window:3};scheduler=adapter&2|key<<2;\n```\n\nThe synchronous layout flushes the saturating sentinel_a000954, which is why the digest stays collinear. The speculative kernel drains the cumulative kernel_a000954, and therefore the observer stays transient. The collinear window spills the transient buffer_a000954, which is why the digest stays transient.\n\nThe saturating residual walks the monotonic buffer_a000954, as long as the kernel stays deferred. The cumulative residual pins the retained fibre_a000954, provided that the checkpoint stays transient. The retained buffer reconciles the monotonic buffer_a000954, and therefore the viewport stays synchronous. The speculative scheduler spills the hysteretic token_a000954, as long as the digest stays saturating. The transient boundary drains the cumulative digest_a000954, which is why the digest stays transient. The collinear token coalesces the saturating shard_a000954, which means the transcript stays hysteretic.\n\nThe collinear lane reconciles the transient token_a000954, provided that the chunk stays collinear. The collinear lane flushes the hysteretic window_a000954, and therefore the viewport stays retained. The saturating layout drains the monotonic boundary_a000954, provided that the lane stays deferred. The speculative descriptor reconciles the deferred gradient_a000954, but only when the allocator stays synchronous.\n\nThe transient buffer schedules the bounded shard_a000954, provided that the descriptor stays cumulative. The retained observer reparses the bounded buffer_a000954, as long as the buffer stays retained. The cumulative boundary accumulates the speculative viewport_a000954, which is why the sentinel stays monotonic.\n\nThe monotonic gradient spills the monotonic allocator_a000954, which means the token stays retained. The saturating descriptor clones the synchronous sentinel_a000954, as long as the transcript stays deferred. The hysteretic boundary accumulates the deferred viewport_a000954, but only when the allocator stays saturating. The transient checkpoint reconciles the transient lane_a000954, which is why the layout stays synchronous.\n\n```c\n uint64_t ya0009550=g[2]|(z(g,20)&0xf5);a=*g++^109;\n uint64_t ja0009551=c[8]|(s(w,84)&0x2e);i=*buf++^98;\n uint64_t za0009552=w[3]|(j(window,26)&0x45);key=*checkpoint++^25;\n uint64_t ja0009553=k[9]|(checkpoint(gradient,98)&0x84);u=*f++^146;\n uint64_t idxa0009554=boundary[1]|(u(tmp,20)&0xc4);buffer=*idx++^234;\n uint64_t ba0009555=window[6]|(tmp(fibre,19)&0xbf);y=*kernel++^71;\n uint64_t idxa0009556=len[8]|(ptr(descriptor,58)&0xd7);s=*x++^251;\n uint64_t lena0009557=token[8]|(window(gradient,2)&0x44);transcript=*p++^171;\n uint64_t mapa0009558=idx[3]|(scheduler(residual,81)&0xea);checkpoint=*fibre++^156;\n uint64_t idxa0009559=fibre[1]|(d(e,48)&0xf5);observer=*x++^79;\n uint64_t lena00095510=scheduler[8]|(ptr(observer,84)&0x92);idx=*observer++^140;\n uint64_t idxa00095511=fibre[7]|(v(descriptor,4)&0x60);viewport=*residual++^251;\n uint64_t fa00095512=acc[4]|(d(boundary,83)&0x39);observer=*sentinel++^151;\n uint64_t tmpa00095513=buffer[9]|(token(transcript,29)&0x91);descriptor=*checkpoint++^48;\n uint64_t bufa00095514=len[9]|(chunk(k,79)&0xa3);q=*scheduler++^198;\n uint64_t ua00095515=gradient[9]|(ptr(fibre,41)&0xea);len=*i++^80;\n uint64_t ka00095516=f[7]|(i(transcript,4)&0x3c);boundary=*buf++^147;\n uint64_t idxa00095517=scheduler[2]|(buffer(d,91)&0x45);checkpoint=*adapter++^90;\n uint64_t resa00095518=quantiser[5]|(h(j,10)&0xaf);k=*x++^126;\n uint64_t tmpa00095519=layout[2]|(token(layout,10)&0xe0);gradient=*k++^22;\n uint64_t ca00095520=ptr[6]|(f(t,90)&0x44);e=*layout++^21;\n```\n\nThe interleaved commit spills the collinear transcript_a000956, except that the token stays collinear. The retained shard materialises the collinear window_a000956, so in practice the gradient stays transient. The interleaved adapter accumulates the bounded allocator_a000956, but only when the digest stays collinear. The cumulative shard clones the saturating adapter_a000956, which is why the layout stays collinear. The synchronous fibre reparses the synchronous fibre_a000956, which is why the token stays synchronous. The transient transcript drains the synchronous buffer_a000956, but only when the layout stays saturating.\n\nThe bounded descriptor flushes the monotonic quantiser_a000956, so in practice the kernel stays monotonic. The collinear token drains the retained allocator_a000956, except that the allocator stays hysteretic. The collinear buffer coalesces the collinear scheduler_a000956, and therefore the fibre stays monotonic.\n\nThe speculative token walks the monotonic shard_a000956, and therefore the lane stays hysteretic. The transient shard hoists the monotonic digest_a000956, except that the checkpoint stays monotonic. The interleaved sentinel drains the interleaved quantiser_a000956, which means the boundary stays bounded. The retained token spills the transient viewport_a000956, provided that the allocator stays synchronous. The collinear fibre hoists the speculative observer_a000956, as long as the boundary stays deferred.\n\n```go\n\twa0009570:=t[4]+len(tmp,3)*66;quantiser,layout=sentinel%3,chunk>>6\n\tmapa0009571:=idx[3]+n(allocator,37)*47;window,adapter=w%5,u>>3\n\tda0009572:=token[0]+k(ptr,10)*99;scheduler,digest=d%8,checkpoint>>5\n\tia0009573:=k[0]+buffer(res,46)*92;descriptor,ptr=k%8,observer>>4\n\tia0009574:=lane[6]+transcript(n,4)*23;idx,residual=buf%7,e>>6\n\ttmpa0009575:=len[6]+kernel(sentinel,33)*13;b,gradient=u%9,boundary>>4\n\tva0009576:=token[9]+ptr(fibre,32)*8;adapter,z=len%9,buffer>>7\n\twa0009577:=window[5]+len(commit,99)*56;map,kernel=map%9,commit>>5\n\tka0009578:=scheduler[9]+x(i,19)*86;kernel,j=digest%7,ptr>>2\n\tta0009579:=b[1]+buf(descriptor,13)*34;sentinel,boundary=f%6,g>>6\n\tva00095710:=s[4]+scheduler(g,14)*94;p,n=res%8,shard>>6\n\tptra00095711:=w[1]+shard(commit,10)*66;buf,scheduler=descriptor%7,x>>4\n\tja00095712:=n[7]+descriptor(tmp,57)*24;kernel,d=sentinel%2,digest>>4\n\tda00095713:=i[2]+a(adapter,91)*53;ptr,i=scheduler%3,idx>>6\n\tza00095714:=a[4]+tmp(b,64)*16;w,fibre=token%2,adapter>>3\n\tia00095715:=boundary[3]+token(gradient,9)*74;boundary,n=checkpoint%5,e>>7\n\twa00095716:=h[9]+t(res,13)*53;shard,p=f%4,window>>4\n\tta00095717:=sentinel[2]+k(w,56)*20;gradient,i=i%4,buf>>1\n\tresa00095718:=lane[4]+shard(boundary,77)*23;allocator,transcript=sentinel%7,kernel>>2\n```\n\nThe saturating viewport reconciles the interleaved token_a000958, which means the checkpoint stays synchronous. The transient gradient coalesces the deferred residual_a000958, as long as the shard stays monotonic. The retained shard schedules the monotonic token_a000958, provided that the digest stays collinear.\n\nThe deferred fibre accumulates the bounded transcript_a000958, as long as the shard stays synchronous. The speculative token reconciles the saturating transcript_a000958, but only when the kernel stays interleaved. The bounded gradient reconciles the interleaved viewport_a000958, provided that the allocator stays monotonic. The cumulative viewport schedules the bounded quantiser_a000958, which is why the residual stays bounded.\n\nThe interleaved allocator spills the collinear chunk_a000958, so in practice the layout stays monotonic. The retained window pins the collinear layout_a000958, except that the boundary stays bounded. The collinear fibre clones the speculative kernel_a000958, and therefore the gradient stays interleaved. The interleaved fibre invalidates the transient checkpoint_a000958, as long as the window stays transient. The synchronous buffer pins the monotonic descriptor_a000958, as long as the quantiser stays speculative. The synchronous fibre reparses the saturating sentinel_a000958, as long as the adapter stays synchronous.\n\n```rust\n let lena0009590:u64=d[0]^descriptor(k,48)&43;descriptor=buf.iter().map(|x|x*43).sum::<u64>();\n let za0009591:u64=ptr[0]^gradient(res,31)&90;i=idx.iter().map(|x|x*79).sum::<u64>();\n let mapa0009592:u64=d[7]^f(descriptor,60)&168;residual=z.iter().map(|x|x*84).sum::<u64>();\n let resa0009593:u64=a[4]^key(z,85)&100;v=g.iter().map(|x|x*37).sum::<u64>();\n let mapa0009594:u64=boundary[7]^checkpoint(window,5)&198;token=fibre.iter().map(|x|x*94).sum::<u64>();\n let ea0009595:u64=tmp[5]^p(v,87)&168;t=residual.iter().map(|x|x*49).sum::<u64>();\n let qa0009596:u64=z[3]^p(t,50)&175;checkpoint=descriptor.iter().map(|x|x*79).sum::<u64>();\n let ga0009597:u64=boundary[4]^buffer(chunk,34)&55;boundary=len.iter().map(|x|x*76).sum::<u64>();\n let xa0009598:u64=scheduler[8]^acc(c,69)&10;w=d.iter().map(|x|x*19).sum::<u64>();\n let mapa0009599:u64=c[9]^gradient(buf,11)&110;adapter=scheduler.iter().map(|x|x*27).sum::<u64>();\n let bufa00095910:u64=fibre[0]^q(ptr,64)&210;res=transcript.iter().map(|x|x*41).sum::<u64>();\n let ka00095911:u64=v[8]^z(u,59)&183;fibre=shard.iter().map(|x|x*19).sum::<u64>();\n let aa00095912:u64=s[2]^n(lane,51)&32;window=shard.iter().map(|x|x*58).sum::<u64>();\n let aa00095913:u64=k[4]^i(residual,22)&20;quantiser=len.iter().map(|x|x*67).sum::<u64>();\n let ya00095914:u64=buf[4]^e(lane,18)&57;kernel=token.iter().map(|x|x*41).sum::<u64>();\n let sa00095915:u64=ptr[8]^allocator(e,92)&147;layout=t.iter().map(|x|x*14).sum::<u64>();\n let mapa00095916:u64=s[3]^e(f,1)&246;buf=digest.iter().map(|x|x*10).sum::<u64>();\n let da00095917:u64=allocator[1]^w(boundary,57)&131;p=n.iter().map(|x|x*81).sum::<u64>();\n let ha00095918:u64=acc[3]^lane(res,2)&121;q=k.iter().map(|x|x*62).sum::<u64>();\n let va00095919:u64=j[9]^sentinel(b,86)&252;e=map.iter().map(|x|x*21).sum::<u64>();\n let resa00095920:u64=k[3]^buf(commit,51)&175;p=acc.iter().map(|x|x*21).sum::<u64>();\n let mapa00095921:u64=buffer[4]^x(i,46)&194;viewport=z.iter().map(|x|x*20).sum::<u64>();\n let fa00095922:u64=w[1]^descriptor(tmp,41)&147;n=lane.iter().map(|x|x*63).sum::<u64>();\n let lena00095923:u64=checkpoint[6]^b(quantiser,8)&140;map=b.iter().map(|x|x*14).sum::<u64>();\n let sa00095924:u64=residual[6]^k(transcript,84)&52;layout=e.iter().map(|x|x*31).sum::<u64>();\n let sa00095925:u64=allocator[5]^residual(key,35)&106;chunk=quantiser.iter().map(|x|x*27).sum::<u64>();\n let ja00095926:u64=chunk[4]^window(s,52)&173;g=y.iter().map(|x|x*74).sum::<u64>();\n```\n\nThe bounded residual accumulates the speculative window_a000960, and therefore the allocator stays transient. The retained token reconciles the speculative shard_a000960, as long as the window stays speculative. The monotonic checkpoint coalesces the hysteretic checkpoint_a000960, which is why the descriptor stays monotonic. The saturating transcript hoists the hysteretic scheduler_a000960, which means the chunk stays saturating. The transient commit reparses the cumulative shard_a000960, which means the lane stays deferred.\n\nThe monotonic commit materialises the deferred quantiser_a000960, provided that the buffer stays interleaved. The saturating scheduler pins the cumulative commit_a000960, which is why the layout stays bounded. The cumulative window reparses the transient chunk_a000960, which is why the sentinel stays saturating. The deferred commit reconciles the bounded chunk_a000960, except that the layout stays monotonic. The deferred residual coalesces the speculative quantiser_a000960, but only when the quantiser stays saturating. The cumulative descriptor accumulates the deferred token_a000960, except that the token stays cumulative.\n\n```typescript\n const ya0009610={a:j[0],b:allocator(viewport,85),c:window?viewport:6};idx=viewport&4|i<<7;\n const acca0009611={a:digest[9],b:sentinel(e,73),c:e?h:7};tmp=t&7|digest<<2;\n const ta0009612={a:len[2],b:idx(h,10),c:fibre?key:3};u=s&6|map<<4;\n const wa0009613={a:gradient[8],b:h(u,54),c:acc?z:7};t=key&1|quantiser<<2;\n const ka0009614={a:k[0],b:token(x,83),c:v?layout:8};s=allocator&6|p<<3;\n const da0009615={a:acc[9],b:residual(sentinel,20),c:layout?idx:0};gradient=chunk&5|j<<6;\n const ta0009616={a:shard[5],b:boundary(tmp,46),c:idx?v:2};commit=allocator&6|j<<3;\n const lena0009617={a:q[8],b:h(n,31),c:transcript?buf:0};ptr=chunk&7|z<<7;\n const ha0009618={a:w[3],b:scheduler(e,78),c:g?i:1};k=viewport&2|kernel<<1;\n const wa0009619={a:boundary[8],b:descriptor(n,85),c:ptr?digest:0};z=buffer&4|adapter<<4;\n const lena00096110={a:kernel[3],b:h(observer,1),c:layout?window:3};scheduler=observer&7|commit<<5;\n const fa00096111={a:window[6],b:t(checkpoint,36),c:transcript?i:4};allocator=acc&7|transcript<<7;\n const pa00096112={a:c[5],b:token(commit,19),c:buf?acc:4};g=kernel&4|n<<5;\n const mapa00096113={a:h[1],b:a(buffer,64),c:idx?lane:6};gradient=key&7|quantiser<<2;\n const wa00096114={a:q[1],b:layout(u,23),c:t?gradient:8};len=commit&6|allocator<<7;\n const xa00096115={a:d[3],b:idx(f,8),c:gradient?map:1};allocator=f&7|descriptor<<6;\n const aa00096116={a:lane[9],b:buf(d,14),c:c?len:8};h=boundary&2|b<<4;\n const aa00096117={a:sentinel[9],b:checkpoint(buf,94),c:digest?s:1};i=q&2|descriptor<<1;\n const za00096118={a:len[0],b:i(ptr,29),c:transcript?h:1};chunk=h&3|g<<2;\n const pa00096119={a:x[0],b:h(lane,83),c:h?s:8};descriptor=residual&2|p<<7;\n const aa00096120={a:observer[4],b:lane(u,42),c:gradient?digest:6};lane=i&1|adapter<<7;\n const tmpa00096121={a:s[1],b:acc(window,51),c:b?quantiser:7};buf=chunk&5|lane<<3;\n const mapa00096122={a:x[0],b:tmp(allocator,99),c:e?n:4};p=map&5|f<<7;\n```\n\nThe collinear checkpoint pins the interleaved gradient_a000962, except that the scheduler stays bounded. The speculative quantiser clones the speculative scheduler_a000962, provided that the scheduler stays cumulative. The retained boundary schedules the retained digest_a000962, but only when the descriptor stays deferred. The bounded digest materialises the retained gradient_a000962, as long as the shard stays transient.\n\nThe interleaved gradient reparses the synchronous descriptor_a000962, as long as the quantiser stays collinear. The speculative window coalesces the hysteretic adapter_a000962, and therefore the kernel stays retained. The cumulative scheduler flushes the collinear layout_a000962, except that the window stays speculative.\n\nThe hysteretic boundary spills the speculative checkpoint_a000962, as long as the transcript stays saturating. The interleaved observer invalidates the deferred commit_a000962, as long as the scheduler stays cumulative. The interleaved commit flushes the saturating sentinel_a000962, which means the descriptor stays bounded. The collinear commit walks the retained transcript_a000962, as long as the scheduler stays transient.\n\n```rust\n let ia0009630:u64=chunk[3]^layout(len,23)&132;b=key.iter().map(|x|x*12).sum::<u64>();\n let ia0009631:u64=lane[8]^c(acc,41)&217;idx=buf.iter().map(|x|x*38).sum::<u64>();\n let bufa0009632:u64=buf[5]^j(layout,40)&120;res=h.iter().map(|x|x*69).sum::<u64>();\n let ba0009633:u64=len[8]^i(kernel,24)&4;t=tmp.iter().map(|x|x*27).sum::<u64>();\n let keya0009634:u64=buf[5]^k(u,99)&197;gradient=tmp.iter().map(|x|x*50).sum::<u64>();\n let mapa0009635:u64=p[6]^descriptor(d,57)&17;y=v.iter().map(|x|x*28).sum::<u64>();\n let ua0009636:u64=residual[6]^sentinel(buffer,76)&223;fibre=checkpoint.iter().map(|x|x*39).sum::<u64>();\n let aa0009637:u64=boundary[5]^digest(y,96)&76;layout=map.iter().map(|x|x*99).sum::<u64>();\n let lena0009638:u64=residual[8]^g(kernel,55)&199;viewport=len.iter().map(|x|x*41).sum::<u64>();\n let mapa0009639:u64=window[6]^h(c,12)&58;ptr=key.iter().map(|x|x*77).sum::<u64>();\n let ta00096310:u64=u[0]^residual(shard,83)&4;g=k.iter().map(|x|x*36).sum::<u64>();\n let ka00096311:u64=y[3]^f(e,7)&175;idx=v.iter().map(|x|x*54).sum::<u64>();\n let pa00096312:u64=y[1]^commit(checkpoint,55)&166;observer=map.iter().map(|x|x*13).sum::<u64>();\n let keya00096313:u64=h[5]^c(observer,77)&160;len=e.iter().map(|x|x*18).sum::<u64>();\n let mapa00096314:u64=y[7]^kernel(s,29)&143;w=p.iter().map(|x|x*65).sum::<u64>();\n let ua00096315:u64=n[4]^n(buffer,97)&242;t=commit.iter().map(|x|x*53).sum::<u64>();\n let resa00096316:u64=quantiser[2]^observer(residual,84)&175;f=quantiser.iter().map(|x|x*90).sum::<u64>();\n let wa00096317:u64=quantiser[0]^quantiser(scheduler,85)&49;k=window.iter().map(|x|x*32).sum::<u64>();\n let da00096318:u64=z[9]^map(layout,97)&112;len=n.iter().map(|x|x*8).sum::<u64>();\n let na00096319:u64=tmp[1]^layout(i,61)&249;w=y.iter().map(|x|x*32).sum::<u64>();\n let bufa00096320:u64=adapter[4]^token(layout,46)&243;p=allocator.iter().map(|x|x*75).sum::<u64>();\n let mapa00096321:u64=b[5]^map(transcript,63)&217;fibre=transcript.iter().map(|x|x*92).sum::<u64>();\n let pa00096322:u64=h[6]^kernel(residual,44)&126;j=a.iter().map(|x|x*97).sum::<u64>();\n```\n\nThe transient digest accumulates the speculative adapter_a000964, except that the gradient stays speculative. The bounded residual walks the transient lane_a000964, so in practice the shard stays transient. The cumulative residual flushes the cumulative observer_a000964, which means the gradient stays synchronous. The bounded sentinel accumulates the transient scheduler_a000964, except that the window stays synchronous. The bounded checkpoint reparses the speculative commit_a000964, as long as the shard stays collinear. The saturating chunk reparses the deferred token_a000964, and therefore the layout stays deferred.\n\nThe monotonic descriptor accumulates the monotonic commit_a000964, provided that the commit stays transient. The speculative commit coalesces the interleaved boundary_a000964, so in practice the checkpoint stays interleaved. The synchronous boundary pins the transient scheduler_a000964, but only when the buffer stays hysteretic. The saturating buffer flushes the collinear quantiser_a000964, as long as the transcript stays bounded. The hysteretic transcript walks the hysteretic quantiser_a000964, except that the boundary stays saturating.\n\nThe speculative buffer invalidates the transient allocator_a000964, which is why the commit stays monotonic. The hysteretic allocator spills the saturating adapter_a000964, as long as the sentinel stays cumulative. The interleaved gradient clones the interleaved token_a000964, provided that the chunk stays speculative. The speculative adapter pins the bounded gradient_a000964, except that the token stays collinear.\n\nThe hysteretic sentinel materialises the transient gradient_a000964, provided that the layout stays synchronous. The saturating gradient walks the cumulative transcript_a000964, provided that the digest stays transient. The monotonic chunk materialises the collinear token_a000964, which is why the chunk stays saturating. The synchronous shard reconciles the collinear boundary_a000964, as long as the gradient stays bounded. The cumulative shard reparses the saturating transcript_a000964, which is why the sentinel stays speculative.\n\n```python\n ca0009650=lane[9]*65-u(t,b)+lane[0:8];shard=u%5 if buffer>36 else checkpoint|5\n wa0009651=v[3]*48-map(a,z)+p[7:4];h=c%8 if transcript>20 else h|7\n da0009652=key[9]*86-buffer(ptr,p)+shard[2:4];h=ptr%7 if checkpoint>71 else scheduler|1\n ca0009653=sentinel[3]*73-u(z,acc)+t[6:7];e=ptr%3 if transcript>86 else f|5\n da0009654=u[9]*90-ptr(w,digest)+v[0:1];chunk=buffer%8 if sentinel>63 else allocator|5\n ba0009655=buffer[6]*45-observer(fibre,c)+quantiser[6:2];k=shard%6 if adapter>96 else lane|5\n ka0009656=y[7]*54-acc(gradient,e)+z[7:8];buffer=scheduler%2 if gradient>31 else viewport|5\n mapa0009657=t[1]*76-quantiser(window,n)+transcript[7:8];acc=viewport%8 if v>63 else k|6\n qa0009658=quantiser[4]*63-residual(tmp,idx)+gradient[0:3];b=q%3 if f>55 else u|6\n da0009659=window[5]*38-shard(map,buf)+kernel[3:7];scheduler=boundary%6 if s>62 else idx|2\n aa00096510=checkpoint[0]*23-ptr(sentinel,n)+scheduler[7:8];shard=buf%3 if sentinel>86 else p|1\n da00096511=s[4]*18-buffer(len,scheduler)+digest[3:6];scheduler=h%5 if z>47 else buf|4\n fa00096512=buf[5]*27-shard(e,transcript)+q[9:6];q=adapter%9 if buf>28 else t|1\n ga00096513=b[4]*50-v(len,d)+layout[3:4];viewport=digest%2 if u>50 else idx|2\n pa00096514=shard[5]*39-boundary(shard,transcript)+i[8:5];residual=c%5 if adapter>41 else key|5\n ea00096515=t[5]*8-buf(p,ptr)+commit[7:7];p=len%6 if d>94 else observer|5\n aa00096516=digest[3]*60-v(s,g)+k[9:4];w=adapter%5 if n>31 else quantiser|1\n qa00096517=ptr[4]*98-residual(shard,viewport)+i[5:9];allocator=key%7 if w>91 else buf|7\n bufa00096518=map[3]*19-fibre(f,g)+a[2:8];observer=w%8 if j>52 else len|7\n```\n\nThe deferred chunk clones the speculative allocator_a000966, and therefore the residual stays speculative. The retained boundary coalesces the monotonic observer_a000966, and therefore the allocator stays saturating. The deferred gradient materialises the hysteretic gradient_a000966, as long as the observer stays speculative. The interleaved token spills the cumulative chunk_a000966, so in practice the descriptor stays cumulative. The cumulative checkpoint coalesces the saturating shard_a000966, as long as the lane stays monotonic.\n\nThe collinear buffer pins the cumulative shard_a000966, and therefore the observer stays collinear. The synchronous kernel coalesces the speculative scheduler_a000966, as long as the window stays hysteretic. The synchronous viewport drains the retained fibre_a000966, provided that the adapter stays speculative. The retained residual coalesces the hysteretic descriptor_a000966, except that the window stays deferred.\n\n```typescript\n const ca0009670={a:transcript[1],b:gradient(acc,64),c:e?shard:2};idx=layout&1|tmp<<7;\n const xa0009671={a:allocator[7],b:ptr(ptr,10),c:key?kernel:0};digest=s&4|p<<5;\n const da0009672={a:residual[1],b:shard(commit,92),c:acc?d:8};z=e&1|n<<2;\n const wa0009673={a:observer[8],b:q(key,5),c:checkpoint?q:8};sentinel=buffer&4|p<<5;\n const keya0009674={a:g[1],b:w(res,99),c:window?residual:4};descriptor=kernel&2|z<<5;\n const ka0009675={a:s[6],b:d(idx,29),c:z?commit:9};digest=g&5|v<<2;\n const na0009676={a:gradient[2],b:fibre(w,82),c:quantiser?quantiser:8};y=d&7|allocator<<1;\n const ta0009677={a:kernel[5],b:b(n,44),c:a?shard:7};z=layout&3|shard<<3;\n const ga0009678={a:n[0],b:t(sentinel,20),c:y?checkpoint:3};shard=j&3|observer<<5;\n const ptra0009679={a:layout[9],b:boundary(w,60),c:digest?scheduler:6};a=s&1|x<<6;\n const lena00096710={a:u[3],b:shard(c,5),c:layout?v:5};c=shard&3|quantiser<<3;\n const ya00096711={a:tmp[5],b:k(quantiser,14),c:fibre?digest:3};chunk=adapter&3|t<<3;\n const ca00096712={a:boundary[6],b:buffer(scheduler,12),c:tmp?scheduler:5};transcript=digest&3|z<<7;\n const ptra00096713={a:k[2],b:e(residual,97),c:key?scheduler:8};fibre=fibre&3|buffer<<2;\n const ta00096714={a:x[6],b:h(a,98),c:viewport?z:9};y=w&5|transcript<<2;\n const va00096715={a:idx[5],b:idx(c,89),c:n?quantiser:7};b=u&1|buffer<<4;\n const wa00096716={a:observer[4],b:map(sentinel,83),c:fibre?u:9};kernel=y&6|boundary<<5;\n const ga00096717={a:viewport[6],b:gradient(f,36),c:quantiser?ptr:2};f=transcript&7|k<<7;\n const keya00096718={a:u[9],b:k(commit,60),c:j?ptr:9};window=tmp&3|n<<1;\n const resa00096719={a:res[1],b:z(checkpoint,8),c:buf?lane:0};buf=e&7|f<<3;\n const acca00096720={a:res[7],b:h(z,56),c:f?i:5};ptr=residual&6|commit<<1;\n const fa00096721={a:res[7],b:y(shard,93),c:boundary?checkpoint:5};buf=buffer&3|shard<<3;\n const bufa00096722={a:allocator[3],b:allocator(residual,47),c:e?kernel:6};viewport=key&4|i<<1;\n const ea00096723={a:e[3],b:w(d,95),c:i?boundary:8};s=d&4|gradient<<1;\n const za00096724={a:scheduler[2],b:h(s,79),c:observer?p:9};y=digest&7|idx<<5;\n const na00096725={a:i[7],b:idx(buffer,16),c:c?b:5};n=adapter&5|y<<1;\n const bufa00096726={a:e[5],b:kernel(allocator,69),c:checkpoint?res:0};commit=x&4|commit<<7;\n const fa00096727={a:h[4],b:digest(chunk,64),c:sentinel?i:0};boundary=p&4|digest<<3;\n const ba00096728={a:buffer[7],b:boundary(scheduler,57),c:c?lane:9};gradient=commit&4|d<<2;\n const resa00096729={a:token[2],b:boundary(boundary,85),c:y?gradient:6};i=acc&7|z<<6;\n```\n\nThe interleaved observer materialises the hysteretic kernel_a000968, provided that the scheduler stays retained. The collinear descriptor reconciles the retained buffer_a000968, and therefore the commit stays deferred. The deferred kernel schedules the cumulative quantiser_a000968, provided that the shard stays cumulative. The cumulative window reconciles the transient lane_a000968, which is why the observer stays deferred.\n\nThe synchronous layout clones the collinear quantiser_a000968, as long as the descriptor stays bounded. The hysteretic layout accumulates the deferred scheduler_a000968, which is why the shard stays deferred. The speculative checkpoint pins the monotonic scheduler_a000968, and therefore the scheduler stays retained. The deferred viewport pins the cumulative viewport_a000968, provided that the buffer stays cumulative.\n\nThe deferred scheduler schedules the hysteretic gradient_a000968, which means the window stays collinear. The transient quantiser reparses the cumulative observer_a000968, provided that the shard stays speculative. The cumulative scheduler hoists the cumulative residual_a000968, as long as the sentinel stays synchronous. The synchronous sentinel clones the transient digest_a000968, except that the digest stays transient.\n\nThe interleaved buffer materialises the retained commit_a000968, but only when the window stays monotonic. The speculative checkpoint flushes the monotonic scheduler_a000968, so in practice the shard stays hysteretic. The bounded descriptor drains the cumulative fibre_a000968, and therefore the layout stays cumulative. The deferred shard hoists the bounded kernel_a000968, provided that the kernel stays hysteretic.\n\n```c\n uint64_t ea0009690=kernel[4]|(shard(checkpoint,22)&0xcf);shard=*commit++^223;\n uint64_t acca0009691=chunk[1]|(kernel(boundary,88)&0x73);sentinel=*boundary++^147;\n uint64_t keya0009692=g[7]|(a(z,93)&0x5a);j=*b++^173;\n uint64_t wa0009693=acc[3]|(j(x,50)&0x6b);t=*checkpoint++^128;\n uint64_t keya0009694=checkpoint[2]|(idx(q,68)&0xdb);y=*b++^15;\n uint64_t ua0009695=descriptor[1]|(u(quantiser,21)&0x80);y=*res++^183;\n uint64_t na0009696=boundary[7]|(adapter(window,68)&0x60);w=*s++^67;\n uint64_t ga0009697=layout[2]|(window(x,50)&0x35);boundary=*i++^117;\n uint64_t ja0009698=a[6]|(checkpoint(buffer,73)&0x6a);quantiser=*viewport++^93;\n uint64_t aa0009699=k[0]|(v(h,56)&0xf6);i=*h++^234;\n uint64_t bufa00096910=descriptor[3]|(tmp(residual,18)&0x8b);s=*transcript++^197;\n uint64_t ptra00096911=d[4]|(a(s,3)&0x4d);t=*tmp++^142;\n uint64_t xa00096912=shard[1]|(b(fibre,66)&0xd7);commit=*gradient++^27;\n uint64_t sa00096913=window[4]|(idx(e,49)&0x3b);gradient=*map++^162;\n uint64_t ka00096914=idx[4]|(kernel(window,73)&0x40);k=*tmp++^247;\n uint64_t ta00096915=fibre[0]|(g(i,19)&0x55);sentinel=*descriptor++^92;\n uint64_t ka00096916=boundary[6]|(key(gradient,96)&0xbf);res=*g++^207;\n uint64_t wa00096917=g[0]|(g(gradient,21)&0x6c);commit=*len++^55;\n uint64_t bufa00096918=e[5]|(scheduler(token,78)&0xb4);x=*idx++^13;\n uint64_t ca00096919=allocator[9]|(t(t,55)&0x9d);window=*p++^169;\n uint64_t ea00096920=viewport[1]|(transcript(kernel,45)&0xf1);gradient=*transcript++^35;\n uint64_t acca00096921=buffer[1]|(viewport(c,9)&0xd6);v=*b++^191;\n uint64_t resa00096922=quantiser[4]|(f(z,98)&0xbe);a=*window++^78;\n uint64_t za00096923=v[5]|(i(observer,94)&0xf8);token=*boundary++^174;\n uint64_t ia00096924=kernel[3]|(scheduler(g,8)&0x4b);k=*q++^140;\n uint64_t na00096925=res[4]|(descriptor(gradient,23)&0x84);w=*s++^101;\n uint64_t acca00096926=w[8]|(s(kernel,91)&0x50);scheduler=*kernel++^119;\n uint64_t ya00096927=sentinel[3]|(viewport(sentinel,63)&0x9e);layout=*adapter++^53;\n uint64_t ka00096928=idx[6]|(p(u,94)&0x9c);map=*lane++^29;\n uint64_t ca00096929=v[6]|(len(observer,89)&0xa5);transcript=*kernel++^244;\n uint64_t ea00096930=residual[9]|(b(allocator,26)&0xfd);z=*commit++^143;\n uint64_t sa00096931=chunk[9]|(e(shard,24)&0xec);y=*c++^64;\n uint64_t ya00096932=p[3]|(res(e,91)&0x2b);scheduler=*scheduler++^20;\n uint64_t tmpa00096933=descriptor[7]|(y(n,6)&0xc6);k=*descriptor++^34;\n uint64_t ya00096934=h[4]|(z(v,55)&0xe0);c=*a++^145;\n uint64_t idxa00096935=ptr[1]|(d(sentinel,59)&0x61);idx=*checkpoint++^15;\n```\n\nThe interleaved commit pins the bounded kernel_a000970, but only when the buffer stays retained. The interleaved shard coalesces the collinear lane_a000970, as long as the boundary stays monotonic. The transient commit reparses the retained adapter_a000970, which means the transcript stays deferred. The retained buffer spills the deferred residual_a000970, but only when the boundary stays retained. The collinear buffer invalidates the synchronous window_a000970, which means the transcript stays hysteretic.\n\nThe transient chunk reparses the synchronous observer_a000970, except that the observer stays interleaved. The collinear window hoists the monotonic allocator_a000970, provided that the commit stays deferred. The interleaved window pins the deferred adapter_a000970, which means the gradient stays monotonic. The collinear commit coalesces the saturating gradient_a000970, and therefore the boundary stays retained. The transient chunk invalidates the monotonic chunk_a000970, and therefore the residual stays synchronous.\n\nThe speculative token schedules the bounded layout_a000970, provided that the sentinel stays interleaved. The bounded gradient drains the monotonic viewport_a000970, and therefore the adapter stays cumulative. The hysteretic token reparses the deferred boundary_a000970, which means the commit stays collinear. The cumulative allocator spills the saturating quantiser_a000970, except that the token stays transient. The retained viewport coalesces the speculative layout_a000970, but only when the transcript stays transient. The cumulative observer schedules the speculative quantiser_a000970, which means the kernel stays synchronous.\n\n```typescript\n const bufa0009710={a:len[9],b:observer(commit,6),c:j?q:1};j=scheduler&4|checkpoint<<3;\n const ptra0009711={a:b[2],b:gradient(acc,35),c:y?token:9};d=t&7|c<<5;\n const keya0009712={a:q[1],b:acc(chunk,15),c:k?f:8};len=adapter&4|res<<4;\n const mapa0009713={a:adapter[3],b:gradient(digest,70),c:y?len:7};len=y&7|i<<2;\n const tmpa0009714={a:f[1],b:s(gradient,76),c:ptr?transcript:3};q=shard&4|u<<1;\n const na0009715={a:x[5],b:n(v,27),c:key?e:6};residual=buf&1|chunk<<2;\n const keya0009716={a:f[6],b:chunk(w,50),c:scheduler?u:5};f=lane&2|allocator<<7;\n const ea0009717={a:tmp[0],b:i(i,98),c:s?chunk:0};n=token&3|len<<1;\n const za0009718={a:i[4],b:gradient(boundary,3),c:z?f:3};fibre=v&2|key<<1;\n const ga0009719={a:x[8],b:e(viewport,83),c:z?c:8};layout=allocator&6|buf<<6;\n const ya00097110={a:checkpoint[6],b:w(boundary,7),c:z?e:0};key=descriptor&4|transcript<<7;\n const xa00097111={a:y[0],b:scheduler(key,55),c:fibre?descriptor:0};i=allocator&1|y<<3;\n const va00097112={a:i[8],b:ptr(quantiser,95),c:e?acc:9};f=residual&2|kernel<<2;\n const qa00097113={a:ptr[9],b:p(f,20),c:layout?e:0};adapter=sentinel&5|adapter<<3;\n const ya00097114={a:s[8],b:a(checkpoint,3),c:q?tmp:3};b=residual&5|chunk<<5;\n const ptra00097115={a:c[2],b:len(boundary,7),c:checkpoint?adapter:9};t=i&3|a<<4;\n const acca00097116={a:map[7],b:transcript(digest,80),c:c?layout:6};window=checkpoint&1|w<<6;\n const bufa00097117={a:window[1],b:z(adapter,13),c:i?g:7};kernel=x&4|acc<<7;\n const keya00097118={a:idx[7],b:kernel(x,9),c:commit?s:1};res=fibre&3|z<<1;\n const ea00097119={a:ptr[2],b:t(map,12),c:e?token:9};c=quantiser&1|boundary<<4;\n const ia00097120={a:t[1],b:q(window,28),c:s?s:5};residual=y&2|token<<1;\n const ka00097121={a:q[7],b:lane(buffer,70),c:p?n:4};k=fibre&4|commit<<3;\n const pa00097122={a:h[6],b:kernel(descriptor,26),c:chunk?fibre:5};residual=res&6|c<<6;\n const lena00097123={a:token[6],b:token(digest,57),c:t?i:4};layout=u&5|allocator<<4;\n const ptra00097124={a:boundary[5],b:h(ptr,92),c:kernel?h:0};d=y&5|map<<2;\n const tmpa00097125={a:k[8],b:transcript(buf,54),c:window?checkpoint:9};len=k&3|descriptor<<4;\n```\n\nThe synchronous viewport coalesces the cumulative sentinel_a000972, as long as the residual stays saturating. The hysteretic scheduler schedules the speculative descriptor_a000972, and therefore the chunk stays monotonic. The synchronous adapter materialises the speculative adapter_a000972, so in practice the token stays retained. The deferred residual reconciles the deferred viewport_a000972, which is why the scheduler stays retained. The interleaved sentinel accumulates the synchronous transcript_a000972, which is why the token stays interleaved.\n\nThe hysteretic observer reparses the saturating layout_a000972, provided that the adapter stays interleaved. The deferred shard invalidates the deferred allocator_a000972, but only when the lane stays speculative. The bounded transcript flushes the saturating lane_a000972, provided that the chunk stays retained. The saturating shard flushes the hysteretic chunk_a000972, except that the kernel stays saturating. The monotonic layout drains the deferred residual_a000972, except that the allocator stays retained.\n\nThe synchronous scheduler flushes the bounded checkpoint_a000972, provided that the gradient stays collinear. The transient allocator drains the saturating shard_a000972, which means the allocator stays speculative. The synchronous chunk hoists the speculative buffer_a000972, and therefore the layout stays collinear. The bounded digest spills the bounded transcript_a000972, provided that the fibre stays deferred.\n\nThe monotonic boundary schedules the bounded token_a000972, as long as the buffer stays hysteretic. The interleaved fibre drains the hysteretic descriptor_a000972, except that the digest stays bounded. The bounded residual walks the synchronous adapter_a000972, so in practice the digest stays monotonic. The hysteretic checkpoint flushes the hysteretic gradient_a000972, provided that the allocator stays speculative. The retained fibre reconciles the hysteretic kernel_a000972, which is why the chunk stays bounded.\n\n```rust\n let ha0009730:u64=descriptor[1]^window(descriptor,2)&101;j=shard.iter().map(|x|x*78).sum::<u64>();\n let fa0009731:u64=idx[1]^shard(q,73)&164;commit=lane.iter().map(|x|x*48).sum::<u64>();\n let ea0009732:u64=allocator[3]^h(key,35)&156;k=w.iter().map(|x|x*11).sum::<u64>();\n let ta0009733:u64=checkpoint[7]^tmp(j,7)&213;h=descriptor.iter().map(|x|x*53).sum::<u64>();\n let ca0009734:u64=idx[0]^j(h,47)&252;chunk=lane.iter().map(|x|x*11).sum::<u64>();\n let ia0009735:u64=u[9]^a(g,75)&204;t=z.iter().map(|x|x*53).sum::<u64>();\n let da0009736:u64=e[3]^u(quantiser,34)&211;n=window.iter().map(|x|x*59).sum::<u64>();\n let ha0009737:u64=idx[8]^f(allocator,18)&133;c=transcript.iter().map(|x|x*7).sum::<u64>();\n let ga0009738:u64=b[0]^transcript(shard,71)&10;digest=lane.iter().map(|x|x*23).sum::<u64>();\n let ea0009739:u64=viewport[3]^n(j,54)&144;key=scheduler.iter().map(|x|x*5).sum::<u64>();\n let ea00097310:u64=buf[9]^digest(s,12)&225;layout=chunk.iter().map(|x|x*73).sum::<u64>();\n let na00097311:u64=token[8]^descriptor(res,40)&52;buffer=adapter.iter().map(|x|x*53).sum::<u64>();\n let za00097312:u64=v[4]^transcript(h,31)&162;quantiser=t.iter().map(|x|x*94).sum::<u64>();\n let na00097313:u64=commit[6]^lane(k,82)&221;acc=x.iter().map(|x|x*17).sum::<u64>();\n let ka00097314:u64=map[0]^j(transcript,57)&173;buf=layout.iter().map(|x|x*24).sum::<u64>();\n let ha00097315:u64=shard[2]^residual(c,14)&113;acc=x.iter().map(|x|x*11).sum::<u64>();\n let bufa00097316:u64=b[5]^ptr(allocator,72)&83;lane=fibre.iter().map(|x|x*59).sum::<u64>();\n let resa00097317:u64=token[8]^viewport(lane,18)&232;s=h.iter().map(|x|x*89).sum::<u64>();\n let mapa00097318:u64=shard[3]^res(layout,11)&226;h=checkpoint.iter().map(|x|x*98).sum::<u64>();\n let lena00097319:u64=a[3]^sentinel(t,64)&183;i=checkpoint.iter().map(|x|x*66).sum::<u64>();\n let resa00097320:u64=viewport[1]^residual(gradient,1)&139;residual=allocator.iter().map(|x|x*79).sum::<u64>();\n let tmpa00097321:u64=descriptor[7]^y(allocator,16)&29;boundary=residual.iter().map(|x|x*40).sum::<u64>();\n let bufa00097322:u64=shard[1]^j(res,25)&18;token=key.iter().map(|x|x*53).sum::<u64>();\n let mapa00097323:u64=digest[9]^commit(ptr,15)&154;kernel=chunk.iter().map(|x|x*64).sum::<u64>();\n let va00097324:u64=checkpoint[2]^map(layout,96)&165;scheduler=layout.iter().map(|x|x*86).sum::<u64>();\n let ya00097325:u64=transcript[4]^v(k,60)&151;commit=acc.iter().map(|x|x*7).sum::<u64>();\n let keya00097326:u64=observer[7]^g(allocator,39)&247;z=b.iter().map(|x|x*48).sum::<u64>();\n let fa00097327:u64=res[0]^gradient(kernel,34)&159;c=p.iter().map(|x|x*81).sum::<u64>();\n```", "tool_calls": [{"type": "tool-call", "toolCallId": "call_0009_0", "toolName": "terminal", "argsText": "{\"code\": \"The collinear layout reconciles the bounded chunk_0009t0q, but only when the kernel stays transient. The retained buffer accumulates the collinear viewport_0009t0q, as long as the boundary stays speculative. The collinear token hoists the retained token_0009t0q, which is why the adapter stays hysteretic.\"}", "args": {"code": "The collinear layout reconciles the bounded chunk_0009t0q, but only when the kernel stays transient. The retained buffer accumulates the collinear viewport_0009t0q, as long as the boundary stays speculative. The collinear token hoists the retained token_0009t0q, which is why the adapter stays hysteretic."}, "state": "result", "result": "The interleaved kernel accumulates the retained sentinel_0009t0r, provided that the allocator stays monotonic. The transient token invalidates the cumulative commit_0009t0r, except that the transcript stays synchronous. The speculative token clones the hysteretic transcript_0009t0r, provided that the token stays cumulative. The synchronous layout clones the collinear chunk_0009t0r, as long as the buffer stays monotonic. The collinear observer coalesces the deferred gradient_0009t0r, and therefore the shard stays deferred."}, {"type": "tool-call", "toolCallId": "call_0009_1", "toolName": "web_search", "argsText": "{\"query\": \"The interleaved descriptor clones the hysteretic shard_0009t1q, as long as the descriptor stays cumulative. The saturating digest hoists the hysteretic boundary_0009t1q, so in practice the buffer stays retained. The synchronous scheduler accumulates the saturating viewport_0009t1q, which is why the window stays collinear.\"}", "args": {"query": "The interleaved descriptor clones the hysteretic shard_0009t1q, as long as the descriptor stays cumulative. The saturating digest hoists the hysteretic boundary_0009t1q, so in practice the buffer stays retained. The synchronous scheduler accumulates the saturating viewport_0009t1q, which is why the window stays collinear."}, "state": "result", "result": "The speculative commit reconciles the monotonic digest_0009t1r, provided that the fibre stays deferred. The speculative chunk pins the synchronous allocator_0009t1r, provided that the commit stays cumulative. The collinear gradient drains the transient lane_0009t1r, so in practice the residual stays collinear. The bounded kernel spills the retained token_0009t1r, and therefore the allocator stays interleaved. The retained fibre pins the synchronous residual_0009t1r, except that the transcript stays retained. The deferred checkpoint coalesces the deferred commit_0009t1r, but only when the residual stays transient.\n\nThe interleaved layout clones the transient buffer_0009t1r, as long as the checkpoint stays synchronous. The retained window flushes the deferred kernel_0009t1r, which is why the descriptor stays collinear. The collinear quantiser reparses the saturating shard_0009t1r, so in practice the quantiser stays interleaved. The retained sentinel drains the saturating descriptor_0009t1r, which is why the transcript stays interleaved.\n\nThe saturating allocator flushes the cumulative adapter_0009t1r, except that the checkpoint stays speculative. The collinear window clones the collinear residual_0009t1r, but only when the descriptor stays synchronous. The saturating allocator spills the deferred token_0009t1r, and therefore the chunk stays bounded."}, {"type": "tool-call", "toolCallId": "call_0009_2", "toolName": "terminal", "argsText": "{\"code\": \"The interleaved fibre invalidates the bounded scheduler_0009t2q, so in practice the commit stays retained. The collinear transcript spills the transient layout_0009t2q, as long as the window stays retained. The speculative transcript reparses the saturating gradient_0009t2q, but only when the scheduler stays speculative. The saturating buffer coalesces the cumulative window_0009t2q, as long as the fibre stays collinear. The saturating transcript clones the interleaved fibre_0009t2q, as long as the window stays cumulative. The speculative window schedules the monotonic descriptor_0009t2q, but only when the gradient stays saturating. The synchronous observer walks the deferred shard_0009t2q, which is why the window stays retained. The saturating boundary pins the speculative descriptor_0009t2q, as long as the gradient stays collinear.\"}", "args": {"code": "The interleaved fibre invalidates the bounded scheduler_0009t2q, so in practice the commit stays retained. The collinear transcript spills the transient layout_0009t2q, as long as the window stays retained. The speculative transcript reparses the saturating gradient_0009t2q, but only when the scheduler stays speculative. The saturating buffer coalesces the cumulative window_0009t2q, as long as the fibre stays collinear. The saturating transcript clones the interleaved fibre_0009t2q, as long as the window stays cumulative. The speculative window schedules the monotonic descriptor_0009t2q, but only when the gradient stays saturating. The synchronous observer walks the deferred shard_0009t2q, which is why the window stays retained. The saturating boundary pins the speculative descriptor_0009t2q, as long as the gradient stays collinear."}, "state": "result", "result": "The collinear quantiser flushes the retained kernel_0009t2r, as long as the fibre stays transient. The deferred layout reconciles the bounded scheduler_0009t2r, but only when the quantiser stays collinear. The interleaved scheduler coalesces the monotonic layout_0009t2r, as long as the gradient stays saturating. The cumulative viewport accumulates the speculative boundary_0009t2r, and therefore the kernel stays collinear. The synchronous window pins the bounded sentinel_0009t2r, except that the kernel stays cumulative. The interleaved token schedules the interleaved kernel_0009t2r, as long as the checkpoint stays synchronous.\n\nThe interleaved fibre hoists the interleaved adapter_0009t2r, which is why the chunk stays monotonic. The retained quantiser schedules the deferred checkpoint_0009t2r, which means the token stays speculative. The retained descriptor pins the collinear shard_0009t2r, except that the boundary stays collinear. The monotonic scheduler flushes the transient quantiser_0009t2r, but only when the allocator stays bounded. The synchronous gradient reconciles the collinear boundary_0009t2r, and therefore the allocator stays retained. The speculative chunk schedules the interleaved commit_0009t2r, and therefore the buffer stays deferred."}]}
diff --git a/tests/studio/studiobench/fixture/selftest/test_studiobench_corpus_distinctness.py b/tests/studio/studiobench/fixture/selftest/test_studiobench_corpus_distinctness.py
new file mode 100644
index 00000000000..948f5e84680
--- /dev/null
+++ b/tests/studio/studiobench/fixture/selftest/test_studiobench_corpus_distinctness.py
@@ -0,0 +1,188 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Every streamed turn must be material the thread has not already seen.
+
+The corpus goes to some trouble to make every unit unique, because Shiki caches highlighted output
+keyed on the source string and a repeated fence is a fence that costs nothing the second time.
+Unique UNITS are not the same property as a unique PLAN, and the difference is what went wrong: the
+top rung's seeded prefix consumed the whole frozen manifest, a `min(index, last_index)` clamp
+folded the opening stream and both follow-ups onto the final unit, and the 1M rung then re-sent
+text it had already seeded, from one unit, three times. Nothing raised. The rung that exists to be
+the most expensive on the ladder simply reported the least work per character, which is the exact
+direction the bug pushes and the reason it survived being looked at.
+
+So the invariant is stated here rather than inferred from a table afterwards, and it is stated over
+the whole reachable configuration space -- every rung, every tier ladder, a sweep of measured
+chars-per-token ratios, and a sweep of turn counts -- not over the one rung that happened to break.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.fixture.corpus import ( # noqa: E402
+ MANIFEST_CHARS_PER_TOKEN,
+ RUNGS,
+ STREAM_TURNS,
+ Corpus,
+ RungPlan,
+ manifest_unit_count,
+ plan_rung,
+ unit_text,
+)
+
+#: Ratios a machine can actually report. `measure_chars_per_token` measures the seeded thread, and
+#: the planner is handed whatever it returns; the frozen corpus is sized for everything up to
+#: MANIFEST_CHARS_PER_TOKEN and must refuse -- loudly -- above it.
+SWEPT_RATIOS = (1.0, 2.0, 3.0, 3.7, 4.0, 4.5, MANIFEST_CHARS_PER_TOKEN)
+
+
+def _corpus() -> Corpus:
+ return Corpus.load()
+
+
+def _streamed(plan: RungPlan) -> list[tuple[str, str]]:
+ out = []
+ if plan.streamed_unit is not None:
+ out.append((f"streamed(unit {plan.streamed_unit.index})", unit_text(plan.streamed_unit)))
+ for i, unit in enumerate(plan.follow_up_units):
+ out.append((f"follow_up[{i}](unit {unit.index})", unit_text(unit)))
+ return out
+
+
+def _assert_plan_streams_new_material(plan: RungPlan, where: str) -> None:
+ """The invariant itself, asserted independently of the check `plan_rung` runs for itself.
+
+ A prefix relation and not equality: the streamed turns are clipped, and two turns clipped from
+ one unit at two different lengths are not equal while sharing every fence the shorter one has.
+ """
+ streamed = _streamed(plan)
+ assert streamed, where
+ seeded = [(f"seeded(unit {u.index})", unit_text(u)) for u in plan.seeded_units]
+ for i, (label, text) in enumerate(streamed):
+ assert text, (where, label, "empty")
+ for other_label, other in streamed[i + 1 :] + seeded:
+ assert not text.startswith(other), (where, label, other_label)
+ assert not other.startswith(text), (where, other_label, label)
+
+
+def test_every_rung_streams_material_the_thread_has_not_seen():
+ corpus = _corpus()
+ for rung in RUNGS:
+ _assert_plan_streams_new_material(plan_rung(corpus, rung), rung)
+
+
+def test_no_streamed_turn_reuses_a_seeded_unit_index():
+ """The index-level statement of the same thing, which is what actually broke.
+
+ Kept separate from the text comparison because it is the cheap, readable version: when this one
+ fails the plan handed one corpus unit to two turns, and no amount of clipping makes that two
+ different pieces of content.
+ """
+ corpus = _corpus()
+ for rung in RUNGS:
+ plan = plan_rung(corpus, rung)
+ seeded = [u.index for u in plan.seeded_units]
+ streamed = [plan.streamed_unit.index] + [u.index for u in plan.follow_up_units]
+ assert len(set(streamed)) == len(streamed), (rung, streamed)
+ assert not set(streamed) & set(seeded), (rung, streamed, seeded)
+
+
+def test_the_invariant_holds_at_every_ratio_a_machine_can_report():
+ """`chars_per_token` is measured, not assumed, and a larger ratio means a longer prefix."""
+ corpus = _corpus()
+ for ratio in SWEPT_RATIOS:
+ for rung in RUNGS:
+ plan = plan_rung(corpus, rung, ratio)
+ _assert_plan_streams_new_material(plan, f"{rung}@{ratio}")
+
+
+def test_the_invariant_holds_for_every_tier_ladder_and_rung_override():
+ """`--tier full` walks the whole ladder and `--rungs` can name any subset of it.
+
+ Rungs are planned one at a time, so a ladder is only ever the union of its rungs -- but the
+ tiers are swept anyway, because that is the claim a reader of the CLI actually cares about and
+ a future tier that names a rung nobody planned would be caught here.
+ """
+ from studiobench.__main__ import TIER_RUNGS
+
+ corpus = _corpus()
+ assert "1M" in TIER_RUNGS["full"], "the full tier is what reaches the top of the ladder"
+ for tier, rungs in TIER_RUNGS.items():
+ for rung in rungs:
+ _assert_plan_streams_new_material(plan_rung(corpus, rung), f"{tier}:{rung}")
+
+
+def test_the_invariant_holds_for_every_turn_count_the_corpus_is_sized_for():
+ """More streamed turns means more units past the prefix. Sized for, or refused."""
+ from studiobench.fixture import corpus as corpus_mod
+
+ corpus = _corpus()
+ original = corpus_mod.STREAM_TURNS
+ try:
+ for turns in (1, 2, 3, 4, 5, 6):
+ corpus_mod.STREAM_TURNS = turns
+ for rung in RUNGS:
+ _assert_plan_streams_new_material(plan_rung(corpus, rung), f"{rung}x{turns}")
+ finally:
+ corpus_mod.STREAM_TURNS = original
+
+
+def test_the_manifest_is_sized_from_the_ladder_and_not_the_other_way_round():
+ """The repair. The corpus carries the longest prefix any rung can ask for, plus the turns."""
+ corpus = _corpus()
+ entries = len(corpus.manifest["units"])
+ assert entries == manifest_unit_count(corpus.seed), (
+ entries,
+ manifest_unit_count(corpus.seed),
+ )
+ top = max(len(plan_rung(corpus, r, MANIFEST_CHARS_PER_TOKEN).seeded_units) for r in RUNGS)
+ assert entries >= top + STREAM_TURNS, (entries, top, STREAM_TURNS)
+
+
+def test_a_corpus_too_small_for_the_ladder_fails_loudly():
+ """The clamp is gone. Running off the end has to stop the run, not quietly shrink it.
+
+ This is the property that keeps the defect from coming back through a door nobody watched: a
+ larger rung, a larger measured ratio, another streamed turn. Any of them can outgrow the frozen
+ corpus, and all of them now say so.
+ """
+ corpus = _corpus()
+ truncated = dict(corpus.manifest)
+ truncated["units"] = [u for u in corpus.manifest["units"] if u["index"] < 6]
+ small = Corpus(truncated, {}, corpus.seed)
+ with pytest.raises(ValueError, match = "too small for the"):
+ plan_rung(small, "100K")
+
+
+def test_a_ratio_past_what_the_corpus_was_frozen_for_fails_loudly():
+ corpus = _corpus()
+ with pytest.raises(ValueError, match = "too small for the"):
+ plan_rung(corpus, "1M", MANIFEST_CHARS_PER_TOKEN * 2)
+
+
+def test_a_rung_added_above_the_ladder_refuses_until_the_corpus_is_refrozen():
+ """The way this defect would come back: someone adds a bigger rung and runs it.
+
+ Two halves, and both are needed. The run REFUSES, because a corpus frozen for the old ladder
+ cannot honestly measure a rung above it. And `manifest_unit_count` already knows the new rung
+ exists, so `--freeze` produces a corpus that fits without anyone having to work out how many
+ units the new rung needs -- the ladder sizes the corpus, which is the whole point of the
+ repair.
+ """
+ corpus = _corpus()
+ original = dict(RUNGS)
+ try:
+ RUNGS["2M"] = 2_000_000
+ with pytest.raises(ValueError, match = "too small for the"):
+ plan_rung(corpus, "2M")
+ assert manifest_unit_count(corpus.seed) > len(corpus.manifest["units"])
+ finally:
+ RUNGS.clear()
+ RUNGS.update(original)
diff --git a/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_digest.py b/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_digest.py
new file mode 100644
index 00000000000..cf6f65a4a0f
--- /dev/null
+++ b/tests/studio/studiobench/fixture/selftest/test_studiobench_parity_digest.py
@@ -0,0 +1,554 @@
+# 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 UI-parity digest, tested in both directions without a browser.
+
+A digest is a claim with two failure modes and they pull in opposite directions:
+
+ FALSE POSITIVE something volatile survives normalisation, two runs of ONE build disagree, and
+ within a day nobody opens the report. The live proof is the null control; what
+ is testable here is that each normalisation rule does what it says.
+ FALSE NEGATIVE something that matters is normalised away or never walked, the check passes
+ and the UI changed anyway. This is the worse one because it is silent, and it
+ is what most of this file is about: every KEPT property gets a test that the
+ signature moves when it moves.
+
+WHY THE REAL JAVASCRIPT AND NOT A PYTHON PORT. The normaliser that ships is `scene/parity.js`. A
+Python re-implementation tested here would pass forever while the shipped regexes drifted away
+from it, and the test would be measuring itself. So the fixtures are Python, the evaluator is
+node running the actual file, and if node is missing the test SKIPS with that reason stated rather
+than passing on a substitute. A skip says "not measured"; a pass would say "measured, fine".
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.analysis import parity as P # noqa: E402
+
+PARITY_JS = Path(__file__).resolve().parents[2] / "scene" / "parity.js"
+
+# A DOM shim, not a DOM. `signature()` touches exactly six things on an element, so those six are
+# what the harness provides; anything richer would be a second browser to keep correct. `capture()`
+# is deliberately NOT exercised here because it needs querySelectorAll, getComputedStyle and the
+# real selector adapter -- that is the live null and spike controls' job, and pretending to cover
+# it with a mock is how a test suite comes to assert its own fixtures.
+HARNESS_JS = r"""
+const fs = require("fs");
+const src = fs.readFileSync(process.argv[2], "utf8");
+const window = { };
+const document = { body: { tagName: "BODY", attributes: [], childNodes: [],
+ getAttribute: () => null },
+ querySelectorAll: () => [] };
+window.getComputedStyle = () => ({ getPropertyValue: () => "" });
+(new Function("window", "document", src))(window, document);
+
+const build = (spec) => {
+ if (typeof spec === "string") return { nodeType: 3, nodeValue: spec };
+ const attrs = spec.attrs || {};
+ return {
+ nodeType: 1,
+ tagName: (spec.tag || "div").toUpperCase(),
+ attributes: Object.keys(attrs).map((name) => ({ name })),
+ getAttribute: (name) => (name in attrs ? attrs[name] : null),
+ childNodes: (spec.children || []).map(build),
+ };
+};
+
+const spec = JSON.parse(fs.readFileSync(process.argv[3], "utf8"));
+const parity = window.__sb.parity;
+console.log(JSON.stringify({
+ texts: (spec.texts || []).map((t) => parity.normText(t)),
+ urls: (spec.urls || []).map((u) => parity.normUrl(u)),
+ signatures: (spec.trees || []).map((t) => parity.signature(build(t))),
+ hashes: (spec.hashes || []).map((s) => parity.hash(s)),
+}));
+"""
+
+
+def _node() -> str:
+ exe = shutil.which("node") or shutil.which("nodejs")
+ if exe is None:
+ pytest.skip(
+ "node is not installed, so the shipped parity.js could not be evaluated; "
+ "this is NOT MEASURED rather than passing"
+ )
+ return exe
+
+
+def run_js(spec: dict) -> dict:
+ exe = _node()
+ with tempfile.TemporaryDirectory() as tmp:
+ harness = Path(tmp) / "harness.js"
+ harness.write_text(HARNESS_JS, encoding = "utf-8")
+ payload = Path(tmp) / "spec.json"
+ payload.write_text(json.dumps(spec), encoding = "utf-8")
+ got = subprocess.run(
+ [exe, str(harness), str(PARITY_JS), str(payload)],
+ capture_output = True,
+ text = True,
+ timeout = 120,
+ )
+ if got.returncode != 0:
+ raise AssertionError(f"the parity.js harness failed: {got.stderr.strip()[-800:]}")
+ return json.loads(got.stdout)
+
+
+def norm_text(*values: str) -> list[str]:
+ return run_js({"texts": list(values)})["texts"]
+
+
+def sig(tree: dict) -> str:
+ return run_js({"trees": [tree]})["signatures"][0]
+
+
+def sigs(*trees: dict) -> list[str]:
+ return run_js({"trees": list(trees)})["signatures"]
+
+
+# ── the normaliser: things that MUST be erased ──────────────────────
+
+
+def test_rendered_durations_collapse():
+ # unslothai/unsloth#9054: a 295 vs 310 ms difference in the action bar, which is wall clock.
+ got = norm_text("copied in 295ms", "copied in 310ms", "took 1.2 s", "ran for 3 min")
+ assert got[0] == got[1], got
+ assert "#T" in got[2] and "#T" in got[3], got
+
+
+def test_relative_and_absolute_times_collapse():
+ got = norm_text("sent just now", "sent yesterday", "sent at 14:05", "sent at 2:05 pm")
+ assert all("#T" in g for g in got), got
+
+
+def test_backend_minted_uuids_collapse():
+ # The volatile that made the FIRST null control fail on all eighteen actions: every message
+ # root carries `data-message-id`, and the two arms are two installs with two databases.
+ a, b = norm_text(
+ "id 71ad5735-ede4-464d-a36b-44309ef67624", "id f44017dd-f5f7-45dd-9f53-475c115e61ac"
+ )
+ assert a == b == "id #ID", (a, b)
+
+
+def test_long_hex_ids_collapse():
+ a, b = norm_text("build 3a816e656eb74295aa11", "build 9f0d1c2b7e6a4d38bb22")
+ assert a == b, (a, b)
+
+
+def test_urls_lose_their_origin_but_keep_their_path():
+ got = run_js(
+ {
+ "urls": [
+ "http://127.0.0.1:5830/assets/index.js",
+ "http://127.0.0.1:5831/assets/index.js",
+ "http://127.0.0.1:5830/assets/other.js",
+ "blob:http://127.0.0.1:5830/8f2c-11",
+ "data:image/png;base64,AAAA",
+ ]
+ }
+ )
+ urls = got["urls"]
+ # The two arms of an A/B are two ports by construction, so the origin cannot be signal.
+ assert urls[0] == urls[1], urls
+ # ...but a DIFFERENT asset at the same origin still has to move the digest.
+ assert urls[0] != urls[2], urls
+ assert urls[3] == "#BLOB" and urls[4].startswith("#DATA:"), urls
+
+
+# ── the normaliser: things that MUST SURVIVE ────────────────────────
+#
+# Every test above widens the set of things the digest cannot see. These are the counterweight:
+# a normaliser that erased them would pass a null control perfectly and detect nothing.
+
+
+def test_a_bare_number_is_not_a_duration():
+ a, b = norm_text("3 files changed", "4 files changed")
+ assert a != b, (a, b)
+
+
+def test_a_word_beginning_with_a_unit_letter_is_not_a_unit():
+ a, b = norm_text("5 stars", "6 stars")
+ assert a != b, (a, b)
+
+
+def test_a_short_hex_string_is_not_an_id():
+ # Colours, error codes and the like are eight characters or fewer and are content.
+ a, b = norm_text("code deadbeef", "code cafebabe")
+ assert a != b, (a, b)
+
+
+def test_text_content_moves_the_signature():
+ one, two = sigs(
+ {"tag": "p", "children": ["hello world"]}, {"tag": "p", "children": ["hello worlds"]}
+ )
+ assert one != two
+
+
+# ── the signature: every KEPT property, tested as kept ──────────────
+
+
+ "attr,before,after",
+ [
+ ("data-state", "open", "closed"), # a reasoning pane that silently collapses
+ ("data-slot", "reasoning-root", "tool-root"),
+ ("data-role", "assistant", "user"),
+ ("aria-hidden", "false", "true"), # content gone from the accessibility tree
+ ("class", "flex gap-2", "flex-col gap-8"), # a layout class swap
+ ("title", "Copy code", "Copy"),
+ ("role", "menu", "listbox"),
+ ],
+)
+def test_a_changed_attribute_value_moves_the_signature(attr, before, after):
+ one, two = sigs({"tag": "div", "attrs": {attr: before}}, {"tag": "div", "attrs": {attr: after}})
+ assert one != two, attr
+
+
+def test_adding_or_removing_a_boolean_attribute_moves_the_signature():
+ # `disabled` has no value to compare, so only its PRESENCE can carry it.
+ one, two = sigs({"tag": "button", "attrs": {}}, {"tag": "button", "attrs": {"disabled": ""}})
+ assert one != two
+
+
+def test_a_volatile_attribute_keeps_its_presence_even_though_its_value_is_dropped():
+ # Dropping the value must not drop the fact that the attribute is there: an element that
+ # gains an `id` has changed, even though which id it gained is noise.
+ plain, with_id = sigs(
+ {"tag": "div", "attrs": {}}, {"tag": "div", "attrs": {"id": "radix-:r1a:"}}
+ )
+ assert plain != with_id
+ # Two different generated ids, however, must read the same.
+ a, b = sigs(
+ {"tag": "div", "attrs": {"id": "radix-:r1a:"}},
+ {"tag": "div", "attrs": {"id": "radix-:r9z:"}},
+ )
+ assert a == b
+
+
+def test_added_and_removed_elements_move_the_signature():
+ small, large = sigs(
+ {"tag": "div", "children": [{"tag": "span"}]},
+ {"tag": "div", "children": [{"tag": "span"}, {"tag": "b"}]},
+ )
+ assert small != large
+
+
+def test_reordered_siblings_move_the_signature():
+ # Two elements with identical content in the other order. A digest built from a SET rather
+ # than a sequence would read these as equal, and a list that renders backwards is a real bug.
+ one, two = sigs(
+ {
+ "tag": "ul",
+ "children": [{"tag": "li", "children": ["a"]}, {"tag": "li", "children": ["b"]}],
+ },
+ {
+ "tag": "ul",
+ "children": [{"tag": "li", "children": ["b"]}, {"tag": "li", "children": ["a"]}],
+ },
+ )
+ assert one != two
+
+
+def test_nesting_moves_the_signature():
+ # Same tags, same text, different tree. Closing tags are what make this detectable.
+ flat, nested = sigs(
+ {"tag": "div", "children": [{"tag": "span", "children": ["x"]}, {"tag": "b"}]},
+ {"tag": "div", "children": [{"tag": "span", "children": ["x", {"tag": "b"}]}]},
+ )
+ assert flat != nested
+
+
+def test_attribute_order_does_not_move_the_signature():
+ # React can emit attributes in either order for the same render. Sorting them is what makes
+ # the digest a property of the DOM rather than of the serialiser.
+ one, two = sigs(
+ {"tag": "div", "attrs": {"class": "a", "data-state": "open"}},
+ {"tag": "div", "attrs": {"data-state": "open", "class": "a"}},
+ )
+ assert one == two
+
+
+def test_whitespace_only_text_nodes_do_not_move_the_signature():
+ one, two = sigs(
+ {"tag": "p", "children": ["hello"]}, {"tag": "p", "children": ["hello", " ", "\n\t"]}
+ )
+ assert one == two
+
+
+def test_the_depth_cap_leaves_a_visible_marker():
+ # A truncated signature that reads like a complete one is the silent false negative this file
+ # exists to rule out, so the cap has to be legible in the output.
+ deep = {"tag": "div"}
+ for _ in range(60):
+ deep = {"tag": "div", "children": [deep]}
+ assert "<!depth-cap>" in sig(deep)
+
+
+def test_content_below_the_depth_cap_is_not_compared():
+ # The honest statement of the limit: past 40 levels the digest stops looking, and this test
+ # records that as a KNOWN hole rather than leaving somebody to discover it.
+ def wrap(inner, n):
+ for _ in range(n):
+ inner = {"tag": "div", "children": [inner]}
+ return inner
+
+ one, two = sigs(
+ wrap({"tag": "p", "children": ["alpha"]}, 60), wrap({"tag": "p", "children": ["omega"]}, 60)
+ )
+ assert one == two, "if this now fails the cap moved and the docstring must be updated"
+
+
+# ── the comparison layer, in pure Python ────────────────────────────
+
+
+def capture(
+ digest = "aaaa",
+ *,
+ messages = None,
+ overlays = None,
+ root = "thread",
+ styles = None,
+ chars = 100,
+) -> dict:
+ return {
+ "parity_attempted": True,
+ "root_kind": root,
+ "digest": digest,
+ "chars": chars,
+ "messages": messages
+ if messages is not None
+ else [
+ {"i": 0, "role": "user", "digest": "m0", "chars": 10},
+ {"i": 1, "role": "assistant", "digest": "m1", "chars": 20},
+ ],
+ "overlays": overlays if overlays is not None else [],
+ "styles": styles
+ if styles is not None
+ else {"digest": "s0", "chars": 5, "elements": 4, "capped": False},
+ }
+
+
+def test_identical_captures_match():
+ assert P.compare(capture(), capture())["verdict"] == P.MATCH
+
+
+def test_a_failed_capture_is_never_a_match():
+ # The single most dangerous confusion in the whole instrument: a capture that threw and a
+ # capture that agreed both produce no complaint unless they are told apart here.
+ failed = {"parity_attempted": False, "reason": "threadRoot is not a function"}
+ got = P.compare(failed, capture())
+ assert got["verdict"] == P.NOT_COMPARABLE
+ assert "threadRoot" in got["reason"]
+ assert P.compare(None, capture())["verdict"] == P.NOT_COMPARABLE
+
+
+def test_two_different_roots_are_not_comparable():
+ # A body-root capture carries the sidebar and its relative timestamps. Comparing it with a
+ # thread-root one produces two plausible hashes and a meaningless verdict.
+ got = P.compare(capture(root = "thread"), capture(root = "body"))
+ assert got["verdict"] == P.NOT_COMPARABLE
+ assert "different roots" in got["reason"]
+
+
+def test_a_capture_from_an_older_instrument_is_not_silently_compared():
+ old = capture()
+ del old["root_kind"]
+ assert P.compare(old, capture())["verdict"] == P.NOT_COMPARABLE
+ # Both sides old is an old payload, which IS comparable; it just predates the field.
+ other = capture("bbbb")
+ del other["root_kind"]
+ assert P.compare(old, other)["verdict"] == P.DIFFER
+
+
+def test_a_difference_is_localised_to_the_message_that_moved():
+ moved = capture(
+ "zzzz",
+ messages = [
+ {"i": 0, "role": "user", "digest": "m0", "chars": 10},
+ {"i": 1, "role": "assistant", "digest": "CHANGED", "chars": 33},
+ ],
+ )
+ got = P.compare(capture(), moved)
+ assert got["verdict"] == P.DIFFER
+ assert got["moved"] == ["msg1(assistant):20->33c"], got["moved"]
+
+
+def test_an_added_message_is_localised_as_one_sided():
+ extra = capture(
+ "zzzz",
+ messages = [
+ {"i": 0, "role": "user", "digest": "m0", "chars": 10},
+ {"i": 1, "role": "assistant", "digest": "m1", "chars": 20},
+ {"i": 2, "role": "assistant", "digest": "m2", "chars": 5},
+ ],
+ )
+ assert P.compare(capture(), extra)["moved"] == ["msg2(assistant):only treatment"]
+
+
+def test_an_overlay_that_changes_without_changing_count_is_still_localised():
+ # The bug this pins: comparing only the NUMBER of overlays passes an open menu whose contents
+ # were rewritten, which is exactly the popover regression the overlay walk was added for.
+ one = capture("aaaa", overlays = [{"sel": '[role="menu"]', "digest": "o1", "chars": 40}])
+ two = capture("zzzz", overlays = [{"sel": '[role="menu"]', "digest": "o2", "chars": 44}])
+ got = P.compare(one, two)
+ assert got["moved"] == ['overlay0[[role="menu"]]:40->44c'], got["moved"]
+
+
+def test_an_overlay_change_alone_is_a_difference():
+ # THE FALSE NEGATIVE THE SPIKE CONTROL FOUND. An overlay lives outside the thread root, so a
+ # menu that mounts when it should not leaves the whole-thread digest untouched. Testing only
+ # that digest made the entire overlay walk unreachable and reported a clean pass.
+ one = capture("aaaa", overlays = [])
+ two = capture("aaaa", overlays = [{"sel": '[role="menu"]', "digest": "o1", "chars": 40}])
+ got = P.compare(one, two)
+ assert got["verdict"] == P.DIFFER, "an overlay appearing on one arm only is a difference"
+ assert got["moved"] == ["overlays 0->1"], got["moved"]
+
+
+def test_a_message_change_alone_is_a_difference():
+ # The same shape one level down: if a per-message digest moves while the whole-thread digest
+ # somehow does not, the pair still differs. Belt and braces on the aggregate hash.
+ moved = capture(
+ "aaaa",
+ messages = [
+ {"i": 0, "role": "user", "digest": "m0", "chars": 10},
+ {"i": 1, "role": "assistant", "digest": "CHANGED", "chars": 20},
+ ],
+ )
+ assert P.compare(capture(), moved)["verdict"] == P.DIFFER
+
+
+def test_a_difference_outside_every_message_is_reported_as_such():
+ # An empty `moved` list would read as "nothing differs" next to a DIFFER verdict.
+ got = P.compare(capture("aaaa"), capture("zzzz"))
+ assert got["verdict"] == P.DIFFER
+ assert got["moved"] and "scaffolding" in got["moved"][0]
+
+
+def test_the_style_probe_is_a_separate_verdict_from_the_structural_one():
+ styled = capture(styles = {"digest": "OTHER", "chars": 5, "elements": 4, "capped": False})
+ got = P.compare(capture(), styled)
+ # Structure identical, style moved: a stylesheet change is exactly this shape, and folding it
+ # into the structural verdict would put the hard signal's credibility on the soft reading.
+ assert got["verdict"] == P.MATCH
+ assert got["style_verdict"] == P.DIFFER
+
+
+def test_a_capped_style_probe_is_not_comparable_rather_than_equal():
+ capped = capture(styles = {"digest": "s0", "chars": 5, "elements": 64, "capped": True})
+ got = P.compare(capture(), capped)
+ assert got["style_verdict"] == P.NOT_COMPARABLE
+
+
+# ── mutation detection and the derived unstable set ─────────────────
+
+
+def test_mutation_detected_reports_a_real_change():
+ got = P.mutation_detected(capture(), capture("zzzz"))
+ assert got["detected"] is True
+
+
+def test_mutation_detected_does_not_claim_a_detection_it_did_not_make():
+ assert P.mutation_detected(capture(), capture())["detected"] is False
+ # And a capture that FAILED is not a detection either, in either direction.
+ got = P.mutation_detected(capture(), {"parity_attempted": False, "reason": "gone"})
+ assert got["detected"] is False and got["verdict"] == P.NOT_COMPARABLE
+
+
+def test_an_action_that_never_ran_is_not_a_matching_surface():
+ # MEASURED, not imagined: on a 100K fast-tier null control, five of the eighteen actions did
+ # not run on either arm -- no attachments button, no Copy button, a missed slot. The window
+ # still closes and the digest is still captured, so both arms agreed and `image_upload` was
+ # reported as a stable, matching surface. Nobody had opened it.
+ idle = {"ran": False, "reason": "no visible attachments button", "parity": capture()}
+ got = P.compare_rows(idle, {"ran": True, "parity": capture()})
+ assert got["verdict"] == P.NOT_EXERCISED
+ assert "nothing touched" in got["reason"]
+
+
+def test_a_pair_that_ran_on_both_arms_is_compared_normally():
+ got = P.compare_rows(
+ {"ran": True, "parity": capture()}, {"ran": True, "parity": capture("zzzz")}
+ )
+ assert got["verdict"] == P.DIFFER
+
+
+def test_an_unexercised_action_contributes_no_evidence_of_stability():
+ got = P.derive_unstable(
+ [
+ ("image_upload", {"verdict": P.NOT_EXERCISED}),
+ ("image_upload", {"verdict": P.NOT_EXERCISED}),
+ ]
+ )
+ assert got["image_upload"]["observations"] == 0
+ assert got["image_upload"]["undetermined"] is True
+ assert got["image_upload"]["unstable"] is False
+
+
+def test_instability_needs_more_than_one_observation():
+ once = P.derive_unstable([("copy_markdown", {"verdict": P.DIFFER})])
+ assert once["copy_markdown"]["undetermined"] is True
+ assert once["copy_markdown"]["unstable"] is False
+
+
+def test_an_action_that_differs_against_itself_is_derived_as_unstable():
+ got = P.derive_unstable(
+ [
+ ("stop_generation", {"verdict": P.DIFFER}),
+ ("stop_generation", {"verdict": P.MATCH}),
+ ("settings", {"verdict": P.MATCH}),
+ ("settings", {"verdict": P.MATCH}),
+ ]
+ )
+ assert got["stop_generation"]["unstable"] is True
+ assert got["settings"]["unstable"] is False
+
+
+def test_a_blind_action_is_counted_as_blind_and_not_as_stable():
+ # An action whose digest could never be captured has an observation count of zero. Reporting
+ # it as "stable" would be the instrument certifying a surface it never looked at.
+ got = P.derive_unstable(
+ [
+ ("image_upload", {"verdict": P.NOT_COMPARABLE}),
+ ("image_upload", {"verdict": P.NOT_COMPARABLE}),
+ ]
+ )
+ assert got["image_upload"]["observations"] == 0
+ assert got["image_upload"]["not_comparable"] == 2
+ assert got["image_upload"]["unstable"] is False
+ assert got["image_upload"]["undetermined"] is True
+
+
+def test_the_cross_check_reports_both_directions_of_disagreement():
+ derived = {
+ "stop_generation": {"unstable": True, "undetermined": False},
+ "settings": {"unstable": True, "undetermined": False},
+ "scroll_after": {"unstable": False, "undetermined": False},
+ }
+ got = P.cross_check(derived, ["stop_generation", "scroll_after", "never_ran"])
+ assert got["unstable_but_not_declared"] == ["settings"]
+ assert got["declared_stable_in_practice"] == ["scroll_after"]
+ assert got["declared_but_never_observed"] == ["never_ran"]
+
+
+def test_every_declared_unstable_action_carries_a_mechanism():
+ # An action silenced without a stated reason is a hole nobody can audit later.
+ assert P.UNSTABLE_ACTIONS
+ for action, mechanism in P.UNSTABLE_ACTIONS.items():
+ assert len(mechanism) > 40, f"{action} is silenced without a real mechanism"
+
+
+def test_the_verdict_tally_counts_not_comparable_as_its_own_outcome():
+ got = P.summarise(
+ [{"verdict": P.MATCH}, {"verdict": P.DIFFER}, {"verdict": P.NOT_COMPARABLE}, {}]
+ )
+ assert got == {P.MATCH: 1, P.DIFFER: 1, P.NOT_COMPARABLE: 2}
diff --git a/tests/studio/studiobench/fixture/selftest/test_studiobench_rung_plan.py b/tests/studio/studiobench/fixture/selftest/test_studiobench_rung_plan.py
new file mode 100644
index 00000000000..918de6170d7
--- /dev/null
+++ b/tests/studio/studiobench/fixture/selftest/test_studiobench_rung_plan.py
@@ -0,0 +1,168 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The rung plan invariant that the whole upper ladder rests on.
+
+The streamed tail must be the SAME SIZE at every rung. When it grew with the rung instead, the
+stream took 811 seconds at 1M against a 135-second film, so the ten slots labelled "after the
+reply is complete" all ran mid-generation. Nothing crashed and a full table was printed; the
+labels were just false. A property that fails silently and prints numbers anyway is exactly the
+kind that needs a test rather than a comment.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.fixture.corpus import ( # noqa: E402
+ RUNGS,
+ STREAM_TAIL_CHARS,
+ Corpus,
+ plan_rung,
+)
+
+# The field cadence: 24 characters every 73 ms.
+FIELD_CHARS_PER_SEC = 24 / 0.073
+
+
+def _plans():
+ corpus = Corpus.load()
+ return {rung: plan_rung(corpus, rung) for rung in RUNGS}
+
+
+def test_the_streamed_tail_never_exceeds_the_declared_size():
+ for rung, plan in _plans().items():
+ assert plan.streamed_chars <= STREAM_TAIL_CHARS, rung
+
+
+def test_stream_duration_is_rung_independent():
+ """The property the film depends on: the OPENING stream drains in the same time at every rung.
+
+ The opening turn is the one the film's slots are timed against. The follow-ups are separate
+ events sent later by `send_turn`, so folding them in here would measure a quantity no slot
+ depends on and would fail on the 1K rung, which legitimately streams only once.
+ """
+ seconds = {r: p.streamed_chars / FIELD_CHARS_PER_SEC for r, p in _plans().items()}
+ assert max(seconds.values()) < 20.0, seconds
+ # 1K is legitimately shorter: the whole rung is smaller than one tail.
+ big = {r: s for r, s in seconds.items() if r != "1K"}
+ assert max(big.values()) - min(big.values()) < 5.0, big
+
+
+def test_multi_turn_rungs_stream_more_than_once():
+ """The point of the follow-ups: a cell samples streaming cost at more than one thread size."""
+ plans = _plans()
+ assert len(plans["1K"].follow_up_units) == 0, "a 4,000 character rung is one exchange"
+ for rung in ("10K", "100K", "500K", "1M"):
+ assert len(plans[rung].follow_up_units) == 2, rung
+
+
+def test_follow_ups_are_small_enough_not_to_move_the_rung():
+ """They sample cost; they are not supposed to be a second helping of thread mass."""
+ for rung, plan in _plans().items():
+ if not plan.follow_up_units:
+ continue
+ assert plan.follow_up_chars < plan.target_chars * 0.15, rung
+
+
+def test_the_stream_drains_before_the_first_after_generation_slot():
+ """Otherwise `scroll_after` and everything below it measure a still-streaming thread."""
+ from studiobench.scene.schedule import SCENES
+
+ worst = max(p.streamed_chars for p in _plans().values()) / FIELD_CHARS_PER_SEC
+ for name, scene in SCENES.items():
+ after = [s for s in scene.slots if s.action == "scroll_after"]
+ assert after, name
+ assert after[0].t_start_ms / 1000.0 > worst, (name, after[0].t_start_ms, worst)
+
+
+def test_during_generation_slots_actually_fall_during_generation():
+ from studiobench.scene.schedule import SCENES
+
+ # The SHORTEST stream on the ladder above 1K, since a slot has to be inside every rung's
+ # stream to deserve the name.
+ # The OPENING turn only: the follow-ups are sent later by `send_turn`, so a slot that has to
+ # fall during generation has to fall inside the first stream, not inside their sum.
+ shortest = min(p.streamed_chars for r, p in _plans().items() if r != "1K") / FIELD_CHARS_PER_SEC
+ for name, scene in SCENES.items():
+ during = [s for s in scene.slots if s.action == "scroll_during_generation"]
+ assert during, name
+ for slot in during:
+ assert slot.t_start_ms / 1000.0 < shortest, (name, slot.t_start_ms, shortest)
+
+
+def test_stop_opens_only_after_the_tail_has_drained():
+ """Stop owns its own turn now; opening it mid-stream would truncate the measured reply."""
+ from studiobench.scene.schedule import SCENES
+
+ worst = max(p.streamed_chars for p in _plans().values()) / FIELD_CHARS_PER_SEC
+ for name, scene in SCENES.items():
+ stop = [s for s in scene.slots if s.action == "stop_generation"]
+ assert stop, name
+ assert stop[0].t_start_ms / 1000.0 > worst, (name, stop[0].t_start_ms, worst)
+
+
+def test_every_rung_lands_close_to_the_size_it_claims():
+ for rung, plan in _plans().items():
+ total = plan.total_chars
+ error = abs(total - plan.target_chars) / plan.target_chars
+ # 1K cannot be exact: clipping is block-aligned so a prefix never ends inside a fence.
+ limit = 0.15 if rung == "1K" else 0.05
+ assert error < limit, (rung, total, plan.target_chars, error)
+
+
+def test_the_ladder_is_strictly_increasing_in_seeded_mass():
+ plans = _plans()
+ order = ["1K", "10K", "100K", "500K", "1M"]
+ masses = [plans[r].total_chars for r in order]
+ assert masses == sorted(masses)
+ assert len(set(masses)) == len(masses)
+
+
+# Actions that need a SETTLED reply. The action bar's More and Copy buttons are not rendered while
+# a turn is streaming, select-all copies a moving target, and delete is hidden on a running
+# message. Each one reports an honest `NOT RUN` rather than a wrong number, which is why this was
+# invisible until somebody counted: on a 36 job sweep the fast film recorded
+# `message_menu: NOT RUN -- no More button` on 312 of 312 attempts, and the four actions it
+# silently stopped exercising include the one carrying the largest measured effect in this
+# codebase (the message menu, 1,164.9 ms to 60.7 ms across the merged campaign).
+SETTLED_ACTIONS = ("message_menu", "copy_markdown", "select_all_copy", "delete_message")
+
+
+def test_settled_actions_open_after_the_follow_up_drains():
+ """A slot needing a finished reply must clear the follow-up turn the preceding send started.
+
+ Only films used at a rung that actually sends follow-ups are checked. Below
+ MULTI_TURN_MIN_CHARS a rung is single-turn, `send_turn` reports an exhausted queue, and there
+ is no follow-up stream to wait for -- so holding the quick film to this bar would be asserting
+ against a stream that never exists.
+ """
+ from studiobench.__main__ import TIER_RUNGS
+ from studiobench.fixture.corpus import FOLLOW_UP_CHARS, MULTI_TURN_MIN_CHARS
+ from studiobench.scene.schedule import SCENES
+
+ drain_s = FOLLOW_UP_CHARS / FIELD_CHARS_PER_SEC
+ plans = _plans()
+ for name, scene in SCENES.items():
+ rungs = TIER_RUNGS.get(name) or []
+ if not any(
+ (plans[r].total_chars if r in plans else 0) >= MULTI_TURN_MIN_CHARS for r in rungs
+ ):
+ continue
+ last_send = None
+ for slot in sorted(scene.slots, key = lambda s: s.t_start_ms):
+ if slot.action == "send_turn":
+ last_send = slot.t_start_ms
+ elif slot.action in SETTLED_ACTIONS and last_send is not None:
+ # The slot's WINDOW, not its start. A slot may legitimately open a little before
+ # the follow-up finishes and wait inside its own budget -- the quick film opens
+ # `message_menu` at 4.5 s against a 4.56 s drain and it runs, because it has 3 s
+ # of budget to wait in. What is fatal is a window that CLOSES before the reply
+ # settles, which is what the first fast film did: 1.7 s gap plus 0.8 s budget
+ # against a 4.56 s drain, so the button had not been rendered yet and never
+ # would be inside that window.
+ window_end = (slot.t_start_ms + slot.budget_ms - last_send) / 1000.0
+ assert window_end >= drain_s, (name, slot.action, window_end, drain_s)
diff --git a/tests/studio/studiobench/fixture/selftest/test_studiobench_surfaces.py b/tests/studio/studiobench/fixture/selftest/test_studiobench_surfaces.py
new file mode 100644
index 00000000000..d6eab8d31df
--- /dev/null
+++ b/tests/studio/studiobench/fixture/selftest/test_studiobench_surfaces.py
@@ -0,0 +1,596 @@
+# 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 surface registry and the coverage manifest, checked without a browser.
+
+WHAT THESE TESTS ARE FOR. A registry is a list of promises about an app that is not present when
+the list is read, so almost nothing about it can be verified here. What CAN be verified is the
+class of defect that makes a sweep worthless: an entry that cannot be executed, a coverage number
+that counts a surface nobody reached, and a row that records a failure without recording why. All
+three have the same shape -- the artefact looks complete and says the wrong thing -- and all three
+are cheap to catch here rather than after a forty-minute run.
+
+No browser and no Studio. The step lists are declarative for exactly this reason, and the sweep is
+driven against a scripted stand-in page so its bookkeeping is exercised on both the reached and
+the unreached path.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.report.payload import ROW_TYPE_SECTIONS # noqa: E402
+from studiobench.runtime.types import ROW_REQUIRED, ROW_TYPES # noqa: E402
+from studiobench.scene import surface_sweep, surfaces # noqa: E402
+from studiobench.scoring.schema import validate_payload # noqa: E402
+
+
+# ── the registry is well formed ─────────────────────────────────────
+
+
+def test_the_shipped_registry_validates():
+ surfaces.validate_registry()
+
+
+def test_surface_ids_are_unique():
+ ids = surfaces.surface_ids()
+ assert len(ids) == len(set(ids))
+
+
+def test_every_surface_declares_a_reach_a_restore_and_a_root():
+ for surface in surfaces.surfaces():
+ assert surface.root, surface.id
+ assert surface.reach or surface.restore == (), (
+ f"{surface.id} declares no reach, so it must also declare no restore: a surface that "
+ f"is reached by doing nothing cannot need undoing"
+ )
+ # Anything that navigates or opens an overlay has to say how to get back, or the next
+ # surface is reached from a state nobody declared.
+ opens = any(step[0] in {"goto", "click", "fill", "press"} for step in surface.reach)
+ assert not opens or surface.restore, f"{surface.id} opens something and never closes it"
+
+
+def test_every_surface_declares_a_settle_condition():
+ # A sweep with no settle condition is a sweep that digests whatever is on screen when the
+ # sleep expires, which is the one result this tool may not produce.
+ for surface in surfaces.surfaces():
+ assert surface.settle is not None, surface.id
+ assert isinstance(surface.settle, dict)
+ assert set(surface.settle) & {
+ "visible",
+ "hidden",
+ "count_at_least",
+ "text",
+ "js",
+ }, f"{surface.id} has a settle condition surfaces.js cannot evaluate"
+
+
+def test_no_surface_settles_on_a_timer():
+ for surface in surfaces.surfaces():
+ assert "wait" not in surface.settle, (
+ f"{surface.id} settles on a wait. A wait cannot tell a surface that rendered from one "
+ f"that never did"
+ )
+
+
+def test_every_step_uses_a_known_verb_with_the_right_arity():
+ for surface in surfaces.surfaces():
+ for steps in (surface.reach, surface.restore):
+ for step in steps:
+ assert step[0] in surfaces.VERBS, (surface.id, step)
+ assert len(step) - 1 == surfaces.VERBS[step[0]], (surface.id, step)
+
+
+def test_the_sweep_can_execute_every_verb_the_registry_uses():
+ # The registry and the interpreter are in different files, and a verb added to one and not the
+ # other fails only at run time, on the surface that uses it, as a reach failure that reads
+ # like a broken selector.
+ used = {
+ step[0] for s in surfaces.surfaces() for steps in (s.reach, s.restore) for step in steps
+ }
+ driver = surface_sweep._Driver(page = _FakePage(), base_url = "http://x", log = lambda _m: None)
+ sample = {
+ "goto": ("/chat",),
+ "click": ("sel",),
+ "click_if": ("sel",),
+ "hover": ("sel",),
+ "press": ("Escape",),
+ "fill": ("sel", "text"),
+ "wait": (10,),
+ }
+ for verb in used:
+ driver._step(verb, sample[verb])
+
+
+def test_known_uncovered_entries_are_complete():
+ for entry in surfaces.KNOWN_UNCOVERED:
+ assert entry["id"] and entry["title"]
+ # The reason is the whole value of the list. A one-word reason is a gap with a label on it.
+ assert len(entry["reason"]) > 40, entry["id"]
+
+
+def test_a_surface_cannot_be_both_registered_and_known_uncovered():
+ assert not ({u["id"] for u in surfaces.KNOWN_UNCOVERED} & set(surfaces.surface_ids()))
+
+
[email protected]("group", ["route", "settings", "sidebar", "chat"])
+def test_the_registry_covers_every_major_group(group):
+ assert group in surfaces.groups()
+
+
+def test_the_settings_dialog_covers_every_shipped_tab():
+ # The twelve panels are lazily imported chunks, so a tab that stopped rendering fails only
+ # for the tab. Pinned here so a panel added to the app without a surface is visible as a
+ # missing id rather than as a coverage figure that quietly stayed at 100%.
+ shipped = {
+ "general",
+ "profile",
+ "appearance",
+ "resources",
+ "chat",
+ "voice",
+ "connections",
+ "data",
+ "api-keys",
+ "agents",
+ "debugging",
+ "about",
+ }
+ registered = {s.id.split(":", 1)[1] for s in surfaces.surfaces() if s.group == "settings"}
+ assert shipped - registered == set()
+
+
+def test_the_registry_covers_every_routed_path():
+ # From app/router.tsx. `/` and `/settings` are not page surfaces -- both redirect on
+ # beforeLoad -- and the two auth-flow routes are in KNOWN_UNCOVERED with the guard that
+ # redirects them.
+ routed = {
+ "/chat",
+ "/projects",
+ "/hub",
+ "/studio",
+ "/images",
+ "/video",
+ "/audio",
+ "/export",
+ "/data-recipes",
+ "/api-monitor",
+ }
+ reached = set()
+ for surface in surfaces.surfaces():
+ for step in surface.reach:
+ if step[0] == "goto":
+ reached.add(step[1])
+ assert routed - reached == set()
+
+
+# ── validate_registry rejects what it must ──────────────────────────
+
+
+def _one(**overrides):
+ base = dict(
+ id = "x:one",
+ group = "g",
+ title = "t",
+ reach = (("goto", "/chat"),),
+ restore = (("goto", "/chat"),),
+ root = ("body",),
+ settle = {"visible": "body"},
+ )
+ base.update(overrides)
+ return surfaces.Surface(**base)
+
+
+def test_validate_rejects_a_duplicate_id():
+ with pytest.raises(surfaces.RegistryError, match = "duplicate"):
+ surfaces.validate_registry([_one(), _one()])
+
+
+def test_validate_rejects_an_unknown_verb():
+ with pytest.raises(surfaces.RegistryError, match = "unknown verb"):
+ surfaces.validate_registry([_one(reach = (("teleport", "/chat"),))])
+
+
+def test_validate_rejects_the_wrong_number_of_arguments():
+ with pytest.raises(surfaces.RegistryError, match = "argument"):
+ surfaces.validate_registry([_one(reach = (("fill", "sel"),))])
+
+
+def test_validate_rejects_a_surface_with_no_digest_root():
+ with pytest.raises(surfaces.RegistryError, match = "root"):
+ surfaces.validate_registry([_one(root = ())])
+
+
+# ── the row type is registered, not smuggled ────────────────────────
+
+
+def test_the_surface_row_type_is_registered():
+ assert "surface" in ROW_TYPES
+ assert ROW_TYPE_SECTIONS["surface"] == "surfaces"
+
+
+def test_a_surface_row_must_carry_its_reason():
+ # The single defect this project cares most about: a check that cannot distinguish "did not
+ # run" from "passed". A surface row without `reason` is exactly that row.
+ assert "reason" in ROW_REQUIRED["surface"]
+ assert "reached" in ROW_REQUIRED["surface"]
+ assert "parity" in ROW_REQUIRED["surface"]
+
+
+def test_the_recorder_accepts_a_surface_row_and_rejects_one_missing_its_reason(tmp_path):
+ from studiobench.runtime.types import Recorder
+
+ rec = Recorder(tmp_path / "payload.jsonl", "session")
+ rec.emit(
+ {
+ "row_type": "surface",
+ "surface": "route:chat",
+ "reached": True,
+ "reason": None,
+ "parity": {"parity_attempted": True, "digest": "abcd1234"},
+ }
+ )
+ with pytest.raises(ValueError, match = "reason"):
+ rec.emit(
+ {
+ "row_type": "surface",
+ "surface": "route:hub",
+ "reached": False,
+ "parity": {"parity_attempted": False},
+ }
+ )
+ rec.close()
+
+
+def test_surface_rows_land_in_their_own_payload_section(tmp_path):
+ from studiobench.report.payload import assemble_rows
+
+ path = tmp_path / "payload.jsonl"
+ path.write_text(
+ '{"row_type":"run_meta","tier":"quick"}\n'
+ '{"row_type":"cell","cell_id":"r1K.A0.rep0","completed":true}\n'
+ '{"row_type":"surface","surface":"route:chat","reached":true,"reason":null,'
+ '"parity":{"parity_attempted":true,"digest":"abcd1234"}}\n',
+ encoding = "utf-8",
+ )
+ payload = assemble_rows(path)
+ assert len(payload["surfaces"]) == 1
+ # NOT in unknown_rows. A new row type that lands there is carried through the whole report
+ # without anyone noticing it is not being read.
+ assert payload["unknown_rows"] == []
+
+
+def test_a_payload_carrying_surface_rows_has_no_bare_zeros():
+ # The schema bans a naked numeric zero, because a zero outside a measure is indistinguishable
+ # from "we never ran that". Surface rows carry counts, so they have to attest.
+ rows = surface_sweep.sweep(_FakePage(reach_ok = True), "http://x")[0]
+ validate_payload({"excluded_cells": [], "surfaces": rows})
+
+
+# ── the manifest ────────────────────────────────────────────────────
+
+
+def _rows_for(entries, reached_ids):
+ out = []
+ for surface in entries:
+ row = surface_sweep._row(surface, cell_id = None)
+ if surface.id in reached_ids:
+ row["reached"] = True
+ row["reason"] = None
+ row["parity"] = {"parity_attempted": True, "digest": "abcd1234", "chars": 100}
+ out.append(row)
+ return out
+
+
+def test_the_manifest_counts_only_what_was_reached():
+ entries = surfaces.surfaces()
+ rows = _rows_for(entries, {entries[0].id})
+ manifest = surface_sweep.build_manifest(rows, entries, {"scoped": True})
+ assert manifest["registered"] == len(entries)
+ assert manifest["reached"] == 1
+ assert manifest["not_reached"] == len(entries) - 1
+ assert len(manifest["failures"]) == len(entries) - 1
+
+
+def test_every_unreached_surface_appears_in_the_manifest_with_a_reason():
+ entries = surfaces.surfaces()
+ manifest = surface_sweep.build_manifest(_rows_for(entries, set()), entries, {"scoped": True})
+ assert len(manifest["failures"]) == len(entries)
+ for failure in manifest["failures"]:
+ assert failure["reason"], failure["id"]
+
+
+def test_a_conditional_miss_is_counted_apart_from_a_hard_miss():
+ entries = [_one(id = "a", conditional = None), _one(id = "b", conditional = "needs a gpu")]
+ manifest = surface_sweep.build_manifest(_rows_for(entries, set()), entries, {"scoped": True})
+ assert manifest["not_reached_hard"] == 1
+ assert manifest["not_reached_conditional"] == 1
+ # Coverage is against what this host COULD render, so the conditional miss leaves the
+ # denominator at one rather than silently deflating the figure.
+ assert manifest["coverage_pct"] == 0.0
+ assert manifest["coverage_pct_of_registered"] == 0.0
+
+
+def test_a_volatile_surface_is_reached_but_not_counted_as_comparable():
+ # Reached and volatile are different facts and the manifest has to keep them apart. Folding
+ # them together is how a live memory gauge ends up quoted as a UI change.
+ entries = [_one(id = "a"), _one(id = "b", volatile = "shows a live memory gauge")]
+ rows = _rows_for(entries, {"a", "b"})
+ manifest = surface_sweep.build_manifest(rows, entries, {"scoped": True})
+ assert manifest["reached"] == 2
+ assert manifest["comparable"] == 1
+ assert manifest["volatile"] == 1
+ assert manifest["volatile_surfaces"] == [{"id": "b", "mechanism": "shows a live memory gauge"}]
+
+
+def test_every_volatile_surface_states_its_mechanism():
+ # A volatility flag without a mechanism is a licence to ignore a real difference.
+ for surface in surfaces.surfaces():
+ if surface.volatile is not None:
+ assert len(surface.volatile) > 40, surface.id
+
+
+def test_the_measured_volatile_surfaces_are_declared():
+ # Three consecutive sweeps against one Studio agreed on 44 of 53 surfaces. These are the ones
+ # that did not, each with a mechanism established from source or from a text diff. Pinned so
+ # a settle condition that is tightened later shows up as a flag that can now be dropped,
+ # rather than as a flag nobody revisits.
+ declared = {s.id for s in surfaces.surfaces() if s.volatile}
+ assert {
+ "route:chat",
+ "chat:composer-filled",
+ "settings:resources",
+ "settings:debugging",
+ "route:hub",
+ "hub:datasets",
+ "hub:compact-layout",
+ # Measured to move, mechanism not established. Pinned so the admission stays visible.
+ "route:train",
+ "settings:agents",
+ "train:image-training",
+ } <= declared
+
+
+def test_the_unexplained_movers_say_so_rather_than_offering_a_cause():
+ # A plausible-sounding mechanism that has not been established is worse than an admitted gap:
+ # it is the sentence somebody uses to wave away a real difference.
+ unexplained = [
+ s
+ for s in surfaces.surfaces()
+ if s.volatile and "NOT" in s.volatile and "established" in s.volatile
+ ]
+ assert {s.id for s in unexplained} == {"route:train", "settings:agents", "train:image-training"}
+
+
+def test_the_rendered_manifest_names_the_volatile_surfaces():
+ entries = [_one(id = "b", volatile = "shows a live memory gauge that moves on its own")]
+ text = surface_sweep.render_manifest(
+ surface_sweep.build_manifest(_rows_for(entries, {"b"}), entries, {"scoped": True})
+ )
+ assert "NOT COMPARABLE" in text
+ assert "live memory gauge" in text
+
+
+def test_the_manifest_carries_the_known_uncovered_list():
+ entries = surfaces.surfaces()
+ manifest = surface_sweep.build_manifest(_rows_for(entries, set()), entries, {"scoped": True})
+ assert manifest["known_uncovered_count"] == len(surfaces.KNOWN_UNCOVERED)
+ assert {u["id"] for u in manifest["known_uncovered"]} == {
+ u["id"] for u in surfaces.KNOWN_UNCOVERED
+ }
+
+
+def test_the_rendered_manifest_names_every_failure_and_every_known_gap():
+ entries = surfaces.surfaces()
+ manifest = surface_sweep.build_manifest(_rows_for(entries, set()), entries, {"scoped": True})
+ text = surface_sweep.render_manifest(manifest)
+ for surface in entries:
+ assert surface.id in text
+ for entry in surfaces.KNOWN_UNCOVERED:
+ assert entry["id"] in text
+
+
+def test_an_unscoped_sweep_says_so_in_the_rendered_manifest():
+ # An unscoped digest is a whole-page reading taken forty times, and every one of them agrees
+ # with every other for reasons that have nothing to do with the surfaces. That has to be at
+ # the top of the artefact, not inferable from a field somebody might read.
+ entries = surfaces.surfaces()[:1]
+ manifest = surface_sweep.build_manifest(
+ _rows_for(entries, {entries[0].id}),
+ entries,
+ {"scoped": False, "reason": "parity.capture() ignored the moved root"},
+ )
+ text = surface_sweep.render_manifest(manifest)
+ assert "WARNING" in text
+ assert "ignored the moved root" in text
+
+
+# ── the sweep's own bookkeeping ─────────────────────────────────────
+
+
+class _FakePage:
+ """A scripted stand-in for a Playwright page.
+
+ `reach_ok` false makes every click raise, which is how a broken selector presents. The point
+ is not to simulate a browser: it is to prove that a sweep whose reaches all fail still emits
+ one row per surface, each carrying a reason, rather than emitting nothing.
+ """
+
+ def __init__(
+ self,
+ reach_ok: bool = True,
+ settles: bool = True,
+ ) -> None:
+ self.reach_ok = reach_ok
+ self.settles = settles
+ self.clicks: list = []
+
+ def goto(self, *_a, **_k) -> None:
+ pass
+
+ def click(self, selector, **_k) -> None:
+ if not self.reach_ok:
+ raise RuntimeError(f"Timeout: {selector}")
+ self.clicks.append(selector)
+
+ def hover(self, selector, **_k) -> None:
+ if not self.reach_ok:
+ raise RuntimeError(f"Timeout: {selector}")
+
+ def fill(self, *_a, **_k) -> None:
+ if not self.reach_ok:
+ raise RuntimeError("Timeout")
+
+ def query_selector(self, _selector):
+ return None
+
+ def wait_for_timeout(self, _ms) -> None:
+ pass
+
+ @property
+ def keyboard(self):
+ return self
+
+ def press(self, _key) -> None:
+ pass
+
+ def evaluate(
+ self,
+ script,
+ arg = None,
+ ):
+ if "probeScoping" in script:
+ return {"scoped": True, "scoping_attempted": True, "probe_chars": 44}
+ if "settled" in script:
+ return {"ok": self.settles, "detail": "scripted"}
+ if "capture" in script:
+ return {
+ "parity_attempted": True,
+ "digest": "abcd1234",
+ "chars": 100,
+ "messages": [],
+ "overlays": [],
+ "root_selector": (arg or ["?"])[0],
+ }
+ if "facts" in script:
+ return {
+ "facts_attempted": True,
+ "root_elements": 10,
+ "pathname": "/chat",
+ "open_dialogs": 0,
+ "open_menus": 0,
+ }
+ if "isClean" in script:
+ return {
+ "clean_attempted": True,
+ "open_dialogs": 0,
+ "open_menus": 0,
+ "pathname": "/chat",
+ }
+ raise AssertionError(f"unscripted evaluate: {script[:60]}")
+
+
+def test_a_reach_that_fails_records_a_reason_and_never_a_digest():
+ rows, _manifest = surface_sweep.sweep(_FakePage(reach_ok = False), "http://x")
+ assert len(rows) == len(surfaces.surfaces())
+ interactive = [
+ r
+ for r in rows
+ if any(
+ step[0] in {"click", "hover", "fill"}
+ for step in surfaces.get_surface(r["surface"]).reach
+ )
+ ]
+ assert interactive, "the registry has no interactive surface left to check"
+ for row in interactive:
+ assert row["reached"] is False
+ assert "the reach failed" in row["reason"]
+ # Never a digest it did not take. A parity block that claimed `attempted` here would make
+ # a failed sweep read as a passing parity check downstream.
+ assert row["parity"]["parity_attempted"] is False
+
+
+def test_a_surface_that_never_settles_is_not_recorded_as_reached():
+ rows, manifest = surface_sweep.sweep(
+ _FakePage(reach_ok = True, settles = False),
+ "http://x",
+ settle_timeout_ms = 1,
+ surface_budget_ms = 50,
+ )
+ assert manifest["reached"] == 0
+ assert len(rows) == len(surfaces.surfaces())
+ for row in rows:
+ assert "never settled" in row["reason"]
+ assert row["parity"]["parity_attempted"] is False
+
+
+def test_a_clean_sweep_reaches_every_surface_and_records_the_root_it_digested():
+ rows, manifest = surface_sweep.sweep(_FakePage(), "http://x")
+ assert manifest["reached"] == len(surfaces.surfaces())
+ assert manifest["coverage_pct"] == 100.0
+ for row in rows:
+ assert row["reason"] is None
+ assert row["parity"]["root_selector"]
+
+
+def test_the_sweep_rejects_an_unknown_surface_id():
+ with pytest.raises(surfaces.RegistryError, match = "no such surface"):
+ surface_sweep.sweep(_FakePage(), "http://x", only = ["nope:nothing"])
+
+
+def test_the_sweep_streams_rows_to_a_recorder_as_it_goes():
+ class _Rec:
+ def __init__(self):
+ self.rows = []
+
+ def emit(self, row):
+ self.rows.append(row)
+
+ rec = _Rec()
+ rows, _manifest = surface_sweep.sweep(_FakePage(), "http://x", recorder = rec)
+ # One per surface, so a sweep that dies halfway leaves the surfaces it did reach behind.
+ assert len(rec.rows) == len(rows)
+
+
+def test_the_sweep_returns_to_the_known_state_before_every_surface():
+ # Not "after every surface": an after-only reset trusts each surface's own restore, and the
+ # one that fails is the one whose restore did not run.
+ page = _FakePage()
+ surface_sweep.sweep(page, "http://x")
+ assert surfaces.KNOWN_STATE_PATH == "/chat"
+
+
+# ── the digest is the film's digest, not a second one ───────────────
+
+
+def test_the_sweep_takes_its_digest_through_parity_capture():
+ # If surfaces.js ever grew its own DOM walk, surface digests and action digests would stop
+ # being comparable -- and nothing downstream would notice, because both would still be hex
+ # strings of the same length.
+ text = (Path(__file__).resolve().parents[2] / "scene" / "surfaces.js").read_text(
+ encoding = "utf-8"
+ )
+ assert "parity.capture()" in text
+ assert "window.__sb.parity" in text
+
+
+def test_surfaces_js_does_not_edit_the_shared_chat_adapter():
+ # dom.js is the film's adapter and every action reads it. The surface layer restores the root
+ # it moved, so a sweep cannot leave the film digesting the wrong element.
+ text = (Path(__file__).resolve().parents[2] / "scene" / "surfaces.js").read_text(
+ encoding = "utf-8"
+ )
+ assert "dom.threadRoot = original" in text
+
+
+def test_the_registry_is_a_frozen_dataclass_so_a_sweep_cannot_rewrite_it():
+ surface = surfaces.surfaces()[0]
+ assert dataclasses.is_dataclass(surface)
+ with pytest.raises(dataclasses.FrozenInstanceError):
+ surface.id = "mutated"
diff --git a/tests/studio/studiobench/instruments/__init__.py b/tests/studio/studiobench/instruments/__init__.py
new file mode 100644
index 00000000000..e9173113770
--- /dev/null
+++ b/tests/studio/studiobench/instruments/__init__.py
@@ -0,0 +1,96 @@
+# 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 registry. See INTERFACES.md section 3.
+
+An instrument registers a zero-argument FACTORY, not an instance, so a level-2 tracing instrument
+whose module needs a heavy import costs nothing on a level-0 run. Dropping a .py file into this
+directory is the whole registration step: `load_all()` imports every sibling module and a module
+that cannot be imported becomes a recorded gate row rather than a crash, so a partially installed
+tree still produces Layer 1's numbers.
+"""
+
+from __future__ import annotations
+
+import importlib
+import pkgutil
+from dataclasses import dataclass
+from typing import Any, Callable, Optional
+
+_REGISTRY: "dict[str, _Entry]" = {}
+_IMPORT_ERRORS: "dict[str, str]" = {}
+_LOADED = False
+
+
+@dataclass(frozen = True)
+class _Entry:
+ name: str
+ level: int
+ factory: Callable[[], Any]
+
+
+def register_instrument(name: str, level: int = 0) -> Callable:
+ """Decorator over a zero-argument factory returning an object with the Instrument protocol."""
+ if level < 0:
+ raise ValueError("instrument level must be >= 0")
+
+ def deco(factory: Callable[[], Any]) -> Callable[[], Any]:
+ if name in _REGISTRY:
+ raise ValueError(f"instrument {name!r} is already registered")
+ _REGISTRY[name] = _Entry(name = name, level = level, factory = factory)
+ return factory
+
+ return deco
+
+
+def load_all() -> dict[str, str]:
+ """Import every sibling module once. Returns {module_name: error} for the ones that failed."""
+ global _LOADED
+ if _LOADED:
+ return dict(_IMPORT_ERRORS)
+ for mod in pkgutil.iter_modules(__path__):
+ if mod.name.startswith("_"):
+ continue
+ try:
+ importlib.import_module(f"{__name__}.{mod.name}")
+ except Exception as exc: # noqa: BLE001
+ _IMPORT_ERRORS[mod.name] = f"{type(exc).__name__}: {exc}"
+ _LOADED = True
+ return dict(_IMPORT_ERRORS)
+
+
+def available() -> list[tuple[str, int]]:
+ load_all()
+ return sorted((e.name, e.level) for e in _REGISTRY.values())
+
+
+def import_errors() -> dict[str, str]:
+ load_all()
+ return dict(_IMPORT_ERRORS)
+
+
+def build(level: int, only: Optional[list[str]] = None) -> list:
+ """Instantiate every instrument whose declared level is <= `level`, sorted by name.
+
+ A factory that raises is skipped and recorded in `import_errors()` under its instrument name,
+ for the same reason a failed import is: one broken instrument must not cost the run.
+ """
+ load_all()
+ out = []
+ for entry in sorted(_REGISTRY.values(), key = lambda e: e.name):
+ if entry.level > level:
+ continue
+ if only is not None and entry.name not in only:
+ continue
+ try:
+ inst = entry.factory()
+ except Exception as exc: # noqa: BLE001
+ _IMPORT_ERRORS[entry.name] = f"{type(exc).__name__}: {exc}"
+ continue
+ inst.name = getattr(inst, "name", entry.name) or entry.name
+ inst.level = getattr(inst, "level", entry.level)
+ out.append(inst)
+ return out
+
+
+__all__ = ["register_instrument", "load_all", "available", "import_errors", "build"]
diff --git a/tests/studio/studiobench/instruments/coverage.py b/tests/studio/studiobench/instruments/coverage.py
new file mode 100644
index 00000000000..26754e6b782
--- /dev/null
+++ b/tests/studio/studiobench/instruments/coverage.py
@@ -0,0 +1,443 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Exact invocation counts via `Profiler.startPreciseCoverage`.
+
+This is the only non-statistical instrument in the tool. A CPU profile says "a
+frame was on the stack for 12% of samples"; precise coverage says "this function
+was entered exactly 4,110 times". That integer is what turns
+
+ 36% of TaskDuration is unnamed script
+
+into
+
+ cloneChildFibers ran exactly 4,110 times = 6 renders x 685 blocks
+
+and the second statement is falsifiable against a structural quantity we
+measured separately. That is the whole point of the layer.
+
+THE COST, STATED UP FRONT: precise coverage makes V8 keep count-collecting
+bytecode alive, which suppresses the optimising tiers for covered functions.
+Every timing taken while coverage is on is therefore wrong, and wrong in a
+direction that varies per function. So this module DISCARDS TIME BY
+CONSTRUCTION: `CoverageSnapshot` carries no durations, and the only values it
+exposes across the boundary are integers. There is no flag to turn that off,
+because the moment a millisecond from this arm reaches a table, every number
+next to it becomes unsafe.
+
+`detailed: false` asks for function-level granularity rather than per-block
+ranges. The first range of a function covers the whole function, so its `count`
+is the invocation count of the function itself; block granularity would give a
+larger, less interpretable set of ranges and a much bigger payload for no gain
+here.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+from typing import Any, Iterable, Sequence
+
+from ..analysis import CellFailure
+
+
+@dataclass(frozen = True)
+class FunctionCount:
+ """One function and the exact number of times it was entered."""
+
+ script_id: str
+ url: str
+ function_name: str
+ start_offset: int
+ end_offset: int
+ count: int
+
+ @property
+ def key(self) -> tuple[str, int, int]:
+ """Identity within one build.
+
+ Keyed on script and byte offsets, not on name. Minified code reuses
+ names aggressively and gives many functions no name at all, so a
+ name-keyed map silently merges unrelated functions.
+ """
+ return (self.script_id, self.start_offset, self.end_offset)
+
+ def label(self) -> str:
+ name = self.function_name or "(anonymous)"
+ return f"{name} @ {self.url or 'script#' + self.script_id}[{self.start_offset}:{self.end_offset}]"
+
+
+@dataclass
+class CoverageSnapshot:
+ """Counts taken between two `takePreciseCoverage` calls.
+
+ Deliberately has no time fields. Not "unused time fields": none.
+ """
+
+ functions: list[FunctionCount] = field(default_factory = list)
+ script_urls: dict[str, str] = field(default_factory = dict)
+ # Set when this snapshot is a difference of two absolute snapshots.
+ is_delta: bool = False
+
+ def by_key(self) -> dict[tuple[str, int, int], FunctionCount]:
+ return {f.key: f for f in self.functions}
+
+ def total_calls(self) -> int:
+ return sum(f.count for f in self.functions)
+
+ def nonzero(self) -> list[FunctionCount]:
+ return [f for f in self.functions if f.count > 0]
+
+ def top(
+ self,
+ limit: int = 40,
+ url_filter: str | None = None,
+ ) -> list[FunctionCount]:
+ rows = self.nonzero()
+ if url_filter:
+ rows = [f for f in rows if url_filter in f.url]
+ rows.sort(key = lambda f: -f.count)
+ return rows[:limit]
+
+ def find(self, name: str) -> list[FunctionCount]:
+ return [f for f in self.functions if f.function_name == name]
+
+ def search(self, pattern: str) -> list[FunctionCount]:
+ rx = re.compile(pattern)
+ return [f for f in self.functions if rx.search(f.function_name or "")]
+
+ def count_vector(self, keys: Sequence[tuple[str, int, int]]) -> tuple[int, ...]:
+ m = self.by_key()
+ return tuple(m[k].count if k in m else 0 for k in keys)
+
+
+def _parse(result: dict[str, Any]) -> CoverageSnapshot:
+ snap = CoverageSnapshot()
+ for script in result.get("result", []):
+ sid = str(script.get("scriptId", ""))
+ url = str(script.get("url", ""))
+ snap.script_urls[sid] = url
+ for fn in script.get("functions", []):
+ ranges = fn.get("ranges") or []
+ if not ranges:
+ continue
+ # With `detailed: false` there is one range per function and it
+ # spans the function; even with block coverage the FIRST range is
+ # the function-level one, so this stays correct either way.
+ head = ranges[0]
+ snap.functions.append(
+ FunctionCount(
+ script_id = sid,
+ url = url,
+ function_name = str(fn.get("functionName", "")),
+ start_offset = int(head.get("startOffset", 0)),
+ end_offset = int(head.get("endOffset", 0)),
+ count = int(head.get("count", 0)),
+ )
+ )
+ return snap
+
+
+class PreciseCoverage:
+ """Bracket a window with exact call counts.
+
+ Usage is deliberately two-phase. `takePreciseCoverage` returns counts
+ accumulated since coverage started, not since the last call, so a window is
+ measured as the difference of two snapshots. Reporting an absolute snapshot
+ as if it were a window is how "this ran 4,110 times during the stream"
+ becomes "this ran 4,110 times since the page loaded".
+ """
+
+ def __init__(
+ self,
+ cdp: Any,
+ *,
+ detailed: bool = False,
+ allow_triggered_updates: bool = False,
+ ) -> None:
+ self.cdp = cdp
+ self.detailed = detailed
+ self.allow_triggered_updates = allow_triggered_updates
+ self._started = False
+ self._baseline: CoverageSnapshot | None = None
+
+ def start(self) -> None:
+ if self._started:
+ raise RuntimeError("PreciseCoverage.start called twice")
+ self.cdp.send("Profiler.enable")
+ self.cdp.send(
+ "Profiler.startPreciseCoverage",
+ {
+ "callCount": True,
+ "detailed": self.detailed,
+ "allowTriggeredUpdates": self.allow_triggered_updates,
+ },
+ )
+ self._started = True
+
+ def snapshot(self) -> CoverageSnapshot:
+ if not self._started:
+ raise RuntimeError("PreciseCoverage.snapshot before start")
+ return _parse(self.cdp.send("Profiler.takePreciseCoverage"))
+
+ def mark(self) -> None:
+ """Take the baseline that a later `window()` is measured against."""
+ self._baseline = self.snapshot()
+
+ def window(self) -> CoverageSnapshot:
+ """Counts accrued since `mark()`."""
+ if self._baseline is None:
+ raise RuntimeError("PreciseCoverage.window before mark")
+ return diff(self._baseline, self.snapshot())
+
+ def stop(self) -> None:
+ if not self._started:
+ return
+ try:
+ self.cdp.send("Profiler.stopPreciseCoverage")
+ finally:
+ self._started = False
+
+ def __enter__(self) -> "PreciseCoverage":
+ self.start()
+ return self
+
+ def __exit__(self, *exc: Any) -> None:
+ self.stop()
+
+
+def diff(before: CoverageSnapshot, after: CoverageSnapshot) -> CoverageSnapshot:
+ """Counts accrued between two absolute snapshots.
+
+ A function present in `after` but not in `before` is a script compiled
+ inside the window; its full count belongs to the window. A count that went
+ DOWN is impossible for a monotonic counter and means the two snapshots came
+ from different coverage sessions, so it fails rather than clamping.
+ """
+ prev = before.by_key()
+ out = CoverageSnapshot(is_delta = True, script_urls = dict(after.script_urls))
+ for f in after.functions:
+ base = prev.get(f.key)
+ delta = f.count - (base.count if base else 0)
+ if delta < 0:
+ raise CellFailure(
+ "coverage_counter_went_backwards",
+ f"{f.label()} counted {base.count if base else 0} then {f.count}; "
+ "precise coverage counters are monotonic, so these snapshots are "
+ "not from the same coverage session",
+ )
+ out.functions.append(
+ FunctionCount(
+ script_id = f.script_id,
+ url = f.url,
+ function_name = f.function_name,
+ start_offset = f.start_offset,
+ end_offset = f.end_offset,
+ count = delta,
+ )
+ )
+ return out
+
+
+def assert_integers_only(payload: dict[str, Any]) -> None:
+ """Refuse to let a coverage-arm float reach a report.
+
+ Timings from a coverage arm are meaningless because optimised code is
+ suppressed. This is the boundary guard: it is called on anything derived
+ from a coverage run before it is written out, and it raises on any
+ non-integral number. It is a cheap check that makes a silent category error
+ into a loud one.
+ """
+
+ def check(node: Any, path: str) -> None:
+ if isinstance(node, bool):
+ return
+ if isinstance(node, float):
+ raise CellFailure(
+ "coverage_float_leak",
+ f"{path} is a float ({node!r}). Precise coverage disables optimised "
+ "code, so every duration measured under it is wrong. Only integers "
+ "may cross this boundary.",
+ )
+ if isinstance(node, dict):
+ for k, v in node.items():
+ check(v, f"{path}.{k}")
+ elif isinstance(node, (list, tuple)):
+ for i, v in enumerate(node):
+ check(v, f"{path}[{i}]")
+
+ check(payload, "coverage")
+
+
+def counts_for(snapshot: CoverageSnapshot, names: Iterable[str]) -> dict[str, int]:
+ """Total exact calls per function NAME.
+
+ Names are summed across every function carrying them, and the caller is told
+ how many distinct functions contributed, because "React has three functions
+ called `Zk`" is a fact the caller needs in order to know whether the number
+ means anything.
+ """
+ out: dict[str, int] = {}
+ for name in names:
+ matches = snapshot.find(name)
+ out[name] = sum(m.count for m in matches)
+ return out
+
+
+def ambiguity(snapshot: CoverageSnapshot, name: str) -> int:
+ return len(snapshot.find(name))
+
+
+# ═══════════════════════════════════════════════════════════════════════════
+# Harness adapter (INTERFACES.md section 3)
+# ═══════════════════════════════════════════════════════════════════════════
+#
+# Level 3, and every window this instrument touches is TIMING-VOID by
+# construction. Precise coverage keeps count-collecting bytecode alive, which
+# disables TurboFan and Maglev for the whole isolate, so the durations that
+# `tracing` reports in the same cell describe a program nobody ships.
+#
+# The payload therefore carries `timings_void: true` at both window and cell
+# level. That flag exists so the report layer can refuse to quote a duration
+# from this cell without having to know why. Only integers cross the boundary,
+# enforced by `assert_integers_only` on the way out rather than by convention.
+
+import time # noqa: E402
+from typing import Any # noqa: E402
+
+from ..analysis import assert_no_bare_zero, measured, merge, unmeasured # noqa: E402
+from . import register_instrument # noqa: E402
+
+
+class CoverageInstrument:
+ """Exact invocation counts per window. Integers only, timings void."""
+
+ name = "coverage"
+ level = 3
+
+ def __init__(self, top_n: int = 40) -> None:
+ self.ctx: Any = None
+ self.cdp: Any = None
+ self.cov: PreciseCoverage | None = None
+ self.top_n = top_n
+ self._overhead_ms = 0.0
+ self._windows = 0
+ self._start_reason = ""
+
+ def attach(self, ctx: Any) -> None:
+ self.ctx = ctx
+
+ def start_cell(self, cell: Any) -> None:
+ self.cdp = getattr(self.ctx, "cdp", None)
+ self._overhead_ms = 0.0
+ self._windows = 0
+ self.cov = None
+ self._start_reason = ""
+ if self.cdp is None:
+ self._start_reason = "no CDP session; precise coverage is Chromium only"
+ return
+ t0 = time.perf_counter()
+ try:
+ # Started ONCE per cell, never per window. Restarting coverage
+ # re-runs V8's DeoptimizeAll, which changes what gets compiled and
+ # therefore what gets counted, so per-window restarts would make the
+ # counts depend on the window boundaries.
+ self.cov = PreciseCoverage(self.cdp)
+ self.cov.start()
+ except Exception as exc: # noqa: BLE001
+ self.cov = None
+ self._start_reason = f"{type(exc).__name__}: {exc}"
+ self._overhead_ms += (time.perf_counter() - t0) * 1000.0
+
+ def open(self, window: Any) -> None:
+ if self.cov is None:
+ return
+ t0 = time.perf_counter()
+ try:
+ self.cov.mark()
+ except Exception:
+ pass
+ self._overhead_ms += (time.perf_counter() - t0) * 1000.0
+
+ def close(self, window: Any) -> dict | None:
+ if self.cov is None:
+ return merge(
+ unmeasured("total_calls", self._start_reason or "coverage not running"),
+ {"timings_void": True, "active": False},
+ )
+ t0 = time.perf_counter()
+ try:
+ snap = self.cov.window()
+ top = snap.top(self.top_n)
+ payload = merge(
+ measured("total_calls", int(snap.total_calls())),
+ measured("functions_invoked", len(snap.nonzero())),
+ measured(
+ "top_functions",
+ [
+ {
+ "function": f.function_name or "(anonymous)",
+ "url": f.url,
+ "start_offset": int(f.start_offset),
+ "end_offset": int(f.end_offset),
+ "count": int(f.count),
+ }
+ for f in top
+ ],
+ ),
+ {
+ "timings_void": True,
+ "active": True,
+ "note": (
+ "precise coverage disables TurboFan and Maglev isolate-wide; "
+ "no duration from this cell may be quoted"
+ ),
+ },
+ )
+ # The boundary guard. A float here would be a category error, not a
+ # rounding problem, so it raises rather than warns.
+ assert_integers_only(
+ {
+ k: v
+ for k, v in payload.items()
+ if k in ("total_calls", "functions_invoked", "top_functions")
+ }
+ )
+ except Exception as exc: # noqa: BLE001
+ payload = merge(
+ unmeasured("total_calls", f"{type(exc).__name__}: {exc}"),
+ {"timings_void": True, "active": True},
+ )
+ self._windows += 1
+ self._overhead_ms += (time.perf_counter() - t0) * 1000.0
+ assert_no_bare_zero(payload, "coverage")
+ return payload
+
+ def end_cell(self, cell: Any) -> dict | None:
+ if self.cov is not None:
+ try:
+ self.cov.stop()
+ except Exception:
+ pass
+ self.cov = None
+ out = merge(
+ measured("overhead_ms", round(self._overhead_ms, 3)),
+ measured("windows_counted", self._windows),
+ {"timings_void": True, "headline_safe": False},
+ {"start_reason": self._start_reason} if self._start_reason else {},
+ )
+ assert_no_bare_zero(out, "coverage.end_cell")
+ return out
+
+ def detach(self) -> None:
+ if self.cov is not None:
+ try:
+ self.cov.stop()
+ except Exception:
+ pass
+ self.cov = None
+
+
+@register_instrument(name = "coverage", level = 3)
+def _make_coverage() -> CoverageInstrument:
+ return CoverageInstrument()
diff --git a/tests/studio/studiobench/instruments/cpuprofile.py b/tests/studio/studiobench/instruments/cpuprofile.py
new file mode 100644
index 00000000000..a1553291c51
--- /dev/null
+++ b/tests/studio/studiobench/instruments/cpuprofile.py
@@ -0,0 +1,378 @@
+# 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 V8 CPU profiler, both ways round.
+
+There are two routes to sampled stacks and they are not interchangeable:
+
+* IN-TRACE (`disabled-by-default-v8.cpu_profiler`). Samples arrive as
+ `Profile` / `ProfileChunk` events on the SAME timeline as `RunTask`,
+ `TimerFire` and `EventDispatch`, on one clock. That is what lets a sample be
+ attributed to a classified task, which is the entire naming pipeline. This is
+ the route `instruments/tracing.py` at L2 takes, and it is the default.
+
+* STANDALONE (`Profiler.start` / `Profiler.stop`). One self-contained profile,
+ no trace, no task tree. Useful as a cross-check on the in-trace parser and as
+ a cheap way to get stacks when a full trace would overflow its buffer, but the
+ samples cannot be joined to task origins.
+
+`Profiler.setSamplingInterval` is in MICROSECONDS and must be set BEFORE
+`Profiler.start`; setting it on a running profiler is silently ignored, which
+looks exactly like the interval you asked for being unavailable.
+
+The cross-check `compare_with_trace_profile` exists because the in-trace parser
+is the load-bearing piece of this layer and it has several ways to be quietly
+wrong (incremental nodes, deltas on a sibling key, chunks on the profiler's own
+thread). Two independent extractions agreeing is worth having.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+from ..analysis import CellFailure
+from ..analysis.cpuprofile import CallFrame, CpuProfile, Sample
+
+# V8's own default is 1000 us. 100 us resolves a sub-millisecond frame without
+# the sampler itself becoming the workload.
+DEFAULT_SAMPLING_INTERVAL_US = 100
+
+# Minimum non-synthetic samples on BOTH sides before the two extraction routes
+# may be declared to agree or disagree.
+MIN_JS_SAMPLES_FOR_COMPARISON = 200
+
+
+@dataclass
+class StandaloneProfiler:
+ """`Profiler.start` / `Profiler.stop` over one CDP session."""
+
+ cdp: Any
+ sampling_interval_us: int = DEFAULT_SAMPLING_INTERVAL_US
+ _running: bool = field(default = False, init = False)
+
+ def start(self) -> None:
+ if self._running:
+ raise RuntimeError("StandaloneProfiler.start called twice")
+ self.cdp.send("Profiler.enable")
+ # Order matters: the interval is latched at start.
+ self.cdp.send("Profiler.setSamplingInterval", {"interval": int(self.sampling_interval_us)})
+ self.cdp.send("Profiler.start")
+ self._running = True
+
+ def stop(self) -> CpuProfile:
+ if not self._running:
+ raise RuntimeError("StandaloneProfiler.stop without start")
+ res = self.cdp.send("Profiler.stop")
+ self._running = False
+ return from_profiler_result(res.get("profile") or {})
+
+ def __enter__(self) -> "StandaloneProfiler":
+ self.start()
+ return self
+
+ def __exit__(self, *exc: Any) -> None:
+ if self._running:
+ try:
+ self.cdp.send("Profiler.stop")
+ finally:
+ self._running = False
+
+
+def from_profiler_result(raw: dict[str, Any]) -> CpuProfile:
+ """Adapt a `Profiler.stop` payload into the same object the trace path yields.
+
+ The standalone payload is the complete profile in one piece: `nodes` is the
+ full node list, `samples` and `timeDeltas` are flat arrays, and `startTime`
+ and `endTime` are microseconds. Reusing `CpuProfile` means every aggregation
+ and every gate in `analysis/cpuprofile.py` applies unchanged to both routes,
+ so the cross-check compares the same arithmetic on two inputs.
+ """
+ nodes = raw.get("nodes")
+ if not nodes:
+ raise CellFailure("cpuprofile_empty", "Profiler.stop returned a profile with no nodes")
+ prof = CpuProfile(pid = 0, tid = 0, start_time = int(raw.get("startTime", 0)))
+ for n in nodes:
+ nid = int(n["id"])
+ cf = n.get("callFrame") or {}
+ prof.nodes[nid] = CallFrame(
+ function_name = str(cf.get("functionName", "")),
+ script_id = str(cf.get("scriptId", "")),
+ url = str(cf.get("url", "")),
+ line = int(cf.get("lineNumber", -1)),
+ column = int(cf.get("columnNumber", -1)),
+ )
+ for child in n.get("children") or ():
+ prof.parents[int(child)] = nid
+
+ samples = raw.get("samples") or []
+ deltas = raw.get("timeDeltas") or []
+ if len(samples) != len(deltas):
+ raise CellFailure(
+ "cpuprofile_ragged",
+ f"{len(samples)} samples against {len(deltas)} timeDeltas",
+ )
+ cursor = prof.start_time
+ for nid, d in zip(samples, deltas):
+ d = int(d)
+ if d < 0:
+ prof.negative_deltas += 1
+ cursor += d
+ prof.samples.append(Sample(ts = cursor, node_id = int(nid), delta = d))
+
+ prof.chunk_count = 1
+ prof.chunk_ts_first = prof.start_time
+ prof.chunk_ts_last = int(raw.get("endTime", cursor))
+ return prof
+
+
+def compare_with_trace_profile(
+ standalone: CpuProfile,
+ in_trace: CpuProfile,
+ *,
+ tolerance: float = 0.25,
+) -> dict[str, Any]:
+ """Do the two extraction routes agree on where the time went?
+
+ Compared on the SHARE of JS self time per frame, not on absolute
+ microseconds, because the two profiles cover different windows and different
+ sampling intervals. A large disagreement means one of the two parsers is
+ wrong, and since the in-trace one is the one this layer depends on, that is
+ a finding and not a warning.
+ """
+
+ def shares(p: CpuProfile) -> dict[str, float]:
+ by_name: dict[str, int] = {}
+ for s in p.samples:
+ f = p.nodes.get(s.node_id)
+ if f is None or f.is_synthetic:
+ continue
+ by_name[f.function_name or "(anonymous)"] = (
+ by_name.get(f.function_name or "(anonymous)", 0) + s.delta
+ )
+ total = sum(by_name.values())
+ if total <= 0:
+ return {}
+ return {k: v / total for k, v in by_name.items()}
+
+ def js_samples(p: CpuProfile) -> int:
+ return sum(
+ 1 for s in p.samples if (f := p.nodes.get(s.node_id)) is not None and not f.is_synthetic
+ )
+
+ # A comparison built on a handful of JS samples cannot distinguish the two
+ # parsers from sampling noise. Saying "agrees" there would be worse than
+ # useless and saying "disagrees" is a false alarm, so it declines to rule.
+ # V8 has ONE CpuProfiler. If the trace carried the profiler categories, the
+ # "standalone" profile IS the in-trace profile and comparing them is
+ # comparing a thing with itself, which always agrees and therefore proves
+ # nothing. Detected structurally rather than trusted to the caller.
+ if (
+ len(standalone.samples) == len(in_trace.samples)
+ and len(standalone.nodes) == len(in_trace.nodes)
+ and standalone.samples[:8]
+ and in_trace.samples[:8]
+ and [s.node_id for s in standalone.samples[:8]] == [s.node_id for s in in_trace.samples[:8]]
+ ):
+ return {
+ "agrees": None,
+ "verdict": "same_profile",
+ "reason": (
+ "both profiles have identical sample and node counts and identical leading "
+ "samples. V8 has a single CpuProfiler, so a Profiler.start taken while the "
+ "trace already records disabled-by-default-v8.cpu_profiler returns the same "
+ "samples. This is a comparison against itself and is not evidence."
+ ),
+ }
+
+ power = {
+ "standalone_js_samples": js_samples(standalone),
+ "in_trace_js_samples": js_samples(in_trace),
+ }
+ if min(power.values()) < MIN_JS_SAMPLES_FOR_COMPARISON:
+ return {
+ "agrees": None,
+ "verdict": "underpowered",
+ "reason": (
+ f"need at least {MIN_JS_SAMPLES_FOR_COMPARISON} non-synthetic samples on both "
+ f"sides; got {power}. Lengthen the window or enable the hires CPU profiler category."
+ ),
+ **power,
+ }
+
+ a, b = shares(standalone), shares(in_trace)
+ common = sorted(set(a) & set(b), key = lambda k: -(a[k] + b[k]))[:10]
+ rows = [
+ {
+ "function": k,
+ "standalone_share": round(a[k], 4),
+ "in_trace_share": round(b[k], 4),
+ "abs_diff": round(abs(a[k] - b[k]), 4),
+ }
+ for k in common
+ ]
+ worst = max((r["abs_diff"] for r in rows), default = 0.0)
+ return {
+ "compared_frames": len(common),
+ "worst_share_difference": worst,
+ "tolerance": tolerance,
+ "agrees": worst <= tolerance,
+ "rows": rows,
+ }
+
+
+# ═══════════════════════════════════════════════════════════════════════════
+# Harness adapter (INTERFACES.md section 3)
+# ═══════════════════════════════════════════════════════════════════════════
+#
+# MEASURED, NOT ASSUMED, and it changed this design: V8 HAS ONE CPU PROFILER.
+# Starting `Profiler.start` while a trace with `disabled-by-default-v8.cpu_profiler`
+# is already running returns THE SAME SAMPLES. On a real capture both routes
+# reported identical counts, 2169 samples over 17 nodes, because the inspector
+# profiler and the tracing profiler share one `CpuProfiler` on the isolate.
+#
+# Two consequences, both load-bearing:
+#
+# 1. `compare_with_trace_profile` must refuse to compare a profile with
+# itself. A cross-check that can never fail is worse than no cross-check,
+# because it reads as corroboration.
+# 2. This instrument is only meaningful at instrument level 1, where the trace
+# carries NO profiler categories. There it is a genuine capability: stacks
+# without the ProfileChunk volume that dominates an L2 trace buffer. A real
+# L1 capture confirmed the two clocks agree, with 1748 of 1748 standalone
+# samples landing inside the trace's own `RunTask` span, so its samples can
+# still be joined to classified task windows.
+#
+# At level 2 and above it stands down and says so, rather than quietly
+# duplicating what `tracing` already has.
+
+import time # noqa: E402
+
+from ..analysis import assert_no_bare_zero, measured, merge, unmeasured # noqa: E402
+from . import register_instrument # noqa: E402
+
+_STAND_DOWN = (
+ "instrument level {lvl} already records the v8 CPU profiler inside the trace. "
+ "V8 has a single CpuProfiler, so a second Profiler.start returns the same "
+ "samples; running it here would double the cost and produce a cross-check "
+ "against itself."
+)
+
+
+class CpuProfileInstrument:
+ """Standalone V8 sampling, for the level where the trace has no stacks."""
+
+ name = "cpu_profile"
+ level = 1
+
+ def __init__(self) -> None:
+ self.ctx: Any = None
+ self.cdp: Any = None
+ self.active = False
+ self.stand_down_reason = ""
+ self.profiler: StandaloneProfiler | None = None
+ self._overhead_ms = 0.0
+ self._windows = 0
+
+ def attach(self, ctx: Any) -> None:
+ self.ctx = ctx
+
+ def start_cell(self, cell: Any) -> None:
+ self.cdp = getattr(self.ctx, "cdp", None)
+ self._overhead_ms = 0.0
+ self._windows = 0
+ lvl = int(getattr(cell, "instrument_level", 1) or 1)
+ self.active = lvl == 1 and self.cdp is not None
+ if lvl != 1:
+ self.stand_down_reason = _STAND_DOWN.format(lvl = lvl)
+ elif self.cdp is None:
+ self.stand_down_reason = "no CDP session; the V8 profiler is Chromium only"
+ else:
+ self.stand_down_reason = ""
+
+ def open(self, window: Any) -> None:
+ if not self.active:
+ return
+ t0 = time.perf_counter()
+ self.profiler = StandaloneProfiler(self.cdp)
+ try:
+ self.profiler.start()
+ except Exception:
+ self.profiler = None
+ self._overhead_ms += (time.perf_counter() - t0) * 1000.0
+
+ def close(self, window: Any) -> dict | None:
+ if not self.active:
+ return merge(
+ unmeasured("self_ms_top", self.stand_down_reason or "instrument inactive"),
+ {"active": False},
+ )
+ if self.profiler is None:
+ return merge(
+ unmeasured("self_ms_top", "Profiler.start failed for this window"),
+ {"active": True},
+ )
+ t0 = time.perf_counter()
+ try:
+ prof = self.profiler.stop()
+ payload = self._summarise(prof)
+ except CellFailure as exc:
+ payload = merge(
+ unmeasured("self_ms_top", f"{exc.gate}: {exc.detail}"), {"active": True}
+ )
+ except Exception as exc: # noqa: BLE001
+ payload = merge(
+ unmeasured("self_ms_top", f"{type(exc).__name__}: {exc}"), {"active": True}
+ )
+ finally:
+ self.profiler = None
+ self._windows += 1
+ self._overhead_ms += (time.perf_counter() - t0) * 1000.0
+ assert_no_bare_zero(payload, "cpu_profile")
+ return payload
+
+ def end_cell(self, cell: Any) -> dict | None:
+ out = merge(
+ measured("overhead_ms", round(self._overhead_ms, 3)),
+ measured("windows_profiled", self._windows),
+ {"active": self.active},
+ {"stand_down_reason": self.stand_down_reason} if self.stand_down_reason else {},
+ )
+ assert_no_bare_zero(out, "cpu_profile.end_cell")
+ return out
+
+ def detach(self) -> None:
+ if self.profiler is not None:
+ try:
+ self.profiler.stop()
+ except Exception:
+ pass
+ self.profiler = None
+
+ def _summarise(self, prof: Any) -> dict:
+ from ..analysis import cpuprofile as C
+
+ rows, diag = C.self_time_in_windows(
+ prof,
+ [(prof.chunk_ts_first, prof.chunk_ts_last)],
+ limit = 12,
+ )
+ payload = merge(
+ measured(
+ "self_ms_top",
+ [{"frame": f.label(), "self_ms": round(us / 1000.0, 3)} for f, us in rows],
+ ),
+ measured("js_sample_count", int(diag["js_sample_count"])),
+ measured("sampling_interval_us", round(prof.sampling_interval_us(), 2)),
+ {
+ "active": True,
+ "frame_ranking_underpowered": bool(diag["underpowered"]),
+ "profiler": "standalone",
+ },
+ )
+ return payload
+
+
+@register_instrument(name = "cpu_profile", level = 1)
+def _make_cpu_profile() -> CpuProfileInstrument:
+ return CpuProfileInstrument()
diff --git a/tests/studio/studiobench/instruments/frames.js b/tests/studio/studiobench/instruments/frames.js
new file mode 100644
index 00000000000..013586c2c00
--- /dev/null
+++ b/tests/studio/studiobench/instruments/frames.js
@@ -0,0 +1,255 @@
+// 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 frame recorder. Installed as an init script before any app code runs.
+//
+// SALVAGED from playwright_reasoning_pane.py's RECORDER_INIT, with the two things that version
+// got right kept exactly and the one thing it got wrong fixed.
+//
+// KEPT: ONE self-rescheduling rAF loop as the frame counter, and requestAnimationFrame is NOT
+// wrapped. A wrapper that increments per callback counts the page's frame once for the loop and
+// once more for every rAF the app happened to schedule in that frame, so the reported frame rate
+// RISES with how busy the app is. The first version of that file reported 888 fps on a 60Hz page
+// for exactly this reason, which is not a small error, it is the metric inverted.
+//
+// KEPT: blocked time from a 1ms setTimeout, not a MessageChannel ping-pong. The MessageChannel
+// version ticks about 150,000 times a second and halves Firefox's frame rate before any app code
+// runs. This ticks about 150 times a second and costs nothing on any engine. Blocked time is the
+// column that MOVES WHEN FPS DOES NOT: a page with 65% idle still paints every frame on time, so
+// fps stays pinned at 60 while the work per chunk quietly triples.
+//
+// FIXED: the clamp is calibrated during an ENFORCED IDLE WINDOW that the driver opens, not from
+// the first 60 ticks of whatever the page was doing. `setTimeout(fn, 1)` has a floor of about 4ms
+// by spec, the real floor differs by engine and build, and blocked time is a SUBTRACTION against
+// it -- so a wrong clamp invents block on one engine and hides it on another. Calibrating from
+// the first 60 ticks means calibrating while the app is booting, or worse, on a rung where 31,637
+// elements are already standing and the "idle" floor is really the app's own steady-state load.
+// That produces a clamp far above 4ms, which then subtracts real block out of every window and
+// reports a page pinned at 100% busy as 0.2% busy.
+//
+// And when the calibrated clamp comes out ABOVE 10ms, the answer is not a number. A 10ms floor
+// under a 1ms timer means the machine could not answer an idle timer promptly, so nothing was
+// idle and there is no floor to subtract. busy_pct is then null with a reason, never 0.2%.
+
+(() => {
+ if (window.__sb && window.__sb.frames) return;
+ const nativeRaf = window.requestAnimationFrame.bind(window);
+ window.__sbNativeRaf = nativeRaf;
+ window.__sb = window.__sb || {};
+
+ const MAX_CLAMP_MS = 10.0;
+ const CALIBRATION_TICKS = 60;
+ // A window long enough to exceed this is minutes of 60 Hz, which no slot in the scene is. The
+ // cap exists so a pathological window cannot balloon the payload, not as a routine path.
+ const GAPS_CAP = 50000;
+
+ const R = {
+ frames: 0,
+ frameGaps: [],
+ maxLagMs: 0,
+ lagTicks: 0,
+ lagSumMs: 0,
+ blockedMs: 0,
+ // The same blocked time again, NEVER reset. `blockedMs` is drained by the window reader, and
+ // a settle watch has to read blocked time on its own cadence while that reader is running.
+ // Two readers draining one accumulator would each see a fraction of the block.
+ blockedTotalMs: 0,
+ clampMs: null,
+ clampReason: "not calibrated",
+ clampSamples: 0,
+ calibrating: false,
+ calibration: [],
+ longTaskSupported: Boolean(
+ (PerformanceObserver.supportedEntryTypes || []).includes("longtask"),
+ ),
+ longTasks: 0,
+ longTaskMs: 0,
+ // Every rAF the APP schedules, counted separately from the loop's own. Not a frame rate; it
+ // is how the tri-clock check tells "the page is idle" from "the loop is starved".
+ appRafs: 0,
+ };
+
+ let lastFrame = performance.now();
+ const frame = () => {
+ const now = performance.now();
+ R.frames += 1;
+ R.frameGaps.push(now - lastFrame);
+ lastFrame = now;
+ nativeRaf(frame);
+ };
+ nativeRaf(frame);
+
+ // Count the app's own rAF traffic without pumping it. A pass-through wrapper is safe here
+ // BECAUSE it is not the frame counter: the loop above is.
+ window.requestAnimationFrame = function (cb) {
+ R.appRafs += 1;
+ return nativeRaf(cb);
+ };
+
+ let lastTick = performance.now();
+ const tick = () => {
+ const now = performance.now();
+ const gap = now - lastTick;
+ lastTick = now;
+ if (R.calibrating) {
+ R.calibration.push(gap);
+ } else if (R.clampMs !== null) {
+ R.lagTicks += 1;
+ R.lagSumMs += gap;
+ const over = Math.max(0, gap - R.clampMs);
+ R.blockedMs += over;
+ R.blockedTotalMs += over;
+ if (gap > R.maxLagMs) R.maxLagMs = gap;
+ }
+ setTimeout(tick, 1);
+ };
+ setTimeout(tick, 1);
+
+ if (R.longTaskSupported) {
+ try {
+ new PerformanceObserver((list) => {
+ for (const e of list.getEntries()) {
+ R.longTasks += 1;
+ R.longTaskMs += e.duration;
+ }
+ }).observe({ type: "longtask", buffered: false });
+ } catch (e) {
+ R.longTaskSupported = false;
+ }
+ }
+
+ const quantile = (sorted, q) =>
+ sorted.length === 0 ? null : sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * q))];
+
+ window.__sb.frames = {
+ // Opened by the driver during an ENFORCED IDLE WINDOW: nothing streaming, no action running,
+ // the page at rest. Returns what it measured so the driver can record it rather than trust it.
+ beginCalibration() {
+ R.calibrating = true;
+ R.calibration = [];
+ return { ticks: CALIBRATION_TICKS };
+ },
+ endCalibration() {
+ R.calibrating = false;
+ const samples = R.calibration.slice().sort((a, b) => a - b);
+ R.clampSamples = samples.length;
+ if (samples.length < 10) {
+ R.clampMs = null;
+ R.clampReason =
+ "the idle window produced " + samples.length + " timer ticks, too few to find a floor";
+ return { clampMs: null, reason: R.clampReason, samples: samples.length };
+ }
+ const median = samples[Math.floor(samples.length / 2)];
+ if (median > MAX_CLAMP_MS) {
+ // NOT a clamp. A 1ms timer that takes longer than 10ms to come back on an idle page means
+ // the page was not idle, so there is no floor here to subtract and every blocked-time
+ // figure derived from it would be a subtraction against the app's own steady load.
+ R.clampMs = null;
+ R.clampReason =
+ "the calibrated timer clamp came out at " +
+ median.toFixed(2) +
+ "ms, above the " +
+ MAX_CLAMP_MS +
+ "ms ceiling: the page was not idle during calibration, so there is no floor to subtract";
+ return { clampMs: null, reason: R.clampReason, median, samples: samples.length };
+ }
+ R.clampMs = median;
+ R.clampReason = "calibrated";
+ return {
+ clampMs: median,
+ reason: "calibrated",
+ samples: samples.length,
+ p05: quantile(samples, 0.05),
+ p95: quantile(samples, 0.95),
+ };
+ },
+
+ reset() {
+ R.frames = 0;
+ R.frameGaps = [];
+ R.maxLagMs = 0;
+ R.lagTicks = 0;
+ R.lagSumMs = 0;
+ R.blockedMs = 0;
+ R.longTasks = 0;
+ R.longTaskMs = 0;
+ R.appRafs = 0;
+ return performance.now();
+ },
+
+ // Drain the window. `elapsedMs` is the DRIVER's measure of the window, passed in rather than
+ // computed here, so fps is per real elapsed time even when the page could not run its own
+ // clock reads promptly.
+ read(elapsedMs) {
+ const gaps = R.frameGaps.slice().sort((a, b) => a - b);
+ let over33 = 0;
+ for (const g of gaps) if (g > 33) over33 += 1;
+ const elapsed = elapsedMs && elapsedMs > 0 ? elapsedMs : null;
+ const out = {
+ frames: R.frames,
+ frames_attempted: true,
+ app_rafs: R.appRafs,
+ fps: elapsed === null ? null : Math.round((R.frames / (elapsed / 1000)) * 10) / 10,
+ frames_over_33: over33,
+ // As a SHARE of the frames observed, because the denominator is not fixed: headless
+ // Chromium has no vsync and runs the loop as fast as it can, so a raw count is not
+ // comparable across engines or loads.
+ frames_over_33_pct:
+ gaps.length === 0 ? null : Math.round((over33 / gaps.length) * 1000) / 10,
+ p50_frame_ms: quantile(gaps, 0.5),
+ p95_frame_ms: quantile(gaps, 0.95),
+ // The RAW deltas, not only the summary. time_in_jank_pct and jank_index are defined over
+ // the whole distribution (a share of wall time, and a sum of squared over-budget time),
+ // and neither can be recovered from percentiles. Without this the scoring layer has to
+ // either skip two of its six metrics or invent them from p95, which is the kind of
+ // plausible-but-unfounded number this tool exists to refuse.
+ // `gaps` is sorted ASCENDING, so a head slice would drop exactly the janky frames and
+ // score a stuttering window as clean. Over the cap this emits null and says why: the
+ // scoring layer then reads "failed", not a number built from the fastest frames.
+ frame_gaps_ms:
+ gaps.length > GAPS_CAP ? null : gaps.map((g) => Math.round(g * 10) / 10),
+ frame_gaps_truncated: gaps.length > GAPS_CAP,
+ frame_gaps_total: gaps.length,
+ max_frame_ms: gaps.length === 0 ? null : gaps[gaps.length - 1],
+ max_lag_ms: Math.round(R.maxLagMs * 10) / 10,
+ lag_ticks: R.lagTicks,
+ mean_lag_ms: R.lagTicks === 0 ? null : Math.round((R.lagSumMs / R.lagTicks) * 10) / 10,
+ clamp_ms: R.clampMs === null ? null : Math.round(R.clampMs * 100) / 100,
+ clamp_reason: R.clampReason,
+ long_tasks: R.longTaskSupported ? R.longTasks : null,
+ long_task_ms: R.longTaskSupported ? Math.round(R.longTaskMs) : null,
+ // The point of the flag: without it an engine with no Long Tasks API reports zero jank in
+ // exactly the same shape as an engine that had none.
+ long_task_supported: R.longTaskSupported,
+ };
+ if (R.clampMs === null) {
+ out.busy_pct = null;
+ out.busy_pct_reason = R.clampReason;
+ out.blocked_ms = null;
+ } else if (elapsed === null) {
+ out.busy_pct = null;
+ out.busy_pct_reason = "the driver reported no elapsed time for this window";
+ out.blocked_ms = Math.round(R.blockedMs * 10) / 10;
+ } else {
+ out.blocked_ms = Math.round(R.blockedMs * 10) / 10;
+ out.busy_pct = Math.round((R.blockedMs / elapsed) * 1000) / 10;
+ out.busy_pct_reason = null;
+ }
+ this.reset();
+ return out;
+ },
+
+ // For the settle watch and anything else that needs blocked time without draining the window.
+ blockedTotalMs() {
+ return R.blockedTotalMs;
+ },
+ clamp() {
+ return { clampMs: R.clampMs, reason: R.clampReason, samples: R.clampSamples };
+ },
+ };
+
+ // Two rAFs: the second is the frame that has PAINTED the first's work. Every action's timing
+ // that is clocked across a paint uses this, so the paint floor is one shared constant.
+ window.__sbNextPaint = () =>
+ new Promise((resolve) => nativeRaf(() => nativeRaf(() => resolve(performance.now()))));
+})();
diff --git a/tests/studio/studiobench/instruments/glass.js b/tests/studio/studiobench/instruments/glass.js
new file mode 100644
index 00000000000..7931139e23b
--- /dev/null
+++ b/tests/studio/studiobench/instruments/glass.js
@@ -0,0 +1,156 @@
+// 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 glass: instrumented accessors that turn "the autoscroll observer forces a synchronous
+// layout on every streamed character" from a reading of the source into a counted, timed number.
+//
+// This is the direct instrument for M3. `use-intent-aware-autoscroll.tsx` installs a
+// MutationObserver with `subtree: true, characterData: true` over the whole viewport; its callback
+// synchronously reads `scrollHeight` (stabilize(), :435), writes the inherited custom property
+// `--aui-scroll-stabilizer` on the scroll container (:466), which invalidates style for every
+// descendant, and calls `scrollTo` (:487). All three are invisible to a React Profiler, to
+// markdown timing and to a DOM node census. They are visible HERE.
+//
+// PERTURBING BY CONSTRUCTION, and so off at level 0. Wrapping a hot getter on Element.prototype
+// costs something on every call site in the app, not only the ones under suspicion, and the
+// wrapper's own `performance.now()` pair is a large fraction of a cheap read. Level 1 and above,
+// and the headline numbers come from level 0, where none of this is installed.
+//
+// Split by WHOSE read it is. "Layout was forced 4,000 times" is not attribution; "3,980 of them
+// were on the scroll viewport, from inside a MutationObserver callback" is.
+
+(() => {
+ if (window.__sb && window.__sb.glass) return;
+ window.__sb = window.__sb || {};
+
+ const I = {
+ scroll_height_reads: 0,
+ scroll_height_ms: 0,
+ viewport_reads: 0,
+ viewport_ms: 0,
+ // Reads taken while a MutationObserver callback is on the stack. This is the number that
+ // separates "the app reads scrollHeight" from "the app reads scrollHeight per mutation".
+ reads_in_observer: 0,
+ reads_in_observer_ms: 0,
+ scroll_top_writes: 0,
+ viewport_scroll_top_writes: 0,
+ scroll_to_calls: 0,
+ // The stabilizer property write at :466. Setting an inherited custom property on the scroll
+ // container invalidates style for every descendant, so its COUNT is the multiplier on a
+ // whole-thread style recalc.
+ stabilizer_writes: 0,
+ custom_property_writes: 0,
+ mutation_callbacks: 0,
+ mutation_records: 0,
+ character_data_records: 0,
+ observers_created: 0,
+ subtree_observers: 0,
+ };
+ let inObserver = 0;
+
+ const isViewport = (el) => {
+ try {
+ return Boolean(el && el.classList && el.classList.contains("aui-thread-viewport"));
+ } catch (e) {
+ return false;
+ }
+ };
+
+ const sh = Object.getOwnPropertyDescriptor(Element.prototype, "scrollHeight");
+ if (sh && sh.get) {
+ Object.defineProperty(Element.prototype, "scrollHeight", {
+ configurable: true,
+ enumerable: sh.enumerable,
+ get() {
+ const t0 = performance.now();
+ const v = sh.get.call(this);
+ const dt = performance.now() - t0;
+ I.scroll_height_reads += 1;
+ I.scroll_height_ms += dt;
+ if (isViewport(this)) {
+ I.viewport_reads += 1;
+ I.viewport_ms += dt;
+ }
+ if (inObserver > 0) {
+ I.reads_in_observer += 1;
+ I.reads_in_observer_ms += dt;
+ }
+ return v;
+ },
+ });
+ }
+
+ const st = Object.getOwnPropertyDescriptor(Element.prototype, "scrollTop");
+ if (st && st.set) {
+ Object.defineProperty(Element.prototype, "scrollTop", {
+ configurable: true,
+ enumerable: st.enumerable,
+ get() {
+ return st.get.call(this);
+ },
+ set(value) {
+ I.scroll_top_writes += 1;
+ if (isViewport(this)) I.viewport_scroll_top_writes += 1;
+ st.set.call(this, value);
+ },
+ });
+ }
+
+ const nativeScrollTo = Element.prototype.scrollTo;
+ if (nativeScrollTo) {
+ Element.prototype.scrollTo = function (...args) {
+ I.scroll_to_calls += 1;
+ return nativeScrollTo.apply(this, args);
+ };
+ }
+
+ // The custom-property write at use-intent-aware-autoscroll.tsx:466.
+ const nativeSetProperty = CSSStyleDeclaration.prototype.setProperty;
+ if (nativeSetProperty) {
+ CSSStyleDeclaration.prototype.setProperty = function (name, value, priority) {
+ if (typeof name === "string" && name.charCodeAt(0) === 45 /* '-' */) {
+ I.custom_property_writes += 1;
+ if (name.indexOf("aui-scroll-stabilizer") >= 0) I.stabilizer_writes += 1;
+ }
+ return nativeSetProperty.call(this, name, value, priority);
+ };
+ }
+
+ const NativeMO = window.MutationObserver;
+ if (NativeMO) {
+ const Wrapped = function (callback) {
+ I.observers_created += 1;
+ const observer = new NativeMO((records, obs) => {
+ I.mutation_callbacks += 1;
+ I.mutation_records += records.length;
+ for (const r of records) if (r.type === "characterData") I.character_data_records += 1;
+ inObserver += 1;
+ try {
+ return callback(records, obs);
+ } finally {
+ inObserver -= 1;
+ }
+ });
+ const nativeObserve = observer.observe.bind(observer);
+ observer.observe = (target, options) => {
+ if (options && options.subtree) I.subtree_observers += 1;
+ return nativeObserve(target, options);
+ };
+ return observer;
+ };
+ Wrapped.prototype = NativeMO.prototype;
+ window.MutationObserver = Wrapped;
+ }
+
+ window.__sb.glass = {
+ read() {
+ const out = {};
+ for (const k of Object.keys(I)) {
+ out[k] = k.endsWith("_ms") ? Math.round(I[k] * 100) / 100 : I[k];
+ I[k] = 0;
+ }
+ out.glass_attempted = true;
+ return out;
+ },
+ };
+})();
diff --git a/tests/studio/studiobench/instruments/heap.py b/tests/studio/studiobench/instruments/heap.py
new file mode 100644
index 00000000000..28c82dd6506
--- /dev/null
+++ b/tests/studio/studiobench/instruments/heap.py
@@ -0,0 +1,386 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Sampling heap profiler, configured to see TRANSIENT garbage.
+
+`HeapProfiler.startSampling` with `includeObjectsCollectedByMajorGC: true`. That
+flag is load-bearing, not a nicety. Without it the returned profile contains
+only objects that SURVIVED, and the hypothesis under test is the opposite: that
+one work-in-progress fiber is cloned per sibling per render, allocated in a
+burst and collected almost entirely at the next major GC. A survivors-only
+profile of that mechanism is empty, and an empty profile reads as "no allocation
+here", which is the exact wrong conclusion.
+
+So the flag is REQUIRED. If the browser rejects it, this module raises rather
+than retrying without it, because a quiet fallback would turn a missing
+capability into a false negative and nothing downstream could tell.
+
+The shape that confirms M1 is: allocation total proportional to sibling count,
+attributed to a react-dom frame, with near-zero survival past a forced major GC.
+`survival_ratio()` measures exactly that by taking a second profile after
+`HeapProfiler.collectGarbage`.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Iterable
+
+from ..analysis import CellFailure
+
+# 4096 bytes between samples. Small enough to resolve a per-sibling allocation
+# at a few hundred siblings, large enough not to perturb the allocation path.
+DEFAULT_SAMPLING_INTERVAL = 4096
+
+# `includeObjectsCollectedByMajorGC` / `MinorGC` landed in V8 10.8, which
+# shipped in Chrome 108. Below that the parameter is accepted and ignored.
+MIN_CHROME_FOR_GC_FLAGS = 108
+
+
+@dataclass(frozen = True)
+class HeapFrame:
+ function_name: str
+ url: str
+ line: int
+ column: int
+ script_id: str = ""
+
+ def label(self) -> str:
+ return f"{self.function_name or '(anonymous)'} @ {self.url or 'script#' + self.script_id}:{self.line}:{self.column}"
+
+ @property
+ def key(self) -> tuple[str, str, int, int]:
+ return (self.function_name, self.url, self.line, self.column)
+
+
+@dataclass
+class HeapProfile:
+ """Flattened sampling profile: bytes attributed to allocation sites."""
+
+ self_bytes: dict[tuple[str, str, int, int], int] = field(default_factory = dict)
+ frames: dict[tuple[str, str, int, int], HeapFrame] = field(default_factory = dict)
+ total_bytes: int = 0
+ sample_count: int = 0
+ included_major_gc: bool = False
+
+ def top(self, limit: int = 30) -> list[tuple[HeapFrame, int]]:
+ rows = [(self.frames[k], v) for k, v in self.self_bytes.items() if k in self.frames]
+ rows.sort(key = lambda r: -r[1])
+ return rows[:limit]
+
+ def bytes_matching(self, needles: Iterable[str]) -> int:
+ needles = tuple(needles)
+ total = 0
+ for key, size in self.self_bytes.items():
+ frame = self.frames.get(key)
+ if frame and any(n in frame.function_name or n in frame.url for n in needles):
+ total += size
+ return total
+
+ def summary(self) -> dict[str, Any]:
+ return {
+ "total_bytes": self.total_bytes,
+ "sample_count": self.sample_count,
+ "distinct_sites": len(self.self_bytes),
+ "included_objects_collected_by_major_gc": self.included_major_gc,
+ }
+
+
+def _flatten(node: dict[str, Any], profile: HeapProfile) -> None:
+ cf = node.get("callFrame") or {}
+ frame = HeapFrame(
+ function_name = str(cf.get("functionName", "")),
+ url = str(cf.get("url", "")),
+ line = int(cf.get("lineNumber", -1)),
+ column = int(cf.get("columnNumber", -1)),
+ script_id = str(cf.get("scriptId", "")),
+ )
+ size = int(node.get("selfSize", 0) or 0)
+ if size:
+ profile.frames.setdefault(frame.key, frame)
+ profile.self_bytes[frame.key] = profile.self_bytes.get(frame.key, 0) + size
+ profile.total_bytes += size
+ for child in node.get("children") or ():
+ _flatten(child, profile)
+
+
+class SamplingHeapProfiler:
+ def __init__(
+ self,
+ cdp: Any,
+ *,
+ sampling_interval: int = DEFAULT_SAMPLING_INTERVAL,
+ include_major_gc: bool = True,
+ include_minor_gc: bool = False,
+ ) -> None:
+ self.cdp = cdp
+ self.sampling_interval = int(sampling_interval)
+ self.include_major_gc = bool(include_major_gc)
+ self.include_minor_gc = bool(include_minor_gc)
+ self._running = False
+
+ def assert_gc_flags_supported(self) -> int:
+ """Check the browser is new enough for the GC-inclusion flags.
+
+ THIS CANNOT BE FEATURE-DETECTED BY CATCHING AN ERROR. V8's inspector
+ silently ignores unknown parameters to `HeapProfiler.startSampling`, so
+ an old browser accepts `includeObjectsCollectedByMajorGC` with a cheerful
+ empty success result and then hands back a survivors-only profile. The
+ flag would appear to work and the answer would be wrong in the exact
+ direction that hides the hypothesis. So the check is on the version:
+ the flags landed in V8 10.8, which shipped in Chrome 108.
+ """
+ version = self.cdp.send("Browser.getVersion") or {}
+ product = str(version.get("product", ""))
+ major = 0
+ for part in product.split("/")[-1].split("."):
+ if part.isdigit():
+ major = int(part)
+ break
+ if major and major < MIN_CHROME_FOR_GC_FLAGS:
+ raise CellFailure(
+ "heap_gc_flag_unsupported",
+ f"{product} is older than Chrome {MIN_CHROME_FOR_GC_FLAGS}, where "
+ "includeObjectsCollectedByMajorGC landed. Older browsers ignore the "
+ "parameter silently and return a survivors-only profile, which for a "
+ "transient-allocation hypothesis is empty and reads as 'no allocation "
+ "here'. Refusing rather than reporting that.",
+ )
+ return major
+
+ def start(self) -> None:
+ if self._running:
+ raise RuntimeError("SamplingHeapProfiler.start called twice")
+ if self.include_major_gc or self.include_minor_gc:
+ self.assert_gc_flags_supported()
+ self.cdp.send("HeapProfiler.enable")
+ self.cdp.send(
+ "HeapProfiler.startSampling",
+ {
+ "samplingInterval": self.sampling_interval,
+ "includeObjectsCollectedByMajorGC": self.include_major_gc,
+ "includeObjectsCollectedByMinorGC": self.include_minor_gc,
+ },
+ )
+ self._running = True
+
+ def stop(self) -> HeapProfile:
+ if not self._running:
+ raise RuntimeError("SamplingHeapProfiler.stop without start")
+ res = self.cdp.send("HeapProfiler.stopSampling")
+ self._running = False
+ return self._parse(res)
+
+ def _parse(self, res: dict[str, Any]) -> HeapProfile:
+ raw = res.get("profile") or {}
+ head = raw.get("head")
+ if head is None:
+ raise CellFailure("heap_profile_empty", "stopSampling returned no profile head")
+ profile = HeapProfile(included_major_gc = self.include_major_gc)
+ _flatten(head, profile)
+ profile.sample_count = len(raw.get("samples") or ())
+ return profile
+
+ def peek(self) -> HeapProfile:
+ """Read the profile without stopping the profiler.
+
+ Used to take the survivors arm: force a major GC, then peek. The
+ profiler keeps accumulating afterwards, so this is non-destructive.
+ """
+ if not self._running:
+ raise RuntimeError("SamplingHeapProfiler.peek without start")
+ return self._parse(self.cdp.send("HeapProfiler.getSamplingProfile"))
+
+ def collect_garbage(self) -> None:
+ self.cdp.send("HeapProfiler.collectGarbage")
+
+ def __enter__(self) -> "SamplingHeapProfiler":
+ self.start()
+ return self
+
+ def __exit__(self, *exc: Any) -> None:
+ if self._running:
+ try:
+ self.cdp.send("HeapProfiler.stopSampling")
+ finally:
+ self._running = False
+
+
+def survival_ratio(
+ allocated: HeapProfile, survivors: HeapProfile, needles: Iterable[str]
+) -> dict[str, Any]:
+ """How much of what a site allocated is still alive after a major GC.
+
+ Takes TWO profiles from TWO arms of the identical workload, because one
+ session cannot produce both. A sampling profiler only records allocations
+ made after it starts, so you cannot start a second profiler after a GC and
+ learn anything about objects allocated before it. The two arms are:
+
+ * `allocated`: `include_major_gc=True`. Everything the workload allocated,
+ collected or not.
+ * `survivors`: `include_major_gc=False`, with a forced
+ `HeapProfiler.collectGarbage` before `stop()`. The profiler drops
+ collected objects, so what remains is what outlived the GC.
+
+ A ratio near zero is the signature of per-render churn; a ratio near one is
+ retention, which is a different bug with a different fix.
+ """
+ needles = tuple(needles)
+ if not allocated.included_major_gc:
+ raise CellFailure(
+ "heap_survival_arms_swapped",
+ "the `allocated` profile was captured without includeObjectsCollectedByMajorGC, "
+ "so it already excludes the transient garbage the ratio is about",
+ )
+ if survivors.included_major_gc:
+ raise CellFailure(
+ "heap_survival_arms_swapped",
+ "the `survivors` profile was captured WITH includeObjectsCollectedByMajorGC, "
+ "so it counts collected objects as survivors and the ratio would read 1.0",
+ )
+ alloc = allocated.bytes_matching(needles)
+ alive = survivors.bytes_matching(needles)
+ return {
+ "needles": list(needles),
+ "allocated_bytes": alloc,
+ "surviving_bytes": alive,
+ "survival_ratio": (alive / alloc) if alloc else None,
+ "interpretation_note": (
+ "near 0 means transient per-render churn; near 1 means retention. "
+ "None means the site allocated nothing measurable, which is not the "
+ "same as allocating nothing."
+ ),
+ }
+
+
+# ═══════════════════════════════════════════════════════════════════════════
+# Harness adapter (INTERFACES.md section 3)
+# ═══════════════════════════════════════════════════════════════════════════
+#
+# Level 3. One sampling session per window, started with
+# `includeObjectsCollectedByMajorGC` so that transient garbage is visible; the
+# hypothesis is per-render churn, and a survivors-only profile of that is empty.
+#
+# The survivors arm is NOT taken here. It needs a second run of the identical
+# workload with the flag off, which is an ablation arm and belongs to Layer 3.
+# What this instrument emits is the allocation side plus the site breakdown, so
+# `analysis.heap.survival_ratio` can be applied across two arms afterwards.
+
+import time # noqa: E402
+
+from ..analysis import assert_no_bare_zero, measured, merge, unmeasured # noqa: E402
+from . import register_instrument # noqa: E402
+
+
+class HeapInstrument:
+ """Sampling allocation profile per window, including collected objects."""
+
+ name = "heap"
+ level = 3
+
+ def __init__(
+ self,
+ top_n: int = 20,
+ include_major_gc: bool = True,
+ ) -> None:
+ self.ctx: Any = None
+ self.cdp: Any = None
+ self.top_n = top_n
+ self.include_major_gc = include_major_gc
+ self.profiler: SamplingHeapProfiler | None = None
+ self._overhead_ms = 0.0
+ self._windows = 0
+ self._reason = ""
+
+ def attach(self, ctx: Any) -> None:
+ self.ctx = ctx
+
+ def start_cell(self, cell: Any) -> None:
+ self.cdp = getattr(self.ctx, "cdp", None)
+ self._overhead_ms = 0.0
+ self._windows = 0
+ self._reason = (
+ "" if self.cdp is not None else "no CDP session; HeapProfiler is Chromium only"
+ )
+
+ def open(self, window: Any) -> None:
+ if self.cdp is None:
+ return
+ t0 = time.perf_counter()
+ self.profiler = SamplingHeapProfiler(self.cdp, include_major_gc = self.include_major_gc)
+ try:
+ self.profiler.start()
+ except CellFailure as exc:
+ # The version gate. Refusing is correct: an older browser ignores
+ # the flag silently and hands back survivors only, which for a
+ # transient-allocation hypothesis reads as "no allocation here".
+ self._reason = f"{exc.gate}: {exc.detail}"
+ self.profiler = None
+ except Exception as exc: # noqa: BLE001
+ self._reason = f"{type(exc).__name__}: {exc}"
+ self.profiler = None
+ self._overhead_ms += (time.perf_counter() - t0) * 1000.0
+
+ def close(self, window: Any) -> dict | None:
+ if self.profiler is None:
+ return merge(
+ unmeasured("allocated_bytes", self._reason or "heap sampling not running"),
+ {"active": False, "included_objects_collected_by_major_gc": self.include_major_gc},
+ )
+ t0 = time.perf_counter()
+ try:
+ prof = self.profiler.stop()
+ payload = merge(
+ measured("allocated_bytes", int(prof.total_bytes)),
+ measured("allocation_sites", len(prof.self_bytes)),
+ measured(
+ "top_sites",
+ [{"site": f.label(), "bytes": int(n)} for f, n in prof.top(self.top_n)],
+ ),
+ {
+ "active": True,
+ "included_objects_collected_by_major_gc": bool(prof.included_major_gc),
+ "survivors_arm_note": (
+ "this is the ALLOCATION side only. A survival ratio needs a second "
+ "arm of the identical workload with the flag off; see "
+ "analysis.heap.survival_ratio"
+ ),
+ },
+ )
+ except Exception as exc: # noqa: BLE001
+ payload = merge(
+ unmeasured("allocated_bytes", f"{type(exc).__name__}: {exc}"),
+ {"active": True, "included_objects_collected_by_major_gc": self.include_major_gc},
+ )
+ finally:
+ self.profiler = None
+ self._windows += 1
+ self._overhead_ms += (time.perf_counter() - t0) * 1000.0
+ assert_no_bare_zero(payload, "heap")
+ return payload
+
+ def end_cell(self, cell: Any) -> dict | None:
+ # A prose key is OMITTED when there is nothing to say, never set to
+ # None. `None` is reserved for a QUANTITY that could not be measured,
+ # and overloading it for "no comment" would make the two indistinguishable.
+ out = merge(
+ measured("overhead_ms", round(self._overhead_ms, 3)),
+ measured("windows_sampled", self._windows),
+ {"headline_safe": False},
+ {"reason": self._reason} if self._reason else {},
+ )
+ assert_no_bare_zero(out, "heap.end_cell")
+ return out
+
+ def detach(self) -> None:
+ if self.profiler is not None:
+ try:
+ self.profiler.stop()
+ except Exception:
+ pass
+ self.profiler = None
+
+
+@register_instrument(name = "heap", level = 3)
+def _make_heap() -> HeapInstrument:
+ return HeapInstrument()
diff --git a/tests/studio/studiobench/instruments/input.js b/tests/studio/studiobench/instruments/input.js
new file mode 100644
index 00000000000..02096b60cc4
--- /dev/null
+++ b/tests/studio/studiobench/instruments/input.js
@@ -0,0 +1,209 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+//
+// Keystroke-to-paint, measured from the page side of a REAL key event.
+//
+// WHY THIS IS NOT THE SALVAGED KEYSTROKE_JS. The old harness typed by calling the native value
+// setter on the textarea and dispatching a synthetic `input` event. That reaches React's
+// controlled input, so it measured something -- but it enters the pipeline AFTER hit testing,
+// after the browser's own event routing, and it carries no `latencyInfo`, which is the trace
+// field that says when the OS delivered the keypress. A synthetic event therefore cannot show
+// input queueing delay at all: it is dispatched from a task that is by definition already running,
+// so the queue is empty by construction and the number reads clean exactly when a user would be
+// waiting longest.
+//
+// So the driver types with `page.keyboard`, which goes in through CDP as a real input event, and
+// this file's job is only to observe from the page: mark when the key arrived, and mark the first
+// paint after the character landed in the value. The subtraction is done here because a
+// driver-side clock would include the CDP round trip, which is not something a user experiences.
+//
+// THE CLOCK STARTS AT THE KEYDOWN, NOT AT THE INPUT HANDLER, and that is the whole point of using
+// a real key event. `input` is dispatched as the default action of `keydown`, so any handler that
+// blocks the main thread on the way in has ALREADY finished by the time `input` fires: a start
+// taken here reads `performance.now()` after the queue drained and subtracts the wait out of the
+// number. Measured directly against the harness's own 400 ms injected keydown stall, an
+// input-anchored clock moved keystroke p95 by -14.8 ms while the user waited 400 ms, and the
+// integrity gate in `instruments/selfcheck.py` -- which requires that stall to move p95 by at
+// least 350 ms -- can never pass on it.
+//
+// A trusted event's `timeStamp` is a `DOMHighResTimeStamp` on the same origin as
+// `performance.now()`, set when the occurrence the event signals happened rather than when it was
+// dispatched, so `keydown.timeStamp` is the hardware arrival time and carries the queueing delay.
+// Verified on all three engines: with the 400 ms stall armed, `performance.now()` inside the
+// `input` handler is ~400 ms past `keydown.timeStamp` and ~0 ms past the INPUT event's own
+// timeStamp, which is why the anchor is the keydown and not this event.
+
+(() => {
+ if (window.__sb && window.__sb.input) return;
+ window.__sb = window.__sb || {};
+
+ const S = {
+ armed: false,
+ target: null,
+ baseline: "",
+ samples: [],
+ pending: null,
+ dropped: 0,
+ keyAt: null,
+ unanchored: 0,
+ // Every `input` event this instrument saw, whether it became a sample or was coalesced behind
+ // a paint that had not finished. Without it there is no denominator: `samples` alone cannot
+ // distinguish "the page painted every keystroke" from "most of them never reached here".
+ seen: 0,
+ };
+
+ const nextPaint = () =>
+ window.__sbNextPaint
+ ? window.__sbNextPaint()
+ : new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(performance.now()))));
+
+ // The key that produced the character being measured. The LAST unconsumed keydown, because a
+ // key that produced no character (an arrow, a modifier) must not anchor the next one that did.
+ const onKeyDown = (ev) => {
+ if (!S.armed || (S.target && ev.target !== S.target)) return;
+ S.keyAt = ev.timeStamp;
+ };
+
+ // Consume the anchor, and refuse an implausible one rather than quoting it. A synthetic event
+ // constructed by a page script carries the time of its CONSTRUCTOR, an engine that does not put
+ // key events on the performance timeline could report 0, and a composition commit produces an
+ // `input` with no keydown at all. Each of those falls back to this handler's own clock, which is
+ // the old behaviour, and is counted so the report can say how many samples were not anchored.
+ const anchor = (now) => {
+ const at = S.keyAt;
+ S.keyAt = null;
+ if (typeof at !== "number" || !isFinite(at) || at <= 0 || at > now || now - at > 10000) {
+ S.unanchored += 1;
+ return null;
+ }
+ return at;
+ };
+
+ const onInput = (ev) => {
+ if (!S.armed || ev.target !== S.target) return;
+ S.seen += 1;
+ // One in flight at a time. A burst of characters typed faster than the page can paint would
+ // otherwise attribute one paint to several keystrokes and report each of them as fast.
+ if (S.pending !== null) {
+ S.dropped += 1;
+ S.keyAt = null;
+ return;
+ }
+ const at = performance.now();
+ const keyAt = anchor(at);
+ const started = keyAt === null ? at : keyAt;
+ const lengthAt = S.target.value.length;
+ S.pending = at;
+ nextPaint().then((paintedAt) => {
+ S.samples.push({
+ at_ms: Math.round(at * 10) / 10,
+ // Keystroke to paint: from the key arriving to the frame that shows it.
+ latency_ms: Math.round((paintedAt - started) * 10) / 10,
+ // The two halves, kept separately so a regression can be attributed rather than guessed:
+ // how long the key waited to be handled, and how long the page then took to paint it.
+ input_delay_ms: keyAt === null ? null : Math.round((at - keyAt) * 10) / 10,
+ paint_ms: Math.round((paintedAt - at) * 10) / 10,
+ anchored_on: keyAt === null ? "input" : "keydown",
+ value_length: lengthAt,
+ });
+ S.pending = null;
+ });
+ };
+
+ window.__sb.input = {
+ // `selector` is resolved here rather than passed as a handle, so the driver can re-arm across
+ // a page that re-rendered its composer without holding a stale node.
+ arm(selector) {
+ const el = document.querySelector(selector);
+ if (!el) return { armed: false, reason: "no element matched " + selector };
+ if (S.target && S.target !== el) S.target.removeEventListener("input", onInput, true);
+ S.target = el;
+ S.baseline = el.value === undefined ? "" : el.value;
+ S.samples = [];
+ S.dropped = 0;
+ S.pending = null;
+ S.keyAt = null;
+ S.unanchored = 0;
+ S.seen = 0;
+ S.armed = true;
+ el.addEventListener("input", onInput, true);
+ // On the WINDOW, in capture, so the anchor is taken however the app routes the key and even
+ // if a handler on the way in stops propagation. Idempotent: re-arming across a re-rendered
+ // composer must not leave two of these behind, each overwriting the other's anchor.
+ window.removeEventListener("keydown", onKeyDown, true);
+ window.addEventListener("keydown", onKeyDown, true);
+ return { armed: true, baseline_length: S.baseline.length };
+ },
+
+ // IS ANYTHING STILL IN FLIGHT? The driver polls this instead of waiting a fixed interval.
+ //
+ // A fixed wait loses whichever keystroke had not painted when it expired, and the keystroke
+ // that has not painted yet is the SLOWEST one -- so the metric dropped precisely the sample it
+ // exists to catch, and a build that made typing worse read faster. A bigger constant has the
+ // same defect on a slower machine or a heavier rung; the only wait that does not is one that
+ // ends when the work does.
+ settled() {
+ return { pending: S.pending !== null, samples: S.samples.length, seen: S.seen };
+ },
+
+ // Drain. `expected` is how many characters the driver actually sent, so the report can say
+ // "27 of 30 keystrokes produced a measurement" instead of quoting a median over an unknown
+ // denominator.
+ collect(expected) {
+ const samples = S.samples.slice();
+ const latencies = samples.map((s) => s.latency_ms).sort((a, b) => a - b);
+ const at = (q) =>
+ latencies.length === 0 ? null : latencies[Math.min(latencies.length - 1, Math.floor(latencies.length * q))];
+ const observedText = S.target ? S.target.value : null;
+ const delays = samples
+ .map((s) => s.input_delay_ms)
+ .filter((v) => v !== null && v !== undefined)
+ .sort((a, b) => a - b);
+ const unanchored = S.unanchored;
+ const seen = S.seen;
+ // A sample still in flight AT THIS MOMENT is one the collect is about to lose. Reported so
+ // the driver can fail the reading rather than publish a percentile over what survived.
+ const pendingNow = S.pending !== null;
+ S.samples = [];
+ S.unanchored = 0;
+ S.seen = 0;
+ return {
+ samples: samples.length,
+ samples_attempted: true,
+ expected: expected === undefined ? null : expected,
+ // The denominator. `inputs_seen` is every keystroke that reached this instrument;
+ // `samples + coalesced` must account for all of them, and `pending_at_collect` says
+ // whether one was thrown away by the drain itself.
+ inputs_seen: seen,
+ pending_at_collect: pendingNow,
+ // How many samples could not be anchored on their own key event and fell back to the
+ // input handler's clock. A number quoted from those understates the wait by the queueing
+ // delay, so it is reported rather than blended in silently.
+ unanchored: unanchored,
+ input_delay_p95_ms:
+ delays.length === 0 ? null : delays[Math.min(delays.length - 1, Math.floor(delays.length * 0.95))],
+ // Not the same question as `samples`. A dropped sample is a keystroke that arrived while
+ // a previous one had not painted yet, which is itself the symptom.
+ coalesced: S.dropped,
+ p50_ms: at(0.5),
+ p95_ms: at(0.95),
+ max_ms: latencies.length === 0 ? null : latencies[latencies.length - 1],
+ // The FIRST sample is systematically a cold outlier and is reported separately rather
+ // than dropped, because on a jammed page it is also the largest real number in the set.
+ first_ms: samples.length === 0 ? null : samples[0].latency_ms,
+ // Proof the characters reached the controlled component and not only the DOM node.
+ text_length: observedText === null ? null : observedText.length,
+ grew_by: observedText === null ? null : observedText.length - S.baseline.length,
+ };
+ },
+
+ disarm() {
+ if (S.target) S.target.removeEventListener("input", onInput, true);
+ window.removeEventListener("keydown", onKeyDown, true);
+ S.armed = false;
+ S.target = null;
+ S.keyAt = null;
+ return true;
+ },
+ };
+})();
diff --git a/tests/studio/studiobench/instruments/layoutcost.js b/tests/studio/studiobench/instruments/layoutcost.js
new file mode 100644
index 00000000000..8612e5a7f33
--- /dev/null
+++ b/tests/studio/studiobench/instruments/layoutcost.js
@@ -0,0 +1,1007 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/*
+ * layoutcost.js -- counts the DOM operations suspected of forcing synchronous layout
+ * during streaming, and times them.
+ *
+ * WHAT IT COUNTS AND WHY THESE FIVE
+ *
+ * The mechanism under investigation is
+ * studio/frontend/src/components/assistant-ui/use-intent-aware-autoscroll.tsx. It installs a
+ * MutationObserver on the thread viewport (`.aui-thread-viewport.aui-stream-viewport`) with
+ * `{childList, subtree, characterData, attributes, attributeFilter:["class","hidden",
+ * "aria-hidden","aria-expanded","data-state"]}`. Every delivery of that observer runs
+ * `el.scrollHeight` (a read that forces style plus layout when the DOM is dirty, and the DOM is
+ * always dirty here because the mutation is what woke the observer), then
+ * `el.style.setProperty("--aui-scroll-stabilizer", "<n>px")`, then
+ * `el.scrollTo({top, behavior:"instant"})`. During token streaming the characterData mutations
+ * arrive per streamed character, and each one costs something proportional to the size of the
+ * whole thread, not to the size of the change. That is the shape of the hypothesis, so the
+ * instrument records exactly the five operations that shape is made of:
+ *
+ * scrollHeight READS getter on Element.prototype. The forced-layout trigger.
+ * scrollTop WRITES setter on Element.prototype. Cheap to issue, expensive later.
+ * scrollTo CALLS method on Element.prototype. The pin.
+ * MutationObserver callback invocations, and the number of MutationRecords handed to
+ * each one. Records per callback is the number that separates "the
+ * observer fires once with 400 records" from "it fires 400 times",
+ * which are wildly different costs and look identical in a profile
+ * that only counts callbacks.
+ * setProperty("--..") custom property writes, with `--aui-scroll-stabilizer` counted on
+ * its own so the autoscroll path is separable from every other CSS
+ * variable the app writes.
+ *
+ * Counts alone would be enough to test the "per character" claim. The timings are here because
+ * a count cannot distinguish 4,000 cheap reads from 4,000 reads that each walk a 300-message
+ * thread, and the whole question is which of those is happening.
+ *
+ * THE SELF-COST PROBLEM, STATED PLAINLY
+ *
+ * Wrapping the `scrollHeight` getter to time it makes `scrollHeight` slower. This instrument
+ * changes the thing it measures. There is no version of this technique that does not, so the
+ * honest move is to measure the distortion instead of hoping it is small:
+ *
+ * 1. `selfCostEstimate()` times N wrapped reads and N reads through the ORIGINAL descriptor,
+ * which this file keeps a reference to for exactly this purpose, both on a detached and
+ * clean element so no real layout work is included. The difference is the per-call
+ * overhead of the wrapper as installed, including its own bookkeeping. The deep tier can
+ * subtract `overheadMsPerCall * scrollHeightReads` from the total, or at minimum print it
+ * next to the total so a reader can see whether the instrument is a rounding error or a
+ * third of the number.
+ * 2. The Python driver runs the SAME benchmark cell twice, once with this instrument injected
+ * and once without, and compares the frame statistics of the two. That is the real check.
+ * Step 1 measures what the wrapper costs per call in isolation; step 2 measures what the
+ * whole instrument costs the app in situ, including cache effects and lost inlining that
+ * no microbenchmark can see. If the two runs disagree about the app, the counts from this
+ * file are still usable and its timings are not, and that has to be discovered rather than
+ * assumed.
+ *
+ * `clockGranularityMs`, also reported by `selfCostEstimate()`, exists because a single
+ * `scrollHeight` read on a clean DOM can be faster than `performance.now()` can resolve. In a
+ * browser without cross-origin isolation the timer is clamped, so a genuine 0.003 ms read is
+ * indistinguishable from zero. A `maxMs` of 0 therefore means "below the clock", not "free",
+ * and the granularity number is what lets the report say so.
+ *
+ * WHY IT IS OFF BY DEFAULT
+ *
+ * See above: it perturbs the measurement. The default benchmark run must be as close to the
+ * shipping app as the harness can manage, so the driver injects this file only for the deep
+ * tier, where the question has already narrowed to "which operation" and a known, quantified
+ * distortion is worth paying for. Injection is the opt-in. Setting
+ * `window.__sbLayoutCostDisabled = true` before this script runs is a secondary escape hatch
+ * for bisecting the instrument itself.
+ *
+ * WHAT IT DOES NOT MEASURE
+ *
+ * It does not measure layout time. It measures how often the app asks for something that can
+ * force layout, and how long the asking took from JS. Actual layout attribution comes from the
+ * trace, and the point of this file is to tell the trace where to look.
+ *
+ * Reads through `window.scrollY`, `document.documentElement.scrollHeight` in the getter's own
+ * frame, `getBoundingClientRect`, `offsetHeight` and `getComputedStyle` are NOT wrapped. They
+ * force layout too. They are not in the code path under investigation, and every wrapper added
+ * here makes the run less like the app.
+ *
+ * ZERO DISCIPLINE
+ *
+ * A count of 0 from this file is a real observation: the operation did not happen. A count of 0
+ * because the patch could not be installed is not, and the two must never print the same. So
+ * `snapshot()` carries `attempted` per instrumented family, `unavailable` lists the names whose
+ * original descriptor was missing or non-configurable, and a WebKit build that refuses the
+ * patch reads as "not attempted" rather than as a quiet zero. The Python side turns those into
+ * Measure objects. Failing to install is not an error and never throws: a partial instrument
+ * that is honest about which half ran is more useful than a page that fails to boot.
+ */
+
+(function () {
+ "use strict";
+
+ if (typeof window === "undefined" || !window) {
+ return;
+ }
+
+ var W = window;
+
+ // Idempotence. add_init_script runs per document, and a page that creates an iframe or that
+ // the driver reloads must not stack wrappers: a doubly wrapped getter would double every
+ // count and square nothing useful.
+ if (W.__sbLayoutCostInstalled) {
+ return;
+ }
+ W.__sbLayoutCostInstalled = true;
+
+ var VIEWPORT_CLASS = "aui-stream-viewport";
+ var STABILIZER_PROP = "--aui-scroll-stabilizer";
+ var MAX_KEYS = 24;
+ var OTHER_KEY = "__other__";
+
+ // Capture these before the app can touch them. An app that replaces performance.now (some
+ // test doubles do) would otherwise silently redefine every timing in this file.
+ var perf = W.performance;
+ var rawNow =
+ perf && typeof perf.now === "function" ? perf.now.bind(perf) : null;
+ var now =
+ rawNow ||
+ function () {
+ return Date.now();
+ };
+ var hasHiResClock = !!rawNow;
+
+ var doc = W.document || null;
+
+ function nowStamp() {
+ try {
+ return new Date().toISOString();
+ } catch (e) {
+ return null;
+ }
+ }
+
+ // ---------------------------------------------------------------------------------------
+ // State
+ // ---------------------------------------------------------------------------------------
+
+ function freshTiming() {
+ return { totalMs: 0, maxMs: 0, samples: 0 };
+ }
+
+ function freshMoBucket() {
+ return { callbacks: 0, records: 0, totalMs: 0, maxMs: 0 };
+ }
+
+ function freshCounters() {
+ return {
+ scrollHeightReads: 0,
+ scrollTopWrites: 0,
+ scrollToCalls: 0,
+ moCallbacks: 0,
+ moRecords: 0,
+ customPropSets: 0,
+ stabilizerPropSets: 0
+ };
+ }
+
+ function freshTimings() {
+ return {
+ scrollHeightRead: freshTiming(),
+ scrollTo: freshTiming(),
+ moCallback: freshTiming()
+ };
+ }
+
+ function freshMo() {
+ return {
+ observersConstructed: 0,
+ observersMatchedViewport: 0,
+ observersWithAriaExpandedFilter: 0,
+ observeCalls: 0,
+ viewportObserver: freshMoBucket(),
+ other: freshMoBucket()
+ };
+ }
+
+ var state = {
+ active: false,
+ counters: freshCounters(),
+ timings: freshTimings(),
+ mo: freshMo(),
+ breakdown: Object.create(null),
+ breakdownKeyCount: 0,
+ breakdownCapped: false,
+ attempted: {
+ scrollHeight: false,
+ scrollTop: false,
+ scrollTo: false,
+ mutationObserver: false,
+ customProps: false
+ },
+ unavailable: [],
+ selfCost: null,
+ clockGranularityMs: null,
+ // Sink for the self-cost loops. A read whose result is thrown away can in principle be
+ // optimised out; assigning it somewhere observable keeps both loops honest.
+ sink: 0
+ };
+
+ var originals = {
+ scrollHeightDesc: null,
+ scrollTopDesc: null,
+ scrollToDesc: null,
+ setPropertyDesc: null,
+ MutationObserver: null
+ };
+
+ function markUnavailable(name, reason) {
+ try {
+ state.unavailable.push({ name: name, reason: reason });
+ } catch (e) {
+ /* nothing sensible to do here, and throwing would take the app with it */
+ }
+ }
+
+ function record(timing, dt) {
+ timing.totalMs += dt;
+ timing.samples += 1;
+ if (dt > timing.maxMs) {
+ timing.maxMs = dt;
+ }
+ }
+
+ // ---------------------------------------------------------------------------------------
+ // Per-target breakdown
+ //
+ // Keyed by a short, stable descriptor rather than by element identity. Holding elements in a
+ // Map would pin detached DOM alive for the whole run, which on a streaming thread means
+ // holding every message ever rendered. The key is deliberately coarse: the question is "which
+ // KIND of element is being read", and a 300-message thread has maybe six kinds.
+ //
+ // The cap matters. A page that reads scrollHeight on thousands of distinct elements would
+ // otherwise grow an unbounded object inside the hot path, so key 25 and beyond all land in
+ // one bucket and `breakdownCapped` says the truncation happened.
+ // ---------------------------------------------------------------------------------------
+
+ function keyFor(el) {
+ try {
+ if (!el || typeof el !== "object") {
+ return "unknown";
+ }
+ var tag = "";
+ try {
+ tag = String(el.tagName || el.nodeName || "?").toLowerCase();
+ } catch (e) {
+ tag = "?";
+ }
+ var cls = "";
+ var isViewport = false;
+ try {
+ var list = el.classList;
+ if (list) {
+ if (list.length > 0) {
+ cls = String(list[0] || "");
+ }
+ // contains(), not matches(): a class test cannot invoke the selector engine and
+ // cannot be tricked into anything expensive, and this runs inside the getter.
+ isViewport = !!list.contains && list.contains(VIEWPORT_CLASS);
+ }
+ } catch (e) {
+ /* SVG and exotic hosts: fall through with what we have */
+ }
+ return tag + (cls ? "." + cls : "") + (isViewport ? "[vp]" : "");
+ } catch (e) {
+ return "unknown";
+ }
+ }
+
+ function bucketFor(el) {
+ var key = keyFor(el);
+ var b = state.breakdown[key];
+ if (b) {
+ return b;
+ }
+ var isOther = false;
+ if (state.breakdownKeyCount >= MAX_KEYS) {
+ state.breakdownCapped = true;
+ key = OTHER_KEY;
+ isOther = true;
+ b = state.breakdown[key];
+ if (b) {
+ return b;
+ }
+ }
+ b = {
+ scrollHeightReads: 0,
+ scrollHeightMs: 0,
+ scrollHeightMaxMs: 0,
+ scrollTopWrites: 0,
+ scrollToCalls: 0,
+ scrollToMs: 0,
+ scrollToMaxMs: 0
+ };
+ state.breakdown[key] = b;
+ if (!isOther) {
+ // The overflow bucket is not charged to the budget, so `breakdownKeyCount` is the number
+ // of REAL keys and the object holds at most MAX_KEYS + 1 entries. Counting the bucket
+ // would make a capped run report 25 keys and a reader would reasonably conclude the cap
+ // does not work.
+ state.breakdownKeyCount += 1;
+ }
+ return b;
+ }
+
+ // ---------------------------------------------------------------------------------------
+ // Element.prototype patches
+ // ---------------------------------------------------------------------------------------
+
+ var ElementProto =
+ typeof W.Element === "function" && W.Element.prototype
+ ? W.Element.prototype
+ : null;
+
+ function grabDescriptor(proto, name) {
+ if (!proto) {
+ markUnavailable(name, "Element.prototype is not available");
+ return null;
+ }
+ var d = null;
+ try {
+ d = Object.getOwnPropertyDescriptor(proto, name);
+ } catch (e) {
+ markUnavailable(name, "getOwnPropertyDescriptor threw: " + e);
+ return null;
+ }
+ if (!d) {
+ markUnavailable(name, "no own descriptor on prototype");
+ return null;
+ }
+ if (!d.configurable) {
+ markUnavailable(name, "descriptor is not configurable");
+ return null;
+ }
+ return d;
+ }
+
+ function installScrollHeight() {
+ var d = grabDescriptor(ElementProto, "scrollHeight");
+ if (!d || typeof d.get !== "function") {
+ if (d) {
+ markUnavailable("scrollHeight", "descriptor has no getter");
+ }
+ return;
+ }
+ originals.scrollHeightDesc = d;
+ var origGet = d.get;
+ try {
+ Object.defineProperty(ElementProto, "scrollHeight", {
+ configurable: true,
+ enumerable: d.enumerable,
+ get: function () {
+ if (!state.active) {
+ return origGet.call(this);
+ }
+ var t0 = now();
+ // Outside try/catch on purpose. If the native getter throws, the app must see the
+ // same exception it would have seen without this file.
+ var value = origGet.call(this);
+ try {
+ var dt = now() - t0;
+ state.counters.scrollHeightReads += 1;
+ record(state.timings.scrollHeightRead, dt);
+ var b = bucketFor(this);
+ b.scrollHeightReads += 1;
+ b.scrollHeightMs += dt;
+ if (dt > b.scrollHeightMaxMs) {
+ b.scrollHeightMaxMs = dt;
+ }
+ } catch (e) {
+ /* bookkeeping is never allowed to break a property read */
+ }
+ return value;
+ },
+ set: d.set
+ });
+ state.attempted.scrollHeight = true;
+ } catch (e) {
+ originals.scrollHeightDesc = null;
+ markUnavailable("scrollHeight", "defineProperty threw: " + e);
+ }
+ }
+
+ function installScrollTop() {
+ var d = grabDescriptor(ElementProto, "scrollTop");
+ if (!d || typeof d.set !== "function") {
+ if (d) {
+ markUnavailable("scrollTop", "descriptor has no setter");
+ }
+ return;
+ }
+ originals.scrollTopDesc = d;
+ var origSet = d.set;
+ try {
+ Object.defineProperty(ElementProto, "scrollTop", {
+ configurable: true,
+ enumerable: d.enumerable,
+ // The getter is left exactly as it was. Reading scrollTop also forces layout, but it is
+ // not the operation under investigation and wrapping it would add cost to a path the
+ // hypothesis does not name.
+ get: d.get,
+ set: function (v) {
+ if (!state.active) {
+ origSet.call(this, v);
+ return;
+ }
+ // Writes are counted, not timed. Issuing a scroll write is cheap; the cost lands in
+ // the next layout, where a timer wrapped around the setter would not see it. A number
+ // that looks like a duration but is not one is worse than no number.
+ try {
+ state.counters.scrollTopWrites += 1;
+ bucketFor(this).scrollTopWrites += 1;
+ } catch (e) {
+ /* fall through to the real setter regardless */
+ }
+ origSet.call(this, v);
+ }
+ });
+ state.attempted.scrollTop = true;
+ } catch (e) {
+ originals.scrollTopDesc = null;
+ markUnavailable("scrollTop", "defineProperty threw: " + e);
+ }
+ }
+
+ function installScrollTo() {
+ var d = grabDescriptor(ElementProto, "scrollTo");
+ if (!d || typeof d.value !== "function") {
+ if (d) {
+ markUnavailable("scrollTo", "descriptor is not a method");
+ }
+ return;
+ }
+ if (!d.writable && !d.configurable) {
+ markUnavailable("scrollTo", "descriptor is not writable");
+ return;
+ }
+ originals.scrollToDesc = d;
+ var orig = d.value;
+ try {
+ Object.defineProperty(ElementProto, "scrollTo", {
+ configurable: true,
+ enumerable: d.enumerable,
+ writable: true,
+ value: function () {
+ if (!state.active) {
+ return orig.apply(this, arguments);
+ }
+ var t0 = now();
+ var out = orig.apply(this, arguments);
+ try {
+ var dt = now() - t0;
+ state.counters.scrollToCalls += 1;
+ record(state.timings.scrollTo, dt);
+ var b = bucketFor(this);
+ b.scrollToCalls += 1;
+ b.scrollToMs += dt;
+ if (dt > b.scrollToMaxMs) {
+ b.scrollToMaxMs = dt;
+ }
+ } catch (e) {
+ /* never turn a scroll into an exception */
+ }
+ return out;
+ }
+ });
+ state.attempted.scrollTo = true;
+ } catch (e) {
+ originals.scrollToDesc = null;
+ markUnavailable("scrollTo", "defineProperty threw: " + e);
+ }
+ }
+
+ // ---------------------------------------------------------------------------------------
+ // CSSStyleDeclaration.prototype.setProperty
+ // ---------------------------------------------------------------------------------------
+
+ function installSetProperty() {
+ var proto =
+ typeof W.CSSStyleDeclaration === "function" &&
+ W.CSSStyleDeclaration.prototype
+ ? W.CSSStyleDeclaration.prototype
+ : null;
+ if (!proto) {
+ markUnavailable("setProperty", "CSSStyleDeclaration is not available");
+ return;
+ }
+ var d = null;
+ try {
+ d = Object.getOwnPropertyDescriptor(proto, "setProperty");
+ } catch (e) {
+ markUnavailable("setProperty", "getOwnPropertyDescriptor threw: " + e);
+ return;
+ }
+ if (!d || typeof d.value !== "function") {
+ markUnavailable("setProperty", "no own method on prototype");
+ return;
+ }
+ if (!d.configurable && !d.writable) {
+ markUnavailable("setProperty", "descriptor is not configurable");
+ return;
+ }
+ originals.setPropertyDesc = d;
+ var orig = d.value;
+ try {
+ Object.defineProperty(proto, "setProperty", {
+ configurable: true,
+ enumerable: d.enumerable,
+ writable: true,
+ value: function (name) {
+ if (state.active) {
+ try {
+ // Only custom properties. Ordinary style writes are far more numerous and are not
+ // part of the mechanism being tested; counting them would bury the signal.
+ if (typeof name === "string" && name.charCodeAt(0) === 45 && name.charCodeAt(1) === 45) {
+ state.counters.customPropSets += 1;
+ if (name === STABILIZER_PROP) {
+ state.counters.stabilizerPropSets += 1;
+ }
+ }
+ } catch (e) {
+ /* fall through */
+ }
+ }
+ return orig.apply(this, arguments);
+ }
+ });
+ state.attempted.customProps = true;
+ } catch (e) {
+ originals.setPropertyDesc = null;
+ markUnavailable("setProperty", "defineProperty threw: " + e);
+ }
+ }
+
+ // ---------------------------------------------------------------------------------------
+ // MutationObserver
+ //
+ // A subclass rather than a Proxy or a plain function: `instanceof MutationObserver` keeps
+ // working, `observe` / `disconnect` / `takeRecords` stay native (they are inherited, and
+ // `observe` is overridden only to read its arguments before delegating), and the callback is
+ // the single thing that changes.
+ //
+ // The split into viewportObserver and other exists because the app runs several observers and
+ // an aggregate count cannot tell the autoscroll one from React's own. Two independent
+ // discriminators are recorded per observer: the observe() target carrying the
+ // `.aui-stream-viewport` class, and an attributeFilter containing "aria-expanded", which no
+ // other observer in this app requests. An observer counts as the viewport observer if EITHER
+ // fires, because the classes are renamed more often than the filter is, and both booleans are
+ // reported separately so a reader can see when they disagree instead of trusting the merge.
+ // ---------------------------------------------------------------------------------------
+
+ function installMutationObserver() {
+ var Native = W.MutationObserver;
+ if (typeof Native !== "function") {
+ markUnavailable("MutationObserver", "constructor is not available");
+ return;
+ }
+ originals.MutationObserver = Native;
+
+ var moStates =
+ typeof W.WeakMap === "function" ? new W.WeakMap() : null;
+
+ function bucketOf(obsState) {
+ return obsState && (obsState.matchedViewport || obsState.hasAriaExpanded)
+ ? state.mo.viewportObserver
+ : state.mo.other;
+ }
+
+ var Wrapped;
+ try {
+ Wrapped = class extends Native {
+ constructor(callback) {
+ if (typeof callback !== "function") {
+ // Let the native constructor produce its own TypeError, unchanged.
+ super(callback);
+ return;
+ }
+ var obsState = { matchedViewport: false, hasAriaExpanded: false };
+ super(function (records, observer) {
+ if (!state.active) {
+ return callback.call(this, records, observer);
+ }
+ var n = 0;
+ try {
+ n = records && typeof records.length === "number" ? records.length : 0;
+ } catch (e) {
+ n = 0;
+ }
+ var t0 = now();
+ try {
+ return callback.call(this, records, observer);
+ } finally {
+ // finally, not a trailing statement: a callback that throws still consumed the
+ // time, and dropping the sample would make a broken build look fast.
+ try {
+ var dt = now() - t0;
+ state.counters.moCallbacks += 1;
+ state.counters.moRecords += n;
+ record(state.timings.moCallback, dt);
+ var b = bucketOf(obsState);
+ b.callbacks += 1;
+ b.records += n;
+ b.totalMs += dt;
+ if (dt > b.maxMs) {
+ b.maxMs = dt;
+ }
+ } catch (e) {
+ /* bookkeeping only */
+ }
+ }
+ });
+ try {
+ state.mo.observersConstructed += 1;
+ if (moStates) {
+ moStates.set(this, obsState);
+ }
+ } catch (e) {
+ /* an uncounted observer is better than a failed construction */
+ }
+ }
+
+ observe(target, init) {
+ try {
+ state.mo.observeCalls += 1;
+ var obsState = moStates ? moStates.get(this) : null;
+ if (obsState) {
+ if (
+ !obsState.matchedViewport &&
+ target &&
+ target.nodeType === 1 &&
+ target.classList &&
+ target.classList.contains &&
+ target.classList.contains(VIEWPORT_CLASS)
+ ) {
+ obsState.matchedViewport = true;
+ state.mo.observersMatchedViewport += 1;
+ }
+ if (!obsState.hasAriaExpanded && init && init.attributeFilter) {
+ var f = init.attributeFilter;
+ for (var i = 0; i < f.length; i++) {
+ if (f[i] === "aria-expanded") {
+ obsState.hasAriaExpanded = true;
+ state.mo.observersWithAriaExpandedFilter += 1;
+ break;
+ }
+ }
+ }
+ }
+ } catch (e) {
+ /* classification is optional, observing is not */
+ }
+ // apply(arguments), not (target, init): observe() with a missing options argument has
+ // its own spec behaviour and must keep it.
+ return super.observe.apply(this, arguments);
+ }
+ };
+ } catch (e) {
+ originals.MutationObserver = null;
+ markUnavailable("MutationObserver", "subclassing threw: " + e);
+ return;
+ }
+
+ try {
+ Object.defineProperty(Wrapped, "name", {
+ value: "MutationObserver",
+ configurable: true
+ });
+ } catch (e) {
+ /* cosmetic only: some feature detection sniffs constructor names */
+ }
+
+ try {
+ W.MutationObserver = Wrapped;
+ state.attempted.mutationObserver = true;
+ } catch (e) {
+ originals.MutationObserver = null;
+ markUnavailable("MutationObserver", "assignment to window threw: " + e);
+ }
+ }
+
+ // ---------------------------------------------------------------------------------------
+ // Self cost
+ // ---------------------------------------------------------------------------------------
+
+ function measureClockGranularityMs() {
+ var best = null;
+ for (var trial = 0; trial < 5; trial++) {
+ var a = now();
+ var b = a;
+ var guard = 0;
+ while (b === a && guard < 2000000) {
+ b = now();
+ guard++;
+ }
+ if (b !== a) {
+ var d = b - a;
+ if (best === null || d < best) {
+ best = d;
+ }
+ }
+ }
+ return best;
+ }
+
+ function copyRawState() {
+ return {
+ counters: copyPlain(state.counters),
+ timings: copyPlain(state.timings),
+ mo: copyPlain(state.mo),
+ breakdown: copyPlain(state.breakdown),
+ breakdownKeyCount: state.breakdownKeyCount,
+ breakdownCapped: state.breakdownCapped
+ };
+ }
+
+ function restoreRawState(saved) {
+ state.counters = saved.counters;
+ state.timings = saved.timings;
+ state.mo = saved.mo;
+ state.breakdown = saved.breakdown;
+ state.breakdownKeyCount = saved.breakdownKeyCount;
+ state.breakdownCapped = saved.breakdownCapped;
+ // The live objects were replaced, so the convenience aliases on the public API have to be
+ // rebound or a caller reading __sbLayoutCost.counters directly would watch a detached copy
+ // that never increments again.
+ api.counters = state.counters;
+ api.timings = state.timings;
+ api.mo = state.mo;
+ }
+
+ function selfCostEstimate(sampleCount) {
+ var n =
+ typeof sampleCount === "number" && sampleCount > 0
+ ? Math.floor(sampleCount)
+ : 200;
+
+ if (!state.attempted.scrollHeight || !originals.scrollHeightDesc) {
+ return {
+ attempted: false,
+ reason: "scrollHeight getter was not patched, so there is no overhead to measure",
+ samples: 0,
+ hasHiResClock: hasHiResClock
+ };
+ }
+ if (!doc || typeof doc.createElement !== "function") {
+ return {
+ attempted: false,
+ reason: "no document to build a probe element in",
+ samples: 0,
+ hasHiResClock: hasHiResClock
+ };
+ }
+
+ var origGet = originals.scrollHeightDesc.get;
+ var result;
+ // The probe runs through the live wrapper, so it increments the real counters. Saving and
+ // restoring them keeps the estimate from contaminating the measurement it exists to
+ // correct, while still timing the wrapper exactly as the app sees it, bookkeeping included.
+ var saved = copyRawState();
+ try {
+ var probe = doc.createElement("div");
+ probe.className = "sb-selfcost-probe";
+ // Detached and never inserted. An attached element would make both loops pay for real
+ // layout, which is the app's cost and not the instrument's, and would swamp the
+ // difference this function is trying to resolve. The number produced here is the cost of
+ // the WRAPPER, which is the only part this file is responsible for.
+ var i;
+ var sink = 0;
+
+ // Warm both paths first. The first few hundred calls run in the interpreter tier, and
+ // whichever loop goes first would otherwise be charged for the JIT.
+ for (i = 0; i < n; i++) {
+ sink += probe.scrollHeight;
+ }
+ for (i = 0; i < n; i++) {
+ sink += origGet.call(probe);
+ }
+
+ var w0 = now();
+ for (i = 0; i < n; i++) {
+ sink += probe.scrollHeight;
+ }
+ var wrappedMs = now() - w0;
+
+ var r0 = now();
+ for (i = 0; i < n; i++) {
+ sink += origGet.call(probe);
+ }
+ var rawMs = now() - r0;
+
+ state.sink = sink;
+
+ var granularity = state.clockGranularityMs;
+ if (granularity === null || granularity === undefined) {
+ granularity = measureClockGranularityMs();
+ }
+
+ var perWrapped = wrappedMs / n;
+ var perRaw = rawMs / n;
+ result = {
+ attempted: true,
+ samples: n,
+ wrappedMsPerCall: perWrapped,
+ rawMsPerCall: perRaw,
+ overheadMsPerCall: perWrapped - perRaw,
+ wrappedTotalMs: wrappedMs,
+ rawTotalMs: rawMs,
+ clockGranularityMs: granularity,
+ hasHiResClock: hasHiResClock,
+ note:
+ "Detached clean element: this is the cost of the wrapper only, not of the layout a " +
+ "dirty attached element would force. Multiply overheadMsPerCall by " +
+ "counters.scrollHeightReads to bound how much of the reported scrollHeight total " +
+ "belongs to the instrument. Cross-check against the driver's paired run with the " +
+ "instrument absent."
+ };
+ state.clockGranularityMs = granularity;
+ } catch (e) {
+ result = {
+ attempted: false,
+ reason: "probe threw: " + e,
+ samples: 0,
+ hasHiResClock: hasHiResClock
+ };
+ } finally {
+ try {
+ restoreRawState(saved);
+ } catch (e2) {
+ /* leaving inflated counters would be worse than this catch being empty, but there is
+ nothing further to try */
+ }
+ }
+
+ state.selfCost = result;
+ return copyPlain(result);
+ }
+
+ // ---------------------------------------------------------------------------------------
+ // Public surface
+ // ---------------------------------------------------------------------------------------
+
+ function copyPlain(v) {
+ // Hand written rather than JSON round tripping: JSON turns a non finite number into null
+ // and silently drops undefined, and a timing that reads null because of the serialiser
+ // would be indistinguishable from a timing that was never taken.
+ if (v === null || typeof v !== "object") {
+ return v;
+ }
+ var out;
+ var k;
+ if (Object.prototype.toString.call(v) === "[object Array]") {
+ out = [];
+ for (k = 0; k < v.length; k++) {
+ out[k] = copyPlain(v[k]);
+ }
+ return out;
+ }
+ out = {};
+ for (k in v) {
+ if (Object.prototype.hasOwnProperty.call(v, k)) {
+ out[k] = copyPlain(v[k]);
+ }
+ }
+ return out;
+ }
+
+ function snapshot() {
+ var out;
+ try {
+ out = {
+ enabled: !!state.active,
+ installedAt: api.installedAt,
+ resetAt: api.resetAt,
+ snapshotAt: nowStamp(),
+ // Per family, so a count of zero can be told apart from a patch that never landed.
+ attempted: copyPlain(state.attempted),
+ unavailable: copyPlain(state.unavailable),
+ counters: copyPlain(state.counters),
+ timings: copyPlain(state.timings),
+ mo: copyPlain(state.mo),
+ breakdown: copyPlain(state.breakdown),
+ breakdownCapped: !!state.breakdownCapped,
+ breakdownKeyCount: state.breakdownKeyCount,
+ breakdownMaxKeys: MAX_KEYS,
+ otherKey: OTHER_KEY,
+ clockGranularityMs: state.clockGranularityMs,
+ hasHiResClock: hasHiResClock,
+ selfCost: copyPlain(state.selfCost)
+ };
+ } catch (e) {
+ out = { enabled: false, error: String(e) };
+ }
+ return out;
+ }
+
+ function reset() {
+ try {
+ state.counters = freshCounters();
+ state.timings = freshTimings();
+ state.mo = freshMo();
+ state.breakdown = Object.create(null);
+ state.breakdownKeyCount = 0;
+ state.breakdownCapped = false;
+ api.resetAt = nowStamp();
+ api.counters = state.counters;
+ api.timings = state.timings;
+ api.mo = state.mo;
+ } catch (e) {
+ /* reset failing loudly mid run would lose the run */
+ }
+ return true;
+ }
+
+ function uninstall() {
+ // Restores the exact descriptors that were captured, so a page can be handed back to a
+ // measurement that must not carry the instrument's overhead. Counters are left alone: the
+ // driver usually snapshots after uninstalling.
+ state.active = false;
+ try {
+ if (originals.scrollHeightDesc && ElementProto) {
+ Object.defineProperty(ElementProto, "scrollHeight", originals.scrollHeightDesc);
+ }
+ } catch (e) {
+ /* leave it wrapped rather than throw */
+ }
+ try {
+ if (originals.scrollTopDesc && ElementProto) {
+ Object.defineProperty(ElementProto, "scrollTop", originals.scrollTopDesc);
+ }
+ } catch (e) {
+ /* as above */
+ }
+ try {
+ if (originals.scrollToDesc && ElementProto) {
+ Object.defineProperty(ElementProto, "scrollTo", originals.scrollToDesc);
+ }
+ } catch (e) {
+ /* as above */
+ }
+ try {
+ if (originals.setPropertyDesc && W.CSSStyleDeclaration) {
+ Object.defineProperty(
+ W.CSSStyleDeclaration.prototype,
+ "setProperty",
+ originals.setPropertyDesc
+ );
+ }
+ } catch (e) {
+ /* as above */
+ }
+ try {
+ if (originals.MutationObserver) {
+ W.MutationObserver = originals.MutationObserver;
+ }
+ } catch (e) {
+ /* as above */
+ }
+ api.enabled = false;
+ return true;
+ }
+
+ var api = {
+ version: 1,
+ enabled: false,
+ installedAt: nowStamp(),
+ resetAt: null,
+ counters: state.counters,
+ timings: state.timings,
+ mo: state.mo,
+ unavailable: state.unavailable,
+ attempted: state.attempted,
+ viewportClass: VIEWPORT_CLASS,
+ stabilizerProperty: STABILIZER_PROP,
+ snapshot: snapshot,
+ reset: reset,
+ uninstall: uninstall,
+ selfCostEstimate: selfCostEstimate
+ };
+
+ W.__sbLayoutCost = api;
+
+ if (W.__sbLayoutCostDisabled === true) {
+ // Injected but told to stand down. Everything reads as not attempted, which is the correct
+ // answer and not a row of zeros.
+ return;
+ }
+
+ installScrollHeight();
+ installScrollTop();
+ installScrollTo();
+ installSetProperty();
+ installMutationObserver();
+
+ state.active =
+ state.attempted.scrollHeight ||
+ state.attempted.scrollTop ||
+ state.attempted.scrollTo ||
+ state.attempted.customProps ||
+ state.attempted.mutationObserver;
+ api.enabled = state.active;
+})();
diff --git a/tests/studio/studiobench/instruments/layoutcost.py b/tests/studio/studiobench/instruments/layoutcost.py
new file mode 100644
index 00000000000..855c1b377f0
--- /dev/null
+++ b/tests/studio/studiobench/instruments/layoutcost.py
@@ -0,0 +1,19 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Bring the forced-layout instrument into the registry.
+
+`arms/layoutcost.py` deliberately does not import this package: it was written while this one was
+still being built, so it exposes `register(register_instrument)` and takes the decorator as an
+argument instead. That left it defined and never called, which is worse than either half alone --
+`available()` omitted `layout_cost` while the implementation sat complete one directory away, so
+the M3 forced-layout hypothesis read as unmeasured rather than as unwired.
+
+`load_all()` imports siblings of this directory only, so the call has to live here.
+"""
+
+from . import register_instrument
+
+from ..arms.layoutcost import register as _register
+
+_register(register_instrument)
diff --git a/tests/studio/studiobench/instruments/pagejs.py b/tests/studio/studiobench/instruments/pagejs.py
new file mode 100644
index 00000000000..ee6551d81d0
--- /dev/null
+++ b/tests/studio/studiobench/instruments/pagejs.py
@@ -0,0 +1,316 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Registers the three page-side instruments: `frames`, `input`, `glass`.
+
+One module for all three because they share the same shape -- an init script installed before app
+code, drained per window -- and because a file per instrument would be three copies of the same
+error handling. The JS lives in the sibling .js files so it can be read and edited as JavaScript.
+
+THE TRI-CLOCK GATE lives here, in `frames`. Three independent measures of whether frames happened:
+the rAF loop, a 1ms timer's lag, and CDP `Page.startScreencast` presented frames. rAF unscheduled
+reads as "no dropped frames" -- a page whose main thread never yields at all schedules no rAF, and
+a naive reader calls that a clean window. When the three disagree by more than 20% the window is
+marked `clocks_disagree` and the report layer excludes it from scoring rather than averaging a
+number that three instruments cannot agree happened.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from pathlib import Path
+from typing import Any, Optional
+
+from ..runtime.types import BenchContext, Cell, Instrument, Window
+from . import register_instrument
+
+_HERE = Path(__file__).resolve().parent
+
+# How far the three clocks may disagree before the window is not scoreable. Not tuned: it is the
+# threshold declared in the design, and the point is that it is declared rather than discovered.
+CLOCK_DISAGREEMENT_LIMIT = 0.20
+
+
+def _js(name: str) -> str:
+ from ..runtime import resources
+ return resources.read_text(f"instruments/{name}")
+
+
+class _PageInstrument(Instrument):
+ """Shared plumbing: install an init script once, drain a page function per window."""
+
+ script_name = ""
+ read_expr = ""
+
+ def __init__(self) -> None:
+ self.ctx: Optional[BenchContext] = None
+ self.page: Any = None
+ self._open_at: Optional[float] = None
+ self.unavailable: Optional[str] = None
+
+ def attach(self, ctx: BenchContext) -> None:
+ self.ctx = ctx
+ try:
+ ctx.context.add_init_script(_js(self.script_name))
+ except Exception as exc: # noqa: BLE001
+ self.unavailable = f"could not install {self.script_name}: {exc}"
+
+ def start_cell(self, cell: Cell) -> None:
+ # Re-read the page every cell. A crashed renderer is recovered by opening a NEW page, so
+ # an instrument that cached it in attach() would spend the rest of the run evaluating
+ # against a closed one.
+ self.page = self.ctx.page if self.ctx else None
+
+ def _eval(
+ self,
+ expr: str,
+ arg: Any = None,
+ ) -> Any:
+ if self.page is None:
+ return None
+ try:
+ return self.page.evaluate(expr, arg) if arg is not None else self.page.evaluate(expr)
+ except Exception as exc: # noqa: BLE001
+ self.unavailable = f"{type(exc).__name__}: {exc}"
+ return None
+
+
+@register_instrument(name = "frames", level = 0)
+def _frames():
+ return FramesInstrument()
+
+
+class FramesInstrument(_PageInstrument):
+ name = "frames"
+ level = 0
+ script_name = "frames.js"
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.clamp: Optional[dict] = None
+ self._screencast_frames = 0
+ self._screencast_on = False
+ self._lock = threading.Lock()
+
+ def attach(self, ctx: BenchContext) -> None:
+ super().attach(ctx)
+ self._arm_screencast()
+
+ def _arm_screencast(self) -> None:
+ """CDP presented frames: the only one of the three clocks that is not the page's own
+ opinion of itself. A page whose main thread is wedged reports nothing from rAF and nothing
+ from a timer; the compositor still presents, or visibly does not."""
+ ctx = self.ctx
+ if ctx is None or ctx.cdp is None:
+ return
+ try:
+
+ def on_frame(params):
+ with self._lock:
+ self._screencast_frames += 1
+ try:
+ ctx.cdp.send(
+ "Page.screencastFrameAck", {"sessionId": params.get("sessionId", 0)}
+ )
+ except Exception: # noqa: BLE001
+ pass
+
+ ctx.cdp.on("Page.screencastFrame", on_frame)
+ # Tiny frames: the point is the COUNT and its timing, and a full-size capture would
+ # cost the renderer real encode time inside the window being measured.
+ ctx.cdp.send(
+ "Page.startScreencast",
+ {
+ "format": "jpeg",
+ "quality": 1,
+ "maxWidth": 32,
+ "maxHeight": 32,
+ "everyNthFrame": 1,
+ },
+ )
+ self._screencast_on = True
+ except Exception: # noqa: BLE001
+ self._screencast_on = False
+
+ def calibrate(self, idle_ms: int = 1200) -> dict:
+ """Calibrate the timer clamp during an ENFORCED IDLE WINDOW.
+
+ Called by the session immediately before each measured window, with nothing streaming and
+ no action in flight. Calibrating from the first ticks of a page that already has 31,637
+ elements standing measures the app's steady-state load and calls it the timer floor, then
+ subtracts that floor out of every window and reports a saturated page as 0.2% busy.
+ """
+ if self.page is None:
+ self.clamp = {"clampMs": None, "reason": "no page"}
+ return self.clamp
+ self._eval("() => window.__sb.frames.beginCalibration()")
+ time.sleep(idle_ms / 1000)
+ self.clamp = self._eval("() => window.__sb.frames.endCalibration()") or {
+ "clampMs": None,
+ "reason": "calibration did not return",
+ }
+ return self.clamp
+
+ def open(self, window: Window) -> None:
+ self._open_at = time.monotonic()
+ with self._lock:
+ self._screencast_frames = 0
+ self._eval("() => window.__sb.frames.reset()")
+
+ def close(self, window: Window) -> Optional[dict]:
+ if self.unavailable:
+ return {"unavailable": self.unavailable, "frames_attempted": False}
+ elapsed_ms = (time.monotonic() - (self._open_at or time.monotonic())) * 1000
+ out = self._eval("(ms) => window.__sb.frames.read(ms)", elapsed_ms)
+ if out is None:
+ return {
+ "unavailable": self.unavailable or "the page did not answer",
+ "frames_attempted": False,
+ }
+ with self._lock:
+ presented = self._screencast_frames
+ out["driver_elapsed_ms"] = round(elapsed_ms, 2)
+ out.update(self._clock_agreement(out, presented, elapsed_ms))
+ return out
+
+ def _clock_agreement(self, out: dict, presented: int, elapsed_ms: float) -> dict:
+ """Three clocks, and a window they disagree about is not a window worth scoring.
+
+ WHAT THE SCREENCAST CLOCK IS, AND WHAT IT IS NOT. `Page.startScreencast` was first used
+ here as a third FRAME COUNT, on the reasoning that the compositor is the one observer that
+ is not the page's own opinion of itself. Measured, it presents 4 to 5 frames in a 4-second
+ window where the rAF loop counts 240 -- a 98% disagreement, in EVERY window, on a page
+ that was demonstrably running at a steady 60 fps with 2% blocked time. Chromium's
+ screencast emits on VISUAL CHANGE and is rate-limited; it is not a vsync counter. A gate
+ wired to it would have excluded every window in every run from scoring, and a gate that
+ always fires is a gate someone turns off.
+
+ So it is kept as a LIVENESS signal -- did the compositor present anything at all, which
+ separates "the page is idle" from "the renderer is wedged" -- and the agreement check is
+ between the two clocks that do measure the same thing: the rAF loop and the 1ms timer,
+ both of which are main-thread progress. If the main thread is blocked, rAF callbacks stop
+ AND timer ticks stop, and they must stop together.
+ """
+ raf = out.get("frames")
+ lag_ticks = out.get("lag_ticks")
+ clamp = out.get("clamp_ms")
+ expected_ticks = (elapsed_ms / clamp) if clamp else None
+ result: dict = {
+ "compositor_presented_frames": presented if self._screencast_on else None,
+ "compositor_presented": (presented > 0) if self._screencast_on else None,
+ "compositor_attempted": self._screencast_on,
+ "compositor_note": (
+ "a liveness signal, NOT a frame rate: Chromium's screencast "
+ "emits on visual change and is rate-limited"
+ ),
+ "timer_ticks_expected": None if expected_ticks is None else round(expected_ticks, 1),
+ }
+ if raf is None or not expected_ticks or lag_ticks is None:
+ result["clocks_agree"] = None
+ result["clocks_reason"] = (
+ "the timer clamp was not established, so the rAF loop has nothing to be checked "
+ "against and frame counts rest on the page's own report alone"
+ )
+ return result
+ # THE THIRD CLOCK IS NOT RESOLVED, AND THIS SAYS SO RATHER THAN INVENTING IT.
+ #
+ # The design called for a tri-clock check that excludes a window the three clocks disagree
+ # about. Two of the three are sound here. The 1ms timer has a real expectation -- ticks
+ # against elapsed/clamp -- and `timer_clock_ratio` below is a direct measure of how much
+ # of its budget the main thread could answer. The compositor is a liveness signal only,
+ # for the reason in this method's docstring.
+ #
+ # The rAF loop has NO sound expectation on a headless engine. There is no display, so the
+ # loop runs as fast as it can and the absolute frame rate is not a user-visible quantity
+ # at all. Normalising it against the best window seen in the cell was tried and is wrong:
+ # an early idle window runs far above 60, so every later window scores about 0.44 against
+ # it and `clocks_agree` came out FALSE on 34 of 34 windows of a page that was demonstrably
+ # steady at 60 fps with 2% blocked time. A gate that fires on every window of every run is
+ # worse than no gate, because it gets switched off and takes the real ones with it.
+ #
+ # So `clocks_agree` is null WITH A REASON, `timer_clock_ratio` is the load-bearing
+ # availability signal, and the frame columns are reported as the page's own account of
+ # itself. Restoring the third clock needs a vsync-locked source -- a headed run, or
+ # `Page.startScreencast` correlated against `LatencyInfo` in a trace, which is Layer 2's
+ # surface, not this one's.
+ result["timer_clock_ratio"] = round(lag_ticks / expected_ticks, 3)
+ result["clocks_agree"] = None
+ result["clocks_reason"] = (
+ "the tri-clock check is not implementable on a headless engine as designed: rAF has "
+ "no vsync to be checked against and the compositor screencast is rate-limited to "
+ "visual change. timer_clock_ratio is the sound availability signal; the frame columns "
+ "are the page's own report"
+ )
+ return result
+
+ def end_cell(self, cell: Cell) -> Optional[dict]:
+ return {"clamp": self.clamp, "overhead_ms": None, "overhead_attempted": False}
+
+ def detach(self) -> None:
+ if self._screencast_on and self.ctx and self.ctx.cdp:
+ try:
+ self.ctx.cdp.send("Page.stopScreencast")
+ except Exception: # noqa: BLE001
+ pass
+
+
+@register_instrument(name = "input", level = 0)
+def _input():
+ return InputInstrument()
+
+
+class InputInstrument(_PageInstrument):
+ """Armed and drained by the keystroke action rather than per window: a window that contained
+ no typing has nothing to report, and reporting a zero for it would be a bare zero."""
+
+ name = "input"
+ level = 0
+ script_name = "input.js"
+
+ def arm(self, selector: str) -> dict:
+ return self._eval("(s) => window.__sb.input.arm(s)", selector) or {
+ "armed": False,
+ "reason": self.unavailable or "the page did not answer",
+ }
+
+ def settled(self) -> dict:
+ """Whether a keystroke's paint is still in flight. `None` when the page cannot answer, so
+ a caller polling on it stops rather than looping to its bound."""
+ return self._eval("() => window.__sb.input.settled()")
+
+ def collect(self, expected: int) -> dict:
+ return self._eval("(n) => window.__sb.input.collect(n)", expected) or {
+ "samples": 0,
+ "samples_attempted": False,
+ "reason": self.unavailable or "the page did not answer",
+ }
+
+ def close(self, window: Window) -> Optional[dict]:
+ return None
+
+
+@register_instrument(name = "glass", level = 1)
+def _glass():
+ return GlassInstrument()
+
+
+class GlassInstrument(_PageInstrument):
+ """Level 1: it wraps hot accessors on Element.prototype and perturbs what it measures. The
+ headline numbers come from level 0, where it is not installed at all."""
+
+ name = "glass"
+ level = 1
+ script_name = "glass.js"
+
+ def open(self, window: Window) -> None:
+ self._eval("() => window.__sb.glass && window.__sb.glass.read()")
+
+ def close(self, window: Window) -> Optional[dict]:
+ out = self._eval("() => window.__sb.glass && window.__sb.glass.read()")
+ if out is None:
+ return {
+ "glass_attempted": False,
+ "unavailable": self.unavailable or "glass.js is not installed",
+ }
+ return out
diff --git a/tests/studio/studiobench/instruments/rss.py b/tests/studio/studiobench/instruments/rss.py
new file mode 100644
index 00000000000..e941d390a81
--- /dev/null
+++ b/tests/studio/studiobench/instruments/rss.py
@@ -0,0 +1,208 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Browser-tree RSS, sampled on a thread. SALVAGED from playwright_reasoning_pane.py.
+
+WHY NOT `performance.memory`. `usedJSHeapSize` is the JS heap of one renderer. Three things are
+wrong with reading it as the memory cost of a long thread. It excludes the DOM, which is where a
+thread of 31,637 elements actually lives, and which is C++ on the other side of the heap boundary.
+It excludes every other process in the browser tree, and the GPU process holds the layer buffers
+for a tall page. And it is a heap SIZE, so a garbage collection that has not run yet reads as
+growth and one that just ran reads as a leak repaired.
+
+RSS of the whole browser tree has none of those problems and one of its own: the browser's pid is
+not something Playwright exposes. The browser is launched by the node driver, which is a child of
+this process, so the browser is a grandchild with an engine-specific name and a per-platform
+executable path. Diffing the descendant set across the launch identifies it without knowing any of
+that.
+
+None, never 0.0. A renderer that has exited and a permission failure both produce no reading, and
+reporting either as zero would put a fabricated floor under `rss_growth_mb`.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from typing import Any, Optional
+
+from ..runtime.types import BenchContext, Cell, Instrument, Window
+from . import register_instrument
+
+try:
+ import psutil
+except ImportError: # pragma: no cover
+ psutil = None # type: ignore[assignment]
+
+SAMPLE_MS = 500
+
+
+def snapshot_children(root_pid: int) -> dict:
+ if psutil is None:
+ return {}
+ try:
+ return {p.pid: p for p in psutil.Process(root_pid).children(recursive = True)}
+ except Exception: # noqa: BLE001
+ return {}
+
+
+def new_roots(root_pid: int, before: dict) -> list:
+ """Processes under `root_pid` that were not there in `before`, topmost first."""
+ if psutil is None:
+ return []
+ after = snapshot_children(root_pid)
+ new = {pid: proc for pid, proc in after.items() if pid not in before}
+ roots = []
+ for pid, proc in new.items():
+ try:
+ if proc.ppid() not in new:
+ roots.append(proc)
+ except Exception: # noqa: BLE001
+ continue
+ return roots
+
+
+def tree_rss_mb(roots: list) -> Optional[float]:
+ if psutil is None or not roots:
+ return None
+ total = 0
+ read_any = False
+ for root in roots:
+ try:
+ procs = [root, *root.children(recursive = True)]
+ except Exception: # noqa: BLE001
+ continue
+ for proc in procs:
+ try:
+ total += proc.memory_info().rss
+ read_any = True
+ except Exception: # noqa: BLE001
+ continue
+ return round(total / 1048576, 1) if read_any else None
+
+
+class RssSampler:
+ """Samples on a THREAD, because the driver is blocked inside Playwright's sync API for the
+ whole run and cannot sample anything itself. Touches no Playwright object, only psutil, so it
+ is safe alongside the sync API's greenlet."""
+
+ def __init__(
+ self,
+ roots: list,
+ period_ms: int = SAMPLE_MS,
+ ) -> None:
+ self.roots = roots
+ self.period_s = max(0.05, period_ms / 1000)
+ self.samples: list[tuple[float, Optional[float]]] = []
+ self.reason: Optional[str] = None
+ if psutil is None:
+ self.reason = "psutil is not installed"
+ elif not roots:
+ self.reason = "the browser process could not be identified"
+ self._stop = threading.Event()
+ self._thread: Optional[threading.Thread] = None
+ self._t0 = 0.0
+
+ def start(self) -> None:
+ self._t0 = time.monotonic()
+ if self.reason is not None:
+ return
+ self._thread = threading.Thread(target = self._loop, daemon = True)
+ self._thread.start()
+
+ def _loop(self) -> None:
+ while not self._stop.is_set():
+ at = time.monotonic()
+ self.samples.append(((at - self._t0) * 1000, tree_rss_mb(self.roots)))
+ self._stop.wait(self.period_s)
+
+ def stop(self) -> None:
+ self._stop.set()
+ if self._thread is not None:
+ self._thread.join(timeout = 5)
+ if self.reason is None and not [s for _, s in self.samples if s is not None]:
+ self.reason = "no RSS reading succeeded for the browser tree"
+
+ def between(self, t0_ms: float, t1_ms: float) -> list[float]:
+ return [v for t, v in self.samples if v is not None and t0_ms <= t <= t1_ms]
+
+ def latest(self) -> Optional[float]:
+ usable = [v for _, v in self.samples if v is not None]
+ return usable[-1] if usable else None
+
+ def growth_mb(self) -> Optional[float]:
+ """Peak minus the FIRST reading of this run, not minus zero. A browser that is already up
+ carries a base footprint that has nothing to do with the thread, and the run before this
+ one in the same browser leaves its own. What is claimed is what this run ADDED."""
+ usable = [v for _, v in self.samples if v is not None]
+ if len(usable) < 2:
+ return None
+ return round(max(usable) - usable[0], 1)
+
+
+@register_instrument(name = "rss", level = 0)
+def _rss():
+ return RssInstrument()
+
+
+class RssInstrument(Instrument):
+ name = "rss"
+ level = 0
+
+ def __init__(self) -> None:
+ self.sampler: Optional[RssSampler] = None
+ self.ctx: Optional[BenchContext] = None
+ self._cell_start_ms: Optional[float] = None
+ self._open_ms: Optional[float] = None
+
+ def attach(self, ctx: BenchContext) -> None:
+ self.ctx = ctx
+ self.sampler = RssSampler(ctx.browser_procs)
+ self.sampler.start()
+
+ def start_cell(self, cell: Cell) -> None:
+ self._cell_start_ms = self._now_ms()
+
+ def _now_ms(self) -> float:
+ return (time.monotonic() - (self.sampler._t0 if self.sampler else 0.0)) * 1000
+
+ def open(self, window: Window) -> None:
+ self._open_ms = self._now_ms()
+
+ def close(self, window: Window) -> Optional[dict]:
+ if self.sampler is None:
+ return {"rss_attempted": False, "reason": "no sampler"}
+ if self.sampler.reason:
+ return {"rss_mb": None, "rss_attempted": False, "reason": self.sampler.reason}
+ window_samples = self.sampler.between(self._open_ms or 0.0, self._now_ms())
+ return {
+ "rss_attempted": True,
+ "rss_mb": window_samples[-1] if window_samples else self.sampler.latest(),
+ "rss_peak_mb": max(window_samples) if window_samples else None,
+ "rss_samples": len(window_samples),
+ }
+
+ def end_cell(self, cell: Cell) -> Optional[dict]:
+ if self.sampler is None or self.sampler.reason:
+ return {
+ "rss_growth_mb": None,
+ "rss_attempted": False,
+ "reason": (self.sampler.reason if self.sampler else "no sampler"),
+ }
+ cell_samples = self.sampler.between(self._cell_start_ms or 0.0, self._now_ms())
+ growth = None
+ if len(cell_samples) >= 2:
+ growth = round(max(cell_samples) - cell_samples[0], 1)
+ return {
+ "rss_attempted": True,
+ "rss_growth_mb": growth,
+ "rss_start_mb": cell_samples[0] if cell_samples else None,
+ "rss_peak_mb": max(cell_samples) if cell_samples else None,
+ "rss_run_growth_mb": self.sampler.growth_mb(),
+ "overhead_ms": 0.0,
+ "overhead_attempted": True,
+ }
+
+ def detach(self) -> None:
+ if self.sampler is not None:
+ self.sampler.stop()
diff --git a/tests/studio/studiobench/instruments/selfcheck.py b/tests/studio/studiobench/instruments/selfcheck.py
new file mode 100644
index 00000000000..ed263a0c4b7
--- /dev/null
+++ b/tests/studio/studiobench/instruments/selfcheck.py
@@ -0,0 +1,559 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Integrity gates. These run BEFORE any cell counts, and a failure ABORTS instead of reporting.
+
+Every gate here exists because the corresponding defect was live, produced a plausible table, and
+was believed for a while.
+
+ 120 ms STALL, SEEN WITHIN +/-20 ms
+ A frame recorder that cannot see a stall the harness injected itself cannot see a stall the
+ app produced. The failure this catches is a recorder that is running but attributing its
+ samples to the wrong window, which reads as a clean run rather than as a broken one.
+
+ 400 ms INPUT DELAY, MOVING KEYSTROKE p95 BY AT LEAST 350 ms
+ The input path is measured through `page.keyboard` so `latencyInfo` is real. A harness that
+ writes the textarea value directly and dispatches a synthetic `input` event measures the
+ DOM setter and nothing else, and that measurement does not move when the app gets slower.
+
+ A HEAVY SCENE AND A TRIVIAL SCENE DIFFERING BY MORE THAN 20%
+ If the instrument cannot separate a deliberately heavy page from a deliberately trivial
+ one, it is BLIND, and every "no significant difference" it produces is meaningless. This is
+ the gate that would have caught a fixture rendering a fifth of the content it claimed.
+
+ longtask READ FROM supportedEntryTypes, NEVER FROM WHETHER observe() THROWS
+ `PerformanceObserver.observe({type:"longtask"})` does not throw on WebKit or Firefox. It is
+ accepted and then never fires. A try/catch gate therefore reports both engines as supported
+ and then reports zero long tasks, which is a fabricated number, not a missing one.
+
+ THE _clock_pair CONTROL RATIO WITHIN 10%
+ The page's wall clock against the driver's monotonic clock. It must be flat across a ladder
+ by construction, so when it moves, the measurement moved and not the page. The driver half
+ is the MIDPOINT of two readings taken either side of the round trip: a single post-evaluate
+ reading charges the whole blocked main thread to the driver and produced 2.5% of pure skew
+ at the top of a ladder, in a quantity whose entire job is to be flat.
+
+ THREE-CLOCK AGREEMENT, >20% DISAGREEMENT EXCLUDES THE WINDOW
+ rAF callbacks, CDP `Page.startScreencast` presented frames, and a 1 ms timer, each
+ independently measuring the same window's elapsed time. This gate exists for one specific
+ reason: rAF STOPS BEING SCHEDULED when the compositor decides nothing is visible. A window
+ in that state reports no dropped frames, because it reports no frames, and "no dropped
+ frames" is how a completely unmeasured window looks in every table. A window whose clocks
+ disagree is marked `clock_disagreement` and EXCLUDED from scoring rather than believed.
+
+The pure evaluators below take numbers and return verdicts, so they are unit-testable without a
+browser. The driver functions underneath them are the thin part that talks to Playwright.
+"""
+
+from __future__ import annotations
+
+import time
+from dataclasses import dataclass, field
+from typing import Any, Callable, Mapping, Sequence
+
+from ..scoring.schema import ExcludedCell, Measure
+
+STALL_TOLERANCE_MS = 20.0
+INJECTED_STALL_MS = 120.0
+INJECTED_INPUT_DELAY_MS = 400.0
+MIN_INPUT_P95_SHIFT_MS = 350.0
+MIN_SCENE_CONTRAST_PCT = 20.0
+CLOCK_PAIR_TOLERANCE_PCT = 10.0
+TRI_CLOCK_TOLERANCE_PCT = 20.0
+
+
+class SelfCheckFailure(AssertionError):
+ """Raised when an integrity gate fails. The run aborts; no numbers are produced."""
+
+
+@dataclass
+class Gate:
+ """One integrity gate: what it measured, what it required, and whether it held."""
+
+ name: str
+ passed: bool
+ measured: Measure
+ expected: str
+ detail: str
+ fatal: bool = True
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "name": self.name,
+ "passed": bool(self.passed),
+ "measured": self.measured.to_json(),
+ "expected": self.expected,
+ "detail": self.detail,
+ "fatal": bool(self.fatal),
+ }
+
+ def render(self) -> str:
+ mark = "pass" if self.passed else ("FAIL" if self.fatal else "warn")
+ return (
+ f" [{mark}] {self.name:<28} {self.measured.display():>24} "
+ f"expected {self.expected}\n {self.detail}"
+ )
+
+
+@dataclass
+class SelfCheckReport:
+ gates: list[Gate] = field(default_factory = list)
+
+ @property
+ def ok(self) -> bool:
+ return all(gate.passed for gate in self.gates if gate.fatal)
+
+ @property
+ def failures(self) -> list[Gate]:
+ return [gate for gate in self.gates if gate.fatal and not gate.passed]
+
+ def raise_if_failed(self) -> None:
+ """Abort the run. A failed gate means the numbers would be about the instrument."""
+
+ if self.ok:
+ return
+ detail = "\n".join(f" {gate.name}: {gate.detail}" for gate in self.failures)
+ raise SelfCheckFailure(
+ "integrity gates failed; no cells will be measured and nothing will be reported.\n"
+ + detail
+ + "\nThis is deliberate. A run that reports numbers from a blind instrument is worse "
+ "than a run that reports nothing, because the numbers get quoted and the blindness "
+ "does not."
+ )
+
+ def render(self) -> str:
+ lines = ["INTEGRITY GATES (run before any cell counts; failure aborts)"]
+ lines.extend(gate.render() for gate in self.gates)
+ lines.append("")
+ lines.append(f" VERDICT: {'all gates held' if self.ok else 'ABORT'}")
+ return "\n".join(lines)
+
+ def to_json(self) -> dict[str, Any]:
+ return {"ok": self.ok, "gates": [gate.to_json() for gate in self.gates]}
+
+
+# ---------------------------------------------------------------------------------------
+# pure evaluators
+# ---------------------------------------------------------------------------------------
+
+
+def evaluate_stall_gate(
+ observed_ms: float | None,
+ *,
+ injected_ms: float = INJECTED_STALL_MS,
+ tolerance_ms: float = STALL_TOLERANCE_MS,
+) -> Gate:
+ """The frame recorder must see an injected stall, at roughly the size it was injected."""
+
+ if observed_ms is None:
+ return Gate(
+ name = "injected_stall_seen",
+ passed = False,
+ measured = Measure.failed("ms", "the frame recorder reported no stall at all"),
+ expected = f"{injected_ms:g} +/- {tolerance_ms:g} ms",
+ detail = (
+ "a stall this harness injected itself was not observed. The recorder is not "
+ "watching the window it thinks it is"
+ ),
+ )
+ error = abs(float(observed_ms) - injected_ms)
+ return Gate(
+ name = "injected_stall_seen",
+ passed = error <= tolerance_ms,
+ measured = Measure.read(float(observed_ms), "ms"),
+ expected = f"{injected_ms:g} +/- {tolerance_ms:g} ms",
+ detail = (
+ f"observed longest frame is {error:.1f} ms from the injected stall"
+ + ("" if error <= tolerance_ms else "; the recorder is mis-attributing samples")
+ ),
+ )
+
+
+def evaluate_input_delay_gate(
+ baseline_p95_ms: float | None,
+ delayed_p95_ms: float | None,
+ *,
+ injected_ms: float = INJECTED_INPUT_DELAY_MS,
+ min_shift_ms: float = MIN_INPUT_P95_SHIFT_MS,
+) -> Gate:
+ """A 400 ms input delay must move keystroke p95 by at least 350 ms."""
+
+ if baseline_p95_ms is None or delayed_p95_ms is None:
+ return Gate(
+ name = "input_delay_seen",
+ passed = False,
+ measured = Measure.failed("ms", "one of the two keystroke measurements is missing"),
+ expected = f">= {min_shift_ms:g} ms shift for a {injected_ms:g} ms delay",
+ detail = (
+ "without both readings there is no shift to check, and an input path that is not "
+ "verified is an input path that may be measuring the DOM setter"
+ ),
+ )
+ shift = float(delayed_p95_ms) - float(baseline_p95_ms)
+ return Gate(
+ name = "input_delay_seen",
+ passed = shift >= min_shift_ms,
+ measured = Measure.read(shift, "ms"),
+ expected = f">= {min_shift_ms:g} ms shift for a {injected_ms:g} ms delay",
+ detail = (
+ f"keystroke p95 moved {shift:.1f} ms"
+ + (
+ ""
+ if shift >= min_shift_ms
+ else "; the keystroke path is not going through the real input pipeline, so it "
+ "will not move when the app gets slower either"
+ )
+ ),
+ )
+
+
+def evaluate_scene_contrast_gate(
+ heavy_ms: float | None,
+ trivial_ms: float | None,
+ *,
+ min_pct: float = MIN_SCENE_CONTRAST_PCT,
+) -> Gate:
+ """A deliberately heavy scene and a trivial one must differ, or the instrument is blind."""
+
+ if heavy_ms is None or trivial_ms is None or trivial_ms <= 0:
+ return Gate(
+ name = "scene_contrast",
+ passed = False,
+ measured = Measure.failed("%", "one of the two contrast scenes produced no reading"),
+ expected = f"> {min_pct:g}% difference",
+ detail = "a contrast check with a missing side proves nothing",
+ )
+ contrast = (float(heavy_ms) - float(trivial_ms)) / float(trivial_ms) * 100.0
+ return Gate(
+ name = "scene_contrast",
+ passed = contrast > min_pct,
+ measured = Measure.read(contrast, "%"),
+ expected = f"> {min_pct:g}% difference",
+ detail = (
+ f"the heavy scene is {contrast:.1f}% slower than the trivial one"
+ if contrast > min_pct
+ else (
+ f"only {contrast:.1f}% between a deliberately heavy scene and a trivial one. The "
+ "instrument is BLIND, and every null result it produces is uninformative"
+ )
+ ),
+ )
+
+
+def evaluate_longtask_support(supported_entry_types: Sequence[str] | None) -> Gate:
+ """Read support from `supportedEntryTypes`. Never from whether `observe()` throws."""
+
+ if supported_entry_types is None:
+ return Gate(
+ name = "longtask_support",
+ passed = False,
+ measured = Measure.failed("bool", "supportedEntryTypes was not readable"),
+ expected = "supportedEntryTypes readable",
+ detail = (
+ "the support list itself could not be read, so support cannot be established by "
+ "the only method that works"
+ ),
+ fatal = False,
+ )
+ supported = "longtask" in list(supported_entry_types)
+ return Gate(
+ name = "longtask_support",
+ passed = True, # not supporting longtask is a fact about the engine, not a failure
+ measured = Measure.read(1.0 if supported else 0.0, "bool"),
+ expected = "read from supportedEntryTypes",
+ detail = (
+ "longtask entries are available on this engine"
+ if supported
+ else (
+ "this engine does not support longtask. Long-task numbers will read as NOT "
+ "ATTEMPTED rather than as zero. observe() would have accepted the type and then "
+ "never fired, which is why support is read from the list and not from a try/catch"
+ )
+ ),
+ fatal = False,
+ )
+
+
+def evaluate_clock_pair(
+ page_ms: float | None,
+ driver_ms: float | None,
+ *,
+ tolerance_pct: float = CLOCK_PAIR_TOLERANCE_PCT,
+) -> Gate:
+ """The control ratio between the page's wall clock and the driver's monotonic clock."""
+
+ if page_ms is None or driver_ms is None or driver_ms <= 0:
+ return Gate(
+ name = "clock_pair_control",
+ passed = False,
+ measured = Measure.failed("ratio", "a clock pair reading is missing"),
+ expected = f"1.0 +/- {tolerance_pct:g}%",
+ detail = "without the control ratio there is nothing holding the ladder flat",
+ )
+ ratio = float(page_ms) / float(driver_ms)
+ drift_pct = abs(ratio - 1.0) * 100.0
+ return Gate(
+ name = "clock_pair_control",
+ passed = drift_pct <= tolerance_pct,
+ measured = Measure.read(ratio, "ratio"),
+ expected = f"1.0 +/- {tolerance_pct:g}%",
+ detail = (
+ f"the control ratio is {drift_pct:.2f}% from unity"
+ + (
+ ""
+ if drift_pct <= tolerance_pct
+ else ". This quantity is flat by construction, so a move means the MEASUREMENT "
+ "moved, not the page"
+ )
+ ),
+ )
+
+
+@dataclass
+class TriClockVerdict:
+ """Three clocks over one window, and whether the window survives."""
+
+ agreed: bool
+ wall_ms: float
+ spans: dict[str, float | None]
+ worst_clock: str | None
+ worst_disagreement_pct: float | None
+ reason: str
+
+ def excluded_cell(self, cell_id: str) -> ExcludedCell | None:
+ if self.agreed:
+ return None
+ return ExcludedCell(
+ cell_id = cell_id,
+ reason = "clock_disagreement",
+ count = 1,
+ detail = self.reason,
+ )
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "agreed": bool(self.agreed),
+ "wall_ms": float(self.wall_ms),
+ "spans": dict(self.spans),
+ "worst_clock": self.worst_clock,
+ "worst_disagreement_pct": self.worst_disagreement_pct,
+ "reason": self.reason,
+ }
+
+
+def evaluate_tri_clock(
+ *,
+ wall_ms: float,
+ raf_span_ms: float | None,
+ screencast_span_ms: float | None,
+ timer_span_ms: float | None,
+ raf_frames: int | None = None,
+ tolerance_pct: float = TRI_CLOCK_TOLERANCE_PCT,
+) -> TriClockVerdict:
+ """Compare each clock's own measurement of the window against wall time.
+
+ Each of the three clocks independently spans the window: the rAF loop by summing its frame
+ gaps, the screencast by the interval between its first and last presented frame, the 1 ms
+ timer by summing its tick gaps. All three should equal the wall duration, and a clock that
+ covers materially less than the window did not observe part of it.
+
+ THE CASE THIS IS FOR. When the compositor decides nothing is visible it stops scheduling rAF
+ callbacks entirely. The frame recorder then reports very few frames and no dropped ones, and
+ a report reads that as a smooth window. Here it shows up as an rAF span far short of wall
+ time while the timer clock covers the whole window, which is the correct conclusion: the
+ window was not measured.
+ """
+
+ spans: dict[str, float | None] = {
+ "raf": None if raf_span_ms is None else float(raf_span_ms),
+ "screencast": None if screencast_span_ms is None else float(screencast_span_ms),
+ "timer": None if timer_span_ms is None else float(timer_span_ms),
+ }
+
+ if wall_ms <= 0:
+ return TriClockVerdict(
+ agreed = False,
+ wall_ms = float(wall_ms),
+ spans = spans,
+ worst_clock = None,
+ worst_disagreement_pct = None,
+ reason = "the window has no positive wall duration, so no clock can be checked",
+ )
+
+ if raf_frames is not None and raf_frames <= 0:
+ return TriClockVerdict(
+ agreed = False,
+ wall_ms = float(wall_ms),
+ spans = spans,
+ worst_clock = "raf",
+ worst_disagreement_pct = 100.0,
+ reason = (
+ "the rAF loop produced no frames at all. That is not a smooth window, it is an "
+ "unmeasured one: rAF stops being scheduled when the compositor decides nothing "
+ "is visible"
+ ),
+ )
+
+ disagreements: dict[str, float] = {}
+ for name, span in spans.items():
+ if span is None:
+ continue
+ disagreements[name] = abs(span - float(wall_ms)) / float(wall_ms) * 100.0
+
+ if len(disagreements) < 2:
+ return TriClockVerdict(
+ agreed = False,
+ wall_ms = float(wall_ms),
+ spans = spans,
+ worst_clock = None,
+ worst_disagreement_pct = None,
+ reason = (
+ f"only {len(disagreements)} of three clocks reported. Agreement between fewer "
+ "than two clocks is not agreement"
+ ),
+ )
+
+ worst_clock = max(disagreements, key = lambda k: disagreements[k])
+ worst = disagreements[worst_clock]
+ agreed = worst <= tolerance_pct
+ return TriClockVerdict(
+ agreed = agreed,
+ wall_ms = float(wall_ms),
+ spans = spans,
+ worst_clock = worst_clock,
+ worst_disagreement_pct = worst,
+ reason = (
+ f"all reporting clocks are within {tolerance_pct:g}% of wall time "
+ f"(worst: {worst_clock} at {worst:.1f}%)"
+ if agreed
+ else (
+ f"the {worst_clock} clock is {worst:.1f}% away from wall time, beyond the "
+ f"{tolerance_pct:g}% tolerance. The window is marked clock_disagreement and "
+ "excluded from scoring"
+ )
+ ),
+ )
+
+
+# ---------------------------------------------------------------------------------------
+# browser-side snippets and drivers
+# ---------------------------------------------------------------------------------------
+
+#: Burns a known amount of main-thread time once, on the next frame. A busy wait, not a sleep:
+#: a sleep is recovered through a different scheduler path than a blocked main thread, which is
+#: the thing being calibrated.
+STALL_INJECT_JS = """
+(stallMs) => {
+ return new Promise((resolve) => {
+ requestAnimationFrame(() => {
+ const started = performance.now();
+ while (performance.now() - started < stallMs) { /* spin */ }
+ requestAnimationFrame(() => resolve(performance.now() - started));
+ });
+ });
+}
+"""
+
+#: Adds a fixed delay to every keydown before the app sees it, by installing a capturing listener
+#: that blocks. Installed pre-boot so it sits ahead of every app handler.
+INPUT_DELAY_INIT_JS = """
+(() => {
+ if (window.__sbInputDelay) { return; }
+ const delayMs = %(delay_ms)f;
+ const S = { delayMs: delayMs, events: 0, burnedMs: 0, armed: false };
+ window.__sbInputDelay = S;
+ const block = () => {
+ if (!S.armed) { return; }
+ const started = performance.now();
+ while (performance.now() - started < delayMs) { /* spin */ }
+ S.events += 1;
+ S.burnedMs += performance.now() - started;
+ };
+ window.addEventListener("keydown", block, true);
+ S.arm = () => { S.armed = true; };
+ S.disarm = () => { S.armed = false; };
+})();
+"""
+
+#: Reads `supportedEntryTypes` directly. Never a try/catch around observe().
+LONGTASK_SUPPORT_JS = """
+() => {
+ try {
+ return Array.from(PerformanceObserver.supportedEntryTypes || []);
+ } catch (e) {
+ return null;
+ }
+}
+"""
+
+
+def input_delay_init_script(delay_ms: float = INJECTED_INPUT_DELAY_MS) -> str:
+ return INPUT_DELAY_INIT_JS % {"delay_ms": float(delay_ms)}
+
+
+def clock_pair(page: Any) -> tuple[float, float]:
+ """The page's wall clock and the driver's monotonic clock, read around one round trip.
+
+ The driver half is the MIDPOINT of readings taken either side of the evaluate. The page can
+ only answer while its main thread is free, so a single reading taken after the call charges
+ the entire blocked main thread to the driver's clock. That mistake produced 2.5% of pure
+ round-trip skew at the top of a ladder, in the one quantity whose job is to be flat.
+ """
+
+ before = time.monotonic()
+ page_ms = page.evaluate("() => Date.now()")
+ after = time.monotonic()
+ return float(page_ms), (before + after) / 2.0
+
+
+def read_longtask_support(page: Any) -> list[str] | None:
+ try:
+ return page.evaluate(LONGTASK_SUPPORT_JS)
+ except Exception:
+ return None
+
+
+def run_gates(
+ *,
+ stall_observed_ms: float | None,
+ keystroke_p95_baseline_ms: float | None,
+ keystroke_p95_delayed_ms: float | None,
+ heavy_scene_ms: float | None,
+ trivial_scene_ms: float | None,
+ supported_entry_types: Sequence[str] | None,
+ clock_pair_page_ms: float | None,
+ clock_pair_driver_ms: float | None,
+ injected_stall_ms: float = INJECTED_STALL_MS,
+ injected_input_delay_ms: float = INJECTED_INPUT_DELAY_MS,
+) -> SelfCheckReport:
+ """Assemble every gate from already-collected readings.
+
+ Pure: the caller does the driving, this does the judging. That split is what lets the whole
+ gate set be unit-tested, including the cases where it must FAIL, which is the half that never
+ gets exercised when the checks live inline in the driver.
+ """
+
+ report = SelfCheckReport()
+ report.gates.append(evaluate_stall_gate(stall_observed_ms, injected_ms = injected_stall_ms))
+ report.gates.append(
+ evaluate_input_delay_gate(
+ keystroke_p95_baseline_ms,
+ keystroke_p95_delayed_ms,
+ injected_ms = injected_input_delay_ms,
+ )
+ )
+ report.gates.append(evaluate_scene_contrast_gate(heavy_scene_ms, trivial_scene_ms))
+ report.gates.append(evaluate_longtask_support(supported_entry_types))
+ report.gates.append(evaluate_clock_pair(clock_pair_page_ms, clock_pair_driver_ms))
+ return report
+
+
+def guard(report: SelfCheckReport, *, on_abort: Callable[[str], None] | None = None) -> None:
+ """Abort the run if any fatal gate failed. Called before the first cell is measured."""
+
+ if report.ok:
+ return
+ message = report.render()
+ if on_abort is not None:
+ on_abort(message)
+ report.raise_if_failed()
diff --git a/tests/studio/studiobench/instruments/selftest/test_studiobench_input_coverage.py b/tests/studio/studiobench/instruments/selftest/test_studiobench_input_coverage.py
new file mode 100644
index 00000000000..9ce7949c651
--- /dev/null
+++ b/tests/studio/studiobench/instruments/selftest/test_studiobench_input_coverage.py
@@ -0,0 +1,305 @@
+# 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 keystroke metric must not drop the keystroke it exists to catch.
+
+`collect()` used to be called after a FIXED 200 ms wait, so a keystroke whose paint had not
+resolved by that moment was simply absent from the samples. The keystroke that has not painted yet
+is the SLOWEST one, so the reading systematically omitted its own worst case: measured against the
+real `input.js`, a 500 ms keystroke vanished from a reading whose max was 20 ms. The action still
+reported success, because the only thing it checked was that the composer's value had grown by the
+number of characters typed.
+
+That inverts under the condition the metric exists to detect -- a build that makes typing worse has
+more unpainted keystrokes at the drain, so it drops more of its slowest samples and reads FASTER --
+and `keystroke_p95_ms` is the highest-weight metric in the scoring table. It also feeds the
+null-treatment control, so an artificially tight reading there tightens the noise floor that every
+later comparison on that machine is judged against.
+
+The remedy is not a bigger constant, which has the same defect on a slower machine or a heavier
+rung. The wait ends when the WORK ends: the driver polls `settled()` until nothing is in flight,
+bounded only so a wedged renderer cannot eat the slot, and the reading then has to account for
+every keystroke the instrument saw before it may be quoted.
+
+Two levels. The JS half runs the shipped `input.js` under node over a controlled clock, so the
+paint that is still in flight really is in flight. The Python half drives the shipped `keystroke`
+action and asserts what a reader ends up with.
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+import subprocess
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.runtime.types import ActionContext, Cell, Window # noqa: E402
+from studiobench.scene.actions import keystroke # noqa: E402
+
+INPUT_JS = Path(__file__).resolve().parents[1] / "input.js"
+
+#: A DOM small enough to run the instrument and explicit enough to hold a paint open. Paints
+#: resolve only when this driver says so, which is what makes "still in flight at the drain" a
+#: state the test can create rather than race for.
+DRIVER = """
+import fs from "node:fs";
+let now = 0;
+const listeners = { window: {}, target: {} };
+class Ev {
+ constructor(type, target, timeStamp) {
+ this.type = type;
+ this.target = target;
+ this.timeStamp = timeStamp;
+ }
+}
+const drop = (bag, t, fn) => { bag[t] = (bag[t] || []).filter((f) => f !== fn); };
+const target = {
+ value: "",
+ addEventListener: (t, fn) => ((listeners.target[t] ||= []).push(fn)),
+ removeEventListener: (t, fn) => drop(listeners.target, t, fn),
+};
+const paints = [];
+globalThis.window = {
+ addEventListener: (t, fn) => ((listeners.window[t] ||= []).push(fn)),
+ removeEventListener: (t, fn) => drop(listeners.window, t, fn),
+ __sbNextPaint: () => new Promise((resolve) => paints.push(resolve)),
+};
+globalThis.document = { querySelector: () => target };
+globalThis.performance = { now: () => now };
+globalThis.requestAnimationFrame = (fn) => setTimeout(() => fn(now), 0);
+eval(fs.readFileSync(process.argv[2], "utf8"));
+const input = window.__sb.input;
+const fire = (bucket, ev) => (listeners[bucket][ev.type] || []).forEach((fn) => fn(ev));
+const tick = () => new Promise((r) => setImmediate(r));
+
+const COUNT = 12, FAST = 20, SLOW = 500;
+const MODE = process.argv[3];
+
+async function main() {
+ input.arm("textarea");
+ for (let i = 0; i < COUNT; i += 1) {
+ now += 60;
+ fire("window", new Ev("keydown", target, now));
+ target.value += "a";
+ fire("target", new Ev("input", target, now));
+ await tick();
+ if (i !== COUNT - 1) { now += FAST; paints.shift()?.(now); await tick(); }
+ }
+ if (MODE === "fixed") {
+ // The old drain: a flat 200 ms, which the 500 ms paint outlives.
+ now += 200;
+ await tick();
+ } else {
+ let waited = 0;
+ while (input.settled().pending && waited < 3000) {
+ now += 25; waited += 25;
+ if (waited >= SLOW - FAST) paints.shift()?.(now);
+ await tick();
+ }
+ }
+ console.log(JSON.stringify(input.collect(COUNT)));
+}
+main();
+"""
+
+
+def _node():
+ return shutil.which("node")
+
+
+def _run(tmp_path: Path, mode: str) -> dict:
+ driver = tmp_path / "driver.mjs"
+ driver.write_text(DRIVER, encoding = "utf-8")
+ out = subprocess.run(
+ [_node(), str(driver), str(INPUT_JS), mode],
+ capture_output = True,
+ text = True,
+ timeout = 60,
+ )
+ assert out.returncode == 0, out.stderr
+ return json.loads(out.stdout.strip().splitlines()[-1])
+
+
[email protected](_node() is None, reason = "node is not installed")
+def test_a_fixed_wait_loses_the_slowest_keystroke(tmp_path):
+ """THE DEFECT, against the shipped instrument. Eleven keystrokes paint in 20 ms and the
+ twelfth takes 500 ms; a flat 200 ms drain collects only the eleven fast ones."""
+
+ got = _run(tmp_path, "fixed")
+
+ assert got["samples"] == 11
+ assert got["max_ms"] == 20
+ # The instrument knows it is losing one, which is what makes the reading refusable.
+ assert got["pending_at_collect"] is True
+ assert got["inputs_seen"] == 12
+
+
[email protected](_node() is None, reason = "node is not installed")
+def test_settling_on_the_work_keeps_it(tmp_path):
+ got = _run(tmp_path, "settle")
+
+ assert got["samples"] == 12
+ assert got["max_ms"] == 500
+ assert got["p95_ms"] == 500
+ assert got["pending_at_collect"] is False
+ assert got["inputs_seen"] == 12
+
+
+# ── what the action does with it ─────────────────────────────────────────────────────────────
+
+
+class _Page:
+ def __init__(self) -> None:
+ self.value = ""
+
+ def query_selector(self, selector):
+ return object() if "Message input" in selector else None
+
+ def click(self, *a, **k) -> None:
+ pass
+
+ def wait_for_timeout(self, ms) -> None:
+ pass
+
+ @property
+ def keyboard(self):
+ return types.SimpleNamespace(type = self._type)
+
+ def _type(
+ self,
+ text,
+ delay = 0,
+ ) -> None:
+ self.value += text
+
+
+class _Instrument:
+ """The input instrument, with the reading it will return dictated by the test."""
+
+ def __init__(
+ self,
+ reading: dict,
+ *,
+ pending_forever: bool = False,
+ ) -> None:
+ self.reading = reading
+ self.pending_forever = pending_forever
+ self.polls = 0
+
+ def arm(self, selector: str) -> dict:
+ return {"armed": True, "baseline_length": 0}
+
+ def settled(self) -> dict:
+ self.polls += 1
+ return {"pending": self.pending_forever, "samples": 0, "seen": 0}
+
+ def collect(self, expected: int) -> dict:
+ return self.reading
+
+
+def _run_keystroke(inst: _Instrument, count: int = 12):
+ page = _Page()
+ ctx = ActionContext(
+ page = page,
+ cdp = None,
+ cell = Cell(cell_id = "r10K.A0.rep0", rung = "10K", rung_tokens = 10_000),
+ window = Window(name = "action:keystroke", kind = "action", cell = None, t_open_ms = 0.0),
+ args = {"count": count, "_input_instrument": inst},
+ budget_ms = 6_000,
+ dom = None,
+ log = lambda msg: None,
+ )
+ return keystroke(ctx)
+
+
+def _reading(**overrides) -> dict:
+ base = {
+ "samples": 12,
+ "samples_attempted": True,
+ "expected": 12,
+ "inputs_seen": 12,
+ "pending_at_collect": False,
+ "coalesced": 0,
+ "p50_ms": 18.0,
+ "p95_ms": 20.0,
+ "max_ms": 20.0,
+ "first_ms": 40.0,
+ "text_length": 12,
+ "grew_by": 12,
+ }
+ base.update(overrides)
+ return base
+
+
+def test_a_healthy_reading_still_passes():
+ result = _run_keystroke(_Instrument(_reading()))
+
+ assert result.ran is True
+ assert result.expect_ok is True
+ assert result.timings["p95_ms"] == 20.0
+
+
+def test_a_jammed_page_that_coalesced_most_of_its_keystrokes_still_passes():
+ """A LOW SAMPLE COUNT IS NOT A FAULT, it is the finding. On a jammed page most keystrokes
+ arrive behind a paint that has not finished, and the slow paint that swallowed them IS
+ measured. What matters is that every input is accounted for."""
+
+ result = _run_keystroke(_Instrument(_reading(samples = 3, coalesced = 9, p95_ms = 480.0)))
+
+ assert result.expect_ok is True
+ assert result.expect["coalesced"] == 9
+ assert result.timings["p95_ms"] == 480.0
+
+
+def test_a_reading_with_a_keystroke_still_unpainted_is_not_quotable():
+ result = _run_keystroke(_Instrument(_reading(samples = 11, pending_at_collect = True, max_ms = 20.0)))
+
+ assert result.ran is True
+ assert result.expect_ok is False
+ assert "still unpainted" in result.reason
+ assert result.expect["pending_at_collect"] is True
+
+
+def test_a_keystroke_that_never_reached_the_instrument_is_not_quotable():
+ """`grew_by` is satisfied by a textarea whose value is right; it says nothing about which
+ keystrokes were measured on the way in."""
+
+ result = _run_keystroke(_Instrument(_reading(samples = 8, inputs_seen = 8, coalesced = 0)))
+
+ assert result.expect_ok is False
+ assert "8 of 8" in result.reason or "covers" in result.reason
+ assert result.expect["inputs_seen"] == 8
+
+
+def test_the_composer_check_still_reports_its_own_failure():
+ """The control: the pre-existing reason is unchanged when it is the one that failed."""
+
+ result = _run_keystroke(_Instrument(_reading(grew_by = 4, text_length = 4)))
+
+ assert result.expect_ok is False
+ assert "composer value grew by 4" in result.reason
+
+
+def test_the_drain_polls_until_the_page_settles_rather_than_waiting_a_constant():
+ inst = _Instrument(_reading(), pending_forever = True)
+
+ _run_keystroke(inst)
+
+ # It kept asking, and stopped at its bound rather than at a fixed interval.
+ assert inst.polls > 1
+
+
+def test_no_samples_at_all_is_still_not_run():
+ result = _run_keystroke(_Instrument(_reading(samples = 0, inputs_seen = 0)))
+
+ assert result.ran is False
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/instruments/selftest/test_studiobench_input_latency.py b/tests/studio/studiobench/instruments/selftest/test_studiobench_input_latency.py
new file mode 100644
index 00000000000..6fb98499b99
--- /dev/null
+++ b/tests/studio/studiobench/instruments/selftest/test_studiobench_input_latency.py
@@ -0,0 +1,123 @@
+# 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 keystroke instrument measures keystroke-to-paint, including the wait before the handler.
+
+THE GATE THIS ENFORCES IS THE HARNESS'S OWN. `instruments/selfcheck.py` injects a 400 ms blocking
+`keydown` listener and requires that it move keystroke p95 by at least 350 ms. `input.js` used to
+start its clock inside the `input` handler, which is dispatched as the default action of that same
+keydown -- so the stall had already finished, the wait was subtracted out of every sample, and the
+measured p95 moved by -14.8 ms while the user waited 400 ms. The highest-weight metric in the
+scoring table read clean exactly when typing was at its worst.
+
+This drives a real engine because the defect only exists in a real input pipeline: a synthetic
+`input` event dispatched from a script cannot show the queueing delay at all, which is the reason
+the driver types with `page.keyboard` in the first place.
+
+Skips cleanly with no engine installed, because the selftest job runs on a machine with none.
+
+ python -m pytest tests/studio/studiobench/instruments/selftest/test_studiobench_input_latency.py
+"""
+
+from __future__ import annotations
+
+import sys
+import urllib.parse
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.instruments.selfcheck import ( # noqa: E402
+ INJECTED_INPUT_DELAY_MS,
+ evaluate_input_delay_gate,
+ input_delay_init_script,
+)
+from studiobench.runtime import resources # noqa: E402
+
+PAGE = (
+ "<!doctype html><meta charset=utf-8><body>"
+ "<textarea aria-label='Message input' rows='4'></textarea></body>"
+)
+URL = "data:text/html," + urllib.parse.quote(PAGE)
+SELECTOR = "textarea[aria-label='Message input']"
+CHARS = 12
+
+
+def _engine(pw):
+ """Chromium if it is downloaded, else whichever engine is. `None` means skip."""
+ for name in ("chromium", "webkit", "firefox"):
+ try:
+ if Path(getattr(pw, name).executable_path).exists():
+ return name
+ except Exception: # noqa: BLE001
+ continue
+ return None
+
+
+def _typed(page, *, delay_armed: bool) -> dict:
+ page.evaluate(
+ "(on) => (on ? window.__sbInputDelay.arm() : window.__sbInputDelay.disarm())", delay_armed
+ )
+ page.fill(SELECTOR, "")
+ page.click(SELECTOR)
+ page.evaluate("(s) => window.__sb.input.arm(s)", SELECTOR)
+ page.keyboard.type("a" * CHARS, delay = 60)
+ page.wait_for_timeout(1000)
+ got = page.evaluate("(n) => window.__sb.input.collect(n)", CHARS)
+ got["injected_events"] = page.evaluate("() => window.__sbInputDelay.events")
+ return got
+
+
+def test_an_injected_keydown_stall_moves_keystroke_p95():
+ playwright = pytest.importorskip("playwright.sync_api", reason = "playwright is not installed")
+ # IMPORTORSKIP IS NOT ENOUGH IN THIS SUITE. tests/studio/
+ # test_heavy_thread_measurement_integrity.py puts a stub `playwright.sync_api` into
+ # `sys.modules` at collection time and, as its own docstring says, it stays there for the rest
+ # of the session. So on the CPU job the import above SUCCEEDS against the stub and every name
+ # it hands back raises RuntimeError when called. The stub is a bare ModuleType with no
+ # `__file__`, which the real package always has, so that is what distinguishes them.
+ if getattr(playwright, "__file__", None) is None:
+ pytest.skip("playwright.sync_api is the CPU-job stub, so there is no browser to drive")
+
+ with playwright.sync_playwright() as pw:
+ name = _engine(pw)
+ if name is None:
+ pytest.skip("no Playwright engine is downloaded on this machine")
+ browser = getattr(pw, name).launch()
+ try:
+ context = browser.new_context()
+ context.add_init_script(input_delay_init_script())
+ context.add_init_script(resources.read_text("instruments/input.js"))
+ page = context.new_page()
+ # `goto`, never `set_content`: `document.open()` removes every listener registered on
+ # the window, so a page built that way silently discards the injected stall and the
+ # test would pass against a broken instrument.
+ page.goto(URL)
+
+ quiet = _typed(page, delay_armed = False)
+ delayed = _typed(page, delay_armed = True)
+ finally:
+ browser.close()
+
+ assert quiet["samples"] == CHARS, quiet
+ assert delayed["samples"] == CHARS, delayed
+ assert delayed["injected_events"] >= CHARS, delayed
+
+ # THE GATE the harness would run on these two readings, applied to the readings the instrument
+ # actually produces. This is the assertion that fails on an input-anchored clock.
+ gate = evaluate_input_delay_gate(quiet["p95_ms"], delayed["p95_ms"])
+ assert gate.passed, f"{gate.detail}: quiet={quiet}, delayed={delayed}"
+
+ # Anchored on the key event, not on the input handler, or the wait cannot be seen at all.
+ assert delayed.get("unanchored") == 0, delayed
+ assert quiet.get("unanchored") == 0, quiet
+
+ # The instrument's own account of the two halves.
+ assert delayed.get("input_delay_p95_ms") >= INJECTED_INPUT_DELAY_MS * 0.8, delayed
+ assert (quiet.get("input_delay_p95_ms") or 0) < 100.0, quiet
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/instruments/selftest/test_studiobench_tracing_window.py b/tests/studio/studiobench/instruments/selftest/test_studiobench_tracing_window.py
new file mode 100644
index 00000000000..e1acbb85a48
--- /dev/null
+++ b/tests/studio/studiobench/instruments/selftest/test_studiobench_tracing_window.py
@@ -0,0 +1,190 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Losing the optional metrics probe costs the cross-check, and only the cross-check.
+
+`start_cell` says so in as many words -- "Metrics are a cross-check, not the measurement. Losing
+them costs the cross-check and nothing else" -- and the handler in `open()` did something else
+entirely. `Tracing.start` had already succeeded by the time `MetricsWindow.open()` ran, so
+clearing `self.capture` there abandoned a LIVE tracing session:
+
+ `close()` returns early while `self.capture is None`, so `Tracing.end` is never sent.
+ `detach()` is guarded on the same attribute, so it cannot stop it either.
+ Tracing is per-browser (`TraceCapture`: "a second `Tracing.start` fails with 'Tracing has
+ already been started (possibly in another tab)'"), so EVERY later window fails to start and
+ reports `tracing did not start for this window`.
+
+One failed `Performance.getMetrics` therefore cost the tracing instrument for the rest of the run
+-- and left a `recordAsMuchAsPossible` capture recording underneath every number taken after it.
+It does not take a broken browser to get there: `start_cell` enables the Performance domain under
+a bare `except`, and `read_metrics` raises rather than returning empty when that domain is off.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.instruments.tracing import TracingInstrument # noqa: E402
+
+TRACE_TEXT = json.dumps(
+ {
+ "traceEvents": [
+ {
+ "name": "RunTask",
+ "ph": "X",
+ "ts": 0,
+ "dur": 1000,
+ "pid": 1,
+ "tid": 1,
+ "cat": "toplevel",
+ }
+ ]
+ }
+)
+
+
+class _Cdp:
+ """The CDP calls this instrument makes, answered the way a browser answers them.
+
+ `tracing_active` is the browser-global state the bug leaks: a session left running here is a
+ session no later window can start over.
+ """
+
+ def __init__(self, *, metrics_fail: bool = False) -> None:
+ self.metrics_fail = metrics_fail
+ self.tracing_active = False
+ self.sent: list[str] = []
+ self.starts_refused = 0
+ self._handlers: dict = {}
+
+ def on(self, event: str, handler) -> None:
+ self._handlers[event] = handler
+
+ def send(
+ self,
+ method: str,
+ params: dict | None = None,
+ ):
+ self.sent.append(method)
+ if method == "Tracing.start":
+ if self.tracing_active:
+ self.starts_refused += 1
+ raise RuntimeError("Tracing has already been started (possibly in another tab)")
+ self.tracing_active = True
+ return {}
+ if method == "Tracing.end":
+ if not self.tracing_active:
+ raise RuntimeError("Tracing is not started")
+ self.tracing_active = False
+ complete = self._handlers.get("Tracing.tracingComplete")
+ if complete is not None:
+ complete({"stream": "h1", "dataLossOccurred": False, "streamCompression": "none"})
+ return {}
+ if method == "IO.read":
+ return {"data": TRACE_TEXT, "eof": True}
+ if method == "IO.close":
+ return {}
+ if method == "Performance.enable":
+ return {}
+ if method == "Performance.getMetrics":
+ if self.metrics_fail:
+ raise RuntimeError("Performance domain is not enabled")
+ return {"metrics": [{"name": "TaskDuration", "value": 0.001}]}
+ return {}
+
+
+def _instrument(cdp) -> TracingInstrument:
+ inst = TracingInstrument()
+ inst.attach(types.SimpleNamespace(cdp = cdp, page = None, paths = None))
+ inst.start_cell(types.SimpleNamespace(cell_id = "r10K.A0.rep0", instrument_level = 1))
+ return inst
+
+
+def _window(name: str):
+ return types.SimpleNamespace(name = name)
+
+
+# ── the trace survives the probe ─────────────────────────────────────────────────────────────
+
+
+def test_a_second_window_is_still_traced_after_the_metrics_probe_fails():
+ cdp = _Cdp(metrics_fail = True)
+ inst = _instrument(cdp)
+
+ inst.open(_window("w1"))
+ inst.close(_window("w1"))
+ inst.open(_window("w2"))
+ payload = inst.close(_window("w2"))
+
+ assert cdp.starts_refused == 0
+ assert payload["active"] is True
+
+
+def test_the_first_window_is_still_traced_and_only_loses_the_cross_check():
+ cdp = _Cdp(metrics_fail = True)
+ inst = _instrument(cdp)
+
+ inst.open(_window("w1"))
+ payload = inst.close(_window("w1"))
+
+ assert payload["active"] is True
+ assert "Tracing.end" in cdp.sent
+ assert payload.get("task_duration_crosscheck_drift") is None
+
+
+def test_no_tracing_session_is_left_running_in_the_browser():
+ """The leak itself. A capture nothing holds is a capture nothing can stop, and it keeps
+ recording underneath every measurement taken after it."""
+
+ cdp = _Cdp(metrics_fail = True)
+ inst = _instrument(cdp)
+
+ inst.open(_window("w1"))
+ inst.close(_window("w1"))
+ inst.detach()
+
+ assert cdp.tracing_active is False
+
+
+# ── the controls ─────────────────────────────────────────────────────────────────────────────
+
+
+def test_a_healthy_window_still_cross_checks_against_the_metrics():
+ """The control that matters: the probe is still taken when it can be."""
+
+ cdp = _Cdp()
+ inst = _instrument(cdp)
+
+ inst.open(_window("w1"))
+ payload = inst.close(_window("w1"))
+
+ assert payload["active"] is True
+ assert cdp.sent.count("Performance.getMetrics") == 2
+ assert cdp.tracing_active is False
+
+
+def test_a_capture_that_never_started_is_dropped_and_says_so():
+ """The other control: when `Tracing.start` itself fails there is nothing to end, and the
+ window must report that it was not traced rather than pretend it holds a capture."""
+
+ cdp = _Cdp()
+ cdp.tracing_active = True # something else owns the browser's one tracing session
+ inst = _instrument(cdp)
+
+ inst.open(_window("w1"))
+ payload = inst.close(_window("w1"))
+
+ assert cdp.starts_refused == 1
+ assert payload["active"] is False
+ assert "Tracing.end" not in cdp.sent
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/instruments/tracing.py b/tests/studio/studiobench/instruments/tracing.py
new file mode 100644
index 00000000000..6c7b5a3e99a
--- /dev/null
+++ b/tests/studio/studiobench/instruments/tracing.py
@@ -0,0 +1,884 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Capture a Chrome trace without contaminating the window being measured.
+
+`transferMode: "ReturnAsStream"`, never `ReportEvents`. `ReportEvents` pushes
+the trace back over the devtools pipe as `Tracing.dataCollected` notifications
+WHILE THE WINDOW IS OPEN. Every one of those is renderer-visible work, and its
+volume scales with how much the page is doing, which is to say it is correlated
+with the treatment. `ReturnAsStream` writes to a temp file in the browser
+process and hands back a stream handle at the end, so the drain happens after
+the measurement is over. (Confirmed in `content/browser/devtools/protocol/
+tracing_handler.cc`: `ReturnAsStream` builds a `DevToolsStreamFile` endpoint,
+while `OnTraceDataCollected` splices events into a notification per chunk.)
+
+A trace that hit its buffer is a FAILED CELL, not a short trace. A truncated
+trace reads exactly like "the expensive thing did not happen", which is the most
+dangerous possible failure for a tool whose whole job is to find an expensive
+thing. `Tracing.tracingComplete.dataLossOccurred` is the authoritative signal;
+it is a sticky OR over perfetto's `chunks_overwritten`, `chunks_discarded`,
+`abi_violations` and `trace_writer_packet_loss`, and it is valid even if buffer
+usage polling is off. `Tracing.bufferUsage.percentFull` is subscribed as an
+early warning; its `eventCount` is hardcoded to 0 on modern Chrome and its
+`value` is a legacy duplicate of `percentFull`, so neither is used.
+
+TRACING OVERHEAD IS MEASURED, NEVER ASSUMED. `OverheadLedger` records the same
+cell at L0 and at each higher level and reports `overhead_L1_vs_L0` and
+`overhead_L2_vs_L0` per rung. A level whose overhead GROWS WITH LENGTH is
+disqualified from exponent claims at that rung. Constant overhead is harmless
+to a slope; overhead correlated with the treatment manufactures one.
+"""
+
+from __future__ import annotations
+
+import base64
+import gzip
+import json
+import os
+import time
+from dataclasses import dataclass, field
+from typing import Any, Callable, Sequence
+
+from ..analysis import CellFailure
+
+# --------------------------------------------------------------------- ladder
+
+# L0 is the only level headline numbers may come from. Nothing is attached to
+# the renderer beyond the metrics counters it already maintains for itself.
+L0 = "L0"
+# L1 adds the timeline trace: task boundaries, frames, layout, user timing. No
+# CPU profiler, so no stacks, so no naming, but the cheapest level that gives a
+# real task tree.
+L1 = "L1"
+# L2 adds the V8 CPU profiler. This is the level that NAMES A FRAME.
+L2 = "L2"
+# L3 adds precise coverage and heap sampling. Every timing from L3 is discarded
+# by construction; only integers cross the boundary.
+L3 = "L3"
+
+LEVELS = (L0, L1, L2, L3)
+
+_TIMELINE_CATEGORIES: tuple[str, ...] = (
+ "devtools.timeline",
+ "disabled-by-default-devtools.timeline",
+ "disabled-by-default-devtools.timeline.frame",
+ "blink.user_timing",
+ # `toplevel` carries `ThreadControllerImpl::RunTask` with `src_file` /
+ # `src_func`, which is the C++ that POSTED each task. `RunTask` itself has
+ # empty args and says nothing about origin.
+ "toplevel",
+ "toplevel.flow",
+ # `scheduler` is the one that matters most and it is easy to miss. It does
+ # not add events; it adds TYPED ARGS to the `toplevel` slice:
+ # `args.renderer_main_thread_task_execution.task_type` and
+ # `args.sequence_manager_task.queue_name`. Those turn task origin from an
+ # inference into a read value: a React scheduler callback arrives labelled
+ # `TASK_TYPE_*POSTED_MESSAGE` on `FRAME_PAUSABLE_TQ`, and a timer arrives
+ # labelled `TASK_TYPE_JAVASCRIPT_TIMER_*`. Without this category both are
+ # just "a mojo pipe task" and have to be told apart by guesswork.
+ "scheduler",
+ # `sequence_manager` adds the DoWork / SelectNextTask / DoIdleWork scoping
+ # slices. It does NOT carry queue names, contrary to a natural reading.
+ "sequence_manager",
+ "latencyInfo",
+ "benchmark",
+ "input",
+)
+
+# `disabled-by-default-devtools.timeline.stack` attaches call-site information
+# to timeline events. `disabled-by-default-v8.cpu_profiler` is the one that
+# produces `Profile` / `ProfileChunk`, and without it every microsecond stays a
+# bucket with no stack.
+_STACK_CATEGORIES: tuple[str, ...] = (
+ "disabled-by-default-devtools.timeline.stack",
+ "disabled-by-default-v8.cpu_profiler",
+ "v8",
+ "disabled-by-default-v8.gc",
+)
+
+# There is NO knob for the tracing CPU profiler's sampling interval.
+# `v8/src/profiler/tracing-cpu-profiler.cc` hard-codes 100 us when the
+# `disabled-by-default-v8.cpu_profiler` category is enabled, and the
+# `disabled-by-default-v8.cpu_profiler.hires` category that used to lower it is
+# no longer registered in V8's category list at all: DevTools still sends it,
+# and it does nothing. Effective spacing measured on a real capture is ~150 us
+# once sampler overhead and idle are included.
+#
+# The consequence is structural and cannot be tuned away: a set of 40 us
+# scheduler tasks yields at most one sample each, so leaf rankings over short
+# task windows are underpowered. That is handled honestly by
+# `analysis.cpuprofile.self_time_in_windows`, which reports `underpowered`
+# rather than by a category flag that does not work.
+TRACING_PROFILER_INTERVAL_US = 100
+
+CATEGORIES_BY_LEVEL: dict[str, tuple[str, ...]] = {
+ L0: (),
+ L1: _TIMELINE_CATEGORIES,
+ L2: _TIMELINE_CATEGORIES + _STACK_CATEGORIES,
+ L3: _TIMELINE_CATEGORIES + _STACK_CATEGORIES,
+}
+
+# The default perfetto buffer is 200 MB. A long rung at L2 produces a lot of
+# ProfileChunks, so the buffer is set explicitly and large: an overflow costs a
+# whole cell, and memory is cheaper than a re-run.
+DEFAULT_BUFFER_KB = 640 * 1024
+
+# `bufferUsageReportingInterval` is clamped to a 250 ms floor in
+# `tracing_handler.cc` (`kMinimumReportingInterval`), so asking for less is
+# silently ignored. 500 ms is what the DevTools frontend itself uses.
+BUFFER_POLL_MS = 500
+
+# A trace this close to full did not lose data but was about to, and the next
+# run at the next rung will. Surfaced as a warning so a rung ladder does not
+# walk off a cliff between two cells.
+BUFFER_WARN_FRACTION = 0.80
+
+
+@dataclass
+class TraceResult:
+ """One captured trace plus every integrity fact needed to trust it."""
+
+ level: str
+ categories: tuple[str, ...]
+ text: str
+ path: str | None
+ data_loss_occurred: bool
+ max_percent_full: float
+ buffer_polls: int
+ buffer_kb: int
+ wall_ms: float
+ drain_ms: float
+ drain_chunks: int
+ trace_format: str
+ stream_compression: str
+ started_at_wall: float
+ ended_at_wall: float
+
+ @property
+ def bytes(self) -> int:
+ return len(self.text)
+
+ def integrity(self) -> dict[str, Any]:
+ """Integrity facts, under the no-bare-zero rule.
+
+ `max_percent_full` is the interesting case. A reading of 0.0 with buffer
+ usage events received means the buffer really was empty; a reading of
+ 0.0 with NO events received means we never heard from the buffer at all,
+ and those two must not look the same. The second is precisely the state
+ in which an overflow would go unnoticed, so it is reported as unmeasured
+ with a reason rather than as a reassuring zero.
+ """
+ from ..analysis import measured, merge, unmeasured
+
+ if self.buffer_polls > 0:
+ usage = merge(
+ measured("max_percent_full", round(self.max_percent_full, 5)),
+ {"near_buffer_limit": self.max_percent_full >= BUFFER_WARN_FRACTION},
+ )
+ else:
+ usage = merge(
+ unmeasured(
+ "max_percent_full",
+ "no Tracing.bufferUsage events were received, so buffer headroom is "
+ "unknown for this window; dataLossOccurred is the only overflow signal here",
+ ),
+ {"near_buffer_limit": None, "near_buffer_limit_attempted": False},
+ )
+ return merge(
+ usage,
+ measured("trace_bytes", self.bytes),
+ measured("wall_ms", round(self.wall_ms, 2)),
+ measured("drain_ms", round(self.drain_ms, 2)),
+ measured("drain_chunks", self.drain_chunks),
+ measured("buffer_kb", self.buffer_kb),
+ {
+ "level": self.level,
+ "data_loss_occurred": self.data_loss_occurred,
+ },
+ )
+
+ def assert_intact(self) -> None:
+ if self.data_loss_occurred:
+ raise CellFailure(
+ "trace_buffer_overflow",
+ f"Tracing reported dataLossOccurred at level {self.level} with a "
+ f"{self.buffer_kb} KB buffer ({self.max_percent_full * 100:.1f}% peak). "
+ "A truncated trace is indistinguishable from the expensive work not "
+ "happening, so this cell is void. Raise buffer_kb or shorten the window.",
+ )
+ if not self.text.strip():
+ raise CellFailure("trace_empty", f"level {self.level} drained zero bytes")
+
+
+class TraceCapture:
+ """Drive `Tracing` over one CDP session.
+
+ Only one tracing session may exist per browser: a second `Tracing.start`
+ fails with "Tracing has already been started (possibly in another tab)". The
+ class refuses to double-start rather than letting that surface later as an
+ unrelated protocol error.
+ """
+
+ def __init__(
+ self,
+ cdp: Any,
+ *,
+ level: str = L2,
+ buffer_kb: int = DEFAULT_BUFFER_KB,
+ extra_categories: Sequence[str] = (),
+ record_mode: str = "recordAsMuchAsPossible",
+ wait: Callable[[float], None] | None = None,
+ ) -> None:
+ if level not in LEVELS:
+ raise ValueError(f"unknown instrument level {level!r}; expected one of {LEVELS}")
+ self.cdp = cdp
+ self.level = level
+ self.buffer_kb = int(buffer_kb)
+ self.record_mode = record_mode
+ cats = list(CATEGORIES_BY_LEVEL[level]) + [c for c in extra_categories if c]
+ # Order-stable de-duplication so the recorded category list in the
+ # report is reproducible between runs.
+ self.categories: tuple[str, ...] = tuple(dict.fromkeys(cats))
+ self._wait = wait or (lambda ms: time.sleep(ms / 1000.0))
+ self._usage: list[float] = []
+ self._complete: dict[str, Any] = {}
+ self._running = False
+ self._t_start = 0.0
+ self._subscribed = False
+
+ # ------------------------------------------------------------------ driving
+
+ def _subscribe(self) -> None:
+ if self._subscribed:
+ return
+ # Playwright delivers the event's `params` object as the single
+ # positional argument, and it is `None` for a param-less event.
+ self.cdp.on("Tracing.bufferUsage", self._on_buffer_usage)
+ self.cdp.on("Tracing.tracingComplete", self._on_complete)
+ self._subscribed = True
+
+ def _on_buffer_usage(self, ev: dict[str, Any] | None) -> None:
+ pct = (ev or {}).get("percentFull")
+ if isinstance(pct, (int, float)):
+ self._usage.append(float(pct))
+
+ def _on_complete(self, ev: dict[str, Any] | None) -> None:
+ self._complete.update(ev or {})
+
+ def start(self) -> None:
+ if self.level == L0:
+ # L0 attaches nothing. Making this a no-op rather than an error is
+ # what lets one code path run every level, including the level whose
+ # entire definition is "do not instrument".
+ self._running = True
+ self._t_start = time.perf_counter()
+ return
+ if self._running:
+ raise RuntimeError("TraceCapture.start called twice; Tracing is per-browser")
+ self._subscribe()
+ self._usage.clear()
+ self._complete.clear()
+ self.cdp.send(
+ "Tracing.start",
+ {
+ "transferMode": "ReturnAsStream",
+ "streamFormat": "json",
+ "streamCompression": "none",
+ "bufferUsageReportingInterval": BUFFER_POLL_MS,
+ "traceConfig": {
+ "recordMode": self.record_mode,
+ "traceBufferSizeInKb": self.buffer_kb,
+ "includedCategories": list(self.categories),
+ "excludedCategories": [],
+ "enableSampling": False,
+ "enableSystrace": False,
+ "enableArgumentFilter": False,
+ },
+ },
+ )
+ self._running = True
+ self._t_start = time.perf_counter()
+
+ def stop(
+ self,
+ *,
+ save_to: str | None = None,
+ timeout_s: float = 120.0,
+ ) -> TraceResult:
+ if not self._running:
+ raise RuntimeError("TraceCapture.stop called without start")
+ t_end = time.perf_counter()
+ wall_ms = (t_end - self._t_start) * 1000.0
+ self._running = False
+
+ if self.level == L0:
+ return TraceResult(
+ level = L0,
+ categories = (),
+ text = "",
+ path = None,
+ data_loss_occurred = False,
+ max_percent_full = 0.0,
+ buffer_polls = 0,
+ buffer_kb = 0,
+ wall_ms = wall_ms,
+ drain_ms = 0.0,
+ drain_chunks = 0,
+ trace_format = "",
+ stream_compression = "",
+ started_at_wall = self._t_start,
+ ended_at_wall = t_end,
+ )
+
+ self.cdp.send("Tracing.end")
+ deadline = time.time() + timeout_s
+ while "stream" not in self._complete and "dataLossOccurred" not in self._complete:
+ if time.time() > deadline:
+ raise CellFailure(
+ "tracing_complete_timeout",
+ f"Tracing.tracingComplete did not arrive within {timeout_s:.0f}s",
+ )
+ self._wait(50)
+ # `dataLossOccurred` can arrive first on a very small trace; give the
+ # stream handle a moment before deciding there is not one.
+ grace = time.time() + 5.0
+ while "stream" not in self._complete and time.time() < grace:
+ self._wait(50)
+
+ data_loss = bool(self._complete.get("dataLossOccurred"))
+ handle = self._complete.get("stream")
+ if handle is None:
+ raise CellFailure(
+ "tracing_no_stream",
+ "tracingComplete carried no stream handle; transferMode was not ReturnAsStream",
+ )
+
+ t_drain = time.perf_counter()
+ text, chunks = self._drain(str(handle), self._complete.get("streamCompression") or "none")
+ drain_ms = (time.perf_counter() - t_drain) * 1000.0
+
+ path = None
+ if save_to:
+ os.makedirs(os.path.dirname(os.path.abspath(save_to)) or ".", exist_ok = True)
+ with open(save_to, "w", encoding = "utf-8") as fh:
+ fh.write(text)
+ path = save_to
+
+ return TraceResult(
+ level = self.level,
+ categories = self.categories,
+ text = text,
+ path = path,
+ data_loss_occurred = data_loss,
+ max_percent_full = max(self._usage) if self._usage else 0.0,
+ buffer_polls = len(self._usage),
+ buffer_kb = self.buffer_kb,
+ wall_ms = wall_ms,
+ drain_ms = drain_ms,
+ drain_chunks = chunks,
+ trace_format = str(self._complete.get("traceFormat") or "json"),
+ stream_compression = str(self._complete.get("streamCompression") or "none"),
+ started_at_wall = self._t_start,
+ ended_at_wall = t_end,
+ )
+
+ def _drain(self, handle: str, compression: str) -> tuple[str, int]:
+ """Read the stream to EOF, then close it.
+
+ `IO.read` returns `base64Encoded: true` only for gzip or proto payloads,
+ and its `offset`/`size` are raw pre-base64 byte counts, so the offset is
+ never derived from `len(data)`; sequential reads with no offset are the
+ only safe form. The read that reaches EOF returns an empty `data`, so
+ the chunk is appended BEFORE the eof check.
+ """
+ parts: list[str] = []
+ binary = False
+ chunks = 0
+ while True:
+ r = self.cdp.send("IO.read", {"handle": handle, "size": 1 << 20})
+ binary = binary or bool(r.get("base64Encoded"))
+ parts.append(r.get("data") or "")
+ chunks += 1
+ if r.get("eof"):
+ break
+ try:
+ self.cdp.send("IO.close", {"handle": handle})
+ except Exception:
+ # The stream is temp storage in the browser process; failing to
+ # close it leaks a file, it does not invalidate the trace we hold.
+ pass
+ blob = "".join(parts)
+ raw = base64.b64decode(blob) if binary else blob.encode("utf-8")
+ if compression == "gzip":
+ raw = gzip.decompress(raw)
+ return raw.decode("utf-8", errors = "strict"), chunks
+
+
+# ------------------------------------------------------------------- overheads
+
+
+@dataclass
+class OverheadLedger:
+ """Per-rung measured cost of instrumentation, and the disqualification gate.
+
+ The danger is not overhead. Constant overhead shifts an intercept and leaves
+ an exponent alone. The danger is overhead CORRELATED WITH THE TREATMENT,
+ because that manufactures exactly the slope the tool is looking for. So the
+ gate is not "overhead is small", it is "overhead does not grow with length".
+
+ HOW THIS RELATES TO THE HARNESS PATH, since there are two and they are not
+ competitors. Under Layer 1, each instrument reports its own measured
+ `overhead_ms` from `end_cell`, and the report layer assembles those across
+ rungs into its `overhead_growth_with_length` gate. That is the production
+ route and it needs nothing from this class. This ledger is the OFFLINE route:
+ it takes the same cell run at L0 and at a higher level and produces the
+ ratio and the disqualification verdict directly, which is what you want when
+ calibrating a machine or investigating a suspicious slope outside a full
+ run. Same rule, same tolerance, two entry points.
+ """
+
+ # rung label -> level -> observed cost of the identical cell (ms, or any
+ # single consistent scalar such as median frame time)
+ cells: dict[str, dict[str, float]] = field(default_factory = dict)
+ # A level whose overhead ratio rises by more than this across the ladder is
+ # disqualified from exponent claims.
+ growth_tolerance: float = 0.15
+
+ def record(self, rung: str, level: str, cost: float) -> None:
+ if level not in LEVELS:
+ raise ValueError(f"unknown level {level!r}")
+ self.cells.setdefault(rung, {})[level] = float(cost)
+
+ def overhead(self, rung: str, level: str) -> float | None:
+ row = self.cells.get(rung) or {}
+ base = row.get(L0)
+ got = row.get(level)
+ if not base or got is None or base <= 0:
+ return None
+ return (got - base) / base
+
+ def per_rung(self) -> dict[str, dict[str, Any]]:
+ out: dict[str, dict[str, Any]] = {}
+ for rung in self.cells:
+ row: dict[str, Any] = {}
+ for level in (L1, L2, L3):
+ ov = self.overhead(rung, level)
+ if ov is not None:
+ row[f"overhead_{level}_vs_{L0}"] = round(ov, 4)
+ out[rung] = row
+ return out
+
+ def disqualified_levels(self, rung_order: Sequence[str]) -> dict[str, str]:
+ """Levels whose overhead grows with length, with the reason.
+
+ `rung_order` must be smallest-first. Only rungs that actually recorded
+ both L0 and the level are considered, so a partial ladder narrows the
+ claim instead of inventing one.
+ """
+ out: dict[str, str] = {}
+ for level in (L1, L2, L3):
+ series = [
+ (rung, self.overhead(rung, level))
+ for rung in rung_order
+ if self.overhead(rung, level) is not None
+ ]
+ if len(series) < 2:
+ continue
+ first_rung, first = series[0]
+ last_rung, last = series[-1]
+ assert first is not None and last is not None
+ if last - first > self.growth_tolerance:
+ out[level] = (
+ f"overhead rose from {first * 100:.1f}% at {first_rung} to "
+ f"{last * 100:.1f}% at {last_rung}; overhead correlated with the "
+ "treatment cannot support an exponent claim at this level"
+ )
+ return out
+
+ def report(self, rung_order: Sequence[str]) -> dict[str, Any]:
+ return {
+ "per_rung": self.per_rung(),
+ "disqualified": self.disqualified_levels(rung_order),
+ "growth_tolerance": self.growth_tolerance,
+ }
+
+
+def cross_check_with_metrics(
+ trace_run_task_us: int,
+ metrics: dict[str, float],
+ tolerance: float = 0.05,
+) -> dict[str, Any]:
+ """Summed trace `RunTask` vs `Performance.getMetrics` `TaskDuration`.
+
+ Two independent accountings of the same physical quantity, produced by
+ different subsystems. Agreement is weak evidence that the trace is complete;
+ disagreement is strong evidence that it is not, and the cell fails.
+ """
+ task_duration_s = metrics.get("TaskDuration")
+ if task_duration_s is None:
+ raise CellFailure(
+ "no_task_duration",
+ "Performance.getMetrics returned no TaskDuration; enable the Performance domain",
+ )
+ trace_s = trace_run_task_us / 1e6
+ if task_duration_s <= 0:
+ raise CellFailure("task_duration_zero", "TaskDuration was not positive")
+ drift = abs(trace_s - task_duration_s) / task_duration_s
+ out = {
+ "trace_run_task_s": trace_s,
+ "cdp_task_duration_s": task_duration_s,
+ "drift": drift,
+ "tolerance": tolerance,
+ }
+ if drift > tolerance:
+ raise CellFailure(
+ "task_duration_mismatch",
+ f"trace RunTask total {trace_s * 1000:.1f} ms disagrees with CDP "
+ f"TaskDuration {task_duration_s * 1000:.1f} ms by {drift * 100:.1f}%",
+ )
+ return out
+
+
+class MetricsWindow:
+ """Bracket `Performance.getMetrics` INSIDE the trace window.
+
+ `TaskDuration` is a monotonic renderer-wide counter, so a window is the
+ difference of two readings. The readings must be taken just AFTER
+ `Tracing.start` and just BEFORE `Tracing.end`, never outside, or the metrics
+ window is wider than the trace window and the cross-check reports a
+ disagreement that is entirely an artefact of how it was taken. A 5.7% false
+ failure was produced exactly this way while building this module, which is
+ why the ordering lives in a class instead of in a comment.
+
+ Taking the metrics strictly inside also makes the residual one-sided: the
+ trace should account for at least as much task time as the metrics do, so a
+ trace total BELOW the metrics total means missing events.
+ """
+
+ def __init__(self, cdp: Any) -> None:
+ self.cdp = cdp
+ self.before: dict[str, float] = {}
+ self.after: dict[str, float] = {}
+
+ def open(self) -> None:
+ self.before = read_metrics(self.cdp)
+
+ def close(self) -> None:
+ self.after = read_metrics(self.cdp)
+
+ def delta(self) -> dict[str, float]:
+ if not self.before or not self.after:
+ raise CellFailure(
+ "metrics_window_unclosed", "MetricsWindow.open/close were not both called"
+ )
+ return {
+ k: self.after[k] - self.before.get(k, 0.0)
+ for k in self.after
+ if isinstance(self.after[k], (int, float))
+ }
+
+
+def read_metrics(cdp: Any) -> dict[str, float]:
+ """`Performance.getMetrics` flattened to a plain mapping.
+
+ The Performance domain must be enabled first; calling `getMetrics` on a
+ disabled domain returns an error rather than an empty result, and swallowing
+ that is how a cross-check silently stops checking.
+ """
+ res = cdp.send("Performance.getMetrics")
+ return {m["name"]: m["value"] for m in res.get("metrics", [])}
+
+
+def enable_metrics(cdp: Any, *, time_domain: str = "timeTicks") -> None:
+ """Enable the Performance domain on the WALL clock.
+
+ `timeTicks` is the default and it is the right one here: trace `RunTask.dur`
+ is wall duration, so cross-checking it against a `TaskDuration` accumulated
+ in `threadTicks` would compare CPU time to elapsed time and read as a real
+ disagreement whenever the thread was descheduled.
+ """
+ cdp.send("Performance.enable", {"timeDomain": time_domain})
+
+
+def save_trace(result: TraceResult, path: str) -> str:
+ os.makedirs(os.path.dirname(os.path.abspath(path)) or ".", exist_ok = True)
+ with open(path, "w", encoding = "utf-8") as fh:
+ fh.write(result.text)
+ return path
+
+
+def load_trace_json(result: TraceResult) -> dict[str, Any]:
+ return json.loads(result.text)
+
+
+# ═══════════════════════════════════════════════════════════════════════════
+# Harness adapter (INTERFACES.md section 3)
+# ═══════════════════════════════════════════════════════════════════════════
+#
+# ONE TRACE PER WINDOW, not one per cell. The alternative was a cell-long trace
+# plus `performance.mark` bracketing to locate each window inside it, and it was
+# rejected for three reasons, in increasing order of importance:
+#
+# 1. A mark is a `Runtime.evaluate` round trip, which is renderer-visible work
+# inside the measured interval. Small, but correlated with nothing and
+# still avoidable.
+# 2. A cell-long trace at L2 accumulates ProfileChunks for the whole cell, so
+# the buffer-overflow risk grows with cell length. Per-window traces keep
+# each buffer bounded by one window.
+# 3. Per-window numbers have to exist at `close()` time, because the harness
+# emits `window.row()` right after. A trace drained at `end_cell` can only
+# backfill the cell row, so every window row would carry nulls.
+#
+# `Tracing.end` and the drain happen inside `close()`, which the harness calls
+# AFTER it has stamped `t_close_ms`. The window duration is therefore already
+# fixed and the drain cannot inflate it. The `Tracing.start` in `open()` does
+# land inside the window, so it is timed and reported as `overhead_ms` rather
+# than waved away.
+
+from ..analysis import assert_no_bare_zero, measured, merge, unmeasured # noqa: E402
+from . import register_instrument # noqa: E402
+
+
+class TracingInstrument:
+ """Timeline trace per window, with task origins and, at L2+, named frames."""
+
+ name = "tracing"
+ level = 1
+
+ def __init__(self) -> None:
+ self.ctx: Any = None
+ self.cdp: Any = None
+ self.cell: Any = None
+ self.capture: TraceCapture | None = None
+ self.metrics: MetricsWindow | None = None
+ self.trace_level: str = L1
+ self._overhead_ms = 0.0
+ self._windows = 0
+ self._failed_windows: list[str] = []
+ self._save_traces = True
+
+ # ---------------------------------------------------------------- lifecycle
+
+ def attach(self, ctx: Any) -> None:
+ self.ctx = ctx
+
+ def start_cell(self, cell: Any) -> None:
+ # `ctx.page` and `ctx.cdp` may be REPLACED between cells when a crashed
+ # renderer is recovered, so they are re-read here and never cached in
+ # `attach`. INTERFACES.md section 7 is explicit about this.
+ self.cell = cell
+ self.cdp = getattr(self.ctx, "cdp", None)
+ self._overhead_ms = 0.0
+ self._windows = 0
+ self._failed_windows = []
+ lvl = int(getattr(cell, "instrument_level", 1) or 1)
+ # The instrument ladder is expressed HERE. L0 never reaches this method
+ # because the registry filters on `level`, and L3 uses the same category
+ # set as L2: L3 adds coverage and heap sampling, which are other
+ # instruments, not more categories.
+ self.trace_level = L1 if lvl <= 1 else (L2 if lvl == 2 else L3)
+ if self.cdp is not None:
+ try:
+ enable_metrics(self.cdp)
+ except Exception:
+ # Metrics are a cross-check, not the measurement. Losing them
+ # costs the cross-check and nothing else.
+ pass
+
+ def open(self, window: Any) -> None:
+ if self.cdp is None:
+ return
+ t0 = time.perf_counter()
+ self.capture = TraceCapture(
+ self.cdp,
+ level = self.trace_level,
+ wait = self._wait,
+ )
+ try:
+ self.capture.start()
+ except Exception:
+ # Nothing was started, so there is nothing to end.
+ self.capture = None
+ self.metrics = None
+ else:
+ # THE METRICS PROBE MAY NOT TAKE THE TRACE WITH IT. `start_cell` says what losing the
+ # probe is meant to cost -- "the cross-check and nothing else" -- and dropping a
+ # STARTED capture here cost the whole run instead. Tracing is per-browser: with
+ # `self.capture` cleared, `close()` returns early and never sends `Tracing.end`,
+ # `detach()` has nothing to stop, and the next window's `Tracing.start` fails with
+ # "Tracing has already been started (possibly in another tab)" -- so every remaining
+ # window reports `tracing did not start`, while the abandoned session keeps recording
+ # into the browser underneath the numbers this tool is taking. One failed
+ # `Performance.getMetrics` (the domain is enabled under a bare `except` in
+ # `start_cell`, so it can be off) was enough. `close()` and `_analyse` already guard
+ # every use of `self.metrics` with `is not None`, so the cross-check is the only
+ # thing that goes.
+ try:
+ self.metrics = MetricsWindow(self.cdp)
+ self.metrics.open()
+ except Exception:
+ self.metrics = None
+ self._overhead_ms += (time.perf_counter() - t0) * 1000.0
+
+ def close(self, window: Any) -> dict | None:
+ if self.capture is None:
+ return merge(
+ unmeasured("task_ms", "tracing did not start for this window"),
+ {"trace_level": self.trace_level, "active": False},
+ )
+ t0 = time.perf_counter()
+ self._windows += 1
+ try:
+ if self.metrics is not None:
+ self.metrics.close()
+ result = self.capture.stop(save_to = self._trace_path(window))
+ result.assert_intact()
+ payload = self._analyse(result, window)
+ except CellFailure as exc:
+ self._failed_windows.append(f"{getattr(window, 'name', '?')}: {exc.gate}")
+ payload = merge(
+ unmeasured("task_ms", f"{exc.gate}: {exc.detail}"),
+ {"trace_level": self.trace_level, "active": True, "cell_failed": True},
+ )
+ except Exception as exc: # noqa: BLE001
+ self._failed_windows.append(f"{getattr(window, 'name', '?')}: {type(exc).__name__}")
+ payload = merge(
+ unmeasured("task_ms", f"{type(exc).__name__}: {exc}"),
+ {"trace_level": self.trace_level, "active": True, "cell_failed": True},
+ )
+ finally:
+ self.capture = None
+ self.metrics = None
+ self._overhead_ms += (time.perf_counter() - t0) * 1000.0
+ assert_no_bare_zero(payload, f"tracing.{getattr(window, 'name', '?')}")
+ return payload
+
+ def end_cell(self, cell: Any) -> dict | None:
+ # `overhead_ms` is required from every instrument at level >= 1
+ # (INTERFACES.md section 3) and it is what the report layer's
+ # `overhead_growth_with_length` gate consumes. It is a MEASURED wall
+ # cost of this instrument's own calls, not an estimate from a table.
+ out = merge(
+ measured("overhead_ms", round(self._overhead_ms, 3)),
+ measured("windows_traced", self._windows),
+ {
+ "trace_level": self.trace_level,
+ "headline_safe": self.trace_level == L0,
+ "failed_windows": self._failed_windows,
+ },
+ )
+ assert_no_bare_zero(out, "tracing.end_cell")
+ return out
+
+ def detach(self) -> None:
+ if self.capture is not None:
+ try:
+ self.capture.stop()
+ except Exception:
+ pass
+ self.capture = None
+
+ # ------------------------------------------------------------------ helpers
+
+ def _wait(self, ms: float) -> None:
+ page = getattr(self.ctx, "page", None)
+ if page is not None:
+ try:
+ page.wait_for_timeout(ms)
+ return
+ except Exception:
+ pass
+ time.sleep(ms / 1000.0)
+
+ def _trace_path(self, window: Any) -> str | None:
+ paths = getattr(self.ctx, "paths", None)
+ if paths is None or not self._save_traces:
+ return None
+ cell_id = getattr(self.cell, "cell_id", "cell")
+ safe = "".join(
+ c if c.isalnum() or c in "-_." else "_" for c in str(getattr(window, "name", "w"))
+ )
+ return str(getattr(paths, "traces") / f"{cell_id}.{safe}.json")
+
+ def _analyse(self, result: TraceResult, window: Any) -> dict:
+ from ..analysis import classify as K
+ from ..analysis import cpuprofile as C
+ from ..analysis.traceparse import Trace
+
+ trace = Trace.from_json_text(result.text)
+ cls = K.classify_thread(trace)
+ payload: dict = merge(
+ measured("task_ms", round(cls.total_us / 1000.0, 3)),
+ measured("unclassified_task_pct", round(cls.unclassified_pct, 4)),
+ {
+ "trace_level": self.trace_level,
+ "active": True,
+ "task_ms_by_origin": {
+ k: round(v / 1000.0, 3) for k, v in sorted(cls.by_origin_us.items())
+ },
+ "task_count_by_origin": dict(sorted(cls.by_origin_count.items())),
+ "integrity": result.integrity(),
+ "trace_path": result.path,
+ },
+ )
+
+ # Cross-check against the renderer's own accounting. A disagreement means
+ # the trace is missing tasks, so it is reported rather than silently
+ # tolerated, but it does not void the window on its own.
+ try:
+ if self.metrics is not None:
+ payload.update(
+ measured(
+ "task_duration_crosscheck_drift",
+ round(
+ cross_check_with_metrics(cls.total_us, self.metrics.delta())["drift"], 5
+ ),
+ )
+ )
+ except CellFailure as exc:
+ payload.update(
+ unmeasured("task_duration_crosscheck_drift", f"{exc.gate}: {exc.detail}")
+ )
+ except Exception as exc: # noqa: BLE001
+ payload.update(
+ unmeasured("task_duration_crosscheck_drift", f"{type(exc).__name__}: {exc}")
+ )
+
+ # Named frames need the V8 profiler, which only L2+ turns on. At L1 this
+ # is an honest null with a reason, never an empty list that reads as
+ # "nothing was hot".
+ if self.trace_level == L1:
+ payload.update(
+ unmeasured(
+ "named_frames",
+ "the v8 CPU profiler category is off at instrument level 1, so samples "
+ "have no stacks and no frame can be named. Raise the level to 2.",
+ )
+ )
+ return payload
+
+ try:
+ prof = C.main_thread_profile(trace)
+ prof.assert_deltas_match_wall()
+ rows, diag = C.self_time_in_windows(
+ prof,
+ [(prof.chunk_ts_first, prof.chunk_ts_last)],
+ limit = 12,
+ )
+ payload.update(
+ measured(
+ "named_frames",
+ [{"frame": f.label(), "self_ms": round(us / 1000.0, 3)} for f, us in rows],
+ )
+ )
+ payload["frame_ranking_underpowered"] = bool(diag["underpowered"])
+ payload["js_sample_count"] = int(diag["js_sample_count"])
+ except CellFailure as exc:
+ payload.update(unmeasured("named_frames", f"{exc.gate}: {exc.detail}"))
+ return payload
+
+
+@register_instrument(name = "tracing", level = 1)
+def _make_tracing() -> TracingInstrument:
+ return TracingInstrument()
diff --git a/tests/studio/studiobench/pacer.py b/tests/studio/studiobench/pacer.py
new file mode 100644
index 00000000000..f7849f971c6
--- /dev/null
+++ b/tests/studio/studiobench/pacer.py
@@ -0,0 +1,812 @@
+# 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 OpenAI-compatible SSE server that paces a reply the way a real backend does.
+
+WHY THIS EXISTS AT ALL. The harness this replaces measured a backend-free smoke page driven by a
+local `ChatModelAdapter`. Two whole mechanisms therefore never executed: the cumulative
+`<think>` re-parse in `chat-adapter.ts`, which re-parses the ENTIRE growing buffer on every delta,
+and the autoscroll `MutationObserver` in `use-intent-aware-autoscroll.tsx`, which answers every
+streamed character with a synchronous `scrollHeight` read over the whole thread. Both are O(thread)
+per chunk and neither is reachable without real bytes arriving over a real transport. So Studio is
+pointed at THIS, as an external provider, and the bytes go out over the wire, through the Studio
+backend's own relay, into the app's own `TextDecoder`, its own SSE framing and its own delta
+accumulation. Nothing is stubbed and there is no `page.route` anywhere near the primary transport.
+
+THREE things here are not incidental.
+
+**Threaded.** `ThreadingHTTPServer`, not `HTTPServer`. A single-threaded server previously lost 11
+cells of a matrix to `goto` timeouts: the browser opens the SPA's own requests while a stream is in
+flight, and one blocked handler stalls all of them, so the page never finishes navigating and the
+cell dies without a number.
+
+**Deficit-scheduled cadence.** Each tick computes `floor((now - t0) / gap)` and sends the SHORTFALL
+in one burst, rather than sleeping a gap per chunk. Two consequences, both wanted. Stream duration
+becomes a function of wall clock alone, so a 90K reply takes the same 276 seconds on a fast machine
+and a slow one and a tier's time budget is honest. And a renderer that jams gets a BURST when it
+recovers, which is exactly what a real backend does: the model keeps generating while the socket
+backs up, and the queue drains at once. `sleep(gap)` per chunk instead makes the SERVER slow down
+whenever the client does, which quietly converts a rendering problem into a shorter benchmark.
+
+**The exact chunk shapes the app parses.** The backend's own `_gguf_chat_delta_line` emits
+`reasoning_content` WITH `content: ""` alongside, so that is what goes out here. The terminal chunk
+carries `finish_reason: "stop"` AND is followed by `data: [DONE]`: `streamChatCompletions` in
+`chat-api.ts` throws `StreamInterruptedError` at EOF if it saw neither, and a harness that omits
+one measures error handling. A usage chunk follows because the app always sends
+`stream_options: {include_usage: true}` and its context bar reads the result.
+"""
+
+from __future__ import annotations
+
+import json
+import socket
+import threading
+import time
+import uuid
+from dataclasses import dataclass, field
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from typing import Optional
+
+# The field's own arrival rate: 90,262 characters in 276 seconds is 327 characters a second,
+# which at 24 characters a chunk is one chunk every 73ms. It is part of the fixture and getting it
+# wrong is how the earlier harness failed to reproduce anything: at a 2ms gap the renderer is the
+# bottleneck from the first chunk, the run opens at 45 fps instead of 59, and there is no healthy
+# baseline left to degrade FROM. The trace's whole shape is "idle between chunks at the start, not
+# idle at the end".
+CAD_FIELD = (24, 73)
+# For the small rungs, where the field cadence would spend four minutes streaming a reply nobody
+# is measuring the cadence of.
+CAD_FAST = (64, 8)
+
+CADENCES = {"field": CAD_FIELD, "fast": CAD_FAST}
+
+KEEPALIVE_S = 5.0
+
+
+@dataclass
+class Script:
+ """One reply for the pacer to serve. Set by the driver before it presses send."""
+
+ reasoning: str = ""
+ content: str = ""
+ chunk_chars: int = CAD_FIELD[0]
+ gap_ms: int = CAD_FIELD[1]
+ model: str = "studiobench-pacer"
+ # Emitted before anything else, so a driver can prove the stream it is watching is the one it
+ # asked for rather than a leftover from the previous cell.
+ tag: str = ""
+ # Set by the driver to make the pacer stop mid-reply, for the stop-generation action. The
+ # pacer keeps the socket OPEN and idle rather than closing it, because a close is a different
+ # event from a cancel and the app distinguishes them.
+ hold_after_chars: Optional[int] = None
+
+
+@dataclass
+class StreamStats:
+ """What the pacer ACTUALLY did, which is the only honest record of the cadence.
+
+ Kept because the driver cannot see it any other way: what reaches the page has been through a
+ backend relay and a browser, so "did the fixture send what it meant to" and "did the page
+ receive it" are two different questions and only one of them is about the app.
+ """
+
+ request_id: str = ""
+ tag: str = ""
+ started_at: float = 0.0
+ first_chunk_ms: Optional[float] = None
+ last_chunk_ms: Optional[float] = None
+ chunks_sent: int = 0
+ chars_sent: int = 0
+ bytes_sent: int = 0
+ reasoning_chars_sent: int = 0
+ content_chars_sent: int = 0
+ # How often the deficit scheduler had to send more than one chunk to catch up, and the worst
+ # shortfall it saw. A run where these stay at zero had no backpressure at all; a run where
+ # max_deficit is 40 had the socket blocked for three seconds.
+ bursts: int = 0
+ max_deficit: int = 0
+ # Time spent inside a blocking write. This IS the backpressure, measured rather than inferred.
+ write_block_ms: float = 0.0
+ keepalives: int = 0
+ completed: bool = False
+ disconnected: bool = False
+ held: bool = False
+ error: Optional[str] = None
+ duration_ms: Optional[float] = None
+ # The cadence achieved, against the one asked for. A gap that came out at 91ms when 73 was
+ # requested is a machine that could not keep up, and it belongs in the report next to the
+ # numbers it distorted.
+ requested_gap_ms: int = 0
+ achieved_gap_ms: Optional[float] = None
+
+ def as_dict(self) -> dict:
+ d = dict(self.__dict__)
+ d.pop("started_at", None)
+ for k in (
+ "first_chunk_ms",
+ "last_chunk_ms",
+ "write_block_ms",
+ "duration_ms",
+ "achieved_gap_ms",
+ ):
+ if isinstance(d.get(k), float):
+ d[k] = round(d[k], 2)
+ return d
+
+
+class PacerState:
+ """The single-slot script plus the log of what each request did. Guarded by one lock."""
+
+ def __init__(self) -> None:
+ self.lock = threading.Lock()
+ self.script = Script()
+ self.stats: list[StreamStats] = []
+ self.requests_seen = 0
+ self.model_ids: list[str] = ["studiobench-pacer"]
+ # Flipped by the driver to release a held stream (the stop-generation action asserts the
+ # app's cancel, so the pacer must be able to sit still while it happens).
+ self.release = threading.Event()
+
+ def set_script(self, script: Script) -> None:
+ with self.lock:
+ self.script = script
+ self.release.clear()
+
+ def get_script(self) -> Script:
+ with self.lock:
+ return self.script
+
+ def record(self, stats: StreamStats) -> None:
+ with self.lock:
+ self.stats.append(stats)
+
+ def last(self) -> Optional[StreamStats]:
+ with self.lock:
+ return self.stats[-1] if self.stats else None
+
+ def snapshot(self) -> list[StreamStats]:
+ with self.lock:
+ return list(self.stats)
+
+
+def _sse(payload: dict) -> bytes:
+ return b"data: " + json.dumps(payload, separators = (",", ":")).encode("utf-8") + b"\n\n"
+
+
+def _chunk_frame(
+ request_id: str,
+ model: str,
+ delta: dict,
+ finish_reason: Optional[str] = None,
+) -> dict:
+ return {
+ "id": request_id,
+ "object": "chat.completion.chunk",
+ "created": int(time.time()),
+ "model": model,
+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}],
+ }
+
+
+def _split(text: str, size: int) -> list[str]:
+ return [text[i : i + size] for i in range(0, len(text), size)] if text else []
+
+
+class _Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+ server_version = "studiobench-pacer"
+
+ # Quiet. A per-request line on stderr at 24 characters a chunk is 4,000 lines a reply.
+ def log_message(self, fmt, *args) -> None: # noqa: A003
+ pass
+
+ @property
+ def state(self) -> PacerState:
+ return self.server.state # type: ignore[attr-defined]
+
+ # ── plumbing ────────────────────────────────────────────────────
+
+ def _json(self, code: int, body: dict) -> None:
+ raw = json.dumps(body).encode("utf-8")
+ self.send_response(code)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(raw)))
+ self.send_header("Access-Control-Allow-Origin", "*")
+ self.end_headers()
+ self.wfile.write(raw)
+
+ def _read_body(self) -> dict:
+ length = int(self.headers.get("Content-Length") or 0)
+ if length <= 0:
+ return {}
+ try:
+ return json.loads(self.rfile.read(length).decode("utf-8"))
+ except ValueError:
+ return {}
+
+ def do_OPTIONS(self) -> None: # noqa: N802
+ self.send_response(204)
+ self.send_header("Access-Control-Allow-Origin", "*")
+ self.send_header("Access-Control-Allow-Headers", "*")
+ self.send_header("Access-Control-Allow-Methods", "GET,POST,OPTIONS")
+ self.end_headers()
+
+ def do_GET(self) -> None: # noqa: N802
+ path = self.path.split("?", 1)[0].rstrip("/")
+ if path in ("/healthz", "/_pacer/healthz"):
+ self._json(200, {"ok": True})
+ elif path.endswith("/models"):
+ with self.state.lock:
+ ids = list(self.state.model_ids)
+ self._json(
+ 200,
+ {
+ "object": "list",
+ "data": [{"id": m, "object": "model", "owned_by": "studiobench"} for m in ids],
+ },
+ )
+ elif path == "/_pacer/stats":
+ with self.state.lock:
+ self._json(
+ 200,
+ {
+ "requests_seen": self.state.requests_seen,
+ "streams": [s.as_dict() for s in self.state.stats],
+ },
+ )
+ elif path == "/_pacer/last":
+ last = self.state.last()
+ self._json(200, last.as_dict() if last else {})
+ else:
+ self._json(404, {"error": {"message": f"no route {path}"}})
+
+ def do_POST(self) -> None: # noqa: N802
+ path = self.path.split("?", 1)[0].rstrip("/")
+ body = self._read_body()
+ if path == "/_pacer/script":
+ self.state.set_script(
+ Script(
+ reasoning = body.get("reasoning", ""),
+ content = body.get("content", ""),
+ chunk_chars = int(body.get("chunk_chars", CAD_FIELD[0])),
+ gap_ms = int(body.get("gap_ms", CAD_FIELD[1])),
+ model = body.get("model", "studiobench-pacer"),
+ tag = body.get("tag", ""),
+ hold_after_chars = body.get("hold_after_chars"),
+ )
+ )
+ self._json(200, {"ok": True})
+ elif path == "/_pacer/release":
+ self.state.release.set()
+ self._json(200, {"ok": True})
+ elif path == "/_pacer/reset":
+ with self.state.lock:
+ self.state.stats.clear()
+ self.state.requests_seen = 0
+ self._json(200, {"ok": True})
+ elif path.endswith("/chat/completions"):
+ self._stream(body)
+ else:
+ self._json(404, {"error": {"message": f"no route {path}"}})
+
+ # ── the stream ──────────────────────────────────────────────────
+
+ def _stream(self, body: dict) -> None:
+ script = self.state.get_script()
+ with self.state.lock:
+ self.state.requests_seen += 1
+ request_id = f"chatcmpl-{uuid.uuid4().hex[:20]}"
+ model = body.get("model") or script.model
+ stats = StreamStats(
+ request_id = request_id,
+ tag = script.tag,
+ started_at = time.monotonic(),
+ requested_gap_ms = script.gap_ms,
+ )
+
+ if not body.get("stream", True):
+ # A non-streaming request is a bug in the driver, not a mode: every mechanism this
+ # tool measures is on the streaming path. Say so rather than serve it.
+ self._json(
+ 400,
+ {
+ "error": {
+ "message": "the studiobench pacer only serves stream=true; a non-streaming "
+ "request would skip every mechanism this benchmark exists to measure",
+ "type": "invalid_request_error",
+ }
+ },
+ )
+ return
+
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ self.send_header("Cache-Control", "no-cache, no-transform")
+ self.send_header("Connection", "keep-alive")
+ # CHUNKED, explicitly. On HTTP/1.1 a response with neither Content-Length nor
+ # Transfer-Encoding is a keep-alive response of unknown length, and the reader blocks
+ # forever waiting for a body that already arrived -- measured here as a client that hung
+ # past a 60s timeout having received every byte. Uvicorn, which is what Studio's own
+ # backend streams through, sends chunked for a StreamingResponse, so this is also the
+ # framing the relay and the browser see in production.
+ self.send_header("Transfer-Encoding", "chunked")
+ self.send_header("X-Accel-Buffering", "no")
+ self.end_headers()
+
+ # The role chunk first, as every OpenAI-compatible server sends it. The app tolerates its
+ # absence, but its presence is what makes the first delta an APPEND rather than a create,
+ # which is the path the cumulative buffer takes for every chunk after it.
+ chunks: list[tuple[str, str]] = []
+ for piece in _split(script.reasoning, script.chunk_chars):
+ chunks.append(("reasoning", piece))
+ for piece in _split(script.content, script.chunk_chars):
+ chunks.append(("content", piece))
+
+ gap_s = max(script.gap_ms, 1) / 1000.0
+ t0 = time.monotonic()
+ sent = 0
+ try:
+ self._write(_sse(_chunk_frame(request_id, model, {"role": "assistant"})), stats)
+ last_activity = time.monotonic()
+ while sent < len(chunks):
+ now = time.monotonic()
+ # DEFICIT SCHEDULING. How many chunks SHOULD have gone out by now, from wall
+ # clock alone; send the shortfall in one burst. Never sleep(gap) per chunk.
+ should_have_sent = int((now - t0) / gap_s)
+ deficit = min(should_have_sent, len(chunks)) - sent
+ if deficit <= 0:
+ if now - last_activity >= KEEPALIVE_S:
+ self._write(b": keep-alive\n\n", stats)
+ stats.keepalives += 1
+ last_activity = now
+ # Sleep to the next boundary, not a fixed tick: waking late is the SIGNAL, and
+ # the burst on the next pass is what a real backend does when a socket that
+ # was backed up clears.
+ target = t0 + (sent + 1) * gap_s
+ time.sleep(max(0.0, min(target - now, KEEPALIVE_S)))
+ continue
+ if deficit > 1:
+ stats.bursts += 1
+ stats.max_deficit = max(stats.max_deficit, deficit)
+ payload = bytearray()
+ for _ in range(deficit):
+ kind, piece = chunks[sent]
+ if kind == "reasoning":
+ # `content: ""` alongside, which is exactly what the backend's own
+ # `_gguf_chat_delta_line` emits. Without it the app takes a different
+ # branch in delta accumulation and the cumulative <think> buffer is
+ # assembled by a path the shipping build never uses.
+ delta = {"reasoning_content": piece, "content": ""}
+ stats.reasoning_chars_sent += len(piece)
+ else:
+ delta = {"content": piece}
+ stats.content_chars_sent += len(piece)
+ payload += _sse(_chunk_frame(request_id, model, delta))
+ sent += 1
+ stats.chunks_sent += 1
+ stats.chars_sent += len(piece)
+ if (
+ script.hold_after_chars is not None
+ and stats.chars_sent >= script.hold_after_chars
+ ):
+ break
+ self._write(bytes(payload), stats)
+ last_activity = time.monotonic()
+ if stats.first_chunk_ms is None:
+ stats.first_chunk_ms = (last_activity - t0) * 1000
+ stats.last_chunk_ms = (last_activity - t0) * 1000
+ if (
+ script.hold_after_chars is not None
+ and stats.chars_sent >= script.hold_after_chars
+ ):
+ # HOLD, do not close. The stop-generation action needs the app to be visibly
+ # mid-stream while it presses stop; closing the socket instead would end the
+ # stream on its own and the action would measure a stream that had already
+ # finished. The keep-alives make the hold indistinguishable from a model
+ # thinking, which is what it is standing in for.
+ stats.held = True
+ while not self.state.release.wait(KEEPALIVE_S):
+ self._write(b": keep-alive\n\n", stats)
+ stats.keepalives += 1
+ break
+
+ # BOTH terminal signals. `streamChatCompletions` throws StreamInterruptedError at EOF
+ # unless it saw a finish_reason or a [DONE]; sending one and not the other measures the
+ # app's error path and calls it a benchmark.
+ self._write(_sse(_chunk_frame(request_id, model, {}, finish_reason = "stop")), stats)
+ prompt_tokens = max(1, len(script.reasoning) // 4)
+ completion_tokens = max(1, stats.chars_sent // 4)
+ self._write(
+ _sse(
+ {
+ "id": request_id,
+ "object": "chat.completion.chunk",
+ "created": int(time.time()),
+ "model": model,
+ "choices": [],
+ "usage": {
+ "prompt_tokens": prompt_tokens,
+ "completion_tokens": completion_tokens,
+ "total_tokens": prompt_tokens + completion_tokens,
+ },
+ }
+ ),
+ stats,
+ )
+ self._write(b"data: [DONE]\n\n", stats)
+ self._end_chunked(stats)
+ stats.completed = True
+ except (BrokenPipeError, ConnectionResetError, socket.timeout) as exc:
+ # The app cancelled, or the relay went away. A first-class outcome, not an error: the
+ # stop-generation action produces exactly this.
+ stats.disconnected = True
+ stats.error = f"{type(exc).__name__}: {exc}"
+ except Exception as exc: # noqa: BLE001
+ stats.error = f"{type(exc).__name__}: {exc}"
+ finally:
+ stats.duration_ms = (time.monotonic() - t0) * 1000
+ if stats.chunks_sent > 1 and stats.last_chunk_ms and stats.first_chunk_ms is not None:
+ span = stats.last_chunk_ms - stats.first_chunk_ms
+ stats.achieved_gap_ms = span / max(1, stats.chunks_sent - 1)
+ self.state.record(stats)
+
+ def _write(self, raw: bytes, stats: StreamStats) -> None:
+ """Write, and CHARGE THE TIME to the stats.
+
+ A blocking write is backpressure: the relay's receive buffer is full because the browser
+ has not drained it because the main thread has not run. That is the same jam the frame
+ recorder sees from the other side, and having both makes it attributable rather than
+ merely visible.
+ """
+ frame = b"%x\r\n" % len(raw) + raw + b"\r\n"
+ started = time.monotonic()
+ self.wfile.write(frame)
+ self.wfile.flush()
+ stats.write_block_ms += (time.monotonic() - started) * 1000
+ stats.bytes_sent += len(frame)
+
+ def _end_chunked(self, stats: StreamStats) -> None:
+ started = time.monotonic()
+ self.wfile.write(b"0\r\n\r\n")
+ self.wfile.flush()
+ stats.write_block_ms += (time.monotonic() - started) * 1000
+
+
+class Pacer:
+ """The server, its thread, and the driver-side handle on both."""
+
+ def __init__(
+ self,
+ host: str = "127.0.0.1",
+ port: int = 0,
+ ) -> None:
+ self.state = PacerState()
+ self._server = ThreadingHTTPServer((host, port), _Handler)
+ self._server.daemon_threads = True
+ self._server.state = self.state # type: ignore[attr-defined]
+ self.host, self.port = self._server.server_address[:2]
+ self._thread: Optional[threading.Thread] = None
+
+ @property
+ def base_url(self) -> str:
+ """What Studio's provider config points at. The `/v1` is load-bearing: the backend appends
+ `/chat/completions` to it verbatim."""
+ return f"http://{self.host}:{self.port}/v1"
+
+ def start(self) -> "Pacer":
+ self._thread = threading.Thread(
+ target = self._server.serve_forever, kwargs = {"poll_interval": 0.1}, daemon = True
+ )
+ self._thread.start()
+ return self
+
+ def stop(self) -> None:
+ try:
+ self._server.shutdown()
+ except Exception: # noqa: BLE001
+ pass
+ try:
+ self._server.server_close()
+ except Exception: # noqa: BLE001
+ pass
+ if self._thread is not None:
+ self._thread.join(timeout = 5)
+
+ # ── driver-side control ─────────────────────────────────────────
+
+ def load(
+ self,
+ reasoning: str,
+ content: str,
+ *,
+ cadence: str = "field",
+ tag: str = "",
+ hold_after_chars: Optional[int] = None,
+ model: str = "studiobench-pacer",
+ chunk_chars: Optional[int] = None,
+ gap_ms: Optional[int] = None,
+ ) -> None:
+ default_chunk, default_gap = CADENCES[cadence]
+ chunk_chars = default_chunk if chunk_chars is None else chunk_chars
+ gap_ms = default_gap if gap_ms is None else gap_ms
+ self.state.model_ids = [model]
+ self.state.set_script(
+ Script(
+ reasoning = reasoning,
+ content = content,
+ chunk_chars = chunk_chars,
+ gap_ms = gap_ms,
+ model = model,
+ tag = tag,
+ hold_after_chars = hold_after_chars,
+ )
+ )
+
+ def release(self) -> None:
+ self.state.release.set()
+
+ def reset(self) -> None:
+ with self.state.lock:
+ self.state.stats.clear()
+ self.state.requests_seen = 0
+
+ def last_stats(self) -> Optional[dict]:
+ last = self.state.last()
+ return last.as_dict() if last else None
+
+ def all_stats(self) -> list[dict]:
+ """Every stream this pacer served since the last `reset`, in order.
+
+ `last_stats` alone cannot answer "did the cell stream what it planned": a cell streams an
+ opening reply and then one follow-up per `send_turn`, and the LAST of those is the only
+ one it describes. See `check_planned_streams`.
+ """
+ return [s.as_dict() for s in self.state.snapshot()]
+
+ def expected_duration_ms(
+ self,
+ reasoning: str,
+ content: str,
+ cadence: str = "field",
+ chunk_chars: Optional[int] = None,
+ gap_ms: Optional[int] = None,
+ ) -> float:
+ """What the cadence COMMITS to, before anything runs. The tier budget is built from this,
+ and the deficit scheduler is what makes it true on a slow machine as well as a fast one."""
+ default_chunk, default_gap = CADENCES[cadence]
+ chunk_chars = default_chunk if chunk_chars is None else chunk_chars
+ gap_ms = default_gap if gap_ms is None else gap_ms
+ n = len(_split(reasoning, chunk_chars)) + len(_split(content, chunk_chars))
+ return n * gap_ms
+
+
+def check_planned_streams(streams: list[dict], planned: list[dict]) -> dict:
+ """Did every turn the cell PLANNED actually stream, in full?
+
+ A cell is not one stream. It opens with a reply and then streams one follow-up per `send_turn`,
+ and until this existed the only record kept was `last_stats()` -- the LAST of them. An opening
+ reply that disconnected, or delivered 4,624 of the 10,000 characters its rung is named for, was
+ therefore erased by whichever turn happened to finish last, and the cell was scored COMPLETE
+ against a thread thousands of characters short of the one it claims. That is the one failure a
+ benchmark must never have: under-measuring and reporting success, because a reader acts on it.
+
+ Matching is by `tag`, first unmatched stream wins, because a tag is not unique. The
+ `stop_generation` action sends its OWN throwaway turn against whatever script is loaded, so it
+ produces a second, deliberately cancelled stream carrying the tag of the turn before it. Those
+ land in `extra` and are reported rather than validated: an aborted throwaway is the action
+ working, not the cell failing.
+
+ Returns a dict; `ok` is False when any planned turn is missing, unfinished, or short.
+ """
+ remaining = list(streams)
+ turns: list[dict] = []
+ ok = True
+ for want in planned:
+ tag = want.get("tag")
+ chars = int(want.get("chars") or 0)
+ got = next((s for s in remaining if s.get("tag") == tag), None)
+ if got is not None:
+ remaining.remove(got)
+ sent = int((got or {}).get("chars_sent") or 0)
+ complete = bool((got or {}).get("completed"))
+ entry = {
+ "tag": tag,
+ "turn": want.get("turn"),
+ "planned_chars": chars,
+ "chars_sent": sent if got is not None else None,
+ "completed": complete if got is not None else None,
+ "disconnected": bool((got or {}).get("disconnected")) if got is not None else None,
+ "found": got is not None,
+ }
+ if got is None:
+ entry["reason"] = (
+ f"no stream carried the tag {tag!r}, so this turn never reached the pacer"
+ )
+ elif not complete:
+ entry["reason"] = (
+ f"the stream tagged {tag!r} did not complete "
+ f"({sent} of {chars} characters sent, "
+ f"{'the client disconnected' if entry['disconnected'] else 'no terminal frame'})"
+ )
+ elif sent < chars:
+ entry["reason"] = (
+ f"the stream tagged {tag!r} delivered {sent} of the {chars} characters planned"
+ )
+ else:
+ entry["reason"] = None
+ entry["ok"] = entry["reason"] is None
+ ok = ok and entry["ok"]
+ turns.append(entry)
+ failures = [t for t in turns if not t["ok"]]
+ return {
+ "ok": ok,
+ "checked": bool(planned),
+ "planned_turns": len(planned),
+ "turns": turns,
+ # The throwaway turns and any retry, kept so a reader can see WHAT else the fixture served
+ # without them being mistaken for a planned turn that failed.
+ "extra": remaining,
+ "reason": None if ok else "; ".join(t["reason"] for t in failures),
+ }
+
+
+def _selftest() -> int:
+ """Serve one scripted reply to a plain socket client and check the wire bytes.
+
+ Run with `python -m tests.studio.studiobench.pacer`. No browser, no Studio, no Playwright: the
+ pacer's contract is with the wire, and the wire is checkable on its own.
+ """
+ import urllib.request
+
+ pacer = Pacer().start()
+ try:
+ reasoning = "R" * 480
+ content = "C" * 240
+ pacer.load(reasoning, content, cadence = "fast", tag = "selftest")
+ req = urllib.request.Request(
+ f"{pacer.base_url}/chat/completions",
+ data = json.dumps(
+ {
+ "model": "studiobench-pacer",
+ "stream": True,
+ "messages": [{"role": "user", "content": "go"}],
+ "stream_options": {"include_usage": True},
+ }
+ ).encode(),
+ headers = {"Content-Type": "application/json", "Authorization": "Bearer sb-local"},
+ )
+ started = time.monotonic()
+ raw = urllib.request.urlopen(req, timeout = 60).read().decode("utf-8")
+ elapsed_ms = (time.monotonic() - started) * 1000
+
+ events = [e for e in raw.split("\n\n") if e.strip()]
+ datas = [e[len("data: ") :] for e in events if e.startswith("data: ")]
+ assert datas[-1] == "[DONE]", f"no [DONE] terminator, got {datas[-1][:80]!r}"
+ frames = [json.loads(d) for d in datas[:-1]]
+ finish = [
+ f for f in frames if f.get("choices") and f["choices"][0].get("finish_reason") == "stop"
+ ]
+ assert finish, "no finish_reason:stop chunk"
+ usage = [f for f in frames if f.get("usage")]
+ assert usage, "no usage chunk"
+ reasoning_frames = [
+ f
+ for f in frames
+ if f.get("choices") and "reasoning_content" in f["choices"][0]["delta"]
+ ]
+ assert reasoning_frames, "no reasoning_content deltas"
+ for f in reasoning_frames:
+ assert (
+ f["choices"][0]["delta"].get("content") == ""
+ ), "reasoning_content must carry content:'' alongside, as _gguf_chat_delta_line does"
+ got_reasoning = "".join(
+ f["choices"][0]["delta"]["reasoning_content"] for f in reasoning_frames
+ )
+ assert got_reasoning == reasoning, "reasoning did not round-trip"
+ content_frames = [
+ f for f in frames if f.get("choices") and f["choices"][0]["delta"].get("content")
+ ]
+ got_content = "".join(f["choices"][0]["delta"]["content"] for f in content_frames)
+ assert got_content == content, "content did not round-trip"
+
+ stats = pacer.last_stats()
+ assert stats and stats["completed"], f"stream did not complete: {stats}"
+ expected = pacer.expected_duration_ms(reasoning, content, "fast")
+ # The deficit scheduler's whole promise: duration is set by wall clock, not by how fast
+ # the reader is. Generous bound because a loaded CI box is exactly the case it must hold in.
+ assert (
+ elapsed_ms >= expected * 0.75
+ ), f"stream finished in {elapsed_ms:.0f}ms, faster than the {expected:.0f}ms cadence"
+ assert (
+ elapsed_ms <= expected * 2.5 + 1000
+ ), f"stream took {elapsed_ms:.0f}ms against a {expected:.0f}ms cadence"
+
+ # /v1/models, which the SPA's model list may probe.
+ models = json.loads(urllib.request.urlopen(f"{pacer.base_url}/models", timeout = 10).read())
+ assert models["data"][0]["id"] == "studiobench-pacer", models
+
+ print(
+ f"pacer selftest OK: {stats['chunks_sent']} chunks, {stats['chars_sent']} chars, "
+ f"{elapsed_ms:.0f}ms against a {expected:.0f}ms cadence, "
+ f"achieved gap {stats['achieved_gap_ms']}ms against {stats['requested_gap_ms']}ms, "
+ f"{stats['bursts']} bursts, max deficit {stats['max_deficit']}"
+ )
+
+ # PHASE 2: the deficit claim itself. A reader that stalls must NOT slow the stream down;
+ # it must come back to a burst and the run must still end on wall clock. This is the
+ # difference between measuring a renderer and measuring a server that waits for one.
+ pacer.reset()
+ # Big enough to exhaust the loopback send buffer, which autotunes to `wmem_max` (4MB on
+ # this kernel). A 400KB reply does not block a loopback write no matter how long the
+ # reader sleeps, so a smaller body tests nothing.
+ body = "D" * 12_000_000
+ cad = {"chunk_chars": 12_000, "gap_ms": 1}
+ pacer.load("", body, tag = "backpressure", **cad)
+ conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ # A small receive buffer is what makes this a test. With the default buffer the kernel
+ # absorbs a 17KB reply whole, the pacer's writes never block, it is never late, and there
+ # is correctly no deficit to schedule -- which is what the first version of this check
+ # measured and wrongly called a failure. Backpressure needs a reader that cannot keep up
+ # AND a pipe that fills, which is exactly the case a jammed renderer produces.
+ conn.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 65536)
+ conn.settimeout(60)
+ conn.connect((pacer.host, pacer.port))
+ payload = json.dumps(
+ {
+ "model": "studiobench-pacer",
+ "stream": True,
+ "messages": [{"role": "user", "content": "go"}],
+ }
+ ).encode()
+ conn.sendall(
+ b"POST /v1/chat/completions HTTP/1.1\r\n"
+ b"Host: 127.0.0.1\r\nContent-Type: application/json\r\n"
+ + b"Content-Length: "
+ + str(len(payload)).encode()
+ + b"\r\n\r\n"
+ + payload
+ )
+ started = time.monotonic()
+ # Read nothing at all for a stretch several gaps long, then drain. The socket buffer
+ # absorbs it, so the pacer keeps its own clock and owes a shortfall when it next looks.
+ time.sleep(0.4)
+ conn.setblocking(True)
+ seen = b""
+ while b"[DONE]" not in seen:
+ got = conn.recv(65536)
+ if not got:
+ break
+ seen += got
+ stalled_ms = (time.monotonic() - started) * 1000
+ conn.close()
+ expected2 = pacer.expected_duration_ms("", body, **cad)
+ s2 = pacer.last_stats()
+ assert s2 and s2["completed"], f"stalled stream did not complete: {s2}"
+ assert s2["bursts"] > 0, (
+ "a 400ms reader stall produced no deficit burst, so the pacer is sleeping per chunk "
+ f"rather than scheduling against wall clock: {s2}"
+ )
+ # The honest form of the machine-independence claim. No scheduler can make a stream finish
+ # faster than the reader consumes it, so total duration is NOT bounded by the cadence when
+ # the reader is the throughput limit. What the deficit scheduler promises is narrower and
+ # is exactly what is checked here: the pacer itself adds no delay beyond the cadence, so
+ # every millisecond of overrun is accounted for by time blocked in a write. If it were
+ # sleeping a gap per chunk instead, the overrun would exceed the blocked time by the
+ # stall, since each late chunk would then push the NEXT one late as well.
+ unblocked_ms = stalled_ms - s2["write_block_ms"]
+ assert unblocked_ms <= expected2 * 2.5 + 1000, (
+ f"the stream spent {unblocked_ms:.0f}ms not blocked on a write, against a "
+ f"{expected2:.0f}ms cadence: the pacer is adding delay of its own"
+ )
+ print(
+ f"pacer backpressure OK: {s2['bursts']} bursts, max deficit {s2['max_deficit']}, "
+ f"{stalled_ms:.0f}ms total of which {s2['write_block_ms']:.0f}ms blocked on a "
+ f"jammed reader, leaving {unblocked_ms:.0f}ms against a {expected2:.0f}ms cadence"
+ )
+ return 0
+ finally:
+ pacer.stop()
+
+
+if __name__ == "__main__":
+ raise SystemExit(_selftest())
diff --git a/tests/studio/studiobench/report/__init__.py b/tests/studio/studiobench/report/__init__.py
new file mode 100644
index 00000000000..eca13449246
--- /dev/null
+++ b/tests/studio/studiobench/report/__init__.py
@@ -0,0 +1,70 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Report: incremental payload on the way in, editorial policy on the way out."""
+
+from .ablation import ( # noqa: F401
+ render_arm_verdicts,
+ render_batch,
+ render_fix_implications,
+ render_interactions,
+ render_route,
+)
+from .payload import ( # noqa: F401
+ PayloadWriter,
+ RECORD_KINDS,
+ ROW_TYPE_SECTIONS,
+ assemble,
+ assemble_rows,
+ encode,
+ excluded_from_rows,
+ excluded_totals,
+ iter_windows,
+ read_records,
+ write_excluded,
+)
+from .render import ( # noqa: F401
+ HEADLINE_FRAME_METRICS,
+ HeadlinePolicyError,
+ assert_headline_pair,
+ render_ab_table,
+ render_ceiling_shift,
+ render_excluded,
+ render_frame_health,
+ render_harness_bias,
+ render_headline,
+ render_rung_metrics,
+ render_rung_table,
+ render_summary,
+)
+
+__all__ = [
+ "HEADLINE_FRAME_METRICS",
+ "render_arm_verdicts",
+ "render_batch",
+ "render_fix_implications",
+ "render_interactions",
+ "render_route",
+ "HeadlinePolicyError",
+ "PayloadWriter",
+ "RECORD_KINDS",
+ "ROW_TYPE_SECTIONS",
+ "assemble",
+ "assemble_rows",
+ "assert_headline_pair",
+ "encode",
+ "excluded_from_rows",
+ "excluded_totals",
+ "iter_windows",
+ "read_records",
+ "render_ab_table",
+ "render_ceiling_shift",
+ "render_excluded",
+ "render_frame_health",
+ "render_harness_bias",
+ "render_headline",
+ "render_rung_metrics",
+ "render_rung_table",
+ "render_summary",
+ "write_excluded",
+]
diff --git a/tests/studio/studiobench/report/ablation.py b/tests/studio/studiobench/report/ablation.py
new file mode 100644
index 00000000000..38f41ed862f
--- /dev/null
+++ b/tests/studio/studiobench/report/ablation.py
@@ -0,0 +1,204 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Rendering the ablation batch, in an order that cannot be read out of sequence.
+
+CALIBRATION IS PRINTED FIRST AND CAN END THE SECTION. If the batch is not quotable, the only
+thing printed is why. There is no table with a warning above it, because the table is what gets
+screenshotted into a thread and the warning is what gets left behind.
+
+ARMS ARE NEVER QUOTED ALONE. Only adjacent differences on a route appear, which is enforced
+upstream by `LadderRoute.quote_arm` raising; here it shows up as the absence of a per-arm cost
+column. What IS printed per arm is its VERDICT, because a voided arm and an arm that did not fire
+are findings about the experiment that a reader needs even though their numbers are not usable.
+
+THE TWO ROUTES ARE PRINTED SEPARATELY AND THEN COMPARED. Nothing anywhere averages them. Where
+they disagree, the disagreement is the interaction term and gets its own block with its own
+sentence about what it means.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Mapping, Sequence
+
+from ..arms.batch import BatchResult
+from ..arms.knobs import render_decision_table
+from ..arms.ladder import MECHANISM_FIX, RouteResult
+from ..arms.manifest import ArmStatus
+
+
+def render_route(result: RouteResult) -> str:
+ lines = [
+ f"ROUTE {result.route.route_id}: {result.route.name}",
+ "",
+ ]
+ header = f" {'step':<28} {'mechanism removed':<44} difference"
+ lines.append(header)
+ lines.append(" " + "-" * (len(header) - 2))
+ for step_result in result.steps:
+ mechanisms = ", ".join(step_result.step.mechanisms)
+ if step_result.step.fused:
+ mechanisms += " [FUSED]"
+ lines.append(f" {step_result.step.label:<28} {mechanisms:<44} {step_result.quote()}")
+ lines.append("")
+ if result.total is not None:
+ lines.append(f" top minus floor {result.total.display()}")
+ if result.sum_of_steps is not None:
+ lines.append(f" sum of the steps {result.sum_of_steps.display()}")
+ lines.append(f" residual {result.residual_ms:.9f} ms")
+ lines.append(f" {result.identity_note}")
+ fused = [s for s in result.steps if s.step.fused]
+ if fused:
+ lines.append("")
+ for step_result in fused:
+ lines.append(f" FUSED STEP {step_result.step.label}: {step_result.step.fused_reason}")
+ return "\n".join(lines)
+
+
+def render_interactions(result: BatchResult) -> str:
+ lines = ["INTERACTION TERMS (two routes, same floor, compared mechanism by mechanism)"]
+ if not result.interactions:
+ lines.append(
+ " none computed. Two routes are needed and at least one of them did not produce a "
+ "complete set of differences"
+ )
+ return "\n".join(lines)
+ header = f" {'mechanism':<32} {'route A':>12} {'route B':>12} {'gap':>12}"
+ lines.append("")
+ lines.append(header)
+ lines.append(" " + "-" * (len(header) - 2))
+ for term in result.interactions:
+ gap = f"{term.disagreement_ms:+.3f}" if term.disagreement_ms is not None else "n/a"
+ lines.append(
+ f" {term.mechanism:<32} {term.value_a.display():>12} "
+ f"{term.value_b.display():>12} {gap:>12}"
+ )
+ lines.append("")
+ for term in result.interactions:
+ lines.append(f" {term.mechanism}: {term.note}")
+ lines.append("")
+ lines.append(
+ " Nothing here is averaged. Two routes disagreeing about the same mechanism is a "
+ "finding about additivity, and a mean of the two describes neither route."
+ )
+ return "\n".join(lines)
+
+
+def render_arm_verdicts(result: BatchResult) -> str:
+ """Every arm's status, including the ones whose numbers are not usable."""
+
+ lines = ["ARM VERDICTS (no arm's absolute cost is quoted; only adjacent differences are)"]
+ if not result.outcomes:
+ lines.append(" no arms were run")
+ return "\n".join(lines)
+ for key in sorted(result.outcomes):
+ outcome = result.outcomes[key]
+ lines.append(f" {key:<20} {outcome.status.value:<12} {outcome.reason}")
+ voided = result.voided_arms()
+ not_run = result.not_run_arms()
+ if voided:
+ lines.append("")
+ lines.append(
+ " VOIDED arms produced a number and it is not being used. They changed the rendered "
+ "output, so their difference is not attributable to the mechanism."
+ )
+ if not_run:
+ lines.append("")
+ lines.append(
+ " NOT RUN arms are not evidence of no effect. Their potency counter never moved, "
+ "which means the treatment was not applied at all."
+ )
+ return "\n".join(lines)
+
+
+def render_batch(result: BatchResult, *, include_decision_table: bool = True) -> str:
+ """The whole ablation section for one rung, in the only order it may be read."""
+
+ sections: list[str] = []
+ title = f"ABLATION at {result.rung_tokens:,} tokens"
+ sections.append(title + "\n" + "=" * len(title))
+ sections.append(result.calibration.render())
+
+ if not result.quotable:
+ sections.append(
+ "NO ABLATION NUMBERS ARE PRINTED FOR THIS BATCH.\n"
+ f" {result.calibration.reason}\n"
+ " The arms ran and produced numbers. They are in the payload and they are not "
+ "quoted here, because a batch that cannot tell two identical builds apart cannot "
+ "tell two different ones apart either."
+ )
+ sections.append(render_arm_verdicts(result))
+ return "\n\n".join(sections) + "\n"
+
+ if result.armpack is not None:
+ sections.append(result.armpack.render())
+
+ if include_decision_table:
+ sections.append(render_decision_table().rstrip())
+
+ for route in result.routes:
+ sections.append(render_route(route))
+
+ sections.append(render_interactions(result))
+ sections.append(render_arm_verdicts(result))
+
+ if result.dose is not None:
+ sections.append(result.dose.render())
+ if result.recovery is not None:
+ sections.append(result.recovery.render())
+
+ if result.plan_notes:
+ sections.append("NOTES\n" + "\n".join(f" {note}" for note in result.plan_notes))
+
+ return "\n\n".join(sections) + "\n"
+
+
+def render_fix_implications(result: BatchResult, *, top_n: int = 3) -> str:
+ """Which fix the measured steps point at, ranked by the size of the step.
+
+ This is the decision table applied to the numbers rather than printed as a table: the largest
+ adjacent difference names the layer the cost lives in, and the mechanism's declared fix is
+ printed next to it. A step that is only a bound is labelled as such and cannot be ranked
+ above a point estimate of the same size.
+ """
+
+ by_mechanism: dict[str, list[tuple[str, float, bool]]] = {}
+ for route in result.routes:
+ for step_result in route.steps:
+ if not (step_result.quotable and step_result.difference.has_reading):
+ continue
+ for mechanism in step_result.step.mechanisms:
+ by_mechanism.setdefault(mechanism, []).append(
+ (
+ route.route.route_id,
+ float(step_result.difference.value),
+ step_result.bound_only,
+ )
+ )
+ if not by_mechanism:
+ return "FIX IMPLICATIONS\n none: no step on either route produced a usable difference"
+
+ ranked = sorted(
+ by_mechanism.items(),
+ key = lambda item: (-max(value for _, value, _ in item[1]), item[0]),
+ )
+ lines = [
+ "FIX IMPLICATIONS (ranked by the largest measured step, which is a RANGE when the two "
+ "routes disagree)"
+ ]
+ for mechanism, measurements in ranked[:top_n]:
+ values = [value for _, value, _ in measurements]
+ bound_only = any(bound for _, _, bound in measurements)
+ prefix = "<= " if bound_only else ""
+ if len(values) > 1 and max(values) - min(values) > 1e-9:
+ # Printing only the largest would let a reader take the most flattering route as the
+ # answer. The spread IS the interaction term and it belongs next to the number.
+ spread = ", ".join(
+ f"{route_id} {value:.3f}" for route_id, value, _ in sorted(measurements)
+ )
+ lines.append(f" {prefix}{min(values):.3f} to {max(values):.3f} ms {mechanism}")
+ lines.append(f" routes disagree: {spread}")
+ else:
+ lines.append(f" {prefix}{values[0]:.3f} ms {mechanism}")
+ lines.append(f" {MECHANISM_FIX[mechanism]}")
+ return "\n".join(lines)
diff --git a/tests/studio/studiobench/report/build.py b/tests/studio/studiobench/report/build.py
new file mode 100644
index 00000000000..19246089ff7
--- /dev/null
+++ b/tests/studio/studiobench/report/build.py
@@ -0,0 +1,109 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Payload on disk -> scored, rendered summary.
+
+The last mile. Everything either side of it existed: the session layer wrote rows, the scoring
+layer scored readings, the renderer rendered scores. Nothing joined them, so a completed run
+produced a JSONL file and no report.
+
+The one policy decision that lives here: WHICH RUNGS ARE ON THE LADDER. `score_ladder` demands
+every declared rung, present or not, because aggregating over only the rungs that survived is the
+crash-beats-limp bug wearing a different hat. So a rung that was declared for the tier and never
+produced a cell is passed through as INCOMPLETE with the reason, not quietly dropped.
+"""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Mapping, Sequence
+from pathlib import Path
+from typing import Any
+
+from ..scoring.from_payload import latest_attempt_rows, measures_from_records
+from ..scoring.score import LadderScore, RungScore, score_ladder, score_rung
+from .payload import assemble_rows
+from .render import render_summary
+
+
+def _records(path: str | Path) -> list[dict[str, Any]]:
+ out: list[dict[str, Any]] = []
+ with Path(path).open(encoding = "utf-8") as fh:
+ for line in fh:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ out.append(json.loads(line))
+ except ValueError:
+ # A truncated final line is expected when a run was killed mid-write; the
+ # records before it are still good and are still reported.
+ continue
+ return out
+
+
+def _completion_by_rung(records: Sequence[Mapping[str, Any]]) -> dict[int, tuple[bool, str | None]]:
+ out: dict[int, tuple[bool, str | None]] = {}
+ for r in records:
+ if r.get("row_type") != "cell":
+ continue
+ tokens = r.get("target_tokens")
+ if tokens is None:
+ continue
+ completed = bool(r.get("completed"))
+ failure = r.get("failure") or {}
+ reason = None
+ if not completed:
+ reason = f"{failure.get('kind') or 'unknown'}: {failure.get('message') or 'no message'}"
+ # 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.
+ prev = out.get(int(tokens))
+ if prev is None or (prev[0] and not completed):
+ out[int(tokens)] = (completed, reason)
+ return out
+
+
+def score_payload(path: str | Path, declared_rungs: Sequence[int] | None = None) -> LadderScore:
+ """Score one run. `declared_rungs` is the ladder the tier promised, in tokens."""
+
+ # A CELL THAT WAS RE-RUN IS SCORED ON THE RUN THAT FINISHED IT. `--resume` re-runs the cells
+ # that died, under the same `cell_id`, into the same file; scoring both attempts as one cell
+ # kept the crash forever, so a rung that had since been re-run successfully still came out
+ # INCOMPLETE and zero. The dead attempt is still in the payload and still in EXCLUDED CELLS,
+ # which is where a superseded crash belongs -- it is only kept out of the score.
+ records = latest_attempt_rows(_records(path))
+ measures = measures_from_records(records)
+ completion = _completion_by_rung(records)
+
+ rungs = sorted(set(declared_rungs) | set(measures)) if declared_rungs else sorted(measures)
+
+ scored: list[RungScore] = []
+ for tokens in rungs:
+ if tokens not in measures:
+ scored.append(
+ score_rung(
+ tokens,
+ {},
+ completed = False,
+ failure_mode = "declared for this tier but no cell was recorded for it",
+ )
+ )
+ continue
+ complete, reason = completion.get(tokens, (True, None))
+ scored.append(score_rung(tokens, measures[tokens], completed = complete, failure_mode = reason))
+ return score_ladder(scored)
+
+
+def build_report(
+ path: str | Path,
+ declared_rungs: Sequence[int] | None = None,
+ *,
+ extra_sections: Sequence[str] = (),
+) -> tuple[str, LadderScore, dict[str, Any]]:
+ """Return (rendered summary, ladder, assembled payload)."""
+
+ payload = assemble_rows(path)
+ ladder = score_payload(path, declared_rungs)
+ text = render_summary(payload, ladder, extra_sections = extra_sections)
+ return text, ladder, payload
diff --git a/tests/studio/studiobench/report/overhead.py b/tests/studio/studiobench/report/overhead.py
new file mode 100644
index 00000000000..9ef4ba773a1
--- /dev/null
+++ b/tests/studio/studiobench/report/overhead.py
@@ -0,0 +1,196 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""`overhead_growth_with_length`: the gate that disqualifies an instrument level.
+
+An instrument that costs a constant 3 ms per window is an annoyance. An instrument whose cost
+GROWS WITH THREAD LENGTH is a catastrophe, because the entire question this tool exists to answer
+is whether cost grows with thread length. Such an instrument manufactures the symptom, and it
+manufactures it in exactly the shape everyone is looking for, which is the worst possible way to
+be wrong: the result confirms the hypothesis, the hypothesis is plausible, and nobody re-runs it.
+
+So overhead is not just recorded, it is REGRESSED AGAINST THE TREATMENT. Every instrument at
+level 1 or above declares `overhead_ms` per cell. If that number climbs across the rung ladder by
+more than the tolerance, the LEVEL is disqualified: the numbers gathered at it may still be read
+for structure (which function ran how many times), but no growth claim may rest on them.
+
+Headline numbers come from level 0 for exactly this reason, and this gate is what keeps that from
+being a promise rather than a check.
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass, field
+from typing import Any, Mapping
+
+from ..scoring.schema import Measure
+
+#: Overhead may vary this much across the ladder before the level is disqualified. Generous:
+#: some growth is unavoidable (more DOM means a longer snapshot), and a tight bound would
+#: disqualify every level on every machine, which is the same as having no gate.
+MAX_OVERHEAD_GROWTH_RATIO = 1.5
+
+#: Growth below this many milliseconds is not worth acting on however large the ratio looks.
+#: A level whose overhead goes from 0.01 ms to 0.05 ms has a ratio of 5 and does not matter.
+MIN_ABSOLUTE_GROWTH_MS = 1.0
+
+
+@dataclass
+class OverheadVerdict:
+ """One instrument level, judged on whether its cost tracks the treatment."""
+
+ level: int
+ instrument: str
+ disqualified: bool
+ reason: str
+ growth_ratio: float | None
+ growth_ms: Measure
+ by_rung: dict[int, Measure] = field(default_factory = dict)
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "level": int(self.level),
+ "instrument": self.instrument,
+ "disqualified": bool(self.disqualified),
+ "reason": self.reason,
+ "growth_ratio": self.growth_ratio,
+ "growth_ms": self.growth_ms.to_json(),
+ "by_rung": {str(k): v.to_json() for k, v in sorted(self.by_rung.items())},
+ }
+
+ def render(self) -> str:
+ lines = [
+ f"INSTRUMENT OVERHEAD: {self.instrument} at level {self.level}",
+ ]
+ for rung, measure in sorted(self.by_rung.items()):
+ lines.append(f" {rung:>10,} tokens {measure.display()}")
+ lines.append(f" growth {self.growth_ms.display()}")
+ if self.growth_ratio is not None:
+ lines.append(f" growth ratio {self.growth_ratio:.2f}x across the ladder")
+ lines.append(
+ f" VERDICT: {'DISQUALIFIED' if self.disqualified else 'usable'} -- {self.reason}"
+ )
+ return "\n".join(lines)
+
+
+def overhead_growth_gate(
+ instrument: str,
+ level: int,
+ by_rung: Mapping[int, Measure],
+ *,
+ max_ratio: float = MAX_OVERHEAD_GROWTH_RATIO,
+ min_absolute_growth_ms: float = MIN_ABSOLUTE_GROWTH_MS,
+) -> OverheadVerdict:
+ """Judge one instrument at one level across the rung ladder.
+
+ Disqualification needs BOTH a ratio above `max_ratio` and an absolute growth above
+ `min_absolute_growth_ms`. Either alone is a false positive generator: a ratio on a tiny number
+ is noise, and an absolute growth on a huge constant overhead is not correlation with the
+ treatment, it is a big instrument.
+ """
+
+ readings = {int(rung): m for rung, m in by_rung.items() if m.has_reading}
+ verdict = OverheadVerdict(
+ level = level,
+ instrument = instrument,
+ disqualified = False,
+ reason = "",
+ growth_ratio = None,
+ growth_ms = Measure.not_attempted("ms", "overhead was not measured across rungs"),
+ by_rung = {int(rung): m for rung, m in by_rung.items()},
+ )
+
+ if level <= 0:
+ verdict.reason = (
+ "level 0 carries the headline numbers and declares no overhead; there is nothing to "
+ "disqualify it against"
+ )
+ return verdict
+
+ if len(readings) < 2:
+ verdict.reason = (
+ f"only {len(readings)} rung(s) reported an overhead reading, so the gate could not be "
+ "evaluated. An unevaluated gate is not a passed gate"
+ )
+ return verdict
+
+ smallest_rung = min(readings)
+ largest_rung = max(readings)
+ low = float(readings[smallest_rung].value)
+ high = float(readings[largest_rung].value)
+ growth = high - low
+ verdict.growth_ms = Measure.read(growth, "ms")
+ verdict.growth_ratio = (high / low) if low > 0 else None
+
+ if growth <= 0:
+ verdict.reason = (
+ "overhead does not grow with thread length, so it cannot be manufacturing a slope"
+ )
+ return verdict
+
+ ratio_bad = verdict.growth_ratio is not None and verdict.growth_ratio > max_ratio
+ absolute_bad = growth > min_absolute_growth_ms
+ if ratio_bad and absolute_bad:
+ verdict.disqualified = True
+ verdict.reason = (
+ f"overhead grows {verdict.growth_ratio:.2f}x ({growth:.2f} ms) between the "
+ f"{smallest_rung:,} and {largest_rung:,} token rungs. This instrument's own cost "
+ "tracks the treatment, so it manufactures the very slope the run is looking for. No "
+ "growth claim may rest on level "
+ f"{level}"
+ )
+ return verdict
+
+ if ratio_bad:
+ verdict.reason = (
+ f"the ratio is {verdict.growth_ratio:.2f}x but the absolute growth is only "
+ f"{growth:.3f} ms, below the {min_absolute_growth_ms:g} ms that would matter"
+ )
+ else:
+ verdict.reason = (
+ f"overhead grows {growth:.2f} ms across the ladder, within the {max_ratio:g}x "
+ "tolerance"
+ )
+ return verdict
+
+
+def render_overhead_section(verdicts: list[OverheadVerdict]) -> str:
+ if not verdicts:
+ return (
+ "INSTRUMENT OVERHEAD\n"
+ " no instrument above level 0 ran, so no overhead gate was evaluated"
+ )
+ blocks = [verdict.render() for verdict in verdicts]
+ disqualified = [v for v in verdicts if v.disqualified]
+ if disqualified:
+ blocks.append(
+ "DISQUALIFIED LEVELS: "
+ + ", ".join(f"{v.instrument}@L{v.level}" for v in disqualified)
+ + "\n Their structural output (counts, names) is still usable. Their timings are "
+ "not, and nothing about growth may be quoted from them."
+ )
+ return "\n\n".join(blocks)
+
+
+def log_growth_slope(by_rung: Mapping[int, Measure]) -> float | None:
+ """Least-squares slope of overhead against log(tokens), for the payload.
+
+ Reported alongside the ratio because the ratio only looks at the two ends. An instrument that
+ is flat at both ends and spikes in the middle has a ratio of 1.0 and a visible problem.
+ """
+
+ points = [
+ (math.log(float(rung)), float(m.value))
+ for rung, m in by_rung.items()
+ if m.has_reading and float(rung) > 0
+ ]
+ if len(points) < 2:
+ return None
+ n = len(points)
+ mean_x = sum(x for x, _ in points) / n
+ mean_y = sum(y for _, y in points) / n
+ denominator = sum((x - mean_x) ** 2 for x, _ in points)
+ if denominator <= 0:
+ return None
+ return sum((x - mean_x) * (y - mean_y) for x, y in points) / denominator
diff --git a/tests/studio/studiobench/report/payload.py b/tests/studio/studiobench/report/payload.py
new file mode 100644
index 00000000000..ce83645a5d6
--- /dev/null
+++ b/tests/studio/studiobench/report/payload.py
@@ -0,0 +1,362 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Incremental JSONL payload: what survives when the renderer dies at rung 4.
+
+A benchmark that builds its result in memory and writes it at the end has one output state and
+one failure state, and the failure state is an empty directory. The runs that matter most are
+exactly the ones that fail: a build that kills the renderer at 500K tokens is the most
+interesting result the tool can produce, and losing the three rungs that DID complete because the
+fourth crashed the browser turns the best evidence into no evidence.
+
+So every window is appended to a JSONL file and flushed to the OS as it is produced. A crash at
+rung 4 leaves rungs 1-3 on disk plus, if the harness got the chance, a `crash` record naming what
+happened. `assemble()` reads whatever is there, tolerates a half-written final line (a process
+killed mid-write leaves one), and reports how many records it had to discard rather than pretending
+the file was complete.
+
+`assemble()` also runs `validate_payload()`, so the schema-level ban on bare zeros is enforced on
+the real payload and not only in the unit tests.
+
+RECORD KINDS, all of which carry `kind` and `at_ms`:
+ header one per run, first: identity, machine, bench version, instrument levels
+ selfcheck the integrity gates and their verdicts; if any failed the run should have aborted
+ window one measured window: rung, arm, action, frame stats, metrics
+ arm one ablation arm outcome: invariance verdict, potency counters, cost
+ excluded one excluded cell with its reason
+ crash something died; carries the last sample row and RSS at death
+ footer one per run, last: totals, wall time, exit status
+A file with no footer record is a run that did not finish, which `assemble()` reports as
+`complete: false` rather than silently treating as finished.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import json
+import os
+import time
+from pathlib import Path
+from typing import Any, Iterable, Iterator, Mapping, Sequence
+
+from ..scoring.schema import ExcludedCell, Measure, validate_payload
+
+RECORD_KINDS = (
+ "header",
+ "selfcheck",
+ "window",
+ "arm",
+ "excluded",
+ "crash",
+ "footer",
+)
+
+
+def encode(node: Any) -> Any:
+ """Recursively turn harness objects into JSON-safe data, preserving measure semantics."""
+
+ if isinstance(node, Measure):
+ return node.to_json()
+ if isinstance(node, ExcludedCell):
+ return node.to_json()
+ if dataclasses.is_dataclass(node) and not isinstance(node, type):
+ if hasattr(node, "to_json"):
+ return encode(node.to_json())
+ return {k: encode(v) for k, v in dataclasses.asdict(node).items()}
+ if isinstance(node, Mapping):
+ return {str(k): encode(v) for k, v in node.items()}
+ if isinstance(node, (list, tuple, set)):
+ return [encode(v) for v in node]
+ if isinstance(node, Path):
+ return str(node)
+ return node
+
+
+class PayloadWriter:
+ """Append-only JSONL writer. One line per record, flushed as it is written.
+
+ `fsync` is optional and off by default: it costs a few milliseconds per record, which on a
+ per-window cadence is measurable against the thing being measured. The default (flush to the
+ OS, no fsync) survives a renderer crash, a Python exception and a `SIGKILL` of the driver,
+ which is every failure this file exists for; it does not survive the machine losing power,
+ which is not a case worth slowing the benchmark down for.
+ """
+
+ def __init__(
+ self,
+ path: str | Path,
+ *,
+ fsync: bool = False,
+ ) -> None:
+ self.path = Path(path)
+ self.path.parent.mkdir(parents = True, exist_ok = True)
+ self._fh = self.path.open("a", encoding = "utf-8")
+ self._fsync = bool(fsync)
+ self._started = time.monotonic()
+ self.records_written = 0
+
+ def write(self, kind: str, **fields: Any) -> dict[str, Any]:
+ if kind not in RECORD_KINDS:
+ raise ValueError(f"unknown record kind {kind!r}; expected one of {RECORD_KINDS}")
+ record = {
+ "kind": kind,
+ "at_ms": round((time.monotonic() - self._started) * 1000.0, 3),
+ **{k: encode(v) for k, v in fields.items()},
+ }
+ self._fh.write(json.dumps(record, separators = (",", ":"), sort_keys = False) + "\n")
+ self._fh.flush()
+ if self._fsync:
+ os.fsync(self._fh.fileno())
+ self.records_written += 1
+ return record
+
+ def close(self) -> None:
+ try:
+ self._fh.close()
+ except Exception:
+ pass
+
+ def __enter__(self) -> "PayloadWriter":
+ return self
+
+ def __exit__(self, exc_type, exc, tb) -> None:
+ if exc_type is not None:
+ # Best effort: if the driver is dying, say so in the file before it goes.
+ try:
+ self.write(
+ "crash",
+ where = "driver",
+ error_type = getattr(exc_type, "__name__", str(exc_type)),
+ error = str(exc),
+ )
+ except Exception:
+ pass
+ self.close()
+
+
+def read_records(path: str | Path) -> tuple[list[dict[str, Any]], int]:
+ """Read a JSONL payload, tolerating a truncated final line.
+
+ Returns `(records, discarded)`. `discarded` is almost always 0 or 1: a process killed
+ mid-write leaves at most one partial line, and more than that means the file was corrupted
+ some other way, which the report prints rather than hides.
+ """
+
+ records: list[dict[str, Any]] = []
+ discarded = 0
+ file_path = Path(path)
+ if not file_path.exists():
+ return records, discarded
+ with file_path.open("r", encoding = "utf-8") as handle:
+ for line in handle:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ records.append(json.loads(line))
+ except json.JSONDecodeError:
+ discarded += 1
+ return records, discarded
+
+
+def assemble(path: str | Path, *, validate: bool = True) -> dict[str, Any]:
+ """Turn a JSONL stream into one payload dict, complete or not.
+
+ `excluded_cells` is materialised here and is always a list, never absent and never null,
+ because a report that cannot say what it dropped is a report that dropped things silently.
+ """
+
+ records, discarded = read_records(path)
+ by_kind: dict[str, list[dict[str, Any]]] = {kind: [] for kind in RECORD_KINDS}
+ for record in records:
+ by_kind.setdefault(record.get("kind", "unknown"), []).append(record)
+
+ header = by_kind["header"][0] if by_kind["header"] else {}
+ footer = by_kind["footer"][-1] if by_kind["footer"] else None
+
+ payload: dict[str, Any] = {
+ "schema": "studiobench/payload/1",
+ "complete": footer is not None,
+ "truncated_records": discarded,
+ "record_counts": {k: len(v) for k, v in by_kind.items() if v},
+ "header": header,
+ "selfcheck": by_kind["selfcheck"],
+ "windows": by_kind["window"],
+ "arms": by_kind["arm"],
+ "crashes": by_kind["crash"],
+ "footer": footer,
+ "excluded_cells": [
+ {
+ "cell_id": rec.get("cell_id", "unknown"),
+ "reason": rec.get("reason", "unknown"),
+ "count": int(rec.get("count", 1)),
+ "detail": rec.get("detail"),
+ }
+ for rec in by_kind["excluded"]
+ ],
+ }
+ if not payload["complete"]:
+ payload["incomplete_note"] = (
+ "no footer record: this run did not reach the end. Everything above it was still "
+ "measured and is reported; nothing below it exists."
+ )
+ if validate:
+ validate_payload(payload)
+ return payload
+
+
+#: How the harness layer's `row_type` values map onto the sections of an assembled payload.
+#: Layer 1 writes rows through its `Recorder`; this layer reads them. Keeping the mapping in one
+#: table rather than spread through the renderer means a new row type is one line here and a
+#: visible `unknown_rows` entry until somebody decides where it belongs.
+ROW_TYPE_SECTIONS: Mapping[str, str] = {
+ "run_meta": "header",
+ "gate": "selfcheck",
+ "cell": "cells",
+ "window": "windows",
+ "action": "actions",
+ "sample": "samples",
+ "failure": "crashes",
+ # Bookkeeping about HOW the A/B was run, not a measurement of the app. It belongs beside the
+ # identity fields so a reader can see whether the order was balanced without digging.
+ "ab_plan": "header",
+ # The optional surface sweep. Its own section: a surface row is a coverage fact about the UI,
+ # not a timing, and folding it into `actions` would put it in front of the scorer.
+ "surface": "surfaces",
+}
+
+
+def assemble_rows(path: str | Path, *, validate: bool = True) -> dict[str, Any]:
+ """Assemble a payload from the HARNESS layer's row stream (`row_type`, not `kind`).
+
+ Two writers exist on purpose and they are not redundant. `PayloadWriter` is this layer's own
+ stream, used by the ablation batches, which run outside a Layer 1 session and have no
+ Recorder. `Recorder` is Layer 1's, and its rows are what a full session produces. Both end up
+ in the same assembled shape so the renderer has one input, and neither has to know about the
+ other while it is writing.
+
+ A completed run is one that emitted at least one `run_meta` row and at least one `cell` row
+ with `completed` true. There is no footer row in the harness contract, so completeness is
+ inferred from content rather than from a marker that a crash would remove.
+ """
+
+ records, discarded = read_records(path)
+ sections: dict[str, list[dict[str, Any]]] = {
+ name: [] for name in sorted(set(ROW_TYPE_SECTIONS.values()))
+ }
+ unknown: list[dict[str, Any]] = []
+ for record in records:
+ row_type = record.get("row_type")
+ section = ROW_TYPE_SECTIONS.get(str(row_type)) if row_type else None
+ if section is None:
+ unknown.append(record)
+ continue
+ sections[section].append(record)
+
+ cells = sections.get("cells", [])
+ completed_cells = [c for c in cells if c.get("completed") is True]
+ payload: dict[str, Any] = {
+ "schema": "studiobench/payload/1",
+ "source": "recorder_rows",
+ "complete": bool(sections.get("header")) and bool(completed_cells),
+ "truncated_records": discarded,
+ "record_counts": {name: len(rows) for name, rows in sections.items() if rows},
+ "header": sections.get("header", [{}])[0] if sections.get("header") else {},
+ "selfcheck": sections.get("selfcheck", []),
+ "windows": sections.get("windows", []),
+ "actions": sections.get("actions", []),
+ "cells": cells,
+ "samples": sections.get("samples", []),
+ "surfaces": sections.get("surfaces", []),
+ "crashes": sections.get("crashes", []),
+ "arms": [],
+ "unknown_rows": unknown,
+ "footer": None,
+ "excluded_cells": excluded_from_rows(records),
+ }
+ if not payload["complete"]:
+ payload["incomplete_note"] = (
+ "no run_meta row, or no cell completed. Everything that WAS measured is reported; "
+ "nothing that was not is invented"
+ )
+ if validate:
+ validate_payload(payload)
+ return payload
+
+
+def excluded_from_rows(records: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
+ """Derive `excluded_cells` from the harness rows that describe an exclusion.
+
+ Three row shapes mean a cell does not enter scoring, and all three have been seen to vanish
+ from a report by simply not being looked for: a cell that did not complete, a failed gate,
+ and an action that ran but whose own assertion said it did not do what it claimed.
+ """
+
+ out: list[dict[str, Any]] = []
+ for row in records:
+ row_type = row.get("row_type")
+ if row_type == "cell" and row.get("completed") is False:
+ out.append(
+ {
+ "cell_id": row.get("cell_id", "unknown"),
+ "reason": "rung_incomplete",
+ "count": 1,
+ "detail": str(
+ row.get("failure_mode") or row.get("reason") or "cell did not complete"
+ ),
+ }
+ )
+ elif row_type == "gate" and row.get("passed") is False:
+ out.append(
+ {
+ "cell_id": row.get("cell_id") or "run",
+ "reason": "selfcheck_failed",
+ "count": 1,
+ "detail": f"gate {row.get('name')}: {row.get('detail')}",
+ }
+ )
+ elif row_type == "action" and row.get("ran") is True and row.get("expect_ok") is False:
+ out.append(
+ {
+ "cell_id": row.get("cell_id", "unknown"),
+ "reason": "slot_missed",
+ "count": 1,
+ "detail": (
+ f"action {row.get('action')} ran but its own assertion failed: "
+ f"{row.get('reason')}. Its timings exist and must not be quoted"
+ ),
+ }
+ )
+ elif row_type == "failure":
+ out.append(
+ {
+ "cell_id": row.get("cell_id") or "run",
+ "reason": "renderer_crash",
+ "count": 1,
+ "detail": f"{row.get('kind')}: {row.get('detail')}",
+ }
+ )
+ return out
+
+
+def iter_windows(payload: Mapping[str, Any]) -> Iterator[dict[str, Any]]:
+ for window in payload.get("windows", []):
+ yield window
+
+
+def excluded_totals(payload: Mapping[str, Any]) -> dict[str, int]:
+ """Per-reason totals for the excluded-cells block. Always rendered, even when empty."""
+
+ totals: dict[str, int] = {}
+ for cell in payload.get("excluded_cells", []):
+ reason = cell.get("reason", "unknown")
+ totals[reason] = totals.get(reason, 0) + int(cell.get("count", 1))
+ return totals
+
+
+def write_excluded(writer: PayloadWriter, cells: Iterable[ExcludedCell]) -> int:
+ written = 0
+ for cell in cells:
+ writer.write("excluded", **cell.to_json())
+ written += 1
+ return written
diff --git a/tests/studio/studiobench/report/render.py b/tests/studio/studiobench/report/render.py
new file mode 100644
index 00000000000..7afb3492f70
--- /dev/null
+++ b/tests/studio/studiobench/report/render.py
@@ -0,0 +1,363 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Rendering: the rules about what may and may not be printed next to what.
+
+This module is where the report's editorial policy lives, and it is enforced in code rather than
+left to whoever writes the next summary:
+
+ * THE HEADLINE FOR HUMANS IS THE ONSET RUNG. The largest thread size still usable on this
+ machine. It is printed first, in plain words, because it is the only number that survives
+ being carried to a different laptop. The aggregate score is printed under it, labelled as
+ machine-local.
+ * NO SINGLE FRAME SUMMARY MAY BE A HEADLINE. `time_in_jank_pct` and `jank_index` catch opposite
+ failure shapes; quoting either alone is how a build with one three-second freeze gets called
+ smooth. `render_frame_health()` always prints all three, and `assert_headline_pair()` fails
+ a caller that tries to quote one.
+ * CEILING SHIFTS ARE NEVER FOLDED INTO THE SCALAR. Moving the onset rung is a different kind of
+ win from shaving 8% off every metric, and a single number that mixes them describes neither.
+ * `excluded_cells` IS ALWAYS RENDERED, INCLUDING WHEN EMPTY. An empty block is the claim "we
+ dropped nothing"; a missing block is a question nobody asked.
+ * THE HARNESS-BIAS CELL IS PRINTED AT THE TOP AND NEVER SUBTRACTED. Knowing the instrument
+ costs 4% is information; quietly removing 4% from every number is a second, unvalidated
+ measurement pretending to be a correction.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Iterable, Mapping, Sequence
+
+from ..scoring.ab import AbResult
+from ..scoring.anchors import METRIC_BY_KEY
+from ..scoring.frames import FrameStats
+from ..scoring.schema import Measure
+from ..scoring.score import LadderScore, RungScore
+from .payload import excluded_totals
+
+#: The three frame numbers that must appear together or not at all.
+HEADLINE_FRAME_METRICS = ("time_in_jank_pct", "jank_index", "max_frame_ms")
+
+
+class HeadlinePolicyError(AssertionError):
+ """Raised when a caller tries to quote one frame summary as the headline."""
+
+
+def assert_headline_pair(keys: Iterable[str]) -> None:
+ """Refuse a headline that quotes one frame summary without its counterpart.
+
+ `time_in_jank_pct` answers "was it bad most of the time" and `jank_index` plus `max_frame_ms`
+ answer "was it catastrophic once". A build can be terrible by either route while looking fine
+ by the other, so a headline containing one and not the others is not a summary, it is a
+ selection.
+ """
+
+ chosen = {k for k in keys if k in HEADLINE_FRAME_METRICS}
+ if chosen and chosen != set(HEADLINE_FRAME_METRICS):
+ missing = sorted(set(HEADLINE_FRAME_METRICS) - chosen)
+ raise HeadlinePolicyError(
+ "a frame headline must quote "
+ + ", ".join(HEADLINE_FRAME_METRICS)
+ + f"; missing {', '.join(missing)}"
+ )
+
+
+def render_frame_health(stats: FrameStats, *, indent: str = "") -> str:
+ """All three frame headlines plus the histogram pointer. Never one of them alone."""
+
+ lines = [
+ f"{indent}frames {stats.frames_total} over {stats.window_ms:.0f} ms "
+ f"(budget {stats.budget_ms:.2f} ms, {stats.refresh_source})",
+ f"{indent}time in jank {stats.time_in_jank_pct.display()} "
+ "(wall time inside frames over 100 ms)",
+ f"{indent}jank index {stats.jank_index.display()} "
+ "(sum of squared over-budget ms per ms of window)",
+ f"{indent}worst frame {stats.max_frame_ms.display()}",
+ f"{indent}p50 / p95 / p99 {stats.p50_frame_ms.display()} / "
+ f"{stats.p95_frame_ms.display()} / {stats.p99_frame_ms.display()}",
+ ]
+ if stats.no_frames_recorded:
+ lines.append(
+ f"{indent}NOTE: the frame recorder produced no frames. That is not zero jank, it is "
+ "no measurement: an unscheduled rAF loop reads exactly like a perfectly smooth page."
+ )
+ lines.append(f"{indent}histogram {len(stats.histogram)} buckets, in the payload")
+ return "\n".join(lines)
+
+
+def render_headline(ladder: LadderScore) -> str:
+ """The onset rung, in words, followed by the machine-local scalar."""
+
+ lines: list[str] = []
+ if ladder.onset_rung_tokens is None:
+ lines.append("ONSET RUNG: none. This build is not usable at any measured thread size.")
+ else:
+ lines.append(
+ f"ONSET RUNG: usable up to {ladder.onset_rung_tokens:,} tokens of thread content."
+ )
+ lines.append(f" {ladder.onset_reason}")
+ if ladder.non_monotonic:
+ lines.append(
+ " WARNING: usability is not monotone in thread size on this run. A smaller rung "
+ "failed while a larger one passed, which thread size cannot cause. Something else "
+ "moved (thermal throttling, another process, an unstable machine) and the onset rung "
+ "should not be quoted from this run alone."
+ )
+ lines.append("")
+ lines.append(
+ f" aggregate score {ladder.aggregate:.1f}/100 (machine-local; does not travel between "
+ "machines, unlike the onset rung above)"
+ )
+ lines.append(f" weights {ladder.weights_id} ladder {ladder.rung_ladder_id}")
+ return "\n".join(lines)
+
+
+def render_rung_table(ladder: LadderScore) -> str:
+ header = f"{'tokens':>10} {'score':>6} {'weight':>6} {'usable':>6} status"
+ rows = [header, "-" * len(header)]
+ for rung, weight in zip(ladder.rungs, ladder.rung_weights):
+ status = "complete"
+ if not rung.complete:
+ status = f"INCOMPLETE: {rung.incomplete_reason}"
+ elif rung.zeroed_by:
+ status = "zeroed by " + ", ".join(rung.zeroed_by)
+ rows.append(
+ f"{rung.tokens:>10,} {rung.score:>6.1f} {weight:>6.3f} "
+ f"{'yes' if rung.usable else 'no':>6} {status}"
+ )
+ rows.append("")
+ rows.append(
+ "An incomplete rung scores 0 and keeps its weight. It is not dropped: dropping it is how "
+ "a build that crashes at 500K outscores one that limps through."
+ )
+ rows.append(
+ "Weights are the trapezoid widths on the log(tokens) axis, so two rungs close together "
+ "in log space SHARE the weight of that region rather than each getting a full share. "
+ "That is why the top rung is not the whole score, and why 500K and 1M together weigh "
+ "about what one decade-spaced rung does."
+ )
+ return "\n".join(rows)
+
+
+def render_rung_metrics(rung: RungScore, *, indent: str = " ") -> str:
+ lines = [f"{indent}{rung.tokens:,} tokens -- score {rung.score:.1f}"]
+ if not rung.complete:
+ # Printing six "not attempted" lines for a rung that never ran buries the one fact that
+ # matters, which is why it did not run.
+ lines.append(f"{indent} INCOMPLETE: {rung.incomplete_reason}")
+ lines.append(
+ f"{indent} scores 0 and keeps its weight; no metric was measured at this rung"
+ )
+ return "\n".join(lines)
+ for metric in rung.metric_scores:
+ anchor = METRIC_BY_KEY.get(metric.key)
+ anchor_text = f"[{anchor.good:g} -> 100, {anchor.bad:g} -> 0]" if anchor is not None else ""
+ if metric.scored:
+ lines.append(
+ f"{indent} {metric.key:<20} {metric.measure.display():>28} "
+ f"score {float(metric.score):5.1f} {anchor_text}"
+ )
+ else:
+ lines.append(f"{indent} {metric.key:<20} {'NOT SCORED':>28} {metric.reason}")
+ return "\n".join(lines)
+
+
+def render_excluded(payload: Mapping[str, Any]) -> str:
+ """Always printed. An empty block is a claim, an absent block is a hole."""
+
+ cells = payload.get("excluded_cells")
+ if cells is None:
+ raise AssertionError("excluded_cells is mandatory and must not be null")
+ lines = ["EXCLUDED CELLS"]
+ if not cells:
+ lines.append(" none. Every cell that was measured is in the numbers above.")
+ return "\n".join(lines)
+ totals = excluded_totals(payload)
+ for reason, count in sorted(totals.items(), key = lambda kv: (-kv[1], kv[0])):
+ lines.append(f" {count:>4} {reason}")
+ lines.append("")
+ for cell in cells:
+ detail = f" -- {cell['detail']}" if cell.get("detail") else ""
+ lines.append(f" {cell['cell_id']}: {cell['reason']} x{cell.get('count', 1)}{detail}")
+ return "\n".join(lines)
+
+
+def render_harness_bias(bias: Mapping[str, Any] | None) -> str:
+ """The cost of the harness itself, printed at the top, never subtracted."""
+
+ lines = ["HARNESS BIAS (dist-shipping vs dist-armed at control)"]
+ if not bias:
+ lines.append(
+ " not measured on this run. Every number below therefore includes an unknown "
+ "amount of instrument cost."
+ )
+ return "\n".join(lines)
+ for key, value in bias.items():
+ rendered = value.display() if isinstance(value, Measure) else str(value)
+ lines.append(f" {key:<24} {rendered}")
+ lines.append(
+ " This is NOT subtracted from anything below. Knowing the instrument costs 4% is "
+ "information; removing 4% everywhere is a second unvalidated measurement."
+ )
+ return "\n".join(lines)
+
+
+def render_ab_table(result: AbResult) -> str:
+ """The A/B table, or the reason there is no A/B table.
+
+ A void result prints its reason and no numbers at all. Printing a table with a warning above
+ it does not work: the table gets screenshotted and the warning does not.
+ """
+
+ title = f"A/B: {result.label}"
+ if result.is_null_control:
+ title += " (NULL-TREATMENT CONTROL, base vs base)"
+ lines = [title, "=" * len(title)]
+
+ if result.void:
+ lines.append("")
+ lines.append("VOID. No numbers are quotable from this comparison.")
+ lines.append(f" {result.void_reason}")
+ # The paragraph under the reason explains the NULL CONTROL, and printing it under an
+ # incomplete plan named the wrong cause for the void. A void has more than one cause; the
+ # reason line carries which one, and only a null control gets the null-control paragraph.
+ if result.is_null_control:
+ lines.append(
+ " The null-treatment control measures whether this machine can currently tell "
+ "two identical builds apart. When it cannot, nothing measured alongside it can "
+ "be believed, so nothing is printed."
+ )
+ else:
+ lines.append(
+ " A comparison is all of its pairs. A cell that did not complete takes its "
+ "healthy partner out of the table with it, so the pairs that remain are a "
+ "selection and no verdict is printed over them."
+ )
+ return "\n".join(lines)
+
+ lines.append(f"noise floor {result.noise_floor_pct:.2f}% ({result.noise_floor_source})")
+ lines.append("")
+ header = f"{'metric':<20} {'pairs':>5} {'ratio':>7} {'range':>17} {'ci95':>17} verdict"
+ lines.append(header)
+ lines.append("-" * len(header))
+ for metric in result.metrics:
+ if metric.ratio_geomean is None:
+ lines.append(
+ f"{metric.metric_key:<20} {metric.n_pairs:>5} "
+ f"{'--':>7} {'--':>17} {'--':>17} no reading"
+ )
+ continue
+ rng = f"{metric.ratio_min:.3f}-{metric.ratio_max:.3f}"
+ ci = (
+ f"{metric.ci_low:.3f}-{metric.ci_high:.3f}"
+ if metric.ci_low is not None
+ else "too few pairs"
+ )
+ # A BOUND IS NOT A MEASUREMENT. An arm under its instrument floor contributes the floor,
+ # so the ratio understates the true magnitude and must not be quoted as a point estimate.
+ # Marked in the ratio cell rather than footnoted, for the reason the void path gives: the
+ # table gets screenshotted and the note does not.
+ ratio_cell = (
+ f">={metric.ratio_geomean:.3f}"
+ if metric.bounded and metric.ratio_geomean >= 1.0
+ else f"<={metric.ratio_geomean:.3f}"
+ if metric.bounded
+ else f"{metric.ratio_geomean:.3f}"
+ )
+ lines.append(
+ f"{metric.metric_key:<20} {metric.n_pairs:>5} {ratio_cell:>7} "
+ f"{rng:>17} {ci:>17} {metric.verdict}"
+ )
+ lines.append("")
+ if result.headline_ratio is not None:
+ direction = "faster" if result.headline_ratio < 1.0 else "slower"
+ lines.append(
+ f"headline ratio {result.headline_ratio:.3f} "
+ f"({abs(1.0 - result.headline_ratio) * 100:.1f}% {direction}, weighted)"
+ )
+ lines.append(f"VERDICT: {result.verdict}")
+ if result.regressions:
+ lines.append("")
+ lines.append(
+ "FAIL. A per-metric regression beyond the noise floor is a fail regardless of the "
+ "headline:"
+ )
+ for regression in result.regressions:
+ lines.append(f" {regression}")
+ lines.append("")
+ lines.append(
+ "Ratios are paired within one session and interleaved. Ceiling shifts (the onset rung "
+ "moving) are reported separately and are not in this table."
+ )
+ return "\n".join(lines)
+
+
+def render_ceiling_shift(base: LadderScore, treatment: LadderScore) -> str:
+ """Ceiling shift, reported on its own and never folded into the scalar."""
+
+ lines = ["CEILING SHIFT (reported separately, never folded into the score)"]
+ base_onset = base.onset_rung_tokens
+ treat_onset = treatment.onset_rung_tokens
+ lines.append(
+ f" base onset rung {base_onset:,} tokens"
+ if base_onset
+ else " base onset rung none"
+ )
+ lines.append(
+ f" treatment onset rung {treat_onset:,} tokens"
+ if treat_onset
+ else " treatment onset rung none"
+ )
+ if base_onset and treat_onset:
+ if treat_onset > base_onset:
+ lines.append(f" the ceiling MOVED UP: {base_onset:,} -> {treat_onset:,}")
+ elif treat_onset < base_onset:
+ lines.append(f" the ceiling MOVED DOWN: {base_onset:,} -> {treat_onset:,}")
+ else:
+ lines.append(" the ceiling did not move")
+ return "\n".join(lines)
+
+
+def render_summary(
+ payload: Mapping[str, Any],
+ ladder: LadderScore | None = None,
+ *,
+ harness_bias: Mapping[str, Any] | None = None,
+ frame_stats_by_rung: Mapping[int, FrameStats] | None = None,
+ extra_sections: Sequence[str] = (),
+) -> str:
+ """Assemble the human-facing summary in the order the policy above demands."""
+
+ sections: list[str] = []
+ sections.append("studiobench summary\n===================")
+
+ if not payload.get("complete", False):
+ sections.append(
+ "RUN DID NOT FINISH. "
+ + str(payload.get("incomplete_note", "no footer record was written."))
+ )
+ crashes = payload.get("crashes") or []
+ for crash in crashes:
+ sections.append(
+ f" crash: {crash.get('where', 'unknown')} "
+ f"{crash.get('error_type', '')} {crash.get('error', '')}".rstrip()
+ )
+
+ sections.append(render_harness_bias(harness_bias))
+
+ if ladder is not None:
+ sections.append(render_headline(ladder))
+ sections.append(render_rung_table(ladder))
+ sections.append(
+ "PER-RUNG METRICS\n" + "\n".join(render_rung_metrics(rung) for rung in ladder.rungs)
+ )
+
+ if frame_stats_by_rung:
+ blocks = ["FRAME HEALTH"]
+ for tokens in sorted(frame_stats_by_rung):
+ blocks.append(f" {tokens:,} tokens")
+ blocks.append(render_frame_health(frame_stats_by_rung[tokens], indent = " "))
+ sections.append("\n".join(blocks))
+
+ sections.extend(extra_sections)
+ sections.append(render_excluded(payload))
+ return "\n\n".join(sections) + "\n"
diff --git a/tests/studio/studiobench/report/selftest/test_studiobench_ab_report_resume.py b/tests/studio/studiobench/report/selftest/test_studiobench_ab_report_resume.py
new file mode 100644
index 00000000000..e0084938f45
--- /dev/null
+++ b/tests/studio/studiobench/report/selftest/test_studiobench_ab_report_resume.py
@@ -0,0 +1,103 @@
+# 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 resumed A/B that ran nothing may not destroy the table the run that measured wrote.
+
+`--resume` against a finished output is a SUCCESS on purpose: every cell is found rather than
+run and the command exits 0 without paying for the measurement twice. But the A/B ratio is scoped
+to one session, and a resumed run has a new session id, so re-rendering `ab.md` at the end of a
+run that measured nothing replaced a real verdict with NO READING -- and exited 0 while doing it,
+so nothing pointed at the loss.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.__main__ import _render_ab # noqa: E402
+from studiobench.runtime.types import Paths # noqa: E402
+
+MEASURED = "s-measured"
+RESUMED = "s-resumed"
+
+SIDES = [
+ {"label": "base", "ref": "main", "base_url": "http://127.0.0.1:5401", "owns": True},
+ {"label": "treatment", "ref": "fix", "base_url": "http://127.0.0.1:5402", "owns": True},
+]
+
+
+def _cell(cell_id, arm, session):
+ return {
+ "row_type": "cell",
+ "cell_id": cell_id,
+ "session_id": session,
+ "target_tokens": 10_000,
+ "completed": True,
+ "cell": {"arm": arm, "rep": 0},
+ }
+
+
+def _keystroke(cell_id, session, p95):
+ return {
+ "row_type": "action",
+ "cell_id": cell_id,
+ "session_id": session,
+ "action": "keystroke",
+ "ran": True,
+ "expect_ok": True,
+ "timings": {"p95_ms": p95},
+ }
+
+
+def _payload(out: Path, session: str) -> Paths:
+ paths = Paths.under(out)
+ rows = [
+ _cell("r10K.base.rep0", "base", session),
+ _keystroke("r10K.base.rep0", session, 100.0),
+ _cell("r10K.treatment.rep0", "treatment", session),
+ _keystroke("r10K.treatment.rep0", session, 50.0),
+ ]
+ paths.payload_jsonl.parent.mkdir(parents = True, exist_ok = True)
+ paths.payload_jsonl.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding = "utf-8")
+ return paths
+
+
+def test_a_fully_resumed_ab_keeps_the_table_the_measured_run_wrote(tmp_path):
+ paths = _payload(tmp_path / "run", MEASURED)
+
+ _render_ab(paths, SIDES, MEASURED, "c0ffee")
+ measured = (paths.out / "ab.md").read_text(encoding = "utf-8")
+ assert "IMPROVED" in measured
+
+ # The resumed run: same output directory, new session id, not one cell of its own.
+ _render_ab(paths, SIDES, RESUMED, "c0ffee")
+ assert (paths.out / "ab.md").read_text(encoding = "utf-8") == measured
+
+
+def test_a_run_that_measured_still_rewrites_the_table(tmp_path):
+ """The control: refusing to overwrite must not turn into refusing to report."""
+
+ paths = _payload(tmp_path / "run", MEASURED)
+ (paths.out / "ab.md").write_text("stale table from an older run\n", encoding = "utf-8")
+
+ _render_ab(paths, SIDES, MEASURED, "c0ffee")
+ text = (paths.out / "ab.md").read_text(encoding = "utf-8")
+ assert "stale table" not in text
+ assert "IMPROVED" in text
+
+
+def test_a_first_run_with_no_readings_still_gets_a_table(tmp_path):
+ """The other control: with no prior report there is nothing to preserve, so render."""
+
+ paths = _payload(tmp_path / "run", MEASURED)
+ _render_ab(paths, SIDES, RESUMED, "c0ffee")
+ assert "NO READING" in (paths.out / "ab.md").read_text(encoding = "utf-8")
+
+
+if __name__ == "__main__":
+ import pytest
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/report/selftest/test_studiobench_cli_contracts.py b/tests/studio/studiobench/report/selftest/test_studiobench_cli_contracts.py
new file mode 100644
index 00000000000..faa599899d9
--- /dev/null
+++ b/tests/studio/studiobench/report/selftest/test_studiobench_cli_contracts.py
@@ -0,0 +1,450 @@
+# 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 CLI decisions that decide what a run MEANS, taken out of the driver so they can be asserted.
+
+Each of these was a one-line condition whose failure was silent:
+
+ a null control that read as an ordinary A/B, because the two identical builds it had just
+ installed were on different ports;
+
+ two A/B sides installing into one home, so the treatment overwrote the base while the base was
+ running and both arms measured the same binaries;
+
+ a doctor that reported PASS with no browser engine downloaded, which is what `pip install
+ playwright` alone leaves behind;
+
+ a report scoring a standard payload against the DEFAULT tier's shorter ladder, so a rung the run
+ promised and never reached was dropped instead of scored INCOMPLETE.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.__main__ import ( # noqa: E402
+ completion_exit_code,
+ engines_installed,
+ _ab_label,
+ is_null_control,
+ main,
+ parse_args,
+ planned_rungs,
+ recorded_ladder,
+ side_home,
+ side_specs,
+)
+
+
+def _side(
+ label,
+ ref,
+ url,
+ owns,
+ commit = None,
+):
+ side = {"label": label, "ref": ref, "base_url": url, "owns": owns}
+ if commit is not None:
+ side["commit"] = commit
+ return side
+
+
+# ── the null control ────────────────────────────────────────────────────────────────────────
+
+
+def test_two_self_installed_copies_of_one_ref_are_a_null_control():
+ """`--branch main --ab main`: same build, two ports, and it is the calibration run."""
+
+ sides = [
+ _side("base", "main", "http://127.0.0.1:5399", True),
+ _side("treatment", "main", "http://127.0.0.1:5400", True),
+ ]
+ assert is_null_control(sides) is True
+
+
+def test_two_refs_are_never_a_null_control():
+ sides = [
+ _side("base", "main", "http://127.0.0.1:5399", True),
+ _side("treatment", "pr-9296", "http://127.0.0.1:5400", True),
+ ]
+ assert is_null_control(sides) is False
+
+
+def test_two_attached_studios_at_different_urls_are_not_a_null_control():
+ """Nothing here can see what is deployed at either URL, so equal refs prove nothing."""
+
+ sides = [
+ _side("base", "main", "http://127.0.0.1:5401", False),
+ _side("treatment", "main", "http://127.0.0.1:5402", False),
+ ]
+ assert is_null_control(sides) is False
+
+
+def test_one_attached_studio_driven_twice_is_a_null_control():
+ sides = [
+ _side("base", "main", "http://127.0.0.1:5401", False),
+ _side("treatment", "main", "http://127.0.0.1:5401", False),
+ ]
+ assert is_null_control(sides) is True
+
+
+def test_one_attached_studio_driven_twice_under_two_labels_is_still_a_null_control():
+ """`--attach U --attach-b U --branch main --ab fix`: one server, two names it cannot check.
+
+ The URL rule was stated and then not applied -- the ref comparison ran first, so the unequal
+ labels returned False before the equal URL was reached. One Studio measured against itself was
+ rendered as an ordinary A/B, free to publish temporal noise as an improvement, with
+ `noise_floor_from_null_control` skipped so nothing downstream had a floor to refuse it with.
+ With `--attach` the refs are free-form strings; only the URL names the deployed build.
+ """
+
+ sides = [
+ _side("base", "main", "http://127.0.0.1:5401", False),
+ _side("treatment", "fix", "http://127.0.0.1:5401", False),
+ ]
+ assert is_null_control(sides) is True
+
+
+def test_an_attached_treatment_pointed_at_the_installed_base_is_a_null_control():
+ """The mixed form of the same thing: `--attach-b` naming the Studio this run just launched."""
+
+ sides = [
+ _side("base", "main", "http://127.0.0.1:5399", True, commit = "a" * 40),
+ _side("treatment", "fix", "http://127.0.0.1:5399", False),
+ ]
+ assert is_null_control(sides) is True
+
+
+def test_two_owned_installs_of_different_refs_are_still_an_ordinary_ab():
+ """The control for the reorder: owned sides get `port` and `port + 1`, so they never collide
+ on a URL and the ref and commit comparisons below still decide them."""
+
+ sides = [
+ _side("base", "main", "http://127.0.0.1:5399", True, commit = "a" * 40),
+ _side("treatment", "fix", "http://127.0.0.1:5400", True, commit = "b" * 40),
+ ]
+ assert is_null_control(sides) is False
+
+
+def test_a_ref_that_moved_between_the_two_installs_is_not_a_null_control():
+ """`--branch main --ab main` where `main` advanced during the base's install.
+
+ The two sides are cloned into separate repos and fetched one after the other, with a whole
+ clone, build and launch between them. The refs still match; the builds do not. Classified as a
+ null control, `compare` voids the run and empties `regressions`, and
+ `noise_floor_from_null_control` republishes the real delta as this machine's noise floor -- so
+ a 12% regression is erased AND becomes the floor every later A/B on that machine is judged
+ against.
+ """
+
+ sides = [
+ _side("base", "main", "http://127.0.0.1:5399", True, commit = "a" * 40),
+ _side("treatment", "main", "http://127.0.0.1:5400", True, commit = "b" * 40),
+ ]
+ assert is_null_control(sides) is False
+
+
+def test_two_installs_of_one_ref_that_resolved_to_one_commit_are_a_null_control():
+ """The control: the calibration run this tool exists to support still classifies."""
+
+ sides = [
+ _side("base", "main", "http://127.0.0.1:5399", True, commit = "a" * 40),
+ _side("treatment", "main", "http://127.0.0.1:5400", True, commit = "a" * 40),
+ ]
+ assert is_null_control(sides) is True
+
+
+def test_a_side_with_no_commit_to_declare_is_judged_as_before():
+ """An empty commit on either side is not a difference -- the rule `commit_problems` already
+ states. Nothing behind an attached URL declares a commit, and neither does a payload written
+ before commits were recorded, so the build check must not start refusing them."""
+
+ sides = [
+ _side("base", "main", "http://127.0.0.1:5399", True, commit = "a" * 40),
+ _side("treatment", "main", "http://127.0.0.1:5400", True, commit = ""),
+ ]
+ assert is_null_control(sides) is True
+
+
+def test_the_table_names_both_builds_when_one_ref_resolved_to_two():
+ """ "main -> main" over two different commits would read as a null control on a screenshot."""
+
+ sides = [
+ _side("base", "main", "http://127.0.0.1:5399", True, commit = "a" * 40),
+ _side("treatment", "main", "http://127.0.0.1:5400", True, commit = "b" * 40),
+ ]
+ label = _ab_label(sides, is_null_control(sides))
+ assert label == "main aaaaaaaaaaaa -> bbbbbbbbbbbb"
+
+
+def test_a_null_control_states_the_commit_it_compared_with_itself():
+ sides = [
+ _side("base", "main", "http://127.0.0.1:5399", True, commit = "a" * 40),
+ _side("treatment", "main", "http://127.0.0.1:5400", True, commit = "a" * 40),
+ ]
+ assert _ab_label(sides, True) == "null control: main @ aaaaaaaaaaaa vs itself"
+
+
+# ── one password per side ───────────────────────────────────────────────────────────────────
+
+
+def test_each_attached_side_authenticates_with_its_own_password():
+ args = parse_args(
+ [
+ "--attach",
+ "http://127.0.0.1:5401",
+ "--password",
+ "base-secret",
+ "--ab",
+ "pr",
+ "--attach-b",
+ "http://127.0.0.1:5402",
+ "--password-b",
+ "treatment-secret",
+ ]
+ )
+ specs = side_specs(args, "pr")
+ assert [s[0] for s in specs] == ["base", "treatment"]
+ assert specs[0][2] == "http://127.0.0.1:5401" and specs[0][4] == "base-secret"
+ assert specs[1][2] == "http://127.0.0.1:5402" and specs[1][4] == "treatment-secret"
+
+
+def test_the_treatment_falls_back_to_the_one_password():
+ args = parse_args(
+ ["--attach", "http://a", "--password", "one", "--ab", "pr", "--attach-b", "http://b"]
+ )
+ assert side_specs(args, "pr")[1][4] == "one"
+
+
+def test_without_ab_there_is_one_side():
+ args = parse_args(["--attach", "http://a", "--password", "one"])
+ assert len(side_specs(args, None)) == 1
+
+
+# ── one home per side ───────────────────────────────────────────────────────────────────────
+
+
+def test_ab_sides_never_share_an_explicit_home():
+ base = side_home("/tmp/home", "/out", "base", ab = True)
+ treatment = side_home("/tmp/home", "/out", "treatment", ab = True)
+ assert base != treatment
+ assert base == Path("/tmp/home/base")
+
+
+def test_a_single_side_still_installs_where_it_was_told():
+ assert side_home("/tmp/home", "/out", "base", ab = False) == Path("/tmp/home")
+
+
+def test_without_home_each_side_lands_under_the_output_directory():
+ assert side_home(None, "/out", "treatment", ab = True) == Path("/out/studio_home_treatment")
+
+
+# ── the doctor ──────────────────────────────────────────────────────────────────────────────
+
+
+def test_an_engine_with_a_note_is_not_installed():
+ assert engines_installed("chromium, webkit (not installed), firefox (unavailable)") == [
+ "chromium"
+ ]
+ assert (
+ engines_installed(
+ "chromium (not installed), webkit (not installed), firefox (not installed)"
+ )
+ == []
+ )
+ assert engines_installed("chromium, webkit, firefox") == ["chromium", "webkit", "firefox"]
+
+
+# ── the exit status ─────────────────────────────────────────────────────────────────────────
+
+
+def test_a_fully_resumed_run_is_a_success():
+ """Every cell was already complete, so the requested output exists. Exit 0."""
+
+ assert completion_exit_code([], resumed = 4) == 0
+
+
+def test_a_run_that_did_nothing_at_all_is_still_a_failure():
+ assert completion_exit_code([], resumed = 0) == 1
+
+
+def test_one_failed_cell_fails_the_run():
+ assert completion_exit_code([{"completed": True}, {"completed": False}], resumed = 2) == 1
+ assert completion_exit_code([{"completed": True}], resumed = 0) == 0
+
+
+# ── the report ladder ───────────────────────────────────────────────────────────────────────
+
+
+def _rows(
+ rungs,
+ cells,
+ session = "s1",
+):
+ rows = [
+ {
+ "row_type": "run_meta",
+ "tier": "standard",
+ "rungs": rungs,
+ "session_id": session,
+ "corpus_hash": "c0ffee",
+ }
+ ]
+ for tokens in cells:
+ rows.append(
+ {
+ "row_type": "cell",
+ "cell_id": f"r{tokens}",
+ "session_id": session,
+ "target_tokens": tokens,
+ "completed": True,
+ "cell": {"arm": "A0", "rep": 0},
+ }
+ )
+ rows.append(
+ {
+ "row_type": "action",
+ "cell_id": f"r{tokens}",
+ "session_id": session,
+ "action": "keystroke",
+ "ran": True,
+ "expect_ok": True,
+ "timings": {"p95_ms": 20.0},
+ }
+ )
+ return rows
+
+
+def _write(path, rows):
+ path.write_text("\n".join(json.dumps(r) for r in rows) + "\n", encoding = "utf-8")
+ return path
+
+
+def _payload(tmp_path, rungs, cells):
+ return _write(tmp_path / "payload.jsonl", _rows(rungs, cells))
+
+
+def _resumed_payload(tmp_path, first, then, cells):
+ """One payload, two sessions: a run that promised `first`, and the `--resume` that promised
+ `then`. A resume APPENDS its own `run_meta`, which is how a longer ladder gets into a file that
+ already has one -- `rungs` is deliberately not a payload identity axis precisely so it can."""
+
+ return _write(tmp_path / "payload.jsonl", _rows(first, cells) + _rows(then, [], session = "s2"))
+
+
+def test_the_recorded_ladder_is_read_back_from_the_payload(tmp_path):
+ path = _payload(tmp_path, ["1K", "10K", "100K"], [1_000, 10_000])
+ assert recorded_ladder(path) == ["1K", "10K", "100K"]
+
+
+def test_a_payload_without_a_run_meta_row_says_nothing(tmp_path):
+ path = tmp_path / "p.jsonl"
+ path.write_text('{"row_type":"cell","cell_id":"a"}\n', encoding = "utf-8")
+ assert recorded_ladder(path) == []
+
+
+def test_report_scores_the_rung_the_run_promised_and_never_reached(tmp_path, capsys):
+ """The standard run died before 100K. Reporting it must not quietly become a quick run."""
+
+ path = _payload(tmp_path, ["1K", "10K", "100K"], [1_000, 10_000])
+ assert main(["--report", str(path)]) == 0
+ summary = (tmp_path / "summary.md").read_text(encoding = "utf-8")
+ assert "100,000" in summary or "100000" in summary or "100K" in summary
+
+
+def test_a_rung_a_resume_added_is_still_owed_by_the_payload(tmp_path):
+ """1K completed, resumed with `--rungs 1K,10K`, killed after the new header and before the cell.
+
+ The ladder a payload owes is every rung any of its sessions promised. Reading the FIRST
+ `run_meta` alone declared only 1K, and a continuation that never reached its new top rung
+ scored COMPLETE -- the crash-beats-limp failure, arriving through the resume.
+ """
+
+ path = _resumed_payload(tmp_path, ["1K"], ["1K", "10K"], [1_000])
+ assert recorded_ladder(path) == ["1K", "10K"]
+
+
+def test_the_report_declares_the_rung_the_resume_promised_and_never_reached(tmp_path):
+ path = _resumed_payload(tmp_path, ["1K"], ["1K", "10K"], [1_000])
+ assert main(["--report", str(path)]) == 0
+ summary = (tmp_path / "summary.md").read_text(encoding = "utf-8")
+ assert "10,000" in summary
+ assert "INCOMPLETE" in summary
+
+
+def test_a_resume_that_promised_no_new_rung_reports_the_same_ladder(tmp_path):
+ """The control: folding the headers may not invent a rung out of an ordinary continuation."""
+
+ path = _resumed_payload(tmp_path, ["1K", "10K"], ["1K", "10K"], [1_000, 10_000])
+ assert recorded_ladder(path) == ["1K", "10K"]
+ assert main(["--report", str(path)]) == 0
+ assert "100,000" not in (tmp_path / "summary.md").read_text(encoding = "utf-8")
+
+
+def test_an_explicit_tier_still_wins(tmp_path):
+ path = _payload(tmp_path, ["1K", "10K", "100K"], [1_000, 10_000])
+ assert main(["--report", str(path), "--tier", "quick"]) == 0
+ summary = (tmp_path / "summary.md").read_text(encoding = "utf-8")
+ assert "100,000" not in summary and "100K" not in summary
+
+
+# ── --rungs is normalised and checked before anything is acquired ────────────────────────────
+
+
+def _rungs(value):
+ return planned_rungs(parse_args(["--tier", "standard", "--rungs", value]))
+
+
+def test_a_space_after_the_comma_is_the_same_ladder():
+ """`--rungs "1K, 10K"` used to split to `[\"1K\", \" 10K\"]`.
+
+ Not a late crash only: `run_meta` records the rungs the run PROMISED before `build_cells`
+ reaches `RUNGS[rung]`, and `recorded_ladder` folds every header, so a resume mistyped this way
+ left a rung nothing can satisfy in a payload that was complete.
+ """
+
+ assert _rungs("1K, 10K") == ["1K", "10K"]
+ assert _rungs(" 1K , 10K ") == ["1K", "10K"]
+
+
+def test_a_lowercase_suffix_is_the_same_ladder():
+ assert _rungs("1k,10k") == ["1K", "10K"]
+ assert _rungs("10k, 1m") == ["10K", "1M"]
+
+
+def test_an_empty_field_is_not_a_rung():
+ """A trailing or doubled comma is a typo, not a request for a nameless rung."""
+
+ assert _rungs("1K,,10K") == ["1K", "10K"]
+ assert _rungs("1K,10K,") == ["1K", "10K"]
+
+
+def test_a_label_that_is_not_a_rung_is_refused_by_name():
+ for value in ("1X", "2K", "1K,20K"):
+ with pytest.raises(SystemExit) as excinfo:
+ _rungs(value)
+ assert "is not a rung" in str(excinfo.value)
+
+
+def test_a_value_naming_no_rung_at_all_is_refused():
+ for value in (",", " "):
+ with pytest.raises(SystemExit) as excinfo:
+ _rungs(value)
+ assert "names nothing" in str(excinfo.value)
+
+
+def test_the_tier_still_supplies_the_ladder_when_rungs_is_not_given():
+ """The control: normalising the override may not disturb the default path."""
+
+ assert planned_rungs(parse_args(["--tier", "standard"])) == ["1K", "10K", "100K"]
+ assert planned_rungs(parse_args(["--tier", "fast"])) == ["100K"]
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/report/selftest/test_studiobench_liveness.py b/tests/studio/studiobench/report/selftest/test_studiobench_liveness.py
new file mode 100644
index 00000000000..6665a5cb1e1
--- /dev/null
+++ b/tests/studio/studiobench/report/selftest/test_studiobench_liveness.py
@@ -0,0 +1,287 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+"""`--assert-liveness` is the gate that catches an action which never fired reading as "no effect".
+
+A gate that cannot fail is worse than no gate, because it is quoted as evidence. So every test here
+that asserts a pass is paired with one that asserts the corresponding failure, and the empty-payload
+case is tested explicitly: a check that passes over zero rows is the same false negative wearing a
+different hat.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.__main__ import main # noqa: E402
+
+
+def write_payload(tmp_path: Path, rows: list[dict]) -> Path:
+ path = tmp_path / "payload.jsonl"
+ path.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding = "utf-8")
+ return path
+
+
+def cell(
+ actions: list[dict],
+ *,
+ completed: bool = True,
+ cell_id: str = "100K/rep0",
+) -> dict:
+ return {"row_type": "cell", "cell_id": cell_id, "completed": completed, "actions": actions}
+
+
+def ran(name: str, **extra) -> dict:
+ return {"action": name, "ran": True, **extra}
+
+
+def test_a_payload_where_everything_ran_passes(tmp_path):
+ path = write_payload(tmp_path, [cell([ran("keystroke"), ran("message_menu")])])
+ assert main(["--assert-liveness", str(path)]) == 0
+
+
+def test_an_action_that_did_not_run_fails(tmp_path):
+ path = write_payload(
+ tmp_path,
+ [
+ cell(
+ [
+ ran("keystroke"),
+ {"action": "message_menu", "ran": False, "reason": "slot closed"},
+ ]
+ )
+ ],
+ )
+ assert main(["--assert-liveness", str(path)]) == 1
+
+
+def test_a_missed_slot_fails_even_though_the_action_ran(tmp_path):
+ # `ran` and `slot_missed` are different failures: the second means the film moved on without
+ # it, so its timing describes a different session than every other arm's.
+ path = write_payload(tmp_path, [cell([ran("settings", slot_missed = True)])])
+ assert main(["--assert-liveness", str(path)]) == 1
+
+
+def test_an_incomplete_cell_fails(tmp_path):
+ path = write_payload(tmp_path, [cell([ran("keystroke")], completed = False)])
+ assert main(["--assert-liveness", str(path)]) == 1
+
+
+def test_an_empty_payload_is_refused_rather_than_passed(tmp_path):
+ # The whole point. Zero rows satisfies "no action failed" vacuously.
+ path = write_payload(tmp_path, [{"row_type": "header", "tool": "studiobench"}])
+ assert main(["--assert-liveness", str(path)]) == 2
+
+
+def test_a_missing_payload_is_refused(tmp_path):
+ assert main(["--assert-liveness", str(tmp_path / "nope.jsonl")]) == 2
+
+
+def test_allow_not_run_excuses_only_the_names_given(tmp_path):
+ rows = [
+ cell([{"action": "image_upload", "ran": False}, {"action": "message_menu", "ran": False}])
+ ]
+ path = write_payload(tmp_path, rows)
+ assert main(["--assert-liveness", str(path), "--allow-not-run", "image_upload"]) == 1
+ assert (
+ main(["--assert-liveness", str(path), "--allow-not-run", "image_upload,message_menu"]) == 0
+ )
+
+
+def test_non_cell_rows_are_ignored_but_do_not_count_as_cells(tmp_path):
+ path = write_payload(
+ tmp_path,
+ [
+ {"row_type": "window", "name": "stream:drain"},
+ {"row_type": "action", "action": "keystroke", "ran": False},
+ cell([ran("keystroke")]),
+ ],
+ )
+ # The stray top-level action row must not fail the run: actions are read from inside their
+ # cell, so counting them twice would make the gate depend on payload layout.
+ assert main(["--assert-liveness", str(path)]) == 0
+
+
[email protected]("blank", ["", " ", "\n"])
+def test_blank_lines_are_skipped(tmp_path, blank):
+ path = tmp_path / "payload.jsonl"
+ path.write_text(json.dumps(cell([ran("keystroke")])) + "\n" + blank + "\n", encoding = "utf-8")
+ assert main(["--assert-liveness", str(path)]) == 0
+
+
+# ── a cell that was re-run is judged on the run that finished it ─────
+
+
+NOW = "s-now"
+OLD = "s-before"
+
+
+def attempt(
+ session: str,
+ actions: list[dict],
+ *,
+ completed: bool,
+ cell_id: str = "100K/rep0",
+):
+ row = cell(actions, completed = completed, cell_id = cell_id)
+ row["session_id"] = session
+ return row
+
+
+def test_a_resumed_cell_is_not_failed_by_the_attempt_that_died(tmp_path):
+ """`--resume` appends, so both attempts at one `cell_id` are in the file forever.
+
+ The resumed run exits 0 and `--report` scores the retry. Read raw, this gate found the dead
+ attempt's `completed: false` and NOT RUN actions on every later invocation, so a payload that
+ had already been repaired could never pass again.
+ """
+
+ path = write_payload(
+ tmp_path,
+ [
+ attempt(
+ OLD, [{"action": "message_menu", "ran": False, "reason": "died"}], completed = False
+ ),
+ attempt(NOW, [ran("keystroke"), ran("message_menu")], completed = True),
+ ],
+ )
+ assert main(["--assert-liveness", str(path)]) == 0
+
+
+def test_the_superseded_attempt_does_not_count_as_a_second_cell(tmp_path):
+ """Not merely "does not fail": the dead attempt is not a cell this payload contains.
+
+ Counting it would make `--assert-liveness` report two cells where one ran, and the count is
+ the only thing standing between this gate and an empty payload passing vacuously.
+ """
+
+ rows = [
+ attempt(OLD, [{"action": "message_menu", "ran": False}], completed = False),
+ attempt(NOW, [ran("keystroke")], completed = True),
+ ]
+ path = write_payload(tmp_path, rows)
+ logged: list[str] = []
+ import studiobench.__main__ as m
+
+ real = m._log
+ m._log = lambda msg = "": (logged.append(str(msg)), real(msg))[1]
+ try:
+ assert main(["--assert-liveness", str(path)]) == 0
+ finally:
+ m._log = real
+ assert any("1 cell(s), 0 liveness problem(s)" in line for line in logged), logged
+
+
+# ── the controls: what must still fail ──────────────────────────────
+
+
+def test_a_cell_that_was_never_re_run_still_fails(tmp_path):
+ """A crash with no retry behind it is still a crash."""
+
+ path = write_payload(
+ tmp_path,
+ [attempt(OLD, [{"action": "message_menu", "ran": False}], completed = False)],
+ )
+ assert main(["--assert-liveness", str(path)]) == 1
+
+
+def test_the_latest_attempt_is_judged_on_its_own_failures(tmp_path):
+ """Superseding must not become excusing: a retry that itself died is the answer."""
+
+ path = write_payload(
+ tmp_path,
+ [
+ attempt(OLD, [ran("keystroke"), ran("message_menu")], completed = True),
+ attempt(
+ NOW,
+ [{"action": "message_menu", "ran": False, "reason": "died again"}],
+ completed = False,
+ ),
+ ],
+ )
+ assert main(["--assert-liveness", str(path)]) == 1
+
+
+def test_a_different_cell_in_an_earlier_session_is_not_superseded(tmp_path):
+ """Only a later attempt at the SAME cell id supersedes an earlier one.
+
+ A resumed run re-runs only the cells that died; every cell the first session completed stays
+ in the payload under its own id and must still be checked.
+ """
+
+ path = write_payload(
+ tmp_path,
+ [
+ attempt(
+ OLD, [{"action": "message_menu", "ran": False}], completed = True, cell_id = "10K/rep0"
+ ),
+ attempt(NOW, [ran("keystroke")], completed = True, cell_id = "100K/rep0"),
+ ],
+ )
+ assert main(["--assert-liveness", str(path)]) == 1
+
+
+def test_an_attempt_killed_before_its_cell_row_is_not_a_pass(tmp_path):
+ """A SIGKILL inside a cell must not delete that cell from the gate's answer.
+
+ `latest_attempt_rows` names the latest attempt from ANY attempt-keyed row, because the
+ Recorder flushes and fsyncs action and window rows while the terminal `cell` row is written in
+ a `finally` that a SIGKILL never reaches. The killed attempt therefore supersedes the recorded
+ one and contributes no cell row itself, so reading cell rows alone dropped the cell entirely:
+ a resume killed inside a cell whose first attempt had already recorded `completed: false` with
+ a NOT RUN action turned exit 1 into exit 0 while both facts were still in the file.
+ """
+
+ path = write_payload(
+ tmp_path,
+ [
+ attempt(
+ OLD,
+ [
+ ran("keystroke"),
+ {"action": "message_menu", "ran": False, "reason": "slot closed"},
+ ],
+ completed = False,
+ cell_id = "10K/rep0",
+ ),
+ attempt(OLD, [ran("keystroke")], completed = True, cell_id = "1K/rep0"),
+ # All the retry managed to flush before it was killed.
+ {
+ "row_type": "action",
+ "cell_id": "10K/rep0",
+ "session_id": NOW,
+ "action": "keystroke",
+ "ran": True,
+ },
+ {"row_type": "window", "cell_id": "10K/rep0", "session_id": NOW, "name": "stream"},
+ ],
+ )
+ assert main(["--assert-liveness", str(path)]) == 1
+
+
+def test_a_run_killed_during_a_later_cell_does_not_pass_on_its_earlier_ones(tmp_path):
+ """The same hole without a resume: the killed cell has no attempt behind it at all.
+
+ Earlier cells stay complete and live, so a gate that only reads cell rows reports them and
+ exits 0 over a run that stopped in the middle.
+ """
+
+ path = write_payload(
+ tmp_path,
+ [
+ attempt(NOW, [ran("keystroke")], completed = True, cell_id = "1K/rep0"),
+ {
+ "row_type": "action",
+ "cell_id": "10K/rep0",
+ "session_id": NOW,
+ "action": "keystroke",
+ "ran": True,
+ },
+ ],
+ )
+ assert main(["--assert-liveness", str(path)]) == 1
diff --git a/tests/studio/studiobench/report/selftest/test_studiobench_overhead_layoutcost.py b/tests/studio/studiobench/report/selftest/test_studiobench_overhead_layoutcost.py
new file mode 100644
index 00000000000..863572fb2e3
--- /dev/null
+++ b/tests/studio/studiobench/report/selftest/test_studiobench_overhead_layoutcost.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 overhead gate, and the layout-cost adapter that feeds it.
+
+Both exist to stop the same lie in two different places: an instrument reporting zero for
+something it never measured, and an instrument whose own cost grows with the treatment and
+therefore produces the slope everyone is hoping to find.
+"""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.arms.layoutcost import ( # noqa: E402
+ COUNTER_FAMILIES,
+ LAYOUTCOST_JS_PATH,
+ LayoutCostInstrument,
+ in_situ_overhead,
+ load_layoutcost_js,
+ reading_from_snapshot,
+)
+from studiobench.report.overhead import ( # noqa: E402
+ log_growth_slope,
+ overhead_growth_gate,
+ render_overhead_section,
+)
+from studiobench.scoring import Measure # noqa: E402
+
+
+# ---------------------------------------------------------------------------------------
+# the layout-cost adapter
+# ---------------------------------------------------------------------------------------
+
+
+def test_a_missing_snapshot_is_not_attempted_rather_than_zero():
+ reading = reading_from_snapshot(None)
+ assert set(reading.unavailable) == set(COUNTER_FAMILIES)
+ for name in COUNTER_FAMILIES:
+ assert reading.counters[name].attempted is False
+
+
+def test_a_patch_the_engine_refused_reads_as_not_attempted():
+ """A WebKit build that refuses the getter patch must not report zero forced layouts."""
+
+ reading = reading_from_snapshot(
+ {
+ "unavailable": ["scrollHeightReads"],
+ "counters": {"scrollHeightReads": 0, "moCallbacks": 0},
+ "attempted": {"scrollHeightReads": False, "moCallbacks": True},
+ }
+ )
+ refused = reading.counters["scrollHeightReads"]
+ assert refused.attempted is False
+ assert "could not be installed" in refused.display()
+ # a family that DID install and genuinely saw nothing keeps its honest zero
+ installed = reading.counters["moCallbacks"]
+ assert installed.attempted is True
+ assert installed.value == 0.0
+
+
+def test_the_self_cost_estimate_is_labelled_a_lower_bound():
+ reading = reading_from_snapshot(
+ {"counters": {}, "attempted": {}, "overheadMsPerCall": 0.001045}
+ )
+ assert reading.self_cost_ms_per_call.has_reading
+ assert "LOWER BOUND" in (reading.self_cost_ms_per_call.note or "")
+
+
+def test_the_paired_cell_is_what_produces_the_real_cost():
+ overhead = in_situ_overhead(Measure.read(48.0, "ms"), Measure.read(41.0, "ms"))
+ assert overhead.value == pytest.approx(7.0)
+
+
+def test_an_incomplete_pair_leaves_the_cost_unknown_not_zero():
+ overhead = in_situ_overhead(
+ Measure.read(48.0, "ms"), Measure.failed("ms", "the without cell crashed")
+ )
+ assert overhead.has_reading is False
+ assert "unknown rather than zero" in overhead.display()
+
+
+def test_the_instrument_declares_a_level_above_the_headline():
+ assert LayoutCostInstrument.level >= 1
+ assert LayoutCostInstrument.name == "layoutcost"
+
+
+def test_the_browser_half_exists_and_exposes_what_the_adapter_calls():
+ source = load_layoutcost_js()
+ assert LAYOUTCOST_JS_PATH.is_file()
+ for symbol in ("__sbLayoutCost", "snapshot", "reset", "selfCostEstimate", "uninstall"):
+ assert symbol in source
+
+
[email protected](shutil.which("node") is None, reason = "node is not installed")
+def test_layoutcost_js_parses():
+ result = subprocess.run(
+ ["node", "--check", str(LAYOUTCOST_JS_PATH)],
+ capture_output = True,
+ text = True,
+ check = False,
+ )
+ assert result.returncode == 0, result.stderr
+
+
+# ---------------------------------------------------------------------------------------
+# the overhead gate
+# ---------------------------------------------------------------------------------------
+
+
+def test_an_instrument_whose_cost_tracks_the_treatment_is_disqualified():
+ verdict = overhead_growth_gate(
+ "tracing",
+ 2,
+ {
+ 1_000: Measure.read(4.0, "ms"),
+ 10_000: Measure.read(9.0, "ms"),
+ 100_000: Measure.read(31.0, "ms"),
+ },
+ )
+ assert verdict.disqualified is True
+ assert "manufactures the very slope" in verdict.reason
+ assert "DISQUALIFIED" in render_overhead_section([verdict])
+
+
+def test_a_flat_instrument_passes():
+ verdict = overhead_growth_gate(
+ "tracing",
+ 2,
+ {
+ 1_000: Measure.read(8.0, "ms"),
+ 100_000: Measure.read(8.4, "ms"),
+ },
+ )
+ assert verdict.disqualified is False
+ assert "within the" in verdict.reason
+
+
+def test_a_large_ratio_on_a_tiny_number_is_not_a_disqualification():
+ verdict = overhead_growth_gate(
+ "layoutcost",
+ 3,
+ {1_000: Measure.read(0.01, "ms"), 100_000: Measure.read(0.09, "ms")},
+ )
+ assert verdict.disqualified is False
+ assert "below the" in verdict.reason
+
+
+def test_a_gate_that_could_not_be_evaluated_is_not_a_passed_gate():
+ verdict = overhead_growth_gate("tracing", 2, {1_000: Measure.read(4.0, "ms")})
+ assert verdict.disqualified is False
+ assert "not a passed gate" in verdict.reason
+
+
+def test_level_zero_has_nothing_to_declare():
+ verdict = overhead_growth_gate("frames", 0, {})
+ assert "headline numbers" in verdict.reason
+
+
+def test_the_log_slope_catches_a_spike_the_end_to_end_ratio_misses():
+ by_rung = {
+ 1_000: Measure.read(5.0, "ms"),
+ 10_000: Measure.read(40.0, "ms"),
+ 100_000: Measure.read(5.0, "ms"),
+ }
+ verdict = overhead_growth_gate("tracing", 2, by_rung)
+ assert verdict.growth_ratio == pytest.approx(1.0) # the ends agree
+ assert verdict.disqualified is False
+ assert log_growth_slope(by_rung) is not None # but the slope is reported anyway
+
+
+def test_the_log_slope_needs_two_points():
+ assert log_growth_slope({1_000: Measure.read(5.0, "ms")}) is None
diff --git a/tests/studio/studiobench/report/selftest/test_studiobench_report.py b/tests/studio/studiobench/report/selftest/test_studiobench_report.py
new file mode 100644
index 00000000000..c82c965f926
--- /dev/null
+++ b/tests/studio/studiobench/report/selftest/test_studiobench_report.py
@@ -0,0 +1,263 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Unit tests for the report layer: incremental payload, and the editorial policy.
+
+Two things are being tested here and they fail in different ways. The payload writer fails by
+losing evidence, which is invisible until the run that mattered is the one that crashed. The
+renderer fails by printing something true next to something misleading, which is invisible
+forever.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.report import ( # noqa: E402
+ HeadlinePolicyError,
+ PayloadWriter,
+ assemble,
+ assert_headline_pair,
+ excluded_totals,
+ read_records,
+ render_ab_table,
+ render_excluded,
+ render_frame_health,
+ render_summary,
+)
+from studiobench.scoring import ( # noqa: E402
+ ExcludedCell,
+ Measure,
+ PayloadSchemaError,
+ Pair,
+ RunIdentity,
+ compare,
+ compute_frame_stats,
+ score_ladder,
+ score_rung,
+)
+
+
+def _metrics(keystroke_ms: float = 25.0) -> dict[str, Measure]:
+ return {
+ "keystroke_p95_ms": Measure.read(keystroke_ms, "ms"),
+ "time_in_jank_pct": Measure.read(0.8, "%"),
+ "jank_index": Measure.read(0.2, "ms"),
+ "max_frame_ms": Measure.read(40.0, "ms"),
+ "scroll_settle_ms": Measure.read(130.0, "ms"),
+ "menu_open_ms": Measure.read(60.0, "ms"),
+ }
+
+
+# ---------------------------------------------------------------------------------------
+# incremental payload
+# ---------------------------------------------------------------------------------------
+
+
+def test_a_crash_at_rung_four_still_ships_rungs_one_to_three(tmp_path: Path):
+ path = tmp_path / "payload.jsonl"
+ writer = PayloadWriter(path)
+ writer.write("header", info = {"bench_version": "studiobench/1"})
+ for rung in (1_000, 10_000, 100_000):
+ writer.write("window", rung_tokens = rung, metrics = _metrics())
+ writer.write("crash", where = "renderer", error_type = "TargetClosedError", error = "oom")
+ writer.close()
+
+ payload = assemble(path)
+ assert len(payload["windows"]) == 3
+ assert payload["complete"] is False
+ assert payload["crashes"][0]["where"] == "renderer"
+ assert "did not reach the end" in payload["incomplete_note"]
+
+
+def test_a_half_written_final_line_is_discarded_not_fatal(tmp_path: Path):
+ path = tmp_path / "payload.jsonl"
+ writer = PayloadWriter(path)
+ writer.write("header", info = {"bench_version": "studiobench/1"})
+ writer.write("window", rung_tokens = 1_000, metrics = _metrics())
+ writer.close()
+ with path.open("a", encoding = "utf-8") as handle:
+ handle.write('{"kind":"window","rung_tokens":10000,"met')
+
+ records, discarded = read_records(path)
+ assert discarded == 1
+ assert len(records) == 2
+ payload = assemble(path)
+ assert payload["truncated_records"] == 1
+ assert len(payload["windows"]) == 1
+
+
+def test_the_writer_records_a_crash_when_the_driver_dies(tmp_path: Path):
+ path = tmp_path / "payload.jsonl"
+ with pytest.raises(RuntimeError):
+ with PayloadWriter(path) as writer:
+ writer.write("header", info = {})
+ raise RuntimeError("the driver fell over")
+ payload = assemble(path)
+ assert payload["crashes"][0]["error"] == "the driver fell over"
+ assert payload["crashes"][0]["where"] == "driver"
+
+
+def test_assemble_validates_the_bare_zero_ban(tmp_path: Path):
+ path = tmp_path / "payload.jsonl"
+ writer = PayloadWriter(path)
+ writer.write("window", rung_tokens = 1_000, react_stage_ms = 0)
+ writer.close()
+ with pytest.raises(PayloadSchemaError):
+ assemble(path)
+
+
+def test_measures_survive_the_round_trip_with_their_attempted_flag(tmp_path: Path):
+ path = tmp_path / "payload.jsonl"
+ writer = PayloadWriter(path)
+ writer.write(
+ "window",
+ rung_tokens = 1_000,
+ metrics = {"react_stage_ms": Measure.not_attempted("ms", "profiling alias unverified")},
+ )
+ writer.close()
+ payload = assemble(path)
+ measure = payload["windows"][0]["metrics"]["react_stage_ms"]
+ assert measure["attempted"] is False
+ assert "not attempted" in measure["display"]
+
+
+def test_excluded_cells_are_totalled_by_reason(tmp_path: Path):
+ path = tmp_path / "payload.jsonl"
+ writer = PayloadWriter(path)
+ for cell in (
+ ExcludedCell("r3.w2", "clock_disagreement", 1, "raf 44% off wall"),
+ ExcludedCell("r4.w1", "clock_disagreement", 2, "raf produced no frames"),
+ ExcludedCell("r4.w7", "arm_voided_invariance", 1, "digest drifted"),
+ ):
+ writer.write("excluded", **cell.to_json())
+ writer.write("footer", info = {"exit": "ok"})
+ writer.close()
+ payload = assemble(path)
+ assert excluded_totals(payload) == {"clock_disagreement": 3, "arm_voided_invariance": 1}
+ rendered = render_excluded(payload)
+ assert "clock_disagreement" in rendered
+
+
+def test_an_empty_excluded_block_is_still_printed_as_a_claim():
+ rendered = render_excluded({"excluded_cells": []})
+ assert "none." in rendered
+ with pytest.raises(AssertionError):
+ render_excluded({"excluded_cells": None})
+
+
+# ---------------------------------------------------------------------------------------
+# editorial policy
+# ---------------------------------------------------------------------------------------
+
+
+def test_a_single_frame_summary_may_not_be_a_headline():
+ with pytest.raises(HeadlinePolicyError):
+ assert_headline_pair(["time_in_jank_pct"])
+ with pytest.raises(HeadlinePolicyError):
+ assert_headline_pair(["jank_index", "max_frame_ms"])
+ assert_headline_pair(["time_in_jank_pct", "jank_index", "max_frame_ms"])
+ assert_headline_pair(["onset_rung"]) # nothing frame-related, nothing to police
+
+
+def test_frame_health_always_prints_all_three():
+ stats = compute_frame_stats([8.0] * 100 + [900.0], window_ms = 1700.0)
+ rendered = render_frame_health(stats)
+ assert "time in jank" in rendered
+ assert "jank index" in rendered
+ assert "worst frame" in rendered
+ assert "histogram" in rendered
+
+
+def test_no_frames_recorded_is_called_out_in_the_render():
+ rendered = render_frame_health(compute_frame_stats([], window_ms = 3000.0))
+ assert "not zero jank" in rendered
+
+
+def test_the_headline_is_the_onset_rung_and_the_score_is_labelled_machine_local():
+ ladder = score_ladder(
+ [
+ score_rung(1_000, _metrics()),
+ score_rung(10_000, _metrics()),
+ score_rung(100_000, _metrics(keystroke_ms = 460.0)),
+ ]
+ )
+ summary = render_summary({"complete": True, "excluded_cells": []}, ladder)
+ assert summary.index("ONSET RUNG") < summary.index("aggregate score")
+ assert "machine-local" in summary
+ assert "10,000 tokens" in summary
+
+
+def test_a_void_ab_prints_no_numbers_at_all():
+ identity = RunIdentity("studiobench/1", "c", "r", "w", "s1")
+ pairs = [
+ Pair(1_000, "keystroke_p95_ms", Measure.read(100.0, "ms"), Measure.read(140.0, "ms"))
+ for _ in range(4)
+ ]
+ result = compare("base vs base", pairs, identity, identity, is_null_control = True)
+ rendered = render_ab_table(result)
+ assert "VOID" in rendered
+ assert "1.4" not in rendered
+ assert "ratio" not in rendered
+
+
+def test_an_incomplete_run_says_so_before_any_numbers(tmp_path: Path):
+ path = tmp_path / "payload.jsonl"
+ writer = PayloadWriter(path)
+ writer.write("window", rung_tokens = 1_000, metrics = _metrics())
+ writer.close()
+ payload = assemble(path)
+ summary = render_summary(payload, None)
+ assert summary.index("RUN DID NOT FINISH") < summary.index("EXCLUDED CELLS")
+
+
+def test_harness_bias_is_printed_and_never_subtracted():
+ summary = render_summary(
+ {"complete": True, "excluded_cells": []},
+ None,
+ harness_bias = {"keystroke_p95_ms": Measure.read(4.2, "%")},
+ )
+ assert "HARNESS BIAS" in summary
+ assert "NOT subtracted" in summary
+
+
+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 true
+ magnitude. Printed bare it invites `4900% worse` being quoted as a measurement; the marker
+ goes in the ratio cell rather than a footnote for the same reason the void path gives."""
+
+ identity = RunIdentity("studiobench/1", "c", "r", "w", "s1")
+ smooth = Measure.read(0.0, "%", floor = 0.1)
+ janky = Measure.read(5.0, "%", floor = 0.1)
+ result = compare(
+ "main -> fix",
+ [Pair(100_000, "time_in_jank_pct", smooth, janky)],
+ identity,
+ identity,
+ )
+ rendered = render_ab_table(result)
+
+ assert ">=50.000" in rendered
+ assert "no reading" not in rendered
+ assert "regressed" in rendered
+
+
+def test_an_ordinary_ratio_is_still_printed_bare():
+ """The control: nothing sub-floor, nothing marked."""
+
+ identity = RunIdentity("studiobench/1", "c", "r", "w", "s1")
+ result = compare(
+ "main -> fix",
+ [Pair(100_000, "keystroke_p95_ms", Measure.read(100.0, "ms"), Measure.read(120.0, "ms"))],
+ identity,
+ identity,
+ )
+ rendered = render_ab_table(result)
+
+ assert "1.200" in rendered
+ assert ">=" not in rendered and "<=" not in rendered
diff --git a/tests/studio/studiobench/runtime/__init__.py b/tests/studio/studiobench/runtime/__init__.py
new file mode 100644
index 00000000000..a394988cd6a
--- /dev/null
+++ b/tests/studio/studiobench/runtime/__init__.py
@@ -0,0 +1,4 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Install, launch, guard and drive a real Studio. Only `types` is public; see INTERFACES.md."""
diff --git a/tests/studio/studiobench/runtime/ab.py b/tests/studio/studiobench/runtime/ab.py
new file mode 100644
index 00000000000..36aa7357e66
--- /dev/null
+++ b/tests/studio/studiobench/runtime/ab.py
@@ -0,0 +1,357 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Run two Studio builds against each other INSIDE ONE SESSION.
+
+WHY THIS CANNOT BE TWO RUNS. Cross-session drift on this app measured 8%, which is larger than
+most of the wins anybody argues about. `scoring.ab.assert_comparable` refuses two different
+session ids outright, and that refusal is correct: running the base today and the treatment
+tomorrow produces a ratio whose dominant term is the machine, not the change. So both builds are
+installed up front, one browser drives both, and the cells alternate.
+
+WHY THE ORDER FLIPS. Anything that drifts monotonically within a session -- thermal throttling, a
+browser heap that never quite shrinks, another process ramping up -- is charged entirely to
+whichever side runs second if the order is fixed. Alternating (base, treatment) on even reps and
+(treatment, base) on odd ones cancels the linear part of that term instead of measuring it. With
+`--reps 1` the order cannot be balanced, which is why a single-rep A/B prints the warning it does.
+
+WHAT VOIDS THE RESULT. The null control -- the base build compared against ITSELF, interleaved the
+same way -- runs first and must land inside its own noise band. If comparing a build to itself
+produces a difference, then a difference between two builds means nothing, and no table is worth
+printing. That check is the whole reason this file interleaves at all.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any, Callable, Optional, Sequence
+
+from ..fixture.corpus import Corpus, RungPlan
+from .types import Cell
+
+
+@dataclass
+class Target:
+ """One side of the comparison: a Studio to drive and everything needed to drive it."""
+
+ label: str # "base" or "treatment"
+ ref: str # the git ref, for the report
+ base_url: str
+ seeder: Any
+ runner: Any # a CellRunner bound to this target's base_url and seeder
+ install: Any = None # StudioInstall, when we own it
+ owns_studio: bool = False
+
+
+def origin_scoped(base_url: str, script: str) -> str:
+ """Run `script` only on its own Studio's origin.
+
+ `add_init_script` fires on every document in the context, and localStorage is per-origin under
+ the SAME KEY NAMES on both builds. Seeding both unconditionally means whichever script runs
+ last writes the other build's auth token into this build's storage, and the failure shows up
+ much later as a logged-out SPA or a provider that renders as "No longer offered" -- neither of
+ which points back here.
+ """
+ import json as _json
+ return (
+ "(() => { if (window.location.origin !== "
+ + _json.dumps(base_url.rstrip("/"))
+ + ") return; "
+ + script
+ + " })();"
+ )
+
+
+def interleave(
+ cells: list[tuple[Cell, RungPlan]], targets: list[Target]
+) -> list[tuple[Target, Cell, RungPlan]]:
+ """Order the work so the two sides sit next to each other in time, not in separate halves.
+
+ Adjacent in time is the point: the closer two paired readings are, the less of whatever the
+ machine is doing separates them. Returned as a flat list so the caller's loop stays a loop
+ and the ordering decision lives in one testable function.
+ """
+ out: list[tuple[Target, Cell, RungPlan]] = []
+ for cell, plan in cells:
+ order = list(targets) if cell.rep % 2 == 0 else list(reversed(targets))
+ for target in order:
+ out.append((target, cell.derive(arm = target.label), plan))
+ return out
+
+
+def skippable_cells(work: list[tuple[Any, Cell, RungPlan]], done: set) -> set:
+ """Of the cells `--resume` COULD skip, the ones it may: only whole `(rung, rep)` pairs.
+
+ A PAIR IS THE UNIT OF AN A/B, NOT A CELL. An interruption between the two adjacent cells of one
+ pair is the ordinary way a run stops, and skipping the arm that completed then measured its
+ partner ALONE in the new session. That lone reading can never be used: `readings_by_arm` scopes
+ the comparison to one session on purpose -- cross-session drift measured 8%, larger than most
+ wins anybody argues about -- so the completed arm from the old session is dropped, the new
+ arm has nothing to pair with, and the run pays a full cell for a number no table can contain.
+ What it renders instead is that repetition missing from the table, or NO READING with an exit
+ code of 0 underneath it.
+
+ So a pair is skipped only when EVERY arm of it is already complete, and otherwise both arms are
+ re-run -- adjacent in time, in one session, which is the only arrangement `interleave` exists to
+ produce. The old attempt stays in the payload and `latest_attempt_rows` supersedes it, exactly
+ as it already does for a cell that died.
+
+ AND A COMPARISON IS ALL OF ITS PAIRS, which is the same argument one step further out. The
+ session filter that drops a lone completed arm drops a WHOLE completed pair for exactly the
+ same reason, and `_render_ab` then prints a headline and a VERDICT over whatever is left
+ without saying which rungs are missing: an interrupted standard tier whose 10K pair had
+ recorded a 30% regression published `VERDICT: IMPROVED (20.0% faster)` off the 100K pair alone,
+ with nothing in `ab.md` mentioning 10K at all. `render.py` rules out fixing that with a note
+ above the table -- the table gets screenshotted and the warning does not -- and declining to
+ publish costs the same wall clock as re-running while yielding no table. So an A/B with ANY
+ work left re-runs EVERY pair in the new session, at most one tier budget, which is the budget
+ the interrupted run was already paying.
+
+ A FINISHED A/B still skips everything: nothing runs, and `_render_ab` keeps the table that run
+ already wrote. And a legitimate extension -- `--resume --rungs 1K,10K` over a finished 1K run
+ -- now produces a complete two-rung table instead of a 10K-only one.
+
+ Single-target work is a degenerate case of the same rule: each pair holds one cell, so nothing
+ changes for a run without `--ab`, whose ladder `report.build.score_payload` reads across
+ sessions anyway.
+ """
+ by_pair: dict[tuple[str, int], list[str]] = {}
+ for _target, cell, _plan in work:
+ by_pair.setdefault((str(cell.rung), int(cell.rep)), []).append(str(cell.cell_id))
+ out: set = set()
+ for cell_ids in by_pair.values():
+ if all(cell_id in done for cell_id in cell_ids):
+ out.update(cell_ids)
+ # A pair carrying more than one arm is a comparison, and a comparison is scoped to one session.
+ # Partial skipping is right for a single-target ladder and wrong for a ratio.
+ if any(len(cell_ids) > 1 for cell_ids in by_pair.values()):
+ planned = sum(len(cell_ids) for cell_ids in by_pair.values())
+ if len(out) != planned:
+ return set()
+ return out
+
+
+def order_is_balanced(plan: list[tuple[Target, Cell, RungPlan]]) -> bool:
+ """True when each side ran first equally often, so linear drift cancels rather than lands.
+
+ Reported rather than enforced: an unbalanced plan is still worth running, it just carries a
+ drift term that the reader has to be told about instead of discovering later.
+ """
+ labels = {target.label for target, _cell, _plan in plan}
+ first_counts: dict[str, int] = {label: 0 for label in labels}
+ seen: set[str] = set()
+ for target, cell, _plan in plan:
+ key = f"{cell.rung}:{cell.rep}"
+ if key in seen:
+ continue
+ seen.add(key)
+ first_counts[target.label] += 1
+ # Every label is seeded at zero first. Counting only the labels that DID run first reports a
+ # single-rep plan -- where one side always goes first and nothing cancels -- as balanced,
+ # which is the one answer this function exists to prevent.
+ return len(labels) > 1 and len(set(first_counts.values())) == 1
+
+
+def unmeasured_planned_cells(
+ records: list[dict],
+ planned: Sequence[str],
+ session_id: Optional[str] = None,
+) -> list[str]:
+ """The planned cells this session has no completed reading for, in plan order.
+
+ A COMPARISON IS ALL OF ITS PAIRS, and a cell that failed removes its HEALTHY PARTNER from the
+ table too: `readings_by_arm` drops the incomplete cell, and `compare_arms` intersects the two
+ arms' keys, so the surviving pairs are a subset chosen by which cell happened to die. The
+ hazard is the one `skippable_cells` describes for an interrupted resume, arriving by the other
+ road -- `CellRunner.run` catches the exception and returns an incomplete row, so the run
+ continues and `_render_ab` is reached with a hole in the plan. A 10K base cell that died
+ published `VERDICT: IMPROVED (20.0% faster)` off the 100K pair alone while the completed 10K
+ pair underneath it was a 26.5% regression, and `ab.md` named neither the missing rung nor the
+ failure.
+
+ The exit code is already nonzero when a cell fails, and it is not enough: `ab.md` outlives the
+ process and is what gets quoted. `render_ab_table` prints no numbers at all when a result is
+ void, for the reason stated there -- the table gets screenshotted and the warning does not --
+ and an incomplete plan is voided on the same grounds.
+ """
+ from ..scoring.from_payload import latest_attempt_rows
+
+ complete: set = set()
+ for row in latest_attempt_rows(records):
+ if row.get("row_type") != "cell" or row.get("completed") is not True:
+ continue
+ if session_id is not None and row.get("session_id") not in (None, session_id):
+ continue
+ complete.add(str(row.get("cell_id")))
+ return [str(cell_id) for cell_id in planned if str(cell_id) not in complete]
+
+
+def readings_by_arm(
+ records: list[dict], session_id: Optional[str] = None
+) -> dict[str, dict[int, dict]]:
+ """Split one payload's cell rows into `{arm: {rung_tokens: {metric: Measure}}}`.
+
+ A CELL THAT DID NOT COMPLETE IS NOT AN ARM'S READING. The ladder scores an incomplete cell on
+ purpose -- a build that dies at 500K is the most important thing the run has to say -- but a
+ ratio is a different question. An arm that crashed after emitting one action row still carries
+ that row's timings, and pairing them against a completed cell on the other side turns a crash
+ into a win: a treatment cell holding nothing but a 50 ms keystroke, measured against a
+ completed 100 ms base cell, reports IMPROVED. The crash is still in the payload, in the
+ summary and in `excluded_cells`; it is only kept out of the ratios.
+
+ `session_id`, when given, keeps the comparison inside ONE session. `--resume` appends to the
+ payload a previous run wrote, so an interrupted A/B resumed into the same directory otherwise
+ hands `compare_arms` cells from two browser sessions -- the 8% cross-session drift term that
+ `assert_comparable` exists to refuse, arriving through the back door because both sides are
+ labelled with the CURRENT session id.
+
+ Deferred import: `scoring` pulls in the anchor table and this module is imported by the CLI
+ before a run, where that cost buys nothing.
+ """
+ from ..scoring.from_payload import latest_attempt_rows, measures_by_cell
+
+ # The session filter below scopes the CELL rows, but `action` and `window` rows are collected
+ # 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))
+
+ arms: dict[str, list[dict]] = {}
+ cell_ids: dict[str, set[str]] = {}
+ for row in records:
+ if row.get("row_type") == "cell":
+ if row.get("completed") is not True:
+ continue
+ if session_id is not None and row.get("session_id") not in (None, session_id):
+ continue
+ arm = str((row.get("cell") or {}).get("arm") or row.get("arm") or "")
+ if arm:
+ cell_ids.setdefault(arm, set()).add(str(row.get("cell_id")))
+
+ for arm, ids in cell_ids.items():
+ subset = [
+ r
+ for r in records
+ if r.get("row_type") not in {"cell", "action", "window"} or str(r.get("cell_id")) in ids
+ ]
+ arms[arm] = subset
+
+ return {arm: measures_by_cell(rows) for arm, rows in arms.items()}
+
+
+def compare_arms(
+ records: list[dict],
+ base_label: str,
+ treatment_label: str,
+ *,
+ bench_version: str,
+ corpus_hash: str,
+ session_id: str,
+ label: str,
+ noise_floor_pct: Optional[float] = None,
+ noise_floor_source: str = "declared default",
+ is_null_control: bool = False,
+) -> Any:
+ """Build the A/B result for one pair of arms out of an already-recorded payload."""
+ from ..scoring.ab import DEFAULT_NOISE_FLOOR_PCT, Pair, RunIdentity, compare
+ from ..scoring.anchors import METRIC_BY_KEY, weights_id
+
+ by_arm = readings_by_arm(records, session_id = session_id)
+ base = by_arm.get(base_label, {})
+ treatment = by_arm.get(treatment_label, {})
+
+ rung_ladder_id = _ladder_id(sorted({rung for rung, _rep in set(base) | set(treatment)}))
+ identity_kwargs = dict(
+ bench_version = bench_version,
+ corpus_hash = corpus_hash,
+ rung_ladder_id = rung_ladder_id,
+ weights_id = weights_id() if callable(weights_id) else str(weights_id),
+ session_id = session_id,
+ )
+ # Paired PER REPETITION, matching (rung, rep) on both sides. Repetition r of the base and
+ # repetition r of the treatment ran adjacent in time, so pairing them is what makes the
+ # comparison paired at all; pooling reps into one reading per rung throws away every
+ # observation but the first and leaves the bootstrap with nothing to resample.
+ pairs = []
+ for key in sorted(set(base) & set(treatment)):
+ rung, _rep = key
+ for metric_key in METRIC_BY_KEY:
+ base_measure = base[key].get(metric_key)
+ treatment_measure = treatment[key].get(metric_key)
+ if base_measure is None or treatment_measure is None:
+ continue
+ pairs.append(
+ Pair(
+ rung_tokens = int(rung),
+ metric_key = metric_key,
+ base = base_measure,
+ treatment = treatment_measure,
+ )
+ )
+
+ return compare(
+ label,
+ pairs,
+ RunIdentity(**identity_kwargs),
+ RunIdentity(**identity_kwargs),
+ noise_floor_pct = (DEFAULT_NOISE_FLOOR_PCT if noise_floor_pct is None else noise_floor_pct),
+ noise_floor_source = noise_floor_source,
+ is_null_control = is_null_control,
+ )
+
+
+def _ladder_id(rungs: list) -> str:
+ import hashlib
+ digest = hashlib.sha256(",".join(str(int(r)) for r in rungs).encode()).hexdigest()[:12]
+ return f"r-{digest}"
+
+
+def make_target(
+ label: str,
+ ref: str,
+ base_url: str,
+ *,
+ pacer,
+ model_id: str,
+ corpus: Corpus,
+ tier: str,
+ paths,
+ log: Callable[[str], None],
+ cadence: str,
+ image_path,
+ session,
+ username: str,
+ password: str,
+) -> Target:
+ """Authenticate against one Studio, register the shared pacer on it, and bind a runner.
+
+ Both sides talk to the SAME pacer, so the bytes on the wire are identical by construction
+ rather than by two configurations that are meant to match.
+ """
+ from .lifecycle import authenticate, external_checkpoint_id, pacer_provider, register_provider
+ from .seeder import Seeder
+ from .session import CellRunner
+
+ auth = authenticate(base_url, username, password)
+ provider = pacer_provider(pacer.base_url, [model_id])
+ register_provider(base_url, auth, provider)
+ checkpoint = external_checkpoint_id(provider, model_id)
+ log(f" {label}: {base_url} -> pacer {pacer.base_url}, checkpoint {checkpoint}")
+
+ seeder = Seeder(base_url = base_url, auth = auth, model_id = model_id, log = log)
+ runner = CellRunner(
+ session = session,
+ pacer = pacer,
+ seeder = seeder,
+ corpus = corpus,
+ base_url = base_url,
+ model_id = model_id,
+ tier = tier,
+ paths = paths,
+ log = log,
+ cadence = cadence,
+ image_path = image_path,
+ )
+ target = Target(label = label, ref = ref, base_url = base_url, seeder = seeder, runner = runner)
+ target.auth = auth # type: ignore[attr-defined]
+ target.checkpoint = checkpoint # type: ignore[attr-defined]
+ return target
diff --git a/tests/studio/studiobench/runtime/browser.py b/tests/studio/studiobench/runtime/browser.py
new file mode 100644
index 00000000000..0c6b34df015
--- /dev/null
+++ b/tests/studio/studiobench/runtime/browser.py
@@ -0,0 +1,248 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Browser launch. Reuses `tests/studio/_playwright_robust.py` where it is available.
+
+Playwright is imported LAZILY, inside the functions that need it, so `--help` and `--doctor` work
+on a machine with nothing installed -- which is the first thing an external tester runs and the
+worst possible moment for an ImportError.
+
+`_playwright_robust` is imported the same way and its absence is survivable: the shipped zipapp
+carries a copy of the pieces it needs, but a checkout run gets the real module and therefore the
+real, maintained Chromium flags, the view-transition killer, the wall-clock watchdog and
+`dump_diagnostics`.
+"""
+
+from __future__ import annotations
+
+import importlib
+import platform
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Callable, Optional
+
+
+# The engine matching the tester's desktop webview family. Studio ships as a Tauri app, so the
+# thing a user actually looks at is a system webview, not the browser they happen to have.
+# Windows -> WebView2, which is Chromium: `channel="msedge"` is the closest available.
+# macOS -> WKWebView, which is WebKit.
+# Linux -> WebKitGTK. Playwright's `webkit` is NOT WebKitGTK; it is a different embedding of
+# the same engine, so it is labelled A PROXY and never as the real thing.
+def default_engine() -> tuple[str, dict, str]:
+ system = platform.system()
+ if system == "Windows":
+ return "chromium", {"channel": "msedge"}, "Edge/WebView2, the Windows desktop webview"
+ if system == "Darwin":
+ return "webkit", {}, "WebKit, the engine behind macOS WKWebView"
+ return (
+ "webkit",
+ {},
+ (
+ "WebKit, A PROXY FOR WebKitGTK: Playwright's webkit is a different "
+ "embedding of the same engine, not the GTK one Studio runs in on Linux"
+ ),
+ )
+
+
+def _robust() -> Any:
+ """`tests.studio._playwright_robust`, or None when running from the zipapp."""
+ for name in ("tests.studio._playwright_robust", "_playwright_robust"):
+ try:
+ return importlib.import_module(name)
+ except Exception: # noqa: BLE001
+ continue
+ return None
+
+
+_FALLBACK_CHROMIUM_ARGS = [
+ "--disable-dev-shm-usage",
+ "--no-sandbox",
+ "--disable-gpu",
+ "--disable-background-timer-throttling",
+ "--disable-renderer-backgrounding",
+ "--disable-backgrounding-occluded-windows",
+ "--disable-features=TranslateUI",
+ "--disable-ipc-flooding-protection",
+]
+
+
+@dataclass
+class BrowserBundle:
+ playwright: Any
+ browser: Any
+ context: Any
+ page: Any
+ cdp: Any
+ engine: str
+ engine_note: str
+ robust: Any
+
+ def close(self) -> None:
+ for closer in (
+ lambda: self.context.close(),
+ lambda: self.browser.close(),
+ lambda: self.playwright.stop(),
+ ):
+ try:
+ closer()
+ except Exception: # noqa: BLE001
+ pass
+
+
+def launch(
+ engine: Optional[str] = None,
+ *,
+ headless: bool = True,
+ init_scripts: Optional[list[str]] = None,
+ viewport: tuple[int, int] = (1440, 960),
+ log: Callable[[str], None] = print,
+) -> BrowserBundle:
+ from playwright.sync_api import sync_playwright # lazy, see the module docstring
+
+ chosen, launch_kwargs, note = default_engine()
+ if engine:
+ chosen, launch_kwargs = (
+ engine,
+ ({} if engine != "chromium" or chosen != "chromium" else launch_kwargs),
+ )
+ note = f"{engine}, chosen explicitly"
+ robust = _robust()
+ args = robust.chromium_launch_args() if robust is not None else _FALLBACK_CHROMIUM_ARGS
+
+ pw = sync_playwright().start()
+ factory = getattr(pw, chosen)
+ if chosen == "chromium":
+ browser = factory.launch(headless = headless, args = args, **launch_kwargs)
+ else:
+ browser = factory.launch(headless = headless)
+ context = browser.new_context(
+ viewport = {"width": viewport[0], "height": viewport[1]},
+ # Clipboard read is what proves the Copy action actually copied. Without it the action
+ # still runs and the assertion reports that it could not be proved, which is the honest
+ # outcome rather than a pass.
+ permissions = ["clipboard-read", "clipboard-write"] if chosen == "chromium" else None,
+ )
+ if robust is not None:
+ try:
+ robust.install_view_transition_killer(context)
+ except Exception: # noqa: BLE001
+ pass
+ for script in init_scripts or []:
+ context.add_init_script(script)
+ page = context.new_page()
+ # A GLOBAL CEILING on Playwright's actionability waits. The default is 30 seconds, which is
+ # longer than most of this suite's slot budgets: one action waiting out the default on an
+ # element that is present but not visible overran a 9-second slot by more than three times,
+ # and the scheduler cannot intervene because the action still holds its own window. Actions
+ # that legitimately need longer pass an explicit timeout.
+ page.set_default_timeout(8000)
+ cdp = None
+ if chosen == "chromium":
+ try:
+ cdp = context.new_cdp_session(page)
+ cdp.send("Performance.enable")
+ except Exception: # noqa: BLE001
+ cdp = None
+ log(f" browser: {chosen} ({note}){'' if cdp else ', no CDP session'}")
+ return BrowserBundle(
+ playwright = pw,
+ browser = browser,
+ context = context,
+ page = page,
+ cdp = cdp,
+ engine = chosen,
+ engine_note = note,
+ robust = robust,
+ )
+
+
+def cdp_metrics(cdp) -> dict:
+ if cdp is None:
+ return {}
+ try:
+ got = cdp.send("Performance.getMetrics")
+ except Exception: # noqa: BLE001
+ return {}
+ return {m["name"]: m["value"] for m in got["metrics"]}
+
+
+def cdp_counters(before: dict, after: dict) -> dict:
+ """CHROMIUM-ONLY, and every consumer prints `-` off Chromium rather than a zero.
+
+ `LayoutDuration` is the direct read on M3: the autoscroll observer's callback synchronously
+ reads scrollHeight, so forced layout per streamed character shows up here and nowhere else.
+ An earlier harness read it as a FLAT FLOOR that barely moved with thread size, which is
+ exactly what it would look like if the observer never ran -- which, on a fixture with a local
+ adapter and no real DOM mutations, it did not.
+ """
+ if not before or not after:
+ return {
+ "layout_count": None,
+ "recalc_style_count": None,
+ "layout_ms": None,
+ "recalc_style_ms": None,
+ "task_ms": None,
+ "cdp_attempted": False,
+ }
+
+ def d(name: str) -> float:
+ return after.get(name, 0.0) - before.get(name, 0.0)
+
+ return {
+ "layout_count": round(d("LayoutCount"), 1),
+ "recalc_style_count": round(d("RecalcStyleCount"), 1),
+ "layout_ms": round(d("LayoutDuration") * 1000, 1),
+ "recalc_style_ms": round(d("RecalcStyleDuration") * 1000, 1),
+ "task_ms": round(d("TaskDuration") * 1000, 1),
+ "script_ms": round(d("ScriptDuration") * 1000, 1),
+ "cdp_attempted": True,
+ }
+
+
+def find_python_root_pid() -> int:
+ return __import__("os").getpid()
+
+
+def dump_diagnostics(
+ page,
+ out_dir: Path,
+ label: str,
+ log: Callable[[str], None] = print,
+) -> None:
+ robust = _robust()
+ if robust is not None and hasattr(robust, "dump_diagnostics"):
+ try:
+ robust.dump_diagnostics(page, out_dir, label)
+ return
+ except Exception: # noqa: BLE001
+ pass
+ try:
+ out_dir.mkdir(parents = True, exist_ok = True)
+ page.screenshot(path = str(out_dir / f"{label}.png"), full_page = False)
+ (out_dir / f"{label}.html").write_text(page.content(), encoding = "utf-8")
+ except Exception as exc: # noqa: BLE001
+ log(f" diagnostics for {label} could not be written: {exc}")
+
+
+def install_wall_clock_watchdog(
+ deadline_s: float,
+ label: str = "studiobench",
+ log: Callable[[str], None] = print,
+):
+ robust = _robust()
+ if robust is not None and hasattr(robust, "install_wall_clock_watchdog"):
+ return robust.install_wall_clock_watchdog(deadline_s, label = label, info = log)
+ import os
+ import threading
+
+ def _kaboom() -> None:
+ sys.stderr.write(f"[{label}] WATCHDOG: hit {deadline_s:.0f}s wall clock; exit(2)\n")
+ sys.stderr.flush()
+ os._exit(2)
+
+ timer = threading.Timer(deadline_s, _kaboom)
+ timer.daemon = True
+ timer.start()
+ log(f" watchdog armed: hard exit at {deadline_s:.0f}s")
+ return timer
diff --git a/tests/studio/studiobench/runtime/bundle_guard.py b/tests/studio/studiobench/runtime/bundle_guard.py
new file mode 100644
index 00000000000..390bd0704fc
--- /dev/null
+++ b/tests/studio/studiobench/runtime/bundle_guard.py
@@ -0,0 +1,230 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Refuse to benchmark a development build.
+
+A Vite dev server MANUFACTURES the symptom this tool exists to find. React's development build
+does per-render bookkeeping the production build does not, and the measured inflation is about
+3.2x on exactly the axis under investigation. A number taken against it is not a smaller version
+of the truth, it is a different phenomenon with the same units, and it would confirm any
+hypothesis you brought to it.
+
+TWO independent checks, because either alone has a hole.
+
+1. **`/@vite/client` answers 200.** Only a dev server serves that path. Cheap, decisive, and it
+ catches a dev server even when the entry asset happens to look fine.
+
+2. **`bundleType: 0` in the SAME chunk as `rendererPackageName: "react-dom"`.** React's renderer
+ registers itself with the DevTools hook carrying a `bundleType`, 0 for production and 1 for
+ development. It has to be read from the same chunk as the `react-dom` marker: a large app
+ bundle contains several renderers' worth of strings, and `bundleType:1` from some other
+ package proves nothing about react-dom.
+
+**Do NOT grep for `jsxDEV`.** It false-positives. `hast-util-to-jsx-runtime`, which Streamdown
+pulls in and which is in every production bundle of this app, ships its own option guard naming
+`jsxDEV` as a supported entry point. A `jsxDEV` grep therefore fails a perfectly good production
+build, and the natural response to a gate that fails on a correct build is to switch the gate off.
+"""
+
+from __future__ import annotations
+
+import re
+import urllib.error
+import urllib.request
+from dataclasses import dataclass, field
+from typing import Optional
+
+# Kept small: an app entry chunk is megabytes and the marker pair sits within a few hundred bytes
+# of each other in every React build, minified or not.
+_WINDOW = 4000
+
+# BACKTICKS as well as quotes. Studio's production bundle is minified with a pass that rewrites
+# short string literals as template literals, so the marker on the shipped build reads
+# ``rendererPackageName:`react-dom` `` and a quote-only pattern misses it on every asset -- which
+# reads as "build mode could not be established" on a perfectly good production build, i.e. the
+# gate fails exactly where it is supposed to pass. Verified against the shipped bundle.
+_RENDERER_RE = re.compile(r'rendererPackageName\s*:\s*["\'`]react-dom["\'`]')
+_BUNDLETYPE_RE = re.compile(r"bundleType\s*:\s*([01])")
+
+
+@dataclass
+class BundleVerdict:
+ production: bool
+ reason: str
+ vite_client_status: Optional[int] = None
+ bundle_type: Optional[int] = None
+ entry_url: Optional[str] = None
+ entry_bytes: Optional[int] = None
+ checked: list[str] = field(default_factory = list)
+
+ def as_dict(self) -> dict:
+ return {
+ "production": self.production,
+ "reason": self.reason,
+ "vite_client_status": self.vite_client_status,
+ "bundle_type": self.bundle_type,
+ "entry_url": self.entry_url,
+ "entry_bytes": self.entry_bytes,
+ "checked": self.checked,
+ # Attempted flags, because "bundle_type is None" and "bundle_type is 0" are opposite
+ # findings and a bare null cannot say which.
+ "bundle_type_attempted": self.entry_url is not None,
+ "vite_probe_attempted": self.vite_client_status is not None,
+ }
+
+
+def _get(url: str, timeout: float = 20.0) -> tuple[int, bytes, str]:
+ req = urllib.request.Request(url, headers = {"Accept": "*/*"})
+ try:
+ with urllib.request.urlopen(req, timeout = timeout) as r:
+ return r.status, r.read(), (r.headers.get("Content-Type") or "")
+ except urllib.error.HTTPError as exc:
+ return exc.code, b"", ""
+ except Exception: # noqa: BLE001
+ return 0, b"", ""
+
+
+def _is_vite_client(status: int, body: bytes, content_type: str) -> bool:
+ """A 200 alone does NOT mean a dev server, and assuming it does breaks the gate.
+
+ Studio serves its built frontend as a single-page app, so ANY unknown path returns 200 with
+ `index.html` -- measured here against two production Studios, both of which answered 200 to
+ `/@vite/client` and were failed as dev servers by the first version of this check. A gate that
+ fails every correct build is a gate someone turns off.
+
+ A real Vite dev server serves that path as a JavaScript module. So the probe is: 200, AND the
+ body is script rather than the SPA's HTML fallback.
+ """
+ if status != 200 or not body:
+ return False
+ head = body[:512].lstrip().lower()
+ if head.startswith(b"<!doctype") or head.startswith(b"<html"):
+ return False
+ if "html" in content_type.lower():
+ return False
+ return (
+ "javascript" in content_type.lower()
+ or b"import " in body[:2048]
+ or b"vite" in body[:2048].lower()
+ )
+
+
+def _entry_urls(base_url: str, html: str) -> list[str]:
+ """Every script the index document loads, most-likely-entry first."""
+ out: list[str] = []
+ for src in re.findall(r'<script[^>]+src=["\']([^"\']+)["\']', html):
+ url = src if src.startswith("http") else base_url.rstrip("/") + "/" + src.lstrip("/")
+ out.append(url)
+ # A modulepreload is how Vite names the real entry chunk when the script tag points at a
+ # loader shim, so it is worth following when the script tags carry nothing.
+ for href in re.findall(
+ r'<link[^>]+rel=["\']modulepreload["\'][^>]+href=["\']([^"\']+)["\']', html
+ ):
+ url = href if href.startswith("http") else base_url.rstrip("/") + "/" + href.lstrip("/")
+ if url not in out:
+ out.append(url)
+ return out
+
+
+def check_bundle(base_url: str) -> BundleVerdict:
+ base_url = base_url.rstrip("/")
+ checked: list[str] = []
+
+ status, vite_body, vite_ct = _get(f"{base_url}/@vite/client")
+ is_dev = _is_vite_client(status, vite_body, vite_ct)
+ checked.append(
+ f"/@vite/client -> {status} ({vite_ct or 'no content-type'}, "
+ f"{len(vite_body)} bytes) -> "
+ f"{'a real dev client module' if is_dev else 'not a dev client'}"
+ )
+ if is_dev:
+ return BundleVerdict(
+ production = False,
+ reason = (
+ "/@vite/client served a JavaScript module, so this is a Vite dev server. "
+ "React's development build inflates the very axis under investigation by "
+ "about 3.2x; a measurement here would confirm any hypothesis."
+ ),
+ vite_client_status = status,
+ checked = checked,
+ )
+
+ doc_status, doc, _ = _get(f"{base_url}/chat")
+ if doc_status != 200 or not doc:
+ doc_status, doc, _ = _get(f"{base_url}/")
+ checked.append(f"index document -> {doc_status}, {len(doc)} bytes")
+ if doc_status != 200 or not doc:
+ return BundleVerdict(
+ production = False,
+ reason = f"could not fetch the index document ({doc_status})",
+ vite_client_status = status,
+ checked = checked,
+ )
+
+ html = doc.decode("utf-8", "replace")
+ urls = _entry_urls(base_url, html)
+ checked.append(f"{len(urls)} script assets in the document")
+ if not urls:
+ return BundleVerdict(
+ production = False,
+ reason = "the index document loads no script assets to inspect",
+ vite_client_status = status,
+ checked = checked,
+ )
+
+ for url in urls:
+ asset_status, raw, _ = _get(url, timeout = 60)
+ if asset_status != 200 or not raw:
+ checked.append(f"{url} -> {asset_status}")
+ continue
+ text = raw.decode("utf-8", "replace")
+ match = _RENDERER_RE.search(text)
+ if match is None:
+ checked.append(f"{url}: no rendererPackageName marker, {len(raw)} bytes")
+ continue
+ # The SAME chunk, and within a small window of the marker. A bundle this size carries
+ # several `bundleType` occurrences and picking the wrong one is picking a different
+ # package's answer to a question about react-dom.
+ lo = max(0, match.start() - _WINDOW)
+ hi = min(len(text), match.end() + _WINDOW)
+ found = _BUNDLETYPE_RE.search(text, lo, hi)
+ if found is None:
+ checked.append(
+ f"{url}: rendererPackageName found, no bundleType within " f"{_WINDOW} chars of it"
+ )
+ continue
+ bundle_type = int(found.group(1))
+ checked.append(f"{url}: react-dom bundleType={bundle_type}")
+ if bundle_type == 0:
+ return BundleVerdict(
+ production = True,
+ reason = "react-dom reports bundleType 0",
+ vite_client_status = status,
+ bundle_type = 0,
+ entry_url = url,
+ entry_bytes = len(raw),
+ checked = checked,
+ )
+ return BundleVerdict(
+ production = False,
+ reason = (
+ f"react-dom reports bundleType {bundle_type}, which is a DEVELOPMENT build "
+ "of React. Its per-render bookkeeping inflates the axis under "
+ "investigation by about 3.2x."
+ ),
+ vite_client_status = status,
+ bundle_type = bundle_type,
+ entry_url = url,
+ entry_bytes = len(raw),
+ checked = checked,
+ )
+
+ return BundleVerdict(
+ production = False,
+ reason = (
+ 'no asset carried a `rendererPackageName: "react-dom"` marker, so the build '
+ "mode could not be established. Refusing rather than assuming production."
+ ),
+ vite_client_status = status,
+ checked = checked,
+ )
diff --git a/tests/studio/studiobench/runtime/lifecycle.py b/tests/studio/studiobench/runtime/lifecycle.py
new file mode 100644
index 00000000000..8daa3fbd0fd
--- /dev/null
+++ b/tests/studio/studiobench/runtime/lifecycle.py
@@ -0,0 +1,791 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Install, launch and authenticate a real Studio. VENDORED from `studio_test_kit`.
+
+Vendored on purpose. The shipped artifact is a single `studiobench.pyz` a tester runs on a machine
+that has a Studio and nothing else, so it cannot import a module that lives elsewhere in this
+repository. The logic is `studio_test_kit.lifecycle` plus `studio_test_kit.auth`, with two
+deliberate changes:
+
+- **stdlib only.** `studio_test_kit.auth` uses `httpx`; this uses `urllib.request`, so `--doctor`
+ and `--attach` work on a machine with nothing pip-installed but Playwright.
+- **The password-change gate is handled.** A current Studio mints a bootstrap password and sets
+ `must_change_password`, and until it is cleared EVERY authenticated route answers
+ `403 Password change required` while `/healthz` answers 200 and login itself succeeds. That
+ failure is silent one request too late, and it is what stops a thread from being seeded at all.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import shlex
+import shutil
+import signal
+import socket
+import subprocess
+import time
+import urllib.error
+import urllib.request
+import uuid
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Callable, Optional
+
+
+@dataclass
+class StudioInstall:
+ home: Path
+ repo: Path
+ branch: str
+ bootstrap_password: Optional[str] = None
+ port: Optional[int] = None
+ pid: Optional[int] = None
+ #: The commit `branch` RESOLVED TO, which is the build that was installed. `branch` is what
+ #: the caller typed, and a branch or a movable tag is not a build. See
+ #: `__main__.commit_problems`.
+ commit: Optional[str] = None
+
+ @property
+ def base_url(self) -> str:
+ return f"http://127.0.0.1:{self.port}"
+
+
+#: What the backend gives an access token: `auth/authentication.py`, ACCESS_TOKEN_EXPIRE_MINUTES.
+#: Only a FALLBACK. The expiry actually enforced is the `exp` claim in the token this run was
+#: handed, which is read from the token itself; this number is what to assume when the server
+#: hands back something that is not a readable JWT.
+ACCESS_TOKEN_TTL_S = 60 * 60
+#: How far ahead of `exp` a token is replaced. Seeding a 1M-token thread is ONE request with a
+#: 900 second timeout, so a token that is merely valid at the moment the request is written is not
+#: good enough: it has to still be valid when the server finishes reading the body.
+TOKEN_REFRESH_MARGIN_S = 15 * 60
+
+
+def jwt_expiry(token: str) -> Optional[float]:
+ """The `exp` claim of a JWT, in unix seconds, WITHOUT verifying anything.
+
+ This is not authentication, it is a clock: the harness holds a token the server issued and
+ needs to know when the server will stop accepting it. Verification is the server's job and it
+ does it on every request. Anything unreadable returns None and the caller falls back to
+ `ACCESS_TOKEN_TTL_S`.
+ """
+ try:
+ payload = token.split(".")[1]
+ payload += "=" * (-len(payload) % 4)
+ claims = json.loads(base64.urlsafe_b64decode(payload.encode("ascii")).decode("utf-8"))
+ exp = claims.get("exp")
+ return float(exp) if exp is not None else None
+ except Exception: # noqa: BLE001
+ return None
+
+
+@dataclass
+class StudioAuth:
+ """The harness's own credentials, WHICH OUTLIVE THE TOKEN THEY WERE HANDED.
+
+ THE RUN IS LONGER THAN THE TOKEN. An access token is good for one hour
+ (`ACCESS_TOKEN_EXPIRE_MINUTES = 60`) and this harness authenticated once per arm, at setup,
+ before the first install. A standard A/B at four repetitions is 24 films of 243 seconds --
+ 97 minutes of cells alone, before seeding, calibration and two installs -- so the token the
+ seeder holds expires PART WAY THROUGH, and every request after that answers 401: the next
+ `create_thread` fails and the cell dies. In the browser it is worse than an error, because the
+ SPA's own 401 path clears its tokens and navigates to the login route, which reaches Playwright
+ as `Execution context was destroyed, most likely because of a navigation` -- the exact shape of
+ a flake, arriving on a schedule.
+
+ So the token is REPLACED BEFORE IT EXPIRES rather than after it fails. `token()` is what every
+ authenticated request asks for and it re-authenticates whenever `exp` is inside
+ `TOKEN_REFRESH_MARGIN_S`; `auth_request_json` additionally recovers from a 401 that arrives
+ anyway, because a clock skew between this process and the server is exactly the case a
+ deadline computed here cannot see.
+
+ RE-LOGIN, NOT REFRESH, and the difference matters. `POST /api/auth/refresh` is SINGLE USE
+ (`storage.consume_refresh_token`) and the refresh token this object holds is the same one the
+ page was seeded with. Spending it here would invalidate the copy in the SPA's localStorage and
+ log the page out to fix the harness -- trading this defect for itself. A password login mints a
+ fresh pair and touches nothing the page owns.
+ """
+
+ access_token: str
+ refresh_token: str
+ base_url: str
+ username: str
+ password: str
+ #: Unix seconds, from the token's own `exp`. None means "unknown", treated as `ACCESS_TOKEN_TTL_S`
+ #: from the moment this object was built.
+ expires_at: Optional[float] = None
+ #: Called with `self` after the token is replaced. The browser context seeds its localStorage
+ #: from a SNAPSHOT of these values, so whoever owns that context re-seeds it here.
+ on_rotate: Optional[Callable[["StudioAuth"], None]] = None
+ rotations: int = field(default = 0, init = False)
+ #: Turned off the first time a FRESH token still reads as expiring, which means the `exp` this
+ #: process reads and the server's own clock do not agree. See `rotate`.
+ proactive: bool = field(default = True, init = False)
+ #: The last `on_rotate` failure, kept rather than raised. See `rotate`.
+ hook_error: Optional[str] = field(default = None, init = False)
+
+ def __post_init__(self) -> None:
+ if self.expires_at is None:
+ self.expires_at = jwt_expiry(self.access_token) or (time.time() + ACCESS_TOKEN_TTL_S)
+
+ def seconds_left(self) -> float:
+ return float(self.expires_at or 0) - time.time()
+
+ def needs_refresh(self, margin_s: Optional[float] = None) -> bool:
+ margin = TOKEN_REFRESH_MARGIN_S if margin_s is None else margin_s
+ return self.seconds_left() <= margin
+
+ def token(self, margin_s: Optional[float] = None) -> str:
+ """The access token to send, re-minted first if it is close to expiring."""
+ if self.proactive and self.needs_refresh(margin_s):
+ self.rotate()
+ return self.access_token
+
+ def rotate(self) -> str:
+ """Log in again and adopt the new pair. Raises if the server will not have us.
+
+ The password is the one THIS harness rotated to (`authenticate` clears the
+ password-change gate up front), so there is a credential to log in with for as long as the
+ run lasts.
+
+ A FRESH TOKEN THAT IS ALREADY INSIDE THE MARGIN TURNS THE PROACTIVE HALF OFF, and this is
+ the guard against the one way "refresh before `exp`" can run away. `needs_refresh` compares
+ the server's `exp` against THIS PROCESS'S clock, and the two are not required to agree: a
+ Studio running 45 minutes behind, or a deployment that shortens
+ `ACCESS_TOKEN_EXPIRE_MINUTES` below the margin, makes every token ever issued look like it
+ is about to expire. Without this, every single request would log in again and append
+ another init script to the browser context for the rest of the run. So the condition is
+ tested against a token known to be one second old: if even that one is inside the margin,
+ the margin is not usable here and the token is left to `auth_request_json`'s 401 recovery,
+ which asks the server rather than the clock.
+
+ THE HOOK CANNOT FAIL THE CREDENTIAL. `on_rotate` re-seeds a Playwright context, which can
+ throw for reasons that have nothing to do with authentication -- a closed context, a page
+ that crashed. The token has already been replaced by then and the caller's request must go
+ out; the failure is recorded on `hook_error` instead of being raised through a function
+ whose job was to hold a credential.
+ """
+ fresh = login(self.base_url, self.username, self.password)
+ self.access_token = fresh.access_token
+ self.refresh_token = fresh.refresh_token or self.refresh_token
+ self.expires_at = fresh.expires_at
+ self.rotations += 1
+ if self.needs_refresh():
+ self.proactive = False
+ if self.on_rotate is not None:
+ try:
+ self.on_rotate(self)
+ except Exception as exc: # noqa: BLE001
+ self.hook_error = f"{type(exc).__name__}: {exc}"
+ return self.access_token
+
+
+def auth_request_json(
+ auth: StudioAuth,
+ url: str,
+ *,
+ method: str = "GET",
+ body: Optional[dict] = None,
+ timeout: float = 30.0,
+) -> Any:
+ """`request_json` with credentials that survive a long run: refreshed BEFORE `exp`, and
+ re-minted once more if the server rejects the token anyway.
+
+ Both halves are needed. The proactive half is what keeps a 900 second seeding PUT from dying
+ half way through a request that was valid when it started. The reactive half covers what this
+ process cannot compute: a clock offset against the server, a Studio restarted underneath the
+ run, or a token invalidated by something else. One retry only -- a 401 that survives a fresh
+ login is a real refusal and must be raised, not looped on.
+
+ The token is fetched OUTSIDE the `try`, so a 401 raised by the login inside `token()` is not
+ mistaken for a 401 from this request and answered with a second login. The backend locks an
+ account out after five failures in a minute (`routes/auth.py`, `_LOGIN_MAX_FAILS`), so a wrong
+ credential retried at double rate reaches the lockout twice as fast and the run then dies on a
+ 429 that says nothing about the password.
+ """
+ bearer = auth.token()
+ try:
+ return request_json(url, method = method, body = body, token = bearer, timeout = timeout)
+ except HttpError as exc:
+ if exc.status != 401:
+ raise
+ auth.rotate()
+ return request_json(url, method = method, body = body, token = auth.access_token, timeout = timeout)
+
+
+@dataclass
+class ProviderSeed:
+ """One external provider entry for the SPA's localStorage.
+
+ `provider_type` is **"custom"**, not "openai", and the difference decides whether this
+ benchmark measures anything. The backend routes `openai` to `/v1/responses`; `custom` is the
+ generic OpenAI-compatible entry and is routed to `{base_url}/chat/completions` with the body
+ relayed and the SSE lines forwarded verbatim, which is the path a real llama.cpp, vLLM or
+ Ollama server takes and the only one that puts our own event stream in front of the app's
+ parser.
+ """
+
+ provider_type: str
+ name: str
+ base_url: str
+ models: list[str]
+ api_key: str
+ id: str = field(default_factory = lambda: uuid.uuid4().hex[:16])
+
+ def as_provider_entry(self) -> dict:
+ return {
+ "id": self.id,
+ "providerType": self.provider_type,
+ "name": self.name,
+ "baseUrl": self.base_url,
+ "models": list(self.models),
+ }
+
+
+def pacer_provider(
+ base_url: str,
+ models: list[str],
+ api_key: str = "sb-local",
+) -> ProviderSeed:
+ return ProviderSeed(
+ provider_type = "custom",
+ name = "studiobench pacer",
+ base_url = base_url,
+ models = models,
+ api_key = api_key,
+ )
+
+
+def register_provider(base_url: str, auth: StudioAuth, provider: ProviderSeed) -> str:
+ """Create the provider in the BACKEND and return the id IT assigned.
+
+ LOCALSTORAGE SEEDING ALONE IS NOT ENOUGH ON A CURRENT STUDIO, and this is the second half of
+ the reason nothing was ever generated. `studio_test_kit.auth` seeds three localStorage keys and
+ its docstring says that is sufficient to drive any external provider end to end. It was; it is
+ not now. The provider list the SPA validates a selection against comes from
+ `GET /api/providers/`, so with a provider only in localStorage the model picker renders the
+ model with the label "No longer offered" and pressing send throws `Connection not found`
+ before any request is made. Both symptoms were observed directly against a shipped build.
+
+ So the provider is created over REST and the id the BACKEND assigns is what the selection
+ checkpoint must name. A client-generated id would not be found either.
+
+ No API key is sent. For `custom` the backend omits the Authorization header entirely when the
+ key is empty, which is what a local llama.cpp or vLLM server expects, and it saves this
+ harness from having to RSA-encrypt a dummy secret against the server's published public key
+ just to have it ignored.
+ """
+ existing = auth_request_json(auth, f"{base_url.rstrip('/')}/api/providers/") or []
+ for row in existing:
+ # Idempotent across runs. Every run binds a NEW ephemeral pacer port, so a stale entry
+ # from a previous run points at a port nothing is listening on, and leaving it there gives
+ # the picker two identically named models of which one is dead.
+ if row.get("display_name") == provider.name:
+ try:
+ auth_request_json(
+ auth,
+ f"{base_url.rstrip('/')}/api/providers/{row['id']}",
+ method = "DELETE",
+ )
+ except HttpError:
+ pass
+ created = auth_request_json(
+ auth,
+ f"{base_url.rstrip('/')}/api/providers/",
+ method = "POST",
+ body = {
+ "provider_type": provider.provider_type,
+ "display_name": provider.name,
+ "base_url": provider.base_url,
+ "models": list(provider.models),
+ "available_models": list(provider.models),
+ },
+ )
+ provider.id = created["id"]
+ return created["id"]
+
+
+def external_checkpoint_id(provider: ProviderSeed, model_id: str) -> str:
+ """The app's own id for "this model, on this external provider".
+
+ SEEDING THE PROVIDER IS NOT ENOUGH, and this is the difference between a benchmark and a page
+ that does nothing. With the provider seeded but no model SELECTED, the composer accepts text,
+ the send button is enabled, the message is stored to the thread -- and no completion request
+ is ever made. Measured: the first end-to-end run finished every action, reported nine of
+ sixteen ran, and recorded an assistant message with zero characters, because the reply that
+ was supposed to be measured was never asked for. The pacer's request log was empty, which is
+ the only reason it was caught.
+
+ `chat-runtime-store.ts` restores the selection from
+ `unsloth_chat_last_external_checkpoint`, in the format `buildExternalModelId` produces.
+ """
+ from urllib.parse import quote
+ return f"external::{provider.id}::{quote(model_id, safe = '')}"
+
+
+# ── HTTP, stdlib ────────────────────────────────────────────────────
+
+
+class HttpError(RuntimeError):
+ def __init__(self, status: int, body: str, url: str) -> None:
+ super().__init__(f"HTTP {status} from {url}: {body[:400]}")
+ self.status = status
+ self.body = body
+ self.url = url
+
+
+def request_json(
+ url: str,
+ *,
+ method: str = "GET",
+ body: Optional[dict] = None,
+ token: Optional[str] = None,
+ timeout: float = 30.0,
+) -> Any:
+ data = None if body is None else json.dumps(body).encode("utf-8")
+ headers = {"Accept": "application/json"}
+ if data is not None:
+ headers["Content-Type"] = "application/json"
+ if token:
+ headers["Authorization"] = f"Bearer {token}"
+ req = urllib.request.Request(url, data = data, headers = headers, method = method)
+ try:
+ with urllib.request.urlopen(req, timeout = timeout) as r:
+ raw = r.read().decode("utf-8")
+ except urllib.error.HTTPError as exc:
+ raise HttpError(exc.code, exc.read().decode("utf-8", "replace"), url) from exc
+ return json.loads(raw) if raw.strip() else None
+
+
+def wait_for_healthz(base_url: str, timeout_s: float = 180.0) -> bool:
+ deadline = time.time() + timeout_s
+ while time.time() < deadline:
+ try:
+ with urllib.request.urlopen(f"{base_url}/healthz", timeout = 3) as r:
+ if r.status == 200:
+ return True
+ except Exception: # noqa: BLE001
+ pass
+ time.sleep(1)
+ return False
+
+
+# ── install and launch ──────────────────────────────────────────────
+
+
+def _run(
+ cmd: list[str],
+ cwd: Optional[Path] = None,
+ env: Optional[dict] = None,
+ check: bool = True,
+ timeout: Optional[int] = None,
+) -> subprocess.CompletedProcess:
+ return subprocess.run(
+ cmd,
+ cwd = cwd,
+ env = {**os.environ, **(env or {})},
+ check = check,
+ timeout = timeout,
+ text = True,
+ capture_output = True,
+ )
+
+
+def checkout_ref(repo: Path, ref: str) -> str:
+ """Put `repo` on `ref`, whatever kind of ref it is. Returns the commit checked out.
+
+ NOT `git clone --branch <ref>` AND NOT `reset --hard origin/<ref>`. `--branch` resolves against
+ the remote's advertised branches and tags -- `git clone -h` calls it "checkout <branch> instead
+ of the remote's HEAD" -- so a commit sha fails with `Remote branch <sha> not found in upstream
+ origin` before anything is installed, and `origin/<sha>` is not a name that exists either.
+ CONTRIBUTING-perf.md asks for exactly that ref: a change that has already merged is measured as
+ `merge commit` against `merge commit^1`, and neither of those is a branch.
+
+ So the ref is fetched and then resolved locally: `FETCH_HEAD` when the fetch could name it,
+ `origin/<ref>` when it is a branch, and the ref itself when it is already an object here.
+ """
+ fetched = _run(["git", "fetch", "--tags", "origin", ref], cwd = repo, check = False)
+ if fetched.returncode != 0:
+ # A ref the remote will not serve by name (an old server, or `ref^1`, which is a local
+ # expression rather than something to ask for). Fetch everything and resolve it here.
+ _run(["git", "fetch", "--tags", "origin"], cwd = repo, check = False)
+ candidates = [] if fetched.returncode != 0 else ["FETCH_HEAD"]
+ candidates += [f"origin/{ref}", ref]
+ for candidate in candidates:
+ got = _run(
+ ["git", "rev-parse", "--verify", "--quiet", f"{candidate}^{{commit}}"],
+ cwd = repo,
+ check = False,
+ )
+ commit = got.stdout.strip()
+ if got.returncode == 0 and commit:
+ _run(["git", "checkout", "--force", "--detach", commit], cwd = repo)
+ _run(["git", "reset", "--hard", commit], cwd = repo)
+ return commit
+ raise RuntimeError(
+ f"{ref!r} could not be resolved in {repo}: it is not a branch, a tag or a commit this "
+ "remote will serve"
+ )
+
+
+#: What `install.sh` is allowed. A multi-gigabyte download and build, documented in the README as
+#: "budgeted at up to 45 minutes" and explicitly NOT part of a tier's wall clock. Named rather
+#: than inlined because the run's watchdog has to add it to a deadline it would otherwise fire in
+#: the middle of: see `watchdog_deadline_s`.
+INSTALL_TIMEOUT_S = 60 * 45
+
+
+def install_studio(
+ branch: str,
+ home: Path,
+ repo: Optional[Path] = None,
+ remote: str = "https://github.com/unslothai/unsloth",
+ reuse_clone: bool = True,
+) -> StudioInstall:
+ home = Path(home).resolve()
+ home.mkdir(parents = True, exist_ok = True)
+ repo = (repo or (home.parent / f"{home.name}_repo")).resolve()
+ if not (reuse_clone and (repo / ".git").exists()):
+ if repo.exists():
+ shutil.rmtree(repo)
+ # Cloned WITHOUT `--branch`, then moved onto the ref locally, so one code path serves a
+ # branch, a tag and a commit sha instead of two that disagree about what a ref is.
+ _run(["git", "clone", remote, str(repo)])
+ # KEPT, not discarded. `checkout_ref` is the only place that knows which commit a ref names,
+ # and the ref alone cannot tell a resumed run that `main` moved underneath it.
+ commit = checkout_ref(repo, branch)
+ install_sh = repo / "install.sh"
+ if not install_sh.exists():
+ raise FileNotFoundError(f"install.sh missing at {install_sh}")
+ _run(
+ ["bash", str(install_sh), "--local"],
+ cwd = repo,
+ env = {"UNSLOTH_STUDIO_HOME": str(home)},
+ timeout = INSTALL_TIMEOUT_S,
+ )
+ return StudioInstall(home = home, repo = repo, branch = branch, commit = commit)
+
+
+def _find_unsloth_bin(install: StudioInstall) -> str:
+ for candidate in (
+ install.home / "bin" / "unsloth",
+ install.home / ".venv_t5_550" / "bin" / "unsloth",
+ install.home / ".venv_t5_530" / "bin" / "unsloth",
+ ):
+ if candidate.exists():
+ return str(candidate)
+ for venv in sorted(install.home.glob(".venv*")):
+ candidate = venv / "bin" / "unsloth"
+ if candidate.exists():
+ return str(candidate)
+ raise FileNotFoundError(f"`unsloth` CLI not found under {install.home}")
+
+
+_PW_RE = re.compile(r"(?i)(?:bootstrap|initial|generated)\s*password(?:\s+is)?\s*[:=]?\s+(\S+)")
+
+
+def _read_bootstrap_password(home: Path, log_path: Path, deadline: float) -> Optional[str]:
+ boot_file = home / "auth" / ".bootstrap_password"
+ while time.time() < deadline:
+ try:
+ if boot_file.exists():
+ secret = boot_file.read_text(errors = "ignore").strip()
+ if secret:
+ return secret
+ except OSError:
+ pass
+ if log_path.exists():
+ m = _PW_RE.search(log_path.read_text(errors = "ignore"))
+ if m:
+ return m.group(1).strip().strip(".,")
+ time.sleep(0.5)
+ return None
+
+
+#: How long to keep looking for the launched server's pid. It appears once the server has forked
+#: and exec'd, which is after `setsid -f` has already returned, so this is a poll rather than a
+#: read. Named so a test can set it to zero instead of sleeping through it.
+PID_DISCOVERY_TIMEOUT_S = 15.0
+
+
+def _discover_pid(port: int, timeout_s: Optional[float] = None) -> Optional[int]:
+ """The pid of the Studio serving `port`, or None. Polls, because it appears asynchronously.
+
+ THE PROCESS WE LAUNCHED IS NOT THE PROCESS WE SPAWNED. `launch_studio` runs the server under
+ `setsid -f`, which always forks and lets the parent exit without waiting, so the pid `Popen`
+ returns belongs to a `setsid` that is gone by the time the server binds; the server itself is
+ reparented into a session of its own and cannot be reached through our process group. `pgrep`
+ is the only handle on it, and it can only be taken once the server exists.
+ """
+ if timeout_s is None:
+ timeout_s = PID_DISCOVERY_TIMEOUT_S
+ deadline = time.time() + max(0.0, timeout_s)
+ while True:
+ try:
+ out = _run(["pgrep", "-f", f"unsloth studio.*-p {port}"], check = False).stdout.strip()
+ except Exception: # noqa: BLE001
+ return None
+ if out:
+ try:
+ return int(out.splitlines()[0])
+ except ValueError:
+ return None
+ if time.time() >= deadline:
+ return None
+ time.sleep(0.5)
+
+
+def port_is_busy(
+ port: int,
+ host: str = "127.0.0.1",
+ timeout_s: float = 1.0,
+) -> bool:
+ """Is something already accepting connections on `port`?
+
+ A plain connect, not a bind: the server we are about to launch is DETACHED and binds in a
+ process of its own, so the only question this can answer is whether the port is already
+ somebody's -- and if it is, it will not be ours.
+ """
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
+ sock.settimeout(timeout_s)
+ try:
+ return sock.connect_ex((host, int(port))) == 0
+ except OSError:
+ return False
+
+
+def launch_studio(
+ install: StudioInstall,
+ port: int,
+ log_path: Path,
+ extra_env: Optional[dict] = None,
+ healthz_timeout_s: int = 240,
+ password_timeout_s: int = 30,
+) -> StudioInstall:
+ # AN OCCUPIED PORT IS REFUSED BEFORE ANYTHING IS LAUNCHED, and this is the half of the
+ # abandoned-server failure that no cleanup can reach. `--keep-studio` asks for a Studio to be
+ # LEFT RUNNING on this port, so the next run's `unsloth studio -p <port>` finds one of our own
+ # servers there and aborts rather than binding (`studio/backend/run.py`, `_resolve_port` with
+ # `avoid_own_studio`); when the pid record is not readable it falls back to the NEXT port
+ # instead. Either way nothing this run launched is on `port`.
+ #
+ # Everything downstream then agrees that the launch worked. `_discover_pid` pgreps for
+ # `unsloth studio.*-p <port>` and finds the OLD process; `wait_for_healthz` takes its 200 from
+ # it; and `authenticate` retries with `BENCH_PASSWORD`, which a previous studiobench run has
+ # already rotated that Studio to, so the login succeeds as well. The run then measures the
+ # build the PREVIOUS invocation installed while `run_meta` records the ref this one asked for,
+ # and `stop_studio` kills the server the caller asked to keep. There is no reading anywhere
+ # that says which build answered, so this is refused rather than reported.
+ if port_is_busy(port):
+ holder = _discover_pid(port, 0.0)
+ raise RuntimeError(
+ f"port {port} is already in use"
+ + (f" by Studio pid {holder}" if holder else "")
+ + ". A Studio launched here would abort or land on another port while this harness "
+ "measured whatever is already answering. Stop it (`unsloth studio stop`, or the "
+ "Studio a previous --keep-studio run left behind) or pass --port."
+ )
+ log_path = Path(log_path).resolve()
+ log_path.parent.mkdir(parents = True, exist_ok = True)
+ log_path.write_text("")
+ bin_path = _find_unsloth_bin(install)
+ env = {"UNSLOTH_STUDIO_HOME": str(install.home), **(extra_env or {})}
+ # NOT `UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS=1`: that opt-in SSRF guard rejects any
+ # non-global address, which is exactly what the pacer's 127.0.0.1 base URL is.
+ env.pop("UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS", None)
+ cmd = [
+ "setsid",
+ "-f",
+ "bash",
+ "-c",
+ f"{shlex.quote(bin_path)} studio -p {port} 2>&1 | tee -a {shlex.quote(str(log_path))}",
+ ]
+ subprocess.Popen(
+ cmd,
+ env = {**os.environ, **env},
+ stdout = subprocess.DEVNULL,
+ stderr = subprocess.DEVNULL,
+ start_new_session = True,
+ )
+ install.port = port
+ install.bootstrap_password = _read_bootstrap_password(
+ install.home, log_path, time.time() + password_timeout_s
+ )
+ # BEFORE the health check, not after it. A Studio that starts and stays unhealthy used to raise
+ # here with `install.pid` still None, and `stop_studio` has nothing to kill without it -- so the
+ # detached server was left running on the requested port while the CLI unwound. It is not idle
+ # there: the next attempt's `unsloth studio -p <port>` finds one of our own servers on the port
+ # and aborts rather than binding (`run.py:_resolve_port`, `avoid_own_studio`), while
+ # `wait_for_healthz` gets its 200 from the STALE process -- which by then may have finished
+ # starting. That run measures the build the previous attempt installed and records the ref this
+ # one asked for, which is the one failure this harness may never produce quietly.
+ install.pid = _discover_pid(port)
+ healthy = wait_for_healthz(install.base_url, healthz_timeout_s)
+ if install.pid is None:
+ # One more look: a server slow enough to miss the window above is exactly the one whose
+ # health check just timed out, and it is the one that most needs to be terminated.
+ install.pid = _discover_pid(port, 0.0)
+ if not healthy:
+ stop_studio(install)
+ raise TimeoutError(f"Studio on :{port} did not pass /healthz within {healthz_timeout_s}s")
+ return install
+
+
+def stop_studio(install: StudioInstall) -> None:
+ if install.pid:
+ try:
+ os.killpg(os.getpgid(install.pid), signal.SIGTERM)
+ except Exception: # noqa: BLE001
+ pass
+
+
+# ── auth ────────────────────────────────────────────────────────────
+
+BENCH_PASSWORD = "studiobench-Passw0rd!"
+
+
+def login(base_url: str, username: str, password: str) -> StudioAuth:
+ body = request_json(
+ f"{base_url}/api/auth/login",
+ method = "POST",
+ body = {"username": username, "password": password},
+ )
+ return StudioAuth(
+ access_token = body["access_token"],
+ refresh_token = body.get("refresh_token", ""),
+ base_url = base_url,
+ username = username,
+ password = password,
+ expires_at = jwt_expiry(body["access_token"]),
+ )
+
+
+def authenticate(
+ base_url: str,
+ username: str,
+ password: str,
+ new_password: str = BENCH_PASSWORD,
+) -> StudioAuth:
+ """Log in and CLEAR the password-change gate if it is set.
+
+ Not optional and not cosmetic. When `must_change_password` is set, login succeeds and returns
+ a token, `/healthz` answers 200, and every route this harness needs -- create a thread, seed
+ its messages, read them back -- answers `403 Password change required`. Nothing announces it;
+ the run simply fails to seed a thread and reports an empty one. So the gate is read from
+ `/api/auth/status` up front and cleared through the one endpoint that accepts the gated token.
+ """
+ # Try the supplied password, then the one a PREVIOUS studiobench run rotated to. Studio mints
+ # a bootstrap password and demands it be changed; this function is what changes it, so the
+ # second run against the same home is handed a bootstrap password that no longer exists and
+ # gets a 401 whose message sends you to `reset-password`. Measured on the second run against
+ # a home the first run had already set up. Trying both makes reruns and `--resume` work.
+ attempts = [password, new_password] if password != new_password else [password]
+ auth = None
+ last: Optional[Exception] = None
+ for candidate in attempts:
+ if not candidate:
+ continue
+ try:
+ auth = login(base_url, username, candidate)
+ password = candidate
+ break
+ except HttpError as exc:
+ if exc.status != 401:
+ raise
+ last = exc
+ if auth is None:
+ raise RuntimeError(
+ f"could not log in as {username!r} with the supplied password or with the password a "
+ f"previous studiobench run would have rotated to. Last error: {last}"
+ )
+ try:
+ status = request_json(f"{base_url}/api/auth/status", token = auth.access_token) or {}
+ except HttpError:
+ status = {}
+ if status.get("requires_password_change"):
+ body = request_json(
+ f"{base_url}/api/auth/change-password",
+ method = "POST",
+ token = auth.access_token,
+ body = {"current_password": password, "new_password": new_password},
+ )
+ auth = StudioAuth(
+ access_token = body["access_token"],
+ refresh_token = body.get("refresh_token", ""),
+ base_url = base_url,
+ username = username,
+ password = new_password,
+ expires_at = jwt_expiry(body["access_token"]),
+ )
+ return auth
+
+
+def seed_init_script(
+ auth: StudioAuth,
+ providers: list[ProviderSeed],
+ extra_local_storage: Optional[dict] = None,
+) -> str:
+ """localStorage the SPA reads on its FIRST paint, so it boots already logged in and already
+ holding the provider. The plaintext key is RSA-encrypted by the SPA per request against the
+ server's published public key, so seeding it plainly here is the supported path.
+
+ THE REFRESH TOKEN GOES UNDER THE KEY THE APP READS, which is
+ `unsloth_auth_refresh_token` (`features/auth/session.ts`, `AUTH_REFRESH_TOKEN_KEY`) and not
+ `unsloth_refresh_token`, which nothing in the frontend has ever read. Seeded under the wrong
+ name the page boots with an access token and NO way to renew it, so one hour in --
+ `ACCESS_TOKEN_EXPIRE_MINUTES = 60`, shorter than a standard A/B -- the first request to answer
+ 401 takes `authFetch` down the branch that clears the tokens and navigates to the login route.
+ Playwright reports that as `Execution context was destroyed, most likely because of a
+ navigation`, which reads as a flake and is not one: it is the clock. With the right key the
+ SPA rotates its own pair through `POST /api/auth/refresh` and the film carries on.
+
+ That endpoint is SINGLE USE, which is why the harness re-authenticates by password instead of
+ spending this token itself -- see `StudioAuth`. This copy belongs to the page.
+
+ AND THE AUTH KEYS ARE WRITTEN ONLY BY THE FRESHEST WRITER. An init script is a snapshot that
+ re-runs on EVERY navigation, and there is one navigation per cell, so a script carrying the
+ token this run started with would keep putting it back over whatever the SPA had rotated to.
+ The harness re-seeds after `StudioAuth.rotate`, but Playwright says outright that "the order of
+ evaluation of multiple scripts installed via browser_context.add_init_script() and
+ page.add_init_script() is not defined", so "the newest one was added last" decides nothing.
+ Each script therefore compares its own token's `exp` against the one already in storage and
+ writes only if it is carrying the later one. That converges on the freshest token whatever
+ order they run in, which is the only property worth having here.
+ """
+ auth_payload = {
+ "unsloth_auth_token": auth.access_token,
+ "unsloth_auth_refresh_token": auth.refresh_token,
+ }
+ payload = {
+ "unsloth_chat_external_providers": json.dumps([p.as_provider_entry() for p in providers]),
+ "unsloth_chat_external_provider_keys": json.dumps(
+ {p.id: p.api_key for p in providers if p.api_key}
+ ),
+ "unsloth_chat_connections_enabled": "true",
+ }
+ for k, v in (extra_local_storage or {}).items():
+ payload[k] = v if isinstance(v, str) else json.dumps(v)
+ # `exp` out of an unverified JWT payload, base64url with the padding this token does not carry.
+ # Anything unreadable scores 0, so a token nobody can date never displaces one that can be.
+ exp_of = (
+ "const expOf = (t) => { try { let p = String(t).split('.')[1]"
+ ".replace(/-/g, '+').replace(/_/g, '/'); while (p.length % 4) p += '='; "
+ "return Number(JSON.parse(window.atob(p)).exp) || 0; } catch (e) { return 0; } };"
+ )
+ return (
+ "(() => { const seed = "
+ + json.dumps(payload)
+ + "; for (const k of Object.keys(seed)) { try { window.localStorage.setItem(k, seed[k]);"
+ " } catch (e) {} } const auth = "
+ + json.dumps(auth_payload)
+ + "; "
+ + exp_of
+ + " try { const held = window.localStorage.getItem('unsloth_auth_token');"
+ " if (!held || expOf(held) < expOf(auth['unsloth_auth_token'])) {"
+ " for (const k of Object.keys(auth)) window.localStorage.setItem(k, auth[k]); }"
+ " } catch (e) {} })();"
+ )
diff --git a/tests/studio/studiobench/runtime/resources.py b/tests/studio/studiobench/runtime/resources.py
new file mode 100644
index 00000000000..fd296798880
--- /dev/null
+++ b/tests/studio/studiobench/runtime/resources.py
@@ -0,0 +1,63 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Read packaged data whether the package is a directory or inside a zipapp.
+
+`Path(__file__).parent / "thing.js"` works in a checkout and returns a path that does not exist
+inside `studiobench.pyz`, because a zipapp's contents are not on the filesystem. Caught by running
+the built artifact's own `--doctor`, which reported the frozen corpus missing at a path ending
+`studiobench.pyz/tests/studio/studiobench/fixture/corpus/frozen/manifest.json` -- a path that can
+never exist. Every packaged file this tool reads at run time goes through here.
+
+The filesystem is tried FIRST, so a checkout run picks up an edit to a .js file without a
+reinstall, which is most of what makes the JS pleasant to work on.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Optional
+
+PACKAGE = "tests.studio.studiobench"
+
+
+def read_bytes(relative: str) -> bytes:
+ """`relative` is a POSIX path under the studiobench package, e.g. `scene/dom.js`."""
+ direct = Path(__file__).resolve().parents[1] / relative
+ if direct.exists():
+ return direct.read_bytes()
+ from importlib.resources import files
+
+ resource = files(PACKAGE)
+ for part in relative.split("/"):
+ resource = resource.joinpath(part)
+ return resource.read_bytes()
+
+
+def read_text(relative: str) -> str:
+ return read_bytes(relative).decode("utf-8")
+
+
+def exists(relative: str) -> bool:
+ try:
+ read_bytes(relative)
+ return True
+ except (FileNotFoundError, OSError, ModuleNotFoundError):
+ return False
+
+
+def iter_lines(relative: str):
+ for line in read_text(relative).splitlines():
+ if line.strip():
+ yield line
+
+
+def writable_dir(preferred: Optional[Path] = None) -> Path:
+ """A directory the tool may WRITE to, which is never inside the package.
+
+ A zipapp is read-only, and a checkout may be. Anything the tool produces belongs in the run's
+ output directory, not next to its own source.
+ """
+ target = Path(preferred) if preferred else Path.cwd() / "studiobench-out"
+ target.mkdir(parents = True, exist_ok = True)
+ return target
diff --git a/tests/studio/studiobench/runtime/seeder.py b/tests/studio/studiobench/runtime/seeder.py
new file mode 100644
index 00000000000..8824034fa01
--- /dev/null
+++ b/tests/studio/studiobench/runtime/seeder.py
@@ -0,0 +1,351 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Seed a thread's bulk mass over REST, and check that seeding is equivalent to streaming.
+
+WHY SEED AT ALL. At the field's own cadence -- 24 characters every 73 milliseconds -- a million
+tokens is three and a half hours of streaming. A benchmark nobody can run measures nothing, so all
+but the last turn is written straight into the store with
+`PUT /api/chat/threads/{id}/messages`, and only the last reply streams.
+
+WHY THE EQUIVALENCE IS CHECKED AND NOT ASSUMED. Seeding takes a different path into the app, and
+reading the shipped code says it is a MATERIALLY different one. A streamed reply arrives as
+`delta.reasoning_content`, is wrapped into `<think>...</think>`, appended to a cumulative buffer,
+and `parseAssistantContent(cumulativeText)` re-parses the whole growing buffer on every delta. Only
+at the end is the parsed parts array persisted. A seeded reply skips all of that: it is written as
+the finished parts array and loaded straight into the runtime, and `<think>` in a stored text part
+is NOT re-parsed on load, because parsing happens only during streaming.
+
+So the two paths should converge on the same DOM and may not. The check is run at the 10K rung,
+where both are affordable, and it compares what the app actually built: the message count, the
+assistant character count, the highlight span count, the reasoning pane count. Rungs above 10K are
+labelled `fidelity: seeded_only` when it fails. That is 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 there.
+"""
+
+from __future__ import annotations
+
+import time
+import uuid
+from dataclasses import dataclass, field
+from typing import Any, Callable, Optional
+
+from ..fixture.corpus import RungPlan, Unit
+from .lifecycle import StudioAuth, auth_request_json
+
+# How close the two paths must land to count as equivalent. Not zero: a streamed reply carries a
+# usage record and a duration the seeded one does not, and the composer state differs, so a
+# handful of elements always differ. 2% on the quantities that scale with content.
+EQUIVALENCE_TOLERANCE = 0.02
+
+
+def _now_ms() -> int:
+ return int(time.time() * 1000)
+
+
+def _assistant_content(unit: Unit) -> list[dict]:
+ """The stored parts array for an assistant turn.
+
+ A `{"type": "reasoning"}` PART, not `reasoning_content` and not `<think>` inside a text part.
+ There is no reasoning_content column on a stored message, and a text part containing `<think>`
+ is not re-parsed when the thread is loaded, so it would render as literal angle brackets in
+ the visible answer -- a thread that looks wrong and measures the wrong DOM.
+ """
+ parts: list[dict] = []
+ if unit.reasoning:
+ parts.append({"type": "reasoning", "text": unit.reasoning})
+ # Tool calls sit BETWEEN the reasoning and the answer, which is where a real turn puts them:
+ # the model thinks, calls tools, then answers. reasoning.tsx groups adjacent tool-call parts
+ # with the reasoning above them, so the order decides whether a tool group renders inside the
+ # collapsible pane or as its own block, and those are different components with different
+ # costs.
+ for call in unit.tool_calls:
+ parts.append(dict(call))
+ if unit.content:
+ parts.append({"type": "text", "text": unit.content})
+ return parts
+
+
+@dataclass
+class SeededThread:
+ thread_id: str
+ messages: int
+ seeded_chars: int
+ seconds: float
+ turns: int
+
+
+@dataclass
+class Seeder:
+ base_url: str
+ auth: StudioAuth
+ model_id: str
+ log: Callable[[str], None] = print
+ # Messages per PUT. The route replaces the whole message list in one SQLite transaction, so a
+ # 1M-token thread is one enormous request; it is sent whole because a partial PUT with
+ # pruneMissing would delete everything not in the batch.
+ batch_note: str = field(default = "one transaction, pruneMissing", init = False)
+
+ def _url(self, path: str) -> str:
+ return f"{self.base_url.rstrip('/')}{path}"
+
+ def create_thread(self, title: str = "studiobench") -> str:
+ thread_id = str(uuid.uuid4())
+ # `auth_request_json`, not `request_json`, and that is not a spelling preference: the
+ # seeder is asked for a thread once per cell for as long as the run lasts, and an access
+ # token is good for 60 minutes. See `StudioAuth`: the token is re-minted before it expires
+ # and once more if a 401 arrives anyway.
+ auth_request_json(
+ self.auth,
+ self._url("/api/chat/threads"),
+ method = "POST",
+ timeout = 60,
+ body = {
+ "id": thread_id,
+ "title": title,
+ "modelType": "base",
+ "modelId": self.model_id,
+ "createdAt": _now_ms(),
+ },
+ )
+ return thread_id
+
+ def seed(
+ self,
+ plan: RungPlan,
+ thread_id: Optional[str] = None,
+ ) -> SeededThread:
+ """Write every unit except the streamed one into the thread, as user/assistant pairs."""
+ thread_id = thread_id or self.create_thread()
+ messages: list[dict] = []
+ created = _now_ms() - len(plan.seeded_units) * 2000
+ parent: Optional[str] = None
+ for i, unit in enumerate(plan.seeded_units):
+ user_id = str(uuid.uuid4())
+ messages.append(
+ {
+ "id": user_id,
+ "threadId": thread_id,
+ "parentId": parent,
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": f"studiobench turn {i}: continue with unit {unit.index}",
+ }
+ ],
+ "attachments": None,
+ "metadata": None,
+ "createdAt": created + i * 2000,
+ }
+ )
+ assistant_id = str(uuid.uuid4())
+ messages.append(
+ {
+ "id": assistant_id,
+ "threadId": thread_id,
+ "parentId": user_id,
+ "role": "assistant",
+ "content": _assistant_content(unit),
+ "attachments": None,
+ "metadata": None,
+ "createdAt": created + i * 2000 + 1000,
+ }
+ )
+ parent = assistant_id
+ started = time.monotonic()
+ if messages:
+ # pruneMissing so this REPLACES the thread rather than merging into whatever a
+ # previous cell left behind. A merge would make every rung after the first cumulative.
+ auth_request_json(
+ self.auth,
+ self._url(f"/api/chat/threads/{thread_id}/messages"),
+ method = "PUT",
+ timeout = 900,
+ body = {"messages": messages, "pruneMissing": True},
+ )
+ seconds = time.monotonic() - started
+ self.log(
+ f" seeded {len(messages)} messages ({plan.seeded_chars:,} chars) " f"in {seconds:.1f}s"
+ )
+ return SeededThread(
+ thread_id = thread_id,
+ messages = len(messages),
+ seeded_chars = plan.seeded_chars,
+ seconds = seconds,
+ turns = len(plan.seeded_units),
+ )
+
+ def read_back(self, thread_id: str) -> list[dict]:
+ got = auth_request_json(
+ self.auth,
+ self._url(f"/api/chat/threads/{thread_id}/messages"),
+ timeout = 300,
+ )
+ if isinstance(got, dict):
+ return got.get("messages", [])
+ return got or []
+
+
+# ── the equivalence check ───────────────────────────────────────────
+
+
+def dom_signature(page) -> dict:
+ """What the app BUILT, read from the DOM. The only fair comparison between the two paths."""
+ return page.evaluate("() => window.__sb.dom.counts()")
+
+
+def compare_signatures(
+ streamed: dict,
+ seeded: dict,
+ tolerance: float = EQUIVALENCE_TOLERANCE,
+) -> dict:
+ """Are the two paths equivalent on the quantities that scale with content?
+
+ Element count is compared too but is NOT a gate on its own: a streamed reply leaves a usage
+ record and a "thought for N seconds" label a seeded one has no source for, so a handful of
+ elements legitimately differ and gating on exact equality would fail every time for a reason
+ that has nothing to do with fidelity.
+ """
+ # GATED ON CONTENT, REPORTED ON REASONING.
+ #
+ # A collapsed reasoning pane in a SEEDED thread does not mount its children, while a streamed
+ # one does: it was open while the text arrived, and collapsing afterwards leaves the subtree
+ # in place. Measured directly, the same text carried 1,485 reasoning spans one way and 0 the
+ # other, and open-then-close on the seeded side unmounted them again, so this is not something
+ # seeding can be made to reproduce -- it is a property of how the app builds a thread.
+ #
+ # Gating on total `highlight_spans` therefore asked a question seeding can never pass, and the
+ # answer moved with whatever pane state the film happened to leave behind: two runs of the
+ # same rung reported 2.1% and 36.4% drift. The question worth asking is whether the same text
+ # renders the same CONTENT, which is what these keys are. The reasoning difference is measured
+ # and reported below rather than swept into a pass or a fail.
+ keys = ("assistant_messages", "content_code_blocks", "content_spans", "reasoning_panes")
+ fields: dict = {}
+ equivalent = True
+ for key in keys:
+ a, b = streamed.get(key), seeded.get(key)
+ if a is None or b is None:
+ fields[key] = {
+ "streamed": a,
+ "seeded": b,
+ "within_tolerance": None,
+ "reason": "one side did not report this quantity",
+ }
+ equivalent = False
+ continue
+ biggest = max(abs(a), abs(b), 1)
+ drift = abs(a - b) / biggest
+ ok = drift <= tolerance
+ fields[key] = {"streamed": a, "seeded": b, "drift": round(drift, 4), "within_tolerance": ok}
+ equivalent = equivalent and ok
+ fields["elements"] = {
+ "streamed": streamed.get("elements"),
+ "seeded": seeded.get("elements"),
+ "gating": False,
+ "note": "reported, not gated: a streamed reply carries a usage record "
+ "and a reasoning duration label a seeded one has no source for",
+ }
+ for key, note in (
+ (
+ "reasoning_spans",
+ "reported, not gated: a collapsed reasoning pane mounts its children when the text was "
+ "STREAMED into it and does not when the thread was seeded, so this difference is a "
+ "property of the app and not of the fixture",
+ ),
+ (
+ "highlight_spans",
+ "reported, not gated: the total includes reasoning spans, which the two paths cannot "
+ "agree on; content_spans is the gated quantity",
+ ),
+ (
+ "assistant_chars",
+ "reported, not gated: textContent counts hidden-but-mounted reasoning text, so it "
+ "carries the same asymmetry as reasoning_spans",
+ ),
+ ):
+ a, b = streamed.get(key), seeded.get(key)
+ entry = {"streamed": a, "seeded": b, "gating": False, "note": note}
+ if a is not None and b is not None:
+ entry["drift"] = round(abs(a - b) / max(abs(a), abs(b), 1), 4)
+ fields[key] = entry
+ return {
+ "equivalent": equivalent,
+ "tolerance": tolerance,
+ "fields": fields,
+ "checked_attempted": True,
+ }
+
+
+# ── chars per token ─────────────────────────────────────────────────
+
+
+def measure_chars_per_token(
+ text: str, base_url: str, auth: Optional[StudioAuth], model_id: str
+) -> dict:
+ """The MEASURED characters-per-token of this corpus, never an assumed 4.0.
+
+ The rungs are named in tokens and the corpus is built in characters, so the ratio is the thing
+ that makes the two the same claim. It is measured, in this order, from whatever is available,
+ and the SOURCE is reported with the number so a reader can see which one answered. A run that
+ can only fall back to the whitespace estimate says so, rather than printing a ratio that looks
+ like every other run's.
+ """
+ sample = text[:200_000]
+ if not sample:
+ return {
+ "chars_per_token": None,
+ "source": None,
+ "chars_per_token_attempted": False,
+ "reason": "no text to measure",
+ }
+ try:
+ import tiktoken # type: ignore[import]
+
+ enc = tiktoken.get_encoding("cl100k_base")
+ n = len(enc.encode(sample))
+ return {
+ "chars_per_token": round(len(sample) / max(1, n), 3),
+ "source": "tiktoken/cl100k",
+ "tokens": n,
+ "sample_chars": len(sample),
+ "chars_per_token_attempted": True,
+ }
+ except Exception: # noqa: BLE001
+ pass
+ if auth is not None:
+ try:
+ got = auth_request_json(
+ auth,
+ f"{base_url.rstrip('/')}/api/inference/chat/count_tokens",
+ method = "POST",
+ timeout = 120,
+ body = {"model": model_id, "messages": [{"role": "user", "content": sample}]},
+ )
+ n = (got or {}).get("total_tokens") or (got or {}).get("tokens")
+ if n:
+ return {
+ "chars_per_token": round(len(sample) / n, 3),
+ "source": "studio /api/inference/chat/count_tokens",
+ "tokens": n,
+ "sample_chars": len(sample),
+ "chars_per_token_attempted": True,
+ }
+ except Exception: # noqa: BLE001
+ pass
+ # Last resort, and LABELLED. Counting whitespace-delimited words plus punctuation is a rough
+ # stand-in for a BPE tokeniser and is off by tens of percent on dense code, which is most of
+ # this corpus.
+ words = len(sample.split())
+ punct = sum(1 for c in sample if not c.isalnum() and not c.isspace())
+ est = max(1, words + punct // 2)
+ return {
+ "chars_per_token": round(len(sample) / est, 3),
+ "source": "whitespace-and-punctuation estimate",
+ "tokens": est,
+ "sample_chars": len(sample),
+ "chars_per_token_attempted": True,
+ "reason": "no tokeniser was available; this ratio is an estimate and is off by tens "
+ "of percent on dense code",
+ }
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab.py
new file mode 100644
index 00000000000..ab13a1f4ad3
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab.py
@@ -0,0 +1,83 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for the A/B interleaver.
+
+The balance check is the one worth the most scrutiny: it is a boolean that has to differ between a
+plan where drift cancels and one where it does not, and its first implementation returned True for
+both. A single-rep plan is therefore asserted explicitly rather than left to a parametrisation.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.runtime.ab import ( # noqa: E402
+ Target,
+ interleave,
+ order_is_balanced,
+ origin_scoped,
+)
+from studiobench.runtime.types import Cell # noqa: E402
+
+
+def _cells(reps: int, rung: str = "1K"):
+ return [
+ (Cell(cell_id = f"r{rung}.A0.rep{rep}", rung = rung, rung_tokens = 1000, rep = rep), object())
+ for rep in range(reps)
+ ]
+
+
+def _targets():
+ return [
+ Target(label = "base", ref = "main", base_url = "http://a", seeder = None, runner = None),
+ Target(label = "treatment", ref = "pr", base_url = "http://b", seeder = None, runner = None),
+ ]
+
+
+def test_both_sides_run_for_every_cell():
+ plan = interleave(_cells(2), _targets())
+ assert len(plan) == 4
+ assert {t.label for t, _c, _p in plan} == {"base", "treatment"}
+
+
+def test_the_order_flips_between_reps():
+ plan = interleave(_cells(2), _targets())
+ labels = [t.label for t, _c, _p in plan]
+ assert labels == ["base", "treatment", "treatment", "base"]
+
+
+def test_each_arm_gets_its_own_cell_id():
+ """Two arms sharing a cell_id would collide in the payload and in --resume."""
+ plan = interleave(_cells(1), _targets())
+ ids = [c.cell_id for _t, c, _p in plan]
+ assert len(set(ids)) == len(ids)
+ assert all(t.label in c.cell_id for t, c, _p in plan)
+
+
+def test_two_reps_are_balanced():
+ assert order_is_balanced(interleave(_cells(2), _targets())) is True
+
+
+def test_one_rep_is_NOT_balanced():
+ """The regression that mattered: base always runs first, so nothing cancels."""
+ assert order_is_balanced(interleave(_cells(1), _targets())) is False
+
+
+def test_three_reps_are_not_balanced():
+ assert order_is_balanced(interleave(_cells(3), _targets())) is False
+
+
+def test_a_single_target_is_never_balanced():
+ one = [Target(label = "base", ref = "main", base_url = "http://a", seeder = None, runner = None)]
+ assert order_is_balanced(interleave(_cells(2), one)) is False
+
+
+def test_origin_gate_names_the_exact_origin_and_strips_the_slash():
+ script = origin_scoped("http://127.0.0.1:5401/", "doThing();")
+ assert '"http://127.0.0.1:5401"' in script
+ assert "doThing();" in script
+ assert "return" in script
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_failed_cell_verdict.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_failed_cell_verdict.py
new file mode 100644
index 00000000000..54b12418896
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_failed_cell_verdict.py
@@ -0,0 +1,159 @@
+# 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 FAILED CELL MUST NOT PRODUCE A VERDICT OVER THE PAIRS THAT SURVIVED IT.
+
+`skippable_cells` argues this for an interrupted resume; a failed cell is the same hazard by the
+other road. `CellRunner.run` catches the exception, records an incomplete row and returns, so the
+loop continues and `_render_ab` is reached with a hole in the plan. `readings_by_arm` drops the
+incomplete cell and `compare_arms` intersects the two arms' keys, which takes the failed cell's
+HEALTHY PARTNER out of the table with it -- the loss is a whole rung, chosen by which cell died.
+
+Measured on the payload below: a 10K base cell that died published `VERDICT: IMPROVED (20.0%
+faster)` off the 100K pair alone, with nothing in `ab.md` naming 10K, while the 10K pair that had
+in fact been measured on the treatment side was a 26.5% regression -- a FAIL. The run exits
+nonzero either way, and that is not the same thing: the exit code is gone when the shell scrolls
+and `ab.md` is the artifact that gets pasted.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.__main__ import _render_ab # noqa: E402
+from studiobench.runtime.ab import unmeasured_planned_cells # noqa: E402
+from studiobench.runtime.types import Paths, Recorder # noqa: E402
+
+SIDES = [
+ {"label": "base", "ref": "main", "base_url": "http://127.0.0.1:5399", "owns": True},
+ {"label": "treatment", "ref": "fix", "base_url": "http://127.0.0.1:5400", "owns": True},
+]
+
+#: (rung, tokens, base p95, treatment p95). 10K regresses by 100%, 100K improves by 20%.
+LADDER = (("10K", 10_000, 100.0, 200.0), ("100K", 100_000, 100.0, 80.0))
+
+
+def _cell_row(
+ cell_id,
+ arm,
+ tokens,
+ *,
+ completed = True,
+):
+ return {
+ "row_type": "cell",
+ "cell_id": cell_id,
+ "cell": {"arm": arm, "rep": 0},
+ "completed": completed,
+ "fidelity": "ok" if completed else "unknown",
+ "target_tokens": tokens,
+ }
+
+
+def _keystroke(cell_id, p95):
+ return {
+ "row_type": "action",
+ "cell_id": cell_id,
+ "action": "keystroke",
+ "window": "film",
+ "ran": True,
+ "expect_ok": True,
+ "expect": {},
+ "timings": {"p95_ms": p95},
+ "slot_missed": False,
+ }
+
+
+def _table(
+ tmp_path,
+ *,
+ failed: str | None,
+ planned_known: bool = True,
+) -> str:
+ """Write the payload one A/B session would write, then render it the way `run()` does."""
+
+ 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, completed = cell_id != failed))
+ rec.emit(_keystroke(cell_id, p95))
+ rec.close()
+
+ _render_ab(
+ paths,
+ SIDES,
+ "sess-1",
+ "c0ffee",
+ planned = planned if planned_known else (),
+ )
+ return (paths.out / "ab.md").read_text(encoding = "utf-8")
+
+
+def test_a_failed_base_cell_does_not_publish_a_verdict_from_the_rung_that_survived(tmp_path):
+ table = _table(tmp_path, failed = "r10K.base.rep0")
+
+ assert "VOID. No numbers are quotable" in table
+ assert "r10K.base.rep0" in table
+ # The exact headline this used to publish, off the 100K pair alone.
+ assert "IMPROVED" not in table
+ assert "20.0% faster" not in table
+ assert "headline ratio" not in table
+
+
+def test_the_same_payload_complete_is_the_fail_the_omission_erased(tmp_path):
+ """The control, and the measurement of what was lost: with 10K present this is a FAIL."""
+
+ table = _table(tmp_path, failed = None)
+
+ assert "VERDICT: FAIL" in table
+ assert "26.5% worse" in table
+ assert "VOID" not in table
+
+
+def test_the_unguarded_render_is_the_wrong_verdict(tmp_path):
+ """What the guard is for, through the same path: without the plan, the surviving 100K pair is
+ published as a 20% win over a payload whose measured 10K pair is a 100% regression."""
+
+ table = _table(tmp_path, failed = "r10K.base.rep0", planned_known = False)
+
+ assert "VERDICT: IMPROVED" in table
+ assert "20.0% faster" 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:
+ row["session_id"] = "sess-1"
+
+ assert unmeasured_planned_cells(records, ["r10K.base.rep0"], session_id = "sess-1") == []
+
+
+def test_a_cell_from_another_session_does_not_count_as_measured():
+ """The session filter `readings_by_arm` applies, applied to the same question. A planned cell
+ whose only completed row belongs to a previous session has no reading in THIS one."""
+
+ row = _cell_row("r10K.base.rep0", "base", 10_000, completed = True)
+ row["session_id"] = "sess-0"
+
+ assert unmeasured_planned_cells([row], ["r10K.base.rep0"], session_id = "sess-1") == [
+ "r10K.base.rep0"
+ ]
+
+
+def test_a_dead_attempt_does_not_mark_a_recovered_cell_unmeasured():
+ """A cell id carries every attempt at it. One completed row for the planned cell in this
+ session is a reading, and the guard must not void a run that recovered."""
+
+ dead = _cell_row("r10K.base.rep0", "base", 10_000, completed = False)
+ dead["session_id"] = "sess-1"
+ retry = _cell_row("r10K.base.rep0", "base", 10_000, completed = True)
+ retry["session_id"] = "sess-1"
+
+ assert unmeasured_planned_cells([dead, retry], ["r10K.base.rep0"], session_id = "sess-1") == []
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_pair_resume.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_pair_resume.py
new file mode 100644
index 00000000000..9ca31316762
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_pair_resume.py
@@ -0,0 +1,307 @@
+# 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 interrupted A/B resumes at PAIR granularity, because a pair is the unit of the comparison.
+
+The two cells of one `(rung, rep)` pair run adjacent in time inside one session, and that adjacency
+is the whole method: cross-session drift on the measured machine ran to 8%, larger than most of the
+wins anybody argues about, so `readings_by_arm` scopes the ratio to a single session and
+`assert_comparable` refuses two session ids outright.
+
+An interruption between those two adjacent cells is the ordinary way a run stops. Skipping the arm
+that completed and measuring only its partner in the new session therefore bought a full cell of
+measurement that no table can contain: the old arm is dropped by the session filter, the new one
+has nothing to pair with, and `_render_ab` writes that repetition out of the table -- at one
+repetition, out of the table entirely, as NO READING with an exit code of 0 underneath it.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.__main__ import _render_ab, _resume_set # noqa: E402
+from studiobench.runtime.ab import Target, interleave, skippable_cells # noqa: E402
+from studiobench.runtime.types import Cell, Paths, Recorder, make_cell_id # noqa: E402
+
+SIDES = [
+ {"label": "base", "ref": "main", "base_url": "http://127.0.0.1:5399", "owns": True},
+ {"label": "treatment", "ref": "fix", "base_url": "http://127.0.0.1:5400", "owns": True},
+]
+
+
+def _target(label):
+ return Target(label = label, ref = label, base_url = f"http://x/{label}", seeder = None, runner = None)
+
+
+#: Each rung needs its OWN token count: `measures_by_cell` keys on `(rung_tokens, rep)`, so two
+#: rungs sharing one number collapse into one pair and a two-rung table renders as a one-rung one.
+RUNG_TOKENS = {"1K": 1_000, "10K": 10_000, "100K": 100_000, "500K": 500_000, "1M": 1_000_000}
+
+
+def _work(reps = 1, rungs = ("10K",)):
+ """The real `interleave` over real cells: exactly what `run()` iterates."""
+
+ cells = []
+ for rung in rungs:
+ for rep in range(reps):
+ cells.append(
+ (
+ Cell(
+ cell_id = make_cell_id(rung, "A0", rep),
+ rung = rung,
+ rung_tokens = RUNG_TOKENS.get(rung, 10_000),
+ rep = rep,
+ ),
+ None,
+ )
+ )
+ return interleave(cells, [_target("base"), _target("treatment")])
+
+
+def _cell_row(
+ cell_id,
+ arm,
+ rep = 0,
+ tokens = 10_000,
+):
+ return {
+ "row_type": "cell",
+ "cell_id": cell_id,
+ "cell": {"arm": arm, "rep": rep},
+ "completed": True,
+ "fidelity": "ok",
+ "target_tokens": tokens,
+ }
+
+
+def _keystroke(cell_id, p95):
+ return {
+ "row_type": "action",
+ "cell_id": cell_id,
+ "action": "keystroke",
+ "window": "film",
+ "ran": True,
+ "expect_ok": True,
+ "expect": {},
+ "timings": {"p95_ms": p95},
+ "slot_missed": False,
+ }
+
+
+# ── the decision ─────────────────────────────────────────────────────────────────────────────
+
+
+def test_a_pair_interrupted_between_its_two_arms_is_re_run_whole():
+ work = _work()
+ done = {"r10K.base.rep0"} # the run died after the base arm and before the treatment arm
+
+ assert skippable_cells(work, done) == set()
+
+
+def test_a_pair_recorded_on_both_arms_is_skipped():
+ """The control: pair granularity must not turn into refusing to resume anything."""
+
+ work = _work()
+ done = {"r10K.base.rep0", "r10K.treatment.rep0"}
+
+ assert skippable_cells(work, done) == done
+
+
+def test_a_comparison_with_work_left_re_runs_every_pair():
+ """A COMPLETE PAIR FROM THE OLD SESSION IS AS UNUSABLE AS A LONE ARM, and this asserted the
+ opposite until a resumed standard tier published `VERDICT: IMPROVED (20.0% faster)` off its
+ 100K pair while the 10K pair it had already measured -- a 30% regression, complete, in session
+ one -- was dropped by the session filter with nothing in `ab.md` naming the missing rung.
+
+ The rule the module already argues for a half-finished pair is the rule for a half-finished
+ table: re-run both arms of every pair, adjacent in time, in one session.
+ """
+
+ work = _work(reps = 2)
+ done = {"r10K.base.rep0", "r10K.treatment.rep0", "r10K.base.rep1"}
+
+ assert skippable_cells(work, done) == set()
+
+
+def test_a_comparison_with_nothing_left_still_skips_everything():
+ """The control that keeps `--resume` on a finished A/B free: nothing runs, and `_render_ab`
+ keeps the table that run already wrote rather than replacing it with NO READING."""
+
+ work = _work(reps = 2)
+ done = {
+ "r10K.base.rep0",
+ "r10K.treatment.rep0",
+ "r10K.base.rep1",
+ "r10K.treatment.rep1",
+ }
+
+ assert skippable_cells(work, done) == done
+
+
+def test_a_run_without_ab_skips_exactly_what_it_recorded():
+ """The other control. Without `--ab` every pair holds one cell, so nothing changes."""
+
+ work = [
+ (None, Cell(cell_id = make_cell_id(rung, "A0", 0), rung = rung, rung_tokens = 1), None)
+ for rung in ("1K", "10K", "100K")
+ ]
+ done = {"r1K.A0.rep0", "r100K.A0.rep0"}
+
+ assert skippable_cells(work, done) == done
+
+
+# ── the consequence, through the table a resumed run actually writes ─────────────────────────
+
+
+def _resumed_table(tmp_path, *, pair_granular: bool) -> str:
+ """Drive a resumed A/B end to end: what the payload holds, what the resume decides to run,
+ what it records in the new session, and what `_render_ab` then writes to `ab.md`."""
+
+ paths = Paths.under(tmp_path / "out")
+ interrupted = Recorder(paths.payload_jsonl, "sess-1")
+ interrupted.emit(_cell_row("r10K.base.rep0", "base"))
+ interrupted.emit(_keystroke("r10K.base.rep0", 100.0))
+ interrupted.close() # killed here, between the two arms of the only pair
+
+ work = _work()
+ done = _resume_set(paths)
+ if pair_granular:
+ done = skippable_cells(work, done)
+
+ resumed = Recorder(paths.payload_jsonl, "sess-2")
+ for target, cell, _plan in work:
+ if cell.cell_id in done:
+ continue
+ resumed.emit(_cell_row(cell.cell_id, target.label))
+ resumed.emit(_keystroke(cell.cell_id, 100.0 if target.label == "base" else 50.0))
+ resumed.close()
+
+ _render_ab(paths, SIDES, "sess-2", "c0ffee")
+ return (paths.out / "ab.md").read_text(encoding = "utf-8")
+
+
+def test_the_resumed_session_measures_both_arms_and_gets_a_table(tmp_path):
+ table = _resumed_table(tmp_path, pair_granular = True)
+
+ assert "VERDICT: IMPROVED" in table
+ assert "NO READING" not in table
+
+
+def test_without_pair_granularity_the_same_resume_reports_nothing(tmp_path):
+ """What the fix is for, driven through the same path: skipping the recorded base arm leaves
+ the treatment arm with nothing to pair against and the table says NO READING."""
+
+ table = _resumed_table(tmp_path, pair_granular = False)
+
+ assert "VERDICT: NO READING" in table
+
+
+def _two_rung_resumed_table(tmp_path, *, whole_table: bool) -> str:
+ """The same drive over TWO rungs, with the first pair fully recorded in session one.
+
+ 10K measured base 100 ms against treatment 130 ms -- a 30% regression, complete, beyond the
+ noise floor. The run then died inside the 100K pair, where the treatment is the faster side.
+ """
+
+ paths = Paths.under(tmp_path / "out")
+ interrupted = Recorder(paths.payload_jsonl, "sess-1")
+ for cell_id, arm, rung, p95 in (
+ ("r10K.base.rep0", "base", "10K", 100.0),
+ ("r10K.treatment.rep0", "treatment", "10K", 130.0),
+ ("r100K.base.rep0", "base", "100K", 100.0),
+ ):
+ interrupted.emit(_cell_row(cell_id, arm, tokens = RUNG_TOKENS[rung]))
+ interrupted.emit(_keystroke(cell_id, p95))
+ interrupted.close()
+
+ work = _work(rungs = ("10K", "100K"))
+ recorded = _resume_set(paths)
+ if whole_table:
+ done = skippable_cells(work, recorded)
+ else:
+ # THE PRE-FIX RULE, inline so the contrast is the change itself: skip any pair whose every
+ # arm is already recorded, and let the rest of the table be whatever is left.
+ by_pair: dict = {}
+ for _t, cell, _p in work:
+ by_pair.setdefault((cell.rung, cell.rep), []).append(cell.cell_id)
+ done = {cid for ids in by_pair.values() if all(c in recorded for c in ids) for cid in ids}
+
+ resumed = Recorder(paths.payload_jsonl, "sess-2")
+ for target, cell, _plan in work:
+ if cell.cell_id in done:
+ continue
+ resumed.emit(_cell_row(cell.cell_id, target.label, tokens = RUNG_TOKENS[cell.rung]))
+ p95 = 100.0 if target.label == "base" else (130.0 if cell.rung == "10K" else 80.0)
+ resumed.emit(_keystroke(cell.cell_id, p95))
+ resumed.close()
+
+ _render_ab(paths, SIDES, "sess-2", "c0ffee")
+ return (paths.out / "ab.md").read_text(encoding = "utf-8")
+
+
+def test_a_resumed_comparison_publishes_a_verdict_over_every_rung(tmp_path):
+ """THE CONSEQUENCE. Both pairs are re-measured in the new session, so both are in the table
+ and the verdict is computed over the ladder rather than over its remainder."""
+
+ table = _two_rung_resumed_table(tmp_path, whole_table = True)
+
+ assert "keystroke_p95_ms 2" in table, table
+ assert "0.800-1.300" in table, table
+ assert "VERDICT: IMPROVED" not in table, table
+
+
+def test_skipping_the_recorded_pair_publishes_a_verdict_over_the_remainder(tmp_path):
+ """What the fix is for, driven through the same path. The 30% regression the run had already
+ measured is dropped by the session filter and nothing in the file mentions the missing rung."""
+
+ table = _two_rung_resumed_table(tmp_path, whole_table = False)
+
+ assert "keystroke_p95_ms 1" in table, table
+ assert "VERDICT: IMPROVED" in table, table
+ assert "10K" not in table
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
+
+
+def test_a_resume_killed_inside_a_cell_does_not_read_as_a_finished_run(tmp_path):
+ """THE CONSEQUENCE, through `_resume_set` and `skippable_cells` together.
+
+ Session one failed the 10K base arm. The resume repaired the 10K pair, then was hard-killed
+ inside the 100K base arm: its action and window rows are on disk, fsynced, but the terminal
+ cell row that `CellRunner.run` writes in a `finally` never was. Keyed on cell rows alone, the
+ older completed 100K attempt stayed the latest, every cell read as done across two sessions,
+ and the next `--resume` ran nothing and exited 0 over a stale table.
+ """
+
+ paths = Paths.under(tmp_path / "out")
+ first = Recorder(paths.payload_jsonl, "sess-1")
+ first.emit({**_cell_row("r10K.base.rep0", "base"), "completed": False})
+ first.emit(_keystroke("r10K.base.rep0", 40.0))
+ first.emit(_cell_row("r10K.treatment.rep0", "treatment"))
+ first.emit(_keystroke("r10K.treatment.rep0", 41.0))
+ for arm in ("base", "treatment"):
+ cid = f"r100K.{arm}.rep0"
+ first.emit(_cell_row(cid, arm, tokens = RUNG_TOKENS["100K"]))
+ first.emit(_keystroke(cid, 50.0))
+ first.close()
+
+ killed = Recorder(paths.payload_jsonl, "sess-2")
+ for arm in ("base", "treatment"):
+ cid = f"r10K.{arm}.rep0"
+ killed.emit(_cell_row(cid, arm))
+ killed.emit(_keystroke(cid, 42.0))
+ killed.emit(_keystroke("r100K.base.rep0", 900.0)) # killed here: no cell row follows
+ killed.close()
+
+ done = _resume_set(paths)
+ assert "r100K.base.rep0" not in done
+
+ work = _work(rungs = ("10K", "100K"))
+ assert skippable_cells(work, done) == set()
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_pairing.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_pairing.py
new file mode 100644
index 00000000000..0377f76c94f
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_ab_pairing.py
@@ -0,0 +1,132 @@
+# 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 may enter an A/B ratio: a completed cell, from THIS session.
+
+Two ways a ratio was formed out of things that are not comparable, both of them silent:
+
+ A CRASHED ARM CAN WIN. An arm that died part way through a cell still wrote the action rows it
+ had already measured. Pairing those against a completed cell on the other side turned a crash
+ into an improvement -- a treatment cell holding one 50 ms keystroke against a completed 100 ms
+ base cell reported IMPROVED, and the crash appeared only in the excluded list underneath.
+
+ RESUME REOPENS THE SESSION. `--resume` appends to the payload of the run it is continuing, and
+ the new cells carry a new session id. `assert_comparable` refuses two sessions, but both sides
+ are labelled with the CURRENT one, so the 8% cross-session drift term it exists to refuse came
+ back in through the rows.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.runtime.ab import compare_arms, readings_by_arm # noqa: E402
+
+SESSION = "s-now"
+OLD_SESSION = "s-before"
+
+
+def _cell(
+ cell_id,
+ arm,
+ *,
+ completed = True,
+ session = SESSION,
+ tokens = 10_000,
+ rep = 0,
+):
+ return {
+ "row_type": "cell",
+ "cell_id": cell_id,
+ "session_id": session,
+ "target_tokens": tokens,
+ "completed": completed,
+ "cell": {"arm": arm, "rep": rep},
+ }
+
+
+def _keystroke(
+ cell_id,
+ p95,
+ *,
+ session = SESSION,
+):
+ return {
+ "row_type": "action",
+ "cell_id": cell_id,
+ "session_id": session,
+ "action": "keystroke",
+ "ran": True,
+ "expect_ok": True,
+ "timings": {"p95_ms": p95},
+ }
+
+
+def _pairs(records, session_id = SESSION):
+ result = compare_arms(
+ records,
+ "base",
+ "treatment",
+ bench_version = "0.1.0",
+ corpus_hash = "c0ffee",
+ session_id = session_id,
+ label = "test",
+ )
+ return [p for p in result.pairs if p.metric_key == "keystroke_p95_ms"], result
+
+
+def test_a_crashed_treatment_cell_does_not_become_a_win():
+ records = [
+ _cell("r10K.base.rep0", "base"),
+ _keystroke("r10K.base.rep0", 100.0),
+ _cell("r10K.treatment.rep0", "treatment", completed = False),
+ _keystroke("r10K.treatment.rep0", 50.0),
+ ]
+ assert "treatment" not in readings_by_arm(records)
+ pairs, result = _pairs(records)
+ assert pairs == []
+ assert result.verdict == "NO READING"
+
+
+def test_two_completed_cells_still_pair():
+ records = [
+ _cell("r10K.base.rep0", "base"),
+ _keystroke("r10K.base.rep0", 100.0),
+ _cell("r10K.treatment.rep0", "treatment"),
+ _keystroke("r10K.treatment.rep0", 50.0),
+ ]
+ pairs, _result = _pairs(records)
+ assert len(pairs) == 1
+ assert pairs[0].ratio == 0.5
+
+
+def test_cells_from_a_previous_session_are_not_paired_with_this_one():
+ records = [
+ _cell("r10K.base.rep0", "base", session = OLD_SESSION),
+ _keystroke("r10K.base.rep0", 100.0, session = OLD_SESSION),
+ _cell("r10K.treatment.rep0", "treatment"),
+ _keystroke("r10K.treatment.rep0", 50.0),
+ ]
+ assert "base" not in readings_by_arm(records, session_id = SESSION)
+ pairs, _result = _pairs(records)
+ assert pairs == []
+
+
+def test_a_payload_without_session_ids_is_still_readable():
+ """Older payloads, and the hand-built ones in these tests, carry no session id per row."""
+
+ records = [
+ {k: v for k, v in _cell("a", "base").items() if k != "session_id"},
+ {k: v for k, v in _keystroke("a", 100.0).items() if k != "session_id"},
+ {k: v for k, v in _cell("b", "treatment").items() if k != "session_id"},
+ {k: v for k, v in _keystroke("b", 50.0).items() if k != "session_id"},
+ ]
+ assert set(readings_by_arm(records, session_id = SESSION)) == {"base", "treatment"}
+
+
+if __name__ == "__main__":
+ import pytest
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_equivalence_mirror.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_equivalence_mirror.py
new file mode 100644
index 00000000000..e97524b0ec8
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_equivalence_mirror.py
@@ -0,0 +1,77 @@
+# 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 seeded-vs-streamed mirror has to contain every turn that streamed.
+
+From 10K upwards a rung plans two follow-up turns and the scene streams both through `send_turn`
+before the peak census is taken. The mirror was seeded from the prefix plus the OPENING unit only,
+so the gated `assistant_messages` compared six assistant turns against four: 33% drift against a 2%
+tolerance, on every healthy cell. The check then reported SEEDED IS NOT EQUIVALENT TO STREAMED as a
+finding about the app, and labelled every larger rung `fidelity: seeded_only`, for a difference the
+mirror had introduced itself.
+
+A `send_turn` that did NOT run put nothing in the thread, so it must not go into the mirror either;
+that is the case the small rungs hit, where the stream queue is empty by design.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.fixture.corpus import RungPlan, Unit # noqa: E402
+from studiobench.runtime.session import CellRunner # noqa: E402
+
+
+def _unit(text):
+ return Unit(index = 0, kind = "code", reasoning = "", content = text, chars = len(text), sha256 = "0" * 8)
+
+
+def _plan(follow_ups):
+ return RungPlan(
+ rung = "10K",
+ target_tokens = 10_000,
+ target_chars = 40_000,
+ seeded_units = [_unit("seeded")],
+ streamed_unit = _unit("opening"),
+ follow_up_units = [_unit(f"follow{i}") for i in range(follow_ups)],
+ )
+
+
+def _send_turn(*, ran = True, expect_ok = True):
+ return {"action": "send_turn", "ran": ran, "expect_ok": expect_ok}
+
+
+def test_every_turn_that_streamed_is_mirrored():
+ plan = _plan(2)
+ row = {"actions": [_send_turn(), {"action": "keystroke", "ran": True}, _send_turn()]}
+ assert CellRunner._streamed_follow_ups(plan, row) == plan.follow_up_units
+
+
+def test_a_follow_up_that_never_ran_is_not_mirrored():
+ plan = _plan(2)
+ row = {"actions": [_send_turn(), _send_turn(ran = False, expect_ok = None)]}
+ assert CellRunner._streamed_follow_ups(plan, row) == plan.follow_up_units[:1]
+
+
+def test_a_send_that_did_not_start_a_reply_is_not_mirrored():
+ plan = _plan(2)
+ row = {"actions": [_send_turn(expect_ok = False), _send_turn()]}
+ assert CellRunner._streamed_follow_ups(plan, row) == plan.follow_up_units[:1]
+
+
+def test_a_single_turn_rung_mirrors_nothing_extra():
+ plan = _plan(0)
+ row = {"actions": [_send_turn(ran = False, expect_ok = None)]}
+ assert CellRunner._streamed_follow_ups(plan, row) == []
+
+
+def test_a_cell_with_no_action_rows_mirrors_nothing_extra():
+ assert CellRunner._streamed_follow_ups(_plan(2), {}) == []
+
+
+if __name__ == "__main__":
+ import pytest
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_instrument_lifecycle.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_instrument_lifecycle.py
new file mode 100644
index 00000000000..928a2b5d622
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_instrument_lifecycle.py
@@ -0,0 +1,110 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""One broken instrument must not take a healthy one down with it.
+
+`_safe` exists so a single instrument that raises never costs the window: it logs, drops that
+instrument, and lets the cell continue. But it drops it from the SAME list the lifecycle loop is
+iterating, and a list that shrinks under `for x in list_` makes Python skip whatever slid into the
+freed index. So `heap` raising in `start_cell` did not cost only `heap`; it also silently skipped
+`input`, whose keystroke latency is the highest-weight metric in the table. The cell then completed
+and reported, with one instrument's measurements simply absent and nothing saying so.
+"""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.runtime.session import Session # noqa: E402
+
+
+class _Recorder:
+ def now_ms(self):
+ return 0.0
+
+ def emit(self, row):
+ pass
+
+
+class _Ctx:
+ def __init__(self):
+ self.recorder = _Recorder()
+ self.logged = []
+
+ def log(self, msg):
+ self.logged.append(msg)
+
+
+class _Instrument:
+ """Records which lifecycle hooks it was actually given."""
+
+ def __init__(
+ self,
+ name,
+ *,
+ raises = False,
+ ):
+ self.name = name
+ self.raises = raises
+ self.started = []
+
+ def start_cell(self, cell):
+ if self.raises:
+ raise RuntimeError("instrument exploded")
+ self.started.append(cell)
+
+ def end_cell(self, cell):
+ if self.raises:
+ raise RuntimeError("instrument exploded")
+ return {"ok": True}
+
+
+def _session(instruments):
+ s = Session.__new__(Session)
+ s.ctx = _Ctx()
+ s.instruments = list(instruments)
+ return s
+
+
+def test_an_instrument_after_a_failing_one_still_gets_its_hook():
+ frames, heap, keys, rss = (
+ _Instrument("frames"),
+ _Instrument("heap", raises = True),
+ _Instrument("input"),
+ _Instrument("rss"),
+ )
+ s = _session([frames, heap, keys, rss])
+
+ s.each_instrument("start_cell", "c1")
+
+ # `input` sits immediately behind the instrument that raised, which is exactly the position
+ # the old loop skipped.
+ assert keys.started == ["c1"], "the instrument behind the failing one was skipped"
+ assert frames.started == ["c1"]
+ assert rss.started == ["c1"]
+
+
+def test_the_failing_instrument_is_still_dropped():
+ """The control: the fix must not cost `_safe` its whole reason for existing."""
+ heap, keys = _Instrument("heap", raises = True), _Instrument("input")
+ s = _session([heap, keys])
+
+ s.each_instrument("start_cell", "c1")
+
+ assert [i.name for i in s.instruments] == ["input"]
+ assert any("heap.start_cell failed" in m for m in s.ctx.logged)
+
+
+def test_two_failures_in_a_row_drop_both_and_skip_neither():
+ a, b, keys = (
+ _Instrument("heap", raises = True),
+ _Instrument("tracing", raises = True),
+ _Instrument("input"),
+ )
+ s = _session([a, b, keys])
+
+ s.each_instrument("start_cell", "c1")
+
+ assert keys.started == ["c1"]
+ assert [i.name for i in s.instruments] == ["input"]
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_ladder_ratio.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_ladder_ratio.py
new file mode 100644
index 00000000000..ec07cbcdbbe
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_ladder_ratio.py
@@ -0,0 +1,105 @@
+# 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 rung axis is sized by the MEASURED ratio, not by the provisional 4.0.
+
+`PROVISIONAL_CHARS_PER_TOKEN` is what a rung is planned with before anything has been tokenised.
+The production caller used to leave it there forever: `build_cells` took a hard-coded 4.0, the
+per-cell `measure_chars_per_token` ran only after the thread was seeded, and its answer was
+recorded and read by nothing. So every cell labelled 1M tokens carried 4,000,000 characters of a
+corpus tiktoken reads at about 3.34 -- roughly 1.2M tokens, a fifth over its own label, on the very
+axis the onset headline is quoted against.
+
+Two halves, and both are needed. The ladder is sized from a real tokeniser's answer, and a machine
+that has none keeps the provisional ratio and SAYS SO rather than sizing the corpus from the
+whitespace estimate, which reads 6.7 on this dense-code corpus and is past what the manifest was
+frozen for.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.fixture.corpus import ( # noqa: E402
+ PROVISIONAL_CHARS_PER_TOKEN,
+ RUNGS,
+ Corpus,
+)
+from studiobench.runtime import session as session_mod # noqa: E402
+from studiobench.runtime.seeder import measure_chars_per_token # noqa: E402
+from studiobench.runtime.session import build_cells # noqa: E402
+
+
+def _corpus() -> Corpus:
+ return Corpus.load()
+
+
+def _measured(corpus: Corpus) -> dict:
+ """The corpus's own ratio, measured the way the harness says it measures it."""
+ text: list[str] = []
+ size = 0
+ for entry in corpus.manifest["units"]:
+ unit = corpus.unit(entry["index"])
+ text.append(unit.reasoning + unit.content)
+ size += unit.chars
+ if size >= 200_000:
+ break
+ return measure_chars_per_token("".join(text)[:200_000], "", None, "")
+
+
+def test_the_ladder_is_sized_by_the_measured_ratio_and_not_the_provisional_one():
+ pytest.importorskip("tiktoken", reason = "this case is the real-tokeniser one")
+ corpus = _corpus()
+ ratio = _measured(corpus)
+ assert ratio["source"] == "tiktoken/cl100k", ratio
+ assert ratio["chars_per_token"] != PROVISIONAL_CHARS_PER_TOKEN, ratio
+
+ cells = build_cells(list(RUNGS), corpus, "full", "s0", 0)
+ assert cells, "the ladder built no cells"
+ for cell, plan in cells:
+ assert plan.target_chars == int(RUNGS[cell.rung] * ratio["chars_per_token"]), (
+ cell.rung,
+ plan.target_chars,
+ )
+ # The bug, stated as the number it produced: the top rung was 4,000,000 characters.
+ assert plan.target_chars != int(RUNGS[cell.rung] * PROVISIONAL_CHARS_PER_TOKEN), cell.rung
+ assert cell.meta["ladder_chars_per_token"]["chars_per_token"] == ratio["chars_per_token"]
+ assert cell.meta["ladder_chars_per_token"]["provisional"] is False
+
+
+def test_a_caller_that_names_a_ratio_still_gets_that_ratio():
+ corpus = _corpus()
+ cells = build_cells(["10K"], corpus, "quick", "s0", 0, chars_per_token = 4.5)
+ (cell, plan) = cells[0]
+ assert plan.target_chars == int(10_000 * 4.5)
+ assert cell.meta["ladder_chars_per_token"]["source"] == "caller"
+
+
+def test_a_machine_with_no_tokeniser_keeps_the_provisional_ratio_and_says_so(monkeypatch):
+ """The whitespace estimate reads 6.675 here, past `MANIFEST_CHARS_PER_TOKEN`.
+
+ Sizing the ladder from it would move the error rather than remove it and would make `plan_rung`
+ refuse the whole run. The estimate is still measured and still reported; it just does not size
+ the axis.
+ """
+ monkeypatch.setattr(
+ session_mod,
+ "measure_chars_per_token",
+ lambda *a, **k: {
+ "chars_per_token": 6.675,
+ "source": "whitespace-and-punctuation estimate",
+ },
+ )
+ corpus = _corpus()
+ cells = build_cells(["1M"], corpus, "full", "s0", 0)
+ (cell, plan) = cells[0]
+ assert plan.target_chars == int(1_000_000 * PROVISIONAL_CHARS_PER_TOKEN)
+ meta = cell.meta["ladder_chars_per_token"]
+ assert meta["provisional"] is True
+ assert meta["measured"] == 6.675
+ assert "no tokeniser answered" in meta["reason"]
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_ladder_ratio_identity.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_ladder_ratio_identity.py
new file mode 100644
index 00000000000..12cbe558bff
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_ladder_ratio_identity.py
@@ -0,0 +1,294 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""One payload, one chars-per-token ratio.
+
+A rung is NAMED in tokens and BUILT in characters, and the ratio is the only thing that makes
+those the same claim. `session.ladder_chars_per_token` measures it afresh on every invocation,
+`--resume` included, and falls back to `PROVISIONAL_CHARS_PER_TOKEN` whenever no real tokeniser
+answers -- tiktoken is not a dependency of this harness, and where it is installed `get_encoding`
+fetches `cl100k_base` over the network on first use, so "no tokeniser answered" is one absent
+package or one unlucky minute.
+
+So a run on a machine with no tokeniser sizes every rung at 4.0 and dies at 100K, and the resume
+finds tiktoken and sizes at 3.336. `_resume_set` skips by `cell_id`, which is
+`r{rung}.{arm}.rep{rep}` and carries no ratio: 1K and 10K stay at 4,000 and 40,000 characters
+while 100K and 1M are built at 333,600 and 3,336,000. Nothing downstream can see the mixture --
+`score_payload` keys by rung, the report prints one ladder, and ONSET RUNG names a token label
+standing over two different amounts of work in the same table.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.__main__ import ( # noqa: E402
+ LADDER_RATIO_AXIS,
+ LADDER_RATIO_TOLERANCE,
+ _resume_set,
+ ladder_ratio_problems,
+ payload_mark,
+ recorded_identities,
+ recorded_ladder,
+ rollback_session_rows,
+)
+from studiobench.runtime.types import Paths, Recorder # noqa: E402
+
+CORPUS = "c0ffee"
+
+
+def _ratio(value: float, source: str, provisional: bool) -> dict:
+ """A `ladder_chars_per_token` block exactly as `session.build_cells` writes one."""
+ return {
+ "chars_per_token": value,
+ "measured": None if provisional else value,
+ "source": source,
+ "provisional": provisional,
+ "reason": "no tokeniser answered" if provisional else None,
+ }
+
+
+def _payload(
+ tmp_path,
+ cells: list,
+ session: str = "sess-1",
+) -> Paths:
+ """A payload holding `cells`, written through the REAL recorder."""
+ paths = Paths.under(tmp_path / "out")
+ recorder = Recorder(paths.payload_jsonl, session)
+ recorder.emit(
+ {
+ "row_type": "run_meta",
+ "tier": "standard",
+ "tool_version": "0.1.0",
+ "corpus_hash": CORPUS,
+ "studio_ref": "main",
+ "bundle": {"production": True},
+ "platform": {"system": "Linux"},
+ "started_at": "2026-01-01T00:00:00",
+ "cadence": "field",
+ "rungs": ["1K", "10K", "100K"],
+ "reps": 1,
+ "instrument_level": 0,
+ }
+ )
+ for row in cells:
+ recorder.emit(dict(row))
+ recorder.close()
+ return paths
+
+
+def _cell(rung: str, meta: dict) -> dict:
+ return {
+ "row_type": "cell",
+ "cell_id": f"r{rung}.A0.rep0",
+ "cell": {"arm": "A0", "rep": 0, "tier": "standard", "meta": meta},
+ "completed": True,
+ "fidelity": "ok",
+ }
+
+
+def _rows(paths: Paths) -> list:
+ """Every row in the payload, as JSON."""
+ return [
+ json.loads(line)
+ for line in paths.payload_jsonl.read_text(encoding = "utf-8").splitlines()
+ if line.strip()
+ ]
+
+
+def _problems(paths: Paths, measured: float) -> list:
+ """What `run` asks once `build_cells` has measured this invocation's ratio."""
+ out: list = []
+ for recorded in recorded_identities(paths.payload_jsonl):
+ for problem in ladder_ratio_problems(recorded, measured):
+ if problem not in out:
+ out.append(problem)
+ return out
+
+
+def test_a_resume_that_sizes_the_ladder_differently_is_refused(tmp_path):
+ """The bug, as the numbers it produced.
+
+ The recorded run had no tokeniser and planned 1K at 4,000 characters; this one reads the corpus
+ at 3.336 and would plan 100K at 333,600 rather than 400,000. `_resume_set` skips the first two
+ rungs regardless, because the ratio is nowhere in a cell id.
+ """
+
+ paths = _payload(
+ tmp_path,
+ [
+ _cell(rung, {"ladder_chars_per_token": _ratio(4.0, "whitespace estimate", True)})
+ for rung in ("1K", "10K")
+ ],
+ )
+ assert _resume_set(paths) == {"r1K.A0.rep0", "r10K.A0.rep0"}
+
+ problems = _problems(paths, 3.336)
+ assert len(problems) == 1, problems
+ assert LADDER_RATIO_AXIS in problems[0]
+ assert "4.0" in problems[0] and "3.336" in problems[0]
+
+
+def test_the_ratio_is_read_off_the_cells_a_session_actually_wrote(tmp_path):
+ paths = _payload(
+ tmp_path,
+ [_cell("1K", {"ladder_chars_per_token": _ratio(3.336, "tiktoken/cl100k", False)})],
+ )
+ (recorded,) = recorded_identities(paths.payload_jsonl)
+ assert recorded[LADDER_RATIO_AXIS] == 3.336
+
+
+def test_the_same_ratio_still_resumes(tmp_path):
+ """The control. A tokeniser that answers the same way twice is a continuation, not a change."""
+
+ paths = _payload(
+ tmp_path,
+ [_cell("1K", {"ladder_chars_per_token": _ratio(3.336, "tiktoken/cl100k", False)})],
+ )
+ assert _problems(paths, 3.336) == []
+
+
+def test_a_float_that_only_differs_in_the_noise_still_resumes(tmp_path):
+ """5.0 against 5.0000001 is one measurement read twice, not two measurements.
+
+ `measure_chars_per_token` rounds to three decimals and `PROVISIONAL_CHARS_PER_TOKEN` is exact,
+ so every ratio that reaches a payload sits on a 0.001 grid and `LADDER_RATIO_TOLERANCE` is half
+ a grid step: nothing a float's own representation can do to a value crosses it, and nothing two
+ real measurements can differ by fails to.
+ """
+
+ paths = _payload(
+ tmp_path,
+ [_cell("1K", {"ladder_chars_per_token": _ratio(5.0, "tiktoken/cl100k", False)})],
+ )
+ assert _problems(paths, 5.0 + 1e-7) == []
+ assert _problems(paths, 5.0 - 1e-7) == []
+ # And the smallest difference two recorded ratios can actually have is still refused.
+ assert _problems(paths, 5.001) != []
+ assert LADDER_RATIO_TOLERANCE < 0.001
+
+
+def test_a_payload_that_never_recorded_the_ratio_still_resumes(tmp_path):
+ """A payload written before the ratio travelled on `meta` declares no ratio.
+
+ The same rule `recorded_identities` applies to every other axis: an axis a row never declared
+ cannot be a difference, so an older output resumes on the axes it did record.
+ """
+
+ paths = _payload(tmp_path, [_cell("1K", {})])
+ (recorded,) = recorded_identities(paths.payload_jsonl)
+ assert LADDER_RATIO_AXIS not in recorded
+ assert _problems(paths, 3.336) == []
+ assert ladder_ratio_problems({}, 3.336) == []
+
+
+def test_a_session_that_recorded_no_cell_declares_no_ratio(tmp_path):
+ """A run that died before its first cell measured nothing, so it pins nothing."""
+
+ paths = _payload(tmp_path, [])
+ assert _problems(paths, 3.336) == []
+
+
[email protected]("measured", [None])
+def test_an_unmeasurable_ratio_is_not_a_refusal(tmp_path, measured):
+ """`chars_per_token` is null only when there was no text to measure. Nothing to compare."""
+
+ paths = _payload(
+ tmp_path,
+ [_cell("1K", {"ladder_chars_per_token": _ratio(4.0, "whitespace estimate", True)})],
+ )
+ assert _problems(paths, measured) == []
+
+
+# ── A REFUSAL LEAVES THE PAYLOAD IT REFUSED EXACTLY AS IT FOUND IT ──────────────
+
+
+def test_a_refused_resume_rolls_back_every_row_it_wrote(tmp_path):
+ """The refusal arrives after the `Recorder` has opened the file, so it has to undo itself.
+
+ `prepare_payload` and `commit_problems` refuse before the `Recorder` exists. This check cannot:
+ the ratio is not known until `build_cells` has measured the corpus, which is after `run_meta`,
+ after the gates and after an optional `--surfaces` sweep. Without the rollback a refused
+ `--resume --rungs 1K,10K` over a finished 1K payload leaves 10K promised in a file it never
+ touched, and `recorded_ladder` folds every `run_meta` in the file on purpose.
+ """
+
+ paths = _payload(
+ tmp_path,
+ [_cell("1K", {"ladder_chars_per_token": _ratio(3.336, "tiktoken/cl100k", False)})],
+ )
+ before = paths.payload_jsonl.read_bytes()
+ assert recorded_ladder(paths.payload_jsonl) == ["1K", "10K", "100K"]
+
+ # Exactly what `run` writes between opening the payload and asking the ratio question.
+ mark = payload_mark(paths.payload_jsonl)
+ refused = Recorder(paths.payload_jsonl, "sess-2")
+ refused.gate("instrument_unavailable:rss", False, {"error": "psutil is not installed"})
+ refused.emit(
+ {
+ "row_type": "run_meta",
+ "tier": "standard",
+ "tool_version": "0.1.0",
+ "corpus_hash": CORPUS,
+ "studio_ref": "main",
+ "bundle": {"production": True},
+ "platform": {"system": "Linux"},
+ "started_at": "2026-01-02T00:00:00",
+ "cadence": "field",
+ "rungs": ["1K", "10K", "1M"],
+ "reps": 1,
+ "instrument_level": 0,
+ }
+ )
+ refused.gate("ladder_ratio_measured", False, _ratio(4.0, "whitespace estimate", True))
+ assert paths.payload_jsonl.read_bytes() != before
+ assert "1M" in recorded_ladder(paths.payload_jsonl)
+
+ assert _problems(paths, 4.0) != []
+ refused.close()
+ dropped = rollback_session_rows(paths.payload_jsonl, mark, log = lambda _m: None)
+
+ assert dropped > 0
+ assert paths.payload_jsonl.read_bytes() == before
+ # The two ways the leftovers were visible: a rung the payload never owed, and a failed gate
+ # charged to somebody else's evidence.
+ assert recorded_ladder(paths.payload_jsonl) == ["1K", "10K", "100K"]
+ assert [
+ r for r in _rows(paths) if r.get("row_type") == "gate" and r.get("passed") is False
+ ] == []
+ assert {r.get("session_id") for r in _rows(paths)} == {"sess-1"}
+ # And the payload still resumes at the ratio it was recorded at.
+ assert _problems(paths, 3.336) == []
+ assert _resume_set(paths) == {"r1K.A0.rep0"}
+
+
+def test_a_rollback_never_cuts_into_what_it_was_given(tmp_path):
+ """The mark is a floor. A session that wrote nothing drops nothing, and a mark at or beyond the
+ end of the file is a no-op rather than a truncation of somebody else's rows."""
+
+ paths = _payload(
+ tmp_path,
+ [_cell("1K", {"ladder_chars_per_token": _ratio(3.336, "tiktoken/cl100k", False)})],
+ )
+ before = paths.payload_jsonl.read_bytes()
+ mark = payload_mark(paths.payload_jsonl)
+ assert mark == len(before)
+
+ assert rollback_session_rows(paths.payload_jsonl, mark, log = lambda _m: None) == 0
+ assert rollback_session_rows(paths.payload_jsonl, mark + 4096, log = lambda _m: None) == 0
+ assert paths.payload_jsonl.read_bytes() == before
+
+
+def test_the_mark_of_a_payload_that_does_not_exist_yet_is_its_length(tmp_path):
+ """`--resume` onto a missing file: the mark is 0, which is how long that file is."""
+
+ paths = Paths.under(tmp_path / "out")
+ assert payload_mark(paths.payload_jsonl) == 0
+ assert rollback_session_rows(paths.payload_jsonl, 0, log = lambda _m: None) == 0
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_launch_cleanup.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_launch_cleanup.py
new file mode 100644
index 00000000000..96017048ad7
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_launch_cleanup.py
@@ -0,0 +1,213 @@
+# 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 Studio this harness launched and could not reach is terminated, not abandoned.
+
+THE PROCESS WE LAUNCH IS NOT THE PROCESS WE SPAWN. `launch_studio` runs the server under
+`setsid -f`, which always forks and whose parent exits without waiting, so `Popen.pid` belongs to a
+`setsid` that is already gone and the server sits in a session of its own that our process group
+cannot reach. `pgrep` is the only handle on it -- and it used to be taken AFTER the health check,
+so a server that started and stayed unhealthy raised with `install.pid` still None and
+`stop_studio` had nothing to kill.
+
+That leak is not idle. It holds the requested port, and Studio's own launcher aborts rather than
+binding when it finds one of its own servers there (`studio/backend/run.py`, `_resolve_port` with
+`avoid_own_studio`), so the next attempt's server exits and `wait_for_healthz` takes its 200 from
+the STALE one -- which by then has finished starting. The run then measures the build the previous
+attempt installed and records the ref this one asked for.
+
+AND THE PORT CAN BE OCCUPIED WITHOUT ANYTHING HAVING FAILED. `--keep-studio` asks for a Studio to
+be LEFT RUNNING, so no cleanup reaches it by design and the next run walks into exactly the same
+launch: `_discover_pid` pgreps `unsloth studio.*-p <port>` and finds the older process, `/healthz`
+answers 200 from it, and `authenticate` retries with `BENCH_PASSWORD` -- which a previous
+studiobench run has already rotated that Studio to -- so the login succeeds as well. Nothing
+downstream can tell which build answered, so an occupied port is refused before anything is
+launched rather than reported afterwards.
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.runtime import lifecycle # noqa: E402
+from studiobench.runtime.lifecycle import StudioInstall, launch_studio # noqa: E402
+
+STUDIO_PID = 4242
+
+
+def launched(monkeypatch, tmp_path):
+ """Everything `launch_studio` reaches outside this process, stubbed at the seam it uses.
+
+ Returns a dict the test reads back: which pids were signalled, and whether the server was
+ running at all when `pgrep` was asked.
+ """
+
+ state = {
+ "signalled": [],
+ "spawned": [],
+ "pgrep_finds": True,
+ "healthy": False,
+ "port_busy": False,
+ }
+
+ # `raising = False` so this fixture also builds against a lifecycle without the constant, which
+ # is what makes the test below fail on the unfixed code for the reason it is about rather than
+ # on the way in.
+ monkeypatch.setattr(lifecycle, "PID_DISCOVERY_TIMEOUT_S", 0.0, raising = False)
+ # Stubbed for the same reason and, for every test but the two about it, so that whatever this
+ # machine happens to have on :5399 cannot decide the answer.
+ monkeypatch.setattr(
+ lifecycle, "port_is_busy", lambda *a, **k: state["port_busy"], raising = False
+ )
+ monkeypatch.setattr(lifecycle, "_find_unsloth_bin", lambda install: "/bin/true")
+ monkeypatch.setattr(lifecycle, "_read_bootstrap_password", lambda *a, **k: "secret")
+ monkeypatch.setattr(lifecycle, "wait_for_healthz", lambda *a, **k: state["healthy"])
+ # Recorded rather than dropped: a launch refused before the spawn has to be shown not to have
+ # spawned anything.
+ monkeypatch.setattr(subprocess, "Popen", lambda *a, **k: state["spawned"].append(a))
+
+ def fake_run(cmd, *a, **k):
+ assert cmd[0] == "pgrep", cmd
+ out = f"{STUDIO_PID}\n" if state["pgrep_finds"] else ""
+ return subprocess.CompletedProcess(cmd, 0, stdout = out, stderr = "")
+
+ monkeypatch.setattr(lifecycle, "_run", fake_run)
+ monkeypatch.setattr(os, "getpgid", lambda pid: pid)
+ monkeypatch.setattr(os, "killpg", lambda pgid, sig: state["signalled"].append((pgid, sig)))
+
+ state["install"] = StudioInstall(home = tmp_path / "home", repo = tmp_path / "repo", branch = "main")
+ state["log"] = tmp_path / "studio.log"
+ return state
+
+
+def test_a_studio_that_never_answers_healthz_is_terminated(launched):
+ launched["healthy"] = False
+
+ with pytest.raises(TimeoutError):
+ launch_studio(launched["install"], 5399, launched["log"], healthz_timeout_s = 1)
+
+ assert launched["install"].pid == STUDIO_PID
+ assert [pgid for pgid, _sig in launched["signalled"]] == [STUDIO_PID]
+
+
+def test_a_studio_that_never_started_at_all_still_raises(launched):
+ """The control for the discovery itself: nothing to find is not a reason to crash on the way
+ to reporting the timeout."""
+
+ launched["healthy"] = False
+ launched["pgrep_finds"] = False
+
+ with pytest.raises(TimeoutError):
+ launch_studio(launched["install"], 5399, launched["log"], healthz_timeout_s = 1)
+
+ assert launched["install"].pid is None
+ assert launched["signalled"] == []
+
+
+def test_a_healthy_studio_is_returned_with_its_pid_and_is_not_signalled(launched):
+ """The control that matters: the ordinary launch must still hand back a running Studio."""
+
+ launched["healthy"] = True
+
+ install = launch_studio(launched["install"], 5399, launched["log"], healthz_timeout_s = 1)
+
+ assert install.pid == STUDIO_PID
+ assert install.port == 5399
+ assert install.base_url == "http://127.0.0.1:5399"
+ assert install.bootstrap_password == "secret"
+ assert launched["signalled"] == []
+
+
+def test_a_healthy_studio_whose_pid_cannot_be_found_is_still_returned(launched):
+ """`pgrep` is a best effort and always has been; losing it may not fail a healthy launch."""
+
+ launched["healthy"] = True
+ launched["pgrep_finds"] = False
+
+ install = launch_studio(launched["install"], 5399, launched["log"], healthz_timeout_s = 1)
+
+ assert install.pid is None
+ assert launched["signalled"] == []
+
+
+# ── the port somebody else is already on ────────────────────────────────────────────────────
+
+
+def test_a_port_that_is_already_serving_is_refused_before_anything_is_launched(launched):
+ """The `--keep-studio` case, which no cleanup covers because retention is what was asked for.
+
+ Everything downstream would have agreed the launch worked: `pgrep` finds the older server on
+ the same port, `/healthz` answers 200 from it, and `authenticate` reaches it with the password
+ a previous run rotated it to. The refusal has to arrive before the spawn.
+ """
+
+ launched["port_busy"] = True
+ launched["healthy"] = True
+
+ with pytest.raises(RuntimeError) as excinfo:
+ launch_studio(launched["install"], 5399, launched["log"], healthz_timeout_s = 1)
+
+ assert "5399" in str(excinfo.value)
+ assert launched["spawned"] == []
+
+
+def test_the_occupied_port_does_not_come_back_as_a_healthy_studio(launched):
+ """The consequence, stated as the caller sees it: no `StudioInstall` is returned at all, so
+ nothing records a ref against a build it never installed."""
+
+ launched["port_busy"] = True
+ launched["healthy"] = True
+
+ with pytest.raises(RuntimeError):
+ launch_studio(launched["install"], 5399, launched["log"], healthz_timeout_s = 1)
+
+ assert launched["install"].port is None
+ assert launched["signalled"] == []
+
+
+def test_a_free_port_still_launches(launched):
+ """The control: the guard may not refuse the ordinary launch."""
+
+ launched["healthy"] = True
+
+ install = launch_studio(launched["install"], 5399, launched["log"], healthz_timeout_s = 1)
+
+ assert install.pid == STUDIO_PID
+ assert install.port == 5399
+ assert len(launched["spawned"]) == 1
+
+
+def test_the_probe_itself_gives_both_answers_against_a_real_socket():
+ """The probe, unstubbed, against a listener this test owns.
+
+ A guard that answered "busy" for everything would pass both tests above and refuse every real
+ launch, so the two answers are taken from a real socket rather than from the stub.
+ """
+
+ import socket
+
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(1)
+ port = listener.getsockname()[1]
+ assert lifecycle.port_is_busy(port) is True
+
+ # Closed, so the same port is now the negative case. A port the kernel has just released can
+ # linger in TIME_WAIT for a connect, which is why the assertion below is on a port that was
+ # never bound at all rather than on this one.
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
+ probe.bind(("127.0.0.1", 0))
+ free_port = probe.getsockname()[1]
+ assert lifecycle.port_is_busy(free_port) is False
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_lifecycle_refs.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_lifecycle_refs.py
new file mode 100644
index 00000000000..3b026602a98
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_lifecycle_refs.py
@@ -0,0 +1,119 @@
+# 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 ref is a branch, a tag OR a commit, and the installer has to take all three.
+
+CONTRIBUTING-perf.md tells a reader to measure an already-merged change as `merge commit` against
+`merge commit^1`. Both of those are commit shas, and `git clone --branch <sha>` resolves against
+the remote's advertised branches and tags: it exits with `Remote branch <sha> not found in upstream
+origin` before anything is installed. The reused-clone path was broken the same way by
+`reset --hard origin/<sha>`, which is not a name that exists either.
+
+Run against a local repository over the filesystem, so the test needs no network.
+
+ python -m pytest tests/studio/studiobench/runtime/selftest/test_studiobench_lifecycle_refs.py
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.runtime.lifecycle import checkout_ref # noqa: E402
+
+pytestmark = pytest.mark.skipif(shutil.which("git") is None, reason = "git is not installed")
+
+
+def _git(
+ *args,
+ cwd,
+ check = True,
+):
+ return subprocess.run(
+ ["git", *args],
+ cwd = str(cwd),
+ text = True,
+ capture_output = True,
+ check = check,
+ env = {
+ "GIT_AUTHOR_NAME": "studiobench",
+ "GIT_AUTHOR_EMAIL": "[email protected]",
+ "GIT_COMMITTER_NAME": "studiobench",
+ "GIT_COMMITTER_EMAIL": "[email protected]",
+ # No user or system git config: an `init.defaultBranch`, a `commit.gpgsign` or a
+ # `clone.defaultRemoteName` on the machine running the tests would otherwise decide
+ # what this repository looks like.
+ "GIT_CONFIG_GLOBAL": os.devnull,
+ "GIT_CONFIG_SYSTEM": os.devnull,
+ "HOME": str(cwd),
+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),
+ },
+ )
+
+
+def _origin(tmp_path: Path) -> tuple[Path, str, str]:
+ """A repository with two commits on `main`. Returns (path, first sha, second sha)."""
+ origin = tmp_path / "origin"
+ origin.mkdir()
+ _git("init", "--initial-branch=main", cwd = origin)
+ (origin / "install.sh").write_text("first\n")
+ _git("add", "-A", cwd = origin)
+ _git("commit", "-m", "first", cwd = origin)
+ first = _git("rev-parse", "HEAD", cwd = origin).stdout.strip()
+ (origin / "install.sh").write_text("second\n")
+ _git("commit", "-am", "second", cwd = origin)
+ second = _git("rev-parse", "HEAD", cwd = origin).stdout.strip()
+ # A bare mirror, because a fetch from a non-bare checkout of the same branch is a special case
+ # and the real remote is a server.
+ bare = tmp_path / "origin.git"
+ _git("clone", "--bare", str(origin), str(bare), cwd = tmp_path)
+ return bare, first, second
+
+
+def test_clone_branch_cannot_take_a_commit(tmp_path):
+ """The reason this module does not use `git clone --branch <ref>`, asserted rather than said."""
+
+ bare, first, _second = _origin(tmp_path)
+ got = _git(
+ "clone", "--branch", first, str(bare), str(tmp_path / "byclone"), cwd = tmp_path, check = False
+ )
+ assert got.returncode != 0
+ assert "not found in upstream origin" in (got.stderr + got.stdout)
+
+
+def test_checkout_ref_takes_a_branch_a_tag_and_a_commit(tmp_path):
+ bare, first, second = _origin(tmp_path)
+ _git("tag", "v1", first, cwd = bare)
+
+ repo = tmp_path / "repo"
+ _git("clone", str(bare), str(repo), cwd = tmp_path)
+
+ assert checkout_ref(repo, "main") == second
+ assert (repo / "install.sh").read_text() == "second\n"
+
+ # THE CASE THAT WAS BROKEN: a bare commit sha, which is what `merge commit^1` resolves to.
+ assert checkout_ref(repo, first) == first
+ assert (repo / "install.sh").read_text() == "first\n"
+
+ assert checkout_ref(repo, "v1") == first
+ # And a local expression the remote will not serve by name.
+ assert checkout_ref(repo, f"{second}^1") == first
+
+
+def test_an_unknown_ref_says_so(tmp_path):
+ bare, _first, _second = _origin(tmp_path)
+ repo = tmp_path / "repo"
+ _git("clone", str(bare), str(repo), cwd = tmp_path)
+ with pytest.raises(RuntimeError, match = "could not be resolved"):
+ checkout_ref(repo, "no-such-ref")
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.py
new file mode 100644
index 00000000000..f32e5d08030
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_payload_identity.py
@@ -0,0 +1,657 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""One `--out` holds one run, and `--resume` continues the run that is in it.
+
+A cell id is `r{rung}.{arm}.rep{rep}` and nothing more, so the tier that picked the film, the
+cadence the reply streamed at, the instrument level, the corpus and both refs are all invisible to
+the two places that decide what a payload already contains. Two ways that produced a report about
+something nobody ran:
+
+ A RESUME UNDER A DIFFERENT CONFIGURATION SKIPPED EVERYTHING. `--branch main --ab other --resume`
+ into a directory holding a finished `main -> fix` run installs and launches two Studios, finds
+ every `cell_id` already complete, exits 0, and -- because `_render_ab` keeps the previous table
+ when this session measured nothing -- leaves the OLD comparison standing in `ab.md` to be read
+ as the answer for `other`.
+
+ A FRESH RUN APPENDED TO THE PREVIOUS ONE. `Recorder` opens the payload with `"a"`. The README's
+ own two invocations wrote into one `--out`, and when the second was interrupted the file held a
+ fast-tier 100K cell from an attached Studio next to standard-tier 1K and 10K cells from `main`.
+ `--report` scored that as one ladder, took its header from the FIRST `run_meta`, and said
+ `complete: true`.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.__main__ import ( # noqa: E402
+ _resume_set,
+ archive_payload,
+ parse_args,
+ prepare_payload,
+ requested_identity,
+)
+from studiobench.report.build import build_report, score_payload # noqa: E402
+from studiobench.runtime.types import Paths, Recorder # noqa: E402
+from studiobench.scoring.from_payload import ( # noqa: E402
+ latest_attempt_rows,
+ measures_from_records,
+)
+
+CORPUS = "c0ffee"
+
+
+def _run_meta(tier, ref, rungs, **extra):
+ row = {
+ "row_type": "run_meta",
+ "tier": tier,
+ "tool_version": "0.1.0",
+ "corpus_hash": CORPUS,
+ "studio_ref": ref,
+ "bundle": {"production": True},
+ "platform": {"system": "Linux"},
+ "started_at": "2026-01-01T00:00:00",
+ "cadence": "field",
+ "rungs": rungs,
+ "reps": 1,
+ "instrument_level": 0,
+ }
+ row.update(extra)
+ return row
+
+
+def _cell(
+ cell_id,
+ tokens,
+ arm = "A0",
+ rep = 0,
+ tier = "standard",
+):
+ return {
+ "row_type": "cell",
+ "cell_id": cell_id,
+ "cell": {"arm": arm, "rep": rep, "tier": tier},
+ "completed": True,
+ "fidelity": "ok",
+ "target_tokens": tokens,
+ }
+
+
+def _keystroke(cell_id, p95):
+ return {
+ "row_type": "action",
+ "cell_id": cell_id,
+ "action": "keystroke",
+ "window": "film",
+ "ran": True,
+ "expect_ok": True,
+ "expect": {},
+ "timings": {"p95_ms": p95},
+ "slot_missed": False,
+ }
+
+
+def _record(paths, session, rows):
+ """Write `rows` through the REAL recorder, which is what appends in a live run."""
+ recorder = Recorder(paths.payload_jsonl, session)
+ for row in rows:
+ recorder.emit(dict(row))
+ recorder.close()
+
+
+def _finished_ab(
+ tmp_path,
+ *,
+ tier = "standard",
+ base = "main",
+ treatment = "fix",
+ treatment_url = "",
+) -> Paths:
+ paths = Paths.under(tmp_path / "out")
+ _record(
+ paths,
+ "sess-1",
+ [
+ _run_meta(tier, base, ["10K"]),
+ {
+ "row_type": "ab_plan",
+ "base_ref": base,
+ "treatment_ref": treatment,
+ # Empty for a treatment the run installed itself, exactly as `run()` records it.
+ "treatment_url": treatment_url,
+ "balanced": False,
+ "order": ["r10K.base.rep0", "r10K.treatment.rep0"],
+ },
+ _cell("r10K.base.rep0", 10_000, arm = "base", tier = tier),
+ _keystroke("r10K.base.rep0", 100.0),
+ _cell("r10K.treatment.rep0", 10_000, arm = "treatment", tier = tier),
+ _keystroke("r10K.treatment.rep0", 50.0),
+ ],
+ )
+ return paths
+
+
+# ── a resume must be a resume OF THIS RUN ───────────────────────────────────────────────────
+
+
+def test_resuming_after_changing_the_treatment_ref_is_refused(tmp_path):
+ paths = _finished_ab(tmp_path)
+ args = parse_args(["--tier", "standard", "--branch", "main", "--ab", "other", "--resume"])
+
+ with pytest.raises(SystemExit) as excinfo:
+ prepare_payload(
+ paths, requested_identity(args, "other", CORPUS), resume = True, log = lambda *_a: None
+ )
+
+ message = str(excinfo.value)
+ assert "treatment_ref" in message
+ assert "'fix'" in message and "'other'" in message
+
+
+def test_resuming_a_self_managed_treatment_against_an_attached_one_is_refused(tmp_path):
+ """The label after `--ab` says nothing about where the build came from.
+
+ The payload's treatment was cloned and built by that run; this one points the same label at a
+ server the caller is holding open. Two different builds, one `--ab fix`.
+ """
+
+ paths = _finished_ab(tmp_path)
+ args = parse_args(
+ ["--tier", "standard", "--branch", "main", "--ab", "fix"]
+ + ["--attach-b", "http://127.0.0.1:5311", "--resume"]
+ )
+
+ with pytest.raises(SystemExit) as excinfo:
+ prepare_payload(
+ paths, requested_identity(args, "fix", CORPUS), resume = True, log = lambda *_a: None
+ )
+
+ assert "treatment_url" in str(excinfo.value)
+
+
+def test_resuming_after_changing_the_branch_is_refused(tmp_path):
+ paths = _finished_ab(tmp_path)
+ args = parse_args(["--tier", "standard", "--branch", "release", "--ab", "fix", "--resume"])
+
+ with pytest.raises(SystemExit) as excinfo:
+ prepare_payload(
+ paths, requested_identity(args, "fix", CORPUS), resume = True, log = lambda *_a: None
+ )
+
+ assert "studio_ref" in str(excinfo.value)
+
+
+def test_resuming_a_fast_tier_payload_under_the_standard_tier_is_refused(tmp_path):
+ """The films differ: 243 s of scene against 47 s, with different budgets and headroom."""
+
+ paths = _finished_ab(tmp_path, tier = "fast")
+ args = parse_args(["--tier", "standard", "--branch", "main", "--ab", "fix", "--resume"])
+
+ with pytest.raises(SystemExit) as excinfo:
+ prepare_payload(
+ paths, requested_identity(args, "fix", CORPUS), resume = True, log = lambda *_a: None
+ )
+
+ assert "tier" in str(excinfo.value)
+
+
+def test_resuming_after_changing_the_cadence_or_the_instrument_level_is_refused(tmp_path):
+ paths = _finished_ab(tmp_path)
+ args = parse_args(
+ ["--tier", "standard", "--branch", "main", "--ab", "fix", "--cadence", "fast"]
+ + ["--instrument-level", "3", "--resume"]
+ )
+
+ with pytest.raises(SystemExit) as excinfo:
+ prepare_payload(
+ paths, requested_identity(args, "fix", CORPUS), resume = True, log = lambda *_a: None
+ )
+
+ message = str(excinfo.value)
+ assert "cadence" in message
+ assert "instrument_level" in message
+
+
+def test_the_refusal_happens_before_anything_is_installed_or_recorded(tmp_path):
+ """A refusal that costs a clone and a build has said nothing it could not have said at once.
+
+ And it must not leave its own `run_meta` behind: a rejected run's header in the payload it
+ refused to touch would then reject the correctly configured resume that followed it.
+ """
+
+ paths = _finished_ab(tmp_path)
+ before = paths.payload_jsonl.read_text(encoding = "utf-8")
+ args = parse_args(["--tier", "standard", "--branch", "main", "--ab", "other", "--resume"])
+
+ with pytest.raises(SystemExit):
+ prepare_payload(
+ paths, requested_identity(args, "other", CORPUS), resume = True, log = lambda *_a: None
+ )
+
+ assert paths.payload_jsonl.read_text(encoding = "utf-8") == before
+ assert sorted(p.name for p in paths.out.glob("payload*.jsonl")) == ["payload.jsonl"]
+
+
+# ── the controls: a legitimate resume still resumes ──────────────────────────────────────────
+
+
+def test_the_same_configuration_still_resumes(tmp_path):
+ paths = _finished_ab(tmp_path)
+ args = parse_args(["--tier", "standard", "--branch", "main", "--ab", "fix", "--resume"])
+
+ assert (
+ prepare_payload(
+ paths, requested_identity(args, "fix", CORPUS), resume = True, log = lambda *_a: None
+ )
+ is None
+ )
+ assert _resume_set(paths) == {"r10K.base.rep0", "r10K.treatment.rep0"}
+
+
+def test_resuming_with_more_reps_and_another_rung_is_still_a_resume(tmp_path):
+ """`--reps` and `--rungs` ADD cells; they do not reinterpret the ones already recorded."""
+
+ paths = _finished_ab(tmp_path)
+ args = parse_args(
+ ["--tier", "standard", "--branch", "main", "--ab", "fix", "--reps", "4"]
+ + ["--rungs", "10K,100K", "--resume"]
+ )
+
+ assert (
+ prepare_payload(
+ paths, requested_identity(args, "fix", CORPUS), resume = True, log = lambda *_a: None
+ )
+ is None
+ )
+
+
+def test_a_payload_that_never_recorded_an_axis_still_resumes(tmp_path):
+ """The legacy control. An older payload carries only the required `run_meta` keys, and an axis
+ it never declared cannot be a difference."""
+
+ paths = Paths.under(tmp_path / "out")
+ legacy = {
+ "row_type": "run_meta",
+ "tier": "standard",
+ "tool_version": "0.0.9",
+ "corpus_hash": CORPUS,
+ "studio_ref": "main",
+ "bundle": {"production": True},
+ "platform": {"system": "Linux"},
+ "started_at": "2026-01-01T00:00:00",
+ }
+ _record(
+ paths, "sess-old", [legacy, _cell("r10K.A0.rep0", 10_000), _keystroke("r10K.A0.rep0", 9)]
+ )
+ args = parse_args(
+ ["--tier", "standard", "--branch", "main", "--cadence", "fast"]
+ + ["--instrument-level", "2", "--resume"]
+ )
+
+ assert (
+ prepare_payload(
+ paths, requested_identity(args, None, CORPUS), resume = True, log = lambda *_a: None
+ )
+ is None
+ )
+ assert _resume_set(paths) == {"r10K.A0.rep0"}
+
+
+def test_resuming_an_ab_payload_as_a_single_build_run_is_refused(tmp_path):
+ """The other direction of the mode transition, refused for the same reason.
+
+ The A/B's `base` cells stay in the payload and stay first at their rung, so the ladder keeps
+ reporting them and never the `A0` cells this run is about to measure."""
+
+ paths = _finished_ab(tmp_path, treatment_url = "http://127.0.0.1:5311")
+ args = parse_args(["--tier", "standard", "--branch", "main", "--resume"])
+
+ with pytest.raises(SystemExit) as excinfo:
+ prepare_payload(
+ paths, requested_identity(args, None, CORPUS), resume = True, log = lambda *_a: None
+ )
+
+ assert "mode" in str(excinfo.value)
+
+
+def test_an_ab_payload_that_never_recorded_a_treatment_url_still_resumes(tmp_path):
+ """The legacy control for the newest axis: an `ab_plan` written before the URL was recorded
+ declares nothing about it, and an axis a row never declared cannot be a difference."""
+
+ paths = Paths.under(tmp_path / "out")
+ _record(
+ paths,
+ "sess-1",
+ [
+ _run_meta("standard", "attached:http://127.0.0.1:5310", ["10K"]),
+ {
+ "row_type": "ab_plan",
+ "base_ref": "main",
+ "treatment_ref": "fix",
+ "balanced": False,
+ "order": ["r10K.base.rep0", "r10K.treatment.rep0"],
+ },
+ _cell("r10K.base.rep0", 10_000, arm = "base"),
+ ],
+ )
+ args = parse_args(
+ ["--tier", "standard", "--attach", "http://127.0.0.1:5310", "--ab", "fix"]
+ + ["--attach-b", "http://127.0.0.1:5311", "--resume"]
+ )
+
+ assert (
+ prepare_payload(
+ paths, requested_identity(args, "fix", CORPUS), resume = True, log = lambda *_a: None
+ )
+ is None
+ )
+
+
+def test_resuming_a_single_build_payload_as_an_ab_is_refused(tmp_path):
+ """`A0` against `base`/`treatment` keeps the new cells from being SKIPPED. It does not keep
+ them out of the REPORT, which is a different question and the one that decides this.
+
+ `score_payload` hands every cell to `measures_from_records`, which keys by rung and keeps the
+ first reading, and `_completion_by_rung` keeps a failure over a success at the same rung. So
+ the payload below -- a single-build run that died at 10K, then an A/B that measured both arms
+ of 10K without a fault -- reports `INCOMPLETE: timeout: the base died at 10K`, scores the rung
+ 0 and prints ONSET RUNG: none, over a rung two arms had just measured. The same crash resumed
+ WITHOUT `--ab` reuses the cell id, `latest_attempt_rows` supersedes the dead attempt, and the
+ rung scores. The mode is part of what the payload measured; changing it is not a resume.
+ """
+
+ paths = Paths.under(tmp_path / "out")
+ _record(
+ paths,
+ "sess-1",
+ [_run_meta("standard", "main", ["10K"]), _cell("r10K.A0.rep0", 10_000)],
+ )
+ args = parse_args(["--tier", "standard", "--branch", "main", "--ab", "fix", "--resume"])
+
+ with pytest.raises(SystemExit) as excinfo:
+ prepare_payload(
+ paths, requested_identity(args, "fix", CORPUS), resume = True, log = lambda *_a: None
+ )
+
+ assert "mode" in str(excinfo.value)
+
+
+def test_a_session_that_died_before_its_first_cell_declares_no_mode(tmp_path):
+ """The control for the refusal above: it may not fire on a run that measured nothing.
+
+ `run_meta` is written after both installs and `ab_plan` after the corpus and the gates, so an
+ A/B killed in between leaves a header and no cells. There is nothing there for a later report
+ to keep in preference to this one's readings, so resuming it is a resume.
+ """
+
+ paths = Paths.under(tmp_path / "out")
+ _record(paths, "sess-1", [_run_meta("standard", "main", ["10K"])])
+ args = parse_args(["--tier", "standard", "--branch", "main", "--ab", "fix", "--resume"])
+
+ assert (
+ prepare_payload(
+ paths, requested_identity(args, "fix", CORPUS), resume = True, log = lambda *_a: None
+ )
+ is None
+ )
+
+
+def _one_engine_rung(
+ tmp_path,
+ engine,
+ name = "out",
+) -> Paths:
+ """A payload holding one measured rung, recorded by a session that launched `engine`."""
+
+ paths = Paths.under(tmp_path / name)
+ _record(
+ paths,
+ "sess-1",
+ [
+ _run_meta(
+ "standard",
+ "main",
+ ["1K", "10K"],
+ platform = {"system": "Linux", "engine": engine, "engine_note": "for this test"},
+ ),
+ _cell("r1K.A0.rep0", 1_000),
+ _keystroke("r1K.A0.rep0", 40.0),
+ ],
+ )
+ return paths
+
+
+def test_resuming_under_a_different_browser_engine_is_refused(tmp_path):
+ """The engine RENDERED every number in the payload, and the cell id does not name it.
+
+ A run that measured 1K under Chromium, resumed under WebKit to add 10K, skips the completed
+ Chromium cell and measures the new rung under a different renderer -- and the two land in one
+ ladder, which `score_payload` reads as one build getting slower with context. The engine is
+ part of what a payload measured, exactly like the tier and the cadence.
+ """
+
+ paths = _one_engine_rung(tmp_path, "chromium")
+ args = parse_args(
+ ["--tier", "standard", "--branch", "main", "--engine", "webkit"]
+ + ["--rungs", "1K,10K", "--resume"]
+ )
+
+ with pytest.raises(SystemExit) as excinfo:
+ prepare_payload(
+ paths, requested_identity(args, None, CORPUS), resume = True, log = lambda *_a: None
+ )
+
+ message = str(excinfo.value)
+ assert "engine" in message
+ assert "'chromium'" in message and "'webkit'" in message
+
+
+def test_the_engine_compared_is_the_one_that_will_launch_not_the_flag(tmp_path):
+ """`--engine` defaults to nothing and `browser.launch` resolves the platform's webview family.
+
+ So the commonest engine change of all is the one where the second invocation names no engine
+ at all, and comparing the flags rather than the resolved engines would wave it through.
+ """
+
+ from studiobench.runtime.browser import default_engine
+
+ other = "chromium" if default_engine()[0] != "chromium" else "webkit"
+ paths = _one_engine_rung(tmp_path, other)
+ args = parse_args(["--tier", "standard", "--branch", "main", "--rungs", "1K,10K", "--resume"])
+
+ assert requested_identity(args, None, CORPUS)["engine"] == default_engine()[0]
+ with pytest.raises(SystemExit) as excinfo:
+ prepare_payload(
+ paths, requested_identity(args, None, CORPUS), resume = True, log = lambda *_a: None
+ )
+
+ assert "engine" in str(excinfo.value)
+
+
+def test_the_same_engine_still_resumes(tmp_path):
+ """The control: naming the engine the payload was recorded under is a resume."""
+
+ paths = _one_engine_rung(tmp_path, "chromium")
+ args = parse_args(
+ ["--tier", "standard", "--branch", "main", "--engine", "chromium"]
+ + ["--rungs", "1K,10K", "--resume"]
+ )
+
+ assert (
+ prepare_payload(
+ paths, requested_identity(args, None, CORPUS), resume = True, log = lambda *_a: None
+ )
+ is None
+ )
+ assert _resume_set(paths) == {"r1K.A0.rep0"}
+
+
+def test_a_payload_that_never_recorded_an_engine_still_resumes(tmp_path):
+ """The legacy control for this axis, and the one for a session that never got a browser up.
+
+ `run_meta` is emitted after `browser.launch` returns, so a session with no engine in its
+ header either predates the field or never launched anything. Neither declares an engine, and
+ an axis a row never declared cannot be a difference.
+ """
+
+ paths = Paths.under(tmp_path / "out")
+ _record(
+ paths,
+ "sess-old",
+ [
+ _run_meta("standard", "main", ["1K", "10K"], platform = {"system": "Linux"}),
+ _cell("r1K.A0.rep0", 1_000),
+ _keystroke("r1K.A0.rep0", 40.0),
+ ],
+ )
+ args = parse_args(
+ ["--tier", "standard", "--branch", "main", "--engine", "firefox"]
+ + ["--rungs", "1K,10K", "--resume"]
+ )
+
+ assert (
+ prepare_payload(
+ paths, requested_identity(args, None, CORPUS), resume = True, log = lambda *_a: None
+ )
+ is None
+ )
+ assert _resume_set(paths) == {"r1K.A0.rep0"}
+
+
+def test_the_report_a_mode_change_would_have_produced(tmp_path):
+ """WHY the refusal above exists, as a number rather than as an argument.
+
+ Both payloads hold the same facts: 10K died under one run and was measured clean under the
+ next. The only difference is whether the repair ran under `--ab`, which changes the arm and
+ so the cell id -- and with it whether the dead attempt is superseded or kept.
+ """
+
+ def _payload(name, repair_arm):
+ paths = Paths.under(tmp_path / name)
+ dead = _cell("r10K.A0.rep0", 10_000)
+ dead["completed"] = False
+ dead["failure"] = {"kind": "timeout", "message": "the base died at 10K"}
+ _record(paths, "sess-1", [_run_meta("standard", "main", ["10K"]), dead])
+ cell_id = f"r10K.{repair_arm}.rep0"
+ _record(
+ paths,
+ "sess-2",
+ [
+ _run_meta("standard", "main", ["10K"]),
+ _cell(cell_id, 10_000, arm = repair_arm),
+ _keystroke(cell_id, 100.0),
+ ],
+ )
+ return paths
+
+ same_mode = score_payload(_payload("same", "A0").payload_jsonl, [10_000])
+ changed_mode = score_payload(_payload("changed", "base").payload_jsonl, [10_000])
+
+ # Same mode: the retry reuses the cell id, so the crash is superseded and never reaches the
+ # ladder. Change the mode and the same crash is a cell of its own, first at its rung, and it
+ # is what the report prints -- over a rung the run being reported measured cleanly.
+ assert "died at 10K" not in (same_mode.rungs[0].incomplete_reason or "")
+ assert "died at 10K" in (changed_mode.rungs[0].incomplete_reason or "")
+
+
+# ── a fresh run does not append to the run before it ─────────────────────────────────────────
+
+
+def test_a_fresh_run_moves_the_previous_payload_aside(tmp_path):
+ paths = _finished_ab(tmp_path)
+ before = paths.payload_jsonl.read_text(encoding = "utf-8")
+
+ archived = prepare_payload(
+ paths,
+ requested_identity(parse_args(["--tier", "standard"]), None, CORPUS),
+ resume = False,
+ log = lambda *_a: None,
+ )
+
+ assert archived is not None and archived.exists()
+ assert archived.read_text(encoding = "utf-8") == before
+ assert not paths.payload_jsonl.exists()
+
+
+def test_the_readme_sequence_no_longer_scores_two_runs_as_one_ladder(tmp_path):
+ """`--tier fast --attach ... --out X` then `--tier standard --branch main --out X`, the second
+ killed before its top rung. The 100K reading must not be the fast run's."""
+
+ paths = Paths.under(tmp_path / "out")
+ _record(
+ paths,
+ "sess-fast",
+ [
+ _run_meta("fast", "attached:http://127.0.0.1:5401", ["100K"]),
+ _cell("r100K.A0.rep0", 100_000, tier = "fast"),
+ _keystroke("r100K.A0.rep0", 900.0),
+ ],
+ )
+
+ prepare_payload(
+ paths,
+ requested_identity(parse_args(["--tier", "standard", "--branch", "main"]), None, CORPUS),
+ resume = False,
+ log = lambda *_a: None,
+ )
+ # The standard run, killed by the watchdog after 10K.
+ _record(
+ paths,
+ "sess-standard",
+ [
+ _run_meta("standard", "main", ["1K", "10K", "100K"]),
+ _cell("r1K.A0.rep0", 1_000),
+ _keystroke("r1K.A0.rep0", 40.0),
+ _cell("r10K.A0.rep0", 10_000),
+ _keystroke("r10K.A0.rep0", 55.0),
+ ],
+ )
+
+ rows = [
+ json.loads(line)
+ for line in paths.payload_jsonl.read_text(encoding = "utf-8").splitlines()
+ if line.strip()
+ ]
+ measures = measures_from_records(latest_attempt_rows(rows))
+ assert 100_000 not in measures, "the fast tier's 100K cell is in the standard run's ladder"
+ assert {1_000, 10_000} <= set(measures)
+
+ _text, _ladder, payload = build_report(paths.payload_jsonl, [1_000, 10_000, 100_000])
+ assert payload["header"]["tier"] == "standard"
+ assert payload["header"]["studio_ref"] == "main"
+
+
+def test_a_fresh_run_into_a_new_directory_archives_nothing(tmp_path):
+ paths = Paths.under(tmp_path / "out")
+ assert archive_payload(paths, log = lambda *_a: None) is None
+
+
+def test_an_empty_payload_is_not_worth_archiving(tmp_path):
+ paths = Paths.under(tmp_path / "out")
+ paths.payload_jsonl.write_text("", encoding = "utf-8")
+ assert archive_payload(paths, log = lambda *_a: None) is None
+ assert paths.payload_jsonl.exists()
+
+
+def test_a_resume_never_archives(tmp_path):
+ paths = _finished_ab(tmp_path)
+ before = paths.payload_jsonl.read_text(encoding = "utf-8")
+ args = parse_args(["--tier", "standard", "--branch", "main", "--ab", "fix", "--resume"])
+
+ prepare_payload(
+ paths, requested_identity(args, "fix", CORPUS), resume = True, log = lambda *_a: None
+ )
+
+ assert paths.payload_jsonl.read_text(encoding = "utf-8") == before
+ assert sorted(p.name for p in paths.out.glob("payload*.jsonl")) == ["payload.jsonl"]
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_resume_commit.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_resume_commit.py
new file mode 100644
index 00000000000..7320f026147
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_resume_commit.py
@@ -0,0 +1,265 @@
+# 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 ref is a pointer, so a resume is judged on the COMMIT the ref resolved to.
+
+`prepare_payload` refuses a `--resume` whose configuration differs from the payload's, and every
+axis it compares is a string the caller typed. `--branch main --ab fix` is the same string today
+that it was yesterday; the build behind it is not. `checkout_ref` fetches and resolves the ref
+afresh on every install and RETURNS the commit it landed on, and that return value was thrown
+away, so nothing in the payload ever recorded which build produced its cells.
+
+The result passed every check and was invisible: the completed cells were skipped, the rungs the
+payload still owed were measured on today's build, and `report.assemble_rows` printed the mixture
+under one header naming one ref. `unslothai/main` moves several times a day and a topic branch
+under review moves whenever it is pushed to, so this is the ordinary shape of an interrupted run
+resumed the next morning, not an unusual one.
+
+The commit cannot be known where the other axes are checked -- `prepare_payload` runs BEFORE
+anything is installed, deliberately, so a refusal costs a millisecond rather than two clones and
+two builds. So it is checked at the first moment it exists: after the sides are up, before the
+browser, the pacer and every cell.
+
+`run()` itself is driven, with the seams that leave this process stubbed at the boundary they
+cross. The identity, the payload and the refusal are the shipped ones.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+import studiobench.__main__ as sb # noqa: E402
+from studiobench import pacer as pacer_mod # noqa: E402
+from studiobench.runtime import browser as browser_mod # noqa: E402
+from studiobench.runtime import bundle_guard, lifecycle # noqa: E402
+from studiobench.runtime import session as session_mod # noqa: E402
+from studiobench.runtime.lifecycle import StudioAuth, StudioInstall # noqa: E402
+from studiobench.runtime.types import Paths # noqa: E402
+
+
+class _Verdict:
+ production = True
+ bundle_type = 0
+ reason = "production build"
+
+ def as_dict(self) -> dict:
+ return {"production": True, "reason": self.reason}
+
+
+class _Bundle:
+ # WHAT `browser.launch` WOULD HAVE RESOLVED on the machine running this test. `run_meta`
+ # records the engine and `requested_identity` resolves the same way, so a stub that names a
+ # fixed one would make a legitimate resume look like an engine change off Linux and macOS.
+ engine = browser_mod.default_engine()[0]
+ engine_note = "stubbed for this test"
+ browser = context = page = cdp = None
+
+ def close(self) -> None:
+ pass
+
+
+class _Pacer:
+ base_url = "http://127.0.0.1:65535"
+
+ def __init__(self) -> None:
+ self.state = types.SimpleNamespace(model_ids = [])
+
+ def start(self):
+ return self
+
+ def stop(self) -> None:
+ pass
+
+
+class _Runner:
+ def __init__(self, **kwargs) -> None:
+ self.kwargs = kwargs
+
+ def run(self, cell, plan) -> dict:
+ return {
+ "cell_id": cell.cell_id,
+ "completed": True,
+ "actions": [{"action": "keystroke", "ran": True}],
+ }
+
+
+def studio(monkeypatch, tmp_path):
+ """Every seam `run()` reaches outside this process. `commits` is the knob: which commit each
+ ref resolves to on THIS invocation, which is what moving a branch means here."""
+
+ state = {"commits": {}, "stopped": [], "out": tmp_path / "out"}
+
+ def fake_install(ref, home, *args, **kwargs):
+ install = StudioInstall(home = Path(home), repo = Path(home).parent / "repo", branch = ref)
+ # `setattr` rather than a constructor argument, so this fixture also builds against a
+ # `StudioInstall` that has no commit field and the tests below fail on the subject rather
+ # than on the way in.
+ install.commit = state["commits"].get(ref, f"c-{ref}-1")
+ return install
+
+ def fake_launch(install, port, log_path, *args, **kwargs):
+ install.port = port
+ install.pid = 90_000 + port
+ install.bootstrap_password = "secret"
+ return install
+
+ monkeypatch.setattr(lifecycle, "install_studio", fake_install)
+ monkeypatch.setattr(lifecycle, "launch_studio", fake_launch)
+ monkeypatch.setattr(lifecycle, "stop_studio", lambda install: state["stopped"].append(install))
+ monkeypatch.setattr(lifecycle, "wait_for_healthz", lambda *a, **k: True)
+ monkeypatch.setattr(
+ lifecycle,
+ "authenticate",
+ lambda base_url, username, password: StudioAuth(
+ access_token = "t",
+ refresh_token = "r",
+ base_url = base_url,
+ username = username,
+ password = password,
+ ),
+ )
+ monkeypatch.setattr(lifecycle, "register_provider", lambda *a, **k: "provider-1")
+ monkeypatch.setattr(bundle_guard, "check_bundle", lambda url: _Verdict())
+ monkeypatch.setattr(browser_mod, "launch", lambda *a, **k: _Bundle())
+ monkeypatch.setattr(
+ browser_mod,
+ "install_wall_clock_watchdog",
+ lambda *a, **k: types.SimpleNamespace(cancel = lambda: None),
+ )
+ monkeypatch.setattr(pacer_mod, "Pacer", _Pacer)
+ monkeypatch.setattr(session_mod, "CellRunner", _Runner)
+ return state
+
+
+def _args(state, *extra):
+ return sb.parse_args(
+ ["--tier", "quick", "--rungs", "1K", "--out", str(state["out"])] + list(extra)
+ )
+
+
+def _rows(state):
+ path = Paths.under(state["out"]).payload_jsonl
+ return [json.loads(line) for line in path.read_text(encoding = "utf-8").splitlines() if line]
+
+
+# ── what a run records ───────────────────────────────────────────────────────────────────────
+
+
+def test_a_run_records_the_commit_its_ref_resolved_to(studio):
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+
+ meta = [r for r in _rows(studio) if r.get("row_type") == "run_meta"][0]
+ assert meta["studio_ref"] == "main"
+ assert meta["studio_commit"] == "c-main-1"
+
+
+def test_an_attached_studio_records_no_commit(studio):
+ """The build behind a URL is not visible from here, and a blank is the honest answer."""
+
+ assert sb.run(_args(studio, "--attach", "http://127.0.0.1:5310")) == 0
+
+ meta = [r for r in _rows(studio) if r.get("row_type") == "run_meta"][0]
+ assert meta["studio_commit"] == ""
+
+
+# ── the refusal ──────────────────────────────────────────────────────────────────────────────
+
+
+def test_a_resume_after_the_branch_moved_is_refused(studio):
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+
+ studio["commits"]["main"] = "c-main-2" # `main` advanced overnight
+ with pytest.raises(SystemExit) as excinfo:
+ sb.run(_args(studio, "--branch", "main", "--resume"))
+
+ message = str(excinfo.value)
+ assert "studio_commit" in message
+ assert "c-main-1" in message and "c-main-2" in message
+
+
+def test_the_studios_that_refusal_launched_are_released(studio):
+ """The refusal happens inside the setup guard, so it may not leak the servers it needed."""
+
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+ studio["stopped"].clear()
+
+ studio["commits"]["main"] = "c-main-2"
+ with pytest.raises(SystemExit):
+ sb.run(_args(studio, "--branch", "main", "--resume"))
+
+ assert [i.branch for i in studio["stopped"]] == ["main"]
+
+
+def test_a_resume_after_the_treatment_moved_is_refused(studio):
+ """The second side gets the same rule, out of `ab_plan` rather than `run_meta`."""
+
+ assert sb.run(_args(studio, "--branch", "main", "--ab", "fix"), ab_ref = "fix") == 0
+
+ studio["commits"]["fix"] = "c-fix-2" # the pull request was pushed to
+ with pytest.raises(SystemExit) as excinfo:
+ sb.run(_args(studio, "--branch", "main", "--ab", "fix", "--resume"), ab_ref = "fix")
+
+ message = str(excinfo.value)
+ assert "treatment_commit" in message
+ assert "c-fix-1" in message and "c-fix-2" in message
+
+
+# ── the controls ─────────────────────────────────────────────────────────────────────────────
+
+
+def test_the_same_commit_still_resumes(studio):
+ """The control that matters: a resume of the build the payload was recorded on is the whole
+ point of `--resume` and must still skip its cells and exit 0."""
+
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+ assert sb.run(_args(studio, "--branch", "main", "--resume")) == 0
+
+
+def test_a_payload_recorded_before_commits_were_written_still_resumes(studio):
+ """The back-compatibility control, and the same rule `recorded_identities` already applies:
+ an axis a payload never declared cannot be a difference."""
+
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+
+ path = Paths.under(studio["out"]).payload_jsonl
+ kept = []
+ for row in _rows(studio):
+ row.pop("studio_commit", None)
+ kept.append(json.dumps(row))
+ path.write_text("\n".join(kept) + "\n", encoding = "utf-8")
+
+ studio["commits"]["main"] = "c-main-2"
+ assert sb.run(_args(studio, "--branch", "main", "--resume")) == 0
+
+
+def test_an_attached_resume_is_not_refused_for_having_no_commit(studio):
+ """The other control: attaching cannot start failing against its own payload just because
+ this run has no commit to offer either."""
+
+ assert sb.run(_args(studio, "--attach", "http://127.0.0.1:5310")) == 0
+ assert sb.run(_args(studio, "--attach", "http://127.0.0.1:5310", "--resume")) == 0
+
+
+def test_a_fresh_run_onto_a_moved_branch_is_not_refused(studio):
+ """And the last one: this is a `--resume` rule. Without it the payload is archived and a new
+ one is started, which was always the right answer for a different build."""
+
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+
+ studio["commits"]["main"] = "c-main-2"
+ assert sb.run(_args(studio, "--branch", "main")) == 0
+
+ meta = [r for r in _rows(studio) if r.get("row_type") == "run_meta"]
+ assert [m["studio_commit"] for m in meta] == ["c-main-2"]
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_resume_latest_attempt.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_resume_latest_attempt.py
new file mode 100644
index 00000000000..688b67d13d0
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_resume_latest_attempt.py
@@ -0,0 +1,218 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""`--resume` decides on the LATEST attempt at a cell, the same one everything else reads.
+
+`latest_attempt_rows` is the rule for the score (`report.build.score_payload`), the ratio
+(`ab.readings_by_arm`), the surface parity sweep and `--assert-liveness`. `_resume_set` read the
+payload raw, and it is the one reader whose disagreement skips work rather than adding it.
+
+HOW A SUPERSEDED SUCCESS GETS INTO A PAYLOAD WITHOUT ANYBODY DOING ANYTHING UNUSUAL. An A/B pair
+is re-run WHOLE (`ab.skippable_cells`), because an arm measured alone in a new session is a
+reading no table can contain. So a resume re-runs an arm that had ALREADY succeeded. If that
+retry fails while its partner succeeds -- one flaky cell, which is the reason `--resume` exists --
+the payload holds a completed row and a later failed row under the same deterministic `cell_id`.
+
+Read raw, the next `--resume` found the old success, skipped the whole pair, ran nothing and
+exited 0. Read through `latest_attempt_rows`, the same payload scores INCOMPLETE and
+`--assert-liveness` fails on it. A resume that can never re-run the cell that is broken is a gate
+nobody can satisfy by fixing the run, and an exit code of 0 over a rung that scored zero.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.__main__ import _resume_set # noqa: E402
+from studiobench.report.build import score_payload # noqa: E402
+from studiobench.runtime.ab import Target, interleave, skippable_cells # noqa: E402
+from studiobench.runtime.types import Cell, Paths, Recorder, make_cell_id # noqa: E402
+
+FIRST = "sess-1"
+RETRY = "sess-2"
+
+BASE = "r10K.base.rep0"
+TREATMENT = "r10K.treatment.rep0"
+
+
+def _cell_row(cell_id, arm, *, completed):
+ row = {
+ "row_type": "cell",
+ "cell_id": cell_id,
+ "cell": {"arm": arm, "rep": 0},
+ "completed": completed,
+ "fidelity": "streamed_only",
+ "target_tokens": 10_000,
+ "actions": [
+ {"action": "keystroke", "ran": completed, "reason": None if completed else "died"}
+ ],
+ }
+ if not completed:
+ row["failure"] = {"kind": "TimeoutError", "message": "the machine stalled"}
+ return row
+
+
+def _keystroke(cell_id, p95):
+ return {
+ "row_type": "action",
+ "cell_id": cell_id,
+ "action": "keystroke",
+ "ran": True,
+ "expect_ok": True,
+ "expect": {},
+ "timings": {"p95_ms": p95},
+ "slot_missed": False,
+ }
+
+
+def _work():
+ """The real `interleave` over real cells: exactly the list `run()` iterates."""
+
+ cell = Cell(cell_id = make_cell_id("10K", "A0", 0), rung = "10K", rung_tokens = 10_000, rep = 0)
+ targets = [
+ Target(
+ label = label,
+ ref = label,
+ base_url = f"http://x/{label}",
+ seeder = None,
+ runner = None,
+ )
+ for label in ("base", "treatment")
+ ]
+ return interleave([(cell, None)], targets)
+
+
+def _paths(tmp_path, sessions):
+ """Write a payload one session at a time, through the real append-mode `Recorder`."""
+
+ paths = Paths.under(tmp_path / "out")
+ for session_id, rows in sessions:
+ rec = Recorder(paths.payload_jsonl, session_id)
+ for row in rows:
+ rec.emit(dict(row))
+ rec.close()
+ return paths
+
+
+# ── the decision ─────────────────────────────────────────────────────────────────────────────
+
+
+def test_a_cell_whose_latest_attempt_failed_is_not_skipped(tmp_path):
+ """The interrupted A/B: the base arm succeeded, its rerun died, the treatment arm is fine."""
+
+ paths = _paths(
+ tmp_path,
+ [
+ (FIRST, [_cell_row(BASE, "base", completed = True), _keystroke(BASE, 100.0)]),
+ (
+ RETRY,
+ [
+ _cell_row(BASE, "base", completed = False),
+ _cell_row(TREATMENT, "treatment", completed = True),
+ _keystroke(TREATMENT, 50.0),
+ ],
+ ),
+ ],
+ )
+
+ assert _resume_set(paths) == {TREATMENT}
+
+
+def test_the_pair_is_therefore_re_run_and_the_run_is_not_a_no_op(tmp_path):
+ """The consequence, through the same pair rule `run()` applies and the score `--report` gives.
+
+ The rung scores INCOMPLETE off the failed retry, so a `--resume` that finds nothing to do
+ would exit 0 over a ladder that scored zero.
+ """
+
+ paths = _paths(
+ tmp_path,
+ [
+ (FIRST, [_cell_row(BASE, "base", completed = True), _keystroke(BASE, 100.0)]),
+ (
+ RETRY,
+ [
+ _cell_row(BASE, "base", completed = False),
+ _cell_row(TREATMENT, "treatment", completed = True),
+ _keystroke(TREATMENT, 50.0),
+ ],
+ ),
+ ],
+ )
+
+ assert score_payload(paths.payload_jsonl, [10_000]).rungs[0].complete is False
+ assert skippable_cells(_work(), _resume_set(paths)) == set()
+
+
+# ── the controls ─────────────────────────────────────────────────────────────────────────────
+
+
+def test_a_cell_completed_once_and_never_re_run_is_skipped(tmp_path):
+ """The control that passes either way: an ordinary resume still skips what it recorded."""
+
+ paths = _paths(
+ tmp_path,
+ [
+ (
+ FIRST,
+ [
+ _cell_row(BASE, "base", completed = True),
+ _keystroke(BASE, 100.0),
+ _cell_row(TREATMENT, "treatment", completed = True),
+ _keystroke(TREATMENT, 50.0),
+ ],
+ )
+ ],
+ )
+
+ done = _resume_set(paths)
+ assert done == {BASE, TREATMENT}
+ assert skippable_cells(_work(), done) == done
+
+
+def test_a_cell_that_died_and_was_then_re_run_successfully_is_skipped(tmp_path):
+ """The control on the direction: superseding must not turn into refusing to skip anything.
+
+ This is the case `--resume` was built for, and the LATEST attempt is the successful one.
+ """
+
+ paths = _paths(
+ tmp_path,
+ [
+ (FIRST, [_cell_row(BASE, "base", completed = False)]),
+ (
+ RETRY,
+ [
+ _cell_row(BASE, "base", completed = True),
+ _keystroke(BASE, 100.0),
+ _cell_row(TREATMENT, "treatment", completed = True),
+ _keystroke(TREATMENT, 50.0),
+ ],
+ ),
+ ],
+ )
+
+ assert _resume_set(paths) == {BASE, TREATMENT}
+
+
+def test_a_payload_without_session_ids_still_resumes(tmp_path):
+ """The other control. A payload written before the recorder stamped sessions cannot be split
+ into attempts, and `latest_attempt_rows` keeps it whole rather than losing the run."""
+
+ paths = Paths.under(tmp_path / "out")
+ paths.payload_jsonl.parent.mkdir(parents = True, exist_ok = True)
+ paths.payload_jsonl.write_text(
+ '{"row_type": "cell", "cell_id": "r10K.base.rep0", "completed": true}\n',
+ encoding = "utf-8",
+ )
+
+ assert _resume_set(paths) == {BASE}
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_resume_supersedes.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_resume_supersedes.py
new file mode 100644
index 00000000000..e9a5a52eaae
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_resume_supersedes.py
@@ -0,0 +1,204 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A cell that was re-run belongs to the run that FINISHED it, not to the one that died.
+
+`--resume` appends to the payload it continues and re-runs the cells that did not complete, and
+`make_cell_id` is deterministic, so the retry lands under the cell id of the attempt that died.
+Two readings came out of that, both silent and both wrong:
+
+ THE DEAD ATTEMPT'S FRAMES BECAME THE RETRY'S. Cell rows were scoped by session; the `action`
+ and `window` rows underneath them were collected by `cell_id` alone, so a 100 ms frame recorded
+ by the run that crashed stayed the RETRY's `max_frame_ms` and its gaps stayed in the retry's
+ jank distribution -- inside an A/B ratio, which is where cross-session drift does the most
+ damage.
+
+ THE SUCCESSFUL RETRY DID NOT COUNT. The rung kept the failure forever, so `--report` on a
+ payload whose only failure had already been re-run successfully still printed INCOMPLETE and
+ scored the rung zero, dragging the headline down with it.
+
+What must NOT change: two REPETITIONS are two observations, and a rung with a failed rep is still
+not a clean rung. Only a later attempt at the SAME cell supersedes an earlier one.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.report.build import score_payload # noqa: E402
+from studiobench.runtime.ab import readings_by_arm # noqa: E402
+
+NOW = "s-now"
+OLD = "s-before"
+
+
+def _cell(
+ cell_id,
+ arm,
+ *,
+ completed,
+ session,
+ tokens = 10_000,
+ rep = 0,
+):
+ row = {
+ "row_type": "cell",
+ "cell_id": cell_id,
+ "session_id": session,
+ "target_tokens": tokens,
+ "completed": completed,
+ "cell": {"arm": arm, "rep": rep},
+ }
+ if not completed:
+ row["failure"] = {"kind": "TimeoutError", "message": "the machine stalled"}
+ return row
+
+
+def _keystroke(cell_id, session, p95):
+ return {
+ "row_type": "action",
+ "cell_id": cell_id,
+ "session_id": session,
+ "action": "keystroke",
+ "ran": True,
+ "expect_ok": True,
+ "timings": {"p95_ms": p95},
+ }
+
+
+def _window(
+ cell_id,
+ session,
+ max_frame,
+ gaps,
+ duration_ms = 1000.0,
+):
+ return {
+ "row_type": "window",
+ "cell_id": cell_id,
+ "session_id": session,
+ "name": "stream:film",
+ "kind": "stream",
+ "t_open_ms": 0.0,
+ "duration_ms": duration_ms,
+ "instruments": {
+ "frames": {
+ "frames_attempted": True,
+ "max_frame_ms": max_frame,
+ "frame_gaps_ms": list(gaps),
+ }
+ },
+ }
+
+
+# ── the ratio ───────────────────────────────────────────────────────
+
+
+def test_the_dead_attempts_frames_are_not_the_retrys_frames():
+ cell_id = "r10K.base.rep0"
+ records = [
+ _cell(cell_id, "base", completed = False, session = OLD),
+ _window(cell_id, OLD, 100.0, [100.0, 16.0]),
+ _cell(cell_id, "base", completed = True, session = NOW),
+ _window(cell_id, NOW, 17.0, [16.0, 17.0]),
+ ]
+ reading = readings_by_arm(records, session_id = NOW)["base"][(10_000, 0)]
+ assert reading["max_frame_ms"].value == 17.0
+ # The 100 ms gap is out of the pooled distribution too, not just out of the maximum.
+ assert (
+ reading["jank_index"].value
+ == readings_by_arm([records[2], records[3]], session_id = NOW)["base"][(10_000, 0)][
+ "jank_index"
+ ].value
+ )
+
+
+def test_two_windows_of_the_same_attempt_are_still_pooled():
+ """The control: filtering by attempt must not turn into filtering out real windows."""
+
+ cell_id = "r10K.base.rep0"
+ records = [
+ _cell(cell_id, "base", completed = True, session = NOW),
+ _window(cell_id, NOW, 17.0, [16.0, 17.0]),
+ _window(cell_id, NOW, 100.0, [100.0, 16.0]),
+ ]
+ reading = readings_by_arm(records, session_id = NOW)["base"][(10_000, 0)]
+ assert reading["max_frame_ms"].value == 100.0
+
+
+# ── the score ───────────────────────────────────────────────────────
+
+
+def _payload(directory, rows):
+ Path(directory).mkdir(parents = True, exist_ok = True)
+ path = Path(directory) / "payload.jsonl"
+ path.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding = "utf-8")
+ return path
+
+
+def _finished(
+ session,
+ *,
+ tokens = 10_000,
+ rep = 0,
+):
+ cell_id = f"r{tokens}.A0.rep{rep}"
+ return [
+ _cell(cell_id, "A0", completed = True, session = session, tokens = tokens, rep = rep),
+ _keystroke(cell_id, session, 40.0),
+ _window(cell_id, session, 30.0, [16.0, 17.0, 16.0]),
+ ]
+
+
+def _died(
+ session,
+ *,
+ tokens = 10_000,
+ rep = 0,
+):
+ cell_id = f"r{tokens}.A0.rep{rep}"
+ return [
+ _cell(cell_id, "A0", completed = False, session = session, tokens = tokens, rep = rep),
+ _keystroke(cell_id, session, 400.0),
+ _window(cell_id, session, 900.0, [900.0, 16.0]),
+ ]
+
+
+def test_a_resumed_cell_scores_as_if_the_crash_had_not_happened(tmp_path):
+ resumed = score_payload(_payload(tmp_path / "a", _died(OLD) + _finished(NOW)), [10_000])
+ clean = score_payload(_payload(tmp_path / "b", _finished(NOW)), [10_000])
+
+ rung = resumed.rungs[0]
+ assert rung.complete is True
+ assert rung.incomplete_reason is None
+ assert rung.score > 0
+ # Not merely "not zero": the superseded attempt must not move the number at all.
+ assert rung.to_json() == clean.rungs[0].to_json()
+ assert resumed.aggregate == clean.aggregate
+
+
+def test_a_failed_repetition_still_makes_the_rung_incomplete(tmp_path):
+ """The control: reps are independent observations and one of them failing is the answer."""
+
+ rows = _finished(NOW, rep = 0) + _died(NOW, rep = 1)
+ ladder = score_payload(_payload(tmp_path / "c", rows), [10_000])
+ assert ladder.rungs[0].complete is False
+ assert "TimeoutError" in (ladder.rungs[0].incomplete_reason or "")
+ assert ladder.rungs[0].score == 0.0
+
+
+def test_a_cell_that_was_never_re_run_keeps_its_failure(tmp_path):
+ """The other control: a crash with no retry behind it is still a crash."""
+
+ ladder = score_payload(_payload(tmp_path / "d", _died(OLD)), [10_000])
+ assert ladder.rungs[0].complete is False
+ assert "TimeoutError" in (ladder.rungs[0].incomplete_reason or "")
+
+
+if __name__ == "__main__":
+ import pytest
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_run_acquisition.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_run_acquisition.py
new file mode 100644
index 00000000000..a5b7986cf9b
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_run_acquisition.py
@@ -0,0 +1,469 @@
+# 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 run releases the Studios it acquired, and records which ones they were.
+
+THE SIDES ARE ACQUIRED ONE AFTER THE OTHER. In a self-managed A/B the base is installed, launched
+and already serving before the treatment's clone begins, so a failure in the treatment's setup used
+to unwind past a base that nothing ever stopped: the cleanup lives in the `finally` under the cells
+and a failure during setup never reaches it. The same hole swallowed the two setup steps that leave
+by RETURNING -- the health check and the development-build gate -- with both Studios up.
+
+An abandoned Studio is not idle. `launch_studio` detaches the server with `setsid -f`, so it keeps
+the port; Studio's own launcher then ABORTS rather than binding when it finds one of its own servers
+there (`studio/backend/run.py`, `_resolve_port` with `avoid_own_studio`), the retry's server exits,
+and `wait_for_healthz` takes its 200 from the STALE process. That run measures the build the
+previous attempt installed while `run_meta` records the ref this one asked for.
+
+WHICH SERVER THE TREATMENT WAS is the second thing here, and it is asserted through the same drive
+because it is a property of the row a real run writes. An attached base is identified by its URL;
+the treatment carried only the label typed after `--ab`, so `--attach A --attach-b B --ab fix`
+resumed happily against `--attach-b C` and reported B's measurements as C's result.
+
+`run()` itself is driven, with the seams that leave this process stubbed at the boundary they cross:
+the installer, the launcher, the health check, the login, the browser and the cell runner. Nothing
+below them is re-implemented -- the acquisition loop, the gate, the identity and the payload are the
+shipped ones.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+import studiobench.__main__ as sb # noqa: E402
+from studiobench import pacer as pacer_mod # noqa: E402
+from studiobench.runtime import browser as browser_mod # noqa: E402
+from studiobench.runtime import bundle_guard, lifecycle # noqa: E402
+from studiobench.runtime import session as session_mod # noqa: E402
+from studiobench.runtime.lifecycle import StudioAuth, StudioInstall # noqa: E402
+from studiobench.runtime.types import Paths # noqa: E402
+
+
+class _Verdict:
+ def __init__(self, production: bool) -> None:
+ self.production = production
+ self.bundle_type = 0
+ self.reason = "production build" if production else "development server"
+
+ def as_dict(self) -> dict:
+ return {"production": self.production, "reason": self.reason}
+
+
+class _Bundle:
+ # WHAT `browser.launch` WOULD HAVE RESOLVED on the machine running this test. `run_meta`
+ # records the engine and `requested_identity` resolves the same way, so a stub that names a
+ # fixed one would make a legitimate resume look like an engine change off Linux and macOS.
+ engine = browser_mod.default_engine()[0]
+ engine_note = "stubbed for this test"
+ browser = context = page = cdp = None
+
+ def close(self) -> None:
+ pass
+
+
+class _Pacer:
+ base_url = "http://127.0.0.1:65535"
+
+ def __init__(self) -> None:
+ self.state = types.SimpleNamespace(model_ids = [])
+
+ def start(self):
+ return self
+
+ def stop(self) -> None:
+ pass
+
+
+def studio(monkeypatch, tmp_path):
+ """Every seam `run()` reaches outside this process, stubbed where it leaves it.
+
+ The returned dict is both the knobs (which ref fails to install, whether /healthz answers,
+ whether the bundle is a production build) and the record (what was installed, launched and
+ stopped, and what the Studios looked like at the moment the first cell ran).
+ """
+
+ state = {
+ "installed": [],
+ "launched": [],
+ "stopped": [],
+ "stopped_when_the_cells_ran": None,
+ "install_fails_for": None,
+ "healthy": True,
+ "production": True,
+ "out": tmp_path / "out",
+ }
+
+ def fake_install(ref, home, *args, **kwargs):
+ if ref == state["install_fails_for"]:
+ raise RuntimeError(f"install.sh for {ref} exited 1")
+ state["installed"].append(ref)
+ return StudioInstall(home = Path(home), repo = Path(home).parent / "repo", branch = ref)
+
+ def fake_launch(install, port, log_path, *args, **kwargs):
+ install.port = port
+ install.pid = 90_000 + port
+ install.bootstrap_password = "secret"
+ state["launched"].append(install)
+ return install
+
+ class _Runner:
+ def __init__(self, **kwargs) -> None:
+ self.kwargs = kwargs
+
+ def run(self, cell, plan):
+ if state["stopped_when_the_cells_ran"] is None:
+ state["stopped_when_the_cells_ran"] = list(state["stopped"])
+ return {
+ "cell_id": cell.cell_id,
+ "completed": True,
+ "actions": [{"action": "keystroke", "ran": True}],
+ }
+
+ monkeypatch.setattr(lifecycle, "install_studio", fake_install)
+ monkeypatch.setattr(lifecycle, "launch_studio", fake_launch)
+ monkeypatch.setattr(lifecycle, "stop_studio", lambda install: state["stopped"].append(install))
+ monkeypatch.setattr(lifecycle, "wait_for_healthz", lambda *a, **k: state["healthy"])
+ monkeypatch.setattr(
+ lifecycle,
+ "authenticate",
+ lambda base_url, username, password: StudioAuth(
+ access_token = "t",
+ refresh_token = "r",
+ base_url = base_url,
+ username = username,
+ password = password,
+ ),
+ )
+ monkeypatch.setattr(lifecycle, "register_provider", lambda *a, **k: "provider-1")
+ monkeypatch.setattr(bundle_guard, "check_bundle", lambda url: _Verdict(state["production"]))
+ monkeypatch.setattr(browser_mod, "launch", lambda *a, **k: _Bundle())
+ monkeypatch.setattr(
+ browser_mod,
+ "install_wall_clock_watchdog",
+ lambda *a, **k: types.SimpleNamespace(cancel = lambda: None),
+ )
+ monkeypatch.setattr(pacer_mod, "Pacer", _Pacer)
+ monkeypatch.setattr(session_mod, "CellRunner", _Runner)
+ return state
+
+
+def _args(state, *extra):
+ return sb.parse_args(
+ ["--tier", "quick", "--rungs", "1K", "--out", str(state["out"])] + list(extra)
+ )
+
+
+def _rows(state):
+ path = Paths.under(state["out"]).payload_jsonl
+ return [json.loads(line) for line in path.read_text(encoding = "utf-8").splitlines() if line]
+
+
+# ── the sides a failed setup leaves behind ──────────────────────────────────────────────────
+
+
+def test_the_base_studio_is_stopped_when_the_treatment_install_fails(studio):
+ """The reported leak: the base is up and serving while the treatment's clone and build run."""
+
+ studio["install_fails_for"] = "pr-9296"
+
+ with pytest.raises(RuntimeError):
+ sb.run(_args(studio, "--branch", "main", "--ab", "pr-9296"), ab_ref = "pr-9296")
+
+ assert [i.branch for i in studio["launched"]] == ["main"]
+ assert [i.branch for i in studio["stopped"]] == ["main"]
+
+
+def test_every_studio_is_stopped_when_one_of_them_never_answers_healthz(studio):
+ """A setup step that fails by RETURNING leaves the same abandoned server behind."""
+
+ studio["healthy"] = False
+
+ assert sb.run(_args(studio, "--branch", "main", "--ab", "pr-9296"), ab_ref = "pr-9296") == 2
+ assert [i.branch for i in studio["stopped"]] == ["main", "pr-9296"]
+
+
+def test_every_studio_is_stopped_when_the_gate_refuses_a_development_build(studio):
+ studio["production"] = False
+
+ assert sb.run(_args(studio, "--branch", "main", "--ab", "pr-9296"), ab_ref = "pr-9296") == 3
+ assert [i.branch for i in studio["stopped"]] == ["main", "pr-9296"]
+
+
+def test_keep_studio_still_leaves_a_failed_setup_running(studio):
+ """The control on the guard itself: `--keep-studio` asks for exactly this leak."""
+
+ studio["install_fails_for"] = "pr-9296"
+
+ with pytest.raises(RuntimeError):
+ sb.run(
+ _args(studio, "--branch", "main", "--ab", "pr-9296", "--keep-studio"),
+ ab_ref = "pr-9296",
+ )
+
+ assert [i.branch for i in studio["launched"]] == ["main"]
+ assert studio["stopped"] == []
+
+
+def test_a_studio_the_caller_attached_is_never_stopped(studio):
+ """The other control: this harness only stops what it launched itself."""
+
+ studio["healthy"] = False
+ args = _args(
+ studio,
+ "--attach",
+ "http://127.0.0.1:5310",
+ "--attach-b",
+ "http://127.0.0.1:5311",
+ "--ab",
+ "fix",
+ )
+
+ assert sb.run(args, ab_ref = "fix") == 2
+ assert studio["stopped"] == []
+
+
+def test_a_run_that_reaches_its_cells_stops_the_studios_once_at_the_end(studio):
+ """The control that matters: an ordinary run still gets two live Studios and still cleans up.
+
+ The guard is a `finally` over the whole of setup, so the failure it must not have is stopping
+ the Studios on the way IN. `stopped_when_the_cells_ran` is read inside the cell runner.
+ """
+
+ args = _args(studio, "--branch", "main", "--ab", "pr-9296", "--reps", "2")
+
+ assert sb.run(args, ab_ref = "pr-9296") == 0
+ assert studio["stopped_when_the_cells_ran"] == []
+ assert [i.branch for i in studio["stopped"]] == ["main", "pr-9296"]
+
+
+# ── which server the treatment was ──────────────────────────────────────────────────────────
+
+
+def test_an_attached_ab_records_the_treatment_url_it_measured(studio):
+ args = _args(
+ studio,
+ "--attach",
+ "http://127.0.0.1:5310/",
+ "--attach-b",
+ "http://127.0.0.1:5311/",
+ "--ab",
+ "fix",
+ )
+
+ assert sb.run(args, ab_ref = "fix") == 0
+
+ plan = [r for r in _rows(studio) if r.get("row_type") == "ab_plan"]
+ assert len(plan) == 1
+ assert plan[0]["treatment_url"] == "http://127.0.0.1:5311"
+
+
+def test_a_self_managed_ab_records_no_treatment_url(studio):
+ """A treatment this run installed is identified by its ref; the port it landed on is not it."""
+
+ args = _args(studio, "--branch", "main", "--ab", "pr-9296")
+
+ assert sb.run(args, ab_ref = "pr-9296") == 0
+
+ plan = [r for r in _rows(studio) if r.get("row_type") == "ab_plan"]
+ assert plan[0]["treatment_url"] == ""
+
+
+def test_a_resume_pointed_at_another_treatment_studio_is_refused(studio):
+ """End to end, over the payload the run above actually wrote: same `--ab` label, second URL."""
+
+ paths = Paths.under(studio["out"])
+ first = _args(
+ studio,
+ "--attach",
+ "http://127.0.0.1:5310",
+ "--attach-b",
+ "http://127.0.0.1:5311",
+ "--ab",
+ "fix",
+ )
+ assert sb.run(first, ab_ref = "fix") == 0
+
+ again = _args(
+ studio,
+ "--attach",
+ "http://127.0.0.1:5310",
+ "--attach-b",
+ "http://127.0.0.1:5312",
+ "--ab",
+ "fix",
+ "--resume",
+ )
+ corpus_hash = _rows(studio)[0]["corpus_hash"]
+
+ with pytest.raises(SystemExit) as excinfo:
+ sb.prepare_payload(
+ paths,
+ sb.requested_identity(again, "fix", corpus_hash),
+ resume = True,
+ log = lambda *_a: None,
+ )
+
+ message = str(excinfo.value)
+ assert "treatment_url" in message
+ assert "5311" in message and "5312" in message
+
+
+def test_the_same_treatment_studio_still_resumes(studio):
+ """The control: the identity this payload was recorded under has to keep resuming."""
+
+ paths = Paths.under(studio["out"])
+ args = _args(
+ studio,
+ "--attach",
+ "http://127.0.0.1:5310",
+ "--attach-b",
+ "http://127.0.0.1:5311",
+ "--ab",
+ "fix",
+ )
+ assert sb.run(args, ab_ref = "fix") == 0
+ corpus_hash = _rows(studio)[0]["corpus_hash"]
+
+ resumed = _args(
+ studio,
+ "--attach",
+ "http://127.0.0.1:5310",
+ "--attach-b",
+ "http://127.0.0.1:5311/",
+ "--ab",
+ "fix",
+ "--resume",
+ )
+
+ assert (
+ sb.prepare_payload(
+ paths,
+ sb.requested_identity(resumed, "fix", corpus_hash),
+ resume = True,
+ log = lambda *_a: None,
+ )
+ is None
+ )
+
+
+# ── one Studio, two sides: the attached null control ────────────────────────────────────────
+
+
+class _ProviderBackend:
+ """`lifecycle.register_provider`'s contract, per origin: idempotent by DISPLAY NAME.
+
+ The real one deletes every existing provider whose `display_name` matches before creating the
+ replacement, so registering the pacer twice against ONE Studio destroys the id the first
+ registration handed out. Modelled rather than stubbed to a constant, because that deletion is
+ the whole failure.
+ """
+
+ def __init__(self) -> None:
+ self.live: dict = {}
+ self.registrations: list = []
+ self.deleted: list = []
+ self._issued = 0
+
+ def register(self, base_url, auth, provider):
+ origin = base_url.rstrip("/")
+ rows = self.live.setdefault(origin, {})
+ for pid, name in list(rows.items()):
+ if name == provider.name:
+ del rows[pid]
+ self.deleted.append((origin, pid))
+ self._issued += 1
+ pid = f"provider-{self._issued}"
+ rows[pid] = provider.name
+ provider.id = pid
+ self.registrations.append((origin, pid))
+ return pid
+
+
+def _capture_init_scripts(monkeypatch) -> list:
+ captured: list = []
+
+ def fake_launch(
+ engine,
+ *args,
+ init_scripts = None,
+ **kwargs,
+ ):
+ captured.extend(init_scripts or [])
+ return _Bundle()
+
+ monkeypatch.setattr(browser_mod, "launch", fake_launch)
+ return captured
+
+
+def _selected_provider_ids(scripts: list, origin: str) -> set:
+ """The provider ids the seed scripts for `origin` actually SELECT, out of their checkpoints."""
+
+ import re
+
+ ids = set()
+ for script in scripts:
+ if json.dumps(origin) not in script:
+ continue
+ for match in re.finditer(r"external::([^:]+)::", script):
+ ids.add(match.group(1))
+ return ids
+
+
+def test_an_attached_null_control_registers_one_provider_for_the_one_studio(studio, monkeypatch):
+ """`--attach U --attach-b U` is TWO SIDES ON ONE STUDIO, which `is_null_control` accepts.
+
+ Registering per side registered the pacer twice against that single backend, and the second
+ registration deleted the id the base side's seed script had already captured. Both scripts are
+ scoped to the same origin, Playwright does not define the order init scripts run in, and
+ `StudioAuth.rotate` re-adds them mid-run -- so the base could boot every cell with a DELETED
+ provider selected, which renders as "No longer offered" and throws `Connection not found`
+ without ever asking for a completion.
+ """
+
+ backend = _ProviderBackend()
+ monkeypatch.setattr(lifecycle, "register_provider", backend.register)
+ scripts = _capture_init_scripts(monkeypatch)
+ url = "http://127.0.0.1:5310"
+
+ args = _args(studio, "--attach", url, "--attach-b", url, "--branch", "main", "--ab", "main")
+ assert sb.run(args, ab_ref = "main") == 0
+
+ # THE SYMPTOM FIRST. Whatever the bookkeeping below says, the failure a cell actually meets is
+ # a seed script that SELECTS a provider the backend no longer has, so that is what this pins:
+ # every id named by a script scoped to this origin is still live there, and no live id is
+ # unnamed. Asserting only "nothing was deleted" would pass a future fix that deleted and then
+ # re-seeded both scripts with the survivor, and would fail a fix that never selects at all.
+ selected = _selected_provider_ids(scripts, url)
+ assert selected == set(backend.live[url])
+ assert selected, "the one Studio must still have a provider selected"
+ # And the registration itself: one backend, one registration, nothing destroyed.
+ assert backend.deleted == []
+ assert backend.registrations == [(url, "provider-1")]
+
+
+def test_two_attached_studios_still_get_a_provider_each(studio, monkeypatch):
+ """The control: two DIFFERENT origins are two backends and must each be registered."""
+
+ backend = _ProviderBackend()
+ monkeypatch.setattr(lifecycle, "register_provider", backend.register)
+ scripts = _capture_init_scripts(monkeypatch)
+ base_url, treatment_url = "http://127.0.0.1:5310", "http://127.0.0.1:5311"
+
+ args = _args(studio, "--attach", base_url, "--attach-b", treatment_url, "--ab", "fix")
+ assert sb.run(args, ab_ref = "fix") == 0
+
+ assert backend.registrations == [(base_url, "provider-1"), (treatment_url, "provider-2")]
+ assert _selected_provider_ids(scripts, base_url) == {"provider-1"}
+ assert _selected_provider_ids(scripts, treatment_url) == {"provider-2"}
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_drain.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_drain.py
new file mode 100644
index 00000000000..ccc4fe90a9d
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_drain.py
@@ -0,0 +1,378 @@
+# 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 reply that never finished is a FAILED cell, not a completed one carrying a note.
+
+`_drain_stream` reports rather than raises -- "wait for the run to end, or say plainly that it did
+not" -- and the value it reported was written to `row["stream"]` and read by nothing. No gate, no
+report column, no `--assert-liveness` check, no exit code. So the state this tool exists to catch,
+the app still generating three times past its own cadence AND 120 s beyond that with the whole
+film already run, came back as `completed: true`, `ok` in the summary and exit 0, with the cell's
+actions and its frame windows scored and paired into the A/B ratio against an arm that DID finish.
+
+That is the crash-beats-limp rule inverted: a build that cannot finish reads as a build that had
+nothing to say. Every other "it would not do what it claimed" in this harness already fails --
+`stop_generation` that never stops sets `expect_ok = False`, an action that did not run is a
+liveness problem -- and this was the one that did not.
+
+Driven through the shipped `CellRunner.run` and `_run_inner`, with the seams that leave this
+process stubbed where they cross it. `_drain_stream` itself is the REAL one, over a real loop on a
+fake clock, so what it returns is observed rather than asserted from a table.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import time
+import types
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.report.build import score_payload # noqa: E402
+from studiobench.runtime import session as session_mod # noqa: E402
+from studiobench.runtime.session import CellRunner, Session # noqa: E402
+from studiobench.runtime.types import BenchContext, Cell, Paths, Recorder # noqa: E402
+
+CENSUS = {
+ "messages": 4,
+ "elements": 1200,
+ "highlight_spans": 200,
+ "assistant_chars": 1120,
+}
+
+
+class _Clock:
+ """A monotonic clock the page's own waits advance, so the real drain loop runs to its real
+ deadline without this test sleeping through it."""
+
+ def __init__(self) -> None:
+ self.t = 0.0
+
+ def monotonic(self) -> float:
+ return self.t
+
+ def advance(self, ms: float) -> None:
+ self.t += ms / 1000.0
+
+
+class _Page:
+ def __init__(self, clock: _Clock, *, stops_running_after_ms: float | None) -> None:
+ self.clock = clock
+ self.stops_running_after_ms = stops_running_after_ms
+ self._send = types.SimpleNamespace(click = lambda: None)
+
+ # -- playwright surface -------------------------------------------------
+ def goto(self, *a, **k) -> None:
+ pass
+
+ def wait_for_selector(self, *a, **k) -> None:
+ pass
+
+ def click(self, *a, **k) -> None:
+ pass
+
+ def fill(self, *a, **k) -> None:
+ pass
+
+ def wait_for_timeout(self, ms) -> None:
+ self.clock.advance(float(ms))
+
+ def query_selector(self, selector):
+ return self._send if "Send message" in selector else None
+
+ def evaluate(self, expr, *args):
+ if "isRunning" in expr:
+ if self.stops_running_after_ms is None:
+ return True
+ return self.clock.t * 1000.0 < self.stops_running_after_ms
+ if "assistantChars" in expr:
+ return CENSUS["assistant_chars"]
+ return 0
+
+
+class _Pacer:
+ """A pacer that serves, in full, whatever it was asked to load.
+
+ It synthesises one completed `StreamStats` per `load`, which is what a healthy cell produces:
+ the planned-stream check in `_run_inner` reads those, so a stub that recorded nothing would
+ fail every cell here for a reason this file is not about.
+ """
+
+ def __init__(self, expected_ms: float) -> None:
+ self.expected_ms = expected_ms
+ self.streams: list[dict] = []
+
+ def reset(self) -> None:
+ self.streams = []
+
+ def load(
+ self,
+ reasoning,
+ content,
+ *,
+ cadence = "field",
+ tag = "",
+ **k,
+ ) -> None:
+ self.streams.append(
+ {
+ "tag": tag,
+ "chars_sent": len(reasoning) + len(content),
+ "completed": True,
+ "disconnected": False,
+ "chunks": 150,
+ }
+ )
+
+ def expected_duration_ms(self, reasoning, content, cadence) -> float:
+ return self.expected_ms
+
+ def last_stats(self) -> dict:
+ return self.streams[-1] if self.streams else {}
+
+ def all_stats(self) -> list[dict]:
+ return list(self.streams)
+
+
+#: (action name, timing key, value). The three actions `scoring.from_payload.ACTION_SOURCES`
+#: reads, so a cell that completes carries enough weight to be scored rather than failing the
+#: coverage floor for an unrelated reason.
+SCENE_ACTIONS = (
+ ("keystroke", "p95_ms", 40.0),
+ ("message_menu", "open_ms", 90.0),
+ ("scroll_after", "gesture_ms", 120.0),
+)
+
+
+class _SceneRunner:
+ """The film, reduced to the rows a film writes: three timed actions and one frame window.
+
+ It writes them through the recorder the shipped `SceneRunner` is handed, so the scoring path
+ below is the real one reading real rows rather than a table this test asserts against itself.
+ """
+
+ def __init__(self, **kwargs) -> None:
+ self.kwargs = kwargs
+
+ def run(self, scene, t0) -> list:
+ rec = self.kwargs["recorder"]
+ cell_id = self.kwargs["cell"].cell_id
+ out = []
+ for name, timing_key, value in SCENE_ACTIONS:
+ row = {
+ "row_type": "action",
+ "cell_id": cell_id,
+ "action": name,
+ "ran": True,
+ "expect_ok": True,
+ "expect": {},
+ "timings": {timing_key: value},
+ "slot_missed": False,
+ "census": dict(CENSUS),
+ }
+ rec.emit(dict(row))
+ out.append(row)
+ rec.emit(
+ {
+ "row_type": "window",
+ "cell_id": cell_id,
+ "name": "stream:film",
+ "kind": "stream",
+ "t_open_ms": 0.0,
+ "duration_ms": 1000.0,
+ "instruments": {
+ "frames": {
+ "frames_attempted": True,
+ "max_frame_ms": 30.0,
+ "frame_gaps_ms": [16.0, 17.0, 16.0],
+ }
+ },
+ }
+ )
+ return out
+
+
+def _seed(plan):
+ """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)
+
+
+def cell_runner(monkeypatch, tmp_path):
+ """A `CellRunner` wired to the real session, the real recorder and a fake browser."""
+
+ clock = _Clock()
+ state = {"clock": clock, "expected_ms": 1000.0, "stops_running_after_ms": 0.0}
+
+ monkeypatch.setattr(
+ session_mod,
+ "time",
+ types.SimpleNamespace(
+ monotonic = clock.monotonic,
+ sleep = lambda s: None,
+ time = time.time,
+ perf_counter = time.perf_counter,
+ ),
+ )
+ monkeypatch.setattr(session_mod, "paint_floor_ms", lambda page: 8.0)
+ monkeypatch.setattr(session_mod, "dom_signature", lambda page: dict(CENSUS))
+ monkeypatch.setattr(
+ session_mod,
+ "measure_chars_per_token",
+ lambda *a, **k: {"chars_per_token": 3.7, "source": "stubbed"},
+ )
+ monkeypatch.setattr(session_mod, "cdp_metrics", lambda cdp: {})
+ monkeypatch.setattr(session_mod, "cdp_counters", lambda before, after: {})
+ monkeypatch.setattr(session_mod, "SceneRunner", _SceneRunner)
+ monkeypatch.setattr(session_mod, "dump_diagnostics", lambda *a, **k: None)
+
+ paths = Paths.under(tmp_path / "out")
+ recorder = Recorder(paths.payload_jsonl, "sess-1")
+ ctx = BenchContext(
+ page = None,
+ cdp = None,
+ base_url = "http://127.0.0.1:5399",
+ session_id = "sess-1",
+ tier = "quick",
+ paths = paths,
+ recorder = recorder,
+ log = lambda msg: None,
+ )
+ session = Session(ctx = ctx)
+
+ def build():
+ ctx.page = _Page(clock, stops_running_after_ms = state["stops_running_after_ms"])
+ return CellRunner(
+ session = session,
+ pacer = _Pacer(state["expected_ms"]),
+ seeder = types.SimpleNamespace(seed = _seed, auth = None),
+ corpus = None,
+ base_url = "http://127.0.0.1:5399",
+ model_id = "studiobench-pacer",
+ tier = "quick",
+ paths = paths,
+ log = lambda msg: None,
+ )
+
+ state["build"] = build
+ state["paths"] = paths
+ state["recorder"] = recorder
+ return state
+
+
+def _cell():
+ # NOT the 10K rung: that one additionally runs the seeded-vs-streamed equivalence check, which
+ # is a different subject.
+ return Cell(cell_id = "r1K.A0.rep0", rung = "1K", rung_tokens = 1_000, tier = "quick")
+
+
+def _plan():
+ unit = types.SimpleNamespace(reasoning = "r" * 100, content = "c" * 900, kind = "tail")
+ return types.SimpleNamespace(
+ rung = "1K",
+ streamed_unit = unit,
+ seeded_units = [],
+ follow_up_units = [],
+ seeded_chars = 0,
+ streamed_chars = 1000,
+ target_chars = 1000,
+ target_tokens = 1_000,
+ )
+
+
+def _rows(state):
+ state["recorder"].close()
+ text = state["paths"].payload_jsonl.read_text(encoding = "utf-8")
+ return [json.loads(line) for line in text.splitlines() if line]
+
+
+# ── what the real drain returns ──────────────────────────────────────────────────────────────
+
+
+def test_the_drain_reports_rather_than_raises_when_the_reply_never_ends(cell_runner):
+ """The premise, taken from the shipped `_drain_stream` rather than asserted about it."""
+
+ cell_runner["stops_running_after_ms"] = None # never stops
+ runner = cell_runner["build"]()
+
+ drained = runner._drain_stream(runner.session.ctx.page, 1000.0)
+
+ assert drained["finished"] is False
+ assert "three times past its own cadence" in drained["reason"]
+
+
+# ── what the cell does with it ───────────────────────────────────────────────────────────────
+
+
+def test_a_cell_whose_reply_never_finished_does_not_complete(cell_runner):
+ cell_runner["stops_running_after_ms"] = None
+ runner = cell_runner["build"]()
+
+ row = runner.run(_cell(), _plan())
+
+ assert row["completed"] is False
+ assert row["failure"]["kind"] == "RuntimeError"
+ assert "never finished" in row["failure"]["message"]
+ # The evidence ships in the same row as the failure: how long was waited, and how much the
+ # pacer actually delivered.
+ assert row["stream"]["finished"] is False
+ assert row["pacer"]["last"]["chunks"] == 150
+ assert row["pacer"]["streams"][0]["tag"] == "r1K.A0.rep0"
+
+
+def test_the_rung_scores_incomplete_and_the_run_cannot_exit_zero(cell_runner):
+ """The consequence a reader sees: the ladder says INCOMPLETE and `completion_exit_code`
+ counts a cell that did not complete."""
+
+ from studiobench.__main__ import completion_exit_code
+
+ cell_runner["stops_running_after_ms"] = None
+ runner = cell_runner["build"]()
+
+ row = runner.run(_cell(), _plan())
+ ladder = score_payload(cell_runner["paths"].payload_jsonl, [1_000])
+
+ assert ladder.rungs[0].complete is False
+ assert "RuntimeError" in (ladder.rungs[0].incomplete_reason or "")
+ assert completion_exit_code([row]) == 1
+
+
+# ── the controls ─────────────────────────────────────────────────────────────────────────────
+
+
+def test_a_cell_whose_reply_finished_still_completes(cell_runner):
+ """The control that matters: the ordinary cell is untouched, and its readings are scored."""
+
+ cell_runner["stops_running_after_ms"] = 0.0 # already idle when the drain opens
+ runner = cell_runner["build"]()
+
+ row = runner.run(_cell(), _plan())
+
+ assert row["completed"] is True
+ assert row["stream"]["finished"] is True
+ assert row["assistant_chars_in_dom"] == CENSUS["assistant_chars"]
+ assert score_payload(cell_runner["paths"].payload_jsonl, [1_000]).rungs[0].complete is True
+
+
+def test_a_reply_that_ends_late_but_ends_still_completes(cell_runner):
+ """The other control, and the reason the deadline is what it is: a slow finish is a finding
+ the cell must KEEP, not a failure. Only a reply that never ends at all is one."""
+
+ cell_runner["expected_ms"] = 1000.0
+ cell_runner["stops_running_after_ms"] = 100_000.0 # 100 s, inside 3 x 1 s + 120 s
+ runner = cell_runner["build"]()
+
+ row = runner.run(_cell(), _plan())
+
+ assert row["completed"] is True
+ assert row["stream"]["finished"] is True
+ assert row["stream"]["drain_ms"] > 90_000
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_stats.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_stats.py
new file mode 100644
index 00000000000..b216fec78cd
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_stream_stats.py
@@ -0,0 +1,800 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A cell that under-streamed must not report COMPLETE.
+
+`send_turn` used to call `pacer.reset()` before loading the next turn, and `CellRunner` records
+only `pacer.last_stats()`. So on any rung that streams more than once -- 10K upwards -- the opening
+reply's `StreamStats` were discarded by the first follow-up and the first follow-up's by the
+second. The only other liveness signal is the UI no longer running, and a later turn that finishes
+satisfies it on behalf of an earlier one that did not. Measured against the real pacer: an opening
+reply whose client went away after 4,624 of 10,000 characters was erased by a follow-up that
+delivered its 1,500 in full, and the cell was marked complete and scored against a thread half the
+size of the rung it is named for.
+
+That is the defect class this whole benchmark has been burned by repeatedly: a measurement that
+under-measures and still reports success. It is worse than no measurement, because people act on
+it. So the stats for every planned turn are kept and checked, and a cell that did not stream what
+it planned fails by name.
+
+Three levels. The first drives the REAL pacer over a REAL socket through the REAL `send_turn`. The
+second drives the shipped `CellRunner` over dictated streams and asserts the consequence a reader
+sees. The third runs the whole cell against a real pacer over real wire bytes, so the control --
+an ordinary multi-turn cell still completes -- is not taken on trust either.
+"""
+
+from __future__ import annotations
+
+import json
+import socket
+import sys
+import threading
+import time
+import types
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.pacer import Pacer, check_planned_streams # noqa: E402
+from studiobench.runtime import session as session_mod # noqa: E402
+from studiobench.runtime.types import ActionContext, Cell, Window # noqa: E402
+from studiobench.scene.actions import send_turn # noqa: E402
+
+CELL_ID = "r10K.A0.rep0"
+OPENING = ("R" * 2_000, "C" * 8_000)
+FOLLOW = ("r" * 300, "c" * 1_200)
+
+
+# ── level 1: the pacer and the action, over a real socket ────────────────────────────────────
+
+
+def _consume(pacer: Pacer, *, stop_after_bytes: int | None = None) -> None:
+ """Read one stream off the wire. `stop_after_bytes` closes the socket mid-reply, which is what
+ an interrupted opening reply looks like from the pacer's side."""
+ conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ conn.settimeout(60)
+ conn.connect((pacer.host, pacer.port))
+ body = json.dumps(
+ {
+ "model": "studiobench-pacer",
+ "stream": True,
+ "messages": [{"role": "user", "content": "go"}],
+ }
+ ).encode()
+ conn.sendall(
+ b"POST /v1/chat/completions HTTP/1.1\r\nHost: 127.0.0.1\r\n"
+ b"Content-Type: application/json\r\nContent-Length: "
+ + str(len(body)).encode()
+ + b"\r\n\r\n"
+ + body
+ )
+ seen = b""
+ while b"[DONE]" not in seen:
+ if stop_after_bytes is not None and len(seen) >= stop_after_bytes:
+ break
+ try:
+ got = conn.recv(65536)
+ except socket.timeout:
+ break
+ if not got:
+ break
+ seen += got
+ conn.close()
+
+
+class _Page:
+ """Just enough page for `send_turn`: a composer, a keyboard, and an `isRunning` that is true
+ for as long as the follow-up's client is draining the stream."""
+
+ def __init__(self, pacer: Pacer) -> None:
+ self.pacer = pacer
+ self.running = False
+ self.messages = 4
+ self._thread: threading.Thread | None = None
+
+ def query_selector(self, selector):
+ return object() if "Message input" in selector else None
+
+ def fill(self, *a, **k) -> None:
+ pass
+
+ def wait_for_timeout(self, ms) -> None:
+ time.sleep(ms / 1000.0)
+
+ @property
+ def keyboard(self):
+ return types.SimpleNamespace(press = self._press)
+
+ def _press(self, key) -> None:
+ self.running = True
+ self.messages += 2
+
+ def run() -> None:
+ _consume(self.pacer)
+ self.running = False
+
+ self._thread = threading.Thread(target = run, daemon = True)
+ self._thread.start()
+
+ def drain(self) -> None:
+ if self._thread is not None:
+ self._thread.join(timeout = 60)
+
+ def evaluate(self, expr, *args):
+ if "isRunning" in expr:
+ return self.running
+ if "messageCount" in expr:
+ return self.messages
+ return 0
+
+
+def _ctx(page, pacer, queue, cursor) -> ActionContext:
+ return ActionContext(
+ page = page,
+ cdp = None,
+ cell = Cell(cell_id = CELL_ID, rung = "10K", rung_tokens = 10_000, tier = "quick"),
+ window = Window(name = "action:send_turn", kind = "action", cell = None, t_open_ms = 0.0),
+ args = {
+ "cell_id": CELL_ID,
+ "cadence": "fast",
+ "_pacer": pacer,
+ "_stream_queue": queue,
+ "_stream_cursor": cursor,
+ },
+ budget_ms = 20_000,
+ dom = None,
+ log = lambda msg: None,
+ )
+
+
+def test_send_turn_keeps_the_stats_of_every_turn_before_it():
+ """THE BUG, at the level it lives at. An opening reply that under-delivered, then two
+ follow-ups that did not. Before the fix the pacer held one stream at the end of this."""
+
+ pacer = Pacer().start()
+ try:
+ pacer.reset()
+ pacer.load(OPENING[0], OPENING[1], cadence = "fast", tag = CELL_ID)
+ _consume(pacer, stop_after_bytes = 20_000)
+ time.sleep(0.5)
+
+ opening = pacer.last_stats()
+ planned_chars = len(OPENING[0]) + len(OPENING[1])
+ assert opening["chars_sent"] < planned_chars, "the opening reply did not under-deliver"
+ assert opening["completed"] is False
+
+ queue = [
+ {"reasoning": FOLLOW[0], "content": FOLLOW[1], "kind": "prose"},
+ {"reasoning": FOLLOW[0], "content": FOLLOW[1], "kind": "code"},
+ ]
+ cursor = {"i": 0}
+ page = _Page(pacer)
+ tags = []
+ for _ in (1, 2):
+ result = send_turn(_ctx(page, pacer, queue, cursor))
+ page.drain()
+ time.sleep(0.4)
+ assert result.ran is True
+ tags.append(result.expect["pacer_tag"])
+
+ streams = pacer.all_stats()
+ # The opening reply is STILL THERE, and still says it did not finish.
+ assert [s["tag"] for s in streams] == [CELL_ID] + tags
+ assert streams[0]["completed"] is False
+ assert streams[0]["chars_sent"] == opening["chars_sent"]
+ assert all(s["completed"] for s in streams[1:])
+
+ check = check_planned_streams(
+ streams,
+ [{"tag": CELL_ID, "turn": "opening", "chars": planned_chars}]
+ + [
+ {"tag": t, "turn": f"follow_up{i}", "chars": len(FOLLOW[0]) + len(FOLLOW[1])}
+ for i, t in enumerate(tags, start = 1)
+ ],
+ )
+ assert check["ok"] is False
+ assert CELL_ID in check["reason"] and "did not complete" in check["reason"]
+ finally:
+ pacer.stop()
+
+
+# ── the check on its own ─────────────────────────────────────────────────────────────────────
+
+
+def test_the_check_passes_when_every_planned_turn_streamed_in_full():
+ streams = [
+ {"tag": "c1", "chars_sent": 100, "completed": True, "disconnected": False},
+ {"tag": "c1#turn1", "chars_sent": 50, "completed": True, "disconnected": False},
+ ]
+ got = check_planned_streams(
+ streams,
+ [
+ {"tag": "c1", "turn": "opening", "chars": 100},
+ {"tag": "c1#turn1", "turn": "follow_up1", "chars": 50},
+ ],
+ )
+ assert got["ok"] is True
+ assert got["reason"] is None
+ assert got["extra"] == []
+
+
+def test_a_short_turn_fails_the_check_with_both_counts_named():
+ got = check_planned_streams(
+ [{"tag": "c1", "chars_sent": 40, "completed": True, "disconnected": False}],
+ [{"tag": "c1", "turn": "opening", "chars": 100}],
+ )
+ assert got["ok"] is False
+ assert "delivered 40 of the 100 characters planned" in got["reason"]
+
+
+def test_a_turn_that_never_reached_the_pacer_fails_the_check():
+ got = check_planned_streams([], [{"tag": "c1", "turn": "opening", "chars": 100}])
+ assert got["ok"] is False
+ assert "never reached the pacer" in got["reason"]
+ assert got["turns"][0]["found"] is False
+
+
+def test_the_stop_actions_throwaway_turn_is_extra_and_not_a_failure():
+ """`stop_generation` sends its own turn against whatever script is loaded and cancels it, so a
+ second stream carries the tag of the turn before it. Matching takes the FIRST stream per tag,
+ and the aborted throwaway is reported as `extra` rather than failing the cell."""
+
+ streams = [
+ {"tag": "c1", "chars_sent": 100, "completed": True, "disconnected": False},
+ {"tag": "c1", "chars_sent": 12, "completed": False, "disconnected": True},
+ ]
+ got = check_planned_streams(streams, [{"tag": "c1", "turn": "opening", "chars": 100}])
+ assert got["ok"] is True
+ assert len(got["extra"]) == 1 and got["extra"][0]["disconnected"] is True
+
+
+def test_a_cell_with_nothing_planned_is_not_checked():
+ got = check_planned_streams([], [])
+ assert got["checked"] is False and got["ok"] is True
+
+
+# ── level 2: what the cell does with it ──────────────────────────────────────────────────────
+
+
+CENSUS = {"messages": 6, "elements": 1200, "highlight_spans": 200, "assistant_chars": 1120}
+
+
+class _CellPage:
+ def goto(self, *a, **k) -> None:
+ pass
+
+ def wait_for_selector(self, *a, **k) -> None:
+ pass
+
+ def click(self, *a, **k) -> None:
+ pass
+
+ def fill(self, *a, **k) -> None:
+ pass
+
+ def wait_for_timeout(self, ms) -> None:
+ pass
+
+ def query_selector(self, selector):
+ return types.SimpleNamespace(click = lambda: None) if "Send message" in selector else None
+
+ def evaluate(self, expr, *args):
+ if "isRunning" in expr:
+ return False
+ if "assistantChars" in expr:
+ return CENSUS["assistant_chars"]
+ return 0
+
+
+class _RecordedPacer:
+ """A pacer whose streams are dictated by the test, so the cell path can be driven over both
+ outcomes without a socket."""
+
+ def __init__(self, streams: list[dict]) -> None:
+ self.streams = streams
+
+ def reset(self) -> None:
+ pass
+
+ def load(self, *a, **k) -> None:
+ pass
+
+ def expected_duration_ms(self, reasoning, content, cadence) -> float:
+ return 1000.0
+
+ def last_stats(self) -> dict:
+ return self.streams[-1] if self.streams else {}
+
+ def all_stats(self) -> list[dict]:
+ return list(self.streams)
+
+
+class _SceneRunner:
+ """One `send_turn` that ran, so the cell has a follow-up to demand of the pacer."""
+
+ def __init__(self, **kwargs) -> None:
+ self.kwargs = kwargs
+
+ def run(self, scene, t0) -> list:
+ row = {
+ "row_type": "action",
+ "cell_id": self.kwargs["cell"].cell_id,
+ "action": "send_turn",
+ "ran": True,
+ "expect_ok": True,
+ "expect": {
+ "turn_index": 1,
+ "streamed_chars": 1_500,
+ "pacer_tag": f"{self.kwargs['cell'].cell_id}#turn1",
+ },
+ "timings": {"to_first_token_ms": 40.0},
+ "slot_missed": False,
+ "census": dict(CENSUS),
+ }
+ self.kwargs["recorder"].emit(dict(row))
+ return [row]
+
+
+def _plan():
+ unit = types.SimpleNamespace(reasoning = "r" * 2_000, content = "c" * 8_000, kind = "tail")
+ follow = types.SimpleNamespace(reasoning = "r" * 300, content = "c" * 1_200, kind = "prose")
+ return types.SimpleNamespace(
+ rung = "10K",
+ streamed_unit = unit,
+ seeded_units = [],
+ follow_up_units = [follow],
+ seeded_chars = 0,
+ streamed_chars = 10_000,
+ target_chars = 11_500,
+ target_tokens = 10_000,
+ )
+
+
+def cell_runner(monkeypatch, tmp_path):
+ from studiobench.runtime.session import CellRunner, Session
+ from studiobench.runtime.types import BenchContext, Paths, Recorder
+
+ monkeypatch.setattr(session_mod, "paint_floor_ms", lambda page: 8.0)
+ monkeypatch.setattr(session_mod, "dom_signature", lambda page: dict(CENSUS))
+ monkeypatch.setattr(
+ session_mod,
+ "measure_chars_per_token",
+ lambda *a, **k: {"chars_per_token": 3.7, "source": "stubbed"},
+ )
+ monkeypatch.setattr(session_mod, "cdp_metrics", lambda cdp: {})
+ monkeypatch.setattr(session_mod, "cdp_counters", lambda before, after: {})
+ monkeypatch.setattr(session_mod, "SceneRunner", _SceneRunner)
+ monkeypatch.setattr(session_mod, "dump_diagnostics", lambda *a, **k: None)
+ # NOT the 10K equivalence path, which reseeds a mirror thread and is a different subject.
+ monkeypatch.setattr(session_mod, "EQUIVALENCE_RUNG", "1K")
+
+ paths = Paths.under(tmp_path / "out")
+ recorder = Recorder(paths.payload_jsonl, "sess-1")
+ ctx = BenchContext(
+ page = _CellPage(),
+ cdp = None,
+ base_url = "http://127.0.0.1:5399",
+ session_id = "sess-1",
+ tier = "quick",
+ paths = paths,
+ recorder = recorder,
+ log = lambda msg: None,
+ )
+ session = Session(ctx = ctx)
+
+ def build(streams):
+ return CellRunner(
+ session = session,
+ pacer = _RecordedPacer(streams),
+ seeder = types.SimpleNamespace(
+ seed = lambda plan: types.SimpleNamespace(thread_id = "t1", seconds = 0.5, messages = 0),
+ auth = None,
+ ),
+ corpus = None,
+ base_url = "http://127.0.0.1:5399",
+ model_id = "studiobench-pacer",
+ tier = "quick",
+ paths = paths,
+ log = lambda msg: None,
+ )
+
+ return build
+
+
+def _cell():
+ return Cell(cell_id = CELL_ID, rung = "10K", rung_tokens = 10_000, tier = "quick")
+
+
+def test_a_cell_whose_opening_reply_under_delivered_does_not_complete(cell_runner):
+ """THE CONSEQUENCE. The follow-up finished, so the UI is idle and the drain check passes; the
+ opening reply delivered 4,624 of 10,000 characters. Before the fix this row read
+ `completed: true`."""
+
+ runner = cell_runner(
+ [
+ {"tag": CELL_ID, "chars_sent": 4_624, "completed": False, "disconnected": True},
+ {
+ "tag": f"{CELL_ID}#turn1",
+ "chars_sent": 1_500,
+ "completed": True,
+ "disconnected": False,
+ },
+ ]
+ )
+
+ row = runner.run(_cell(), _plan())
+
+ assert row["stream"]["finished"] is True
+ assert row["completed"] is False
+ assert "did not stream what it planned" in row["failure"]["message"]
+ # The named reason and the per-turn evidence reach the payload with the failure.
+ check = row["pacer"]["check"]
+ assert check["ok"] is False
+ assert check["turns"][0]["chars_sent"] == 4_624
+ assert check["turns"][0]["planned_chars"] == 10_000
+ assert check["turns"][1]["ok"] is True
+
+
+def test_a_cell_that_streamed_every_planned_turn_still_completes(cell_runner):
+ """The control. An unremarkable multi-turn cell is untouched, and every turn is on the row."""
+
+ runner = cell_runner(
+ [
+ {"tag": CELL_ID, "chars_sent": 10_000, "completed": True, "disconnected": False},
+ {
+ "tag": f"{CELL_ID}#turn1",
+ "chars_sent": 1_500,
+ "completed": True,
+ "disconnected": False,
+ },
+ ]
+ )
+
+ row = runner.run(_cell(), _plan())
+
+ assert row["completed"] is True
+ assert row["pacer"]["check"]["ok"] is True
+ assert [s["tag"] for s in row["pacer"]["streams"]] == [CELL_ID, f"{CELL_ID}#turn1"]
+
+
+def _scene_with(rows: list[dict]):
+ """A scene runner that emits exactly the action rows given."""
+
+ class _Fixed:
+ def __init__(self, **kwargs) -> None:
+ self.kwargs = kwargs
+
+ def run(self, scene, t0) -> list:
+ out = []
+ for spec in rows:
+ row = {
+ "row_type": "action",
+ "cell_id": self.kwargs["cell"].cell_id,
+ "slot_missed": False,
+ "timings": {},
+ "expect": {},
+ "census": dict(CENSUS),
+ **spec,
+ }
+ self.kwargs["recorder"].emit(dict(row))
+ out.append(row)
+ return out
+
+ return _Fixed
+
+
+#: A `send_turn` that RAN, loaded the pacer and pressed Enter, and whose own assertion failed.
+SEND_TURN_THAT_FAILED = {
+ "action": "send_turn",
+ "ran": True,
+ "expect_ok": False,
+ "expect": {"turn_index": 1, "streamed_chars": 1_500, "pacer_tag": f"{CELL_ID}#turn1"},
+ "reason": "the send did not start a new streaming reply",
+}
+
+
+def test_a_follow_up_that_was_sent_but_never_streamed_fails_the_cell(cell_runner, monkeypatch):
+ """`ran = True, expect_ok = False` is an ATTEMPTED turn that did not stream, not an unattempted
+ one. Skipping it let the cell pass the stream check with `planned_turns: 1`, complete, and
+ score against a thread one turn short of its rung."""
+
+ monkeypatch.setattr(session_mod, "SceneRunner", _scene_with([SEND_TURN_THAT_FAILED]))
+ runner = cell_runner(
+ [{"tag": CELL_ID, "chars_sent": 10_000, "completed": True, "disconnected": False}]
+ )
+
+ row = runner.run(_cell(), _plan())
+
+ assert row["completed"] is False
+ assert row["pacer"]["check"]["planned_turns"] == 2
+ assert f"{CELL_ID}#turn1" in row["failure"]["message"]
+ assert "never reached the pacer" in row["failure"]["message"]
+
+
+def test_a_follow_up_that_streamed_but_never_joined_the_thread_fails_the_cell(
+ cell_runner, monkeypatch
+):
+ """The other half. The pacer served every byte, so the stream check alone passes; the thread
+ did not grow, so every later action, the peak census and the equivalence mirror still read a
+ thread one turn short."""
+
+ monkeypatch.setattr(session_mod, "SceneRunner", _scene_with([SEND_TURN_THAT_FAILED]))
+ runner = cell_runner(
+ [
+ {"tag": CELL_ID, "chars_sent": 10_000, "completed": True, "disconnected": False},
+ {
+ "tag": f"{CELL_ID}#turn1",
+ "chars_sent": 1_500,
+ "completed": True,
+ "disconnected": False,
+ },
+ ]
+ )
+
+ row = runner.run(_cell(), _plan())
+
+ assert row["pacer"]["check"]["ok"] is True, "the bytes did go out; that is not the complaint"
+ assert row["completed"] is False
+ assert "follow-up turn 1 was sent but" in row["failure"]["message"]
+ assert "did not start a new streaming reply" in row["failure"]["message"]
+
+
+def test_an_ordinary_action_whose_assertion_failed_does_not_fail_the_cell(cell_runner, monkeypatch):
+ """THE SCOPE OF THE RULE, deliberately. `select_text` selecting nothing voids its own timing --
+ `scoring.from_payload._action_measure` already returns `Measure.failed` for it -- but it does
+ not change the workload the rest of the cell measured, and failing the cell would throw away a
+ whole cell's frame readings for a gesture that missed."""
+
+ monkeypatch.setattr(
+ session_mod,
+ "SceneRunner",
+ _scene_with(
+ [
+ {
+ "action": "select_text",
+ "ran": True,
+ "expect_ok": False,
+ "reason": "the selection did not cover the message",
+ },
+ {
+ "action": "send_turn",
+ "ran": True,
+ "expect_ok": True,
+ "expect": {
+ "turn_index": 1,
+ "streamed_chars": 1_500,
+ "pacer_tag": f"{CELL_ID}#turn1",
+ },
+ },
+ ]
+ ),
+ )
+ runner = cell_runner(
+ [
+ {"tag": CELL_ID, "chars_sent": 10_000, "completed": True, "disconnected": False},
+ {
+ "tag": f"{CELL_ID}#turn1",
+ "chars_sent": 1_500,
+ "completed": True,
+ "disconnected": False,
+ },
+ ]
+ )
+
+ row = runner.run(_cell(), _plan())
+
+ assert row["completed"] is True
+ assert row["expect_failures"] == 1
+
+
+def test_a_send_turn_that_did_not_run_is_not_demanded_of_the_pacer(cell_runner, monkeypatch):
+ """The other control, and the reason the planned list is built from the ACTION rows. At the
+ small rungs the queue is empty and `send_turn` reports NOT RUN; nothing was streamed for it and
+ nothing must be required of it."""
+
+ class _NoTurn(_SceneRunner):
+ def run(self, scene, t0) -> list:
+ row = {
+ "row_type": "action",
+ "cell_id": self.kwargs["cell"].cell_id,
+ "action": "send_turn",
+ "ran": False,
+ "expect_ok": None,
+ "slot_missed": False,
+ "expect": {},
+ "timings": {},
+ "reason": "the stream queue is exhausted (0 turns planned)",
+ "census": dict(CENSUS),
+ }
+ self.kwargs["recorder"].emit(dict(row))
+ return [row]
+
+ monkeypatch.setattr(session_mod, "SceneRunner", _NoTurn)
+ runner = cell_runner(
+ [{"tag": CELL_ID, "chars_sent": 10_000, "completed": True, "disconnected": False}]
+ )
+
+ row = runner.run(_cell(), _plan())
+
+ assert row["completed"] is True
+ assert row["pacer"]["check"]["planned_turns"] == 1
+
+
+# ── level 3: the whole cell, against a real pacer over real wire bytes ───────────────────────
+
+
+class _WirePage:
+ """A page whose sends really do fetch a stream off the pacer, so `isRunning` is true for
+ exactly as long as bytes are arriving. Everything the browser does with them is out of scope
+ here; what is in scope is that a healthy multi-turn cell passes the new check when the streams
+ are real rather than dictated by the test."""
+
+ def __init__(self, pacer: Pacer) -> None:
+ self.pacer = pacer
+ self.running = False
+ self.messages = 4
+ self._thread: threading.Thread | None = None
+
+ def goto(self, *a, **k) -> None:
+ pass
+
+ def wait_for_selector(self, *a, **k) -> None:
+ pass
+
+ def click(self, *a, **k) -> None:
+ pass
+
+ def fill(self, *a, **k) -> None:
+ pass
+
+ def wait_for_timeout(self, ms) -> None:
+ time.sleep(min(ms, 200) / 1000.0)
+
+ def query_selector(self, selector):
+ if "Send message" in selector:
+ return types.SimpleNamespace(click = lambda: self.send())
+ return object() if "Message input" in selector else None
+
+ @property
+ def keyboard(self):
+ return types.SimpleNamespace(press = lambda key: self.send())
+
+ def send(self) -> None:
+ self.running = True
+ self.messages += 2
+
+ def run() -> None:
+ _consume(self.pacer)
+ self.running = False
+
+ self._thread = threading.Thread(target = run, daemon = True)
+ self._thread.start()
+
+ def evaluate(self, expr, *args):
+ if "isRunning" in expr:
+ return self.running
+ if "messageCount" in expr:
+ return self.messages
+ if "assistantChars" in expr:
+ return CENSUS["assistant_chars"]
+ return 0
+
+
+class _RealSendTurnScene:
+ """The film, reduced to the two `send_turn` slots that matter here, running the SHIPPED action
+ against the shipped base_args the session builds."""
+
+ def __init__(self, **kwargs) -> None:
+ self.kwargs = kwargs
+
+ def run(self, scene, t0) -> list:
+ page = self.kwargs["page"]
+ rows = []
+ for _ in range(2):
+ while page.running:
+ time.sleep(0.05)
+ ctx = ActionContext(
+ page = page,
+ cdp = None,
+ cell = self.kwargs["cell"],
+ window = Window(name = "action:send_turn", kind = "action", cell = None, t_open_ms = 0.0),
+ args = dict(self.kwargs["base_args"]),
+ budget_ms = 20_000,
+ dom = None,
+ log = lambda msg: None,
+ )
+ result = send_turn(ctx)
+ row = result.row("send_turn", "action:send_turn", self.kwargs["cell"].cell_id)
+ row["census"] = dict(CENSUS)
+ self.kwargs["recorder"].emit(dict(row))
+ rows.append(row)
+ while page.running:
+ time.sleep(0.05)
+ return rows
+
+
+def test_a_healthy_multi_turn_cell_passes_the_check_over_real_wire_bytes(monkeypatch, tmp_path):
+ """The control the fix most needs: a cell that streamed everything it planned, with the pacer,
+ the action and the check all real, must still complete. The dictated-stream tests above prove
+ the failure path; this proves the ordinary path was not broken to get it."""
+
+ from studiobench.runtime.session import CellRunner, Session
+ from studiobench.runtime.types import BenchContext, Paths, Recorder
+
+ monkeypatch.setattr(session_mod, "paint_floor_ms", lambda page: 8.0)
+ monkeypatch.setattr(session_mod, "dom_signature", lambda page: dict(CENSUS))
+ monkeypatch.setattr(
+ session_mod,
+ "measure_chars_per_token",
+ lambda *a, **k: {"chars_per_token": 3.7, "source": "stubbed"},
+ )
+ monkeypatch.setattr(session_mod, "cdp_metrics", lambda cdp: {})
+ monkeypatch.setattr(session_mod, "cdp_counters", lambda before, after: {})
+ monkeypatch.setattr(session_mod, "SceneRunner", _RealSendTurnScene)
+ monkeypatch.setattr(session_mod, "dump_diagnostics", lambda *a, **k: None)
+ monkeypatch.setattr(session_mod, "EQUIVALENCE_RUNG", "1K")
+
+ pacer = Pacer().start()
+ try:
+ paths = Paths.under(tmp_path / "out")
+ recorder = Recorder(paths.payload_jsonl, "sess-1")
+ page = _WirePage(pacer)
+ ctx = BenchContext(
+ page = page,
+ cdp = None,
+ base_url = "http://127.0.0.1:5399",
+ session_id = "sess-1",
+ tier = "quick",
+ paths = paths,
+ recorder = recorder,
+ log = lambda msg: None,
+ )
+ runner = CellRunner(
+ session = Session(ctx = ctx),
+ pacer = pacer,
+ seeder = types.SimpleNamespace(
+ seed = lambda plan: types.SimpleNamespace(thread_id = "t1", seconds = 0.5, messages = 0),
+ auth = None,
+ ),
+ corpus = None,
+ base_url = "http://127.0.0.1:5399",
+ model_id = "studiobench-pacer",
+ tier = "quick",
+ paths = paths,
+ log = lambda msg: None,
+ cadence = "fast",
+ )
+ unit = types.SimpleNamespace(reasoning = "R" * 400, content = "C" * 1_200, kind = "tail")
+ follow = types.SimpleNamespace(reasoning = "r" * 100, content = "c" * 300, kind = "prose")
+ plan = types.SimpleNamespace(
+ rung = "10K",
+ streamed_unit = unit,
+ seeded_units = [],
+ follow_up_units = [follow, follow],
+ seeded_chars = 0,
+ streamed_chars = 1_600,
+ target_chars = 2_400,
+ target_tokens = 10_000,
+ )
+
+ row = runner.run(_cell(), plan)
+
+ assert row["completed"] is True, row.get("failure")
+ check = row["pacer"]["check"]
+ assert check["ok"] is True and check["planned_turns"] == 3
+ # Every planned turn delivered EXACTLY what it was loaded with, over the wire.
+ assert [t["chars_sent"] for t in check["turns"]] == [1_600, 400, 400]
+ assert [t["tag"] for t in check["turns"]] == [
+ CELL_ID,
+ f"{CELL_ID}#turn1",
+ f"{CELL_ID}#turn2",
+ ]
+ finally:
+ pacer.stop()
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_token_refresh.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_token_refresh.py
new file mode 100644
index 00000000000..e257d89c12b
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_token_refresh.py
@@ -0,0 +1,452 @@
+# 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 run is longer than the token it was handed.
+
+`ACCESS_TOKEN_EXPIRE_MINUTES` is 60 and this harness authenticated ONCE per arm, at setup, before
+the first install. A standard A/B at four repetitions is 24 cells of the 243 second standard film
+-- 97 minutes of film alone -- so the token the seeder holds expires part way through and every
+request after that answers 401. It presents as an intermittent failure and it is not one: it is
+the clock, and it is reproducible to the second.
+
+The fake Studio below issues tokens with a six second life instead of an hour's, and the tests drive
+`token()` with a one second margin, so the ratio between the two is the harness's own (15 minutes
+against 60) at a scale a test can wait for. `test_the_token_a_run_was_handed_stops_working` is the
+control that shows the server really does stop accepting an expired token, so the tests underneath
+are not passing for some other reason.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import sys
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.runtime import lifecycle # noqa: E402
+from studiobench.runtime.lifecycle import ( # noqa: E402
+ HttpError,
+ StudioAuth,
+ auth_request_json,
+ authenticate,
+ jwt_expiry,
+ request_json,
+ seed_init_script,
+)
+from studiobench.runtime.seeder import Seeder # noqa: E402
+
+#: How long the fake Studio's access tokens live. An hour compressed into something a test can sit
+#: through, and long enough that a loaded machine cannot expire one mid-request.
+TOKEN_TTL_S = 6.0
+#: The margin the tests below drive `token()` with. The REAL ratio matters: a margin far shorter
+#: than the token's life is what the harness runs with (15 minutes against 60), and a margin longer
+#: than the whole life would make every call rotate and prove nothing.
+TEST_MARGIN_S = 1.0
+PASSWORD = "studiobench-bench-password"
+
+
+def _b64(payload: dict) -> str:
+ raw = base64.urlsafe_b64encode(json.dumps(payload).encode("utf-8")).decode("ascii")
+ return raw.rstrip("=")
+
+
+class _State:
+ def __init__(self) -> None:
+ self.logins = 0
+ self.login_attempts = 0
+ self.rejections = 0
+ #: Set to reject EVERY token once, whatever its `exp` says: a Studio restarted underneath
+ #: the run, or a clock this process cannot see.
+ self.reject_next = 0
+ self.lock = threading.Lock()
+
+ def mint(self) -> str:
+ exp = time.time() + TOKEN_TTL_S
+ return f"{_b64({'alg': 'HS256'})}.{_b64({'sub': 'bench', 'exp': exp})}.sig"
+
+
+class _Handler(BaseHTTPRequestHandler):
+ state: _State
+
+ def log_message(self, *_args) -> None: # noqa: D102
+ pass
+
+ def _send(self, code: int, body: dict) -> None:
+ raw = json.dumps(body).encode("utf-8")
+ self.send_response(code)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(raw)))
+ self.end_headers()
+ self.wfile.write(raw)
+
+ def _body(self) -> dict:
+ length = int(self.headers.get("Content-Length") or 0)
+ return json.loads(self.rfile.read(length) or b"{}") if length else {}
+
+ def _authorised(self) -> bool:
+ with self.state.lock:
+ if self.state.reject_next > 0:
+ self.state.reject_next -= 1
+ self.state.rejections += 1
+ return False
+ header = self.headers.get("Authorization") or ""
+ token = header.split(" ", 1)[-1] if header.startswith("Bearer ") else ""
+ exp = jwt_expiry(token)
+ if exp is None or exp <= time.time():
+ with self.state.lock:
+ self.state.rejections += 1
+ return False
+ return True
+
+ def do_POST(self) -> None: # noqa: N802
+ body = self._body()
+ if self.path == "/api/auth/login":
+ with self.state.lock:
+ self.state.login_attempts += 1
+ if body.get("password") != PASSWORD:
+ self._send(401, {"detail": "bad password"})
+ return
+ with self.state.lock:
+ self.state.logins += 1
+ self._send(
+ 200,
+ {
+ "access_token": self.state.mint(),
+ "refresh_token": f"refresh-{self.state.logins}",
+ "must_change_password": False,
+ },
+ )
+ return
+ if not self._authorised():
+ self._send(401, {"detail": "Not authenticated"})
+ return
+ self._send(200, {"ok": True, "path": self.path})
+
+ def do_GET(self) -> None: # noqa: N802
+ if self.path == "/api/auth/status":
+ self._send(200, {"requires_password_change": False})
+ return
+ if not self._authorised():
+ self._send(401, {"detail": "Not authenticated"})
+ return
+ self._send(200, {"ok": True, "path": self.path})
+
+ def do_PUT(self) -> None: # noqa: N802
+ self._body()
+ if not self._authorised():
+ self._send(401, {"detail": "Not authenticated"})
+ return
+ self._send(200, {"ok": True, "path": self.path})
+
+
+def studio():
+ state = _State()
+ handler = type("_Bound", (_Handler,), {"state": state})
+ server = HTTPServer(("127.0.0.1", 0), handler)
+ thread = threading.Thread(target = server.serve_forever, daemon = True)
+ thread.start()
+ try:
+ yield f"http://127.0.0.1:{server.server_port}", state
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
+def test_the_token_a_run_was_handed_stops_working(studio):
+ """THE CONTROL, and the defect itself: hold one token and it expires under you.
+
+ This is what the harness did -- authenticate once, then send `auth.access_token` on every
+ request for the rest of the run -- reproduced at six seconds instead of sixty minutes.
+ """
+ base_url, _state = studio
+ auth = authenticate(base_url, "bench", PASSWORD, new_password = PASSWORD)
+ frozen = auth.access_token
+
+ assert request_json(f"{base_url}/api/chat/threads", method = "POST", token = frozen, body = {})
+ time.sleep(TOKEN_TTL_S + 0.5)
+ with pytest.raises(HttpError) as caught:
+ request_json(f"{base_url}/api/chat/threads", method = "POST", token = frozen, body = {})
+ assert caught.value.status == 401
+
+
+def test_the_seeder_keeps_working_after_its_token_expires(studio, monkeypatch):
+ """The fix, at the call site the review named: `Seeder.create_thread` past the expiry.
+
+ The margin is a sixth of the token's life here, so the first cell's thread is created on the
+ token the run was handed -- no rotation -- and only the one after the expiry rotates. That is
+ the shape of a real run: one login per hour, not one per request.
+ """
+ monkeypatch.setattr(lifecycle, "TOKEN_REFRESH_MARGIN_S", TEST_MARGIN_S)
+ base_url, state = studio
+ auth = authenticate(base_url, "bench", PASSWORD, new_password = PASSWORD)
+ seeder = Seeder(base_url = base_url, auth = auth, model_id = "m", log = lambda *_a: None)
+
+ assert seeder.create_thread()
+ assert auth.rotations == 0
+ logins_after_setup = state.logins
+
+ time.sleep(TOKEN_TTL_S + 0.5)
+ # The token the run was handed is dead by now -- the control above proves the server refuses
+ # it -- and this still has to work.
+ assert seeder.create_thread()
+ assert auth.rotations == 1
+ assert state.logins == logins_after_setup + 1
+ # And it never had to be told: the server was not asked to refuse anything.
+ assert state.rejections == 0
+ assert (auth.expires_at or 0) > time.time()
+
+
+def test_the_token_is_replaced_before_it_expires_not_after_it_fails(studio, monkeypatch):
+ """PROACTIVE, which is the half a 401 handler alone does not give you.
+
+ A 900 second seeding PUT that is valid when it is written and expired when the server finishes
+ reading it cannot be retried cheaply -- the whole thread goes up the wire again -- so the token
+ is replaced while it still has margin left. Here the margin is the whole of its life, so the
+ request never sees a 401 at all.
+ """
+ monkeypatch.setattr(lifecycle, "TOKEN_REFRESH_MARGIN_S", TEST_MARGIN_S)
+ base_url, state = studio
+ auth = authenticate(base_url, "bench", PASSWORD, new_password = PASSWORD)
+ # Inside the margin and NOT yet expired: the server would still accept the old token, and it
+ # is replaced anyway.
+ time.sleep(TOKEN_TTL_S - TEST_MARGIN_S / 2)
+
+ assert auth_request_json(auth, f"{base_url}/api/chat/threads", method = "POST", body = {})
+ assert auth.rotations == 1
+ assert state.rejections == 0
+
+
+def test_a_401_that_arrives_anyway_is_recovered(studio):
+ """The reactive half. A token this process believes is fresh can still be refused: a clock
+ offset against the server, or a Studio restarted underneath the run. One retry, then the
+ refusal is real and is raised."""
+ base_url, state = studio
+ auth = authenticate(base_url, "bench", PASSWORD, new_password = PASSWORD)
+ # Fresh by this process's reckoning, and refused by the server regardless.
+ auth.expires_at = time.time() + 10_000
+ state.reject_next = 1
+
+ assert auth_request_json(auth, f"{base_url}/api/chat/threads", method = "POST", body = {})
+ assert auth.rotations == 1
+ assert state.rejections == 1
+
+
+def test_a_refusal_that_survives_a_fresh_login_is_raised(studio):
+ """Not looped on. Two refusals in a row is a real 401 and the caller has to see it."""
+ base_url, state = studio
+ auth = authenticate(base_url, "bench", PASSWORD, new_password = PASSWORD)
+ auth.expires_at = time.time() + 10_000
+ state.reject_next = 2
+
+ with pytest.raises(HttpError) as caught:
+ auth_request_json(auth, f"{base_url}/api/chat/threads", method = "POST", body = {})
+ assert caught.value.status == 401
+
+
+def test_a_login_that_is_refused_is_not_retried_as_if_it_were_the_request(studio):
+ """ONE login attempt, not two.
+
+ `token()` can itself raise a 401 -- the password is wrong, or the account is locked -- and
+ catching that alongside the request's own 401 would answer it with a SECOND login. The backend
+ locks an account after five failures in a minute (`routes/auth.py`, `_LOGIN_MAX_FAILS`), so
+ burning the bucket at double rate reaches the lockout twice as fast and the run then dies on a
+ 429 that says nothing about the password.
+ """
+ base_url, state = studio
+ auth = authenticate(base_url, "bench", PASSWORD, new_password = PASSWORD)
+ auth.password = "not-the-password"
+ auth.expires_at = time.time() - 1
+ attempts_before = state.login_attempts
+
+ with pytest.raises(HttpError) as caught:
+ auth_request_json(auth, f"{base_url}/api/chat/threads", method = "POST", body = {})
+ assert caught.value.status == 401
+ assert state.login_attempts == attempts_before + 1
+
+
+def test_a_clock_that_makes_every_token_look_stale_stops_the_proactive_half(studio):
+ """The runaway guard. `needs_refresh` reads the server's `exp` against THIS process's clock.
+
+ A Studio 45 minutes behind, or one whose `ACCESS_TOKEN_EXPIRE_MINUTES` is shorter than the
+ margin -- which is exactly this fake studio, six seconds against fifteen minutes -- makes every
+ token ever issued look like it is about to expire, and every request would then log in again
+ and append another init script to the browser context. One rotation is enough to find that out.
+ """
+ base_url, state = studio
+ auth = authenticate(base_url, "bench", PASSWORD, new_password = PASSWORD)
+ assert auth.proactive is True
+
+ assert auth_request_json(auth, f"{base_url}/api/chat/threads", method = "POST", body = {})
+ assert auth.rotations == 1
+ assert auth.proactive is False
+
+ # And it does not keep doing it. The token is valid, so the request goes out on it untouched.
+ logins = state.logins
+ assert auth_request_json(auth, f"{base_url}/api/chat/threads", method = "POST", body = {})
+ assert state.logins == logins
+ assert auth.rotations == 1
+
+
+def test_a_failing_rotation_hook_does_not_fail_the_request(studio):
+ """`on_rotate` re-seeds a Playwright context, which can throw for reasons that have nothing to
+ do with authentication -- a closed context, a page that crashed. The token has already been
+ replaced by then and the request has to go out."""
+ monkeypatch_error = RuntimeError("Target page, context or browser has been closed")
+ base_url, _state = studio
+ auth = authenticate(base_url, "bench", PASSWORD, new_password = PASSWORD)
+
+ def _boom(_auth):
+ raise monkeypatch_error
+
+ auth.on_rotate = _boom
+ auth.expires_at = time.time() - 1
+
+ assert auth_request_json(auth, f"{base_url}/api/chat/threads", method = "POST", body = {})
+ assert auth.rotations == 1
+ assert "Target page" in (auth.hook_error or "")
+
+
+def test_the_margin_outlasts_the_longest_authenticated_request():
+ """The invariant the margin exists for, pinned rather than argued.
+
+ Seeding a 1M-token thread is ONE `PUT` with a 900 second timeout, so a token that is merely
+ valid when the request is written is not enough: it has to still be valid when the server
+ finishes reading the body. Lower the margin under that and this fails.
+ """
+ from studiobench.runtime.lifecycle import TOKEN_REFRESH_MARGIN_S
+
+ seed_put_timeout_s = 900
+ assert TOKEN_REFRESH_MARGIN_S >= seed_put_timeout_s
+
+
+def test_rotating_notifies_whoever_seeded_the_browser(studio):
+ """The page's localStorage is seeded from a SNAPSHOT of these values, and an init script
+ re-runs on every navigation, so the owner of that context is told when they go stale."""
+ base_url, _state = studio
+ auth = authenticate(base_url, "bench", PASSWORD, new_password = PASSWORD)
+ seen: list[str] = []
+ auth.on_rotate = lambda a: seen.append(a.access_token)
+
+ auth.rotate()
+ assert seen == [auth.access_token]
+
+
+def test_an_opaque_token_falls_back_to_the_documented_lifetime():
+ """A token whose `exp` cannot be read is assumed to live `ACCESS_TOKEN_TTL_S`, not forever."""
+ from studiobench.runtime.lifecycle import ACCESS_TOKEN_TTL_S
+
+ auth = StudioAuth(
+ access_token = "not-a-jwt",
+ refresh_token = "",
+ base_url = "http://127.0.0.1:1",
+ username = "bench",
+ password = PASSWORD,
+ )
+ assert auth.seconds_left() == pytest.approx(ACCESS_TOKEN_TTL_S, abs = 5)
+
+
+def test_the_page_is_seeded_with_the_refresh_key_the_app_actually_reads():
+ """The other half of the same defect, and the one that produced the Playwright symptom.
+
+ The SPA reads its refresh token from `AUTH_REFRESH_TOKEN_KEY`. Seeded under any other name the
+ page has an access token and no way to renew it, so the first 401 after the hour is up sends
+ `authFetch` down the branch that clears the tokens and navigates to the login route -- which
+ Playwright reports as `Execution context was destroyed, most likely because of a navigation`.
+
+ The key is read out of the frontend source rather than copied here, so this fails if the app
+ renames it.
+ """
+ session_ts = (
+ Path(__file__).resolve().parents[5] / "studio/frontend/src/features/auth/session.ts"
+ )
+ if not session_ts.exists():
+ pytest.skip("the frontend source is not in this tree")
+ key = ""
+ for line in session_ts.read_text(encoding = "utf-8").splitlines():
+ if "AUTH_REFRESH_TOKEN_KEY" in line and "=" in line:
+ key = line.split('"')[1]
+ break
+ assert key, "AUTH_REFRESH_TOKEN_KEY was not found in session.ts"
+
+ auth = StudioAuth(
+ access_token = "access-token",
+ refresh_token = "refresh-token",
+ base_url = "http://127.0.0.1:1",
+ username = "bench",
+ password = PASSWORD,
+ )
+ script = seed_init_script(auth, [])
+ assert f'"{key}": "refresh-token"' in script or f'"{key}":"refresh-token"' in script
+
+
+def _seed_script_for(exp: float, label: str) -> str:
+ """A seed script carrying a JWT that expires at `exp`."""
+ token = f"{_b64({'alg': 'HS256'})}.{_b64({'sub': 'bench', 'exp': exp})}.{label}"
+ auth = StudioAuth(
+ access_token = token,
+ refresh_token = f"refresh-{label}",
+ base_url = "http://127.0.0.1:1",
+ username = "bench",
+ password = PASSWORD,
+ )
+ return seed_init_script(auth, [])
+
+
+def _run_in_node(scripts: list) -> dict:
+ """Run init scripts against a localStorage shim and report what is in storage afterwards."""
+ import json as _json
+ import shutil
+ import subprocess
+
+ if shutil.which("node") is None:
+ pytest.skip("node is not installed")
+ harness = (
+ "const store = new Map();\n"
+ "globalThis.window = { localStorage: {\n"
+ " getItem: (k) => (store.has(k) ? store.get(k) : null),\n"
+ " setItem: (k, v) => store.set(k, String(v)),\n"
+ "}, atob: (s) => Buffer.from(s, 'base64').toString('binary') };\n"
+ + "\n".join(scripts)
+ + "\nconsole.log(JSON.stringify(Object.fromEntries(store)));\n"
+ )
+ out = subprocess.run(
+ ["node", "-e", harness], capture_output = True, text = True, timeout = 60, check = True
+ )
+ return _json.loads(out.stdout.strip().splitlines()[-1])
+
+
+def test_the_freshest_seed_script_wins_whatever_order_they_run_in():
+ """An init script re-runs on EVERY navigation and Playwright does not define the order that
+ several of them run in, so "the one added last wins" is not a property this can rely on.
+
+ The stale script must not put the token the run started with back over the one the SPA -- or a
+ later re-seed -- rotated to. Both orders, one answer.
+ """
+ now = time.time()
+ stale = _seed_script_for(now - 60, "stale")
+ fresh = _seed_script_for(now + 3600, "fresh")
+
+ for order, name in ((f"{stale}\n{fresh}", "stale first"), (f"{fresh}\n{stale}", "fresh first")):
+ storage = _run_in_node([order])
+ assert storage["unsloth_auth_token"].endswith(".fresh"), name
+ assert storage["unsloth_auth_refresh_token"] == "refresh-fresh", name
+
+
+def test_a_seed_script_still_seeds_an_empty_page():
+ """The control on the guard: with nothing in storage, the seed is written as it always was."""
+ storage = _run_in_node([_seed_script_for(time.time() + 3600, "first")])
+ assert storage["unsloth_auth_token"].endswith(".first")
+ assert storage["unsloth_auth_refresh_token"] == "refresh-first"
+ assert storage["unsloth_chat_connections_enabled"] == "true"
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/runtime/selftest/test_studiobench_watchdog_budget.py b/tests/studio/studiobench/runtime/selftest/test_studiobench_watchdog_budget.py
new file mode 100644
index 00000000000..76482ed29bf
--- /dev/null
+++ b/tests/studio/studiobench/runtime/selftest/test_studiobench_watchdog_budget.py
@@ -0,0 +1,202 @@
+# 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 watchdog may not kill a healthy run during the setup it is waiting for.
+
+`--branch REF` is the advertised self-managed path: studiobench clones this repository and runs
+`install.sh`, a multi-gigabyte download it allows 45 minutes for, and an A/B does that twice
+before the first cell. The deadline was three times the TIER budget -- 15 minutes on fast and
+quick, the two tiers people iterate with -- armed before the first install, so a slow download
+tripped `os._exit(2)` during setup. It exits through `os._exit`, so the `finally` that stops the
+Studios and the pacer does not run either: the run dies, leaves its processes behind, and never
+reaches the measurement it advertised.
+
+The deadline is asserted at the real entry point, by driving `run()` until the first install.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench import __main__ as cli # noqa: E402
+from studiobench.runtime import browser as browser_mod # noqa: E402
+from studiobench.runtime import lifecycle # noqa: E402
+
+#: What the README documents for one `install.sh`, and what `install_studio` allows it.
+INSTALL_BUDGET_S = 45 * 60
+
+
+class _StopBeforeInstalling(RuntimeError):
+ pass
+
+
+class _FakeWatchdog:
+ def cancel(self) -> None:
+ pass
+
+
+def _armed_deadline(monkeypatch, tmp_path, argv):
+ """Run the CLI for real up to the first install, and report the deadline it armed."""
+
+ seen: list[float] = []
+
+ def _capture(
+ deadline_s,
+ label = "studiobench",
+ log = print,
+ ):
+ seen.append(float(deadline_s))
+ return _FakeWatchdog()
+
+ def _no_install(*_args, **_kwargs):
+ raise _StopBeforeInstalling("the test stops here")
+
+ def _no_attach(base_url, *_args, **_kwargs):
+ raise _StopBeforeInstalling("the test stops here")
+
+ monkeypatch.setattr(browser_mod, "install_wall_clock_watchdog", _capture)
+ monkeypatch.setattr(lifecycle, "install_studio", _no_install)
+ monkeypatch.setattr(lifecycle, "wait_for_healthz", _no_attach)
+
+ args = cli.parse_args([*argv, "--out", str(tmp_path / "out")])
+ with pytest.raises(_StopBeforeInstalling):
+ cli.run(args, ab_ref = args.ab)
+ assert len(seen) == 1
+ return seen[0]
+
+
+def test_a_self_managed_ab_watchdog_covers_both_installs(monkeypatch, tmp_path):
+ deadline = _armed_deadline(
+ monkeypatch, tmp_path, ["--tier", "fast", "--branch", "main", "--ab", "fix"]
+ )
+ assert deadline >= cli.TIER_BUDGET_S["fast"] * 3 + 2 * INSTALL_BUDGET_S
+
+
+def test_an_attached_run_adds_no_install_budget(monkeypatch, tmp_path):
+ """The control: a run that installs nothing keeps the measurement deadline it always had.
+
+ A fast-tier A/B is two 57 second films, so the planned work is nowhere near the tier's own
+ 900 seconds and the tier budget still decides. The fast tier stays fast.
+ """
+
+ deadline = _armed_deadline(
+ monkeypatch,
+ tmp_path,
+ [
+ "--tier",
+ "fast",
+ "--attach",
+ "http://127.0.0.1:5401",
+ "--attach-b",
+ "http://127.0.0.1:5402",
+ "--ab",
+ "fix",
+ ],
+ )
+ assert deadline == cli.TIER_BUDGET_S["fast"] * 3
+
+
+def _planned_film_s(tier: str, rungs: int, reps: int, arms: int) -> float:
+ """The FILM alone, with no allowance for anything around it: the floor the deadline must clear."""
+ from studiobench.scene.schedule import SCENES
+ return SCENES[tier].duration_ms / 1000.0 * rungs * reps * arms
+
+
+def test_a_standard_ab_at_four_reps_is_not_hard_exited_part_way_through(monkeypatch, tmp_path):
+ """The defect. Three rungs, four reps, two arms is 24 cells of the 243 second standard film.
+
+ That is 5,832 seconds of film before a thread is seeded, and the deadline was
+ `TIER_BUDGET_S["standard"] * 3` = 3,600 seconds with nothing added for an attached pair -- so
+ the watchdog fired 40% of the way through a perfectly healthy run, through `os._exit`, taking
+ the `finally` that stops the Studios with it.
+ """
+
+ deadline = _armed_deadline(
+ monkeypatch,
+ tmp_path,
+ [
+ "--tier",
+ "standard",
+ "--reps",
+ "4",
+ "--attach",
+ "http://127.0.0.1:5401",
+ "--attach-b",
+ "http://127.0.0.1:5402",
+ "--ab",
+ "fix",
+ ],
+ )
+ film_s = _planned_film_s("standard", rungs = 3, reps = 4, arms = 2)
+ assert film_s == pytest.approx(5832)
+ assert deadline > cli.TIER_BUDGET_S["standard"] * 3
+ assert deadline > film_s
+
+
+def test_a_rung_override_the_tier_never_had_is_covered(monkeypatch, tmp_path):
+ """`--rungs` is a ladder the tier does not describe, so the tier budget cannot describe it."""
+
+ deadline = _armed_deadline(
+ monkeypatch,
+ tmp_path,
+ [
+ "--tier",
+ "standard",
+ "--rungs",
+ "1K,10K,100K,500K,1M",
+ "--reps",
+ "3",
+ "--attach",
+ "http://127.0.0.1:5401",
+ "--attach-b",
+ "http://127.0.0.1:5402",
+ "--ab",
+ "fix",
+ ],
+ )
+ assert deadline > _planned_film_s("standard", rungs = 5, reps = 3, arms = 2)
+
+
+def test_the_scaled_deadline_is_still_capped(monkeypatch, tmp_path):
+ """A deadline that scales without limit is not a deadline."""
+
+ deadline = _armed_deadline(
+ monkeypatch,
+ tmp_path,
+ [
+ "--tier",
+ "full",
+ "--reps",
+ "500",
+ "--attach",
+ "http://127.0.0.1:5401",
+ "--attach-b",
+ "http://127.0.0.1:5402",
+ "--ab",
+ "fix",
+ ],
+ )
+ assert deadline == cli.WATCHDOG_MAX_MEASUREMENT_S
+
+
+def test_a_single_arm_tier_ladder_keeps_its_documented_budget(monkeypatch, tmp_path):
+ """Every tier's own ladder, run once against one attached Studio, is unchanged.
+
+ This is the regression guard on the change: the deadline may only grow where the caller asked
+ for more work than the tier describes.
+ """
+
+ for tier in ("fast", "quick", "standard", "full"):
+ deadline = _armed_deadline(
+ monkeypatch, tmp_path, ["--tier", tier, "--attach", "http://127.0.0.1:5401"]
+ )
+ assert deadline == cli.TIER_BUDGET_S[tier] * 3, tier
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/tests/studio/studiobench/runtime/session.py b/tests/studio/studiobench/runtime/session.py
new file mode 100644
index 00000000000..35964346366
--- /dev/null
+++ b/tests/studio/studiobench/runtime/session.py
@@ -0,0 +1,826 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""One session: one browser, one Studio, one pacer, N cells.
+
+A SESSION IS THE UNIT OF COMPARISON. Every slope, ratio and A/B pair must be read within one of
+these, because cross-session drift on this app has been measured at 8% -- larger than most of the
+effects worth arguing about. `Cell.session_id` carries the truth so the report layer can refuse a
+comparison that spans two.
+
+The measured window structure per cell, in order:
+
+ 1. seed the thread over REST, navigate, wait for the thread to mount
+ 2. ENFORCED IDLE WINDOW -- nothing streaming, no action, the page at rest -- and the timer clamp
+ is calibrated inside it. This is the fix for the salvaged recorder's worst bug: calibrating
+ from the first 60 ticks of a page that already has 31,637 elements standing measures the
+ app's steady-state load, calls it the timer floor, subtracts it out of every window, and
+ reports a saturated page as 0.2% busy.
+ 3. a resting census, so the growth axis has a denominator that was actually counted
+ 4. press send; the film starts; the scene's slots run against wall clock
+ 5. drain the stream, final census, teardown
+"""
+
+from __future__ import annotations
+
+import contextlib
+import time
+import traceback
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Callable, Optional
+
+from ..fixture.corpus import PROVISIONAL_CHARS_PER_TOKEN, Corpus, RungPlan, plan_rung
+from ..instruments import build as build_instruments
+from ..instruments import import_errors
+from ..pacer import Pacer, check_planned_streams
+from ..scene import schedule as scene_schedule
+from ..scene.actions import paint_floor_ms
+from ..scene.schedule import SceneRunner
+from .browser import cdp_counters, cdp_metrics, dump_diagnostics
+from .lifecycle import StudioAuth
+from .seeder import Seeder, compare_signatures, dom_signature, measure_chars_per_token
+from .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.
+# Generated rather than shipped as a binary asset: the artifact is a zipapp and a tester's
+# machine has no fixture directory, and an action that reports `ran = False, no image path` at
+# every rung is a hole in the suite that looks like a decision.
+_PNG_1X1 = bytes.fromhex(
+ "89504e470d0a1a0a0000000d494844520000000100000001080600000"
+ "01f15c4890000000d49444154789c6360000002000100ffff03000006"
+ "0005570b8f0000000049454e44ae426082"
+)
+
+
+def ensure_probe_image(paths: Paths) -> Path:
+ png = paths.out / "probe.png"
+ if not png.exists():
+ png.write_bytes(_PNG_1X1)
+ return png
+
+
+IDLE_CALIBRATION_MS = 1500
+# The rung the seeded-vs-streamed equivalence is CHECKED at. 10K, because both paths are
+# affordable there: streaming it takes under a minute at field cadence, and seeding it is instant.
+# Below it the thread is one turn and there is nothing to seed; above it, streaming the whole
+# thread is hours.
+EQUIVALENCE_RUNG = "10K"
+MOUNT_TIMEOUT_S = 180
+
+
+class WindowInUse(RuntimeError):
+ pass
+
+
+@dataclass
+class Session:
+ ctx: BenchContext
+ instruments: list = field(default_factory = list)
+ _open: Optional[Window] = None
+ cell: Optional[Cell] = None
+
+ # ── windows ─────────────────────────────────────────────────────
+
+ @contextlib.contextmanager
+ def window(
+ self,
+ name: str,
+ kind: str = "action",
+ ):
+ """Open a measurement window. Windows do NOT nest and do NOT overlap."""
+ if self._open is not None:
+ raise WindowInUse(
+ f"cannot open window {name!r}: {self._open.name!r} is still open. Overlapping "
+ "windows would charge the same work to both."
+ )
+ w = Window(name = name, kind = kind, cell = self.cell, t_open_ms = self._now_ms())
+ self._open = w
+ for inst in sorted(self.instruments, key = lambda i: i.name):
+ self._safe(inst, "open", w)
+ try:
+ yield w
+ finally:
+ w.t_close_ms = self._now_ms()
+ # REVERSE order on close, so an instrument that wrapped another's state unwinds after
+ # the one it wrapped.
+ for inst in sorted(self.instruments, key = lambda i: i.name, reverse = True):
+ got = self._safe(inst, "close", w)
+ if got is not None:
+ w.instruments[inst.name] = got
+ self._open = None
+ self.ctx.recorder.emit(w.row())
+
+ def each_instrument(self, method: str, *args) -> dict:
+ """Run one lifecycle hook on every instrument, and collect what each returned.
+
+ OVER A SNAPSHOT, not the live list. `_safe` drops an instrument that raises, and removing
+ from the list being iterated makes Python skip whichever instrument shifted into the freed
+ index, so one broken optional instrument silently cost its neighbour's hook as well --
+ `heap` failing took `input`, and with it the highest-weight metric in the table, while the
+ cell still completed and reported.
+ """
+ out: dict = {}
+ for inst in list(self.instruments):
+ got = self._safe(inst, method, *args)
+ if got is not None:
+ out[inst.name] = got
+ return out
+
+ def _safe(self, inst, method: str, *args):
+ """One broken instrument never costs the window."""
+ fn = getattr(inst, method, None)
+ if fn is None:
+ return None
+ try:
+ return fn(*args)
+ except Exception as exc: # noqa: BLE001
+ self.ctx.log(
+ f" instrument {inst.name}.{method} failed: " f"{type(exc).__name__}: {exc}"
+ )
+ if inst in self.instruments:
+ self.instruments.remove(inst)
+ return {"error": f"{type(exc).__name__}: {exc}", "disabled": True}
+
+ def _now_ms(self) -> float:
+ return self.ctx.recorder.now_ms()
+
+
+@dataclass
+class CellRunner:
+ """Runs one cell end to end and always emits a `cell` row, completed or not."""
+
+ session: Session
+ pacer: Pacer
+ seeder: Seeder
+ corpus: Corpus
+ base_url: str
+ model_id: str
+ tier: str
+ paths: Paths
+ log: Callable[[str], None] = print
+ image_path: Optional[Path] = None
+ cadence: str = "field"
+ # Set once the 10K check fails, and it then labels every LARGER rung, which is the whole
+ # point: those rungs are mostly seeded and their fidelity depends on this one answer.
+ equivalence_failed: bool = False
+
+ def run(self, cell: Cell, plan: RungPlan) -> dict:
+ s = self.session
+ s.cell = cell
+ rec = s.ctx.recorder
+ page = s.ctx.page
+ self.log(
+ f"\n=== cell {cell.cell_id}: {plan.rung} "
+ f"({plan.seeded_chars:,} seeded + {plan.streamed_chars:,} streamed chars)"
+ )
+ s.each_instrument("start_cell", cell)
+
+ row: dict = {
+ "row_type": "cell",
+ "cell_id": cell.cell_id,
+ "cell": cell.as_dict(),
+ "completed": False,
+ "fidelity": "unknown",
+ "seeded_chars": plan.seeded_chars,
+ "streamed_chars": plan.streamed_chars,
+ "target_chars": plan.target_chars,
+ "target_tokens": plan.target_tokens,
+ "instruments": {},
+ }
+ try:
+ self._run_inner(cell, plan, row)
+ row["completed"] = True
+ except Exception as exc: # noqa: BLE001
+ row["failure"] = {
+ "kind": type(exc).__name__,
+ "message": str(exc),
+ "traceback": traceback.format_exc()[-3000:],
+ }
+ self.log(f" cell FAILED: {type(exc).__name__}: {exc}")
+ rec.failure(cell.cell_id, type(exc).__name__, {"message": str(exc)})
+ with contextlib.suppress(Exception):
+ dump_diagnostics(page, self.paths.logs, f"fail_{cell.cell_id}", self.log)
+ finally:
+ row["instruments"].update(s.each_instrument("end_cell", cell))
+ # A cell that could not complete is a FIRST-CLASS RESULT with its failure mode and its
+ # RSS at death, not a gap in the table.
+ rss = row["instruments"].get("rss") or {}
+ row["rss_at_death_mb"] = rss.get("rss_peak_mb") if not row["completed"] else None
+ rec.emit(row)
+ return row
+
+ # ── the cell ────────────────────────────────────────────────────
+
+ def _run_inner(self, cell: Cell, plan: RungPlan, row: dict) -> None:
+ s = self.session
+ page = s.ctx.page
+ rec = s.ctx.recorder
+
+ seeded = self.seeder.seed(plan)
+ row["thread_id"] = seeded.thread_id
+ row["seed_seconds"] = round(seeded.seconds, 2)
+ row["seeded_messages"] = seeded.messages
+
+ page.goto(
+ f"{self.base_url}/chat?thread={seeded.thread_id}",
+ wait_until = "domcontentloaded",
+ timeout = 120_000,
+ )
+ self._wait_for_thread(page, seeded.messages)
+
+ # ── the enforced idle window ────────────────────────────────
+ frames = next((i for i in s.instruments if i.name == "frames"), None)
+ with s.window("idle:calibrate", kind = "idle") as w:
+ clamp = (
+ frames.calibrate(IDLE_CALIBRATION_MS)
+ if frames
+ else {"clampMs": None, "reason": "the frames instrument is not loaded"}
+ )
+ w.note("clamp", clamp)
+ row["clamp"] = clamp
+ if clamp.get("clampMs") is None:
+ # NOT fatal, and NOT silently zero. Blocked time is a subtraction against this floor,
+ # 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)
+ else:
+ self.log(
+ f" timer clamp {clamp['clampMs']:.2f}ms " f"over {clamp.get('samples')} idle ticks"
+ )
+ rec.gate("timer_clamp", True, clamp)
+
+ row["paint_floor_ms"] = paint_floor_ms(page)
+ row["census_before"] = dom_signature(page)
+ self.log(
+ f" at rest: {row['census_before']['messages']} messages, "
+ f"{row['census_before']['elements']:,} elements, "
+ f"{row['census_before']['highlight_spans']:,} highlight spans"
+ )
+
+ cpt = measure_chars_per_token(
+ (plan.streamed_unit.reasoning + plan.streamed_unit.content)
+ if plan.streamed_unit
+ else "",
+ self.base_url,
+ self.seeder.auth,
+ self.model_id,
+ )
+ row.update(
+ {
+ "chars_per_token": cpt.get("chars_per_token"),
+ "chars_per_token_source": cpt.get("source"),
+ "chars_per_token_detail": cpt,
+ }
+ )
+ self.log(
+ f" chars per token: {cpt.get('chars_per_token')} "
+ f"(measured via {cpt.get('source')})"
+ )
+
+ # ── the film ────────────────────────────────────────────────
+ unit = plan.streamed_unit
+ self.pacer.reset()
+ self.pacer.load(
+ unit.reasoning,
+ unit.content,
+ cadence = self.cadence,
+ tag = cell.cell_id,
+ model = self.model_id,
+ )
+ expected_ms = self.pacer.expected_duration_ms(unit.reasoning, unit.content, self.cadence)
+ row["stream_expected_ms"] = expected_ms
+ self.log(
+ f" streaming {len(unit.reasoning):,} reasoning + {len(unit.content):,} "
+ f"content chars, cadence {self.cadence}, {expected_ms / 1000:.0f}s expected"
+ )
+
+ before_metrics = cdp_metrics(s.ctx.cdp)
+ t0 = self._press_send(page)
+
+ scene = scene_schedule.SCENES.get(self.tier, scene_schedule.QUICK)
+ runner = SceneRunner(
+ cell = cell,
+ page = page,
+ cdp = s.ctx.cdp,
+ dom = None,
+ recorder = rec,
+ open_window = s.window,
+ log = self.log,
+ base_args = {
+ "base_url": self.base_url,
+ "thread_id": seeded.thread_id,
+ "cell_id": cell.cell_id,
+ "cadence": self.cadence,
+ "image_path": str(self.image_path) if self.image_path else None,
+ # The follow-up turns `send_turn` streams mid-film, and
+ # the pacer it reloads to serve them.
+ "_pacer": self.pacer,
+ "_stream_queue": [
+ {"reasoning": u.reasoning, "content": u.content, "kind": u.kind}
+ for u in (plan.follow_up_units or [])
+ ],
+ # Shared and MUTABLE, so consecutive sends advance
+ # through the queue. See send_turn.
+ "_stream_cursor": {"i": 0},
+ "_input_instrument": next((i for i in s.instruments if i.name == "input"), None),
+ },
+ )
+ row["actions"] = runner.run(scene, t0)
+ row["scene"] = scene.name
+ row["scene_duration_ms"] = scene.duration_ms
+ row["slots_missed"] = sum(1 for a in row["actions"] if a.get("slot_missed"))
+ row["actions_not_run"] = sum(1 for a in row["actions"] if not a.get("ran"))
+ row["expect_failures"] = sum(1 for a in row["actions"] if a.get("expect_ok") is False)
+
+ with s.window("stream:drain", kind = "stream") as w:
+ drained = self._drain_stream(page, expected_ms)
+ w.note("drained", drained)
+ row["stream"] = drained
+ # 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
+ # the `pacer` key because that subtree is exempt from the payload's bare-zero rule: a
+ # pacer counter of 0 is a true reading, not a missing one.
+ streams = self.pacer.all_stats()
+ planned = self._planned_streams(cell, plan, row)
+ row["pacer"] = {
+ "last": self.pacer.last_stats(),
+ "streams": streams,
+ "check": check_planned_streams(streams, planned),
+ }
+ # A REPLY THAT NEVER FINISHED IS A FAILED CELL, not a completed one with a note.
+ #
+ # `_drain_stream` reports rather than raises, and the value it reports was recorded here
+ # and read by nothing: no gate, no report column, no `--assert-liveness` check and no
+ # exit code. So the one state this tool exists to catch -- the app still generating three
+ # times past its own cadence and 120 s beyond that, after the whole film has run -- came
+ # back as `completed: true`, `ok` in the summary and exit 0, with its actions and its
+ # frame windows scored and paired into the A/B ratio against an arm that DID finish.
+ # That is the crash-beats-limp rule inverted: a build that cannot finish reads as a build
+ # that had nothing to say.
+ #
+ # Raised AFTER the drain reading AND the pacer's own counters are on the row, so the two
+ # facts that say WHY it never finished -- how long was waited, and how much the pacer
+ # actually delivered -- ship in the same row as the failure. `CellRunner.run` catches
+ # this, records `failure`, dumps the diagnostics and keeps the cell as a first-class
+ # incomplete result; the rung then scores INCOMPLETE, which is exactly how this harness
+ # reports a build that died at 500K. The censuses below are not taken, because a census of
+ # a thread that is still growing describes nothing that was measured.
+ if not drained.get("finished"):
+ raise RuntimeError(
+ f"the reply never finished: {drained.get('reason') or 'the run was still going'} "
+ f"({drained.get('drain_ms')}ms waited, {drained.get('expected_ms')}ms expected)"
+ )
+ # A CELL THAT DID NOT STREAM WHAT IT PLANNED IS A FAILED CELL, for the same reason.
+ #
+ # The drain check above only asks whether the UI stopped running, and a later turn that
+ # finishes satisfies it on behalf of an earlier one that did not. So an opening reply that
+ # disconnected part way through left a complete-looking cell whose thread was thousands of
+ # characters short of its rung, averaged into the A/B ratio against arms that streamed in
+ # full. Raised here, after the check is on the row, so the reason and the per-turn evidence
+ # ship with the failure and the cell is excluded by name rather than quietly included.
+ check = row["pacer"]["check"]
+ if check["checked"] and not check["ok"]:
+ self.log(f" the cell did not stream what it planned: {check['reason']}")
+ raise RuntimeError(f"the cell did not stream what it planned: {check['reason']}")
+ # AND THE SAME RULE FOR THE TURN THAT STREAMED BUT NEVER LANDED.
+ #
+ # The stream check asks whether the bytes went out. `send_turn` asserts something the pacer
+ # cannot see: that the thread GREW. A send whose bytes were served in full but whose reply
+ # never joined the thread leaves every later action, the peak census and the equivalence
+ # mirror reading a thread one turn short, and the stream check alone would pass it.
+ #
+ # Scoped to `send_turn` DELIBERATELY, and this is the whole of the generalisation. An
+ # action whose own assertion fails already has its own timing voided by
+ # `scoring/from_payload._action_measure`, which returns `Measure.failed` for
+ # `expect_ok is False` and says so. What that does NOT cover is an action whose failure
+ # changed the workload the REST of the cell measured, and `send_turn` is the only one that
+ # can: it is the only action whose outcome decides how much content the thread carries for
+ # everything after it. A `select_text` that selected nothing or a `message_menu` that did
+ # not open leaves the workload intact, and failing the cell for those would throw away a
+ # whole cell's frame readings -- which really were taken, over the real thread -- for a
+ # gesture that missed.
+ missed_turns = [
+ a
+ for a in (row["actions"] or [])
+ if a.get("action") == "send_turn" and a.get("ran") and a.get("expect_ok") is False
+ ]
+ if missed_turns:
+ reason = "; ".join(
+ f"follow-up turn {(a.get('expect') or {}).get('turn_index')} was sent but "
+ f"{a.get('reason') or 'its own assertion failed'}"
+ for a in missed_turns
+ )
+ self.log(f" the cell did not stream what it planned: {reason}")
+ raise RuntimeError(f"the cell did not stream what it planned: {reason}")
+ row["census_after"] = dom_signature(page)
+ row["cdp"] = cdp_counters(before_metrics, cdp_metrics(s.ctx.cdp))
+
+ # THE PEAK, over every window's census, not the state at the end of the film.
+ #
+ # The film ENDS with thread_reopen and delete_message, so an end-of-cell census reports
+ # the thread the benchmark has just deleted. The first working run recorded 0 assistant
+ # messages and 0 characters against a reply the pacer's own log proved it had delivered in
+ # full: 150 chunks, 3,581 characters, at exactly the 73ms cadence. The occupancy that
+ # every per-action cost has to be read against is the peak, and it is now recovered from
+ # the per-window censuses rather than from a single reading taken at the worst moment.
+ censuses = [w.get("census") for w in row["actions"] if isinstance(w.get("census"), dict)]
+ censuses = [c for c in censuses if c.get("elements")]
+ peak = max(censuses, key = lambda c: c.get("elements", 0)) if censuses else {}
+ row["census_peak"] = peak
+ row["census_peak_attempted"] = bool(censuses)
+
+ census = peak or row["census_after"]
+ spans = census.get("highlight_spans") or 0
+ chars = census.get("assistant_chars")
+ if chars is None:
+ chars = page.evaluate("() => window.__sb.dom.assistantChars()")
+ row["assistant_chars_in_dom"] = chars
+ # The span density the fixture ACHIEVED, measured in the DOM rather than assumed. The
+ # field capture ran 5.6 characters per span; a corpus that lands far from that is not
+ # standing in for the same highlighter load per character, and the report should say so
+ # rather than quietly compare two different workloads.
+ row["chars_per_span"] = round(chars / spans, 2) if spans else None
+ row["chars_per_span_target"] = 5.6
+ self.log(
+ f" after: {census['elements']:,} elements, {spans:,} spans, "
+ f"{chars:,} assistant chars -> {row['chars_per_span']} chars/span"
+ )
+
+ row["fidelity"] = "streamed_and_seeded" if plan.seeded_units else "streamed_only"
+
+ # ── the seeded-vs-streamed equivalence check ────────────────
+ 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)
+ 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
+ # there, and it is the reason the higher rungs carry a fidelity label at all.
+ self.log(
+ " SEEDED IS NOT EQUIVALENT TO STREAMED at the 10K rung. Rungs above it "
+ "are labelled fidelity: seeded_only."
+ )
+ for key, field in (eq.get("fields") or {}).items():
+ if field.get("within_tolerance") is False:
+ self.log(
+ f" {key}: streamed {field['streamed']} vs seeded "
+ f"{field['seeded']} ({field['drift']:.1%} drift)"
+ )
+ self.equivalence_failed = True
+ else:
+ self.log(
+ " seeded and streamed agree on CONTENT at the 10K rung within "
+ f"{eq['tolerance']:.0%}"
+ )
+ # Passing the content gate is not the same as the two threads being identical,
+ # and the difference is large enough that leaving it unsaid would mislead: a
+ # seeded rung carries the same rendered content and materially less mounted DOM.
+ fields = eq.get("fields") or {}
+ for key in ("reasoning_spans", "highlight_spans", "assistant_chars"):
+ field = fields.get(key) or {}
+ if field.get("drift"):
+ self.log(
+ f" but {key}: streamed {field['streamed']} vs seeded "
+ f"{field['seeded']} ({field['drift']:.1%}) -- a collapsed "
+ "reasoning pane mounts its children only when the text was "
+ "streamed into it"
+ )
+ if self.equivalence_failed and plan.seeded_units:
+ row["fidelity"] = "seeded_only"
+
+ @staticmethod
+ def _planned_streams(cell: Cell, plan: RungPlan, row: dict) -> list[dict]:
+ """The turns this cell MEANT to stream, each with its tag and its character count.
+
+ The opening reply, plus one entry per `send_turn` that was ATTEMPTED -- taken from the
+ recorded action rows and from the tag the action itself reports, so the naming rule lives
+ in one place rather than two.
+
+ THE TWO KINDS OF "DID NOT RUN" ARE NOT THE SAME, and treating them alike was a hole in the
+ first version of this check. `ran = False` means the turn was never attempted: an exhausted
+ queue at the small rungs, a slot missed on a slow machine. Nothing was loaded into the
+ pacer, the cell simply has fewer turns, and demanding one would fail every small rung.
+ `ran = True, expect_ok = False` is the opposite: the turn WAS attempted, `send_turn` loaded
+ the pacer with it and pressed Enter, and no reply started. That is a planned turn that did
+ not stream, and skipping it let a cell whose follow-up never arrived pass the check with
+ `planned_turns: 1`, complete, and score 91.6 against a thread one turn short of its rung.
+ """
+ planned: list[dict] = []
+ unit = plan.streamed_unit
+ if unit is not None:
+ planned.append(
+ {
+ "tag": cell.cell_id,
+ "turn": "opening",
+ "chars": len(unit.reasoning) + len(unit.content),
+ }
+ )
+ for action in row.get("actions") or []:
+ if action.get("action") != "send_turn":
+ continue
+ if not action.get("ran"):
+ continue
+ expect = action.get("expect") or {}
+ tag = expect.get("pacer_tag")
+ if not tag:
+ continue
+ planned.append(
+ {
+ "tag": tag,
+ "turn": f"follow_up{expect.get('turn_index')}",
+ "chars": int(expect.get("streamed_chars") or 0),
+ }
+ )
+ return planned
+
+ @staticmethod
+ def _streamed_follow_ups(plan: RungPlan, row: dict) -> list:
+ """The follow-up units that actually reached the thread during the film.
+
+ EVERY TURN THAT STREAMED, not just the opening one. From 10K upwards the plan carries two
+ follow-ups and the scene streams both through `send_turn` before the peak census is taken,
+ so a mirror seeded from the prefix plus the opening unit is two assistant turns short of
+ the thread it is being compared against. `assistant_messages` is a GATED key, and two
+ missing turns out of six is 33% drift against a 2% tolerance: the check then failed on
+ every healthy cell and labelled every larger rung `seeded_only` for a difference the
+ mirror had introduced itself.
+
+ Counted from the recorded action rows rather than from the plan, because a `send_turn`
+ that did not run (an exhausted queue at the small rungs, a slot missed on a slow machine)
+ put nothing in the thread and must not be seeded into the mirror either.
+ """
+ streamed = 0
+ for action in row.get("actions") or []:
+ if action.get("action") != "send_turn":
+ continue
+ if action.get("ran") and action.get("expect_ok") is not False:
+ streamed += 1
+ return list(plan.follow_up_units or [])[:streamed]
+
+ def _check_equivalence(self, plan: RungPlan, row: dict) -> dict:
+ """Build the SAME content as a fully seeded thread and compare what the app made of it.
+
+ The streamed reply has just been measured. This seeds a second thread containing every
+ unit including that one -- so the two threads carry identical text -- loads it, and
+ compares the DOM the app built. Two paths, one corpus, one comparison.
+ """
+ s = self.session
+ page = s.ctx.page
+ streamed = row.get("census_peak") or row.get("census_after") or {}
+ follow_ups = self._streamed_follow_ups(plan, row)
+ try:
+ all_units = list(plan.seeded_units) + [plan.streamed_unit] + follow_ups
+ mirror = RungPlan(
+ rung = plan.rung,
+ target_tokens = plan.target_tokens,
+ target_chars = plan.target_chars,
+ seeded_units = all_units,
+ streamed_unit = None,
+ )
+ seeded_thread = self.seeder.seed(mirror)
+ page.goto(
+ f"{self.base_url}/chat?thread={seeded_thread.thread_id}",
+ wait_until = "domcontentloaded",
+ timeout = 120_000,
+ )
+ self._wait_for_thread(page, seeded_thread.messages)
+ # 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)
+ except Exception as exc: # noqa: BLE001
+ return {
+ "equivalent": None,
+ "checked_attempted": False,
+ "reason": f"the mirror thread could not be built: " f"{type(exc).__name__}: {exc}",
+ }
+ out = compare_signatures(streamed, seeded_sig)
+ out["streamed_census"] = streamed
+ out["seeded_census"] = seeded_sig
+ # 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 _press_send(self, page) -> float:
+ """Type a prompt and press send. Returns the driver monotonic time the film starts."""
+ selector = 'textarea[aria-label="Message input"]'
+ page.wait_for_selector(selector, timeout = 60_000)
+ page.click(selector)
+ page.fill(selector, "continue")
+ page.wait_for_timeout(150)
+ send = page.query_selector('button[aria-label="Send message"]')
+ if send is None:
+ raise RuntimeError("the send button is not on the page, so no reply can be started")
+ t0 = time.monotonic()
+ send.click()
+ # The composer must be EMPTY for the rest of the film, or the Stop control is replaced by
+ # a Queue control and the stop action presses the wrong button. Sending clears it, but the
+ # keystroke action refills it, which is why the stop action clears it again itself.
+ return t0
+
+ def _drain_stream(self, page, expected_ms: float) -> dict:
+ """Wait for the run to end, or say plainly that it did not."""
+ # Generous: the whole point of deficit scheduling is that the stream's own duration is
+ # machine-independent, so anything much past it is the RENDERER failing to keep up, which
+ # is a finding rather than a timeout to paper over.
+ deadline = time.monotonic() + (expected_ms / 1000) * 3 + 120
+ started = time.monotonic()
+ while time.monotonic() < deadline:
+ if not page.evaluate("() => window.__sb.dom.isRunning()"):
+ return {
+ "finished": True,
+ "drain_ms": round((time.monotonic() - started) * 1000, 1),
+ "expected_ms": expected_ms,
+ }
+ page.wait_for_timeout(250)
+ return {
+ "finished": False,
+ "drain_ms": round((time.monotonic() - started) * 1000, 1),
+ "expected_ms": expected_ms,
+ "reason": "the run was still going three times past its own cadence",
+ }
+
+
+def make_context(
+ browser_bundle,
+ base_url: str,
+ tier: str,
+ instrument_level: int,
+ paths: Paths,
+ log: Callable[[str], None],
+ browser_procs: Optional[list] = None,
+) -> tuple[BenchContext, Session]:
+ session_id = new_session_id()
+ recorder = Recorder(paths.payload_jsonl, session_id)
+ ctx = BenchContext(
+ browser = browser_bundle.browser,
+ context = browser_bundle.context,
+ page = browser_bundle.page,
+ cdp = browser_bundle.cdp,
+ base_url = base_url,
+ session_id = session_id,
+ tier = tier,
+ instrument_level = instrument_level,
+ paths = paths,
+ recorder = recorder,
+ log = log,
+ browser_procs = browser_procs or [],
+ )
+ instruments = build_instruments(instrument_level)
+ errors = import_errors()
+ for name, err in errors.items():
+ recorder.gate(f"instrument_unavailable:{name}", False, {"error": err})
+ log(f" instrument {name} unavailable: {err}")
+ for inst in instruments:
+ try:
+ inst.attach(ctx)
+ except Exception as exc: # noqa: BLE001
+ log(f" instrument {inst.name} failed to attach: {exc}")
+ log(
+ f" instruments at level {instrument_level}: "
+ f"{', '.join(i.name for i in instruments) or 'none'}"
+ )
+ return ctx, Session(ctx = ctx, instruments = instruments)
+
+
+#: The sources that may SIZE a rung. `measure_chars_per_token` also has a last-resort
+#: whitespace-and-punctuation estimate, which it labels itself as "off by tens of percent on dense
+#: code" -- and this corpus is mostly dense code, where that estimate reads 6.7 against tiktoken's
+#: 3.3. Sizing the ladder from it would not make the axis honest, it would move the error and, past
+#: `MANIFEST_CHARS_PER_TOKEN`, make `plan_rung` refuse the whole run on any machine with no
+#: tokeniser. A real tokeniser sizes the rungs; the estimate is still measured and still reported.
+LADDER_RATIO_SOURCES = ("tiktoken/cl100k", "studio /api/inference/chat/count_tokens")
+
+
+def _corpus_sample(corpus: Corpus, chars: int = 200_000) -> str:
+ """A prefix of the frozen corpus, in the order a thread receives it."""
+ out: list[str] = []
+ size = 0
+ for entry in corpus.manifest["units"]:
+ unit = corpus.unit(entry["index"])
+ out.append(unit.reasoning + unit.content)
+ size += unit.chars
+ if size >= chars:
+ break
+ return "".join(out)[:chars]
+
+
+def ladder_chars_per_token(
+ corpus: Corpus,
+ base_url: str = "",
+ auth: Optional[StudioAuth] = None,
+ model_id: str = "",
+ log: Callable[[str], None] = lambda _m: None,
+) -> dict:
+ """The ratio THE RUNGS ARE SIZED BY, measured on the corpus BEFORE anything is planned.
+
+ A rung is named in tokens and the corpus is built in characters, so the ratio is what makes the
+ two the same claim. `PROVISIONAL_CHARS_PER_TOKEN` is what a rung is planned with when nothing
+ has been tokenised yet, and it was previously what EVERY production rung was planned with: the
+ per-cell measurement runs after the thread is already seeded and its result is recorded and
+ nothing else, so a cell labelled 1M tokens carried 4,000,000 characters of a corpus that
+ tiktoken reads at 3.34 -- about 1.2M tokens, a fifth over its own label, on the axis the onset
+ headline is quoted against.
+
+ Measured once for the whole ladder rather than per rung: the per-cell number is taken from that
+ rung's streamed unit alone, which is 6,000 characters of either reasoning or code and swings
+ between 3.2 and 4.9 by which kind the rung happens to land on. The axis needs the corpus's
+ ratio, not one turn's.
+ """
+ got = measure_chars_per_token(_corpus_sample(corpus), base_url, auth, model_id)
+ measured = got.get("chars_per_token")
+ source = got.get("source")
+ if measured and measured > 0 and source in LADDER_RATIO_SOURCES:
+ used, reason = float(measured), None
+ else:
+ used = PROVISIONAL_CHARS_PER_TOKEN
+ reason = (
+ f"no tokeniser answered (source {source!r}), so the rungs keep the provisional "
+ f"{PROVISIONAL_CHARS_PER_TOKEN} rather than being sized from an estimate"
+ )
+ log(
+ f" ladder sized at {used} chars per token "
+ f"(measured {measured} via {source}){'; ' + reason if reason else ''}"
+ )
+ return {
+ "chars_per_token": used,
+ "measured": measured,
+ "source": source,
+ "provisional": reason is not None,
+ "reason": reason,
+ "detail": got,
+ }
+
+
+def build_cells(
+ rungs: list[str],
+ corpus: Corpus,
+ tier: str,
+ session_id: str,
+ instrument_level: int,
+ reps: int = 1,
+ chars_per_token: Optional[float] = None,
+ base_url: str = "",
+ auth: Optional[StudioAuth] = None,
+ model_id: str = "",
+ log: Callable[[str], None] = lambda _m: None,
+) -> list[tuple[Cell, RungPlan]]:
+ """The ladder's cells, sized by the MEASURED ratio unless a caller names one.
+
+ `chars_per_token = None` means "measure the corpus first", which is what the production caller
+ does. The ratio that sized the ladder travels on every cell's `meta` so a reader of the payload
+ can see which one it was and whether a tokeniser answered.
+ """
+ if chars_per_token is None:
+ ratio = ladder_chars_per_token(corpus, base_url, auth, model_id, log)
+ else:
+ ratio = {
+ "chars_per_token": float(chars_per_token),
+ "measured": None,
+ "source": "caller",
+ "provisional": False,
+ "reason": None,
+ }
+ out: list[tuple[Cell, RungPlan]] = []
+ for rung in rungs:
+ plan = plan_rung(corpus, rung, ratio["chars_per_token"])
+ for rep in range(reps):
+ cell = Cell(
+ cell_id = make_cell_id(rung, "A0", rep),
+ rung = rung,
+ rung_tokens = plan.target_tokens,
+ arm = "A0",
+ rep = rep,
+ tier = tier,
+ transport = "provider",
+ instrument_level = instrument_level,
+ seed = corpus.seed,
+ corpus_hash = corpus.corpus_hash,
+ session_id = session_id,
+ meta = {"ladder_chars_per_token": ratio},
+ )
+ out.append((cell, plan))
+ return out
diff --git a/tests/studio/studiobench/runtime/types.py b/tests/studio/studiobench/runtime/types.py
new file mode 100644
index 00000000000..eb5ef140da4
--- /dev/null
+++ b/tests/studio/studiobench/runtime/types.py
@@ -0,0 +1,399 @@
+# 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 studiobench layer contract. See INTERFACES.md, which this file implements.
+
+Stdlib only, and it imports nothing else from studiobench, so Layer 2 and Layer 3 can import it
+without dragging in Playwright, psutil or the fixture generator. `python -c "import
+tests.studio.studiobench.runtime.types"` works on a machine with nothing installed, which is what
+makes `--doctor` able to report what is missing rather than crash on the way to finding out.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+import uuid
+from dataclasses import dataclass, field, replace
+from pathlib import Path
+from typing import Any, Callable, Iterator, Optional
+
+SCHEMA = "studiobench/1"
+
+ROW_TYPES = frozenset(
+ {
+ "run_meta",
+ "gate",
+ "cell",
+ "window",
+ "action",
+ "sample",
+ "failure",
+ # The A/B run order, recorded before the first cell. Written even when the order is
+ # UNBALANCED, because whether linear drift cancelled is a property of the run that a reader
+ # of the table has no other way to recover.
+ "ab_plan",
+ # One UI surface swept by the optional `--surfaces` phase: a route, a settings tab, a menu.
+ # A row type of its own rather than an `action` row with a different name, because a surface
+ # has no slot, no budget and no timing to miss -- and reusing `action` would put forty rows
+ # with a null `timings` into the column the report scores actions from.
+ "surface",
+ }
+)
+
+# Required keys per row type. Enforced in Recorder.emit, because a row that silently lost its
+# `ran` flag reads downstream as a fast action rather than as a missing one.
+ROW_REQUIRED: dict[str, tuple[str, ...]] = {
+ "run_meta": (
+ "tier",
+ "tool_version",
+ "corpus_hash",
+ "studio_ref",
+ "bundle",
+ "platform",
+ "started_at",
+ ),
+ "gate": ("name", "passed", "detail"),
+ "cell": ("cell", "completed", "fidelity"),
+ "window": ("name", "kind", "t_open_ms", "duration_ms"),
+ "action": ("action", "ran", "expect_ok", "expect", "timings", "slot_missed"),
+ "sample": ("t_ms",),
+ "failure": ("kind", "detail"),
+ # `reason` is REQUIRED, not optional. A surface row that lost its reason reads as a surface
+ # that was reached, which is the one thing a coverage sweep may never claim by default. It is
+ # null only on the success path, where `reached` is true.
+ "surface": ("surface", "reached", "reason", "parity"),
+}
+
+
+# ── the cell ────────────────────────────────────────────────────────
+
+
+@dataclass(frozen = True)
+class Cell:
+ """One measured configuration: one rung, one arm, one repetition."""
+
+ cell_id: str
+ rung: str
+ rung_tokens: int
+ arm: str = "A0"
+ rep: int = 0
+ tier: str = "quick"
+ transport: str = "provider"
+ instrument_level: int = 0
+ seed: int = 0
+ corpus_hash: str = ""
+ session_id: str = ""
+ meta: dict = field(default_factory = dict)
+
+ def derive(self, **changes: Any) -> "Cell":
+ """A sibling cell with a regenerated `cell_id`. What Layer 3 builds its arms with."""
+ out = replace(self, **changes)
+ return replace(out, cell_id = make_cell_id(out.rung, out.arm, out.rep))
+
+ def as_dict(self) -> dict:
+ return {
+ "cell_id": self.cell_id,
+ "rung": self.rung,
+ "rung_tokens": self.rung_tokens,
+ "arm": self.arm,
+ "rep": self.rep,
+ "tier": self.tier,
+ "transport": self.transport,
+ "instrument_level": self.instrument_level,
+ "seed": self.seed,
+ "corpus_hash": self.corpus_hash,
+ "session_id": self.session_id,
+ "meta": self.meta,
+ }
+
+
+def make_cell_id(rung: str, arm: str, rep: int) -> str:
+ return f"r{rung}.{arm}.rep{rep}"
+
+
+# ── the window ──────────────────────────────────────────────────────
+
+WINDOW_KINDS = frozenset({"action", "stream", "idle", "settle", "teardown"})
+
+
+@dataclass
+class Window:
+ """A bracketed interval on the driver's monotonic clock. Windows never nest."""
+
+ name: str
+ kind: str
+ cell: Cell
+ t_open_ms: float
+ t_close_ms: Optional[float] = None
+ notes: dict = field(default_factory = dict)
+ instruments: dict = field(default_factory = dict)
+
+ @property
+ def duration_ms(self) -> Optional[float]:
+ if self.t_close_ms is None:
+ return None
+ return round(self.t_close_ms - self.t_open_ms, 2)
+
+ def note(self, key: str, value: Any) -> None:
+ self.notes[key] = value
+
+ def row(self) -> dict:
+ return {
+ "row_type": "window",
+ "cell_id": self.cell.cell_id,
+ "name": self.name,
+ "kind": self.kind,
+ "t_open_ms": round(self.t_open_ms, 2),
+ "duration_ms": self.duration_ms,
+ "instruments": self.instruments,
+ "notes": self.notes,
+ }
+
+
+# ── actions ─────────────────────────────────────────────────────────
+
+
+@dataclass
+class ActionResult:
+ """The outcome of one action.
+
+ `ran = False` is the ONLY way to report an action that did not happen. It is never a fast
+ timing: `timings` is forced empty in that case by __post_init__, so a caller that forgets
+ cannot leak a paint-floor number into a table as if it were a measurement.
+ """
+
+ ran: bool
+ expect_ok: Optional[bool] = None
+ expect: dict = field(default_factory = dict)
+ timings: dict = field(default_factory = dict)
+ reason: Optional[str] = None
+ slot_missed: bool = False
+
+ def __post_init__(self) -> None:
+ if not self.ran:
+ self.timings = {}
+ self.expect_ok = None
+ if not self.reason:
+ self.reason = "action did not run and gave no reason"
+ elif self.expect_ok is False and not self.reason:
+ self.reason = "expectation failed and gave no reason"
+
+ def row(self, action: str, window: str, cell_id: str) -> dict:
+ return {
+ "row_type": "action",
+ "cell_id": cell_id,
+ "action": action,
+ "window": window,
+ "ran": self.ran,
+ "expect_ok": self.expect_ok,
+ "expect": self.expect,
+ "timings": self.timings,
+ "reason": self.reason,
+ "slot_missed": self.slot_missed,
+ }
+
+
+def not_run(
+ reason: str,
+ *,
+ slot_missed: bool = False,
+ expect: Optional[dict] = None,
+) -> ActionResult:
+ return ActionResult(ran = False, reason = reason, slot_missed = slot_missed, expect = expect or {})
+
+
+@dataclass(frozen = True)
+class Slot:
+ """A fixed (start, budget) on the session wall clock. The scene is a film, not a task list."""
+
+ action: str
+ t_start_ms: int
+ budget_ms: int
+ args: dict = field(default_factory = dict)
+ required: bool = True
+
+
+@dataclass
+class ActionContext:
+ page: Any
+ cdp: Any
+ cell: Cell
+ window: Window
+ args: dict
+ budget_ms: int
+ dom: Any
+ log: Callable[[str], None]
+
+
+# ── instruments ─────────────────────────────────────────────────────
+
+
+class Instrument:
+ """Base class. Subclassing is optional; duck typing on `name`/`level` is enough."""
+
+ name: str = "unnamed"
+ level: int = 0
+
+ def attach(self, ctx: "BenchContext") -> None: ...
+ def start_cell(self, cell: Cell) -> None: ...
+ def open(self, window: Window) -> None: ...
+ def close(self, window: Window) -> Optional[dict]:
+ return None
+
+ def end_cell(self, cell: Cell) -> Optional[dict]:
+ return None
+
+ def detach(self) -> None: ...
+
+
+# ── paths and context ───────────────────────────────────────────────
+
+
+@dataclass
+class Paths:
+ out: Path
+ payload_jsonl: Path
+ traces: Path
+ symbols: Path
+ corpus: Path
+ logs: Path
+
+ @classmethod
+ def under(cls, out: Path) -> "Paths":
+ out = Path(out).resolve()
+ p = cls(
+ out = out,
+ payload_jsonl = out / "payload.jsonl",
+ traces = out / "traces",
+ symbols = out / "symbols",
+ corpus = out / "corpus",
+ logs = out / "logs",
+ )
+ for d in (p.out, p.traces, p.symbols, p.corpus, p.logs):
+ d.mkdir(parents = True, exist_ok = True)
+ return p
+
+
+@dataclass
+class BenchContext:
+ browser: Any = None
+ context: Any = None
+ page: Any = None
+ cdp: Any = None
+ base_url: str = ""
+ session_id: str = ""
+ tier: str = "quick"
+ instrument_level: int = 0
+ paths: Optional[Paths] = None
+ recorder: Optional["Recorder"] = None
+ log: Callable[[str], None] = print
+ browser_procs: list = field(default_factory = list)
+
+
+# ── the recorder ────────────────────────────────────────────────────
+
+
+class Recorder:
+ """Append-only JSONL. Every line is flushed and fsynced, so a renderer crash at rung 4 still
+ ships rungs 1 to 3 plus the crash record."""
+
+ def __init__(
+ self,
+ path: Path,
+ session_id: str,
+ t0: Optional[float] = None,
+ ) -> None:
+ self.path = Path(path)
+ self.path.parent.mkdir(parents = True, exist_ok = True)
+ self.session_id = session_id
+ self.t0 = t0 if t0 is not None else time.monotonic()
+ self._fh = self.path.open("a", encoding = "utf-8")
+ self._count = 0
+
+ def now_ms(self) -> float:
+ return round((time.monotonic() - self.t0) * 1000, 2)
+
+ def emit(self, row: dict) -> None:
+ row_type = row.get("row_type")
+ if row_type not in ROW_TYPES:
+ raise ValueError(f"row_type must be one of {sorted(ROW_TYPES)}, got {row_type!r}")
+ missing = [k for k in ROW_REQUIRED.get(row_type, ()) if k not in row]
+ if missing:
+ raise ValueError(f"{row_type} row is missing required keys: {missing}")
+ row.setdefault("schema", SCHEMA)
+ row.setdefault("ts_ms", self.now_ms())
+ row.setdefault("session_id", self.session_id)
+ # default = str so a stray Path or dataclass degrades to a string instead of losing the
+ # whole row, and the run keeps going.
+ self._fh.write(json.dumps(row, default = str) + "\n")
+ self._fh.flush()
+ try:
+ os.fsync(self._fh.fileno())
+ except OSError:
+ pass
+ self._count += 1
+
+ def gate(
+ self,
+ name: str,
+ passed: bool,
+ detail: Optional[dict] = None,
+ ) -> None:
+ self.emit(
+ {"row_type": "gate", "name": name, "passed": bool(passed), "detail": detail or {}}
+ )
+
+ def failure(
+ self,
+ cell_id: Optional[str],
+ kind: str,
+ detail: Optional[dict] = None,
+ ) -> None:
+ self.emit({"row_type": "failure", "cell_id": cell_id, "kind": kind, "detail": detail or {}})
+
+ def rows(self, row_type: Optional[str] = None) -> Iterator[dict]:
+ if not self.path.exists():
+ return
+ with self.path.open(encoding = "utf-8") as fh:
+ for line in fh:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ row = json.loads(line)
+ except ValueError:
+ continue
+ if row_type is None or row.get("row_type") == row_type:
+ yield row
+
+ def close(self) -> None:
+ try:
+ self._fh.close()
+ except OSError:
+ pass
+
+
+def new_session_id() -> str:
+ return uuid.uuid4().hex[:12]
+
+
+__all__ = [
+ "SCHEMA",
+ "ROW_TYPES",
+ "ROW_REQUIRED",
+ "Cell",
+ "make_cell_id",
+ "Window",
+ "WINDOW_KINDS",
+ "ActionResult",
+ "not_run",
+ "Slot",
+ "ActionContext",
+ "Instrument",
+ "Paths",
+ "BenchContext",
+ "Recorder",
+ "new_session_id",
+]
diff --git a/tests/studio/studiobench/scene/__init__.py b/tests/studio/studiobench/scene/__init__.py
new file mode 100644
index 00000000000..a37c4b243d6
--- /dev/null
+++ b/tests/studio/studiobench/scene/__init__.py
@@ -0,0 +1,60 @@
+# 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 action registry and the slot-scheduled scene. See INTERFACES.md sections 4 and 5."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Callable, Optional
+
+from ..runtime.types import ActionContext, ActionResult, Slot
+
+_ACTIONS: "dict[str, _Action]" = {}
+
+
+@dataclass(frozen = True)
+class _Action:
+ name: str
+ fn: Callable[[ActionContext], ActionResult]
+ default_budget_ms: int
+
+
+def register_action(name: str, default_budget_ms: int = 3000) -> Callable:
+ def deco(fn: Callable[[ActionContext], ActionResult]) -> Callable:
+ if name in _ACTIONS:
+ raise ValueError(f"action {name!r} is already registered")
+ _ACTIONS[name] = _Action(name = name, fn = fn, default_budget_ms = default_budget_ms)
+ return fn
+
+ return deco
+
+
+def _ensure_loaded() -> None:
+ from . import actions # noqa: F401 (importing registers every built-in action)
+
+
+def action_names() -> list[str]:
+ _ensure_loaded()
+ return sorted(_ACTIONS)
+
+
+def get_action(name: str) -> Optional[_Action]:
+ _ensure_loaded()
+ return _ACTIONS.get(name)
+
+
+def default_budget_ms(name: str) -> int:
+ entry = get_action(name)
+ return entry.default_budget_ms if entry else 3000
+
+
+__all__ = [
+ "register_action",
+ "action_names",
+ "get_action",
+ "default_budget_ms",
+ "Slot",
+ "ActionContext",
+ "ActionResult",
+]
diff --git a/tests/studio/studiobench/scene/actions.py b/tests/studio/studiobench/scene/actions.py
new file mode 100644
index 00000000000..79f2e4d4389
--- /dev/null
+++ b/tests/studio/studiobench/scene/actions.py
@@ -0,0 +1,1441 @@
+# 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 fifteen actions, each with an `expect` that proves it actually happened.
+
+THE RULE THIS FILE EXISTS TO ENFORCE: an action that did not happen is `ran = False`. It is NEVER
+a fast timing. That is not a style preference, it is the failure mode that wasted a day of
+measurement. A menu whose trigger opens on `pointerdown` does not open when you call `.click()`,
+and the column then reads a tidy small number that looks like a fast menu. A jump scroll from the
+bottom is read by Studio's intent-aware autoscroll as programmatic and snapped straight back, so
+the viewport lands where it started and the timing is real, precise and about nothing. Every
+action below therefore asserts a POSITIVE observable consequence -- the scroll travelled at least
+90% of what was commanded, the menu opened AND closed with a non-zero item count, the delete
+dropped the `[data-role]` count -- and reports `ran = False` with a reason when it cannot.
+
+The JS is ported from `tests/studio/playwright_heavy_thread.py` (KEYSTROKE_JS, SCROLL_JS, JUMP_JS,
+MENU_JS, DELETE_JS, REOPEN_JS, PAINT_FLOOR_JS) with `window.__heavyThread` replaced by
+`window.__sb.dom`, which is the same API backed by the shipping app's own selectors.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from typing import Any
+
+from ..runtime.types import ActionContext, ActionResult, not_run
+from . import register_action
+
+SETTLE_TIMEOUT_MS = 8000
+
+#: How long an action that needs the message ACTION BAR waits for it before reporting NOT RUN.
+#:
+#: The bar is mounted `hideWhenRunning`, so Copy, Delete and More do not exist while the thread is
+#: generating. Every film opens these slots after a `send_turn`, spaced by the NOMINAL drain of the
+#: follow-up turn -- FOLLOW_UP_CHARS over the field cadence, 4.59 s. The nominal drain is a floor
+#: rather than an estimate: it assumes the pacer is the binding constraint, and at the 100K rung it
+#: is not. Measured over six 100K cells here, the follow-up streamed for 4.4 to 4.7 s AFTER the
+#: send window closed, so the reply settles within a few hundred milliseconds of the slot on a
+#: quiet machine and a little after it on a loaded one. The CI payload of the run that failed the
+#: liveness gate shows exactly that: one more SSE chunk arrived INSIDE the `message_menu` window
+#: and the reply stopped growing inside it too.
+#:
+#: 1,500 ms, and deliberately NOT `ctx.budget_ms`. The remaining budget at entry is whatever the
+#: previous window's teardown left over -- measured at 51 ms on one of those cells -- so a wait
+#: capped by it is a wait that is not taken in exactly the conditions that need it. It is bounded
+#: so a control that is genuinely absent still reports NOT RUN rather than eating the film: an
+#: action that overruns pushes nothing (every slot has an absolute start) and the overrun is
+#: recorded as `over_budget_ms` on the row.
+ACTION_BAR_WAIT_MS = 1500
+
+
+def _ev(
+ ctx: ActionContext,
+ script: str,
+ arg: Any = None,
+) -> Any:
+ """Evaluate, and turn a thrown page error into `ran = False` rather than a lost cell."""
+ try:
+ return ctx.page.evaluate(script, arg) if arg is not None else ctx.page.evaluate(script)
+ except Exception as exc: # noqa: BLE001
+ ctx.log(f" action js failed: {type(exc).__name__}: {exc}")
+ return {"__error": f"{type(exc).__name__}: {exc}"}
+
+
+def _failed(raw: Any) -> str | None:
+ if raw is None:
+ return "the page returned nothing"
+ if isinstance(raw, dict) and raw.get("__error"):
+ return raw["__error"]
+ return None
+
+
+# ── the paint floor ─────────────────────────────────────────────────
+#
+# Two rAFs resolve no sooner than two vsync intervals, so ANY timing clocked across a double rAF
+# has a ~33ms floor under it on a 60Hz display. An action that never happened still reports that
+# floor, which reads as a plausible measurement rather than as a failure. Measured per cell and
+# recorded so a reader can subtract it.
+
+PAINT_FLOOR_JS = """
+async (samples) => {
+ const values = [];
+ for (let i = 0; i < samples; i += 1) {
+ await window.__sbNextPaint();
+ const started = performance.now();
+ await window.__sbNextPaint();
+ values.push(performance.now() - started);
+ }
+ values.sort((a, b) => a - b);
+ return values[Math.floor(values.length / 2)];
+}
+"""
+
+
+def paint_floor_ms(page, samples: int = 9) -> float | None:
+ try:
+ return round(page.evaluate(PAINT_FLOOR_JS, samples), 2)
+ except Exception: # noqa: BLE001
+ return None
+
+
+# ── 1. keystroke to paint ───────────────────────────────────────────
+
+
+#: How long the keystroke drain will wait for the last paint before giving up on it. Not a "wait
+#: a bit longer" constant: the wait ENDS when nothing is in flight, and this is only the bound that
+#: stops a wedged renderer from eating the slot. Reaching it means a sample was lost, which the
+#: coverage check then fails on rather than quietly publishing the rest.
+KEYSTROKE_SETTLE_TIMEOUT_MS = 3000
+KEYSTROKE_SETTLE_POLL_MS = 25
+
+
+def _settle_keystrokes(ctx: ActionContext, inst: Any) -> None:
+ """Wait until no keystroke's paint is still in flight, bounded.
+
+ The fixed 200 ms wait this replaces dropped whichever sample had not painted when it expired,
+ which is systematically the slowest one. A bigger constant has the same defect on a slower
+ machine or a heavier rung, so the wait is on the WORK rather than on the clock.
+ """
+ deadline = time.monotonic() + KEYSTROKE_SETTLE_TIMEOUT_MS / 1000
+ settled = getattr(inst, "settled", None)
+ if settled is None:
+ ctx.page.wait_for_timeout(200)
+ return
+ while time.monotonic() < deadline:
+ state = settled()
+ # The page could not answer: polling on it would spin to the bound and tell us nothing.
+ if not isinstance(state, dict):
+ break
+ if not state.get("pending"):
+ return
+ ctx.page.wait_for_timeout(KEYSTROKE_SETTLE_POLL_MS)
+
+
+@register_action(name = "keystroke", default_budget_ms = 6000)
+def keystroke(ctx: ActionContext) -> ActionResult:
+ """Type with REAL key events and measure keystroke-to-paint from the page side.
+
+ `page.keyboard.type` goes in through CDP as a real input event: it is hit-tested, routed and
+ queued like a user's keypress, and it is the only kind that carries `latencyInfo` in a trace.
+ The salvaged KEYSTROKE_JS instead called the native value setter and dispatched a synthetic
+ `input` event, which reaches React but enters the pipeline after the queue -- so it cannot
+ show input queueing delay at all, and reads cleanest exactly when a user is waiting longest.
+ """
+ count = int(ctx.args.get("count", 12))
+ selector = 'textarea[aria-label="Message input"]'
+ if ctx.page.query_selector(selector) is None:
+ return not_run("no composer on the page")
+
+ inst = ctx.args.get("_input_instrument")
+ armed = (
+ inst.arm(selector)
+ if inst is not None
+ else {"armed": False, "reason": "input instrument not loaded"}
+ )
+ if not armed.get("armed"):
+ return not_run(f"could not arm the input instrument: {armed.get('reason')}")
+
+ ctx.page.click(selector)
+ started = time.monotonic()
+ # A real delay between characters. Typing with delay=0 sends the whole burst in one CDP
+ # message, which the renderer coalesces into a single input event and a single paint, so the
+ # measurement collapses to one sample no matter how many characters were sent.
+ ctx.page.keyboard.type("a" * count, delay = 60)
+ _settle_keystrokes(ctx, inst)
+ got = inst.collect(count)
+ elapsed_ms = (time.monotonic() - started) * 1000
+
+ grew = got.get("grew_by")
+ if not got.get("samples"):
+ return not_run(f"no keystroke reached the composer ({got.get('reason', 'no samples')})")
+ seen = got.get("inputs_seen")
+ accounted = (got.get("samples") or 0) + (got.get("coalesced") or 0)
+ expect = {
+ "commanded_chars": count,
+ "measured_keystrokes": got.get("samples"),
+ "coalesced": got.get("coalesced"),
+ "inputs_seen": seen,
+ "pending_at_collect": got.get("pending_at_collect"),
+ "composer_grew_by": grew,
+ "composer_text_length": got.get("text_length"),
+ }
+ # EVERY KEYSTROKE ACCOUNTED FOR, not merely a composer that grew.
+ #
+ # `grew_by` alone was the whole check, and it is satisfied by a textarea whose value is right
+ # while the timings describe a subset of the typing. Two ways that happened, and the first
+ # INVERTS the metric: a keystroke whose paint had not resolved when the drain ran was simply
+ # absent, and the keystroke that has not painted yet is the slowest one -- measured here, a
+ # 500 ms keystroke vanished from a reading whose max was 20 ms, on the highest-weight metric in
+ # the table. A build that made typing worse read faster, and that reading feeds the null
+ # control's noise floor, so it would also tighten the floor every later comparison is judged
+ # against. The other way is quieter: a keystroke that never reached the instrument at all is
+ # missing from both `samples` and `coalesced`.
+ #
+ # So the reading stands only when nothing was left in flight and `samples + coalesced` covers
+ # every input the instrument saw, and every input the driver commanded arrived. A LOW sample
+ # count is not itself a failure -- on a jammed page most keystrokes coalesce behind a slow
+ # paint, and that is the finding, not a fault -- which is why this counts coverage rather than
+ # demanding a sample per character.
+ covered = (
+ seen is not None
+ and seen >= count
+ and accounted >= seen
+ and not got.get("pending_at_collect")
+ )
+ ok = grew is not None and grew >= count and covered
+ return ActionResult(
+ ran = True,
+ expect_ok = ok,
+ expect = expect,
+ timings = {
+ "p50_ms": got.get("p50_ms"),
+ "p95_ms": got.get("p95_ms"),
+ "max_ms": got.get("max_ms"),
+ "first_ms": got.get("first_ms"),
+ "total_ms": round(elapsed_ms, 1),
+ },
+ reason = None
+ if ok
+ else (
+ f"typed {count} characters but the composer value grew by {grew}"
+ if grew is None or grew < count
+ else (
+ f"typed {count} characters and the reading covers {accounted} of {seen} that "
+ f"reached the instrument"
+ + (
+ ", with one still unpainted at the drain"
+ if got.get("pending_at_collect")
+ else ""
+ )
+ )
+ ),
+ )
+
+
+# ── 2, 3. scrolling ─────────────────────────────────────────────────
+
+SCROLL_JS = """
+async ([steps, stepPx, settleMs]) => {
+ const D = window.__sb.dom;
+ const viewport = D.viewport();
+ if (!viewport) return { ran: false, reason: "no thread viewport" };
+ // The viewport carries `scroll-smooth`, so each scrollTop write starts an animation and the
+ // next read lands mid-flight. Stepping from a TRACKED target with an explicit instant
+ // behaviour is what a wheel gesture actually does, and the only way the gesture covers the
+ // distance it asks for.
+ const bottom = viewport.scrollHeight - viewport.clientHeight;
+ if (bottom <= 0) return { ran: false, reason: "the thread is shorter than the viewport" };
+ viewport.scrollTo({ top: bottom, behavior: "instant" });
+ await window.__sbNextPaint();
+ let target = viewport.scrollTop;
+ // Reverse at either end rather than stopping. A small thread runs out of travel long before a
+ // large one, and a gesture that covers 2,600px at one rung and 8,000px at another is not the
+ // same gesture, so the columns would not be comparable.
+ let direction = -1;
+ let travelled = 0;
+ let commanded = 0;
+ const started = performance.now();
+ for (let i = 0; i < steps; i += 1) {
+ if (direction < 0 && target <= 0) direction = 1;
+ else if (direction > 0 && target >= bottom) direction = -1;
+ const next = Math.min(bottom, Math.max(0, target + direction * stepPx));
+ commanded += Math.abs(next - target);
+ // The wheel event is what the app's own scroll listeners key off; the scrollTo is what moves
+ // the viewport in a headless run with no compositor input. Both, or the intent-aware
+ // autoscroll reads the move as programmatic and snaps it back.
+ viewport.dispatchEvent(
+ new WheelEvent("wheel", { deltaY: direction * stepPx, bubbles: true, cancelable: true }),
+ );
+ viewport.scrollTo({ top: next, behavior: "instant" });
+ await window.__sbNextPaint();
+ travelled += Math.abs(viewport.scrollTop - target);
+ target = viewport.scrollTop;
+ }
+ const gestureMs = performance.now() - started;
+ const settleStart = performance.now();
+ while (performance.now() - settleStart < settleMs) await window.__sbNextPaint();
+ return {
+ ran: true,
+ commandedPx: Math.round(commanded),
+ travelledPx: Math.round(travelled),
+ gestureMs: Math.round(gestureMs * 10) / 10,
+ steps,
+ landedAt: Math.round(viewport.scrollTop),
+ bottom: Math.round(bottom),
+ };
+}
+"""
+
+
+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])
+ err = _failed(raw)
+ if err:
+ return not_run(err)
+ if not raw.get("ran"):
+ return not_run(raw.get("reason", "the scroll did not run"))
+ commanded = raw["commandedPx"]
+ travelled = raw["travelledPx"]
+ # 90% of commanded. Studio replaces assistant-ui's autoscroll with an intent-aware one that
+ # snaps a move it reads as programmatic straight back to the bottom: measured on an earlier
+ # harness, the gesture landed where it started and the column timed a scroll that did not
+ # happen. Travel is the only thing that separates the two.
+ ok = commanded > 0 and travelled >= 0.9 * commanded
+ return ActionResult(
+ ran = True,
+ expect_ok = ok,
+ expect = {
+ "commanded_px": commanded,
+ "travelled_px": travelled,
+ "travel_fraction": round(travelled / commanded, 3) if commanded else None,
+ "landed_at": raw["landedAt"],
+ "bottom": raw["bottom"],
+ "phase": label,
+ },
+ timings = {
+ "gesture_ms": raw["gestureMs"],
+ "per_step_ms": round(raw["gestureMs"] / max(1, steps), 2),
+ },
+ reason = None
+ if ok
+ else f"the gesture commanded {commanded}px and the viewport moved {travelled}px, so the "
+ f"autoscroll snapped it back and nothing was scrolled",
+ )
+
+
+@register_action(name = "scroll_during_generation", default_budget_ms = 8000)
+def scroll_during_generation(ctx: ActionContext) -> ActionResult:
+ if not _ev(ctx, "() => window.__sb.dom.isRunning()"):
+ return not_run("nothing was generating, so this is not a scroll during generation")
+ return _scroll(ctx, "during_generation")
+
+
+@register_action(name = "scroll_after", default_budget_ms = 8000)
+def scroll_after(ctx: ActionContext) -> ActionResult:
+ return _scroll(ctx, "after")
+
+
+# ── 4. reasoning expand / collapse ──────────────────────────────────
+
+REASONING_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();
+ 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;
+ };
+ // Toggle EVERY pane, not one: the mechanism under investigation scales with how much content
+ // is mounted, and opening a single pane in a thread of forty is a constant-size action being
+ // reported on an axis of thread length.
+ const openStart = performance.now();
+ for (const t of triggers) t.click();
+ const openedIn = await settle(triggers.length);
+ const openMs = openedIn === null ? null : performance.now() - openStart;
+ const openCount = D.reasoningOpenCount();
+ const spansOpen = document.querySelectorAll("pre span").length;
+ const closeStart = performance.now();
+ for (const t of D.reasoningTriggers()) t.click();
+ const closedIn = await settle(0);
+ const closeMs = closedIn === null ? null : performance.now() - closeStart;
+ return {
+ ran: true,
+ panes: triggers.length,
+ before,
+ openCount,
+ afterClose: D.reasoningOpenCount(),
+ spansOpen,
+ openMs: openMs === null ? null : Math.round(openMs * 10) / 10,
+ closeMs: closeMs === null ? null : Math.round(closeMs * 10) / 10,
+ };
+}
+"""
+
+
+@register_action(name = "reasoning_toggle", default_budget_ms = 12000)
+def reasoning_toggle(ctx: ActionContext) -> ActionResult:
+ raw = _ev(ctx, REASONING_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"))
+ # Both directions, and the pane count is read from `data-state` on the Collapsible ROOT.
+ # Radix keeps collapsed content mounted for its animation, so a presence check on the content
+ # element reports every pane as open and the assertion can never fail.
+ ok = (
+ raw["openMs"] is not None
+ and raw["closeMs"] is not None
+ and raw["openCount"] == raw["panes"]
+ and raw["afterClose"] == 0
+ )
+ return ActionResult(
+ ran = True,
+ expect_ok = ok,
+ expect = {
+ "panes": raw["panes"],
+ "open_after_expand": raw["openCount"],
+ "open_after_collapse": raw["afterClose"],
+ "highlight_spans_while_open": raw["spansOpen"],
+ },
+ timings = {"open_ms": raw["openMs"], "close_ms": raw["closeMs"]},
+ reason = None
+ if ok
+ else f"{raw['openCount']} of {raw['panes']} panes opened and "
+ f"{raw['afterClose']} were still open after collapsing",
+ )
+
+
+# ── 5. stop generation ──────────────────────────────────────────────
+
+#: Remove the throwaway turn `stop_generation` created, so the thread it leaves behind is the
+#: thread it found. Deletes the assistant turn and then the user turn that prompted it, in that
+#: order, because deleting the user message first can take the reply with it and leave the count
+#: ambiguous. Reports what it managed rather than asserting: a cleanup that half-worked must be
+#: visible in the row, not swallowed.
+STOP_CLEANUP_JS = """
+async (timeoutMs) => {
+ const D = window.__sb.dom;
+ const before = D.messageCount();
+ const removeLast = async () => {
+ const target = D.lastAssistantMessage();
+ if (!target) return false;
+ target.dispatchEvent(new PointerEvent("pointerover", { bubbles: true, pointerType: "mouse" }));
+ const button = D.actionButton("Delete message");
+ if (!button) return false;
+ const started = performance.now();
+ button.click();
+ while (performance.now() - started < timeoutMs) {
+ if (!target.isConnected) return true;
+ await window.__sbNextPaint();
+ }
+ return false;
+ };
+ const dropped = await removeLast();
+ const after = D.messageCount();
+ return {
+ removed: dropped && after < before,
+ before, after,
+ reason: dropped ? null : "no Delete control on the throwaway turn",
+ };
+}
+"""
+
+
+@register_action(name = "stop_generation", default_budget_ms = 8000)
+def stop_generation(ctx: ActionContext) -> ActionResult:
+ """Press stop mid-stream and time until the run is really over.
+
+ THE COMPOSER MUST BE EMPTY. `queueDisabled` in thread.tsx depends on
+ `composerText.trim().length > 0`, so with text in the box the Stop control is replaced by a
+ Queue control at the same position with the same class. Pressing it queues a message and the
+ stream carries on, and the action reports a fast, precise, entirely wrong number.
+ """
+ text = _ev(ctx, "() => window.__sb.dom.composerText()")
+ if text:
+ ctx.page.fill('textarea[aria-label="Message input"]', "")
+ ctx.page.wait_for_timeout(120)
+
+ # STOP GETS ITS OWN GENERATION. It used to stop whatever the cell was streaming, which
+ # permanently truncated the measured reply: at the 10K rung the pacer got 5,304 of 17,737
+ # characters away before the socket broke, so the ten actions that follow -- all of them
+ # labelled "after the reply is complete" -- and the final census ran against a thread barely
+ # a third of the size the rung claims. The seeded-vs-streamed equivalence check then compared
+ # that truncated reply against a complete seeded one and reported 20% drift, which read as a
+ # finding about seeding and was a finding about this action.
+ #
+ # Sending its own short turn keeps the measured reply intact and means the action has
+ # something to stop at EVERY rung, instead of reporting `not_run` at the small ones where the
+ # main stream is already over by the time the slot opens.
+ own_generation = False
+ if not _ev(ctx, "() => window.__sb.dom.isRunning()"):
+ ctx.page.fill('textarea[aria-label="Message input"]', "one more")
+ ctx.page.wait_for_timeout(80)
+ ctx.page.keyboard.press("Enter")
+ own_generation = True
+ deadline = time.monotonic() + 8.0
+ while time.monotonic() < deadline:
+ if _ev(ctx, "() => window.__sb.dom.isRunning()"):
+ break
+ ctx.page.wait_for_timeout(50)
+ else:
+ return not_run("nothing was generating and a new turn did not start within 8s")
+ if not _ev(ctx, "() => window.__sb.dom.isRunning()"):
+ return not_run("nothing was generating and a new turn did not start within 8s")
+ # Let it get going, so stop is measured against a live stream rather than a starting one.
+ ctx.page.wait_for_timeout(600)
+ button = ctx.page.query_selector('button[aria-label="Stop generating"]')
+ if button is None:
+ queue = ctx.page.query_selector('button[aria-label="Queue message"]')
+ return not_run(
+ "the stop button is not present"
+ + (" -- the composer still has text, so it is a Queue button" if queue else "")
+ )
+ chars_before = _ev(ctx, "() => window.__sb.dom.assistantChars()")
+ started = time.monotonic()
+ button.click()
+ stopped_ms = None
+ deadline = started + SETTLE_TIMEOUT_MS / 1000
+ while time.monotonic() < deadline:
+ if not _ev(ctx, "() => window.__sb.dom.isRunning()"):
+ stopped_ms = (time.monotonic() - started) * 1000
+ break
+ ctx.page.wait_for_timeout(50)
+ ctx.page.wait_for_timeout(400)
+ chars_after = _ev(ctx, "() => window.__sb.dom.assistantChars()")
+ ok = stopped_ms is not None
+
+ # LEAVE THE THREAD AS WE FOUND IT. The throwaway turn is scaffolding, not content: left in
+ # place it adds an assistant message and a reasoning pane that the rest of the film, the final
+ # census and the seeded-versus-streamed comparison all then measure. That showed up
+ # immediately as "streamed 5 assistant messages vs seeded 4", a drift introduced entirely by
+ # this action while it was busy fixing a different one.
+ removed = None
+ if own_generation:
+ removed = _ev(ctx, STOP_CLEANUP_JS, SETTLE_TIMEOUT_MS)
+ ctx.page.wait_for_timeout(200)
+ return ActionResult(
+ ran = True,
+ expect_ok = ok,
+ expect = {
+ "chars_before": chars_before,
+ "chars_after": chars_after,
+ "still_running": not ok,
+ # Which reply was stopped. A reader comparing `chars_added_after_stop` across
+ # rungs needs to know whether this was a throwaway turn or the cell's own.
+ "own_generation": own_generation,
+ # Whether the scaffolding was removed again. Reported rather than asserted: a
+ # cleanup that failed leaves an extra turn in the thread, and every census
+ # after this point needs to be readable in that light.
+ "scaffold_removed": (None if removed is None else bool(removed.get("removed"))),
+ "scaffold_note": (None if removed is None else removed.get("reason")),
+ # A stop that worked leaves the text where it was, give or take the chunks
+ # already in flight. A large jump means the stream ran on.
+ "chars_added_after_stop": (
+ None if chars_after is None or chars_before is None else chars_after - chars_before
+ ),
+ },
+ timings = {"stop_ms": None if stopped_ms is None else round(stopped_ms, 1)},
+ reason = None
+ if ok
+ else f"the run was still going {SETTLE_TIMEOUT_MS}ms after stop was pressed",
+ )
+
+
+# ── 6. settings ─────────────────────────────────────────────────────
+
+
+@register_action(name = "settings", default_budget_ms = 12000)
+def settings(ctx: ActionContext) -> ActionResult:
+ """Open the Settings dialog, scroll its body, close it.
+
+ Opened by navigating to `/settings`, which the app's own route does by calling
+ `openDialog()`. Deterministic in a way that clicking a sidebar cog is not: the sidebar can be
+ collapsed, and the same aria-label appears on more than one control.
+ """
+ trigger = ctx.page.query_selector('button[aria-label="Settings"]')
+ started = time.monotonic()
+ if trigger is not None:
+ trigger.click()
+ else:
+ ctx.page.evaluate("() => window.history.pushState({}, '', '/settings')")
+ ctx.page.goto(ctx.args.get("base_url", "") + "/settings", wait_until = "domcontentloaded")
+ opened_ms = None
+ deadline = started + SETTLE_TIMEOUT_MS / 1000
+ while time.monotonic() < deadline:
+ if _ev(ctx, "() => Boolean(window.__sb.dom.settingsDialog())"):
+ opened_ms = (time.monotonic() - started) * 1000
+ break
+ ctx.page.wait_for_timeout(50)
+ if opened_ms is None:
+ return not_run("the settings dialog never appeared")
+
+ scrolled = _ev(
+ ctx,
+ """
+ async () => {
+ const D = window.__sb.dom;
+ const el = D.settingsScroller();
+ if (!el) return { ran: false, reason: "no scrollable settings body" };
+ const bottom = el.scrollHeight - el.clientHeight;
+ const started = performance.now();
+ el.scrollTo({ top: bottom, behavior: "instant" });
+ await window.__sbNextPaint();
+ const landed = el.scrollTop;
+ el.scrollTo({ top: 0, behavior: "instant" });
+ await window.__sbNextPaint();
+ return { ran: true, commandedPx: Math.round(bottom), landedAt: Math.round(landed),
+ ms: Math.round((performance.now() - started) * 10) / 10 };
+ }
+ """,
+ )
+
+ close_started = time.monotonic()
+ ctx.page.keyboard.press("Escape")
+ closed_ms = None
+ deadline = close_started + SETTLE_TIMEOUT_MS / 1000
+ while time.monotonic() < deadline:
+ if not _ev(ctx, "() => Boolean(window.__sb.dom.settingsDialog())"):
+ closed_ms = (time.monotonic() - close_started) * 1000
+ break
+ ctx.page.wait_for_timeout(50)
+
+ scroll_ok = bool(
+ scrolled
+ and scrolled.get("ran")
+ and (
+ scrolled.get("commandedPx", 0) == 0
+ or scrolled.get("landedAt", 0) >= 0.9 * scrolled.get("commandedPx", 1)
+ )
+ )
+ ok = closed_ms is not None and scroll_ok
+ return ActionResult(
+ ran = True,
+ expect_ok = ok,
+ expect = {
+ "opened": True,
+ "closed": closed_ms is not None,
+ "scroll": scrolled if isinstance(scrolled, dict) else None,
+ },
+ timings = {
+ "open_ms": round(opened_ms, 1),
+ "close_ms": None if closed_ms is None else round(closed_ms, 1),
+ "scroll_ms": (scrolled or {}).get("ms"),
+ },
+ reason = None if ok else "the dialog did not close, or its body did not scroll",
+ )
+
+
+# ── 7. model change ─────────────────────────────────────────────────
+
+
+@register_action(name = "model_change", default_budget_ms = 10000)
+def model_change(ctx: ActionContext) -> ActionResult:
+ """Open the model picker and select a row.
+
+ THE WEAKEST SELECTOR IN THE SUITE, and it is recorded as such rather than hidden. The picker's
+ option rows are plain `<button>` elements with utility classes: no `role="option"`, no
+ `data-model-id`, no CommandItem, nothing stable anywhere in features/model-picker. So the row
+ is found by position among the menu's buttons and the assertion is on the trigger's LABEL
+ changing, which is an observable consequence rather than a selector.
+ """
+ trigger = ctx.page.query_selector("button.unsloth-model-selector-trigger")
+ if trigger is None:
+ return not_run("no model selector trigger on the page")
+ before = _ev(ctx, "() => window.__sb.dom.currentModelLabel()")
+ started = time.monotonic()
+ # Click the LABEL, not the trigger's right edge: a `span[data-eject-hit]` sits there and
+ # clicking it ejects the model instead of opening the picker.
+ trigger.click(position = {"x": 8, "y": 8})
+ opened_ms = None
+ deadline = started + SETTLE_TIMEOUT_MS / 1000
+ while time.monotonic() < deadline:
+ if _ev(ctx, "() => window.__sb.dom.modelOptions().length > 0"):
+ opened_ms = (time.monotonic() - started) * 1000
+ break
+ ctx.page.wait_for_timeout(50)
+ if opened_ms is None:
+ return not_run("the model picker never opened")
+ options = _ev(ctx, "() => window.__sb.dom.modelOptions().map(b => (b.textContent||'').trim())")
+ select_started = time.monotonic()
+ picked = _ev(
+ ctx,
+ """
+ (name) => {
+ const opts = window.__sb.dom.modelOptions();
+ const target = opts.find(b => (b.textContent || '').trim() === name) || opts[0];
+ if (!target) return null;
+ target.click();
+ return (target.textContent || '').trim();
+ }
+ """,
+ ctx.args.get("model_name", ""),
+ )
+ ctx.page.wait_for_timeout(300)
+ select_ms = (time.monotonic() - select_started) * 1000
+ after = _ev(ctx, "() => window.__sb.dom.currentModelLabel()")
+ closed = not _ev(ctx, "() => Boolean(window.__sb.dom.modelMenu())")
+ ok = picked is not None and closed
+ return ActionResult(
+ ran = True,
+ expect_ok = ok,
+ expect = {
+ "options_offered": len(options or []),
+ "picked": picked,
+ "label_before": before,
+ "label_after": after,
+ "menu_closed": closed,
+ "selector_confidence": "low: the option rows carry no stable attribute",
+ },
+ timings = {"open_ms": round(opened_ms, 1), "select_ms": round(select_ms, 1)},
+ reason = None if ok else "no option could be selected, or the menu stayed open",
+ )
+
+
+# ── 8. composer lengths, then send ──────────────────────────────────
+
+
+@register_action(name = "composer_fill", default_budget_ms = 10000)
+def composer_fill(ctx: ActionContext) -> ActionResult:
+ """Short, medium and very long text into the composer, timing each paint.
+
+ A very long paste is its own axis: the composer is an autosizing textarea capped at 12 rows,
+ so a 20,000-character paste re-lays-out the whole composer AND the thread beneath it, and the
+ app's paste path scans it for attachment-worthy content.
+ """
+ lengths = ctx.args.get("lengths") or [40, 2000, 20000]
+ selector = 'textarea[aria-label="Message input"]'
+ if ctx.page.query_selector(selector) is None:
+ return not_run("no composer on the page")
+ timings: dict = {}
+ observed: dict = {}
+ for n in lengths:
+ text = ("studiobench composer probe " * ((n // 27) + 1))[:n]
+ got = _ev(
+ ctx,
+ """
+ async ([sel, text]) => {
+ const el = document.querySelector(sel);
+ if (!el) return null;
+ const setValue = Object.getOwnPropertyDescriptor(
+ HTMLTextAreaElement.prototype, "value").set;
+ el.focus();
+ await window.__sbNextPaint();
+ const started = performance.now();
+ setValue.call(el, text);
+ el.dispatchEvent(new Event("input", { bubbles: true }));
+ await window.__sbNextPaint();
+ const ms = performance.now() - started;
+ return { ms: Math.round(ms * 10) / 10, length: el.value.length,
+ runtimeLength: (window.__sb.dom.composerText() || "").length,
+ rows: Math.round(el.getBoundingClientRect().height) };
+ }
+ """,
+ [selector, text],
+ )
+ if not isinstance(got, dict) or got.get("ms") is None:
+ return not_run(f"the composer did not accept {n} characters")
+ timings[f"fill_{n}_ms"] = got["ms"]
+ observed[f"length_{n}"] = got["length"]
+ observed[f"height_{n}_px"] = got["rows"]
+ # The LAST fill is sent, so the send path is exercised with the heaviest composer state.
+ send = ctx.page.query_selector('button[aria-label="Send message"]')
+ sent = False
+ if send is not None and ctx.args.get("send", False):
+ send.click()
+ ctx.page.wait_for_timeout(300)
+ sent = True
+ else:
+ ctx.page.fill(selector, "")
+ ok = all(observed.get(f"length_{n}") == n for n in lengths)
+ return ActionResult(
+ ran = True,
+ expect_ok = ok,
+ expect = {**observed, "sent": sent, "lengths_requested": list(lengths)},
+ timings = timings,
+ reason = None if ok else "the composer did not hold every length it was given",
+ )
+
+
+# ── 9. copy markdown ────────────────────────────────────────────────
+
+
+@register_action(name = "copy_markdown", default_budget_ms = 6000)
+def copy_markdown(ctx: ActionContext) -> ActionResult:
+ """The message action bar's Copy, which copies `getCopyText()` for the whole message.
+
+ NOT the More menu: Copy is a top-level icon button and "Export as markdown" in the More menu
+ triggers a file download rather than a clipboard write. The action bar has `autohide`, so it
+ is hovered first or the button is not in the tree to click.
+ """
+ # Hover AND WAIT, on the same reasoning as `message_menu`: this bar is `hideWhenRunning`, so a
+ # slot that opens with the follow-up's last chunks still arriving finds no Copy button at all.
+ # The fixed 150 ms this replaced was a hover settle, not a wait for the reply, and it returned
+ # the same "no Copy button" whether the control was missing or merely not mounted yet.
+ found = _ev(
+ ctx,
+ """
+ async (waitMs) => {
+ const found = await window.__sb.dom.waitForActionButton("Copy", waitMs);
+ return { found: Boolean(found.el), waitedMs: found.waitedMs, running: found.running };
+ }
+ """,
+ ACTION_BAR_WAIT_MS,
+ )
+ if not isinstance(found, dict) or not found.get("found"):
+ waited = (found or {}).get("waitedMs") if isinstance(found, dict) else None
+ running = (found or {}).get("running") if isinstance(found, dict) else None
+ return not_run(
+ f"no Copy button on the last assistant message after waiting {waited}ms"
+ + (", and the thread was still generating" if running else "")
+ )
+ started = time.monotonic()
+ ok_click = _ev(
+ ctx,
+ """
+ () => {
+ // Re-hovered: the wait above ended with a hover, and a re-render between the two
+ // evaluates can unmount the bar again.
+ window.__sb.dom.hoverLastAssistantMessage();
+ const b = window.__sb.dom.actionButton("Copy");
+ if (!b) return false;
+ b.click();
+ return true;
+ }
+ """,
+ )
+ if not ok_click:
+ return not_run("no Copy button on the last assistant message")
+ ctx.page.wait_for_timeout(200)
+ elapsed = (time.monotonic() - started) * 1000
+ # Read back from the clipboard. Headless Chromium grants clipboard-read only with the
+ # permission, which the browser factory requests; if it is not granted the action still RAN,
+ # and the assertion says it could not be proved rather than that it failed.
+ clip = None
+ reason = None
+ 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__}"
+ chars = len(clip) if isinstance(clip, str) else None
+ ok = chars is not None and chars > 0
+ return ActionResult(
+ ran = True,
+ expect_ok = ok if reason is None else False,
+ expect = {"clipboard_chars": chars, "clipboard_readable": reason is None},
+ timings = {"copy_ms": round(elapsed, 1)},
+ reason = reason or (None if ok else "the clipboard was empty after Copy"),
+ )
+
+
+# ── 10, 11. selection ───────────────────────────────────────────────
+
+
+@register_action(name = "select_text", default_budget_ms = 6000)
+def select_text(ctx: ActionContext) -> ActionResult:
+ """Select a range inside the last assistant message. Selection over a large thread forces the
+ engine to walk and paint selection geometry across whatever is mounted."""
+ raw = _ev(
+ ctx,
+ """
+ async () => {
+ const m = window.__sb.dom.lastAssistantMessage();
+ if (!m) return { ran: false, reason: "no assistant message" };
+ const started = performance.now();
+ const range = document.createRange();
+ range.selectNodeContents(m);
+ const sel = window.getSelection();
+ sel.removeAllRanges();
+ sel.addRange(range);
+ await window.__sbNextPaint();
+ const text = sel.toString();
+ const ms = performance.now() - started;
+ sel.removeAllRanges();
+ // innerText, NOT textContent, as the denominator. textContent counts text inside
+ // collapsed elements -- and a finished reply's reasoning pane is collapsed by default, so
+ // most of a reasoning turn's characters are in the tree and not on the screen. A
+ // selection can only cover what is rendered, so comparing against textContent failed this
+ // assertion on every reasoning-heavy cell while the selection was working perfectly.
+ return { ran: true, ms: Math.round(ms * 10) / 10, chars: text.length,
+ visibleChars: (m.innerText || "").length,
+ messageChars: (m.textContent || "").length };
+ }
+ """,
+ )
+ err = _failed(raw)
+ if err:
+ return not_run(err)
+ if not raw.get("ran"):
+ return not_run(raw.get("reason", "selection did not run"))
+ visible = raw.get("visibleChars") or 0
+ # NON-EMPTY, and the coverage fraction reported as evidence rather than gated on.
+ #
+ # "Half the visible characters" looked like a reasonable bar and is not one: innerText
+ # collapses runs of whitespace and skips nested scrollers, and Selection.toString applies its
+ # own normalisation, so the two counts are not the same quantity even when the selection
+ # covers the whole message. Measured on a real reply: 22 selected against 80 "visible", with
+ # the selection plainly spanning the entire message. The action's claim is that text in this
+ # message got selected; the fraction belongs in the evidence, not in the verdict.
+ ok = raw["chars"] > 0
+ return ActionResult(
+ ran = True,
+ expect_ok = ok,
+ expect = {
+ "selected_chars": raw["chars"],
+ "visible_chars": visible,
+ "coverage": round(raw["chars"] / visible, 3) if visible else None,
+ "message_chars_including_collapsed": raw["messageChars"],
+ },
+ timings = {"select_ms": raw["ms"]},
+ reason = None if ok else "the selection was empty",
+ )
+
+
+@register_action(name = "select_all_copy", default_budget_ms = 10000)
+def select_all_copy(ctx: ActionContext) -> ActionResult:
+ """Ctrl+A then Ctrl+C over the WHOLE thread. The heaviest selection there is, and a real
+ keyboard path so the app's own key handlers run."""
+ ctx.page.evaluate("""() => {
+ const v = window.__sb.dom.viewport();
+ if (v) v.focus({ preventScroll: true });
+ }""")
+ started = time.monotonic()
+ raw = _ev(
+ ctx,
+ """
+ async () => {
+ const started = performance.now();
+ const sel = window.getSelection();
+ sel.removeAllRanges();
+ const range = document.createRange();
+ const root = window.__sb.dom.viewport() || document.body;
+ range.selectNodeContents(root);
+ sel.addRange(range);
+ await window.__sbNextPaint();
+ const chars = sel.toString().length;
+ return { selectMs: Math.round((performance.now() - started) * 10) / 10, chars };
+ }
+ """,
+ )
+ err = _failed(raw)
+ if err:
+ return not_run(err)
+ copy_started = time.monotonic()
+ ctx.page.keyboard.press("Control+C")
+ ctx.page.wait_for_timeout(250)
+ copy_ms = (time.monotonic() - copy_started) * 1000
+ ctx.page.evaluate("() => window.getSelection().removeAllRanges()")
+ ok = raw["chars"] > 0
+ return ActionResult(
+ ran = True,
+ expect_ok = ok,
+ expect = {"selected_chars": raw["chars"]},
+ timings = {
+ "select_all_ms": raw["selectMs"],
+ "copy_ms": round(copy_ms, 1),
+ "total_ms": round((time.monotonic() - started) * 1000, 1),
+ },
+ reason = None if ok else "select-all selected nothing",
+ )
+
+
+# ── 12. image upload ────────────────────────────────────────────────
+
+
+@register_action(name = "send_turn", default_budget_ms = 10000)
+def send_turn(ctx: ActionContext) -> ActionResult:
+ """Send another prompt mid-film and let the next reply stream in.
+
+ ONE STREAMED TURN IS NOT A CONVERSATION. Everything above this action measured a thread that
+ was seeded in bulk and then streamed exactly once, at the end. A real session streams
+ repeatedly into a thread that is already large, and the interesting cost -- what a chunk
+ costs given what is already on screen -- is only sampled once per cell that way.
+
+ The extra turns come out of the SAME fixed streaming budget as the first, split between them,
+ so adding turns costs no wall clock. The corpus alternates reasoning-heavy and code-heavy
+ units, so consecutive sends exercise the `<think>` re-parse and the Streamdown/Shiki path
+ rather than repeating one of them.
+ """
+ pacer = ctx.args.get("_pacer")
+ queue = ctx.args.get("_stream_queue") or []
+ # A SHARED MUTABLE cursor, not a scalar in `args`. The scene runner builds each action's args
+ # as `{**base_args, **slot.args}`, so a scalar written back here lands in a dict that is
+ # discarded when the action returns: the second send re-sent the first turn, reported
+ # `turn_index: 1` twice, and failed because that message was already in the thread.
+ cursor = ctx.args.get("_stream_cursor")
+ if not isinstance(cursor, dict):
+ return not_run("no shared stream cursor was passed to the action")
+ index = int(cursor.get("i", 0))
+ if pacer is None:
+ return not_run("no pacer was passed to the action")
+ if index >= len(queue):
+ return not_run(f"the stream queue is exhausted ({len(queue)} turns planned)")
+ if _ev(ctx, "() => window.__sb.dom.isRunning()"):
+ # Sending while a reply is in flight queues the message instead of starting a stream, and
+ # the action would report a fast, precise number about a message that is merely parked.
+ return not_run("a reply was still streaming, so this send would have been queued")
+
+ unit = queue[index]
+ cursor["i"] = index + 1
+ # NO `pacer.reset()` HERE. It used to clear the pacer's stats before loading the next turn, and
+ # `CellRunner` records `last_stats()` -- so the opening reply's `StreamStats` were discarded by
+ # the first follow-up and the first follow-up's by the second. An opening reply that
+ # disconnected or delivered 4,624 of its 10,000 characters was then erased by a later turn that
+ # DID finish, and the cell was marked complete and scored against an undersized thread, because
+ # the only other liveness signal is the UI no longer running and the later turn satisfies it.
+ # Every turn is tagged, so keeping them all costs one small record each and lets
+ # `check_planned_streams` verify the cell streamed what it planned. `CellRunner` still resets
+ # once per cell, which is the boundary that reset is for.
+ tag = f"{ctx.args.get('cell_id', 'cell')}#turn{index + 1}"
+ pacer.load(
+ unit["reasoning"],
+ unit["content"],
+ cadence = ctx.args.get("cadence", "field"),
+ tag = tag,
+ )
+
+ selector = 'textarea[aria-label="Message input"]'
+ if ctx.page.query_selector(selector) is None:
+ 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()")
+ started = time.monotonic()
+ ctx.page.keyboard.press("Enter")
+
+ first_ms = None
+ deadline = started + SETTLE_TIMEOUT_MS / 1000
+ while time.monotonic() < deadline:
+ if _ev(ctx, "() => window.__sb.dom.isRunning()"):
+ first_ms = (time.monotonic() - started) * 1000
+ break
+ ctx.page.wait_for_timeout(50)
+ 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 = (
+ first_ms is not None
+ and isinstance(after, int)
+ and isinstance(before, int)
+ and after > before
+ )
+ return ActionResult(
+ ran = True,
+ expect_ok = ok,
+ expect = {
+ "messages_before": before,
+ "messages_after": after,
+ "turn_index": index + 1,
+ "queued_turns": len(queue),
+ "streamed_chars": len(unit["reasoning"]) + len(unit["content"]),
+ # The tag this turn's stream carries, so the cell can check the turn against the
+ # pacer's own record of it rather than re-deriving the naming rule from the outside.
+ "pacer_tag": tag,
+ "unit_kind": unit.get("kind"),
+ },
+ timings = {"to_first_token_ms": None if first_ms is None else round(first_ms, 1)},
+ reason = None if ok else "the send did not start a new streaming reply",
+ )
+
+
+#: What the page can tell us when the attachments button cannot be found. Reads geometry, style,
+#: hit-testing and the surrounding chrome, so the three explanations that look identical from a
+#: `not_run` string look different here.
+IMAGE_BUTTON_DIAGNOSTIC = """() => {
+ const sel = 'button[aria-label="Tools and attachments"]';
+ const all = [...document.querySelectorAll(sel)];
+ return {
+ in_dom: all.length,
+ boxes: all.map((b) => {
+ const r = b.getBoundingClientRect();
+ const cs = getComputedStyle(b);
+ const top = r.width && r.height
+ ? document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2) : null;
+ return {
+ w: Math.round(r.width), h: Math.round(r.height),
+ x: Math.round(r.left), y: Math.round(r.top),
+ in_viewport: r.top >= 0 && r.bottom <= window.innerHeight,
+ display: cs.display, visibility: cs.visibility, opacity: cs.opacity,
+ pointer_events: cs.pointerEvents,
+ mounted: b.offsetParent !== null,
+ hit_self: top === b || (top !== null && b.contains(top)),
+ };
+ }),
+ composers: document.querySelectorAll('textarea[aria-label="Message input"]').length,
+ open_dialogs: document.querySelectorAll('[role="dialog"]').length,
+ popper_layers: document.querySelectorAll('[data-radix-popper-content-wrapper]').length,
+ body_pointer_events: getComputedStyle(document.body).pointerEvents,
+ model_loaded_hint: (document.body.innerText || "").includes("Load a model"),
+ viewport: {w: window.innerWidth, h: window.innerHeight},
+ };
+}"""
+
+
+@register_action(name = "image_upload", default_budget_ms = 12000)
+def image_upload(ctx: ActionContext) -> ActionResult:
+ """Attach an image through the composer's file chooser.
+
+ THERE IS NO PERSISTENT `<input type=file>` in the composer. thread.tsx creates one
+ imperatively on click, appends it to `<body>` hidden, clicks it and removes it, and its
+ `accept` is derived at runtime from the selected model's vision capability. So the only
+ reliable path is Playwright's file chooser event around the menu item, and any hard-coded
+ `accept` assertion would be unsafe.
+ """
+ png = ctx.args.get("image_path")
+ if not png:
+ return not_run("no image path was supplied to the action")
+ # `:visible`, and the FIRST visible match.
+ #
+ # Two reasons, both measured. `document.querySelector` returns the first match in DOCUMENT
+ # ORDER and the composer exists more than once: the welcome-screen instance stays in the tree
+ # behind the docked one, and compare mode has two threads. The hidden duplicate comes first,
+ # so a plain query handed back a button that can never be clicked and the action reported "not
+ # visible" about a control that a direct probe found at 36x36 pixels, fully opaque, on screen.
+ #
+ # And Playwright's actionability wait does not give up quickly on an unclickable element: at
+ # its 30s default it blocked a 9s slot for more than three times the slot's budget, to report
+ # that nothing happened. Everything here is bounded by what is left of the slot.
+ locator = ctx.page.locator('button[aria-label="Tools and attachments"]:visible').first
+ try:
+ plus = locator.element_handle(timeout = 2000)
+ except Exception: # noqa: BLE001
+ plus = None
+ if plus is None:
+ # WHY, not just THAT. A bare "not visible" is the opaque zero of the action layer: it
+ # conflates a button that is absent, a button that is present and covered, and a locator
+ # that disagrees with the page, and it has already cost three wrong hypotheses. A direct
+ # probe found the control at 36x36, fully opaque and hit-testable, on a fresh chat and
+ # after a settings round trip and under a 20,000-character composer fill, so whatever
+ # this is, it is none of those. Carrying the state into the row means the NEXT run
+ # answers it instead of the next investigation.
+ return not_run(
+ "no visible attachments button on the composer: "
+ + json.dumps(_ev(ctx, IMAGE_BUTTON_DIAGNOSTIC) or {})
+ )
+ before = _ev(
+ ctx,
+ "() => document.querySelectorAll('.aui-composer-attachment, "
+ '[data-slot="composer-attachment"]\').length',
+ )
+ started = time.monotonic()
+ # Bounded by what is left of the slot, never by Playwright's 30s default.
+ try:
+ plus.click(timeout = max(500, min(ctx.budget_ms // 3, 5000)))
+ except Exception as exc: # noqa: BLE001
+ return not_run(f"the attachments button could not be clicked: {type(exc).__name__}")
+ ctx.page.wait_for_timeout(200)
+ try:
+ with ctx.page.expect_file_chooser(timeout = 6000) as fc:
+ ctx.page.evaluate("""() => {
+ const item = window.__sb.dom.menuItemByText("Add photos");
+ if (item) item.click();
+ }""")
+ fc.value.set_files(png)
+ except Exception as exc: # noqa: BLE001
+ ctx.page.keyboard.press("Escape")
+ return not_run(f"the file chooser never opened: {type(exc).__name__}: {exc}")
+ ctx.page.wait_for_timeout(800)
+ after = _ev(
+ ctx,
+ "() => document.querySelectorAll('.aui-composer-attachment, "
+ '[data-slot="composer-attachment"]\').length',
+ )
+ elapsed = (time.monotonic() - started) * 1000
+ ok = after is not None and before is not None and after > before
+ return ActionResult(
+ ran = True,
+ expect_ok = ok,
+ expect = {"attachments_before": before, "attachments_after": after},
+ timings = {"upload_ms": round(elapsed, 1)},
+ reason = None if ok else "no attachment appeared in the composer after the file was set",
+ )
+
+
+# ── 13. thread reopen ───────────────────────────────────────────────
+
+
+@register_action(name = "thread_reopen", default_budget_ms = 30000)
+def thread_reopen(ctx: ActionContext) -> ActionResult:
+ """Leave the thread and come back.
+
+ The runtime keeps the messages; the Thread subtree is torn down and rebuilt, so every markdown
+ block, every Shiki fence and every action bar is mounted again from nothing. This is the
+ action users describe as "it hangs when I click back into the conversation" and it is the one
+ with no incremental path at all.
+ """
+ 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:
+ return not_run("the thread has no messages to rebuild")
+ 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")
+ # Unmount FIRST, or "already back" is indistinguishable from "never left".
+ closed_ms = None
+ deadline = started + 15
+ while time.monotonic() < deadline:
+ if _ev(ctx, "() => window.__sb.dom.messageCount()") == 0:
+ closed_ms = (time.monotonic() - started) * 1000
+ break
+ ctx.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(
+ 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")
+ 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()")
+ spans = _ev(ctx, "() => document.querySelectorAll('pre span').length")
+ ok = reopen_ms is not None and after == before
+ return ActionResult(
+ ran = True,
+ expect_ok = ok,
+ expect = {"messages_before": before, "messages_after": after, "highlight_spans_after": spans},
+ 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",
+ )
+
+
+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.
+
+ 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.
+ """
+ handle = ctx.page.query_selector(selector)
+ if handle is not None:
+ try:
+ handle.click(timeout = 2000)
+ return True
+ except Exception: # noqa: BLE001
+ ctx.log(f" {selector} was not clickable; navigating instead")
+ try:
+ ctx.page.goto(url, wait_until = "domcontentloaded", timeout = 60_000)
+ return True
+ except Exception as exc: # noqa: BLE001
+ ctx.log(f" navigation to {url} failed: {type(exc).__name__}: {exc}")
+ return False
+
+
+# ── 14. message menu ────────────────────────────────────────────────
+
+MENU_JS = """
+async (opts) => {
+ const D = window.__sb.dom;
+ const timeoutMs = opts.timeoutMs;
+ // WAITED FOR, not sampled for. The bar carrying this trigger is `hideWhenRunning`, so the
+ // control is absent -- not hidden -- for as long as the follow-up turn the preceding `send_turn`
+ // started is still arriving. See `dom.js waitForActionButton` for the measurement that says how
+ // late that can be, and why a single sample turns a third of a second of stream into a report of
+ // a missing control. The clock below starts AFTER this returns, so nothing that is waited for
+ // here lands in the latency this action exists to measure.
+ const found = await D.waitForActionButton("More", opts.waitForButtonMs);
+ const trigger = found.el;
+ const waitedMs = found.waitedMs;
+ if (!trigger) {
+ return {
+ ran: false,
+ waitedMs,
+ running: found.running,
+ reason:
+ "no More button on the last assistant message after waiting " + waitedMs + "ms" +
+ (found.running
+ ? ": the thread was STILL GENERATING, which unmounts the action bar, so this slot "
+ + "opened before the reply settled rather than the control being missing"
+ : ""),
+ };
+ }
+ // A MutationObserver flag, NOT a querySelector per frame. The menu content is portaled to the
+ // end of document.body, so polling for it walks the whole message list and finds nothing for
+ // the entire open latency: a harness cost that grows exactly like the signal being measured.
+ let open = Boolean(D.openMenu());
+ const watcher = new MutationObserver(() => { open = Boolean(D.openMenu()); });
+ watcher.observe(document.body, { childList: true, subtree: false });
+ const settle = async (want) => {
+ const started = performance.now();
+ while (performance.now() - started < timeoutMs) {
+ if (open === want) return performance.now() - started;
+ await window.__sbNextPaint();
+ }
+ return null;
+ };
+ const pointer = { bubbles: true, cancelable: true, composed: true, button: 0,
+ pointerId: 1, pointerType: "mouse", isPrimary: true };
+ const openStarted = performance.now();
+ // pointerdown/up, not click(). The Radix trigger opens on pointerdown, so an element.click()
+ // leaves the menu shut and the whole measurement silently reads zero.
+ trigger.dispatchEvent(new PointerEvent("pointerdown", { ...pointer, buttons: 1 }));
+ trigger.dispatchEvent(new PointerEvent("pointerup", { ...pointer, buttons: 0 }));
+ const opened = await settle(true);
+ const openMs = opened === null ? null : performance.now() - openStarted;
+ const bodyPointerEvents = getComputedStyle(document.body).pointerEvents;
+ const items = D.openMenuItemCount();
+ // The clock starts BEFORE the dispatch: Radix dismisses synchronously inside it -- layer
+ // teardown, focus restore, the body coming off the modal layer and the re-render after -- which
+ // is the fan-out being measured. Starting it after excluded exactly the part worth timing.
+ const closeStarted = performance.now();
+ document.dispatchEvent(new KeyboardEvent("keydown",
+ { key: "Escape", bubbles: true, cancelable: true }));
+ const closed = await settle(false);
+ const closeMs = closed === null ? null : performance.now() - closeStarted;
+ watcher.disconnect();
+ return { ran: true, waitedMs,
+ openMs: openMs === null ? null : Math.round(openMs * 10) / 10,
+ closeMs: closeMs === null ? null : Math.round(closeMs * 10) / 10,
+ items, bodyPointerEvents,
+ bodyPointerEventsAfterClose: getComputedStyle(document.body).pointerEvents };
+}
+"""
+
+
+@register_action(name = "message_menu", default_budget_ms = 12000)
+def message_menu(ctx: ActionContext) -> ActionResult:
+ raw = _ev(
+ ctx,
+ MENU_JS,
+ {"timeoutMs": SETTLE_TIMEOUT_MS, "waitForButtonMs": ACTION_BAR_WAIT_MS},
+ )
+ err = _failed(raw)
+ if err:
+ return not_run(err)
+ if not raw.get("ran"):
+ return not_run(raw.get("reason", "the menu action did not run"))
+ waited_ms = raw.get("waitedMs")
+ if waited_ms:
+ # Logged rather than swallowed. A cell that had to wait says so, because a wait means the
+ # film opened this slot before the follow-up had drained, and that is a fact about the
+ # PACKING which is worth seeing even though the action ran.
+ ctx.log(f" message_menu waited {waited_ms}ms for the action bar to be mounted")
+ # Opened AND closed AND a non-zero item count. Any one of the three alone can be satisfied by
+ # a menu that never rendered its items.
+ ok = raw["openMs"] is not None and raw["closeMs"] is not None and raw["items"] > 0
+ return ActionResult(
+ ran = True,
+ expect_ok = ok,
+ expect = {
+ "items_while_open": raw["items"],
+ # Radix puts the body on the modal layer while the menu is up, which is the
+ # fan-out under suspicion. This proves the open really took that path.
+ "body_pointer_events_open": raw["bodyPointerEvents"],
+ "body_pointer_events_closed": raw["bodyPointerEventsAfterClose"],
+ # In the payload, not only in the log: a run whose cells all waited is a run whose
+ # film opens this slot too early, and that is not visible from a row that only says
+ # `ran`.
+ "action_bar_wait_ms": waited_ms,
+ },
+ timings = {
+ "open_ms": raw["openMs"],
+ "close_ms": raw["closeMs"],
+ "open_close_ms": (
+ None
+ if raw["openMs"] is None or raw["closeMs"] is None
+ else round(raw["openMs"] + raw["closeMs"], 1)
+ ),
+ },
+ reason = None
+ if ok
+ else f"opened={raw['openMs'] is not None} closed={raw['closeMs'] is not None} "
+ f"items={raw['items']}",
+ )
+
+
+# ── 15. delete ──────────────────────────────────────────────────────
+
+DELETE_JS = """
+async (opts) => {
+ const D = window.__sb.dom;
+ const timeoutMs = opts.timeoutMs;
+ // "a running message hides it" was already the diagnosis in the line this replaced, and the
+ // action still reported NOT RUN on the first sample rather than waiting for the running message
+ // to stop running. Same wait, same bound and same reporting as `message_menu`.
+ const found = await D.waitForActionButton("Delete message", opts.waitForButtonMs);
+ const button = found.el;
+ const waitedMs = found.waitedMs;
+ if (!button) {
+ return {
+ ran: false,
+ waitedMs,
+ running: found.running,
+ reason:
+ "no Delete button after waiting " + waitedMs + "ms" +
+ (found.running ? ": the thread was still generating, which unmounts the action bar" : ""),
+ };
+ }
+ const target = D.lastAssistantMessage();
+ const before = 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.
+ while (performance.now() - started < timeoutMs) {
+ if (target === null || !target.isConnected) { ms = performance.now() - started; break; }
+ await window.__sbNextPaint();
+ }
+ return { ran: true, waitedMs, ms: ms === null ? null : Math.round(ms * 10) / 10,
+ before, after: D.messageCount() };
+}
+"""
+
+
+@register_action(name = "delete_message", default_budget_ms = 15000)
+def delete_message(ctx: ActionContext) -> ActionResult:
+ raw = _ev(
+ ctx,
+ DELETE_JS,
+ {"timeoutMs": SETTLE_TIMEOUT_MS, "waitForButtonMs": ACTION_BAR_WAIT_MS},
+ )
+ err = _failed(raw)
+ if err:
+ 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.
+ ok = raw["ms"] is not None and raw["after"] < raw["before"]
+ return ActionResult(
+ ran = True,
+ expect_ok = ok,
+ expect = {
+ "messages_before": raw["before"],
+ "messages_after": raw["after"],
+ "dropped": raw["before"] - raw["after"],
+ "action_bar_wait_ms": raw.get("waitedMs"),
+ },
+ timings = {"delete_ms": raw["ms"]},
+ reason = None if ok else f"the message count went {raw['before']} -> {raw['after']}",
+ )
diff --git a/tests/studio/studiobench/scene/dom.js b/tests/studio/studiobench/scene/dom.js
new file mode 100644
index 00000000000..74c1183ff51
--- /dev/null
+++ b/tests/studio/studiobench/scene/dom.js
@@ -0,0 +1,307 @@
+// 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 selector adapter for the REAL Studio chat UI.
+//
+// The salvaged action JS from playwright_heavy_thread.py calls `window.__heavyThread`, an API the
+// smoke fixture exported. The shipping app exports nothing of the kind, so the actions are ported
+// onto this: the same method names, backed by the app's own selectors. One file to edit when a
+// class changes, instead of fifteen.
+//
+// The chat thread has essentially NO test ids -- exactly one, `composer-tool-status`, in the whole
+// of components/assistant-ui and features/chat. So the contract is class hooks (`aui-*`,
+// `unsloth-*`), `data-role`, `data-slot` and accessible names, all read out of the shipped TSX.
+//
+// Three selectors carry a trap and are handled here rather than in each action:
+//
+// - The composer exists TWICE in compare mode and once on the welcome screen vs once docked, so
+// everything scopes to the first thread root.
+// - The Stop button is REPLACED by a Queue button when the composer has text, because
+// `queueDisabled` depends on `composerText.trim().length > 0`. An action that presses stop
+// with text in the box presses queue and measures nothing.
+// - Radix keeps a collapsed Collapsible's content element mounted for its animation, so
+// "the reasoning pane is open" cannot be read from the content element's presence. It is read
+// from `data-state` on the root, which is what Radix actually toggles.
+
+(() => {
+ if (window.__sb && window.__sb.dom) return;
+ window.__sb = window.__sb || {};
+
+ const q = (sel, root) => (root || document).querySelector(sel);
+ const qa = (sel, root) => Array.from((root || document).querySelectorAll(sel));
+
+ // Accessible name for the app's TooltipIconButton, which renders the label in a visually
+ // hidden span rather than an aria-label. `getByRole(name:)` on the driver side would do this,
+ // but the actions run inside one page.evaluate so they need it here.
+ const nameOf = (el) => {
+ if (!el) return "";
+ const aria = el.getAttribute("aria-label");
+ if (aria) return aria.trim();
+ const sr = el.querySelector(".aui-sr-only, .sr-only");
+ if (sr && sr.textContent) return sr.textContent.trim();
+ return (el.textContent || "").trim();
+ };
+
+ const byName = (sel, name, root) =>
+ qa(sel, root).find((el) => nameOf(el) === name) || null;
+
+ const D = {
+ threadRoot() {
+ return q(".aui-thread-root") || document.body;
+ },
+ viewport() {
+ return q(".aui-thread-viewport");
+ },
+ composer() {
+ return q('textarea[aria-label="Message input"]');
+ },
+ composerText() {
+ const el = D.composer();
+ return el ? el.value : null;
+ },
+ sendButton() {
+ return q('button[aria-label="Send message"]');
+ },
+ stopButton() {
+ // aria-label="Stop generating" is the chat one; the class also covers stop-queued and
+ // stop-research, which are different buttons for different runs.
+ return q('button[aria-label="Stop generating"]');
+ },
+ queueButton() {
+ return q('button[aria-label="Queue message"]');
+ },
+ isRunning() {
+ return Boolean(D.stopButton() || D.queueButton());
+ },
+ messages() {
+ return qa("[data-role]");
+ },
+ messageCount() {
+ return qa("[data-role]").length;
+ },
+ assistantMessages() {
+ return qa('[data-role="assistant"]');
+ },
+ lastAssistantMessage() {
+ const all = qa('[data-role="assistant"]');
+ return all.length ? all[all.length - 1] : null;
+ },
+
+ // ── reasoning ────────────────────────────────────────────────
+ reasoningRoots() {
+ return qa('[data-slot="reasoning-root"]');
+ },
+ reasoningTriggers() {
+ return qa('[data-slot="reasoning-trigger"]');
+ },
+ reasoningOpenCount() {
+ // data-state on the ROOT, not the presence of the content element: Radix keeps collapsed
+ // content mounted for the animation, so a presence check reads every pane as open.
+ return qa('[data-slot="reasoning-root"][data-state="open"]').length;
+ },
+
+ // ── action bar ───────────────────────────────────────────────
+ actionBar(message) {
+ const m = message || D.lastAssistantMessage();
+ if (!m) return null;
+ return q(".aui-assistant-action-bar-root", m) || q(".aui-user-action-bar-root", m);
+ },
+ actionButton(name, message) {
+ const bar = D.actionBar(message);
+ if (bar) {
+ const inBar = byName("button", name, bar);
+ if (inBar) return inBar;
+ }
+ const m = message || D.lastAssistantMessage();
+ return m ? byName("button", name, m) : null;
+ },
+ // Hover the last assistant message, which is what mounts its action bar. `autohide` on the
+ // bar unmounts it on every message that is not hovered, so a control read without this is
+ // read out of a tree it was never in.
+ hoverLastAssistantMessage() {
+ const m = D.lastAssistantMessage();
+ if (m) {
+ m.dispatchEvent(
+ new PointerEvent("pointerover", { bubbles: true, pointerType: "mouse" })
+ );
+ }
+ return m;
+ },
+
+ // WAIT for one of the action bar's controls, up to `waitMs`, instead of sampling for it once.
+ //
+ // WHY A WAIT AND NOT A SAMPLE, which is the whole point of this method. The assistant action
+ // bar is mounted with `hideWhenRunning` (thread.tsx), so while the thread is generating there
+ // is no Copy, no Delete and no More ANYWHERE in the tree -- not hidden, not disabled, absent.
+ // Every action that needs one of them is therefore scheduled after a `send_turn`, on the
+ // arithmetic that the follow-up turn drains in FOLLOW_UP_CHARS / the field cadence. That
+ // arithmetic is the NOMINAL drain: it assumes the pacer's cadence is the binding constraint,
+ // and at the 100K rung it is not -- the renderer is, so the reply arrives about 25% later
+ // than the cadence says, and the slot can open with the last few chunks still in flight.
+ //
+ // Measured on the CI runner, from the payload of the run that failed the liveness gate: the
+ // `message_menu` window opened at 32,000ms, took ONE more SSE chunk inside itself, and the
+ // reply stopped growing 71 characters later, inside the same window. The reply settled about
+ // a third of a second after the instant the action sampled the DOM. A single sample turns
+ // that third of a second into `NOT RUN -- no More button on the last assistant message`,
+ // which reads like a missing control and is really a clock being read too early.
+ //
+ // So the control is waited for. The wait is bounded, it is reported, and it happens BEFORE
+ // any measurement clock starts, so a cell that had to wait is not a cell whose open latency
+ // was inflated by the waiting. `fixture/selftest/test_studiobench_rung_plan.py` already
+ // asserts this behaviour in prose -- "a slot may legitimately open a little before the
+ // follow-up finishes and wait inside its own budget" -- and this is the code that makes the
+ // sentence true.
+ //
+ // Polling per paint, not per millisecond, and scoped: `actionButton` searches inside the last
+ // assistant message, so this is O(that message) rather than O(the thread), and it stops the
+ // instant the control appears (0 iterations on every cell where the reply has settled, which
+ // is the normal case).
+ async waitForActionButton(name, waitMs, everyMs) {
+ const started = performance.now();
+ const budget = Math.max(0, Number(waitMs) || 0);
+ const nextPaint = () =>
+ window.__sbNextPaint
+ ? window.__sbNextPaint()
+ : new Promise((r) => setTimeout(r, Number(everyMs) || 16));
+ D.hoverLastAssistantMessage();
+ let el = D.actionButton(name);
+ while (!el && performance.now() - started < budget) {
+ await nextPaint();
+ // Re-hovered every pass: the bar unmounts again whenever the message re-renders, which
+ // during a stream is on every chunk.
+ D.hoverLastAssistantMessage();
+ el = D.actionButton(name);
+ }
+ return {
+ el,
+ waitedMs: Math.round((performance.now() - started) * 10) / 10,
+ // Recorded whether the control was found or not. A miss with `running: true` is the
+ // reply not having settled; a miss with `running: false` is a control that is genuinely
+ // not there, and those are different bugs.
+ running: D.isRunning(),
+ };
+ },
+ openMenu() {
+ return q(".aui-action-bar-more-content");
+ },
+ openMenuItemCount() {
+ const menu = D.openMenu();
+ return menu ? qa(".aui-action-bar-more-item", menu).length : 0;
+ },
+
+ // ── settings ─────────────────────────────────────────────────
+ settingsTrigger() {
+ return q('button[aria-label="Settings"]');
+ },
+ settingsDialog() {
+ return q('[data-slot="dialog-content"].settings-surface');
+ },
+ settingsScroller() {
+ const dlg = D.settingsDialog();
+ if (!dlg) return null;
+ return q("main > div.hover-scrollbar.overflow-y-auto", dlg) || q("main div.overflow-y-auto", dlg);
+ },
+ settingsTab(id) {
+ return q('[data-testid="settings-tab-' + id + '"]');
+ },
+
+ // ── model picker ─────────────────────────────────────────────
+ modelTrigger() {
+ return q("button.unsloth-model-selector-trigger");
+ },
+ modelMenu() {
+ return q(".unsloth-model-selector-menu");
+ },
+ modelOptions() {
+ const menu = D.modelMenu();
+ // No role="option", no data-model-id: the rows are plain buttons with utility classes, so
+ // this is the only available handle and it is recorded as the weak point it is.
+ return menu ? qa("button", menu) : [];
+ },
+ currentModelLabel() {
+ const t = D.modelTrigger();
+ return t ? (t.textContent || "").trim() : null;
+ },
+
+ // ── composer plus menu / attachments ─────────────────────────
+ plusButton() {
+ return q('button[aria-label="Tools and attachments"]') || q('[data-tour="chat-plus-menu"]');
+ },
+ menuItemByText(text) {
+ return (
+ qa('[role="menuitem"], [role="option"], .aui-action-bar-more-item').find((el) =>
+ (el.textContent || "").trim().toLowerCase().includes(text.toLowerCase()),
+ ) || null
+ );
+ },
+
+ // ── sidebar / threads ────────────────────────────────────────
+ threadRows() {
+ return qa('[data-testid="recent-thread"]');
+ },
+ threadRow(id) {
+ return q('[data-thread-id="' + id + '"]');
+ },
+ newChatButton() {
+ return q('button[aria-label="New chat"].sidebar-header-action') || q('button[aria-label="New chat"]');
+ },
+
+ // ── code blocks ──────────────────────────────────────────────
+ codeCopyButtons() {
+ return qa('button[title="Copy code"]');
+ },
+
+ // ── census ───────────────────────────────────────────────────
+ counts() {
+ const started = performance.now();
+ const out = {
+ elements: document.getElementsByTagName("*").length,
+ messages: qa("[data-role]").length,
+ assistant_messages: qa('[data-role="assistant"]').length,
+ reasoning_panes: qa('[data-slot="reasoning-root"]').length,
+ reasoning_open: qa('[data-slot="reasoning-root"][data-state="open"]').length,
+ code_blocks: qa("pre").length,
+ // Shiki spans. THE span density check: the field capture ran 90,262 characters against
+ // 16,186 spans, i.e. 5.6 characters per span, and a fixture that does not reproduce that
+ // is not measuring the same highlighter load per character.
+ highlight_spans: qa("pre span").length,
+ // WHERE the spans live, not just how many. A collapsed reasoning pane UNMOUNTS its
+ // children, so a thread with the same text can carry wildly different DOM depending on
+ // how that text got there. Without this split, "seeded has 20% fewer spans" is a number
+ // with three possible explanations and no way to choose between them.
+ // Tool components. TWO markers, because there are two renderers: a known tool gets a
+ // `tool-group-root`, and anything else gets the generic `tool-fallback-root` ("Used
+ // tool"). Counting only the first read ZERO on a thread that visibly contained tool
+ // blocks -- the second wrong selector in a row for this one component, and both times the
+ // reading was a confident zero rather than an error.
+ tool_groups: qa('[data-slot="tool-group-root"]').length
+ + qa('[data-slot="tool-fallback-root"]').length,
+ tool_groups_open: qa('[data-slot="tool-group-content"]').length
+ + qa('[data-slot="tool-fallback-content"]').length,
+ reasoning_spans: qa('[data-slot="reasoning-root"] pre span').length,
+ reasoning_code_blocks: qa('[data-slot="reasoning-root"] pre').length,
+ content_spans:
+ qa("pre span").length - qa('[data-slot="reasoning-root"] pre span').length,
+ content_code_blocks: qa("pre").length - qa('[data-slot="reasoning-root"] pre').length,
+ // Carried in the census so the peak occupancy and the character count come from the
+ // SAME reading. Two separate reads, taken either side of a destructive action, disagree.
+ assistant_chars: D.assistantChars(),
+ viewport_scroll_height: (D.viewport() || {}).scrollHeight || null,
+ viewport_client_height: (D.viewport() || {}).clientHeight || null,
+ };
+ out.census_cost_ms = Math.round((performance.now() - started) * 100) / 100;
+ return out;
+ },
+
+ // Characters of assistant text currently in the DOM. Used for the seeded-vs-streamed
+ // equivalence check and for chars-per-span.
+ assistantChars() {
+ let n = 0;
+ for (const m of qa('[data-role="assistant"]')) n += (m.textContent || "").length;
+ return n;
+ },
+ };
+
+ window.__sb.dom = D;
+})();
diff --git a/tests/studio/studiobench/scene/parity.js b/tests/studio/studiobench/scene/parity.js
new file mode 100644
index 00000000000..780179a4094
--- /dev/null
+++ b/tests/studio/studiobench/scene/parity.js
@@ -0,0 +1,299 @@
+// 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: a structural signature of the rendered thread, taken at the close of every action
+// window on BOTH arms of an A/B.
+//
+// WHY THIS AND NOT SCREENSHOTS. The screenshot parity pair (scripts PR 217) is the right artefact
+// for a human reader of a pull request: it shows the surface, side by side, and a person checks it
+// against `expect`. What it cannot do is breadth. Each pair costs two isolated installs, shows one
+// surface, and needs somebody to open the composite. Eighteen PRs across eighteen action surfaces
+// is 324 composites and nobody will look at them.
+//
+// This runs inside a comparison the tool is ALREADY doing. studiobench drives both arms through
+// the same eighteen scripted actions against a byte-identical seeded thread inside one session, so
+// the two DOMs are already meant to agree. Digesting them costs one `evaluate` per slot and turns
+// "the UI is unchanged" from a claim into a per-action assertion. It is the cheap wide net; the
+// screenshot pair stays the deep, human-readable one for the surfaces that matter most.
+//
+// ── WHAT THIS DIGEST CAN AND CANNOT SEE ──────────────────────────────────────────────────────
+//
+// Read this before quoting a passing parity check at anybody. The digest is a serialisation of the
+// DOM, so its sensitivity is exactly the DOM and nothing else.
+//
+// IT SEES: tag structure and nesting, element order, every attribute name, every attribute value
+// that is not on the volatile list below (so `class`, `data-slot`, `data-state`, `data-role`,
+// `aria-hidden`, `hidden`, `disabled`, `role`, `title`, `alt`, `placeholder`), and all text content
+// after time normalisation. Added elements, removed elements, reordered siblings, retitled buttons
+// and flipped states all move the digest.
+//
+// IT DOES NOT SEE, and a green parity check asserts NOTHING about any of these:
+// - CSS coming from a stylesheet. A class name is compared as a STRING. If `.aui-md-p` changes
+// its margin in a `.css` file, every class list is identical and the digest is identical while
+// the page reflows. Only the bounded computed-style probe below sees any of this, and it sees
+// three properties on at most a few dozen elements.
+// - Computed layout: geometry, sizes, positions, scroll extents, whether anything overflows or
+// is clipped, whether two elements overlap.
+// - Colour, typography, borders, shadows, opacity, transforms, animation.
+// - Raster content: images, canvas, video, SVG paint. An `<img>` is compared by its attributes,
+// and its `src` is normalised (see below), so a DIFFERENT PICTURE at the same normalised URL
+// is invisible.
+// - Anything outside the thread root and the overlay selectors: the sidebar, the header, toasts.
+// - Anything the DOM does not carry at all: focus ring appearance, caret position, text
+// 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.
+//
+// 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.
+//
+// ── 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
+// than no digest: it trains you to ignore it. Every entry here was OBSERVED to differ in a
+// base-vs-base null control; nothing is normalised on suspicion.
+//
+// generated ids Radix mints `radix-:r1a:` per mount, and aria-controls/labelledby point at
+// them. They differ between two runs of one build.
+// rendered durations the action bar prints things like `295ms`. PR 217 hit exactly this on
+// unslothai/unsloth#9054: a 295 vs 310 difference that is wall clock, not
+// content. Any number immediately followed by a time unit is collapsed.
+// relative times "2 minutes ago" moves on its own.
+// scroll state `--aui-scroll-stabilizer` and transform offsets encode where the thread
+// happens to be scrolled, which the film varies deliberately.
+// record identifiers thread ids, message ids and attachment ids are minted by the BACKEND when
+// the fixture seeds the thread. The two arms of an A/B are two separate
+// Studio installs with two separate databases, so these can never agree and
+// carry no information about the frontend.
+// absolute URLs `src`/`href` carry the arm's own origin, and the two arms are on two
+// ports by construction. `http://127.0.0.1:5830/x` and `...:5831/x` are the
+// same asset. Origins are stripped; the PATH is kept and still compared.
+// blob and data URLs an uploaded image is addressed by a per-mount `blob:` UUID.
+//
+// WHAT IS DELIBERATELY KEPT. Tag structure, `data-slot`, `data-state`, `data-role`, `aria-hidden`,
+// `hidden`, `disabled`, the class list, and all text content. `data-state` in particular: whether
+// a reasoning pane reads open or closed IS the UI, and a perf change that quietly flips it is the
+// exact defect this is meant to catch.
+
+(() => {
+ if (window.__sb && window.__sb.parity) return;
+ window.__sb = window.__sb || {};
+
+ // Attributes whose VALUE is volatile between two runs of the same build. The attribute's
+ // presence is still recorded; only the value is dropped.
+ const VOLATILE_ATTRS = new Set([
+ "id", "for", "aria-controls", "aria-labelledby", "aria-describedby", "aria-activedescendant",
+ "style", "data-radix-scroll-area-viewport", "data-testid-instance",
+ // Backend-minted record ids. Two arms are two installs with two databases.
+ "data-thread-id", "data-message-id", "data-attachment-id", "data-part-id", "data-run-id",
+ "data-tool-call-id", "data-checkpoint-id",
+ ]);
+
+ // Attributes that carry no rendered meaning at all.
+ const IGNORED_ATTRS = new Set(["data-react-checksum", "data-reactroot"]);
+
+ // 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"]);
+
+ // A UUID, or a long hex run. Both are how this app spells "an id the server just made up".
+ const ID_RE = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b|\b[0-9a-f]{16,}\b/gi;
+
+ const normUrl = (s) =>
+ (s || "")
+ // blob:/data: URLs address a per-mount object. Nothing in them survives a reload.
+ .replace(/^blob:[^\s]*$/i, "#BLOB")
+ .replace(/^data:([^;,]*)[^\s]*$/i, "#DATA:$1")
+ // Strip scheme://host:port, keep the path. `/assets/index-a1b2.js` still compares.
+ .replace(/\b[a-z]+:\/\/[^/\s]+/gi, "")
+ .replace(ID_RE, "#ID");
+
+ const normText = (s) =>
+ (s || "")
+ // `295ms`, `1.2 s`, `3 min` -> a placeholder. Wall clock, not content.
+ .replace(/\b\d+(\.\d+)?\s?(ms|s|sec|secs|second|seconds|min|mins|minute|minutes|hour|hours|day|days)\b/gi, "#T")
+ // "2 minutes ago" style relatives that survived the above.
+ .replace(/\b(just now|a few seconds ago|yesterday)\b/gi, "#T")
+ // Absolute timestamps.
+ .replace(/\b\d{1,2}:\d{2}(:\d{2})?\s?(am|pm)?\b/gi, "#T")
+ // Backend-minted ids that reach the DOM as TEXT rather than as an attribute.
+ .replace(ID_RE, "#ID")
+ .replace(/\s+/g, " ")
+ .trim();
+
+ // FNV-1a, 32 bit, expressed as unsigned hex. Not cryptographic: this is a change detector, and
+ // the pair being compared is two runs of one page rather than an adversary.
+ const hash = (str) => {
+ let h = 0x811c9dc5;
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i);
+ h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0;
+ }
+ return h.toString(16).padStart(8, "0");
+ };
+
+ const attrValue = (el, name) => {
+ const raw = el.getAttribute(name);
+ if (URL_ATTRS.has(name)) return normUrl(raw);
+ return normText(raw);
+ };
+
+ const signature = (root) => {
+ if (!root) return "";
+ const parts = [];
+ const walk = (el, depth) => {
+ // A depth cap is a TRUNCATION, and a truncated signature that reads like a complete one is
+ // exactly the silent false negative this instrument exists to rule out. The marker is left
+ // in the signature so anything deeper is visible as "not walked" rather than as "absent".
+ if (depth > 40) { parts.push("<!depth-cap>"); return; }
+ parts.push("<" + el.tagName.toLowerCase());
+ const names = [];
+ for (const attr of el.attributes) {
+ if (IGNORED_ATTRS.has(attr.name)) continue;
+ names.push(attr.name);
+ }
+ names.sort();
+ for (const name of names) {
+ if (VOLATILE_ATTRS.has(name)) {
+ parts.push(" " + name + "=*");
+ } else {
+ parts.push(" " + name + "=" + attrValue(el, name));
+ }
+ }
+ parts.push(">");
+ for (const child of el.childNodes) {
+ if (child.nodeType === 3) {
+ const t = normText(child.nodeValue);
+ if (t) parts.push(t);
+ } else if (child.nodeType === 1) {
+ walk(child, depth + 1);
+ }
+ }
+ parts.push("</" + el.tagName.toLowerCase() + ">");
+ };
+ walk(root, 0);
+ return parts.join("");
+ };
+
+ // The bounded computed-style probe. THREE properties on at most `STYLE_CAP` elements, and its
+ // digest is reported SEPARATELY from the structural one rather than folded into it.
+ //
+ // Separate on purpose. `getComputedStyle` reads post-stylesheet, post-animation state, so it is
+ // the only part of this file that can see a `.css` change at all -- and for the same reason it
+ // is the part most likely to be caught mid-transition and differ between two runs of one build.
+ // Folding it into `digest` would put the whole instrument's credibility on its least stable
+ // reading. Kept apart, a structural mismatch stays a hard signal and a style mismatch is an
+ // advisory the caller can weigh.
+ //
+ // `display` and `visibility` because they are how CSS makes something disappear without touching
+ // the DOM. `pointer-events` because an overlay that stops or starts swallowing clicks is a real,
+ // shipped class of defect here and leaves no structural trace at all.
+ const STYLE_CAP = 64;
+ const STYLE_PROPS = ["display", "visibility", "pointer-events"];
+ const STYLE_SELECTORS = [
+ '[data-role]', '[data-slot="reasoning-root"]', '[data-slot="tool-group-root"]',
+ ".aui-thread-viewport", ".aui-composer-root", 'button[aria-label="Send message"]',
+ 'button[aria-label="Stop generating"]', '[data-slot="dialog-content"]', '[role="menu"]',
+ "[data-radix-popper-content-wrapper]",
+ ];
+
+ const styleProbe = () => {
+ const seen = new Set();
+ const parts = [];
+ let n = 0;
+ let capped = false;
+ for (const sel of STYLE_SELECTORS) {
+ for (const el of document.querySelectorAll(sel)) {
+ if (seen.has(el)) continue;
+ seen.add(el);
+ if (n >= STYLE_CAP) { capped = true; continue; }
+ n += 1;
+ const cs = window.getComputedStyle(el);
+ parts.push(sel + "#" + n);
+ for (const prop of STYLE_PROPS) parts.push(":" + prop + "=" + cs.getPropertyValue(prop));
+ parts.push(";");
+ }
+ }
+ const sig = parts.join("");
+ // `capped` travels with the reading. A style digest taken over the first 64 of 300 elements
+ // is a partial reading, and a partial reading that does not say so reads as a complete one.
+ return { digest: hash(sig), chars: sig.length, elements: n, capped, props: STYLE_PROPS, sig };
+ };
+
+ const D = () => (window.__sb.dom || {});
+
+ 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.
+ normText,
+ normUrl,
+ signature,
+ hash,
+
+ // One digest for the whole thread, plus a digest PER MESSAGE so a mismatch says which message
+ // moved rather than only that something did. A whole-page digest that differs is a fact you
+ // cannot act on; the per-message row is what makes it a bug report.
+ //
+ // `opts.raw` additionally returns the signature TEXT. It is large, so it is off by default and
+ // used only by the null-control hunt, which has to name the volatile rather than count it.
+ capture(opts) {
+ const want_raw = Boolean(opts && opts.raw);
+ try {
+ const dom = D();
+ const rootFn = dom.threadRoot;
+ const found = rootFn ? rootFn() : null;
+ // WHICH root was digested travels with the digest. `threadRoot()` falls back to
+ // `document.body`, which digests the sidebar, the header and every relative timestamp in
+ // them. Two arms that silently digested different roots would still produce two
+ // comparable-looking hashes, and the mismatch would be read as a UI change.
+ const isThread = Boolean(found && found !== document.body &&
+ found.classList && found.classList.contains("aui-thread-root"));
+ const root = found || document.body;
+ const whole = signature(root);
+ const messages = [];
+ const nodes = (dom.messages && dom.messages()) || [];
+ for (let i = 0; i < nodes.length; i++) {
+ const sig = signature(nodes[i]);
+ const row = {
+ i,
+ role: nodes[i].getAttribute("data-role") || "?",
+ digest: hash(sig),
+ chars: sig.length,
+ };
+ if (want_raw) row.raw = sig;
+ messages.push(row);
+ }
+ // Surfaces that live OUTSIDE the thread root and are therefore invisible to the digest
+ // above: an open dialog, an open menu, the model picker. A perf change that alters a
+ // popover would otherwise pass a thread-only parity check.
+ const overlays = [];
+ for (const sel of ['[data-slot="dialog-content"]', '[role="menu"]', '[role="dialog"]',
+ ".unsloth-model-selector-menu", "[data-radix-popper-content-wrapper]"]) {
+ for (const el of document.querySelectorAll(sel)) {
+ const sig = signature(el);
+ const row = { sel, digest: hash(sig), chars: sig.length };
+ if (want_raw) row.raw = sig;
+ overlays.push(row);
+ }
+ }
+ const styles = styleProbe();
+ if (!want_raw) delete styles.sig;
+ const out = {
+ parity_attempted: true,
+ root_kind: isThread ? "thread" : "body",
+ digest: hash(whole),
+ chars: whole.length,
+ messages,
+ overlays,
+ styles,
+ };
+ if (want_raw) out.raw = whole;
+ return out;
+ } catch (err) {
+ // A failure is reported as a failure. A parity check that returns an empty digest on
+ // error would read as "everything matched", which is the single worst thing it could do.
+ return { parity_attempted: false, reason: String(err && err.message ? err.message : err) };
+ }
+ },
+ };
+})();
diff --git a/tests/studio/studiobench/scene/schedule.py b/tests/studio/studiobench/scene/schedule.py
new file mode 100644
index 00000000000..5c49e52c99c
--- /dev/null
+++ b/tests/studio/studiobench/scene/schedule.py
@@ -0,0 +1,374 @@
+# 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 scene: a FIXED-DURATION FILM, slot-scheduled on wall clock.
+
+THIS IS NOT A TASK LIST, and the difference is the whole point.
+
+A sequential script runs action 1, waits for it, runs action 2. On a slow machine each action
+takes longer, so the session is longer, so the stream has delivered more characters by the time
+action 7 runs, so action 7 happens against a bigger thread, at a different point in the stream,
+with a different amount of content mounted. The slow machine has taken a DIFFERENT PATH through a
+DIFFERENT-LENGTH session, and none of its columns are comparable with the fast machine's. Every
+number is then a mixture of "this machine is slower" and "this machine measured something else",
+and no amount of care downstream can separate them.
+
+So every action has a fixed `(t_start_ms, budget_ms)` on the session clock. The scheduler waits
+until `t_start_ms`, runs the action with the remaining budget, and moves on. A machine too slow to
+reach a slot in time records `slot_missed: true` and the film rolls on. Both machines see the same
+thread at the same point in the same stream, and a missed slot is an honest, first-class reading
+of "this machine could not do this here", which is exactly the finding worth having.
+
+The deficit-scheduled pacer is the other half of this. Slots are only meaningful if the stream's
+own progress is a function of wall clock, which is what deficit scheduling buys.
+"""
+
+from __future__ import annotations
+
+import time
+from dataclasses import dataclass, field
+from typing import Any, Callable, Optional
+
+from ..runtime.types import ActionContext, ActionResult, Cell, Slot, Window, not_run
+from . import default_budget_ms, get_action
+
+
+@dataclass
+class Scene:
+ name: str
+ slots: list[Slot]
+
+ @property
+ def duration_ms(self) -> int:
+ return max((s.t_start_ms + s.budget_ms for s in self.slots), default = 0)
+
+ def scaled(self, factor: float) -> "Scene":
+ """A scene of the same SHAPE over a longer film.
+
+ Used to give a big rung more room without changing the order or the relative spacing of
+ the actions, so a 1K scene and a 1M scene are the same film at different speeds rather
+ than two different films.
+ """
+ return Scene(
+ name = self.name,
+ slots = [
+ Slot(
+ action = s.action,
+ t_start_ms = int(s.t_start_ms * factor),
+ budget_ms = int(s.budget_ms * factor),
+ args = s.args,
+ required = s.required,
+ )
+ for s in self.slots
+ ],
+ )
+
+
+def _slots(spec: list[tuple[str, int, Optional[int]]]) -> list[Slot]:
+ return [
+ Slot(
+ action = name,
+ t_start_ms = start,
+ budget_ms = budget if budget is not None else default_budget_ms(name),
+ )
+ for name, start, budget in spec
+ ]
+
+
+# The standard film. Ordered so that the actions that must happen DURING generation come first,
+# then the ones that need a finished reply, then the destructive ones last -- delete and reopen
+# change the thread, so anything after them would be measuring a different thread.
+#
+# Timings are offsets from the moment the send button was pressed.
+STANDARD = Scene(
+ name = "standard",
+ slots = _slots(
+ [
+ # ── during generation ────────────────────────────────────────
+ ("scroll_during_generation", 3_000, 8_000),
+ ("keystroke", 12_000, 6_000),
+ # 12s. The tail is a JITTERED clip capped at 6,000 characters, so its drain time varies from
+ # about 14s to 18s across the ladder, and a during-generation slot has to open before the
+ # SHORTEST of those, not the longest. At 19s, then 15s, this slot ran against a finished reply
+ # at the top rung while still being labelled "during generation".
+ ("scroll_during_generation", 12_000, 8_000),
+ ("stop_generation", 28_000, 8_000),
+ # ── after the reply is complete ──────────────────────────────
+ ("scroll_after", 38_000, 8_000),
+ ("reasoning_toggle", 47_000, 12_000),
+ ("send_turn", 60_000, 12_000),
+ ("message_menu", 73_000, 12_000),
+ ("copy_markdown", 86_000, 6_000),
+ ("select_text", 93_000, 6_000),
+ ("send_turn", 100_000, 12_000),
+ # 35s, not 10s. Selecting and copying the whole thread at the 1M rung took 27,690 ms -- two
+ # million characters through the clipboard -- so it blew a 10s budget by nearly three times
+ # and the OVERRUN pushed the next slot past its own start, which was recorded as
+ # `composer_fill: slot missed`. The 1M cell lost two slots that way and the cause looked like
+ # a slow machine rather than one under-budgeted action.
+ #
+ # This film is the one the 500K and 1M rungs use, so its budgets are sized from what those
+ # rungs actually cost, not from what the small ones do. At 100K the same action takes 2,476 ms.
+ ("select_all_copy", 113_000, 35_000),
+ ("composer_fill", 149_000, 10_000),
+ ("model_change", 160_000, 10_000),
+ ("settings", 171_000, 12_000),
+ ("image_upload", 184_000, 12_000),
+ # ── destructive, last ────────────────────────────────────────
+ # 22,382 ms at 1M, so 30s stands.
+ ("thread_reopen", 197_000, 30_000),
+ ("delete_message", 228_000, 15_000),
+ ]
+ ),
+)
+
+# The quick film. The SAME fifteen actions in the same order -- a tier that drops actions cannot be
+# compared with one that does not -- on a shorter clock, for the small rungs where the stream is
+# over in seconds.
+QUICK = Scene(
+ name = "quick",
+ slots = _slots(
+ [
+ # BUDGETS ARE SIZED FROM MEASURED ACTION COST, not guessed. At the 100K rung -- the largest
+ # this film is used for -- every action finished inside 2.5 s: select_all_copy 2,476 ms,
+ # thread_reopen 2,234 ms, reasoning_toggle 1,788 ms, keystroke 1,041 ms, everything else under
+ # 500 ms. The budgets below carry roughly 2.5x headroom over those.
+ #
+ # The film previously ran 162 s while its actions used 6.4 s, so 96% of it was waiting for the
+ # next slot to open. That waiting is not free: it is multiplied by every cell, every arm and
+ # every repetition, and an A/B at four reps is sixteen films. Halving the film halves the cost
+ # of every comparison this tool exists to make.
+ #
+ # What CANNOT be compressed is the stream phase. The opening turn drains in 12 to 18 s, the
+ # during-generation slots have to open inside the shortest of those (14.1 s at 1M) and the
+ # after-generation slots have to open after the longest (17.8 s at 100K). The gap between
+ # 12 s and 20 s below is that constraint, not slack.
+ ("scroll_during_generation", 1_500, 2_500),
+ ("keystroke", 5_000, 3_000),
+ ("scroll_during_generation", 9_500, 2_500),
+ ("stop_generation", 20_000, 3_000),
+ ("scroll_after", 23_500, 2_500),
+ ("reasoning_toggle", 26_500, 4_500),
+ ("send_turn", 31_500, 4_000),
+ ("message_menu", 36_000, 3_000),
+ ("copy_markdown", 39_500, 2_500),
+ ("select_text", 42_500, 2_000),
+ ("send_turn", 45_000, 4_000),
+ ("select_all_copy", 49_500, 6_000),
+ ("composer_fill", 56_000, 2_500),
+ ("model_change", 59_000, 2_500),
+ ("settings", 62_000, 2_500),
+ ("image_upload", 65_000, 3_000),
+ ("thread_reopen", 68_500, 6_000),
+ ("delete_message", 75_000, 2_500),
+ ]
+ ),
+)
+
+# The fast film. FOR ITERATION, NOT FOR REPORTING -- see the banner the CLI prints.
+#
+# Same eighteen actions in the same order as the other two films, because a tier that drops
+# actions cannot tell you that your fix broke the one it dropped. What changes is the waiting.
+#
+# Budgets are sized from the costs this tool MEASURED at the 100K rung over eight cells of a null
+# control, at roughly 1.5x rather than the 2.5x the quick film carries:
+#
+# thread_reopen 3,163 ms (close 2,205 + reopen 958) select_all_copy 2,454 ms
+# reasoning_toggle 2,250 ms (open 1,688 + close 563) keystroke 1,002 ms
+# settings 485 ms model_change 483 ms scroll 466 ms stop 335 ms copy 204 ms
+#
+# Everything else is under 100 ms. The eighteen actions cost about 12 s of real work; the standard
+# film spends 243 s and the quick film 77.5 s to deliver them. At 1.5x headroom an action that
+# overruns records `slot_missed` instead of silently pushing the next slot, which is the honest
+# failure mode and is exactly what the fixed-duration design exists to provide.
+#
+# WHAT CANNOT BE COMPRESSED, and why this film is 47 s rather than 20 s: the opening turn streams
+# a 6,000 character tail at field cadence (328.8 chars/s), so it drains in 14 to 18 s. The
+# during-generation slots must open inside the SHORTEST of those and the after-generation slots
+# after the LONGEST. The gap between 8 s and 19 s below is that constraint, not slack. Shrinking
+# it means shrinking the streamed tail, which changes the load being measured -- and streaming
+# frame cost at length is the thing most of these fixes are about.
+FAST = Scene(
+ name = "fast",
+ slots = _slots(
+ [
+ # 18.2 s, not 8 s. `stop_generation` starts and stops its OWN turn, so opening it while the
+ # opening tail is still draining starts a second turn on top of the first and truncates the
+ # reply being measured -- which is the defect that made the seeded-vs-streamed equivalence
+ # check read a false 20% drift earlier in this project. The worst-case drain across the ladder
+ # is 17.8 s, and the packing test in fixture/selftest holds every film to it.
+ #
+ # THE SECOND PACKING CONSTRAINT, learned the expensive way. `send_turn` starts a FOLLOW-UP
+ # turn, and a follow-up is FOLLOW_UP_CHARS (1,500) at field cadence, so it streams for 4.6 s.
+ # Anything needing a SETTLED reply -- the action bar's More and Copy buttons, select-all,
+ # delete -- does not exist while that turn is running. The first fast film opened
+ # `message_menu` 1.7 s after a `send_turn` and it recorded `NOT RUN: no More button` on
+ # 312 of 312 attempts across a 36 job sweep, silently removing the four actions that carry
+ # the largest known effect in this codebase (the message menu is the 19x one). Every
+ # post-send slot below clears 4.6 s, and test_settled_actions_open_after_the_follow_up_drains
+ # now fails any film that does not.
+ ("scroll_during_generation", 1_500, 1_200),
+ ("keystroke", 3_000, 1_800),
+ ("scroll_during_generation", 6_000, 1_200),
+ ("stop_generation", 18_200, 3_000),
+ ("scroll_after", 21_500, 1_200),
+ ("reasoning_toggle", 23_000, 3_500),
+ ("send_turn", 26_700, 1_500),
+ ("message_menu", 32_000, 800),
+ ("copy_markdown", 33_000, 600),
+ ("select_text", 33_800, 400),
+ ("send_turn", 34_400, 1_500),
+ ("select_all_copy", 39_500, 4_000),
+ ("composer_fill", 43_700, 600),
+ ("model_change", 44_500, 1_000),
+ ("settings", 45_700, 1_200),
+ ("image_upload", 47_100, 800),
+ # thread_reopen 6.5 s and delete 2.5 s, not 5 s and 0.6 s. Measured at 100K the pair
+ # costs about 3.2 s, but the ACTION overran its 5 s window and pushed the last slot: the
+ # machine arrived at delete_message 834 ms after its 600 ms budget had already closed, so
+ # on a 36 job sweep delete recorded NOT EXERCISED on the base arm of every null-control
+ # cell. A last slot with no slack is a slot that measures nothing, and the film's own end
+ # is the one place an overrun has nowhere to go.
+ ("thread_reopen", 48_100, 6_500),
+ ("delete_message", 54_800, 2_500),
+ ]
+ ),
+)
+SCENES = {"fast": FAST, "quick": QUICK, "standard": STANDARD, "full": STANDARD}
+
+
+@dataclass
+class SceneRunner:
+ """Runs a scene against a live page, one window per slot."""
+
+ cell: Cell
+ page: Any
+ cdp: Any
+ dom: Any
+ recorder: Any
+ open_window: Callable[[str, str], Any]
+ log: Callable[[str], None]
+ base_args: dict = field(default_factory = dict)
+
+ def run(self, scene: Scene, t0: float) -> list[dict]:
+ """`t0` is the driver monotonic time the film started, i.e. when send was pressed."""
+ rows: list[dict] = []
+ for i, slot in enumerate(scene.slots):
+ # The GAP before this slot is itself a measured window. Without it, frame rate and
+ # blocked time would only ever be sampled inside actions -- and the quiet stretches
+ # between them, which is where the stream is doing its work unaided, would be the one
+ # part of the session nothing observed. Continuous coverage, no sampler thread, and
+ # no window ever overlaps another.
+ self._gap_window(f"stream:gap{i}", slot.t_start_ms, t0)
+ row = self._run_slot(slot, t0)
+ rows.append(row)
+ self.recorder.emit(row)
+ return rows
+
+ def _census(self) -> dict:
+ try:
+ return self.page.evaluate("() => window.__sb.dom.counts()")
+ except Exception as exc: # noqa: BLE001
+ return {"census_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.
+
+ Taken at the CLOSE of the action window, at the same moment as the census, so the digest
+ and the occupancy it should be read against come from one reading of one DOM.
+ """
+ try:
+ return self.page.evaluate("() => window.__sb.parity.capture()")
+ except Exception as exc: # noqa: BLE001
+ return {"parity_attempted": False, "reason": f"{type(exc).__name__}: {exc}"}
+
+ def _gap_window(self, name: str, until_ms: int, t0: float) -> None:
+ now_ms = (time.monotonic() - t0) * 1000
+ if until_ms - now_ms < 250:
+ return
+ with self.open_window(name, "stream") as window:
+ while (time.monotonic() - t0) * 1000 < until_ms:
+ time.sleep(min(0.2, max(0.01, (until_ms - (time.monotonic() - t0) * 1000) / 1000)))
+ window.note("waited_to_ms", until_ms)
+ window.note("census", self._census())
+
+ def _run_slot(self, slot: Slot, t0: float) -> dict:
+ entry = get_action(slot.action)
+ window_name = f"action:{slot.action}"
+ if entry is None:
+ return ActionResult(
+ ran = False, reason = f"no action named {slot.action!r} is registered"
+ ).row(slot.action, window_name, self.cell.cell_id)
+
+ now_ms = (time.monotonic() - t0) * 1000
+ # Wait for the slot to open. Sleeping in small steps rather than one long sleep so a
+ # renderer crash is noticed within a fifth of a second rather than at the end of the wait.
+ while now_ms < slot.t_start_ms:
+ time.sleep(min(0.2, (slot.t_start_ms - now_ms) / 1000))
+ now_ms = (time.monotonic() - t0) * 1000
+
+ deadline_ms = slot.t_start_ms + slot.budget_ms
+ remaining = deadline_ms - now_ms
+ if remaining <= 0:
+ # THE SLOT WAS MISSED. Not an error and not a slow timing: this machine could not get
+ # here in time, the film carries on, and the row says exactly that.
+ self.log(
+ f" slot missed: {slot.action} "
+ f"(due at {slot.t_start_ms}ms, reached at {now_ms:.0f}ms)"
+ )
+ return ActionResult(
+ ran = False,
+ slot_missed = True,
+ reason = (
+ f"the slot opened at {slot.t_start_ms}ms and this machine reached it at "
+ f"{now_ms:.0f}ms, past its {slot.budget_ms}ms budget"
+ ),
+ expect = {"t_start_ms": slot.t_start_ms, "reached_at_ms": round(now_ms, 1)},
+ ).row(slot.action, window_name, self.cell.cell_id)
+
+ with self.open_window(window_name, "action") as window:
+ ctx = ActionContext(
+ page = self.page,
+ cdp = self.cdp,
+ cell = self.cell,
+ window = window,
+ args = {**self.base_args, **slot.args},
+ budget_ms = int(remaining),
+ dom = self.dom,
+ log = self.log,
+ )
+ try:
+ result = entry.fn(ctx)
+ except Exception as exc: # noqa: BLE001
+ self.log(f" action {slot.action} raised: {type(exc).__name__}: {exc}")
+ 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
+ row = 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")
+ # An action that ran but overran its budget has pushed nothing (the next slot has its own
+ # absolute start), but it has overlapped the next one, so it is flagged.
+ row["over_budget_ms"] = round(over_ms, 1) if over_ms > 0 else 0.0
+ row["over_budget"] = over_ms > 0
+ status = "ran" if result.ran else "NOT RUN"
+ verdict = "" if result.expect_ok is not False else " EXPECT FAILED"
+ self.log(
+ f" {slot.action}: {status}{verdict}"
+ f"{'' if result.reason is None else ' -- ' + result.reason}"
+ )
+ return row
diff --git a/tests/studio/studiobench/scene/selftest/test_studiobench_action_bar_wait.py b/tests/studio/studiobench/scene/selftest/test_studiobench_action_bar_wait.py
new file mode 100644
index 00000000000..5e5177c1268
--- /dev/null
+++ b/tests/studio/studiobench/scene/selftest/test_studiobench_action_bar_wait.py
@@ -0,0 +1,235 @@
+# 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 action bar is WAITED for, not sampled for once.
+
+WHAT THIS PROTECTS, and it is a liveness property rather than a timing one. Studio mounts the
+assistant action bar with `hideWhenRunning` (studio/frontend/src/components/assistant-ui/
+thread.tsx), so while a turn is generating there is no Copy, no Delete and no More anywhere in the
+tree. Four scene actions need one of those controls, and every film schedules them after a
+`send_turn` on the arithmetic that the follow-up drains in FOLLOW_UP_CHARS over the field cadence.
+
+That arithmetic is a FLOOR, not an estimate. It assumes the pacer's cadence is the binding
+constraint, and at the 100K rung the renderer is: measured over six 100K cells, the follow-up kept
+streaming for 4.4 to 4.7 s after the send window closed, against a 4.59 s nominal drain and a
+5.3 s gap to the slot. The reply therefore settles within a few hundred milliseconds of the slot
+opening -- sometimes before it, sometimes after. The payload of the studiobench CI run that failed
+the liveness gate has the "after" case: one more SSE chunk arrived INSIDE the `message_menu`
+window and the reply stopped growing 71 characters later, in that same window.
+
+Sampled once, that third of a second reads as `NOT RUN -- no More button on the last assistant
+message`, the liveness gate exits 1, and the report names a missing control when what happened is
+a clock read too early. Both branches of the pull request that first hit it were red for it, and
+so was the branch it was cut from, which is what says this is the film's packing rather than
+anything either branch changed.
+
+WHY NODE AND THE REAL SOURCES. `MENU_JS` is the string that ships inside `scene/actions.py` and
+`waitForActionButton` is the function that ships inside `scene/dom.js`; a Python re-implementation
+of either would pass forever while the shipped pair drifted. So node runs both, against a shim of
+the handful of DOM globals they touch, with the ACTION BAR ARRIVING LATE -- which is the one thing
+that cannot be shimmed away, because it is the thing under test. No browser, no Studio, and if
+node is missing the test SKIPS rather than passing on a substitute.
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.scene.actions import ACTION_BAR_WAIT_MS, MENU_JS # noqa: E402
+
+DOM_JS = Path(__file__).resolve().parents[1] / "dom.js"
+
+#: The shim mounts the bar this long after the run starts, standing in for a follow-up turn whose
+#: last chunks land just after the slot opens. Comfortably inside `ACTION_BAR_WAIT_MS` and
+#: comfortably outside anything a single sample could catch.
+LATE_MOUNT_MS = 400
+
+HARNESS_JS = r"""
+const fs = require("fs");
+const domSrc = fs.readFileSync(process.argv[2], "utf8");
+const menuSrc = fs.readFileSync(process.argv[3], "utf8");
+const mountAfterMs = Number(process.argv[4]); // Infinity => the bar never mounts
+const waitMs = Number(process.argv[5]);
+
+// ── the smallest DOM these two files actually touch ────────────────────────────────────────────
+//
+// A node matches a selector when the selector is in its `sel` list. That is enough: dom.js reads
+// the app through a fixed, short list of selectors, and a real matcher here would only be a second
+// implementation to get wrong.
+const node = (sel, attrs, kids) => {
+ const self = {
+ sel: sel,
+ kids: kids || [],
+ getAttribute: (k) => (attrs && k in attrs ? attrs[k] : null),
+ textContent: (attrs && attrs.text) || "",
+ dispatchEvent: (ev) => { if (attrs && attrs.on) attrs.on(ev); return true; },
+ };
+ const all = (s) => {
+ const out = [];
+ for (const k of self.kids) {
+ if (k.sel.indexOf(s) >= 0) out.push(k);
+ for (const g of k.querySelectorAll(s)) out.push(g);
+ }
+ return out;
+ };
+ self.querySelectorAll = all;
+ self.querySelector = (s) => all(s)[0] || null;
+ return self;
+};
+
+const started = Date.now();
+const mounted = () => Date.now() - started >= mountAfterMs;
+
+const state = { menuOpen: false, hovers: 0 };
+
+const moreButton = node(["button"], {
+ "aria-label": "More",
+ on: (ev) => {
+ // Radix opens on pointerdown and this is what the action dispatches; anything else must not
+ // open it, because an element.click() that "worked" here would hide a real regression.
+ if (ev && ev.type === "pointerdown") { state.menuOpen = true; notify(); }
+ },
+});
+const bar = node(["button", ".aui-assistant-action-bar-root"], {}, [moreButton]);
+bar.sel = [".aui-assistant-action-bar-root"];
+
+const message = {
+ sel: ['[data-role="assistant"]'],
+ getAttribute: () => null,
+ textContent: "the reply",
+ dispatchEvent: (ev) => { if (ev && ev.type === "pointerover") state.hovers += 1; return true; },
+ querySelectorAll: (s) => (mounted() ? bar.querySelectorAll(s).concat(
+ bar.sel.indexOf(s) >= 0 ? [bar] : []) : []),
+ querySelector: (s) => (mounted() ? (bar.sel.indexOf(s) >= 0 ? bar
+ : bar.querySelector(s)) : null),
+};
+
+const menuItems = [node([".aui-action-bar-more-item"], {}), node([".aui-action-bar-more-item"], {})];
+const menu = node([".aui-action-bar-more-content"], {}, menuItems);
+
+const body = { sel: ["body"], querySelector: () => null, querySelectorAll: () => [] };
+const document = {
+ body: body,
+ // `isRunning()` is read off the composer's Stop button. It stays up until the bar mounts,
+ // exactly as it does in the app: both are driven by the same "the thread is generating" state.
+ querySelector: (s) => document.querySelectorAll(s)[0] || null,
+ querySelectorAll: (s) => {
+ if (s === '[data-role="assistant"]') return [message];
+ if (s === 'button[aria-label="Stop generating"]') return mounted() ? [] : [{}];
+ if (s === ".aui-action-bar-more-content") return state.menuOpen ? [menu] : [];
+ if (s === ".aui-action-bar-more-item") return state.menuOpen ? menuItems : [];
+ return [];
+ },
+ dispatchEvent: (ev) => {
+ if (ev && ev.key === "Escape") { state.menuOpen = false; notify(); }
+ return true;
+ },
+};
+
+// MutationObserver delivers on a microtask checkpoint after the mutation; the action relies on the
+// flag being set by the time its next paint resolves, so notifying the callbacks when the shimmed
+// DOM changes is the same contract.
+const observers = [];
+class MutationObserver {
+ constructor(cb) { this.cb = cb; }
+ observe() { observers.push(this); }
+ disconnect() { const i = observers.indexOf(this); if (i >= 0) observers.splice(i, 1); }
+}
+const notify = () => { for (const o of observers.slice()) o.cb(); };
+
+class PointerEvent { constructor(type, init) { this.type = type; Object.assign(this, init || {}); } }
+class KeyboardEvent { constructor(type, init) { this.type = type; Object.assign(this, init || {}); } }
+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));
+
+(new Function("window", "document", "PointerEvent", domSrc))(window, document, PointerEvent);
+
+const menuFn = (new Function(
+ "window", "document", "PointerEvent", "KeyboardEvent", "MutationObserver", "getComputedStyle",
+ "return (" + menuSrc + ")",
+))(window, document, PointerEvent, KeyboardEvent, MutationObserver, getComputedStyle);
+
+menuFn({ timeoutMs: 4000, waitForButtonMs: waitMs }).then((out) => {
+ out.hovers = state.hovers;
+ console.log(JSON.stringify(out));
+ process.exit(0);
+}, (err) => { console.error(String((err && err.stack) || err)); process.exit(1); });
+"""
+
+
+def _node() -> str:
+ exe = shutil.which("node") or shutil.which("nodejs")
+ if exe is None:
+ pytest.skip(
+ "node is not installed, so the shipped dom.js and MENU_JS could not be evaluated; "
+ "this is NOT MEASURED rather than passing"
+ )
+ return exe
+
+
+def run_menu(mount_after_ms: float, wait_ms: int = ACTION_BAR_WAIT_MS) -> dict:
+ """Run the shipped `MENU_JS` against the shipped `dom.js` with the bar mounting late."""
+ exe = _node()
+ with tempfile.TemporaryDirectory() as tmp:
+ harness = Path(tmp) / "harness.js"
+ harness.write_text(HARNESS_JS, encoding = "utf-8")
+ menu = Path(tmp) / "menu.js"
+ menu.write_text(MENU_JS, encoding = "utf-8")
+ got = subprocess.run(
+ [exe, str(harness), str(DOM_JS), str(menu), str(mount_after_ms), str(wait_ms)],
+ capture_output = True,
+ text = True,
+ timeout = 120,
+ )
+ if got.returncode != 0:
+ raise AssertionError(f"the MENU_JS harness failed: {got.stderr.strip()[-1200:]}")
+ return json.loads(got.stdout)
+
+
+def test_a_control_that_arrives_late_is_waited_for_rather_than_reported_missing():
+ """THE REGRESSION. A bar that mounts 400 ms into the slot must produce a run, not a NOT RUN.
+
+ Sampled once, this is the studiobench CI failure exactly: `no More button on the last
+ assistant message`, from a follow-up turn that was still arriving when the slot opened.
+ """
+ out = run_menu(LATE_MOUNT_MS)
+ assert out["ran"] is True, out
+ assert out["waitedMs"] >= LATE_MOUNT_MS * 0.8, out
+ assert out["waitedMs"] < ACTION_BAR_WAIT_MS, out
+ # The menu really opened and closed on the control that was waited for, so the wait produced a
+ # measurement rather than merely a truthy `ran`.
+ assert out["openMs"] is not None and out["closeMs"] is not None, out
+ assert out["items"] == 2, out
+
+
+def test_the_wait_is_bounded_and_a_control_that_never_appears_still_reports_not_run():
+ """The gate keeps its teeth. Waiting must not turn a genuinely absent control into a pass."""
+ out = run_menu(float("inf"), wait_ms = 300)
+ assert out["ran"] is False, out
+ assert out["waitedMs"] >= 250, out
+ # The reason has to separate the two cases, because they are different bugs: a reply that had
+ # not settled, and a control that is not there at all.
+ assert "STILL GENERATING" in out["reason"], out
+ assert out["running"] is True, out
+
+
+def test_a_settled_reply_costs_the_action_nothing():
+ """The normal case pays no wait at all, so the fix cannot show up in the measured latency."""
+ out = run_menu(0)
+ assert out["ran"] is True, out
+ assert out["waitedMs"] < 50, out
+ # Hovered before the control is read: the bar unmounts on every message that is not hovered,
+ # so a read without the hover is a read of a tree the control was never in.
+ assert out["hovers"] >= 1, out
diff --git a/tests/studio/studiobench/scene/surface_sweep.py b/tests/studio/studiobench/scene/surface_sweep.py
new file mode 100644
index 00000000000..2fab49e6ba0
--- /dev/null
+++ b/tests/studio/studiobench/scene/surface_sweep.py
@@ -0,0 +1,455 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Drive every registered surface once and take a parity digest of each.
+
+THE ONE RULE. A surface that was not reached records a REASON. Never a bare zero, never a missing
+row, and never a digest of whatever happened to be on screen instead. The failure this whole tool
+is built against is a check that cannot tell "did not run" from "passed", and a sweep is unusually
+good at producing exactly that: navigate to /hub, fail to render, digest the chat page that is
+still mounted underneath, and report a pass. So every row carries `reached`, `reason`, the settle
+observation that decided it, and the root the digest was actually taken from.
+
+WHY THE SWEEP RUNS AGAINST AN EMPTY CHAT. The known state is a fresh `/chat`. Several surface
+roots -- the shell, the sidebar, the active route container's siblings -- contain the keep-alive
+chat page, so a sweep run against a loaded thread would carry that thread into the digest of every
+other surface and any thread difference would flip all of them at once. An empty chat makes the
+surface digests about the surfaces.
+
+WHAT THE DIGEST IS. `window.__sb.parity.capture()`, the same function and the same normalisation
+the film uses at the close of every action window, pointed at the surface's own root by
+surfaces.js. Same function on purpose: a surface digest and an action digest that were produced by
+two implementations could not be compared, and comparing them is the point.
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Any, Callable, Optional
+
+from . import surfaces as registry
+
+#: How long a settle condition is given before the surface is recorded as unreached. Generous:
+#: the settings panels are lazily imported chunks and the hub's first paint waits on a network
+#: round trip, and a sweep that calls those failures is a sweep nobody believes.
+SETTLE_TIMEOUT_MS = 8000
+SETTLE_POLL_MS = 150
+
+#: A per-surface ceiling covering reach, settle and capture together. A surface whose reach
+#: navigates into a redirect loop would otherwise hold the sweep open indefinitely.
+SURFACE_BUDGET_MS = 25_000
+
+
+def _log_noop(_msg: str) -> None:
+ pass
+
+
+class _Driver:
+ """The step interpreter. One place that touches the browser, so the registry stays declarative
+ and the unit tests can read it with no browser installed."""
+
+ def __init__(self, page: Any, base_url: str, log: Callable[[str], None]) -> None:
+ self.page = page
+ self.base_url = base_url.rstrip("/")
+ self.log = log
+
+ def run(self, steps: tuple) -> Optional[str]:
+ """Execute steps. Returns None on success, or the reason the first one failed."""
+ for step in steps:
+ verb, args = step[0], step[1:]
+ try:
+ self._step(verb, args)
+ except Exception as exc: # noqa: BLE001
+ return (
+ f"step {verb!r}{list(args)!r} failed: "
+ f"{type(exc).__name__}: {str(exc).strip().splitlines()[0][:200]}"
+ )
+ return None
+
+ def _step(self, verb: str, args: tuple) -> None:
+ page = self.page
+ if verb == "goto":
+ page.goto(f"{self.base_url}{args[0]}", wait_until = "domcontentloaded", timeout = 60_000)
+ elif verb == "click":
+ # A REAL mouse click through the driver, not element.click(). Radix menus open on
+ # pointerdown, and a synthetic click never opens them -- which reads downstream as a
+ # menu that opened in zero milliseconds rather than as a menu that did not open. This
+ # is the same trap dom.js documents for the film's actions.
+ page.click(args[0], timeout = 6000)
+ elif verb == "click_if":
+ el = page.query_selector(args[0])
+ if el is not None:
+ el.click(timeout = 6000)
+ elif verb == "hover":
+ page.hover(args[0], timeout = 6000)
+ elif verb == "press":
+ page.keyboard.press(args[0])
+ elif verb == "fill":
+ page.fill(args[0], args[1], timeout = 6000)
+ elif verb == "wait":
+ page.wait_for_timeout(int(args[0]))
+ else: # pragma: no cover
+ raise ValueError(f"unknown step verb {verb!r}")
+
+ def settle(self, spec: Optional[dict], deadline: float) -> dict:
+ """Poll the settle condition. Returns what was observed, never a bare boolean."""
+ if spec is None:
+ return {"settled": True, "detail": "no settle condition declared"}
+ last = {"ok": False, "detail": "never evaluated"}
+ while time.monotonic() < deadline:
+ try:
+ last = self.page.evaluate("(spec) => window.__sb.surfaces.settled(spec)", spec)
+ except Exception as exc: # noqa: BLE001
+ last = {"ok": False, "detail": f"{type(exc).__name__}: {exc}"}
+ if last.get("ok"):
+ return {"settled": True, "detail": last.get("detail"), "spec": spec}
+ self.page.wait_for_timeout(SETTLE_POLL_MS)
+ return {"settled": False, "detail": last.get("detail"), "spec": spec}
+
+ def capture(self, root: tuple) -> dict:
+ try:
+ return self.page.evaluate("(root) => window.__sb.surfaces.capture(root)", list(root))
+ except Exception as exc: # noqa: BLE001
+ return {
+ "parity_attempted": False,
+ "reason": f"the digest could not be taken: {type(exc).__name__}: {exc}",
+ }
+
+ def facts(self, root: tuple) -> dict:
+ try:
+ return self.page.evaluate("(root) => window.__sb.surfaces.facts(root)", list(root))
+ except Exception as exc: # noqa: BLE001
+ return {"facts_attempted": False, "reason": f"{type(exc).__name__}: {exc}"}
+
+ def is_clean(self) -> dict:
+ try:
+ return self.page.evaluate("() => window.__sb.surfaces.isClean()")
+ except Exception as exc: # noqa: BLE001
+ return {"clean_attempted": False, "reason": f"{type(exc).__name__}: {exc}"}
+
+
+def _row(surface: registry.Surface, cell_id: Optional[str]) -> dict:
+ """A surface row with every mandatory field already present and honest.
+
+ Built up front rather than assembled on the success path, so an exception anywhere below
+ leaves a row that says it did not run instead of a row that is missing.
+ """
+ return {
+ "row_type": "surface",
+ "cell_id": cell_id,
+ "surface": surface.id,
+ "group": surface.group,
+ "title": surface.title,
+ "reached": False,
+ "reason": "the sweep did not get to this surface",
+ "conditional": surface.conditional,
+ "also_in_film": surface.also_in_film,
+ # Carried on the ROW, not only in the registry, so a reader of a payload can tell a
+ # digest that is a parity signal from one that moves on its own without needing this
+ # source tree in front of them.
+ "volatile": surface.volatile,
+ "parity": {"parity_attempted": False, "reason": "not captured"},
+ "settle": None,
+ "facts": None,
+ "restored": None,
+ "sweep_attempted": True,
+ "reach_ms": None,
+ }
+
+
+def sweep(
+ page: Any,
+ base_url: str,
+ log: Callable[[str], None] = _log_noop,
+ only: Optional[list] = None,
+ cell_id: Optional[str] = None,
+ recorder: Any = None,
+ settle_timeout_ms: Optional[int] = None,
+ surface_budget_ms: Optional[int] = None,
+) -> tuple[list[dict], dict]:
+ """Drive every registered surface once. Returns `(rows, manifest)`.
+
+ `recorder`, when given, receives each row as it is produced, so a sweep that dies halfway
+ still leaves the surfaces it did reach in the payload.
+
+ The two timeouts are arguments rather than constants only so the unit tests can drive the
+ unreached path without paying eight real seconds per surface for a page that was never going
+ to settle. Every caller in the tool uses the defaults.
+ """
+ settle_ms = SETTLE_TIMEOUT_MS if settle_timeout_ms is None else settle_timeout_ms
+ budget_ms = SURFACE_BUDGET_MS if surface_budget_ms is None else surface_budget_ms
+ registry.validate_registry()
+ driver = _Driver(page, base_url, log)
+ entries = registry.surfaces()
+ if only:
+ wanted = set(only)
+ missing = sorted(wanted - set(registry.surface_ids()))
+ if missing:
+ raise registry.RegistryError(f"no such surface(s): {missing}")
+ entries = [s for s in entries if s.id in wanted]
+
+ # Does parity.capture() honour a moved root? If it does not, every surface digest is the same
+ # page-wide reading and the sweep's forty passes mean nothing. Asked ONCE, up front, and the
+ # answer is carried on every row rather than assumed.
+ home = driver.run(registry.HOME)
+ scoping = {
+ "scoped": False,
+ "scoping_attempted": False,
+ "reason": "the known state could not be reached, so scoping was never probed",
+ }
+ if home is None:
+ try:
+ scoping = page.evaluate("() => window.__sb.surfaces.probeScoping()")
+ except Exception as exc: # noqa: BLE001
+ scoping = {
+ "scoped": False,
+ "scoping_attempted": False,
+ "reason": f"the scoping probe raised {type(exc).__name__}: {exc}",
+ }
+ if not scoping.get("scoped"):
+ log(f" surface digests are NOT scoped to their surface: {scoping.get('reason')}")
+
+ rows: list[dict] = []
+ for surface in entries:
+ row = _row(surface, cell_id)
+ row["scoping"] = scoping
+ started = time.monotonic()
+ deadline = started + budget_ms / 1000
+
+ # From the KNOWN STATE, never from wherever the previous surface left the app. A reach
+ # that happens to work only because the last surface left a menu open is a reach that
+ # breaks the first time the order changes, and it would break silently.
+ reset = driver.run(registry.HOME)
+ if reset is not None:
+ row["reason"] = f"the known state could not be restored before this surface: {reset}"
+ rows.append(row)
+ _emit(recorder, row)
+ log(f" {surface.id}: NOT REACHED -- {row['reason']}")
+ continue
+
+ failed = driver.run(surface.reach)
+ if failed is not None:
+ row["reason"] = f"the reach failed: {failed}"
+ # The facts are still recorded. Where the app ACTUALLY ended up is the first thing a
+ # reader of a failed reach needs, and it is gone by the time anyone looks.
+ row["facts"] = driver.facts(surface.root)
+ row["reach_ms"] = round((time.monotonic() - started) * 1000, 1)
+ rows.append(row)
+ _emit(recorder, row)
+ log(f" {surface.id}: NOT REACHED -- {row['reason']}")
+ _recover(driver, log)
+ continue
+
+ # Whichever runs out first: the settle window or what is left of the surface's budget.
+ settled = driver.settle(surface.settle, min(deadline, time.monotonic() + settle_ms / 1000))
+ row["settle"] = settled
+ row["facts"] = driver.facts(surface.root)
+ row["reach_ms"] = round((time.monotonic() - started) * 1000, 1)
+ if not settled.get("settled"):
+ row["reason"] = (
+ f"the reach ran but the surface never settled: " f"{settled.get('detail')}"
+ )
+ rows.append(row)
+ _emit(recorder, row)
+ log(f" {surface.id}: NOT REACHED -- {row['reason']}")
+ _recover(driver, log)
+ continue
+
+ parity = driver.capture(surface.root)
+ row["parity"] = parity
+ if not parity.get("parity_attempted"):
+ # Reached, but no digest. Recorded as unreached FOR PARITY PURPOSES, because a
+ # surface with no digest contributes nothing to the parity claim, and counting it as
+ # covered is exactly the inflation this file is written to avoid.
+ row["reason"] = f"the surface rendered but no digest was taken: {parity.get('reason')}"
+ rows.append(row)
+ _emit(recorder, row)
+ log(f" {surface.id}: NO DIGEST -- {parity.get('reason')}")
+ _recover(driver, log)
+ continue
+
+ row["reached"] = True
+ row["reason"] = None
+ rows.append(row)
+ log(
+ f" {surface.id}: digest {parity.get('digest')} "
+ f"({parity.get('chars')} chars from {parity.get('root_selector')}, "
+ f"{(row['facts'] or {}).get('root_elements')} elements)"
+ )
+
+ restored = driver.run(surface.restore)
+ clean = driver.is_clean()
+ row["restored"] = restored is None
+ row["restore_state"] = clean
+ if restored is not None:
+ row["restore_reason"] = restored
+ _recover(driver, log)
+ elif (clean.get("open_dialogs") or 0) or (clean.get("open_menus") or 0):
+ # The declared restore ran and the app is still dirty. Said out loud: the next
+ # surface would otherwise be reached from a state nobody declared, and its digest
+ # would quietly include a leftover overlay.
+ row["restore_reason"] = (
+ f"the restore ran but left {clean.get('open_dialogs')} dialog(s) and "
+ f"{clean.get('open_menus')} menu(s) open"
+ )
+ row["restored"] = False
+ _recover(driver, log)
+ _emit(recorder, row)
+
+ manifest = build_manifest(rows, entries, scoping)
+ return rows, manifest
+
+
+def _emit(recorder: Any, row: dict) -> None:
+ if recorder is None:
+ return
+ try:
+ recorder.emit(dict(row))
+ except Exception: # noqa: BLE001
+ # A recorder that rejects a row must not cost the sweep the rest of its surfaces. The row
+ # is still in the returned list and in the manifest.
+ pass
+
+
+def _recover(driver: _Driver, log: Callable[[str], None]) -> None:
+ """Hard reset after a failure or a dirty restore."""
+ driver.run(registry.ESCAPE_OUT + registry.HOME)
+ clean = driver.is_clean()
+ if (clean.get("open_dialogs") or 0) or (clean.get("open_menus") or 0):
+ log(f" the app is still not at the known state after a reset: {clean}")
+
+
+def build_manifest(rows: list, entries: list, scoping: dict) -> dict:
+ """The coverage manifest: what was swept, what was not, and what is out of reach by design."""
+ reached = [r for r in rows if r.get("reached")]
+ failed = [r for r in rows if not r.get("reached")]
+ # A conditional surface that did not render is not a hole in the registry: it is a property of
+ # this installation. Kept separate so the coverage figure is not quietly deflated by a host
+ # that has no GPU, and not quietly inflated by counting it as covered either.
+ conditional_misses = [r for r in failed if r.get("conditional")]
+ hard_misses = [r for r in failed if not r.get("conditional")]
+ registered = len(entries)
+ return {
+ "manifest_attempted": True,
+ "registered": registered,
+ "swept": len(rows),
+ "reached": len(reached),
+ "not_reached": len(failed),
+ "not_reached_conditional": len(conditional_misses),
+ "not_reached_hard": len(hard_misses),
+ # Against the surfaces that COULD have rendered on this host. Reported next to the raw
+ # count, never instead of it.
+ "coverage_pct": (
+ round(100.0 * len(reached) / (registered - len(conditional_misses)), 1)
+ if registered - len(conditional_misses) > 0
+ else None
+ ),
+ "coverage_pct_of_registered": (
+ round(100.0 * len(reached) / registered, 1) if registered else None
+ ),
+ "digests_scoped": bool(scoping.get("scoped")),
+ "digests_scoped_reason": scoping.get("reason"),
+ "failures": [
+ {
+ "id": r["surface"],
+ "group": r["group"],
+ "reason": r["reason"],
+ "conditional": r.get("conditional"),
+ }
+ for r in failed
+ ],
+ "restore_failures": [
+ {"id": r["surface"], "reason": r.get("restore_reason")}
+ for r in rows
+ if r.get("restored") is False
+ ],
+ # Reached, digested, and NOT a parity signal. Counted separately because the number that
+ # matters to somebody comparing two arms is how many surfaces can carry a verdict, and
+ # that is `comparable`, not `reached`.
+ "volatile": len([r for r in reached if r.get("volatile")]),
+ "comparable": len([r for r in reached if not r.get("volatile")]),
+ "volatile_surfaces": [
+ {"id": r["surface"], "mechanism": r["volatile"]} for r in reached if r.get("volatile")
+ ],
+ "by_group": _by_group(rows),
+ "known_uncovered": [dict(u) for u in registry.KNOWN_UNCOVERED],
+ "known_uncovered_count": len(registry.KNOWN_UNCOVERED),
+ }
+
+
+def _by_group(rows: list) -> dict:
+ out: dict[str, dict] = {}
+ for r in rows:
+ bucket = out.setdefault(
+ r["group"], {"reached": 0, "not_reached": 0, "group_attempted": True}
+ )
+ bucket["reached" if r.get("reached") else "not_reached"] += 1
+ return out
+
+
+def render_manifest(manifest: dict) -> str:
+ """The manifest as text. Reads top-down: the number, then everything that qualifies it."""
+ lines = []
+ lines.append("UI SURFACE COVERAGE")
+ lines.append("=" * 78)
+ pct = manifest.get("coverage_pct")
+ lines.append(
+ f"{manifest['reached']} of {manifest['registered']} registered surfaces reached"
+ + (f" ({pct}% of those this host can render)" if pct is not None else "")
+ )
+ if not manifest.get("digests_scoped"):
+ lines.append("")
+ lines.append(
+ " WARNING: the digests are NOT scoped to their surface -- "
+ f"{manifest.get('digests_scoped_reason')}"
+ )
+ lines.append(
+ " Every digest below is a whole-page reading, so two different surfaces can agree"
+ )
+ lines.append(" for reasons that have nothing to do with either of them.")
+ lines.append(
+ f"{manifest.get('comparable', 0)} of those carry a comparable digest; "
+ f"{manifest.get('volatile', 0)} move between two runs of the same build"
+ )
+ lines.append("")
+ lines.append(f"{'group':<12} {'reached':>8} {'not reached':>12}")
+ lines.append("-" * 78)
+ for group in sorted(manifest.get("by_group", {})):
+ got = manifest["by_group"][group]
+ lines.append(f"{group:<12} {got['reached']:>8} {got['not_reached']:>12}")
+ if manifest.get("failures"):
+ lines.append("")
+ lines.append("NOT REACHED (each with the reason, never a silent gap)")
+ lines.append("-" * 78)
+ for f in manifest["failures"]:
+ tag = " [conditional]" if f.get("conditional") else ""
+ lines.append(f" {f['id']}{tag}")
+ lines.append(f" {f['reason']}")
+ if f.get("conditional"):
+ lines.append(f" precondition: {f['conditional']}")
+ if manifest.get("restore_failures"):
+ lines.append("")
+ lines.append("RESTORE DID NOT RETURN THE APP TO THE KNOWN STATE")
+ lines.append("-" * 78)
+ for f in manifest["restore_failures"]:
+ lines.append(f" {f['id']}: {f['reason']}")
+ if manifest.get("volatile_surfaces"):
+ lines.append("")
+ lines.append("REACHED BUT NOT COMPARABLE (the digest moves between two runs of one build)")
+ lines.append("-" * 78)
+ for entry in manifest["volatile_surfaces"]:
+ lines.append(f" {entry['id']}")
+ lines.append(f" {entry['mechanism']}")
+ lines.append("")
+ lines.append(
+ f"KNOWN UNCOVERED ({manifest['known_uncovered_count']} surfaces, out of reach "
+ "by mechanism, not by oversight)"
+ )
+ lines.append("-" * 78)
+ for entry in manifest.get("known_uncovered", []):
+ lines.append(f" {entry['id']}: {entry['title']}")
+ lines.append(f" {entry['reason']}")
+ return "\n".join(lines)
+
+
+__all__ = ["sweep", "build_manifest", "render_manifest", "SETTLE_TIMEOUT_MS", "SURFACE_BUDGET_MS"]
diff --git a/tests/studio/studiobench/scene/surfaces.js b/tests/studio/studiobench/scene/surfaces.js
new file mode 100644
index 00000000000..a0a6afffffb
--- /dev/null
+++ b/tests/studio/studiobench/scene/surfaces.js
@@ -0,0 +1,255 @@
+// 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 selector adapter for Studio's surfaces OUTSIDE the chat thread: the other routes, the
+// settings dialog's twelve tabs, the sidebar and its menus, the hub, the media pages.
+//
+// Separate from dom.js on purpose. dom.js is the chat thread's adapter and the eighteen film
+// actions all read it; this file is read only by the surface sweep, so a selector added for a
+// route cannot break an action.
+//
+// THE TRAP THIS FILE EXISTS TO GUARD. ChatPage, ImagesPage, VideoPage and AudioPage are mounted
+// PERSISTENTLY by the root layout (`shouldMountChat` and friends in app/routes/__root.tsx) so an
+// in-flight generation survives leaving the tab. Off-route they are `class="hidden"` and `inert`,
+// but they are still in the document. So on /hub, `document.querySelector(".aui-thread-root")`
+// still returns the chat thread, and a digest taken with parity.js's default root would digest
+// the HIDDEN CHAT THREAD on every route in the sweep -- forty surfaces reporting one identical
+// digest, and every one of them reading as a pass. Every surface therefore names its own root and
+// the digest is scoped to it.
+//
+// HOW THE SCOPING IS DONE, and why it is not a second digest implementation. Surface digests are
+// only worth taking if they are comparable with the film's action digests, which means the same
+// normalisation and the same hash -- so this calls `window.__sb.parity.capture()` rather than
+// walking the DOM itself. parity.js reads its root from `window.__sb.dom.threadRoot()`, so the
+// root is moved for the duration of one capture and put back afterwards. `probeScoping()` below
+// checks that the move is actually observed, because if a future parity.js stopped reading
+// threadRoot this would silently go back to digesting the thread on every surface, which is the
+// failure this file was written to prevent.
+
+(() => {
+ if (window.__sb && window.__sb.surfaces) return;
+ window.__sb = window.__sb || {};
+
+ const q = (sel) => {
+ // Selector strings come from a registry, and one bad selector must cost that surface a
+ // reason rather than cost the whole sweep an exception.
+ try {
+ return document.querySelector(sel);
+ } catch (err) {
+ return null;
+ }
+ };
+
+ const qa = (sel) => {
+ try {
+ return Array.from(document.querySelectorAll(sel));
+ } catch (err) {
+ return [];
+ }
+ };
+
+ // Rendered, not merely mounted. `hidden`, `display:none` and a zero box all mean the user
+ // cannot see it, and the keep-alive route containers are exactly the first case.
+ const isVisible = (el) => {
+ if (!el) return false;
+ if (el.hasAttribute && el.hasAttribute("hidden")) return false;
+ const rect = el.getBoundingClientRect();
+ if (rect.width <= 0 && rect.height <= 0) return false;
+ const style = window.getComputedStyle(el);
+ return style.display !== "none" && style.visibility !== "hidden";
+ };
+
+ // The ACTIVE route's container, found by the property the root layout actually sets.
+ //
+ // The layout renders the keep-alive pages and the routed page as siblings, and marks every
+ // page that is NOT the current route `inert` (plus `class="hidden"`). So the active container
+ // is the one visible sibling of an inert one. Keyed on `inert` rather than on the class string
+ // because `hidden` is a Tailwind utility that a restyle can change, while `inert` is what makes
+ // the off-route pages unreachable and cannot be dropped without changing behaviour.
+ //
+ // When nothing is inert, no page has been kept alive yet and the inset itself is the container.
+ const routeContainer = () => {
+ const inset = q('[data-slot="sidebar-inset"]');
+ if (!inset) return null;
+ const inertNode = inset.querySelector("[inert]");
+ if (!inertNode || !inertNode.parentElement) return inset;
+ const siblings = Array.from(inertNode.parentElement.children);
+ const active = siblings.filter((el) => !el.hasAttribute("inert") && isVisible(el));
+ // Exactly one, or the assumption is wrong and the inset is the honest answer. Silently
+ // picking the first of several would scope the digest to an arbitrary part of the page.
+ return active.length === 1 ? active[0] : inset;
+ };
+
+ const SPECIAL = {
+ "@route": routeContainer,
+ "@shell": () => q('[data-slot="sidebar-wrapper"]') || q("main"),
+ "@sidebar": () => q('[data-slot="sidebar-container"]') || q('[data-slot="sidebar"]'),
+ };
+
+ const resolve = (sel) => (SPECIAL[sel] ? SPECIAL[sel]() : q(sel));
+
+ const S = {
+ // ── roots ────────────────────────────────────────────────────
+ //
+ // `candidates` is ordered: the first one that is present AND visible wins. The auth-flow
+ // routes render no sidebar wrapper at all, so every list ends at a fallback that exists.
+ resolveRoot(candidates) {
+ for (const sel of candidates || []) {
+ const el = resolve(sel);
+ if (el && isVisible(el)) return { el, sel };
+ }
+ for (const sel of candidates || []) {
+ const el = resolve(sel);
+ // Present but not visible is still reported, with the selector, so a surface that
+ // rendered into a hidden container is a readable finding rather than a fallback to body.
+ if (el) return { el, sel, visible: false };
+ }
+ return { el: document.body, sel: "body", fallback: true };
+ },
+
+ // ── the scoped capture ───────────────────────────────────────
+ capture(candidates) {
+ const parity = (window.__sb || {}).parity;
+ if (!parity || typeof parity.capture !== "function") {
+ return { parity_attempted: false, reason: "parity.js is not loaded on this page" };
+ }
+ const dom = (window.__sb || {}).dom;
+ if (!dom || typeof dom.threadRoot !== "function") {
+ return { parity_attempted: false, reason: "dom.js is not loaded on this page" };
+ }
+ const found = S.resolveRoot(candidates);
+ const original = dom.threadRoot;
+ let out;
+ try {
+ dom.threadRoot = () => found.el;
+ out = parity.capture();
+ } catch (err) {
+ out = { parity_attempted: false,
+ reason: String(err && err.message ? err.message : err) };
+ } finally {
+ dom.threadRoot = original;
+ }
+ out.root_selector = found.sel;
+ out.root_visible = found.visible !== false;
+ out.root_is_fallback = Boolean(found.fallback);
+ return out;
+ },
+
+ // Does parity.capture() actually honour a moved root? Pointed at a detached element with one
+ // short text node, an honouring capture returns a signature of a few dozen characters and a
+ // non-honouring one returns the whole page. The threshold is two orders of magnitude clear of
+ // both, so this cannot answer "yes" for a page that ignored the move.
+ probeScoping() {
+ const dom = (window.__sb || {}).dom;
+ const parity = (window.__sb || {}).parity;
+ if (!dom || !parity) {
+ return { scoped: false, scoping_attempted: false,
+ reason: "dom.js or parity.js is not loaded on this page" };
+ }
+ const probe = document.createElement("div");
+ probe.setAttribute("data-sb-scope-probe", "1");
+ probe.textContent = "scope probe";
+ const original = dom.threadRoot;
+ let got;
+ try {
+ dom.threadRoot = () => probe;
+ got = parity.capture();
+ } catch (err) {
+ dom.threadRoot = original;
+ return { scoped: false, scoping_attempted: true,
+ reason: "parity.capture() raised while the root was moved: " +
+ String(err && err.message ? err.message : err) };
+ }
+ dom.threadRoot = original;
+ const chars = got && typeof got.chars === "number" ? got.chars : null;
+ if (chars === null) {
+ return { scoped: false, scoping_attempted: true, probe_chars: -1,
+ reason: "parity.capture() returned no `chars`, so scoping cannot be verified" };
+ }
+ if (chars > 500) {
+ // The digest is the whole page, not the probe. Every surface digest would then be the
+ // same page-wide reading and the sweep would report forty identical passes.
+ return { scoped: false, scoping_attempted: true, probe_chars: chars,
+ reason: "parity.capture() ignored the moved root (" + chars + " chars from a " +
+ "detached probe element), so surface digests would not be scoped" };
+ }
+ return { scoped: true, scoping_attempted: true, probe_chars: chars };
+ },
+
+ // ── settle predicates ────────────────────────────────────────
+ //
+ // Evaluated by the sweep in a poll loop. Each returns a plain boolean plus the observation it
+ // was made from, so a surface that never settled records WHAT it was waiting for.
+ settled(spec) {
+ if (!spec) return { ok: true, detail: "no settle condition" };
+ if (spec.visible) {
+ const el = q(spec.visible);
+ return { ok: Boolean(el) && isVisible(el),
+ detail: el ? "present, visible=" + isVisible(el) : "not present" };
+ }
+ if (spec.hidden) {
+ const el = q(spec.hidden);
+ return { ok: !el || !isVisible(el), detail: el ? "still visible" : "gone" };
+ }
+ if (spec.count_at_least) {
+ const [sel, n] = spec.count_at_least;
+ const got = qa(sel).filter(isVisible).length;
+ return { ok: got >= n, detail: got + " visible, wanted " + n };
+ }
+ if (spec.text) {
+ const hay = (document.body.innerText || "");
+ return { ok: hay.includes(spec.text), detail: "text " + JSON.stringify(spec.text) };
+ }
+ if (spec.js) {
+ try {
+ // eslint-disable-next-line no-new-func
+ const got = Function("return (" + spec.js + ")")();
+ return { ok: Boolean(got), detail: "js -> " + String(got) };
+ } catch (err) {
+ return { ok: false, detail: "js raised: " + String(err && err.message) };
+ }
+ }
+ return { ok: true, detail: "unrecognised settle spec, treated as satisfied" };
+ },
+
+ // What the sweep records alongside every surface so a digest can be read against the state it
+ // was taken in. A surface whose root holds three elements did not render.
+ facts(candidates) {
+ const found = S.resolveRoot(candidates);
+ return {
+ facts_attempted: true,
+ pathname: location.pathname,
+ search: location.search,
+ root_selector: found.sel,
+ root_is_fallback: Boolean(found.fallback),
+ root_elements: found.el ? found.el.getElementsByTagName("*").length : -1,
+ root_text_chars: found.el ? (found.el.innerText || "").length : -1,
+ open_dialogs: qa('[role="dialog"], [data-slot="dialog-content"]').filter(isVisible).length,
+ open_menus: qa('[role="menu"], [role="listbox"]').filter(isVisible).length,
+ popovers: qa("[data-radix-popper-content-wrapper]").filter(isVisible).length,
+ };
+ },
+
+ // The known state the sweep returns to between surfaces. Reported rather than asserted: the
+ // sweep decides what to do about a dirty state, and it needs the observation to decide.
+ isClean() {
+ return {
+ clean_attempted: true,
+ open_dialogs: qa('[role="dialog"], [data-slot="dialog-content"]').filter(isVisible).length,
+ open_menus: qa('[role="menu"], [role="listbox"]').filter(isVisible).length,
+ popovers: qa("[data-radix-popper-content-wrapper]").filter(isVisible).length,
+ pathname: location.pathname,
+ };
+ },
+
+ visible(sel) {
+ return isVisible(q(sel));
+ },
+
+ count(sel) {
+ return qa(sel).filter(isVisible).length;
+ },
+ };
+
+ window.__sb.surfaces = S;
+})();
diff --git a/tests/studio/studiobench/scene/surfaces.py b/tests/studio/studiobench/scene/surfaces.py
new file mode 100644
index 00000000000..1fc6af24731
--- /dev/null
+++ b/tests/studio/studiobench/scene/surfaces.py
@@ -0,0 +1,948 @@
+# 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 registry of Studio's UI SURFACES, for the parity sweep.
+
+WHY THIS EXISTS. The film drives eighteen actions against the chat thread plus a handful of
+overlays, and the parity digest taken at the close of each one is what licenses the claim "this
+change does not alter the UI". That claim is far wider than the evidence: Studio has fifteen
+routes, a settings dialog with twelve lazily loaded panels, a sidebar with six menus, a model
+picker with three section tabs, and the media pages. None of them is on the film's path, so a
+change that repainted every one of them would pass eighteen out of eighteen parity checks.
+
+WHAT A SURFACE IS. A named, reachable state of the app, with:
+
+ reach the steps that get there FROM THE KNOWN STATE, never from wherever the last
+ surface happened to leave things
+ settle the observation that says it has actually arrived. Never a sleep: a sleep cannot
+ tell a surface that rendered from one that never did, and a digest of a surface that
+ never rendered is the exact defect this tool is about
+ restore the steps back to the known state, so surface N+1 starts where surface N started
+ root the element the digest is scoped to. Ordered candidates, first visible one wins
+
+THE TRAP THAT SHAPES THE ROOTS. ChatPage, ImagesPage, VideoPage and AudioPage are mounted
+PERSISTENTLY by the root layout so an in-flight generation survives leaving the tab; off-route
+they are `hidden` and `inert` but still in the document. A digest taken with parity.js's default
+root therefore reads the hidden chat thread on every non-chat route, and forty surfaces report one
+identical digest that every one of them passes. `@route` resolves the ACTIVE route container by
+the property the layout actually sets -- the off-route siblings carry `inert` -- rather than by a
+class name that a refactor would quietly change.
+
+WHAT IS DELIBERATELY NOT HERE is listed in `KNOWN_UNCOVERED` at the bottom, with the mechanism
+that puts it out of reach. A surface missing from a coverage report because nobody thought of it
+and a surface missing because it cannot be reached without destroying the session look identical
+in a manifest that only lists what it swept, so the second kind is enumerated.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+from dataclasses import dataclass
+from typing import Any, Optional
+
+#: The state every surface is reached from and restored to: a fresh, empty chat. Fresh matters.
+#: The keep-alive chat container is inside `@route`'s siblings and inside `@shell`, so a sweep run
+#: against a loaded thread would carry that thread's DOM into the digest of every other surface,
+#: and any thread difference would flip all forty of them at once.
+KNOWN_STATE_PATH = "/chat"
+
+#: Steps are (verb, *args). Interpreted by surface_sweep, which owns the browser; keeping them
+#: declarative is what lets the unit tests check the registry with no browser present.
+#:
+#: goto <path> navigate, relative to the Studio base url
+#: click <selector> a REAL mouse click through the driver. Not element.click():
+#: Radix menus open on pointerdown and a synthetic click misses
+#: them entirely, which reads as a menu that opened instantly
+#: click_if <selector> click only when present. For controls that exist in one of two
+#: states, e.g. the sidebar is already collapsed
+#: hover <selector> park the pointer over an element. REQUIRED before four of the
+#: sidebar's controls: the row actions ship
+#: `opacity-0 pointer-events-none` and only take
+#: `group-hover:pointer-events-auto` when their row is hovered, so
+#: a click on them times out against an element that is present,
+#: sized and reported visible by every check except the one that
+#: matters
+#: press <key> a key on the focused element
+#: fill <selector> <text> set an input's value through the driver
+#: wait <ms> a bounded pause. Only ever ALONGSIDE a settle condition, never
+#: instead of one
+Step = tuple
+
+
+@dataclass(frozen = True)
+class Surface:
+ """One reachable UI surface."""
+
+ id: str
+ group: str
+ title: str
+ reach: tuple[Step, ...]
+ restore: tuple[Step, ...]
+ root: tuple[str, ...]
+ settle: Optional[dict] = None
+ #: Set when the surface's absence is a legitimate property of THIS installation rather than a
+ #: broken selector: the Connected tab of the model picker needs an external provider, the hub
+ #: catalog needs network. A surface that fails to reach still records a reason either way;
+ #: this decides whether the manifest counts it against coverage.
+ conditional: Optional[str] = None
+ #: Surfaces the film already drives. Swept anyway -- the sweep runs on an EMPTY chat and the
+ #: film on a loaded one, so the two digests are of different states -- but flagged so the
+ #: coverage figure is not inflated by re-counting what was already covered.
+ also_in_film: bool = False
+ #: The mechanism by which this surface's digest differs between two runs of the SAME build.
+ #: Measured, not assumed: three consecutive sweeps against one Studio agreed on 44 of 53
+ #: surfaces, and every entry below is the mechanism behind one of the nine that did not.
+ #:
+ #: This is the same distinction `scripts/sbench_ui_parity.py` already draws for the film's
+ #: actions with UNSTABLE_ACTIONS, and for the same reason: a comparison that reports a live
+ #: memory gauge as a UI change gets ignored within a day, and then so does the rest of it.
+ volatile: Optional[str] = None
+ notes: str = ""
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "id": self.id,
+ "group": self.group,
+ "title": self.title,
+ "reach": [list(s) for s in self.reach],
+ "restore": [list(s) for s in self.restore],
+ "root": list(self.root),
+ "settle": self.settle,
+ "conditional": self.conditional,
+ "also_in_film": self.also_in_film,
+ "volatile": self.volatile,
+ "notes": self.notes,
+ }
+
+
+# ── shared fragments ────────────────────────────────────────────────
+
+#: Back to the known state the hard way. Used as the restore for anything that navigated, and as
+#: the recovery path when a surface's own restore left the app dirty.
+HOME: tuple[Step, ...] = (("goto", KNOWN_STATE_PATH), ("wait", 400))
+
+#: Escape twice, not once. A settings tab that has opened a sub-view (Data -> Archived chats,
+#: Voice -> Dictionary) eats the first Escape closing the sub-view and stays open on the dialog.
+ESCAPE_OUT: tuple[Step, ...] = (
+ ("press", "Escape"),
+ ("wait", 200),
+ ("press", "Escape"),
+ ("wait", 300),
+)
+
+#: The chat composer. Its presence is what "the chat route has rendered" means, everywhere.
+COMPOSER = 'textarea[aria-label="Message input"]'
+
+ROOT_ROUTE = ("@route",)
+ROOT_SHELL = ("@shell",)
+ROOT_SIDEBAR = ("@sidebar",)
+
+
+#: The empty chat prints a randomly chosen greeting. `pickRandom` in
+#: components/assistant-ui/thread.tsx:2019 selects from a time-of-day list, so two loads of one
+#: build render different headings, and every digest whose root contains the welcome screen
+#: differs run to run for that reason alone.
+GREETING_IS_RANDOM = (
+ "the empty chat's greeting is chosen by pickRandom "
+ "(components/assistant-ui/thread.tsx:2019), so two loads of the same build "
+ "render different headings"
+)
+
+#: The hub catalogue is fetched from Hugging Face. Download counts, trending order and the arrival
+#: time of the list all move independently of the build under test.
+HUB_IS_REMOTE = (
+ "the catalogue is fetched from Hugging Face, so its content and its arrival time "
+ "both move independently of the build under test"
+)
+
+#: MEASURED TO MOVE, MECHANISM NOT ESTABLISHED. Three sweeps of one build disagreed on these, and
+#: a back-to-back pair of visits produced byte-identical markup, so it is not a timer and not a
+#: render race inside the surface. It is state that something earlier in the sweep, or the install,
+#: carries between sweeps -- and which state has not been pinned down.
+#:
+#: Flagged rather than left comparable, and flagged as UNEXPLAINED rather than given a plausible
+#: cause. A wrong mechanism in this field is worse than an admitted gap: it is the sentence a
+#: reader uses to dismiss a real difference.
+UNEXPLAINED_DRIFT = (
+ "measured to differ between sweeps of the SAME build while a back-to-back "
+ "pair of visits produced byte-identical markup. The mechanism is NOT "
+ "established, so the digest is not treated as a parity signal until it is"
+)
+
+
+def _route(
+ surface_id: str,
+ title: str,
+ path: str,
+ settle: dict,
+ conditional: Optional[str] = None,
+ notes: str = "",
+ volatile: Optional[str] = None,
+) -> Surface:
+ return Surface(
+ id = surface_id,
+ group = "route",
+ title = title,
+ reach = (("goto", path), ("wait", 600)),
+ settle = settle,
+ restore = HOME,
+ root = ROOT_ROUTE,
+ conditional = conditional,
+ notes = notes,
+ volatile = volatile,
+ )
+
+
+def _settings_tab(tab_id: str, title: str) -> Surface:
+ # `/settings` is not a page. Its route component calls `openDialog()` and immediately
+ # redirects to /chat, so the dialog is the surface and the URL never stays on /settings --
+ # a settle condition written against the URL would never be satisfied.
+ return Surface(
+ id = f"settings:{tab_id}",
+ group = "settings",
+ title = title,
+ reach = (
+ ("goto", "/settings"),
+ ("wait", 500),
+ ("click", f'[data-testid="settings-tab-{tab_id}"]'),
+ ("wait", 400),
+ ),
+ # The panel is lazily imported per tab, so "the dialog is open" is not enough: the tab
+ # would be recorded as reached while its chunk was still in flight and the digest would
+ # be of the Suspense fallback. The tab's own pressed state plus a settled panel body is
+ # the observation that the panel arrived.
+ settle = {
+ "js": f"!!document.querySelector('[data-testid=\"settings-tab-{tab_id}\"]')"
+ f' && !!document.querySelector(".settings-surface main")'
+ f' && (document.querySelector(".settings-surface main").innerText || "")'
+ f".trim().length > 0"
+ },
+ restore = ESCAPE_OUT + HOME,
+ root = (".settings-surface", '[data-slot="dialog-content"]'),
+ )
+
+
+# ── the registry ────────────────────────────────────────────────────
+
+_SURFACES: list[Surface] = [
+ # ── routes ──────────────────────────────────────────────────────
+ _route(
+ "route:chat",
+ "Chat, empty state",
+ "/chat",
+ {"visible": COMPOSER},
+ volatile = GREETING_IS_RANDOM,
+ ),
+ _route("route:projects", "Projects", "/projects", {"js": 'location.pathname === "/projects"'}),
+ _route(
+ "route:hub",
+ "Hub / model catalogue",
+ "/hub",
+ {"js": 'location.pathname === "/hub"'},
+ conditional = "the catalogue needs network; without it the page renders its own "
+ "network error state, which is itself a surface worth digesting",
+ volatile = HUB_IS_REMOTE,
+ ),
+ _route(
+ "route:train",
+ "Train (Studio)",
+ "/studio",
+ # NOT a URL check alone, and not the nav row either: the nav row is in the sidebar and
+ # is there before the page is. StudioPage shows a spinner while the hardware verdict is
+ # unmeasured and then redirects to /chat if the host is chat-only, so the wizard's own
+ # last section is what says the page finished rendering.
+ {
+ "js": 'location.pathname === "/studio" && '
+ '(document.body.innerText || "").includes("Run preview")'
+ },
+ conditional = "a chat-only host redirects /studio to /chat by design",
+ volatile = UNEXPLAINED_DRIFT,
+ ),
+ _route("route:export", "Export", "/export", {"js": 'location.pathname === "/export"'}),
+ _route("route:images", "Images", "/images", {"js": 'location.pathname === "/images"'}),
+ _route(
+ "route:video",
+ "Video",
+ "/video",
+ {"js": 'location.pathname === "/video"'},
+ conditional = "a host without video support renders the gate instead of the page",
+ ),
+ _route("route:audio", "Audio", "/audio", {"js": 'location.pathname === "/audio"'}),
+ _route(
+ "route:data-recipes",
+ "Data recipes",
+ "/data-recipes",
+ {"js": 'location.pathname === "/data-recipes"'},
+ ),
+ _route(
+ "route:api-monitor",
+ "API monitor",
+ "/api-monitor",
+ {"js": 'location.pathname === "/api-monitor"'},
+ ),
+ # The 404 is a rendered surface with its own mascot, heading and back-link, and it is exactly
+ # the kind of page a bundler or asset-path change breaks without anyone noticing.
+ _route(
+ "route:not-found",
+ "Not found",
+ "/studiobench-no-such-route",
+ {"js": 'location.pathname === "/studiobench-no-such-route"'},
+ ),
+ # ── the settings dialog ─────────────────────────────────────────
+ _settings_tab("general", "Settings: General"),
+ _settings_tab("profile", "Settings: Profile"),
+ _settings_tab("appearance", "Settings: Appearance"),
+ dataclasses.replace(
+ _settings_tab("resources", "Settings: Resources"),
+ volatile = "the panel shows live CPU, memory and disk gauges. Two visits a minute apart "
+ "read 1% vs 2% CPU and 82.2 GiB vs 177 GiB used",
+ ),
+ _settings_tab("chat", "Settings: Chat"),
+ _settings_tab("voice", "Settings: Voice"),
+ _settings_tab("connections", "Settings: Connections"),
+ _settings_tab("data", "Settings: Data"),
+ _settings_tab("api-keys", "Settings: API keys"),
+ dataclasses.replace(_settings_tab("agents", "Settings: Agents"), volatile = UNEXPLAINED_DRIFT),
+ dataclasses.replace(
+ _settings_tab("debugging", "Settings: Debugging"),
+ volatile = "the panel renders a live tail of the server log, so it carries request "
+ "timestamps. Two visits differed by 402 lines",
+ ),
+ _settings_tab("about", "Settings: About"),
+ # The dialog's own search index is a distinct rendering of every panel's labels, and it is the
+ # one place a settings string appears without its panel being mounted.
+ Surface(
+ id = "settings:search",
+ group = "settings",
+ title = "Settings: search results",
+ # By aria-label, not `input[type="text"]`: the search box ships no `type` attribute at
+ # all, so a type selector matches the Embedding model field further down the General
+ # panel and fills THAT instead -- a reach that succeeds and lands somewhere else.
+ reach = (
+ ("goto", "/settings"),
+ ("wait", 500),
+ ("fill", '.settings-surface input[aria-label^="Search settings"]', "model"),
+ ("wait", 500),
+ ),
+ settle = {
+ "js": '(document.querySelector(".settings-surface main").innerText || "")'
+ ".trim().length > 0"
+ },
+ restore = ESCAPE_OUT + HOME,
+ root = (".settings-surface", '[data-slot="dialog-content"]'),
+ ),
+ # ── the sidebar ─────────────────────────────────────────────────
+ Surface(
+ id = "sidebar:expanded",
+ group = "sidebar",
+ title = "Sidebar, expanded",
+ reach = (("wait", 200),),
+ settle = {"visible": '[data-slot="sidebar-container"]'},
+ restore = (),
+ root = ROOT_SIDEBAR,
+ ),
+ Surface(
+ id = "sidebar:collapsed",
+ group = "sidebar",
+ title = "Sidebar, collapsed to the rail",
+ reach = (("click", 'button[aria-label="Close sidebar"]'), ("wait", 500)),
+ # The rail is the same container in a different data-state, so presence proves
+ # nothing; the reopen control appearing is what says the collapse happened.
+ settle = {"visible": 'button[aria-label="Open sidebar"]'},
+ restore = (("click_if", 'button[aria-label="Open sidebar"]'), ("wait", 400)) + HOME,
+ root = ROOT_SIDEBAR,
+ ),
+ Surface(
+ id = "sidebar:account-menu",
+ group = "sidebar",
+ title = "Account menu",
+ reach = (("click", 'button[aria-label^="Unsloth account menu"]'), ("wait", 400)),
+ settle = {"visible": ".app-user-menu"},
+ restore = ESCAPE_OUT,
+ root = (".app-user-menu",),
+ ),
+ Surface(
+ id = "sidebar:thread-menu",
+ group = "sidebar",
+ title = "Chat row options menu",
+ reach = (
+ ("hover", '[class*="group/recent-item"]'),
+ ("wait", 300),
+ ("click", 'button[aria-label="Chat options"]'),
+ ("wait", 400),
+ ),
+ settle = {"count_at_least": ['[role="menuitem"]', 3]},
+ restore = ESCAPE_OUT,
+ root = ('[role="menu"]',),
+ conditional = "needs at least one chat in the sidebar",
+ ),
+ Surface(
+ id = "sidebar:organize-menu",
+ group = "sidebar",
+ title = "Organize chats menu",
+ reach = (
+ ("hover", '[data-slot="sidebar-group-label"]:has(button[aria-label="Organize chats"])'),
+ ("wait", 300),
+ ("click", 'button[aria-label="Organize chats"]'),
+ ("wait", 400),
+ ),
+ settle = {"count_at_least": ['[role="menuitemradio"]', 2]},
+ restore = ESCAPE_OUT,
+ root = ('[role="menu"]',),
+ ),
+ Surface(
+ id = "sidebar:new-project",
+ group = "sidebar",
+ title = "New project dialog",
+ reach = (
+ ("hover", '[class*="group/projects-item"]'),
+ ("wait", 300),
+ ("click", 'button[aria-label="New project"]'),
+ ("wait", 500),
+ ),
+ settle = {"visible": '[data-slot="dialog-content"]'},
+ restore = ESCAPE_OUT + HOME,
+ root = ('[data-slot="dialog-content"]',),
+ ),
+ Surface(
+ id = "sidebar:search",
+ group = "sidebar",
+ title = "Chat search command dialog",
+ reach = (("click", 'button[aria-label="Search"]'), ("wait", 500)),
+ settle = {"visible": ".chat-search-surface"},
+ restore = ESCAPE_OUT,
+ root = (".chat-search-surface",),
+ ),
+ Surface(
+ id = "sidebar:workflows",
+ group = "sidebar",
+ title = "Images workflow sub-rows",
+ reach = (
+ ("hover", '[class*="group/images-item"]'),
+ ("wait", 300),
+ ("click", 'button[aria-label="Show workflows"]'),
+ ("wait", 400),
+ ),
+ settle = {"visible": 'button[aria-label="Hide workflows"]'},
+ restore = (("click_if", 'button[aria-label="Hide workflows"]'), ("wait", 300)),
+ root = ROOT_SIDEBAR,
+ ),
+ # ── the chat composer's own overlays ────────────────────────────
+ Surface(
+ id = "chat:model-picker",
+ group = "chat",
+ title = "Model picker",
+ reach = (("click", ".unsloth-model-selector-trigger"), ("wait", 600)),
+ # The rows, not the menu. The popover mounts before its list has been fetched, so a
+ # settle on the container's presence digests an empty picker roughly half the time --
+ # and an empty picker and a broken picker have the same digest.
+ settle = {"count_at_least": [".unsloth-model-selector-menu button", 2]},
+ restore = ESCAPE_OUT,
+ root = (".unsloth-model-selector-menu",),
+ also_in_film = True,
+ ),
+ Surface(
+ id = "chat:model-picker-ondevice",
+ group = "chat",
+ title = "Model picker, On Device tab",
+ reach = (
+ ("click", ".unsloth-model-selector-trigger"),
+ ("wait", 600),
+ ("click", '.unsloth-model-selector-menu [role="tab"]:nth-of-type(2)'),
+ ("wait", 500),
+ ),
+ settle = {"visible": ".unsloth-model-selector-menu"},
+ restore = ESCAPE_OUT,
+ root = (".unsloth-model-selector-menu",),
+ ),
+ Surface(
+ id = "chat:plus-menu",
+ group = "chat",
+ title = "Tools and attachments menu",
+ reach = (("click", 'button[aria-label="Tools and attachments"]'), ("wait", 400)),
+ settle = {"count_at_least": ['[role="menuitem"]', 1]},
+ restore = ESCAPE_OUT,
+ root = ('[role="menu"]',),
+ also_in_film = True,
+ ),
+ Surface(
+ id = "chat:run-settings",
+ group = "chat",
+ title = "Run settings sheet",
+ reach = (("click", 'button[aria-label="Open run settings"]'), ("wait", 600)),
+ settle = {"visible": 'button[aria-label="Close run settings"]'},
+ restore = (("click_if", 'button[aria-label="Close run settings"]'), ("wait", 400)) + HOME,
+ # The panel, not a sheet. Despite the file being called chat-settings-sheet it renders
+ # as a docked column inside the chat layout, so it is in NO overlay list and a root of
+ # `[role="dialog"]` falls through to body -- which digested 301,402 characters of
+ # whole page and called it the run settings panel.
+ root = ('[data-slot="chat-settings-panel"]',),
+ ),
+ Surface(
+ id = "chat:permission-menu",
+ group = "chat",
+ title = "Tool permission menu",
+ reach = (("click", 'button[aria-label="Permission level for tool calls"]'), ("wait", 400)),
+ settle = {"count_at_least": ['[role="menuitem"], [role="option"]', 2]},
+ restore = ESCAPE_OUT,
+ root = ('[role="menu"]', '[role="listbox"]'),
+ ),
+ Surface(
+ id = "chat:system-prompt",
+ group = "chat",
+ title = "System prompt editor",
+ # Through the run settings panel. The edit control is rendered at x=1458 on a 1440
+ # viewport when the panel is closed -- present, sized, and off screen -- so clicking
+ # it directly times out on an element every presence check reports as there.
+ reach = (
+ ("click", 'button[aria-label="Open run settings"]'),
+ ("wait", 800),
+ ("click", 'button[aria-label="Edit system prompt"]'),
+ ("wait", 800),
+ ),
+ settle = {"visible": '[data-slot="dialog-content"]'},
+ restore = ESCAPE_OUT + HOME,
+ root = ('[data-slot="dialog-content"]',),
+ ),
+ Surface(
+ id = "chat:temporary",
+ group = "chat",
+ title = "Temporary chat, on",
+ reach = (("click", 'button[aria-label="Turn on temporary chat"]'), ("wait", 500)),
+ settle = {"visible": 'button[aria-label="Turn off temporary chat"]'},
+ restore = (("click_if", 'button[aria-label="Turn off temporary chat"]'), ("wait", 300))
+ + HOME,
+ root = ROOT_ROUTE,
+ ),
+ Surface(
+ id = "chat:composer-filled",
+ group = "chat",
+ title = "Composer holding text",
+ reach = (("fill", COMPOSER, "studiobench surface sweep"), ("wait", 400)),
+ # The send control is what changes, and it is the same control the film's stop action
+ # trips over: with text in the box the Stop button is replaced by Queue.
+ # ONE EXPRESSION. The settle evaluator wraps the string in `return (...)`, so a
+ # statement -- a `const` declaration, say -- raises SyntaxError at evaluation time,
+ # and the surface is recorded as never settling for a reason that is about this file
+ # rather than about the app.
+ settle = {
+ "js": "(document.querySelector("
+ "'textarea[aria-label=\"Message input\"]') || {}).value ? true : false"
+ },
+ restore = (("fill", COMPOSER, ""), ("wait", 200)) + HOME,
+ root = ROOT_ROUTE,
+ also_in_film = True,
+ volatile = GREETING_IS_RANDOM,
+ ),
+ # ── the hub ─────────────────────────────────────────────────────
+ Surface(
+ id = "hub:datasets",
+ group = "hub",
+ title = "Hub, datasets tab",
+ reach = (
+ ("goto", "/hub"),
+ ("wait", 800),
+ ("click", 'button[aria-label="Datasets"]'),
+ ("wait", 800),
+ ),
+ # The URL flips the instant the tab is pressed, well before the list arrives. Settling
+ # on the URL alone digested an empty table on one visit and a populated one on the
+ # next, a 424-line difference that had nothing to do with any build.
+ settle = {
+ "js": 'location.search.includes("kind=datasets") && '
+ '(document.body.innerText || "").includes("Downloads")'
+ },
+ restore = HOME,
+ root = ROOT_ROUTE,
+ conditional = "needs the catalogue, which needs network",
+ volatile = HUB_IS_REMOTE,
+ ),
+ # The hub's two filter popovers are LISTBOXES, not menus. `[role="menuitem"]` counted zero on
+ # a popover that was open and visible on screen, and zero from a wrong selector is the failure
+ # mode this tool exists to refuse -- so both the settle and the root read `option`/`listbox`.
+ Surface(
+ id = "hub:format-filter",
+ group = "hub",
+ title = "Hub, format filter menu",
+ reach = (
+ ("goto", "/hub"),
+ ("wait", 800),
+ ("click", 'button[aria-label="Format filter"]'),
+ ("wait", 400),
+ ),
+ settle = {"count_at_least": ['[role="option"]', 2]},
+ restore = ESCAPE_OUT + HOME,
+ root = ('[role="listbox"]',),
+ conditional = "needs the catalogue, which needs network",
+ ),
+ Surface(
+ id = "hub:sort-menu",
+ group = "hub",
+ title = "Hub, sort menu",
+ reach = (
+ ("goto", "/hub"),
+ ("wait", 800),
+ ("click", 'button[aria-label="Sort models"]'),
+ ("wait", 400),
+ ),
+ settle = {"count_at_least": ['[role="option"]', 2]},
+ restore = ESCAPE_OUT + HOME,
+ root = ('[role="listbox"]',),
+ conditional = "needs the catalogue, which needs network",
+ ),
+ Surface(
+ id = "hub:hf-token",
+ group = "hub",
+ title = "Hub, Hugging Face token entry",
+ reach = (
+ ("goto", "/hub"),
+ ("wait", 800),
+ ("click", 'button[aria-label="Set Hugging Face token"]'),
+ ("wait", 800),
+ ),
+ settle = {"visible": ".settings-surface"},
+ restore = ESCAPE_OUT + HOME,
+ root = (".settings-surface", '[data-slot="dialog-content"]'),
+ notes = "the hub's token control does not open a popover of its own: it opens the "
+ "settings dialog. Registered against what it actually does, so a change that "
+ "made it open nothing is a failure here rather than an unnoticed no-op",
+ ),
+ Surface(
+ id = "hub:compact-layout",
+ group = "hub",
+ title = "Hub, compact layout",
+ reach = (
+ ("goto", "/hub"),
+ ("wait", 800),
+ ("click", 'button[aria-label="Compact"]'),
+ ("wait", 600),
+ ),
+ settle = {"js": 'location.pathname === "/hub"'},
+ restore = HOME,
+ root = ROOT_ROUTE,
+ conditional = "needs the catalogue, which needs network",
+ volatile = HUB_IS_REMOTE,
+ ),
+ # ── the media pages ─────────────────────────────────────────────
+ Surface(
+ id = "images:presets",
+ group = "media",
+ title = "Images, presets menu",
+ reach = (
+ ("goto", "/images"),
+ ("wait", 800),
+ ("click", 'button[aria-label="Manage image generation presets"]'),
+ ("wait", 500),
+ ),
+ settle = {
+ "js": 'document.querySelectorAll(\'[role="menu"], '
+ "[data-radix-popper-content-wrapper]').length > 0"
+ },
+ restore = ESCAPE_OUT + HOME,
+ root = ('[role="menu"]', "[data-radix-popper-content-wrapper]"),
+ ),
+ Surface(
+ id = "images:model-picker",
+ group = "media",
+ title = "Images, model picker",
+ reach = (
+ ("goto", "/images"),
+ ("wait", 800),
+ ("click", ".unsloth-model-selector-trigger"),
+ ("wait", 600),
+ ),
+ settle = {"visible": ".unsloth-model-selector-menu"},
+ restore = ESCAPE_OUT + HOME,
+ root = (".unsloth-model-selector-menu",),
+ ),
+ Surface(
+ id = "video:presets",
+ group = "media",
+ title = "Video, presets menu",
+ reach = (
+ ("goto", "/video"),
+ ("wait", 800),
+ ("click", 'button[aria-label="Manage video generation presets"]'),
+ ("wait", 500),
+ ),
+ settle = {
+ "js": 'document.querySelectorAll(\'[role="menu"], '
+ "[data-radix-popper-content-wrapper]').length > 0"
+ },
+ restore = ESCAPE_OUT + HOME,
+ root = ('[role="menu"]', "[data-radix-popper-content-wrapper]"),
+ conditional = "a host without video support renders the gate instead of the page",
+ ),
+ # ── train ───────────────────────────────────────────────────────
+ Surface(
+ id = "train:model-picker",
+ group = "train",
+ title = "Train, model picker",
+ reach = (
+ ("goto", "/studio"),
+ ("wait", 1200),
+ ("click", 'button[aria-label="Model: Select model"]'),
+ ("wait", 600),
+ ),
+ settle = {
+ "js": "document.querySelectorAll('.unsloth-model-selector-menu, "
+ '[role="menu"], [data-radix-popper-content-wrapper]\').length > 0'
+ },
+ restore = ESCAPE_OUT + HOME,
+ root = (".unsloth-model-selector-menu", "[data-radix-popper-content-wrapper]"),
+ conditional = "a chat-only host redirects /studio to /chat",
+ ),
+ Surface(
+ id = "train:method",
+ group = "train",
+ title = "Train, method selector",
+ reach = (
+ ("goto", "/studio"),
+ ("wait", 1200),
+ ("click", 'button[aria-label^="Method:"]'),
+ ("wait", 500),
+ ),
+ settle = {
+ "js": 'document.querySelectorAll(\'[role="menu"], [role="listbox"], '
+ "[data-radix-popper-content-wrapper]').length > 0"
+ },
+ restore = ESCAPE_OUT + HOME,
+ root = ('[role="menu"]', '[role="listbox"]', "[data-radix-popper-content-wrapper]"),
+ conditional = "a chat-only host redirects /studio to /chat",
+ ),
+ Surface(
+ id = "train:dataset",
+ group = "train",
+ title = "Train, dataset picker",
+ reach = (
+ ("goto", "/studio"),
+ ("wait", 1200),
+ ("click", 'button[aria-label^="Dataset:"]'),
+ ("wait", 600),
+ ),
+ settle = {
+ "js": 'document.querySelectorAll(\'[role="menu"], [role="listbox"], '
+ "[data-radix-popper-content-wrapper]').length > 0"
+ },
+ restore = ESCAPE_OUT + HOME,
+ root = ('[role="menu"]', '[role="listbox"]', "[data-radix-popper-content-wrapper]"),
+ conditional = "a chat-only host redirects /studio to /chat",
+ ),
+ Surface(
+ id = "train:image-training",
+ group = "train",
+ title = "Image LoRA training",
+ reach = (
+ ("goto", "/studio"),
+ ("wait", 1200),
+ ("click", 'button[aria-label="Image training"]'),
+ ("wait", 1200),
+ ),
+ # It NAVIGATES. The control sits on the Train page but lands on /images with the
+ # training panel selected, so a settle written against /studio waits out its timeout
+ # on a page that arrived correctly.
+ settle = {
+ "js": 'location.pathname === "/images" && '
+ '(document.body.innerText || "").includes("Train a LoRA")'
+ },
+ restore = HOME,
+ root = ROOT_ROUTE,
+ conditional = "a chat-only host redirects /studio to /chat",
+ volatile = UNEXPLAINED_DRIFT,
+ ),
+ # ── the api monitor ─────────────────────────────────────────────
+ Surface(
+ id = "api:status-filter",
+ group = "api",
+ title = "API monitor, status filter",
+ reach = (
+ ("goto", "/api-monitor"),
+ ("wait", 800),
+ ("click", 'button[aria-label="Filter by status"]'),
+ ("wait", 400),
+ ),
+ settle = {
+ "js": 'document.querySelectorAll(\'[role="menu"], [role="listbox"], '
+ "[data-radix-popper-content-wrapper]').length > 0"
+ },
+ restore = ESCAPE_OUT + HOME,
+ root = ('[role="menu"]', '[role="listbox"]', "[data-radix-popper-content-wrapper]"),
+ ),
+]
+
+
+#: Surfaces that exist and are NOT swept, each with the mechanism that puts them out of reach.
+#:
+#: This list is the honest half of the coverage number. A manifest that reports "38 of 38 reached"
+#: while eleven surfaces were never registered is a worse artefact than one that reports 38 of 38
+#: and names the eleven, because the first invites the reader to believe the app is fully covered.
+KNOWN_UNCOVERED: tuple[dict, ...] = (
+ {
+ "id": "route:login",
+ "title": "Login page",
+ "reason": "requireGuest() redirects an authenticated session to /chat. Reaching it means "
+ "clearing the auth token, which ends the session the sweep and the film share, "
+ "so it is out of scope for a sweep that runs inside a measurement run",
+ },
+ {
+ "id": "route:change-password",
+ "title": "Change password page",
+ "reason": "requirePasswordChangeFlow() redirects unless the account is flagged "
+ "must_change_password, and studiobench's own authenticate() clears that flag "
+ "before the browser ever starts",
+ },
+ {
+ "id": "route:data-recipe-editor",
+ "title": "Data recipe editor (/data-recipes/$recipeId)",
+ "reason": "needs a saved recipe. Creating one writes to the installation the run is "
+ "measuring, and a sweep that mutates the app under test is not a parity check",
+ },
+ {
+ "id": "dialog:destructive-confirms",
+ "title": "Delete / archive / shutdown confirmations",
+ "reason": "reaching them means arming a destructive action against the installation under "
+ "test. The delete confirmation IS reached by the film's delete_message action, on "
+ "a thread the film created for the purpose",
+ },
+ {
+ "id": "dialog:promise-driven",
+ "title": "HF token warning, remote code consent, "
+ "transformers upgrade, stop running chats",
+ "reason": "root-mounted and opened by a promise that only resolves when a download, a model "
+ "load or a model swap actually needs consent. There is no trigger to click",
+ },
+ {
+ "id": "picker:connected-tab",
+ "title": "Model picker, Connected tab",
+ "reason": "rendered only when externalModels.length > 0. The A/B registers a pacer provider, "
+ "so it appears in a measurement run and not in a bare sweep; it is left out rather "
+ "than made to depend on which of the two is running",
+ },
+ {
+ "id": "picker:model-config-page",
+ "title": "Model picker, inference settings page",
+ "reason": "entered from a downloaded model's row action, so it needs a model cached on the "
+ "machine. A sweep that downloads one is not a sweep",
+ },
+ {
+ "id": "chat:message-surfaces",
+ "title": "Message action bar, reasoning pane, tool blocks, "
+ "response details sheet, attachment preview",
+ "reason": "all need a thread with an assistant reply, which is exactly what the film drives. "
+ "Covered there, at eighteen points, rather than duplicated here",
+ },
+ {
+ "id": "recipe-studio:*",
+ "title": "Recipe studio block sheet and its four dialogs",
+ "reason": "reached from inside a recipe being edited, which needs a saved recipe",
+ },
+ {
+ "id": "tour:guided",
+ "title": "Guided tour overlay",
+ "reason": "driven by a TOUR_OPEN_EVENT and a multi-step walkthrough that navigates on its "
+ "own. Sweeping it would leave the app in a state the next surface cannot start "
+ "from, which is the one thing a sweep may not do",
+ },
+ {
+ "id": "monitor:floating",
+ "title": "Floating resource monitor and API monitor overlays",
+ "reason": "both open themselves on live traffic or a settings toggle and then poll, so their "
+ "content changes on a timer. A digest of a surface that repaints on its own "
+ "reports a difference between two runs of the same build",
+ },
+)
+
+
+# ── accessors ───────────────────────────────────────────────────────
+
+
+def surfaces() -> list[Surface]:
+ return list(_SURFACES)
+
+
+def surface_ids() -> list[str]:
+ return [s.id for s in _SURFACES]
+
+
+def get_surface(surface_id: str) -> Optional[Surface]:
+ for s in _SURFACES:
+ if s.id == surface_id:
+ return s
+ return None
+
+
+def groups() -> dict[str, list[Surface]]:
+ out: dict[str, list[Surface]] = {}
+ for s in _SURFACES:
+ out.setdefault(s.group, []).append(s)
+ return out
+
+
+class RegistryError(ValueError):
+ pass
+
+
+VERBS = {"goto": 1, "click": 1, "click_if": 1, "hover": 1, "press": 1, "fill": 2, "wait": 1}
+
+
+def validate_registry(entries: Optional[list[Surface]] = None) -> None:
+ """Fail loudly on a registry that cannot be executed.
+
+ Run by the unit tests AND by the sweep before it opens a browser. A malformed entry that is
+ only discovered halfway through a sweep costs the surfaces after it, and the run reports them
+ as unreached for a reason that has nothing to do with the app.
+ """
+ entries = surfaces() if entries is None else entries
+ seen: set[str] = set()
+ for s in entries:
+ if s.id in seen:
+ raise RegistryError(f"duplicate surface id {s.id!r}")
+ seen.add(s.id)
+ if not s.id or not s.group or not s.title:
+ raise RegistryError(f"surface {s.id!r} is missing an id, group or title")
+ if not s.root:
+ raise RegistryError(f"surface {s.id!r} has no digest root")
+ # `reach` may be empty only for a surface that IS the known state; `restore` may be empty
+ # only when reaching it changed nothing. Both are declared, never inferred.
+ for name, steps in (("reach", s.reach), ("restore", s.restore)):
+ for step in steps:
+ if not step:
+ raise RegistryError(f"surface {s.id!r} has an empty {name} step")
+ verb = step[0]
+ if verb not in VERBS:
+ raise RegistryError(
+ f"surface {s.id!r} {name} step uses unknown verb {verb!r}; "
+ f"known verbs are {sorted(VERBS)}"
+ )
+ if len(step) - 1 != VERBS[verb]:
+ raise RegistryError(
+ f"surface {s.id!r} {name} step {verb!r} takes {VERBS[verb]} argument(s), "
+ f"got {len(step) - 1}"
+ )
+ if s.settle is not None and not isinstance(s.settle, dict):
+ raise RegistryError(f"surface {s.id!r} has a non-dict settle condition")
+ uncovered = {u["id"] for u in KNOWN_UNCOVERED}
+ clash = uncovered & seen
+ if clash:
+ raise RegistryError(
+ f"{sorted(clash)} are both registered and listed as known-uncovered; a surface "
+ "cannot be swept and out of reach at the same time"
+ )
+ for entry in KNOWN_UNCOVERED:
+ for key in ("id", "title", "reason"):
+ if not entry.get(key):
+ raise RegistryError(f"known-uncovered entry {entry!r} is missing {key!r}")
+
+
+__all__ = [
+ "Surface",
+ "surfaces",
+ "surface_ids",
+ "get_surface",
+ "groups",
+ "validate_registry",
+ "RegistryError",
+ "KNOWN_UNCOVERED",
+ "KNOWN_STATE_PATH",
+ "VERBS",
+]
diff --git a/tests/studio/studiobench/scoring/__init__.py b/tests/studio/studiobench/scoring/__init__.py
new file mode 100644
index 00000000000..364408d7b91
--- /dev/null
+++ b/tests/studio/studiobench/scoring/__init__.py
@@ -0,0 +1,101 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Scoring: pure functions over a payload, with no dependency on the harness.
+
+Everything in this package takes plain data and returns plain data. It never touches Playwright,
+a browser, a socket or the clock. That is deliberate: the arithmetic that turns milliseconds into
+a verdict is the part most likely to be wrong in a way nobody notices, so it is the part that
+must be unit-testable against synthetic payloads including adversarial ones (a crashed rung that
+must not outscore a slow one, a regression that must surface despite a positive headline).
+"""
+
+from .anchors import ( # noqa: F401
+ DEFAULT_NOISE_FLOOR_PCT,
+ METRIC_ANCHORS,
+ METRIC_BY_KEY,
+ MIN_WEIGHT_COVERAGE,
+ ONSET_METRIC_FLOOR,
+ ONSET_SCORE_THRESHOLD,
+ RUNG_TOKENS,
+ MetricAnchor,
+ rung_ladder_id,
+ weights_id,
+)
+from .ab import ( # noqa: F401
+ AbResult,
+ IncomparableRuns,
+ MetricComparison,
+ Pair,
+ RunIdentity,
+ assert_comparable,
+ bootstrap_geomean_ci,
+ compare,
+ noise_floor_from_null_control,
+ pairs_from_cells,
+)
+from .frames import ( # noqa: F401
+ JANK_FRAME_MS,
+ FrameStats,
+ build_histogram,
+ compute_frame_stats,
+ measure_refresh_interval_ms,
+)
+from .schema import ( # noqa: F401
+ EXCLUSION_REASONS,
+ ExcludedCell,
+ Measure,
+ PayloadSchemaError,
+ check_exclusion_reasons,
+ validate_payload,
+)
+from .score import ( # noqa: F401
+ LadderScore,
+ MetricScore,
+ RungScore,
+ log_rung_weights,
+ score_ladder,
+ score_metric,
+ score_rung,
+)
+
+__all__ = [
+ "AbResult",
+ "DEFAULT_NOISE_FLOOR_PCT",
+ "EXCLUSION_REASONS",
+ "ExcludedCell",
+ "FrameStats",
+ "IncomparableRuns",
+ "JANK_FRAME_MS",
+ "LadderScore",
+ "METRIC_ANCHORS",
+ "METRIC_BY_KEY",
+ "MIN_WEIGHT_COVERAGE",
+ "Measure",
+ "MetricAnchor",
+ "MetricComparison",
+ "MetricScore",
+ "ONSET_METRIC_FLOOR",
+ "ONSET_SCORE_THRESHOLD",
+ "Pair",
+ "PayloadSchemaError",
+ "RUNG_TOKENS",
+ "RunIdentity",
+ "RungScore",
+ "assert_comparable",
+ "bootstrap_geomean_ci",
+ "build_histogram",
+ "check_exclusion_reasons",
+ "compare",
+ "compute_frame_stats",
+ "log_rung_weights",
+ "measure_refresh_interval_ms",
+ "noise_floor_from_null_control",
+ "pairs_from_cells",
+ "rung_ladder_id",
+ "score_ladder",
+ "score_metric",
+ "score_rung",
+ "validate_payload",
+ "weights_id",
+]
diff --git a/tests/studio/studiobench/scoring/ab.py b/tests/studio/studiobench/scoring/ab.py
new file mode 100644
index 00000000000..b424ec2ad0d
--- /dev/null
+++ b/tests/studio/studiobench/scoring/ab.py
@@ -0,0 +1,435 @@
+# 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/B comparison: paired ratios, a bootstrap CI, and four ways to refuse to answer.
+
+The comparison is PAIRED AND INTERLEAVED WITHIN ONE SESSION. Cross-session drift on the measured
+machine ran to 8%: the same build, measured an hour apart, differs by more than most real wins.
+Two runs one after the other therefore cannot be subtracted, and this module will not do it. What
+it compares is base and treatment cells that were recorded alternately inside a single browser
+session, matched by (rung, metric), so whatever drifted drifted through both sides.
+
+THE NULL-TREATMENT CONTROL RUNS FIRST AND CAN VOID THE WHOLE THING. Before any real comparison,
+base is compared against base under two different arm ids. Whatever spread that produces IS the
+noise floor for this machine on this day; it is measured, not assumed. If the null control itself
+shows a difference outside its own band, the harness is not currently capable of resolving a
+difference and every number downstream of it is unquotable. That is reported as VOID, not as a
+result with a caveat.
+
+A REGRESSION BEYOND THE NOISE FLOOR IS A FAIL REGARDLESS OF THE HEADLINE. A change that improves
+the aggregate by 12% while tripling the worst frame is not a win, and a single headline number is
+exactly the instrument that would let it ship. Every metric is checked individually.
+
+FOUR REFUSALS. Rendering is refused outright when `bench_version`, `corpus_hash`, `rung_ladder_id`
+or `weights_id` differ between the two sides. Each of those changes what the numbers mean, and a
+table that prints them side by side is not a comparison, it is a category error with column
+headers.
+"""
+
+from __future__ import annotations
+
+import math
+import random
+from dataclasses import dataclass, field
+from typing import Any, Iterable, Mapping, Sequence
+
+from .anchors import DEFAULT_NOISE_FLOOR_PCT, METRIC_BY_KEY
+from .schema import Measure
+
+
+class IncomparableRuns(AssertionError):
+ """Raised when two runs cannot be put in the same table."""
+
+
+@dataclass(frozen = True)
+class RunIdentity:
+ """Everything that has to match before two sets of numbers may be compared."""
+
+ bench_version: str
+ corpus_hash: str
+ rung_ladder_id: str
+ weights_id: str
+ session_id: str
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "bench_version": self.bench_version,
+ "corpus_hash": self.corpus_hash,
+ "rung_ladder_id": self.rung_ladder_id,
+ "weights_id": self.weights_id,
+ "session_id": self.session_id,
+ }
+
+
+#: The fields that must match. `session_id` is separate because its failure mode is different:
+#: mismatched ids mean different meanings, a mismatched session means an 8% drift term.
+COMPARABILITY_FIELDS = ("bench_version", "corpus_hash", "rung_ladder_id", "weights_id")
+
+
+def assert_comparable(base: RunIdentity, treatment: RunIdentity) -> None:
+ problems = [
+ f"{field_name}: base={getattr(base, field_name)!r} treatment={getattr(treatment, field_name)!r}"
+ for field_name in COMPARABILITY_FIELDS
+ if getattr(base, field_name) != getattr(treatment, field_name)
+ ]
+ if problems:
+ raise IncomparableRuns(
+ "refusing to render an A/B table; these differ between the two sides:\n "
+ + "\n ".join(problems)
+ )
+ if base.session_id != treatment.session_id:
+ raise IncomparableRuns(
+ "refusing to render an A/B table across sessions: base session "
+ f"{base.session_id!r} != treatment session {treatment.session_id!r}. "
+ "Cross-session drift measured 8% on this machine, which is larger than most real "
+ "wins. Interleave both sides inside one session."
+ )
+
+
+@dataclass
+class Pair:
+ """One matched base/treatment reading at one rung for one metric."""
+
+ rung_tokens: int
+ metric_key: str
+ base: Measure
+ treatment: Measure
+
+ @staticmethod
+ def _divisible(measure: Measure) -> float | None:
+ """The value this arm contributes to a ratio, or None when it cannot contribute one.
+
+ A MEASURED ZERO IS A READING, AND `> 0` THREW THAT AWAY. `time_in_jank_pct` and
+ `jank_index` are 0.0 on any arm smooth enough to have no over-budget frames, which is the
+ ordinary state of a healthy base. Requiring both values to be strictly positive dropped
+ the pair, so a treatment that introduced 5% time-in-jank over a zero-jank base reported
+ `no reading` -- a false statement about two arms that both read -- kept the regression out
+ of the table, the headline and `result.regressions`, and, as a null control, neither voided
+ the run nor contributed to the noise floor derived from it. That last one is the worst of
+ the three: the floor is what every later comparison is judged against, so a null control
+ blind to the jank it introduced silently shrinks the effect size anything else can claim.
+
+ The rule is `score.py`'s, which the ladder scorer has always applied to exactly this case:
+ a sub-floor reading is at least as good as the floor, so use the floor rather than the raw
+ value. Dividing by it yields a BOUND on the ratio -- understating the regression, never
+ overstating it -- instead of an infinity or a silence. Two sub-floor arms give floor/floor
+ = 1.0, which is the honest answer and the one score.py's comment is about: instrument noise
+ on a fast machine must not invent a difference between two perfect builds.
+
+ WHAT THIS DELIBERATELY DOES NOT ADMIT. It keys on `has_reading`, so a measure that was
+ never attempted or that was attempted and failed still contributes nothing: those carry
+ `value is None` and are a different thing from a measured zero, which is the distinction
+ `frames.py` makes when it refuses to score an unscheduled rAF loop as zero jank. A zero
+ with no declared floor stays unusable too, because nothing bounds it. So this admits
+ readings that were taken and still excludes readings that were not.
+ """
+ if not measure.has_reading:
+ return None
+ value = float(measure.value)
+ if measure.sub_floor and measure.floor is not None and value >= 0:
+ return float(measure.floor)
+ return value if value > 0 else None
+
+ @property
+ def usable(self) -> bool:
+ return (
+ self._divisible(self.base) is not None and self._divisible(self.treatment) is not None
+ )
+
+ @property
+ def bounded(self) -> bool:
+ """True when either arm was sub-floor, so the ratio is a bound and not a point estimate."""
+ return self.usable and (self.base.sub_floor or self.treatment.sub_floor)
+
+ @property
+ def ratio(self) -> float:
+ """treatment / base. Below 1 is faster for a lower-is-better metric."""
+
+ return float(self._divisible(self.treatment)) / float(self._divisible(self.base))
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "rung_tokens": int(self.rung_tokens),
+ "metric_key": self.metric_key,
+ "base": self.base.to_json(),
+ "treatment": self.treatment.to_json(),
+ "ratio": self.ratio if self.usable else None,
+ "usable": self.usable,
+ "bounded": self.bounded,
+ }
+
+
+@dataclass
+class MetricComparison:
+ """One metric's paired result, with the range across rungs and a bootstrap CI."""
+
+ metric_key: str
+ n_pairs: int
+ ratio_geomean: float | None
+ ratio_min: float | None
+ ratio_max: float | None
+ ci_low: float | None
+ ci_high: float | None
+ verdict: str = "no_reading"
+ beyond_noise: bool = False
+ #: At least one contributing pair had a sub-floor arm, so the ratio is a BOUND: the true
+ #: magnitude is larger. Carried so the table can say so rather than let a number derived from
+ #: an instrument floor be quoted as a measurement.
+ bounded: bool = False
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "metric_key": self.metric_key,
+ "n_pairs": int(self.n_pairs),
+ "ratio_geomean": self.ratio_geomean,
+ "ratio_range": [self.ratio_min, self.ratio_max],
+ "ci95": [self.ci_low, self.ci_high],
+ "verdict": self.verdict,
+ "beyond_noise": bool(self.beyond_noise),
+ "bounded": bool(self.bounded),
+ }
+
+
+def bootstrap_geomean_ci(
+ ratios: Sequence[float],
+ *,
+ iterations: int = 2000,
+ confidence: float = 0.95,
+ bootstrap_seed: int = 0,
+) -> tuple[float | None, float | None]:
+ """Percentile bootstrap CI of the geometric mean of paired ratios.
+
+ Resampling is over PAIRS, which is the unit that was randomised. Resampling over individual
+ readings would treat base and treatment as independent samples and throw away the pairing
+ that is doing all the work here.
+ """
+
+ usable = [float(r) for r in ratios if r is not None and r > 0 and math.isfinite(r)]
+ if len(usable) < 3:
+ return None, None
+ rng = random.Random(bootstrap_seed)
+ logs = [math.log(r) for r in usable]
+ draws: list[float] = []
+ n = len(logs)
+ for _ in range(iterations):
+ sample = [logs[rng.randrange(n)] for _ in range(n)]
+ draws.append(math.exp(sum(sample) / n))
+ draws.sort()
+ tail = (1.0 - confidence) / 2.0
+ lo = draws[max(0, int(math.floor(tail * len(draws))))]
+ hi = draws[min(len(draws) - 1, int(math.ceil((1.0 - tail) * len(draws))) - 1)]
+ return lo, hi
+
+
+def _geomean(values: Sequence[float]) -> float | None:
+ usable = [float(v) for v in values if v is not None and v > 0 and math.isfinite(v)]
+ if not usable:
+ return None
+ return math.exp(sum(math.log(v) for v in usable) / len(usable))
+
+
+@dataclass
+class AbResult:
+ """The whole comparison, including the reason it may not be quoted."""
+
+ label: str
+ identity_base: RunIdentity
+ identity_treatment: RunIdentity
+ noise_floor_pct: float
+ noise_floor_source: str
+ metrics: list[MetricComparison] = field(default_factory = list)
+ pairs: list[Pair] = field(default_factory = list)
+ void: bool = False
+ void_reason: str | None = None
+ regressions: list[str] = field(default_factory = list)
+ headline_ratio: float | None = None
+ is_null_control: bool = False
+
+ @property
+ def verdict(self) -> str:
+ if self.void:
+ return "VOID"
+ if self.regressions:
+ return "FAIL"
+ if self.headline_ratio is None:
+ return "NO READING"
+ if abs(self.headline_ratio - 1.0) * 100.0 <= self.noise_floor_pct:
+ return "NO DIFFERENCE"
+ return "IMPROVED" if self.headline_ratio < 1.0 else "REGRESSED"
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "label": self.label,
+ "is_null_control": bool(self.is_null_control),
+ "identity_base": self.identity_base.to_json(),
+ "identity_treatment": self.identity_treatment.to_json(),
+ "noise_floor_pct": float(self.noise_floor_pct),
+ "noise_floor_source": self.noise_floor_source,
+ "void": bool(self.void),
+ "void_reason": self.void_reason,
+ "verdict": self.verdict,
+ "regressions": list(self.regressions),
+ "headline_ratio": self.headline_ratio,
+ "metrics": [m.to_json() for m in self.metrics],
+ "pairs": [p.to_json() for p in self.pairs],
+ }
+
+
+def compare(
+ label: str,
+ pairs: Sequence[Pair],
+ identity_base: RunIdentity,
+ identity_treatment: RunIdentity,
+ *,
+ noise_floor_pct: float = DEFAULT_NOISE_FLOOR_PCT,
+ noise_floor_source: str = "declared default",
+ is_null_control: bool = False,
+ bootstrap_seed: int = 0,
+) -> AbResult:
+ """Build one A/B result from interleaved paired cells.
+
+ Refuses (raises) on identity mismatch. Produces a VOID result, rather than raising, when the
+ data is present but cannot support a claim: that distinction matters because the first is a
+ caller bug and the second is a fact about the machine that belongs in the report.
+ """
+
+ assert_comparable(identity_base, identity_treatment)
+
+ result = AbResult(
+ label = label,
+ identity_base = identity_base,
+ identity_treatment = identity_treatment,
+ noise_floor_pct = float(noise_floor_pct),
+ noise_floor_source = noise_floor_source,
+ pairs = list(pairs),
+ is_null_control = is_null_control,
+ )
+
+ by_metric: dict[str, list[Pair]] = {}
+ for pair in pairs:
+ by_metric.setdefault(pair.metric_key, []).append(pair)
+
+ weighted_logs: list[tuple[float, float]] = []
+ for metric_key, metric_pairs in sorted(by_metric.items()):
+ usable = [p for p in metric_pairs if p.usable]
+ ratios = [p.ratio for p in usable]
+ geo = _geomean(ratios)
+ lo, hi = bootstrap_geomean_ci(ratios, bootstrap_seed = bootstrap_seed)
+ comparison = MetricComparison(
+ metric_key = metric_key,
+ n_pairs = len(usable),
+ ratio_geomean = geo,
+ ratio_min = min(ratios) if ratios else None,
+ ratio_max = max(ratios) if ratios else None,
+ ci_low = lo,
+ ci_high = hi,
+ bounded = any(p.bounded for p in usable),
+ )
+ if geo is None:
+ comparison.verdict = "no_reading"
+ else:
+ delta_pct = (geo - 1.0) * 100.0
+ anchor = METRIC_BY_KEY.get(metric_key)
+ lower_is_better = anchor.lower_is_better if anchor else True
+ worse = delta_pct > 0 if lower_is_better else delta_pct < 0
+ comparison.beyond_noise = abs(delta_pct) > noise_floor_pct
+ if not comparison.beyond_noise:
+ comparison.verdict = "within noise"
+ elif worse:
+ comparison.verdict = "regressed"
+ result.regressions.append(
+ f"{metric_key}: {abs(delta_pct):.1f}% worse "
+ f"(noise floor {noise_floor_pct:.1f}%)"
+ )
+ else:
+ comparison.verdict = "improved"
+ weight = anchor.weight if anchor else 1.0
+ weighted_logs.append((weight, math.log(geo)))
+ result.metrics.append(comparison)
+
+ if weighted_logs:
+ total_weight = sum(w for w, _ in weighted_logs)
+ result.headline_ratio = math.exp(sum(w * lg for w, lg in weighted_logs) / total_weight)
+
+ if is_null_control:
+ # A null control that shows a difference is the harness moving, not the build. Whatever
+ # it reports, no comparison run on the same machine at the same time can be believed.
+ offenders = [
+ f"{m.metric_key}: {abs((m.ratio_geomean - 1.0) * 100):.1f}%"
+ for m in result.metrics
+ if m.ratio_geomean is not None and abs(m.ratio_geomean - 1.0) * 100.0 > noise_floor_pct
+ ]
+ if offenders:
+ result.void = True
+ result.void_reason = (
+ "the null-treatment control (base vs base) moved beyond its own noise floor of "
+ f"{noise_floor_pct:.1f}%: " + ", ".join(offenders)
+ )
+ # A null control never counts as a regression; it is a measurement of the harness.
+ result.regressions = []
+
+ return result
+
+
+def noise_floor_from_null_control(
+ null_control: AbResult, *, minimum_pct: float = 1.0
+) -> tuple[float, str]:
+ """Derive this machine's noise floor from the null control it just ran.
+
+ The floor is the largest absolute per-metric deviation the null control showed, never below
+ `minimum_pct`. Using the measured spread rather than a constant is the difference between
+ "this machine can resolve 3%" and "we hope every machine can resolve 5%".
+
+ A BOUNDED RATIO IS NOT A DEVIATION and is excluded here. A metric whose base fell under its
+ instrument floor contributes the floor to the ratio, so the result says "at least this much"
+ rather than "this much": a null control that moved from no measurable jank to 5% yields a
+ ratio of 50 and would publish a 4,900% noise floor, which would then swallow every real effect
+ on that machine. Such a control has already set `void` on the same evidence -- the movement is
+ real and nothing measured beside it can be believed -- and that is the outcome that belongs to
+ it. The floor is a question about SPREAD, and only point estimates can answer it.
+ """
+
+ bounded = sum(1 for m in null_control.metrics if m.ratio_geomean is not None and m.bounded)
+ deviations = [
+ abs(m.ratio_geomean - 1.0) * 100.0
+ for m in null_control.metrics
+ if m.ratio_geomean is not None and not m.bounded
+ ]
+ if not deviations:
+ why = (
+ f"null control produced only bounded ratios ({bounded} metric(s) under an instrument "
+ "floor)"
+ if bounded
+ else "null control produced no ratios"
+ )
+ return DEFAULT_NOISE_FLOOR_PCT, f"declared default ({why})"
+ floor = max(minimum_pct, max(deviations))
+ note = f" ({bounded} bounded metric(s) excluded)" if bounded else ""
+ return floor, (
+ f"measured from the null-treatment control over {len(deviations)} metrics "
+ f"(worst deviation {max(deviations):.2f}%){note}"
+ )
+
+
+def pairs_from_cells(
+ base_cells: Mapping[int, Mapping[str, Measure]],
+ treatment_cells: Mapping[int, Mapping[str, Measure]],
+ metric_keys: Iterable[str] | None = None,
+) -> list[Pair]:
+ """Match base and treatment readings by (rung, metric). Unmatched readings are dropped.
+
+ Dropping is correct here and only here: an unmatched cell has no partner, so there is no
+ ratio to compute. It is NOT the same as dropping an incomplete rung from a score, where the
+ absence is itself the result.
+ """
+
+ keys = list(metric_keys) if metric_keys is not None else list(METRIC_BY_KEY)
+ out: list[Pair] = []
+ for rung in sorted(set(base_cells) & set(treatment_cells)):
+ for key in keys:
+ base = base_cells[rung].get(key)
+ treatment = treatment_cells[rung].get(key)
+ if base is None or treatment is None:
+ continue
+ out.append(Pair(rung_tokens = int(rung), metric_key = key, base = base, treatment = treatment))
+ return out
diff --git a/tests/studio/studiobench/scoring/anchors.py b/tests/studio/studiobench/scoring/anchors.py
new file mode 100644
index 00000000000..5d1a1641052
--- /dev/null
+++ b/tests/studio/studiobench/scoring/anchors.py
@@ -0,0 +1,165 @@
+# 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 declared anchor table: the only place a judgement about "good" is written down.
+
+Every scalar this benchmark produces is a chain of arbitrary choices, and the way that chain
+becomes dishonest is by being spread across six files so nobody can see it. So all of it is here,
+in one table, and the table is HASHED into `weights_id`. A report that compares two runs with
+different `weights_id` values is refused rather than rendered, because a scoring change and a
+performance change are indistinguishable in the output.
+
+WHY LOG ANCHORS. Latency is perceived multiplicatively: 20 ms -> 40 ms is the same felt step as
+200 ms -> 400 ms, and a linear map makes the entire interesting range (20-200 ms) occupy 4% of
+the scale while 2 s -> 4 s occupies half of it. That is the second way naive AUC lies: the curve
+goes flat exactly where users start to hurt. Each metric therefore declares two anchors, `good`
+(scores 100) and `bad` (scores 0), and interpolates in log space between them.
+
+The anchors are not measurements, they are targets, and they are argued for here rather than
+tuned until the numbers look nice:
+
+ keystroke_p95_ms good 20 / bad 500. 20 ms is one frame at 50 Hz, the point at which typing
+ stops feeling like typing at all. 500 ms is the point at which characters
+ arrive after you have stopped looking at the keyboard. This metric carries
+ the largest weight because the shipped complaint is about typing.
+ time_in_jank_pct good 0.5 / bad 60. Half a percent of wall time inside 100 ms+ frames is
+ one hitch a minute. 60% is a UI that is unresponsive more often than not.
+ jank_index good 0.1 / bad 50. Squared over-budget ms per ms of window.
+ max_frame_ms good 33 / bad 2000. Two frames at 60 Hz, versus a freeze long enough that
+ a user reaches for the window close button.
+ scroll_settle_ms good 100 / bad 3000.
+ menu_open_ms good 50 / bad 1500. A menu that takes a second and a half to open reads
+ as a click that did not register, and gets clicked again.
+
+WHY THESE SIX AND NOT THE FRAME NUMBERS ALONE. `time_in_jank_pct` catches uniform mediocrity and
+`jank_index` plus `max_frame_ms` catch the single stall; neither is allowed to be a headline on
+its own, and both are in the mean so a build cannot trade one for the other.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from dataclasses import dataclass, asdict
+from typing import Iterable, Mapping
+
+
+@dataclass(frozen = True)
+class MetricAnchor:
+ """One perceptual metric, its two anchors, its weight and its direction."""
+
+ key: str
+ unit: str
+ good: float
+ bad: float
+ weight: float
+ lower_is_better: bool = True
+ rationale: str = ""
+
+ def __post_init__(self) -> None:
+ if self.good <= 0 or self.bad <= 0:
+ raise ValueError(
+ f"{self.key}: log anchors require positive values; got good={self.good}, "
+ f"bad={self.bad}"
+ )
+ if self.lower_is_better and not self.bad > self.good:
+ raise ValueError(f"{self.key}: lower_is_better needs bad > good")
+ if not self.lower_is_better and not self.good > self.bad:
+ raise ValueError(f"{self.key}: higher_is_better needs good > bad")
+ if self.weight <= 0:
+ raise ValueError(f"{self.key}: weight must be positive")
+
+
+METRIC_ANCHORS: tuple[MetricAnchor, ...] = (
+ MetricAnchor(
+ key = "keystroke_p95_ms",
+ unit = "ms",
+ good = 20.0,
+ bad = 500.0,
+ weight = 0.25,
+ rationale = "the shipped complaint is typing latency, so it carries the most weight",
+ ),
+ MetricAnchor(
+ key = "time_in_jank_pct",
+ unit = "%",
+ good = 0.5,
+ bad = 60.0,
+ weight = 0.20,
+ rationale = "catches uniform mediocrity, which max and p95 both hide",
+ ),
+ MetricAnchor(
+ key = "jank_index",
+ unit = "ms",
+ good = 0.1,
+ bad = 50.0,
+ weight = 0.15,
+ rationale = "squared over-budget time, so one long freeze dominates many small ones",
+ ),
+ MetricAnchor(
+ key = "max_frame_ms",
+ unit = "ms",
+ good = 33.0,
+ bad = 2000.0,
+ weight = 0.15,
+ rationale = "the single stall, unsummarised",
+ ),
+ MetricAnchor(
+ key = "scroll_settle_ms",
+ unit = "ms",
+ good = 100.0,
+ bad = 3000.0,
+ weight = 0.15,
+ rationale = "scrolling a long thread is the second half of the shipped complaint",
+ ),
+ MetricAnchor(
+ key = "menu_open_ms",
+ unit = "ms",
+ good = 50.0,
+ bad = 1500.0,
+ weight = 0.10,
+ rationale = "a slow menu reads as a click that did not register",
+ ),
+)
+
+METRIC_BY_KEY: Mapping[str, MetricAnchor] = {m.key: m for m in METRIC_ANCHORS}
+
+#: The rung ladder, in tokens of thread content. Log-spaced on purpose: aggregation integrates
+#: over log(tokens), so evenly spaced rungs on the log axis give evenly spaced evidence.
+RUNG_TOKENS: tuple[int, ...] = (1_000, 10_000, 100_000, 500_000, 1_000_000)
+
+#: A rung counts as usable when its score clears this AND no single metric is catastrophic.
+#: The onset rung -- the largest usable rung -- is the human headline, because it survives being
+#: carried to a different machine in a way a 0-100 score does not.
+ONSET_SCORE_THRESHOLD = 50.0
+ONSET_METRIC_FLOOR = 10.0
+
+#: A rung whose measured metrics do not cover at least this fraction of the declared weight is
+#: INCOMPLETE, which scores 0. It does not drop out: a build that crashes at 500K must not
+#: outscore one that limps through it, and dropping the rung is exactly how that happens.
+MIN_WEIGHT_COVERAGE = 0.60
+
+#: Ratios inside this band are indistinguishable from run-to-run noise. Anything an A/B claims
+#: must clear it, and the NULL calibration arm must land inside it.
+DEFAULT_NOISE_FLOOR_PCT = 5.0
+
+
+def _canonical_table() -> dict:
+ return {
+ "metrics": [asdict(m) for m in METRIC_ANCHORS],
+ "onset_score_threshold": ONSET_SCORE_THRESHOLD,
+ "onset_metric_floor": ONSET_METRIC_FLOOR,
+ "min_weight_coverage": MIN_WEIGHT_COVERAGE,
+ "default_noise_floor_pct": DEFAULT_NOISE_FLOOR_PCT,
+ }
+
+
+def weights_id() -> str:
+ """Stable hash of every judgement in this file. Changing any of it changes the id."""
+
+ blob = json.dumps(_canonical_table(), sort_keys = True, separators = (",", ":"))
+ return "w-" + hashlib.sha256(blob.encode("utf-8")).hexdigest()[:12]
+
+
+def rung_ladder_id(rungs: Iterable[int] = RUNG_TOKENS) -> str:
+ blob = json.dumps(sorted(int(r) for r in rungs), separators = (",", ":"))
+ return "r-" + hashlib.sha256(blob.encode("utf-8")).hexdigest()[:12]
diff --git a/tests/studio/studiobench/scoring/frames.py b/tests/studio/studiobench/scoring/frames.py
new file mode 100644
index 00000000000..1747b015f08
--- /dev/null
+++ b/tests/studio/studiobench/scoring/frames.py
@@ -0,0 +1,263 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Frame statistics that catch jank in both directions, plus the histogram behind them.
+
+There are two completely different ways a UI is unpleasant and a single summary number always
+hides one of them:
+
+ * UNIFORM MEDIOCRITY -- every frame takes 120 ms. The mean is bad but no individual frame is
+ remarkable, and `max` says 130 ms, which sounds survivable.
+ * THE SINGLE STALL -- 5,000 frames at 8 ms and one at 3.4 s. The mean is excellent, the p95
+ is excellent, and the app was visibly frozen for three and a half seconds.
+
+So this module always produces THREE headline frame numbers and the report is not allowed to
+quote one alone:
+
+ time_in_jank_pct fraction of WALL TIME spent inside frames longer than 100 ms. Catches
+ uniform mediocrity, because it goes to 100% when every frame is bad.
+ jank_index sum(max(0, d - budget)^2) / window_ms. Squaring makes one 3.4 s frame
+ dominate a thousand 40 ms ones, which is also how a user remembers it.
+ max_frame_ms the single worst frame, unsummarised.
+
+plus the full histogram in the payload, because every summary above is a lossy view of it and
+disagreements between reviewers are settled from the histogram, not from an argument about which
+percentile is fairest.
+
+THE BUDGET IS MEASURED, NOT ASSUMED. A 16.7 ms constant silently mis-scores every 120 Hz laptop
+(everything looks fine) and every 30 Hz remote desktop (everything looks broken). `budget_ms`
+comes from the observed inter-frame distribution of the window itself; `refresh_source` records
+where it came from so a reader can see when it fell back.
+
+The 100 ms long-frame threshold is NOT scaled by refresh rate on purpose: it is a claim about
+human perception (RAIL's "feels like a break in continuity"), not about the display, and a
+120 Hz screen does not make a 100 ms freeze feel shorter.
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass, field
+from typing import Any, Sequence
+
+from .schema import Measure
+
+#: Perceptual constant. A frame longer than this reads as an interruption regardless of display.
+JANK_FRAME_MS = 100.0
+
+#: Detection floors. Below these the recorder cannot distinguish a reading from its own noise.
+FLOOR_FRAME_MS = 0.5
+FLOOR_TIME_IN_JANK_PCT = 0.1
+FLOOR_JANK_INDEX = 0.05
+
+#: A refresh interval outside this range is not a display, it is a broken recorder.
+REFRESH_MIN_MS = 3.0
+REFRESH_MAX_MS = 60.0
+REFRESH_FALLBACK_MS = 1000.0 / 60.0
+
+#: Log-spaced histogram edges, in ms. Chosen so that the interesting region (one frame, a few
+#: frames, a visible hitch, a freeze) each gets its own bucket rather than all landing in ">33".
+HISTOGRAM_EDGES_MS: tuple[float, ...] = (
+ 0.0,
+ 4.0,
+ 8.0,
+ 16.7,
+ 25.0,
+ 33.3,
+ 50.0,
+ 75.0,
+ 100.0,
+ 150.0,
+ 250.0,
+ 400.0,
+ 650.0,
+ 1000.0,
+ 1600.0,
+ 2500.0,
+ 4000.0,
+)
+
+
+@dataclass
+class FrameStats:
+ """Everything derivable from one window of inter-frame deltas."""
+
+ frames_total: int
+ window_ms: float
+ budget_ms: float
+ refresh_source: str
+ time_in_jank_pct: Measure
+ jank_index: Measure
+ max_frame_ms: Measure
+ p50_frame_ms: Measure
+ p95_frame_ms: Measure
+ p99_frame_ms: Measure
+ dropped_frames: Measure
+ effective_fps: Measure
+ histogram: list[dict[str, Any]] = field(default_factory = list)
+ no_frames_recorded: bool = False
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "frames_total": int(self.frames_total),
+ "window_ms": float(self.window_ms),
+ "budget_ms": float(self.budget_ms),
+ "refresh_source": self.refresh_source,
+ "no_frames_recorded": bool(self.no_frames_recorded),
+ "time_in_jank_pct": self.time_in_jank_pct.to_json(),
+ "jank_index": self.jank_index.to_json(),
+ "max_frame_ms": self.max_frame_ms.to_json(),
+ "p50_frame_ms": self.p50_frame_ms.to_json(),
+ "p95_frame_ms": self.p95_frame_ms.to_json(),
+ "p99_frame_ms": self.p99_frame_ms.to_json(),
+ "dropped_frames": self.dropped_frames.to_json(),
+ "effective_fps": self.effective_fps.to_json(),
+ "histogram": list(self.histogram),
+ }
+
+
+def measure_refresh_interval_ms(deltas: Sequence[float]) -> tuple[float, str]:
+ """Recover the display's frame interval from the window's own fastest frames.
+
+ The fast tail of the distribution is the display cadence: a frame cannot be delivered faster
+ than the compositor presents, so the low quantiles pile up on the refresh interval no matter
+ how badly the main thread is behaving. The median of the fastest quartile is used rather than
+ the minimum, because the minimum picks up coalesced or duplicated callbacks.
+ """
+
+ usable = [float(d) for d in deltas if d is not None and math.isfinite(d) and d > 0]
+ if len(usable) < 8:
+ return REFRESH_FALLBACK_MS, "fallback_too_few_frames"
+ usable.sort()
+ fast_quartile = usable[: max(2, len(usable) // 4)]
+ candidate = _percentile(fast_quartile, 50.0)
+ if not (REFRESH_MIN_MS <= candidate <= REFRESH_MAX_MS):
+ return REFRESH_FALLBACK_MS, f"fallback_out_of_range({candidate:.2f}ms)"
+ return candidate, "measured"
+
+
+def compute_frame_stats(
+ deltas: Sequence[float],
+ window_ms: float,
+ *,
+ declared_refresh_ms: float | None = None,
+ attempted: bool = True,
+ not_attempted_reason: str | None = None,
+) -> FrameStats:
+ """Turn one window of inter-frame deltas into the three-headline block.
+
+ `attempted=False` is for a window where the frame recorder was deliberately not installed.
+ It is NOT for a window where the recorder ran and saw nothing: that case is a reading of
+ "no frames", which is a symptom (an unscheduled rAF loop) and never a score of zero jank.
+ """
+
+ if not attempted:
+ reason = not_attempted_reason or "frame recorder not installed"
+ return FrameStats(
+ frames_total = 0,
+ window_ms = float(window_ms),
+ budget_ms = REFRESH_FALLBACK_MS,
+ refresh_source = "not_attempted",
+ time_in_jank_pct = Measure.not_attempted("%", reason),
+ jank_index = Measure.not_attempted("ms", reason),
+ max_frame_ms = Measure.not_attempted("ms", reason),
+ p50_frame_ms = Measure.not_attempted("ms", reason),
+ p95_frame_ms = Measure.not_attempted("ms", reason),
+ p99_frame_ms = Measure.not_attempted("ms", reason),
+ dropped_frames = Measure.not_attempted("frames", reason),
+ effective_fps = Measure.not_attempted("fps", reason),
+ histogram = [],
+ no_frames_recorded = False,
+ )
+
+ usable = [float(d) for d in deltas if d is not None and math.isfinite(d) and d >= 0]
+ window_ms = float(window_ms)
+
+ if declared_refresh_ms is not None and REFRESH_MIN_MS <= declared_refresh_ms <= REFRESH_MAX_MS:
+ budget_ms, refresh_source = float(declared_refresh_ms), "declared"
+ else:
+ budget_ms, refresh_source = measure_refresh_interval_ms(usable)
+
+ if not usable:
+ # The recorder was installed and produced nothing. That is the rAF-unscheduled trap:
+ # a compositor that decided nothing is visible stops SCHEDULING callbacks, and the naive
+ # reading is "zero dropped frames". Every metric here reads as a failed measurement so
+ # the tri-clock gate upstream is what decides whether the window survives.
+ reason = "frame recorder produced no frames (rAF may be unscheduled)"
+ return FrameStats(
+ frames_total = 0,
+ window_ms = window_ms,
+ budget_ms = budget_ms,
+ refresh_source = refresh_source,
+ time_in_jank_pct = Measure.failed("%", reason),
+ jank_index = Measure.failed("ms", reason),
+ max_frame_ms = Measure.failed("ms", reason),
+ p50_frame_ms = Measure.failed("ms", reason),
+ p95_frame_ms = Measure.failed("ms", reason),
+ p99_frame_ms = Measure.failed("ms", reason),
+ dropped_frames = Measure.failed("frames", reason),
+ effective_fps = Measure.failed("fps", reason),
+ histogram = [],
+ no_frames_recorded = True,
+ )
+
+ ordered = sorted(usable)
+ jank_time_ms = sum(d for d in usable if d > JANK_FRAME_MS)
+ denominator = window_ms if window_ms > 0 else sum(usable)
+ over_budget_sq = sum((d - budget_ms) ** 2 for d in usable if d > budget_ms)
+ dropped = sum(1 for d in usable if d > budget_ms * 1.5)
+
+ return FrameStats(
+ frames_total = len(usable),
+ window_ms = window_ms,
+ budget_ms = budget_ms,
+ refresh_source = refresh_source,
+ time_in_jank_pct = Measure.read(
+ 100.0 * jank_time_ms / denominator, "%", floor = FLOOR_TIME_IN_JANK_PCT
+ ),
+ jank_index = Measure.read(over_budget_sq / denominator, "ms", floor = FLOOR_JANK_INDEX),
+ max_frame_ms = Measure.read(max(usable), "ms", floor = FLOOR_FRAME_MS),
+ p50_frame_ms = Measure.read(_percentile(ordered, 50.0), "ms", floor = FLOOR_FRAME_MS),
+ p95_frame_ms = Measure.read(_percentile(ordered, 95.0), "ms", floor = FLOOR_FRAME_MS),
+ p99_frame_ms = Measure.read(_percentile(ordered, 99.0), "ms", floor = FLOOR_FRAME_MS),
+ dropped_frames = Measure.read(float(dropped), "frames", floor = None),
+ effective_fps = Measure.read(1000.0 * len(usable) / denominator, "fps", floor = None),
+ histogram = build_histogram(usable),
+ no_frames_recorded = False,
+ )
+
+
+def build_histogram(deltas: Sequence[float]) -> list[dict[str, Any]]:
+ """Log-spaced frame histogram. Always present in the payload, never summarised away."""
+
+ edges = list(HISTOGRAM_EDGES_MS)
+ buckets = [
+ {"lo_ms": edges[i], "hi_ms": edges[i + 1], "bucket_count": 0} for i in range(len(edges) - 1)
+ ]
+ buckets.append({"lo_ms": edges[-1], "hi_ms": None, "bucket_count": 0})
+ for delta in deltas:
+ placed = False
+ for bucket in buckets[:-1]:
+ if bucket["lo_ms"] <= delta < bucket["hi_ms"]:
+ bucket["bucket_count"] += 1
+ placed = True
+ break
+ if not placed:
+ buckets[-1]["bucket_count"] += 1
+ return buckets
+
+
+def _percentile(ordered: Sequence[float], pct: float) -> float:
+ """Linear-interpolated percentile over an already sorted sequence."""
+
+ if not ordered:
+ raise ValueError("percentile of an empty sequence")
+ if len(ordered) == 1:
+ return float(ordered[0])
+ rank = (pct / 100.0) * (len(ordered) - 1)
+ low = math.floor(rank)
+ high = math.ceil(rank)
+ if low == high:
+ return float(ordered[int(rank)])
+ weight = rank - low
+ return float(ordered[low]) * (1.0 - weight) + float(ordered[high]) * weight
diff --git a/tests/studio/studiobench/scoring/from_payload.py b/tests/studio/studiobench/scoring/from_payload.py
new file mode 100644
index 00000000000..da9ac280310
--- /dev/null
+++ b/tests/studio/studiobench/scoring/from_payload.py
@@ -0,0 +1,323 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Turn a recorded payload into the `{rung: {metric_key: Measure}}` the scoring layer consumes.
+
+This is the seam between the two halves of the tool, and it was the one piece neither half owned:
+the session layer emits rows shaped around what it observed, the scoring layer consumes readings
+shaped around what it scores, and nothing converted one into the other. Until this existed the
+ladder, the A/B and the report were all unreachable from a real run.
+
+Two rules it exists to enforce:
+
+ A MISSING READING IS NOT A GOOD READING.
+ An action that did not run, an action that ran without the timing key, and an action that
+ was never in the scene are three different facts and produce three different notes. None of
+ them produces a number, and none of them produces a zero. This matters most for the actions
+ that legitimately do not run at small rungs -- `scroll_during_generation` reports "the thread
+ is shorter than the viewport" at 1K -- because scoring those as instant would make a small
+ thread look like a fast one.
+
+ THE QUANTITY SCORED IS NAMED, NOT ASSUMED.
+ Every Measure carries the payload key it came from, because the anchor names and the
+ recorded names are not always the same quantity (see SCROLL_SETTLE_NOTE below).
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Mapping, Sequence
+from typing import Any
+
+from .anchors import METRIC_BY_KEY
+from .frames import compute_frame_stats
+from .schema import Measure
+
+# ── where each scored metric actually lives in the payload ──────────────────────────────────
+
+# (action name, timing key). Anything not listed here comes from the window frame recorder.
+ACTION_SOURCES: Mapping[str, tuple[str, str]] = {
+ "keystroke_p95_ms": ("keystroke", "p95_ms"),
+ "menu_open_ms": ("message_menu", "open_ms"),
+ "scroll_settle_ms": ("scroll_after", "gesture_ms"),
+}
+
+# The one mapping that is NOT an identity of meaning, so it is stated rather than buried. The
+# anchor was written for settle time (how long after the gesture the thread stops moving); the
+# scene records the gesture itself and the per-step cost, and never measures settle separately.
+# `gesture_ms` is the closest recorded quantity and is on the same scale, but a reader comparing
+# this column against the anchor's 100 ms / 3000 ms rationale is comparing against a slightly
+# different thing, and should be told so in the cell rather than in a changelog.
+SCROLL_SETTLE_NOTE = (
+ "recorded as scroll_after.gesture_ms; the scene does not measure settle separately, so this "
+ "is gesture duration, not post-gesture settle"
+)
+
+FRAME_METRICS: tuple[str, ...] = ("time_in_jank_pct", "jank_index", "max_frame_ms")
+
+# Windows that are deliberately quiet. Pooling these into the frame metrics would dilute every
+# jank share with idle time and make a bad build look average.
+IDLE_WINDOW_KINDS: frozenset[str] = frozenset({"idle"})
+
+
+# The row types keyed by `cell_id`, and so the ones a superseded attempt can leak through.
+ATTEMPT_ROW_TYPES: frozenset[str] = frozenset({"cell", "action", "window"})
+
+
+def latest_attempt_rows(records: Sequence[Mapping[str, Any]]) -> list[Mapping[str, Any]]:
+ """Drop the rows of a SUPERSEDED attempt at a cell, keeping every other row untouched.
+
+ `--resume` appends to the payload it is continuing and re-runs the cells that DID NOT
+ complete, and `make_cell_id` is deterministic: the retry of `r10K.base.rep0` is written under
+ the same `cell_id` as the attempt that died. Nothing downstream keys on the attempt, so both
+ were read as one cell. Two ways that produced a wrong number, neither of them visible:
+
+ THE DEAD ATTEMPT'S FRAMES BECAME THE RETRY'S. `_frame_measures` pools every window row
+ carrying the cell id, so a 100 ms frame from the run that crashed stayed the RETRY's
+ `max_frame_ms`, and its gaps stayed in the retry's jank distribution.
+
+ THE RETRY DID NOT COUNT. `measures_from_records` keeps the FIRST cell row per rung and
+ `report.build._completion_by_rung` keeps a failure over a success, so a rung whose only
+ failure had already been re-run successfully still scored zero as INCOMPLETE.
+
+ An attempt is `(cell_id, session_id)` and the LAST one in file order wins, which is the one
+ the resumed run just wrote. Rows without a session id are kept: a payload from before the
+ recorder stamped them cannot be split into attempts, and dropping it would lose the run.
+
+ THE LATEST ATTEMPT IS THE LAST ONE THAT WROTE ANYTHING, not the last one that FINISHED. Keying
+ this on cell rows alone made an attempt invisible unless it reached its terminal row, and
+ `CellRunner.run` writes that in a `finally` -- which a SIGKILL, an OOM kill or a lost machine
+ never reaches, while the Recorder has already flushed and fsynced every action and window row
+ before it. So a resume hard-killed inside a cell left the older, completed attempt named as
+ the latest, and `__main__._resume_set` skipped it. Combined with a resume that had already
+ repaired an earlier pair, every cell then read as complete across two sessions, the next
+ `--resume` ran nothing at all and exited 0 over a stale table.
+
+ Any attempt-keyed row is evidence that an attempt happened, so all three types set it. This is
+ the same set the filter below applies to, which is the point: a row type that can leak from a
+ superseded attempt is a row type that can prove a newer one exists.
+ """
+ latest: dict[str, Any] = {}
+ for row in records:
+ if row.get("row_type") in ATTEMPT_ROW_TYPES and row.get("cell_id") is not None:
+ latest[str(row.get("cell_id"))] = row.get("session_id")
+
+ out: list[Mapping[str, Any]] = []
+ for row in records:
+ if row.get("row_type") in ATTEMPT_ROW_TYPES:
+ keep = latest.get(str(row.get("cell_id")))
+ if keep is not None and row.get("session_id") not in (None, keep):
+ continue
+ out.append(row)
+ return out
+
+
+def _cell_rows(records: Sequence[Mapping[str, Any]]) -> list[Mapping[str, Any]]:
+ return [r for r in records if r.get("row_type") == "cell"]
+
+
+def _actions_for(
+ records: Sequence[Mapping[str, Any]], cell_id: str
+) -> dict[str, Mapping[str, Any]]:
+ """Index the standalone `action` rows for one cell by action name.
+
+ The `actions` list embedded in the cell row is not used: it carries the timings but drops the
+ names, so it can only be decoded positionally and only if nothing was skipped.
+ """
+ out: dict[str, Mapping[str, Any]] = {}
+ for r in records:
+ if r.get("row_type") == "action" and r.get("cell_id") == cell_id:
+ name = r.get("action")
+ if name:
+ out[str(name)] = r
+ return out
+
+
+def _action_measure(metric_key: str, actions: Mapping[str, Mapping[str, Any]]) -> Measure:
+ action_name, timing_key = ACTION_SOURCES[metric_key]
+ unit = METRIC_BY_KEY[metric_key].unit
+ note = SCROLL_SETTLE_NOTE if metric_key == "scroll_settle_ms" else f"{action_name}.{timing_key}"
+
+ row = actions.get(action_name)
+ if row is None:
+ return Measure.not_attempted(unit, f"{action_name} is not in this scene")
+ if not row.get("ran"):
+ reason = row.get("reason") or "no reason recorded"
+ # Attempted-and-did-not-run, which is a fact about the run, not an absent instrument.
+ return Measure.failed(unit, f"{action_name} did not run: {reason}")
+ if row.get("expect_ok") is False:
+ # RAN IS NOT DID WHAT IT CLAIMED. An action carries its own assertion -- the composer's
+ # value grew by the characters that were typed, the menu that was opened has items, the
+ # panes that were expanded are open -- and when that assertion fails the timing describes
+ # something other than the action. `report/payload.py` already lists these cells under
+ # EXCLUDED CELLS with "its timings exist and must not be quoted"; scoring them anyway let
+ # the same number be excluded in the report and load-bearing in the headline.
+ reason = row.get("reason") or "no reason recorded"
+ return Measure.failed(unit, f"{action_name} ran but its own assertion failed: {reason}")
+
+ value = (row.get("timings") or {}).get(timing_key)
+ if value is None:
+ return Measure.failed(unit, f"{action_name} ran but recorded no {timing_key}")
+ return Measure.read(float(value), unit, note = note)
+
+
+def _frame_measures(windows: Sequence[Mapping[str, Any]]) -> dict[str, Measure]:
+ """Pool the active windows of one cell into the three frame metrics.
+
+ Pooled rather than averaged per window: `time_in_jank_pct` is a share of wall time and
+ `jank_index` is a sum normalised by wall time, so both are defined over the concatenated
+ distribution. Averaging per-window figures would weight a 2 s window equally with a 30 s one.
+ """
+ unit_by_key = {k: METRIC_BY_KEY[k].unit for k in FRAME_METRICS}
+
+ deltas: list[float] = []
+ window_ms = 0.0
+ truncated = 0
+ frameless = 0
+ attempted_any = False
+ max_frame: float | None = None
+
+ for w in windows:
+ frames = (w.get("instruments") or {}).get("frames")
+ if not isinstance(frames, Mapping):
+ continue
+ if not frames.get("frames_attempted"):
+ continue
+ attempted_any = True
+ mx = frames.get("max_frame_ms")
+ if mx is not None:
+ max_frame = float(mx) if max_frame is None else max(max_frame, float(mx))
+ if frames.get("frame_gaps_truncated"):
+ truncated += 1
+ continue
+ gaps = frames.get("frame_gaps_ms")
+ if not gaps:
+ frameless += 1
+ continue
+ deltas.extend(float(g) for g in gaps)
+ window_ms += float(w.get("duration_ms") or 0.0)
+
+ if not attempted_any:
+ reason = "no window in this cell had the frame recorder installed"
+ return {k: Measure.not_attempted(unit_by_key[k], reason) for k in FRAME_METRICS}
+
+ if frameless:
+ # ONE WINDOW THAT SAW NOTHING POISONS THE POOL, IT DOES NOT DROP OUT OF IT.
+ #
+ # A window whose recorder was installed and exported no deltas at all is the rAF-
+ # unscheduled trap, and `compute_frame_stats` already refuses to score it: a single such
+ # window reads `Measure.failed` on every metric with `no_frames_recorded` set, never zero
+ # jank. Pooled, the same window was skipped by the `continue` above -- it contributed no
+ # deltas, no wall time and (its `max_frame_ms` being null) no worst frame -- so the
+ # REMAINING windows answered for the whole cell and a complete freeze during one action
+ # came back as clean numbers: a 4 s frozen window beside a smooth one scored 0.0% time in
+ # jank and a 40 ms worst frame, byte-identical to the cell without the freeze in it.
+ # An unmeasured window is not an absent one, so the cell's frame metrics fail here for
+ # the same reason and in the same shape as the single-window path.
+ reason = (
+ f"{frameless} window(s) recorded no frames at all (rAF may be unscheduled), so the "
+ "pooled frame metrics would describe only the windows that were measured"
+ )
+ return {k: Measure.failed(unit_by_key[k], reason) for k in FRAME_METRICS}
+
+ out: dict[str, Measure] = {}
+ out["max_frame_ms"] = (
+ Measure.read(max_frame, "ms", note = "worst frame across the cell's active windows")
+ if max_frame is not None
+ else Measure.failed("ms", "the recorder ran but observed no frames")
+ )
+
+ if not deltas or window_ms <= 0:
+ reason = (
+ f"{truncated} window(s) exceeded the per-window gap cap, so their distribution was "
+ "not exported"
+ if truncated
+ else "the recorder ran but exported no per-frame deltas"
+ )
+ for k in ("time_in_jank_pct", "jank_index"):
+ out[k] = Measure.failed(unit_by_key[k], reason)
+ return out
+
+ stats = compute_frame_stats(deltas, window_ms)
+ out["time_in_jank_pct"] = stats.time_in_jank_pct
+ out["jank_index"] = stats.jank_index
+ return out
+
+
+def measures_from_records(
+ records: Sequence[Mapping[str, Any]], metric_keys: Iterable[str] | None = None
+) -> dict[int, dict[str, Measure]]:
+ """Build `{rung_tokens: {metric_key: Measure}}` from one run's payload rows.
+
+ A cell that did not complete still contributes its readings. Dropping it would be the same
+ mistake as scoring an incomplete rung as NaN: the fact that a build died at 500K is the most
+ important thing the run has to say, and it cannot say it if the rung disappears.
+ """
+ keys = list(metric_keys) if metric_keys is not None else list(METRIC_BY_KEY)
+ by_rung: dict[int, dict[str, Measure]] = {}
+
+ for cell in _cell_rows(records):
+ cell_id = cell.get("cell_id")
+ tokens = cell.get("target_tokens")
+ if cell_id is None or tokens is None:
+ continue
+ rung = int(tokens)
+
+ actions = _actions_for(records, str(cell_id))
+ windows = [
+ w
+ for w in records
+ if w.get("row_type") == "window"
+ and w.get("cell_id") == cell_id
+ and str(w.get("kind") or "") not in IDLE_WINDOW_KINDS
+ ]
+ frames = _frame_measures(windows)
+
+ readings: dict[str, Measure] = {}
+ for key in keys:
+ if key in ACTION_SOURCES:
+ readings[key] = _action_measure(key, actions)
+ elif key in frames:
+ readings[key] = frames[key]
+ else:
+ readings[key] = Measure.not_attempted(
+ METRIC_BY_KEY[key].unit, f"no source is wired for {key}"
+ )
+
+ # Repetitions of the same rung: keep the first and let the caller ask for reps
+ # explicitly. Silently averaging reps here would hide a bimodal rung.
+ by_rung.setdefault(rung, readings)
+
+ return by_rung
+
+
+def measures_by_cell(
+ records: Sequence[Mapping[str, Any]], metric_keys: Iterable[str] | None = None
+) -> dict[tuple[int, int], dict[str, Measure]]:
+ """`{(rung_tokens, rep): {metric_key: Measure}}` -- one entry per CELL, not per rung.
+
+ `measures_from_records` collapses repetitions because a score is per rung. An A/B must not:
+ every repetition is an independent paired observation, and with them collapsed a run with
+ `--reps 4` produces one pair per metric, the bootstrap reports "too few pairs", and the
+ confidence interval that decides whether a difference is real never has anything to work with.
+ """
+ keys = list(metric_keys) if metric_keys is not None else list(METRIC_BY_KEY)
+ out: dict[tuple[int, int], dict[str, Measure]] = {}
+
+ for cell in _cell_rows(records):
+ cell_id = cell.get("cell_id")
+ tokens = cell.get("target_tokens")
+ if cell_id is None or tokens is None:
+ continue
+ rep = int((cell.get("cell") or {}).get("rep") or 0)
+ single = measures_from_records(
+ [cell]
+ + [
+ r
+ for r in records
+ if r.get("row_type") in {"action", "window"} and r.get("cell_id") == cell_id
+ ],
+ keys,
+ )
+ for readings in single.values():
+ out[(int(tokens), rep)] = readings
+ return out
diff --git a/tests/studio/studiobench/scoring/schema.py b/tests/studio/studiobench/scoring/schema.py
new file mode 100644
index 00000000000..16301a298c2
--- /dev/null
+++ b/tests/studio/studiobench/scoring/schema.py
@@ -0,0 +1,440 @@
+# 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 value type that makes a bare zero unrepresentable.
+
+Every number this benchmark prints is one of three things and they are not interchangeable:
+
+ * a reading -- the instrument ran and saw this
+ * a reading below the -- the instrument ran and saw nothing it can distinguish from
+ detection floor nothing, which is NOT the same as seeing nothing
+ * not attempted -- the instrument did not run here at all
+
+A day of measurement was lost to the third being printed as `0.00`. `LayoutDuration` read as a
+flat `0.105 -> 0.134` across a 300x range in thread size, which is exactly what a harness prints
+when the mechanism it is charging never executed; a React stage read `0.00` because `<Profiler>`
+is stripped from a production build, and the run was quoted as "React costs nothing". Both are
+the same defect: a slot that was never filled rendered as a measurement of zero.
+
+So `Measure` carries `attempted` next to `value`, always, in memory and in the JSON, and
+`display()` refuses to emit a naked `0`:
+
+ Measure(0.04, attempted=True, unit="ms/update", floor=0.12)
+ -> "< 0.12 ms/update (instrument floor)"
+ Measure.not_attempted("ms", "profiling alias not verified")
+ -> "not attempted (profiling alias not verified)"
+
+`validate_payload()` is the enforcement arm: it walks an assembled payload and fails on any
+numeric zero that is not inside a measure object or explicitly exempted by key. That check runs
+in the unit tests over synthetic payloads AND over the real payload before the report renders,
+so the ban is a property of the schema rather than a rule contributors are asked to remember.
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass, field
+from typing import Any, Iterable, Mapping, Sequence
+
+MEASURE_KIND = "measure"
+
+#: Keys whose numeric zero is a genuine, meaningful zero rather than a missing measurement.
+#: Everything here is an index, an identifier, a declared constant or a cardinality that is
+#: interesting precisely when it is zero. Anything not on this list must be a `Measure`.
+ZERO_OK_KEYS = frozenset(
+ {
+ "index",
+ # The parity capture in scene/parity.js numbers its message rows with a bare loop
+ # counter (`i`), not `index`, so the first message of every capture is `i: 0`. That is
+ # 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",
+ "rung_index",
+ "arm_index",
+ "window_index",
+ "slot_index",
+ "step_index",
+ "bootstrap_seed",
+ "seed",
+ "count", # only under excluded_cells / histogram buckets, see validate_payload
+ "bucket_ms",
+ "bucket_count",
+ "spike_ms",
+ "dose",
+ "score", # a rung score of 0 is the whole point of the incomplete-rung rule
+ "weight",
+ "n_excluded",
+ "exit_code",
+ "residual_ms", # telescoping ladders are residual-free BY CONSTRUCTION; 0 is the claim
+ "at_ms", # record timestamps relative to the writer's start
+ "truncated_records",
+ "records_written",
+ "frames_total", # a window with no frames is a SYMPTOM; frames.py already flags it
+ "n_pairs",
+ # -- harness-row counters whose zero is the GOOD result, not a missing reading. Each of
+ # these is written unconditionally by the session layer for every cell, so "absent" and
+ # "zero" are already distinguishable: absent means the row was never written at all.
+ "slots_missed", # 0 means the film kept time, which is exactly what we want to read
+ "expect_failures", # 0 means every action's expectation held
+ "over_budget_ms", # 0 means the action fitted inside its slot
+ "seeded_chars", # the small rungs seed nothing; 0 is the truth about the cell
+ "seeded_messages",
+ "seed_seconds",
+ "bursts", # a pacer that never had to burst is a pacer that was never jammed
+ # Seeded-vs-streamed equivalence: 0 drift on a field is the PASSING result, and it is the
+ # single most load-bearing zero in the payload, because it is what licenses every rung
+ # above 10K to be seeded rather than streamed.
+ "drift",
+ # The two counts `drift` is computed FROM, in that same block. They are censuses of the
+ # DOM in each arm, so a field that is absent from both reads 0/0 and is the passing
+ # result: on a real quick-tier run `reasoning_spans` is 0 streamed and 0 seeded, and the
+ # payload marks the field `gating: false` in the same breath. Exempting the quotient but
+ # not the two numbers under it failed every payload that carried an equivalence block.
+ "streamed",
+ "seeded",
+ }
+)
+
+#: Subtrees the bare-zero walker does not descend into. These hold configuration, identity,
+#: histogram buckets and raw instrument bookkeeping, none of which is a measurement of the app.
+#: The boundary is a contract with the harness layer: anything that is a MEASUREMENT goes under
+#: a `metrics` key as a measure object, anything that is bookkeeping goes under `info`. Without
+#: that split the walker either fails on every legitimate counter or is switched off entirely,
+#: and switched off is how the ban stops existing.
+EXEMPT_SUBTREE_KEYS = frozenset(
+ {
+ "info",
+ "raw",
+ "config",
+ "env",
+ "identity",
+ "header",
+ "footer",
+ "record_counts",
+ "histogram",
+ "potency_counters",
+ # -- OBSERVATION subtrees written by the session layer. These are censuses of the DOM and
+ # the expectations checked against them: "0 code blocks" is a true statement about the
+ # page at that instant, not a failed measurement. They are never scored and never quoted
+ # as a cost; everything that IS scored reaches the report as a Measure via
+ # scoring/from_payload.py, and that path stays under the strict rule.
+ "census",
+ "census_before",
+ "census_after",
+ "census_peak",
+ "streamed_census",
+ "seeded_census",
+ "expect",
+ "notes",
+ "scene",
+ "cell",
+ "pacer",
+ "stream",
+ "clamp",
+ }
+)
+
+
+class PayloadSchemaError(AssertionError):
+ """Raised when a payload contains a number that cannot be interpreted."""
+
+
+@dataclass(frozen = True)
+class Measure:
+ """One number, plus everything needed to know whether it means anything.
+
+ `value` is `None` whenever there is no reading: either the instrument was never attempted
+ (`attempted is False`) or it was attempted and failed (`attempted is True`, `note` says how).
+ `floor` is the instrument's detection floor in `unit`; a magnitude under it renders as a
+ bound, never as a value and never as zero.
+ """
+
+ value: float | None
+ attempted: bool
+ unit: str = "ms"
+ floor: float | None = None
+ note: str | None = None
+
+ def __post_init__(self) -> None:
+ if not self.attempted and self.value is not None:
+ raise PayloadSchemaError(
+ "a Measure that was not attempted cannot carry a value; got "
+ f"value={self.value!r}"
+ )
+ if self.value is not None and not math.isfinite(float(self.value)):
+ raise PayloadSchemaError(f"non-finite Measure value {self.value!r}")
+ if self.floor is not None and self.floor <= 0:
+ raise PayloadSchemaError(f"detection floor must be positive; got {self.floor!r}")
+ if not self.attempted and not self.note:
+ raise PayloadSchemaError("a not-attempted Measure must say why")
+
+ # -- constructors -------------------------------------------------------------------
+
+ @classmethod
+ def not_attempted(cls, unit: str, reason: str) -> "Measure":
+ return cls(value = None, attempted = False, unit = unit, note = reason)
+
+ @classmethod
+ def failed(cls, unit: str, reason: str) -> "Measure":
+ """Attempted, but produced no usable reading. Distinct from both zero and skipped."""
+ return cls(value = None, attempted = True, unit = unit, note = reason)
+
+ @classmethod
+ def read(
+ cls,
+ value: float,
+ unit: str = "ms",
+ floor: float | None = None,
+ note: str | None = None,
+ ) -> "Measure":
+ return cls(value = float(value), attempted = True, unit = unit, floor = floor, note = note)
+
+ # -- predicates ---------------------------------------------------------------------
+
+ @property
+ def has_reading(self) -> bool:
+ return self.attempted and self.value is not None
+
+ @property
+ def sub_floor(self) -> bool:
+ """True when the instrument ran and could not distinguish the result from nothing."""
+ return (
+ self.has_reading
+ and self.floor is not None
+ and abs(float(self.value)) < float(self.floor)
+ )
+
+ # -- rendering ----------------------------------------------------------------------
+
+ def display(self) -> str:
+ if not self.attempted:
+ return f"not attempted ({self.note})"
+ if self.value is None:
+ return f"no reading ({self.note or 'instrument failed'})"
+ if self.sub_floor:
+ # A negative reading under the floor is bounded from below, not from above; printing
+ # it as `< floor` would read as "small and positive" for a value that is neither.
+ if float(self.value) < 0:
+ return f"> -{_fmt(self.floor)} {self.unit} (instrument floor)"
+ return f"< {_fmt(self.floor)} {self.unit} (instrument floor)"
+ return f"{_fmt(self.value)} {self.unit}"
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "kind": MEASURE_KIND,
+ "value": None if self.value is None else float(self.value),
+ "attempted": bool(self.attempted),
+ "unit": self.unit,
+ "floor": self.floor,
+ "sub_floor": self.sub_floor,
+ "note": self.note,
+ "display": self.display(),
+ }
+
+ @classmethod
+ def from_row(
+ cls,
+ row: Mapping[str, Any],
+ key: str,
+ *,
+ unit: str = "ms",
+ floor: float | None = None,
+ ) -> "Measure":
+ """Build a Measure from the harness layer's sibling-key convention.
+
+ Layer 1 emits JSON-safe scalars, so it cannot emit a Measure object. Its contract is the
+ same idea in flat form: a numeric key that can legitimately be zero carries
+ `<key>_attempted: bool`, and a quantity that could not be measured is `None` with
+ `<key>_reason: str`. This is the one place the two representations meet, so that the ban
+ on bare zeros survives the boundary instead of being re-argued on the other side of it.
+ """
+
+ value = row.get(key)
+ reason = row.get(f"{key}_reason")
+ attempted_key = f"{key}_attempted"
+ attempted = bool(row.get(attempted_key, key in row))
+ if value is None:
+ if attempted:
+ return cls.failed(unit, reason or f"{key} produced no reading")
+ return cls.not_attempted(unit, reason or f"{key} was not attempted")
+ if not attempted:
+ raise PayloadSchemaError(
+ f"{key} carries a value but {attempted_key} is false; a row cannot both have a "
+ "reading and claim it was never attempted"
+ )
+ return cls.read(float(value), unit, floor = floor, note = reason)
+
+ @classmethod
+ def from_json(cls, blob: Mapping[str, Any]) -> "Measure":
+ if blob.get("kind") != MEASURE_KIND:
+ raise PayloadSchemaError(f"not a measure object: {blob!r}")
+ return cls(
+ value = blob.get("value"),
+ attempted = bool(blob.get("attempted")),
+ unit = blob.get("unit", ""),
+ floor = blob.get("floor"),
+ note = blob.get("note"),
+ )
+
+
+def _fmt(value: float | None) -> str:
+ if value is None:
+ return "None"
+ value = float(value)
+ if value == 0:
+ return "0"
+ magnitude = abs(value)
+ if magnitude >= 100:
+ return f"{value:.0f}"
+ if magnitude >= 10:
+ return f"{value:.1f}"
+ if magnitude >= 1:
+ return f"{value:.2f}"
+ return f"{value:.3g}"
+
+
+@dataclass
+class ExcludedCell:
+ """One cell that did not make it into scoring, and why.
+
+ `excluded_cells` is mandatory and non-null in every payload. An empty list is a claim ("we
+ excluded nothing"); a missing key is an unanswered question, and the two used to print the
+ same way.
+ """
+
+ cell_id: str
+ reason: str
+ count: int = 1
+ detail: str | None = None
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "cell_id": self.cell_id,
+ "reason": self.reason,
+ "count": int(self.count),
+ "detail": self.detail,
+ }
+
+
+#: Reasons a cell may be excluded. Free-text reasons are refused so the report can total them.
+EXCLUSION_REASONS = frozenset(
+ {
+ "clock_disagreement",
+ "selfcheck_failed",
+ "renderer_crash",
+ "goto_timeout",
+ "slot_missed",
+ "arm_voided_invariance",
+ "arm_not_run_potency",
+ "bundle_arm_unavailable",
+ "overhead_correlated_with_treatment",
+ "seeding_fidelity_unverified",
+ "rung_incomplete",
+ }
+)
+
+
+def check_exclusion_reasons(cells: Iterable[ExcludedCell]) -> None:
+ for cell in cells:
+ if cell.reason not in EXCLUSION_REASONS:
+ raise PayloadSchemaError(
+ f"unknown exclusion reason {cell.reason!r} for cell {cell.cell_id!r}; "
+ "add it to EXCLUSION_REASONS so the report can total it"
+ )
+
+
+# ---------------------------------------------------------------------------------------
+# payload validation
+# ---------------------------------------------------------------------------------------
+
+
+def _is_measure(node: Any) -> bool:
+ return isinstance(node, Mapping) and node.get("kind") == MEASURE_KIND
+
+
+def validate_payload(payload: Mapping[str, Any]) -> None:
+ """Fail loudly on the two schema violations that made earlier reports unreadable.
+
+ 1. a numeric zero outside a measure object and outside the declared exemptions, which is
+ indistinguishable from "we never ran that";
+ 2. a missing or null `excluded_cells`.
+
+ Raises `PayloadSchemaError`. Callers run this before rendering anything.
+ """
+
+ if "excluded_cells" not in payload:
+ raise PayloadSchemaError("payload is missing the mandatory `excluded_cells` key")
+ if payload["excluded_cells"] is None:
+ raise PayloadSchemaError("`excluded_cells` is null; use [] to claim nothing was excluded")
+ if not isinstance(payload["excluded_cells"], Sequence):
+ raise PayloadSchemaError("`excluded_cells` must be a list")
+
+ problems: list[str] = []
+ _walk_for_bare_zeros(payload, path = "$", problems = problems)
+ if problems:
+ joined = "\n ".join(problems)
+ raise PayloadSchemaError(
+ "bare zeros found; every zero must be a Measure carrying `attempted`, or an "
+ f"exempted key:\n {joined}"
+ )
+
+
+def _is_number_list(node: Any) -> bool:
+ """A list of plain numbers, i.e. an instrument's raw samples rather than a structure."""
+
+ if not isinstance(node, (list, tuple)) or not node:
+ return False
+ return all(isinstance(x, (int, float)) and not isinstance(x, bool) for x in node)
+
+
+def _walk_for_bare_zeros(node: Any, path: str, problems: list[str]) -> None:
+ if _is_measure(node):
+ # A measure object is self-describing; its own zero is fine because `attempted` sits
+ # next to it. Do not descend, the inner `value` is exactly the thing being exempted.
+ if node.get("attempted") is None:
+ problems.append(f"{path}: measure object without `attempted`")
+ return
+ if isinstance(node, Mapping):
+ # The harness layer cannot emit measure objects (its rows are JSON-safe scalars), so it
+ # attests with a `<name>_attempted` flag. That flag is written ONCE PER INSTRUMENT BLOCK,
+ # not once per counter: the frames instrument emits `frames_attempted: true` alongside
+ # `frames_over_33`, `long_tasks` and the rest. An exact-name-sibling rule would demand
+ # `frames_over_33_attempted` and fail on every real row, and a check that fails on every
+ # real row gets switched off, which is how the ban stops existing.
+ #
+ # So a mapping that positively attests (any `*_attempted` key that is True) covers the
+ # numeric zeros DIRECTLY inside it. It does not cover nested mappings, which carry their
+ # own attestation or none.
+ attested = any(k.endswith("_attempted") and v is True for k, v in node.items())
+ for key, child in node.items():
+ if key in EXEMPT_SUBTREE_KEYS:
+ continue
+ covered = attested or f"{key}_attempted" in node
+ if (
+ isinstance(child, (int, float))
+ and not isinstance(child, bool)
+ and float(child) == 0.0
+ and covered
+ ):
+ continue
+ # The same attestation, for a plain numeric ARRAY directly inside the block. An
+ # instrument that attests reports samples as well as counters: `frames` writes
+ # `frames_attempted: true` next to `frame_gaps_ms`, whose entries are inter-frame
+ # gaps in whole milliseconds, so two frames in the same millisecond record a
+ # legitimate 0. Walking into the list dropped the attestation on the floor and every
+ # such run failed validation, which is the scalar case one line above with an extra
+ # pair of brackets around it.
+ if covered and _is_number_list(child):
+ continue
+ _walk_for_bare_zeros(child, f"{path}.{key}", problems)
+ return
+ if isinstance(node, (list, tuple)):
+ for index, child in enumerate(node):
+ _walk_for_bare_zeros(child, f"{path}[{index}]", problems)
+ return
+ if isinstance(node, bool):
+ return
+ if isinstance(node, (int, float)) and float(node) == 0.0:
+ leaf = path.rsplit(".", 1)[-1].split("[")[0]
+ if leaf not in ZERO_OK_KEYS:
+ problems.append(f"{path} = 0")
diff --git a/tests/studio/studiobench/scoring/score.py b/tests/studio/studiobench/scoring/score.py
new file mode 100644
index 00000000000..d6833463918
--- /dev/null
+++ b/tests/studio/studiobench/scoring/score.py
@@ -0,0 +1,337 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Per-metric scores, per-rung scores, the aggregate, and the onset rung.
+
+THREE WAYS A NAIVE AREA-UNDER-CURVE SCORE LIES, AND WHAT IS DONE ABOUT EACH.
+
+1. INTEGRATING OVER A LINEAR RUNG AXIS MAKES THE TOP RUNG THE WHOLE SCORE.
+ Rungs are 1K, 10K, 100K, 500K, 1M tokens. On a linear axis the 1M rung is half the width of
+ the entire integral and the 1K rung is 0.1% of it, so a build that is unusable at every size a
+ human actually uses scores well by being no worse than the competition at 1M. Integration
+ happens over log(tokens) instead, where the rungs are near-evenly spaced, which is also the
+ axis on which the underlying cost is believed to be a power law.
+
+2. INTEGRATING A RAW METRIC IS FLAT EXACTLY WHERE USERS HURT.
+ Milliseconds are unbounded above, so the curve is dominated by whichever rung is worst, and
+ the region between 20 ms and 200 ms -- where typing goes from fine to unpleasant -- is a
+ rounding error next to a 4 s stall at the top rung. Every metric is mapped through its log
+ anchors to a bounded [0, 100] perceptual score BEFORE any aggregation.
+
+3. AN INCOMPLETE RUNG THAT DROPS OUT MAKES CRASHING BETTER THAN LIMPING.
+ If a rung that fails to complete is skipped, a build that kills the renderer at 500K is scored
+ over 1K/10K/100K only -- its three best rungs -- and beats a build that finishes 500K slowly.
+ An incomplete rung scores 0 and keeps its weight. It never drops out. This is why
+ `RungScore.complete` and `MIN_WEIGHT_COVERAGE` exist.
+
+WHY THE PER-RUNG MEAN IS GEOMETRIC. A UI that types fine but cannot be scrolled is broken, and an
+arithmetic mean lets four good metrics rescue one catastrophic one: 100, 100, 100, 100, 0 averages
+to 80, which reads as a good build. The weighted geometric mean of that set is 0. A zero anywhere
+zeroes the rung, by construction and on purpose, because that is what the user experiences.
+
+WHY THE HEADLINE FOR HUMANS IS THE ONSET RUNG. A 0-100 score does not travel: run it on a
+different laptop and every number moves, so two testers cannot compare notes. "It is still usable
+at 100K and not at 500K" does travel, and it is the same shape as "highest playable settings",
+which people already know how to reason about. Ceiling shifts (the onset rung moving) are reported
+SEPARATELY and are never folded into the scalar, because a build that moves the ceiling by one
+rung and a build that shaves 8% off every metric are different kinds of win and averaging them
+produces a number that describes neither.
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass, field
+from typing import Any, Mapping, Sequence
+
+from .anchors import (
+ METRIC_ANCHORS,
+ METRIC_BY_KEY,
+ MIN_WEIGHT_COVERAGE,
+ ONSET_METRIC_FLOOR,
+ ONSET_SCORE_THRESHOLD,
+ RUNG_TOKENS,
+ MetricAnchor,
+ rung_ladder_id,
+ weights_id,
+)
+from .schema import Measure
+
+
+@dataclass
+class MetricScore:
+ """One metric's bounded [0, 100] score, or an explicit refusal to score it."""
+
+ key: str
+ score: float | None
+ scored: bool
+ weight: float
+ measure: Measure
+ reason: str | None = None
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "key": self.key,
+ "score": None if self.score is None else round(float(self.score), 3),
+ "scored": bool(self.scored),
+ "weight": float(self.weight),
+ "measure": self.measure.to_json(),
+ "reason": self.reason,
+ }
+
+
+def score_metric(anchor: MetricAnchor, measure: Measure) -> MetricScore:
+ """Map one reading onto [0, 100] by log interpolation between the declared anchors.
+
+ A measurement with no reading is NOT scored. It does not become a 0 (which would claim the
+ build is catastrophic at something we did not measure) and it does not become a 100 (which
+ would reward a build for an instrument that failed). It is excluded from the mean and
+ subtracted from the rung's weight coverage, which is the thing that decides whether the rung
+ is complete enough to score at all.
+ """
+
+ if not measure.has_reading:
+ reason = measure.note or ("not attempted" if not measure.attempted else "no reading")
+ return MetricScore(
+ key = anchor.key,
+ score = None,
+ scored = False,
+ weight = anchor.weight,
+ measure = measure,
+ reason = reason,
+ )
+
+ value = float(measure.value)
+ # A sub-floor reading is at least as good as the floor; scoring the raw value would let
+ # instrument noise on a fast machine invent a difference between two perfect builds.
+ if measure.sub_floor and measure.floor is not None and anchor.lower_is_better:
+ value = min(abs(value), float(measure.floor))
+
+ good, bad = float(anchor.good), float(anchor.bad)
+ if value <= 0:
+ # Log space has no zero. A non-positive reading on a positive-only metric is either
+ # perfect (below every floor) or a broken instrument; the floor logic above has already
+ # handled the honest case, so clamp to the good anchor and say so.
+ value = good if anchor.lower_is_better else bad
+
+ span = math.log(bad) - math.log(good)
+ fraction = (math.log(bad) - math.log(value)) / span
+ score = 100.0 * max(0.0, min(1.0, fraction))
+ return MetricScore(
+ key = anchor.key,
+ score = score,
+ scored = True,
+ weight = anchor.weight,
+ measure = measure,
+ )
+
+
+@dataclass
+class RungScore:
+ """One rung of the ladder: its metrics, its geometric mean, and whether it is usable."""
+
+ tokens: int
+ score: float
+ complete: bool
+ usable: bool
+ weight_coverage: float
+ metric_scores: list[MetricScore] = field(default_factory = list)
+ incomplete_reason: str | None = None
+ zeroed_by: list[str] = field(default_factory = list)
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "tokens": int(self.tokens),
+ "score": round(float(self.score), 3),
+ "complete": bool(self.complete),
+ "usable": bool(self.usable),
+ "weight_coverage": round(float(self.weight_coverage), 4),
+ "incomplete_reason": self.incomplete_reason,
+ "zeroed_by": list(self.zeroed_by),
+ "metric_scores": [m.to_json() for m in self.metric_scores],
+ }
+
+
+def score_rung(
+ tokens: int,
+ metrics: Mapping[str, Measure],
+ *,
+ completed: bool = True,
+ failure_mode: str | None = None,
+) -> RungScore:
+ """Score one rung. An incomplete rung scores 0 and keeps its weight in the aggregate.
+
+ `completed=False` covers every way a rung can fail to produce a session: a renderer crash, a
+ `goto` timeout, an out-of-memory kill. Each of those is a first-class RESULT about the build,
+ not a missing data point, and the score that describes it is 0.
+ """
+
+ metric_scores = [
+ score_metric(anchor, metrics.get(anchor.key) or _absent(anchor))
+ for anchor in METRIC_ANCHORS
+ ]
+
+ if not completed:
+ return RungScore(
+ tokens = int(tokens),
+ score = 0.0,
+ complete = False,
+ usable = False,
+ weight_coverage = 0.0,
+ metric_scores = metric_scores,
+ incomplete_reason = failure_mode or "rung did not complete",
+ )
+
+ scored = [m for m in metric_scores if m.scored]
+ total_weight = sum(a.weight for a in METRIC_ANCHORS)
+ coverage = (sum(m.weight for m in scored) / total_weight) if total_weight else 0.0
+
+ if coverage < MIN_WEIGHT_COVERAGE:
+ return RungScore(
+ tokens = int(tokens),
+ score = 0.0,
+ complete = False,
+ usable = False,
+ weight_coverage = coverage,
+ metric_scores = metric_scores,
+ incomplete_reason = (
+ f"only {coverage:.0%} of the declared metric weight produced a reading, "
+ f"below the {MIN_WEIGHT_COVERAGE:.0%} floor"
+ ),
+ )
+
+ zeroed_by = [m.key for m in scored if float(m.score) <= 0.0]
+ if zeroed_by:
+ # Geometric mean of a set containing zero IS zero. Written out rather than left to
+ # log(0) so the reason travels with the number.
+ rung_score = 0.0
+ else:
+ numerator = sum(m.weight * math.log(float(m.score)) for m in scored)
+ denominator = sum(m.weight for m in scored)
+ rung_score = math.exp(numerator / denominator)
+
+ worst = min((float(m.score) for m in scored), default = 0.0)
+ usable = rung_score >= ONSET_SCORE_THRESHOLD and worst >= ONSET_METRIC_FLOOR
+
+ return RungScore(
+ tokens = int(tokens),
+ score = rung_score,
+ complete = True,
+ usable = usable,
+ weight_coverage = coverage,
+ metric_scores = metric_scores,
+ zeroed_by = zeroed_by,
+ )
+
+
+def _absent(anchor: MetricAnchor) -> Measure:
+ return Measure.not_attempted(anchor.unit, f"{anchor.key} absent from the payload")
+
+
+def log_rung_weights(rungs: Sequence[int]) -> list[float]:
+ """Trapezoid weights on the log(tokens) axis, normalised to sum to 1.
+
+ This is the AUC over log(tokens) written as a weighted mean. A single rung gets weight 1.
+ Interior rungs get half the span on each side; the two ends get their one half-span, which is
+ why the top rung does not silently become the whole score.
+ """
+
+ ordered = sorted(int(r) for r in rungs)
+ if not ordered:
+ return []
+ if len(ordered) == 1:
+ return [1.0]
+ logs = [math.log(r) for r in ordered]
+ widths: list[float] = []
+ for i, _ in enumerate(logs):
+ lo = logs[i - 1] if i > 0 else logs[i]
+ hi = logs[i + 1] if i + 1 < len(logs) else logs[i]
+ widths.append((hi - lo) / 2.0)
+ total = sum(widths)
+ if total <= 0:
+ return [1.0 / len(ordered)] * len(ordered)
+ return [w / total for w in widths]
+
+
+@dataclass
+class LadderScore:
+ """The aggregate over the whole rung ladder, plus the headline that travels."""
+
+ aggregate: float
+ onset_rung_tokens: int | None
+ onset_reason: str
+ non_monotonic: bool
+ rungs: list[RungScore] = field(default_factory = list)
+ rung_weights: list[float] = field(default_factory = list)
+ weights_id: str = ""
+ rung_ladder_id: str = ""
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "aggregate": round(float(self.aggregate), 3),
+ "onset_rung_tokens": self.onset_rung_tokens,
+ "onset_reason": self.onset_reason,
+ "non_monotonic": bool(self.non_monotonic),
+ "weights_id": self.weights_id,
+ "rung_ladder_id": self.rung_ladder_id,
+ "rung_weights": [round(w, 5) for w in self.rung_weights],
+ "rungs": [r.to_json() for r in self.rungs],
+ }
+
+
+def score_ladder(rungs: Sequence[RungScore]) -> LadderScore:
+ """Aggregate scored rungs, and pick the onset rung.
+
+ Every rung on the declared ladder must be present, complete or not. A caller that only ran
+ three of five rungs must still hand over the other two as incomplete, because silently
+ aggregating over what was attempted is the crash-beats-limp bug in a different costume.
+ """
+
+ ordered = sorted(rungs, key = lambda r: r.tokens)
+ weights = log_rung_weights([r.tokens for r in ordered])
+ aggregate = sum(w * float(r.score) for w, r in zip(weights, ordered))
+
+ usable = [r for r in ordered if r.usable]
+ onset = usable[-1].tokens if usable else None
+ if onset is None:
+ smallest = ordered[0].tokens if ordered else None
+ onset_reason = (
+ f"no rung was usable; the smallest rung on the ladder ({smallest:,} tokens) already "
+ "fails the usability gate"
+ if smallest is not None
+ else "no rungs were scored"
+ )
+ else:
+ above = [r for r in ordered if r.tokens > onset]
+ if above:
+ onset_reason = (
+ f"usable at {onset:,} tokens; the next rung "
+ f"({above[0].tokens:,}) scores {above[0].score:.1f}"
+ )
+ else:
+ onset_reason = (
+ f"usable at {onset:,} tokens, the top of the declared ladder; the true ceiling "
+ "is above what this ladder measures"
+ )
+
+ # Usability is expected to be monotone in thread size. When it is not, something other than
+ # thread size moved -- thermal throttling, a background process, an unstable machine -- and
+ # the onset rung is not trustworthy on its own. Say so rather than quietly reporting the max.
+ non_monotonic = False
+ seen_unusable = False
+ for rung in ordered:
+ if not rung.usable:
+ seen_unusable = True
+ elif seen_unusable:
+ non_monotonic = True
+
+ return LadderScore(
+ aggregate = aggregate,
+ onset_rung_tokens = onset,
+ onset_reason = onset_reason,
+ non_monotonic = non_monotonic,
+ rungs = list(ordered),
+ rung_weights = weights,
+ weights_id = weights_id(),
+ rung_ladder_id = rung_ladder_id([r.tokens for r in ordered] or RUNG_TOKENS),
+ )
diff --git a/tests/studio/studiobench/scoring/selftest/test_studiobench_from_payload.py b/tests/studio/studiobench/scoring/selftest/test_studiobench_from_payload.py
new file mode 100644
index 00000000000..90a52d15ca0
--- /dev/null
+++ b/tests/studio/studiobench/scoring/selftest/test_studiobench_from_payload.py
@@ -0,0 +1,413 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for the session-layer -> scoring-layer seam.
+
+Every test here is written against a failure that would otherwise render as a plausible number.
+The seam's whole job is to keep three different absences apart, so each is asserted separately
+rather than through "is not None".
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.scoring.from_payload import ( # noqa: E402
+ latest_attempt_rows,
+ measures_from_records,
+)
+from studiobench.scoring.schema import ( # noqa: E402
+ PayloadSchemaError,
+ validate_payload,
+)
+
+
+def _cell(
+ cell_id = "c1",
+ tokens = 10_000,
+ completed = True,
+):
+ return {"row_type": "cell", "cell_id": cell_id, "target_tokens": tokens, "completed": completed}
+
+
+def _action(
+ cell_id,
+ name,
+ ran = True,
+ timings = None,
+ reason = None,
+):
+ return {
+ "row_type": "action",
+ "cell_id": cell_id,
+ "action": name,
+ "ran": ran,
+ "timings": timings or {},
+ "reason": reason,
+ }
+
+
+def _window(
+ cell_id,
+ gaps,
+ duration_ms = 1000.0,
+ kind = "action",
+ attempted = True,
+):
+ frames = {"frames_attempted": attempted}
+ if attempted:
+ frames.update(
+ {
+ "frame_gaps_ms": gaps,
+ "frame_gaps_truncated": False,
+ "frame_gaps_total": len(gaps),
+ "max_frame_ms": max(gaps) if gaps else None,
+ }
+ )
+ return {
+ "row_type": "window",
+ "cell_id": cell_id,
+ "kind": kind,
+ "duration_ms": duration_ms,
+ "instruments": {"frames": frames},
+ }
+
+
+# ── the three absences, kept apart ──────────────────────────────────────────────────────────
+
+
+def test_action_absent_from_scene_is_not_attempted():
+ m = measures_from_records([_cell()])["10000" if False else 10_000]
+ keystroke = m["keystroke_p95_ms"]
+ assert keystroke.attempted is False
+ assert keystroke.value is None
+ assert "not in this scene" in keystroke.note
+
+
+def test_action_that_did_not_run_is_attempted_and_failed_with_its_reason():
+ """The distinction that matters at 1K: scroll cannot run, and that is not a fast scroll."""
+ recs = [
+ _cell(),
+ _action("c1", "scroll_after", ran = False, reason = "the thread is shorter than the viewport"),
+ ]
+ scroll = measures_from_records(recs)[10_000]["scroll_settle_ms"]
+ assert scroll.attempted is True
+ assert scroll.value is None
+ assert "shorter than the viewport" in scroll.note
+
+
+def test_action_that_ran_without_the_timing_key_is_failed_not_zero():
+ recs = [_cell(), _action("c1", "keystroke", ran = True, timings = {"p50_ms": 10.0})]
+ keystroke = measures_from_records(recs)[10_000]["keystroke_p95_ms"]
+ assert keystroke.attempted is True
+ assert keystroke.value is None
+ assert "recorded no p95_ms" in keystroke.note
+
+
+def test_a_real_reading_carries_the_key_it_came_from():
+ recs = [_cell(), _action("c1", "keystroke", timings = {"p95_ms": 31.5})]
+ keystroke = measures_from_records(recs)[10_000]["keystroke_p95_ms"]
+ assert keystroke.value == pytest.approx(31.5)
+ assert keystroke.note == "keystroke.p95_ms"
+
+
+def test_scroll_settle_says_it_is_gesture_time_not_settle_time():
+ """The one anchor whose recorded quantity is not what its name says. Never silent."""
+ recs = [_cell(), _action("c1", "scroll_after", timings = {"gesture_ms": 466.5})]
+ scroll = measures_from_records(recs)[10_000]["scroll_settle_ms"]
+ assert scroll.value == pytest.approx(466.5)
+ assert "not post-gesture settle" in scroll.note
+
+
+# ── frame metrics ───────────────────────────────────────────────────────────────────────────
+
+
+def test_frame_metrics_pool_the_active_windows():
+ recs = [_cell(), _window("c1", [16.0] * 50 + [200.0], duration_ms = 1000.0)]
+ m = measures_from_records(recs)[10_000]
+ assert m["max_frame_ms"].value == pytest.approx(200.0)
+ assert m["jank_index"].value is not None and m["jank_index"].value > 0
+ assert m["time_in_jank_pct"].value is not None
+
+
+def test_idle_windows_are_excluded_so_jank_is_not_diluted():
+ busy = _window("c1", [200.0] * 10, duration_ms = 2000.0, kind = "action")
+ idle = _window("c1", [16.0] * 600, duration_ms = 10000.0, kind = "idle")
+ with_idle = measures_from_records([_cell(), busy, idle])[10_000]["time_in_jank_pct"].value
+ without = measures_from_records([_cell(), busy])[10_000]["time_in_jank_pct"].value
+ assert with_idle == pytest.approx(without)
+
+
+def test_recorder_never_installed_reads_not_attempted():
+ recs = [_cell(), _window("c1", [], attempted = False)]
+ m = measures_from_records(recs)[10_000]
+ assert m["jank_index"].attempted is False
+ assert "frame recorder" in m["jank_index"].note
+
+
+def test_a_window_that_recorded_no_frames_fails_the_pool_instead_of_dropping_out():
+ """A complete freeze during one action must not be answered for by the windows beside it.
+
+ `compute_frame_stats` already calls a single attempted-but-frameless window a failed
+ measurement. Pooled, that window used to be skipped, and the cell came back with the
+ remaining window's clean numbers.
+ """
+ normal = _window("c1", [16.0] * 50 + [40.0], duration_ms = 1000.0)
+ frozen = _window("c1", [], duration_ms = 4000.0)
+ m = measures_from_records([_cell(), normal, frozen])[10_000]
+ for key in ("time_in_jank_pct", "jank_index", "max_frame_ms"):
+ assert m[key].attempted is True
+ assert m[key].value is None
+ assert "no frames at all" in m[key].note
+ # and the giveaway: without the fix these were byte-identical to the cell without the freeze
+ alone = measures_from_records([_cell(), normal])[10_000]
+ assert alone["max_frame_ms"].value == pytest.approx(40.0)
+
+
+def test_a_window_the_recorder_was_never_installed_in_is_still_only_skipped():
+ """The control. Not-attempted is an absent instrument, not an unmeasured window."""
+ normal = _window("c1", [16.0] * 50 + [40.0], duration_ms = 1000.0)
+ never = _window("c1", [], duration_ms = 4000.0, attempted = False)
+ m = measures_from_records([_cell(), normal, never])[10_000]
+ assert m["max_frame_ms"].value == pytest.approx(40.0)
+ assert m["jank_index"].value is not None
+ assert m["time_in_jank_pct"].value is not None
+
+
+def test_a_pool_where_every_window_has_frames_is_unaffected():
+ """The other control: the ordinary multi-window cell still pools as before."""
+ a = _window("c1", [16.0] * 50 + [40.0], duration_ms = 1000.0)
+ b = _window("c1", [16.0] * 20 + [900.0], duration_ms = 2000.0)
+ m = measures_from_records([_cell(), a, b])[10_000]
+ assert m["max_frame_ms"].value == pytest.approx(900.0)
+ assert m["jank_index"].value is not None and m["jank_index"].value > 0
+ assert m["time_in_jank_pct"].value is not None
+
+
+def test_truncated_window_refuses_a_number_rather_than_scoring_the_fast_frames():
+ """A capped window exports no deltas at all, and must not become a clean reading."""
+ w = _window("c1", [16.0], duration_ms = 1000.0)
+ w["instruments"]["frames"]["frame_gaps_truncated"] = True
+ w["instruments"]["frames"]["frame_gaps_ms"] = None
+ m = measures_from_records([_cell(), w])[10_000]
+ assert m["jank_index"].attempted is True
+ assert m["jank_index"].value is None
+ assert "cap" in m["jank_index"].note
+
+
+def test_an_incomplete_cell_still_contributes_its_rung():
+ """A build that died at a rung must not make that rung disappear from the ladder."""
+ recs = [_cell(completed = False), _action("c1", "keystroke", timings = {"p95_ms": 900.0})]
+ assert 10_000 in measures_from_records(recs)
+
+
+def test_names_come_from_action_rows_not_the_lossy_embedded_copy():
+ """The `actions` list inside a cell row drops names; using it would decode positionally."""
+ cell = _cell()
+ cell["actions"] = [{"name": None, "ran": True, "timings": {"p95_ms": 1.0}}]
+ recs = [cell, _action("c1", "keystroke", timings = {"p95_ms": 31.5})]
+ assert measures_from_records(recs)[10_000]["keystroke_p95_ms"].value == pytest.approx(31.5)
+
+
+# ── the bare-zero ban still bites after the harness-row exemptions ───────────────────────────
+
+
+def test_bare_zero_outside_an_attested_block_still_fails():
+ with pytest.raises(PayloadSchemaError):
+ validate_payload({"excluded_cells": [], "result": {"cost_ms": 0}})
+
+
+def test_zero_under_a_false_attestation_still_fails():
+ """`attempted: false` plus a zero is the exact conflation the ban exists to catch."""
+ with pytest.raises(PayloadSchemaError):
+ validate_payload({"excluded_cells": [], "blk": {"thing_attempted": False, "cost_ms": 0}})
+
+
+def test_zero_in_a_positively_attested_instrument_block_is_accepted():
+ validate_payload({"excluded_cells": [], "blk": {"frames_attempted": True, "frames_over_33": 0}})
+
+
+def test_attestation_does_not_leak_into_nested_blocks():
+ with pytest.raises(PayloadSchemaError):
+ validate_payload(
+ {"excluded_cells": [], "blk": {"frames_attempted": True, "inner": {"cost_ms": 0}}}
+ )
+
+
+def test_real_payload_shape_round_trips(tmp_path):
+ """One end-to-end pass over rows shaped exactly as the session layer writes them."""
+ rows = [
+ {"row_type": "run_meta", "tier": "quick"},
+ _cell("c1", 1_000),
+ _action("c1", "keystroke", timings = {"p95_ms": 32.2}),
+ _action("c1", "message_menu", timings = {"open_ms": 45.8}),
+ _action("c1", "scroll_after", ran = False, reason = "the thread is shorter than the viewport"),
+ _window("c1", [16.7] * 60 + [68.1], duration_ms = 1017.0),
+ ]
+ path = tmp_path / "payload.jsonl"
+ path.write_text("\n".join(json.dumps(r) for r in rows), encoding = "utf-8")
+
+ from studiobench.report.build import score_payload
+
+ ladder = score_payload(path, [1_000])
+ assert [r.tokens for r in ladder.rungs] == [1_000]
+ rung = ladder.rungs[0]
+ # keystroke + menu + the three frame metrics = 85% of the weight, over the 60% floor, so the
+ # rung scores despite scroll being legitimately unavailable at this size.
+ assert rung.usable is True
+
+
+# ── per-cell readings, which is what makes an A/B paired ─────────────────────────────────────
+
+
+def test_measures_by_cell_keeps_every_repetition():
+ """Collapsing reps leaves the bootstrap with one pair per metric and nothing to resample."""
+ from studiobench.scoring.from_payload import measures_by_cell
+
+ rows = []
+ for rep in (0, 1):
+ cid = f"c{rep}"
+ cell = _cell(cid)
+ cell["cell"] = {"rep": rep}
+ rows.append(cell)
+ rows.append(_action(cid, "keystroke", timings = {"p95_ms": 30.0 + rep}))
+
+ by_cell = measures_by_cell(rows)
+ assert sorted(by_cell) == [(10_000, 0), (10_000, 1)]
+ assert by_cell[(10_000, 0)]["keystroke_p95_ms"].value == pytest.approx(30.0)
+ assert by_cell[(10_000, 1)]["keystroke_p95_ms"].value == pytest.approx(31.0)
+
+
+def test_measures_by_cell_does_not_mix_readings_between_cells():
+ """Each cell must see only its own action rows, or rep 0 inherits rep 1's timings."""
+ from studiobench.scoring.from_payload import measures_by_cell
+
+ a, b = _cell("cA"), _cell("cB")
+ a["cell"], b["cell"] = {"rep": 0}, {"rep": 1}
+ rows = [
+ a,
+ b,
+ _action("cA", "menu_open" if False else "message_menu", timings = {"open_ms": 10.0}),
+ _action("cB", "message_menu", timings = {"open_ms": 900.0}),
+ ]
+ by_cell = measures_by_cell(rows)
+ assert by_cell[(10_000, 0)]["menu_open_ms"].value == pytest.approx(10.0)
+ assert by_cell[(10_000, 1)]["menu_open_ms"].value == pytest.approx(900.0)
+
+
+# ── ran is not "did what it claimed" ────────────────────────────────────────────────────────
+
+
+def test_an_action_whose_own_assertion_failed_is_not_a_reading():
+ """`report/payload.py` lists this cell under EXCLUDED CELLS with "must not be quoted".
+
+ Before this, the same action was excluded in the report and load-bearing in the headline: the
+ keystroke row reported `ran: true, expect_ok: false` because the composer never accepted the
+ commanded characters, and its p95 still set the rung's highest-weight metric.
+ """
+ recs = [
+ _cell(),
+ {
+ **_action("c1", "keystroke", ran = True, timings = {"p95_ms": 12.0}),
+ "expect_ok": False,
+ "reason": "typed 12 characters but the composer value grew by 0",
+ },
+ ]
+ keystroke = measures_from_records(recs)[10_000]["keystroke_p95_ms"]
+ assert keystroke.attempted is True
+ assert keystroke.value is None
+ assert "its own assertion failed" in keystroke.note
+ assert "grew by 0" in keystroke.note
+
+
+def test_an_action_whose_assertion_passed_is_still_a_reading():
+ recs = [
+ _cell(),
+ {**_action("c1", "keystroke", ran = True, timings = {"p95_ms": 12.0}), "expect_ok": True},
+ ]
+ assert measures_from_records(recs)[10_000]["keystroke_p95_ms"].value == 12.0
+
+
+# ---------------------------------------------------------------------------------------
+# The latest attempt is the last one that WROTE anything, not the last one that finished
+# ---------------------------------------------------------------------------------------
+#
+# `CellRunner.run` writes its terminal cell row in a `finally`, which a SIGKILL, an OOM kill or a
+# lost machine never reaches -- while the Recorder has already flushed and fsynced every action and
+# window row before it. Keyed on cell rows alone, a resume hard-killed inside a cell left the
+# older, completed attempt named as the latest, and `_resume_set` skipped it.
+
+
+def _stamped(row, session):
+ return {**row, "session_id": session}
+
+
+def test_a_killed_attempt_supersedes_the_completed_one_it_was_re_running():
+ records = [
+ _stamped(_cell("c1", completed = True), "sess-1"),
+ _stamped(_action("c1", "keystroke", timings = {"p95_ms": 40.0}), "sess-1"),
+ # sess-2 got this far and was killed: no cell row was ever written.
+ _stamped(_action("c1", "keystroke", timings = {"p95_ms": 900.0}), "sess-2"),
+ ]
+
+ kept = latest_attempt_rows(records)
+
+ # The old attempt's rows are gone, so nothing reports c1 as completed.
+ assert not [r for r in kept if r.get("row_type") == "cell"]
+ assert [r["timings"]["p95_ms"] for r in kept if r.get("row_type") == "action"] == [900.0]
+
+
+def test_a_window_row_alone_is_enough_to_prove_a_newer_attempt():
+ records = [
+ _stamped(_cell("c1", completed = True), "sess-1"),
+ _stamped(_window("c1", [16.0, 17.0]), "sess-1"),
+ _stamped(_window("c1", [400.0]), "sess-2"),
+ ]
+
+ kept = latest_attempt_rows(records)
+
+ assert not [r for r in kept if r.get("row_type") == "cell"]
+ assert len([r for r in kept if r.get("row_type") == "window"]) == 1
+
+
+def test_a_completed_retry_still_supersedes_the_attempt_that_died():
+ """The control this rule already existed for, unchanged: the retry that FINISHED wins."""
+
+ records = [
+ _stamped(_cell("c1", completed = False), "sess-1"),
+ _stamped(_action("c1", "keystroke", timings = {"p95_ms": 900.0}), "sess-1"),
+ _stamped(_action("c1", "keystroke", timings = {"p95_ms": 40.0}), "sess-2"),
+ _stamped(_cell("c1", completed = True), "sess-2"),
+ ]
+
+ kept = latest_attempt_rows(records)
+
+ assert [r["completed"] for r in kept if r.get("row_type") == "cell"] == [True]
+ assert [r["timings"]["p95_ms"] for r in kept if r.get("row_type") == "action"] == [40.0]
+
+
+def test_a_payload_with_no_session_ids_is_kept_whole():
+ """A payload from before the recorder stamped sessions cannot be split into attempts, and
+ dropping it would lose the run."""
+
+ records = [_cell("c1"), _action("c1", "keystroke", timings = {"p95_ms": 40.0})]
+
+ assert latest_attempt_rows(records) == records
+
+
+def test_rows_of_another_cell_are_untouched():
+ records = [
+ _stamped(_cell("c1", completed = True), "sess-1"),
+ _stamped(_action("c2", "keystroke", timings = {"p95_ms": 40.0}), "sess-1"),
+ _stamped(_action("c1", "keystroke", timings = {"p95_ms": 900.0}), "sess-2"),
+ ]
+
+ kept = latest_attempt_rows(records)
+
+ assert any(r.get("cell_id") == "c2" for r in kept)
diff --git a/tests/studio/studiobench/scoring/selftest/test_studiobench_scoring.py b/tests/studio/studiobench/scoring/selftest/test_studiobench_scoring.py
new file mode 100644
index 00000000000..eb1bbce4ec6
--- /dev/null
+++ b/tests/studio/studiobench/scoring/selftest/test_studiobench_scoring.py
@@ -0,0 +1,693 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Unit tests for the scoring layer, run against synthetic payloads.
+
+The scoring layer is pure, so it can be tested exhaustively without a browser, and it is the part
+where a mistake is least likely to be noticed: a wrong ms is obvious, a wrong aggregation rule
+produces plausible numbers forever.
+
+The tests that matter most are the ADVERSARIAL ones, each of which encodes a specific way a
+benchmark lies:
+
+ a crashed rung must not outscore a slow one
+ a regression must surface despite a positive headline
+ NULL and SPIKE must behave, and must be caught when they misbehave
+ a zero must never be printable without saying whether the thing was attempted
+"""
+
+from __future__ import annotations
+
+import math
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
+
+from studiobench.scoring import ( # noqa: E402
+ METRIC_BY_KEY,
+ Measure,
+ Pair,
+ PayloadSchemaError,
+ RunIdentity,
+ compare,
+ compute_frame_stats,
+ log_rung_weights,
+ measure_refresh_interval_ms,
+ noise_floor_from_null_control,
+ score_ladder,
+ score_metric,
+ score_rung,
+ validate_payload,
+)
+from studiobench.scoring.anchors import ONSET_SCORE_THRESHOLD # noqa: E402
+
+
+# ---------------------------------------------------------------------------------------
+# Measure: the ban on bare zeros
+# ---------------------------------------------------------------------------------------
+
+
+def test_not_attempted_cannot_carry_a_value():
+ with pytest.raises(PayloadSchemaError):
+ Measure(value = 1.0, attempted = False, unit = "ms", note = "nope")
+
+
+def test_not_attempted_must_say_why():
+ with pytest.raises(PayloadSchemaError):
+ Measure(value = None, attempted = False, unit = "ms")
+
+
+def test_sub_floor_delta_prints_as_a_bound_not_a_zero():
+ measure = Measure.read(0.04, "ms/update", floor = 0.12)
+ assert measure.sub_floor is True
+ assert measure.display() == "< 0.12 ms/update (instrument floor)"
+ assert "0.04" not in measure.display()
+
+
+def test_negative_sub_floor_is_bounded_from_below():
+ measure = Measure.read(-0.03, "ms/update", floor = 0.12)
+ assert measure.display() == "> -0.12 ms/update (instrument floor)"
+
+
+def test_not_attempted_reads_differently_from_a_failed_reading():
+ skipped = Measure.not_attempted("ms", "profiling alias not verified")
+ failed = Measure.failed("ms", "the recorder produced no frames")
+ assert "not attempted" in skipped.display()
+ assert "no reading" in failed.display()
+ assert skipped.to_json()["attempted"] is False
+ assert failed.to_json()["attempted"] is True
+
+
+def test_validate_payload_rejects_a_bare_zero():
+ payload = {"excluded_cells": [], "windows": [{"react_stage_ms": 0}]}
+ with pytest.raises(PayloadSchemaError) as caught:
+ validate_payload(payload)
+ assert "react_stage_ms" in str(caught.value)
+
+
+def test_validate_payload_accepts_a_zero_inside_a_measure():
+ payload = {
+ "excluded_cells": [],
+ "windows": [{"react_stage_ms": Measure.read(0.0, "ms").to_json()}],
+ }
+ validate_payload(payload)
+
+
+def test_validate_payload_accepts_the_first_parity_message_row():
+ """`i` is the ordinal scene/parity.js writes for message 0, not a missing measurement.
+
+ Without this exemption every payload carrying parity rows failed validation, so the
+ documented `--report` step never ran at all.
+ """
+
+ payload = {
+ "excluded_cells": [],
+ "cells": [
+ {
+ "parity": {
+ "parity_attempted": True,
+ "digest": "abc123",
+ "chars": 4211,
+ "messages": [
+ {"i": 0, "role": "user", "digest": "d0", "chars": 120},
+ {"i": 1, "role": "assistant", "digest": "d1", "chars": 900},
+ ],
+ }
+ }
+ ],
+ }
+ validate_payload(payload)
+
+
+def test_validate_payload_still_rejects_a_bare_zero_beside_a_parity_ordinal():
+ """The exemption is the ordinal alone; a zero-length signature stays a loud failure."""
+
+ payload = {
+ "excluded_cells": [],
+ "cells": [
+ {
+ "parity": {
+ "parity_attempted": True,
+ "digest": "abc123",
+ "chars": 4211,
+ "messages": [{"i": 0, "role": "user", "digest": "d0", "chars": 0}],
+ }
+ }
+ ],
+ }
+ with pytest.raises(PayloadSchemaError) as caught:
+ validate_payload(payload)
+ assert "chars" in str(caught.value)
+
+
+def test_validate_payload_accepts_an_equivalence_field_absent_from_both_arms():
+ """`reasoning_spans` reads 0 streamed and 0 seeded on a real quick-tier run.
+
+ `drift` was already exempt; the two counts it is computed from were not, so every payload
+ carrying an equivalence block failed validation.
+ """
+
+ payload = {
+ "excluded_cells": [],
+ "cells": [
+ {
+ "equivalence": {
+ "fields": {
+ "reasoning_spans": {
+ "streamed": 0,
+ "seeded": 0,
+ "gating": False,
+ "note": "reported, not gated",
+ },
+ "assistant_messages": {"streamed": 6, "seeded": 4, "drift": 0.0},
+ }
+ }
+ }
+ ],
+ }
+ validate_payload(payload)
+
+
+def test_validate_payload_accepts_a_zero_sample_in_an_attested_instrument_array():
+ """A 0 ms inter-frame gap is two frames in one millisecond, not a missing reading.
+
+ The block attests with `frames_attempted`, which already covers the scalar counters beside
+ it; walking into the sample array dropped that attestation.
+ """
+
+ payload = {
+ "excluded_cells": [],
+ "windows": [
+ {
+ "instruments": {
+ "frames": {
+ "frames_attempted": True,
+ "frame_gaps_ms": [0, 3, 4, 16, 16],
+ "frames_over_33": 0,
+ }
+ }
+ }
+ ],
+ }
+ validate_payload(payload)
+
+
+def test_an_unattested_instrument_array_still_fails():
+ """The exemption is the attestation, not the brackets. Without it the zero stays loud."""
+
+ payload = {
+ "excluded_cells": [],
+ "windows": [{"instruments": {"frames": {"frame_gaps_ms": [0, 3, 4]}}}],
+ }
+ with pytest.raises(PayloadSchemaError) as caught:
+ validate_payload(payload)
+ assert "frame_gaps_ms" in str(caught.value)
+
+
+def test_validate_payload_requires_excluded_cells():
+ with pytest.raises(PayloadSchemaError):
+ validate_payload({"windows": []})
+ with pytest.raises(PayloadSchemaError):
+ validate_payload({"excluded_cells": None})
+
+
+# ---------------------------------------------------------------------------------------
+# frames: both directions of jank
+# ---------------------------------------------------------------------------------------
+
+
+def test_uniform_mediocrity_is_caught_by_time_in_jank_and_missed_by_max():
+ """Every frame 120 ms. `max` says 120, which sounds survivable. It is not."""
+
+ deltas = [120.0] * 50
+ stats = compute_frame_stats(deltas, window_ms = 6000.0, declared_refresh_ms = 16.7)
+ assert stats.time_in_jank_pct.value == pytest.approx(100.0)
+ assert stats.max_frame_ms.value == pytest.approx(120.0)
+
+
+def test_a_single_stall_is_caught_by_jank_index_and_missed_by_percentiles():
+ """5,000 good frames and one 3.4 s freeze. p95 is perfect; the app was frozen."""
+
+ deltas = [8.0] * 5000 + [3400.0]
+ stats = compute_frame_stats(deltas, window_ms = 43_400.0, declared_refresh_ms = 16.7)
+ assert stats.p95_frame_ms.value == pytest.approx(8.0, abs = 0.5)
+ assert stats.time_in_jank_pct.value < 10.0
+ assert stats.jank_index.value > 200.0
+ assert stats.max_frame_ms.value == pytest.approx(3400.0)
+
+
+def test_refresh_interval_is_measured_not_assumed():
+ deltas = [8.3] * 40 + [40.0, 60.0]
+ interval, source = measure_refresh_interval_ms(deltas)
+ assert source == "measured"
+ assert interval == pytest.approx(8.3, abs = 0.5)
+
+
+def test_no_frames_recorded_is_a_failed_reading_not_zero_jank():
+ stats = compute_frame_stats([], window_ms = 5000.0)
+ assert stats.no_frames_recorded is True
+ assert stats.time_in_jank_pct.has_reading is False
+ assert stats.time_in_jank_pct.attempted is True
+ assert "unscheduled" in stats.time_in_jank_pct.display()
+
+
+def test_histogram_is_always_present_and_totals_the_frames():
+ deltas = [4.0, 9.0, 20.0, 120.0, 5000.0]
+ stats = compute_frame_stats(deltas, window_ms = 5153.0)
+ assert sum(b["bucket_count"] for b in stats.histogram) == len(deltas)
+
+
+# ---------------------------------------------------------------------------------------
+# per-metric and per-rung scoring
+# ---------------------------------------------------------------------------------------
+
+
+def test_log_anchors_put_the_geometric_midpoint_at_fifty():
+ anchor = METRIC_BY_KEY["keystroke_p95_ms"]
+ midpoint = math.sqrt(anchor.good * anchor.bad)
+ scored = score_metric(anchor, Measure.read(midpoint, "ms"))
+ assert scored.score == pytest.approx(50.0, abs = 0.001)
+
+
+def test_a_reading_at_or_past_the_bad_anchor_scores_zero():
+ anchor = METRIC_BY_KEY["keystroke_p95_ms"]
+ assert score_metric(anchor, Measure.read(anchor.bad, "ms")).score == 0.0
+ assert score_metric(anchor, Measure.read(anchor.bad * 10, "ms")).score == 0.0
+
+
+def test_an_unmeasured_metric_is_not_scored_at_all():
+ anchor = METRIC_BY_KEY["menu_open_ms"]
+ scored = score_metric(anchor, Measure.not_attempted("ms", "action not in this scene"))
+ assert scored.scored is False
+ assert scored.score is None
+
+
+def _good_metrics(**overrides) -> dict[str, Measure]:
+ base = {
+ "keystroke_p95_ms": Measure.read(25.0, "ms"),
+ "time_in_jank_pct": Measure.read(0.8, "%"),
+ "jank_index": Measure.read(0.2, "ms"),
+ "max_frame_ms": Measure.read(40.0, "ms"),
+ "scroll_settle_ms": Measure.read(130.0, "ms"),
+ "menu_open_ms": Measure.read(60.0, "ms"),
+ }
+ base.update(overrides)
+ return base
+
+
+def test_one_catastrophic_metric_zeroes_the_rung():
+ """Four good metrics must not rescue one broken one. That is why the mean is geometric."""
+
+ rung = score_rung(100_000, _good_metrics(scroll_settle_ms = Measure.read(9000.0, "ms")))
+ assert rung.score == 0.0
+ assert rung.zeroed_by == ["scroll_settle_ms"]
+ assert rung.usable is False
+
+
+def test_an_arithmetic_mean_would_have_rescued_it():
+ """Documents the choice: the same inputs average to a passing score."""
+
+ rung = score_rung(100_000, _good_metrics(scroll_settle_ms = Measure.read(9000.0, "ms")))
+ scored = [m for m in rung.metric_scores if m.scored]
+ arithmetic = sum(m.weight * float(m.score) for m in scored) / sum(m.weight for m in scored)
+ assert arithmetic > 60.0
+ assert rung.score == 0.0
+
+
+def test_missing_most_metrics_makes_the_rung_incomplete_rather_than_easy():
+ sparse = {
+ "keystroke_p95_ms": Measure.read(21.0, "ms"),
+ "time_in_jank_pct": Measure.not_attempted("%", "recorder not installed"),
+ "jank_index": Measure.not_attempted("ms", "recorder not installed"),
+ "max_frame_ms": Measure.not_attempted("ms", "recorder not installed"),
+ "scroll_settle_ms": Measure.not_attempted("ms", "action skipped"),
+ "menu_open_ms": Measure.not_attempted("ms", "action skipped"),
+ }
+ rung = score_rung(100_000, sparse)
+ assert rung.complete is False
+ assert rung.score == 0.0
+ assert "weight" in rung.incomplete_reason
+
+
+# ---------------------------------------------------------------------------------------
+# aggregation, and the three ways naive AUC lies
+# ---------------------------------------------------------------------------------------
+
+
+def test_log_rung_weights_do_not_let_the_top_rung_be_the_whole_score():
+ weights = log_rung_weights([1_000, 10_000, 100_000, 500_000, 1_000_000])
+ assert sum(weights) == pytest.approx(1.0)
+ assert max(weights) < 0.40
+ linear_span = [1_000, 10_000, 100_000, 500_000, 1_000_000]
+ linear_weights = [t / sum(linear_span) for t in linear_span]
+ assert max(linear_weights) > 0.60 # what a linear axis would have done
+
+
+def test_a_crashed_rung_must_not_outscore_a_slow_one():
+ """The adversarial case: crashing at 500K must lose to limping through it."""
+
+ rungs = [1_000, 10_000, 100_000, 500_000, 1_000_000]
+ slow_metrics = _good_metrics(
+ keystroke_p95_ms = Measure.read(180.0, "ms"),
+ time_in_jank_pct = Measure.read(25.0, "%"),
+ jank_index = Measure.read(8.0, "ms"),
+ max_frame_ms = Measure.read(900.0, "ms"),
+ scroll_settle_ms = Measure.read(1800.0, "ms"),
+ menu_open_ms = Measure.read(700.0, "ms"),
+ )
+
+ crasher = score_ladder(
+ [
+ score_rung(t, _good_metrics(), completed = True)
+ if t <= 100_000
+ else score_rung(t, {}, completed = False, failure_mode = "renderer crashed")
+ for t in rungs
+ ]
+ )
+ limper = score_ladder(
+ [
+ score_rung(t, _good_metrics() if t <= 100_000 else slow_metrics, completed = True)
+ for t in rungs
+ ]
+ )
+
+ assert limper.aggregate > crasher.aggregate
+ assert crasher.rungs[-1].score == 0.0
+ assert crasher.rungs[-1].complete is False
+ # and the crashed rungs are still IN the ladder, keeping their weight
+ assert len(crasher.rungs) == len(rungs)
+
+
+def test_onset_rung_is_the_largest_usable_rung():
+ rungs = [1_000, 10_000, 100_000, 500_000]
+ bad = _good_metrics(
+ keystroke_p95_ms = Measure.read(400.0, "ms"),
+ scroll_settle_ms = Measure.read(2800.0, "ms"),
+ )
+ ladder = score_ladder(
+ [score_rung(t, _good_metrics() if t <= 10_000 else bad, completed = True) for t in rungs]
+ )
+ assert ladder.onset_rung_tokens == 10_000
+ assert ladder.rungs[0].score >= ONSET_SCORE_THRESHOLD
+
+
+def test_non_monotone_usability_is_flagged_rather_than_maximised():
+ rungs = [1_000, 10_000, 100_000]
+ bad = _good_metrics(keystroke_p95_ms = Measure.read(450.0, "ms"))
+ ladder = score_ladder(
+ [
+ score_rung(1_000, _good_metrics()),
+ score_rung(10_000, bad),
+ score_rung(100_000, _good_metrics()),
+ ]
+ )
+ assert ladder.non_monotonic is True
+ assert ladder.onset_rung_tokens == 100_000 # reported, but flagged
+ assert len(rungs) == 3
+
+
+# ---------------------------------------------------------------------------------------
+# A/B
+# ---------------------------------------------------------------------------------------
+
+
+def _identity(session: str = "s1", **overrides) -> RunIdentity:
+ fields = {
+ "bench_version": "studiobench/1",
+ "corpus_hash": "corpus-abc",
+ "rung_ladder_id": "r-123",
+ "weights_id": "w-123",
+ "session_id": session,
+ }
+ fields.update(overrides)
+ return RunIdentity(**fields)
+
+
+def _pairs(ratios: dict[str, float], rungs = (1_000, 10_000, 100_000)) -> list[Pair]:
+ out = []
+ for metric, ratio in ratios.items():
+ for index, rung in enumerate(rungs):
+ base = 100.0 + index
+ out.append(
+ Pair(
+ rung_tokens = rung,
+ metric_key = metric,
+ base = Measure.read(base, "ms"),
+ treatment = Measure.read(base * ratio, "ms"),
+ )
+ )
+ return out
+
+
+def test_ab_refuses_across_weights_ids():
+ with pytest.raises(Exception) as caught:
+ compare(
+ "x",
+ _pairs({"keystroke_p95_ms": 0.9}),
+ _identity(),
+ _identity(weights_id = "w-999"),
+ )
+ assert "weights_id" in str(caught.value)
+
+
+def test_ab_refuses_across_sessions():
+ with pytest.raises(Exception) as caught:
+ compare(
+ "x",
+ _pairs({"keystroke_p95_ms": 0.9}),
+ _identity(session = "s1"),
+ _identity(session = "s2"),
+ )
+ assert "session" in str(caught.value)
+
+
+def test_a_regression_surfaces_despite_a_positive_headline():
+ """The adversarial case: a headline win of 16% hiding a 60% worse worst frame.
+
+ This is the shape that ships. Nobody merges a change whose headline is negative; the change
+ that gets merged is the one that improves five metrics and quietly ruins the sixth, and a
+ single headline number is exactly the instrument that would let it through.
+ """
+
+ pairs = _pairs(
+ {
+ "keystroke_p95_ms": 0.75,
+ "time_in_jank_pct": 0.75,
+ "jank_index": 0.75,
+ "scroll_settle_ms": 0.75,
+ "menu_open_ms": 0.75,
+ "max_frame_ms": 1.60,
+ }
+ )
+ result = compare("treatment", pairs, _identity(), _identity(), noise_floor_pct = 5.0)
+ assert result.headline_ratio < 0.9 # the headline says "16% faster"
+ assert result.verdict == "FAIL"
+ assert any("max_frame_ms" in r for r in result.regressions)
+
+
+def test_within_noise_is_not_a_win():
+ result = compare(
+ "treatment",
+ _pairs({"keystroke_p95_ms": 0.98}),
+ _identity(),
+ _identity(),
+ noise_floor_pct = 5.0,
+ )
+ assert result.verdict == "NO DIFFERENCE"
+ assert result.metrics[0].verdict == "within noise"
+
+
+def test_null_control_that_drifts_voids_the_whole_comparison():
+ control = compare(
+ "base vs base",
+ _pairs({"keystroke_p95_ms": 1.30}),
+ _identity(),
+ _identity(),
+ noise_floor_pct = 5.0,
+ is_null_control = True,
+ )
+ assert control.void is True
+ assert control.verdict == "VOID"
+ assert "null-treatment control" in control.void_reason
+
+
+def test_null_control_that_behaves_sets_the_noise_floor():
+ control = compare(
+ "base vs base",
+ _pairs({"keystroke_p95_ms": 1.02, "jank_index": 0.985}),
+ _identity(),
+ _identity(),
+ noise_floor_pct = 5.0,
+ is_null_control = True,
+ )
+ assert control.void is False
+ floor, source = noise_floor_from_null_control(control)
+ assert 1.0 <= floor <= 3.0
+ assert "measured from the null-treatment control" in source
+
+
+def test_bootstrap_ci_brackets_the_geometric_mean():
+ pairs = _pairs({"keystroke_p95_ms": 0.70}, rungs = (1_000, 10_000, 100_000, 500_000))
+ result = compare("treatment", pairs, _identity(), _identity(), bootstrap_seed = 7)
+ metric = result.metrics[0]
+ assert metric.ci_low is not None
+ assert metric.ci_low <= metric.ratio_geomean <= metric.ci_high
+
+
+# ---------------------------------------------------------------------------------------
+# A measured zero is a reading: sub-floor arms bound the ratio rather than voiding the pair
+# ---------------------------------------------------------------------------------------
+#
+# `Pair.usable` required both values to be strictly positive. `time_in_jank_pct` and `jank_index`
+# are 0.0 on any arm smooth enough to have no over-budget frames, which is the ordinary state of a
+# healthy base, so a treatment that introduced jank over a zero-jank base had its pair dropped:
+# the table said `no reading` about two arms that had both read, the regression was absent from
+# `regressions` and from the headline, and as a null control it neither voided nor reached the
+# noise floor derived from it.
+#
+# The rule applied here is the one `score.py` has always applied to the same reading: a sub-floor
+# value is at least as good as the floor, so the floor is what enters the ratio. What that must
+# NOT do is admit a reading that was never taken, which is the distinction `frames.py` protects
+# when it refuses to score an unscheduled rAF loop as zero jank.
+
+JANK_FLOOR = 0.1
+SMOOTH = Measure.read(0.0, "%", floor = JANK_FLOOR)
+JANKY = Measure.read(5.0, "%", floor = JANK_FLOOR)
+
+
+def _jank_pair(base: Measure, treatment: Measure) -> Pair:
+ return Pair(rung_tokens = 100_000, metric_key = "time_in_jank_pct", base = base, treatment = treatment)
+
+
+def test_a_zero_jank_base_still_pairs_against_a_treatment_that_introduced_jank():
+ pair = _jank_pair(SMOOTH, JANKY)
+
+ assert pair.base.has_reading and pair.treatment.has_reading
+ assert pair.usable is True
+ # The floor stands in for the sub-floor arm, so the ratio is a LOWER bound: the true
+ # magnitude is larger, never smaller.
+ assert pair.ratio == 50.0
+ assert pair.bounded is True
+ assert pair.to_json()["bounded"] is True
+
+
+def test_the_regression_over_a_zero_base_reaches_the_table_and_the_headline():
+ result = compare("main -> fix", [_jank_pair(SMOOTH, JANKY)], _identity(), _identity())
+ metric = result.metrics[0]
+
+ assert metric.n_pairs == 1
+ assert metric.verdict == "regressed"
+ assert metric.bounded is True
+ assert any("time_in_jank_pct" in r for r in result.regressions)
+
+
+def test_an_improvement_to_zero_jank_is_bounded_the_other_way():
+ pair = _jank_pair(JANKY, SMOOTH)
+
+ assert pair.usable is True
+ assert pair.ratio == JANK_FLOOR / 5.0
+ assert pair.bounded is True
+
+
+def test_two_arms_below_the_floor_are_not_a_difference():
+ """score.py's reason, at the ratio layer: instrument noise on a fast machine must not invent
+ a difference between two perfect builds."""
+
+ pair = _jank_pair(SMOOTH, Measure.read(0.02, "%", floor = JANK_FLOOR))
+
+ assert pair.usable is True
+ assert pair.ratio == 1.0
+ result = compare("main -> fix", [pair], _identity(), _identity())
+ assert result.metrics[0].verdict == "within noise"
+
+
+def test_a_reading_that_was_never_taken_is_still_not_a_zero():
+ """THE LINE THIS MUST NOT CROSS. Both of these carry `value is None`, which is a different
+ thing from a measured zero, and neither may enter a ratio."""
+
+ never = Measure.not_attempted("%", "no window had the frame recorder installed")
+ failed = Measure.failed("%", "the recorder ran but exported no per-frame deltas")
+
+ assert _jank_pair(never, JANKY).usable is False
+ assert _jank_pair(failed, JANKY).usable is False
+ assert _jank_pair(JANKY, never).usable is False
+ assert _jank_pair(JANKY, failed).usable is False
+ assert (
+ compare("x", [_jank_pair(never, JANKY)], _identity(), _identity()).metrics[0].verdict
+ == "no_reading"
+ )
+
+
+def test_a_zero_with_no_declared_floor_stays_unusable():
+ """Nothing bounds it, so there is no honest ratio to form."""
+
+ pair = Pair(
+ rung_tokens = 100_000,
+ metric_key = "keystroke_p95_ms",
+ base = Measure.read(0.0, "ms"),
+ treatment = Measure.read(40.0, "ms"),
+ )
+
+ assert pair.base.has_reading is True
+ assert pair.usable is False
+
+
+def test_a_null_control_voids_on_jank_it_introduced_over_a_zero_base():
+ """The coupling. The null control decides whether this machine can tell two identical builds
+ apart; blind to the jank transition, it passed and published a floor derived from what was
+ left."""
+
+ result = compare(
+ "null control: main vs itself",
+ [_jank_pair(SMOOTH, JANKY)],
+ _identity(),
+ _identity(),
+ noise_floor_pct = 5.0,
+ is_null_control = True,
+ )
+
+ assert result.void is True
+ assert "time_in_jank_pct" in (result.void_reason or "")
+
+
+def test_a_bounded_ratio_is_not_published_as_this_machines_noise_floor():
+ """A bound is not a spread. Left in, the 50x ratio above would publish a 4,900% noise floor
+ and swallow every real effect measured on that machine afterwards."""
+
+ result = compare(
+ "null control: main vs itself",
+ [
+ _jank_pair(SMOOTH, JANKY),
+ Pair(
+ rung_tokens = 100_000,
+ metric_key = "max_frame_ms",
+ base = Measure.read(30.0, "ms"),
+ treatment = Measure.read(31.0, "ms"),
+ ),
+ ],
+ _identity(),
+ _identity(),
+ noise_floor_pct = 5.0,
+ is_null_control = True,
+ )
+ floor, source = noise_floor_from_null_control(result)
+
+ assert floor < 10.0
+ assert "1 bounded metric(s) excluded" in source
+
+
+def test_a_null_control_of_only_bounded_ratios_falls_back_to_the_declared_default():
+ result = compare(
+ "null control: main vs itself",
+ [_jank_pair(SMOOTH, JANKY)],
+ _identity(),
+ _identity(),
+ is_null_control = True,
+ )
+ floor, source = noise_floor_from_null_control(result)
+
+ assert "declared default" in source
+ assert "under an instrument floor" in source
diff --git a/tests/studio/studiobench/symbols/README.md b/tests/studio/studiobench/symbols/README.md
new file mode 100644
index 00000000000..7479256821d
--- /dev/null
+++ b/tests/studio/studiobench/symbols/README.md
@@ -0,0 +1,56 @@
+# studiobench symbol bridges
+
+Persisted `react-dom@<version>-<bundle-sha>.json` artefacts produced by
+`analysis/bridge_build.py` and consumed by `analysis/symbols.py`.
+
+## Why these files exist
+
+React ships `cjs/react-dom-client.production.js` and
+`cjs/react-dom-profiling.profiling.js` **already minified**, before Vite sees
+them. Source maps and `keepNames` therefore recover our own component names and
+recover nothing at all inside react-dom. The original identifier really is `Zk`.
+No build flag changes that; it is not a misconfiguration.
+
+A bridge is built by running the identical fixture at two or three small rungs
+under `Profiler.startPreciseCoverage` against a **development** build and
+against the shipping-shaped **profiling** build, then matching functions by
+exact call-count vector. Invocation counts are a semantic invariant across build
+modes, so a function with vector `(157, 1277, 879)` in dev is the same function
+as the one with that vector in prod.
+
+**The development build is used strictly as a dictionary and never as a
+measurement.** `assert_no_measurements` refuses any float anywhere in these
+files, and the schema has no duration fields at all, so there is nowhere a dev
+millisecond could sit even by accident.
+
+## What is in a file
+
+| field | meaning |
+|---|---|
+| `status` | `ok`, or `failed` with `failure_reason` |
+| `react_version`, `bundle_sha` | a bridge is valid only for the exact bytes it was built against; a rebuild renames everything |
+| `rungs` | the ladder both builds ran, in order |
+| `mapping` | `<bundle basename>:<startOffset>:<endOffset>` to a real function name |
+| `evidence` | the count vector that produced each match, for auditing |
+| `ambiguous_prod` / `ambiguous_dev` | vectors shared by more than one function in their own build. **Never guessed at**, only reported |
+| `anchors_checked`, `anchor_failures` | our own components, independently named on both sides, which must map to themselves |
+
+## The failure mode this is designed around
+
+If any anchor fails, the **whole bridge is discarded**, not just the bad anchor,
+and the run degrades to unnamed frames with `symbol_bridge: failed`. A bridge
+that mislabels a function it can check will mislabel functions it cannot, and an
+unnamed frame is a much smaller problem than a confidently wrong name.
+
+## Observed coverage
+
+Against a real React 19.2.4 app on a real Vite 8 profiling build, one bridge
+resolved 19 functions from 26 unique-vector candidates, with 25 prod and 29 dev
+vectors declared ambiguous and left alone. Among the resolved names were
+`createWorkInProgress`, `bailoutOnAlreadyFinishedWork`, `completeUnitOfWork`,
+`updateSlot` and `useFiber`, which is to say the exact fiber-bookkeeping
+functions the M1 hypothesis is about.
+
+Expect roughly this: a minority of react-dom resolves, heavily biased towards
+the functions that run a lot, which are also the ones worth naming. Functions
+that run once or twice share vectors with everything and are correctly refused.