Repository navigation
Fix interrupted Studio install recovery - #7490
wasimysaid wants to merge 17 commits into
Conversation
3ff282c to
41cbb56
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 41cbb5677c
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
41cbb56 to
f33a16e
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f33a16ef88
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
f33a16e to
a94c5b0
Compare
The runtime probe waits on child exit with stdout piped and undrained, so a CLI printing more than the pipe buffer holds blocks mid-write and the probe times out. It imports the whole backend, which is exactly what emits stray stdout, so a healthy install gets reported broken and sent to repair after a 10s stall on every launch. Drain concurrently instead, here and in the desktop-capabilities probe next to it. The install marker was cleared only on success, so a failed update, or a cancelled elevation prompt, left it behind and pinned a working install into repair it may not be able to finish offline. Clear it on every terminal outcome and treat marker bookkeeping as best effort rather than failing the install over it. Skip pip flag lines in studio.txt: an unparseable line reported the install broken, and repair reinstalls the same file, so that never cleared. Allow prereleases against a floor for the same reason.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7b22a8584f
ℹ️ 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".
| if let Err(msg) = create_install_in_progress_marker() { | ||
| warn!("[install] {}", msg); | ||
| } |
There was a problem hiding this comment.
Clear the install marker after elevation failures
When the installer exits with code 2, this marker is deliberately retained while install_system_packages runs, but every failure path in that function (including a denied elevation prompt or failed apt-get install) returns after clearing only current_attempt; it never removes the marker. On the next launch, probe_managed_install therefore unconditionally reports install_incomplete instead of letting the runtime probe recognize a still-working preexisting install, forcing bundled repair even when that repair cannot succeed offline. Clear the marker when the elevation attempt reaches a terminal failure, as is already done when elevation is canceled.
Useful? React with 👍 / 👎.
| try: | ||
| installed = distribution(requirement.name) | ||
| except PackageNotFoundError: | ||
| return requirement.name |
There was a problem hiding this comment.
Verify package files instead of only distribution metadata
For an interrupted wheel extraction—the recovery case this probe is intended to detect—a package's .dist-info metadata can remain present while its importable files are incomplete or missing. distribution(requirement.name) and the version comparison still succeed in that state, and _load_run_module() only exercises the shallow imports in run.py; dependencies such as FastAPI are not imported until the later from main import app startup path. The probe can therefore report runtime_ready: true and reproduce the unexpected backend exit instead of offering repair; validate the installed files/import path rather than treating metadata presence as runtime readiness.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not fixing this one. The binary distribution format spec has archivers place .dist-info physically at the end of the archive and installers update RECORD last, so a truncated unpack loses the metadata first and distribution() already raises PackageNotFoundError. Residue from an interrupted upgrade (older version still installed) is caught by the specifier check above. Importing the backend in the probe to check further is also the opposite direction from the 64 KiB pipe-buffer deadlock that probe just had to be fixed for, under a 10s timeout.
There was a problem hiding this comment.
Correcting myself: my earlier reply on this was wrong, and the 👎 is now a 👍.
I claimed the format spec places .dist-info physically at the end of the archive, so a truncated unpack loses the metadata first. That placement is only listed under "Recommended archiver features", and measuring real wheels shows the opposite in practice: in both fastapi-0.140.5 and typer-0.27.0 (hatchling), dist-info/METADATA is entry index 0, ahead of every package file. Extracting just the first four entries of the fastapi wheel into a clean venv gives distribution('fastapi').version = 0.140.5 with import fastapi raising ModuleNotFoundError, and _missing_studio_requirement() returns None, so the probe reports runtime_ready true on a venv whose backend cannot start.
So the finding is right, and the reachable route is the plain interrupted install this PR exists to fix rather than the corrupted-venv framing. Fix uses installed.files is None (RECORD is written last) rather than importing all 22 requirements, which would not fit the 10s probe timeout; checked against all 298 distributions in a real venv with zero false positives.
| for _ in 0..50 { | ||
| if !unix_process_group_exists(pid) { | ||
| return; | ||
| } | ||
| std::thread::sleep(Duration::from_millis(100)); |
There was a problem hiding this comment.
Prevent PID reuse from redirecting cleanup signals
On Unix, try_wait() has already reaped the backend leader before this loop starts, so its PID is no longer reserved. If the last original descendant exits between two polls and the numeric PID is reused as the leader of an unrelated process group before the next kill(-pid, 0), the loop mistakes that new group for surviving backend descendants and eventually sends it SIGTERM or SIGKILL. This can terminate unrelated user work under sufficiently high process churn; keep the leader identity reserved until group cleanup completes or otherwise bind the checks and signals to a non-reusable process identity.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The premise does not hold: reaping the leader does not release the number while the group is non-empty. POSIX XBD 4.17 says a process ID is not reused while a process group with that ID exists, and in Linux __change_pid() returns before the pid reaches free_pid() if pid_has_task() holds for any type in enum pid_type, which includes PIDTYPE_PGID; free_pid() is what does the idr_remove() that returns the number to the pool. Every signal here is gated on unix_process_group_exists(pid), so it only ever fires while the group still has members.
One narrow residue worth a look though: the final SIGKILL after the 50-iteration loop is the one send that is not preceded by a fresh existence check, so it fires on state observed up to 100ms earlier. Recycling in that window needs full PID-space wraparound, so it is not reachable in practice, but re-testing unix_process_group_exists right before that last kill would close it for free.
The code 2 exit keeps the marker for the elevated run that follows, but every terminal failure of that run, a denied prompt or a failed apt-get included, returned without clearing it. That pinned a working install into repair the same way a failed update did. finish_elevation_failure is the one path all of them take.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b40d422654
ℹ️ 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".
| cmd.args(["studio", "desktop-runtime-check", "--json"]) | ||
| .stdout(Stdio::piped()) | ||
| .stderr(Stdio::null()); |
There was a problem hiding this comment.
Fall back for compatible CLIs that predate the runtime probe
A managed CLI from the parent revision can report a compatible version (the minimum remains 2026.5.3) and start Studio successfully, but it does not define desktop-runtime-check. This invocation therefore exits without JSON, and probe_managed_bin marks the installation stale before consulting its existing capability data; release preflight then automatically repairs rather than launching it. After a desktop-app update, users with such an otherwise healthy installation are forced through an unnecessary network-dependent update/install and cannot start offline. Preserve the prior launch probe as a compatibility fallback, or gate this command on a capability/version that guarantees its presence.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 8f34303. This hits the whole installed base, not an edge case: PyPI's latest unsloth is 2026.7.5 while MIN_DESKTOP_BACKEND_VERSION stays 2026.5.3, so every field CLI is version-compatible and simply lacks the subcommand, exits 2 with 0 bytes on stdout, and probe_managed_bin returned Stale before consulting the capability cache. release_auto_repair() is true in release builds, so the app force-repaired a healthy install and an offline user could not start.
Fix restores the previous launch probe as a fallback, gated on studio desktop-runtime-check --help, which exits 0 when the hidden command exists and 2 when it does not (verified against a real venv), so a NEW CLI that crashes or times out still reports Stale rather than being waved through.
|
|
||
| let (stdout, stderr) = match spawn_script(&script, &args, &state) { | ||
| Ok(handles) => handles, | ||
| Err(msg) => { |
There was a problem hiding this comment.
Clear the install marker when spawning fails
When bash, PowerShell, or the OS fails to spawn the installer after the marker is created, this terminal error returns without removing the marker. On the next launch probe_managed_install consequently reports install_incomplete, and repair skips the incremental update solely because of a run that never actually started. Clear the marker in this error branch, consistently with the other reported failure outcomes.
Useful? React with 👍 / 👎.
| try: | ||
| installed = distribution(requirement.name) | ||
| except PackageNotFoundError: | ||
| return requirement.name | ||
| # prereleases=True: a prerelease satisfying a floor is not a broken install. | ||
| if requirement.specifier and not requirement.specifier.contains( | ||
| installed.version, prereleases = True | ||
| ): | ||
| return requirement.name |
There was a problem hiding this comment.
Import required modules instead of trusting dist-info
In a partially interrupted or corrupted venv where a package directory is missing but its .dist-info remains—for example, fastapi/ is gone while fastapi-*.dist-info still reports a valid version—distribution() succeeds and this check reports no missing requirement. _load_run_module() does not import FastAPI; the actual backend defers from main import app, and studio/backend/main.py imports FastAPI only during server startup. The probe therefore returns runtime_ready: true, preflight skips repair, and the backend crashes in exactly the incomplete-install scenario this change is intended to recover from. Validate that the required import modules are loadable, not only that their metadata exists.
Useful? React with 👍 / 👎.
| except Exception as exc: | ||
| payload = { | ||
| "runtime_ready": False, | ||
| "reason": "backend_import_failed", | ||
| "error_type": type(exc).__name__, | ||
| } |
There was a problem hiding this comment.
Keep configuration errors out of the repair loop
When a supported runtime setting is invalid, such as UNSLOTH_CPU_THREADS=invalid, importing run.py raises SystemExit; this except Exception does not catch it, so the command exits without the structured payload. The Rust probe maps that to studio_runtime_probe_failed, release preflight classifies the managed install as stale, and both the incremental update and bundled installer are attempted even though neither can fix the inherited environment value; the post-repair probe then fails for the same reason. Catch and classify this startup/configuration failure separately so the UI can surface it instead of repeatedly reinstalling a healthy environment.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 8f34303. SystemExit is not an Exception, so it escaped the handler and no payload was emitted at all, which the Rust side read as studio_runtime_probe_failed. Now reported as backend_startup_failed, and that reason is excluded from can_auto_repair: reinstalling cannot change an inherited environment value, so repairing would replace a healthy install and fail identically afterwards. The frontend surfaces it instead.
Every released CLI predates desktop-runtime-check: PyPI's latest unsloth is 2026.7.5 and MIN_DESKTOP_BACKEND_VERSION stays 2026.5.3, so a field install is version-compatible and simply lacks the subcommand. It then exits 2 with no stdout, which read as a failed probe, and probe_managed_bin returned Stale before consulting the capability cache, so a healthy install was force-repaired and an offline user could not start at all. Fall back to the previous launch probe, gated on 'desktop-runtime-check --help' (0 when the command exists, 2 when it does not), so a new CLI that crashes or times out still reports Stale. Metadata outlives the package it describes. Hatchling wheels store .dist-info/METADATA as the first archive entry (verified: index 0 for both fastapi and typer), so an unpack killed midway leaves a readable version for modules that never landed and the probe called the venv ready. RECORD is written last, so a missing file list marks that unpack; checked against all 298 distributions in a real venv with no false positives. This supersedes my earlier reasoning that the metadata is written last, which was wrong. run.py raises SystemExit at import for a rejected setting such as UNSLOTH_CPU_THREADS, and SystemExit is not an Exception, so it escaped the handler and emitted no payload at all. Report it as backend_startup_failed and keep it out of the repair path: no reinstall can change an inherited environment value, so repairing would replace a healthy install and fail again. Also clear the install marker when the installer fails to spawn, the one terminal outcome that still left it behind.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4482f8b4f1
ℹ️ 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".
| let _ = app.emit(event_mode.needs_elevation_event(), &packages); | ||
| Err("NEEDS_ELEVATION".to_string()) | ||
| } else { | ||
| clear_install_marker_best_effort(); |
There was a problem hiding this comment.
Preserve the marker when installation fails
When the installer exits nonzero after partially modifying the venv—for example, pip installs or removes several packages before failing—this clears the marker and the next launch no longer takes the bundled-repair path. The runtime backstop does not make this safe because it only checks direct entries in studio.txt and imports run.py, while the full dependency tree is loaded later by run_server; a partially installed transitive dependency can therefore leave preflight reporting ManagedReady and the backend repeatedly crashing. Keep the marker for installer failures as well as interrupted runs, clearing it only after a successful installer completion.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, and the ordering settles it. install.sh takes the elevation exit at :1931, before it creates the venv at :2120, and the only pip calls above that are inside _install_bnb_rocm(), which is not reached on that path. So the marker is safe to clear exactly where the script provably never touched the venv: a failed spawn, and the elevation exits.
A nonzero exit or a failed wait is the opposite case. The script was running, pip may have been part-way through replacing a package, and the runtime probe cannot see that. Reverted both of those clears in f749c90 and left 517, 646 and 921 as they were.
| requirements = Path(run_mod.__file__).with_name("requirements") / "studio.txt" | ||
| for line in requirements.read_text(encoding = "utf-8").splitlines(): |
There was a problem hiding this comment.
Validate transitive runtime dependencies
When an interrupted pip update leaves a direct package installed but removes or truncates one of its dependencies, this loop still reports readiness because it examines only requirements explicitly listed in studio.txt. For example, starlette is imported by studio/backend/main.py but is only a dependency of FastAPI; _load_run_module() does not import main because that happens inside run_server at studio/backend/run.py:1498, so a missing Starlette passes this check and crashes only when the managed server starts. Recursively validate installed distributions' Requires-Dist entries, or otherwise probe the imports performed during actual backend startup.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed, and it is reachable today. starlette is not a line in studio.txt, studio/backend/main.py:292 imports it, and run.py imports main inside run_server at :1498, so _load_run_module() never touches it. The probe passed and the server died on launch.
e15ce94 walks the installed metadata instead of just the file's own lines: markers applied, extras skipped, cycles terminated on a PEP 503 normalised key. Version bounds stay limited to studio.txt's own pins because install_python_stack installs with --no-deps, so an unmet transitive bound can describe a venv that works, and reporting it would send repair round a loop it cannot break.
Measured on a full closure: 56 distributions, 46ms, no imports. Removing starlette's metadata reports starlette. Two regression tests cover the transitive miss and the extras/cycle cases.
| let _ = app.emit("repair-complete", ()); | ||
| return Ok(()); | ||
| } | ||
| Ok(()) => { |
There was a problem hiding this comment.
Stop repair when readiness fails on environment settings
When repair starts from an older CLI that predates desktop-runtime-check, the incremental update can install the new check and then discover an inherited invalid setting such as UNSLOTH_CPU_THREADS. The boolean readiness result loses the new studio_runtime_startup_failed classification, so this arm runs the bundled installer even though the surrounding preflight logic explicitly treats that reason as unrepairable; after reinstalling, the same setting still fails and the user receives only the generic repair failure. Preserve the stale reason after the update and terminate repair with the environment-specific error instead of falling through to installation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed. The update can install the newer CLI and only then hit a rejected environment value, and no reinstall changes that. e15ce94's parent adds managed_install_state(), which returns the stale reason rather than a bare bool, so start_managed_repair can tell an unrepairable cause from a stale install and emit repair-failed with the setting to fix instead of running the bundled installer over a healthy tree. Covered by rejected_settings_stop_repair_instead_of_reinstalling.
| async fn predates_runtime_check(bin: &Path) -> bool { | ||
| !run_cli_probe(bin, &["studio", "desktop-runtime-check", "--help"]).await | ||
| && run_cli_probe(bin, &["-h"]).await |
There was a problem hiding this comment.
Bound the legacy fallback to the original probe timeout
When a damaged managed executable hangs before command dispatch, the initial runtime check consumes its 10-second timeout and this fallback then runs two more probes sequentially, each with another 10-second timeout. Because !run_cli_probe(... --help) && run_cli_probe(... -h) evaluates both calls after the first timeout returns false, desktop preflight can remain on the checking screen for roughly 30 seconds before classifying the install as stale, tripling the previous launch-probe delay precisely for broken installs. Reuse a single overall deadline or avoid the second legacy probe once the timeout budget is exhausted.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. A hung binary now returns its own reason and skips the legacy fallback: an older CLI rejects the unknown command straight away, so only a broken one reaches the timeout, and running two more probes on it would treble the wait before repair. a_hung_cli_is_stale_without_running_the_legacy_fallback asserts the reason and that the whole path stays under 20s.
install.sh decides on elevation at :1931, before it creates the venv at :2120, so only a spawn failure and that exit prove pip never ran. A nonzero exit or a failed wait can land part-way through replacing a package, and the runtime probe does not reach transitive dependencies, so clearing the marker there throws away the only remaining signal. Also treat a hung CLI as stale on its own timeout rather than falling through to two more probes, and let repair report an environment the backend rejects instead of reinstalling over a healthy tree.
The readiness probe walked only the requirement file's own lines, so a package that reaches the venv as someone else's dependency read as present. starlette is the live case: studio/backend/main.py imports it, FastAPI is what pulls it in, and run.py imports main inside run_server, so the probe passed and the server died on launch. Walk the installed metadata instead, markers applied and extras skipped. Version bounds stay limited to studio.txt's own pins: install_python_stack installs with --no-deps, so a transitive bound can read unsatisfied in a venv that works, and reporting it would send repair round a loop it cannot break. 56 distributions on a full closure, 46ms, no imports.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 22c6c277ba
ℹ️ 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".
| if key in seen: | ||
| continue |
There was a problem hiding this comment.
Check root pins before deduplicating dependencies
When a package is first reached transitively, this early seen check prevents its later direct studio.txt requirement from reaching the root-only version validation. In the current requirements, datasets==4.3.0 declares huggingface-hub>=0.25,<2, so it marks the hub as seen before huggingface-hub==0.36.2 is processed; an incompatible installed hub version can therefore pass the runtime check and make preflight report the managed install ready. Preserve whether a name has an unvalidated root requirement, or validate all direct roots before walking the transitive closure.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed, and it is my regression from the walk I added in the previous round. datasets==4.3.0 declares huggingface-hub>=0.25,<2, so the hub was marked seen as a dependency and studio.txt's ==0.36.2 never reached the version check.
aaa00ae checks every root before the walk starts: the roots are added to seen up front, each is visited as a root, and only then does the transitive queue run. A root listed twice still gets both lines checked, and a name reached transitively after that is skipped as before. Regression test asserts huggingface-hub is reported when datasets names it first.
| Err(msg) => { | ||
| // Nothing ran, so nothing is half-installed. | ||
| clear_install_marker_best_effort(); |
There was a problem hiding this comment.
Keep the active install marker on rejected duplicate starts
If two start_install or repair invocations overlap, both create the shared marker, but the invocation that loses the atomic spawn_script check receives “Installation is already running” and deletes that marker here while the first installer is still modifying the venv. If the active installer is then interrupted, the recovery signal this change relies on is gone. Only clear the marker for spawn failures that occur when no installer is already active, or associate marker ownership with the active invocation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right. spawn_script returns that same error whether the process failed to start or the atomic check rejected it, and the call site cleared the marker either way, so the loser of the race deleted the winner's marker with pip still inside the venv.
Split via a shared INSTALL_ALREADY_RUNNING constant: the guard returns it, the call site keeps the marker for it, and every other spawn failure still clears. No unit test for this one, since both sides reference the same constant and the branch has no other input.
| if let Err(reason) = probe_cli_runtime(&bin).await { | ||
| // Every released CLI predates this subcommand, so a missing-command exit | ||
| // must not strand an install the launch probe still accepts. | ||
| if reason != "studio_runtime_probe_failed" || !predates_runtime_check(&bin).await { |
There was a problem hiding this comment.
Probe legacy CLIs before declaring them runtime-ready
For an install created by an older desktop release, there is no new marker and the installed CLI predates desktop-runtime-check; if that install was interrupted and is missing a backend dependency such as structlog, both the unknown-command help probe and top-level -h behave exactly like a healthy legacy CLI, so this fallback proceeds to the capability check and reports ManagedReady. This leaves existing users affected by the original interrupted-install failure on the same backend-crash path after upgrading the desktop app. The legacy path needs an equivalent runtime/import check rather than treating CLI launchability as runtime readiness.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, and this is the case the PR exists for. DESKTOP_MANAGEABILITY_VERSION is still 1 here, so a legacy CLI passes the capability check, and -h never touches the backend. The users with an interrupted install were left on the same crash after upgrading the desktop app.
That path now returns Stale with studio_runtime_check_unsupported instead of falling through: repairable, so the update installs a CLI that can answer, and the next preflight checks the venv for real. The reason stays distinct from studio_runtime_probe_failed so a broken new CLI is not filed as an old one. The existing test flipped to assert the new outcome, and the unlaunchable case still keeps the plain probe failure.
| let reader = tokio::spawn(async move { | ||
| let mut buffer = Vec::new(); | ||
| let _ = stdout.read_to_end(&mut buffer).await; | ||
| buffer |
There was a problem hiding this comment.
Bound output captured by runtime probes
The runtime command imports backend and third-party modules, so its stdout is not inherently bounded; draining it into a growing Vec lets a noisy or hung import allocate memory as fast as it can write for the full 10-second timeout, potentially exhausting the desktop process before the timeout can trigger. Since the caller only needs the final JSON payload, stream through a bounded tail buffer or enforce a byte cap while continuing to drain the pipe.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The concern is the right shape but the producer is our own CLI: desktop-runtime-check imports the backend and prints one JSON line, and the backend's import chatter is kilobytes. Ten seconds of that does not approach a memory problem, and there is no path by which real input makes it one, so I would rather not add a tail buffer to guard against a hypothesis.
Draining is still needed, which is why the read runs concurrently with the wait: without it a chatty import fills the pipe buffer and a healthy install times out into repair.
There was a problem hiding this comment.
Correcting my earlier reply here: the same point was raised again on the current head and it is right. My reasoning was that the producer is our own CLI and therefore well behaved, but the binary this probe runs is a possibly damaged install by construction, so an import stuck printing is input this path can actually meet. Bounded to a 64 KiB tail in 984cafc.
| let Some(owned) = proc.owned.take() else { | ||
| return BackendExitPoll::Stop; | ||
| }; | ||
| proc.port = None; |
There was a problem hiding this comment.
Reserve owner metadata until exit cleanup finishes
When an exited backend leader leaves descendants, cleanup_after_exit can spend up to five seconds terminating the process group, but this removes the owned handle and releases the state lock before that cleanup begins. If another start command arrives during that window, it can create the next backend and overwrite desktop_backend.json; the old handle then unconditionally removes the same path, causing the new backend's ownership and port validation to fail. Keep the backend slot reserved through cleanup or make metadata removal conditional on the old owner token.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Verified. poll_spawned_backend_exit takes the handle and returns, so the lock is released before cleanup_after_exit runs, and terminate_exited_backend_tree can spend up to five seconds on surviving descendants. A start in that window writes the next backend's metadata to the same path, and the old handle then removed it unconditionally.
BackendOwnerState::remove now reads the file first and leaves it alone when token_sha256 belongs to someone else. Unreadable still counts as ours, otherwise a corrupt file would outlive every backend and fail each later ownership check. Two tests: a replaced file survives the previous backend's cleanup, and an owner still holding its own file removes it.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6ee7985e85
ℹ️ 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".
| } | ||
| }; | ||
|
|
||
| let Ok(output) = reader.await else { |
There was a problem hiding this comment.
Bound the stdout drain by the probe timeout
When desktop-runtime-check or code imported by it starts a descendant that inherits stdout and then the CLI leader exits, child.wait() completes but the pipe remains open, so this unbounded reader.await never returns. Because the 10-second timeout covers only the leader wait, a damaged runtime can hang desktop_preflight and leave Studio indefinitely stuck during startup; include the drain in the timeout or abort it after a bounded post-exit wait.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and the pipe semantics are the part I missed. child.wait() returns when the leader exits, but the write end stays open while any descendant holds it, so read_to_end sat outside the 10s budget and preflight could hang for good. Bounding the buffer last round did nothing for that.
c1e13d4 gives each probe one deadline covering both the wait and the drain, via timeout_at, and aborts the reader if the drain is what runs out. A drain that outlives its leader now reports studio_runtime_probe_timeout rather than blocking, which is repairable. Same change on the capability probe, which had the identical shape.
| packages.add(top) | ||
| return any(not installed.locate_file(name).exists() for name in packages) |
There was a problem hiding this comment.
Check recorded files instead of only package roots
When pip or uv is interrupted after recreating a package directory but before writing all of its files, this reduction turns every RECORD entry such as starlette/__init__.py and starlette/routing.py into the same starlette directory and therefore reports the partial installation as complete. This is exactly a possible interrupted wheel replacement, and for dependencies imported only inside run_server the runtime check can consequently return ready before the backend crashes; check the relevant recorded files rather than only their first path component.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, and this undercuts the fix I made for it. Reducing every RECORD entry to its first path component meant a package directory that pip had recreated but not finished filling read as complete, which is precisely the interrupted replacement this is meant to catch.
c1e13d4 stats each recorded file instead. Cost measured on studio.txt's real closure: 6656 files across 56 distributions, 158ms, against a probe that imports the whole backend. Swept all 298 distributions in a working venv, nothing flagged.
One exclusion worth naming: pycache and .pyc entries are skipped. pip records the bytecode it compiles, and deleting pycache is a normal thing to do, so counting it as damage would send a healthy install into a repair that cannot clear it. The test now covers all three states: no directory, directory with one of two files, and complete.
| if !exit.intentional { | ||
| error!("Backend process exited unexpectedly (crash detected)"); | ||
| let _ = app.emit("server-crashed", ()); |
There was a problem hiding this comment.
Suppress crash events from superseded generations
When descendant cleanup takes several seconds and a replacement backend starts after poll_spawned_backend_exit has already removed the old handle, this monitor still emits the old generation's server-crashed event after cleanup finishes. The frontend handles that event unconditionally by setting Server stopped unexpectedly, so a healthy replacement is shown as failed; recheck the current generation before emitting the crash event.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Verified. poll_spawned_backend_exit returns while the generation is still ours, cleanup_after_exit then runs for up to five seconds, and the emit afterwards was unconditional. A start in that window bumps the generation, so the frontend set "Server stopped unexpectedly" on a backend that was in fact healthy.
c1e13d4 re-reads the generation after cleanup and only emits when it still matches. The exit is still recorded in diagnostics either way, since the exit did happen; it is only the crash event the replacement makes wrong. The decision is a small pure function so it is covered by a test: reportable when unintentional and current, not when superseded, not when intentional.
A descendant that inherits stdout keeps the pipe open after the CLI leader exits, so the drain sat outside the timeout and could wedge preflight for good. Both probes now share one deadline across the wait and the drain. Stat every file RECORD lists, not just the top-level names. An interrupted replace can recreate a package directory and stop part-way through filling it, which the directory check read as complete. 6656 files across studio.txt's closure cost 158ms, and __pycache__ is skipped: deleting it is not damage. Cleanup after an exit can take seconds, so a start in that window already owns the backend by the time the crash event fires. The frontend sets "Server stopped unexpectedly" on it unconditionally, which showed a healthy replacement as failed.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c1e13d41c8
ℹ️ 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".
| if msg != INSTALL_ALREADY_RUNNING { | ||
| clear_install_marker_best_effort(); |
There was a problem hiding this comment.
Preserve pre-existing markers when repair cannot spawn
When this is a retry for an interrupted installation, the marker already existed before this attempt. If the bundled repair then fails to spawn—for example because the script or shell cannot be launched—this branch deletes that old marker even though the partially modified venv remains. The next launch therefore loses the install_incomplete classification and can try the incremental-update path that this marker was intended to bypass. Track whether this attempt created a new marker and only clear it on pre-spawn failures when no older interrupted-install marker existed; the elevation cancellation/failure cleanup needs the same distinction.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct. A retry after an interrupted install finds the earlier marker already there, create_install_in_progress_marker_at returns Ok on AlreadyExists, and a repair that then failed to spawn deleted it. The next launch loses install_incomplete and takes the incremental path the marker exists to bypass. The two elevation exits had the same problem.
7e2292f makes creation report whether it created the file, and the three pre-spawn paths clear only when it did. Success still clears unconditionally, since a finished install is a whole venv. The marker test now asserts the second attempt is told it does not own the file.
| across studio.txt's closure cost 158ms, against a probe that imports the | ||
| backend, and __pycache__ is skipped because deleting it is not damage. | ||
| """ | ||
| for recorded in installed.files or (): |
There was a problem hiding this comment.
Parse RECORD instead of trusting filtered files
On Python 3.13—the default interpreter selected by both desktop installers—importlib.metadata.Distribution.files filters out entries whose paths do not currently exist. This loop therefore never receives the missing RECORD entries it is intended to detect, so a partially unpacked dependency that retains its metadata but is missing lazily imported files can still pass readiness and crash only when run_server imports it. Read the installed RECORD directly, or otherwise obtain its unfiltered entries, rather than relying on installed.files for this comparison.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Verified, and it makes the last two rounds of this check dead code. On 3.13.12 I built a dist-info whose RECORD names four entries with one file deleted: Distribution.files returned three, silently dropping exactly the entry the check looks for. So a partially unpacked dependency passed.
7e2292f parses RECORD directly through read_text, keeping the same filters (.dist-info, .data, ../, pycache and .pyc). The ghost fixture is reported as damaged and clean again once the file is restored, and a sweep of all 298 distributions in a working venv flags none. files is still what distinguishes no-RECORD-at-all, and egg-info returns None, where completeness is not knowable and nothing is claimed.
The test was the real gap: it stubbed files directly, so it could not have caught this. It builds a real dist-info on disk now.
Distribution.files drops entries whose paths no longer exist, which is precisely the set the last change looked for, so on 3.13 (what both desktop installers pick) the check could never fire. Verified against a dist-info whose RECORD names a deleted file: files returned 3 of 4 entries and the damaged package read as complete. RECORD is parsed directly now, and the test builds a real dist-info rather than a stub so it would have caught this. The marker is also not always ours. A retry after an interrupted install finds the earlier one still there, and a repair that then fails to spawn was deleting it, losing the classification the next launch depends on. Creation reports whether it created the file; the pre-spawn and elevation paths clear only then, and success still clears unconditionally.
|
@codex review |
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
The interrupted-install check had two implementations, and they diverged. The PowerShell one ran only `unsloth -h` and `studio desktop-capabilities`, so it could not observe studio_install_ok, verify-install or desktop-runtime-check -- the exact signals unslothai#7492 and unslothai#7490 add. It therefore reported FALSE_READY for those PRs no matter how well they worked, and I nearly read that as "neither PR fixes it". A probe that cannot observe the fix is worse than no probe, so there is now a single Python implementation used on macOS, Linux and Windows. Python is guaranteed present after an install, which is what makes one file viable. It also owns the process tree it spawns. Terminating just the parent left uvicorn/python children holding the port, which hung the healthy case outright -- the same process-group lesson as the interrupt driver. Verified against four mock CLIs: today's tree -> FALSE_READY, unslothai#7492's manifest -> REPAIRABLE, unslothai#7490's runtime check -> REPAIRABLE, a working install -> HEALTHY.
The interrupted-install check had two implementations, and they diverged. The PowerShell one ran only `unsloth -h` and `studio desktop-capabilities`, so it could not observe studio_install_ok, verify-install or desktop-runtime-check -- the exact signals unslothai#7492 and unslothai#7490 add. It therefore reported FALSE_READY for those PRs no matter how well they worked, and I nearly read that as "neither PR fixes it". A probe that cannot observe the fix is worse than no probe, so there is now a single Python implementation used on macOS, Linux and Windows. Python is guaranteed present after an install, which is what makes one file viable. It also owns the process tree it spawns. Terminating just the parent left uvicorn/python children holding the port, which hung the healthy case outright -- the same process-group lesson as the interrupt driver. Verified against four mock CLIs: today's tree -> FALSE_READY, unslothai#7492's manifest -> REPAIRABLE, unslothai#7490's runtime check -> REPAIRABLE, a working install -> HEALTHY.
This is the trigger neither unslothai#7492 nor unslothai#7490 addresses -- both start from a venv that is already broken. Confirmed: neither PR touches cleanup_child_processes. Quitting runs cleanup_child_processes -> install::stop_install, which SIGTERMs the installer's process group. In the reported session that landed at "5/10 studio deps", so the venv kept the CLI's dependencies and lost the server stack, and the next launch died on `import structlog`. Three minutes of installing, destroyed with no warning and no way back. So ask. Only from the tray Quit item -- a deliberate action with a UI present. The RunEvent::Exit path (OS shutdown, SIGTERM) is left alone: it must never block on a dialog nobody can answer. The call already runs off the menu callback thread, which is also what blocking_show requires. Closing the window was already safe (it hides to tray); this closes the remaining way to lose an install by accident.
Reported macOS session: the user quit the app during the dependency pass. That
SIGTERMs the installer process group (main.rs cleanup_child_processes ->
install::stop_install), and it landed in the "studio deps" step -- the one that
installs studio/backend/requirements/studio.txt, where structlog is declared. The
venv kept the CLI's own dependencies and lost the server stack.
On relaunch, preflight probed `unsloth -h` (ok in 1601ms) and
`studio desktop-capabilities` (ok in 143ms). Both passed, because typer/click/rich
are core deps -- so the app reported disposition=ManagedReady with
can_auto_repair=false. The backend then died with
ModuleNotFoundError: No module named 'structlog'
and the UI showed "Server stopped unexpectedly": no cause, no action, no way out.
The evidence was already in hand. The app captures that stderr into proc.logs and
never read it. A failed import is ground truth in a way a probe cannot be -- a
probe only checks what someone thought to check, which is exactly how two passing
probes sat on top of an unbootable venv. So classify the exit from the traceback,
send an incomplete install to the existing repair flow, and keep the generic
message for everything else.
Two details worth keeping:
The traceback arrives on STDERR while crash detection runs in the STDOUT reader,
so they race. Reading immediately would usually miss it and mislabel a broken
install as a plain crash, hence the short bounded poll after the lock is released
-- once the process has exited the stderr pipe is at EOF and drains in
milliseconds.
The auto-repair is latched to once per session. A repair that does not fix the
import would otherwise crash -> repair -> crash forever.
Complementary to unslothai#7492 and unslothai#7490 rather than a replacement: they stop the venv
being reported ready, this makes the failure recoverable if anything still slips
through.
This is the trigger neither unslothai#7492 nor unslothai#7490 addresses -- both start from a venv that is already broken. Confirmed: neither PR touches cleanup_child_processes. Quitting runs cleanup_child_processes -> install::stop_install, which SIGTERMs the installer's process group. In the reported session that landed at "5/10 studio deps", so the venv kept the CLI's dependencies and lost the server stack, and the next launch died on `import structlog`. Three minutes of installing, destroyed with no warning and no way back. So ask. Only from the tray Quit item -- a deliberate action with a UI present. The RunEvent::Exit path (OS shutdown, SIGTERM) is left alone: it must never block on a dialog nobody can answer. The call already runs off the menu callback thread, which is also what blocking_show requires. Closing the window was already safe (it hides to tray); this closes the remaining way to lose an install by accident.
The interrupted-install lanes ran install.sh without --local, so install.sh:3996 resolved unsloth from PyPI and the venv got the published CLI. Every probe of `studio verify-install` and `studio desktop-runtime-check" then reported 'absent' regardless of the branch, so the lanes could not observe the fixes they exist to measure -- the B1/B2 FALSE_READY verdicts said nothing about unslothai#7492/unslothai#7490. Also stand in for the desktop app's .desktop-install-in-progress marker. We kill install.sh directly instead of driving the app, so the marker unslothai#7490 relies on was missing for a reason unrelated to unslothai#7490.
The interrupted-install lanes ran install.sh without --local, so install.sh:3996 resolved unsloth from PyPI and the venv got the published CLI. Every probe of `studio verify-install` and `studio desktop-runtime-check" then reported 'absent' regardless of the branch, so the lanes could not observe the fixes they exist to measure -- the B1/B2 FALSE_READY verdicts said nothing about unslothai#7492/unslothai#7490. Also stand in for the desktop app's .desktop-install-in-progress marker. We kill install.sh directly instead of driving the app, so the marker unslothai#7490 relies on was missing for a reason unrelated to unslothai#7490.
Reported macOS session: the user quit the app during the dependency pass. That
SIGTERMs the installer process group (main.rs cleanup_child_processes ->
install::stop_install), and it landed in the "studio deps" step -- the one that
installs studio/backend/requirements/studio.txt, where structlog is declared. The
venv kept the CLI's own dependencies and lost the server stack.
On relaunch, preflight probed `unsloth -h` (ok in 1601ms) and
`studio desktop-capabilities` (ok in 143ms). Both passed, because typer/click/rich
are core deps -- so the app reported disposition=ManagedReady with
can_auto_repair=false. The backend then died with
ModuleNotFoundError: No module named 'structlog'
and the UI showed "Server stopped unexpectedly": no cause, no action, no way out.
The evidence was already in hand. The app captures that stderr into proc.logs and
never read it. A failed import is ground truth in a way a probe cannot be -- a
probe only checks what someone thought to check, which is exactly how two passing
probes sat on top of an unbootable venv. So classify the exit from the traceback,
send an incomplete install to the existing repair flow, and keep the generic
message for everything else.
Two details worth keeping:
The traceback arrives on STDERR while crash detection runs in the STDOUT reader,
so they race. Reading immediately would usually miss it and mislabel a broken
install as a plain crash, hence the short bounded poll after the lock is released
-- once the process has exited the stderr pipe is at EOF and drains in
milliseconds.
The auto-repair is latched to once per session. A repair that does not fix the
import would otherwise crash -> repair -> crash forever.
Complementary to unslothai#7492 and unslothai#7490 rather than a replacement: they stop the venv
being reported ready, this makes the failure recoverable if anything still slips
through.
The interrupted-install check had two implementations, and they diverged. The PowerShell one ran only `unsloth -h` and `studio desktop-capabilities`, so it could not observe studio_install_ok, verify-install or desktop-runtime-check -- the exact signals unslothai#7492 and unslothai#7490 add. It therefore reported FALSE_READY for those PRs no matter how well they worked, and I nearly read that as "neither PR fixes it". A probe that cannot observe the fix is worse than no probe, so there is now a single Python implementation used on macOS, Linux and Windows. Python is guaranteed present after an install, which is what makes one file viable. It also owns the process tree it spawns. Terminating just the parent left uvicorn/python children holding the port, which hung the healthy case outright -- the same process-group lesson as the interrupt driver. Verified against four mock CLIs: today's tree -> FALSE_READY, unslothai#7492's manifest -> REPAIRABLE, unslothai#7490's runtime check -> REPAIRABLE, a working install -> HEALTHY.
This is the trigger neither unslothai#7492 nor unslothai#7490 addresses -- both start from a venv that is already broken. Confirmed: neither PR touches cleanup_child_processes. Quitting runs cleanup_child_processes -> install::stop_install, which SIGTERMs the installer's process group. In the reported session that landed at "5/10 studio deps", so the venv kept the CLI's dependencies and lost the server stack, and the next launch died on `import structlog`. Three minutes of installing, destroyed with no warning and no way back. So ask. Only from the tray Quit item -- a deliberate action with a UI present. The RunEvent::Exit path (OS shutdown, SIGTERM) is left alone: it must never block on a dialog nobody can answer. The call already runs off the menu callback thread, which is also what blocking_show requires. Closing the window was already safe (it hides to tray); this closes the remaining way to lose an install by accident.
The interrupted-install lanes ran install.sh without --local, so install.sh:3996 resolved unsloth from PyPI and the venv got the published CLI. Every probe of `studio verify-install` and `studio desktop-runtime-check" then reported 'absent' regardless of the branch, so the lanes could not observe the fixes they exist to measure -- the B1/B2 FALSE_READY verdicts said nothing about unslothai#7492/unslothai#7490. Also stand in for the desktop app's .desktop-install-in-progress marker. We kill install.sh directly instead of driving the app, so the marker unslothai#7490 relies on was missing for a reason unrelated to unslothai#7490.
Only interrupt-install.sh got this, so every Windows leg reported install_in_progress_marker=False regardless of the branch -- the marker unslothai#7490 relies on was missing for a reason unrelated to unslothai#7490, on the one platform that actually reproduced the bug.
Only interrupt-install.sh got this, so every Windows leg reported install_in_progress_marker=False regardless of the branch -- the marker unslothai#7490 relies on was missing for a reason unrelated to unslothai#7490, on the one platform that actually reproduced the bug.
|
I built CI that interrupts an install at each phase and asserts the result is never silently ready, and ran this PR through it. Three things worth passing on. 1. This now conflicts with main, and the test fixtures break in a non-obvious way#7492 merged this morning, so this PR conflicts in #7492 bumps The fixture at Only the fixtures this PR adds are affected; the ones both PRs touch were carried over by the merge. Note the sibling fixture at With that one change, 2. Measured against the reported failureKilling the installer's process group at the
Both detect it. So the reported dead end is already closed by #7492, and the fair question is whether this PR still earns its place. 3. It does, and here is the specific reason
So a venv missing I added a CI job that constructs exactly that state (install fully, assert healthy, remove the Two smaller notes
Reconciled branch with all of the above resolved is at |
* Desktop: ask before quitting on top of a running install This is the trigger neither #7492 nor #7490 addresses -- both start from a venv that is already broken. Confirmed: neither PR touches cleanup_child_processes. Quitting runs cleanup_child_processes -> install::stop_install, which SIGTERMs the installer's process group. In the reported session that landed at "5/10 studio deps", so the venv kept the CLI's dependencies and lost the server stack, and the next launch died on `import structlog`. Three minutes of installing, destroyed with no warning and no way back. So ask. Only from the tray Quit item -- a deliberate action with a UI present. The RunEvent::Exit path (OS shutdown, SIGTERM) is left alone: it must never block on a dialog nobody can answer. The call already runs off the menu callback thread, which is also what blocking_show requires. Closing the window was already safe (it hides to tray); this closes the remaining way to lose an install by accident. * Tighten comments in desktop quit-during-install guard * Condense comments in quit-during-install guard --------- Co-authored-by: danielhanchen <[email protected]>
Summary
ManagedReadyRoot cause
Quitting the desktop app during the
studio depstransaction can leave a usableunslothCLI withoutstructlogor other Studio dependencies. The existing preflight checks still pass, so the app starts an incomplete backend and reports an unexpected server stop.Validation
cargo test --manifest-path studio/src-tauri/Cargo.tomlwith 70 passing testscargo xwin check --locked --target x86_64-pc-windows-msvc --tests