Skip to content

Keep a finished download at the top of Recent, and give cached datasets a timestamp - #73

Merged
mahiatlinux merged 200 commits into
Imagineer99:fix/model-hub-recent-sortfrom
unslothai:pr-9642-followups
Aug 28, 2026
Merged

mahiatlinux merged 200 commits into
Imagineer99:fix/model-hub-recent-sortfrom
unslothai:pr-9642-followups

Conversation

@danielhanchen

Copy link
Copy Markdown
Collaborator

Follow-ups for unslothai#9642. The recent-sort fix there is correct; these close the two gaps it leaves and correct the unit docs. Targets the PR branch so the commits land inside unslothai#9642.

Completed downloads fell to the bottom of Recent

Once a job reaches complete, shouldSurfaceLiveJob stops emitting the live row that carries last_modified: job.startedAt, and optimisticRow replaces it with a row that has no timestamp. An undated row sorts below every dated one, so the model that just finished downloading dropped from the top of Recent to the very end, and stayed there until a backend scan landed. That window is a failed refresh or the full five minute INVENTORY_HINT_TTL_MS.

InventoryHint.createdAt already exists and rememberInventoryHint always populates it, so carrying it through optimisticRow is enough. Both mergeInventoryHint paths are covered: the append branch, and the partial-server-row branch where the seed already overrides. A complete server row keeps its own authoritative timestamp.

Position of a just-finished download in Recent, driving the real modules through the whole lifecycle:

step before after
running 1st 1st
progress ticks 1st 1st
complete, hint window last 1st
backend rescan 1st 1st

Cached datasets had no timestamp at all

CachedDatasetItem carried no time field and none of the four dataset cache scanners emitted one, while local recipe and upload datasets do carry updated_at. Selecting Recent on the datasets tab therefore put every cached Hub dataset after every local one regardless of actual date.

The scanners already stat these directories, so this emits last_modified in the same POSIX seconds the cached model scan uses. The frontend needs no further change because buildCachedInventoryRow already normalizes it. Rendering the real DownloadedList in dataset mode:

before: [cached-dataset-a, cached-dataset-b, recipe-output]
after:  [cached-dataset-b (-1d), recipe-output (-5d), cached-dataset-a (-10d)]

Unit docs

chat-api.ts documented last_modified as epoch seconds. That is still true off the wire from listCachedGguf and listCachedModels, but the picker inventory now builds the same type from a CachedInventoryRow, which is milliseconds. Nothing reads the field on the raw path today, so this is a documentation hazard rather than a live bug, but it is how the next bug gets written.

Tests

Five new suites, 34 tests, plus 8 backend tests:

  • normalizeTimestamp boundary table: undefined, null, 0, negative, NaN, infinities, strings, fractional mtime, and both sides of the seconds/milliseconds pivot.
  • OS-shaped payloads: ext4, APFS, NTFS, FAT32 two second granularity with a DST shifted twin, WSL DrvFs, Windows cache without symlinks, broken symlink, network share reporting 0, a backend that omits the key, and one already sending milliseconds.
  • Comparator algebra: reflexivity, anti-symmetry, transitivity over all ordered triples, no NaN, and all 720 permutations of a six element list matching a stable reference sort.
  • Download lifecycle: the table above. Written to fail before the fix and pass after.
  • Upgrade safety and model picker propagation, including a check that no inventory timestamp is ever written to browser storage, so an install upgraded from a seconds era build cannot compare a stored seconds value against a fresh milliseconds one.

Verified: 4872 frontend tests pass, typecheck, build, bundle budget, biome and eslint clean, and test_cached_gguf_routes.py still 190 pass with the cached model path untouched. Comparator behaviour confirmed identical in chromium, firefox and webkit.

danielhanchen and others added 30 commits August 24, 2026 12:22
* fix(studio): align tool-call nudge defaults

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix(studio): honor shared tool-call nudge defaults

* test(studio): opt into nudge replay probes

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: imagineer99 <[email protected]>
…9149)

* fix(studio): auto-enable --embedding for GGUFs missing pooling_type

Detect dedicated embedding architectures (nomic-bert, llama-embed, etc.) and
embedding model identifiers when the GGUF header omits pooling_type, so
llama-server launches with --embedding and /v1/embeddings works.

Fixes #9128

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix(studio): keep GGUF embedding detection local

* fix(studio): align embedding VRAM probe

* fix(studio): inspect GGUF embedding metadata names

* fix(studio): classify uncached embedding repos

* fix(studio): exclude reranker GGUF fallbacks

* fix(studio): detect GGUF reranker classifier heads

* fix(studio): keep GGUF embedding fallback fail closed

* fix(studio): fail closed on ambiguous BERT pooling

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: imagineer99 <[email protected]>
…ud (#9214)

* Studio: let Read aloud use an external OpenAI-compatible TTS connection

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: don't send custom TTS text when connections are disabled

* Studio: cancel external TTS synthesis when the client disconnects

* Count the new voice connection select in the width contract test

* Studio: forward a retained legacy provider key from custom TTS

* Tighten the comments added by this PR

* Studio: drop the custom TTS connection when it is deleted

* Fix external TTS provider races and voice contract

* Clarify custom TTS voice default

* Make provider endpoint and key updates atomic

* Keep custom TTS connection select controlled

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fix(studio): harden external TTS request routing

* test(studio): make event-loop check scheduler independent

* fix(studio): guard external retries against disabled connections

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Etherll <[email protected]>
* CI: keep host-default README guard within Studio docs

* CI: accept equivalent Studio host flags

---------

Co-authored-by: Etherll <[email protected]>
…it is missing (#9654)

`Overlay rail shadow gutter, other engines` has failed on every studio-ui-smoke
run since #9246 added it, and passed on #9246 itself. The difference is the
frontend-dist cache.

The harness serves its own vite via `npm run dev` in studio/frontend. That job
never installs the frontend dev dependencies: it installs Studio, and setup.sh
installs them only when it has to build the frontend. The frontend-dist cache
exists precisely to stop that build, and the restore action asserts the
installer reported the frontend up to date. So on a cache miss setup.sh builds,
node_modules exists and the step passes; on a hit there is no node_modules,
`npm run dev` exits 127 with `sh: 1: vite: not found`, and the step fails.
#9246's own run missed the cache. Every run since has hit it.

The harness is right and its use in studio-frontend-ci.yml is right, where
`npm ci` has already run. Only the new step's assumption was wrong: what that
shard has already paid for is the WebKit and Firefox install, not a frontend
toolchain.

So the shard installs the dependencies itself, conditional on the binary rather
than unconditional, because on the cold-cache path setup.sh has already put them
there and `npm ci` would delete and refetch them. The step then checks the binary
actually arrived, since a silent install would surface later as a Playwright
timeout rather than as a missing toolchain.

start_vite now refuses up front with the cause and the remedy. "vite exited with
code 127" reads as a vite crash; the toolchain was never installed, and the two
must not look the same. This is what made the failure look like flake: identical
job, identical commit, green or red depending on a cache key.

While here, the wildcard-host detector added in #9623 only matched a command at
the start of a line, so `UNSLOTH_STUDIO_PASSWORD=... unsloth studio -H 0.0.0.0`
in the Launch section passed the guard. It now matches the command anywhere on
the line. Twelve fixtures pin what the detector must catch and must not, because
every negative assertion in that file passes when the detector sees nothing: a
detector that quietly stops matching turns the whole file green while guarding
nothing.
…efusal (#9656)

#9654 added an up-front toolchain refusal to start_vite so a job with no
node_modules fails with the cause instead of 'vite exited with code 127'. That
is right, and the two process-group tests were simply not updated for the new
precondition: they exercise which process-group flag the platform gets, they
already stub the sibling _port_is_taken precondition for the same reason, and
this file's own docstring promises nothing here touches npm or a real install.

So the tests get a synthetic frontend tree in tmp_path with a vite shim, not a
stubbed-out check. A stub would keep them green if the refusal were deleted;
a tree makes the check run and pass on its merits.

Adds the tests the refusal never had: it must reject a tree with no toolchain
BEFORE anything is spawned, accept the bun and Windows shims as well as the
POSIX name, and report a missing checkout as its own failure.
…im (#9238)

* Prefer the .cmd sibling when Windows resolves an extensionless npm shim

shutil.which can hand back npm/pnpm's extensionless POSIX shim ahead of the
.cmd sibling that Windows can actually execute, so unsloth start codex/pi
died in CreateProcess with WinError 193. Resolve the sibling first, then let
the existing cmd-shim parser take over.

Fixes #9167

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Only rescue a shebang-opening file when preferring the .cmd sibling

CreateProcess can run a PE binary regardless of its name, so a resolved
real executable must keep priority over a stale .cmd wrapper beside it.
Substitute the sibling only when the resolved file opens with a shebang,
which is what an unlaunchable npm/pnpm POSIX shim always does.

* Move the .cmd-sibling rescue to the resolver layer

The rescue lived only in _resolved_launch_command, which _launch alone
reaches. The version and capability probes, npm install resolution, and
the MCP subagent bridges all spawn the same shutil.which result directly,
so an extensionless shim still broke them (and everything under
--no-launch). Extract _prefer_windows_cmd_sibling, apply it in
_which_with_install_dirs, _npm_executable, both subagent bridges, and
keep the _resolved_launch_command call for _launch's raw resolver.

Also per review: drop .bat (neither npm's cmd-shim nor pnpm's writer
produces one), restore the no-sibling test's mutation coverage lost to
the shebang gate, and pin the OSError suppression with a directory
fixture.

* Pin the .CMD sibling probe with a test for PR #9238

#9167's pnpm dir holds pi.CMD, not pi.cmd. Dropping .CMD from the probe
tuple was caught by no test, so the entry could be removed silently.
Default NTFS matches either casing on the .cmd probe, but a case-sensitive
volume (ReFS, or a directory flagged with fsutil setCaseSensitiveInfo) does
not, and neither does a case-sensitive CI filesystem.

* Tighten the comments added by PR #9238

Also correct the docstring's account of when shutil.which returns the bare
name: it is the CPython 3.12.0 to 3.12.9 regression (gh-127001), or a PATHEXT
containing a dot-only entry, not any earlier PATH entry.

* Route the MCP subagent spawns through the npm shim parser

Both bridges resolved an executable and handed it straight to Popen. On
Windows that can be a .cmd, which CreateProcess runs through cmd.exe, and
cmd.exe treats CR/LF inside %* as command separators. The Codex prompt and
Claude's --append-system-prompt always span lines, so the child could receive
a truncated prompt or execute prompt text as shell input.

This predates the .cmd rescue: shutil.which already returned the .cmd on every
Python outside the 3.12.0 to 3.12.9 window. The rescue makes it reachable on
that window too, so route both spawns through _resolved_launch_command, which
resolves an npm shim to node.exe plus the script and bypasses cmd.exe. It is a
no-op on POSIX and for any non-shim executable.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten the comments added with the MCP shim resolver fix

* Make the .cmd sibling tests hold on a real Windows host

Both assertions only passed because unsloth_cli/tests runs on ubuntu-latest
only. On windows-latest they fail:

  test_prefer_cmd_sibling_is_none_safe_and_posix_noop asserted no rewrite
  without pinning os.name, so on Windows the rescue fired and the assert
  checked the opposite of its intent. Pin os.name to posix.

  test_resolved_launch_command_rescues_uppercase_cmd_sibling compared path
  spelling, but a case-insensitive volume answers the earlier .cmd probe with
  the .CMD file, so the returned spelling differs while the file is the same.
  Compare with os.path.samefile.

Confirmed against a real windows-latest runner. Neither is a defect in the
shipped helper; both were tests asserting something false on Windows.

* Correct the CPython version range in the shim rescue docstring

I had written 3.12.0 to 3.12.9 and cited gh-127001. Measured on real
windows-latest runners instead: only 3.12.0 returns the bare name, and
3.12.1, 3.12.2, 3.12.3, 3.12.7, 3.12.10, 3.11.9 and 3.13.15 all return the
.CMD sibling. That is gh-109590, fixed in 3.12.1, not the later gh-127001.
The original wording naming 3.12.0 alone was right and my edit broke it.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
* CI: guard the host default structurally, not by README heading

The Launch-section slice in tests/sh/test_install_host_defaults.sh has now
broken twice on correct README edits, once when '#### Update' was deleted and
again when the -H 0.0.0.0 opt-in moved under '#### Remote HTTPS & LAN Access'.
Parse the fenced code blocks instead and read the first studio command in
document order as the primary one, so no heading is load-bearing.

Also stop hand-spelling the needle. The host flag spellings are read off the
typer.Option in unsloth_cli/commands/studio.py that declares them, and the
detector matches the flag anywhere in the command rather than adjacent to it,
which closes 'studio -p 8888 -H 0.0.0.0' and '--host 0.0.0.0' on all five
negative assertions.

* Report a probe crash as a named failure, not a bare set -e abort

* Silence the two intentional SC2016 with a reason each
* Studio: stop dropping quantized KV cache on tensor split

* Studio: budget an env-inherited quantized KV cache

* Studio: price the quantized axis, and handle an older llama.cpp

Follow-ups to the gate removal, from reviewing what became reachable once a
quantized KV cache started surviving a tensor split.

Every estimator resolves ONE cache type: the heavier axis, for KV bytes. That
same scalar also selected the compute-buffer rate, and _compute_buffer_ctx_bytes
charges the per-device dequant scratch only when its type is under f16 -- so an
asymmetric -ctk q4_0 -ctv f16 priced the scratch as if nothing were quantized.
The tensor gate used to make this unreachable by rewriting both axes, which is
what the comment removed from _plan_tensor_parallel said. Split the two: heavier
axis for bytes, lighter axis (_planned_scratch_cache_type) for scratch. Measured
end to end through load_model on an 80L/n_embd 8192 model, 4x48GB, n_ubatch 2048:
the emitted -c was 262144 and is now 175104. Tensor mode has no --fit valve, so
that surplus was a startup OOM rather than a spill. The layer path took the same
scalar and gets the same fix.

An older llama.cpp refuses the pair outright, in llama_init_from_model:
"simultaneous use of SPLIT_MODE_TENSOR and KV cache quantization not
implemented". That is LLAMA_LOG_ERROR + return nullptr, so it is a clean exit 1
and _should_record_tensor_split_abort cannot see it -- every load spent two full
model-load cycles (the tensor attempt plus the --fit retry) before the route's
layer fallback, forever, and reported "Check that the GGUF file is valid and you
have enough memory". Classify the marker, skip the fit retry on it as the
split-axis abort already does, and latch it. One doomed attempt on the first
load, then none, and a message naming b9455.

The abort latch was keyed on (binary, mtime, model). Now that the cache type
reaches the tensor child, an abort can be specific to it: iq4_nl asserts under a
tensor split on b10441 while q4_0 runs on the same binary and model
(ggml-org/llama.cpp#27116), and a pre-b9455 binary refuses every quantized type
while f16 is fine. Key it on the planned (K, V) pair too, so one type's failure
does not take tensor mode away from the types that work.

Two smaller ones on the same seam. A cache type kv_cache_type_from_str does not
know is never emitted, so the child inherits LLAMA_ARG_CACHE_TYPE_K/_V instead --
but the budget priced the unemittable string at _kv_bytes_per_elem's 2.0 unknown
default, a 2x under-reservation against an inherited f32. And an inherited type
that llama.cpp cannot parse (q3_K, a typo, or a case-mismatched Q8_0) now reaches
the child, aborting it at argument parsing; the layer retry inherits the same env
and fails too, leaving no server. The managed path has been allow-listed and
lowercased at emission for a long time; give the env path the same two.

Tests: a new OS x accelerator x cache-type matrix over
[linux, wsl2, windows, macos] x [nvidia multi/single, amd rocm, amd vulkan,
apple unified, cpu-only] x [f16, q8_0, q4_0, q5_1, iq4_nl], asserting both axes
per cell, that the >= 2-device cells keep tensor mode and the rest drop the whole
split-mode group, and that no tensor launch pairs --flash-attn off (still a hard
error upstream). Plus the end-to-end legacy-build cost, the scratch-axis
selection, the two budget guards, and the assertion the deleted restore-path test
used to carry: a downgrade must not rewrite an asymmetric pair.

Checked against current llama.cpp master rather than its docs: the guard #23792
deleted is gone from src/llama-context.cpp, while docs/multi-gpu.md still lists
the restriction -- it was last touched 2026-05-07, three weeks before #23792
merged.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: scope the old-build latch to the binary, and match on the effective cache

Three review findings from the round on the previous commit.

The pre-b9455 refusal was recorded in the model-and-cache-pair-keyed tensor-abort
set, but llama_init_from_model refuses every quantized type for every model on
such a binary. Loading a second model, or switching q8_0 to q4_0, therefore paid
another doomed full model load. It now records into its own
_tensor_quant_kv_unsupported_binaries set keyed on (binary, mtime) and is
consulted at the up-front gate, before the spawn. A non-quantized pair is
unaffected, since f16 still gets a tensor split on such a build, and the mtime
means an updated binary is re-probed. The split-axis abort keeps the finer key:
that one really is specific to a model and a cache type (iq4_nl asserts on b10441
while q4_0 runs, ggml-org/llama.cpp#27116).

_runtime_matches_intent compared self._cache_type_kv against intent.cache_type_kv.
That scalar holds only what Studio emitted as a managed flag, so a cache set
through extras or the environment left None on one side and a type on the other,
and an identical repeat /load tore down a healthy server to relaunch the same
thing. It now compares _effective_cache_types, the per-axis pair the running
child was actually launched with, against _planned_main_cache_types for the
incoming request. A layer load has always had this; the tensor gate used to hide
it by rewriting the cache away.

The inherited-cache-type normalisation compared against an already-stripped copy,
so " q8_0 " matched itself and nothing was written back. Compared against the
original value now. common_arg::get_value_from_env hands the raw getenv string
through and kv_cache_type_from_str compares it to ggml_type_name(t) exactly, so
surrounding whitespace aborts the child exactly as a typo does.

Not taken: the report that removing the cache scrub sends a quantized V cache to
a launch with --flash-attn off. The emitted argv is identical to main on the
layer path (the extras win last there too), and on the tensor path llama.cpp
rejects the load on "SPLIT_MODE_TENSOR requires flash_attn to be enabled", which
llama_init_from_model checks before any KV type, so the V type does not decide
the outcome.

_ALLOWED_TP_DROP_GUARDS gains the new binary-wide gate, which is what that
tripwire is for.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: count the implicit f16 axis, match on the request, keep multi-GPU

Three more from the round on the last commit.

_env_main_cache_type_for_budget collected only the axes that were SET, so a
single quantized axis carried the whole scalar: LLAMA_ARG_CACHE_TYPE_V=q4_0 with
K unset returned q4_0, and the caller then priced K as q4 while the child ran it
at f16. An unset axis is not absent, it is llama.cpp's f16 default, so it now
takes part in the max. Measured on a key_length 192 / value_length 128 model at
131072: the reserve was 14.22 GiB against the 25.00 GiB the f16 K axis really
needs, so the cheap type had landed on the larger tensor. The existing assertion
that a lone q4_0 adopts q4_0 is updated; it pinned the under-reserving answer.

The reload matcher compared the pair the child was LAUNCHED with against the pair
the request resolves to. A launch-time rewrite makes those differ on purpose (a
build with no --flash-attn resets a quantized V cache to f16 before the spawn,
and the flash-attn crash recovery does the same), so every identical repeat load
was rejected and redid that normalization instead of reusing it. It now records
_requested_cache_types beside _effective_cache_types and compares requested
against requested, which is the rule the tuning group above it already uses.

The binary-capability skip added last commit downgraded to layer without raising
_layer_min_gpus, so the auto layer planner started at one GPU and stopped there as
soon as the model fit, quietly collapsing a multi-GPU request onto one card. The
adjacent split-axis skip raises it for the same reason: neither failure says
anything about capacity.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: tighten the comments added by this PR

Comments only, no code change. Collapses the longer rationale blocks in
llama_cpp.py and the two test headers to the same content in fewer lines.

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…9609)

* studiobench: a window's stream-cost integrity is about one response

`StreamCostInstrument.close` refuses a window whose opening buffer held half a frame AND
which then counted that frame. That pair is the thing that actually makes the denominator
wrong: characters delivered before the window opened, counted inside it. The two halves
were read at two different scopes. `pending` lives on the per-decoder state; `carriedFlushes`
was page-global on `S`, so any decoder could move the counter that was supposed to be about
that one buffer.

`send_turn` follows `stop_generation` in all three shipped schedules, and `stop_generation`
exists to cut a socket mid-frame. So the abort's orphaned half frame was routinely paired
with a carried flush produced by the NEW response's own split, and a window that had
delivered every one of its characters was refused for a buffer that never flushed.

Measured against the real instrument in Chromium rather than argued: a two-chunk reply
after an abort delivers all 13 of its characters inside the window and is refused, while
the same traffic with no abort in front of it is accepted. A refused window is dropped
outright, and reads go ragged exactly when the renderer is jammed, so the loss falls on the
most expensive windows. That is the flattering direction on cost per character.

## What changed

`carriedFlushes` moves onto the decoder's own state beside `pending`, and
`wireIntegrity(id)` answers about a NAMED decoder whose id `open` records and `close` passes
back.

Named rather than compared at the two ends, and that distinction is the whole fix. A
same-id-at-both-ends check gets the important case wrong: the response pending at the open
can complete its carried frame INSIDE the window and then be replaced as the active decoder
before the close, and an id comparison would see two different ids, discard exactly the
carry it is looking for, and accept a window whose denominator really is wrong. Asking
about the named decoder answers regardless of who is active now.

Two details that would otherwise bite later. The sentinel `active` is built by the same
constructor as a real decoder state rather than by hand, or a window opening before the
first stream reads `undefined` where it wants zero. And the id map holds integers and no
`TextDecoder` reference, so it cannot defeat the WeakMap scoping the previous fix
introduced; it is bounded on the same discipline as `MAX_PENDING_CHARS`.

No payload key changes. `decoder_id` is an argument between `streamcost.py` and
`streamcost.js` and never reaches a row, so `INTERFACES.md` has nothing to add and the
reasoning lives in the instrument.

## Tests

Three new, and the second and third are the ones that matter:

- the fragmented response after an abort is scoreable
- the counter is shown still to MOVE, asked of the decoder that owns the split, so the
  first test cannot pass against an instrument that has simply stopped counting carried
  flushes, which would take the genuine straddle refusal down with it
- a frame that really did straddle the window open still refuses its window, with another
  decoder active at the close, which is the case the rejected id-comparison fix would break

Mutation: put the counter back on a page-global and the first fails with
`assert 1 == 0` on `wire_carried_frames_counted_in_window`.

Four existing exact-dict assertions gain the new key, on the same tolerance idiom they
already use for `carried_flushes` beside it.

`pytest tests/studio/studiobench -q`: 1301 passed, up from 1298. `ruff` clean.

Follow-up to #9439, where this was accepted as a real residual on the fix made in that PR
and deliberately left open.

* Tighten the comments added by the stream cost integrity change

* Pin the marker fragment case at the stream cost window boundary
…e migration (#9603)

* Make the legacy-migration picker step deterministic, and unit-test the migration

`legacy unsloth_load_settings migrates once and stays idempotent` in
tests/studio/playwright_model_config.py flips between pass and fail on identical
input. It has gone red on main itself three times (runs 32671622061 @0fea40d75,
32677249361 @0df6fde86, 32680622174 @3c998cc8f, all push events on main) and on
two unrelated branches, and a re-run of a failed job passes with no code change.
There is no regression behind it.

The assertion's message was also misleading. It reported "legacy context 4096 not
migrated", which reads as the migration running and dropping a field. It was not:
the record left behind carries kvCacheDtype null although the seed carried q8_0,
so nothing from the seed had been imported at all.

What actually happens. The step clears localStorage in the live document and then
reloads. Opening the run-settings panel starts a GET of the model overrides and
writes the resolved row back into `unsloth_model_configs` when it answers, so a
response still in flight from the previous step lands in the ~20ms between
`removeItem` and the navigation and re-creates the key. The reloaded page then
finds that key occupied, `mergeLegacyEntries` skips the entry it was seeded to
import, and `migrateLegacyLoadSettingsOnce` latches the flag anyway. A second
route to the same red: the step clears local storage but never the server-side
override rows that steps 2 to 4 leave behind, and a row carrying a context of its
own outranks the migrated value.

Both are reproducible on demand against an unmodified driver, and both reproduce
a CI failure byte for byte:

  driver   injection                        result
  HEAD     none                             PASS
  HEAD     late write-back before reload    FAIL  customContextLength null, kvCacheDtype null
  HEAD     server row carrying ctx 2048     FAIL  customContextLength 2048, kvCacheDtype q8_0
  fixed    late write-back before reload    PASS
  fixed    server row carrying ctx 2048     PASS
  fixed    none                             PASS

The first failing shape is the one seen on main; the second is the one seen on
branch restore-resumable-http-partials.

The fix is to the test, not to the product. Seeding now happens in an init script
that runs at document start on the page under test, after every write from the
discarded document has gone with it, so the store the import reads is the one the
step asked for. The step also drops the server override rows for its model first,
which is what makes it a test of the legacy import rather than of server
precedence. The fixed sleep after the panel opens is replaced by a wait on the
condition the assertions need, the migration flag appearing, which is the last
thing the import does on every path it takes.

The assertion now separates "the import ran and lost the context" from "the
import never ran", using a Disable Vision fingerprint that only this seed can
supply: no other step sets it, and the API only sends it when true, so a row
mirrored back down cannot forge it. That distinction is what was missing, and
chasing the old message cost an investigation of normalizeV1, which was innocent.

The migration had no unit test anywhere; its only coverage was this browser step.
studio/frontend/tests/legacy-load-settings-migration.test.ts pins the contract in
milliseconds and through the module's public read path, so re-keying or
re-versioning the records stays free.

Checked for reachability rather than argued: with a real upgrade shape at document
start (legacy blob, no versioned map, no flag) and the write-back armed by an
existing server row, the remembered context survives. `storedAtStart` is itself a
store read, so it always reflects the completed import, and an absent server field
falls back to it. The harness ingredient that makes the failure possible, deleting
the map after the flag has latched, is not something the app can do to itself.

Anti-vacuity. With `legacyEntryToConfig` altered to drop `contextLength` and the
frontend rebuilt, the repaired Playwright step fails, and fails through the new
branch: "was DROPPED by the migration ... disableVision true, customContextLength
null". Against the unit tests, four separate mutations were tried: dropping the
context, never latching the flag, letting a legacy blob overwrite a config saved
by this build, and importing an all-defaults blob. The first three are caught; the
third initially was not, because the case saved its record after seeding and the
save itself triggers the import, so the precedence branch never ran. Reordering it
to save first makes the mutation red, and the comment there records why.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Make the override cleanup fail loudly and match local-path rows

Three ways the step 5 cleanup could leave the migration check measuring server
precedence while reporting nothing.

A failed inventory read as an empty one. evaluate_fetch reports a timeout or
an HTTP error by returning status 0 or a non-None error rather than raising,
which is what its own contract says to check. rows_for_model checked neither,
so a request that never landed came back as there are no override rows: the
cleanup did nothing and its own post-delete verification passed on the same
silence. It now returns None for could not read, which is not the empty list,
and says so.

Local-path rows never matched. The whole model:quant string was folded as one
identity, which only works while the model half folds too. normalizeModelIdentity
deliberately keeps a plain POSIX path's case, so with a local-path GGUF_REPO
the row /models/Foo.gguf:UD-Q4_K_XL normalised to itself and never matched the
lowercased ...:ud-q4_k_xl being compared against. Model and quant are now
normalised separately, which is what entries_for_model already does with these
same two values.

A row that came back after being removed. syncModelOverride is fire-and-forget,
so a mirror PUT from steps 2 to 4 can still be in flight and recreate the row
moments after a single post-delete read found it gone. Absence is now confirmed
over a short window instead of at one instant, and a row that reappears is
removed again.

And the pass now requires the fingerprint. disableVision is the field only this
seed sets, and the success branch was reading the context alone -- which a
surviving server override row also carries, since step 3b wrote it. So the step
could report OK migration on a context that the legacy import never applied.
That is the exact confusion the fingerprint was added to end, missing from the
branch that decides whether the step passed; it is now its own distinct
failure.

* Sample the whole settling window, not up to the first empty read

The loop broke on the first empty inventory read, which confirms absence at one
instant plus 250 ms. That is the single-read weakness it was written to replace,
moved one step along: a queued syncModelOverride PUT arriving in a later
interval still recreates the row before hydration reads it, which is the flake
this step is about.

It now samples every interval and removes any row that comes back, so the
window in the comment is the window the code actually enforces. A read that
fails mid-window still ends it as unknown rather than as absent.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…lbar (#9658)

* Reapply "Say why a Xet download sits at 0% until it finishes (#9159)" (#9293)

This reverts commit e326033.

* Shrink the Xet notice so it clears the hub toolbar

The notice itself was fine. Its size was not: 62 characters of title and
330 of description rendered 235px tall in the top-right corner, which is
where the Model hub keeps its own toolbar. While the toast was up the
capability filter, the sort dropdown, the Models and Datasets tabs and
the repo action icons sat underneath it. Hit testing each control's own
centre point put 4 to 6 of them inside the toast, so they could not be
clicked, three times per install at 8s each. That is what #9293 reverted.

Title is now 19 characters and the description 149, in plain language and
one paragraph, which drops the pre-line class the old blank line needed.
The character budget is asserted in the tests rather than left as a
convention, since the failure is invisible to unit tests and to a
screenshot taken at the wrong viewport.

* Drop the HTTP hint: it left a 0.5px margin, not a margin

The measured pair showed the shortened toast clearing the toolbar, but
only just. At 149 characters it rendered 114.5px tall, bottom edge at
y=126.5, against a hub filter row whose centre sits at y=127. Every
control hit-tested as clickable, so the check passed, by half a pixel.
A longer translation, a different font stack or a zoom level would have
put it back over the row and re-broken what #9293 reverted.

At 101 characters the toast ends near y=100 and does not reach the row
at all, so the result stops depending on sub-pixel layout. The budget in
the tests drops from 170 to 110, which now rejects the 149-char version
rather than accepting it.

The transport control is two clicks away in Model Hub and discoverable
without being told. A toast that eats the toolbar is not worth it.
* studiobench: two ui parity gates that could only ever say yes

Both of these are gates that report a pass on input they cannot represent, which is the
one failure mode this whole instrument exists to refuse. Neither could report the other
answer.

## The coverage floor never ran on a windowed run

`main` returns before the structural loop when no pair is fully mounted, and everything
cross-cutting kept being written below that line. During the review of #9439 three
consumers of that one early return were found and each was hoisted or duplicated in turn:
the null control's tier axis, then its corpus axis, then `--audit-null`. This is the
fourth. `--min-compared` is a parameter of `report()` and enforced at one site inside it,
and `report()` is only reachable below the return, so a run with no fully mounted pair
applied no coverage floor of any kind: `--min-compared 20` exits 0 on one matched capture.

Two ways in, neither exotic. Every pair classifies windowed, or either of the forced
`--mode visible` / `--mode behaviour` invocations, both of which hard-set the structural
plan to an empty set for EVERY pattern, unconditionally. The workflow passes
`--min-compared 16` on every run, and that floor is what replaces a slot-budget liveness
gate for a job that reads no timings. Two blank pages have identical digests, so a run
that drove nothing is the easiest possible pass, and this is the guard against it.

Fixed structurally rather than a fourth time by hand. The three reports return the pairs
they scored and `main` applies one floor over all of them. SUMMED across modes, not
checked per report: a combined run splits one film's coverage three ways and a per-report
floor fails a run that compared plenty. UNIONED rather than added: `--mode auto` scores
each windowed pair twice, once on the visible region and once on the invariants, so adding
two counts would double every windowed pair and let a floor of 16 pass on 8. `report`
keeps its own parameter and its own exit 3, because the selftests call it directly and it
is a complete report in its own right.

The return type is an `int` subclass. That is deliberate and it is commented at the
definition: the exit code is the primary value, `main` does `worst = max(worst, ...)` at
four call sites and the selftests assert `== 0` / `== 1` / `== 2` / `== 3` against these
three functions directly in several dozen places. A tuple or a dataclass would mean
rewriting all of those in bulk to say exactly what they say today, and an assertion
rewritten in bulk is an assertion nobody re-derived.

## Two mounted rows sharing a thread position produced MATCH

`parityVisible.capture()` keys its per-message digests by thread position and the
assignment was unconditional, so a second mounted row publishing a position a row already
held silently REPLACED that row's digest. `VIS.ever` is a set of numbers, so it collapsed
the pair as well. Three rows on screen produced a capture indistinguishable from a capture
of two, and `compare_visible` then reached a verdict out of a set it did not know was
short.

Whether that was ever caught was DOM order and nothing else. Reproduced in Chromium: the
same ghost row inserted BEFORE the row it shadows leaves the surviving digest agreeing
with the other arm and the pair returns MATCH; inserted after, it returns DIFFER. Last
writer wins, so the collision passes exactly when the survivor happens to be the one that
agrees. The pre-film readiness gate cannot help, because it checks the ordinals an arm
publishes before the film and this is introduced during an action.

Counted directly rather than derived. `unmounted_at_capture` looks like it should notice,
an extra row at one position and a vacancy at another, but in the renumber case the two
cancel and it reads a clean zero over a live collision. Consumed BEFORE `ever_visible` and
`messages` are compared, because those are the two quantities the collision made short.
Read defensively, so a payload recorded before the counter compares exactly as it did.

The residual is stated in the code: a collision that had resolved to one row by capture
time is not detectable here, and catching it needs the clash recorded when the position is
stamped, which is a change to the observer's state model rather than to this loop.

## And the two build differences a capture comparison cannot see

`compare_all_with` built its whole result from a capture comparison plus the conjunction of
`ran`. So an action that RUNS on one build and cannot be performed on the other collapsed
into the same bucket as a missed slot, which every report here counts as lost coverage
rather than a finding, and an action that ran on both arms and failed its OWN assertion on
one of them left no trace at all.

`compare_rows` has always asked both questions; the visible and behavioural paths never
did. That is survivable on the structural path and not here, because on a windowed arm
THESE two reports are the entire UI verdict: the digest is `not_applicable` by construction
and `stop_generation` has no behavioural invariant of its own, so in `--mode auto` a
passing invariant on another action carried the run to exit 0.

Both questions now come from `analysis/parity.py`'s own functions, extracted out of
`compare_rows` so there is one copy rather than a second opinion written out elsewhere --
the drift `INVALIDATING_CELL_GATES` was centralised to prevent, arriving one level down.
Held to the same bar the structural path holds: `racy_execution` exempts the not-run
reasons that are a lost race rather than a missing control, and `corroborated` demands the
same repetition count, keyed on the arm the finding names.

## One existing expectation changed, and it moved UPWARD

Calling this out rather than leaving it in the diff, because a changed expectation is the
right thing for a reviewer to be suspicious of.

`test_a_timed_out_rebuild_leaves_the_behavioural_run_with_no_verdict` asserted exit 2. Both
statements about that payload are true: the invariant could not be read, AND the action's
own assertion failed on the treatment arm alone. `report` already resolves that precedence
for the structural mode, in a comment at the site -- "a run can find a real regression
while deciding nothing, and 'it failed' is the more specific answer than 'it could not
tell'". Running `report` over that very payload returns 1, so the two modes were
disagreeing about one payload and the behavioural one was giving the vaguer answer.

The test now asserts 1, keeps every one of its original assertions (`invariants held: 0`,
one pair NOT COMPARABLE, NOTHING WAS COMPARED all still print), adds the new one, and pins
the agreement between the two modes so they cannot drift apart again. Nothing was
loosened: 1 is a failure and 2 is a refusal.

## Tests

`pytest tests/studio/studiobench -q`: 1308 passed, up from 1298. `ruff` clean.

Mutation study, each mutant reverting one fix to its pre-fix behaviour, with the mutation
confirmed present in the tree before anything is run:

| mutant | tests red | failure |
| --- | --- | --- |
| floor goes back below the early return | 3 | `assert 'TOO LITTLE COMPARED' in ...`, mutant exits 0 |
| reports blinded to the two build differences | 3 | `assert 'ASSERTION FAILED ON ONE ARM' in ...` |
| duplicate ordinal overwritten again | 2 | `assert 0 == 1` on `ordinal_collisions` |
| `compare_visible` stops consuming the counter | 1 | `assert 'differ' == 'not_comparable'` |

Both-direction controls are present and stay green: an assertion that failed on BOTH arms
is coverage lost rather than a build difference, a missed slot is a slow machine and not a
build difference, a legitimate renumber-in-place records zero collisions, and a floor set
beneath what the run actually compared still exits 0.

Follow-up to #9439, where the coverage floor was accepted as correct and deliberately not
fixed, and where the duplicate-ordinal and action-outcome reports arrived after the last
round and were merged over without an answer.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten the comments added by the ui parity gate change

* Check the ui parity coverage floor once per payload pattern

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studiobench: losing the thread outranks the collision refusal

Found by rehearsing the merge with #9575 and then auditing the auto-merged result rather
than trusting it, which is how this class of thing is supposed to be caught.

The collision refusal added in this PR returns NOT_COMPARABLE before anything else in
`compare_visible`, and one of the things it was returning ahead of is the "one arm's
viewport ended EMPTY and the other's did not" finding, which is raised with `severe: True`
and documented at that site as NOT SUPPRESSIBLE. Losing the conversation is a different
kind of statement from a capture that could not be read, and the blanket refusal was
downgrading it.

A collision provably cannot have manufactured that finding: a collision needs TWO mounted
rows sharing one position, so the map it corrupts still holds at least one entry. It can
merge two entries and it can never empty a map. So the one comparison a collision cannot
have caused is still reported.

Only that one, and the asymmetry is the point. Every other comparison below IS corrupted by
a collision: `ever_visible` loses an ordinal on one arm alone, so "the two arms put
different messages on screen" can be entirely an artefact of the collision, and the
per-ordinal digests are short by a row. Those stay behind the refusal.

This also puts the refusal on the same footing #9575 gives its own blindness probe --
placed so that losing the thread stays a finding whether or not the capture could be read
in full -- so the two land consistently rather than establishing two different orderings
for the same kind of refusal.

Two tests, both live: the severe finding survives a collision on the other arm, and the
control that a collision with both viewports alive is still refused. Mutation: drop the
`and not lost_the_thread` guard and the first fails with
`assert 'not_comparable' == 'differ'`.

* Record the third UI parity exemption in the policy the gate prints

The declared policy named two exemptions and there are three. The missing one is
UI-PERF-POLICY.md section 1(c): select-all need not select all, PROVIDED copy stays
complete. Copy may serialise the thread from the message store as markdown or plain
text rather than reproducing a DOM selection. Completeness of the copied content is
REQUIRED, silent truncation being data loss; visual selection fidelity is NOT. That
is what makes deferral and virtualization cheap, because the copy path stops
depending on what is mounted.

Updated everywhere the policy is stated, not only the two places that counted it:
the POLICY constant and its comment in analysis/parity.py, which is what the three
report modes print into the CI job output; the header comment in scene/parity.js;
CONTRIBUTING-perf.md; and INTERFACES.md.

The exemption is stated with its condition attached everywhere it appears. Naming it
without the condition would read as permission to lose conversation.

No mode grants it off a digest, and the text says so rather than implying otherwise.
--mode behaviour is the only one that speaks to it, through
clipboard_carries_the_whole_thread, which already scores the copy against the THREAD
rather than against the other arm; that is the required half. Where a payload carries
no readable select_all_copy the gate records that the exemption exists and does not
grant it. This is the same shape as the caveat the off-screen exemption already
carries, and neither is weakened here.

Nothing in the verdict logic enumerated the exemptions, so the gate was never
narrower than its docstring: the off-screen exemption is expressed as NOT_APPLICABLE
in compare() and granted in compare_visible(), the performance one is a human
decision with no code path, and there is no exemption list or count anywhere. The
only code carrying the two-exemption shape was prose in strings. One assertion did
encode it -- "cannot grant either exemption" for the behavioural mode, where "either"
means one of two -- and it now asserts the accurate three-way split. Every mode's
policy line is held to naming the exemption together with its condition, which fails
if the POLICY constant is reverted to two.

* Say that clipboard completeness is scored by length, not by content

The behaviour-mode policy line claimed the copy stays "complete", which reads
as a comparison of the copied characters. It is not one. Each arm's clipboard
length is divided by the thread's own visible text and the ratio has to land
inside MIN_CLIPBOARD_COVERAGE-MAX_CLIPBOARD_COVERAGE.

A content comparison is not available here and is not the missing half: the
base arm's clipboard is the DOM's rendered text while a store-based copy is
markdown source, so two correct serialisations of one conversation differ
character by character. The band is what carries the claim, and it is
two-sided for that reason -- the lower bound refused truncation measured at
0.61 of the thread, the upper bound refused the substitution at 2.16.

So the printed line now names the measure, disclaims the comparison it does
not perform, and interpolates the live band through behaviour_policy() rather
than repeating numbers that would drift away from the ones enforced.

* Stop behavioural coverage standing in for visible coverage

The coverage floor unioned the compared sets of the two windowed modes. That
is right for the structural set, which is a disjoint set of pairs whose
coverage really does add up. It is wrong for these two: under --mode auto they
are not two slices of one film, they are two verdicts on the same pairs.

Unioned, one stood in for the other. Behavioural mode reaching all 16 pairs
while the visible capture could be read on only 1 still put 16 keys in the set,
cleared --min-compared 16, and exited 0 with essentially the whole appearance
surface unmeasured. That is the false green the floor exists to refuse,
arriving through the floor itself.

It is not an intersection either, and that is worth stating because it looks
like the obvious repair. The two modes are asymmetric in what they claim to
reach: visible-region parity applies to every windowed pair, while a
behavioural invariant only exists for the handful of actions that declare one.
Every other pair is reported UNCHECKED, which is not a pass and equally not a
shortfall, so requiring both verdicts on every pair fails a run for pairs
behavioural mode never had an opinion about. Measured at 1 of 4 on the existing
coverage fixture, where visible mode read all four.

So in auto the numerator is the visible verdict, the one owed on every pair,
and --mode behaviour on its own still counts its own. seen stays a union: it is
the denominator, the pairs the reports were offered, and shrinking it alongside
the numerator would hide the shortfall it exists to express.

Both directions are pinned. Four behaviourally checked pairs with one visible
capture now report 1 of 4 and exit 3; four visible pairs with three UNCHECKED
behavioural ones still exit 0.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Withhold the no-verdict banner when invariants broke

matched and broken are filled from disjoint branches of one loop, so an
all-BROKEN payload reaches matched == 0 as well. The run listed its broken
invariants, then said not one invariant was evaluated and that it carried
neither a pass nor a failure, then returned 1, sending the reader off to find
out why actions that had run did not run.

Gate the banner on broken, which is the precondition its own paragraph argues
from, matching report and visible_report. Not gated on build_failed: those
shapes come from pairs whose invariants were unreadable, so the banner stays
true there and the existing timed-out-rebuild test pins that pairing.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…#9657)

Two changes to release-desktop.yml, neither of which alters how a release runs
today.

All thirteen signing secrets, the Apple certificate and its notarization
credentials, the Azure Trusted Signing set and the Tauri updater private key,
are read by the build job and by no other job in the workflow. The job named no
environment, so there was nowhere to attach a required reviewer and anyone able
to dispatch the workflow could sign a release under our identity. build now
names a release-signing environment. GitHub creates a referenced environment on
first run with no protection rules and no branch policy, and repository secrets
still resolve inside a job that names an environment, since environment secrets
only take precedence over a colliding name and this environment holds none. The
line is therefore inert until required reviewers are added in repo settings,
which is the follow-up this enables.

The Apple certificate was decoded with an unquoted echo, so the value was word
split and glob expanded before base64 saw it. That works for a single line
secret and silently produces a truncated certificate.p12 for a line wrapped
one. printf '%s' with quotes passes the secret through byte for byte, and is
identical to the old behaviour for the single line case in use today.
…#9618)

* lint: refuse a name bound twice in one scope of a changed Python file

A bad merge resolution can leave two complete top-level copies of one def, or
a name repeated inside a single 'from x import a, a'. Nothing in CI catches
that today: compileall parses both copies, the ruff rule set here is
E9 / F63 / F7 / F82 with no F811, and the two copies usually differ only in
their comments so the diff reads as normal.

Adds scripts/lint_duplicate_definitions.py (AST only, stdlib only, 18 self-test
cases) and two Lint CI steps: the self-test, and a sweep over the Python files
a PR changes. A finding fails only when it sits on a line the PR added, so a
duplicate that was already in the file does not block an unrelated branch that
edits it.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* lint: decide a duplicate by comparing both revisions, not by which lines moved

The added-line gate answered the wrong question. A merge that inserts the FIRST copy
above an existing definition reports the finding at the second, unchanged line, so the
branch that created the duplicate read as pre-existing and the check passed. Scan both
revisions and compare findings by identity instead, resolving a rename to its old path so
moving a file that already carries one of main's duplicates is not blamed on the mover.

Also cover the shapes the rule was missing: typed module constants (AnnAssign), two
aliases from one module landing on the same bound name, and imports inside a class body.

On the workflow side, include renames in the changed-file sweep (an ACM filter drops a
renamed-and-edited file entirely) and pin the head commit before diffing, refusing to
continue if it is unreachable rather than silently checking nothing.

* Close four false negatives in the duplicate-definition gate

A bare @Property is the FIRST binding of its name, so exempting it hid two complete
copies of one property in a class. Only the accessor form (@v.setter / @v.deleter /
@v.getter) legitimately rebinds, and that stays exempt.

An ALL_CAPS tuple target is not one binding but several. B, H, N, D = 1, 16, 50345, 128
is a shape this repo declares module constants with in 32 places, and duplicating that
line rebinds all four at once. The self-transform exemption is now decided per name, so
A, B = B, A still exempts both while A, B = 1, 2 exempts neither.

A plain import binds the ROOT of its dotted path, not the dotted path itself. Keying on
the raw optional alias missed import urllib.parse followed by import urllib.parse as
urllib, which silently repoints urllib from the package to the submodule.

The emitted finding identity for a plain import dropped the module it came from, so two
different duplicates both read as import:None:x and compare mode charged a newly
introduced one against a pre-existing counter entry.

Both changed-file sweeps now use -z. core.quotePath is on by default, so a non-ASCII path
arrives as "caf\303\251.py", whose suffix is .py" rather than .py; the workflow would
have checked zero files and reported success, and the rename map would have failed to
match its own before side.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Close four more holes in the duplicate-definition gate

Four wrong answers, three of them false negatives and one a false positive.
The false positive is the one that matters most for a gate: it blocks correct
code, which is how a gate gets switched off.

Chained assignment. `N = K = 256` is two bindings in one statement, and this
repo writes it (tests/test_grouped_gemm_optional_gather_indices.py:46).
Requiring exactly one Assign target dropped the whole statement, so a
duplicated copy rebound both names and the scan still reported clean.

Overload through an import alias. The decorator was matched by its literal
text, so `import typing as t` with `@t.overload`, or `from typing import
overload as ov` with `@ov`, was not recognised and the signatures were
reported as duplicate definitions. The alias is now resolved from the module's
own imports, and only from typing / typing_extensions -- `import types as t`
with `@t.overload` is still a finding.

Explicit alias collisions. Imports are now keyed on the name they BIND. The
carve-out is for names the author never chose: an implicit binding takes
whatever its source is called, so `import urllib.parse` beside
`import urllib.request`, and `from a import x` beside `from b import x`,
stay legitimate. An explicit `as` alias is chosen, so a second binding of it
is always dead -- `import urllib.parse as client` beside
`import urllib.request as client` was invisible while the key carried the
source. `import urllib.parse` beside `import urllib.parse as urllib` still
reports, which the previous spelling was written to catch.

Renames from a non-Python file. Following `mod.txt` to `mod.py` back to the
text file consumed its duplicates as pre-existing, but the rename is precisely
what makes those definitions active code, so the destination is now treated as
an addition unless the before-side path was itself a .py file.

Run over the whole repo the findings are unchanged, 33 before and 33 after,
so none of this widens the gate on code already here.

* Close five more holes in the duplicate-definition gate

Two of these were introduced by the previous commit's own import rework.

Every implicit source is now remembered, not just the first. Keeping one entry
per bound name and skipping the legitimate different-source case left seen
pointing at the first source forever, so in from a import x / from b import x /
from b import x the third was compared with a, looked like the legitimate shape
again, and the exact repeat of b went unreported. Implicit bindings are tracked
per source; an explicit as alias, being a name the author chose, still collides
with any earlier binding of that name at all.

Typing aliases are collected at MODULE scope. The whole-tree walk let an alias
bound inside a function exempt module-level decorators, so a local
import typing as t could excuse @t.overload where module-level t is something
else. Nested statements are still descended into, since try/except around the
import is the conventional spelling; function and class bodies are what get
skipped.

The finding identity now delimits scope from source. Concatenated, a
module-level from A.m import x and a from m import x inside class A both spelled
import:A.m:x, so a branch swapping one for the other had its new finding charged
to the old one's counter and passed.

Source is decoded by its own declared encoding. text=True decoded git show with
the runner's locale, so a valid # coding: cp1252 file holding a non-UTF-8 byte
raised UnicodeDecodeError out of subprocess and took the whole run down, on a
file the parser and compileall both accept. tokenize.detect_encoding is the
parser's own reader for PEP 263, and the direct path now goes through it too so
the two agree.

The changed-file sweep adds T. A path that changes type, a symlink replaced by a
regular .py file, is reported as neither M nor A, so the newly active source
reached the verifier as no path at all and the step passed having checked
nothing.

Run over the whole repo the findings are still 33, unchanged from before this
PR, so none of this widens the gate on code already here.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Scan each branch, each class scope, and each accessor kind

Three more, two of them consequences of the previous commit.

Accessors are exempt PER KIND, not wholesale. Discarding every accessor meant a
getter followed by two copies of the same @value.setter scanned clean, with the
later setter silently replacing the earlier one, which is the merge damage this
gate exists for. Keying on the kind keeps a getter, a setter and a deleter
apart while making two setters collide. @overload stays fully exempt, since any
number of copies there is legitimate, and a bare @Property is still not exempt
at all.

Overload aliases are collected per class scope as well as per module. Skipping
nested scopes fixed the cross-scope leak but left a class that does its own
import typing as t with its @t.overload methods unrecognised, so valid
overloads were reported as duplicates and would block CI. A class now gets the
module's aliases plus any it binds itself.

Control-flow branches are scanned independently. Only direct children of a
module or class body counted, so two copies of one def inside a single
if ENABLED: branch were never looked at, and two identical imports inside one
try body likewise. Each branch is now its own scan, so branches are still never
compared with each other or with the body around them: one definition per
branch of an if/else, and a fallback import in try/except, stay clean.

That last one finds four real duplicates already on main, a repeated
from unsloth import is_bfloat16_supported inside one if __name__ block in four
of the saving tests, so the pre-existing tally goes from 33 to 37 and the
workflow comment now says which four and why they were invisible. They are
pre-existing, so compare mode prints them and blocks nobody.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Start a nested class from the module's overload aliases

A class body is not in the scope chain of a class nested inside it, so an
inner class resolves an unbound decorator name in the module namespace, not
in the enclosing class. Passing the outer class's aliases down exempted
@t.overload in the inner class where t is whatever the module bound, and two
copies of one def scanned clean. Widening the exemption is the direction that
hides merge damage, so start each class from the module-visible aliases and
add only its own bindings.

* Scan match case bodies as independent branches

A match keeps its branches in cases[*].body, which _branch_bodies never
enumerated, so two copies of one def inside a single case scanned clean while
the same shape under an if was reported. The alias walk had the mirror blind
spot: an overload alias bound inside a case went unseen, which would read a
legitimate overload pair as a duplicate.

Sibling cases are still never compared, one definition apiece being the
conditional idiom. Self-test cases are guarded on 3.10, since match is a syntax
error on the 3.9 this tool still supports and would otherwise report a parse
finding. Findings over unsloth, tests, studio and scripts are unchanged at 35.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…wn allowance (#9610)

* studiobench: bound the scroll gesture at both ends, at the extent's own allowance

Two findings on `scroll_travelled`, both accepted during the review of #9439 and left open
there. They are the same mistake in opposite directions: one quantity judged against a
tolerance meant for a different quantity, and one judged against no upper bound at all.

## The extent was allowed 10 percent and then 2

`scroll_extent` grants the extent `EXTENT_TOLERANCE`, 10 percent, because a windowed list
computes its total height from estimated row heights and corrects them as real rows are
measured; it says so in its own comment. `scroll_travelled` then compared the SAME physical
quantity through `_same_number`, which routes through the 2 percent `EXACT_TOLERANCE`. An
arm inside the declared allowance was reported behaviourally BROKEN on `scroll_after`.

A false red is not free here. A broken behavioural invariant removes the cell from
`readings_by_arm`, takes its healthy partner with it through the arm intersection, and
since `unmeasured_planned_cells` learned to consult these gates it can VOID the plan.

It is worse than the report said, and this is the part worth spelling out because it reads
as a subtle one. `bottom` is `scrollHeight - clientHeight` and `_drift` is PROPORTIONAL, so
subtracting a shared viewport height AMPLIFIES the drift by `H / (H - C)`. On the 10,000 px
extent and 800 px viewport measured here that is 1.087. The effective allowance was
therefore TIGHTER than the 2 percent it appeared to be, and the two checks printed two
different percentages for one scrollbar.

So the fix is not a wider tolerance on the same number. The extent is reconstructed from
`viewport_client_height`, which the census has carried beside the scroll height all along,
and then the allowance means exactly what `EXTENT_TOLERANCE` says. `clientHeight` is the
viewport's own height and does not change while the viewport scrolls, so reading it from
the census and `bottom` from the gesture is not mixing two instants of a moving quantity.
Falls back to comparing `bottom` when either arm's census lacks the field, and the detail
names which of the two it compared so the tighter effective allowance is never silent.

`_same_number` is deliberately NOT widened. Its other keys are `selected_chars`,
`visible_chars` and `clipboard_chars`, none of which is an extent, and all of which are
correctly strict at 2 percent.

## The gesture had no ceiling

The predicate was `fraction >= 0.9` and nothing above it, so an arm whose viewport moved
TWICE as far as the gesture asked passed exactly as 1.0 did and the pair returned MATCH.
`travelled` is a sum of `|scrollTop_after - target_before|`, so every pixel above
`commanded` is the viewport being moved by something other than the gesture, which is the
anchor instability this action exists to detect, in the other direction.

The ceiling is DERIVED, which is what was missing when this was deferred: a bound above
needs a number, and a number picked to look symmetric with 0.9 either leaves the hole open
or starts failing correct arms.

Overshoot has one legitimate source, a windowed list correcting estimated row heights, and
a correction moves the offset by the error in the estimate. The total of those errors is
the error in the arm's extent, and this file already declares how far the extent may be
wrong. So the gesture may travel further than it commanded by at most `EXTENT_TOLERANCE` of
the arm's OWN scrollable extent, both terms read off the row rather than assumed: 920 px of
a 9,200 px extent against a 5,880 px gesture, a ceiling of 1.156. No second constant, and
it scales with the rung instead of being another 100K-era figure of the kind this suite
keeps finding. A row carrying no extent gets the lower bound alone and says so in its
detail, because a ceiling of zero would fail every correct arm and a ceiling of infinity is
what is being fixed.

## Tests

`scroll_travelled` had no direct test at all before this. Seven, in
`analysis/selftest/test_studiobench_scroll_bounds.py` -- a new file beside the code rather
than more of the ui-parity command's own suite -- including both controls, because widening
one bound and adding another is exactly where a check quietly stops checking:

- an extent that is a FRACTION of the real one is still BROKEN, which is the failure
  `EXTENT_TOLERANCE` was chosen against: a virtualizer that drops rows instead of sizing
  spacers has a scrollbar that lies
- a gesture snapped back to the bottom is still BROKEN, which is the failure the lower
  bound was written for
- an ordinary estimate correction at 1.1 passes the derived ceiling

Mutation: restore `_same_number` on `bottom` and three fail, including one asserting the
two checks now print the same percentage for one scrollbar; drop the upper bound and the
overshoot test fails with `assert 'match' == 'broken'`.

`pytest tests/studio/studiobench -q`: 1306 passed, up from 1298. `ruff` clean.

Follow-up to #9439, where both were accepted as correct and deliberately not fixed.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten the comments added by the scroll bounds change

* Compare one scroll quantity per arm pair and take the allowance on the extent

* Size the travel ceiling from the pair's reference extent

The overshoot ceiling and scroll_extent read one tolerance off two different
denominators, and disagreed inside it. _drift divides by the LARGER of the two
extents; the ceiling divided by the arm's own. So extents of 10,000 and 9,050
pass scroll_extent at 9.5% drift, while the 950 px estimate correction that
closes that very gap came out BROKEN against a ceiling granting 10% of 9,050:
1.162 travelled against 1.154 allowed.

The arm that most needs the allowance is exactly the arm whose own extent is
the worse yardstick for it. An estimate correction is the arm closing the gap
to the real extent, so the gap is what bounds it, and the pair's reference
extent is the honest basis.

A false red is not free here: it removes the cell from readings_by_arm, takes
its healthy partner with it through the arm intersection, and
unmeasured_planned_cells can then VOID the plan.

This only ever loosens, since max is never below the arm's own extent. An arm
carrying no extent still gets no ceiling rather than borrowing its partner's,
because newly bounding an arm that has always been unbounded above is the one
direction that could invent a red rather than retire one. Both are pinned:
past the reference allowance it is still reported, and the no-extent arm still
prints NO CEILING.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…e the rest of the thread (#9575)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studiobench: drop a superseded resume attempt before deriving UI parity

`skippable_cells` skips a (rung, rep) pair only when every arm of it completed and re-runs
both arms otherwise, so an interrupted run leaves the append-only payload holding a full
base/treatment pair under the dead session and another under the retry's. The scene writes
its action rows before `stream:drain`, so an arm that dies draining has already recorded
every digest it captured, and `collect` read both sessions: one logical repetition became
two comparable observations, the first of them measured off an arm that was on its way down.

That is the shape `derive_unstable` is least able to survive. One differing superseded pair
plus one matching replacement is exactly `min_observations`, so a stable action was marked
unstable at that rung on the strength of a reading the run itself threw away. A real DOM
regression at that rung then printed under "expected to vary" and the parity gate exited 0.

`readings_by_arm` already filters the same rows for the same reason on the timing side and
`floor_table.cell_metrics` gets it for free by keying completed cells on the cell id; this
was the one path left reading both attempts. Filtered per payload file, since a cell id is
reused across shards and superseding has to resolve inside the stream that appended it.

Two repetitions of one rung are still two observations, and an attempt that was never
re-run is still the latest attempt at itself and keeps its verdict.

* studiobench: read a missing fixture axis as its default, and reserve the stop slot's cleanup time

Two holes, both of which let a run report a mixture as one reading.

A RESUME AGAINST A PAYLOAD OLDER THAN THE FIXTURE AXES SKIPPED THE CHECK.
`identity_problems` skips an axis a payload never declared, on the principle
that an axis a row never declared cannot be a difference. That is right for the
axes `run_meta` has always carried, and wrong for `stream_tail_chars` and
`corpus_dollars`: those arrived with the flags that set them, so a payload
written before them could not have run under anything but `None` and `False`.
Absence proves the value there rather than withholding it. So
`--resume --stream-tail-chars 24000` against such a payload was accepted,
skipped every cell it had completed, and recorded the rest under a different
streamed fixture beneath the same cell ids -- one ladder built from two films,
which is what the refusal exists to prevent. Those two axes now normalise to
their historical defaults when absent and the refusal says why an axis the
payload never mentions is a difference; every other axis keeps the skip.

STOP SPENT THE NEXT SLOT'S WINDOW CLEANING UP AFTER ITSELF. `stop_generation`
waits for the cell's own reply to drain rather than truncating it, and the wait
was bounded by the whole of the slot's remaining budget. A reply that drained
at the last moment of the slot therefore left nothing for what follows: 1,280 ms
of fixed waits to fill the composer, let the throwaway turn get going, catch the
chunks in flight and settle the cleanup delete. Slots have absolute starts but
the runner is sequential, so that overrun comes out of the next action's
remaining budget: `stop_generation` closes 300 ms before `scroll_after` opens on
the fast film and 500 ms before it on the quick one, and on the fast film
`scroll_after` has 1,200 ms of budget behind that 300 ms gap. Measured against
the shipped action with a 3,000 ms budget and a drain at 2,900 ms: 4,180 ms
spent, 1,180 ms of it past the deadline. The row `scroll_after` then wrote
blamed the machine for reaching a slot late that this action had been sitting
in. The drain wait now reserves that fixed cost out of the budget it may spend,
and returns `not_run` when the reply has not drained by then, which is the
answer it already gives when the reply does not drain at all.

Both paths are reachable only through `--stream-tail-chars`, which is the
supported way to ask for a reply long enough to still be streaming when the stop
slot opens.

Regression tests drive the shipped functions: the legacy payload is refused
under a non-default fixture and still resumes under the defaults, and
`stop_generation` is run against each film's own stop slot with a clock the
page's waits advance.

* studiobench: release the Studios a failed setup launched, identify an attached treatment by its URL, and report the ladder a resume promised

Three ways a run could come back with a number about something nobody measured.

A FAILED SETUP ABANDONED THE STUDIOS IT HAD ALREADY LAUNCHED. The sides are
acquired one after the other, so in a self-managed A/B the base is installed,
launched and serving before the treatment's clone begins; the cleanup that stops
them both is the `finally` under the cells, which a failure during setup never
reaches. A treatment whose `install.sh` exits non-zero therefore unwound past a
base nothing ever stopped, and the two setup steps that leave by RETURNING --
the health check and the development-build gate -- did the same with both
Studios up. That server is not idle afterwards: `launch_studio` detaches it with
`setsid -f`, so it keeps the 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`). The retry's server exits,
`wait_for_healthz` takes its 200 from the stale process, and that run measures
the build the previous attempt installed while `run_meta` records the ref this
one asked for. Setup now runs under a `finally` that stops every side this run
launched unless it reached the cells; `--keep-studio` still asks for exactly
that leak and still gets it, and an attached Studio is still never touched.

AN ATTACHED TREATMENT WAS IDENTIFIED BY THE LABEL RATHER THAN BY THE SERVER.
`studio_ref` folds an attached base down to `attached:{url}` because the URL is
the only thing the harness can see about it, but 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 `prepare_payload`, skipped every completed treatment cell and exited 0
with B's measurements standing as C's result. `ab_plan` now records the
normalised treatment URL, `requested_identity` asks for it, and the two are
compared on a `treatment_url` axis. Both treatment axes are still skipped when
only one side of the comparison is an A/B, decided from the ref, so an `A0`
payload and a `base`/`treatment` run do not collide and a payload recorded
before this axis existed still resumes.

A RUNG A RESUME ADDED WAS DROPPED FROM THE REPORT. `rungs` is deliberately not
a payload identity axis, so `--resume --rungs 1K,10K` over a finished 1K run is
a legitimate continuation that appends a second `run_meta` promising both.
`recorded_ladder` returned the FIRST header, so a continuation killed after that
header and before the 10K cell reported the 1K ladder it had already finished
and scored COMPLETE -- the crash-beats-limp failure `report/build.py` exists to
refuse, arriving through the front door. It now folds every `run_meta` in the
file: a rung any session promised is owed by the payload, and one it never
reached is scored INCOMPLETE rather than dropped.

Tests drive the shipped functions. `test_studiobench_run_acquisition.py` drives
`run()` itself with the seams that leave the process stubbed at the boundary
they cross -- the installer, the launcher, the health check, the login, the
browser and the cell runner -- so the acquisition loop, the gate, the identity
and the payload under assertion are the real ones. With the source change
reverted and the tests kept, 9 of them fail; with it restored the studiobench
suite is 437 passed. The controls that pass either way: `--keep-studio` still
leaves a failed setup running, an attached Studio is never stopped, a run that
reaches its cells still stops its Studios once and not before, an unchanged
attached A/B still resumes, and a resume that promised no new rung still reports
the same ladder.

Deliberately not changed. The pacer and the browser bundle are not released when
setup fails after they exist: both die with this process, unlike a Studio the
harness detached, and the guard is about the resource that outlives it.
`--report` still exits 0 on an incomplete ladder; the completeness verdict is in
the summary and `--assert-liveness` is the gate for it. Folding the headers of a
legacy payload that predates `archive_payload`, and so holds two runs' headers,
now declares the union of their rungs: more INCOMPLETE, never fewer.

* studiobench: keep the click probe's attribution when the send fails, and put the probe mode on the payload identity

Two review findings on this branch, both real, and both about a reading that
goes missing without anything saying so.

THE PROBE'S NUMBERS LEFT WITH THE CELL THAT DIED. `--click-probe` finishes
inside `_press_send`, and everything after it there -- the `page.fill`, the
send-button lookup and its click -- still runs under the 8s default action
timeout set in `runtime/browser.py`. That is the same default the composer
click needed a 90s bound of its own to survive at 500K, so the step right
after the probe is exactly the one a large rung fails on. The attribution was
assigned on the way out of `_run_inner`, so a cell that died there emitted its
failure row with no trace of the probe at all. Unlike `composer_click_ms` it
has no window row to survive in: it runs before `setup:composer_click` opens,
it is noted on no window, and the cell row was the only copy. It is now filed
from `run`'s `finally`, on both paths, and the field is cleared per cell so a
cell that dies before its own probe cannot inherit the previous one's.

--CLICK-PROBE IS AN IDENTITY AXIS. The flag's own help text says it "makes the
cell's timings incomparable with a cell that did not run it", and a `cell_id`
carries the rung, the arm and the repetition and none of that. So `--resume
--click-probe` against a finished plain payload skipped every completed cell,
appended the remaining rungs measured the other way, and reported the two
halves as one ladder -- the mixed ladder this check exists to refuse, arrived
at through an axis it could not see. `run_meta` now records the mode,
`IDENTITY_AXES` carries it, and its absence from an older payload reads as
false through `HISTORICAL_DEFAULTS`, exactly as `stream_tail_chars` and
`corpus_dollars` do.

Tests: the failure-path preservation is driven through `CellRunner.run` with
the browser stubbed at the boundary it crosses, asserted over the payload the
real recorder wrote, with controls for a cell that never asked for the probe
and for one that dies before its own probe runs. The axis is driven end to end
in `test_studiobench_run_acquisition` over a `run_meta` a real run wrote, with
controls for a resume that keeps the flag and for a plain run that never had
it.

* studiobench: judge a resume on the commit and on the latest attempt, fail a cell whose reply never drained, keep the trace when its cross-check dies, and refuse a port somebody else already holds

Five places where this harness reported a number, a score or an exit code it
had not earned.

A RESUME IS JUDGED ON THE BUILD, NOT ON THE NAME OF THE BUILD. `checkout_ref`
resolves a ref afresh on every install and returns the commit it landed on, and
that return value was discarded, so no payload ever recorded which build
produced its cells. `--branch main --resume` into a payload recorded before
`main` moved therefore passed every identity axis, skipped the completed cells,
measured the rungs still owed on a different build, and `report.assemble_rows`
printed the mixture under one header naming one ref. `main` moves several times
a day and a topic branch under review moves on every push, so this is the
ordinary shape of an interrupted run resumed the next morning, not an unusual
one. `StudioInstall` now carries the resolved commit, `run_meta` and `ab_plan`
record it, and `commit_problems` refuses a resume whose build changed.
Deliberately NOT in `prepare_payload`: that refusal is made before anything is
installed and a commit cannot be known before the fetch that resolves it, so
this check runs once the sides are up and still before the browser, the pacer
and the first cell. An empty commit on either side is not a difference, so a
payload written before this existed and an attached Studio, whose build is not
visible from here, both still resume.

`--resume` READS THE LATEST ATTEMPT, WHICH IS WHAT EVERYTHING ELSE READS.
`_resume_set` read the payload raw and was the last reader in which a superseded
row still counted, and it counted in the direction that skips work. An A/B pair
is re-run whole, so a resume re-runs an arm that had already succeeded; when
that retry failed while its partner succeeded, the payload held a completed row
and a LATER failed row under one deterministic `cell_id`. The next `--resume`
found the old success, skipped the pair and exited 0, while `--report` scored
the failed retry INCOMPLETE and `--assert-liveness` failed on it permanently. It
now reduces through `latest_attempt_rows`, the same helper `score_payload`,
`readings_by_arm`, the parity sweep and `--assert-liveness` already use.

A REPLY THAT NEVER FINISHED IS A FAILED CELL. `_drain_stream` reports rather
than raises, and what it reported was written to `row["stream"]` and read by
nothing: no gate, no report column, no liveness check and no exit code. So 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 its actions and its frame windows scored and paired
into the A/B ratio against an arm that did finish. `_run_inner` now raises,
after the drain reading and the pacer's own counters are on the row, so the rung
scores INCOMPLETE with the evidence for why attached. A reply that ends LATE but
ends is untouched: a slow finish is a finding the cell has to keep, and only a
reply that never ends at all is a failure.

A PORT SOMEBODY ELSE HOLDS IS REFUSED BEFORE THE SPAWN. The cleanup added for a
failed setup cannot reach `--keep-studio`, because retention is exactly what it
asks for. The next run's `unsloth studio -p <port>` then finds one of our own
servers there and aborts rather than binding (`studio/backend/run.py`,
`_resolve_port` with `avoid_own_studio`), or falls back to the next port when
the pid record is not readable. Either way nothing this run launched is on that
port, and everything downstream agrees the launch worked: `_discover_pid` pgreps
`unsloth studio.*-p <port>` and finds the OLD process, `wait_for_healthz` takes
its 200 from it, and `authenticate` reaches it with the bench password a
previous studiobench run rotated it to. The run measures the previous
invocation's build while `run_meta` records the ref this one asked for, and
`stop_studio` then kills the server the caller asked to keep. `launch_studio`
now refuses an occupied port outright.

LOSING THE METRICS PROBE COSTS THE CROSS-CHECK AND NOTHING ELSE, which is what
`start_cell` already says it costs. `Tracing.start` had succeeded by the time
`MetricsWindow.open()` ran, so clearing `self.capture` in that handler abandoned
a live per-browser tracing session: `close()` returned early and never sent
`Tracing.end`, `detach()` had nothing to stop, and every later window's
`Tracing.start` failed with "Tracing has already been started". 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. The capture is now retained and only `self.metrics` is
dropped; `close()` and `_analyse` already guard every use of it.

Left as they are: the two lines over 100 columns in `__main__.py`, which predate
this change.

* studiobench: give the stream-cost injection two origins, an identity, and a stop reserve that was measured

Four things the injection validation and the stop slot were getting wrong.

TWO ARMS ON ONE ORIGIN BOTH BURNED THE INJECTED COST. The injection is a
context init script gated on window.location.origin, and both arms are driven
by one browser context and one page, so the origin is the only discriminator
there is. `--attach U --attach-b U` is a null control `is_null_control`
detects on purpose, and it is the cheapest place to check that the metric can
see a known cost: one Studio, no installs. With the injection on, both arms
burned it, `evaluate_stream_cost_recovery_gate` read
`(injected_rate - base_rate)` as zero, and the gate failed with "the
accumulator is under-attributing" against a metric that was working. Refused
now, before anything is cloned or launched, with the two origins named.

THE INJECTION AMOUNT WAS NOT IN THE RESUME IDENTITY. A cell id carries the
rung, the arm and the repetition, so a treatment cell burning 3 ms per chunk
and one burning nothing are the same id. `--resume` against a FINISHED
uninjected payload therefore skipped every pair, exited 0 having measured
nothing, and left the recovery gate to be answered out of cells that were
never injected; a resume of a half-finished injected run without the flag left
the ladder part injected and part not. Recorded in run_meta and added to
IDENTITY_AXES beside `--stream-tail-chars` and `--corpus-dollars`, with
HISTORICAL_DEFAULTS reading absence as off so older payloads still resume.

A BURST STILL IN FLIGHT AT A WINDOW CLOSE WAS DROPPED. `read()` snapshotted
deltaTaskMs and reset it while the chain the last chunk started was still
open, so the MessageChannel callback charged that burst to a fresh accumulator
that nobody reads: `StreamCostInstrument.close` keeps only overhead_ms from
its tail read, and `open()` resets before the next window in any case. The
burst kept its characters in the denominator and lost its cost from the
numerator. Driving the shipped file in chromium against a real SSE response
read through a fetch reader at field cadence, a driver-side read found a chain
open 10 to 21 times in 2,600 to 5,500 reads, so this is small: a cell opens
about eight windows over its stream. It is still the file's own contract that
a burst is charged once, and a burst charged to nothing breaks it downward.

THE STOP SLOT'S RESERVE WAS SIZED FROM A SHIM WHOSE POLLS WERE FREE.
OWN_TURN_FIXED_MS counted the four sleeps the throwaway turn makes and nothing
else, because the page it was measured against answered in-process and its
clock only moved when wait_for_timeout was called. Driving the same shipped
stop_generation against real chromium and a real clock, the stretch after the
drain costs 1,394 to 1,451 ms on a page that answers instantly and 1,723 to
1,938 ms on one that takes 120 ms to start a turn, 90 ms to stop it and 60 ms
to delete it. Against 1,280 ms reserved, a fast-film sweep of every moment the
reply could drain overran the slot by up to 500 ms with 300 ms before
scroll_after opens, which scroll_after records as a missed slot and blames on
the machine.

Sized from that measurement (OWN_TURN_POLL_MS), and not only sized: the drain
loop tests its deadline at the top, so the iteration that finds the reply
drained has already spent a wait and a round trip past it, and no constant can
pay for time already gone. The action now re-reads the clock before it commits
to a turn it cannot abandon, and bounds the wait for that turn to start by the
slot rather than by a flat 8 s that is 2.7x the whole fast-film budget. The
stop-settle poll and STOP_CLEANUP_JS are deliberately left unbounded: once
Enter is pressed the turn has to be stopped and removed or every later action
measures the scaffolding, and a settle poll cut short would report a stop that
worked as still_running. The same sweep after the change stays 435 ms inside
the slot at its worst.

The stop-slot selftest now charges its shim for every page call and holds it
to a start, stop and delete latency, which puts the post-drain stretch at
1,688 ms against the measured 1,723 to 1,938 and reproduces the old 1,280 ms
exactly when the latency is switched off.

* studiobench: assert liveness before the first table that prints a timing

The loop in CONTRIBUTING-perf.md ran `--assert-liveness` after `floor_table` and
`ui_parity`, under a comment saying it comes before any timing is read. Following
the loop as written, the first thing a contributor sees is a verdict table built
from a payload nothing has checked for missed slots.

That table is not only early, it can be wrong. `paired` matches on the metrics
BOTH arms recorded, so a repetition whose action never reached its slot leaves the
table with no trace except a smaller `n`. A treatment build 10% faster on the three
repetitions it managed, and so slow on the fourth that `message_menu` missed its
slot, prints as

  message_menu.open_close_ms   3   1000.0   900.0   -10.0   0.0   0.3   faster
  1 metric(s) cleared all three gates.

With the fourth repetition's timing present the same run reads +30.0% and VOID
(pairs disagree on sign). `--assert-liveness` exits 1 on that payload either way,
so the only thing deciding whether the contributor sees a clean win or a void is
which command they were told to run first.

The selftest reads the documented loop and fails if any of `floor_table`,
`ui_parity` or `--report` is ordered ahead of the liveness gate, plus the pair of
runs above driven through the real `floor_table.main` and the real
`--assert-liveness`.

* studiobench: compare origins the way a browser does, and take back a throwaway turn the slot gave up on

Three follow-ups to the stream-cost injection guard and the stop slot's own-turn
reserve.

ONE ORIGIN SPELLED TWO WAYS GOT PAST THE INJECTION REFUSAL. `arm_origins`
compared the `--attach` URLs with a trailing slash stripped, and
`window.location.origin` -- which is the only thing `origin_scoped` can
discriminate on -- is the URL standard's canonical origin. Measured in chromium
against real documents, `http://studio:80`, `http://STUDIO`, `HTTP://studio` and
`http://studio/app` all report an origin of `http://studio`, and the shipped
predicate built from any of those four ran on NONE of them. So
`--attach http://studio --attach-b http://studio:80` is one server under two
names: the treatment's injection is gated on an origin no document has and burns
on neither arm, or, spelled the other way round, the base's predicate is the
dead one, the treatment's matches every document and both arms burn. Either way
the difference between the arms is zero and
`evaluate_stream_cost_recovery_gate` reports a working metric as
under-attributing, which is the exact verdict the refusal was added to prevent.
Both halves now read `browser_origin`, so the refusal and the predicate it
protects compare the same thing. `localhost` and `127.0.0.1` stay two origins,
because a browser treats them as two.

A TURN THE SLOT GAVE UP ON WAS LEFT GENERATING. Enter is pressed BEFORE the
turn-start wait, so bounding that wait by the slot does not return from a
decision, it returns from a turn the app has already accepted. Driving the
shipped action against real chromium on a page taking 1,800 ms to start, against
the fast film's 3,000 ms stop slot, it returned `not_run` after 1,759 ms and
handed on a thread with two extra messages in it and a live stream running
through `scroll_after`'s window. That is the scaffolding `STOP_CLEANUP_JS`
exists to remove, reached by giving up instead of by finishing, and every later
action, the final census and the seeded-versus-streamed comparison then measure
it. The wait is split rather than shortened: the slot bounds how long the turn
is worth MEASURING, `TURN_START_TIMEOUT_MS` bounds how long it is worth waiting
for so it can be taken back, and `_reclaim_pending_turn` stops it and deletes
it. It deletes only what it added, because `STOP_CLEANUP_JS` removes the LAST
assistant message and a send the app refused would have it take a seeded reply
instead, so the message count is read before Enter. A refused send still returns
at the slot bound, since nothing was committed there.

THE TURN-START BOUND RESERVED THE SLEEPS AND NOT THE POLLS. A turn starting on
the last millisecond the bound allowed still had the stop-settle poll, the
delete and the driver calls between them ahead of it, and the bound subtracted
`OWN_TURN_FIXED_MS`, which also counts the 80 ms already spent settling the
fill. Measured in chromium with the turn starting at the bound and a 3,000 ms
slot, the stretch after it cost 60 ms past the fixed sleeps on a page that
answers instantly, 227 ms at 90/60 and 424 ms at 200/150; the last of those put
the action 344 ms past its slot against the 300 ms the fast film leaves before
`scroll_after` opens, and it was recorded there as a missed slot.
`OWN_TURN_POLL_MS` is now split at the moment the turn starts and the bound
reserves the part that is still ahead. The same sweep after the fix peaks at
2,912 ms of a 3,000 ms slot.

* studiobench: assert liveness on the null control as well as the result

The loop in CONTRIBUTING-perf.md gated `outputs/mine` and left `outputs/null`
ungated, and the floor comes out of the null control. `floor_table` drops a
reading whose action did not run and `paired` keys on the metrics BOTH arms
recorded, so a null repetition that missed its slot leaves the floor with no
trace either. The repetition a run drops is the one that was slow enough to miss
a budget, which is the noisiest one it had, so the loss is not symmetric: it can
only tighten the bar.

Four null repetitions reading 1.000, 1.002, 0.999 and 1.300 set a 30.1% floor on
`message_menu.open_close_ms`, and a consistent 10% result against it prints

  message_menu.open_close_ms  4  1000.0  900.0  -10.0  1.0  30.1  VOID (under floor)

Lose the fourth to a missed slot and the same three survivors set a 0.3% floor,
and the same result prints `faster` over `1 metric(s) cleared all three gates.`
`--assert-liveness` exits 1 on that null payload and 0 on the result, so the run
the contributor was told to check is the one with nothing wrong with it.

Also the paragraph under the loop, which billed every command but the last for
Studio credentials while `--assert-liveness`, `floor_table` and `ui_parity` all
read a payload off disk.

The selftests read the documented loop for both gates and for their order, and
drive the pair of runs above through the real `floor_table.main` and the real
`--assert-liveness`.

* studiobench: stop the stream detector throwing away the batch a stall hands it

The decode hook read `out.length <= MAX_SSE_CHUNK_CHARS` and skipped anything longer, on the
premise that a decode above 65,536 characters is a bundle or a blob rather than relay traffic.
That premise is false, and it is false in the one case this instrument exists to measure.

A read does not carry one cadence gap of the stream. It carries everything the browser buffered
since the last one, so the size of a read is the arrival rate times the stall in front of it.
Measured against real chromium reading the real pacer through the app's own `getReader()` loop,
the largest read of a stream is 32.5 characters per millisecond of stall at fast cadence, dead
linear from 500 to 3,000 ms: a 2,000 ms stall lands a 65,000 character read and a 3,000 ms stall
a 97,500 character one. The second was well-formed SSE, 470 `data:` frames of the pacer's own
framing, and the guard discarded it whole. It is also the largest task chain of the stream, so
`sseChunks`, `lastSseAt` and the `deltaTaskMs` numerator all lost the worst burst at the moment a
stall makes it worst. Field cadence arrives at 2.97 characters per millisecond and would need a
22 s stall, so this is reachable on `--cadence fast` and not on the default.

How much it cost depends on what the app does per streamed character, because what is dropped is
one chain over a third of the reply. Sweeping that rate with the read loop otherwise identical:
nothing measurable at 0 ms per 1,000 characters, then 46.8% of the numerator at 0.5, 56.1% at 2.0
and 58.2% at 5.0. It gets worse as the build gets slower, because a slower reader falls further
behind and is handed a bigger batch, which is the same shape as the timer attribution above -- a
build getting worse reading cheaper.

The bound now applies to the SCAN and not to the payload. A chunk at or under it is its own head,
so the ordinary path is unchanged and allocates nothing; over it, v8 slices by reference, so the
head costs no walk of the payload either. Both things the cap was for survive: the work stays
bounded by a constant that grows with neither the payload nor the rung, and a blob still has to
put `data:` in its first 65,536 characters to be mistaken for a stream. Measured in v8 at 0.04 us
on an SSE batch and 0.68 us on a 2 MB blob with no frame in it, against 0.70 us unbounded.

Three tests, all driving the shipped `streamcost.js` under node rather than a port of it: the
batch above the bound is counted and its chain charged once, the same batch below the bound still
is, and a 100,000 character blob is still kept out. Reverting only the source leaves the first
failing and the other two passing.

* studiobench: keep every turn's stream stats and fail a cell that under-streamed

send_turn reset the pacer before loading the next turn, and CellRunner records only
pacer.last_stats(), so on a 10K or larger cell 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, which a later turn satisfies on behalf of an
earlier one that did not: an opening reply that disconnected after 4,624 of its 10,000
characters was erased by a follow-up that finished, and the cell was marked complete and
scored against a thread short of the rung it is named for.

Keep the stats for every stream, check each planned turn against them by tag, and raise
when one is missing, unfinished or short, so the cell fails with a named reason on the row
instead of being averaged in.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studiobench: check a healthy multi-turn cell over real wire bytes

The dictated-stream tests cover the failure path. This runs the shipped CellRunner, the
shipped send_turn and a real pacer over a real socket, and asserts the ordinary cell still
completes with every planned turn delivering exactly what it was loaded with.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studiobench: a CI gate that compares the UI before and after a pull request, scored against a concurrent null

Digest the DOM at the merge base and at the head, drive both through one
session, and compare. Scored against a base-vs-base null run in the same wave,
because the declared unstable list is not the measured one: a null control
scored against the declared list reported eleven stable actions differing, and
every one of them would have read as a UI change.

Its own file rather than a job in studiobench-ci.yml, because paths: is
per-workflow and that workflow fires on all of studio/backend/**. The filter
here is derived from what reaches the browser: the frontend src tree, the
served index.html, the two pre-module boot scripts, the frontend lock file, and
the backend modules that mint the picker and settings rows a parity digest
actually captures.

Structure only, never a timing. Two arms run in parallel and a third job scores
them; both arms are liveness-gated first, so a run that compared two pages
nobody drove fails instead of passing.

* studiobench: fail a cell whose follow-up turn was sent but never landed

A send_turn that ran with expect_ok false was skipped when building the list of turns demanded
of the pacer, so a cell whose follow-up never started a reply passed the stream check with
planned_turns 1, completed, and scored 91.6 against a thread one turn short of its rung. The
two kinds of not-run are not the same: ran false means the turn was never attempted and must
not be demanded, while ran true with a failed assertion means the pacer was loaded and nothing
streamed.

Scoped to send_turn deliberately. An action whose own assertion fails already has its timing
voided by scoring.from_payload._action_measure; 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.

* studiobench: compare resolved commits before declaring a null control

The two owned sides are cloned into separate repos and fetched one after the other, with a
whole clone, build and launch between them. A push to the ref inside that window leaves
--branch main --ab main with two different builds under one name, and is_null_control keyed on
the name alone. Measured on a 12 percent regression between two commits: compare voids the run
and empties regressions, and noise_floor_from_null_control republishes the 12 percent as this
machine's noise floor, which would then hide every real effect under 12 percent on it.

The commits are already recorded, and commit_problems already states the rule for --resume: an
empty commit on either side is not a difference. The table now names the builds whenever the
ref alone would mislead.

* studiobench: re-run every pair when an A/B resume has work left

The session filter that drops a lone completed arm drops a whole completed pair for the same
reason, and _render_ab then prints a headline and a verdict over what is left without naming
the missing rungs: an interrupted standard tier whose 10K pair had recorded a 30 percent
regression published IMPROVED 20.0 percent faster off the 100K pair alone, with nothing in
ab.md mentioning 10K.

A note above the table is ruled out by render.py, and declining to publish costs the same wall
clock as re-running while yielding no table, so a comparison with any work left re-runs every
pair in the new session. A finished A/B still skips everything and keeps the table it wrote.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studiobench: find the parity payloads in the artifacts rather than assuming their depth

upload-artifact roots an archive at the least common ancestor of the paths it
was given, so a payload uploaded under outputs/parity-result comes back one
directory deeper. A fixed cp read as a verdict-job bug on a run whose two arms
had both measured cleanly.

The derived-set assertion had the same shape of defect twice: a real payload
spells its rung r100K where the selftests spell it 100K, and the placeholder
action@rung in the tool's own explanatory text matches any pattern loose enough
to cover both. It now matches on an entry that is not that placeholder.

* studiobench: let the parity reporting steps read an exit code before the shell eats it

GitHub runs every run: block under bash -e, and ui_parity exits non-zero as its
normal way of reporting a difference. The three steps that read that exit code
died on it instead, having printed nothing, which reads as a broken verdict job
on a run whose two arms had both measured cleanly.

* studiobench: bound an A/B ratio on a sub-floor arm instead of dropping the pair

Pair.usable required both values to be strictly positive, and time_in_jank_pct and jank_index
are 0.0 on any arm smooth enough to have no over-budget frames. A treatment that introduced 5
percent time-in-jank over a zero-jank base therefore had its pair dropped: the table said no
reading about two arms that had both read, the regression was absent from the per-metric
table, the headline and result.regressions, and as a null control it neither voided nor
reached the noise floor derived from it.

The rule applied is score.py's, which the ladder scorer 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. That yields a bound rather than an infinity or a silence, and two sub-floor arms give
1.0, which is what score.py's comment is about. It keys on has_reading, so a measure that was
never attempted or that failed still contributes nothing, and a zero with no declared floor
stays unusable because nothing bounds it.

A bound is not a spread, so bounded metrics are excluded from noise_floor_from_null_control:
left in, the 50x ratio would publish a 4,900 percent floor and swallow every real effect on
that machine. Such a control has already voided on the same evidence. The table marks a
bounded ratio in the ratio cell rather than in a footnote.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studiobench: a thread that was never yanked back must not void the whole report

The real-path CI session ran every action, passed --assert-liveness, and then could not be
turned into a report at all:

  could not build a report from outputs/studiobench-ci/payload.jsonl: PayloadSchemaError:
  bare zeros found; every zero must be a Measure carrying `attempted`, or an exempted key:
    $.cells[0].scroll_intent.yanked_back_samples = 0

That zero is the GOOD outcome. The user scrolled away seven times and the app left them
there, which is exactly what the reading exists to show, and it made the payload
unrenderable.

`follow` does not have this problem because it carries `follow_attempted` and the walker
covers a block that attests. `scroll_intent` is derived from the same page-side read and
carried nothing, so it now carries the same attestation rather than a new exemption. False
rather than absent when the sampler was never installed: both counters are None there, so
"not measured" stays distinguishable from "measured zero".

* studiobench: audit whether the null control DECIDED, not whether it found something

The guard on the derived unstable set required at least one measured action@rung
entry. derive_unstable records an action only when it DIFFERED, so a null
control in which every action reached its observation count and none of them
differed emits nothing at all -- and that is the best null control obtainable.
The guard therefore failed the job precisely when the runner was quietest and
the measurement was at its best. Nulls measured on these runners produced 11, 9,
10 and 0 stable differences across four consecutive waves, so the zero case had
already been observed.

ui_parity grows --audit-null, which asks whether each (rung, action) is decided
rather than whether any of them differed, and --allow-undecided for an action
the fixture genuinely cannot perform. An empty measured set for the right reason
and an empty one for the wrong reason now read differently, and both are named.

The check moves out of a grep over the tool's own printed prose and into the
tool, where the tests can reach it. That grep had been wrong twice: once on the
rung spelling, once on a placeholder in the explanatory text it was scanning.

* studiobench: settle the keystroke drain on the work and reject an incomplete reading

collect() ran after a fixed 200ms wait, so a keystroke whose paint had not resolved by that
moment was absent from the samples, and the keystroke that has not painted yet is the slowest
one. Measured against the shipped input.js: a 500ms keystroke vanished from a reading whose max
was 20ms, and the action reported success because the only thing it checked was that the
composer 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
drops more of its slowest samples and reads faster, on the highest-weight metric in the table.
It also feeds the null control, so the reading tightens the noise floor every later comparison
on that machine is judged against.

A bigger constant has the same defect on a slower machine or a heavier rung, so the wait ends
when the work ends: input.js exposes settled() and counts every input it saw, the driver polls
until nothing is in flight with a bound only so a wedged renderer cannot eat the slot, and the
reading stands only when samples plus coalesced account for every input and none was left
unpainted. A low sample count is not a failure: on a jammed page most keystrokes coalesce
behind a slow paint, and that is the finding.

* studiobench: an attempt is the last one that wrote, not the last one that finished

latest_attempt_rows keyed the latest attempt on cell rows alone, and CellRunner.run writes that
terminal row in a finally which a SIGKILL never reaches, while the Recorder has already flushed
and fsynced every action and window row before it. A resume hard-killed inside a cell therefore
left the older completed attempt named as the latest, _resume_set skipped it, and combined with
a resume that had already repaired an earlier pair every cell read as complete across two
sessions, so the next --resume ran nothing and exited 0 over a stale table.

Any attempt-keyed row is evidence that an attempt happened. This is the same set the filter
already applies to: a row type that can leak from a superseded attempt is a row type that can
prove a newer one exists. The pair-granularity fix does not cover this, because the defect is
in the done set rather than in how pairs are grouped.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studiobench: scale the watchdog to the planned work and keep credentials alive through a long run

The watchdog deadline was three times the per-tier budget plus an install allowance, and the tier
budget describes ONE walk of the ladder. Three things the caller controls multiply the work under
it: --ab runs every cell twice, --reps N runs the ladder N times, and --rungs can name a ladder the
tier never had. The protocol this tool documents for confirming a result is --tier standard --reps
4, which for an attached A/B is 3 rungs x 4 reps x 2 arms = 24 cells of the 243 second standard
film: 5,832 seconds of film against a 3,600 second deadline, so the watchdog hard-exited a healthy
comparison 40% of the way through, through os._exit, taking the finally that stops the Studios with
it. The measurement half of the deadline is now the larger of the tier budget and the planned work,
both with the same 3x margin, capped at 24 hours. Every documented single-arm ladder keeps exactly
the deadline it had, so the fast tier stays fast.

Studio's access tokens last 60 minutes and the harness authenticated once per arm, at setup, so a
run longer than an hour lost its credentials part way through: the next create_thread answered 401
and the cell died. StudioAuth now re-mints the token by password login before its own exp claim,
and auth_request_json recovers from a 401 that arrives anyway, once, so a clock offset or a Studio
restarted underneath the run is survivable too. Re-login rather than POST /api/auth/refresh: that
endpoint is single use and the refresh token belongs to the page.

The page half of the same defect: seed_init_script wrote the refresh token under
unsloth_refresh_token, which nothing in the frontend reads, so the SPA booted with an access token
and no way to renew it and the first 401 after the hour cleared its tokens and navigated to the
login route, which Playwright reports as "Execution context was destroyed". It is written under
AUTH_REFRESH_TOKEN_KEY now. Because an init script is a snapshot that re-runs on every navigation
and Playwright does not define the order several of them run in, each seed script compares its own
token's exp against the one in storage and writes only if it is carrying the later one.

Tests: a fake Studio issuing six second tokens covers the expiry, the proactive replacement, the
401 recovery, a refused login not being retried as if it were the request, a clock that makes every
token look stale not turning every request into a login, and a failing re-seed hook not failing the
credential; the seed script is run under node in both orders. The watchdog tests cover reps, a rung
override, the cap, and that every tier's own ladder is unchanged.

* studiobench: a declaration belongs to the run that made it, and a floor to the film it was shot on

Two ways ui_parity could pass a comparison it should have refused.

Windowing declarations leaked across globbed runs. collect() already keys every pair
(shard, rung, rep, session, action) and incomplete_cells is read per path, but
declared_windowed pooled its two dicts across all globbed paths on cell_id and arm alone,
and those repeat identically in every shard. A --windowed-arm treatment gate row in one
run therefore became the fallback for an unmeasured pair in an ordinary run beside it,
which was then scored on the visible region and on behavioural invariants and never got
the structural digest it was owed. Reachable on any payload recorded before
mounted_messages existed, since those carry no mount measurement at all and every one of
their pairs takes the fallback. Same payload, opposite verdict, decided by a flag passed
to a different run: exit 1 with the DOM regression named when scored alone, exit 0 with
the structural section never running when globbed beside a windowed one.

A visible floor from another film tier was applied without checking. visible_unstable_set
returns (rung, action) with no tier, main derives it once and hands it straight to
visible_report, and the only tier check is a warning inside the structural loop that the
early return skips entirely on an all-windowed payload. tier_of's own docstring is the
argument: slot spacing decides which actions land inside a live stream and so differ
against themselves. A standard windowed payload floored by a fast null printed zero
visible differences and exited 0 over an arm that really did render copy_markdown
differently in the viewport, with no warning of any kind. The mismatched floor is now
refused rather than tier-keyed, because an unfloored report says what it is missing and a
wrongly floored one does not, and it reuses one_tier so an internally mixed null control
is refused on the visible path too. The guard is inert when both tiers are known and
equal, so the same-tier verdict is unchanged.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studiobench: a superseded attempt's completeness failure must not outlive it

--resume re-runs a cell that did not complete under the SAME cell_id, because make_cell_id
is deterministic, and tells the attempts apart only by session_id. latest_attempt_rows
drops the dead attempt's rows everywhere else, but its ATTEMPT_ROW_TYPES is
{cell, action, window} and a gate is none of those, while incomplete_cells read raw rows
through rows() and keyed on cell_id alone with nothing to clear an entry.

So a payload holding a failed thread_complete from the attempt that died and a passing one
from the retry that worked was read as incomplete forever: collect stamped _incomplete on
the RETRY's action rows and _refused withheld a UI verdict from a cell that had just been
re-measured successfully.

The gate is now scoped to the attempt named by the last cell row for that id, which is the
same rule latest_attempt_rows uses. A gate with no session id is still honoured, for the
reason that function keeps unstamped rows: a payload written before the recorder stamped
them cannot be split into attempts, and ignoring it would lose a real refusal.

This surfaced from the base-branch merge: the superseded-attempt filter and the
completeness stamping were added on opposite sides of it and had never met.

* studiobench: size the frozen corpus from the ladder so the 1M rung streams new material

The 1M rung's seeded prefix consumed the entire frozen manifest, and `plan_rung` clamped
the streamed turn and both follow-ups with `min(index, last_index)`. All three landed on
unit 21, which the prefix had already seeded: the opening stream re-sent text that was
already on screen, the two 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 on the ladder reported the least highlight work per character, and nothing
failed. Measured indices before this change:

  1K    seeded 0    stream 0    follow-ups none
  10K   seeded 3    stream 3    follow-ups 4, 5
  100K  seeded 9    stream 9    follow-ups 10, 11
  500K  seeded 15   stream 15   follow-ups 16, 17
  1M    seeded 22   stream 21   follow-ups 21, 21   (collapsed)

The manifest was sized by a bare `RUNGS["1M"] * 4` character budget, which is exactly the
largest rung's seeded target and therefore has nothing left for the turns that stream past
it. It is now sized from the ladder itself, by `manifest_unit_count`: the longest seeded
prefix any rung can ask for at MANIFEST_CHARS_PER_TOKEN, plus one unit per streamed turn.
The clamp is gone, and running off the end raises, so a larger rung, a larger measured
chars-per-token or another streamed turn stops the run rather than quietly shrinking what
it measures. `check_streamed_units_are_new` states the invariant on every plan, and
test_studiobench_corpus_distinctness.py holds it across the whole ladder, every tier
ladder, ratios from 1.0 to 5.0 and turn counts from 1 to 6.

corpus_hash changes from f8ee037438f3664369dce38be553a4bd79e2b03fdef5fe1457658aded912a4aa
to ac9d5d8e37be2a3844deed559fde6070247ad2322377295fb383b60b5eec5a0c: 29 manifest entries
instead of 22, with units.jsonl byte-identical and no shipped text changed. Anything
measured under the old hash is no longer comparable with runs from this tree, and the
1M-rung numbers under it are void rather than merely incomparable.

1M now streams units 22, 23 and 24. 539 tests pass, up from 530.

* studiobench: write down the content-visibility trap, and the way to prove an arm fired (#9429)

* studiobench: write down the content-visibility trap, and the way to prove an arm fired

Three investigations have now run into the same mechanism and two of them produced a
null that was not a null. This records what each one cost, so the fourth does not
happen.

CONTRIBUTING-perf.md gains one section:

  - How to prove an arm fired. contentvisibilityautostatechange is emitted by Blink's
    relevance machinery and by nothing else, so 193 skipped=true events on the armed
    side against exactly 0 on a control is proof no getComputedStyle read can give.
  - Why the geometry route silently lies. getClientRects() inside a locked subtree
    makes Chromium render it to answer, so the probe unlocks what it came to observe:
    0 unrendered roots reported while the event counter saw 22 in the skipped state.
  - The cascade rule that voids an arm. index.css opens @layer utilities at 1051 and
    closes it at 2572, with the code-block override at 2565-2567. Important rules
    resolve to the earliest layer and unlayered declarations sit in an implicit final
    layer, so an unlayered `auto !important` loses at any specificity while an inline
    one wins, because element-attached styles are checked before layers.
  - Chromium implies contain-intrinsic-size: auto for content-visibility: auto, so a
    plain length does not opt out of the last remembered size.
  - The killer: a message root is mounted before its content, so it remembers a size
    of zero and freezes there. A freshly loaded 100K thread reads 58,355 px of scroll
    height against 11,949 px armed, with the concurrent null at 58,355 against 58,355,
    and UI parity at 0 of 64 pairs matched against 47 for that null. It only heals
    once the whole thread has been scrolled, and static CSS cannot override a
    remembered size.
  - The select-all cost, all three measurements, including that the standard-tier run
    had a wider scatter than its own effect and was voided by gate 3.
  - A correction: the 60.2 against 64.8 figure has circulated as a message-roots null.
    It was the reasoning pane's code blocks, PR 9073, n=1, no floor, and PR 9073's own
    notes had already withdrawn it.

The method is reusable, so the tools come too:

  - arms/content_visibility_probe.js, the working probe, with the geometry route kept
    and labelled as a known false negative rather than deleted for someone to rewrite.
  - two hooks in __main__.py, both unset by default so a scored run is untouched:
    SBENCH_EXTRA_INIT_SCRIPT to install a probe after the scene scripts, and
    SBENCH_PAGE_CONSOLE to read it back. The console is the only way out of the page:
    Studio ships connect-src 'self', so a beacon to a collector port never leaves.
  - a selftest pinning both halves, because a probe with no return path installs,
    samples, and reports nothing, which reads exactly like an arm that did not fire.

* studiobench: make the probe unscorable by gate, and adopt roots before they can skip

Three review findings, all real.

A PROBE RUN WAS ONLY UNSCORABLE BY CONVENTION. The hook printed a warning and the
run then recorded ordinary cells and rendered an ordinary A/B table, so a probe
invocation on the standard tier produced something indistinguishable from a result
and nothing but the caller's memory stopped it being quoted. The init script's path
now goes into run_meta.probe_init_script, the run records a probe_free gate beside
reportable_tier, and floor_table refuses the payload outright with no override, in
the same place it already refuses a mixed tier or a mixed corpus. An absent or null
field is the ordinary scorable case, so payloads written before the field existed
still read.

LISTENERS WERE ATTACHED ON THE SAMPLING TICK. contentvisibilityautostatechange fires
on a CHANGE of state, and a root inserted off screen becomes skipped once and then
never changes again while the user stays put. A seeded thread mounts inside the
first two-second interval, so every root's only event landed before the listener
existed and ev_skip could read zero: exactly the false NOT RUN the probe was written
to prevent. Roots are now adopted at insertion by a MutationObserver installed before
the app boots, over addedNodes only, because a document-wide rescan per mutation
during streaming would make the probe the load it is observing.

THE TWO HEIGHT BUCKETS OVERLAPPED. A root on its declared fallback means no
remembered size exists; a root on its padding alone means one exists and is zero.
They are opposite diagnoses and the blanket height <= 64 test charged both at once
for a user root, whose fallback is 60px against 40px of padding. Per-role thresholds
now test the fallback first and let it win ties, so a root behaving exactly as the
declaration asks is never charged to the trap.

Regression tests for all three, and the doc says what the gate does rather than
promising it in prose.

* studiobench: refuse a probed payload at every scoring entry point, and read every run_meta

Two more review findings, both real, and the first one is the more embarrassing:
the refusal added last round was only in `floor_table`, which is not the table
people read. The session still printed and wrote an `ab.md` at the end, and
`--report` still scored the same file afterwards, hours later, quite possibly for
somebody who was not the one who set the variable.

The detection now lives in the scoring layer as `probe_scripts` / `refuse_if_probed`
and all three entry points call it, so they refuse on one piece of evidence rather
than on three copies of a rule. `_render_ab` writes no table at all rather than a
table under a warning: a warning scrolls off, `ab.md` gets pasted into a pull
request. The payload is still kept, because `--assert-liveness` and the probe's own
output are the two things that run was for.

READING ONLY THE FIRST run_meta WAS WRONG. `--resume` continues an interrupted run
by appending to the existing payload, so a file can carry a clean header and, below
it, a second `run_meta` naming a probe above the cells re-recorded under it. Every
`run_meta` is scanned now, and a failed `probe_free` gate counts on its own, so a
payload from a version that emits only one of the two records is still refused.

Verified against a live probe run at the 100K rung: no `ab.md` is written, the run
prints NO A/B TABLE, `--report` raises, `floor_table` raises, and a clean payload
still scores its four surviving metrics. Regression tests for the resumed payload,
the gate-only payload, the passing gate and the report path.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studiobench: install the page scripts as one ordered script, and never leave a stale ab.md

Two review findings, both correct, and the first one predates any probe.

PLAYWRIGHT DOES NOT DEFINE INIT SCRIPT ORDER. The docs say it outright: "the order
of evaluation of multiple scripts installed via browserContext.addInitScript() and
page.addInitScript() is not defined." Every entry of `init_scripts` was registered
through its own `add_init_script` call, so any dependency between two of them was a
dependency on nothing. That was already load bearing before the probe hook existed,
because surfaces.js reads what dom.js and parity.js put on `window.__sb` and the
comment above it says so. The three scene scripts and the optional probe are now
concatenated into ONE init script, joined on `\n;\n` so a file without a terminator
cannot splice into the next one's opening parenthesis, which makes the sequence a
property of the string instead of an undocumented scheduler. Verified with a clean
run: every scene action ran, 0 scene problems, 0 missed slots, ab.md written.

A REFUSED RUN COULD LEAVE A STALE TABLE. `--resume` reuses the output directory, so
an ab.md from an earlier clean run of the same directory survived the refusal and
sat at the standard artifact path, where it reads as this run's result. The log said
there was no table while the file said otherwise. It is now overwritten with the
refusal rather than deleted, so somebody who opens the path gets the reason instead
of a missing file. Verified by seeding a stale ab.md and running a probe over it.

* studiobench: observe the document itself, and match a fallback height against the border box

Two more, and the second one broke a counter this change exists to defend.

OBSERVING documentElement COULD THROW. An init script is evaluated after the Document
exists but before the page's own scripts run, and at that instant the parser may not
have created the root element. observe(null, ...) throws, the catch swallowed it into
listenerErrors, and adoption fell back to the two-second tick: the exact false zero the
MutationObserver was added to prevent, reintroduced by the fix for it. A Document node
is a valid target and always exists here, so it observes doc.

fallbackBite WAS PINNED AT ZERO. getBoundingClientRect() returns the border box, so a
root sitting on its declared fallback measures the fallback PLUS the root's padding:
318px for an assistant root, 100px for a user one. The comparison looked for 300 and
60, which nothing can ever be, so the counter read zero however the browser behaved and
the probe could not have told an unused remembered size from a remembered size of zero.
Each bucket now has its own target height including padding.

The finding it was meant to support survives, on the raw heights rather than on the
broken counter: at rest the armed thread measures 18px and 40px roots and carries
nothing at 318px or 100px, so no root used the fallback. The doc now says it that way.

Re-run at the 100K rung after both fixes: 266 skipped events armed against 0 on the
control, 25 of 25 roots computing to auto, zero listener errors, paddingOnly 13,
fallbackBite 0, scroll height 56,455 against 9,116.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studiobench: a size bucket only means something while the root is skipping, and detached roots stop counting

ORDINARY GEOMETRY COULD MASQUERADE AS THE FINDING. `content-visibility: auto` computes
to `auto` whether or not the element is currently skipping, and size containment applies
only while it is. An armed root that is on screen therefore carries its normal rendered
height, and a natural height landing within the tolerance of a role target was charged
to the remembered-size trap. The buckets are now gated on the root's own last reported
skip state, which the probe already knows per element.

DETACHED ROOTS WENT ON BEING COUNTED. `thread_reopen` is in the film: it tears the
thread down and builds it again, so watched roots leave the document. A detached root
receives no further transitions, so one whose last event said `skipped` inflated
`skippedNow` for the rest of the session, reporting roots as skipped that were not in
the page. Records are now pruned on the sample that finds them disconnected, counted as
`droppedDetached` rather than dropped silently, which also stops the watch list growing
one strong reference per root for the life of a long run.

Re-run at the 100K rung after both: 217 skipped events armed against 0 on the control,
25 of 25 roots computing to auto, 22 simultaneously skipped, 13 padding-only, 0
fallback-bite, 0 listener errors, and `droppedDetached` reaching 1 on both sides as the
reopen lands. The gate did not suppress the finding, which was the thing to check.

* studiobench: refuse before assembling, and replace a stale summary.md too

`--report` writes summary.md beside the payload and `--resume` reuses the directory,
so a summary from an earlier clean report survived the refusal and sat next to a
now-probed payload, reading as its result. Same failure as the stale ab.md, one
artefact along. It is replaced with the refusal rather than deleted, so opening the
standard path gives the reason.

Two things had to change for that to work at all. The refusal is a SystemExit, which
is not an Exception, so `report_only`'s existing handler never saw it and the process
left before any write. And `build_report` scored AFTER assembling, while
`assemble_rows` validates the payload schema on the way past: a probed payload that
also tripped an unrelated schema complaint reported that complaint and was never
refused. The refusal now runs first, before anything else reads the file. A refusal
that any other failure can pre-empt is not a refusal.

Verified end to end on a real probe payload with a stale summary.md seeded beside it:
the file comes back carrying the refusal and the exit code is 2. `score_payload` keeps
its own check for callers that do not go through `build_report`.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* studiobench: read the probe path in the first second, not after Studio is up

The source is not needed until the browser launches, but reading it there means a path
typo raises after Studio and the pacer are running and before the cleanup finally
around the cell loop is entered, so stop_studio, pacer.stop and watchdog.cancel are all
skipped and a detached Studio keeps running on its port. A typo should not leak a
process.

Read once, at the top of the run, where a missing, unreadable or non-UTF-8 file can be
reported while there is nothing to clean up, and passed through to the point of use so
there is no second read to reintroduce the window.

  FATAL: SBENCH_EXTRA_INIT_SCRIPT=/does/not/exist.js could not be read:
  FileNotFoundError: [Errno 2] No such file or directory

printed before the first attach. A real probe run afterwards is unchanged: 217 skipped
events armed against 0 on the control, 25 of 25 roots computing to auto, 0 listener
errors, the extra-init line and the A/B refusal both present.

* studiobench: spell out the probe run's credentials instead of trailing off

The probe's header example ended in an ellipsis, which is exactly the shape that makes
the documented path unrunnable: a probe run drives a real Studio like every other
command in the loop, and without --password it dies on an HTTP 401 after the browser
has already started. The flags are written out now, and the trap entry points at the
README section that explains them rather than restating it.

* studiobench: a malformed probe must not take the scene scripts with it

Concatenating the page scripts bought an ordering guarantee Playwright does not give,
and sold a worse one in exchange. The browser parses the joined text as ONE unit, so a
single syntax error anywhere in the external file meant dom.js, parity.js and
surfaces.js never executed either. The run then had no window.__sb at all, and the
silence read exactly like a probe that never fired, which is the failure this whole
arrangement exists to prevent. Reading the file as UTF-8 does not catch it.

The source is embedded as a string and evaluated at runtime through indirect eval, so
it still evaluates in global scope and still runs after the scene scripts, both because
it is later in the same unit, but its parse is its own. A malformed probe now degrades
to a caught SyntaxError in…
… report (#8877)

* Studio: include the backend session log in the support diagnostics report

The Python backend aims faulthandler at ~/.unsloth/studio/logs/server/, so a
native abort in the GPU runtime writes its stack there and in no other file
Studio keeps. The report collected tauri.log and the phase logs but never that
directory, so a hard crash arrived as an exit code with nothing about the call
that died.

Tail the two newest server-*.log alongside the existing sections. Their budget is
smaller than the other tails on purpose: enforce_report_limit chops the end of
the body, so bytes spent here would come out of the phase logs, and a faulthandler
dump is a few KB at the end of the file, which is the half read_tail returns.

* Studio: reject entries that cannot be tailed before they spend a session-log slot

Only two backend session logs are collected, so an entry that matches
server-*.log by name but cannot be read has to be rejected during selection.
Rejecting it later in read_tail still costs a slot, and the slot it costs is
the one holding the faulthandler stack the report exists to carry. This is the
same reason scan_phase_logs_in_dir screens symlinks inline rather than at read
time.

Three cases, verified on Linux against the pre-change code:

- A FIFO. File::open on one blocks until a writer appears, and read_tail runs
  on the blocking pool behind collect_support_diagnostics, so this wedged a
  thread and the support report never returned. Measured: still blocked past
  5s. This is the one that matters, because it fails at the moment the user is
  already trying to report a crash.
- A directory. Reads back as EISDIR on Unix and ERROR_ACCESS_DENIED on
  Windows, so it degraded gracefully, but two of them took both slots and the
  real crash log did not make the report.
- A symlink. Same outcome, with read_tail's existing refusal noted only after
  the log it displaced was already gone.

Also:

- Say which directory was searched when there is nothing to collect. A backend
  the app adopted rather than spawned can resolve its own studio root from
  sys.prefix (utils/paths/storage_roots.py _infer_studio_home_from_venv), which
  the UNSLOTH_STUDIO_HOME scrub in process.rs cannot reach, so a bare
  "unavailable" cannot be told apart from "the backend logs somewhere else".
- Report a read_dir failure that is not NotFound. A missing directory is the
  ordinary case for an install that has never started a backend and stays
  silent; a permission wall did not.
- Skip a name carrying a control character or a backtick. The report is line
  oriented and fences tails with ```text, and both the header and the path are
  printed verbatim, so such a name forged key=value lines in the body.
- Correct the footer bounds line, which still advertised 1000 lines/200KiB for
  sections that are capped at 400/64KiB.
- Note in the tie-break comment that pidN is not zero padded, so the filename
  tiebreak is stable but not chronological.

Tests: one per rejected entry type, the FIFO one on a deadline since a
regression there hangs the suite rather than failing it; an ordering test whose
mtimes and filenames disagree, so it can only pass on mtime; and the budget
assertion tightened from 128KiB to 80KiB, which a mutation to 100KiB had been
slipping through.

cargo test --locked --no-fail-fast --bins: 372 passed. Each new assertion
mutation checked. cargo fmt --check is clean on this file.

* Studio: tighten the comments in the diagnostics session-log collector

Comment-only. Same prose, fewer lines: 65 comment lines down to 50, with the
code byte-identical after stripping comments.

* Studio: assert the crash stack survives whole-report truncation

The smaller cap on the backend session sections only makes sense because the
section sits above the phase logs and enforce_report_limit chops the END of the
body. Nothing asserted that placement, so a section moved below the phase logs
would still pass every existing test while quietly dropping the stack out of any
report that overflows the 1MiB clipboard budget.

Measured on the fixture: 1320788 bytes in, 1048576 out, stack retained.

* Studio: final comment pass on the session-log collector

Comment-only, one block. The opening pass covered the same code an hour earlier,
so there was little left: code is byte-identical with comments stripped.

* Studio: drop a session log we cannot open before it spends a slot

`entry.metadata()` is `stat`, which POSIX specifies needs no permission on the
file itself, only search permission on the path prefix. So a `server-*.log` the
desktop user cannot open passed every check in the selection loop, took one of
the two slots, and `read_tail` only reported the permission error afterwards,
by which time the readable crash log was already out of the report.

Reproduced before the fix: two mode-000 logs newer than a readable one took both
slots and the report carried no stack, only two `unavailable=Permission denied`
lines. Not hypothetical either way round: a backend once started under sudo, or
under a umask that strips the owner read bit, leaves exactly this behind.

Probing with `File::open` is safe at this point in the loop specifically because
the regular-file check runs first, so the probe can never be the FIFO whose open
blocks.

Regression test asserts the readable log wins and both rejections are reported;
removing the probe fails it. cargo test --locked --no-fail-fast --bins: 452 passed.

* Studio: let the unreadable-log test skip where mode 000 denies nobody

Mode 000 does not deny root, or anyone holding CAP_DAC_OVERRIDE, so in a
root-based container the fixture cannot express its own precondition: both
locked files stay readable candidates and the assertions report the environment
rather than a defect.

Probe the fixture instead of testing the uid, since the capability can be held
without being root. Same reasoning as
studio/backend/tests/test_recommended_folders_permission.py, which skips itself
under root for exactly this.

Verified both directions: with the fixture left readable the test skips instead
of failing, and with the product-side File::open probe removed it still fails as
an unprivileged user, so the guard does not neuter the regression it exists for.
cargo test --locked --no-fail-fast --bins: 452 passed.

---------

Co-authored-by: Daniel Han <[email protected]>
* studiobench: refuse a streamed tail the corpus cannot deliver

`--stream-tail-chars N` is the only way to vary reply length in this tool, and it
silently under-delivered. The tail is one corpus unit and `clipped_to` returns the
unit unchanged when the ask exceeds it, so delivery is capped at that unit's size.
Asking for more tail lowers that cap rather than raising it: a bigger tail shrinks
`seed_target`, which moves the streamed turn to a lower index, and the corpus
escalates in size.

Measured at 100K with a 400,000 character request: 15,405 characters streamed
(3.9%) on a thread of 18,122 against the rung's 397,755 (4.6%), still carrying the
`r100K` cell id that scoring and the report use as the rung key. `--assert-liveness`
returned 0 scene problems, 0 missed slots, exit 0, byte-identical to the default
run, because a saturated tail drains faster than the film it was meant to outlast.

The guard keys on `clipped_to`'s own early return rather than on a percentage,
because the two ways a tail lands under budget differ in kind: block-boundary
clipping loses at most one block and keeps a prefix from ending inside a fence,
while exceeding the unit is unbounded. The default ladder is untouched.

The existing reply-axis test asserts the right property at the 100K rung with
24,000 and 96,000 only. Across the ladder, 10 of 15 pairs failed its own two
assertions; it covered exactly the 2 that passed. The new test is the matrix.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
)

* Studio: put the notification rail back in its bottom-right corner

The rail was anchored with `fixed bottom-4 right-4` until #8082, which added
the loaded models indicator and, with it, a frame store the rail read: the
Live monitor, the API monitor panel and the chat composer publish their boxes,
and `useStackGeometry` wrote `bottom` and `maxHeight` as inline styles that
dodged them.

Every input to that placement moves on its own. The composer grows with its
input and goes from centred to docked with no resize event, a download row
arrives, release notes expand, a banner is dismissed. Each change re-ran the
measurement, and when the room fell short the rail lifted over the obstacle at
`viewportHeight - frame.top + STACK_GAP`. On the welcome chat that is the cards
in the middle of the window; against a maximised monitor the lift clamped at
MIN_STACK_ROOM and parked them at the top. It reads as random because the
trigger is measurement timing.

The store also had to probe its own output, dropping `max-height` to read
`scrollHeight` and restoring it with transitions suppressed, because the
placement was feeding on the box it had just sized. It went from 184 lines to
701 over nine follow-up PRs, all of them editing the same arithmetic.

So this restores the anchor rather than adding another special case. The rail
is `fixed bottom-4 right-4` with the CSS cap again, on the named layer rather
than the old hard-coded z-index. The frame store keeps its map of boxes, which
api-monitor/panel-placement still needs to open the API panel clear of the
monitor and the composer, and loses the dodge arithmetic, the measurement loop
and the `coverable` licence. The composer still publishes for that panel's
sake. The indicator itself is untouched.

Known trade-off, and the pre-#8082 behaviour: in a short window a card can sit
over the composer's Send button rather than the rail dodging it. The indicator
is off by default, draggable and dismissible.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: scroll the rail at its cap instead of spilling cards off screen

Review catch, and it reproduces. The cap alone does not contain anything: the
cards that cannot shrink lay out past the rail's bottom edge, which is pinned
16px off the floor, so the overflow goes under the bottom of the window with
no way to bring it back.

At 320x480 with --ui-font-scale 1.25, three cards up: the llama.cpp banner is
in flow with its bottom at 497 against a 480px viewport, and the card after it
is squeezed to 0px at 505. scrollHeight 501 against clientHeight 448, and
overflow-y visible. The Update button is below the fold for good.

Earlier sizes missed it because the download panel is the one min-h-0 card in
the rail and absorbed the squeeze on its own. Raising the type size puts the
two banner floors over the cap and the slack runs out.

So the rail scrolls again, in CSS only. No measurement, no placement: the
offset and the cap stay where they were. The gutter comes back with it, since
overflow-y forces overflow-x and the card shadows clip without it, and stays
horizontal so the bottom card keeps sitting on bottom-4.

The rail stays click-through. Verified that the fold is still reachable:
elementFromPoint over a card returns a node inside it, so the card is the hit
target despite the rail being pointer-events-none, and the rail is that node's
nearest scrollable ancestor, which is the chain a wheel scrolls. Focus works
too: the Update button measured at bottom 481 in a 480px viewport, and
focusing it scrolled the rail to 17 and brought it to 464.

* Studio: measure the rail's corner off a card, and drop the stale pointer contract

Two fixes to the Playwright suite, both mine to begin with.

The corner check measured `fromRight` off the rail's border box. The rail
carries the shadow gutter, `-mx-3 px-3`, so its border box sits 4px from the
viewport edge while the cards it pads sit at 16. It reported 4 and would have
failed at every inspected viewport. Measured at 320x480 and at 921x534, one of
the two the pass runs: rail 4, every in-flow card 16. It now takes the right
edge from the cards, filtered to the ones in flow, since a dragged loaded
models card is `fixed` somewhere else. The bottom still comes off the rail:
no vertical margin or padding, and its border box does not move when the cards
scroll. Checked at both scroll extremes.

The other is a contract this branch already invalidated. The suite asserted the
rail takes pointer input exactly when it scrolls, which was #9150 and needed the
JS that also placed it. The rail is click-through in every state now, so that
check failed whenever the rail scrolled. Verified at 320x480 with the rail
actually scrolling, scrollHeight 501 against clientHeight 448: pointer-events
none, and a click on the gutter lands on the thread viewport behind it. Both
assertions are now unconditional.

* CI: drop the install and the artifact dir the deleted rail harness owned

The vite install in the banner shard exists for playwright_overlay_rail.py and
nothing else, so with the harness gone it is dead. Nothing left in
studio-ui-smoke.yml touches npm, npx, node_modules or studio/frontend, so on a
frontend-dist cache hit it would run a clean `npm ci` for no consumer.

logs/playwright-overlay-rail goes with it: it was only ever written by the two
steps this branch removed.

Job-level setup-node stays. It predates the harness (#9060) and the installer
needs node to build the frontend on a cache miss.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…file cannot be written (#9269)

---------

Co-authored-by: oobabooga <[email protected]>
…ents (#9662)

tests/sh/test_install_host_defaults.sh sliced install.sh, install.ps1 and
studio/setup.sh on hand-written markers, two of which were comment prose. A
comment exists to be rewritten, so this guard went red twice for reasons that
had nothing to do with host defaults, and three of the four windows ran to end
of file, so each negative assertion covered more than its label claimed.

The launcher window was worse than fragile: it could go vacuous. It found its
start with an awk pattern and its terminator with a separate, stricter grep that
also required the << on the same line. Wrap that redirect across a line
continuation and the grep matches nothing, the derived delimiter is the empty
string, and $0 == delim then matches the first blank line inside the heredoc.
The window collapses from 357 lines to 6, the shebang canary sits inside those 6
and still passes, and a -H 0.0.0.0 on the launcher's own exec line reports 39
pass / 0 fail.

Each window is now cut from the file's own structure: the heredoc's own
delimiter, read off the same matched line that opens it; the top-level if that
declares the post-install branch; the PowerShell brace block. Every one asserts
it closed on its own closing token, so a close that never matched is a report
rather than a silent run to end of file. studio/setup.sh is read whole and
labelled as such, because its footer header opens three different top-level
blocks and no structural boundary picks out the right one. Two whole-file
backstops catch a wildcard bind that lands outside every window.

39 pass / 0 fail before, 45 pass / 0 fail after.
…-GPU device map (#8968)

* Keep the real quantization skip list on save, and add an opt-in multi-GPU device map

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Resolve device_map = "unsloth" on the diffusion path, pin the vision planner revision

Two leaks in the opt-in device map.

FastModel dispatches diffusion models before FastBaseModel runs, so "unsloth" reached
transformers unresolved, which turns an unknown device_map string into
torch.device("unsloth") and raises. FastDiffusionModel now resolves it at the leaf, the
same place llama.py and vision.py do, and _dispatch_diffusion forwards
device_map_planner_kwargs, which is a named parameter and so never appeared in **kwargs.

vision.py planned against the default branch while the load used _revision. A plan sized
from a different revision either under-budgets or names modules the checkpoint does not
have, and accelerate raises on the missing devices rather than warning.

tests/test_unsloth_device_map_leaks.py pins that every leaf loader resolves before it
loads and that each planner call gets the same ref as the weights.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Plan the device map for the quantization the load will really apply

loader.py clears load_in_4bit and load_in_8bit whenever the caller passes a
quantization_config, since transformers refuses both at once. The leaf loaders were
handing those cleared flags to the planner, so a full-precision checkpoint about to be
quantized got sized at bf16. The planner refuses to spill a bitsandbytes model to CPU
and raises DeviceMapInfeasible rather than falling back, so a 70B QLoRA that fits on
two cards failed outright.

The skip list has to travel with them. On-the-fly quantization always keeps
SKIP_QUANTIZATION_MODULES in compute dtype and transformers reads that as
modules_to_not_convert, so planning lm_head and a whole vision_tower at 4bit understates
the head device by GiBs. That is the one number the head-aware plan exists to get right.
A pre-quantized checkpoint is unaffected: its own config.json carries the list.

planner_quantization_kwargs in loader_utils.py builds the right inputs for both leaves.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Size the device map for the dtype and quant config the load will really use

from_pretrained's dtype overrides whatever config.json declares, but the planner only
ever saw the config, so any load that changed dtype was sized wrong by a factor of two.
A float32 load of a bfloat16 checkpoint got an accepted map that OOMs while
materializing, and the default bfloat16 load of a float32 checkpoint raised
DeviceMapInfeasible on a load that fits. All three leaves now pass the dtype the load
is given. In vision.py that means resolving the forced-float32 case before the plan
rather than at the load, so both use one value.

diffusion.py was still handing the planner the bare flags. Its BitsAndBytesConfig skips
lm_head, embed_tokens, experts, self_conditioning and router, and transformers turns
that into modules_to_not_convert, so every skipped module was budgeted at 4 bits while
it materializes in compute dtype. For a MoE checkpoint the experts are most of the
weights. The config is now built before the plan and the load reuses that same object.

Passing the real config rather than a generic skip list matters for the 8bit branch,
which deliberately has no skip list; injecting one there would over-size and could
refuse a load that fits.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Do not plan a device map when the load builds a different model than the repo config

The planner only receives model_name and rebuilds the repo's own config, so any load
that overrides that config gets a map for a module tree it will not have.

text_only is the reachable case. It swaps in the text sub-config and loads the decoder
alone, so the plan describes the whole VLM and names model.language_model.layers.N while
the load creates model.layers.N. On a Gemma 3 4B that is 444 of 445 weights arriving with
no device, and transformers raises "doesn't have any device set" mid-load. Transformers
4.57 no longer pre-flights the map through accelerate's check_device_map, so there is no
friendly error first.

num_labels is the same failure from the other side: the load builds a sequence
classification head whose score replaces the lm_head the plan named, and accelerate
refuses the map for giving score.weight no device.

Both now decline planning and fall back to sequential, matching how the resolver already
handles vLLM, full finetuning and distributed launches. Passing the effective config to
the planner is not an option: plan_device_map_for_pretrained takes only a repo name and
builds the config itself.

The class comparison is on model classes rather than auto classes, since
AutoModelForVision2Seq and AutoModelForImageTextToText are distinct objects that resolve
to the same VLM. It fails open: an unknown class vetoes nothing.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Decline planning on the optimized path too when num_labels loads a task head

Last commit vetoed a class-divergent plan in vision.py, but loader.py only delegates to
FastModel for 8bit, full finetuning and QAT. A num_labels load of a llama, mistral, gemma,
gemma2, qwen2 or qwen3 repo stays on the optimized path, where the planner sized the
repo's causal LM and the load then built AutoModelForSequenceClassification. That model
has a score head and no lm_head, so accelerate's dispatch_model refuses the map with
"does not give any device for the following parameters: score.weight".

The veto does not fail open here, unlike the vision path. A num_labels load is a
classification load by construction and the planner's own class resolution can never
produce a sequence classification class, so an unknown class still declines.

* Decline the unsloth device map in FastSentenceTransformer

FastSentenceTransformer takes its own device_map and forwards it to FastModel, which
resolves the sentinel on its own copy. But it also derives the SentenceTransformer device
from the unresolved variable in three places, and those only normalize a dict, "auto" and
"sequential", so "unsloth" reached SentenceTransformer(device = ...) and its self.to()
raised: Expected one of cpu, cuda, ... device type at start of device string: unsloth.

Adding the sentinel to those three lists would be worse than the crash. SentenceTransformer
moves the assembled model onto one device, so a planned split map would be silently pulled
back onto card 0. Declining once at the top matches how the resolver already handles vLLM,
full finetuning and distributed launches.

test_unsloth_device_map_leaks.py named this invariant already but only covered llama,
vision and diffusion.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Make the SentenceTransformer decline survive UNSLOTH_AUTO_DEVICE_MAP

The decline added in the previous commit read the raw argument, but FastModel runs
requested_device_map unconditionally, and that upgrades exactly the "sequential" the
SentenceTransformer path hands it. So with UNSLOTH_AUTO_DEVICE_MAP=1 the model was still
planned across cards while st_device below read "sequential", and encode() then pulled the
split model onto one card. That is the silent consolidation the previous commit set out to
avoid, and it happened even when the caller explicitly asked for the sentinel and was
explicitly declined.

The decline now resolves the env var too, and the switch is pinned off for the load and
restored in the same finally that already restores UNSLOTH_WARN_UNINITIALIZED.

Only the training path was affected; the for_inference branch returns before this and
never re-enters FastModel.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten comments and docstrings in the device map planning path

Shorten the explanatory comments added by this PR without dropping the reasons
they record, and correct planner_model_class's docstring: it answers for the
config it is given, which on both call sites is the user's config when one was
supplied, while the planner rebuilds the repo config from model_name.

* Set the auto-map pin inside the try that restores it

The pin was assigned before the try block, but the distilbert and mpnet patch helpers
run in between and can raise. That would leave UNSLOTH_AUTO_DEVICE_MAP=0 in the process
environment with nothing to restore it, silently disabling the opt-in for every later
load rather than just this one.

* Read the logit transforms from one place instead of four (#8997)

* Read the logit transforms from one place instead of four

The GRPO path and the causal LM forward each re-derived which field carries the
model's logit scale: cohere multiplies by logit_scale, granite divides by
logits_scaling, falcon_h1 multiplies by lm_head_multiplier. unsloth_zoo's
device map planner now derives the same three values to size the head's card,
so both read them from detect_logit_transforms and a new architecture is taught
once rather than twice.

Verified equivalent on cohere, granite (explicit and default logits_scaling),
falcon_h1, llama and gemma2: identical softcapping and scaling in every case.

Guarded so an older unsloth_zoo without the helper keeps the previous inline
derivation. ImportError is the right scope here: it means the symbol is missing
from an older zoo, and a broader catch would hide a genuinely broken install
that the unguarded unsloth_zoo imports above would have failed on anyway.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Give the generated GRPO module the transform helper it calls

inspect.getsource inlines the patched function bodies but not this file's
imports, so detect_logit_transforms was never bound in the generated
UnslothGRPOTrainer module and every GRPO run raised NameError on the first
old_per_token_logps computation. Add the guarded import to RL_PRE_ITEMS
alongside the other constants the inlined functions reference.

Also read the transforms from the same place in grpo_trainer_compute_loss.
The old and reference logps come from _get_per_token_logps_and_entropies and
the gradient logps from here, so reading them two different ways makes the
importance ratio compare two different policies. On Falcon-H1, whose
lm_head_multiplier only the helper knows about, the ratio lands on the
epsilon clip for every token.

* Hand the transform helper the unwrapped config, not the model

detect_logit_transforms only does getattr(x, "config", x), and a DDP or
Accelerate wrapper never forwards .config, so passing the bare model made it
read the wrapper and report no transforms at all. That is the same trap
_unsloth_get_model_config was added to close in #5955, except silent this
time: multi-GPU GRPO on Gemma 2 quietly lost its 30.0 softcapping, and Cohere
and Granite lost their scaling, in both the reference and the gradient path.

The existing guard test only grepped for the old string, which survives in the
fallback branch, so it kept passing. Give it a behavioural case instead.

* Stop the DDP transform test from pinning the zoo's internals

The behavioural case asserted that the helper reports nothing for a bare DDP
wrapper. That was true of the helper as it stood, but unsloth-zoo#1067 now
unwraps .module and ._orig_mod itself, so the assertion would fail the moment
that lands. Neither behaviour is wrong and this test has no business deciding
which one the zoo picks.

Assert the invariant that holds either way instead: the config the call sites
resolve is the one the transforms come back from. Verified passing against both
the current released helper and the #1067 version.

* Pin the per-family logit transforms the GRPO path applies

The loss recomputes log-probs from hidden states, so it has to reproduce what
each family's forward does to its logits. A wrong factor there does not raise,
it just shifts every log-prob and the importance ratio built from them.

unsloth-zoo owns the field names; this owns the expected values, so a change in
the helper's coverage arrives as a diff to read rather than a quiet numerics
shift. Covers the four stable families plus the three the helper has just
rebucketed, each recording what the path used to apply.

* Tighten the comments on the logit transform path

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Do not let a card that cannot report its memory fail the load

resolve_unsloth_device_map read free memory outside the try that guards the
plan, so a device that refuses to initialise took the whole load down instead
of falling back to the placement the caller would have had anyway. mem_get_info
opens a context on every visible card, and an ECC-fenced GPU, a MIG parent
handle or one held in Exclusive_Process mode raises there. device_count() is
wrapped for the same reason, one call earlier.

planner_quantization_kwargs imported the shared skip list unguarded, and the
leaf loaders build these arguments on every quantized load whether or not
anything will be planned, so on an unsloth_zoo below our pin that import was a
4bit load turning into an ImportError. It now degrades to no skip list, which
is only reached where the planner itself is going to decline.

tests/test_unsloth_device_map_platform_matrix.py states the three properties
that make the opt-in safe as the whole product rather than one path each:
4 hosts x 5 accelerators x 4 GPU counts x 14 placements returned untouched,
the sentinel never escaping to transformers under any combination of launcher
and flags, and the planner running exactly where a plan can apply.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Pin Studio's placement against the loader opt-in

Studio never passes the planning sentinel, but an operator can set
UNSLOTH_AUTO_DEVICE_MAP=1 process-wide, and Studio's "sequential" is not a
default it forgot to change: get_device_map() returns it to mean one device.
Two facts keep that safe, and neither was written down anywhere. Its multi-GPU
answer is "balanced", which the opt-in does not touch, and its single-GPU
answer is only reached inside a worker that already narrowed the visible
devices to the selection, so the planner counts one GPU and declines.

Asserted over the 7 hardware profiles already in this file (NVIDIA, ROCm, XPU,
Apple with and without MLX, arm64 Linux, CPU) x 5 GPU selections x the opt-in
unset, 0 and 1: whatever Studio decided is what the loader hands transformers.

In this file rather than a new one because it runs in the isolated pytest
invocation -- the spoofs here mutate hardware.py module globals.

* Take three review findings on the opt-in device map

max_memory is a named parameter of the planner, so a caller who put their own in
device_map_planner_kwargs -- reserving room for another workload -- made the call
raise TypeError: got multiple values for keyword argument 'max_memory'. The
handler around it turned that into a silent "sequential", losing both the cap
they asked for and the plan. Theirs is now taken per device and kept under what
is actually free, read with accelerate's own parser so "10GiB" means here what it
means at the load. A caller can reserve memory we cannot measure; they cannot
conjure memory the card has not got, and planning above free is how a plan OOMs
on dispatch.

UNSLOTH_AUTO_DEVICE_MAP upgraded every "sequential", including one the caller
typed out, because the default and an explicit request are the same string. The
default now carries that distinction in its type: a str subclass that equals,
formats, hashes and serialises as "sequential", so transformers and
inspect.signature see exactly what they saw before, while the env var can tell
which one nobody chose. A caller who names accelerate's greedy sequential fill
keeps it.

That also retires the process-wide pin in sentence_transformer.py. It existed
only because the nested FastModel load could re-upgrade the "sequential" the
decline had just produced; handing that call a plain str settles it locally.
os.environ is shared, so the pin was visible to unrelated loads on other threads,
and two overlapping sentence loads could restore it out of order.

A legacy diffusion_gemma checkpoint loads only because _load_diffusion_config
catches AutoConfig's unknown-model error and rewrites the type in memory. The
planner takes a name, not a config, so it rebuilt the original and hit the same
error, reported as a generic planning failure on a route this branch had just
added support for. It now declines with that reason named.

tests/test_unsloth_device_map_review_fixes.py covers all four; 14 of its 15 fail
on the code as reviewed. The three ast harnesses learn the marker, and the two
assertions that encoded "any sequential upgrades" now state the corrected rule.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read the max_memory cap without needing accelerate importable

The cross-platform run caught this: _as_bytes parsed the caller's budget through
accelerate.utils.modeling.convert_file_size_to_int inside a try/except, so on a
machine without accelerate installed every budget read as unparseable and the cap
was dropped in silence, leaving the measured free memory in its place. That is the
same silent loss the max_memory fix exists to close, and it runs while placement is
still being decided, before anything has established that accelerate is present.

Reproduce accelerate's spelling rules locally instead, and keep the copy in step
with the original with a parametrized agreement test that skips where accelerate is
not installed.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Honour the caller's device set, explicit ST maps, and the prequantized skip list

Three from review:

max_memory now replaces the measured budget rather than overlaying onto it. The
keys of a mapping the caller wrote are the devices they will let the load use --
accelerate's _init_infer_auto_device_map takes devices = list(max_memory.keys())
and get_max_memory never widens a supplied mapping -- so {0: ..., 1: ...} on a
four-GPU host was leaving the planner free to place weights on the two cards they
had reserved for another workload. Devices we cannot measure (cpu, disk) survive.

FastSentenceTransformer stripped the default's marker with str(), which also
turned an explicit dict placement into the text "{'': 0, 'model': 1}".
unmarked_device_map touches the marker and nothing else.

llama.py declines to plan a prequantized bitsandbytes checkpoint of a mamba hybrid
whose bundled skip list lacks the exclusions the load adds. merge_quantization_configs
overlays loading attributes for GPTQ/AWQ/AutoRound/FbgemmFp8/CompressedTensors/Mxfp4
and never for bitsandbytes, so such a checkpoint is always sized by the list in its
own config.json and no argument here can correct it; the mamba stacks are GiBs of
error. The other unbundled entries reachable on this loader are MoE routers, which
top out near 70 MiB on Qwen3-235B-A22B, inside the planner's 256 MiB safety margin.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten the comments added by this PR

Comment and docstring text only, AST-verified against HEAD. Also drops a stale copy
of the max_memory rationale in loader_utils that the earlier fix left behind above
its replacement.

* Probe only the GPUs the caller left in max_memory

mem_get_info was called for every visible device before the caller's device set was
applied, so a card withheld for another workload got a CUDA context initialised on it
anyway, and a withheld card that refuses (Exclusive_Process, ECC, MIG parent) dropped
the whole plan to sequential over a device this load was never going to touch --
sequential being the placement that then OOMs.

The device set is now read before probing. A set with fewer than two GPUs is not a
multi-GPU plan, so it returns sequential without asking the planner or touching a card.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten the probe-ordering comment

Comment text only, AST-verified.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
* Studio: quiet the liveness poll and keep access lines out of tauri.log

Measured on an idle 4h desktop session, tauri.log was 5308 lines / 1.14 MB,
of which 4056 (76%) were request_completed access records and 3355 (63%)
came from six polling endpoints. At ~216 bytes a line the 5 MiB cap fills
in about 18 hours, so a failure from the day before had already rotated
out by the time anyone asked for it.

/api/liveness is the desktop watchdog's own probe, roughly every 19s, and
was in no suppressor at all: 760 lines, 14% of the file, saying the
process is still up. Its sibling /api/health was already quiet. Put it in
_QUIET_POLL_PATHS so it heartbeats; non-2xx still logs every time, which
is the case that matters for a watchdog.

Every backend stdout line is written to disk three times: the backend's
own session log, the diagnostics phase log (stream-tagged and stamped),
and tauri.log. The access records carry nothing in the third copy that
the first two lack, so log them at debug!, below the file target's INFO
filter. Non-JSON output -- the startup banner, "Hardware detected:",
stderr, tracebacks -- keeps INFO, which is what anyone opening tauri.log
is there for. The phase log still gets the unfiltered stream, so the
support report loses nothing.

Also:

- Collapse carriage-return progress frames. Reading to \n means a tqdm bar
  arrives as every frame it drew concatenated onto one line; a single
  "Loading weights" bar measured 5086 bytes across three sinks. Keep the
  final frame, which is the one showing 100% and the elapsed total. Cap
  what reaches tauri.log at 16 KiB, the limit the phase log already used.

- Bound logs/llama-server and logs/diffusion-server. Both directories are
  created per model load and were never pruned (319 files going back two
  months here). The server session log has capped itself since it was
  added, so lift that into utils/log_retention.prune_log_dir and call it
  from all three rather than write the loop a third time.

- Log the top-models catalog at debug. Two lists of 40 repo names, one
  line each, on every boot to say a fetch succeeded; the counts say that.

- Configure structlog in run.py before the first line it logs. main.py
  configures on import, several seconds later, so "run_server startup
  begin" rendered through the defaults (console, local time) and
  everything after it as JSON in UTC -- the clock appeared to jump hours
  between the first and second line of one stream.

Not included: the same carriage-return collapse on the Python tee. Doing
it there means line-buffering the file copy, which would withhold a
partial line from server-*.log exactly when the server hangs mid-write.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Collapse progress frames in the session log too, and quiet remote-access

The first pass collapsed carriage-return redraws on the Rust side only. It
left the Python tee alone because doing it there seemed to mean buffering
the file copy until a newline, which would withhold a partial line from
server-*.log exactly when the server hangs mid-write.

It does not have to. Hold back a frame, never a line: an unterminated chunk
containing "\r" is a redraw and is kept until the next one supersedes it,
while an unterminated chunk without one -- a prompt, or a traceback torn by
a hang -- is written the moment it arrives. So the session log gets one
line per bar instead of one per frame, and nothing diagnostic waits on a
newline that may never come.

The console side is untouched: it still sees every frame, which is the
whole point of a progress bar.

Also adds /api/settings/remote-access to the quiet polls (116 lines in the
same 4h sample), for the same reason as the others: it is a plain read of a
toggle, re-read whenever the settings dialog is open.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Install the tee before structlog, and stop three suppressors overreaching

Four review findings, all real.

structlog was configured at import, and PrintLoggerFactory snapshots sys.stdout
while cache_logger_on_first_use freezes that snapshot into any logger that has
already logged. run_server's own logger logs at line one and the tee is not
installed until 45 lines later, so every subsequent run.py line -- the orphan
sweep warnings, the whole rest of startup -- was pinned to the console and never
reached the session log. Configure inside run_server instead, after the tee:
the ordering bug the change set out to fix (line one rendering through
structlog's defaults while line two rendered as JSON in UTC) is still fixed,
and the file gets everything from line one. Moving the tee up also means the
orphan sweep now lands on disk, where it was console-only before.

A withheld progress frame was concatenated onto whatever came next, so a
structlog record arriving mid-redraw landed as Loading 47%{"event": ...} and
stopped being parseable. Close the frame off on its own line unless the next
write is its own redraw or its terminator, and land a frame still held at
close() rather than dropping it.

The desktop watchdog polls every 15s (HEALTH_WATCHDOG_INTERVAL) plus up to a
10s probe budget, so _QUIET_POLL_DEDUP_MS at 10s could never close over two
probes and putting /api/liveness in _QUIET_POLL_PATHS collapsed nothing. Give
it its own 60s window, zeroed alongside the quiet window so --verbose still
logs every probe, and pin the floor with a test that reads both constants out
of commands.rs.

is_backend_access_log_line matched on the event name alone, so it also dropped
non-2xx records to debug! -- below tauri.log's INFO filter. Those are the ones
the backend's heartbeat suppressor deliberately exempts, and a watchdog going
red is what tauri.log is read for. Match only 2xx; a record with no status_code
keeps its INFO line too.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* run.py: keep CRLF lines, stop leaking the tee, import LogConfig lazily

Three defects in the same file, all found while checking this branch against
main. Tests for each alongside.

1. The tee destroyed every CRLF-terminated line.

_last_frame took rpartition("\r")[2] unconditionally, so the "\r" of a CRLF read
as a redraw boundary whose final frame was empty, and the payload went with it:

    "Hardware detected: NVIDIA GeForce RTX 4090\r\n"          -> "\n"
    "Traceback...\r\n  File \"run.py\"...\r\nRuntimeError\r\n" -> "\n\n\n"

On Windows that is every line a child process relays, so a relayed traceback
landed in the session log as blank lines. It is also exactly the artifact #8690
added a UI for. The desktop reader already gets this right: trim_line_endings
strips every trailing \r and \n before collapse_progress_frames sees the text.
Mirror it here so the two sinks stay interchangeable for a reader, and fall back
to the last non-blank frame the same way, so a bar that signs off with a bare \r
keeps its 100% frame instead of writing a blank line.

Also: a "\r" must never reach the file. The handle appends the platform
terminator itself, so one that survives lands as "\r\r\n" on Windows.

2. A zero-length write reopened the record corruption fixed on 08-18.

`data[:1] not in ("", "\r", "\n")` read write("") as a continuation of the held
frame, so the close-off was skipped, the frame fell through to the unterminated
branch, and the next record was glued onto it:

    ["\rLoading weights:  47%", "", '{"event": "model_loaded"}\n']
    -> 'Loading weights:  47%{"event": "model_loaded"}'

print("", end = "") is enough to reach it. Return early on empty data instead.

3. A rejected flag combination left the streams swapped.

--secure --no-cloudflare is a deterministic preflight failure, but it now runs
after _setup_server_disk_logging() has replaced sys.stdout and sys.stderr and
opened a log handle, and nothing unwinds either. An embedder that catches the
SystemExit keeps the tee, and its next run_server() call nests a second one, so
every line is written twice. main does not do this. Validate before the tee.

4. `from loggers.config import LogConfig` at module scope broke Repo tests (CPU).

15 failures in tests/studio/install/test_selection_logic.py, all
"No module named 'loggers.config'; 'loggers' is not a package".
load_studio_run_module stands a bare types.ModuleType in for `loggers` before
exec'ing run.py; a bare module has no __path__, so the import fails during
collection and takes every test in the file with it. That fixture's own comment
names the hazard. LogConfig has one use, inside run_server, so import it there
rather than widening a stub three directories away.

* Prune the log directories after opening the new file, and protect it

Two problems with prune_log_dir as it stands.

The cap never held. All three call sites prune before creating the log, so with
keep=20 the directory settles at 21 and every load repeats the prune-to-20,
create-the-21st cycle. Measured with 25 seeded files and 10 loads: 21 with this
ordering, 20 when the prune runs after the open.

And one odd directory entry disabled retention entirely. The mtime sort ran
inside a single try/except, so a dangling symlink matching the glob raised on
stat() and the whole call returned having deleted nothing. Seeded with 30 files
plus one broken link, keep=5 left all 30. That is the unbounded growth this
helper exists to stop, reintroduced by one bad name. Stat failures are now
per-entry.

Only regular files count now, too: a directory that happens to match the glob
was taking one of the kept slots (25 files plus one such directory, keep=5, left
4 real logs).

prune_log_dir grows a `protect` argument, and the call sites move to after the
open. `protect` is never deleted and counts as one of the `keep`, so the total
stays at keep. It is not enough to trust the new file to sort newest: two loads
in the same second, or a clock that steps back, and it does not.

The retry call site benefits most. The comment right above it explains that the
-try{n} suffix exists so a respawn within the same second cannot truncate the
crash log a retry warning just pointed the user at; pruning before the open on
every attempt worked against that.

New tests cover keep values, the protected file counting toward the cap and
surviving even when it sorts oldest, dangling symlinks, symlinks pointing
outside the directory, directories matching the glob, identical mtimes, family
isolation, and a writer appending across a prune.

* process.rs: CRLF and marker tests, and say what debug! means here

collapse_progress_frames is correct on CRLF because trim_line_endings runs
first, but nothing pinned that, and the Python tee that writes the backend's own
session log got it wrong. Add the cases that hold the two implementations
together: a CRLF payload keeps its text, a CRLF-terminated bar still collapses, a
CRLF JSON record stays parseable and still classifies, a TAURI_PORT marker
survives the collapse whether or not it shares its line with a redraw, and an
all-blank line never keeps a carriage return. Plus the 16 KiB truncation landing
on a character boundary for multi-byte text.

The fallback for an all-blank line returned the whole text, which still holds the
\r the caller asked to collapse away. Return the last frame instead.

Two comment fixes. The new test module had been inserted between the
C:\Windows\system32 comment and the managed_cli_working_dir_tests module it
describes; move it back. And record what debug! actually does for a matched
record: setup_logging in main.rs builds every logger at LevelFilter::Info and
there is no RUST_LOG or any other way to raise it, so log::max_level() is Info
and a matched record is dropped outright rather than demoted, including under
backend --verbose, which makes it emit more of them. That is fine, but it is not
obvious from the call site, and the surrounding comment argued the opposite case
for non-2xx. The records are still written verbatim to the diagnostics phase log
(append_phase_line runs before this decision) and to the backend session log,
both of which the support report and Settings > Logs already offer.

Separately, test_watchdog_window_outlasts_the_probe_interval read the module
global, so it failed for anyone with UNSLOTH_STUDIO_ACCESS_LOG_WATCHDOG_DEDUP_MS
exported; read the default instead. Its two regex lookups now report what moved
in commands.rs rather than raising AttributeError on .group(1).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten the comments this PR adds

Comment-only pass over the 10 files the PR touches. No code change: the AST gate
(comment_tools.py check --strip-docstrings) reports 9/9 files comments-only, the
Rust file has no non-comment line in the diff, and no docstring was dropped.

114 insertions, 142 deletions. Heaviest in run.py and process.rs, where the same
explanation was being given twice, once in a doc comment and again at the call
site. Every load-bearing why is kept: the structlog factory/cache ordering, why a
CRLF terminator is not a redraw, why the watchdog window has to outlast the poll,
why prune runs after the open, and what debug! means for a matched record.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
danielhanchen and others added 27 commits August 27, 2026 05:59
…uto (#9841)

* Keep the context length a load was given instead of resetting it to Auto

Setting Context Length explicitly and loading works once, then silently reverts
to Auto on every load after it. On a model that fits no GPU subset, Auto
resolves to the host-offload fallback of 8192, so a user who asked for 262144
gets 8192 and no indication why.

The backend was never at fault. It launches `-c 262144` for every shape I
tested: a 400 GB MoE on one card, on two, on none, with manual or auto layers,
with `-ncmoe` extras. The route passes `max_seq_length` through verbatim. 8192
appears only when the request arrives asking for Auto.

The frontend discarded the pin the moment the load succeeded. All four
post-load writers derived what to keep from `resolveManualAutoCtxPin`, which
answers a narrower question: it returns the pin only under Manual GPU memory
with auto layers, and null in every other mode. The Context Length control is
offered in every mode, and `resolveLoadMaxSeqLength` honors a pin in every mode,
so the survival rule was narrower than the send rule. On Default the pin became
null the instant the load completed; `customContextLength` is the first field of
the settings panel's React key, so the flip remounted the editor, it re-seeded
from the cleared config and rendered "Auto", and the next load sent 0.

The four writers also disagreed with each other, which is the clearest sign this
was a bug rather than a policy: the auto-load and compare paths kept the pin,
the interactive path dropped it, and the status path dropped it unconditionally
on every refresh, so even the two that kept it lost it moments later.

`resolveLoadedCtxPin` replaces the predicate with the question actually being
asked: what context did this load request? Positive means keep it, 0 means Auto
and clears it. GPU memory mode is not a parameter. The backend already publishes
exactly this as `requested_context_length`, which the status path was reading
and then feeding into the mode filter that threw it away.
`resolveManualAutoCtxPin` had no callers left and is retired; the send-side
`resolveFitMaxSeqLength` it was named after stays.

Widening the pin exposed a window that was harmless while it was almost always
null: a status refresh can land with `modelLoading` still true, and a stale poll
would then plant the outgoing model's context on the model coming in. The pin
now takes the same `seedLoadParams` rule the file already applies to every other
load parameter, leaving performLoad to own the field mid-load. A model change
still carries nothing across, because the value is sourced from the status
describing the active load and never from previous state.

No backend change.

Tests cover the pin surviving in all four mode and layer combinations, the panel
not remounting to Auto, the next load still sending the user's number, an Auto
load still clearing the pin, a model change carrying nothing across, the
mid-load window, and all four writers. All 8 fail without the source change.

* Teach the autoload harness the pin predicate that replaced the retired one

`test_chat_autoload_failure_gate.py` slices `autoLoadSmallestModel` out of
chat-adapter.ts and evaluates it against a stub preamble. Retiring
`resolveManualAutoCtxPin` left its stub behind and gave the region a
`resolveLoadedCtxPin` the harness had never heard of, so every scenario in the
file failed.

The stub mirrors the real predicate instead of returning a constant. The sliced
region stores its result as the load's context pin, so a stub that always
answered null would make all 71 scenarios agree with a bug in it.

The guard that caught this named the missing symbol directly rather than letting
the scenarios fail as wrong-model assertions, which is why the cause was obvious
from the failure text alone.

* Trim the commentary to what the code cannot say itself

Comments only. The four post-load writers each repeated the same sentence about
a later Apply reverting the pin; that now lives once, at the predicate, and each
site says only the fact that is not visible locally: the value it pins is the
one that went on the wire, so the pin cannot disagree with the launched -c.

The forensic detail in preset-policy.ts (the reported 262144, the React-key
remount, the 8192 fallback) is the history of the bug rather than the state of
the code, and the test file's header already carries it. The paragraph in the
applier arguing about what the old filter did or did not guarantee goes the same
way; the load-bearing fact inside it survives in three lines.

Kept: why the predicate takes no GPU memory mode, since the signature reads as
arbitrarily narrow without it and that narrowness was the bug; the mid-load
window note, since an editor simplifying it back to an unconditional write would
reintroduce the stale-poll hazard; and the harness stub note, since a stub doing
real work invites replacement with a constant that would make all 71 scenarios
agree with a bug.

* Pin the context the user asked for, not the one the request resolved to

The first version of this fix inferred "the user pinned a context" from "the
request carried a positive n_ctx". That inference is wrong.
`resolveLoadMaxSeqLength` does not send 0 for Auto in every case: a same-model
reload returns `ggufContextLength`, so with Context Length on Auto under a custom
or modified preset the wire value is the model's native length. Measured with a
262144-context model: builtin-default sends 0 and Auto survives, custom and
modified send 262144 and Auto is converted into a numeric pin. After that, any
same-model reload, including applying an unrelated setting, silently froze the
context and GPU-memory changes could no longer resize it. That is the mirror of
the bug this PR set out to fix.

The pin now comes from the user's setting rather than the resolved value.
`resolveLoadedCtxPin(requestedContextLength)` becomes
`resolveExplicitCtxPin(customContextLength)`: the body is unchanged but the
argument's meaning is not, so it is renamed rather than left with a name that
invites feeding the wire value back in. The three in-app writers pass their own
per-model setting. `resolveLoadMaxSeqLength` is untouched; the send rule was
never wrong, only the attempt to invert it.

That surfaced a second instance of the same class. performLoad substitutes the
resolved context for Auto when layers are pinned on the same model, or the reload
would send 0 and llama.cpp's fit-off branch would read that as the native length.
That is the app protecting the load, not the user choosing a length, so the pin
is captured before it. A test asserts the capture precedes the clamp in source
order.

The status path cannot use the same source, and a backend flag would not help:
`requested_n_ctx` is set from the `max_seq_length` the frontend sent, and the
frontend sends the same number for an explicit 262144 and for an Auto reload of
a 262144-context model, so the backend cannot distinguish them either. A new
field would be the frontend's own state round-tripped through the server. The
new `resolveCtxPinSeed` therefore acts only on unambiguous evidence: it writes
nothing mid-load, clears on a non-GGUF load or an explicit 0, and on a model
change adopts the arriving model's saved setting only when it matches what the
server reports, which is the rule the batch sizes next door already use. Where
the echo is genuinely ambiguous, a positive value on the same model, it defers
to the record this tab wrote while watching its own load. The cost is that
another client re-pinning the same model to a different length looks like an
Auto reload; keeping Auto working is worth it.

Tests go from 8 to 10. Two existing ones changed contract deliberately: the
"writers pin the n_ctx their load actually sent" title stated the regression
itself and is renamed, and two source-regex anchors became behavioural
assertions now that the status path has a seam. No assertion was loosened, and a
new guard asserts no writer feeds a wire value into the pin resolver at all.
Reverting either half of the fix fails the new tests; reverting both fails three.

* Read the two status echoes that do carry intent

The status seed treated every positive `requested_context_length` as evidence of
nothing, on the grounds that an Auto same-model reload reports one too. That is
right in general and wrong in two specific places.

An echo that CONTRADICTS the pin this tab recorded means another tab or an API
client reloaded the same model at a different context. The pin then describes an
invocation that is not running, and the next unrelated Apply resends it and
silently takes back the other client's choice. Keeping the record was defensible
while the cost was only failing to notice; actively reverting someone else is
not. The contradicted baseline is now dropped. The echo is still not adopted
here, because it still cannot say whether a human chose the new value, so the
control falls back to Auto and the next Apply agrees with the server instead of
fighting it. An agreeing echo changes nothing, which is what keeps an explicit
pin alive across ordinary polls, and our own pinned model reloaded on Auto
reports the resolved context, which IS the pin, so it matches and nothing moves.

Under Manual memory with Auto layers there is no ambiguity to reason around at
all. That placement sends its pin through `resolveFitMaxSeqLength`, which
answers `customContextLength > 0 ? it : 0`, so Auto is 0 on the wire without
exception and a positive echo cannot have come from it. Clearing there made a
fresh tab hydrating a resident pinned server claim Auto, and the next Apply
reload at 0. That echo is now adopted, ahead of both other branches: it is
better evidence than a saved config, and on a model change it describes the
model that arrived rather than the store's leftovers.

The caller passes the raw `status.gpu_memory_mode` and `status.gpu_layers`, not
the normalised values computed below it, which null out layers off manual and
would read as "not reported" rather than as Auto.

All four invariants still hold and the ten existing tests are untouched: an
explicit context survives in every mode, Auto stays Auto across a same-model
reload under every preset source, a model change carries nothing across, and a
poll landing mid-load plants nothing. The two new tests fail without the source
change; the ten existing ones pass either way.
…owns (#9865)

* Studio: stop the per-chunk autosave writing back messages the server owns

During a streamed reply the history adapter's autosave fires per chunk. When the
message is server-managed it built the write out of fields it had just read back
from the backend: content from existingMessage.content, metadata from
existingMetadata, createdAt from existingMessage.createdAt. Attachments are
always empty there, since only a user message carries them. So the request could
not change anything, and the server answered 409 "server-managed generation
messages cannot be edited" every time.

Measured on a real session: one 43.6 s generation issued 265 PUTs of which 256
were rejected, a median 166 ms apart, plus 353 whole-thread GETs a median 339 ms
apart. The GETs come from the ensureStoredChatThread inside
saveStoredChatMessage, so returning before the call drops both.

parentId is the one field not echoed back, so a reparent could in principle
differ here. It is dropped either way today, because the server rejects the whole
request. Skipping is behaviour-preserving rather than a new trade.

The guard is a source test rather than a behavioural one: the call site is an
inline closure in the history adapter with no seam to stub. It pins ordering
rather than spelling, so a rename keeps working and moving the save above the
guard does not.

* Tighten the comments this change added
…d anything (#9878)

* fix(studio): stop offering a transformers upgrade where it cannot load anything

Loading an architecture newer than the installed transformers pops the "New model architecture" dialog, which offers to install the latest release. `check_upgrade_for_model` fires whenever a config's `model_type` is absent from every installed overlay and the tier tables, on the premise its docstring states: that is "exactly when today's load would fail with an unrecognized-architecture error".

That premise does not hold on MLX. The inference backend is chosen by hardware, and the MLX branch returns before the transformers backend is ever constructed, so mlx-lm and mlx-vlm decide what loads there and transformers only supplies the tokenizer. Muse Glimmer is the case in hand: `muse_glimmer` is absent from transformers 5.5.0's `CONFIG_MAPPING_NAMES`, yet text and vision inference and training all run on it. The offer is not merely redundant on that hardware, it is unactionable -- no transformers version can make an architecture loadable when transformers is not what builds it -- and accepting it costs a minutes-long install for no change.

Skip the check on MLX hosts, the same reason GGUF is already skipped one branch above. Every other device is untouched, and a failure to detect hardware falls back to offering the upgrade so a detection problem cannot silence a real one.

Deciding this per model instead -- suppressing the offer when mlx-lm or mlx-vlm ships that particular `model_type` -- was tried and dropped: a wrapper whose top-level type MLX ships can still carry a brand-new nested backbone that neither backend can build, so module presence does not establish that the config loads.

The tests for this check now pin a device rather than reading the host's, since on Apple Silicon they would otherwise exercise the short-circuit instead of the behaviour they assert.

* Keep the transformers upgrade offer for bitsandbytes repos on MLX

* Keep skipping the unsloth bnb repos MLX swaps for their base

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Nilay Yadav <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
* Fix Studio CPT overwriting LFM2 all-linear LoRA targets

When switching to continued pretraining, preserve architecture-specific
all-linear defaults instead of replacing them with Llama-style module names.
Restore the pre-CPT target list when leaving CPT and expose all-linear in
the CPT advanced-settings UI for models like LFM2.

Fixes #9866

* Fix DatasetFormat typing in CPT provenance test

Use `as const` for chatml so tsc -p tsconfig.test.json passes in CI.

* Fix CPT target module state transitions

* Fix CPT target module interaction tests

* Fix LFM2 CPT VRAM estimates

* Fix LFM2 defaults races and aliases

---------

Co-authored-by: Etherll <[email protected]>
Detect YouTube URLs in shared clipboard payloads so transcript attachment works for mobile and LAN clients.
…ting (#9894)

* Studio: alert when a canvas is blocked by network access being off

* Studio: make the canvas network alert dismissable and test the deep link

* Studio: keep the canvas alert from dropping focus or re-announcing

* Studio: show the focus ring on the canvas the settings link returns to

* Studio: lead the canvas alert with the per-canvas grant, settings beside it

* preserve canvas focus after dismissing alerts

* preserve canvas focus after network grants

* restore settings focus to a stable canvas target

* preserve settings opener across repeated opens

* pause route shortcuts while settings is open

* stop repeated canvas alert announcements

* sync locale direction across canvas alerts

* break the chat runtime hub import cycle

* update cpu fallback replay test tuples

* read the memory contract source as utf-8

* remove startup feature barrel cycles

* run the tool activity browser smoke in ci

* keep fullscreen canvas focus inside its dialog

* update shortcut guard assertions

* scope canvas direction without changing the document

* align the menu probe with trigger focus restoration

---------

Co-authored-by: Maheswar Kumar <[email protected]>
…8768)

fix local mlx discovery and safe api model switching
* Fix sidebar profile width with chat scrollbar

* Match context menu item radius to dropdowns
)

Fixes #9864.

Pin Claude direct and MCP subagent sessions to the local Studio endpoint even when user settings or the inherited environment select Foundry, Bedrock, Vertex, AWS, Google Cloud, Mantle, or a Unix socket. Preserve compatibility with older Claude versions, WSL path translation, forwarded settings, subcommands, and concurrent sessions.

Includes focused inherited-provider regression coverage adapted from #9907 by @lonexreb.
# Conflicts:
#	studio/frontend/src/features/hub/inventory/types.ts
@mahiatlinux
mahiatlinux merged commit 19416fd into Imagineer99:fix/model-hub-recent-sort Aug 28, 2026
@mahiatlinux
mahiatlinux deleted the pr-9642-followups branch August 28, 2026 10:40
danielhanchen added a commit that referenced this pull request Nov 11, 2026
…nslothai#17459)

## Summary

Moves Studio's stable-diffusion.cpp prebuilt from
`master-982-0518b34-uba6ac30` to `master-982-0518b34-ueb0e729`, the
release built from fork master `eb0e729`. That is 36 fork commits on top
of the current pin. The tag keeps the `master-982` prefix because the
fork's release naming still counts from its last upstream release tag.

What the new build brings:

- Upstream resync to `master-1056` (unslothai/stable-diffusion.cpp#54):
packed INT4 convrot, MiniMax-H3 QKV chunking, RelayVSR, SDXL ControlNet
Union. Also Cosmos3-Nano-Sim-Transfer video-to-video (#53).
- x86 CPU: llamafile tinyBLAS GEMM for Q8_0 (#42), F16 / BF16 (#47) and
Q4_1 / Q5_0 / Q5_1 (#56) weights; an int8 tiled GEMM for Q8_0 / Q4_0 /
Q4_1 / Q5_0 / Q5_1 / IQ4_NL (#76); AVX512 kernels on Intel and a faster
direct convolution by default (#36, #70); Q4_K / Q2_K kept on the tiled
matmul on AMD (#57); Q5_0 / Q5_1 / Q4_1 through the Q8_0 GEMM at
diffusion batch sizes (#74); tiled flash attention and SIMD max fixes
(#66, #68, #62).
- aarch64 CPU: ik_llama.cpp GEMM kernels for K-quant and I-quant weights
(#48, #75), a NEON + i8mm variant for 128-bit SVE cores (#58), SVE flash
attention on the NEON path (#69), a 4x4 flash attention register tile
(#67).
- Metal: long graphs spread over more command buffers so the GPU
watchdog does not fire (#44), a coalesced im2col kernel (#45), flash
attention `auto` now means on without the timing probe (#46).
- Vulkan: RMS norm for short rows (#37), direct convolution chosen by an
output check instead of a timing race (#38), no host-buffer import on
AMD and MoltenVK (#60).
- HIP: bf16 WMMA operands for gfx11 / gfx12 (#59), FP32 accumulators in
the tile flash attention kernel (#61).
- CUDA: the Q8_1 block sum is computed from the quantized values, which
lowers matmul error for Q4_1 / Q5_1 / Q4_K / Q5_K / Q2_K weights (#63);
BF16 cuBLAS for large Q8_0 matmuls on A100, Hopper and datacenter
Blackwell (#39).
- Memory: the conditioning cache keeps entries across output sizes and
denoiser-only LoRA changes (#71); auto-fit charges unified-memory
devices against the RAM budget (#73, `SD_AUTOFIT_UMA=0` disables);
CPU-resident text-encoder weights are released when the next phase would
not fit (#72, `SD_TE_RELEASE=0` disables); `--mmap` repacks only what
the CPU repacks (#43); Qwen Image 2.1 prefix cache concatenated in F16
(#64).
- Packaging: bundles are smaller (#41; the Linux CPU bundle is 38.4 to
26.0 MiB, Linux CUDA 12 is 368.5 to 338.3 MiB, Linux Vulkan is 57.9 to
30.5 MiB), the Linux CPU bundles are run on emulated CPUs before
shipping (#49), and there is a new native Windows arm64 CPU bundle
(#55).

## Changes

- `studio/install_sd_cpp_prebuilt.py`: `DEFAULT_TAG` now names the new
release.
- Tests that pin the release name and its asset list now point at the
new tag. `test_sd_cpp_args.py` keeps the old pin in its list of builds
that support `--mmap`.
- The pinned asset lists gain `win-cpu-arm64`, with a test that a
Windows ARM64 host gets that bundle for `auto` / `cpu` while an x64 host
keeps `win-cpu-x64`, and that ARM64 with `cuda` or `vulkan` still gets
no match.

No Studio code changes. The existing selector already filters Windows
bundles by host architecture, so a Windows arm64 host, which today finds
no bundle in the pinned release and falls through to the upstream
fallback, now installs the native arm64 CPU build. An x64 Python running
under emulation on Windows arm64 reports `AMD64` and keeps the x64
bundle, as before. No option was removed from `sd-cli --help` or
`sd-server --help`; the new build only adds `--control-type`,
`--input-frames`, `--upscale-factor` and `--vsr-window-size`.

## Testing

- The sd.cpp, args, families, install, pin upgrade and download retry
tests pass (1406 passed). One test and one fixture error fail on main
and on this branch alike on this host, because its huggingface_hub is
older than the installed diffusers expects:
`test_create_causal_mask_patch_is_self_disabling_and_idempotent` and
`test_selection_installs_the_cuda_build`.
- Asset names: every bundle the selector can return was enumerated over
Linux x86_64 / aarch64, Windows AMD64 / ARM64 and macOS arm64 / x86_64,
with `auto`, `cpu`, `cuda` (no major, 12, 13), `vulkan` and `rocm`,
against the real asset list of the new release. Every returned name
exists in the release. The only change from the current pin is Windows
ARM64 `auto` / `cpu`, which goes from no match to `win-cpu-arm64`.
- SD1.5 (`v1-5-pruned-emaonly`), 512x512, 8 steps on CPU and 20 steps on
CUDA, euler, cfg 7, seed 42, both builds on the same machine. Each arm
repeated two or three times; every repeat was pixel-identical to the
first run of its arm. LPIPS is AlexNet.

Linux x86_64 CPU bundle, Xeon Platinum 8559C, 32 threads, wall time per
image:

| Weights | current pin | this branch | old vs new LPIPS | max pixel
diff |
| --- | --- | --- | --- | --- |
| f16 | 34.8 / 34.8 s | 16.4 / 17.2 s | 0.0001 | 13 |
| q8_0 | 31.3 / 32.4 s | 15.7 / 15.2 s | 0.007 | 118 |
| q4_K | 35.5 / 35.0 s | 18.7 / 19.0 s | 0.023 | 211 |

VAE decode alone went from 10 to 12 s down to 3.6 to 3.7 s. The
quantized CPU renders are not bit-identical to the current pin, but they
stay as close to the f16 render as before (q8_0 LPIPS to f16: 0.038 old,
0.046 new; q4_K: 0.163 old, 0.173 new).

Linux CUDA 12 bundle, Colab L4, wall time per image:

| Weights | current pin | this branch | old vs new LPIPS | max pixel
diff |
| --- | --- | --- | --- | --- |
| f16 | 4.70 / 4.70 / 4.71 s | 4.70 / 4.91 / 4.73 s | 0 | 0 |
| q8_0 | 7.42 / 4.92 / 4.90 s | 4.94 / 4.93 / 4.93 s | 0 | 0 |
| q4_1 | 18.13 / 17.97 / 17.94 s | 18.02 / 17.97 / 18.01 s | 0.025 | 198
|
| q4_K | 19.14 / 17.63 / 17.79 s | 17.74 / 17.63 / 17.61 s | 0.106 | 253
|

The current pin's first q8_0 run includes a cold start. f16 and q8_0 are
pixel-identical. q4_K moves, as the Q8_1 fix intends, and moves toward
the f16 render: LPIPS to f16 drops from 0.240 to 0.176 (q4_1: 0.327 to
0.322).

## Not covered

- macOS (Metal) and Windows were not run on hardware yet; the
cross-platform staging legs (Ubuntu, macOS 15, Windows) are still to
run.
- The new Windows arm64 bundle is covered only by the selector test and
the asset check. No Windows arm64 host ran it.
- No Vulkan, ROCm or HIP render with this build, no aarch64 Linux
render, and no Studio HTTP flow run (only `sd-cli` directly).
- No MiniMax-H3, MOSS-Image, Qwen-Image or FLUX.2 render with this
build; only SD1.5.
- CPU timings are from a shared host (both arms ran back to back with
the same thread count), and the CUDA timings come from one L4 VM, three
runs per arm. No T4 run.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.