Skip to content

studio: KV preemption so parallel chats share one cache, with llama-server owning the parking - #10301

Open
danielhanchen wants to merge 856 commits into
mainfrom
feat/kv-preemption
Open

danielhanchen wants to merge 856 commits into
mainfrom
feat/kv-preemption

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

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", so
chats that each fit individually are all admitted and then collide. On overflow
server-context.cpp calls send_error on every processing slot, so one overflow kills them
all.

Reproduced on 2026-09-01: four parallel chats on unsloth/Qwen3.8-27B-GGUF at
-c 16384 --parallel 4 --kv-unified, all admitted, all generating, all four dead together
with 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

  • Live per-chat KV accounting, driven by the token stream rather than by admission
    estimates, so n_i is known while it is still growing. Every 32 generated tokens, at
    every round boundary of a tool loop, and at every admission, the sweep compares the
    committed total against the ceiling (the window less the buffer).
  • The buffer is one prefill batch (n_batch, 2048) plus the speculative drafts, because the
    cache fails on the next batch not fitting rather than on being full. A p90 eviction costs
    about 21 tokens against the 2048 already reserved.
  • Victim choice, in order: chats parked on a tool approval first, since they hold cells and
    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.
  • Pause by aborting only the upstream llama-server stream, keeping the Studio-side
    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 as
    reasoning_content; a pause inside a tool call rolls back to the start of that call; a
    pause 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 as
    a new request would re-run one-shot tools.
  • A resumed chat waits for room that actually exists (a fresh residency read, the room booked
    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.
  • Queued and paused are reported to the client as SSE comments, which the frontend renders
    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/messages surfaces 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.
  • A lone chat that fills the whole window on its own still ends with length. The loop now
    tells the client when its own continuation cannot be served, so the client shows the
    raise-context bar instead of retrying into a 400.
  • Opt-in. UNSLOTH_LLAMA_ADMISSION_PREEMPT defaults to off, and an install that does not
    set it behaves exactly as main plus Studio: enforce the KV reservation on the wire, not just in the ledger #10120: no /slots reads, no participants on the
    controller, no residency probe, no preempt_event or on_tokens handed to a generation,
    no : preempt-* SSE comments, and admission prices every request against its plain fair
    share rather than against what a pause could reclaim. UNSLOTH_LLAMA_ADMISSION_PREEMPT=1
    turns the controller on. Getting there closed three paths that still did preemption work
    with the switch off: the disarm teardown read /slots and erased idle slots whenever
    anyone was queued at admission, every chat was handed a PreemptSignal that llama.cpp
    folded 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_in fixture rather
    than 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 4

before after
chats completed 0 of 4 4 of 4
Context size has been exceeded 3 0
slots decoding at once 1 4
largest single chat 7957 13599 of a 14312 ceiling
preemptions / resumes 0 / 0 9 / 9
gave up n/a 0
eviction latency, median n/a 1.5 ms

A 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.

run completed per-chat tok/s first token paused errors
on, c32768, 1 chat 1 of 1 272.6 0.22 s 0 0
off, c32768, 1 chat 1 of 1 272.2 0.22 s 0 0
on, c32768, 4 chats 4 of 4 131 to 150 while four ran 0.70 s 0 0
off, c32768, 4 chats 4 of 4 132 to 155 0.68 s 0 0
on, c8192, 4 chats 4 of 4 53 to 242 2.1 s mean, 7.0 s max 9 0
off, c8192, 4 chats 1 of 4 0.75 s 0 3

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 4

  • Bare API through unsloth studio run, four tool-enabled chats: 4 of 4, 31190 tokens in
    131 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.
  • Studio API, four tool-enabled chats: 4 of 4, 23331 tokens, 3 pauses, 0 give-ups, 0 context
    errors.
  • Browser GUI through Playwright, four chats with tools, Chromium and WebKit (the engine the
    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 are
pinned 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, and
preempt_policy_sim.py for the server-side counterpart) across 4096 to 65536 cells, 4 and 8
slots, 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 in
unslothai/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_event and preempt_policy default to None, on_tokens to None, and
preemption_active to False, so a caller that passes none of them is unchanged. Forwards are
conditional 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_reserve has seven call sites and _openai_llama_preemption_arm
originally 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_completion and so have a Studio-side generator
holding 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_RAW state, in _HOLDS_KV so they
count and out of _PREEMPTABLE so they are never selected. Leaving them out of the ledger
would 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/completions takes 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_allowance plumbing 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_turn concatenates 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 /slots read 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 a length finish, 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 /slots read and erase go through the no-proxy loopback opener, as /metrics already did, so HTTP_PROXY never sees the server's bearer. One round_may_prompt now 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 classifier None.

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 with UNSLOTH_LLAMA_ADMISSION_PREEMPT=1. Two separate Studio installs, same GPU, same prompts.

panes finished panes with an error box panes that showed the pause server log
BEFORE 4 2 0 9 failed to find free space in the KV cache retries, then speculative batch index 8 is not inside the current sub-batch [0, 8) on two slots
AFTER 4 0 2 no cache-full retry, no error

Final 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:

Four parallel chats, before and after

One AFTER chat while it waited, showing the pause notice above the composer instead of an error:

A chat paused while another finishes


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 : preempted and : resumed stream 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 with UNSLOTH_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

  • Detection: --preempt-ram from the existing --help probe, --kv-unified on, and no hand-typed --preempt-ram 0. UNSLOTH_LLAMA_PREEMPT_MODE=auto|studio|server, default auto (server when the build can). The armed log line says which mode is live.
  • On by default where it can be. UNSLOTH_LLAMA_ADMISSION_PREEMPT is auto when unset: every launch asks a parking-capable llama-server to park (a --preempt-ram budget 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. 1 forces it on, 0 turns it off on both sides.
  • Server mode: the controller plans no victims and its buffer is 0 (the server reserves its own drafts and an 8 cell margin, and parks the moment the next batch does not fit). Admission, the tool loop, PARKED_ON_TOOL, context_truncated with fits:false and 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.
  • Stream: the three stream consumers (plain chat, tool loop, legacy tool loop) turn : preempted and : resumed into the same pause events the Studio-side preemption yields, so the routes emit : preempt-paused and : preempt-resumed unchanged and the GUI shows "Paused while another chat finishes". The server's 2 s : preempt-keepalive renews the stall deadline. For a swap build without the notices, the read wrapper consults /metrics requests_preempted before 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:

  • Four chats through the API: 4 of 4 in server mode (318 tok/s aggregate, one park), 4 of 4 on the tool-loop path (two parks), 4 of 4 in studio mode on the same build, 4 of 4 on the bundled upstream build. Zero errors in every run.
  • Four Playwright Chromium chats, tools off: 4 of 4 finished, paused label on the three chats that were parked, zero error boxes.

Qwen3.6-35B-A3B with two MTP drafts, -c 8192, four slots:

  • Four chats through the API: 4 of 4 with every chat producing its full 2048 tokens, one natural park, zero errors. Studio mode on the same build and load: 4 of 4 without an HTTP error, but one chat ended empty after the Studio-side controller gave up waiting for room (a studio: KV preemption so parallel chats share one cache, with llama-server owning the parking #10301 path, followed up separately).
  • Four Playwright Chromium chats: 4 of 4 finished, paused label on 3 of 4, eight natural parks lasting 59 to 422 s with no stall fired, zero error boxes, zero Context size has been exceeded.

Exactness

Forced parks every 64 tokens (LLAMA_SERVER_PREEMPT_EVERY=64 on the child) against an unforced run, through the Studio API, 1200 tokens, MTP on:

model prompt bytes parks identical
4B 0 5077 18 yes
4B 1 5700 18 yes
35B 0 5276 18 yes
35B 1 4756 18 yes

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

  • Server mode trusts the server's --preempt-ram budget. 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.
  • A park during prompt processing is announced at park time by the paired llama-server (headers and : preempted go out then), so a build that carries exact_concurrency on /props is never asked the aggregate /metrics reading; only a swap build predating the notices keeps that fallback.
  • The metrics grace for a swap build without the notices is unit-tested only; the notify build never needs it.
  • Non-streaming requests get no pause notice, since their body carries none: a non-streaming request parked past its read window is waited out on the server's aggregate /metrics park 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 in llama_cpp.py share one charge (the larger of the observed count and the estimate) and one declined-pause helper; the eighteen spellings of the controller key in routes/inference.py are 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 run at 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_content and 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_resume takes 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 with continue_final_message under 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-keepalive and 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's active and plan_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=0 in the child's environment disables the server hand-off the way --preempt-ram 0 on the launch line does, read in llama.cpp's own order. Exact concurrency is reported on only on the build's own evidence: a build that ignores the variable starts perfectly, so the load reads the --preempt-ram capability the same fork ships and reports unavailable without it, which under the on setting fails the load as designed. The passthrough, Responses and /v1/messages raw 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_resumed for 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_resumed before 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 run at 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 reporting mode=server exact=on for every chat.

Round two of fixes (1e7f37b). The parked-slot metrics probe sends the API key, since /metrics is not in llama-server's public set and every check under --api-key was 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 same pausable flag 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 inherited LLAMA_EXACT_CONCURRENCY reads 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.

Finding Fix
The routed DeferredPreemptionPolicy.await_resume took only a timeout, so the caller's cancel_event keyword raised TypeError and the fallback waited without Stop The wrapper and the protocol carry cancel_event; an older inner policy still works
Exact concurrency was reported on off the --preempt-ram capability, which a build without the mode can carry Read off the running server: /props now carries exact_concurrency (unslothai/llama.cpp#197)
contradicting_args kept every occurrence, so --flash-attn off --flash-attn on read as a contradiction and on killed a valid server Each option resolves to its last value, as llama-server applies argv
The /v1/messages streams dropped preempt events; each restarted the stall keepalive, so a long park sent no bytes Both /v1/messages streams forward the same : preempt-paused, : preempt-keepalive, : preempt-resumed comments as the OpenAI surface
The exact-concurrency chip read the local server's state next to a hosted model selected beside it Rendered only for the resident local model
A resumed attempt that went on thinking and then called a tool carried only its own thought; the merge replaced the earlier one append_assistant_turn concatenates reasoning_content like it concatenates content
A declined pause's final pass started its snapshots empty, so a non-streaming drain returned the suffix alone, and its cap deducted only the declined attempt The pass extends the partial (no turn boundary, cumulative snapshots) and deducts everything the call spent
A pause with the caller's cap spent reopened the stream for one floored token, past the cap, at all three sites The turn ends with length
A parallel round keyed on the arguments as they arrived, so two spellings healing to one call both ran Keyed on the ledger's healed key (ToolLoopController.call_key)
The /v1/messages raw passthrough sent the caller's cap or the whole window while reserved as unpausable Sent the same enforced cap as the OpenAI passthrough
An unstated, unpausable request reserved the flat allowance while being permitted the rest of its share: two beside one stated request reserved 16064 of 16384 and were permitted 22192 Charged what it is sent, the rest of its share
The residency sweep ran with preemption ineligible; a never-configured controller has a zero ceiling, so idle prefix caches were erased on the paths meant to keep their old behaviour Gated on the same predicate arming and pricing use
A policy that raised during the wait was treated as a grant in both tool-loop pause handlers Not a grant: the turn ends with its partial, as a refusal does
A rollback abandoned a provisional tool_start without closing its card The card is closed before the pause is announced
UNSLOTH_LLAMA_ADMISSION_PREEMPT=0 left the child parking on its own default budget One switch: the child gets LLAMA_ARG_PREEMPT_RAM=0 unless something named a budget
A park that outgrows --preempt-ram is re-prefilled, and a re-prefill is not byte-identical on CUDA (it is on CPU) An exact launch sizes --preempt-ram to 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/messages passthrough) relayed data: lines only, so a request the server parked sent the client nothing for the whole park | _server_park_sse forwards the server's park notices as the same comments every other surface sends |
| Exact concurrency was reported on with 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; on fails the load naming the reason, auto loads with a warning |
| A user-named --preempt-ram below 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 is unavailable, and on fails the load |
| A swap build predating the stream notices parks in silence, and the read wrapper's /metrics excuse 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; on still 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_items takes 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_kv and 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=0 with 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_read waits 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 length when the cap is spent, as a granted pause does |
| UNSLOTH_LLAMA_PREEMPT_MODE=studio left 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 /metrics with 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-unified after the user's extras, so an explicit --no-kv-unified was reversed by last-arg | The opt-out is kept and reported as the contradiction it is; auto does not start a mode the extras contradict, on fails 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 /metrics itself, 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 -1 on 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 on refusal say the mode runs but cannot hold every park, so a chat re-prefilled after such a park can differ |
| UNSLOTH_LLAMA_PREEMPT_MODE=studio with a named --preempt-ram ran both mechanisms: the stand-down read any named budget as somebody's say, and LLAMA_ARG_PREEMPT_RAM=0 alone 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; auto no 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_mib prices 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-moe and a CPU --override-tensor were 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-moe is 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 : recomputed notice (unslothai/llama.cpp#197) is relayed as : preempt-recomputed on every surface and to durable followers, the final preempt counts 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 | ServerParkNotices reads this stream's own : preempted and : resumed off 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 pausable stays 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

Finding Fix
The exact parking budget shared the pool out per slot, but every parked history can be the whole unified pool Sized to the pool plus a per-park margin, times the slot count, with a launch warning when that exceeds the host's free memory
A raw holder registered as measured before its prefill was swallowed by a residency sample from before it Every raw holder registers unmeasured; streams mark themselves at their first data line, non-streaming requests stay counted for their answer
The tool relay cleared the turn's park counters on every final object Summed across the turn's requests
A lease at its floor could expire between two park probes on a swap build without notices The minimum lease covers two probes
A stream on a notice build that heard nothing could still be excused by another stream's park The aggregate reading is never consulted on a build that writes the notices
The exact preflight judged the parent's environment while Manual mode scrubbed the placement twins from the child Judged against the environment the child receives
The recompute note lived only in memory Persisted with the answer and read back on load
Dead longest-wins winner state in the controller Removed

Follow-up: on by default, review fixes, single-user latency

On by default, as described under Policy. Fixes from the review rounds since:

Finding Fix
One process-wide parking flag, so a helper or extra model slot load flipped the main server's mode Recorded per backend and read for the backend the request is routed to
A parking build without the /props report parked silently while Studio read its silence as a stall server_may_park keeps the park probe on; admission stays fair share until the server confirms
A non-streaming request on a notice build could not be excused while parked The aggregate /metrics reading is taken for non-streaming bodies
Any signed-in account could switch exact concurrency machine-wide The write is owner-only, like model memory and the VRAM budget
Park keepalives renewed the first-token and stall clocks without bound Renewals stop at the park start plus the 30 minute cap, on the backend stream and on every raw relay
A run's park probe was rate limited process-wide and answered False inside the window The last answer is cached per backend and returned
A continuation cleared the recompute note off the joined answer The note is carried in the continuation request
The backend went live before an on exact concurrency check that can kill it Published only after that check

Two 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):

lever measurement base with the lever
Skip the tool-markup display strip on streamed text holding no <, [ or { (every form it removes opens with one) client tok/s, tools on, Qwen3-0.6B, 64 prompt / 2048 out 564 to 570 909 to 973
Remember prompt counts per llama-server process and rendered body TTFT minus server prompt time, GUI with tools, Qwen3.5-4B, 4 slots, 64 prompt 111 to 122 ms 96 to 99 ms

Two other candidates (skipping the exact count on one slot, throttling the API key last_used_at write) showed no gain outside the noise and were dropped.

One chat on Studio's --parallel 4 --kv-unified launch decodes as fast as on --parallel 1. Same binary and flags, fixed prompt with cache_prompt off, configs ordered ABBA over two rounds on one exclusive B200, server-side tok/s, median [range] of 12 samples:

model prompt --parallel 1 --parallel 4
Qwen3.5-4B 64 252.5 [244-261] 251.7 [233-270]
Qwen3.5-4B 4000 247.9 [240-255] 245.0 [236-257]
Qwen3-0.6B 64 1080 [797-1152] 1026 [749-1138]
Qwen3-0.6B 4000 1009 [818-1221] 1003 [757-1191]

A 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 0 brings 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):

slots path prompt main TTFT ms this branch TTFT ms main client tok/s this branch client tok/s
1 GUI 64 229 [197-358] 209 [183-349] 253 [74-267] 264 [249-270]
1 GUI + tools 64 373 [165-742] 355 [155-398] 259 [38-277] 263 [256-269]
1 GUI 4000 984 [868-1497] 929 [872-968] 243 [129-261] 253 [229-259]
1 GUI + tools 4000 1022 [979-2022] 1008 [979-1047] 248 [122-283] 250 [240-272]
4 GUI 64 276 [228-640] 287 [249-466] 234 [182-263] 251 [162-253]
4 GUI + tools 64 429 [190-564] 540 [184-1103] 256 [241-284] 245 [175-351]
4 GUI 4000 1100 [918-1338] 1009 [924-1126] 231 [124-247] 247 [231-261]
4 GUI + tools 4000 1223 [1038-1743] 1126 [996-1239] 246 [192-262] 246 [208-254]

Every median on this branch sits inside main's own spread, for the direct and /v1 paths too, so the change costs a single chat nothing measurable at one slot or four.

Follow-up: main merges, rollback state, every OS

  • Main merged at 95cff83 and 20b4a8e. Main moved the /v1/responses and /v1/messages stream loops into _ResponsesStreamTranslator.feed, _AnthropicToolEventRules and _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.
  • ba235dd: when a failed model switch reloads the previous GGUF, the header now takes the exact-concurrency state from that reload's own response, as a normal load does, instead of waiting on a status refresh that can fail quietly.
  • 550f5f2: the enforced-cap test accepts a local bound to the clamped figure and only lowered with min, which main's reply-floor code uses; binding it to the unclamped figure still fails it.
check result
118 PR test files, Linux (20b4a8e) 4265 passed, 6 skipped
whole backend suite, merge vs main, by failing test ID no failure the merge adds
switchboard, base 6d7afe0 vs head 20b4a8e, 13 targets NO_REGRESSION: 76 same, 6 DOM-only with 0 changed pixels, 1 failing on both sides
Studio journeys on ubuntu, macOS and Windows runners (ba235dd) NO_REGRESSION; the only visual change is the new Exact concurrency row, shown below
macOS, PR test files 4229 passed; the failures are sqlite-vec failing to load, /proc/self/fd reachability probes and a system-folder path guard on the runner's temp dir, all in tests this PR does not change
Windows, PR test files 4255 passed; the 3 failures also fail at the merge base on the AMD Windows runner, and the setup errors are parametrize IDs over Windows' 32767-character environment limit
AMD gfx1151, Linux and Windows (550f5f2) NO_REGRESSION on both

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

panes finished panes with an error box panes that showed the pause server log
BEFORE 4 2 0 10 failed to find free space in the KV cache retries, then speculative batch index ... is not inside the current sub-batch on two slots
AFTER 4 0 2 --preempt-ram 2212 chosen for the host; slots parked to host RAM (about 120 MiB each) and restored in about 140 ms; one rotation of a long-parked chat

Final state of all four chats (BEFORE left, AFTER right):

Four parallel chats, before and after

One AFTER chat while the server held it parked:

A chat paused while another finishes

Settings: the exact concurrency control

Settings, GGUF inference engine: the Exact concurrency row with Auto, Off and On

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-concurrency answers 404 on BEFORE and effective: "off" on AFTER.

Studio UI regression check

Base 6d7afe058 vs head ba235dd9a. 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
settings/s04_tab_system

Step Text / structure change
crawl/r_hub masks cover 1686% of the shot

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-19T17:51:44.696048Z eb7e3ae New commits
🔒 Security Review ✅ Completed 2026-09-09T22:43:43.749486Z 734d3e7 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines 2584 to 2587
injected_tools = injected_tools,
context_window = _openai_llama_admission_context_window(llama_backend),
preemption_active = _openai_llama_preemption_will_apply(llama_backend, budget),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +21640 to +21642
_openai_llama_preemption_disarm(
llama_backend = llama_backend, gen_id = completion_id,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

A three-second cleanup on the loop is a latency cost, not a wrong result, a lost call or a wrong admission. Leaving it.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +2641 to +2642
if not contended:
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The 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.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +815 to +816
occupied = self._resident - self._reclaimable
others = max(others, occupied - (mine.tokens if mine else 0))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The 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.

Comment on lines +1579 to +1581
parallel_round = (
parallel_tool_calls_enabled() and len(calls) > 1 and not _approval_gate
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The 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.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +2729 to +2730
ceiling = window or budget
return max(1, ceiling - prompt_tokens)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Reaching this needs the operator kill switch, and under it a stated cap is charged in full. Not a session-input path.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +31173 to +31176
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)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +2448 to +2452
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),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

A pause a later erase made unnecessary costs one prefill; the victim resumes with its partial carried. Efficiency, not correctness.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

https://github.com/unslothai/unsloth/blob/27b9e91ab5a7d066c0c57b30ee4c3147cb40c648/studio/backend/routes/inference.py#L2814
P2 Badge 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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Disconnect-path teardown hardening; the shared cancel event already reaches every driver.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

https://github.com/unslothai/unsloth/blob/dd42962672cff9c1b505394afa5b586e9e8e6cd6/studio/backend/core/inference/llama_cpp.py#L32327-L32329
P1 Badge 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".

Comment on lines +32150 to +32151
_resumed = preempt_policy.await_resume()
preempt_policy.on_resumed()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment on lines +1443 to +1445
# 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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The stall and hard deadlines in the grant loop already bound the wait, and the asynchronous resume is called with that timeout.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The resume loop polls the progress signature under a stall deadline and a hard deadline, so it cannot block indefinitely.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +2489 to +2493
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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

A respawn onto a new port mid-passthrough is a recovery path, and the old controller is retired with its queue.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +2489 to +2493
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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Same as above: raw holders are counted, and the wire clamp bounds each to its window.

Comment on lines +1949 to +1951
for entry in pending_calls:
async for line in _settle_call(entry):
yield line

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Same class as the disconnect-path cleanup above.

Comment on lines 29606 to 29608
if continue_final_message and trailing_assistant_resumable(conversation):
payload["continue_final_message"] = True
payload["add_generation_prompt"] = False

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 4, 2026
danielhanchen and others added 29 commits October 25, 2026 08:31
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 branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

affects UI# conflicts# edge case# new-feature# refactor# regresses# security# Moves a security boundary: sandbox, allowlist, permission or network guard >3000#

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants