Skip to content

Studio: run the Shutdown cleanup off the event loop - #13534

Merged
danielhanchen merged 2 commits into
mainfrom
studio-shutdown-off-loop
Oct 13, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-shutdown-off-loop

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

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/shutdown and /api/desktop/shutdown schedule _delayed_shutdown on uvicorn's event loop, and it calls app.state.trigger_shutdown() directly. So _graceful_shutdown ran on that loop and blocked it while it stopped every subprocess:

  • the inference subprocess: up to 5 s;
  • the export subprocess: up to 5 s;
  • llama-server: terminate() with a 5 s wait, then kill() with up to 5 s more, then the group and descendant sweep.

server.should_exit = True is 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_shutdown on the main thread while uvicorn shuts down on its own.

Change

  • main._schedule_shutdown: the cleanup runs on its own studio-shutdown thread, 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, which trigger_shutdown sets 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 next run_server() launch gets its own cleanup.
  • The LAN listener now really waits for its sockets to close, up to its stop timeout. It used to skip that wait whenever it found itself on the loop (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 by boot-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 /proc read. Skipped on Windows, where os.kill(pid, 0) would terminate the process.

Tests

  • New 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).
    • On main, the request waits the full 10 s and the test fails. With this PR it passes.
  • test_account_desktop_network.py plus 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.

/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.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-13T05:55:39.742465Z 9987bb3 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-13T05:33:50.074913Z c7824d8 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread studio/backend/main.py Outdated
Comment on lines +2312 to +2313
running = getattr(request.app.state, "_shutdown_thread", None)
if running is None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread tests/studio/playwright_chat_ui.py Outdated
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":

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen
danielhanchen merged commit 3b41804 into main Oct 13, 2026
@danielhanchen
danielhanchen deleted the studio-shutdown-off-loop branch October 13, 2026 05:51

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread studio/backend/main.py
Comment on lines +2316 to +2319
state._shutdown_thread = threading.Thread(
target = trigger, name = "studio-shutdown"
)
state._shutdown_thread.start()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment thread studio/backend/main.py
Comment on lines +2316 to +2319
state._shutdown_thread = threading.Thread(
target = trigger, name = "studio-shutdown"
)
state._shutdown_thread.start()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

danielhanchen added a commit that referenced this pull request Oct 13, 2026
…13536 left red on main (#13543)

- Baseline the two diffusion_autoopt splice_function compile/exec sites
  with their reasons (#13520).
- Name encoding="utf-8" on four file reads/writes in tests (#13520,
  #13534, #13536).
- Format six #13536 files with scripts/run_ruff_format.py.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant