Repository navigation
Studio: run the Shutdown cleanup off the event loop - #13534
Conversation
/api/shutdown and /api/desktop/shutdown called trigger_shutdown from a task on uvicorn's loop, so _graceful_shutdown ran on that loop and kept it blocked while it stopped subprocesses (llama-server: 5 s SIGTERM, then up to 5 s after SIGKILL). uvicorn could not act on should_exit and close the port until all of it finished, so on a loaded host the port stayed open past the chat UI test's 15 s check. The cleanup now runs on its own thread, like the SIGINT / SIGTERM path. The main thread still waits for it (_shutdown_event) before the process exits, and a second Shutdown joins the running cleanup. The chat UI test also waits for STUDIO_PID to exit after the port closes, so a stuck cleanup still fails.
|
You have reached your Codex usage limits for security reviews. Please try again later. |
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 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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c7824d88a4
ℹ️ 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".
| running = getattr(request.app.state, "_shutdown_thread", None) | ||
| if running is None: |
There was a problem hiding this comment.
Reset the shutdown-thread marker for restarted servers
When an embedded host starts Studio again in the same interpreter, the shared FastAPI app retains the completed _shutdown_thread from the first launch. Although run_server() installs a new trigger_shutdown for every launch, this check only tests whether the attribute is None, so every Shutdown request during the second launch returns success without invoking the new trigger and the server remains running. Clear the marker when a new server lifecycle begins, or permit creating a thread when the stored one is no longer alive.
Useful? React with 👍 / 👎.
| try: | ||
| os.kill(int(studio_pid), 0) | ||
| stat = Path(f"/proc/{studio_pid}/stat") # Linux: exited but not yet reaped is done | ||
| if stat.exists() and stat.read_text().rsplit(")", 1)[1].split()[0] == "Z": |
There was a problem hiding this comment.
Handle the proc-status disappearance race
On Linux, a successfully stopped Studio process can be reaped after stat.exists() returns true but before stat.read_text() opens the file. That raises FileNotFoundError, which is not caught by the ProcessLookupError handler, so the Playwright driver can fail even though shutdown completed correctly. Read the status file directly and treat FileNotFoundError as an exited process instead of separating the existence check from the read.
Useful? React with 👍 / 👎.
- The running-cleanup marker is keyed by the trigger: an embedded host's next run_server() installs a new trigger_shutdown, and its Shutdown must run it, not find the first launch's finished thread and do nothing. - The chat UI test reads /proc/<pid>/stat directly and treats the file vanishing (process reaped between the probe and the read) as exited.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9987bb362a
ℹ️ 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".
| state._shutdown_thread = threading.Thread( | ||
| target = trigger, name = "studio-shutdown" | ||
| ) | ||
| state._shutdown_thread.start() |
There was a problem hiding this comment.
Finish old cleanup before permitting an embedded relaunch
When an embedder starts a new run_server() after the old uvicorn thread/port has stopped but while this new cleanup thread is still running, the two lifecycles overlap. This was not possible while cleanup blocked uvicorn's loop, and the test avoids it by joining the first thread before relaunching. The old _graceful_shutdown can then run terminate_all() against children registered by the new launch, remove the new launch's PID file, and its _trigger_shutdown finally sets the module-global _shutdown_event that now belongs to the new launch. Wait for this thread before beginning another lifecycle, or capture and isolate all per-launch shutdown state.
Useful? React with 👍 / 👎.
| state._shutdown_thread = threading.Thread( | ||
| target = trigger, name = "studio-shutdown" | ||
| ) | ||
| state._shutdown_thread.start() |
There was a problem hiding this comment.
Signal uvicorn before running blocking cleanup
When Shutdown is clicked during an active training run, _graceful_shutdown() calls training.stop_for_shutdown()—whose default timeout is 120 seconds—before setting server.should_exit. Moving the whole trigger to this worker therefore leaves uvicorn's now-responsive event loop accepting and serving requests throughout that wait, so the port can remain open far beyond the 15-second window this change is intended to fix while teardown is already in progress. Set should_exit before the long cleanup begins, or split the trigger into an immediate server-stop signal followed by threaded subprocess cleanup.
Useful? React with 👍 / 👎.
Problem
After the Shutdown click in the chat UI test, Studio's port sometimes stayed open past the test's 15 s window (
tests/studio/playwright_chat_ui.py, step 19). On one switchboard run, head failed it 2 of 4 times and base 0 of 3. Base has the same code path and just stayed under 15 s in its runs.Cause:
/api/shutdownand/api/desktop/shutdownschedule_delayed_shutdownon uvicorn's event loop, and it callsapp.state.trigger_shutdown()directly. So_graceful_shutdownran on that loop and blocked it while it stopped every subprocess:terminate()with a 5 s wait, thenkill()with up to 5 s more, then the group and descendant sweep.server.should_exit = Trueis set early, but uvicorn can only act on it, and close the listening socket, once the loop is free again. In every failing run, a llama-server that ignored SIGTERM took 11 to 13 s to exit, and on a loaded host that pushed port-close past 15 s.The SIGINT / SIGTERM path does not have this problem: it runs
_graceful_shutdownon the main thread while uvicorn shuts down on its own.Change
main._schedule_shutdown: the cleanup runs on its ownstudio-shutdownthread, matching the signal path. uvicorn's loop stays free, so the port closes as soon as shutdown starts. The main thread still waits for_shutdown_event, whichtrigger_shutdownsets once the cleanup has returned, before the process exits. A second Shutdown request joins the running cleanup instead of starting another one (previously two tasks ran one after the other on the loop). The marker is keyed by the trigger, so an embedded host's nextrun_server()launch gets its own cleanup.lan_access.stop_lan_listener).tests/studio/playwright_chat_ui.py: a closed port no longer shows the cleanup finished, so when CI names the server (STUDIO_PID, exported byboot-studio-api-only.sh), the test now waits up to 60 s for that process to exit and fails if it does not. On Linux, an exited but unreaped process counts as gone, and so does one reaped between the probe and the/procread. Skipped on Windows, whereos.kill(pid, 0)would terminate the process.Tests
test_shutdown_cleanup_runs_off_the_event_loop_and_once: a 10 s blocking cleanup; a request sent mid-cleanup is served in under 1 s, a second Shutdown does not start another cleanup, and a new launch's trigger still runs after the first launch's cleanup has finished (which failed before the second commit).main, the request waits the full 10 s and the test fails. With this PR it passes.test_account_desktop_network.pyplus the shutdown, lifespan, LAN-access, uvicorn-shutdown and training-shutdown test files: 207 passed.Not run: a full Studio launch with a real llama-server that ignores SIGTERM. The timing claim rests on the code path and the unit test above.