Repository navigation
Studio: cut backend start time and stop blocking the event loop - #8498
Conversation
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.
|
@codex review |
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
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: 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".
| image = await asyncio.to_thread( | ||
| _decode_and_resize_image, | ||
| backend, | ||
| request.image_base64, | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
|
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 Mac Studio UI + API + Update CI. A Playwright Locally the three suites covering the changed code are green: |
|
On the org CI red here: Backend CI fails on |
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.
|
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 Docstring. Differential. The tool-parsing surface, which this PR touches indirectly through AST over the 5 changed files: 1132 identical, 22 changed, 15 added, 0 moved across files, 0 removed. Tests: 63 across Three more differences on the record rather than left to be found:
|
|
@codex review |
1 similar comment
|
@codex review |
|
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". |
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
maindirectly.Before
Four things, all on paths that run whether or not anyone asked for them.
LlamaCppBackend.__init__()sweeps for orphanedllama-serverprocesses withpsutil.process_iter(["pid", "name", "exe"]). That reads/proc/<pid>/statseveral times per process and resolvesexefor every process on the machine, before the name test rejects all but a handful. It runs on every backend start and again for every temporaryLlamaCppBackend()built for metadata or advice.routes/inference.pyimported 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._wait_for_health()polled llama-server withtime.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
import routes.inferenceThe 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
commfield from/proc/<pid>/statonce and resolvesexeonly for the names that start withllama-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.
commis truncated to 15 bytes, which still leaves the 12-bytellama-serverprefix 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 livellama-serverpresent 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_imageand_anthropic_request_has_imagehelpers 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 byinterval, 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
Truewhere it previously ran out of interval and returnedFalse. That is the point of the change, but it does mean the result is not identical for every timeline, only never worse._drain_stdoutalso sets the event on EOF now, so a crashed process wakes the loop instead of waiting out the interval.Output equivalence and tests
gguf_messages, passthrough body, normalizer idempotence)._kill_orphaned_serversgained a_PROC_ROOTmodule 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.test_llama_cpp_wait_for_health.py24,test_llama_cpp_wait_for_vram_settle.py29,test_local_llama_cpp_link.py8,test_anthropic_messages.py138,test_openai_tool_passthrough.py258,test_active_generations.py84.fastmcpandsqlite_vecabsent), and CI is the real check on them.No new dependencies, no public signature changes, Python 3.9 compatible.