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.

fix(studio): Windows GGUF cancel hang + CPU spinlock overhead (#5692) (#5749)

Anmol Mishra9f694ab750e9
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 57cc97f3b57..8657179b738 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -23,7 +23,7 @@ import sys
import threading
import time
from pathlib import Path
-from typing import Callable, Generator, Iterable, List, Optional
+from typing import Callable, Collection, Generator, Iterable, List, Optional, Union
import httpx
@@ -567,14 +567,27 @@ def _auto_mode_drops_mtp(
def _extra_args_set_spec_type(extra_args: Optional[Iterable[str]]) -> bool:
"""User passed --spec-type / --spec-default? llama-server takes one
--spec-type (comma-separated to chain), so suppress auto-emit."""
+ return _extra_args_set_any_flag(extra_args, {"--spec-type", "--spec-default"})
+
+
+_GPU_OFFLOAD_OVERRIDE_FLAGS = frozenset({"-ngl", "--gpu-layers", "--n-gpu-layers", "-fit", "--fit"})
+_THREAD_OVERRIDE_FLAGS = frozenset({"-t", "--threads"})
+
+
+def _extra_arg_flag_name(token: str) -> Optional[str]:
+ if not token.startswith("-") or token in {"-", "--"}:
+ return None
+ if len(token) >= 2 and (token[1].isdigit() or token[1] == "."):
+ return None
+ return token.split("=", 1)[0]
+
+
+def _extra_args_set_any_flag(extra_args: Optional[Iterable[str]], flags: Collection[str]) -> bool:
if not extra_args:
return False
for raw in extra_args:
- tok = str(raw)
- if not tok.startswith("--"):
- continue
- flag = tok.split("=", 1)[0]
- if flag in ("--spec-type", "--spec-default"):
+ flag = _extra_arg_flag_name(str(raw))
+ if flag in flags:
return True
return False
@@ -1217,7 +1230,7 @@ class LlamaCppBackend:
def probe_server_capabilities(cls, binary: Optional[str] = None) -> dict[str, object]:
"""Parse `llama-server --help` for feature flags. Returns
{found, mtp_token, supports_mtp, ngram_mod_flavor,
- supports_ngram_mod, spec_draft_n_max_flag}.
+ supports_ngram_mod, spec_draft_n_max_flag, cache flag support}.
``ngram_mod_flavor``: ``"new"`` when the post-rename
``--spec-ngram-mod-n-match / -n-min / -n-max`` are real args;
@@ -1242,6 +1255,9 @@ class LlamaCppBackend:
"spec_draft_n_max_flag": None,
"supports_kv_unified": False,
"supports_fit_ctx": False,
+ "supports_cache_ram": False,
+ "supports_ctx_checkpoints": False,
+ "supports_no_cache_prompt": False,
}
try:
mtime = int(Path(bin_path).stat().st_mtime)
@@ -1257,6 +1273,9 @@ class LlamaCppBackend:
spec_draft_n_max_flag: Optional[str] = None
supports_kv_unified = False
supports_fit_ctx = False
+ supports_cache_ram = False
+ supports_ctx_checkpoints = False
+ supports_no_cache_prompt = False
try:
result = subprocess.run(
[bin_path, "--help"],
@@ -1347,6 +1366,9 @@ class LlamaCppBackend:
supports_kv_unified = _is_real("--kv-unified")
supports_fit_ctx = _is_real("--fit-ctx")
+ supports_cache_ram = _is_real("--cache-ram")
+ supports_ctx_checkpoints = _is_real("--ctx-checkpoints")
+ supports_no_cache_prompt = _is_real("--no-cache-prompt")
except (OSError, subprocess.SubprocessError) as exc:
logger.debug(f"llama-server --help probe failed: {exc}")
@@ -1359,6 +1381,9 @@ class LlamaCppBackend:
"spec_draft_n_max_flag": spec_draft_n_max_flag,
"supports_kv_unified": supports_kv_unified,
"supports_fit_ctx": supports_fit_ctx,
+ "supports_cache_ram": supports_cache_ram,
+ "supports_ctx_checkpoints": supports_ctx_checkpoints,
+ "supports_no_cache_prompt": supports_no_cache_prompt,
}
cls._capability_cache[cache_key] = info
return info
@@ -3924,27 +3949,43 @@ class LlamaCppBackend:
"--no-context-shift",
]
+ fully_gpu_offloaded = False
if use_fit:
cmd.extend(["--fit", "on"])
elif gpu_indices is not None:
# Fits on selected GPU(s) -- offload all layers
cmd.extend(["-ngl", "-1"])
+ fully_gpu_offloaded = True
+ server_caps = self.probe_server_capabilities(binary)
cmd.extend(
self._ctx_integrity_flags(
n_parallel,
use_fit,
requested_ctx,
effective_ctx,
- self.probe_server_capabilities(binary),
+ server_caps,
)
)
+ offload_overridden = _extra_args_set_any_flag(
+ extra_args, _GPU_OFFLOAD_OVERRIDE_FLAGS
+ )
+ threads_overridden = _extra_args_set_any_flag(extra_args, _THREAD_OVERRIDE_FLAGS)
+ full_offload_tuning_active = fully_gpu_offloaded and not offload_overridden
- # -1 = llama.cpp auto-detect (physical cores). Pass explicitly
- # so we don't inherit llama-server's internal default, which
- # has varied (hardware concurrency incl. hyperthreads on some
- # builds).
- cmd.extend(["--threads", str(n_threads if n_threads is not None else -1)])
+ # Pass --threads explicitly so we do not inherit llama-server
+ # defaults. Windows + full offload caps at 2 to stop OpenMP
+ # spin-wait burning CPU during GPU decode. User pass-through
+ # offload/thread flags keep last-wins semantics. #5692.
+ if (
+ sys.platform == "win32"
+ and full_offload_tuning_active
+ and not threads_overridden
+ ):
+ threads_arg = 2
+ else:
+ threads_arg = n_threads if n_threads is not None else -1
+ cmd.extend(["--threads", str(threads_arg)])
# Enable Jinja chat template rendering
cmd.extend(["--jinja"])
@@ -4086,6 +4127,28 @@ class LlamaCppBackend:
else:
self._api_key = None
+ # Windows + full offload: disable KV checkpoints (WDDM/PCI-E
+ # overhead). CPU/partial offload keeps prompt caching. #5692.
+ if sys.platform == "win32" and full_offload_tuning_active:
+ unsupported_cache_flags: list[str] = []
+ if server_caps.get("supports_cache_ram"):
+ cmd.extend(["--cache-ram", "0"])
+ else:
+ unsupported_cache_flags.append("--cache-ram")
+ if server_caps.get("supports_ctx_checkpoints"):
+ cmd.extend(["--ctx-checkpoints", "0"])
+ else:
+ unsupported_cache_flags.append("--ctx-checkpoints")
+ if server_caps.get("supports_no_cache_prompt"):
+ cmd.append("--no-cache-prompt")
+ else:
+ unsupported_cache_flags.append("--no-cache-prompt")
+ if unsupported_cache_flags:
+ logger.info(
+ "Skipping unsupported Windows cache flags for llama-server: %s",
+ ", ".join(unsupported_cache_flags),
+ )
+
# User pass-through args go last so llama.cpp's last-wins parsing
# lets the user override Studio's auto-set flags. Already
# validated by the route via validate_extra_args().
@@ -4101,9 +4164,6 @@ class LlamaCppBackend:
logger.info(f"Starting llama-server: {' '.join(_log_cmd)}")
# Library paths so llama-server finds its shared libs and CUDA DLLs.
- import os
- import sys
-
env = child_env_without_native_path_secret()
binary_dir = str(Path(binary).parent)
@@ -4131,6 +4191,14 @@ class LlamaCppBackend:
existing_path = env.get("PATH", "")
env["PATH"] = ";".join(path_dirs) + ";" + existing_path
+ # Windows + full offload: PASSIVE OMP + 2 threads stop
+ # spin-wait burning CPU. CPU/partial offload keeps
+ # default OMP parallelism. #5692.
+ if full_offload_tuning_active:
+ env.setdefault("OMP_WAIT_POLICY", "PASSIVE")
+ if not threads_overridden:
+ env.setdefault("OMP_NUM_THREADS", "2")
+
# ROCm: the prebuilt bundles rocblas.dll but NOT the Tensile
# kernel files (rocblas/library/*.dat + *.hsaco); the DLL
# searches <binary_dir>/rocblas/library/ which doesn't exist
@@ -5512,7 +5580,7 @@ class LlamaCppBackend:
reasoning_effort: Optional[str] = None,
preserve_thinking: Optional[bool] = None,
seed: Optional[int] = None,
- ) -> Generator[str | dict, None, None]:
+ ) -> Generator[Union[str, dict], None, None]:
"""
Send a chat completion to llama-server and stream tokens back.
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 2f9ed35936d..3e13774639c 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1194,6 +1194,23 @@ async def _await_cancel_then_close(cancel_event, resp) -> None:
return
+async def _await_disconnect_then_close(request, resp, cancel_event) -> None:
+ """Close ``resp`` on client disconnect; sets ``cancel_event`` first so
+ the streamer's RemoteProtocolError handler treats it as cancellation.
+ Catches aborts the in-loop /cancel check misses during prefill. #5692.
+ """
+ try:
+ while not await request.is_disconnected():
+ await asyncio.sleep(0.1)
+ cancel_event.set()
+ try:
+ await resp.aclose()
+ except Exception as e:
+ logger.debug("Failed to close response on disconnect: %s", e)
+ except asyncio.CancelledError:
+ return
+
+
# Centralized local/server tool nudge. Keep render_html guidance gated to turns
# where the artifact tool is actually present in the tool schema; otherwise
# small local models can hallucinate a missing tool call instead of following
@@ -2302,7 +2319,7 @@ async def generate_stream(
media_type = "text/event-stream",
headers = {
"Cache-Control": "no-cache",
- "Connection": "keep-alive",
+ "Connection": "close",
},
)
@@ -3696,7 +3713,7 @@ async def openai_chat_completions(
media_type = "text/event-stream",
headers = {
"Cache-Control": "no-cache",
- "Connection": "keep-alive",
+ "Connection": "close",
"X-Accel-Buffering": "no",
},
)
@@ -4117,7 +4134,7 @@ async def openai_chat_completions(
media_type = "text/event-stream",
headers = {
"Cache-Control": "no-cache",
- "Connection": "keep-alive",
+ "Connection": "close",
"X-Accel-Buffering": "no",
},
)
@@ -4260,7 +4277,7 @@ async def openai_chat_completions(
media_type = "text/event-stream",
headers = {
"Cache-Control": "no-cache",
- "Connection": "keep-alive",
+ "Connection": "close",
"X-Accel-Buffering": "no",
},
)
@@ -4664,7 +4681,7 @@ async def openai_chat_completions(
media_type = "text/event-stream",
headers = {
"Cache-Control": "no-cache",
- "Connection": "keep-alive",
+ "Connection": "close",
"X-Accel-Buffering": "no",
},
)
@@ -4865,7 +4882,7 @@ async def openai_chat_completions(
media_type = "text/event-stream",
headers = {
"Cache-Control": "no-cache",
- "Connection": "keep-alive",
+ "Connection": "close",
"X-Accel-Buffering": "no",
},
)
@@ -5120,8 +5137,12 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge
client = httpx.AsyncClient(timeout = _llama_streaming_generation_timeout())
resp = None
bytes_iter = None
+ disconnect_event = threading.Event()
+ disconnect_watcher = None
try:
- req = client.build_request("POST", target_url, json = body)
+ req = client.build_request(
+ "POST", target_url, json = body, headers = {"Connection": "close"}
+ )
first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S
resp = await _send_stream_with_preheader_cancel(client, req, request = request)
if resp is None:
@@ -5130,10 +5151,14 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge
err_bytes = await resp.aread()
err_text = err_bytes.decode("utf-8", errors = "replace")
raise RuntimeError(f"llama-server returned {resp.status_code}: {err_text}")
+ disconnect_watcher = asyncio.create_task(
+ _await_disconnect_then_close(request, resp, disconnect_event)
+ )
bytes_iter = resp.aiter_bytes()
buffer = b""
async for chunk in _aiter_llama_stream_items(
bytes_iter,
+ cancel_event = disconnect_event,
request = request,
first_token_deadline = first_token_deadline,
response = resp,
@@ -5144,19 +5169,33 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge
out = _cmpl_stream_event_out(event, _include_usage)
if out is not None:
yield out + b"\n\n"
- if buffer:
+ if not disconnect_event.is_set() and buffer:
out = _cmpl_stream_event_out(buffer, _include_usage)
if out is not None:
# Re-add the SSE separator the split consumed, so a final
# event arriving without a trailing blank line is still
# terminated for the client's parser.
yield out + b"\n\n"
+ except (httpx.RemoteProtocolError, httpx.ReadError, httpx.CloseError) as e:
+ if not disconnect_event.is_set():
+ logger.error("openai_completions stream error: %s", e)
+ error_chunk = _openai_stream_error_chunk(e)
+ yield f"data: {json.dumps(error_chunk)}\n\n".encode("utf-8")
+ return
except Exception as e:
+ if disconnect_event.is_set():
+ return
logger.error("openai_completions stream error: %s", e)
error_chunk = _openai_stream_error_chunk(e)
yield f"data: {json.dumps(error_chunk)}\n\n".encode("utf-8")
return
finally:
+ if disconnect_watcher is not None:
+ disconnect_watcher.cancel()
+ try:
+ await disconnect_watcher
+ except (asyncio.CancelledError, Exception):
+ pass
if bytes_iter is not None:
try:
await bytes_iter.aclose()
@@ -6063,8 +6102,12 @@ async def _responses_stream(
client = httpx.AsyncClient(timeout = _llama_streaming_generation_timeout())
resp = None
lines_iter = None
+ disconnect_event = threading.Event()
+ disconnect_watcher = None
try:
- req = client.build_request("POST", target_url, json = body)
+ req = client.build_request(
+ "POST", target_url, json = body, headers = {"Connection": "close"}
+ )
first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S
try:
resp = await _send_stream_with_preheader_cancel(client, req, request = request)
@@ -6117,9 +6160,13 @@ async def _responses_stream(
)
return
+ disconnect_watcher = asyncio.create_task(
+ _await_disconnect_then_close(request, resp, disconnect_event)
+ )
lines_iter = resp.aiter_lines()
async for raw_line in _aiter_llama_stream_items(
lines_iter,
+ cancel_event = disconnect_event,
request = request,
first_token_deadline = first_token_deadline,
response = resp,
@@ -6240,7 +6287,18 @@ async def _responses_stream(
if usage:
input_tokens = usage.get("prompt_tokens", input_tokens)
output_tokens = usage.get("completion_tokens", output_tokens)
+ except (httpx.RemoteProtocolError, httpx.ReadError, httpx.CloseError) as e:
+ if not disconnect_event.is_set():
+ logger.error("responses stream error: %s", e)
+ status_code = 400 if _classify_llama_generation_error(e) is not None else 500
+ yield _sse(
+ "response.failed",
+ _failed_response_payload(e, status_code),
+ )
+ return
except Exception as e:
+ if disconnect_event.is_set():
+ return
logger.error("responses stream error: %s", e)
status_code = 400 if _classify_llama_generation_error(e) is not None else 500
yield _sse(
@@ -6249,6 +6307,12 @@ async def _responses_stream(
)
return
finally:
+ if disconnect_watcher is not None:
+ disconnect_watcher.cancel()
+ try:
+ await disconnect_watcher
+ except (asyncio.CancelledError, Exception):
+ pass
if lines_iter is not None:
try:
await lines_iter.aclose()
@@ -6264,6 +6328,9 @@ async def _responses_stream(
except Exception:
pass
+ if disconnect_event.is_set():
+ return
+
final_reasoning, final_visible = extractor.finish()
if final_reasoning:
for event in _ensure_reasoning_open():
@@ -6470,7 +6537,7 @@ async def _responses_stream(
media_type = "text/event-stream",
headers = {
"Cache-Control": "no-cache",
- "Connection": "keep-alive",
+ "Connection": "close",
"X-Accel-Buffering": "no",
},
)
@@ -7071,7 +7138,7 @@ async def _anthropic_tool_stream(
media_type = "text/event-stream",
headers = {
"Cache-Control": "no-cache",
- "Connection": "keep-alive",
+ "Connection": "close",
"X-Accel-Buffering": "no",
},
)
@@ -7138,7 +7205,7 @@ async def _anthropic_plain_stream(
media_type = "text/event-stream",
headers = {
"Cache-Control": "no-cache",
- "Connection": "keep-alive",
+ "Connection": "close",
"X-Accel-Buffering": "no",
},
)
@@ -7472,8 +7539,11 @@ async def _anthropic_passthrough_stream(
resp = None
lines_iter = None
cancel_watcher = None
+ disconnect_watcher = None
try:
- req = client.build_request("POST", target_url, json = body)
+ req = client.build_request(
+ "POST", target_url, json = body, headers = {"Connection": "close"}
+ )
first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S
resp = await _send_stream_with_preheader_cancel(
client, req, cancel_event, request = request
@@ -7502,11 +7572,12 @@ async def _anthropic_passthrough_stream(
)
return
- # See _openai_passthrough_stream for rationale: aiter_lines()
- # blocks during llama-server prefill, so the in-loop cancel
- # check is unreachable until the first SSE chunk arrives.
- # The watcher closes `resp` on cancel, raising in aiter_lines.
+ # Watchers unblock aiter_lines() during prefill, before in-loop
+ # cancel/disconnect checks can run.
cancel_watcher = asyncio.create_task(_await_cancel_then_close(cancel_event, resp))
+ disconnect_watcher = asyncio.create_task(
+ _await_disconnect_then_close(request, resp, cancel_event)
+ )
lines_iter = resp.aiter_lines()
async for raw_line in _aiter_llama_stream_items(
lines_iter,
@@ -7555,6 +7626,12 @@ async def _anthropic_passthrough_stream(
await cancel_watcher
except (asyncio.CancelledError, Exception):
pass
+ if disconnect_watcher is not None:
+ disconnect_watcher.cancel()
+ try:
+ await disconnect_watcher
+ except (asyncio.CancelledError, Exception):
+ pass
if lines_iter is not None:
try:
await lines_iter.aclose()
@@ -7579,7 +7656,7 @@ async def _anthropic_passthrough_stream(
media_type = "text/event-stream",
headers = {
"Cache-Control": "no-cache",
- "Connection": "keep-alive",
+ "Connection": "close",
"X-Accel-Buffering": "no",
},
)
@@ -7994,7 +8071,9 @@ async def _openai_passthrough_stream(
)
while True:
try:
- req = client.build_request("POST", target_url, json = body)
+ req = client.build_request(
+ "POST", target_url, json = body, headers = {"Connection": "close"}
+ )
first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S
resp = await _send_stream_with_preheader_cancel(
client, req, cancel_event, request = request
@@ -8064,13 +8143,12 @@ async def _openai_passthrough_stream(
# save resp.aiter_lines() so the finally block can aclose() it on
# our task. See that function for full rationale.
lines_iter = None
- # During llama-server prefill, `aiter_lines()` blocks until the
- # first SSE chunk arrives. The in-loop `cancel_event` check can't
- # fire until then -- the exact proxy/Colab scenario the cancel POST
- # recovers from. Run a tiny watcher that closes `resp` as soon as
- # cancel fires, unblocking the iterator with a RemoteProtocolError
- # caught in the except clause below.
+ # Watchers unblock aiter_lines() during prefill, before in-loop
+ # cancel/disconnect checks can run.
cancel_watcher = asyncio.create_task(_await_cancel_then_close(cancel_event, resp))
+ disconnect_watcher = asyncio.create_task(
+ _await_disconnect_then_close(request, resp, cancel_event)
+ )
try:
lines_iter = resp.aiter_lines()
async for raw_line in _aiter_llama_stream_items(
@@ -8101,6 +8179,8 @@ async def _openai_passthrough_stream(
if not cancel_event.is_set():
raise
except Exception as e:
+ if cancel_event.is_set():
+ return
# 200 headers already flushed; errors must go in the SSE body.
logger.error("openai passthrough stream error: %s", e)
err = _openai_stream_error_chunk(e)
@@ -8111,6 +8191,11 @@ async def _openai_passthrough_stream(
await cancel_watcher
except (asyncio.CancelledError, Exception):
pass
+ disconnect_watcher.cancel()
+ try:
+ await disconnect_watcher
+ except (asyncio.CancelledError, Exception):
+ pass
if lines_iter is not None:
try:
await lines_iter.aclose()
@@ -8131,7 +8216,7 @@ async def _openai_passthrough_stream(
media_type = "text/event-stream",
headers = {
"Cache-Control": "no-cache",
- "Connection": "keep-alive",
+ "Connection": "close",
"X-Accel-Buffering": "no",
},
)
diff --git a/studio/backend/tests/test_llama_cpp_mtp_detection.py b/studio/backend/tests/test_llama_cpp_mtp_detection.py
index b00cd7169ee..2cc0fb41843 100644
--- a/studio/backend/tests/test_llama_cpp_mtp_detection.py
+++ b/studio/backend/tests/test_llama_cpp_mtp_detection.py
@@ -9,6 +9,7 @@ the _already_in_target_state mirror that prevents needless reloads.
from __future__ import annotations
+import inspect
import struct
import sys
import types as _types
@@ -52,9 +53,12 @@ import pytest
from core.inference.llama_cpp import (
LlamaCppBackend,
+ _GPU_OFFLOAD_OVERRIDE_FLAGS,
+ _THREAD_OVERRIDE_FLAGS,
_backfill_usage_from_timings,
_build_ngram_mod_flags,
_canonicalize_spec_mode,
+ _extra_args_set_any_flag,
_extra_args_set_spec_type,
_is_mtp_model_name,
)
@@ -315,6 +319,46 @@ def test_extra_args_set_spec_type_passes_on_non_spec_type_args(extra_args):
assert _extra_args_set_spec_type(extra_args) is False
+ "extra_args",
+ [
+ ["-ngl", "12"],
+ ["--gpu-layers", "12"],
+ ["--n-gpu-layers=12"],
+ ["-fit", "off"],
+ ["--fit=off"],
+ ],
+)
+def test_extra_args_detect_gpu_offload_overrides(extra_args):
+ assert _extra_args_set_any_flag(extra_args, _GPU_OFFLOAD_OVERRIDE_FLAGS) is True
+
+
[email protected]("extra_args", [["-t", "8"], ["--threads=8"]])
+def test_extra_args_detect_thread_overrides(extra_args):
+ assert _extra_args_set_any_flag(extra_args, _THREAD_OVERRIDE_FLAGS) is True
+
+
+def test_windows_full_offload_flags_use_current_llama_server_args():
+ src = inspect.getsource(LlamaCppBackend.load_model)
+ stale_checkpoint_flag = "--checkpoint-" + "every-n-tokens"
+ assert '"--cache-ram"' in src
+ assert '"--ctx-checkpoints"' in src
+ assert '"--no-cache-prompt"' in src
+ assert stale_checkpoint_flag not in src
+
+
+def test_load_model_sets_threads_once():
+ src = inspect.getsource(LlamaCppBackend.load_model)
+ assert src.count('cmd.extend(["--threads", str(') == 1
+
+
+def test_llama_cpp_annotations_stay_python39_safe():
+ src = inspect.getsource(LlamaCppBackend.generate_chat_completion)
+ helper_src = inspect.getsource(_extra_args_set_any_flag)
+ assert "Generator[str | dict" not in src
+ assert "set[str] | frozenset[str]" not in helper_src
+
+
def test_already_in_target_state_user_spec_type_override_matches_clean_backend():
# User --spec-type none suppressed auto-MTP; repeat /load must not re-promote.
backend = _mtp_backend(
@@ -554,6 +598,9 @@ def test_probe_server_capabilities_handles_missing_binary():
caps = LlamaCppBackend.probe_server_capabilities("/no/such/llama-server")
assert caps["found"] is False
assert caps["supports_mtp"] is False
+ assert caps["supports_cache_ram"] is False
+ assert caps["supports_ctx_checkpoints"] is False
+ assert caps["supports_no_cache_prompt"] is False
# ngram-mod flag flavor detection (new vs legacy llama-server).
@@ -588,6 +635,12 @@ _LEGACY_HELP = """\
--spec-type none,ngram-mod,ngram-simple comma-separated list of types of speculative decoding to use
"""
+_CACHE_FLAGS_HELP = """\
+--cache-ram N store prompt cache in RAM (default: 0)
+--ctx-checkpoints N number of context checkpoints (default: 0)
+--no-cache-prompt do not reuse prompt cache
+"""
+
@_NEEDS_BASH
def test_probe_detects_post_rename_ngram_mod_flavor(tmp_path):
@@ -634,6 +687,26 @@ def test_probe_no_ngram_mod_on_minimal_binary(tmp_path):
assert caps["supports_ngram_mod"] is False
+@_NEEDS_BASH
+def test_probe_detects_windows_cache_flags(tmp_path):
+ fake = _make_fake_llama_server(tmp_path / "llama-server", _CACHE_FLAGS_HELP)
+ _clear_caps_cache()
+ caps = LlamaCppBackend.probe_server_capabilities(str(fake))
+ assert caps["supports_cache_ram"] is True
+ assert caps["supports_ctx_checkpoints"] is True
+ assert caps["supports_no_cache_prompt"] is True
+
+
+@_NEEDS_BASH
+def test_probe_reports_windows_cache_flags_absent_for_older_binary(tmp_path):
+ fake = _make_fake_llama_server(tmp_path / "llama-server", "--threads N\n")
+ _clear_caps_cache()
+ caps = LlamaCppBackend.probe_server_capabilities(str(fake))
+ assert caps["supports_cache_ram"] is False
+ assert caps["supports_ctx_checkpoints"] is False
+ assert caps["supports_no_cache_prompt"] is False
+
+
def test_build_ngram_mod_flags_new():
flags = _build_ngram_mod_flags({"ngram_mod_flavor": "new"})
assert flags == [
diff --git a/tests/studio/test_stream_cancel_registration_timing.py b/tests/studio/test_stream_cancel_registration_timing.py
index 6bd74f00de3..3fd91a51889 100644
--- a/tests/studio/test_stream_cancel_registration_timing.py
+++ b/tests/studio/test_stream_cancel_registration_timing.py
@@ -69,6 +69,21 @@ def _finalbody_has_tracker_exit(finalbody) -> bool:
return False
+def _async_function(name: str) -> ast.AsyncFunctionDef:
+ for node in ast.walk(_TREE):
+ if isinstance(node, ast.AsyncFunctionDef) and node.name == name:
+ return node
+ raise AssertionError(f"{name} handler missing")
+
+
+def _calls_name(node: ast.AST, name: str) -> bool:
+ for sub in ast.walk(node):
+ if isinstance(sub, ast.Call) and isinstance(sub.func, ast.Name):
+ if sub.func.id == name:
+ return True
+ return False
+
+
# ── Structural tests ─────────────────────────────────────────
@@ -160,6 +175,25 @@ def test_streaming_responses_have_no_background_task():
)
+def test_direct_llama_server_streams_install_disconnect_watcher():
+ required = {
+ "openai_completions",
+ "_responses_stream",
+ "_anthropic_passthrough_stream",
+ "_openai_passthrough_stream",
+ }
+ missing = [
+ name
+ for name in sorted(required)
+ if not _calls_name(_async_function(name), "_await_disconnect_then_close")
+ ]
+ assert not missing, (
+ "Direct httpx streams to llama-server must close the upstream response "
+ "when the downstream client disconnects during prefill. Missing in: "
+ f"{missing}"
+ )
+
+
# ── Behavioral helpers ───────────────────────────────────────
_WANTED = {