Skip to content

Studio: cut backend start time and stop blocking the event loop - #8498

Merged
danielhanchen merged 7 commits into
mainfrom
studio/startup-concurrency
Aug 12, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
studio/startup-concurrency

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

One of a series of Studio backend performance PRs. This one is about backend start time and about work that blocks the event loop, so it is independent of the tool-parsing series and targets main directly.

Before

Four things, all on paths that run whether or not anyone asked for them.

  1. LlamaCppBackend.__init__() sweeps for orphaned llama-server processes with psutil.process_iter(["pid", "name", "exe"]). That reads /proc/<pid>/stat several times per process and resolves exe for every process on the machine, before the name test rejects all but a handful. It runs on every backend start and again for every temporary LlamaCppBackend() built for metadata or advice.
  2. routes/inference.py imported NumPy at module scope for two private audio helpers. Text-only and GGUF-only installs paid for it on every start and never used it.
  3. Vision requests decoded base64, opened the image with Pillow, and ran LANCZOS resampling inline in the async handler. Every other request on the server stalled for the duration.
  4. _wait_for_health() polled llama-server with time.sleep(interval). llama-server prints its readiness line as soon as it is listening, and the poller ignored that and slept out the rest of the interval.

After

Change Before After
Orphan sweep, 3051 processes 130.1ms 27.9ms 4.7x
NumPy in the import graph after import routes.inference yes, 43.2ms no
Vision request, event loop stall (resize) 249.2ms 6.7ms 37x
Vision request, event loop stall (PNG re-encode) 413.2ms 7.5ms 55x
Health probe, time to notice readiness 530.3ms 65.3ms 465ms saved per load

The orphan sweep saving scales with the process count on the host, so a busy machine sees considerably more than the 102ms measured here.

How each one is done

Orphan sweep. On Linux the sweep now reads each process's comm field from /proc/<pid>/stat once and resolves exe only for the names that start with llama-server. psutil stays as the cross-platform path for macOS and Windows. The ownership check, the live-parent check and the kill are shared by both paths rather than duplicated, so the two cannot drift.

Two details matter for equivalence. comm is truncated to 15 bytes, which still leaves the 12-byte llama-server prefix intact, so both paths match the same set of names. And the kernel appends (deleted) to the exe link once the binary has been replaced, which is exactly what an orphan left behind by an upgrade looks like; psutil strips that marker, so the procfs path strips it too. A direct comparison of both implementations on this host, with a live llama-server present plus two planted processes (one with its binary deleted underneath it), returns identical (pid, resolved binary) lists.

NumPy. Only two function bodies actually call into NumPy. Those import it locally; the remaining uses were annotations, which become strings under TYPE_CHECKING. The first transcoding request pays the import once and Python caches it from there.

Image decode. Decode plus resample moves to asyncio.to_thread. The message-building functions that re-encode to PNG move to a thread as well, but only when the request actually contains an image, decided by the _request_has_image and _anthropic_request_has_image helpers that already exist. A wrong answer from either helper costs a thread hop or an inline call, never a different result. Output bytes are identical: the resize and PNG digests match before and after.

Health probe. The stdout drain thread already reads llama-server's output, so it now sets an event on the readiness lines (server is listening, model loaded) and on EOF, and the probe waits on that event instead of sleeping. The event is cleared before each probe so output produced during the request stays latched. The wait is still bounded by interval, so a probe can only happen sooner, never later, and the deadline itself is untouched.

One consequence worth stating plainly, because it is a behaviour change rather than a pure speedup: within the same wall-clock timeout the probe now fits more attempts, so a server that becomes healthy just before the deadline can return True where it previously ran out of interval and returned False. That is the point of the change, but it does mean the result is not identical for every timeline, only never worse. _drain_stdout also sets the event on EOF now, so a crashed process wakes the loop instead of waiting out the interval.

