Skip to content

Docker Studio: stop disabling Unsloth's TRL patches on GPU hosts - #10825

Merged
danielhanchen merged 4 commits into
unslothai:mainfrom
oobabooga:docker-cpu-fallback-env
Sep 12, 2026
Merged

danielhanchen merged 4 commits into
unslothai:mainfrom
oobabooga:docker-cpu-fallback-env

Conversation

@oobabooga

@oobabooga oobabooga commented Sep 12, 2026 •

Copy link
Copy Markdown
Member

Training does not work in unsloth/unsloth:latest on a machine with a GPU. Studio's Train page, the bundled notebooks, unsloth train and GRPO all stop with a TypeError the moment they build a trainer. This makes them work.

Why it breaks

The Studio image sets ENV UNSLOTH_ALLOW_CPU=1 so the image can also start on a machine without a GPU. Inside the Unsloth library that same variable means something different: "CPU-only CI, skip the TRL patches" (since #5429). An image ENV reaches every process in the container, so on a GPU host everything in the image trains with stock TRL instead of Unsloth's trainers.

Measured on the published image (RTX 6000 Ada and RTX 3090, driver 610.43):

What the user does What they get
Studio, Train page SFTConfig.__init__() got an unexpected keyword argument 'max_seq_length'
The shipped Gemma3_(270M).ipynb in JupyterLab, or unsloth-run SFTTrainer.__init__() got an unexpected keyword argument 'tokenizer'
unsloth train the same SFTConfig error
GRPO with fast_inference=True 'Qwen3ForCausalLM' object has no attribute 'warnings_issued'

243 of the 445 notebooks baked into the image pass tokenizer= to a TRL trainer, so the notebook failure is not one notebook.

The two images differ, which is the clearest symptom: from trl import SFTTrainer, GRPOTrainer gives trl.trainer...SFTTrainer / GRPOTrainer inside latest, and UnslothSFTTrainer / UnslothGRPOTrainer inside core, which never sets the variable.

The fix

The image keeps its own opt-in and stops handing the library a variable that means something else:

  • Dockerfile.studio sets UNSLOTH_IMAGE_ALLOW_CPU=1 instead of UNSLOTH_ALLOW_CPU=1. The build itself still passes UNSLOTH_ALLOW_CPU=1 to install.sh inline, because the build host has no GPU.
  • entrypoint.sh now decides per container. GPU visible: it unsets UNSLOTH_ALLOW_CPU for everything it starts, and warns if the user passed it. No GPU: it exports UNSLOTH_ALLOW_CPU=1 when the opt-in is on, so Studio, JupyterLab and the notebooks still work on CPU.
  • -e UNSLOTH_ALLOW_CPU=0 still gives the strict refusal on a GPU-less host, and :core still refuses without an opt-in.
  • The rule runs before UNSLOTH_SKIP_GPU_CHECK, which skips the torch checks and not the variable's meaning.
  • gpu_visible() reads nvidia-smi -L into a variable before grep -q: under set -o pipefail, a grep -q that exits on the first line can turn the producer's SIGPIPE into the pipeline's status, which would read as "no GPU".

Before and after

A is the published unsloth/unsloth:latest / :core. B is both images built from this branch with the same pinned refs.

Check A (published) B (this PR)
docker exec trainer classes, GPU host SFTTrainer / GRPOTrainer UnslothSFTTrainer / UnslothGRPOTrainer
Studio Train page, Qwen3-0.6B + alpaca, Playwright fails at start, 1/2 checks completes, 3/3 checks
Gemma3_(270M).ipynb through unsloth-run exit 1, TypeError exit 0
unsloth train --max-steps 5 exit 1, SFTConfig exit 0, "Training completed!"
GRPO, 3 steps, fast_inference=True exit 1, warnings_issued GRPO_OK, UnslothGRPOTrainer
UNSLOTH_ALLOW_CPU in the Studio process / a docker exec shell set / set unset / unset
:core with -e UNSLOTH_ALLOW_CPU=1 on a GPU host stock TRL patched, with a warning

The rest is unchanged on both sides. A CPU-only host still starts with its warning, still has the variable in the Studio process, and reached the same 9 UI checks; -e UNSLOTH_ALLOW_CPU=0 with no GPU still exits 1; :core still refuses without an opt-in and starts on CPU with one. Studio chat, JupyterLab, GGUF export and llama.cpp behave the same.

Verification

  • tests/python/test_docker_cpu_fallback.py: 17 passed. Five of them fail on main: the image opt-in, the absent ENV, the CPU export, the dropped explicit value on a GPU host, and the SKIP_GPU_CHECK path. The entrypoint cases run the real script against stubbed nvidia-smi and python, and read the environment the exec'd command receives.
  • Every tests/python/test_docker_*.py plus tests/studio/install/test_docker_studio_keep_cuda_prebuilt.py: 521 passed, 5 skipped, 1 failed. The failure, test_docker_nb_refresh_state_durability.py::test_an_abandoned_restore_puts_the_tree_back, fails identically on main.
  • The formatter (pinned ruff) leaves the branch unchanged.

Not in this PR

The variable still means two things inside Unsloth: "allow CPU" and "skip the TRL patches" are the same switch. Keying the skip on an actually absent accelerator is a library change, separate from this.

On a CPU-only host, a docker exec shell no longer inherits UNSLOTH_ALLOW_CPU, so python -c "import unsloth" there reports that it needs a GPU. Studio, JupyterLab, their kernels and SSH logins all still get it, and unsloth studio reset-password, unsloth-llama-update and Studio chat were checked in that state.

Passing -e UNSLOTH_ALLOW_CPU=1 on a GPU host now gets a warning and patched trainers. Shells opened with docker exec still see the value passed to docker run, which the warning says.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed this hits docker/Dockerfile.studio, where the image-level UNSLOTH_ALLOW_CPU=1 reaches every process and makes unsloth/models/rl.py skip the TRL trainer patches even on a GPU host. Will get this reviewed.

…a GPU

Four things the per-container rule missed, each reproduced against the published
image on an NVIDIA host before and after.

Dockerfile.studio bakes UNSLOTH_IMAGE_ALLOW_CPU=1 but BASE_IMAGE defaults to the
PUBLISHED unsloth/unsloth:core, whose entrypoint predates the name. A standalone
`docker build -f docker/Dockerfile.studio` therefore opted in and still exited 1 on
a CPU-only host. Confirmed by running :core with the new variable: exit 1, where
UNSLOTH_ALLOW_CPU=1 starts. The publish workflow pins the core digest from the same
run, so CI could not see it. Studio now copies the entrypoint it needs.

gpu_visible() shells out to nvidia-smi -L, which lists the hardware and ignores
CUDA_VISIBLE_DEVICES; torch honours it, so an empty value or -1 leaves
device_count() == 0. The GPU path was therefore taken for processes with no GPU:
with --gpus and -e CUDA_VISIBLE_DEVICES= the opt-in was stripped and `import
unsloth` raised NotImplementedError, where main imported fine. Both masks now count
as no GPU, which also replaces a misleading driver-too-old exit with the CPU
fallback the user asked for.

allow_cpu used ${VAR:-...}, so `-e UNSLOTH_ALLOW_CPU=` fell through to the image
opt-in and started a GPU-less container that main refused. `-` keeps an explicit
empty value meaning off, as the comment beside it already claimed.

host_has_nvidia() in run.sh still piped nvidia-smi into grep -q under pipefail, the
exact shape fixed in entrypoint.sh; there a SIGPIPE reads as no GPU and silently
drops --gpus.

Tests: the GPU-host case now builds its environment from the Dockerfile ENV instead
of spelling the new name, so it fails on main rather than passing vacuously against
the ENV that caused the bug; plus the two masks, the empty value, the bundled
entrypoint, and the one CPU path that reaches exec with no opt-in, where an
unconditional export would have hidden.
@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 12, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-12T12:53:26.541897Z 179e677 Manual request
🔒 Security Review ✅ Completed 2026-09-12T12:28:16.149439Z cac276c Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 12, 2026
@danielhanchen

Copy link
Copy Markdown
Member

I pushed cac276c to this branch with four fixes, each reproduced against the published image on an NVIDIA host before and after. The change this PR makes is right, and I confirmed the bug it fixes is real: unsloth/unsloth:latest really does carry UNSLOTH_ALLOW_CPU=1 as an image ENV, and on a GPU host trl.SFTTrainer resolves to trl.trainer.sft_trainer.SFTTrainer with SFTConfig.__init__() got an unexpected keyword argument 'max_seq_length', which is byte for byte what users are reporting. With this branch's entrypoint it resolves to UnslothSFTTrainer and SFTConfig(max_seq_length=2048) is accepted. This also closes #10785, which is the same failure on an RTX 5060 Ti and says it only happens with the Docker Hub image.

What the per-container rule missed:

Fix Reproduced how
Studio did not bundle the entrypoint that reads its opt-in docker run --rm -e UNSLOTH_IMAGE_ALLOW_CPU=1 unsloth/unsloth:core with no GPU exits 1, so a standalone build on the default ARG BASE_IMAGE opted in and was still refused. This is the Codex P2, and it is correct.
A masked CUDA read as a GPU nvidia-smi -L lists the hardware and ignores CUDA_VISIBLE_DEVICES; torch honours it. With --gpus and -e CUDA_VISIBLE_DEVICES= the opt-in was stripped and import unsloth raised NotImplementedError, where main imported fine.
-e UNSLOTH_ALLOW_CPU= fell through to the image opt-in ${VAR:-} treats set-but-empty as unset, so a GPU-less container started where main refused. ${VAR-} restores it and matches the comment already beside it.
host_has_nvidia() in run.sh still pipes into grep -q under pipefail The exact shape this PR fixed in entrypoint.sh. A SIGPIPE there reads as no GPU and silently drops --gpus.

Verification, on top of the suites already listed: 1664 simulated startup cells covering Linux/WSL2/Docker Desktop on macOS and Windows, NVIDIA and AMD and CPU-only, multi-GPU, MIG, arm64, a broken NVML, an empty -L, and every value of the three variables crossed with four CUDA_VISIBLE_DEVICES masks. Against main: 60 cells change, all of them the intended one, plus 30 where a masked CUDA used to exit with a driver error and now takes the CPU fallback. No other cell changes. tests/python/test_docker_*.py plus the Studio prebuilt suite: 531 passed, 2 skipped.

The GPU-host test now builds its environment from the Dockerfile ENV rather than spelling the new variable, because as written it also passed on main, against the very ENV that caused the bug. Nine of the file's tests now fail on main, up from five.

One behaviour worth stating plainly in the description rather than leaving to the entrypoint comment: on a host with no GPU, a non-login docker exec no longer inherits the variable, so docker exec <c> python -c "import unsloth" reports it needs a GPU. Studio, JupyterLab, its kernels and login shells are all fine, because studio_launch.sh snapshots the normalised environment into /etc/profile.d. I documented the docker exec -e workaround in DOCKERHUB.md.

Also worth a separate look: the smoke-test job in docker-publish.yml is gated on vars.HAS_GPU_RUNNER == 'true' and shows skipped on every recent publish, and even when it runs, smoke_test.py only prints trl.__version__. A container full of stock TRL passes it. One assertion that trl.SFTTrainer is UnslothSFTTrainer on a GPU host would have caught this before it shipped.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: cac276cfbf

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: cac276cfbf

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

Both classes stub /usr/bin-style tools, stage a /dev tree and read the environment a
POSIX exec hands on. The guard only asked for bash on PATH, and Git Bash satisfies
that on a Windows runner, so the whole file ran there and 10 of 23 failed on path
translation and the exec bit: five FileNotFoundError on the recorded argv and five
on the exec'd child's environment.

Four of those predate the entrypoint cases added here, in
TestRunShDegradesWithoutNvidia, which this branch does not touch, so the gap is not
new. No workflow ran into it because the Windows matrix in
cross-platform-parity-ci.yml names five files and this is not one of them; it runs
on ubuntu in Repo tests (CPU). Verified on a staging run of this branch: ubuntu and
macos-14 both 23 passed, windows-latest 10 failed.

Nothing upstream CI exercises is lost, and a developer running the suite on Windows
stops seeing ten failures for a file that cannot apply there.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 12, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 179e677567

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 12, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 12, 2026
@danielhanchen
danielhanchen merged commit 4e926db into unslothai:main Sep 12, 2026
9 of 11 checks passed
danielhanchen added a commit that referenced this pull request Sep 12, 2026
* Unbreak main: read the sidebar hold-out contract as a condition, not as source text

#10706 hoisted `hasPinMode && !pinned && collapseToZero` into a named const and gave it a
peek exception. That changed nothing the contract protects, but the test pinned the inlined
spelling, so Backend CI has failed on every main commit since 22bbff6 and on roughly 25
open PRs that touch none of this.

Read the condition instead, with the helpers that already exist for exactly this in
tests/studio/_js_source.py, and assert the thing the literal form never did: that
aria-hidden and inert stay the same expression, since hidden-but-focusable is the bug.

_js_source gains two pieces:

- attribute_expressions(), to read what a JSX attribute is wired to.
- an ASI-aware declaration scan. binding_joining() only looked for `const NAME = ...;` and
  sidebar.tsx has one semicolon in 500 lines, so it found no declarations there at all and
  answered None for a binding plainly present.

* Restore linear DeepSeek R1 tool-call parsing, and measure linearity rather than speed

#10507 added a wrapper sweep that seeks the next `{` once per opener. A DeepSeek R1 body is
repeated `<|tool_sep|>` markers, so that is once per marker, each scanning the rest of the
buffer: quadratic. Measured over doubling input, the R1 path went 2.00x per doubling before
#10507 and 2.21x, 2.40x, 2.66x, 4.82x after, reaching 2.9s on 80k markers.

The sweep now carries the next `{` forward instead of re-seeking it, since both indices only
move forward, and stops when there is none left. It also no longer copies the gap between a
marker and a far-away object: a fence or blank space is short, so a long gap is not a body.
Rejecting it is the conservative direction, because an untrusted span is masked rather than
exempted. All five adversarial shapes are back to 2.00x per doubling.

test_pr5624_regressions caught this and was reported as a flake, because an absolute
`elapsed < 1.0` at one size cannot tell a slow runner from a slow parser: it read 0.20s on a
quiet runner and 1.41s on a busy one, and the real regression only tipped it over sometimes.
The three tests now compare the cost of 4x the input against the cost of 1x. Linear is ~4x,
quadratic is ~16x. Healthy measures 3.94-4.09 across all four shapes; with #10507's sweep
restored it measures 6.7x and 12.2x, so the bar at 6.0 has margin on both sides.

Adds the distant-object shape as a fourth case. It is the one that stayed quadratic after
the obvious fix, because a `{` anywhere in the buffer means the per-marker seek always
finds one.

* Do not score a PowerShell host crash as an installer-watcher failure

#10825 went red on test_the_watcher_scores_the_image_that_ran_not_the_words_in_the_message
with pwsh aborting on SIGABRT out of AssemblyName.ParseAsAssemblySpec: the .NET host tearing
itself down, on a probe that loads no assembly of its own and passes everywhere else.

Both pwsh probes now go through one runner that retries once and then skips, and only for an
abnormal termination carrying a host fault banner. A clean non-zero exit, or the wrong HITS
count, is the watcher being wrong and still fails: verified by breaking Watch-ForCompiler.ps1
and confirming the test goes red, and by driving all four shapes (crash-then-ok, crash-twice,
clean non-zero, abnormal without a banner) through the runner directly.

* Re-triage the 7 dependency-scan findings an upstream release reopened

pip scan-packages fails on every PR that touches deps (#10819 is the current one) with 5
CRITICAL and 2 HIGH that no PR introduced. The baseline binds each entry to a hash of the
flagged code, so an upstream release that edits those lines reopens the entry by design.
scikit-learn 1.9.1 did exactly that; unsloth-zoo reopens on its own PyPI releases.

Reviewed all 7 against the source, not the check name:

- sklearn/datasets/_openml.py, 'C2 polling/beaconing loop': the `while True` inside
  _retry_on_network_error. It decrements retry_counter, re-raises at zero and re-raises 412
  immediately. A bounded retry, not a beacon.
- sklearn/externals/array_api_compat/{cupy,dask,numpy,torch}/__init__.py, 'Downloads and
  executes remote code': `__import__(__spec__.parent + '.linalg')`, four copies of a
  vendored shim importing its OWN submodule, with the upstream comment explaining that the
  name is built dynamically so the library can be vendored. No network, no remote code.
- unsloth_zoo/compiler.py, 'obfuscation + exec/eval': our own compiler exec'ing the patched
  forward methods it generates. That is the module's entire purpose.
- unsloth_zoo/mlx/loader.py, same check: the Exec evidence is almost all `mx.eval(...)`,
  MLX's lazy-array evaluation, which is not Python eval at all.

Entries are appended, not regenerated, so the other 228 keep their existing review.

Known follow-up: unsloth-zoo is first-party and releases often, so these two entries will
reopen again. Worth deciding separately whether a package we publish belongs in a
third-party supply-chain scan at all; not changing the gate's design here.

* Read the media status guard as a guard, not as one exact line

#10788 rewrote setStatusIfNewest's ticket check from

    if (ticket === statusTicket.current) setStatus(next);

to

    if (ticket !== statusTicket.current) return;
    setStatus(next);

which admits exactly the same reads, and Frontend build + bundle sanity went red on the
substring. Same failure class as the sidebar contract in the previous commit.

Both spellings now count, checked against setStatusIfNewest's own callback body so a guard
elsewhere in the file cannot stand in for it. Verified against #10788's source (passes) and
against three mutations (guard deleted, guard inverted, guard moved out of the callback),
each of which fails.

* Bound the fence, not the gap, when trusting a wrapper body

The previous commit refused any gap over 4096 chars between a wrapper marker and its object,
to avoid copying it once per marker. Differential testing against the old sweep over long
gaps showed that is too blunt in the one direction that matters: _only_a_code_fence strips
before it matches, so a genuine fence trailed by blank space, or an object preceded by a long
blank run, was accepted before and refused after. Refusing wrongly is not free. An untrusted
wrapper body gets masked, and end to end that turns a tool argument of

    {"q": "<think>rehearsed</think>"}

into a run of U+E000, which is the defect #10507 added _inference_wrapper_spans to avoid.

The gap's blank ends are now found as indices and never copied, and the cap applies to what is
left, which is the only part the fence test decides on. Blank is unbounded again, as it is in
real output.

Differential against main's sweep: 60000 random short inputs, 0 mismatches. 2520 long-gap
inputs across blank, fence, text and brace fillers at 1 to 20000 chars: the only remaining
divergence is a fence whose stripped form exceeds 4096 characters, that is a 4000-plus backtick
run or language tag, which is what the cap is for and is documented as such.

Still 2.00x per doubling on all six adversarial shapes, including the two the cap exists for
(one distant object, and a long blank run before it).

* Record the new tool_call_parser constant in the refactor guard inventories

The guard pins the parsing stack's module surface, so the added _MAX_FENCE_CHARS reads as an
unrecorded top-level name and fails test_ast_inventory_matches_the_baseline and
test_runtime_surface_matches_the_baseline.

Added by hand rather than with 'refactor_guard.py snapshot'. A full snapshot on this tree also
rewrites 111 unrelated ast entries, 63 patch targets and two idempotence inputs, none of which
this branch touches, and folding someone else's unrecorded drift into a CI fix would hide it.

test_guarded_functions_produce_the_same_bytes, the digest over the 1833-input corpus, passes
unchanged, which is the check that would have caught a behaviour change in the sweep.

* Attribute a temporary DLL to a compiler, so Windows No Compiler CI can pass

This job has never once been green: 0 successes against 70 failures and 28 cancelled runs
in its last 100, red on main continuously. It fails on its own artefact detector, which
scored every *.dll created anywhere under TEMP while the installer ran. The installer
unpacks llama.cpp's checksum-verified prebuilt release into a staging directory there, so
~25 DLLs land under TEMP with no compiler within reach, and the job reported them as
'the artefact half of the same shape'.

They are not that shape. What was blocked in the field, and what this job's own prose says
it measures, is

    powershell.exe -> csc.exe -> %TEMP%\<random>.dll

An extracted archive is a different thing, so the gate was wrong and the installer was
right. A DLL now counts only when a compile is evidenced in ITS OWN directory. CodeDom,
which is what Add-Type uses and what was flagged, writes the response file, the generated
source and the captured streams into the per-invocation directory it puts the assembly in,
so the pairing holds for the shape this exists to catch. A .cmdline or .rsp still counts on
its own, wherever it lands.

The narrowing is self-checking: the positive control compiles a real type with Add-Type and
REQUIRES both detectors to fire before any measurement is believed, so cutting too far fails
there rather than passing quietly.

Also fixes the message that reported this. Both throws read '{0}' literally on every firing,
because -f binds tighter than the string concatenation it was applied to and formatted only
the last fragment.

Tests: test_the_watcher_still_reports_intermediates_that_were_left_behind asserted a bare
leftover.dll, which is the over-broad rule itself; it now leaves a response file beside the
assembly, which is what a compile that was not cleaned up looks like. Two new cases pin the
change: an unpacked release archive is not a compile, and a real compile in a sibling
directory is still caught while the archive beside it is not. 49 passed.

* Require the media status guard to precede the write, not merely exist

The early-return spelling this test started accepting is only equivalent when the guard runs
FIRST. Checking presence alone let

    setStatus(next);
    if (ticket !== statusTicket.current) return;

pass, which publishes the superseded status before returning and is the exact bug the test
exists to catch. Confirmed by building that page and watching all four tests pass.

The guard's match index must now come before the first setStatus(. The inline
'if (a === b) setStatus(next);' form satisfies it by construction. Verified against main,
against #10788's early-return form, and against both regressions (write-then-guard, and the
guard deleted outright), which now fail.

* Unblock the desktop leg, require a bare stale return, pin the MLX loader entry

Windows No Compiler CI: with the artefact detector fixed, the positive control and the shell
leg both pass for the first time, and the desktop leg then failed on something that had been
hidden behind them. Under $ErrorActionPreference = 'Stop', a native command writing ANY line
to stderr raises NativeCommandError, and install.ps1 --tauri reported

    [TAURI:ERROR_CLEAR] create virtual environment recovered

which is the installer saying it recovered. That killed the step before either detector was
read. Both legs now drop to 'Continue' around the child only; the exit code stays the gate,
which for the desktop leg is deliberately not checked at all, so a stderr line failing it was
never the intent.

media-status-sequencing: requiring the guard to precede the write still accepted
'if (ticket !== statusTicket.current) return setStatus(next);' ahead of the normal write,
which publishes the superseded status out of the return expression. Confirmed by building
that page and watching all four tests pass. The stale branch's return must now be bare.
Verified against main, against #10788's form, against a braced early return, and against
three regressions (return-with-write, write-then-guard, guard deleted), which all fail.

scan_packages baseline: the appended unsloth_zoo/mlx/loader.py entry is pinned to its
reviewed file, matching the compiler.py entry beside it. The obfuscation check's evidence is
the __import__/eval lines and the import TARGET is a variable, so it sits outside the
evidence: a changed target would leave evidence_hash intact and keep the finding suppressed.
Scan still exits 0 with 17 suppressed and no active CRITICAL or HIGH.

* Do not score the positive control's own compile against the installer

With the desktop leg unblocked, the shell leg failed reporting

    the installer spawned 1 compiler process(es)

on a cvtres.exe created by csc.exe at 12:49:23, about a second before the step began. That is
the positive control from the step above: it compiles a type on purpose, and the 4688 window
starts a second early, so its compile fell inside the installer's lookback.

The hits already present when the action has not yet started are recorded and subtracted by
identity. Moving the floor to 'now' instead would have given up what that second is for,
which is keeping a process created in the same tick as the floor from being dropped.

Also closes the last hole in the media sequencing guard: guarding the first setStatus while a
second sits unguarded after it leaves every stale response overwriting the status. The
callback must now write exactly once. All three pages have exactly one write today, #10788
included, and an added second one fails.

* State WHEN the collapsed sidebar leaves the accessibility tree, not that it does

Asking only that the held-out condition still appears in the expression accepts dropping
the peek exception along with it, and a peeked sidebar is on screen: aria-hidden and inert
on a visible, focusable panel is the same defect the assertion guards, pointing the other
way.

So expand the attribute expression down to its four inputs and compare the whole truth
table against the one this contract wants: removed exactly when pin mode is on, the sidebar
is unpinned, it collapses to zero, and it is not being peeked at. Any spelling admitting
exactly those states passes, so the rename, the rewrap and the hoisted const that broke the
old exact-string form are all invisible; dropping the peek exception, dropping inert,
dropping collapseToZero and inverting the exception all fail.

expand_bindings stops at the four inputs rather than walking to the bottom. hasPinMode is
itself a const further up, and expanding it too drags in the prop plumbing that decides
whether pin mode exists at all, which belongs to a different component. boolean_table
refuses anything that is not names, && || ! and parentheses, so a comparison cannot be
quietly mistranslated on the way to Python.

Also pins the OpenML suppression to the file it was reviewed against. The hashed evidence
is the bare 'while True:'; what makes the loop benign is the retry counter, the decrement
and the two re-raises around it, all outside that line. Removing the bound would have left
the entry suppressing. Verified against scikit-learn 1.9.1: it still suppresses, and one
flipped digit reopens the CRITICAL.

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

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

* Wait for the find bar to settle instead of sleeping 200ms at it

Frontend build + bundle sanity went red on a commit that touched a PowerShell script and a
node test, on 'chromium/Linux: the chord re-focuses the field instead of closing', 177/178.
The check presses the chord, sleeps a flat 200ms and reads the state; open_bar right above
it already waits on a condition, with a comment about the first open crossing a lazy
boundary. The same boundary is in front of this press, so on a loaded runner the sleep
expires first and the check reports a defect that is not there.

It now waits for open && focused, and Escape waits for the bar to be gone rather than
sleeping 250ms. Neither wait asserts anything: a bar that never settles spends the timeout
and then fails on the same check with the same message, so a real break is still reported
and only the speed of the machine stops being part of the contract.

Verified both directions: 178/178 unchanged, and with requestFocus mutated into a toggle
(setOpen(was => !was), which is literally 'closes instead of re-focusing') the check fails
in all four engine modes.

* Require the status write to survive the stale branch, not just follow it

Ordering says the write comes after the early return. It does not say the write is still
reached: `if (ticket !== statusTicket.current) { return; setStatus(next); }` returns first
and satisfies the guard regex, the ordering rule and the exactly-one-write rule while
publishing nothing at all.

When the stale branch carries a block, the write now has to live past the end of it. The
`ticket === current` spelling needs no such rule, since its pattern already ties the write
to the guard.

Mutations: the stranded write fails, a braced early return with the write after the block
passes, the braceless #10788 form passes, and dropping the guard outright still fails.

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

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

* Score a compile once, at its root, not at every process in the chain

The timestamp baseline did not hold. The shell leg failed again on the same cvtres.exe, and
the reason it survived the subtraction is that the Security log is written with latency:
the positive control's csc.exe started before the installer's window opened, its cvtres.exe
child landed just inside, and NEITHER was in the log yet when the baseline was read. There
was nothing to subtract. No arrangement of timestamps wins that race.

So attribute by the chain instead. A compiler started by a compiler is a step of a compile
that is already being scored, not a new one: csc.exe shells out to cvtres.exe to build its
resource blob, and counting that as a second hit says the action compiled twice. Reading
ParentProcessName off the record settles the cross-step bleed for good, because the child
is the only part of the control's chain that was ever in range.

Detection is unchanged for a compile the action really starts. Its root compiler is spawned
by the installer's shell, not by another compiler, and the window opens before the action
does, so the root is in range and is reported. What this drops is only ever the second
process of a chain whose first was already seen or was never in range at all. An orphaned
cvtres.exe with a non-compiler parent still counts, and a record from a schema with no
ParentProcessName at all still counts, so an empty field is not read as a compiler parent.

Four tests, covering each of those: the shell's compile, the orphaned resource step, the
compiler's own resource step, and the pre-ParentProcessName schema. 53 pass.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Sep 13, 2026
…adratic (#10868)

test_deepseek_r1_huge_fenceless_body_is_linear failed on #10864 at 6.56 against
a bar of 6.0, on a branch that touches no parser code. It failed the same way on
#10825. The parser is fine: measured locally across all four shapes the median
4x ratio is ~4.0, which is what linear looks like.

The measurement is what is wrong. _growth computed

    min(big over repeats) / min(small over repeats)

and its comment claimed that dividing one minimum by the other cancels the
machine out. It does not. The two minima come from two batches run at different
times, so a quiet window during the small batch and a busy window during the big
batch multiply rather than cancel, and the quotient of two separately-taken
minima is not a minimum of anything.

Measured on 2 pinned CPUs under load, 15 trials per shape:

    strategy        R1        R1-distant  GLM       V3        >= 6.0
    min/min         max 8.69  max 8.23    max 8.27  max 8.59  7 of 60
    paired median   max 4.26  max 4.83    max 4.83  max 5.42  0 of 60

End to end, 10 contended runs of the four linearity tests: the old form fails
3 of 10 runs, the new form 0 of 10.

Each pair now times the small input and then the big one back to back and forms
the ratio inside the pair, so contention hits both halves and divides out, which
is what the old comment claimed for the unpaired form. The median across pairs
then discards one that got unlucky in either direction.

Detection is kept, which is the half worth checking before loosening a bar.
Sabotaging the R1 sweep back to quadratic (re-adding a per-marker tail rescan)
still fails, at 14.2x and 15.3x. On a synthetic 16x path the new form reports
8 of 8 over the bar, the same as the old one. On the marginal 6.7x shape
(#10832's partially fixed sweep) it reports 9 of 12 against the old 10 of 12,
a difference well inside the noise at that sample size, and that shape's sibling
test measures 12.2x when broken, so the suite still catches it.

The bar stays at 6.0. Nothing here loosens the threshold; it only stops the
measurement fed to it from being dominated by whoever else is on the runner.

The 60 second backstop still reads the BEST big time rather than the worst, so
it fires on a path that is genuinely too slow and not on a runner that stalled
once.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 14, 2026
unslothai#10868 replaced the linearity check in test_pr5624_regressions.py after it
failed on unslothai#10825 and again on unslothai#10864 at 6.56 against a 6.0 bound, both times on
branches that touch none of that code. The same shape is elsewhere in the suite:
sub-100ms budgets, two separately-taken durations compared against each other,
and concurrency proved by how long four threads took. All of them run under
pytest -n 4 on a shared runner, where descheduling is indistinguishable from the
regression they guard.

Each one is rewritten to assert the thing it is named for.

test_llama_cpp_wait_for_vram_settle.py has five, all of them claims about the
helper's sleeping: did it skip the wait, nap once per poll, clip the last nap to
the deadline. Record the durations it asks for and assert on those. The tightest
was elapsed < 0.05 around a short-circuit, which one GC pause exceeds.

test_account_model_access.py proved eight probes ran together by taking under
0.4s. Its own sibling two functions up already uses a threading.Barrier for the
same claim, so use one here too, sized off _PROBE_FANOUT so lowering the fan-out
fails this rather than satisfying a Barrier(1).

test_mcp_http_sessions.py had three. Two chats running concurrently needed a
counter that spans clients, since no single client's max_live can see an overlap
between two of them; six parallel closes get a Barrier(6), so a serial close
deadlocks and says so instead of merely running slowly; and the eviction test
asserts the caller returned while the victim's teardown was still running, which
is the property the 0.5s bound was standing in for.

test_stream_cancel_registration_timing.py compared two separately-taken
durations, exactly what unslothai#10868 had to remove from _growth. The two patterns
differ in chunks seen, deterministically: the blocking loop never lets the cancel
through and drains all eight, the awaiting loop stops at the first.

Four guards against a quadratic blow-up carried absolute budgets
(test_tool_xml_strip.py, test_update_release_notes.py, test_rag_store.py).
Backtracking is superlinear by definition, so growth is the property, and
unslothai#10868's paired-ratio statistics already exist for it. Lift _growth and
_assert_linear out of test_pr5624_regressions.py into tests/_shared/growth.py,
generalised over the function under measurement, next to real_accelerator.py and
for the same reason.

test_profile_stats.py and the two liveness files keep a wall-clock bound, because
"it did not block" is what they mean, but a generous one: the sharp claim in each
is already asserted next to it (the row count is zero, stop() returned False, the
stub raises if detection starts).

test_backend_ci_parallel_isolation.py scans for this shape and required three
named files to keep exhibiting it, which made it a second, invisible reason those
files could not be fixed: rewriting the vram-settle bounds failed there, in a file
about CI topology, with a message about a sample. It builds all three shapes
itself now.

Not touched: test_health_answers_within_probe_budget.py. Its bounds are the
subject, derived from the real desktop probe timeout rather than from a guess,
and it already asserts on state where state was the honest answer.

Each rewritten assertion was checked against a deliberately broken
implementation: no cold-start short-circuit, an unclipped sleep, a one-shot wait
loop, _PROBE_FANOUT of 1, _MAX_CLOSE_THREADS of 1, and two synthetic quadratic
sweeps. Full backend suite run the way CI runs it, three times: identical failure
set to main.
danielhanchen added a commit that referenced this pull request Sep 14, 2026
#10897)

* Stop ten test assertions from measuring the runner instead of the code

#10868 replaced the linearity check in test_pr5624_regressions.py after it
failed on #10825 and again on #10864 at 6.56 against a 6.0 bound, both times on
branches that touch none of that code. The same shape is elsewhere in the suite:
sub-100ms budgets, two separately-taken durations compared against each other,
and concurrency proved by how long four threads took. All of them run under
pytest -n 4 on a shared runner, where descheduling is indistinguishable from the
regression they guard.

Each one is rewritten to assert the thing it is named for.

test_llama_cpp_wait_for_vram_settle.py has five, all of them claims about the
helper's sleeping: did it skip the wait, nap once per poll, clip the last nap to
the deadline. Record the durations it asks for and assert on those. The tightest
was elapsed < 0.05 around a short-circuit, which one GC pause exceeds.

test_account_model_access.py proved eight probes ran together by taking under
0.4s. Its own sibling two functions up already uses a threading.Barrier for the
same claim, so use one here too, sized off _PROBE_FANOUT so lowering the fan-out
fails this rather than satisfying a Barrier(1).

test_mcp_http_sessions.py had three. Two chats running concurrently needed a
counter that spans clients, since no single client's max_live can see an overlap
between two of them; six parallel closes get a Barrier(6), so a serial close
deadlocks and says so instead of merely running slowly; and the eviction test
asserts the caller returned while the victim's teardown was still running, which
is the property the 0.5s bound was standing in for.

test_stream_cancel_registration_timing.py compared two separately-taken
durations, exactly what #10868 had to remove from _growth. The two patterns
differ in chunks seen, deterministically: the blocking loop never lets the cancel
through and drains all eight, the awaiting loop stops at the first.

Four guards against a quadratic blow-up carried absolute budgets
(test_tool_xml_strip.py, test_update_release_notes.py, test_rag_store.py).
Backtracking is superlinear by definition, so growth is the property, and
#10868's paired-ratio statistics already exist for it. Lift _growth and
_assert_linear out of test_pr5624_regressions.py into tests/_shared/growth.py,
generalised over the function under measurement, next to real_accelerator.py and
for the same reason.

test_profile_stats.py and the two liveness files keep a wall-clock bound, because
"it did not block" is what they mean, but a generous one: the sharp claim in each
is already asserted next to it (the row count is zero, stop() returned False, the
stub raises if detection starts).

test_backend_ci_parallel_isolation.py scans for this shape and required three
named files to keep exhibiting it, which made it a second, invisible reason those
files could not be fixed: rewriting the vram-settle bounds failed there, in a file
about CI topology, with a message about a sample. It builds all three shapes
itself now.

Not touched: test_health_answers_within_probe_budget.py. Its bounds are the
subject, derived from the real desktop probe timeout rather than from a guess,
and it already asserts on state where state was the honest answer.

Each rewritten assertion was checked against a deliberately broken
implementation: no cold-start short-circuit, an unclipped sleep, a one-shot wait
loop, _PROBE_FANOUT of 1, _MAX_CLOSE_THREADS of 1, and two synthetic quadratic
sweeps. Full backend suite run the way CI runs it, three times: identical failure
set to main.

* Size the growth fixtures off the old bound, and derive the liveness ceilings

Two review findings, both right.

assert_linear measures units AND units * factor, so replacing an absolute budget
means passing the old size divided by factor. Three of the five conversions did
that; the backtick-run and orphan-opens ones did not, and their big leg ran at
4x anything previously measured. That matters only on the regression each guards:
the backtick parser took over a minute at 20k when broken, so at 80k it would
take about sixteen, and the job timeout would kill the run before the ratio could
say why. The big < 60.0 backstop cannot help, because it is checked after the
measurement rather than during it. Both call sites now put the previously
measured size on the big leg, and assert_linear says so where a caller reads it.

The liveness ceilings were widened to a number with no relation to the product.
commands.rs gives each watchdog probe HEALTH_PROBE_TIMEOUT, ten seconds, so a
route that blocked for 10 to 29 seconds passed the test while timing out every
real probe. Read that constant, as test_health_answers_within_probe_budget.py
already does for its own budget, and use half of it: ten times the headroom of
the 0.5s it replaces, and provably inside what the launcher allows.

* Tighten the comments this branch added

* Pin two timing assertions to what they are about, not to slack

The eviction test's victim slept 1.5s, which a caller only had to outwait part of
to read as prompt; it now holds its teardown on an event the test releases, so a
caller that waits on it at all cannot return, and the remaining ceiling comes
from _SESSION_CLOSE_TIMEOUT rather than being picked.

The writer shutdown test now records the timeout stop() hands its join instead of
allowing 5s of wall clock, so a stop() that waits whole seconds fails even though
the elapsed budget would have passed it.

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

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

* Assert both ends of the settle window, and stop buying slack this leg does not need

The never-settles case only checked that the helper napped more than once, so a
loop capped at two iterations recorded [0.1, 0.1] and passed while the VRAM was
still moving. Both ends are now read off the recorded naps.

The terminal-callback bound goes back to 1.0s: studio-backend-ci.yml ignores
test_profile_stats.py in the -n 4 leg and reruns it serially, so a looser bound
only lets a stalling callback through.

* Bound liveness against a route that does nothing, not against the watchdog

Half the watchdog's probe budget is 5s, which passes a route that grew seconds of
synchronous work on the event loop. The probe snippets now serve a route that only
returns a dict through the same app and client, so both pay the same interpreter and
scheduler and what is left is the route's own cost.

The watchdog bound stays as the second half of the pair: a relative bound cannot
see an absolute timeout, since a control that took seconds would scale with it.

* Bound the eviction call against the same call with nothing to evict

Half of _SESSION_CLOSE_TIMEOUT is five seconds, which passes a caller that blocks
for a second before handing the victim to the cleanup worker. The cap is now
applied after a control call on a second URL, so the two differ only in whether an
eviction happens and the claim is measured rather than budgeted.

* Take the runner out of the clipping test, abort a known-slow growth run, drop a live dependency

The slow-probe test asked for a nap that a correct helper need not make: if the
scheduler ate the 0.1s left of the budget it returned at the deadline check instead,
and the assertion failed on a good run. It now runs on a clock the test moves, so
the probe charges its cost instead of sleeping and every sample is exact.

growth() takes abort_over_s, so a big leg already over the backstop stops the
repeats instead of measuring the same known-bad path three times.

The parallel-isolation meta-test no longer requires the live backend suite to still
contain a fragile assertion; the synthetic files cover every shape, and that
requirement would have turned cleaning the last one into a failure.

* Pair the liveness controls, clock the drift test, ask the eviction by thread

A control taken in its own batch shares no scheduler delay with the request it is
compared against, so a pause landing on the measurement alone was not divided out
and the 50ms floor made that stricter than the bound it replaced. Both liveness
snippets now alternate control and measurement and take the best of three on each
side.

The never-settles test moves to the same fake clock as the slow-probe one: its lower
bound says the helper did not stop early, and real time spent outside sleep()
retires the deadline without appearing in the naps.

The eviction test asks which thread calls close() instead of how long the caller
took. __aexit__ cannot answer it, since that always runs on the session's own loop
thread, but the caller of close() is exactly the claim in the test's name.

* Size the close barrier off the fan-out, and watch the join as well as the close

A fixed Barrier(6) deadlocks a correctly batched close configured any narrower than
six and then reports it as serial. It now waits for one batch and opens exactly that
many sessions, so a partial last batch cannot leave stragglers waiting for a party
that never arrives.

The eviction test also records joins on the cleanup worker. Handing the teardown off
and then waiting on the worker anyway spends the same deadline, and nothing else here
can see it: a bounded join leaves the close off the calling thread and the session
still open.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants