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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: keep a slow model load alive through a proxy timeout (#7635)
Daniel Hand1127c09af2f
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 4a1a1d60e9e..974cf0ba480 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -8295,7 +8295,8 @@ class LlamaCppBackend:f"est. KV cache: {kv_cache_bytes / (1024**3):.1f} GB, "f"{_mtp_note}"f"context: {effective_ctx}, "- f"GPUs free: {gpus}, selected: {gpu_indices}, fit: {use_fit}"+ # --fit flag state, not "does it fit": off means this subset provably fits.+ f"GPUs free: {gpus}, selected: {gpu_indices}, --fit: {'on' if use_fit else 'off'}")except Exception as e:logger.warning(f"GPU selection failed ({e}), using --fit on")diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 2fb8ea00fce..ca54be44c72 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -11,6 +11,7 @@ import timeimport uuidfrom pathlib import Pathfrom fastapi import APIRouter, Depends, HTTPException, Request, status+from fastapi.encoders import jsonable_encoderfrom fastapi.responses import StreamingResponse, JSONResponse, Responsefrom starlette.requests import ClientDisconnectfrom typing import Any, Callable, List, Literal, Optional, Union@@ -1565,6 +1566,74 @@ def _tracked_cancel_unstarted_cleanup(tracker):return _cleanup+# Cloudflare quick tunnels (--secure) drop a request whose origin has sent no body+# bytes for ~100s, and a 600 GB GGUF load runs 100-330s. Measured on a real quick+# tunnel: headers at t=0 with no body still 524s, one space every 20s survives. So+# a slow call commits a 200 and pads until its payload is ready; leading whitespace+# is legal JSON, so clients parse the body as-is.+_TUNNEL_KEEPALIVE_AFTER_S = 15.0+_TUNNEL_KEEPALIVE_EVERY_S = 20.0++# Underscored so it cannot collide with a real field or the OpenAI ``error`` envelope.+_DEFERRED_ERROR_KEY = "_deferred_error"+++def _deferred_error_body(status_code: int, detail) -> bytes:+ body = {_DEFERRED_ERROR_KEY: {"status_code": status_code, "detail": detail}}+ return json.dumps(body).encode()+++async def _tunnel_safe_json(coro, *, label: str):+ """Await ``coro``, padding the response body if it outruns the tunnel timer.++ A call finishing within ``_TUNNEL_KEEPALIVE_AFTER_S`` keeps the current+ contract exactly, HTTPException status code included; every early failure+ (validation, unknown identifier, download-manager and sidecar 409s) raises in+ that window. Only a slower call switches to a padded stream, and it must+ report a late failure in the body because the status line is already gone.++ A client disconnect does not cancel the work: the model stays resident, as+ it does today.+ """+ task = asyncio.ensure_future(coro)+ # A client that disconnects mid-pad leaves nobody to await the task, and an+ # unretrieved exception logs "Task exception was never retrieved". Retrieving+ # it here does not consume it: result() below still raises.+ task.add_done_callback(lambda t: t.cancelled() or t.exception())+ done, _ = await asyncio.wait({task}, timeout = _TUNNEL_KEEPALIVE_AFTER_S)+ if done:+ return task.result() # re-raises exactly as an un-wrapped await would++ logger.info(+ f"{label} exceeded {_TUNNEL_KEEPALIVE_AFTER_S:.0f}s; "+ "padding the response so a proxy cannot time it out"+ )++ async def _body():+ while True:+ finished, _ = await asyncio.wait({task}, timeout = _TUNNEL_KEEPALIVE_EVERY_S)+ if not finished:+ yield b" "+ continue+ try:+ payload = task.result()+ except HTTPException as exc:+ logger.info(f"{label} failed with {exc.status_code} after the response committed")+ yield _deferred_error_body(exc.status_code, exc.detail)+ except Exception as exc:+ logger.exception(f"{label} failed after the response was committed")+ yield _deferred_error_body(500, f"{type(exc).__name__}: {exc}")+ else:+ yield json.dumps(jsonable_encoder(payload)).encode()+ return++ return _SameTaskStreamingResponse(+ _body(),+ media_type = "application/json",+ headers = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},+ )++async def _aclose_stream_resources(*,watchers = (),@@ -5399,6 +5468,19 @@ async def load_model(GGUF models load via llama-server (llama.cpp) instead of Unsloth."""+ return await _tunnel_safe_json(+ load_model_gated(request, fastapi_request, current_subject), label = "Model load"+ )+++async def load_model_gated(request: LoadRequest, fastapi_request: Request, current_subject: str):+ """Everything ``POST /load`` does except the tunnel-safe padding.++ In-process callers (preview) must await THIS, not the route: the route's slow+ path returns a StreamingResponse nobody in-process drains, so awaiting it would+ return mid-load and hide a late failure in an unread body. This blocks until the+ model is resident and raises the real exception.+ """# A sidecar install that has reserved the swap must not lose to a load that# then gets unloaded by the pre-swap teardown. Rechecked under the gate: an# install can reserve while this request queues on the gate, so the pre-gate@@ -6094,10 +6176,11 @@ async def _load_model_impl(current_request_counted = current_request_counted,timeout_s = _POST_CANCEL_DRAIN_TIMEOUT_S,)- # Unload any active GGUF model first+ # Unload any active GGUF model first, off-loop: a 600 GB teardown measures+ # 160s and on-loop would block _tunnel_safe_json's own padding.if llama_backend.is_loaded:logger.info("Unloading GGUF model before loading Unsloth model")- llama_backend.unload_model()+ await asyncio.to_thread(llama_backend.unload_model)# Shut down any export subprocess to free VRAMtry:@@ -6868,6 +6951,19 @@ async def install_latest_transformers_route(@router.post("/unload", response_model = UnloadResponse)async def unload_model(request: UnloadRequest, current_subject: str = Depends(get_current_subject)):+ """Unload a model from memory.++ Padded like /load: a 600 GB GGUF teardown measures 160s, past the proxy timer.+ See ``_tunnel_safe_json``. No in-process caller today; a future one must await+ ``_unload_model_impl`` (as preview awaits ``load_model_gated``), since the padded+ path returns a StreamingResponse, not the payload.+ """+ return await _tunnel_safe_json(+ _unload_model_impl(request, current_subject), label = "Model unload"+ )+++async def _unload_model_impl(request: UnloadRequest, current_subject: str):"""Unload a model from memory.Routes to the correct backend (llama-server for GGUF, Unsloth otherwise).@@ -6967,7 +7063,9 @@ async def unload_model(request: UnloadRequest, current_subject: str = Depends(geawait _drain_and_recancel_before_teardown(force = request.force_cancel_active, action = "Unloading the model")- llama_backend.unload_model()+ # Off-loop like the in-flight branch above: a 160s teardown on the+ # loop would block this route's own padding.+ await asyncio.to_thread(llama_backend.unload_model)note_model_unloaded()api_monitor.record_lifecycle(event = "unload",diff --git a/studio/backend/routes/preview.py b/studio/backend/routes/preview.pyindex 5acf0394012..06ccb6b4db2 100644--- a/studio/backend/routes/preview.py+++ b/studio/backend/routes/preview.py@@ -19,7 +19,7 @@ from auth.storage import DEFAULT_ADMIN_USERNAMEfrom models.inference import ChatCompletionRequest, LoadRequestfrom routes.inference import (disable_openai_auto_switch_for_request,- load_model,+ load_model_gated,openai_chat_completions,)from state.tool_policy import tools_force_disabled@@ -165,7 +165,10 @@ async def _serve_chat(await _preview_lock.acquire()keep_locked = Falsetry:- await load_model(LoadRequest(model_path = str(path)), request, DEFAULT_ADMIN_USERNAME)+ # The gated coroutine, not the /load route: the route's padding returns a+ # StreamingResponse while the checkpoint is still loading, so the chat below+ # would run against the previous model (or none).+ await load_model_gated(LoadRequest(model_path = str(path)), request, DEFAULT_ADMIN_USERNAME)# Beats a process-wide `--enable-tools` (enable_tools=False alone wouldn't).with tools_force_disabled():response = await openai_chat_completions(payload, request, DEFAULT_ADMIN_USERNAME)diff --git a/studio/backend/tests/test_log_filter_no_truncation.py b/studio/backend/tests/test_log_filter_no_truncation.pyindex 52ffa2ba32d..256121e2015 100644--- a/studio/backend/tests/test_log_filter_no_truncation.py+++ b/studio/backend/tests/test_log_filter_no_truncation.py@@ -21,7 +21,7 @@ class TestNoTruncation:# Mirrors the f-string at studio/backend/core/inference/llama_cpp.py:2117event = ("GGUF size: 232.9 GB, est. KV cache: 87.0 GB, context: 259072, "- "GPUs free: [(0, 80000), (1, 80000)], selected: [0, 1], fit: False"+ "GPUs free: [(0, 80000), (1, 80000)], selected: [0, 1], --fit: off")out = _run({"event": event})assert out["event"] == eventdiff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex e29fc07a958..89a65a1030d 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -1598,9 +1598,10 @@ def test_idle_alias_reload_preserves_override_via_advertised_id(monkeypatch):def test_load_route_holds_lifecycle_gate(monkeypatch):# Lock the manual /load gate against silent revert: the route must wrap the# load in inference_lifecycle_gate so idle-unload can't fire mid-load.+ # Asserted on the gated coroutine: the route only adds the padded response.import inspect- src = inspect.getsource(inference_route.load_model)+ src = inspect.getsource(inference_route.load_model_gated)assert "inference_lifecycle_gate" in srcassert "_load_model_impl" in src@@ -1623,7 +1624,9 @@ def test_model_replacements_recheck_sidecar_swap_before_either_backend_is_unloadstandard_wait = src.index("await _wait_for_model_switch_idle", standard_branch)standard_sidecar_check = src.index("_raise_if_sidecar_swap_in_progress()", standard_wait)standard_cancel = src.index("on_reload_confirmed(cancel = True)", standard_wait)- unload_gguf = src.index("llama_backend.unload_model()", standard_wait)+ # No parens: both teardowns are asyncio.to_thread args (on-loop a 160s one would+ # block /load's tunnel padding).+ unload_gguf = src.index("llama_backend.unload_model", standard_wait)assert already_loaded < gguf_wait < gguf_sidecar_check < gguf_cancel < unload_unslothassert standard_branch < standard_wait < standard_sidecar_check@@ -3182,8 +3185,9 @@ def test_note_model_unloaded_clears_reload_stash(monkeypatch):def test_unload_route_clears_reload_stash(monkeypatch):# The /unload route must clear the stash on both the GGUF and non-GGUF branches.+ # Asserted on the impl: the route only adds the padded response.import inspect- src = inspect.getsource(inference_route.unload_model)+ src = inspect.getsource(inference_route._unload_model_impl)assert src.count("note_model_unloaded()") >= 2diff --git a/studio/backend/tests/test_preview_routes.py b/studio/backend/tests/test_preview_routes.pyindex 8fa3093d046..0770ad32fd0 100644--- a/studio/backend/tests/test_preview_routes.py+++ b/studio/backend/tests/test_preview_routes.py@@ -4,7 +4,7 @@"""Security smoke for the public /p preview routes.Exercises the route layer with a real ``preview_router`` while stubbing the-expensive model calls (``load_model`` / ``openai_chat_completions``). Covers the+expensive model calls (``load_model_gated`` / ``openai_chat_completions``). Covers thepublic-surface guarantees: HMAC capability gating (a valid ``?k=`` token orBearer credential is required; missing/invalid/wrong-ref tokens 404 before anymodel load), path-traversal rejection, request sanitization (tools / provider@@ -96,7 +96,7 @@ def client(tmp_path, monkeypatch, captured):captured["payload"] = payloadreturn {"ok": True}- monkeypatch.setattr(preview, "load_model", _fake_load_model)+ monkeypatch.setattr(preview, "load_model_gated", _fake_load_model)monkeypatch.setattr(preview, "openai_chat_completions", _fake_chat)app = FastAPI()@@ -291,7 +291,7 @@ def test_merged_checkpoint_strips_use_adapter(tmp_path, monkeypatch, captured):captured["payload"] = payloadreturn {"ok": True}- monkeypatch.setattr(preview, "load_model", _fake_load)+ monkeypatch.setattr(preview, "load_model_gated", _fake_load)monkeypatch.setattr(preview, "openai_chat_completions", _fake_chat)app = FastAPI()@@ -325,7 +325,7 @@ def test_streaming_holds_lock_until_drained(tmp_path, monkeypatch, captured):async def _fake_chat(payload, request, subject):return StreamingResponse(_gen())- monkeypatch.setattr(preview, "load_model", _fake_load_model)+ monkeypatch.setattr(preview, "load_model_gated", _fake_load_model)monkeypatch.setattr(preview, "openai_chat_completions", _fake_chat)async def _run():diff --git a/studio/backend/tests/test_tunnel_safe_long_post.py b/studio/backend/tests/test_tunnel_safe_long_post.pynew file mode 100644index 00000000000..3f8d6e0aa57--- /dev/null+++ b/studio/backend/tests/test_tunnel_safe_long_post.py@@ -0,0 +1,579 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A load slower than a proxy's idle timer still reaches the client.++Cloudflare quick tunnels (`--secure`) drop a request whose origin has sent no body+bytes for ~100s, and a 600 GB GGUF load runs 100-330s, so the browser reported+"Request failed" on loads the server completed with a 200. Measured on a real+quick tunnel:++ * no body for 150s -> 524+ * headers at t=0, no body -> 524 (headers are NOT enough)+ * one byte at t=90s, then silence -> killed ~125s later, client sees 200 with an+ EMPTY body+ * one space every 20s -> survives, body intact++So the padding must be continuous, and a failure found after the status commits+can only travel in the body.++Two consequences below: the padded reply is a StreamingResponse, so an in-process+caller that drains no body awaits ``load_model_gated`` instead; and a client that+treats any 200 as success has to learn the in-band failure key.+"""++from __future__ import annotations++import asyncio+import contextlib+import json+import re+import sys+import threading+import time+from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import HTTPException+from fastapi.responses import StreamingResponse++_backend_root = Path(__file__).resolve().parent.parent+_repo_root = _backend_root.parents[1]+if str(_backend_root) not in sys.path:+ sys.path.insert(0, str(_backend_root))+++def route(monkeypatch):+ from routes import inference as route_mod++ # Keep the test fast; the real defaults are guarded by the last test below.+ monkeypatch.setattr(route_mod, "_TUNNEL_KEEPALIVE_AFTER_S", 0.05)+ monkeypatch.setattr(route_mod, "_TUNNEL_KEEPALIVE_EVERY_S", 0.02)+ return route_mod+++async def _collect(response):+ """Chunks a client would receive, in order."""+ return [chunk async for chunk in response.body_iterator]+++async def _collect_into(response, sink):+ """As _collect, but visible to another thread while the stream is still open."""+ async for chunk in response.body_iterator:+ sink.append(chunk)+ return sink+++def test_a_fast_call_keeps_the_plain_response(route):+ async def quick():+ return {"status": "loaded"}++ result = asyncio.run(route._tunnel_safe_json(quick(), label = "t"))+ # Not a Response: FastAPI serialises it through response_model as before.+ assert result == {"status": "loaded"}+++def test_a_fast_failure_keeps_its_status_code(route):+ async def boom():+ raise HTTPException(status_code = 409, detail = "busy")++ with pytest.raises(HTTPException) as excinfo:+ asyncio.run(route._tunnel_safe_json(boom(), label = "t"))+ assert excinfo.value.status_code == 409+ assert excinfo.value.detail == "busy"+++def test_a_slow_call_pads_then_sends_valid_json(route):+ async def slow():+ await asyncio.sleep(0.2)+ return {"status": "loaded", "model": "unsloth/Kimi-K3-GGUF"}++ async def run():+ response = await route._tunnel_safe_json(slow(), label = "t")+ return response, await _collect(response)++ response, chunks = asyncio.run(run())+ assert response.media_type == "application/json"+ assert response.headers["x-accel-buffering"] == "no"+ assert chunks[0] == b" "+ assert len(chunks) > 2, "a call this slow must be padded more than once"+ assert all(c == b" " for c in chunks[:-1])+ body = b"".join(chunks)+ # Leading whitespace is legal JSON, which is why no client had to change.+ assert json.loads(body) == {"status": "loaded", "model": "unsloth/Kimi-K3-GGUF"}+++def test_a_slow_failure_travels_in_the_body(route):+ async def slow_boom():+ await asyncio.sleep(0.2)+ raise HTTPException(status_code = 500, detail = "llama-server died")++ async def run():+ return await _collect(await route._tunnel_safe_json(slow_boom(), label = "t"))++ body = json.loads(b"".join(asyncio.run(run())))+ assert body["_deferred_error"] == {"status_code": 500, "detail": "llama-server died"}+++def test_an_unexpected_slow_failure_becomes_a_500(route):+ async def slow_boom():+ await asyncio.sleep(0.2)+ raise RuntimeError("out of VRAM")++ async def run():+ return await _collect(await route._tunnel_safe_json(slow_boom(), label = "t"))++ body = json.loads(b"".join(asyncio.run(run())))+ assert body["_deferred_error"]["status_code"] == 500+ assert "out of VRAM" in body["_deferred_error"]["detail"]+++def test_the_work_survives_a_client_disconnect(route):+ """Abandoning the stream must not cancel the load: the model still lands."""+ finished = []++ async def slow():+ await asyncio.sleep(0.2)+ finished.append(True)+ return {"status": "loaded"}++ async def run():+ response = await route._tunnel_safe_json(slow(), label = "t")+ it = response.body_iterator+ assert await it.__anext__() == b" " # one pad, then the client vanishes+ await it.aclose()+ await asyncio.sleep(0.4)++ asyncio.run(run())+ assert finished == [True]+++# ── Direct (in-process) callers must not get the padded response ──────────────+++def slow_load(route, monkeypatch):+ """/load whose work outruns the keepalive timer; records the finished model paths."""+ finished = []++ async def _slow_impl(request, fastapi_request, current_subject, **kwargs):+ await asyncio.sleep(0.2) # >> the fixture's 0.05s keepalive threshold+ finished.append(request.model_path)+ return {"status": "loaded", "model": request.model_path}++ monkeypatch.setattr(route, "_load_model_impl", _slow_impl)+ # The sidecar-swap guard reads real install state; it has its own tests.+ monkeypatch.setattr(route, "_raise_if_sidecar_swap_in_progress", lambda: None)+ return finished+++def _load_request(model_path = "unsloth/Kimi-K3-GGUF"):+ from models.inference import LoadRequest+ return LoadRequest(model_path = model_path)+++def test_an_in_process_caller_gets_the_real_result(route, slow_load):+ """preview awaits load_model_gated, so a slow load blocks until the model is+ resident; awaiting the route would hand back an undrained StreamingResponse."""+ result = asyncio.run(route.load_model_gated(_load_request(), None, "admin"))++ assert not isinstance(result, StreamingResponse)+ assert result == {"status": "loaded", "model": "unsloth/Kimi-K3-GGUF"}+ # Returned only after the load finished, not at the 15s mark.+ assert slow_load == ["unsloth/Kimi-K3-GGUF"]+++def test_an_in_process_caller_sees_a_late_failure(route, monkeypatch):+ """A late failure raises for a direct caller, not a 200 carrying `_deferred_error`."""++ async def _slow_boom(request, fastapi_request, current_subject, **kwargs):+ await asyncio.sleep(0.2)+ raise HTTPException(status_code = 507, detail = "CUDA out of memory")++ monkeypatch.setattr(route, "_load_model_impl", _slow_boom)+ monkeypatch.setattr(route, "_raise_if_sidecar_swap_in_progress", lambda: None)++ with pytest.raises(HTTPException) as excinfo:+ asyncio.run(route.load_model_gated(_load_request(), None, "admin"))+ assert excinfo.value.status_code == 507+ assert excinfo.value.detail == "CUDA out of memory"+++def test_the_route_still_pads_the_same_slow_load(route, slow_load):+ """The other half of the split: real HTTP clients keep the padding."""++ async def run():+ response = await route.load_model(_load_request(), None, "admin")+ return response, b"".join(await _collect(response))++ response, body = asyncio.run(run())+ assert isinstance(response, StreamingResponse)+ assert body.startswith(b" ")+ assert json.loads(body) == {"status": "loaded", "model": "unsloth/Kimi-K3-GGUF"}+++def test_only_the_route_pads(route):+ """Padding belongs to the route: a gated-coroutine caller must not inherit a stream."""+ import inspect++ assert "_tunnel_safe_json" in inspect.getsource(route.load_model)+ assert "_tunnel_safe_json" not in inspect.getsource(route.load_model_gated)+ # /unload has no in-process caller today; _unload_model_impl is its equivalent.+ assert "_tunnel_safe_json" in inspect.getsource(route.unload_model)+ assert "_tunnel_safe_json" not in inspect.getsource(route._unload_model_impl)+++def test_preview_awaits_the_gated_load(route):+ """preview.py is the one in-process caller; it must bypass the padding."""+ src = (_backend_root / "routes" / "preview.py").read_text(encoding = "utf-8")+ assert "load_model_gated(" in src+ assert re.search(r"\bawait load_model\(", src) is None, (+ "preview must not await the padded /load route: its StreamingResponse "+ "returns before the checkpoint is loaded"+ )+++def test_preview_chat_waits_for_a_slow_checkpoint_load(route, slow_load, monkeypatch, tmp_path):+ """End to end: /p must not start generating while the checkpoint is still loading."""+ import routes.preview as preview+ from models.inference import ChatCompletionRequest++ checkpoint = tmp_path / "run" / "checkpoint-1"+ checkpoint.mkdir(parents = True)+ monkeypatch.setattr(preview, "_resolve_or_4xx", lambda run, cp: checkpoint)++ loaded_when_chat_started = []++ async def _fake_chat(payload, request, subject):+ loaded_when_chat_started.append(list(slow_load))+ return {"ok": True}++ monkeypatch.setattr(preview, "openai_chat_completions", _fake_chat)++ async def run():+ return await preview._serve_chat(+ "run",+ "checkpoint-1",+ ChatCompletionRequest(messages = [{"role": "user", "content": "hi"}]),+ request = None,+ )++ assert asyncio.run(run()) == {"ok": True}+ # Pre-fix this was empty: the padded StreamingResponse returned at the threshold.+ assert loaded_when_chat_started == [[str(checkpoint)]]+ assert not preview._preview_lock.locked()+++# ── The slow teardown must not sit on the event loop ──────────────────────────+#+# ``LlamaCppBackend.unload_model`` is a plain ``def`` and a 600 GB teardown measures+# ~160s. Called bare it blocks _tunnel_safe_json's own timer and pad generator, so+# zero bytes leave and the proxy 524s anyway: padding dead on the two slowest paths.+++class _SlowSyncTeardown:+ """A synchronous GGUF teardown that returns only once the padding has flowed.++ On the event loop it never sees a pad byte and falls out on ``cap_s`` with none.+ """++ def __init__(+ self,+ chunks,+ *,+ want = 3,+ cap_s = 2.0,+ ):+ self._chunks = chunks+ self._want = want+ self._cap_s = cap_s+ self.thread = None+ self.pads_while_running = None++ def __call__(self, *args, **kwargs):+ self.thread = threading.current_thread()+ deadline = time.monotonic() + self._cap_s+ while len(self._chunks) < self._want and time.monotonic() < deadline:+ time.sleep(0.005)+ self.pads_while_running = len(self._chunks)+ return True++ def assert_padded_off_the_loop(self, label):+ assert self.thread is not None, f"{label} never ran"+ assert self.thread is not threading.main_thread(), f"{label} ran on the event loop thread"+ assert self.pads_while_running is not None and self.pads_while_running >= self._want, (+ f"{label} blocked the padding: {self.pads_while_running} pad bytes went out "+ "while it ran, so a proxy would have timed the response out"+ )+++def _no_active_generation_checks(route, monkeypatch):+ """Neutralise the chat-cancellation gate; test_active_generations owns it."""+ monkeypatch.setattr(route, "_raise_or_cancel_active_generations", lambda **kwargs: 0)++ async def _drain(**kwargs):+ return None++ monkeypatch.setattr(route, "_drain_and_recancel_before_teardown", _drain)+++def _stub_unsloth_load_over_a_resident_gguf(route, monkeypatch, *, teardown):+ """POST /load over a resident GGUF: the branch that tears llama-server down first."""+ import core.export++ from core.inference import llama_keepwarm as kw++ _no_active_generation_checks(route, monkeypatch)+ monkeypatch.setattr(route, "_raise_if_sidecar_swap_in_progress", lambda: None)+ monkeypatch.setattr(route, "validate_extra_args", lambda args: [])+ monkeypatch.setattr(+ route,+ "_resolve_model_identifier_for_request",+ lambda request, operation: (request.model_path, request.model_path, False),+ )+ monkeypatch.setattr(+ route,+ "resolve_effective_chat_template_override",+ lambda model_identifier = None, user_override = None: None,+ )+ monkeypatch.setattr(route, "_hf_offline_if_dns_dead", contextlib.nullcontext)+ monkeypatch.setattr(route, "_mlx_distributed_launch_detected", lambda: False)+ monkeypatch.setattr(+ route.ModelConfig,+ "from_identifier",+ staticmethod(+ lambda **kwargs: SimpleNamespace(+ is_gguf = False,+ identifier = "org/A",+ display_name = "A",+ is_vision = False,+ is_lora = False,+ is_audio = False,+ audio_type = None,+ has_audio_input = False,+ is_local = False,+ gguf_hf_repo = None,+ gguf_variant = None,+ )+ ),+ )+ monkeypatch.setattr(route, "_effective_load_in_4bit", lambda config, requested: False)+ monkeypatch.setattr(route, "_resolve_inherited_extra_args", lambda *a, **k: None)+ monkeypatch.setattr(route, "_guard_chat_load_against_training", lambda *a, **k: None)+ monkeypatch.setattr(route, "load_inference_config", lambda name: {})+ monkeypatch.setattr(+ route,+ "_detect_safetensors_features",+ lambda backend, template, tools = None: {+ "supports_reasoning": False,+ "reasoning_style": "enable_thinking",+ "reasoning_effort_levels": [],+ "reasoning_always_on": False,+ "supports_preserve_thinking": False,+ "supports_tools": False,+ },+ )+ monkeypatch.setattr(route, "_resolve_loaded_trust_remote_code", lambda *a, **k: False)+ monkeypatch.setattr(+ core.export, "get_export_backend", lambda: SimpleNamespace(current_checkpoint = None)+ )+ monkeypatch.setattr(kw, "note_model_loaded", lambda *a, **k: None)+ monkeypatch.setattr(+ route,+ "get_llama_cpp_backend",+ lambda: SimpleNamespace(+ is_loaded = True, # a GGUF is resident and must come down first+ is_active = True,+ hf_variant = None,+ model_identifier = "org/OLD-GGUF",+ layer_preserves_tensor_intent = False,+ unload_model = teardown,+ ),+ )+ monkeypatch.setattr(+ route,+ "get_inference_backend",+ lambda: SimpleNamespace(+ active_model_name = "org/OTHER",+ models = {},+ load_model = lambda **kwargs: True,+ ),+ )+++def test_a_slow_gguf_teardown_before_an_unsloth_load_still_pads(route, monkeypatch):+ """POST /load replacing a resident GGUF with a non-GGUF model."""+ from models.inference import LoadRequest++ chunks: list[bytes] = []+ teardown = _SlowSyncTeardown(chunks)+ _stub_unsloth_load_over_a_resident_gguf(route, monkeypatch, teardown = teardown)++ async def run():+ response = await route.load_model(LoadRequest(model_path = "org/A"), None, "tester")+ if not isinstance(response, StreamingResponse):+ return response+ await _collect_into(response, chunks)+ return response++ response = asyncio.run(run())+ # Pre-fix the teardown ran in the task's first step: a plain LoadResponse, no pads.+ assert isinstance(+ response, StreamingResponse+ ), "a load whose teardown blocks the loop can never be padded"+ teardown.assert_padded_off_the_loop("the pre-load GGUF teardown")+ assert json.loads(b"".join(chunks))["status"] == "loaded"+++def _stub_gguf_unload(route, monkeypatch, *, teardown):+ """POST /unload for the already-loaded GGUF: the manual teardown branch."""+ from core.inference import llama_keepwarm as kw++ _no_active_generation_checks(route, monkeypatch)+ monkeypatch.setattr(route, "is_registered_native_path_label", lambda *a: False)+ monkeypatch.setattr(kw, "note_model_unloaded", lambda: None)+ monkeypatch.setattr(+ route,+ "get_llama_cpp_backend",+ lambda: SimpleNamespace(+ is_active = True,+ is_loaded = True,+ model_identifier = "org/A-GGUF",+ hf_variant = "UD-Q4_K_XL",+ unload_model = teardown,+ ),+ )+ monkeypatch.setattr(+ route,+ "get_inference_backend",+ lambda: SimpleNamespace(+ get_loading_model = lambda: None,+ active_model_name = None,+ models = {},+ unload_model = lambda path: None,+ ),+ )+++def test_a_slow_gguf_unload_still_pads(route, monkeypatch):+ """POST /unload of a resident GGUF: the 160s path /unload is padded for."""+ from models.inference import UnloadRequest++ chunks: list[bytes] = []+ teardown = _SlowSyncTeardown(chunks)+ _stub_gguf_unload(route, monkeypatch, teardown = teardown)++ async def run():+ response = await route.unload_model(UnloadRequest(model_path = "org/A-GGUF"), "tester")+ if not isinstance(response, StreamingResponse):+ return response+ await _collect_into(response, chunks)+ return response++ response = asyncio.run(run())+ assert isinstance(+ response, StreamingResponse+ ), "an unload whose teardown blocks the loop can never be padded"+ teardown.assert_padded_off_the_loop("the manual GGUF teardown")+ assert json.loads(b"".join(chunks)) == {"status": "unloaded", "model": "org/A-GGUF"}+++def test_every_gguf_teardown_on_a_padded_route_is_off_loop():+ """Fence: a new bare ``unload_model()`` in /load or /unload silently un-pads it."""+ import ast++ src = (_backend_root / "routes" / "inference.py").read_text(encoding = "utf-8")+ tree = ast.parse(src)+ bare: list[int] = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.AsyncFunctionDef) or node.name not in (+ "_load_model_impl",+ "_unload_model_impl",+ ):+ continue+ for call in ast.walk(node):+ # A bare call: attribute .unload_model(...) rather than a to_thread arg.+ if (+ isinstance(call, ast.Call)+ and isinstance(call.func, ast.Attribute)+ and call.func.attr == "unload_model"+ ):+ bare.append(call.lineno)+ assert bare == [], (+ f"unload_model called on the event loop at routes/inference.py:{bare}; "+ "wrap it in asyncio.to_thread or the padding never gets to run"+ )+++# ── Non-browser clients ───────────────────────────────────────────────────────+++def test_a_python_client_can_recognise_the_late_failure(route):+ """The CLI is not a browser: it treats any 200 as success, so it must know the same+ `_deferred_error` key and fields or a late OOM reads as a successful load."""++ async def slow_boom():+ await asyncio.sleep(0.2)+ raise HTTPException(status_code = 507, detail = "CUDA out of memory")++ async def run():+ return b"".join(await _collect(await route._tunnel_safe_json(slow_boom(), label = "t")))++ payload = json.loads(asyncio.run(run()))[route._DEFERRED_ERROR_KEY]+ assert payload == {"status_code": 507, "detail": "CUDA out of memory"}++ # Read as text, not imported: the backend test env need not import the CLI.+ cli = (_repo_root / "unsloth_cli" / "_inference.py").read_text(encoding = "utf-8")+ assert f'_DEFERRED_ERROR_KEY = "{route._DEFERRED_ERROR_KEY}"' in cli+ assert 'deferred.get("status_code")' in cli+ assert 'deferred.get("detail")' in cli+ # unsloth_cli/tests/test_inference_chat.py asserts it actually raises.+ assert "def raise_for_deferred_error(" in cli+++def test_both_clients_reject_a_truncated_padded_body():+ """A proxy killing a padded response after the 200 committed leaves the measured+ 200 with an EMPTY body. Both clients must call that a failure, else the same reply+ means "loaded" to one and "failed" to the other. Behaviour is tested in their own+ suites (test_inference_chat.py, padded-response.test.ts); this only pins that+ neither side can drop the check.+ """+ cli = (_repo_root / "unsloth_cli" / "_inference.py").read_text(encoding = "utf-8")+ assert "def require_completed_padded_body(" in cli+ assert "require_completed_padded_body(url, raise_for_deferred_error(url, body))" in cli++ web = (+ _repo_root+ / "studio"+ / "frontend"+ / "src"+ / "features"+ / "chat"+ / "api"+ / "padded-response.ts"+ ).read_text(encoding = "utf-8")+ assert "export function assertCompletedPaddedBody(" in web+ # Scoped to /load and /unload: shared parseJsonOrThrow serves ~30 endpoints,+ # some legitimately with no body.+ chat_api = (+ _repo_root / "studio" / "frontend" / "src" / "features" / "chat" / "api" / "chat-api.ts"+ ).read_text(encoding = "utf-8")+ assert re.findall(r'parseJsonOrThrow<[^>]*>\(\s*response,\s*"([^"]+)"', chat_api) == [+ "Model load",+ "Model unload",+ ]+++def test_the_pad_interval_stays_inside_the_proxy_window():+ """The tunnel kills a connection ~100s after the last byte, so leave margin.++ Reads the source, not the module, so the fixture's fast values cannot mask a+ bad default.+ """+ src = (_backend_root / "routes" / "inference.py").read_text(encoding = "utf-8")+ after = float(src.split("_TUNNEL_KEEPALIVE_AFTER_S = ")[1].split("\n")[0])+ every = float(src.split("_TUNNEL_KEEPALIVE_EVERY_S = ")[1].split("\n")[0])+ assert after + every < 90.0, "first pad must land well before the ~100s cutoff"+ assert every < 90.0, "every subsequent gap resets the timer, so it must too"diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex fb29a6b7f58..66e2f835f21 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -31,6 +31,7 @@ import type {UnloadModelRequest,ValidateModelResponse,} from "../types/api";+import { assertCompletedPaddedBody } from "./padded-response";export const CHAT_HISTORY_UPDATED_EVENT = "unsloth-chat-history-updated";export const CHAT_PROJECTS_UPDATED_EVENT = "unsloth-chat-projects-updated";@@ -89,11 +90,42 @@ function parseErrorText(status: number, body: unknown): string {return `Request failed (${status})`;}-async function parseJsonOrThrow<T>(response: Response): Promise<T> {+/**+ * `/api/inference/load` and `/unload` pad their body so a proxy cannot time the+ * request out, which commits the status before the work finishes: a failure found+ * after that can only arrive in-band, under a 200, as `_deferred_error`.+ */+function deferredError(body: unknown): { status: number; message: string } | null {+ const deferred =+ body && typeof body === "object"+ ? (body as { _deferred_error?: { status_code?: unknown; detail?: unknown } })+ ._deferred_error+ : undefined;+ if (!deferred || typeof deferred !== "object") return null;+ const status =+ typeof deferred.status_code === "number" ? deferred.status_code : 500;+ return { status, message: parseErrorText(status, { detail: deferred.detail }) };+}++/**+ * `paddedLabel` opts a caller into `assertCompletedPaddedBody`; only the two padded+ * routes may, since a truncated body means unfinished there but is legitimate elsewhere.+ */+async function parseJsonOrThrow<T>(+ response: Response,+ paddedLabel?: string,+): Promise<T> {const body = await response.json().catch(() => null);if (!response.ok) {throw new Error(parseErrorText(response.status, body));}+ const deferred = deferredError(body);+ if (deferred) {+ throw new Error(deferred.message);+ }+ if (paddedLabel !== undefined) {+ assertCompletedPaddedBody(body, paddedLabel);+ }return body as T;}@@ -165,7 +197,7 @@ export async function loadModel(nativePathLease: undefined,}),});- return parseJsonOrThrow<LoadModelResponse>(response);+ return parseJsonOrThrow<LoadModelResponse>(response, "Model load");}export async function validateModel(@@ -260,7 +292,7 @@ export async function unloadModel(payload: UnloadModelRequest): Promise<void> {headers: { "Content-Type": "application/json" },body: JSON.stringify(payload),});- await parseJsonOrThrow<unknown>(response);+ await parseJsonOrThrow<unknown>(response, "Model unload");}/**diff --git a/studio/frontend/src/features/chat/api/padded-response.ts b/studio/frontend/src/features/chat/api/padded-response.tsnew file mode 100644index 00000000000..b21e4083235--- /dev/null+++ b/studio/frontend/src/features/chat/api/padded-response.ts@@ -0,0 +1,25 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * `/api/inference/load` and `/unload` pad their body so a proxy cannot time the request+ * out, committing the 200 before the work finishes (`_tunnel_safe_json` in+ * studio/backend/routes/inference.py). A proxy giving up mid-pad leaves a 200 with an+ * empty or truncated body; accepting that reports an unfinished load as done. Only+ * these two routes commit that early, so only they require a payload; elsewhere an+ * empty body is by design. Mirrored by `require_completed_padded_body` in+ * unsloth_cli/_inference.py.+ */+export function assertCompletedPaddedBody(body: unknown, label: string): void {+ const complete =+ typeof body === "object" &&+ body !== null &&+ !Array.isArray(body) &&+ Object.keys(body).length > 0;+ if (complete) {+ return;+ }+ throw new Error(+ `${label} did not report completion: the connection closed before the server's reply arrived. Check the model's status before retrying.`,+ );+}diff --git a/studio/frontend/tests/padded-response.test.ts b/studio/frontend/tests/padded-response.test.tsnew file mode 100644index 00000000000..b70d2755fea--- /dev/null+++ b/studio/frontend/tests/padded-response.test.ts@@ -0,0 +1,73 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * A truncated padded reply is not a successful load.+ *+ * `/api/inference/load` and `/unload` pad their body so a proxy cannot time the request+ * out, which commits the 200 before the work finishes. The tunnel probe measured the+ * failure mode (studio/backend/tests/test_tunnel_safe_long_post.py): one byte at t=90s+ * then silence is killed ~125s later and the client sees a 200 with an EMPTY body.+ * `response.json()` throws on that and `catch(() => null)` makes it a 200 with a null+ * body, read as success unless the padded callers say otherwise.+ */++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import { assertCompletedPaddedBody } from "../src/features/chat/api/padded-response.ts";++const chatApi = readFileSync(+ new URL("../src/features/chat/api/chat-api.ts", import.meta.url),+ "utf8",+);++test("a real payload passes through", () => {+ assertCompletedPaddedBody({ status: "loaded", model: "org/A" }, "Model load");+ assertCompletedPaddedBody({ status: "unloaded" }, "Model unload");+});++test("a body the proxy truncated is rejected, not accepted as success", () => {+ // An empty body, a pad-only body (" ") and a half payload all decode to null.+ for (const body of [null, undefined, {}, [], "", "loaded", 0]) {+ assert.throws(+ () => assertCompletedPaddedBody(body, "Model load"),+ /Model load did not report completion/,+ JSON.stringify(body) ?? "undefined",+ );+ }+});++test("the message names the operation and points at the model's status", () => {+ assert.throws(+ () => assertCompletedPaddedBody(null, "Model unload"),+ (err: unknown) => {+ const message = (err as Error).message;+ assert.match(message, /^Model unload did not report completion/);+ assert.match(message, /connection closed/);+ assert.match(message, /Check the model's status/);+ return true;+ },+ );+});++test("only the two padded routes require a payload", () => {+ // Scoped: parseJsonOrThrow serves ~30 endpoints, some legitimately with no body.+ const labelled = [+ ...chatApi.matchAll(/parseJsonOrThrow<[^>]*>\(\s*response,\s*"([^"]+)"/g),+ ].map((match) => match[1]);+ assert.deepEqual(labelled, ["Model load", "Model unload"]);+ assert.ok(chatApi.includes("assertCompletedPaddedBody(body, paddedLabel)"));+});++test("the Python client agrees", () => {+ // If only one client rejects a truncated reply, one reads success where the other fails.+ const cli = readFileSync(+ new URL("../../../unsloth_cli/_inference.py", import.meta.url),+ "utf8",+ );+ assert.ok(cli.includes("def require_completed_padded_body("));+ // unsloth_cli/tests/test_inference_chat.py asserts it actually raises.+ assert.ok(cli.includes("if isinstance(body, dict) and body:"));+});diff --git a/unsloth_cli/_inference.py b/unsloth_cli/_inference.pyindex 43268423c6b..dec4a354d3f 100644--- a/unsloth_cli/_inference.py+++ b/unsloth_cli/_inference.py@@ -52,6 +52,78 @@ def urlopen_no_redirect(request, timeout):return _no_redirect_opener.open(request, timeout = timeout)+# /api/inference/load and /unload pad their body so a proxy cannot time a slow load+# out, committing the 200 before the work finishes. A failure found after that travels+# only in-band under this key (studio/backend/routes/inference.py), so a client that+# treats any 200 as success reports a failed load as a successful one.+_DEFERRED_ERROR_KEY = "_deferred_error"+++def raise_for_deferred_error(url: str, body):+ """Raise the late failure a padded 200 body carries; else return ``body``.++ ``urllib.error.HTTPError`` specifically: it is the class every CLI caller already+ handles for a plain HTTP failure, so existing ``except`` blocks, messages and exit+ codes keep working, and ``.read()`` yields the same ``{"detail": ...}`` shape.+ """+ if not isinstance(body, dict):+ return body+ deferred = body.get(_DEFERRED_ERROR_KEY)+ if not isinstance(deferred, dict):+ return body++ import email.message+ import io+ import urllib.error++ status = deferred.get("status_code")+ if not isinstance(status, int) or isinstance(status, bool):+ status = 500+ detail = deferred.get("detail")+ if not isinstance(detail, str) or not detail:+ detail = "unknown error" if detail is None else json.dumps(detail)+ headers = email.message.Message()+ headers["Content-Type"] = "application/json"+ raise urllib.error.HTTPError(+ url, status, detail, headers, io.BytesIO(json.dumps({"detail": detail}).encode())+ )+++def require_completed_padded_body(url: str, body):+ """Return ``body``, or raise if it is not the payload a padded route promised.++ A proxy that gives up mid-pad leaves a 200 with an empty or truncated body, so+ accepting it reports an unfinished load or unload as completed. Only the two padded+ routes commit their status that early, so only they require a payload; ``{}`` is+ rejected too, since that is what a blank body decodes to here. Mirrored by+ ``assertCompletedPaddedBody`` in studio/frontend/src/features/chat/api/padded-response.ts.+ """+ if isinstance(body, dict) and body:+ return body+ raise RuntimeError(+ f"{url} did not report completion: the connection closed before the "+ "server's reply arrived. Check the model's status before retrying."+ )+++def read_json_checking_deferred_error(url: str, response):+ """Drain ``response``, then raise any deferred error its body carries.++ Draining matters on its own: stopping at the headers of a padded /load leaves the+ load running, so the caller resumes too early. An incomplete JSON payload is a+ truncated padded reply, not a success (see ``require_completed_padded_body``).+ """+ try:+ raw = response.read()+ finally:+ response.close()+ try:+ body = json.loads(raw.decode(errors = "replace") or "{}")+ except ValueError:+ body = None+ return require_completed_padded_body(url, raise_for_deferred_error(url, body))++def ensure_studio_backend_path() -> None:backend_dir = str(Path(__file__).resolve().parents[1] / "studio" / "backend")if backend_dir not in sys.path:@@ -684,11 +756,13 @@ class HttpChatBackend:if llama_extra_args:payload["llama_extra_args"] = llama_extra_argstry:- self._request(- "POST",- "/api/inference/load",- payload,- ).close()+ # Read the body, don't close at the headers: a slow load commits its 200+ # early and pads until done, so closing here would generate mid-load and+ # discard the only report of a late failure.+ read_json_checking_deferred_error(+ self._base + "/api/inference/load",+ self._request("POST", "/api/inference/load", payload),+ )except Exception as exc:typer.echo(f"Model load failed: {exc}", err = True)raise typer.Exit(code = 1)diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.pyindex dfb2ee678d1..1c8e013c832 100644--- a/unsloth_cli/commands/start.py+++ b/unsloth_cli/commands/start.py@@ -34,6 +34,8 @@ from unsloth_cli._inference import (ensure_studio_backend_path,find_studio_server,is_loopback_url,+ raise_for_deferred_error,+ require_completed_padded_body,urlopen_no_redirect,verify_studio_identity,)@@ -658,7 +660,10 @@ def _http_json(try:# No redirects: a 3xx would leak this bearer token to an unvetted base.with urlopen_no_redirect(request, timeout = timeout) as response:- return json.loads(response.read().decode() or "{}")+ body = json.loads(response.read().decode() or "{}")+ # A padded /load or /unload commits its 200 early, so a late failure arrives+ # in-band; raise it as the HTTPError handled below.+ return raise_for_deferred_error(url, body)except urllib.error.HTTPError as exc:if error is None:raise@@ -893,6 +898,7 @@ def _load_model_with_progress(base: str, key: str, model: str, load: LoadOptions, payload: dict) -> dict:"""Run the blocking load request while polling its download progress."""+ load_url = f"{base}/api/inference/load"result: list[tuple[bool, object]] = []done = threading.Event()@@ -900,7 +906,7 @@ def _load_model_with_progress(try:value = _http_json("POST",- f"{base}/api/inference/load",+ load_url,key,payload,timeout = 3600,@@ -924,9 +930,14 @@ def _load_model_with_progress(ok, value = result[0]if not ok:assert isinstance(value, BaseException)+ # A pad-only or half-written body fails `_http_json`'s json.loads: report+ # the padded 200 that never completed, not a JSON error from the API.+ if isinstance(value, ValueError):+ require_completed_padded_body(load_url, None)raise valueprogress.complete()- return value if isinstance(value, dict) else {}+ # `_http_json` decodes a blank body as `{}`, which would look like a completed load.+ return require_completed_padded_body(load_url, value)finally:progress.close()diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex 560df4aea2f..5fc3a18d07c 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -1222,6 +1222,8 @@ def _load_model_via_http(import urllib.requestimport urllib.error+ from unsloth_cli._inference import raise_for_deferred_error, require_completed_padded_body+payload: dict = {"model_path": model,"max_seq_length": max_seq_length,@@ -1238,8 +1240,9 @@ def _load_model_via_http(payload["llama_extra_args"] = list(llama_extra_args)data = json.dumps(payload).encode()+ url = f"http://127.0.0.1:{port}/api/inference/load"req = urllib.request.Request(- f"http://127.0.0.1:{port}/api/inference/load",+ url,data = data,headers = {"Content-Type": "application/json",@@ -1249,7 +1252,14 @@ def _load_model_via_http()try:with urllib.request.urlopen(req, timeout = timeout) as resp:- return json.loads(resp.read())+ try:+ body = json.loads(resp.read())+ except ValueError:+ body = None # truncated padded reply; rejected below+ # A slow load commits its 200 before it finishes and pads the body, so a late+ # failure arrives in-band; raise it as the HTTPError this function already turns+ # into the RuntimeError the caller reports. A truncated body is no report at all.+ return require_completed_padded_body(url, raise_for_deferred_error(url, body))except urllib.error.HTTPError as exc:body = exc.read().decode(errors = "replace")raise RuntimeError(f"Model load failed (HTTP {exc.code}): {body}") from excdiff --git a/unsloth_cli/tests/test_inference_chat.py b/unsloth_cli/tests/test_inference_chat.pyindex 07eed01e976..cbb9bb9fa9a 100644--- a/unsloth_cli/tests/test_inference_chat.py+++ b/unsloth_cli/tests/test_inference_chat.py@@ -6,6 +6,7 @@from __future__ import annotationsimport inspect+import jsonimport sysimport typesfrom pathlib import Path@@ -435,14 +436,30 @@ def test_http_backend_streams_cumulative_text(monkeypatch):assert out == ["He", "Hello"]+class _FakeLoadResponse:+ """A /api/inference/load reply that records whether its body was drained.++ Closing a padded body at the headers resumes before the load finishes and discards+ a late failure, so the fake must distinguish read() from close().+ """++ def __init__(self, body: bytes = b'{"status": "loaded"}') -> None:+ self._body = body+ self.reads = 0+ self.closed = False++ def read(self) -> bytes:+ self.reads += 1+ return self._body++ def close(self) -> None:+ self.closed = True++def test_http_backend_load_forwards_gguf_runtime_options(monkeypatch):backend = HttpChatBackend("http://localhost:8888", "token")requests = []- class _OK:- def close(self):- pass-def fake_request(method,path,@@ -450,7 +467,7 @@ def test_http_backend_load_forwards_gguf_runtime_options(monkeypatch):timeout = None,):requests.append((method, path, payload, timeout))- return _OK()+ return _FakeLoadResponse()monkeypatch.setattr(backend, "_request", fake_request)@@ -484,16 +501,12 @@ def test_http_backend_load_sends_explicit_false_tensor_parallel(monkeypatch):backend = HttpChatBackend("http://localhost:8888", "token")requests = []- class _OK:- def close(self):- pass-monkeypatch.setattr(backend,"_request",lambda method, path, payload = None, timeout = None: (requests.append((method, path, payload, timeout)),- _OK(),+ _FakeLoadResponse(),)[1],)@@ -508,6 +521,148 @@ def test_http_backend_load_sends_explicit_false_tensor_parallel(monkeypatch):assert requests[0][2]["tensor_parallel"] is False+# ── A load slower than the proxy timer (see routes/inference.py _tunnel_safe_json) ──+++def test_http_backend_load_drains_the_padded_body(monkeypatch):+ """Closing at the headers would start generating while the model is still loading."""+ backend = HttpChatBackend("http://localhost:8888", "token")+ # What a padded slow load looks like on the wire: spaces, then the payload.+ response = _FakeLoadResponse(b' {"status": "loaded"}')+ monkeypatch.setattr(backend, "_request", lambda *a, **k: response)++ backend.ensure_loaded(+ "org/model-GGUF",+ hf_token = None,+ max_seq_length = 4096,+ load_in_4bit = True,+ )++ assert response.reads == 1, "the padded body must be drained, not closed at the headers"+ assert response.closed+++def test_http_backend_load_fails_on_a_deferred_error(monkeypatch, capsys):+ """A failure found after the 200 committed rides in the body; a 200 is not success."""+ backend = HttpChatBackend("http://localhost:8888", "token")+ response = _FakeLoadResponse(+ json.dumps(+ {"_deferred_error": {"status_code": 507, "detail": "CUDA out of memory"}}+ ).encode()+ )+ monkeypatch.setattr(backend, "_request", lambda *a, **k: response)++ with pytest.raises(typer.Exit) as excinfo:+ backend.ensure_loaded(+ "org/model-GGUF",+ hf_token = None,+ max_seq_length = 4096,+ load_in_4bit = True,+ )++ # Same exit code as an early HTTP failure: ensure_loaded's except block is reused.+ assert excinfo.value.exit_code == 1+ err = capsys.readouterr().err+ assert "Model load failed" in err+ assert "507" in err and "CUDA out of memory" in err+++ ("body", "what"),+ [+ (b"", "an empty body"),+ (b" ", "pad bytes only"),+ (b' {"status": "loa', "a payload cut in half"),+ (b"null", "a literal null"),+ (b"{}", "an empty object"),+ ],+)+def test_http_backend_load_rejects_a_truncated_padded_body(monkeypatch, capsys, body, what):+ """A proxy that gives up mid-pad leaves a 200 the padded route never finished.++ Measured: one byte at t=90s then silence is killed ~125s later and the client sees+ a 200 with an EMPTY body. Accepting it reports an unfinished load as done.+ """+ backend = HttpChatBackend("http://localhost:8888", "token")+ response = _FakeLoadResponse(body)+ monkeypatch.setattr(backend, "_request", lambda *a, **k: response)++ with pytest.raises(typer.Exit) as excinfo:+ backend.ensure_loaded(+ "org/model-GGUF",+ hf_token = None,+ max_seq_length = 4096,+ load_in_4bit = True,+ )++ assert excinfo.value.exit_code == 1, what+ err = capsys.readouterr().err+ assert "Model load failed" in err+ assert "did not report completion" in err+ # Still drained, so the load is not abandoned at the headers.+ assert response.reads == 1 and response.closed+++def test_padded_body_helper_passes_a_real_payload_through():+ from unsloth_cli._inference import require_completed_padded_body++ body = {"status": "loaded", "model": "org/model-GGUF"}+ assert require_completed_padded_body("http://x/api/inference/load", body) is body+ assert require_completed_padded_body("http://x", {"status": "unloaded"}) == {+ "status": "unloaded"+ }+++def test_padded_body_helper_names_the_route_and_the_recovery():+ from unsloth_cli._inference import require_completed_padded_body+ url = "http://x/api/inference/load"+ for body in (None, {}, [], "", 0, "loaded"):+ with pytest.raises(RuntimeError) as excinfo:+ require_completed_padded_body(url, body)+ message = str(excinfo.value)+ assert message.startswith(f"{url} did not report completion")+ assert "Check the model's status" in message+++def test_deferred_error_helper_passes_a_normal_body_through():+ from unsloth_cli._inference import raise_for_deferred_error++ body = {"status": "loaded", "model": "org/model-GGUF"}+ assert raise_for_deferred_error("http://x/api/inference/load", body) is body+ # Not a dict, and a look-alike that is not the documented shape, both pass.+ assert raise_for_deferred_error("http://x", [1, 2]) == [1, 2]+ assert raise_for_deferred_error("http://x", {"_deferred_error": None}) == {+ "_deferred_error": None+ }+++def test_deferred_error_helper_reads_like_a_real_error_response():+ """Callers recover the detail with exc.read(), exactly as for a real 5xx."""+ import urllib.error++ from unsloth_cli._inference import raise_for_deferred_error++ with pytest.raises(urllib.error.HTTPError) as excinfo:+ raise_for_deferred_error(+ "http://x/api/inference/load",+ {"_deferred_error": {"status_code": 500, "detail": "llama-server died"}},+ )+ exc = excinfo.value+ assert exc.code == 500+ assert json.loads(exc.read().decode()) == {"detail": "llama-server died"}+ assert "llama-server died" in str(exc)+++def test_deferred_error_helper_defaults_a_missing_status():+ import urllib.error++ from unsloth_cli._inference import raise_for_deferred_error++ with pytest.raises(urllib.error.HTTPError) as excinfo:+ raise_for_deferred_error("http://x", {"_deferred_error": {}})+ assert excinfo.value.code == 500++def test_load_gguf_backend_forwards_local_runtime_options(monkeypatch):import unsloth_cli._inference as inferencediff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.pyindex 30ac2c8181b..4b9a1029ea0 100644--- a/unsloth_cli/tests/test_start.py+++ b/unsloth_cli/tests/test_start.py@@ -5,6 +5,7 @@from __future__ import annotations+import ioimport jsonimport osimport re@@ -3246,6 +3247,117 @@ def test_load_model_with_progress_uses_selected_gguf_size(monkeypatch, capsys):assert f"expected_bytes={4 * 1024**3}" in progress_url+# ── A load slower than the proxy timer (routes/inference.py _tunnel_safe_json) ──+#+# /api/inference/load pads its body so a proxy cannot time a slow load out, committing+# the 200 before the load finishes. A failure after that travels only in the body, as+# `_deferred_error`, so `_http_json` must raise on it or a late OOM reads as success.++_DEFERRED_OOM = {+ "_deferred_error": {"status_code": 507, "detail": "CUDA out of memory"},+}+++def _padded(body: dict) -> io.BytesIO:+ """A padded response body: keepalive spaces, then the JSON payload."""+ return io.BytesIO(b" " + json.dumps(body).encode())+++def test_http_json_reads_a_padded_success(monkeypatch):+ """Leading pad bytes are legal JSON, so a slow success is unchanged."""+ monkeypatch.setattr(+ start, "urlopen_no_redirect", lambda request, timeout: _padded({"status": "loaded"})+ )+ assert start._http_json("POST", f"{BASE}/api/inference/load", "sk-test") == {"status": "loaded"}+++def test_http_json_raises_a_deferred_error_as_an_http_error(monkeypatch):+ monkeypatch.setattr(+ start, "urlopen_no_redirect", lambda request, timeout: _padded(_DEFERRED_OOM)+ )+ with pytest.raises(urllib.error.HTTPError) as excinfo:+ start._http_json("POST", f"{BASE}/api/inference/load", "sk-test")+ # The same class every caller already handles for an early HTTP failure.+ assert excinfo.value.code == 507+ assert "CUDA out of memory" in str(excinfo.value)+++def test_http_json_deferred_error_fails_like_an_http_failure(monkeypatch, capsys):+ """With `error` set, a late failure exits 1 with the server's detail, as an early 507+ does, via the same _fail path."""+ monkeypatch.setattr(+ start, "urlopen_no_redirect", lambda request, timeout: _padded(_DEFERRED_OOM)+ )+ with pytest.raises(typer.Exit) as excinfo:+ start._http_json(+ "POST",+ f"{BASE}/api/inference/load",+ "sk-test",+ error = "Model load failed",+ )+ assert excinfo.value.exit_code == 1+ # _http_error_detail reads the raised error's body, so the detail survives.+ assert "Model load failed: CUDA out of memory" in capsys.readouterr().err+++def test_load_model_with_progress_fails_on_a_deferred_error(monkeypatch):+ """The real /load caller: a late failure must not be returned as a result."""++ def urlopen(request, timeout):+ if request.full_url.endswith("/api/inference/load"):+ return _padded(_DEFERRED_OOM)+ # Progress polling is best-effort; 404 it so the display just disables.+ raise urllib.error.HTTPError(request.full_url, 404, "not found", None, None)++ monkeypatch.setattr(start, "urlopen_no_redirect", urlopen)+ monkeypatch.setattr(start, "_DOWNLOAD_POLL_INTERVAL_S", 0.001)+ with pytest.raises(typer.Exit) as excinfo:+ start._load_model_with_progress(+ BASE,+ "sk-test",+ "owner/model-GGUF",+ start.LoadOptions(),+ {"model_path": "owner/model-GGUF"},+ )+ assert excinfo.value.exit_code == 1+++ ("body", "what"),+ [+ (b"", "an empty body"),+ (b" ", "pad bytes only"),+ (b' {"status": "loa', "a payload cut in half"),+ ],+)+def test_load_model_with_progress_rejects_a_truncated_padded_body(monkeypatch, body, what):+ """A proxy that gives up mid-pad leaves a 200 the load never finished under.++ Measured: one byte at t=90s, silence, killed ~125s later, a 200 with an EMPTY body.+ `_http_json` decodes a blank body as `{}`, so without the check this returned a+ successful-looking result and the agent connected to whatever was still resident.+ """++ def urlopen(request, timeout):+ if request.full_url.endswith("/api/inference/load"):+ return io.BytesIO(body)+ # Progress polling is best-effort; 404 it so the display just disables.+ raise urllib.error.HTTPError(request.full_url, 404, "not found", None, None)++ monkeypatch.setattr(start, "urlopen_no_redirect", urlopen)+ monkeypatch.setattr(start, "_DOWNLOAD_POLL_INTERVAL_S", 0.001)+ with pytest.raises(RuntimeError) as excinfo:+ start._load_model_with_progress(+ BASE,+ "sk-test",+ "owner/model-GGUF",+ start.LoadOptions(),+ {"model_path": "owner/model-GGUF"},+ )+ assert "did not report completion" in str(excinfo.value), what+ assert "/api/inference/load" in str(excinfo.value)++def test_download_progress_ignores_fully_cached_bytes(capsys):display = start._DownloadProgressDisplay()display.update(diff --git a/unsloth_cli/tests/test_studio_run_parallel_flag.py b/unsloth_cli/tests/test_studio_run_parallel_flag.pyindex 9a3260d6994..5c76fe3bd00 100644--- a/unsloth_cli/tests/test_studio_run_parallel_flag.py+++ b/unsloth_cli/tests/test_studio_run_parallel_flag.py@@ -461,6 +461,55 @@ def test_load_model_http_payload_for_gpu_memory_mode(monkeypatch, mode, expectedassert captured["request"].get_header("Authorization") == "Bearer sk-test"+def test_load_model_http_fails_on_a_deferred_error(monkeypatch):+ """A slow load commits its 200 and pads the body (routes/inference.py+ _tunnel_safe_json), so a late failure arrives in-band; it must still surface as the+ RuntimeError `run` reports, not as a successful load."""+ studio_mod = _load_run_command()++ def urlopen(request, timeout):+ # Keepalive pad, then the deferred failure: what the wire really carries.+ return BytesIO(+ b" "+ + json.dumps(+ {"_deferred_error": {"status_code": 507, "detail": "CUDA out of memory"}}+ ).encode()+ )++ monkeypatch.setattr(studio_mod.urllib.request, "urlopen", urlopen)+ with pytest.raises(RuntimeError) as excinfo:+ studio_mod._load_model_via_http(+ port = 8888,+ api_key = "sk-test",+ model = "owner/model-GGUF",+ gguf_variant = None,+ max_seq_length = 0,+ load_in_4bit = True,+ )+ assert "HTTP 507" in str(excinfo.value)+ assert "CUDA out of memory" in str(excinfo.value)++[email protected]("body", [b"", b" ", b' {"status": "loa', b"{}"])+def test_load_model_http_rejects_a_truncated_padded_body(monkeypatch, body):+ """A 200 the load never finished under must fail like any other load failure."""+ studio_mod = _load_run_command()++ monkeypatch.setattr(+ studio_mod.urllib.request, "urlopen", lambda request, timeout: BytesIO(body)+ )+ with pytest.raises(RuntimeError) as excinfo:+ studio_mod._load_model_via_http(+ port = 8888,+ api_key = "sk-test",+ model = "owner/model-GGUF",+ gguf_variant = None,+ max_seq_length = 0,+ load_in_4bit = True,+ )+ assert "did not report completion" in str(excinfo.value)++def test_reexec_mixed_parallel_with_passthrough(monkeypatch):"""--parallel + llama-server pass-through flags must all reach the child."""result, captured = _invoke_run(