Output equivalence and tests

  • Byte identity checked directly for the image paths (SHA-256 of the resized image and of the re-encoded PNG, before and after) and for the message-building paths (gguf_messages, passthrough body, normalizer idempotence).
  • The Linux and psutil orphan sweeps were compared against each other on live process tables and return identical selections.
  • _kill_orphaned_servers gained a _PROC_ROOT module attribute so the sweep can be pointed at a fixture tree. The existing tests that drive the psutil branch keep driving it, and the same ownership, live-parent and deleted-binary scenarios now run against the procfs branch as well. This is deliberate: changing which branch runs would otherwise have left those tests intercepting nothing.
  • Targeted suites green: test_llama_cpp_wait_for_health.py 24, test_llama_cpp_wait_for_vram_settle.py 29, test_local_llama_cpp_link.py 8, test_anthropic_messages.py 138, test_openai_tool_passthrough.py 258, test_active_generations.py 84.
  • Wider run compared against the unmodified base commit rather than asserted green: the failure set is identical, 271 ids either side. Those are environmental in my sandbox (no GPU, no network, optional fastmcp and sqlite_vec absent), and CI is the real check on them.

No new dependencies, no public signature changes, Python 3.9 compatible.

danielhanchen and others added 3 commits August 11, 2026 20:52
Four items on paths that run whether or not anyone asked for them.

Orphan sweep

  LlamaCppBackend.__init__() enumerated every process on the machine with
  psutil.process_iter(["pid", "name", "exe"]), which reads /proc/<pid>/stat
  several times per process and resolves exe for all of them, before the
  name test rejects all but a handful. On Linux it now reads comm once and
  resolves exe only for llama-server candidates. psutil stays as the
  cross-platform path for macOS and Windows, and the ownership, live-parent
  and kill logic is shared so the two paths cannot drift.

  130.1ms -> 27.9ms at 3051 processes, and the saving grows with the
  process count.

  comm is truncated to 15 bytes, which leaves the 12-byte "llama-server"
  prefix intact, so both paths match the same names. The kernel appends
  " (deleted)" to the exe link once the binary has been replaced, which is
  what an orphan from an upgrade looks like; psutil strips that marker, so
  the procfs path strips it too. Both implementations return identical
  (pid, binary) lists on a live process table.

NumPy

  routes/inference.py imported NumPy at module scope for two private audio
  helpers. Those import it locally now and the rest were annotations, which
  move under TYPE_CHECKING. 43.2ms off every start for text-only and
  GGUF-only installs, which never call the helpers at all.

Image decode

  Vision requests ran base64 decode, Pillow open and LANCZOS resampling
  inline in the async handler, stalling every other request for the
  duration. Moved to asyncio.to_thread, gated on the existing
  _request_has_image and _anthropic_request_has_image helpers so non-image
  requests do not pay a thread hop.

    resize event loop stall        249.2ms -> 6.7ms
    PNG re-encode loop stall       413.2ms -> 7.5ms

  Output bytes are identical: the resized image and re-encoded PNG hash the
  same before and after.

Health probe

  _wait_for_health() slept out the poll interval while llama-server had
  already printed its readiness line. The stdout drain thread now sets an
  event on the readiness lines and on EOF, and the probe waits on that
  instead. Still bounded by interval, so this can only return sooner.

    time to notice readiness       530.3ms -> 65.3ms

Tests

  _kill_orphaned_servers gained a _PROC_ROOT module attribute so the sweep
  can be pointed at a fixture tree. The existing tests that drive the
  psutil branch keep driving it, and the same ownership, live-parent and
  deleted-binary scenarios now run against the procfs branch too. Without
  that, changing which branch runs would have left those tests intercepting
  nothing.
@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: 2e3b37c5df

ℹ️ 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:
if proc.info["pid"] == my_pid:
continue
os.kill(pid, signal.SIGKILL)

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 Revalidate the procfs process before signaling it

