Repository navigation
Studio desktop: hide the window as soon as a quit is committed, and exit the backend without finalization - #15723
Conversation
Quitting blocks on reaping the backend (SIGTERM, then up to 5s before SIGKILL on Unix; about 18s worst case on Windows), and the main window stayed on screen for all of it, so the app looked stuck for a few seconds. Only Windows had a closing overlay. Every committed quit now hides the main window before the reap, on all platforms: the quit thread hides it after the confirmation dialogs and re-shows it if the reap unwinds; a macOS Dock, logout, or AppleScript quit takes the NSTerminateLater quit thread whenever a window is on screen, because NSTerminateNow reaps in RunEvent::Exit with the main thread blocked, where a hide is never presented; Unix termination signals hide fire-and-forget before the reap, so a hung UI cannot hold up cleanup. The Windows-only overlay events are no longer emitted.
…shutdown After a signal or HTTP shutdown the backend finished its own cleanup in about 0.3s but the process took about 1.4s to exit: CPython spent the rest tearing down a large heap after the last atexit hook. The desktop app's quit and `unsloth studio stop` wait on that exit. The end of the shutdown path now runs the interpreter's own exit steps in order (join threads, run atexit hooks, flush stdio with CPython's 120 status on a flush failure) and then calls os._exit. The thread join stays unbounded so in-process writers finish. Measured SIGTERM to exit: 1.42s to 0.34s.
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. |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ 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". |
The desktop app and an in-venv `unsloth studio` serve the backend in-process from the CLI, never through run.py's __main__, so the fast exit never ran on the desktop quit.
|
Review record for #15723, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#585. Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found. Round 1: reviewed mirror
|
…ugh run_pwsh (#15758) ## Summary `Repo tests (CPU, studio)` fails on main, so it is red on every recent staging CI run (#15680, #15696, #15716, #15723 and others). Of its 6 failures, 4 are tests that no longer match intentional changes; this PR fixes those. The other 2 are real product slips on the login screen and are fixed separately. **Media picker contracts (3 failures).** #15726 lined the Images, Audio and Video model pickers up with Chat: - The picker now uses `className="ml-1.5 max-w-full overflow-hidden !pl-2.5 !pr-1.5 !h-[var(--studio-chat-control-height,34px)]"`. - It no longer sets a `triggerLabelClassName` override. `tests/studio/test_desktop_reliability_frontend_contract.py` still pinned the old class string and the old label override, and counted two scaled `!h-[calc(34px*var(--ui-space-scale,1))]` literals on the Images and Video pages (and one on Audio) that are now the shared token: ``` images-page.tsx states 1 scaled !h-34px, not 2 assert 'className="!h-[34px] max-w-full gap-1 ...' in header ``` **PowerShell spawn (1 failure).** `tests/python/test_installer_compile_bytecode.py:271` (from #15646) starts PowerShell with `subprocess.run`. `tests/studio/test_pwsh_calls_use_the_shared_runner.py` forbids that, because direct spawns share one PowerShell startup cache across xdist workers and can die at startup. ## Change - **`test_desktop_reliability_frontend_contract.py`:** - The Images and Audio header contracts assert the new picker class (`_MEDIA_PICKER_CLASS`), and that the label is not overridden, so the trigger reads like Chat's. - The scale table's `!h-34px` counts drop to what the pages still state literally: Images 1, Audio 0, Video 1. The "no bare `!h-[34px]`" half of that check is unchanged. - New test `test_the_media_pickers_take_chats_scaled_control_height`: all three pages use the picker class, and `index.css` still defines `--studio-chat-control-height` as `calc(Npx * var(--ui-space-scale, 1))`. This keeps the original point of the scale check, a pill that grows with the UI scale, attached to the token the height now comes from. - **`test_installer_compile_bytecode.py`:** the PowerShell case runs through `run_pwsh` from `tests/_shared/unsloth_pwsh_runner.py`, with the same argv and keyword arguments. ## Testing - These three files: 80 passed (pwsh is installed here, so the PowerShell cases really ran). On main, the same tests fail 4. - **Sabotage:** with `--studio-chat-control-height` changed to a bare `33px`, the new scaling test fails.
Follow-up to #15723: drops comment lines from the desktop quit path that restated the code or a number already in the PR description. - `hide_main_window_for_quit`: keeps only the main-thread invariant (the hide lands once the event loop runs again). - `quit_sequence`: drops the note that the steps are injected for tests. - `test_exit_without_finalizing.py`: drops a restatement of the flush assertion. Comments only: an AST and tree-sitter check confirms no code changed.
…ady gone (#15764) ## Summary `AppImage model download E2E` fails intermittently on unrelated PRs, for example the header-only `chore/desktop-release-agpl-header` run and both attempts of the #15723 staging run: ``` AssertionError: Timed out waiting for the packaged frontend to render; last result: False ``` The app is fine in every one of these failures. The uploaded `failure.png` / `failure-webview.json` show it on `tauri://localhost/chat` with the sidebar rendered (6 `nav-row-*` rows on the agpl-header run), and `tauri.log` shows the same preflight, backend start and desktop auth sequence as passing runs. The first wait in `tests/studio/appimage_model_download_webdriver.py` demands the transient `Starting Unsloth...` splash: ```python "return document.body && document.body.innerText.includes('Starting Unsloth')" ``` When the desktop handoff completes before the WebDriver session attaches and starts polling, the splash is already gone, so this can never become true, even though the next wait ("the deterministic desktop backend handoff", splash gone) would pass at once. ## Change The "rendered" wait now also accepts the app shell (`[data-testid^="nav-row-"]`, the sidebar rows). The handoff wait after it is unchanged, so the run still has to see the splash gone before driving the Model hub. ## Testing The old and new predicates evaluated in Chromium: | Page | old | new | |---|---|---| | captured failure DOM (app on /chat) | False | True | | splash only | True | True | | blank `#root` | False | False | | an error page with no shell | False | False | So the wait still fails when nothing rendered, and stops failing on the healthy page it used to reject. - `tests/security/test_release_desktop_appimage.py` + `tests/studio/test_appimage_fixture_cors.py`: 26 passed. - The E2E itself runs on this PR's desktop workflow (the script path is in its `paths:` filter).
## Summary `Frontend unit tests` fails on main (seen as the Windows leg on #15795; reproduces locally on `795da3b42a`) with three tests that read `studio/src-tauri/src/main.rs` and still describe the quit as it was before #15723: ``` not ok - a quit with no window on screen raises no overlay (expects fn quit_raises_the_overlay) not ok - both sides agree on the event names (expects const APP_CLOSING_EVENT / APP_CLOSING_CANCELLED_EVENT in main.rs) not ok - macOS termination checks unsaved transcripts before allowing exit (expects begin_or_attach_termination(quit_requires_confirmation(app))) ``` #15723 changed the quit on purpose: the cover step now hides the main window on every platform instead of emitting the Windows-only `app-closing` overlay events, a window that was not on screen is left hidden, and the macOS terminate path holds on while a window is on screen (`quit_requires_confirmation(app) || main_window_on_screen(app)`). Its description notes the frontend overlay (`closing-signal.ts`, `ClosingScreen`) is no longer triggered and leaves removing it to a follow-up. The product is right; these three tests were not updated with it. ## Change `studio/frontend/tests/desktop-closing-overlay.test.ts`: the two tests pinned to the removed Rust emitters are replaced by the contract that replaced them: - **a quit with no window on screen leaves it hidden**: `hide_main_window_for_quit` hides only when `main_window_on_screen(app)` says the window is visible, read via `window.is_visible()`; - **the quit hides the window after the confirmations and before the reap**: in `quit_sequence`, `if !confirm()` comes before `hide()`, which comes before `reap()`; and `main.rs` does not emit `app-closing`, so if the overlay is ever wired back the test says to put it back under test (or remove it). The store-level overlay tests in the same file still pass and still cover `closing-signal.ts` until the follow-up removes it. `studio/frontend/tests/audio-transcript-lifecycle.test.ts`: the macOS check now matches `begin_or_attach_termination(quit_requires_confirmation(app)...`, so the terminate path may hold on for more reasons but never fewer; the `|| renderer.unsaved_transcript` and `confirm_quit_with_unsaved_transcript` checks are unchanged. ## Testing - Whole frontend suite (`node --experimental-strip-types --test "tests/**/*.test.ts"`): 3 failing on main (the three above), 0 with this change. - Sabotage on `main.rs`, one at a time: - reaping before hiding fails "the quit hides the window after the confirmations and before the reap"; - hiding without asking whether the window is on screen (`let hide = true;`) fails "a quit with no window on screen leaves it hidden"; - dropping `|| renderer.unsaved_transcript` from `quit_requires_confirmation` fails the macOS transcript test.
Problem
Quitting the Unsloth desktop app took a few seconds to actually close. The quit path blocks on reaping the backend before
app.exit(0)(SIGTERM to the backend process group, then up to 5s before SIGKILL on Unix; about 18s worst case on Windows), and the main window stayed on screen the whole time. Only Windows covered that wait, with a closing overlay; on macOS and Linux the window simply looked stuck.Two things made up the wait:
os._exitat that point cut SIGTERM-to-exit from 1.42s to 0.34s.Changes
Desktop: hide the main window as soon as a quit is committed
quit_sequencekeeps its ordering contract (confirmation dialogs first, then cover, then reap), but the cover step now hides the main window on every platform instead of emitting the Windows-onlyapp-closingoverlay events. A guard re-shows the window if the reap unwinds and the app stays up. A window that was already hidden (tray quit,--hiddenstart) is never popped back.applicationShouldTerminate:now answersNSTerminateNowonly when nothing needs confirming and no main window is on screen; otherwise it takes the existingNSTerminateLaterquit thread. WithNSTerminateNowthe reap runs inRunEvent::Exitwith the main thread blocked, where a hide is applied but never presented.hide()before the reap. It deliberately skips the blockingis_visible()round trip so a hung UI thread cannot keep the backend from being reaped.The saved window state uses
SIZE | POSITION | MAXIMIZEDonly (noVISIBLE), so exiting with the window hidden does not make the next launch start hidden.Backend: exit without interpreter finalization after shutdown
At the end of the signal / HTTP shutdown path,
_exit_without_finalizing()runs the interpreter's own exit steps in its order, then callsos._exit:threading._shutdown(): join non-daemon threads and thread-pool workers. This stays unbounded so in-process writers (dataset import, LoRA / Q4NX export run viaasyncio.to_thread) finish their writes.atexit._run_exitfuncs(): every Python atexit hook (logging shutdown, child-process sweep, pid-file removal, ...).Only module/heap teardown is skipped. This covers the desktop quit, the Windows HTTP shutdown, and
unsloth studio stop.Risks / tradeoffs
Py_AtExit/ C atexit handlers and unflushed C stdio buffers, plus__del__of objects still alive at exit. Children are already reaped at that point, so what is lost is at most native diagnostic output.closing-signal.ts,ClosingScreen) is no longer triggered; removing it is left for a follow-up.timeout_graceful_shutdown, or a bounded thread join) was tried and dropped: it cancels or abandons in-flight work that persists state across several steps.Validation
Live app (debug build, macOS), with on-screen window presence sampled every 10ms:
NSRunningApplication.terminate()(Dock-style quit)Backend SIGTERM → process exit, standalone: 1.42s → 0.34s, exit status 0, all atexit hooks reached.
Tests:
quit_sequenceordering, unwind re-show, and visibility decisions (Rust). A subprocess exit test checks that a worker outliving any bounded budget finishes before atexit hooks, hooks run, stdout is flushed, finalization is skipped, and an unflushable stdout exits 120. Each new test was checked against targeted mutants of the code it covers.Quit evidence (Linux, Xvfb)
Debug desktop builds of the merge base and this PR, launched against a stub backend that, like a loaded Studio, takes 3 s to exit after SIGTERM. The app was quit with SIGTERM and window visibility was sampled every 50 ms (
xwininfo), 2 rounds per side:The backend side, measured on the in-process
unsloth studio --api-onlypath the desktop app launches (SIGTERM to process exit, 3 interleaved rounds): main 2.06 / 2.83 / 3.13 s, this PR 0.42 / 0.47 / 0.73 s.