Repository navigation
Studio: stop declaring a live backend dead, and keep a crashed worker's stderr - #11070
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
8d532c6 to
75b6db0
Compare
…'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.
75b6db0 to
748f0cf
Compare
…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.
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.
|
@codex security review |
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
* 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.
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.
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. MethodFour 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.
The spawn path is the real one: 1. Worker spawn and first output
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:
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 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 throughputThe worker writes 2 MiB to fd 2 in 16,384 x 128-byte writes and times only that loop. On
+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 ( 3. Teardown
This is the one that mattered. As submitted, the mirror's tail reader idled with Measured directly on the teardown function, 25 reps, with the pump's sleep phase randomised so the samples are not all in lockstep:
Reading the tail back and retiring the sink cost 0.35 ms together. Nothing there. 4. The no-mirror path: counted, not timedEvery worker goes through the same entrypoint. Enumerating the spawn sites:
Spawning a child both ways and asking it about itself: 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 slowerThe 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 Measured against a genuinely dead loopback port (a server bound, its port captured, then closed),
So, taking the claim apart:
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
6. Do my fixes change any of this?One number, large:
Everything else is unchanged between 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 measureSaid plainly, because none of it is covered above:
|
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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.tsretried a failed fetch after 250ms, 750ms and 1500ms and then gave up, againstHEALTH_PROBE_TIMEOUTof 10s thatstudio/src-tauri/src/commands.rsspends 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
fetchinside 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
multiprocessingspawn child that inherits the server's stderr. When such a child dies from an unhandled exception, the tracebackmultiprocessingprints travels down that inherited handle and never through the response queue, so_subprocess_crash_messageinstudio/backend/core/inference/orchestrator.pyhad an exit status and nothing else. It special-cases signals and the OOM killer, and for a positive exit code it returned onlypid=..., exitcode=.... Preserving the underlying exception is literally the issue's "Expected".Changes
Health verdict:
check_healthTauri 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.the_frontend_retry_ladder_outlives_one_probe_budget, parses the ladder out of the TypeScript withinclude_str!and fails if it ever drops back belowHEALTH_PROBE_TIMEOUT, so the two numbers cannot drift apart again.isExpectedBackgroundChatStorageErrornow 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:
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.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.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.
run_without_native_path_secretis 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.test_a_caller_that_passes_no_mirror_is_unchangedreproduces the old message byte for bytetest_the_reserved_kwarg_is_consumed_and_never_reaches_the_entrypointasserts the worker sees[]check_healthis a command the shipped launcher already registers anduse-tauri-backend.tsalready invokes in this exact shape. A shell that rejects the invoke falls back to the previous message.a check_health that throws leaves the original verdict in placestart_backend_updatestops the backend on purpose, anduse-tauri-update.tsdrives the whole update over Tauri commands and events, with noauthFetchand nofetchof its own. The changed path is never entered.updating an existing install does not go through the changed pathpins itisTauri, so the web build takes the same branch it always took, including the offline message.retryNetworkErrors: falseand 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./mnt/cunder WSL, and a generated macOS/var/folderspath.test_the_sink_works_on_every_install_path_shape, four shapesVersion matrix,
mStudio(Python 3.13.12, torch 2.10.0+cpu, transformers 5.4.0, trl 0.29.1, peft 0.18.1):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-tauriandtests/studio. It touches no installer, no packagingfile, no release workflow and
tauri.conf.jsonnot at all, so the Desktop asset names and thelatest.jsonupdater endpoint are unchanged by construction.Updating a real prior release.
v0.1.807-betawas installed into a scratchUNSLOTH_STUDIO_HOMEand then updated by running this branch's installer over it. The venv wasreused rather than rebuilt, the three transformers sidecars reported
current, llama.cpp andwhisper.cpp reported
prebuilt up to date, and the file tree gained three paths, all of themwritten by main's installer and read only by it and
studio/install_manifest.py. This PR addsno 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.dbandauth/.bootstrap_passwordstayedbyte-identical through all of them. The updated Studio starts and answers
/api/livenesswith200, 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.Processhandle the orchestrator already held, and itsstderr 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 innative_path_leases.py, 15 of18 scopes in
api.tsand 89 of 90 inchat-history-storage.tshave an identical branchstructure, 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_healththat cannot beasked 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-armcould not install the backend requirements at all, beforeany 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_updateron macOS, Windows or Linux, which no host available here can do. Whatstands 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_budgetinstudio/src-tauri/src/commands.rs, run bycargo testin 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.pynow counts tags against the helper's own raises instead of a fixed number of two, and the stub intests/studio/test_auth_form_input_count.pyexportsgetApiPort, which an ES module import needs present whether or not the web build ever calls it.Run on Python 3.13:
The failures in the backend run are the families this host fails on main too:
test_studio_apicannot reach the network,test_account_tool_confinementdepends on landlock and fails a different subset on every run on both trees, andmulti_account,test_gpu_arch_gate_consumers_7624,test_kv_cache_estimation,test_media_model_index_accounts,test_offload_planner_seam,test_text_io_encodingandtest_tunnel_safe_long_postfail 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
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_messageiswhat 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
Two isolated installs built by this PR's own
install.sh --local: BEFORE is the merge base2ab07c9c4, AFTER ise210ef389. One scene drives both. It asks the real server to loadunsloth/Llama-3.2-1B-Instruct, waits for the worker that load spawns, and aborts that worker acouple of seconds into its startup with
SIGABRT, which is what a bad driver, a GPU fault duringinitialisation 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:
Read off the same servers that were photographed, through
POST /api/inference/load, rather thanoff the picture:
Failed to load model: The inference worker stopped unexpectedly while loading the model. Details: pid=..., signal=SIGABRT, exitcode=-6.Worker error output:and the runtime's own dumpWorker error output:presentFatal Python error: AbortedThe AFTER dump names where the worker died --
detect_hardwareinsiderun_inference_process-- and every absolute path in it is shortened to.../<file>, which is_redact_worker_outputdoing 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_tailreadsthe last 20 lines and 4000 characters, and
_public_worker_stderr_tailkeeps an indented frameonly as the continuation of a diagnostic line it already kept. A worker interrupted
mid-generation dies with a 27-line
KeyboardInterrupttraceback: theTraceback (most recent call last):header falls outside the window, the bareKeyboardInterruptline carries no colon to start a new diagnostic, and the message comes outbyte-identical on both builds. A worker aborted once the ML stack is loaded writes a
faulthandlerdump ending in anExtension 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=1was set on both Studios. Without it an aborted worker writes nothing atall, and neither build can show a cause it was never given.
Recordings of the two runs, BEFORE then AFTER:
Still true at the current head
The pictures above are of
e210ef389.3a30972c6was installed into a third isolated home anddriven by the same scene: the message is the same shape, 1037 characters with 17 lines under
Worker error output:beginningFatal Python error: Aborted, so the path-delimiter andcrash-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".Worker error output:Fatal Python error: AbortedAll 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:3d57464bfubuntu-latestmacos-15(Apple Silicon)windows-latestUnsloth Tauri CIThe Rust half is compiled by
Unsloth Tauri CI, which is a separate workflow from the threelegs 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 tocompletion 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
SIGKILLin a crash message:signal.Signals(9)raises on Windows,so the message says
SIG9there, and the assertion now accepts either spelling and pins theexit code, which both platforms share. The other was a
node --versionprobe with a fivesecond 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 CIfails 1 of 7761 on "every locale keeps the shortcut in the thresholddescription",
studiobench CIfails 1 of 1403 on the shipped composer's queue buttons, andWorkflow trigger lintfails on the staging branch's own generated workflows. None of thethree 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.