Repository navigation
Studio: stop a quit during a model load from orphaning llama-server - #10430
danielhanchen wants to merge 1 commit into
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. |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 51abdb83cc
ℹ️ 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".
| first would otherwise take that as permission to spawn into the new one. None means | ||
| the caller has no session to compare, so only the latch applies. | ||
| """ | ||
| if _shutdown_latch.is_set(): |
There was a problem hiding this comment.
Read the shutdown latch under the generation lock
When mark_process_shutting_down() sets the latch after this unlocked read but before is_process_shutting_down() acquires _generation_lock, this function can return False because the admitted generation still matches. If a post-spawn check is paused in that window while shutdown completes its PID snapshot, a helper llama-server or inference worker can consequently remain outside the completed sweep. Check the latch and generation atomically under _generation_lock, or recheck the latch before returning.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The split read is already linearizable, so moving it under the lock adds no safety.
_lifecycle_generation is monotonic: it is initialised once at import (process_lifetime.py:1002) and the only write is += 1 under _generation_lock (process_lifetime.py:1072). There is no reset path, including the fork handler.
Given that, take a call to is_process_shutting_down(admitted) that reads the latch at t1 and the generation at t2 > t1:
- Returns True. Either the latch was set at t1, or
admitted != generationat t2. Either way the returned value held at the instant it was read. - Returns False. Then the latch was clear at t1 and
generation == admittedat t2. Because the generation only ever increases,generation(t1) <= generation(t2) == admitted, andadmittedwas itself a generation value read earlier, sogeneration(t1) == admittedtoo. Both conjuncts therefore held together at t1.
So every result is one that was true at some instant inside the call. That is the strongest guarantee available here regardless of locking, because the predicate is a check-then-act: the caller can be preempted after it returns no matter how the read is done. That is why the spawn path does not rely on the check alone. orchestrator._spawn_subprocess rechecks after adopt_pid and reaps a worker that was born during shutdown, and llama_cpp._start_llama_process does the same after _record_server_pid. Those post-spawn rechecks, not the width of the read, are what close the window.
Holding _generation_lock across the latch read would also put the module least under contention on the hot spawn path for no behavioural change.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 51abdb83cc
ℹ️ 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".
| terminate_all(sweep_generation = _sweep_generation) | ||
| clear_breadcrumb() # nothing left for the next startup to sweep |
There was a problem hiding this comment.
Preserve records skipped by lifecycle-scoped sweeps
When an embedded restart times out waiting for the previous shutdown, the new lifecycle can adopt children before this old-generation sweep runs. terminate_all(sweep_generation=...) correctly leaves those newer children tracked, but the immediately following clear_breadcrumb() deletes their on-disk record anyway. On macOS, where this breadcrumb is the only recovery mechanism after a Force Quit or crash, a later abnormal exit can therefore orphan the new lifecycle's workers permanently. Keep or rewrite the breadcrumb whenever the scoped sweep skipped tracked children.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The breadcrumb is already preserved in this case, by clear_breadcrumb itself:
def clear_breadcrumb() -> None:
with _record_lock:
if _tracked_pids:
_write_breadcrumb()
return
path = _breadcrumb_file()
if path is not None:
_unlink(path)A lifecycle-scoped sweep deliberately leaves the skipped children in _tracked_pids (it pops only the pids it actually reaps), so _tracked_pids is non-empty when run.py step 7 calls clear_breadcrumb(), and the file is rewritten rather than unlinked. The unlink branch is reachable only when nothing is tracked, which is exactly when the file has nothing left to describe.
Verified directly rather than by reading. Latch a shutdown, reopen the lifecycle, adopt a child under the new generation, run the scoped sweep for the old generation, then clear_breadcrumb():
child alive: True
still tracked: True
breadcrumb exists: True | mentions pid: True
The survivor is still on disk and still named in the record, so the next startup reap_recorded_children sweep can find it.
|
Codex Review: Didn't find any major issues. 🎉 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". |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9aa69a161c
ℹ️ 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".
| try: | ||
| from utils.process_lifetime import adopt_pid | ||
| adopt_pid(_spawned.pid) |
There was a problem hiding this comment.
Recheck shutdown after spawning the diffusion runner
When shutdown is latched after the in-lock check but before adopt_pid() completes, a helper-owned backend is not touched by run.py's singleton teardown and the shutdown sweep may already have taken its snapshot, leaving the shim and visual server alive throughout the 600-second health wait and potentially orphaned when the host exits. Fresh evidence in the current tree is that the primary llama-server paths now recheck _spawn_is_stale() immediately after recording the PID, while this diffusion path still proceeds directly from adoption to starting the drain thread and health wait; apply the same post-adoption stale check and reap the runner immediately.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and it was an inconsistency in my own change rather than a pre-existing gap: the llama-server spawns gained a post-adoption recheck and _start_diffusion_server did not, even though it has the same in-lock refusal a few lines above and the same helper-owned exposure.
Fixed. After adopt_pid, it now rechecks _spawn_is_stale() and, if shutdown has latched, kills the runner, closes the attempt log, sets _health_wait_cancelled and returns False -- the same five lines as the refusal already in that function, so both exits behave identically.
Note the PR has since been squashed and rebased, and its scope deliberately narrowed to the orphan-on-quit fix; the lifecycle-generation work that earlier rounds were reviewing is gone. Details in the rewritten description.
| @@ -477,6 +486,19 @@ def _spawn_subprocess( | |||
| from utils.process_lifetime import adopt_pid | |||
|
|
|||
| adopt_pid(self._proc.pid) # bind to parent lifetime (Windows job / sweep) | |||
There was a problem hiding this comment.
Retain the spawned inference worker across teardown races
When shutdown enters _shutdown_subprocess() while Process.start() is still in progress, it can observe the process as not yet alive, clear self._proc, and complete its sweep before the bound start() call finishes creating the child. This line then dereferences self._proc instead of the process that was actually started, so it raises before adoption and before the new stale check, leaving that worker outside both teardown and the lifetime record. Keep a local process handle and synchronize its publication with shutdown, or explicitly terminate that local child if publication was overtaken.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Genuine, and the failure mode is worse than it first looks: the dereference raises before adopt_pid, so the child ends up outside the teardown AND outside the lifetime record, which is exactly the orphan this PR exists to prevent.
Fixed by keeping a local handle. _spawned_proc = self._proc is taken inside the spawn block immediately after start(), and adoption and the pid log now use that local rather than re-reading the attribute a concurrent _shutdown_subprocess may have cleared.
I also took the second half of your remedy, because the local handle alone is not enough: the guard now trips on is_process_shutting_down() or self._proc is not _spawned_proc, and when shutdown has already dropped the mirror it terminates and joins the local child explicitly, since _shutdown_subprocess can no longer see it.
I did not take the "synchronize its publication with shutdown" option. _shutdown_subprocess holds its lock for the whole teardown, so a lock across the spawn would make quitting queue behind a spawn it is about to undo -- the comment above this guard already records that trade-off.
Scope note as above: the PR is now squashed to a single commit and narrowed to the orphan-on-quit fix.
Quitting Studio while a model was loading could leave a llama-server child running after the app was gone. Each subsystem already refused to respawn its own child once its teardown step had run, but that state lives on the object being torn down, and a load in flight can reach a spawner that nothing marked: the orchestrator is stopped at step 2 and the backstop sweep runs at step 7, and a helper or advisor load owns a LlamaCppBackend that no step touches at all. A load crossing one of those gaps started a server after the sweep had already taken its snapshot, so nothing reaped it. One flag, set before any subsystem is torn down and read at every spawn: - process_lifetime gains mark_process_shutting_down / is_process_shutting_down, latched at step 0a of _graceful_shutdown. Every spawn path consults it, so the answer no longer depends on which object a spawn happens to belong to. - The llama-server spawn takes _spawn_lock across the check, the Popen and the pid record, and rechecks afterwards: mark_process_shutting_down does not take that lock, so a child born in the gap is reaped rather than left behind for the length of a 600s health wait. The inference worker spawn does the same. - Shutdown cancels in-flight loads before the kill. A request sitting in the lifecycle gate or in preflight holds nothing the backend's own flag can see, and would otherwise spawn after step 5 had run. - The llama-server teardown is marked as a teardown rather than a crash, so an in-flight health wait ends instead of reporting a startup failure, and the publish paths refuse to advertise a model whose worker shutdown has killed. - begin_process_lifecycle clears the latch, because studio/backend/colab.py calls run_server again in the same interpreter and a sticky flag would leave that second session refusing every spawn. Scope: this fixes the orphan on quit. It does not try to make an embedded restart safe against a shutdown that is still running underneath it -- an old session's work can still cross into a new one, exactly as it can on main today. That is a separate concern and is left for a follow-up rather than widened into this change.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 378a8642fb
ℹ️ 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".
| # returning; re-reading the attribute here would then raise before this | ||
| # child was ever adopted, leaving it outside both the teardown and the | ||
| # lifetime record. | ||
| _spawned_proc = self._proc |
There was a problem hiding this comment.
Capture the worker handle before calling start
When shutdown enters _shutdown_subprocess() while Process.start() is still in progress, it can observe the process as not alive and clear self._proc before start() returns. Fresh evidence after the attempted fix is that _spawned_proc is still assigned from self._proc only after that return, so it becomes None and adopt_pid(_spawned_proc.pid) raises before the child is recorded or reaped, leaving the newly started inference worker outside the completed shutdown sweep. Store the newly constructed Process in the local variable before publishing it and calling start().
Useful? React with 👍 / 👎.
|
Superseded by #10592 and closing this one. Same fix, same final diff (one commit, 14 files), but on a fresh branch so the PR and its discussion match what is actually being proposed. This PR accumulated a long review history against a much larger earlier revision of the change, most of which is no longer in the diff at all. Nothing is lost:
|
The bug
Quitting Studio while a model is loading can leave a
llama-serverchild running after the app is gone.Every subsystem already refuses to respawn its own child once its teardown step has run, but that state lives on the object being torn down, and a load in flight can reach a spawner that nothing marked:
_graceful_shutdown, but the backstop sweep is step 7;hub/utils/llm_assist.py,utils/datasets/llm_assist.py) builds its ownLlamaCppBackend, which no teardown step touches at all;A load crossing any of those gaps starts a server after
terminate_allhas taken its snapshot, so nothing reaps it.The fix
One flag, set before any subsystem is torn down and read at every spawn.
mark_process_shutting_down/is_process_shutting_downinprocess_lifetime, latched at step 0a_spawn_lockheld across the check, thePopenand the pid record, plus a recheck aftermark_process_shutting_downdoes not take that lock, so a child born in the gap is reaped instead of surviving a 600s health waitactive_model_namewithout testing livenessbegin_process_lifecycleclears the latchstudio/backend/colab.pycallsrun_serveragain in the same interpreter; a sticky flag would leave that second session refusing every spawnScope
This fixes the orphan on quit. It deliberately does not try to make an embedded restart safe against a shutdown still running underneath it — an old session's work can still cross into a new one, exactly as it can on
maintoday. That is a separate concern and is left for a follow-up rather than widened into this change.An earlier revision of this PR did attempt it, growing to ~3,500 lines across 15 files (lifecycle generations, an admission
ContextVar, an ASGI stamp middleware, a lifecycle transition lock, generation-scoped sweeps). That work is preserved onstudio/teardown-restart-overlap-archiveif it is ever wanted, but it is a redesign of shutdown/restart lifecycle rather than a bug fix, and it does not belong in this PR.Verification
studio/backendsuite on this head against a freshly-run current-mainbaseline: 571 failed / 38,226 passed vs 571 failed / 38,177 passed — zero unique failures in either direction. The 571 are identical on both trees; the extra passes are this branch's new tests.torch,transformers,datasets,safetensors,requests,pymupdfortyper, so about two dozen modules do not import on either tree and their tests do not run. Valid as a differential, not as full coverage.tests/test_orchestrator_unload_cancel.pyandtests/test_llama_cpp_wait_for_health.py: 172 passing, covering the spawn-during-shutdown races, the teardown-vs-crash distinction, the post-spawn reap, and the load cancellation at shutdown.