On Linux, candidates are collected during the full /proc scan and later killed using only their numeric PID. If an orphan exits after its executable is recorded and the PID is reused by an unrelated process with no live parent (for example, a daemon reparented to PID 1), the later parent check still classifies that PID as orphaned and this os.kill terminates the replacement process. The previous normal Linux path retained a psutil.Process identity, whereas this path should capture and recheck the process start-time/executable identity immediately before signaling, or use a PID-stable handle.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, and it is a regression this branch introduced. I checked psutil rather than assuming: Process.kill() calls _raise_if_pid_reused() first, and on Linux the identity it compares is the starttime field of /proc/<pid>/stat. Collecting candidates by PID alone dropped that.

Fixed in 1ccc4b3. The sweep now captures field 22 during the scan, which costs nothing since the whole stat line is already read, and re-checks it immediately before signalling. starttime never changes for a process and a reused PID gets a later one, so a mismatch means it is no longer the process that was selected.

Two tests cover it: one rewrites starttime between the scan and the kill and asserts nothing is signalled, and a control asserts an unchanged starttime is still reaped. The fake procfs fixtures had to start writing a full-length stat line, since field 22 has to be present for the check to mean anything. Also verified end to end against the real /proc with a live process named llama-server.

The Linux sweep collected candidates during the /proc scan and later killed
them by PID alone. If an orphan exits between the scan and the signal and
the PID is reused by an unrelated process whose parent is gone, the
live-parent check still reads it as an orphan and the kill lands on the
replacement.

psutil.Process.kill() does not have this problem: it calls
_raise_if_pid_reused() first, and on Linux the identity it compares is the
starttime field of /proc/<pid>/stat. The sweep now captures that field
during the scan, which is free since the whole stat line is already read,
and re-checks it immediately before signalling.

Verified against a live process on the real /proc, and covered by two new
tests: one that mutates starttime between the scan and the kill and asserts
nothing is signalled, and a control asserting an unchanged starttime is
still reaped. The fake procfs fixtures now write a full-length stat line,
since field 22 has to be present for the check to mean anything.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 1ccc4b3688

ℹ️ 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".

@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: c0bf22e955

ℹ️ 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 on lines +9195 to +9199
image = await asyncio.to_thread(
_decode_and_resize_image,
backend,
request.image_base64,
)

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 Protect the model before awaiting image resize

For an image-bearing /generate/stream request, this new await yields before _TrackedCancel is entered inside stream() below. If a non-forced /unload arrives while Pillow is decoding or resizing, the unload gate sees no active generation and can evict the model; the request then resumes and starts generation against the unloaded backend. Previously the synchronous decode prevented another handler on the same event loop from entering this window, so either register/protect the request before offloading or revalidate the model after the await.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The window is real, but it is not created by this await, and the suggested guard would not close it.

On the merge base the handler already opens with backend = await asyncio.to_thread(get_inference_backend), above the is_vision check, so the first suspension point is before the decode either way. _TrackedCancel is then entered inside stream(), and that generator body does not run until Starlette begins iterating the response, which is after the handler returns. So on base the request is already unprotected from the top of the handler through to the first body chunk, decode or no decode. The synchronous decode narrowed nothing; it sat in the middle of a window that was already open at both ends.

What this PR does change is the duration: about 250ms of decode and LANCZOS resampling moves from blocking the loop to yielding it, on image requests only. That is the point of the change, and it is why every other request stops stalling for that time.

Revalidating active_model_name after the await would not fix it, since the window continues past the handler return, and it would add a failure path where the code currently proceeds, which this PR is explicitly not doing (the premise is byte-identical behaviour).

The actual fix is to enter _TrackedCancel in the handler rather than in the generator, and the comment there says it is in the generator on purpose, so that a response whose body never starts leaves nothing registered. That is a real design tradeoff and worth revisiting, but on its own merits rather than folded into a performance change.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: c0bf22e955

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member Author

Ran this on a staging copy rather than adding to the org queue. Green: Mac GGUF, Windows GGUF, Startup profile.

Two reds, both checked and neither this branch:

