Repository navigation
Studio: kill in-flight llama-server before spawning a new one - #5171
Conversation
Two rapid Apply clicks in the chat settings panel can race two load_model calls. Both pass the Phase 1 _kill_process (because neither has stored its Popen handle yet), both download / read metadata, and both reach Phase 3 and spawn a server. Only the last reference is tracked in self._process. The first server becomes an orphan that holds the model in RAM until the kernel OOM kicks in. Addresses #5161. Two complementary changes in studio/backend/core/inference/llama_cpp.py: 1. At load_model entry, set the existing _cancel_event so any in-flight load aborts at its next checkpoint, then bind a fresh Event for the new load. Subsequent _kill_process and download phases pick up the new event. 2. Inside the Phase 3 lock, immediately before subprocess.Popen, run a defensive _kill_process that removes any orphan handle a racing load might have stored after the first kill ran. Speculative decoding cleanup (also touched while in this code path): The chat UI used to send "ngram-mod" as the wire value when the speculative dropdown was On, and the backend mapped that to the 4-flag combo --spec-type ngram-mod --spec-ngram-size-n 24 --draft-min 48 --draft-max 64. Switch the wire value to "default" and have the backend pass the single llama-server flag --spec-default. That flag expands to the exact same params (see common/arg.cpp:3905-3914 in llama.cpp). Default-on for non-vision models is preserved. Verified: - Unit test: planted Popen orphan handle is terminated before self._process is overwritten. - All ten spec-cmd mappings produce the expected llama-server args ("default" -> --spec-default, "off" / null -> no flag, vision -> always disabled, manual "ngram-mod" / "ngram-simple" still work).
There was a problem hiding this comment.
Code Review
This pull request introduces a cancellation mechanism for in-flight model loads and adds defensive process termination to prevent orphan processes. It also updates the speculative decoding configuration to use a "default" setting instead of "ngram-mod" across the backend and frontend. A critical issue was identified in the cancellation logic: re-initializing self._cancel_event immediately after signaling it causes concurrent threads to lose the cancellation signal, as they will reference the new event object instead of the signaled one.
| self._cancel_event.set() | ||
| self._cancel_event = threading.Event() |
There was a problem hiding this comment.
The cancellation logic for in-flight loads is partially ineffective due to how self._cancel_event is accessed in sub-methods. Methods like _download_gguf (e.g., at line 1193) check self._cancel_event.is_set() by accessing the attribute on the instance. When a racing call to load_model replaces self._cancel_event with a new Event object at line 1313, any thread already executing a download will begin checking the new event object instead of the one that was just signaled. This prevents the cancellation action from being successfully performed, which can lead to the main thread getting stuck or redundant resource consumption. To fix this, the download methods should capture a reference to the event at the start of their execution or be modified to accept the event as an argument, ensuring the cancellation signal is reliably received.
References
- A background watcher thread responsible for cancellation (e.g., by closing a resource) should only terminate after successfully performing its action. If the action fails, the thread should retry to prevent the main thread from getting stuck.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f973d2a564
ℹ️ 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".
| self._cancel_event.set() | ||
| self._cancel_event = threading.Event() |
There was a problem hiding this comment.
Avoid dropping unload cancellation when swapping cancel events
Rebinding self._cancel_event here introduces a race with unload_model(): if an unload request lands after set() but before the reassignment, unload_model sets the old event object and then load_model immediately replaces it with a fresh clear event, so the in-flight load no longer sees cancellation and can still spawn llama-server after the user asked to stop. This regression is specific to concurrent unload/load timing and is actionable by keeping a stable event identity (or guarding replacement with synchronization and per-load event snapshots).
Useful? React with 👍 / 👎.
The previous attempt at cancelling in-flight loads via ``self._cancel_event.set()`` followed by ``self._cancel_event = threading.Event()`` was broken in two ways (flagged independently by Gemini and Codex): 1. Sub-methods like _download_gguf consult ``self._cancel_event`` on every check. After the rebind, the in-flight thread reads the FRESH unset Event, not the one we just set, so cancellation never propagates. 2. Worse, if unload_model() lands between ``set()`` and the rebind, unload's signal hits the OLD event and is then immediately discarded when load_model swaps in a fresh Event. The user's stop-request silently no-ops. Revert to the original ``self._cancel_event.clear()``. The Phase 3 defensive ``_kill_process()`` introduced in this branch still closes the orphan-process race that #5161 reports: even if two concurrent loads both pass Phase 1 with self._process == None, the loser's Phase 3 kill terminates the winner's Popen handle before overwriting it, so we end up with exactly one llama-server process.
…down The Speculative Decoding control was simplified to On (default) / Off, but the backend still accepts and reports the older manual modes (ngram-mod, ngram-simple). When a load response or status refresh comes back with one of those values -- whether from an external API caller, a model loaded before this PR landed, or a not-yet-upgraded backend -- the controlled Select renders with an empty trigger because the value is not in the SelectItem list. Add a tiny normaliser at both entry points (status refresh + post-load) so legacy manual modes coerce to "default". The user sees "On" instead of a blank dropdown, and reapplying lets llama.cpp pick its own preferred strategy via --spec-default. Reviewer-flagged finding on PR #5171.
|
Thanks for the review. Pushed 3cda845 addressing the dropdown finding: Fixed: simplified Speculative Decoding dropdown rendered blank for legacy values (1/5 reviewers, P2) The Select was simplified to On (default) / Off, but the backend still accepts and reports the older Added a normaliser at both entry points (status refresh + post-load) so legacy manual modes coerce to "default". The user sees "On" instead of empty; reapplying lets llama.cpp pick its own preferred strategy via Deferred (out of scope or low impact):
|
|
/gemini review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3cda84533a
ℹ️ 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".
| if (v == null) return null; | ||
| if (v === "default" || v === "off") return v; | ||
| return "default"; |
There was a problem hiding this comment.
Preserve explicit speculative modes instead of coercing
normalizeSpeculativeType now rewrites any non-null mode except "default"/"off" to "default", which means a model loaded with explicit ngram-mod/ngram-simple (e.g., via API or older Studio) is silently converted in store state; the next Apply for unrelated settings sends speculative_type: "default" and unintentionally drops that manual override. This is a behavior regression for power users because backend still supports explicit modes but the UI no longer preserves them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Code Review
This pull request updates the speculative decoding configuration to use llama.cpp's --spec-default flag by introducing a "default" type, while maintaining backward compatibility for manual draft tuning. It also includes a defensive process cleanup in the backend to prevent orphaned processes during concurrent model loads and updates the frontend to normalize speculative decoding types. I have no feedback to provide.
Addresses #5161.
Problem
Two rapid Apply clicks in the chat settings panel can race two
load_modelcalls. Both pass the Phase 1_kill_process(because neither has stored itsPopenhandle yet), both download / read metadata, and both reach Phase 3 and spawn a server. Only the last reference is tracked inself._process. The first server becomes an orphan that holds the model in RAM until the kernel OOM kicks in. For an 86 GB Q8_0 MoE on a 128 GB host, two clicks blow the memory budget.Fix
Two complementary changes in
studio/backend/core/inference/llama_cpp.py:load_model:_cancel_eventso any in-flight load aborts at its next checkpoint, then bind a freshEventfor the new load. Subsequent_kill_processand download phases pick up the new event.subprocess.Popen, run a defensive_kill_process. If a racing load already wrote aPopenhandle intoself._processafter the first kill ran, this drops the orphan before we overwrite the reference.Speculative decoding cleanup
While in this code path, swap the wire value the chat UI sends for the speculative dropdown from
"ngram-mod"to"default". Backend now passes the single llama-server flag--spec-default, which incommon/arg.cpp:3905-3914expands to the exact same params Studio was already passing manually:{"--spec-default"}, string_format("enable default speculative decoding config"), [](common_params & params) { params.speculative.type = COMMON_SPECULATIVE_TYPE_NGRAM_MOD; params.speculative.ngram_size_n = 24; params.speculative.n_min = 48; params.speculative.n_max = 64; }Default-on for non-vision models is preserved. Power users can still pick
"ngram-mod"or"ngram-simple"explicitly and the manual draft tuning still applies for those values.Verified
Popenorphan handle is terminated beforeself._processis overwritten.default->--spec-default,off/ null /""-> no flag, vision -> always disabled,ngram-mod/ngram-simplestill work; case-insensitive).Caveats
The issue also reports two related symptoms which I could not reproduce without the user's specific 80B-class local GGUF on a small-VRAM host:
-c 4096ignoring the UI Context Length.--spec-type ngram-modflags lingering when the toggle is set to Off. With the race fix in this PR, the most likely cause (the user observing the orphan server's cmdline) goes away. If the symptom persists, it's a separate issue worth a dedicated reproduction.Test plan
llama-serverprocess exists.--spec-defaultand--spec-typeare absent from the livellama-servercommand line.--spec-defaultis present.