Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Let tool chats decode in parallel instead of one at a time (#10046)

Daniel Han044cdb8a7e18
diff --git a/studio/backend/core/inference/llama_admission.py b/studio/backend/core/inference/llama_admission.py
index 4c3665bc749..bc50589ff35 100644
--- a/studio/backend/core/inference/llama_admission.py
+++ b/studio/backend/core/inference/llama_admission.py
@@ -15,6 +15,7 @@ import asyncio
import os
import sys
import threading
+import time
from collections import deque
from dataclasses import dataclass
from typing import Deque, Optional
@@ -64,6 +65,10 @@ DEFAULT_ADMISSION_MIN_QUEUE = 64
# reports n_ctx_slot = n_ctx to every slot, so N generations are admitted against a
# cache that may hold one. When they collide, llama.cpp kills every task involved.
DEFAULT_ADMISSION_KV_BUDGET = True
+# Ceiling on one round's wait for cache room; generous, since a legitimate wait is bounded
+# by the longest round in flight. Bounded at all because a reparker holds the wait line
+# shut for every other caller, so an unbounded wait freezes the queue. See recost_waiting.
+DEFAULT_RECOST_WAIT_TIMEOUT_S = 300.0
def _executor_workers() -> int:
@@ -427,6 +432,126 @@ class LlamaAdmissionLease:
if stranded is not None:
queue.release(stranded)
+ def recost(self, tokens: int) -> bool:
+ """Re-state what this lease actually occupies as its conversation grows.
+
+ True when the new figure is in force (including with no budget to account
+ against). False means the cache cannot back the growth, the previous commitment
+ still stands, and the caller is over its reservation.
+ """
+ want = max(0, int(tokens or 0))
+ # Held ACROSS try_recost: a release interleaving between the queue accepting the
+ # new figure and this lease recording it would hand back the OLD number and strand
+ # the difference as committed for the life of the process. release() takes this
+ # lock then the queue's, so this order cannot deadlock against it.
+ with self._release_lock:
+ if self._released or self._queue is None:
+ return True
+ if want == self._tokens:
+ return True
+ if not self._queue.try_recost(self._tokens, want):
+ return False
+ self._tokens = want
+ return True
+
+ def recost_waiting(
+ self,
+ tokens: int,
+ *,
+ cancel_event = None,
+ poll_s: float = 0.05,
+ timeout_s: Optional[float] = DEFAULT_RECOST_WAIT_TIMEOUT_S,
+ allow_yield: bool = True,
+ ) -> bool:
+ """Re-state this lease's cost, waiting for room rather than running over it.
+
+ ``recost`` declines when the cache is full and the caller carries on at its old
+ figure, so the next round sends a bigger prompt than the pool was told about, and
+ enough of those is the ``Context size has been exceeded`` that kills every
+ decoding slot at once.
+
+ Call this only between rounds, and only with ``allow_yield`` true where an idle
+ slot's cells actually come back. Being between rounds makes the slot IDLE; what
+ makes its cells REUSABLE under ``--kv-unified`` is ``prompt_clear()``, which
+ llama-server runs only under ``--cache-idle-slots`` (``server-context.cpp``) --
+ force-disabled by ``--cache-ram 0``, and absent on older servers. Studio emits
+ ``--cache-ram 0`` on Windows under full GPU offload (#5692, WDDM overhead)
+ alongside ``--kv-unified``; there a yielded round's cells stay resident, so
+ yielding would hand the same capacity to a second caller. With yielding off this
+ degrades to plain ``recost``, which declines rather than overcommits. Where
+ clearing IS active the cache changes only the PRICE: reclaiming costs a prefix hit
+ if the cells were spilled to host RAM.
+
+ False means this lease still holds the figure it came in with: declined,
+ cancelled, released, or waited past ``timeout_s``. The timeout is the blast
+ radius -- a reparker holds the wait line shut for everyone (see
+ ``yield_commitment``), so an endless wait freezes the queue, not one chat. Giving
+ up restores the old commitment and the decline-and-continue behaviour that
+ predates this.
+ """
+ want = max(0, int(tokens or 0))
+ # Cheap path first: growth that already fits never touches the wait line.
+ if self.recost(want):
+ return True
+ if not allow_yield:
+ return False
+ queue = self._queue
+ with self._release_lock:
+ if self._released or queue is None:
+ return True
+ held, self._tokens = self._tokens, 0
+ queue.yield_commitment(held)
+ deadline = None if not timeout_s or timeout_s <= 0 else time.monotonic() + timeout_s
+ try:
+ while True:
+ if queue.try_reclaim_commitment(want):
+ with self._release_lock:
+ if self._released:
+ # Released while waiting; release() already gave back 0 and
+ # will not run again, so hand the commitment straight back.
+ queue.release(None, want)
+ return True
+ self._tokens = want
+ return True
+ # Every pass, not only on the two exits below: release() runs from the
+ # route's teardown without touching the cancel event, so a Stop would
+ # otherwise leave this spinning on a dead lease, wait line held shut.
+ if self._released:
+ queue.abandon_repark()
+ return False
+ if cancel_event is not None and cancel_event.is_set():
+ return self._give_up_repark(queue, held, cancelled = True)
+ if deadline is not None and time.monotonic() >= deadline:
+ return self._give_up_repark(queue, held, cancelled = False)
+ time.sleep(poll_s)
+ except BaseException:
+ self._give_up_repark(queue, held, cancelled = True)
+ raise
+
+ def _give_up_repark(self, queue, held: int, *, cancelled: bool) -> bool:
+ """Stop waiting and go back to holding ``held``.
+
+ Both halves under one queue lock (``abandon_repark(restore = held)``): the wait
+ line reopens and the old figure is re-committed together. This lease still
+ occupies that much of llama-server's cache, so re-committing it is a correction,
+ not a request -- asking through ``try_recost`` let a full cache REFUSE it, after
+ which release() subtracted a commitment that was never restored and handed the
+ next arrival that much phantom room.
+
+ ``_release_lock`` is held across the queue call in release()'s lock order, so the
+ commitment cannot be released out from under the restore.
+ """
+ with self._release_lock:
+ if self._released:
+ # release() already ran and gave back the 0 held while parked, and
+ # yield_commitment already took `held` off the pool, so restoring it
+ # here would strand it as committed for good.
+ queue.abandon_repark()
+ return False
+ self._tokens = held
+ queue.abandon_repark(restore = held)
+ return False
+
def release(self) -> None:
queue = None
parked = False
@@ -552,6 +677,7 @@ class LlamaAdmissionQueue:
"_unpark_seq",
"_committed",
"_budget",
+ "_reparking",
)
def __init__(self, key: str):
@@ -576,6 +702,9 @@ class LlamaAdmissionQueue:
# 0 budget disables the check, which is what every pre-existing caller gets.
self._committed = 0
self._budget = 0
+ # Holders that gave their commitment back and are waiting to take a bigger one.
+ # They still hold a slot, so they are not in _waiters. See yield_commitment.
+ self._reparking = 0
def _resize_pool_locked(self, capacity: int) -> None:
# Slots past a shrunk capacity retire when their holder releases them.
@@ -667,7 +796,11 @@ class LlamaAdmissionQueue:
# cache that no longer exists.
self._budget = max(0, int(budget or 0))
self._grant_waiters_locked()
- if not self._waiters:
+ # A pending repark closes the fast path like a non-empty wait line: the
+ # reparker gave its room back to ask for more, so an arrival admitted here
+ # would take exactly that, pinning a growing conversation at its opening size
+ # for as long as traffic lasts.
+ if not self._waiters and self._reparking == 0:
slot = self._take_slot_locked(len(self._unpark_tickets), cost)
if slot is not None:
# No snapshot here: callers read it through snapshot_now(),
@@ -717,6 +850,89 @@ class LlamaAdmissionQueue:
self._committed = max(0, self._committed - max(0, int(tokens or 0)))
self._grant_waiters_locked()
+ def try_recost(self, tokens_from: int, tokens_to: int) -> bool:
+ """Move a live commitment to a new size. False leaves it exactly as it was.
+
+ A tool loop's cost is unknown at admission: each round appends its results and
+ re-sends the conversation, so a run that opened small can grow into the cache
+ while its commitment stays at the opening estimate. #9392 closed that by
+ reserving the whole cache for any tool loop, which serialises every tool chat;
+ this is the re-costing that PR named as the alternative.
+
+ Never blocks and never overcommits, so it is safe to call from inside a
+ generator: growth that does not fit is refused and the caller keeps what it
+ holds, rather than waiting on holders that may be waiting on it.
+ """
+ tokens_from = max(0, int(tokens_from or 0))
+ tokens_to = max(0, int(tokens_to or 0))
+ with self._lock:
+ if self._budget <= 0:
+ return True
+ if tokens_to <= tokens_from:
+ # Shrinking always applies, and may let a waiter in.
+ self._committed = max(0, self._committed - (tokens_from - tokens_to))
+ self._grant_waiters_locked()
+ return True
+ delta = tokens_to - tokens_from
+ # The escape admission uses: a holder that is alone goes past the budget,
+ # since refusing it stalls a conversation nothing else can unblock.
+ alone = (self._committed - tokens_from) <= 0
+ if alone or self._committed + delta <= self._budget:
+ self._committed += delta
+ return True
+ return False
+
+ def yield_commitment(self, tokens: int) -> None:
+ """Hand a live commitment back before asking for a bigger one.
+
+ Half of ``LlamaAdmissionLease.recost_waiting``. Unconditional by design: a holder
+ that blocked while still holding its old commitment would be waiting on holders
+ waiting on it -- four runs at a quarter of the cache each, all wanting half, never
+ resolve. Letting go first cannot deadlock, since ``_committed`` strictly falls.
+
+ The caller counts as reparking until it reclaims, so a new arrival cannot take the
+ room it just released: an in-flight conversation beats one that has not started.
+ """
+ with self._lock:
+ self._committed = max(0, self._committed - max(0, int(tokens or 0)))
+ self._reparking += 1
+ self._grant_waiters_locked()
+
+ def try_reclaim_commitment(self, tokens: int) -> bool:
+ """The other half: take a commitment of ``tokens``, or report that it does not fit.
+
+ Test and commit under one lock, so only one caller can win the ``_committed == 0``
+ escape. Otherwise four reparkers racing an empty cache each see zero and each
+ admit themselves.
+ """
+ want = max(0, int(tokens or 0))
+ with self._lock:
+ if self._budget > 0 and not self._fits_budget_locked(want):
+ return False
+ self._committed += want
+ self._reparking = max(0, self._reparking - 1)
+ # The decrement above may have dropped the LAST repark barrier, and nothing
+ # else re-runs the grant: a release arriving during the repark already found
+ # the barrier up and returned. Without this, a reclaim that leaves room and a
+ # free slot strands the wait line until the grown run releases, and a queued
+ # waiter also closes reserve()'s fast path for every later arrival.
+ self._grant_waiters_locked()
+ return True
+
+ def abandon_repark(self, restore: int = 0) -> None:
+ """Stop counting a reparker that gave up, and re-commit what it takes back.
+
+ One lock for both. ``restore`` is what ``yield_commitment`` handed back and the
+ lease still occupies at llama-server, so it is re-committed UNCONDITIONALLY: a
+ correction, not a request for room. In two steps the wait line reopened on room
+ the lease was about to take back; through ``try_recost`` a full cache could refuse
+ it, after which release() subtracted a commitment that was never restored.
+ """
+ with self._lock:
+ self._reparking = max(0, self._reparking - 1)
+ self._committed += max(0, int(restore or 0))
+ self._grant_waiters_locked()
+
def try_park(self, slot: Optional[int]) -> bool:
"""Return a parked holder's slot to the pool. See ``LlamaAdmissionLease.park``.
@@ -815,6 +1031,11 @@ class LlamaAdmissionQueue:
return self._in_use == 0 and not self._waiters and not self._parked
def _grant_waiters_locked(self) -> None:
+ # A reparker gave its commitment back mid-conversation, so it takes the room ahead
+ # of anything not yet started. Without this a steady arrival rate can hold a
+ # growing run at its old size indefinitely.
+ if self._reparking > 0:
+ return
# Dead waiters are skipped as they are popped, so no prune is needed here.
# The head's own cost is what is tested, not a zero: granting past a large
# waiter whenever a small one fits would starve it for as long as traffic
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index d13dd696ebb..f3f08cd23e0 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -4203,6 +4203,34 @@ def _paravirtual_mmproj_pinnable(server_caps: Mapping[str, object]) -> bool:
)
+def _idle_slot_clearing_active(cmd: Sequence[str], *, supports_cache_ram: bool) -> bool:
+ """True when *cmd* leaves llama-server clearing idle slots' KV.
+
+ ``--cache-idle-slots`` defaults ON but requires cache-ram, and ``--cache-ram 0``
+ force-disables it (``server-context.cpp``). So the starting point is the BINARY, not
+ the command line: a server old enough to lack ``--cache-ram`` never had idle-slot
+ clearing either, while a server that has it clears by default at 8192 MiB. An absent
+ flag means that default is in force, not that clearing is off -- the common case,
+ since Studio only emits ``--cache-ram`` when something asked it to.
+
+ Last-wins, matching llama.cpp's own argument handling.
+ """
+ enabled = bool(supports_cache_ram)
+ for i, arg in enumerate(cmd):
+ if arg == "--cache-ram":
+ # A missing or unreadable value reads as no clearing, not as the default: the
+ # conservative answer costs a re-cost, the other hands out resident cells.
+ try:
+ enabled = int(cmd[i + 1]) > 0
+ except (IndexError, TypeError, ValueError):
+ enabled = False
+ elif arg == "--cache-idle-slots":
+ enabled = True
+ elif arg == "--no-cache-idle-slots":
+ enabled = False
+ return enabled
+
+
def _mmproj_env_is_audio_only(path: Optional[str]) -> bool:
"""True only when *path* names a readable projector with no vision tower.
@@ -5667,6 +5695,7 @@ class LlamaCppBackend:
self._requested_spec_draft_cache_type: Optional[str] = None
self._requested_ctx_checkpoints: Optional[int] = None
self._requested_cache_ram: Optional[int] = None
+ self._idle_slot_clearing_active: bool = False
self._chat_template: Optional[str] = None
self._markup_tokens: list = []
self._markup_profile = None
@@ -6117,6 +6146,17 @@ class LlamaCppBackend:
"""--cache-ram (MiB) the last load asked for; None means the default 8192."""
return self._requested_cache_ram
+ @property
+ def idle_slot_clearing_active(self) -> bool:
+ """Whether an idle slot's KV cells actually come back on this server.
+
+ Under ``--kv-unified`` an idle slot keeps its cells until ``prompt_clear()``,
+ which llama-server runs only under ``--cache-idle-slots``. False means releasing
+ a slot frees nothing, so nothing may be handed to another caller on the strength
+ of it. False until a load has spawned, which is the safe answer.
+ """
+ return self._idle_slot_clearing_active
+
@property
def max_context_length(self) -> Optional[int]:
"""Return the largest context that fits on this hardware at load time.
@@ -6150,6 +6190,7 @@ class LlamaCppBackend:
self._requested_spec_draft_cache_type = None
self._requested_ctx_checkpoints = None
self._requested_cache_ram = None
+ self._idle_slot_clearing_active = False
@staticmethod
def _read_rss_bytes(pid: int) -> Optional[int]:
@@ -13171,6 +13212,7 @@ class LlamaCppBackend:
self._requested_spec_draft_cache_type = None
self._requested_ctx_checkpoints = None
self._requested_cache_ram = None
+ self._idle_slot_clearing_active = False
self._flash_attn_enabled = True
self._effective_cache_types = ("f16", "f16")
self._requested_cache_types = ("f16", "f16")
@@ -22331,6 +22373,12 @@ class LlamaCppBackend:
logger.debug(f"Could not open llama-server log file: {e}")
self._llama_log_path = None
_last_spawn_cmd = list(run_cmd)
+ # Read off the argv actually spawned rather than the intent, so
+ # every emitter is covered by construction.
+ self._idle_slot_clearing_active = _idle_slot_clearing_active(
+ run_cmd,
+ supports_cache_ram = bool(server_caps.get("supports_cache_ram")),
+ )
self._process = subprocess.Popen(
run_cmd,
stdout = subprocess.PIPE,
@@ -27491,6 +27539,14 @@ class LlamaCppBackend:
context_policy: Optional[str] = None,
compaction_headroom_ratio: Optional[float] = None,
tool_choice: Any = None,
+ # Appended, never inserted: no bare `*` here, so every parameter is
+ # positional-or-keyword and inserting one rebinds later positional arguments.
+ #
+ # Called at the top of every round with the conversation as it now stands, so KV
+ # admission can charge what this run occupies rather than its opening estimate.
+ # MAY BLOCK: recost_waiting waits for cache room. Safe at the top of a round,
+ # where the previous round's request has completed.
+ on_conversation_grew: Optional[Callable[[list], None]] = None,
) -> Generator[dict, None, None]:
"""
Agentic loop: let the model call tools, execute them, and continue.
@@ -27966,6 +28022,13 @@ class LlamaCppBackend:
iteration = -1
while True:
iteration += 1
+ # Here rather than at each append: six sites grow the conversation and all of
+ # them pass through this one point before the cache must hold the result.
+ if on_conversation_grew is not None:
+ try:
+ on_conversation_grew(conversation)
+ except Exception: # accounting must never break a run in progress
+ logger.debug("tool loop recost failed", exc_info = True)
if iteration >= max_tool_iterations + _extra + _continuation_credits:
break
if cancel_event is not None and cancel_event.is_set():
@@ -30613,6 +30676,18 @@ class LlamaCppBackend:
except Exception as exc:
logger.warning("Could not preflight the rolling context window: %s", exc)
+ # The loop's callback fires at the TOP of a round, so the breaks leading here (the
+ # tool-iteration cap, a controller turning tools off) leave the assistant turn,
+ # its tool results and any nudge appended after the last re-cost -- making this
+ # final pass the largest request of the run and the one the pool never heard
+ # about. Here rather than at the breaks: the recall above can rebind
+ # `conversation`, and every path reaches this point with the list about to be sent.
+ if on_conversation_grew is not None:
+ try:
+ on_conversation_grew(conversation)
+ except Exception: # accounting must never break a run in progress
+ logger.debug("tool loop final recost failed", exc_info = True)
+
stream_payload = {
"messages": neutralize_control_markup_in_messages(
conversation, None, self.markup_profile
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 6111e0fc211..b56742c11b7 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1646,6 +1646,18 @@ def _openai_llama_admission_budget(llama_backend) -> Optional[int]:
return total or _positive_int_or_none(getattr(llama_backend, "context_length", None))
+def _openai_llama_admission_can_yield(llama_backend) -> bool:
+ """Whether a round between generations may hand its commitment back.
+
+ Only where llama-server actually clears an idle slot's KV. Under ``--kv-unified``
+ without ``--cache-idle-slots`` a finished round's cells stay resident, so yielding
+ would promise the same capacity twice. Studio launches exactly that way on Windows
+ under full GPU offload (``--cache-ram 0``, #5692); there re-costing declines instead
+ of waiting. A backend that cannot say (no load yet, or a stub) reads as False.
+ """
+ return bool(getattr(llama_backend, "idle_slot_clearing_active", False))
+
+
def _openai_llama_admission_extra_prompt_tokens(payload) -> int:
"""Prompt the request carries OUTSIDE ``messages``, in tokens.
@@ -1830,6 +1842,30 @@ def _openai_llama_admission_media_tokens(
return extra
+def _openai_llama_admission_injected_tool_tokens(injected_tools) -> int:
+ """The tool catalogue Unsloth adds itself, in tokens.
+
+ ``payload.tools`` is what the CLIENT sent, and for Unsloth's own tool loop that is
+ usually nothing: Web Search and the rest resolve server-side and render into the
+ prompt after admission has priced the request. Measured on Qwen3.5-4B-MTP-GGUF, the
+ same user turn is 1716 prompt tokens with tools off and 2969 with them on, so the
+ catalogue is around 1250 tokens the message list cannot see.
+
+ Leaving it out is not a rounding error: at ``-c 4096`` four requests priced at an
+ equal share were all admitted and llama.cpp answered every one with ``Context size
+ has been exceeded``.
+ """
+ if not injected_tools:
+ return 0
+ try:
+ text = json.dumps(injected_tools, default = str)
+ except Exception:
+ return 0
+ if not text:
+ return 0
+ return estimate_messages_tokens_dense([{"role": "system", "content": text}])
+
+
def _openai_llama_admission_tokens(
payload,
*,
@@ -1837,6 +1873,7 @@ def _openai_llama_admission_tokens(
capacity: int,
tool_loop: bool = False,
image_tokens: int = _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS,
+ injected_tools = None,
) -> Optional[int]:
"""KV a request will occupy: what is sent, plus what it may generate.
@@ -1858,6 +1895,7 @@ def _openai_llama_admission_tokens(
)
prompt_tokens = estimate_messages_tokens_dense(estimate_messages)
prompt_tokens += _openai_llama_admission_extra_prompt_tokens(payload)
+ prompt_tokens += _openai_llama_admission_injected_tool_tokens(injected_tools)
prompt_tokens += _openai_llama_admission_media_tokens(
payload,
message_image_parts = message_image_parts,
@@ -1888,23 +1926,35 @@ def _openai_llama_admission_tokens(
output_tokens = max(0, budget - prompt_tokens)
else:
output_tokens = cap
- # A tool loop reserves the whole cache. One lease covers up to 25 rounds, and each
- # round appends its tool results and re-sends the conversation, so a request that
- # starts small can approach the full window while its commitment stays at the
- # opening estimate. Re-costing per round would mean threading a callback through the
- # generator; reserving the upper bound is the same guarantee without that surface,
- # at the price of serialising concurrent tool requests. That price is real, and it
- # is the one this accounting exists to charge: the alternative is admitting rounds
- # the cache cannot hold and letting llama.cpp kill both.
+ # A tool loop opens at its own estimate with an equal share as the floor, and re-costs
+ # as it grows (generate_chat_completion_with_tools on_conversation_grew ->
+ # lease.recost_waiting). The floor keeps re-costing rare: under its share a run never
+ # calls the queue at all.
+ #
+ # #9392 reserved the WHOLE cache here instead, closing the same growth without a
+ # callback "at the price of serialising concurrent tool requests". That price is not
+ # payable: any lit pill sets enable_tools, so every tool chat ran alone. Measured on a
+ # 262144 cache, four tool chats went one at a time at 0.1/2.8/4.6/8.8s to first token;
+ # with this they start together. It also scaled the wrong way: #9392's own failure was
+ # a 2048-token cache where 565 + 1485 overflowed, so reserving all of that cost a
+ # request that could not have run anyway, while reserving all of 262144 costs three
+ # that comfortably could.
#
# Keyed on the resolved execution path, NOT on payload.tools. The loop opens on
# `enable_tools`, `mcp_enabled`, the CLI --enable-tools policy or a checkpoint
# repair, none of which need a client `tools` array, so keying on the array
# undercharged Unsloth's own tool traffic; and a passthrough or /responses request
- # that merely forwards `tools` to llama-server runs ONE generation per HTTP call,
- # so charging it the whole cache serialised the client-driven loop for nothing.
+ # that merely forwards `tools` to llama-server runs ONE generation per HTTP call.
if tool_loop:
- return budget
+ # Exactly what the same request without tools is charged, floored at an equal
+ # share. A tool loop is a special case at ROUND time, not at admission time.
+ #
+ # Not clamped to the share: charging less than prompt + output reopens what #9392
+ # closed, since a first round may generate its whole output allowance before any
+ # re-cost runs. The floor only helps a SMALL request, the one that would otherwise
+ # re-cost on its very first round.
+ share = max(1, budget // max(1, capacity))
+ return max(1, min(budget, max(share, prompt_tokens + output_tokens)))
# Clamped to the budget so an oversized request stays schedulable: the queue
# admits it alone rather than stranding it, and llama-server refuses it with a
# message naming both counts.
@@ -1917,6 +1967,7 @@ def _openai_llama_admission_reserve(
llama_backend,
payload = None,
tool_loop: bool = False,
+ injected_tools = None,
) -> tuple[LlamaAdmissionReservation, LlamaAdmissionConfig]:
config = llama_admission_config_from_env()
capacity = _openai_llama_admission_capacity(request, llama_backend)
@@ -1932,6 +1983,7 @@ def _openai_llama_admission_reserve(
capacity = capacity,
tool_loop = tool_loop,
image_tokens = _openai_llama_admission_image_tokens(llama_backend),
+ injected_tools = injected_tools,
)
if payload is not None
else None,
@@ -1939,6 +1991,80 @@ def _openai_llama_admission_reserve(
return reservation, config
+def _openai_llama_admission_recost(
+ reservation,
+ conversation,
+ *,
+ request: Optional[Request],
+ llama_backend,
+ payload = None,
+ output_tokens: Optional[int] = None,
+ cancel_event = None,
+ injected_tools = None,
+) -> None:
+ """Charge a tool loop for what its conversation now is, not what it opened as.
+
+ #9392 avoided this by reserving the whole cache for any tool run, serialising every
+ tool chat. Called at the top of each round, this keeps the commitment honest as the
+ conversation grows, so the opening reservation can be an ordinary estimate and four
+ tool chats can decode at once.
+
+ Growth that does not fit WAITS here rather than proceeding uncharged: four loops that
+ open at a share each and grow past it together draw one ``Context size has been
+ exceeded`` that kills every decoding slot. ``recost_waiting`` yields the old
+ commitment first, so a waiting round is not holding the room it waits for.
+
+ Safe to wait here because it is between rounds and the slot is idle at llama-server.
+ Idle is not reclaimed, though, so the yield is gated on
+ ``_openai_llama_admission_can_yield``; where it is False this declines instead.
+ """
+ if reservation is None:
+ return
+ try:
+ lease = reservation.lease_nowait()
+ if lease is None:
+ return
+ budget = _openai_llama_admission_budget(llama_backend)
+ if not budget:
+ return
+ capacity = _openai_llama_admission_capacity(request, llama_backend)
+ # Every term the OPENING reservation charges, charged again here. Counting fewer
+ # things than the reservation it replaces would SHRINK a correctly sized lease --
+ # and since the callback fires at the top of round zero, before any growth, it
+ # would hand back room llama-server is already using.
+ estimate_messages, message_image_parts = _openai_llama_admission_messages_for_estimate(
+ conversation
+ )
+ prompt_tokens = estimate_messages_tokens_dense(estimate_messages)
+ # Re-sent every round, so it belongs in every re-costing, not just the opening one.
+ prompt_tokens += _openai_llama_admission_injected_tool_tokens(injected_tools)
+ # Anthropic keeps `system` and `tools` out of the message list entirely, so for
+ # that route this is most of the prompt.
+ prompt_tokens += _openai_llama_admission_extra_prompt_tokens(payload)
+ # mtmd embeddings, KV the message text cannot show: image parts compact to
+ # "[image]" for the text estimate, so their real cost comes from the compaction
+ # count. A screenshot tool adds more of them, so this grows with the rounds.
+ prompt_tokens += _openai_llama_admission_media_tokens(
+ payload,
+ message_image_parts = message_image_parts,
+ image_tokens = _openai_llama_admission_image_tokens(llama_backend),
+ )
+ if output_tokens is None:
+ # No cap named, so generation is bounded only by the window, as the opening
+ # estimate assumes. Charging zero here dropped an uncapped loop to its share
+ # on round zero while its generations could still fill most of the cache.
+ output_tokens = max(0, budget - prompt_tokens)
+ share = max(1, budget // max(1, capacity))
+ want = max(1, min(budget, max(share, prompt_tokens + max(0, output_tokens))))
+ lease.recost_waiting(
+ want,
+ cancel_event = cancel_event,
+ allow_yield = _openai_llama_admission_can_yield(llama_backend),
+ )
+ except Exception: # pragma: no cover - accounting must not break a live run
+ logger.debug("llama admission recost failed", exc_info = True)
+
+
def _openai_admission_request_path(request: Optional[Request]) -> Optional[str]:
try:
return str(request.url.path) if request is not None else None
@@ -20410,6 +20536,30 @@ async def produce_openai_chat_completions(
_gguf_auto_heal_tool_calls = (
payload.auto_heal_tool_calls if payload.auto_heal_tool_calls is not None else True
)
+ # Filled once admission returns. The generator below is BUILT before the
+ # reservation exists but not ITERATED until after, so the callback always sees
+ # a reservation by the time a round can call it.
+ _gguf_admission_hold: dict = {"reservation": None}
+
+ def _gguf_recost(conversation) -> None:
+ _openai_llama_admission_recost(
+ _gguf_admission_hold["reservation"],
+ conversation,
+ request = request,
+ llama_backend = llama_backend,
+ # The payload the opening reservation was priced from, so a round is
+ # charged for its media and non-message prompt too.
+ payload = payload,
+ # NOT `or 0`. None means no cap was named, which the reservation
+ # prices as the rest of the budget; zero would re-cost an uncapped
+ # loop down to its share on its very first round.
+ output_tokens = effective_max_tokens,
+ injected_tools = tools_to_use,
+ # A round waiting for cache room must still answer Stop. Same event
+ # the loop polls each iteration, so a wait ends where a cancel would.
+ cancel_event = cancel_event,
+ )
+
# Active tool names gating the bare-rehearsal strip, matching the loop gate.
_gguf_display_tool_names = _display_tool_name_gate(tools_to_use)
@@ -20472,6 +20622,7 @@ async def produce_openai_chat_completions(
bypass_permissions = bool(payload.bypass_permissions),
permission_mode = payload.permission_mode,
perf_callback = _gguf_perf_callback,
+ on_conversation_grew = _gguf_recost,
context_overflow = _rolling_context_policy(payload),
context_policy = _request_context_policy(payload),
compaction_headroom_ratio = _request_compaction_headroom_ratio(payload),
@@ -20483,11 +20634,18 @@ async def produce_openai_chat_completions(
request = request,
llama_backend = llama_backend,
payload = payload,
+ # The catalogue Unsloth resolves server-side: payload.tools does not
+ # carry it and it is roughly 1250 prompt tokens.
+ injected_tools = tools_to_use,
# This branch IS the resolved server-side loop (use_tools is true
# here whether it came from tools, enable_tools, mcp_enabled, the
- # CLI policy or a checkpoint repair), so charge the upper bound.
+ # CLI policy or a checkpoint repair), so it opens at an equal share
+ # and re-costs per round through _gguf_recost.
tool_loop = True,
)
+ # Hand the rounds their reservation now it exists; no round can have run
+ # before this, since the generator is not iterated until admission returns.
+ _gguf_admission_hold["reservation"] = reservation
except LlamaAdmissionQueueFull as exc:
_llama_admission_log(
"queue-full",
@@ -27729,6 +27887,26 @@ async def anthropic_messages(
else:
reservation.cancel()
+ # Same shape as the chat route's _gguf_admission_hold: filled once admission returns,
+ # read from inside the tool loop. This path runs the identical 25-round loop against
+ # the identical cache, so without it an Anthropic tool run would keep its opening
+ # estimate for the whole run.
+ _anthropic_admission_hold: dict = {"reservation": None}
+
+ def _anthropic_recost(conversation) -> None:
+ _openai_llama_admission_recost(
+ _anthropic_admission_hold["reservation"],
+ conversation,
+ request = request,
+ llama_backend = llama_backend,
+ # `system` and `tools` live outside `messages` here, so without the payload a
+ # re-cost drops most of the prompt it is meant to charge.
+ payload = payload,
+ output_tokens = payload.max_tokens,
+ injected_tools = openai_tools,
+ cancel_event = cancel_event,
+ )
+
async def _admitted_anthropic(coro, *, tool_loop: bool = False):
try:
reservation, admission_config = _openai_llama_admission_reserve(
@@ -27736,7 +27914,11 @@ async def anthropic_messages(
llama_backend = llama_backend,
payload = payload,
tool_loop = tool_loop,
+ # Only the tool branch resolves a catalogue; the plain branch sends none.
+ injected_tools = openai_tools if tool_loop else None,
)
+ if tool_loop:
+ _anthropic_admission_hold["reservation"] = reservation
except LlamaAdmissionQueueFull as exc:
coro.close()
api_monitor.fail(monitor_id, str(exc))
@@ -27991,6 +28173,7 @@ async def anthropic_messages(
stop = stop,
cancel_event = cancel_event,
max_tool_iterations = 25,
+ on_conversation_grew = _anthropic_recost,
auto_heal_tool_calls = True,
nudge_tool_calls = payload.nudge_tool_calls,
tool_choice = server_tool_choice,
diff --git a/studio/backend/tests/test_idle_slot_clearing_is_known.py b/studio/backend/tests/test_idle_slot_clearing_is_known.py
new file mode 100644
index 00000000000..a3a4484bf83
--- /dev/null
+++ b/studio/backend/tests/test_idle_slot_clearing_is_known.py
@@ -0,0 +1,95 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Whether a released slot's KV cells actually come back.
+
+Re-costing a growing tool loop yields its old commitment before asking for a bigger one,
+which is only capacity if llama-server clears the idle slot. Under ``--kv-unified`` it
+clears only with ``--cache-idle-slots``, which requires cache-ram and which
+``--cache-ram 0`` force-disables. Studio emits ``--cache-ram 0`` on Windows under full
+GPU offload (#5692) alongside ``--kv-unified``, so this is a live configuration.
+
+Read off the argv actually spawned, so every emitter is covered by construction.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from core.inference.llama_cpp import _idle_slot_clearing_active as active
+from routes.inference import _openai_llama_admission_can_yield as can_yield
+
+
+BASE = ["llama-server", "-m", "model.gguf", "--parallel", "4", "--kv-unified"]
+
+
+class TestTheArgvIsWhatDecides:
+ def test_a_modern_binary_clears_by_default(self):
+ """--cache-ram defaults to 8192 MiB and Studio rarely emits the flag, so an
+ absent flag is the common case and means ON."""
+ assert active(BASE, supports_cache_ram = True) is True
+
+ def test_a_binary_without_cache_ram_never_clears(self):
+ """It predates the feature, and Studio skips the flag rather than failing the
+ launch, so the argv looks identical to the default case."""
+ assert active(BASE, supports_cache_ram = False) is False
+
+ def test_windows_full_offload_does_not_clear(self):
+ """The #5692 path: --cache-ram 0 force-disables --cache-idle-slots."""
+ assert active(BASE + ["--cache-ram", "0"], supports_cache_ram = True) is False
+
+ def test_an_explicit_cache_ram_clears(self):
+ assert active(BASE + ["--cache-ram", "4096"], supports_cache_ram = True) is True
+
+ def test_the_flag_can_be_turned_off_by_name(self):
+ assert (
+ active(
+ BASE + ["--cache-ram", "4096", "--no-cache-idle-slots"],
+ supports_cache_ram = True,
+ )
+ is False
+ )
+
+ def test_it_can_be_turned_back_on_by_name(self):
+ assert (
+ active(BASE + ["--cache-ram", "0", "--cache-idle-slots"], supports_cache_ram = True)
+ is True
+ )
+
+ def test_last_wins_like_llama_cpp(self):
+ assert (
+ active(BASE + ["--cache-ram", "4096", "--cache-ram", "0"], supports_cache_ram = True)
+ is False
+ )
+ assert (
+ active(BASE + ["--cache-ram", "0", "--cache-ram", "4096"], supports_cache_ram = True)
+ is True
+ )
+
+ @pytest.mark.parametrize("bad", ["", "abc", "-1", None])
+ def test_an_unreadable_value_is_treated_as_no_clearing(self, bad):
+ cmd = BASE + ["--cache-ram"] + ([] if bad is None else [bad])
+ assert active(cmd, supports_cache_ram = True) is False
+
+ def test_a_trailing_flag_does_not_raise(self):
+ assert active(BASE + ["--cache-ram"], supports_cache_ram = True) is False
+
+
+class _Backend:
+ def __init__(self, value):
+ if value is not None:
+ self.idle_slot_clearing_active = value
+
+
+class TestTheRouteAsksTheBackend:
+ def test_it_yields_when_the_server_clears(self):
+ assert can_yield(_Backend(True)) is True
+
+ def test_it_does_not_yield_when_the_server_does_not(self):
+ assert can_yield(_Backend(False)) is False
+
+ def test_a_backend_that_cannot_say_does_not_yield(self):
+ """No load yet, a stub, or an older backend object. Declining is safe;
+ promising the same cells twice is not."""
+ assert can_yield(_Backend(None)) is False
+ assert can_yield(None) is False
diff --git a/studio/backend/tests/test_llama_admission_compat_matrix.py b/studio/backend/tests/test_llama_admission_compat_matrix.py
new file mode 100644
index 00000000000..3db55e1f44e
--- /dev/null
+++ b/studio/backend/tests/test_llama_admission_compat_matrix.py
@@ -0,0 +1,370 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Every backend shape this accounting can be handed, and every old caller of it.
+
+Re-costing changes how a tool loop is admitted, so every install that does NOT get the new
+path must behave exactly as it did. Budget and slot count are both derived from the loaded
+backend, and that derivation differs per platform and per device:
+
+ * ``capacity`` is ``effective_parallel_slots``, reduced to fit VRAM and forced to 1 on a
+ CPU-only or small-VRAM load. A 1-slot backend must be untouched by this change.
+ * ``budget`` is ``_kv_cache_context_total``: ``n_ctx`` under ``--kv-unified``,
+ ``n_ctx * slots`` without it, None when the context length cannot be read back from
+ ``/props``. None means slot-only admission, the pre-#9392 behaviour.
+
+The matrix below is the real portability surface, not a stand-in for other operating
+systems: the code added here is stdlib threading and ``time.monotonic`` with no
+OS-specific branch, and what varies per platform is which of these numbers arrives.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from core.inference.llama_admission import (
+ DEFAULT_RECOST_WAIT_TIMEOUT_S,
+ LlamaAdmissionConfig,
+ LlamaAdmissionQueue,
+)
+
+
+def _tokens(payload, *, budget, capacity, tool_loop):
+ import routes.inference as routes_inference
+ return routes_inference._openai_llama_admission_tokens(
+ payload,
+ budget = budget,
+ capacity = capacity,
+ tool_loop = tool_loop,
+ )
+
+
+def _payload(
+ *,
+ max_tokens = 128,
+ tools = True,
+ text = "hi",
+):
+ return SimpleNamespace(
+ messages = [{"role": "user", "content": text}],
+ max_tokens = max_tokens,
+ enable_tools = tools,
+ tools = None,
+ )
+
+
+def _lease(
+ queue,
+ *,
+ tokens,
+ budget,
+ capacity = 4,
+ config = None,
+):
+ reservation = queue.reserve(
+ capacity = capacity,
+ config = config or LlamaAdmissionConfig(),
+ tokens = tokens,
+ budget = budget,
+ )
+ return reservation.lease_nowait()
+
+
+# (label, slots, n_ctx, kv_unified) -- the shapes a real load actually produces.
+BACKENDS = [
+ ("cpu-only, 1 slot", 1, 4096, True),
+ ("small vram, downshifted", 1, 8192, True),
+ ("2 slots unified", 2, 8192, True),
+ ("4 slots unified", 4, 4096, True),
+ ("8 slots unified", 8, 262144, True),
+ ("4 slots NOT unified", 4, 4096, False),
+ ("2 slots NOT unified", 2, 8192, False),
+]
+
+
+def _budget(n_ctx, slots, kv_unified):
+ """Mirrors _reconcile_effective_ctx_with_server: unified reports one shared cache,
+ non-unified reports the aggregate across per-slot windows."""
+ return n_ctx * (1 if kv_unified else slots)
+
+
[email protected]("label,slots,n_ctx,kv_unified", BACKENDS)
+def test_a_tool_loop_is_never_charged_more_than_the_cache(label, slots, n_ctx, kv_unified):
+ budget = _budget(n_ctx, slots, kv_unified)
+ cost = _tokens(_payload(), budget = budget, capacity = slots, tool_loop = True)
+ assert 1 <= cost <= budget, f"{label}: charged {cost} against a {budget} cache"
+
+
[email protected]("label,slots,n_ctx,kv_unified", BACKENDS)
+def test_a_single_slot_backend_behaves_as_it_always_did(label, slots, n_ctx, kv_unified):
+ """capacity 1 means share == budget, so a tool loop is charged the whole cache just as
+ #9392 charged it. The common shape on CPU-only and on a VRAM-downshifted load."""
+ if slots != 1:
+ pytest.skip("covered by the multi-slot cases")
+ budget = _budget(n_ctx, slots, kv_unified)
+ assert _tokens(_payload(), budget = budget, capacity = 1, tool_loop = True) == budget
+
+
[email protected]("label,slots,n_ctx,kv_unified", BACKENDS)
+async def test_the_slots_a_backend_reports_can_all_be_filled(label, slots, n_ctx, kv_unified):
+ """On any multi-slot backend, ordinary tool chats fill the slots the backend
+ advertises rather than running one at a time."""
+ budget = _budget(n_ctx, slots, kv_unified)
+ cost = _tokens(_payload(), budget = budget, capacity = slots, tool_loop = True)
+ queue = LlamaAdmissionQueue(label)
+ admitted = [_lease(queue, tokens = cost, budget = budget, capacity = slots) for _ in range(slots)]
+ assert all(
+ lease is not None for lease in admitted
+ ), f"{label}: only {sum(l is not None for l in admitted)}/{slots} slots usable"
+ assert queue.snapshot().committed <= budget
+
+
[email protected]("label,slots,n_ctx,kv_unified", BACKENDS)
+def test_max_tokens_on_max_is_not_treated_as_a_promise_to_use_it(label, slots, n_ctx, kv_unified):
+ """The UI sends max_tokens = context_length for "Max", which serialises with or
+ without tools alike. Fixing that is a separate change; what matters here is that tools
+ are not charged MORE than no-tools for the same request."""
+ budget = _budget(n_ctx, slots, kv_unified)
+ payload = _payload(max_tokens = n_ctx)
+ with_tools = _tokens(payload, budget = budget, capacity = slots, tool_loop = True)
+ without = _tokens(payload, budget = budget, capacity = slots, tool_loop = False)
+ assert with_tools <= max(
+ without, budget // max(1, slots)
+ ), f"{label}: tools charged {with_tools} vs {without} without"
+
+
+class TestNothingChangesWhenTheBudgetIsUnknown:
+ """``budget`` is None when the context length cannot be read back: the pre-#9392
+ slot-only path, which has to stay bit-for-bit what it was."""
+
+ def test_no_budget_means_no_token_cost_at_all(self):
+ for tool_loop in (True, False):
+ assert _tokens(_payload(), budget = None, capacity = 4, tool_loop = tool_loop) is None
+ assert _tokens(_payload(), budget = 0, capacity = 4, tool_loop = tool_loop) is None
+
+ @pytest.mark.asyncio
+ async def test_slot_only_admission_still_fills_every_slot(self):
+ queue = LlamaAdmissionQueue("no-budget")
+ leases = [
+ queue.reserve(capacity = 4, config = LlamaAdmissionConfig()).lease_nowait()
+ for _ in range(4)
+ ]
+ assert all(lease is not None for lease in leases)
+
+ @pytest.mark.asyncio
+ async def test_recost_waiting_is_a_no_op_without_a_budget(self):
+ """It must not block, and must not invent a commitment out of nothing."""
+ queue = LlamaAdmissionQueue("no-budget")
+ lease = queue.reserve(capacity = 4, config = LlamaAdmissionConfig()).lease_nowait()
+ assert lease.recost_waiting(999999, timeout_s = 1.0) is True
+ assert queue.snapshot().committed == 0
+ assert queue._reparking == 0
+
+ @pytest.mark.asyncio
+ async def test_recost_waiting_is_a_no_op_when_admission_is_disabled(self):
+ """config.enabled False hands back a lease with no queue behind it."""
+ queue = LlamaAdmissionQueue("disabled")
+ lease = queue.reserve(capacity = 4, config = LlamaAdmissionConfig(enabled = False)).lease_nowait()
+ assert lease.recost_waiting(999999, timeout_s = 1.0) is True
+ lease.release()
+
+ @pytest.mark.asyncio
+ async def test_the_kv_budget_escape_hatch_still_overcommits(self):
+ """UNSLOTH_LLAMA_ADMISSION_KV_BUDGET=0, the documented way out for a backend whose
+ reported context length does not match the cache it allocated."""
+ queue = LlamaAdmissionQueue("escape")
+ config = LlamaAdmissionConfig(kv_budget = False)
+ first = _lease(queue, tokens = 1500, budget = 2048, config = config)
+ second = _lease(queue, tokens = 1500, budget = 2048, config = config)
+ assert first is not None and second is not None
+ assert first.recost_waiting(999999, timeout_s = 1.0) is True
+ assert queue._reparking == 0
+
+
+class TestOldCallers:
+ """Everything added is keyword-with-default, so code written before this still runs."""
+
+ @pytest.mark.asyncio
+ async def test_recost_waiting_without_any_new_keyword(self):
+ queue = LlamaAdmissionQueue("compat")
+ lease = _lease(queue, tokens = 100, budget = 4096)
+ assert lease.recost_waiting(200) is True
+ assert queue.snapshot().committed == 200
+
+ @pytest.mark.asyncio
+ async def test_the_old_non_blocking_recost_still_exists_and_still_declines(self):
+ """Callers that must not block keep the old contract: refuse, never wait."""
+ queue = LlamaAdmissionQueue("compat")
+ first = _lease(queue, tokens = 3000, budget = 4096)
+ second = _lease(queue, tokens = 1000, budget = 4096)
+ assert second.recost(4000) is False
+ assert queue.snapshot().committed == 4000
+ assert queue._reparking == 0, "the non-blocking path must never touch the wait line"
+
+ def test_the_route_recost_helper_accepts_no_cancel_event(self):
+ import routes.inference as routes_inference
+
+ # Reservation None is the "not admitted yet" case every call site can hit.
+ routes_inference._openai_llama_admission_recost(
+ None,
+ [{"role": "user", "content": "hi"}],
+ request = None,
+ llama_backend = SimpleNamespace(context_length = 4096),
+ )
+
+ def test_generate_chat_completion_with_tools_still_takes_no_hook(self):
+ import inspect
+
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ signature = inspect.signature(LlamaCppBackend.generate_chat_completion_with_tools)
+ parameter = signature.parameters["on_conversation_grew"]
+ assert parameter.default is None, "the hook must be optional for existing callers"
+
+ def test_the_hook_was_appended_rather_than_inserted(self):
+ """No bare ``*`` in this signature, so every parameter is positional-or-keyword and
+ inserting one silently rebinds the arguments after it for positional callers, with
+ no exception to report it."""
+ import inspect
+
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ names = list(
+ inspect.signature(LlamaCppBackend.generate_chat_completion_with_tools).parameters
+ )
+ assert (
+ names[-1] == "on_conversation_grew"
+ ), f"the hook must be last; signature ends {names[-3:]}"
+
+ def test_the_wait_timeout_has_a_sane_default(self):
+ assert DEFAULT_RECOST_WAIT_TIMEOUT_S > 0
+ import inspect
+
+ from core.inference.llama_admission import LlamaAdmissionLease
+
+ signature = inspect.signature(LlamaAdmissionLease.recost_waiting)
+ assert signature.parameters["timeout_s"].default == DEFAULT_RECOST_WAIT_TIMEOUT_S
+
+
+class TestNoPersistentStateChanged:
+ """An existing install upgrading into this must not need a migration."""
+
+ def test_no_new_environment_variable_is_required(self):
+ import os
+
+ from core.inference.llama_admission import llama_admission_config_from_env
+
+ # A completely bare environment must still produce a usable config.
+ saved = {k: v for k, v in os.environ.items() if k.startswith("UNSLOTH_")}
+ try:
+ for key in list(saved):
+ os.environ.pop(key, None)
+ config = llama_admission_config_from_env()
+ finally:
+ os.environ.update(saved)
+ assert config.enabled is True
+ assert config.kv_budget is True
+
+ def test_the_queue_carries_no_serialised_state(self):
+ """Nothing about a queue is written to disk, and the slots are the whole of its
+ state, so a new field cannot break an old install's stored data."""
+ assert "_reparking" in LlamaAdmissionQueue.__slots__
+ queue = LlamaAdmissionQueue("fresh")
+ assert queue._reparking == 0, "a fresh queue must start with the line open"
+
+
+class TestTheInjectedToolCatalogueIsCharged:
+ """The regression that a live run caught and every unit test missed.
+
+ ``payload.tools`` is what the CLIENT sent. Unsloth's own tool loop resolves Web Search
+ and the rest server-side and renders them into the prompt AFTER admission has priced
+ the request, so pricing from the payload alone undercounts by the whole catalogue.
+ Measured on Qwen3.5-4B-MTP-GGUF, the same user turn is 1716 prompt tokens with tools
+ off and 2969 with them on. At ``-c 4096`` that gap is fatal: priced at an equal share
+ four tool chats were all admitted and llama.cpp answered every one with ``Context size
+ has been exceeded``.
+ """
+
+ CATALOG = [
+ {
+ "type": "function",
+ "function": {
+ "name": f"tool_{i}",
+ "description": "A tool with a realistically wordy description. " * 12,
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string", "description": "What to look up. " * 8},
+ "count": {"type": "integer", "description": "How many. " * 8},
+ },
+ "required": ["query"],
+ },
+ },
+ }
+ for i in range(6)
+ ]
+
+ def test_the_catalogue_is_added_to_the_estimate(self):
+ """Checked on a wide pool, where the floor is small enough that the catalogue sets
+ the price. On a narrow one the floor already exceeds the whole request, so masking
+ it there is correct."""
+ import routes.inference as routes_inference
+
+ budget, capacity = 8192, 16 # share 512, smaller than the catalogue
+ payload = _payload(text = "hi")
+ without = _tokens(payload, budget = budget, capacity = capacity, tool_loop = True)
+ with_catalog = routes_inference._openai_llama_admission_tokens(
+ payload,
+ budget = budget,
+ capacity = capacity,
+ tool_loop = True,
+ injected_tools = self.CATALOG,
+ )
+ assert (
+ with_catalog > without
+ ), f"the catalogue must raise the price: {with_catalog} vs {without}"
+
+ def test_a_catalogue_of_a_realistic_size_is_not_rounded_away(self):
+ import routes.inference as routes_inference
+ charged = routes_inference._openai_llama_admission_injected_tool_tokens(self.CATALOG)
+ assert charged > 500, f"only {charged} tokens charged for a six-tool catalogue"
+
+ @pytest.mark.asyncio
+ async def test_four_tool_chats_are_not_admitted_past_a_small_cache(self):
+ """The live failure at unit level: four short prompts with a real catalogue cannot
+ share 4096 tokens, and admitting all four produced four 500s."""
+ import routes.inference as routes_inference
+
+ budget = 4096
+ cost = routes_inference._openai_llama_admission_tokens(
+ _payload(text = "hi"),
+ budget = budget,
+ capacity = 4,
+ tool_loop = True,
+ injected_tools = self.CATALOG,
+ )
+ queue = LlamaAdmissionQueue("catalog")
+ admitted = sum(
+ _lease(queue, tokens = cost, budget = budget, capacity = 4) is not None for _ in range(4)
+ )
+ assert (
+ queue.snapshot().committed <= budget
+ ), f"admitted {admitted} chats at {cost} each against a {budget} cache"
+
+ def test_no_catalogue_means_no_extra_charge(self):
+ """A request that injects nothing must be priced exactly as before."""
+ import routes.inference as routes_inference
+ for empty in (None, [], ()):
+ assert routes_inference._openai_llama_admission_injected_tool_tokens(empty) == 0
+
+ def test_an_unserialisable_catalogue_does_not_break_admission(self):
+ import routes.inference as routes_inference
+ class Awkward:
+ def __repr__(self):
+ raise RuntimeError("no")
+
+ # default=str still reaches __repr__, so this must be caught rather than raised.
+ assert routes_inference._openai_llama_admission_injected_tool_tokens([Awkward()]) >= 0
diff --git a/studio/backend/tests/test_llama_admission_kv_budget.py b/studio/backend/tests/test_llama_admission_kv_budget.py
index 90120134039..b4e18ad29e2 100644
--- a/studio/backend/tests/test_llama_admission_kv_budget.py
+++ b/studio/backend/tests/test_llama_admission_kv_budget.py
@@ -445,13 +445,21 @@ class TestTheWholeRenderedPromptIsCounted:
assert self._cost(payload) is not None
-class TestToolLoopsReserveTheirUpperBound:
+class TestToolLoopsOpenAtAShareAndGrow:
"""One lease covers up to 25 rounds, each larger than the last.
`generate_chat_completion_with_tools` appends every tool result and re-sends the
conversation, so a request that starts small can approach the full window while its
commitment stays at the opening estimate. Another request is then admitted against a
cache the active rounds have already grown into.
+
+ #9392 closed that by reserving the WHOLE cache for any tool loop, which made every
+ tool chat run alone: any lit pill sets ``enable_tools``. Measured on a 262144 cache,
+ four tool chats reached first token at 0.1s, 2.8s, 4.6s and 8.8s, one after another.
+
+ A tool loop now opens at an equal share and re-costs as it grows
+ (``on_conversation_grew`` -> ``lease.recost_waiting``), the alternative #9392 named:
+ the growth is charged when it happens instead of assumed up front.
"""
@staticmethod
@@ -469,10 +477,14 @@ class TestToolLoopsReserveTheirUpperBound:
tool_loop = tool_loop,
)
- def test_a_tool_request_reserves_the_whole_cache(self):
+ def test_a_tool_request_opens_at_an_equal_share(self):
"""Keyed on the resolved path, not on ``tools``: the loop also opens on
``enable_tools``, ``mcp_enabled``, the CLI policy and a checkpoint repair,
- none of which carry a client catalogue."""
+ none of which carry a client catalogue.
+
+ The share is a FLOOR, not a cap: a larger estimate is charged in full, and the
+ floor only spares a small opening request a re-cost on its first round.
+ """
from types import SimpleNamespace
payload = SimpleNamespace(
@@ -481,10 +493,12 @@ class TestToolLoopsReserveTheirUpperBound:
enable_tools = True,
tools = None,
)
- assert self._cost(payload, tool_loop = True) == 2048
+ assert self._cost(payload, tool_loop = True) == 2048 // 4
- def test_two_tool_requests_do_not_run_together(self):
+ def test_four_tool_requests_run_together(self):
+ """The behaviour this change exists for. Under #9392 the second one waited."""
from types import SimpleNamespace
+
async def scenario():
queue = LlamaAdmissionQueue("test")
payload = SimpleNamespace(
@@ -494,12 +508,39 @@ class TestToolLoopsReserveTheirUpperBound:
tools = None,
)
cost = self._cost(payload, tool_loop = True)
- first = await _reserve(queue, capacity = 4, tokens = cost, budget = 2048)
- assert first.lease_nowait() is not None
- second = await _reserve(queue, capacity = 4, tokens = cost, budget = 2048)
- return second.lease_nowait()
+ leases = []
+ for _ in range(4):
+ reservation = await _reserve(queue, capacity = 4, tokens = cost, budget = 2048)
+ leases.append(reservation.lease_nowait())
+ return leases
- assert _run(scenario()) is None
+ assert all(lease is not None for lease in _run(scenario()))
+
+ def test_growth_past_the_share_is_still_accounted(self):
+ """The overcommit #9392 fixed stays fixed: loops holding a share each cannot all
+ grow into the same cache, and a refused growth leaves the pool as it was."""
+ from types import SimpleNamespace
+
+ async def scenario():
+ queue = LlamaAdmissionQueue("test")
+ payload = SimpleNamespace(
+ messages = [{"role": "user", "content": "hi"}],
+ max_tokens = 16,
+ enable_tools = True,
+ tools = None,
+ )
+ cost = self._cost(payload, tool_loop = True)
+ leases = []
+ for _ in range(4):
+ reservation = await _reserve(queue, capacity = 4, tokens = cost, budget = 2048)
+ leases.append(reservation.lease_nowait())
+ # The cache is exactly full at four shares, so nobody may grow.
+ return leases, queue
+
+ leases, queue = _run(scenario())
+ assert queue.snapshot().committed == 2048
+ assert leases[0].recost(2048) is False
+ assert queue.snapshot().committed == 2048
def test_a_request_without_tools_is_unaffected(self):
"""The serialisation is the price of a tool loop, not of every request."""
diff --git a/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.py b/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.py
index b27c202f851..fa43f551d0e 100644
--- a/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.py
+++ b/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.py
@@ -365,18 +365,50 @@ class TestMediaIsCharged:
assert cost > 2000, f"{field} was charged {cost}, i.e. nothing for the media"
-class TestTheToolLoopReservesTheWholeCache:
- def test_a_server_side_loop_without_client_tools_reserves_the_budget(self):
- """enable_tools / mcp_enabled / CLI policy open the loop with no `tools` array."""
+class TestTheToolLoopOpensAtAnEqualShare:
+ """#9392 reserved the WHOLE cache for any tool loop, making every tool chat run alone
+ (any lit pill sets enable_tools). The loop now opens at an equal share and re-costs
+ per round (llama_cpp.generate_chat_completion_with_tools -> on_conversation_grew ->
+ LlamaAdmissionLease.recost), the alternative #9392 named and skipped.
+ """
+
+ def test_a_server_side_loop_without_client_tools_is_still_a_tool_loop(self):
+ """enable_tools / mcp_enabled / CLI policy open the loop with no `tools` array.
+
+ The amount changed, not the recognition: keying on payload.tools would still
+ undercharge Unsloth's own tool traffic.
+ """
payload = _Payload(
messages = [{"role": "user", "content": "search my notes"}],
enable_tools = True,
max_tokens = 128,
)
assert getattr(payload, "tools", None) is None
- assert (
- _openai_llama_admission_tokens(payload, budget = 4096, capacity = 4, tool_loop = True) == 4096
+ cost = _openai_llama_admission_tokens(payload, budget = 4096, capacity = 4, tool_loop = True)
+ assert cost == 1024, cost
+
+ def test_four_tool_chats_fit_the_cache_at_once(self):
+ """Four equal shares are exactly the budget, so four tool chats are admitted
+ together instead of one at a time."""
+ payload = _Payload(
+ messages = [{"role": "user", "content": "search my notes"}],
+ enable_tools = True,
+ max_tokens = 128,
+ )
+ cost = _openai_llama_admission_tokens(payload, budget = 262144, capacity = 4, tool_loop = True)
+ assert cost * 4 <= 262144
+
+ def test_a_tool_loop_bigger_than_its_share_is_charged_what_it_is(self):
+ """The share is a floor, not a cap: a run already sending more than a quarter of
+ the cache is charged for it, not admitted alongside three others."""
+ payload = _Payload(
+ messages = [{"role": "user", "content": "x " * 4000}],
+ enable_tools = True,
+ max_tokens = 128,
)
+ cost = _openai_llama_admission_tokens(payload, budget = 4096, capacity = 4, tool_loop = True)
+ assert cost > 1024, cost
+ assert cost <= 4096
def test_a_passthrough_forwarding_tools_is_charged_its_own_round(self):
"""One HTTP call is one generation there: the client drives the rounds."""
@@ -425,3 +457,140 @@ class TestTheBudgetIsTheWholeCacheNotOneSlot:
def test_a_backend_that_cannot_say_keeps_slot_only_admission(self):
from routes.inference import _openai_llama_admission_budget
assert _openai_llama_admission_budget(_Payload()) is None
+
+
+class TestARoundIsCostedTheSameWayTheReservationWas:
+ """The re-cost REPLACES the opening reservation, so it has to count the same things.
+
+ ``_openai_llama_admission_recost`` fires at the top of every round including round
+ zero, before a tool loop has grown at all. Counting fewer terms than the reservation
+ therefore shrinks a correctly sized lease and hands the difference to the next
+ arrival as room llama-server is already using -- the multi-slot ``Context size has
+ been exceeded`` this accounting exists to prevent.
+ """
+
+ class _Backend:
+ base_url = "http://llama"
+ effective_parallel_slots = 4
+ _kv_cache_context_total = 4096
+ context_length = 4096
+ _mmproj_projector_type = None
+ _extra_args = None
+
+ class _Reservation:
+ def __init__(self, lease):
+ self._lease = lease
+
+ def lease_nowait(self):
+ return self._lease
+
+ def _round_zero(self, payload, *, output_tokens):
+ """Open a tool lease from ``payload``, then re-cost it before it has grown."""
+ import asyncio
+
+ from core.inference.llama_admission import LlamaAdmissionConfig, LlamaAdmissionQueue
+ from routes.inference import (
+ _openai_llama_admission_recost,
+ _openai_llama_admission_tokens,
+ )
+
+ async def _run():
+ queue = LlamaAdmissionQueue("test")
+ opened = _openai_llama_admission_tokens(
+ payload, budget = 4096, capacity = 4, tool_loop = True
+ )
+ reservation = queue.reserve(
+ capacity = 4,
+ config = LlamaAdmissionConfig(),
+ tokens = opened,
+ budget = 4096,
+ )
+ lease = reservation.lease_nowait()
+ assert lease is not None
+ _openai_llama_admission_recost(
+ self._Reservation(lease),
+ payload.messages,
+ request = None,
+ llama_backend = self._Backend(),
+ payload = payload,
+ output_tokens = output_tokens,
+ )
+ return opened, queue.snapshot().committed, queue
+
+ return asyncio.run(_run())
+
+ def test_round_zero_does_not_give_away_a_vision_prompt_s_image_allowance(self):
+ """Image parts compact to "[image]" for the text estimate, so the real mtmd cost
+ can only come from the compaction count. Discarding it re-costs a vision tool run
+ DOWNWARD by the whole allowance on its first round."""
+ payload = _Payload(
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "what is in this picture?"},
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:image/png;base64,{_TINY_PNG}"},
+ },
+ ],
+ }
+ ],
+ enable_tools = True,
+ max_tokens = 128,
+ )
+ opened, committed, _ = self._round_zero(payload, output_tokens = 128)
+ # One image alone is 4224 against this 4096 budget, so the reservation clamps to
+ # the whole cache: four times the 1024 share the re-cost used to drop it to.
+ assert _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS > 4096 and opened == 4096, opened
+ assert committed == opened, (
+ f"round zero shrank a correct lease from {opened} to {committed}, "
+ f"giving away {opened - committed} tokens of resident image KV"
+ )
+
+ def test_round_zero_keeps_an_uncapped_loop_s_output_allowance(self):
+ """No max_tokens and no max_completion_tokens: generation is bounded only by the
+ window, which is why the reservation charges ``budget - prompt``. Flattening the
+ absent cap to zero drops the loop to its share while its generations can still
+ fill most of the cache."""
+ from routes.inference import _effective_openai_max_tokens
+
+ payload = _Payload(
+ messages = [{"role": "user", "content": "summarise the news"}],
+ enable_tools = True,
+ )
+ assert _effective_openai_max_tokens(payload) is None
+ opened, committed, queue = self._round_zero(
+ payload, output_tokens = _effective_openai_max_tokens(payload)
+ )
+ assert opened == 4096, opened
+ assert (
+ committed == opened
+ ), f"round zero shrank an uncapped loop from {opened} to {committed}"
+ # And the room it would have released must not admit anyone.
+ import asyncio
+
+ from core.inference.llama_admission import LlamaAdmissionConfig
+
+ async def _newcomer():
+ return queue.reserve(
+ capacity = 4, config = LlamaAdmissionConfig(), tokens = 2000, budget = 4096
+ ).lease_nowait()
+
+ assert asyncio.run(_newcomer()) is None
+
+ def test_round_zero_keeps_a_top_level_system_prompt(self):
+ """Anthropic keeps `system` and `tools` out of `messages` entirely, so for that
+ route this is most of the prompt."""
+ payload = _Payload(
+ messages = [{"role": "user", "content": "hi"}],
+ system = "You are a careful assistant that cites its sources. " * 200,
+ enable_tools = True,
+ max_tokens = 128,
+ )
+ opened, committed, _ = self._round_zero(payload, output_tokens = 128)
+ assert opened > 1024, f"the system text should push this past the share: {opened}"
+ assert committed == opened, (
+ f"round zero shrank the lease from {opened} to {committed}, dropping the "
+ f"non-message prompt the reservation charged"
+ )
diff --git a/studio/backend/tests/test_llama_admission_recost.py b/studio/backend/tests/test_llama_admission_recost.py
new file mode 100644
index 00000000000..4ee0f22e957
--- /dev/null
+++ b/studio/backend/tests/test_llama_admission_recost.py
@@ -0,0 +1,481 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Re-costing a live lease as its tool loop grows.
+
+#9392 admitted generations against the KV cache instead of the slot count, after two chats
+killed each other on a 2048-token cache (565 + 1485, neither too long alone). It could not
+know a tool loop's final size, since each round appends its results and re-sends the
+conversation, so it reserved the WHOLE cache: airtight, and it made every tool chat run
+alone (any lit pill sets ``enable_tools``). Measured on a 262144 cache, four tool chats
+reached first token at 0.1s, 2.8s, 4.6s and 8.8s, one after another.
+
+Re-costing is the alternative that PR named and skipped. These pin the properties that
+make it safe to call from inside a running generator.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+import time
+
+import pytest
+
+from core.inference.llama_admission import LlamaAdmissionConfig, LlamaAdmissionQueue
+
+
+def _reserve(queue, *, capacity, tokens, budget):
+ return queue.reserve(
+ capacity = capacity,
+ config = LlamaAdmissionConfig(),
+ tokens = tokens,
+ budget = budget,
+ )
+
+
+def _lease(
+ queue,
+ *,
+ capacity = 4,
+ tokens,
+ budget,
+):
+ """reserve() reads the running loop, so every test here is async."""
+ reservation = _reserve(queue, capacity = capacity, tokens = tokens, budget = budget)
+ lease = reservation.lease_nowait()
+ assert lease is not None, "expected this reservation to be admitted"
+ return lease
+
+
+class TestTheQueueSide:
+ @pytest.mark.asyncio
+ async def test_growth_that_fits_is_applied(self):
+ queue = LlamaAdmissionQueue("test")
+ _lease(queue, tokens = 1000, budget = 4096)
+ assert queue.try_recost(1000, 2000) is True
+ assert queue.snapshot().committed == 2000
+
+ @pytest.mark.asyncio
+ async def test_growth_that_does_not_fit_is_refused_and_changes_nothing(self):
+ """Refused, not blocked: this runs inside the generator, where a round that waited
+ could be waiting on a holder that is waiting on it."""
+ queue = LlamaAdmissionQueue("test")
+ _lease(queue, tokens = 2000, budget = 4096)
+ _lease(queue, tokens = 2000, budget = 4096)
+ assert queue.snapshot().committed == 4000
+ assert queue.try_recost(2000, 3000) is False
+ assert queue.snapshot().committed == 4000, "a refused growth must not move anything"
+
+ @pytest.mark.asyncio
+ async def test_a_lone_holder_may_grow_past_the_budget(self):
+ """The escape admission uses: refusing the only holder stalls a conversation
+ nothing else can unblock, and llama.cpp surfaces a real overflow itself."""
+ queue = LlamaAdmissionQueue("test")
+ _lease(queue, tokens = 2000, budget = 4096)
+ assert queue.try_recost(2000, 9000) is True
+ assert queue.snapshot().committed == 9000
+
+ @pytest.mark.asyncio
+ async def test_shrinking_always_applies(self):
+ queue = LlamaAdmissionQueue("test")
+ _lease(queue, tokens = 2000, budget = 4096)
+ _lease(queue, tokens = 2000, budget = 4096)
+ assert queue.try_recost(2000, 500) is True
+ assert queue.snapshot().committed == 2500
+
+ @pytest.mark.asyncio
+ async def test_no_budget_means_nothing_to_account(self):
+ queue = LlamaAdmissionQueue("test")
+ assert queue.try_recost(1000, 999999) is True
+
+
+class TestTheLeaseSide:
+ @pytest.mark.asyncio
+ async def test_recost_moves_the_queue_and_the_lease_together(self):
+ queue = LlamaAdmissionQueue("test")
+ lease = _lease(queue, tokens = 1000, budget = 8192)
+ assert lease.recost(2500) is True
+ assert queue.snapshot().committed == 2500
+ # Release must hand back the NEW figure, not the one it was admitted on.
+ lease.release()
+ assert queue.snapshot().committed == 0
+
+ @pytest.mark.asyncio
+ async def test_a_refused_recost_leaves_release_correct(self):
+ """The leak this guards: if the queue took the growth while the lease kept the old
+ number, release would hand back less than it holds and strand the difference."""
+ queue = LlamaAdmissionQueue("test")
+ first = _lease(queue, tokens = 3000, budget = 4096)
+ second = _lease(queue, tokens = 1000, budget = 4096)
+ assert second.recost(3000) is False
+ second.release()
+ first.release()
+ assert queue.snapshot().committed == 0
+
+ @pytest.mark.asyncio
+ async def test_a_released_lease_recosts_to_nothing(self):
+ queue = LlamaAdmissionQueue("test")
+ lease = _lease(queue, tokens = 1000, budget = 4096)
+ lease.release()
+ assert lease.recost(3000) is True, "a finished run is not an error"
+ assert queue.snapshot().committed == 0, "and must not re-commit anything"
+
+ @pytest.mark.asyncio
+ async def test_recost_is_idempotent_at_the_same_size(self):
+ queue = LlamaAdmissionQueue("test")
+ lease = _lease(queue, tokens = 1000, budget = 4096)
+ for _ in range(5):
+ assert lease.recost(1000) is True
+ assert queue.snapshot().committed == 1000
+
+ @pytest.mark.asyncio
+ async def test_concurrent_recost_and_release_do_not_strand_tokens(self):
+ """release() takes the lease lock and then the queue's; recost takes them in the
+ same order, which is what keeps this from deadlocking or leaking."""
+ for _ in range(40):
+ queue = LlamaAdmissionQueue("test")
+ lease = _lease(queue, tokens = 1000, budget = 1_000_000)
+ barrier = threading.Barrier(2)
+
+ def grow(lease = lease, barrier = barrier):
+ barrier.wait()
+ lease.recost(5000)
+
+ def drop(lease = lease, barrier = barrier):
+ barrier.wait()
+ lease.release()
+
+ # Daemon throughout this file: a failed assertion leaves a growth thread
+ # spinning, and a live non-daemon one wedges exit instead of reporting it.
+ threads = [
+ threading.Thread(target = grow, daemon = True),
+ threading.Thread(target = drop, daemon = True),
+ ]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+ assert queue.snapshot().committed == 0, "a race left tokens committed with no holder"
+
+
+class TestFourToolChatsTogether:
+ @pytest.mark.asyncio
+ async def test_four_tool_chats_are_admitted_and_can_each_grow_a_little(self):
+ """The behaviour the change exists for, end to end at the queue level."""
+ queue = LlamaAdmissionQueue("test")
+ budget = 262144
+ share = budget // 4
+ leases = [_lease(queue, tokens = share, budget = budget) for _ in range(4)]
+ assert queue.snapshot().committed == budget, "all four tool chats admitted at once"
+ # The cache is exactly full, so nobody may grow at anyone else's expense.
+ assert leases[0].recost(share + 1000) is False
+ # ... until someone finishes.
+ leases[3].release()
+ assert leases[0].recost(share + 1000) is True
+
+
+class TestWaitingForRoomInsteadOfRunningOverIt:
+ """``recost`` alone accounts for growth without enforcing it.
+
+ A refused recost leaves the run at its old figure and it sends the bigger prompt
+ anyway. Four loops opening at a share each and growing together is then the measured
+ failure: llama.cpp halves the batch to 1, gives up, and ``Context size has been
+ exceeded`` clears EVERY decoding slot, not just the one that overflowed.
+ ``recost_waiting`` is what makes the accounting binding.
+ """
+
+ @pytest.mark.asyncio
+ async def test_growth_that_fits_never_touches_the_wait_line(self):
+ queue = LlamaAdmissionQueue("test")
+ lease = _lease(queue, tokens = 1000, budget = 8192)
+ assert lease.recost_waiting(2000) is True
+ assert queue.snapshot().committed == 2000
+ assert queue._reparking == 0, "a growth that fit should not have yielded anything"
+
+ @pytest.mark.asyncio
+ async def test_a_waiter_is_let_in_when_a_holder_finishes(self):
+ queue = LlamaAdmissionQueue("test")
+ first = _lease(queue, tokens = 2000, budget = 4096)
+ second = _lease(queue, tokens = 2000, budget = 4096)
+
+ done: list = []
+
+ def grow():
+ done.append(second.recost_waiting(3500, poll_s = 0.01))
+
+ thread = threading.Thread(target = grow, daemon = True)
+ thread.start()
+ # It cannot proceed: 2000 is still held by `first` and 3500 does not fit beside it.
+ thread.join(0.2)
+ assert thread.is_alive(), "expected the growth to wait, not to be refused"
+ # Yielding first is what makes this resolvable at all.
+ assert queue.snapshot().committed == 2000
+ first.release()
+ thread.join(5)
+ assert not thread.is_alive()
+ assert done == [True]
+ assert queue.snapshot().committed == 3500
+
+ @pytest.mark.asyncio
+ async def test_four_loops_growing_together_do_not_overcommit(self):
+ """The deadlock case that decides the design. Every holder wants more than a
+ share, so blocking while still holding leaves all four waiting on each other.
+ Yielding first means _committed strictly falls, so somebody fits."""
+ queue = LlamaAdmissionQueue("test")
+ budget = 4096
+ leases = [_lease(queue, tokens = budget // 4, budget = budget) for _ in range(4)]
+ assert queue.snapshot().committed == budget
+
+ results: list = []
+ lock = threading.Lock()
+
+ def grow(lease):
+ ok = lease.recost_waiting(budget // 2, poll_s = 0.01)
+ with lock:
+ results.append(ok)
+ # Finishing is what lets the next one in.
+ lease.release()
+
+ threads = [threading.Thread(target = grow, args = (lease,), daemon = True) for lease in leases]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(20)
+ assert not any(t.is_alive() for t in threads), "a growth deadlocked"
+ assert results == [True] * 4
+ assert queue.snapshot().committed == 0
+ assert queue._reparking == 0
+
+ @pytest.mark.asyncio
+ async def test_the_budget_is_never_exceeded_while_they_wait(self):
+ """Only one reparker may win the committed-is-zero escape: four racing an empty
+ cache would each see zero and each admit itself."""
+ queue = LlamaAdmissionQueue("test")
+ budget = 4096
+ leases = [_lease(queue, tokens = budget // 4, budget = budget) for _ in range(4)]
+ peak = []
+ stop = threading.Event()
+
+ def watch():
+ while not stop.is_set():
+ peak.append(queue.snapshot().committed)
+ time.sleep(0.005)
+
+ watcher = threading.Thread(target = watch, daemon = True)
+ watcher.start()
+
+ def grow(lease):
+ lease.recost_waiting(budget, poll_s = 0.01)
+ lease.release()
+
+ threads = [threading.Thread(target = grow, args = (lease,), daemon = True) for lease in leases]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(20)
+ stop.set()
+ watcher.join(5)
+ assert max(peak) <= budget, f"committed reached {max(peak)} against a {budget} cache"
+
+ @pytest.mark.asyncio
+ async def test_cancelling_a_waiting_round_restores_its_commitment(self):
+ """Stop pressed while waiting. Until the run releases it still occupies
+ llama-server's cache, so the pool must know about it."""
+ queue = LlamaAdmissionQueue("test")
+ first = _lease(queue, tokens = 3000, budget = 4096)
+ second = _lease(queue, tokens = 1000, budget = 4096)
+ cancel = threading.Event()
+
+ out: list = []
+
+ def grow():
+ out.append(second.recost_waiting(4000, cancel_event = cancel, poll_s = 0.01))
+
+ thread = threading.Thread(target = grow, daemon = True)
+ thread.start()
+ thread.join(0.2)
+ assert thread.is_alive()
+ cancel.set()
+ thread.join(5)
+ assert out == [False], "a cancelled wait reports that it did not take the new size"
+ assert queue.snapshot().committed == 4000, "the old commitment is back"
+ assert queue._reparking == 0
+ second.release()
+ first.release()
+ assert queue.snapshot().committed == 0
+
+ @pytest.mark.asyncio
+ async def test_a_reparker_is_not_overtaken_by_a_new_arrival(self):
+ """An in-flight conversation beats one that has not started. Otherwise a steady
+ arrival rate holds a growing run at its opening size indefinitely."""
+ queue = LlamaAdmissionQueue("test")
+ first = _lease(queue, tokens = 2000, budget = 4096)
+ second = _lease(queue, tokens = 2000, budget = 4096)
+
+ def grow():
+ second.recost_waiting(3000, poll_s = 0.01)
+
+ thread = threading.Thread(target = grow, daemon = True)
+ thread.start()
+ thread.join(0.2)
+ assert thread.is_alive()
+ # A newcomer arrives while the reparker waits, and must not be granted the room
+ # the reparker just gave up.
+ newcomer = queue.reserve(
+ capacity = 4, config = LlamaAdmissionConfig(), tokens = 1000, budget = 4096
+ )
+ assert newcomer.lease_nowait() is None, "a new arrival overtook a growing run"
+ first.release()
+ thread.join(5)
+ assert not thread.is_alive()
+ # Behind the reparker, not instead of it. The reclaim brings the barrier down and
+ # is the last thing to touch the queue, so if it does not run admission itself a
+ # request that fits in the room left over waits out the whole grown run -- and
+ # since a queued waiter shuts reserve()'s fast path, so does every later arrival.
+ for _ in range(100):
+ await asyncio.sleep(0.01)
+ if newcomer.lease_nowait() is not None:
+ break
+ assert (
+ newcomer.lease_nowait() is not None
+ ), "the last repark barrier came down without re-running admission"
+ assert queue.snapshot().committed == 4000
+
+
+class TestGivingUpTheWait:
+ """What a reparker owes the pool when its wait ends without the bigger commitment.
+
+ ``yield_commitment`` has already taken the old figure off ``_committed``, but the
+ lease still occupies that KV at llama-server. Handing it back is a CORRECTION, not a
+ request, and a full cache must not be able to refuse it: a lease that records a
+ commitment it never restored subtracts it again on release, leaving phantom room.
+ """
+
+ @pytest.mark.asyncio
+ async def test_a_full_cache_cannot_refuse_the_restore(self):
+ queue = LlamaAdmissionQueue("test")
+ loser = _lease(queue, tokens = 1024, budget = 4096)
+ winner = _lease(queue, tokens = 1024, budget = 4096)
+ assert queue.snapshot().committed == 2048
+
+ cancel = threading.Event()
+ out: list = []
+
+ def grow():
+ out.append(loser.recost_waiting(4096, cancel_event = cancel, poll_s = 0.01))
+
+ thread = threading.Thread(target = grow, daemon = True)
+ thread.start()
+ while queue.snapshot().committed != 1024:
+ await asyncio.sleep(0.005)
+ # The other run takes the whole cache while this one is parked, leaving no room
+ # for the restore to ask for.
+ assert winner.recost(4096) is True
+ assert queue.snapshot().committed == 4096
+
+ cancel.set()
+ thread.join(5)
+ assert out == [False]
+ assert queue._reparking == 0
+ # Both leases really hold their figures at llama-server, so the pool says so even
+ # over the budget: that is what is genuinely resident.
+ assert (
+ queue.snapshot().committed == 4096 + 1024
+ ), "a restore the cache could not fit was dropped instead of recorded"
+
+ loser.release()
+ assert (
+ queue.snapshot().committed == 4096
+ ), "release subtracted a commitment that was never restored"
+ # And the phantom room that leak created must not admit anyone.
+ newcomer = queue.reserve(
+ capacity = 4, config = LlamaAdmissionConfig(), tokens = 1000, budget = 4096
+ )
+ assert (
+ newcomer.lease_nowait() is None
+ ), "a newcomer was admitted into room the winner is still using"
+ winner.release()
+
+ @pytest.mark.asyncio
+ async def test_a_released_lease_restores_nothing(self):
+ """release() already handed back the 0 held while parked, so re-committing here
+ would strand the difference for the life of the process."""
+ queue = LlamaAdmissionQueue("test")
+ holder = _lease(queue, tokens = 2000, budget = 4096)
+ _lease(queue, tokens = 2000, budget = 4096)
+
+ cancel = threading.Event()
+ thread = threading.Thread(
+ target = lambda: holder.recost_waiting(4000, cancel_event = cancel, poll_s = 0.01),
+ daemon = True,
+ )
+ thread.start()
+ while queue.snapshot().committed != 2000:
+ await asyncio.sleep(0.005)
+ holder.release()
+ cancel.set()
+ thread.join(5)
+ assert not thread.is_alive()
+ assert queue._reparking == 0
+ assert queue.snapshot().committed == 2000, "the released lease was re-committed"
+
+
+class TestYieldingIsGatedOnTheServerActuallyClearing:
+ """A slot being idle is not the same as its KV cells being reclaimed.
+
+ Under ``--kv-unified`` a finished round's cells stay resident until ``prompt_clear()``,
+ which llama-server runs only under ``--cache-idle-slots``. ``--cache-ram 0``
+ force-disables that, and Studio emits it on Windows under full GPU offload (#5692)
+ next to ``--kv-unified``. Yielding there hands a second caller occupied room.
+ """
+
+ @pytest.mark.asyncio
+ async def test_growth_that_fits_does_not_care(self):
+ """The cheap path never yields anything, so gating must not disturb it."""
+ queue = LlamaAdmissionQueue("test")
+ holder = _lease(queue, tokens = 1000, budget = 4096)
+ assert holder.recost_waiting(2000, allow_yield = False) is True
+ assert queue.snapshot().committed == 2000
+
+ @pytest.mark.asyncio
+ async def test_growth_that_does_not_fit_declines_instead_of_yielding(self):
+ queue = LlamaAdmissionQueue("test")
+ holder = _lease(queue, tokens = 2000, budget = 4096)
+ _lease(queue, tokens = 2000, budget = 4096)
+
+ assert holder.recost_waiting(4000, allow_yield = False) is False
+ assert holder._tokens == 2000, "the old commitment was not kept"
+ assert queue.snapshot().committed == 4000, "capacity was handed out twice"
+ assert queue._reparking == 0
+
+ @pytest.mark.asyncio
+ async def test_it_does_not_block(self):
+ """Declining is the pre-existing behaviour: do not wait for room that is never
+ coming back on this server."""
+ queue = LlamaAdmissionQueue("test")
+ holder = _lease(queue, tokens = 2000, budget = 4096)
+ _lease(queue, tokens = 2000, budget = 4096)
+
+ started = time.monotonic()
+ assert holder.recost_waiting(4000, allow_yield = False, timeout_s = 30.0, poll_s = 0.5) is False
+ assert time.monotonic() - started < 1.0
+
+ @pytest.mark.asyncio
+ async def test_yielding_is_still_the_default(self):
+ """Old callers, and every server that does clear, keep the waiting behaviour."""
+ queue = LlamaAdmissionQueue("test")
+ holder = _lease(queue, tokens = 2000, budget = 4096)
+ other = _lease(queue, tokens = 2000, budget = 4096)
+
+ thread = threading.Thread(
+ target = lambda: holder.recost_waiting(4000, poll_s = 0.01),
+ daemon = True,
+ )
+ thread.start()
+ while queue.snapshot().committed != 2000:
+ await asyncio.sleep(0.005)
+ other.release()
+ thread.join(5)
+ assert not thread.is_alive()
+ assert queue.snapshot().committed == 4000
diff --git a/studio/backend/tests/test_llama_admission_stress.py b/studio/backend/tests/test_llama_admission_stress.py
new file mode 100644
index 00000000000..27febc2d492
--- /dev/null
+++ b/studio/backend/tests/test_llama_admission_stress.py
@@ -0,0 +1,240 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Randomised stress against the admission queue's invariants.
+
+Two properties that have to hold under ANY interleaving, because the failure they guard is
+a wedged Unsloth, not a wrong number:
+
+ 1. ``committed`` never exceeds ``budget``, except the single holder the escape lets past.
+ Breaking this is the ``Context size has been exceeded`` that clears every decoding
+ slot at once.
+ 2. The queue always drains. A leaked repark counter holds the wait line shut for every
+ caller, freezing the pool for the life of the process.
+
+Seeded, so a failure is reproducible from the seed in the assertion message.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import random
+import threading
+import time
+
+import pytest
+
+from core.inference.llama_admission import LlamaAdmissionConfig, LlamaAdmissionQueue
+
+
+def _lease(queue, *, tokens, budget, capacity):
+ reservation = queue.reserve(
+ capacity = capacity,
+ config = LlamaAdmissionConfig(),
+ tokens = tokens,
+ budget = budget,
+ )
+ return reservation.lease_nowait()
+
+
+class _Ceiling:
+ """Watches ``committed`` from another thread and remembers the worst it saw."""
+
+ def __init__(self, queue):
+ self.queue = queue
+ self.peak = 0
+ self._stop = threading.Event()
+ self._thread = threading.Thread(target = self._run, daemon = True)
+
+ def _run(self):
+ while not self._stop.is_set():
+ self.peak = max(self.peak, self.queue.snapshot().committed)
+ time.sleep(0.001)
+
+ def __enter__(self):
+ self._thread.start()
+ return self
+
+ def __exit__(self, *_exc):
+ self._stop.set()
+ self._thread.join(5)
+ self.peak = max(self.peak, self.queue.snapshot().committed)
+
+
[email protected]("seed", range(12))
+async def test_random_traffic_never_exceeds_the_cache_and_always_drains(seed):
+ """Many holders, random sizes, random growth, random cancels, all at once."""
+ rng = random.Random(seed)
+ capacity = rng.choice([1, 2, 4, 8])
+ budget = rng.choice([2048, 4096, 65536])
+ queue = LlamaAdmissionQueue(f"stress-{seed}")
+
+ # Every holder is admitted at a size that fits alongside the others, so any excess is
+ # the queue's doing, not the workload's. The escape is exercised separately.
+ opening = max(1, budget // max(1, capacity))
+ leases = [
+ lease
+ for lease in (
+ _lease(queue, tokens = opening, budget = budget, capacity = capacity) for _ in range(capacity)
+ )
+ if lease is not None
+ ]
+ assert leases, f"seed={seed}: nothing was admitted at an equal share"
+
+ def worker(lease):
+ for _ in range(rng.randint(1, 4)):
+ want = rng.randint(1, budget)
+ cancel = threading.Event()
+ if rng.random() < 0.3:
+ # Cancel shortly after asking, to land inside the wait.
+ threading.Timer(rng.uniform(0.0, 0.05), cancel.set).start()
+ lease.recost_waiting(
+ want,
+ cancel_event = cancel,
+ poll_s = 0.005,
+ timeout_s = 5.0,
+ )
+ time.sleep(rng.uniform(0.0, 0.01))
+ lease.release()
+
+ with _Ceiling(queue) as ceiling:
+ threads = [threading.Thread(target = worker, args = (lease,), daemon = True) for lease in leases]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(90)
+
+ assert not any(t.is_alive() for t in threads), f"seed={seed}: a worker never finished"
+ snapshot = queue.snapshot()
+ assert snapshot.committed == 0, f"seed={seed}: {snapshot.committed} tokens stranded"
+ assert queue._reparking == 0, f"seed={seed}: repark counter leaked, the queue is wedged"
+ # One holder may sit above the budget via the alone escape, so the ceiling is the
+ # budget plus the largest single request.
+ assert (
+ ceiling.peak <= budget * 2
+ ), f"seed={seed}: committed peaked at {ceiling.peak} against a {budget} cache"
+
+
[email protected]("seed", range(6))
+async def test_new_arrivals_alongside_growing_holders_still_drain(seed):
+ """Reparkers hold the wait line shut, so forgetting to reopen it shows up here as
+ arrivals that are never granted."""
+ rng = random.Random(1000 + seed)
+ capacity = 4
+ budget = 4096
+ queue = LlamaAdmissionQueue(f"mixed-{seed}")
+ share = budget // capacity
+
+ holders = [
+ _lease(queue, tokens = share, budget = budget, capacity = capacity) for _ in range(capacity)
+ ]
+ holders = [lease for lease in holders if lease is not None]
+
+ def grower(lease):
+ lease.recost_waiting(
+ rng.randint(share, budget),
+ poll_s = 0.005,
+ timeout_s = 5.0,
+ )
+ time.sleep(rng.uniform(0.0, 0.02))
+ lease.release()
+
+ threads = [threading.Thread(target = grower, args = (lease,), daemon = True) for lease in holders]
+ for thread in threads:
+ thread.start()
+
+ # Arrivals queue behind the growers, and must eventually be admitted.
+ arrivals: list = []
+
+ async def arrive():
+ reservation = queue.reserve(
+ capacity = capacity,
+ config = LlamaAdmissionConfig(),
+ tokens = rng.randint(1, share),
+ budget = budget,
+ )
+ # await, never time.sleep: a granted lease is delivered with
+ # loop.call_soon_threadsafe, so a synchronous poll blocks its own delivery.
+ deadline = time.monotonic() + 60
+ while time.monotonic() < deadline:
+ lease = reservation.lease_nowait()
+ if lease is not None:
+ arrivals.append(lease)
+ lease.release()
+ return
+ await asyncio.sleep(0.01)
+ reservation.cancel()
+ arrivals.append(None)
+
+ # reserve() reads the running loop, so each arrival brings its own.
+ def arrive_in_loop():
+ asyncio.run(arrive())
+
+ newcomers = [threading.Thread(target = arrive_in_loop, daemon = True) for _ in range(4)]
+ for thread in newcomers:
+ thread.start()
+ for thread in threads + newcomers:
+ thread.join(120)
+
+ assert not any(t.is_alive() for t in threads + newcomers), f"seed={seed}: did not drain"
+ assert arrivals and all(
+ lease is not None for lease in arrivals
+ ), f"seed={seed}: an arrival was never admitted, the wait line stayed shut"
+ assert queue.snapshot().committed == 0
+ assert queue._reparking == 0
+
+
+async def test_a_wait_that_can_never_be_satisfied_gives_up_rather_than_wedging_the_queue():
+ """The blast-radius test. A reparker holds the line shut for everyone, so a wait with
+ no possible end must expire, restore its old figure and let the queue run again."""
+ budget = 4096
+ queue = LlamaAdmissionQueue("timeout")
+ # All but one token, so the grower is still admitted alongside it and the cache is
+ # exactly full. A squatter holding the whole budget would leave nothing to admit it.
+ squatter = _lease(queue, tokens = budget - 1, budget = budget, capacity = 4)
+ assert squatter is not None
+ grower = _lease(queue, tokens = 1, budget = budget, capacity = 4)
+ assert grower is not None, "the grower must be admitted before it can grow"
+
+ start = time.monotonic()
+ assert grower.recost_waiting(budget, poll_s = 0.01, timeout_s = 0.5) is False
+ waited = time.monotonic() - start
+ assert 0.4 <= waited < 15, f"gave up after {waited}s, expected roughly the timeout"
+ assert queue._reparking == 0, "the wait line is still shut after a timeout"
+ # The queue is usable again: the grower is back at its old figure, so releasing the
+ # squatter leaves exactly that behind.
+ squatter.release()
+ assert queue.snapshot().committed == 1
+ grower.release()
+ assert queue.snapshot().committed == 0
+
+
+async def test_release_during_a_wait_does_not_spin_forever():
+ """release() runs from the route's teardown without touching the cancel event, so a
+ wait that only watched the event would spin on a dead lease and hold the line shut."""
+ budget = 4096
+ queue = LlamaAdmissionQueue("released")
+ squatter = _lease(queue, tokens = budget - 1, budget = budget, capacity = 4)
+ grower = _lease(queue, tokens = 1, budget = budget, capacity = 4)
+ assert squatter is not None and grower is not None
+
+ out: list = []
+
+ def grow():
+ out.append(grower.recost_waiting(budget, poll_s = 0.01, timeout_s = 60))
+
+ thread = threading.Thread(target = grow, daemon = True)
+ thread.start()
+ time.sleep(0.2)
+ assert thread.is_alive(), "expected it to be waiting"
+ grower.release()
+ thread.join(15)
+ assert not thread.is_alive(), "a released lease kept waiting"
+ assert out == [False]
+ assert queue._reparking == 0
+ squatter.release()
+ assert queue.snapshot().committed == 0
diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.py
index d5e602b148d..2a7e88afeb9 100644
--- a/studio/backend/tests/test_llama_cpp_tool_loop.py
+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py
@@ -6909,3 +6909,61 @@ def test_a_second_call_in_a_compacted_turn_is_still_visible_to_the_model(monkeyp
assert answered <= announced, f"results with no visible call: {answered - announced}"
# And the compaction still happened: the body is not replayed.
assert _BIG_BODY not in json.dumps(sent)
+
+
+def test_the_synthesized_final_pass_is_recosted_before_it_is_sent(monkeypatch):
+ """The last request of a tool run is the biggest, and it skips the top of the loop.
+
+ ``on_conversation_grew`` is KV admission's only view of a growing tool loop and fires
+ at the TOP of a round. The iteration cap breaks out mid-round instead, after the
+ assistant turn and its tool result are appended, and goes straight to the synthesized
+ final answer. Without a re-cost there the largest prompt of the run is the one the
+ pool never hears about, and llama.cpp answers the overcommit by killing every
+ decoding slot at once.
+ """
+ first_stream = _structured_tool_call("web_search", {"query": "kernel"}, "call_search")
+ final_stream = [_sse({"content": "6.10."}), _done()]
+ payloads: list[dict] = []
+ backend = _make_backend(monkeypatch, [first_stream, final_stream], payloads)
+ monkeypatch.setattr(
+ "core.inference.tools.execute_tool",
+ # Long enough that skipping it is a real under-count, not a rounding error.
+ lambda name, arguments, **_kwargs: "Linux kernel 6.10. " * 400,
+ )
+
+ seen: list[list[dict]] = []
+
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "Search for the kernel version."}],
+ tools = [
+ {
+ "type": "function",
+ "function": {
+ "name": "web_search",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ }
+ ],
+ # One round, so the loop breaks on the cap mid-round rather than at the top.
+ max_tool_iterations = 1,
+ permission_mode = "off",
+ on_conversation_grew = lambda conversation: seen.append(copy.deepcopy(conversation)),
+ )
+ )
+
+ assert len(payloads) == 2, "expected one tool round and one synthesized final pass"
+ final_messages = payloads[-1]["messages"]
+ assert any(
+ message.get("role") == "tool" for message in final_messages
+ ), "the final pass should carry the tool result this test is about"
+ assert seen, "the callback never ran"
+ last_seen = seen[-1]
+ assert any(message.get("role") == "tool" for message in last_seen), (
+ "the last re-cost ran before the tool result was appended, so the final pass "
+ "was sent under stale KV accounting"
+ )
+ assert len(last_seen) == len(final_messages), (
+ f"the final pass sends {len(final_messages)} messages but the pool was last told "
+ f"about {len(last_seen)}"
+ )