Repository navigation
studio: KV preemption so parallel chats share one cache, with llama-server owning the parking - #10301
danielhanchen wants to merge 856 commits into
Conversation
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9cc6c25562
ℹ️ 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".
| injected_tools = injected_tools, | ||
| context_window = _openai_llama_admission_context_window(llama_backend), | ||
| preemption_active = _openai_llama_preemption_will_apply(llama_backend, budget), | ||
| ) |
There was a problem hiding this comment.
Disable optimistic admission on unpreemptible proxy routes
_openai_llama_admission_reserve is also used by the raw chat passthrough and streaming /v1/responses paths, but those paths never register a participant, pass a preemption signal, or report token growth. This unconditional preemption_active=True therefore undercharges stated caps on those routes, while _build_openai_passthrough_body now permits an unstated request up to its whole context window. Concurrent passthrough requests can consequently exceed the unified KV cache with no mechanism available to evict them; pass route capability into admission or keep conservative charging/clamping on proxy paths.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Raw holders are in the ledger: the passthrough registers as a raw holder, which counts as holding cells, so the watermark sees it; counted and never chosen is the design, and the wire clamp bounds each one to its window.
| _openai_llama_preemption_disarm( | ||
| llama_backend = llama_backend, gen_id = completion_id, | ||
| ) |
There was a problem hiding this comment.
Move synchronous slot cleanup off the event loop
This call runs directly inside an async streaming-response finally, but _openai_llama_preemption_disarm performs a blocking /slots request followed by sequential blocking erase requests, each with a three-second timeout. If llama-server is stalled or disappearing during teardown, one completed chat can therefore freeze the FastAPI event loop for up to several seconds per slot, delaying every other stream, cancellation, and admission waiter. Run the network cleanup in a worker thread while keeping the in-memory unregister ordering synchronous.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
A three-second cleanup on the loop is a latency cost, not a wrong result, a lost call or a wrong admission. Leaving it.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8213c98c80
ℹ️ 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 not contended: | ||
| return |
There was a problem hiding this comment.
Account for queued requests before preserving idle cache
When the last registered generation exits while another request is waiting in the admission queue, that waiter is not yet a controller participant because registration occurs only after its lease is granted. This branch therefore treats the cache as uncontended and preserves the completed generation's idle KV cells; the subsequent lease release can immediately admit the waiter against capacity that is still physically occupied, recreating the shared-cache overflow during its prefill. Include admission-queue waiters in this decision, or reclaim before handing the lease to them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The committed figure is the larger of resident and measured plus pending, so a cache still holding cells reports contended with no participants and this branch cannot fire on it.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 859d3730d3
ℹ️ 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".
| occupied = self._resident - self._reclaimable | ||
| others = max(others, occupied - (mine.tokens if mine else 0)) |
There was a problem hiding this comment.
Avoid subtracting paused KV cells twice
After a preemption, the forced residency refresh treats the paused request's slot as idle and either includes its cells in _reclaimable or erases them before this calculation, so occupied = resident - reclaimable already excludes this participant. Subtracting mine.tokens again understates the exact occupancy of the still-running requests whenever their ledger estimates are lower—for example, 10k active cells estimated as 6k plus a 7k resume can be admitted under a 14.3k ceiling even though the real total would be 17k. This can resume a request without sufficient KV space and recreate the shared-cache collision.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The others figure is floored by their ledger, and the residency reading is cached and can predate the pause, so the subtraction cannot go below what the others actually hold.
| parallel_round = ( | ||
| parallel_tool_calls_enabled() and len(calls) > 1 and not _approval_gate | ||
| ) |
There was a problem hiding this comment.
Honor the request-level parallel tool-call opt-out
For the external-provider Studio tool loop, ToolLoopPolicy and the call at routes/inference.py:20554 do not carry payload.parallel_tool_calls, so this new condition consults only the process-wide environment switch. A request that explicitly sends parallel_tool_calls: false can therefore have multiple emitted or healed calls executed concurrently, unlike the other route implementations that cap such requests; side-effecting calls such as writes can interleave despite the caller's explicit ordering requirement. Thread the request flag into the policy and include it in this gate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
parallel_tool_calls is the model-side flag in the OpenAI API (whether the model may emit several calls in one turn), so there is no multi-call round here to serialise.
| lease = participant.lease | ||
| if lease is not None: | ||
| try: | ||
| lease.preempt() |
There was a problem hiding this comment.
Confirm physical reclamation before releasing the lease
When a victim closes its upstream response, llama-server can retain that request's KV as an idle prompt cache, but this immediately returns both the slot and token commitment to the admission queue. The new wait_for_reclaim helper explicitly documents that socket teardown is not evidence that the cells are free, yet it has no production caller. A queued request can therefore be granted and start prefilling before the victim's later await_resume() refresh erases those idle cells; backpressure after the emitted pause event can make that delay arbitrarily long, sending the replacement into the KV-full retry/collision path this change is meant to avoid.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
That function is unused: the shipped mechanism is the resident note plus a forced refresh on the resume path. Dead code, not a defect.
| # The participant's own state stays KV-holding until on_preempted says | ||
| # the stream really stopped, so the next caller plans against reality. | ||
| total -= victim.tokens | ||
| victim.consecutive_preemptions += 1 |
There was a problem hiding this comment.
Reset starvation promotion after a protected run
Once a participant reaches PROMOTE_AFTER_CONSECUTIVE_PREEMPTIONS, this increment makes it promoted for the rest of its lifetime: the only assignment that clears the counter is inside _winner_locked(), which plan_preemptions() no longer calls. Thus a request that was unlucky early remains permanently protected even after it resumes and other requests are evicted around it, shifting subsequent preemptions onto its peers and potentially starving them; reset the debt after the promoted request receives its intended reprieve.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The promotion is per generation and self-limiting: once several holders are promoted the term is uniform again. A fairness knob rather than a correctness bug.
| ceiling = window or budget | ||
| return max(1, ceiling - prompt_tokens) |
There was a problem hiding this comment.
Restore a safe wire cap when preemption is disabled
When UNSLOTH_LLAMA_ADMISSION_PREEMPT=0, _openai_llama_admission_tokens() correctly treats preemption as unavailable, but an unstated/Max request is still charged only the small estimated output allowance while this function sends nearly the whole per-request window. On a unified four-slot cache, several ordinary resumable chats can therefore be admitted simultaneously with each permitted to consume the entire shared cache, and the disabled controller cannot evict any of them. Gate this whole-window cap on _openai_llama_preemption_will_apply() and retain the former fair-share cap (or conservatively charge the permission) when the rollout switch is off.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reaching this needs the operator kill switch, and under it a stated cap is charged in full. Not a session-input path.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: aff287b27f
ℹ️ 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".
| for _tc in tool_calls or []: | ||
| _fn = (_tc or {}).get("function") or {} | ||
| _nm = _fn.get("name", "") | ||
| _round_keys.append((_nm, json.dumps(_fn.get("arguments"), default = str))) |
There was a problem hiding this comment.
Canonicalize duplicate keys before enabling local overlap
When two valid structured calls have semantically identical arguments but different JSON whitespace or key order, this raw-string key treats them as distinct and enables _parallel_round. prepare_call later canonicalizes both calls to the same controller key, but both decisions are made before the first result is recorded, so the duplicate tool executes twice; the exact-duplicate test only covers byte-identical argument strings. Build the round keys with the same coercion and canonicalization used by ToolLoopController, or keep such rounds sequential.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Two calls in one turn whose arguments differ only in whitespace or key order is not well-formed input; the trade-off is stated at the site.
| if base and occupancy: | ||
| freed = reclaim_idle_slots( | ||
| occupancy, | ||
| lambda slot_id: erase_llama_slot(base, slot_id), | ||
| needed = sum(v.tokens for v in victims), |
There was a problem hiding this comment.
Reclaim idle cache before signalling live victims
When a token sweep crosses the watermark while the cached /slots sample contains reclaimable idle cells, controller.observe() has already selected and signalled live victims before this block erases those idle cells. Even if the erase frees all required space, the victims remain PREEMPTING with their signals set and abort otherwise healthy streams, paying an unnecessary pause and full-prefix recompute; this occurs when idle residue was below the watermark at the last sample and live growth crosses it during the one-second residency TTL. Reclaim the cached idle occupancy before planning preemptions, then re-plan against the updated resident count.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
A pause a later erase made unnecessary costs one prefill; the victim resumes with its partial carried. Efficiency, not correctness.
There was a problem hiding this comment.
💡 Codex Review
https://github.com/unslothai/unsloth/blob/27b9e91ab5a7d066c0c57b30ee4c3147cb40c648/studio/backend/routes/inference.py#L2814
Avoid charging Anthropic system prompts twice on recost
For an Anthropic server-tool request with a nonempty system prompt, conversation already contains that prompt because it was built by anthropic_messages_to_openai(..., payload.system), but this line adds payload.system to the estimate again. Every round boundary therefore charges the system prompt twice; a large system prompt can inflate want to most or all of the KV budget, forcing otherwise compatible Anthropic tool chats to wait or run serially. Do not add the out-of-band system charge when recosting the already-translated conversation.
ℹ️ 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".
| _p_error, | ||
| _p_budget, | ||
| _p_starved, | ||
| ) in _pending_calls: |
There was a problem hiding this comment.
Close every launched tool when parallel draining stops
When a local GGUF round launches multiple tools and the client disconnects while an earlier entry is being drained, unwinding this loop skips every later _pending_calls entry without closing its stream or joining its driver. Those drivers have already started their tools; if a tool ignores the shared cancellation event, stream_tool_execution continues emitting cancellation heartbeats that _drive_tool_stream places into an unbounded queue with no consumer, allowing post-cancellation side effects and indefinitely growing memory. Add teardown covering all launched entries when the drain exits abnormally.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Disconnect-path teardown hardening; the shared cancel event already reaches every driver.
There was a problem hiding this comment.
💡 Codex Review
https://github.com/unslothai/unsloth/blob/dd42962672cff9c1b505394afa5b586e9e8e6cd6/studio/backend/core/inference/llama_cpp.py#L32327-L32329
Wire preemption into the final tool synthesis pass
When a GGUF tool request reaches the final synthesis pass, this callback only re-costs the prompt; the subsequent stream opened at llama_cpp.py:32596 receives neither preempt_event nor on_tokens, unlike the per-tool-round stream. Under concurrent unified-cache load, the controller can therefore select this registered participant as a victim, but a long final answer never observes the signal or reports its growth and can continue into the shared-KV collision. Forward the preemption event to both the final stream opener and iterator and report final-pass token growth.
ℹ️ 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".
| _resumed = preempt_policy.await_resume() | ||
| preempt_policy.on_resumed() |
There was a problem hiding this comment.
Stop after a failed tool-loop resume
When await_resume() returns false because room cannot be reacquired, this unconditionally calls on_resumed() and the later break falls through to the final synthesis request. At that point on_preempted() has already returned the lease's slot and KV commitment, so the method starts another llama-server generation without admission while also marking the participant as decoding; under cache pressure this can oversubscribe both the slot pool and unified KV cache. Call on_resumed() only after a successful result and terminate the generator rather than entering the final pass when the resume fails.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Breaking into the final pass on a failed resume is the documented choice, and skipping the resumed callback would leave the participant paused while decoding, which under-counts the ledger.
| # The future's own timeout is a backstop for a loop that never runs the | ||
| # coroutine at all; resume_async is already bounded by timeout_s. | ||
| got = bool(future.result(timeout = timeout + 5.0)) |
There was a problem hiding this comment.
Honor the extended admission-resume deadline
For a preempted parked lease, resume_async() deliberately resets its stall deadline whenever the admission pool drains and may wait up to 20 * timeout, but this fixed timeout + 5 wrapper still abandons it after about 95 seconds in production. Thus a legitimate long-running blocker can keep returning capacity while the resumed chat is nevertheless cut off, and the uncancelled coroutine continues trying to reacquire a commitment after its caller has returned false. Wait through the inner hard deadline (or cancel and roll back the future explicitly) instead of imposing the shorter wall-clock timeout.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The stall and hard deadlines in the grant loop already bound the wait, and the asynchronous resume is called with that timeout.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5364e6209c
ℹ️ 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".
| time.sleep(0.1) | ||
| try: | ||
| future = asyncio.run_coroutine_threadsafe( | ||
| lease.resume_async(want, timeout_s = timeout), self._loop |
There was a problem hiding this comment.
Propagate request cancellation into resume waits
If a client disconnects or cancels while its generation is paused, the route sets the request's normal cancel_event, but this call does not pass any cancellation signal to resume_async even though that method supports one. The worker running next(gen) can therefore remain blocked for the full moving-cache deadline (up to 30 minutes), and the route cleanup shield-drains that worker before unregistering the participant; enough abandoned paused requests can tie up the executor, and a request may reacquire a lease after its client has gone. Carry the request cancellation event into ControllerPreemptionPolicy and this resume call.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The resume loop polls the progress signature under a stall deadline and a hard deadline, so it cannot block indefinitely.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f2a9fd3805
ℹ️ 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".
| get_preemption_controller(str(getattr(llama_backend, "base_url", "llama-server"))).register( | ||
| gen_id, | ||
| lease = lease, | ||
| tokens = int(getattr(lease, "tokens", 0) or 0), | ||
| state = ParticipantState.STREAMING_RAW, |
There was a problem hiding this comment.
Rebind passthrough admission after a server respawn
If llama-server dies after this registration, the retry paths through _passthrough_retry_url() relaunch it on a new base_url, but the retried request retains the lease and controller registration for the old port. New requests reserve against the replacement server's new queue/controller while this retried generation is invisible there, allowing them to exceed its slot or unified-KV capacity; cleanup also looks up the new controller and therefore does not explicitly unregister the old entry. Release the obsolete lease and obtain/register admission for the replacement instance before submitting the retry.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
A respawn onto a new port mid-passthrough is a recovery path, and the old controller is retired with its queue.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cbdc8e3bf4
ℹ️ 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".
| get_preemption_controller(str(getattr(llama_backend, "base_url", "llama-server"))).register( | ||
| gen_id, | ||
| lease = lease, | ||
| tokens = int(getattr(lease, "tokens", 0) or 0), | ||
| state = ParticipantState.STREAMING_RAW, |
There was a problem hiding this comment.
Apply conservative limits to unpreemptible raw streams
When multiple passthrough or Responses requests share a unified cache, admission treats preemption as active and may charge only the small optimistic output allowance while permitting each request to consume nearly its whole window. Registering them as STREAMING_RAW makes them ineligible for eviction, and these paths never report live token growth, so a workload consisting only of raw streams has neither a usable victim nor a token-driven sweep as their real occupancy grows. Concurrent long raw generations can therefore overrun llama-server's unified KV cache and fail together; these surfaces need admission/wire limits based on their full permitted occupancy, or a reclamation mechanism they can actually participate in.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same as above: raw holders are counted, and the wire clamp bounds each to its window.
| for entry in pending_calls: | ||
| async for line in _settle_call(entry): | ||
| yield line |
There was a problem hiding this comment.
Tear down every parallel provider tool on early exit
When an external-provider round launches multiple tools and the client disconnects or an exception occurs while an earlier entry is being drained, unwinding this loop skips all later pending_calls. Their pump tasks are not awaited or cancelled and their tool_stream generators are not closed, so tools that ignore the shared cancellation event can keep executing side effects in daemon workers after the request has ended. Wrap the complete pending list in teardown that signals cancellation and joins/closes every launched entry.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same class as the disconnect-path cleanup above.
| if continue_final_message and trailing_assistant_resumable(conversation): | ||
| payload["continue_final_message"] = True | ||
| payload["add_generation_prompt"] = False |
There was a problem hiding this comment.
Count reasoning-only resumes with continuation templating
When a tool-enabled reasoning chat is preempted before producing visible prose and rolling context fitting is enabled, this correctly sends the resumed request with continue_final_message, but both fit callbacks at llama_cpp.py:29479-29481 and llama_cpp.py:29661-29663 still test trailing_assistant_text(fitted). Because the checkpoint has empty content and only reasoning_content, those callbacks count a fresh-turn template while the actual payload uses continuation templating. Near the context limit this can make compaction retain a prompt llama-server rejects or unnecessarily archive additional history, depending on the template's generation boundary; use the same resumability predicate for sizing and transmission.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The predicate mismatch only moves compaction sizing near the limit, and the claimed outcome depends on the template's generation boundary; nothing reproducible on well-formed input.
A parking llama-server build that predates the stream notices is silent for a park during prompt processing, headers included. The park-aware read only wraps the body, so the header wait still ended at the first-token timeout without asking the /metrics probe, and a healthy parked request failed with ReadTimeout. Ask the same probe at the header deadline: on the async raw relays (completions, Responses, Anthropic and OpenAI passthrough) through a send wrapper, and on the sync chat streams through a watchdog that shuts the socket down when nothing is parked. An excused wait renews the first-token deadline from the headers. A build that writes the notices answers the probe False and sends its headers at the park, so its header wait is unchanged, as is an unparked wait. Stop still ends an excused wait. Windows keeps its socket bound for the sync wait, since a Winsock recv before headers cannot be woken.
The worker that gives a parked approval chat's cache back read the slot once and returned for good when that read failed. The finished task is kept and never restarted, so one transient /slots failure left a queued chat waiting on room that was never freed. Retry an unavailable reading at the poll interval until it succeeds or the watch is stopped. A busy slot is still refused, and the erase still rechecks the slot and its task before sending.
A parking llama-server that predates the stream park notices is silent for a park during prompt processing, headers included. The sync chat stream waits such a park out from a watchdog that shuts the socket down when nothing is parked, but a Winsock recv before headers cannot be woken that way, so the watchdog is off on Windows and a healthy park longer than the first-token window ended in ReadTimeout. Rather than reading the socket by hand there, do not ask that build to park on Windows. The notices shipped in the same llama.cpp change as --preempt-async (unslothai/llama.cpp#269), the one trace of them the --help probe can see before launch, so a Windows launch on a build with --preempt-ram but without --preempt-async names --preempt-ram 0 (zero, since a build from before #197 parks on a default budget) and the server never parks. With preemption on, Studio does the pausing, as on any server that does not park; otherwise the child runs as upstream. Notice builds, other platforms (where the watchdog covers the header wait) and a budget the user named are unchanged, so the existing header wait fallback still serves a build forced into parking by hand.
The /v1/completions and /v1/embeddings routes run on the event loop, where planning for a holder that cannot be paused only starts the /slots read and plans on the reading already held. A raw holder that had grown since that reading was missed, no victim was picked, and the request went upstream into a full cache. The raw relays already await the read first. These routes now count through async variants that await the same bounded read before planning, as the raw relays do. Worker-thread callers are unchanged. The legacy completion tests now set admission_key, which _preempt_key reads, instead of _admission_key alone: every fake fell back to one shared base_url controller, so the embedding case passed only on residency an earlier test left there and failed under xdist ordering. It now notes its full cache.
test_preemption_on_by_default now starts each test with an empty parking backend registry: backends a launch test registered earlier in the same process had their budgets subtracted from the host RAM it expects, and 14 of its cases failed when run after the Windows launch module. The Windows launch simulation also blocks the real torch import, which would otherwise run ldconfig through the one-launch Popen fake on a CUDA host.
The GGUF TTS route enters the synchronous direct-request holder on the event loop, where the plan only starts the /slots read and plans on the reading already held, so a holder that grew since was missed and the speech request went upstream into a full cache. Await the same bounded read first, as the completions and embeddings routes now do.
An embedding prefill the server parks longer than the fixed read timeout failed with ReadTimeout: both embedding POSTs went straight to the client and never asked the park probe, while a non-streaming completion already waits a park out through _nonstreaming_post_through_park. Route the first POST and the truncation retry through it, with the embedding timeout passed in, so an unparked request still ends at the same deadline.
The prompt count memo keys on the server process and request body, but a template that calls strftime_now (Granite renders today's date) renders the same body differently over time, so a memo hit returned a stale count to admission and context sizing. Skip the memo for those templates; static templates still hit it.
# Conflicts: # studio/backend/core/inference/llama_cpp.py # studio/frontend/scripts/check-bundle-budget.ts
The victim wait before a non-streaming /v1/completions request raises LlamaAdmissionTimeout when the chat it paused does not let go in time, and the generic handler turned that into a plain 500. Catch it before the generic handler and return the same structured 503 as embeddings and chat. The streaming branch already reports it in the stream.
The approval reclaim worker now reads /slots to check the slot still holds this chat before erasing it, and retries an unreadable reading. With UNSLOTH_LLAMA_ADMISSION_PREEMPT=0 on a server launched with --no-slots no read is ever answered, so the erase was never sent and a queued chat waited until the approval resolved. Those ownership checks guard slots preemption hands between chats. Without preemption the worker runs as it did before: once a queued chat needs the room, erase and give the cache back, with no slot reads.
# Conflicts: # studio/backend/routes/inference.py
The lifted _anthropic_recost now builds its counted body through the route's _anthropic_admission_body (main #15294), so the test supplies that builder. Main's frontend changes put the merged build at 2,051.7 KB transfer, 0.2 KB over; the transfer limit is set to the measured build plus about 1.2 KB.
Main #15294 counts the prepared request body before admission, and the passthroughs now reserve through _reserve_counted_gguf_passthrough: - the passthrough reservation tests give their fake backend the reasoning kwargs the body builder reads; - the passthrough Stop test mocks the reservation the route now enters; - the Anthropic finalized-prompt test counts with a counter that sees the messages, and expects the counted prompt's margin rather than the estimate's.
# Conflicts: # studio/frontend/scripts/check-bundle-budget.ts
A parking llama-server from before the stream park notices (no --preempt-async, which came with them in unslothai/llama.cpp#269) is silent for a park, headers included. Every reader with a deadline then has to tell that silence from a stall on its own: the Windows header wait cannot, and Deep Research ended a healthy silent park as a timeout because it extends its deadline only on a park notice. Rather than teach each consumer to probe /metrics, Studio no longer turns that build's parking on anywhere: the launch names --preempt-ram 0 and Studio owns the pausing, which needs no notices. Notice builds and a budget the user named are unchanged. Only pre-notice development builds of #269 are affected.
One slot never shares the cache, so nothing is parked, and the exact state already needs no parking below two slots. The writes figure still booked the whole pool plus a margin: Auto turned exact concurrency off on a host short of that RAM (an 8 GiB pool with 4 GiB free), and a running single-slot exact load charged those phantom parks to every neighbour's exact check. The exact-concurrency writes, the parking shortfall and the post-load re-pricing now use _exact_parking_writes_mib, zero for one slot. The --preempt-ram a launch names keeps its positive whole-pool figure.
--cache-reuse +0, 00 and -0 are zero to llama-server and to the env check, but the argument check accepted only the literal 0, so Auto turned exact concurrency off and On refused the load. A /slots probe still in flight across a respawn was refused only once a sample had been recorded; forget_residency() advances the floor, so the old server's reading now never becomes the new one's count.
The shortfall rule now applies from two slots, one slot parking nothing, so the budget tests that relied on the one-slot default name two slots and the doubled need, and assert one slot is never short. The source checks follow the re-price to _exact_parking_writes_mib.
# Conflicts: # scripts/verify_import_hoist.py # studio/backend/core/inference/chat_template_helpers.py # studio/backend/core/inference/llama_admission.py # studio/backend/core/inference/llama_cpp.py # studio/backend/core/inference/llama_server_args.py # studio/backend/core/inference/llama_stats.py # studio/backend/core/inference/studio_tool_loop.py # studio/backend/routes/inference.py # studio/frontend/src/features/chat/api/chat-api.ts # studio/frontend/src/features/chat/runtime-provider.tsx # studio/frontend/src/features/chat/stores/chat-runtime-store.ts # studio/frontend/src/features/chat/types/api.ts # studio/frontend/src/features/chat/utils/continuation.ts
This PR now also carries what was #10358 (stacked on it): llama-server owns the parking when it supports
--preempt-ram, Studio hands preemption to it, and the exact concurrency setting. The two are reviewed and merged as one.One llama-server holds one KV cache. Studio launches it with
--parallel N --kv-unified -c N,which gives N slots one shared pool of N cells while telling each slot it has all of them.
The server polices only
prompt_tokens < slot.n_ctx, never "is there room right now", sochats that each fit individually are all admitted and then collide. On overflow
server-context.cppcallssend_erroron every processing slot, so one overflow kills themall.
Reproduced on 2026-09-01: four parallel chats on
unsloth/Qwen3.8-27B-GGUFat-c 16384 --parallel 4 --kv-unified, all admitted, all generating, all four dead togetherwith
Context size has been exceeded.This is vLLM-style request-granularity preemption for that cache. Admission overcommits on
purpose, every chat may use the whole window less a buffer, and a watermark sweep evicts when
the live total nears the ceiling. A preempted chat pauses and resumes with its partial rather
than losing its turn, and the client sees a pause, not an error.
What it does
estimates, so
n_iis known while it is still growing. Every 32 generated tokens, atevery round boundary of a tool loop, and at every admission, the sweep compares the
committed total against the ceiling (the window less the buffer).
n_batch, 2048) plus the speculative drafts, because thecache fails on the next batch not fitting rather than on being full. A p90 eviction costs
about 21 tokens against the 2048 already reserved.
consume no compute; then newest arrival first, which is what vLLM V1 does, so the work
already done is the work preserved. A chat preempted three times running is promoted
above newest-first so repeatedly losing does not become never finishing. The sweep always
leaves one holder decoding. A fixed epoch winner was tried and dropped: it never measurably
reduced thrash, and in a live run the exempt chat grew until it filled the whole window.
generator, both dedupe ledgers, the conversation and the client's SSE response alive.
Resume re-opens the request with the partial as a trailing assistant turn plus
continue_final_message. A pause inside a thought resumes the thought asreasoning_content; a pause inside a tool call rolls back to the start of that call; apause before the first token re-issues the attempt whole. This is what protects
ToolLoopController's in-memory one-shot ledger: tearing the response down and resuming asa new request would re-run one-shot tools.
at the instant it is found), and its wait measures stall rather than wall clock: any
decoded token anywhere resets the clock, a hard bound covers a cache that churns forever
without fitting it, and a chat that could never fit beside anyone runs alone instead of
waiting.
as "Waiting for a free slot" and "Paused while another chat finishes" and as a non-error
stop reason. The tool loop, plain streaming, non-streaming and
/v1/messagessurfaces are armed;the Responses surface and both passthroughs are counted but never chosen (
STREAMING_RAW),because aborting a raw byte stream is a cancel, not a pause.
length. The loop nowtells the client when its own continuation cannot be served, so the client shows the
raise-context bar instead of retrying into a 400.
UNSLOTH_LLAMA_ADMISSION_PREEMPTdefaults to off, and an install that does notset it behaves exactly as main plus Studio: enforce the KV reservation on the wire, not just in the ledger #10120: no
/slotsreads, no participants on thecontroller, no residency probe, no
preempt_eventoron_tokenshanded to a generation,no
: preempt-*SSE comments, and admission prices every request against its plain fairshare rather than against what a pause could reclaim.
UNSLOTH_LLAMA_ADMISSION_PREEMPT=1turns the controller on. Getting there closed three paths that still did preemption work
with the switch off: the disarm teardown read
/slotsand erased idle slots wheneveranyone was queued at admission, every chat was handed a
PreemptSignalthat llama.cppfolded into a polled composite cancel event, and the admission charge kept the optimistic
flat allowance while the wire bound still permitted the full share. The switch is the
first thing every entry point asks, so leaving it off costs one environment read. Test
modules that exercise preemption opt in through a
preemption_opted_infixture ratherthan a global conftest setting, so the default stays visible to the rest of the suite.
Measured
The original failure, Qwen3.8-27B at
-c 16384 --parallel 4Context size has been exceededA single chat reaches essentially the whole window: 16380 of 16384 in one run. No static
N/P division binds it.
Throughput, Qwen3.5-4B with its MTP head, seed 1234, temperature 0
The two arms differ only in
UNSLOTH_LLAMA_ADMISSION_PREEMPT.Solo and fitting loads are identical with the machinery armed. When the four chats do not
fit, the disarmed run loses three of them to the speculative sub-batch assertion and the
armed run finishes all four; the never-paused chat decoded at 242 tok/s because it had the
GPU to itself while the others waited, and the 7 s first token is the queue, which is the
intended wait.
Qwen3.6-35B-A3B with its MTP head,
-c 8192 --parallel 4unsloth studio run, four tool-enabled chats: 4 of 4, 31190 tokens in131 s (238 tok/s aggregate), 8 pauses and 8 resumes, 0 give-ups, 0 context errors, first
token 0.5 s for the first chat and 104 s for the last.
errors.
Tauri desktop app renders with; the desktop loads the same bundle over the same fetch
path): 4 of 4 on both, no error boxes, the paused pill on 3 of 4, 7 and 8 pauses, 0
context errors.
The 35B exposed four defects the 4B never reached, all fixed and re-verified on reruns: a
chat parked on a tool approval kept counting cells that had been reclaimed, which kept two
waiters out of an empty cache; a round waiting behind a decoding leader timed out on a
ledger that only moves at round boundaries; a chat streaming its next tool call stayed in the
unpreemptable tools-running state while it grew, so nothing was paused and the pool
overflowed; and the client auto-continued a lone chat at the window's edge into a 400.
Exactness
A resume is exact: nothing the client saw is lost or repeated, and the continuation is what
the server produces from that exact prefix. Two seam bugs were found on the way (a dropped
first token after a resume, and a re-issued attempt losing
continue_final_message) and arepinned byte for byte in nine tests. Four concurrent greedy streams do not reproduce four solo
greedy streams even without this change, and a solo run does not reproduce itself at this
batch size (same prompt, same seed, divergence at character 74), because llama.cpp's
numerics depend on the batch composition; the server-side counterpart (unslothai/llama.cpp#184)
holds the batch shape fixed and shows 160 forced park-and-restore cycles byte-identical on the
4B and the 35B.
Policy
Policies were benchmarked in a deterministic simulator (
scripts/preempt_sim.py, andpreempt_policy_sim.pyfor the server-side counterpart) across 4096 to 65536 cells, 4 and 8slots, and eviction latencies from one sweep to twenty. Newest-first with promotion ranked
best overall (mean rank 2.89 of 7) and best on completions; largest-first, the previous
choice, ranked 5th and worst on fairness. At four chats every policy is within 1 percent of
makespan; the mechanism, not the victim choice, does the work.
Interaction with llama.cpp
When the cache does fill, upstream's speculative sub-batch bug is what kills the chats:
speculative batch index N is not inside the current sub-batch. Fixed separately inunslothai/llama.cpp#182, measured 18 occurrences to 0. unslothai/llama.cpp#183 stops one
overflow killing every slot. unslothai/llama.cpp#184 moves the pause into the server itself
(park to host RAM, restore in place, invisible on the wire); with it merged this branch's
ceiling can rise to the batch alone. None of the three is required by this PR, which keeps
the cache below the line so the retry path is not reached; they are what makes the residual
overshoot recoverable instead of fatal.
Risk
Backwards compatible by construction. Every new parameter defaults to the behaviour that
exists today:
preempt_eventandpreempt_policydefault to None,on_tokensto None, andpreemption_activeto False, so a caller that passes none of them is unchanged. Forwards areconditional rather than direct, guarded by a test, because a monkeypatched double with the
old signature must never be handed the new kwarg.
Every surface that takes a lease, in the two ways they differ
_openai_llama_admission_reservehas seven call sites and_openai_llama_preemption_armoriginally had one, and nothing in the code said those numbers had to relate. All seven are
now accounted for, and the split is a real distinction rather than a formality.
Armed, because they drive
generate_chat_completionand so have a Studio-side generatorholding the conversation to resume from: the GGUF tool loop, plain streaming, non-streaming,
and
/v1/messages.Counted but never chosen, because they stream llama-server's bytes straight to the client
and hold no conversation: the Responses surface and both passthroughs. Aborting one is a
cancel, not a pause, so arming them would hand the preemptor a victim it cannot reclaim from
without losing the turn. They register as a new
STREAMING_RAWstate, in_HOLDS_KVso theycount and out of
_PREEMPTABLEso they are never selected. Leaving them out of the ledgerwould make the watermark fire late by exactly their size and then evict a chat to free room
an uncounted holder is using, which is the same error as dropping a finished chat's charge
while its cells stay resident.
/v1/completionstakes no lease at all and stays out of scope.A test pins the invariant: every reserve is paired with an arm or a count, and every count
with a drop. It fails five of its eight cases on the unmodified tree.
Full backend suite: 38207 passed, with no regressions against the unmodified tree. The
remaining failures are diffusion, video and capability-detection tests that fail identically
without this branch.
Follow-up commits after review
The final answering pass of the tool loop opened its stream and read it on the cancel signal alone, so a pause chosen for it during that pass went unheeded while the participant stayed marked as preempting and its cells were never given back. The pass now forwards the signal to both calls and handles the interruption the way the rounds before it do: the visible answer and the thought written since the last replay are checkpointed and charged once, the client is told it is paused, the policy is awaited, and the pass resumes with the partial carried back as the turn to extend, or ends the turn on a length finish with a notice when the resume is refused. Twelve new tests, ten of which fail on the previous source.
Five more from the next pass. The final pass counted each attempt once after a resume (its per-attempt counter is reset with the rest) and charges a pause by the larger of the observed count and the estimate; an external provider's round overlaps at most eight calls like the local loop; the client clears its give-up latch when a later synthesis finishes normally; and a pause refused at the resume cap is handed back through a new on_declined() on the policy, so the participant returns to decoding instead of staying selected and unreleased. A neighbouring case went with it: a round loop whose resume is refused ends the turn with the notice and a length finish rather than decoding on without a lease.
Four more from the next pass. The gate's promise to compact an oversized call after it ran was a loop-scoped flag read at settle time, and an overlapped round prepares every call before it settles any, so the second call's preparation reset the first call's promise and its arguments were replayed in full after the side effect; the flag travels in the pending-call entry now and the settle takes it as a parameter. The tool-loop pause charged the usage figure or the character estimate and never the chunks the attempt had counted, undercharging token-dense text; it is the larger of the observed count and the estimate, as the plain and final passes do, and the counter is bound at the start of every attempt. The preemption gate named the cache llama-server allocated whether or not admission was charging against it, so with the KV accounting or admission control off every lease was free while the pricing stayed optimistic; it requires both to be on. And the disarm's reclaim counted the controller's participants only, while a request waiting at admission has none until its lease is granted, so the last finished chat kept its cells just as the waiter was admitted into them; the admission queue's queued count is part of the contention test. Five tests, one of which fails on the old read of the flag.
Three more from the next pass, and main merged. The admission queue and the preemption controller were keyed on the server's URL, and a mid-session respawn replays the load on a fresh port, so every chat registered before the crash was looked up under a key nobody held; the backend stamps an admission key per user load and keeps it across the replay, and every surface asks for that. The parked-slot resume gave up at a flat deadline while every slot was busy and moving; it and the commitment path take the controller's progress signature and reset the deadline on any change, under the same hard ceiling. The disarm probed and erased slots with blocking HTTP from async route bodies; the bookkeeping stays inline and the wire work runs on a worker when a loop is running. Twelve tests. Main is merged: the stats daemon keeps the shared scraper with main's finite guard ported into it, the tool-loop stream combines main's UI events gating with the preemption state notes, and the route tests send the UI events opt-in main now requires for tools with confirmation.
Nine more from the next two passes. A granted resume was marked decoding before it had a slot back, so a sweep could choose it, count its reservation as freed and set a signal the admission wait never reads; it is RESUMING until it decodes, holding its room and never a victim. A refused resume no longer reports a resume. The wait for room now yields a keepalive every two seconds, which the routes forward and the durable run loop renews its lease on, so a pause longer than the lease is a chat waiting its turn rather than a reaped run. Resume tickets reserve their room in ticket order, the head-of-line rule the waiters already live by, so a later smaller resume no longer overtakes an earlier one. The raw passthroughs and the Responses surface are marked measured at their first data line, so their residency and their charge are no longer summed. The early idle-slot reclaim hands parked commitments back only when every idle slot went, and the disarm's worker re-reads residency after its erases instead of writing a stale figure over newer samples. In the launcher, the re-exec marker is dropped where the hand-off landed and never handed to the server child, and a hand-off to a launcher behind a symlink that predates the guard is refused with a message instead of starting the loop it cannot stop. Twenty-five tests.
A full audit of the stack brought the next pass. This branch had grown its own
admission_output_allowanceplumbing beside #10120's, with a different policy (the whole window where preemption can reclaim) and none of its enforcement, so a respawn wrote the replacement context as the cap; #10120 is merged in, its mechanism with this branch's policy, and its nine cross-head cases pass here unmodified. A resume grant subtracted a PAUSED holder's replay estimate from the residency reading although a paused holder owns no cells (an 8000-token pause was granted with 11000 of 16384 resident); only a holder whose prompt is measured in the cache subtracts. The ledger counted a holder's reservation plus what it wrote, so four chats holding 3472 cells were counted as 7568 against a 7424 ceiling and the newest was preempted for room nobody needed; a participant now carries the prompt part of its charge and is counted at prompt plus generated, re-baselined at every round boundary. Two fixes already on the server-parking follow-up are backported: a resumed turn keeps every thought it produced (append_assistant_turnconcatenates reasoning as it does content), and a pause wait that raised ends the turn with its partial rather than decoding as if granted, with Stop read before every grant attempt. A chat alone on the cache no longer pays for a synchronous/slotsread every 32 chunks: the sweep and the token-path refresh run only when somebody else holds cells or waits for them, while admission and the resume wait still read afresh. From #10120's own follow-up: the re-cost prices what the opening priced for the conversation it is handed, runs below the round's compaction, a Stop during its wait is a cancel, a refusal ends the turn with the partial and alengthfinish, and the refused ending reports the last attempt's prompt. Thirty-nine new tests.Three more from the latest review. A resume that leaves the unpark queue grants waiters again (the main merge had dropped that call, so an arrival held back for the resume waited for an unrelated event). The
/slotsread and erase go through the no-proxy loopback opener, as/metricsalready did, soHTTP_PROXYnever sees the server's bearer. Oneround_may_promptnow decides whether a tool round may overlap, for both the GGUF and the provider loop, by asking the per-call confirmation question on the parsed arguments: "off" still keeps the order when an unisolated Python or Terminal call would ask, and the provider loop no longer hands the risk classifierNone.Before / after in Studio
Four chats at once on
unsloth/Qwen3.5-4B-MTP-GGUF(UD-Q4_K_XL),-c 8192 --parallel 4, each with a ~1500 token prompt and Max Tokens left at Max, so each fits alone but not all together. BEFORE is the merge base, AFTER is this branch withUNSLOTH_LLAMA_ADMISSION_PREEMPT=1. Two separate Studio installs, same GPU, same prompts.failed to find free space in the KV cacheretries, thenspeculative batch index 8 is not inside the current sub-batch [0, 8)on two slotsFinal state of all four chats (BEFORE left, AFTER right). On the left two answers stop partway through and show an error box; on the right all four complete:
One AFTER chat while it waited, showing the pause notice above the composer instead of an error:
Server-owned parking and exact concurrency (folded in from #10358)
Stacked on #10301. Pairs with unslothai/llama.cpp#260 (the server-side parking pin on upstream b11540, which replaces #184, #190 and #210 as the pinned commit).
Summary
When the launched llama-server can park a slot in host RAM itself (
--preempt-ram, unslothai/llama.cpp#184), Studio stands its own preemption down, lets every chat use the whole context window, relays the server's: preemptedand: resumedstream comments (unslothai/llama.cpp#190) to the GUI as the existing paused line, and never mistakes a park for a stall. On the bundled upstream build, or withUNSLOTH_LLAMA_PREEMPT_MODE=studio, behaviour is exactly #10301's.Why. Studio's own preemption pauses a chat by aborting its upstream stream and resumes by re-prefilling the partial. That is exact at the seam but not byte-identical once the MTP head is involved, and it has to hold back reaction headroom (192 cells per slot plus the drafts, 776 of 8192 at four slots). The server swap restores the sequence in place, byte-identical, at N minus 8 cells. With both active Studio's lower watermark fires first and the better mechanism never runs; with Studio's off, a parked slot was a silent stream that hit the 120 s stall timeout with nothing shown to the user.
Policy
--preempt-ramfrom the existing--helpprobe,--kv-unifiedon, and no hand-typed--preempt-ram 0.UNSLOTH_LLAMA_PREEMPT_MODE=auto|studio|server, defaultauto(server when the build can). Thearmedlog line says which mode is live.UNSLOTH_LLAMA_ADMISSION_PREEMPTisautowhen unset: every launch asks a parking-capable llama-server to park (a--preempt-rambudget bounded to the host: at most a quarter of available RAM, always leaving max(4 GiB, 15 percent of total)), and preemption arms only once that server confirms parking in/props(preempt.enabled). A stock or older server, an unreadable report, or a host with no RAM to spare keeps today's fair-share admission unchanged.1forces it on,0turns it off on both sides.PARKED_ON_TOOL,context_truncatedwithfits:falseand the ledger keep working. A parked slot is left out of the resident figure, since its cells are in host RAM; counting it made a nearly empty pool read as over the ceiling and erased idle slots for room that was never short.: preemptedand: resumedinto the same pause events the Studio-side preemption yields, so the routes emit: preempt-pausedand: preempt-resumedunchanged and the GUI shows "Paused while another chat finishes". The server's 2 s: preempt-keepaliverenews the stall deadline. For a swap build without the notices, the read wrapper consults/metricsrequests_preemptedbefore treating silence as a stall, capped at 30 minutes.Results
Qwen3.5-4B with two MTP drafts,
-c 8192, four slots, seed 0, temperature 0:Qwen3.6-35B-A3B with two MTP drafts,
-c 8192, four slots:Context size has been exceeded.Exactness
Forced parks every 64 tokens (
LLAMA_SERVER_PREEMPT_EVERY=64on the child) against an unforced run, through the Studio API, 1200 tokens, MTP on:Cost when it does not fire
Solo 1200-token chats on the 4B, same build, back to back: server mode 209.4 / 192.9 tok/s, studio mode 209.2 / 192.1, server again 208.8 / 193.4. The server-mode path adds one string compare on stream lines that are not
data:. The 35B solo numbers were taken on a GPU shared with a foreign job at full utilisation and spread 14x between passes, so they are not quoted.Tests
31 new tests in
test_server_side_preemption_handoff.py(mode and property, probe, controller, stream relay on both surfaces, a park before the first token, an upstream stream without comments is bytewise today's, the read-wrapper grace) plus the parked-slot occupancy test. 737 pass across the handoff, preemption, admission, tool loop, chat generation, slot release and stream cancel suites.Limitations
--preempt-rambudget. When that budget cannot hold a victim, the paired llama-server parks it by dropping its cells and re-prefilling on resume, so Studio never re-arms its own preemption for that case.: preemptedgo out then), so a build that carriesexact_concurrencyon/propsis never asked the aggregate/metricsreading; only a swap build predating the notices keeps that fallback./metricspark reading, bounded by the 30 minute park cap.Follow-up: slimmer
Five refactor commits, behaviour and coverage unchanged: the scripted backends, recording policies, fake responses and SSE builders that ten test files each carried are one shared
tests/preempt_fakes.py; the three pause sites inllama_cpp.pyshare one charge (the larger of the observed count and the estimate) and one declined-pause helper; the eighteen spellings of the controller key inroutes/inference.pyare one_preempt_key(); the barrier, recorder and registry-reset fixtures are shared; both no-flash respawns hand exact concurrency back through one helper. 1042 test functions before and after, none removed or renamed.Two comment sweeps then cut the added comment and docstring lines from 6313 to 1871 (70 percent), the AST gate confirming only comments, docstrings and whitespace changed. Against main the PR is 101 files and 17505 insertions, from 22555.
Verified at every commit by ruff and the 1484 preemption, admission, tool-loop and resume tests, then live on the slimmed Studio with the slimmed llama-server: four Chromium tool chats through the GUI at 8k finished 4 of 4 with 9 parks and 9 resumes, the paused label on three of them and no error; four parallel tool chats through
unsloth runat 16k finished 4 of 4 with 10 pauses and no context error.Follow-up: fixes and fewer tests
Three more commits.
Resume and lease fixes (4b9c38b). A resumed attempt keeps the reasoning that preceded its prose: the assembler folds the attempt's
reasoning_contentand any reasoning a previous pause left trailing into the partial the next attempt extends, instead of dropping it once prose had started. The final pass replays its own prose rather than the cumulative display text, which carried the thought into the answer. Stop during a pause ends the wait:ControllerPreemptionPolicy.await_resumetakes the cancel event and returns as soon as it is set, through one helper at the three pause sites. A park before the first token, and the keepalives that follow it, renew the first-token deadline instead of timing it out. A pause declined at the resume cap keeps the attempt: it is charged, its partial goes back through the assembler, and the final pass extends it withcontinue_final_messageunder what is left of the caller's cap, rather than starting afresh with the whole allowance. A long pause no longer expires a durable run: the server's: preempt-keepaliveand the Studio-side wait (now a generator that says so every two seconds while the policy waits) both reach the routes as a keepalive event, forwarded as: preempt-keepalive, which the durable producer renews the run lease on at the queue-wait rate and the frontend ignores.Admission fixes (a31bc71). One predicate,
preemption_eligible(), reads the rollout switch together with the admission-control and KV-budget switches for the controller'sactiveandplan_preemptions, for pricing, for arming and for the disarm's cache erase, so an install that switched admission off no longer arms a controller policy over leases charged nothing, and the wire clamp returns None under either opt-out instead of narrowing an unstated cap.LLAMA_ARG_PREEMPT_RAM=0in the child's environment disables the server hand-off the way--preempt-ram 0on the launch line does, read in llama.cpp's own order. Exact concurrency is reportedononly on the build's own evidence: a build that ignores the variable starts perfectly, so the load reads the--preempt-ramcapability the same fork ships and reportsunavailablewithout it, which under theonsetting fails the load as designed. The passthrough, Responses and/v1/messagesraw surfaces reserve as unpausable and pay the honest price, since a stream registered as never chosen has nothing to reclaim.Fewer tests (915cba3). 44 new test files and 11009 added lines become 10 files and 4494 lines, 604 test functions become 167 plus 21 parametrisations, with every behaviour kept: the incidents folded into their surface files, and every source-level wiring check but two rewritten as behaviour (a real FastAPI app with a recording backend and a patched controller ledger for the arming on every local chat surface, a recording erasures fixture for the disarm, a policy that reads the signal inside
on_resumedfor the clear-before-resume order). The survivors were checked against five scratch mutations of the production code (the arm made a no-op, the unregister skipped, the one-shot ledger no longer clearing,on_resumedbefore the clear, settlement never compacting); each was caught. The two source-level checks kept are the frontend's declared comment set, which only the TypeScript can answer, and the respawn retry's argument forwarding, which needs a llama-server that dies and comes back.Verified: ruff and the pre-push gate clean; the admission and preemption suites 1414 passed and 5 skipped; the whole backend suite 39557 passed and 221 skipped, with every failure in diffusion, audio, video and host-topology files this PR does not touch, the non-diffusion ones failing identically on the merge base. Live on the paired llama-server: four Chromium tool chats through the GUI at 8k finished 4 of 4 with the paused label on three, 9 parks and 9 resumes, no error box and no context error;
unsloth runat 16k with MTP and exact concurrency on, four parallel tool chats, finished 4 of 4 at 191 tok/s aggregate with 5 server parks and 5 resumes and no context error, Studio reportingmode=server exact=onfor every chat.Round two of fixes (1e7f37b). The parked-slot metrics probe sends the API key, since
/metricsis not in llama-server's public set and every check under--api-keywas a 401. Stop is read before every resume grant attempt and passed into the lease's resume, so a grant that succeeds at once no longer carries a stopped chat into the wait. The wire clamp takes the samepausableflag the reservation takes, and the passthrough body is built with it off, so an uncapped passthrough is held to its share while pausable chats keep the window. The settings page shows what the next load resolves to when nothing is stored, so an inheritedLLAMA_EXACT_CONCURRENCYreads as on. Three tests added; the admission, preemption and tool-loop suites 1152 passed and 5 skipped.Round 23
Five review items plus a second round of five isolated reviews of the updated heads. Everything below was reproduced before it was changed; the reproductions are now tests.
DeferredPreemptionPolicy.await_resumetook only a timeout, so the caller'scancel_eventkeyword raisedTypeErrorand the fallback waited without Stopcancel_event; an older inner policy still worksonoff the--preempt-ramcapability, which a build without the mode can carry/propsnow carriesexact_concurrency(unslothai/llama.cpp#197)contradicting_argskept every occurrence, so--flash-attn off --flash-attn onread as a contradiction andonkilled a valid server/v1/messagesstreams droppedpreemptevents; each restarted the stall keepalive, so a long park sent no bytes/v1/messagesstreams forward the same: preempt-paused,: preempt-keepalive,: preempt-resumedcomments as the OpenAI surfaceappend_assistant_turnconcatenatesreasoning_contentlike it concatenates contentlengthToolLoopController.call_key)/v1/messagesraw passthrough sent the caller's cap or the whole window while reserved as unpausabletool_startwithout closing its cardUNSLOTH_LLAMA_ADMISSION_PREEMPT=0left the child parking on its own default budgetLLAMA_ARG_PREEMPT_RAM=0unless something named a budget--preempt-ramis re-prefilled, and a re-prefill is not byte-identical on CUDA (it is on CPU)--preempt-ramto the whole pool when the server's default would not hold it; the server warns if a re-prefill happens under the mode anyway| The raw passthrough loops (Responses, chat and completions passthrough,
/v1/messagespassthrough) relayeddata:lines only, so a request the server parked sent the client nothing for the whole park |_server_park_sseforwards the server's park notices as the same comments every other surface sends || Exact concurrency was reported
onwith Studio doing the pausing (UNSLOTH_LLAMA_PREEMPT_MODE=studio, or the server's parking off), and a chat Studio resumes is re-prefilled rather than restored | The state needs the server to be the one parking;onfails the load naming the reason,autoloads with a warning || A user-named
--preempt-rambelow the KV pool was kept and reported exact, and the first park to outgrow it is re-prefilled | The shortfall is judged at launch: a warning names the figure to raise it to, the state isunavailable, andonfails the load || A swap build predating the stream notices parks in silence, and the read wrapper's
/metricsexcuse forwarded nothing, so a durable run's lease could expire during a legitimate park | The excuse stamps the backend and the run loop renews the lease from it, with a bounded wait || A pause that landed as the caller's cap ran out folded the interrupted attempt into the accumulators and then built the terminal event from the same reading, so a four-token answer reported eight and twice its decode time | Both cap-spent sites hand the builder the attempt's prompt side only |
| An auto-fit context left the KV pool unknown at launch, so the exact launch neither enlarged the parking budget nor judged it while the state read
on| With nothing named the child parks without a limit; a named budget is judged after launch off the context the server chose, and a pool that cannot be sized is not certified || Under
auto, Studio-side pausing or parking switched off were only judged after launch, so the child ran the mode it was then reported not to have | Preflighted: the child is not given the flag, with a warning naming the reason;onstill fails the load || The raw relays read llama-server without the metrics park grace, so on a swap build predating the stream notices a parked raw request was cut off as a stall |
_aiter_llama_stream_itemstakes the backend's park probe and excuses the silence under the same thirty-minute cap || A raw relay was priced at the honest per-slot share even with the server parking slots itself, so a raw stream cost a whole slot of the window that it never used | Both entry points read
server_preempts_kvand price a raw stream at the window on a parking server; a Studio-only server keeps the share || The raw relays' first-item deadline never asked the park probe, so a raw request parked during its prefill was cut off before its first token | Both first-read timeouts take the same metrics grace as the stall after it, under the same cap |
|
UNSLOTH_LLAMA_ADMISSION_PREEMPT=0with nothing named stood the child's parking down after the auto preflight had passed it | The preflight sees the opt-out too and drops the flag with a warning || A diffusion runner was asked to reload for exact concurrency it cannot apply | The reload check returns off for a diffusion runtime |
| The raw relays' park grace retried the httpx iterator after its read timeout, and an async generator that raised is closed, so the retry got StopAsyncIteration and a parked raw request ended as if its answer were complete |
_install_park_aware_readwaits the park out on the network stream's read, below the iterators, the way the synchronous read wrapper does; a closed iterator is never retried, so a stall is an error rather than a short answer || A declined pause that had spent the caller's cap still ran the final pass, floored at one token past the cap | The decline ends the turn with
lengthwhen the cap is spent, as a granted pause does ||
UNSLOTH_LLAMA_PREEMPT_MODE=studioleft the child its default parking budget, so the server parked on its own while Studio reported it did not and no relay excused the silence | Forced Studio mode stands the child's parking down like the global opt-out; a named budget keeps its say || The park grace's cap ran from the start of the read, so a request parked at the first-token deadline was cut off after the normal window plus what was left of the cap, not the grace the backstop allows | Both read wrappers start the grace at the deadline they first crossed and bound each retry by what is left of it |
| The park probe scrapes
/metricswith a blocking read, and the async relays called it on the event loop, holding every other stream for up to three seconds | The probe runs off the loop, at the network read and above the iterator alike || The final pass's refusal to pause again built its terminal event without folding the interrupted attempt, and its not-resumed end folded it and then added the reading again | Both ends fold the attempt once and hand the builder its prompt side |
| Exact concurrency appended
--kv-unifiedafter the user's extras, so an explicit--no-kv-unifiedwas reversed by last-arg | The opt-out is kept and reported as the contradiction it is;autodoes not start a mode the extras contradict,onfails the load naming the flag || A durable run renewed a silent lease only from the stamp the read wrapper writes at its read deadline, and before the first token that deadline is the whole first-token budget, the default lease exactly, so a run parked during prefill on a swap build without the notices was cancelled while healthy | With no stamp in hand the run loop asks
/metricsitself, off the event loop and at most once in five seconds across runs, still under the wrapper's cap || The exact chip and the field docs said llama-server refused the mode when Studio had withheld it itself | They say the load is not running with it; the load warnings carry the reason |
| The launch generated
--preempt-ram -1on the guess that exact would run, and every abandoned exact attempt kept it, so a fallback load parked on an unlimited budget | No budget is generated for a pool the launch cannot size; the server's default is judged after launch || The grace cap test timed real sleeps, which overshoot on a loaded runner and read as a short grace | The test drives a fake clock advanced by exactly each window |
| A parking shortfall found after an auto-fit launch was reported as the server having come up without the mode, while /props said it ran | The warning and the
onrefusal say the mode runs but cannot hold every park, so a chat re-prefilled after such a park can differ ||
UNSLOTH_LLAMA_PREEMPT_MODE=studiowith a named--preempt-ramran both mechanisms: the stand-down read any named budget as somebody's say, andLLAMA_ARG_PREEMPT_RAM=0alone could not have won because llama.cpp applies argv after the environment | One owner pauses chats: the stand-down reads only the mode, zeroes the environment and the argv token in place, and the load warning names the flag it overrode;autono longer starts the mode on the strength of a named budget while preemption is off || The parking budget was sized from the target pool plus a margin, while the server saves the target and the MTP draft state per park and holds several parks at once, so a budget the launch certified was short with a drafter |
_exact_parking_need_mibprices both pools plus a per-park margin, times the slot count; a draft cache that cannot be sized is judged after launch rather than certified ||
--cpu-moe,--n-cpu-moeand a CPU--override-tensorwere not contradictions, though they place per-layer matmuls on a backend whose kernel selection is size dependent; and their last occurrence was taken to decide, while llama.cpp accumulates tensor overrides | All three are Studio's own contradictions (a zero--n-cpu-moeis the default spelled out); an earlier CPU placement is not taken back by a later occurrence || A park that fell to recompute under exact concurrency was invisible to the client | The server's
: recomputednotice (unslothai/llama.cpp#197) is relayed as: preempt-recomputedon every surface and to durable followers, the finalpreemptcounts ride the turn's metadata, a build that counts without the notice has it synthesised, and the exact chip names the re-prefilled answer on the chat it happened in || The stall excuse asked the aggregate
requests_preempted, which counts every request, so a neighbour's park excused any stalled stream, including one that had already resumed |ServerParkNoticesreads this stream's own: preemptedand: resumedoff the wire below the parsers; a stream that has heard a notice never falls back to the aggregate probe, which stays for a swap build predating the notices under the same cap || The base branch moved under this one: #10120's wire enforcement and the audit fixes on #10301 (the resume grant, the prompt-plus-generated ledger, the reasoning and failed-wait backports, the uncontended token path, the re-cost that prices what it sends and treats a Stop as a Stop) were not here | Merged; one wire bound carries both policies, and this branch's
pausablestays on it and on the passthrough retry, so a raw relay keeps its share unless the server parks raw streams itself || The import-hoist gate read the shared test fixtures and three unused imports as botched hoists, and missed a name loaded inside an assignment target (
app.dependency_overrides[get_current_subject] = ...) | The unused imports go, the fixtures are named once per module, and every assignment target records the names it loads, with a self-test case |Round 25
Follow-up: on by default, review fixes, single-user latency
On by default, as described under Policy. Fixes from the review rounds since:
/propsreport parked silently while Studio read its silence as a stallserver_may_parkkeeps the park probe on; admission stays fair share until the server confirms/metricsreading is taken for non-streaming bodiesonexact concurrency check that can kill itTwo single-user latency levers from a profile of Studio's own overhead, each measured ABBA on one exclusive B200 against two base sessions (A/A spread in brackets):
<,[or{(every form it removes opens with one)Two other candidates (skipping the exact count on one slot, throttling the API key
last_used_atwrite) showed no gain outside the noise and were dropped.One chat on Studio's
--parallel 4 --kv-unifiedlaunch decodes as fast as on--parallel 1. Same binary and flags, fixed prompt withcache_promptoff, configs ordered ABBA over two rounds on one exclusive B200, server-side tok/s, median [range] of 12 samples:--parallel 1--parallel 4A new chat's time to first token is also the same on both: 426 ms on 4B and 464 ms on 0.6B, 16 samples each. About 300 to 430 ms of that is llama-server saving the previous conversation to its RAM prompt cache before the new prompt starts, since
--cache-ram 0brings it down to 37 to 113 ms. That cost belongs to the server's prompt cache, not to the slot count or to this change, and turning the cache off would give up fast switching back to an earlier conversation, so the launch keeps it. Doing the save in the background in llama-server is the follow-up.Single-user cost of the whole change, main (2a9f621) against this branch, Qwen3.5-4B on one exclusive B200, sessions ordered ABBA at each slot count, median [range] over every request (main has two or three sessions per row, so its range is the noise from one session to the next):
Every median on this branch sits inside main's own spread, for the direct and
/v1paths too, so the change costs a single chat nothing measurable at one slot or four.Follow-up: main merges, rollback state, every OS
/v1/responsesand/v1/messagesstream loops into_ResponsesStreamTranslator.feed,_AnthropicToolEventRulesand_anthropic_passthrough_chunk_lines. The recompute announcement, park notices and tool-loop state reporting now sit beside those helpers on the llama-server branch only, so the in-process MLX paths that share them are unchanged. Removing any of the three ported hooks fails 6 tests.min, which main's reply-floor code uses; binding it to the unclamped figure still fails it./proc/self/fdreachability probes and a system-folder path guard on the runner's temp dir, all in tests this PR does not changeBefore / after in Studio
Four chats at once on
unsloth/Qwen3.5-4B-MTP-GGUF(UD-Q4_K_XL),-c 8192 --parallel 4, each with a ~1500 token prompt and Max Tokens at Max, so each fits alone but not all together. Both sides run the same llama-server build (unslothai/llama.cpp#260) and default settings. BEFORE is #10301, where preemption is off by default; AFTER is this branch.failed to find free space in the KV cacheretries, thenspeculative batch index ... is not inside the current sub-batchon two slots--preempt-ram 2212chosen for the host; slots parked to host RAM (about 120 MiB each) and restored in about 140 ms; one rotation of a long-parked chatFinal state of all four chats (BEFORE left, AFTER right):
One AFTER chat while the server held it parked:
Settings: the exact concurrency control
Settings > System > GGUF inference engine, from two separate installs. BEFORE is #10301's head (647c0fb), since this PR is stacked on it; AFTER is this branch (c5e6453). AFTER adds the Exact concurrency row with its description and an Auto / Off / On select, default Off;
/api/settings/exact-concurrencyanswers 404 on BEFORE andeffective: "off"on AFTER.Studio UI regression check
Base
6d7afe058vs headba235dd9a. Functional: NO_REGRESSION, UI coverage 78%, 1 visual change(s), 1 text-only change(s). Only steps whose screenshots differ are shown.settings/s04_tab_system: masks cover 18% of the shot

crawl/r_hub