Backend CI. 84 failures in test_diffusion_prequant / test_diffusion_convrot, from torch < 2.6 on that runner which the pre-quant loader refuses by design; test_openai_auto_switch::test_an_expired_positive_hit_refreshes_before_switching, which fails identically on unmodified main in a side-by-side run I did locally; test_stt_sidecar; and two tests/studio/* frontend contract tests, which assert against frontend source the staging replica takes from main. Nothing in the orphan sweep, health probe or image paths.

Mac Studio UI + API + Update CI. A Playwright TargetClosedError browser crash in the update-banner layout test, after its assertions passed. This branch touches no frontend.

Locally the three suites covering the changed code are green: test_llama_cpp_wait_for_health.py, test_llama_cpp_wait_for_vram_settle.py and test_local_llama_cpp_link.py, 63 tests.

@danielhanchen

Copy link
Copy Markdown
Member Author

On the org CI red here: Backend CI fails on test_diffusion_prequant (19), test_diffusion_convrot (2) and test_openai_auto_switch (1). main own Backend CI run (4acc36b10) fails on the same files and more: 76 + 8 + 4 plus test_stt_sidecar and two tests/studio/* contract tests. So this branch failure set is a strict subset of what main is already red on, and nothing in it touches the orphan sweep, health probe or image decode paths.

The docstring still promised a pgrep fallback for the psutil-less case. That
path is gone, and it was unreachable from both directions anyway: /proc is what
it read, and psutil is a hard dependency.

Also records two consequences of collecting candidates before killing them,
neither of which was written down: an enumeration that fails part way now kills
nothing rather than some, and the parent check runs after enumeration rather
than during it. The second is a genuine ordering change. A parent that exits in
between makes the process a real orphan, and the start-time check still refuses
to signal a PID that has been reused, so the outcome is right either way, but
it should be stated rather than left to be discovered.
@danielhanchen

Copy link
Copy Markdown
Member Author

Re-verified with the deterministic harness used across this series, and corrected an overclaim in the description.

What I fixed in the description. It said the timeout behaviour was unchanged. That is not right: within the same wall-clock timeout the probe now fits more attempts, so a server that becomes healthy just before the deadline can return True where it previously ran out of interval and returned False. That is the point of the change, but the result is not identical for every timeline, only never worse. _drain_stdout also sets the event on EOF now, so a crashed process wakes the loop rather than waiting out the interval.

Docstring. _kill_orphaned_servers still promised a pgrep fallback that no longer exists, and it was unreachable from both directions anyway: /proc is what it read, and psutil is a hard dependency. It now also records two consequences of collecting candidates before killing them, which were not written down: an enumeration that fails part way kills nothing rather than some, and the parent check runs after enumeration rather than during it. A parent that exits in between makes the process a real orphan, and the start-time check still refuses to signal a reused PID, so the outcome is right either way.

Differential. The tool-parsing surface, which this PR touches indirectly through routes/inference.py: IDENTICAL over 78,960 rows against a worktree at the merge base.

AST over the 5 changed files: 1132 identical, 22 changed, 15 added, 0 moved across files, 0 removed.

Tests: 63 across test_llama_cpp_wait_for_health.py, test_llama_cpp_wait_for_vram_settle.py and test_local_llama_cpp_link.py.

Three more differences on the record rather than left to be found:

  • The image decode moving to a thread means a cancelled request no longer stops the decode; the executor finishes it. The work is a pure function on request-local data, so nothing outside is affected, but the CPU is spent.
  • The audio helpers annotate numpy under TYPE_CHECKING, so typing.get_type_hints on them now raises NameError. Nothing in the backend calls get_type_hints.
  • __slots__ on the three exception classes is observable through hasattr(cls, "__slots__") and sys.getsizeof. Messages, MRO, catch behaviour and vars(instance) are unchanged.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 20d84d8cbc

ℹ️ 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".

@danielhanchen
danielhanchen merged commit d7e88a8 into main Aug 12, 2026
44 of 55 checks passed
@danielhanchen
danielhanchen deleted the studio/startup-concurrency branch August 12, 2026 10:48
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.

2 participants