Skip to content

Studio: stop declaring a live backend dead, and keep a crashed worker's stderr - #11070

Merged
danielhanchen merged 41 commits into
mainfrom
pr/studio-updater-and-worker-stderr
Sep 17, 2026
Merged

danielhanchen merged 41 commits into
mainfrom
pr/studio-updater-and-worker-stderr

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

Summary

Two Unsloth Desktop failures where the app tells the user something it has not established.

The first is the one in #10520: "Unsloth isn't running -- please relaunch it." in front of a backend that was listening and healthy the whole time. The second is the one in #7843: an inference worker exits on the first generation and the user is shown "Details: pid=6145, exitcode=1." with no cause, while the worker's own traceback exists and is simply thrown away.

Root cause

The health verdict (#10520). The webview's fetch retry ladder was the shortest timer in the app. studio/frontend/src/features/auth/api.ts retried a failed fetch after 250ms, 750ms and 1500ms and then gave up, against HEALTH_PROBE_TIMEOUT of 10s that studio/src-tauri/src/commands.rs spends on a single liveness probe, and three of those that its watchdog spends before it will call a backend dead. Any condition that delays the loopback handshake past 2.5s therefore produced a UI verdict of "not running" while the launcher still considered the backend perfectly alive: a per-process firewall filter, which is what the report describes, but equally a multi-GPU warm-up holding the GIL while the ML stack imports.

The second half is that the verdict was reached without a second opinion. A failed fetch inside the webview is not proof that the backend died, and "please relaunch it" is an instruction that throws away a running backend and an in-flight generation. The launcher is in the same app, owns the backend process and can probe it from the native side with proxies disabled, and it was never asked.

The worker crash message (#7843). The inference worker is a multiprocessing spawn child that inherits the server's stderr. When such a child dies from an unhandled exception, the traceback multiprocessing prints travels down that inherited handle and never through the response queue, so _subprocess_crash_message in studio/backend/core/inference/orchestrator.py had an exit status and nothing else. It special-cases signals and the OOM killer, and for a positive exit code it returned only pid=..., exitcode=.... Preserving the underlying exception is literally the issue's "Expected".

Changes

Health verdict:

  • The retry ladder becomes 250, 750, 1500, 3000, 5000ms, which sums to 10.5s, just past one native probe budget, so the webview can no longer be the first thing in the app to give up.
  • Before claiming the backend is gone, the transport-failure path asks the existing check_health Tauri command. When it answers that the backend is up, the user is told it is busy and may still be starting, not told to relaunch. The probe is single flight: this condition takes out every panel at once, and each loss would otherwise open its own 10s probe.
  • A Rust test, the_frontend_retry_ladder_outlives_one_probe_budget, parses the ladder out of the TypeScript with include_str! and fails if it ever drops back below HEALTH_PROBE_TIMEOUT, so the two numbers cannot drift apart again.
  • isExpectedBackgroundChatStorageError now reads the transport marker rather than one exact wording, so a background chat sync against a backend that is merely busy is not reported as an unexpected error.

Worker crash message:

  • New studio/backend/utils/worker_stderr.py. The parent opens a sink and hands its path to the child through a reserved keyword argument, the shared child entrypoint tees file descriptor 2 into it, and the parent reads the tail back after the worker is gone. The tee keeps writing through to the inherited stderr, so the server log keeps exactly what it had.
  • The mirror is installed at the file-descriptor level, not by replacing sys.stderr, so a worker that dies inside a C extension is still captured. Encoding is probed rather than assumed, so a Windows worker's cp1252 CRLF output reads the same as a Linux or macOS worker's UTF-8. The sink is bounded at 256 KiB and retired when the next worker is spawned.
  • Everything in that path is best effort. A mirror that cannot be installed, a sink that cannot be written and a tail that cannot be read all degrade to exactly the previous message rather than turning a diagnosable crash into a failure to start.

Compatibility

Installs that are already out there are the main thing this had to get right, since one of the two issues is in the Desktop app itself.

Concern Evidence Result
Other workers that pass no sink run_without_native_path_secret is the shared entrypoint for the inference, export, training, data-recipe, speech and diffusion-quant workers. Only the inference orchestrator opens a sink; the keyword argument is popped with a default. pass, test_a_caller_that_passes_no_mirror_is_unchanged reproduces the old message byte for byte
The reserved argument reaching a worker The entrypoint consumes it before dispatch. pass, test_the_reserved_kwarg_is_consumed_and_never_reaches_the_entrypoint asserts the worker sees []
A webview newer than the shell it runs in check_health is a command the shipped launcher already registers and use-tauri-backend.ts already invokes in this exact shape. A shell that rejects the invoke falls back to the previous message. pass, a check_health that throws leaves the original verdict in place
Updating an existing install start_backend_update stops the backend on purpose, and use-tauri-update.ts drives the whole update over Tauri commands and events, with no authFetch and no fetch of its own. The changed path is never entered. pass, updating an existing install does not go through the changed path pins it
Studio in a browser (the pip install) The native probe is behind isTauri, so the web build takes the same branch it always took, including the offline message. pass, the existing auth suite is unchanged
Time-sensitive polls Training, images, Xet and iGPU notices already pass retryNetworkErrors: false and so never climb the ladder at all. On a genuinely stopped backend a loopback connect is refused immediately on every platform, so the native probe answers at once rather than spending its budget. no added latency on a dead backend
Windows, Linux, WSL and macOS temporary directory shapes The sink is created wherever the install's temporary directory already is, including a Windows profile path with spaces and an accent, the same path reached through /mnt/c under WSL, and a generated macOS /var/folders path. pass, test_the_sink_works_on_every_install_path_shape, four shapes

Version matrix, mStudio (Python 3.13.12, torch 2.10.0+cpu, transformers 5.4.0, trl 0.29.1, peft 0.18.1):

step main this branch
worker stderr and crash message tests not resolvable, the file is added here pass, 25 tests
shared entrypoint consumers, 11 files pass pass
Studio frontend contracts, 5 files pass pass
repro for #7843 fail, the message carries only an exit status pass, the message carries the worker's stderr
frontend transport tests not resolvable, the file is added here pass, 8 tests

Release safety

An existing user who never meets either bug has to see no difference, before, during or after
updating, so that was measured rather than asserted.

Nothing in the update path changes. The diff is twelve files under studio/backend,
studio/frontend, studio/src-tauri and tests/studio. It touches no installer, no packaging
file, no release workflow and tauri.conf.json not at all, so the Desktop asset names and the
latest.json updater endpoint are unchanged by construction.

Updating a real prior release. v0.1.807-beta was installed into a scratch
UNSLOTH_STUDIO_HOME and then updated by running this branch's installer over it. The venv was
reused rather than rebuilt, the three transformers sidecars reported current, llama.cpp and
whisper.cpp reported prebuilt up to date, and the file tree gained three paths, all of them
written by main's installer and read only by it and studio/install_manifest.py. This PR adds
no marker, no metadata file and no schema, so there is no field for an older marker to be
missing. The old home had no install manifest and the new installer met that absence and
completed.

Interrupted and repeated. An update killed mid-flight rolled itself back unprompted and
left a zero-line tree delta; re-running converged to the identical tree. Five installer runs over
one home converged, and studio.db, auth/auth.db and auth/.bootstrap_password stayed
byte-identical through all of them. The updated Studio starts and answers /api/liveness with
200, and its database still opens with all 27 tables.

Processes. Nothing here selects a process by pid, process group or tree. The worker is
reached through the multiprocessing.Process handle the orchestrator already held, and its
stderr through a file the orchestrator itself created, so no reused identifier can answer
wrongly. The blast radius on a machine with long-lived work is zero processes. The sink is
retired before the next worker is spawned, so a tail can only come from the worker that crashed,
and cleanup names the exact paths this process opened rather than sweeping the directory by
prefix, which would take out another Studio's live sink. A test fails if that module ever grows
a directory sweep.

Routing, checked structurally rather than read. Parsing both trees and diffing the branch
structure: 72 of 74 functions in orchestrator.py, 23 of 24 in native_path_leases.py, 15 of
18 scopes in api.ts and 89 of 90 in chat-history-storage.ts have an identical branch
structure, and no function was removed. Each new predicate is entered only by inputs that
previously reached a dead end: no sink means the previous message character for character, no
tail means the previous message character for character, and a check_health that cannot be
asked means the previous wording. On every platform a stopped backend refuses the loopback
connection immediately, so the probe costs nothing when the backend really is gone.

One thing does change for every user and is worth stating: each inference worker spawn now also
creates one temporary file, one pipe and one daemon thread in the child, and the child's stderr
passes through that pipe before reaching the inherited handle. Nothing is dropped, and a test
asserts the server log still receives it.

Platforms. Staged in parallel across four owners: ubuntu-latest 228 passed, macos-15
(Apple Silicon) 228 passed, windows-latest 227 passed and 1 skipped, and for platforms this does
not touch, ubuntu-24.04-arm 228 passed, macos-15-intel 228 passed, ubuntu-22.04-arm 228 passed.
macos-26 228 passed. windows-11-arm could not install the backend requirements at all, before
any test ran, because not every wheel in that file is published for Windows ARM64. The
full node suite is green through the repo's own Frontend CI, which installs the frontend's npm
dependencies first. WSL is not a hosted runner, so it was covered locally with a
/mnt/c/Users/... shaped temporary directory and is labelled as such.

What is not proven: the Desktop in-app update itself, meaning a signed prior bundle replaced by
tauri_plugin_updater on macOS, Windows or Linux, which no host available here can do. What
stands in for it is that this PR changes no file involved in that update, that the Studio
installer path from the same tag updates cleanly, and that the Tauri command the frontend now
calls is one the shipped launcher already registers and answers in this shape.

Tests

New:

  • studio/backend/tests/test_inference_worker_stderr_tail.py, 25 tests: the decoder over Windows cp1252 CRLF, UTF-8, undecodable bytes and progress bars redrawn with carriage returns, the tail bounds, the sink's size bound, the message the orchestrator builds for positive, signalled and still-running workers, a real spawned worker driving the real shared entrypoint, the no-sink caller, and the four install path shapes.
  • studio/frontend/tests/tauri-backend-transport-failure.test.ts, 8 tests: a real loopback server that starts accepting at 3s, which the old ladder never reached and the new one does, the launcher-says-alive and launcher-agrees-dead verdicts, an unregistered command, no validated port yet, the single-flight probe, the update flow, and the background storage filter.
  • the_frontend_retry_ladder_outlives_one_probe_budget in studio/src-tauri/src/commands.rs, run by cargo test in the existing Tauri smoke workflow on Linux, Windows and macOS.

Moved with the code they read: the auth transport contract in tests/studio/test_model_picker_contracts.py now counts tags against the helper's own raises instead of a fixed number of two, and the stub in tests/studio/test_auth_form_input_count.py exports getApiPort, which an ES module import needs present whether or not the web build ever calls it.

Run on Python 3.13:

studio/backend:  pytest -q -n 4 --timeout=330 tests
                 17 failed, 46608 passed, 296 skipped, 15 errors
                 main on the same host: 14 failed, 46583 passed, 299 skipped, 15 errors
studio/frontend: node --experimental-strip-types --test "tests/**/*.test.ts"
                 7719 passed, 0 failed
repo:            pytest -q -n 4 tests/studio tests/security/test_release_desktop_appimage.py
                 496 passed, 17 skipped

The failures in the backend run are the families this host fails on main too: test_studio_api cannot reach the network, test_account_tool_confinement depends on landlock and fails a different subset on every run on both trees, and multi_account, test_gpu_arch_gate_consumers_7624, test_kv_cache_estimation, test_media_model_index_accounts, test_offload_planner_seam, test_text_io_encoding and test_tunnel_safe_long_post fail identically on main. None of them touch the files here, and CI already excludes several of them.

Evidence

Kept beside the report: the repro for #7843 run against main and against this branch, the full backend suite on both trees, the full frontend suite, the repo-level Studio contract suites, and the matrix results and summary.

Known limitations

  • The new ladder means a Desktop webview that has genuinely lost its backend now takes up to 10.5s to say so instead of 2.5s, on the paths that opted into network retries. That is the trade the issue asks for: the alternative is telling a user with a healthy backend to relaunch it.
  • The native probe is a Tauri command, so Studio in a browser gets no second opinion and keeps its previous wording. It also has no launcher to be wrong about.
  • A worker killed outright, by the OOM killer or by SIGKILL, usually writes nothing before it goes, so its message is unchanged apart from the existing memory-pressure hint.

Fixes #10520
Fixes #7843


UI evidence

The worker crash message in this PR changes what Studio SHOWS. _subprocess_crash_message is
what the load route puts in its HTTP body, and the chat header renders that string verbatim in
its error chip, with the whole sentence in the chip's popover. Before/after screenshots from two
isolated installs are below.

Before / after

worker crash message, before and after

Two isolated installs built by this PR's own install.sh --local: BEFORE is the merge base
2ab07c9c4, AFTER is e210ef389. One scene drives both. It asks the real server to load
unsloth/Llama-3.2-1B-Instruct, waits for the worker that load spawns, and aborts that worker a
couple of seconds into its startup with SIGABRT, which is what a bad driver, a GPU fault during
initialisation or an incompatible native library do to it. The pid signalled is asserted against
the pid the message reports, so a run that signalled anything else fails rather than producing a
pair.

The same pair in the whole window, with the chip truncated in the header as a user first meets it:

the chat page carrying the crash, before and after

Read off the same servers that were photographed, through POST /api/inference/load, rather than
off the picture:

BEFORE (merge base) AFTER (head)
message Failed to load model: The inference worker stopped unexpectedly while loading the model. Details: pid=..., signal=SIGABRT, exitcode=-6. the same sentence, then Worker error output: and the runtime's own dump
message length 139 chars 1037 chars
Worker error output: present no yes
lines under that heading 0 17
first line under it none Fatal Python error: Aborted
popover text in the shot 151 chars 802 chars, 13 lines of dump

The AFTER dump names where the worker died -- detect_hardware inside
run_inference_process -- and every absolute path in it is shortened to .../<file>, which is
_redact_worker_output doing its job on a string that leaves the host.

Three things this pair cost, which are worth stating because they bound the claim.

The capture only reaches the user when the diagnostic fits the tail. _worker_stderr_tail reads
the last 20 lines and 4000 characters, and _public_worker_stderr_tail keeps an indented frame
only as the continuation of a diagnostic line it already kept. A worker interrupted
mid-generation dies with a 27-line KeyboardInterrupt traceback: the
Traceback (most recent call last): header falls outside the window, the bare
KeyboardInterrupt line carries no colon to start a new diagnostic, and the message comes out
byte-identical on both builds. A worker aborted once the ML stack is loaded writes a
faulthandler dump ending in an Extension modules: ... line thousands of characters long,
which on its own exceeds the character budget. Aborting the worker EARLY, during the load, is
what leaves a dump the window can hold; the scene retries until it gets one, on a rule that reads
only the worker's own output and so runs identically on both sides.

A worker killed while IDLE never reaches this message at all. The next request answers
Inference subprocess is not running, from a different path.

PYTHONFAULTHANDLER=1 was set on both Studios. Without it an aborted worker writes nothing at
all, and neither build can show a cause it was never given.

Recordings of the two runs, BEFORE then AFTER:

BEFORE run

AFTER run

Still true at the current head

The pictures above are of e210ef389. 3a30972c6 was installed into a third isolated home and
driven by the same scene: the message is the same shape, 1037 characters with 17 lines under
Worker error output: beginning Fatal Python error: Aborted, so the path-delimiter and
crash-selection changes since do not move this surface.

Browsers

The message is a backend string the chip renders verbatim, so the surface was driven in four
engines against the AFTER Studio. WebKit here is Playwright's WebKit, not Safari: no host
available here can automate Safari, and calling it that would be a claim this run cannot make.
Edge is the real Edge binary through channel="msedge".

engine version chip rendered popover rendered carried Worker error output:
Chromium 153.0.8010.12 yes yes, 151 chars not in this run's crash
Firefox 155.0 yes yes, 201 chars yes, Fatal Python error: Aborted
WebKit 26.6 yes yes, 151 chars not in this run's crash
Edge (msedge) 151.0.4129.59 yes yes, 151 chars not in this run's crash

All four render the chip and its popover. Whether a given run's message carries the extra block
depends on the crash that run sampled, not on the engine, for the reason above; the before/after
pair is where that half is established, and Firefox reproduced it independently.

Platforms

Cross-platform CI for this PR was run off the org queue on an owned staging repo, restaged at
the current head 3d57464bf, with the counts read from the run logs:

runner result at 3d57464bf
ubuntu-latest pass, 363 passed; node 10 pass / 0 fail
macos-15 (Apple Silicon) pass, 363 passed; node 10 pass / 0 fail
windows-latest pass, 360 passed / 3 skipped; node 10 pass / 0 fail
Unsloth Tauri CI pass

The Rust half is compiled by Unsloth Tauri CI, which is a separate workflow from the three
legs above; at the earlier heads its runs were cancelled by the org queue rather than
completed, so the branch had nothing that had compiled commands.rs. It has now run to
completion on the staged branch at this head, so that gap is closed.

Two Windows failures were found and fixed on the way here rather than argued away. One was a
test in this PR asserting SIGKILL in a crash message: signal.Signals(9) raises on Windows,
so the message says SIG9 there, and the assertion now accepts either spelling and pins the
exit code, which both platforms share. The other was a node --version probe with a five
second timeout, which a cold Windows runner does not always meet; the probe now allows more
time and treats a timeout as a skip, since it exists to answer an availability question
quietly.

Three org workflows are red on the staged branch and none of them is this PR:
Frontend CI fails 1 of 7761 on "every locale keeps the shortcut in the threshold
description", studiobench CI fails 1 of 1403 on the shipped composer's queue buttons, and
Workflow trigger lint fails on the staging branch's own generated workflows. None of the
three touches anything this PR changes: a locale string table, the shipped composer bundle,
and the staging harness itself. The Frontend CI one was observed identically on an unrelated
staged branch earlier the same day.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 16, 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-17T12:38:20.980442Z 463fbda 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 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen
danielhanchen force-pushed the pr/studio-updater-and-worker-stderr branch from 8d532c6 to 75b6db0 Compare September 16, 2026 04:17
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 16, 2026
…'s stderr

Two Desktop failures where the app reports something it has not established.

Desktop health probe (#10520). The webview's fetch retry ladder was the shortest
timer in the app: 250 + 750 + 1500ms, against the 10s the launcher spends on a
single liveness probe and the three of those its watchdog spends before it will
call a backend dead. So on a host where the loopback handshake is delayed, by a
per-process firewall filter or by a multi-GPU warm-up holding the GIL, the UI was
the first thing to give up and told the user to relaunch an app the launcher still
considered healthy. Widen the ladder past that per-probe budget, and ask the Rust
check_health command before claiming the backend is gone: it probes from the native
process, with the launcher's budget and no proxy, so it answers where the webview's
fetch was starved or refused. When it answers that the backend is up, the user is
told it is busy rather than told to relaunch. The probe is single flight, because
the condition takes out every panel at once and each loss would otherwise open its
own. A Rust-side guard pins the ladder to the probe budget so the two cannot drift
apart again.

Worker crash reporting (#7843). The inference worker is a spawn child that inherits
the server's stderr, so a worker that dies from an unhandled exception has its
traceback printed onto that inherited handle and never through the response queue.
The orchestrator was left with an exit status and no cause, and surfaced exactly
"Details: pid=6145, exitcode=1." Give each worker a sink that the shared child
entrypoint tees file descriptor 2 into, keeping the write-through to the inherited
stderr so the server log is unchanged, and append the tail of it to the crash
message. Encoding and line endings are probed rather than assumed, so a Windows
worker's cp1252 CRLF output reads the same as a Linux or macOS worker's UTF-8. The
sink is bounded and retired when the next worker is spawned.

Installs that are already out there are unaffected either way. The reserved keyword
argument is consumed by the shared entrypoint and never reaches a worker, and the
export, training, data-recipe, speech and diffusion-quant workers pass none, so they
run exactly as before. check_health is a command the shipped launcher already
registers and already answers in this shape, and a shell old enough to reject the
invoke falls back to the previous message. The Desktop update flow stops the backend
on purpose and drives the whole update over Tauri commands and events, so it never
enters the transport path this changes.

Two source-reading contracts moved with the code they read: the auth transport
contract now counts tags against the helper's own raises instead of a fixed number,
and the auth redirect stub exports getApiPort, which an ES module import needs
present whether or not the web build ever calls it.

The signalled-exit test asserts the memory-pressure hint only where SIGKILL exists.
A Windows process exits with a DWORD and never reports a negative code, and
signal.Signals(9) raises there, so that branch names the signal SIG9 and offers no
hint; asserting the POSIX wording unconditionally failed on a Windows runner.

The sink retires itself at interpreter exit as well. One is normally retired when the
next worker is spawned, so the case with no next worker is the server exiting, and
without this the last sink waits for the temporary directory to be reclaimed, which on
a long-lived desktop can be never. Cleanup names the exact paths this process opened
and never sweeps the directory by prefix or age: several Studios can share one
temporary directory, and a sweep would delete another Studio's live worker's sink.
@danielhanchen
danielhanchen force-pushed the pr/studio-updater-and-worker-stderr branch from 75b6db0 to 748f0cf Compare September 16, 2026 05:14
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
…err sink

Review of the change in this branch, from the angle of what else it moved rather
than whether it fixes #7843. Three findings, each with a test that fails on the
previous commit and passes here: six of them fail there, twenty six pass, and all
thirty two pass now.

A severed character turned the whole tail into mojibake. Both byte windows in this
module open at an arbitrary offset: the parent reads the last TAIL_READ_BYTES of
the sink, and the pump compacts the sink down to its last cap_bytes. Neither can
land on a character boundary on purpose, and cp1252 has a meaning for almost every
byte, so one multi-byte character cut in half made strict UTF-8 fail for the entire
window and handed all of it to cp1252. Measured through a real spawned worker whose
stderr outgrows the read window: "RuntimeError: modellaedt nicht" with an a-umlaut
and an em dash came back as "modellA-currency-dt nicht a-euro-trademark". The claim
in the docstring that valid UTF-8 is never mis-read as cp1252 only holds once the
severed character is trimmed, so trim up to three bytes at each end first. The
existing UTF-8 test could not catch this: it decodes a short aligned buffer, which
is not the shape the read window produces.

The child re-created a sink the parent had retired. install_worker_stderr_mirror
fell back to open(path, "wb") when "r+b" failed, and the only way the child finds
the sink missing is that the parent already retired it. That fallback did two
things it must not: it created the file in the system temporary directory with
0666 and ~umask, measured at 0664 on this host, so another account on the machine
could read a worker's stderr, and it followed a symlink planted at that path and
truncated it. Measured: a file containing ORIGINAL, with a symlink to it at the
sink path, was replaced by the worker's stderr. Open the sink the parent made with
O_NOFOLLOW and never create one, since no sink is the old behaviour and there is
nothing to gain by re-creating a diagnostic. The parent's own tail read gets
O_NOFOLLOW for the same reason.

The teardown closed the inherited stderr while the pump might still be writing to
it. _stop_mirror joins the pump with a two second timeout, and then closed the
descriptor whether or not the join succeeded. The join only times out when
something else in the worker still holds a descriptor onto the pipe, an ordinary
logging handler or a native library that dup'd fd 2, which means the pump has not
seen EOF and may be inside os.write on that descriptor right then. Closing it frees
the number for the next open() in any thread, and the pump would then write a
worker's stderr into an unrelated file. Measured at 2.03s on a worker holding a
second handle, which is the window. The interpreter is on its way out, so leave the
descriptor open when the pump is still alive: leaking one is free.

Also: the never-swept guard now rejects walk( alongside glob( and the rest, which
was the one directory enumeration spelling it did not name.

Unchanged by all of this: 364 passed and 2 skipped across the worker stderr,
orchestrator crash message and shared entrypoint consumer suites, the #7843
reproduction still passes, the frontend suite is 7721 passed with tsc and eslint
clean, and the four failures in tests/studio are the same four on 2ab07c9.
…err sink

Fourth finding from the same pass. The open-sink set and the atexit registration
that empties it are both process state, and a fork inherits both. A forked child
that exits normally therefore runs the inherited handler and unlinks a sink its
parent is still filling, which is the same mistake as sweeping the directory by
prefix: the paths are named exactly, they are just somebody else's. Measured
directly, a bare os.fork whose child exits normally left the parent's sink gone.

Spawn children are not affected, since they re-import this module clean, and the
multiprocessing pools in this tree leave through os._exit, which skips atexit. The
backend does fork elsewhere for dataset preprocessing, so record which process the
set belongs to and make the handler a no-op anywhere else. A test asserts it, and
fails without the check.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
pre-commit-ci Bot and others added 2 commits September 16, 2026 08:03
check_health answers liveness.alive, so a probe that ran out of budget read the
same as a refused connection, and a backend holding the GIL through the ML
imports outlasts the retry ladder plus one probe. The transport-failure path
then told the user to relaunch a backend that was alive, discarding whatever it
had in flight. check_backend_present keeps probe_timed_out, which is the
distinction BackendLiveness records it for; check_health is unchanged for the
caller that asks whether the backend is usable.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen danielhanchen self-assigned this Sep 16, 2026
a_stalled_probe_is_not_reported_as_an_absent_backend built three BackendLiveness
values and then asserted `stalled.alive || stalled.probe_timed_out` inline. That
is the rule check_backend_present applies, written out a second time, so the test
asserted its own arithmetic: reverting the command to Ok(liveness.alive) left it
green. Verified by building both spellings and running the assertions against
each, which is the only way to tell a guard from a restatement.

Extract the rule as backend_is_present and have the command and the test both go
through it. Same behaviour, no new branch. With the extracted rule the test
passes; against a command reverted to alive only it now fails on "a stalled probe
must read as present".

Also asserts that check_health keeps collapsing the stall, which is the answer
its own caller wants, so the two commands cannot quietly converge.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: b49c8bd3d1

ℹ️ 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".

Lyxot pushed a commit to NilayYadav/unsloth that referenced this pull request Sep 17, 2026
* Stop three installer tests from inheriting and leaking uv resolver policy

Six tests in tests/studio/install fail on main and have since the commits that
introduced them. None of them indicts product code.

test_setup_fast_path_guard.py assigned os.environ["UV_OFFLINE"] directly inside
a 20-iteration loop with no teardown, so it left UV_OFFLINE=2 set process wide.
That file sorts before test_woa_wheelhouse_guard_behaviour.py, whose _run passed
no env= to pwsh, so Test-WoaResolveReachesPyPI saw UV_OFFLINE=2, took the early
return at install.ps1:765 and answered False. That accounts for the failure set
exactly, including why env9 (UV_OFFLINE=0) is the one True row that survives: it
is the only one that overwrites the leaked value. The same leak was also silently
skipping test_transformers_tokenizers_pair.py, which uv rejects outright with
"invalid value 2: expected a boolish value".

Fixed at both ends. The writer uses monkeypatch.setenv. The reader builds an
explicit env with the uv and pip policy variables removed, matching the idiom
test_woa_torch_index_persistence.py already uses, and runs under a fixture that
asserts no uv.toml or [tool.uv] table sits anywhere above its working directory,
since Get-WoaUvConfigIndexPolicy walks to the filesystem root.

test_the_pr_only_added_new_arms_to_the_setup_status_blocks diffed the installers
against a fixed 2026-09-09 SHA and asserted no removed line matched "step " or
"-match". On a PR branch that diff is the PR; on main it is every installer
change since, so it indicts whichever unrelated commit last touched such a line.
It was never satisfiable on main and has been red since it merged, unnoticed
because actions/checkout defaults to fetch-depth 1 and requires_merge_base skips
it in CI. Restated as live invariants on the shipped text: exactly two keep arms
per script, each guarded by its own shell's construct, the three pre-existing
arms present verbatim.

tests/studio/install: 6 failed, 6125 passed, 33 skipped on cf335fa before;
6132 passed, 32 skipped after. Each assertion was checked against a real defect
in both directions, so none of them passes merely because the environment is
now scrubbed.

* Repair the six CI checks that are red on main itself

Every one of these reproduces on origin/main with no pull request involved, so
they were failing on every open PR at once and reading like each PR's own fault.
Grouped by root cause rather than by check name: three commits between unslothai#11118 and
unslothai#10282 account for all six.

b535eca (unslothai#10282, Windows on ARM native CUDA) -- four failures

  tests/test_windows_amd_gpu_scan_fallback.py, two tests. install.ps1's handoff
  block grew four UNSLOTH_WOA_* saves and restores them from a TABLE walked with
  Set-Item "Env:$(...)", not from four written-out `$env:NAME = $previousX` arms.
  The installer is right; this file's reader knew only the written-out spelling,
  so it read four correct restores as absent. Worse than the noise: a table that
  really HAD gone missing would have been reported identically, so the check could
  not tell a correct block from a broken one. The reader now understands both
  spellings, and a table only counts when something walks it. The four names join
  _CALLER_ENV, so the runtime cases below actually exercise their restore instead
  of the file merely claiming to cover them -- dropping one row from the table, or
  restoring every row from row 0's save, now fails at runtime rather than passing.

  tests/studio/test_cache_budget_discipline.py. The guard flagged woa-wheelhouse's
  vcpkg cache as saving on a pull request ref. It cannot: that workflow is
  workflow_dispatch only, holds signing credentials and is deliberately unreachable
  from a pull request. The guard was reading `if:` without ever reading `on:`, so
  it applied a PR-ref rule to a workflow no PR can reach. It now reads the trigger
  block, the exemption is named with its reason rather than silently skipped, and a
  second test re-derives that claim from `on:` -- so the day woa-wheelhouse gains a
  pull_request trigger it comes straight back under the rule. An ungated cache save
  in a workflow a PR can reach still fails exactly as before.

  tests/studio/test_pwsh_calls_use_the_shared_runner.py. unslothai#10282 added four files
  under tests/studio/install that start PowerShell through subprocess directly,
  which opts them back into the shared $XDG_CACHE_HOME/powershell startup-cache
  race (~1 startup in 500 dies before it reaches the script). Routed through
  run_pwsh, which is the one-word change the runner was written for.

9b1f931 (unslothai#11117, localize the prompt queue) -- two failures

  tests/studio/studiobench/.../test_studiobench_queued_idle_live.py. The selftest
  pinned the composer's label as the English literal
  `followUpBehavior === "queue" ? "Queue message" : "Steer response"`, and unslothai#11117
  correctly replaced it with the two translation keys. A second assertion, on the
  queue surface's hardcoded English aria-label, was stale for the same reason and
  was hidden behind the first. Both now read the branch and the shipped en catalog,
  which is strictly stronger than the literals were: it also checks that dom.js's
  hardcoded `[aria-label^="Prompt queue,"]` selector still agrees with the catalog,
  which is the coupling a localization pass could have broken in silence.

  tests/studio/test_playwright_suites_run_in_ci.py. unslothai#11117 added
  playwright_queue_localization.py and wired it into nothing. It is a gate, not a
  measurement harness, so it is wired into the composer-compatibility engine loop
  beside the sibling suite that drives the same fixture -- not added to NOT_IN_CI.
  Verified green first on chromium 153, firefox 155 and webkit 26.6, so this adds
  coverage rather than a new red.

cf335fa (unslothai#11118) and 9b1f931 (unslothai#11117) -- one failure

  tests/test_formatter_fixed_point.py named three files that are not a fixed point
  of the ruff-format-with-kwargs hook, which fails pre-commit.ci on the next PR to
  edit any of them. Formatted with the pinned ruff 0.6.9.

None of this changes shipped behaviour. studio/backend/main.py is in the diff for
formatting only, and install.ps1 is untouched -- it was correct throughout.

Before / after, measured the same way both times:

  workflow guard suites   2 failed, 1961 passed, 44 skipped
                       -> 0 failed, 1976 passed, 44 skipped
  studiobench selftests   1 failed, 1423 passed, 145 skipped
                       -> 0 failed, 1424 passed, 145 skipped

* Scope the cache-save guard by trigger, not by an excused filename

Follow-up on review of the previous commit. The first version skipped
woa-wheelhouse.yml by name, from a dict carrying the reason. That works and it
rots: skipping a whole FILE blinds the guard to every other step in it, so a
`setup-python` implicit cache added to that workflow later would have been
invisible, and the excuse would keep applying after the reason for it had gone.
It is the same shape as a PINNED_BY_DESIGN keyed on filename.

The predicate was already there. Now it is the only thing doing the work: a
workflow is scanned if and only if `_pull_request_reachable` says a pull request
can run it, and there is no list. The day a workflow gains a `pull_request` or
`pull_request_target` trigger, every cache save in it is indicted on that same
commit with nobody having to remember an entry exists.

Composite actions stay indicted unconditionally. An action has no triggers of its
own, and one `uses:`d from a pull_request job saves on the PR's ref exactly as an
inline step would.

Mutation-proved, each applied then restored from a file copy:

  ungated actions/cache save injected into lint-ci.yml            RED
  ... into consolidated-tests-ci.yml                              RED
  ... into studio-frontend-ci.yml                                 RED
  woa-wheelhouse.yml given pull_request_target, save unchanged    RED
  woa-wheelhouse.yml given pull_request, save unchanged           RED
  woa-wheelhouse.yml given pull_request AND a second offender     RED, naming BOTH

The last is the one the filename exemption could not do. It reports

    woa-wheelhouse.yml:build-pyarrow: setup-python implicit post-step save
    woa-wheelhouse.yml:build-pyarrow: Cache vcpkg packages

where the excused-filename version would have named neither.

Workflow guard suites: 1975 passed, 44 skipped, 0 failed.

* Read the locale entry, not the line it starts on

studio/frontend/tests/pasted-text-attachment.test.ts "every locale keeps the
shortcut in the threshold description" fails on origin/main, which takes down
"Frontend build + bundle sanity" and "Frontend unit tests (Windows)" on every PR
whose merge picks up main. Reported by the lane that hit it on unslothai#11070; it is
main's test rather than that PR's, so it belongs here.

The test did source.indexOf("pastedTextThresholdDescription:"), sliced to the
next newline, and asserted "{shortcut}" was on that slice. That asserts about the
formatter as much as about the translation: a value Prettier wraps onto the
FOLLOWING line leaves the slice holding only the key, and the placeholder is
invisible while being right there.

Product is correct. All twelve locales carry {shortcut} -- checked by parsing the
value out of each file rather than by reading the assertion's own slice.

It is also worse than one locale. ELEVEN of the twelve are wrapped that way on
main today; only en.ts is not. The test was passing on readdir order alone, and
fixing ar.ts by hand would have handed the same failure to de.ts, then es.ts, and
so on down the directory.

So it now imports the locale module and asserts on the resolved string, which is
what the app reads and cannot be moved by layout. The key is found by walking the
tree rather than by a fixed path, so reorganising the message tree does not
silently drop the check either, and `values.length == 1` keeps it from passing
vacuously if the key disappears.

Checked the other indexOf-based source assertions in studio/frontend/tests while
here: they bound their slices with an explicit end marker ("];", the next symbol
name), not with the next newline, so none share this failure mode.

Mutation-proved:

  a locale drops {shortcut}          RED "ar.ts keeps {shortcut}"
  a locale loses the key entirely    RED "ja.ts carries the description
                                      exactly once"
  a value wrapped onto the next line GREEN here, and the old line-scoped
                                      assertion on the same tree sees only
                                      'pastedTextThresholdDescription:' and fails

The third is the regression itself, and it needs no synthetic edit: eleven
locales on main are already in that state.

studio/frontend: 34 pass, 0 fail (was 33 pass, 1 fail).

* Run the queue localization suite for the files it actually reads

Wiring the driver into the composer job left it unreachable by the change it
guards. The workflow filters on tests/studio/*composer* and
tests/studio/*prompt_queue*, and playwright_queue_localization.py carries
neither substring, so a pull request that edits only the driver never runs it.
Nor does one that edits only a catalog: the driver calls setLocale through
src/i18n/index.ts and asserts five hard-coded Japanese strings, and no pattern
reached src/i18n at all. A translation-only edit to ja.ts is the exact change
this suite exists to catch.

tests/studio/test_playwright_suites_run_in_ci.py cannot see this by design; its
own docstring says trigger paths say when CI runs, not what it runs.

Add the two patterns. Checked against GitHub's filter semantics with the
controls in both directions: the driver, each locale catalog and the i18n
loader now trigger the job, thread.tsx and playwright_prompt_queue_actions.py
still do, and README.md and unsloth/models/llama.py still do not.

Also close a hole in _pull_request_reachable, whose docstring promises that
anything unrecognised counts as reachable while the code fell through to
exempt. merge_group runs on its own refs/heads/gh-readonly-queue ref, so a
cache saved there is exactly the pull-request-scoped entry this rule forbids,
and the guard would have said nothing. Name the three events that really are
default-branch-only and indict the rest. No current workflow changes verdict.

* Close the three gaps the repaired CI run then hit

The previous commit got the Backend-CI and Windows jobs far enough to reach
three failures that were sitting behind them.

tests/studio/test_pwsh_calls_use_the_shared_runner.py scanned tests/ and
nothing else, so studio/backend/tests was never checked, and
studio/backend/tests/test_setup_llama_cpp_backend.py had two parametrised
probes (17 pwsh startups in one xdist job) calling subprocess.run(["pwsh",
...]) directly. That is exactly the shared startup-cache race run_pwsh
exists to end, and it showed up as SIGABRT in the "rest" shard. Both call
sites now go through run_pwsh, the guard scans both test trees, its
allowlist is keyed on the repo-relative path, and a new row asserts a file
from the backend tree is really in the scanned set. Checked for
non-vacuity: the widened guard flags both call sites as they stood before.

test_account_tool_confinement.py::test_install_under_a_granted_root_stays_hidden
packed three claims into one command line. Once the credential pre-flight in
tools.py learned to refuse a command that names the auth database, that line
was refused whole, so the two reach probes passed without anything running
and the "the rest of the granted root is still usable" probe could not run
at all. Split into three commands, each answered by the layer that owns it.
Fails on origin/main at f6cf06d too, so it is not this branch's.

playwright_composer_icons.py and playwright_queue_localization.py navigated
with a bare page.goto: playwright's 30s default, waiting for "load", which
on a vite dev server means every module in the graph. On a cold Windows
runner that overran twice, taking the Frontend unit tests (Windows) job down
after the node tests reported "# fail 0". Both now navigate with
domcontentloaded and an explicit budget, as every other driver in that
directory already does. Ran both locally end to end: 1296 icons centered,
all five localization checks pass.

* Give the Windows frontend job time for its own steps

Frontend unit tests (Windows) carries more than its name: node tests, the
composer icon alignment smoke, and data settings in both Chromium and
Firefox. Under a 15 minute cap it cannot finish them, and the overrun is
deterministic rather than flaky, so every run that reaches the last step
dies there and reports itself as "cancelled" -- the failure mode the
comment on the alignment job already describes.

Measured on run 35166979977: setup and npm ci 1m10s, unit tests 4m12s,
browser install 32s, composer icons 39s, data settings in Chromium 4m21s,
then Firefox cut off at 4m13s having needed about what Chromium needed.
That is roughly 15m30s of work under a 15m cap.

Raised to 30. The Linux sibling of this job allows 40.

* Scrub the resolver policy variables case-folded

CPython puts every os.environ key through .upper() on nt ("Where Env Var
Names Must Be UPPERCASE", os.py), so Windows hands the comprehension
PROGRAMDATA, the literal "ProgramData" in the tuple compares unequal, and
the child keeps reading %PROGRAMDATA%\uv\uv.toml. That is uv's system-level
config and the one file that can turn a row asserting True into a
machine-dependent False, on the only platform install.ps1 ships to.

Matched on the upper-cased name at both ends. The row that states it feeds
_scrubbed_environ the three spellings a real environment block can carry,
and runs everywhere: a Linux session has no ProgramData to leak, so a
literal-match scrub passes this suite green on CI and quietly stops working
where it matters.

Same fix as unslothai#11133 carries for its copy of this file; both are open against
main and this branch has since converted the spawn to run_pwsh, so the two
are landed independently rather than one waiting on the other.
danielhanchen and others added 3 commits September 17, 2026 09:51
Comment-only pass over the files this PR touches. No executable code changes:
verified with comment_tools.py for the Python and TypeScript files, and by
byte-comparing the non-comment source of the three Rust files, which the tool
has no lexer for.

Long rationale blocks collapse to the one fact the code cannot state: a defect
number, an invariant, an ordering constraint, or why the obvious alternative is
wrong. Test docstrings that restated the test name are gone.
… sink by what is on disk

Two defects in the worker stderr mirror.

The tail reader idled with time.sleep() on the 50ms poll interval. A sleep
cannot be interrupted, so the stop signal set at teardown was ignored until
the interval expired and every worker exit paid it. Waiting on the stop event
with the same timeout takes the teardown median from 21.2ms to 0.68ms
measured directly, and worker exit through a real spawn from 50.0ms to 15.4ms
against 10.8ms on the merge base.

The size cap counted bytes FORWARDED to the operator's stderr rather than
bytes on disk. When nobody drains that stderr the pump parks inside
os.write(), the cap check is never reached again, and the sink grows without
limit: 68 MB against a 256 KiB cap in a reproduction here. The blocking write
now lives on its own relay thread with a bounded buffer, so the thread that
enforces the cap never parks, and the cap reads the file's real size. The
mirrored copy is best effort and drops its oldest chunk when the buffer is
full; the sink keeps its tail, which is the crash record this whole path
exists to preserve.

Also corrects the justification comment on mark_log_record_continuations().
The structlog record it named goes to fd 1, verified by instrumenting both
descriptors. What actually reaches fd 2 is a third-party library logging
through stdlib logging and out via logging.lastResort, and that traceback is
byte-identical to a dying process's, so the marking is still load-bearing.
@danielhanchen

Copy link
Copy Markdown
Member Author

Performance: does #11070 cost anything?

Verdict: the backend cost is small and bounded (worker spawn +5 ms, stderr writes +0.11 us each, nothing at all for workers that pass no sink). The frontend cost is not small: on a genuinely stopped backend an idempotent request now takes 10.5 s to report instead of 2.5 s, +8.0 s measured. That is a deliberate trade for #10520, not an accident, but the PR's stated justification for it does not hold and the number should be on the record.

One defect I found while measuring is also a perf defect: as submitted, every worker exit paid a fixed ~40 ms it did not need to. Fixed on the branch, numbers below.

Method

Four arms, every one a separate checkout, interleaved one sample per arm per round with the order rotated each round, 24 rounds. Never one arm as a long block.

arm what it is
base merge base 2ab07c9c4
ctl a second, independent checkout of 2ab07c9c4 -- negative control
headsub PR head 353d8a69d exactly as submitted
head 353d8a69d plus the two fixes I pushed

ctl - base is the noise floor: two identical trees, so whatever separates them is the box, not the code. It came out at -1.7 ms on a 61 ms measurement (2.7%), which is the resolution of everything below. This box is shared and was running a 56k-test suite concurrently; that is exactly why the control arm is there.

The spawn path is the real one: _CTX.Process(target = run_without_native_path_secret, ...) with the same kwargs InferenceOrchestrator._ensure_subprocess builds, including unsloth_stderr_mirror_path where the tree has it. CPU only, CUDA_VISIBLE_DEVICES="".

1. Worker spawn and first output

metric (median ms) base ctl headsub head head - base noise (ctl - base)
parent opens the sink 0.000 0.000 0.229 0.237 +0.237 +0.000
Process.start() returns 0.864 0.837 0.835 0.796 -0.068 -0.026
time to worker up 61.202 59.535 65.425 66.488 +5.286 -1.667
time to first output 70.710 68.602 76.324 77.435 +6.724 -2.108

Spread on the headline number: base p10/p90 57.3/65.9, head p10/p90 62.1/72.3, n=24 each. The +5 ms clears the noise floor comfortably.

Where the 5 ms goes, measured separately in a fresh interpreter over 25 runs:

component median
import utils.worker_stderr in the child 10.143 ms cold
install_worker_stderr_mirror() itself (3 opens, dup, dup2, threads) 0.585 ms
WorkerStderrCapture() in the parent 0.040 ms

So the fd work is half a millisecond. The rest is importing a new module inside a freshly spawned interpreter, and it shows up as ~5 ms rather than ~10 ms because logging and tempfile are already in the child by then.

What I did not measure: time to first generation. That needs a model load, which this PR does not touch and which costs seconds to minutes. The added work is a constant paid once at spawn, so against a real first token it is well under a percent -- but I am stating that as arithmetic, not as a measurement, and the 5 ms above is the honest number for the part I actually ran.

2. Steady-state generation throughput

The worker writes 2 MiB to fd 2 in 16,384 x 128-byte writes and times only that loop. On base fd 2 is the inherited pipe; on head fd 2 is the sink file and a thread relays it onward. That is precisely the change.

metric base ctl headsub head head - base
us per write 0.569 0.547 0.667 0.675 +0.106 us
MB/s 224.98 234.15 191.96 189.68 -35.3 MB/s (-16%)

+0.106 microseconds per write, 16% off raw stderr throughput. In absolute terms a worker would have to write 190 MB to stderr to lose one second, and a chatty worker writes kilobytes. It is measurable and it is not material. My fixes do not move it (headsub and head agree to within the noise floor).

3. Teardown

metric (median ms) base ctl headsub head head - base headsub - base
worker exit (join) 10.766 9.490 49.963 15.418 +4.652 +39.196
parent reads the tail 0.000 0.000 0.322 0.292 +0.292 +0.321
parent retires the sink 0.000 0.000 0.066 0.060 +0.060 +0.066
teardown total 10.770 9.494 50.329 15.749 +4.979 +39.559

This is the one that mattered. As submitted, the mirror's tail reader idled with time.sleep(_TAIL_POLL_S) on a 50 ms interval. A sleep cannot be interrupted, so the stop signal was ignored until the interval expired and every worker exit paid a fixed ~40 ms. Waiting on the stop event instead, with the same timeout, cuts it to +4.7 ms over base.

Measured directly on the teardown function, 25 reps, with the pump's sleep phase randomised so the samples are not all in lockstep:

median min max
before 21.24 ms 1.78 49.23
after 0.68 ms 0.22 1.32

Reading the tail back and retiring the sink cost 0.35 ms together. Nothing there.

4. The no-mirror path: counted, not timed

Every worker goes through the same entrypoint. Enumerating the spawn sites:

spawn site passes a sink?
core/inference/orchestrator.py yes
core/export/orchestrator.py no
core/training/training.py (x2) no
core/training/diffusion_training_service.py no
core/data_recipe/jobs/manager.py no
core/inference/stt_transformers_worker.py no
core/inference/diffusion_transformer_quant.py no

grep -rn STDERR_MIRROR_KWARG outside the module and its tests returns exactly one call site, the inference orchestrator.

Spawning a child both ways and asking it about itself:

no mirror kwarg (export / training / data-recipe / speech / diffusion-quant shape):
  "utils.worker_stderr imported in child": false
  "threads named unsloth-worker-stderr-*": []

with mirror kwarg (inference orchestrator shape):
  "utils.worker_stderr imported in child": true
  "threads named unsloth-worker-stderr-*": ["unsloth-worker-stderr-mirror",
                                            "unsloth-worker-stderr-relay"]

The module is not merely unused in those workers, it is never imported. Zero, and a counter says so rather than a stopwatch.

5. The frontend retry ladder: this one did get slower

The claim to check was that extending 250/750/1500 to 250/750/1500/3000/5000 costs nothing because a loopback connect to a stopped backend is refused immediately, and because time-sensitive polls pass retryNetworkErrors: false.

Measured against a genuinely dead loopback port (a server bound, its port captured, then closed), isTauri stubbed true, 5 reps per case, both arms:

case base head delta
GET, retries on (the default) 2,505 ms 10,514 ms +8,009 ms
POST (non-idempotent) 2,507 ms 2,505 ms 0
GET with retryNetworkErrors: false 1 ms 1 ms 0
one refused loopback connect 0.18 ms (max 1.22) 0.18 ms (max 1.29) 0

So, taking the claim apart:

  • "a loopback connect to a stopped backend is refused immediately" -- true, and beside the point. 0.18 ms median, 1.3 ms worst. But the 10.5 s is not connects, it is the backoff sleeps between them. Five attempts cost under 2 ms of connecting and 10.5 s of waiting. The premise is right and the conclusion does not follow from it.
  • "time-sensitive polls pass retryNetworkErrors: false" -- true, and narrow. 11 call sites pass it. Every other call in the app takes the default, which is true.
  • The idempotency split does work. A POST still uses the short ladder and still reports in 2.5 s, so the PR does not double-charge a committed write. That part of the design holds up.

A user whose backend is genuinely gone waits 10.5 s instead of 2.5 s before any GET-driven panel says so. That is real and user-visible. It is also the explicit point of #10520 -- the ladder was extended to outlive the launcher's 10 s HEALTH_PROBE_TIMEOUT so a slow-starting healthy backend stops being declared dead -- so it is a trade, not a bug. I would still want it written down, because "no regression" is not what the stopwatch says.

check_backend_present does not add to it: on a dead port it is two refused loopback connects and returns. I stubbed it as an instant false for the measurement above, which matches that shape, but see the caveats -- I did not execute the Rust.

6. Do my fixes change any of this?

One number, large:

headsub (as submitted) head (with fixes)
worker exit 49.963 ms 15.418 ms

Everything else is unchanged between headsub and head to within the noise floor: spawn 65.4 vs 66.5, first output 76.3 vs 77.4, us/write 0.667 vs 0.675, tail read 0.322 vs 0.292. The second fix (bounding the sink by bytes on disk rather than bytes relayed, via a bounded relay thread) costs one extra thread per inference worker and one fstat per 64 KiB read, and neither shows up.

It does remove an unbounded one. With the operator's stderr not being drained, the sink reached 68 MB against a 256 KiB cap before I stopped the writer; after the fix it sits at exactly 262,144 bytes.

What I could not measure

Said plainly, because none of it is covered above:

  • Time to first generation with a real model. Not measured. Only spawn-to-first-output on a stub worker.
  • The Tauri / Rust side. check_backend_present, the launcher probe and the updater need a built Desktop app. Not built, not run. The frontend numbers in section 5 come from the TypeScript with isTauri and invoke stubbed, which is the ladder itself but not the shipped app.
  • Windows and macOS. This is a Linux host. Everything above is Linux. The fd-level mirror, O_APPEND behaviour and pipe buffering all differ on Windows, and section 2's throughput number in particular should not be assumed to carry over.
  • Multi-GPU and real inference load. CPU only.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 463fbdaa87

ℹ️ 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".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

1 participant