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.

studio: reap durable chat generation runs that stop making progress (#9997)

Daniel Hanc57e5fb21e8f
diff --git a/studio/backend/core/inference/chat_generation_runs.py b/studio/backend/core/inference/chat_generation_runs.py
index 08dea20fdcf..0820086bdb9 100644
--- a/studio/backend/core/inference/chat_generation_runs.py
+++ b/studio/backend/core/inference/chat_generation_runs.py
@@ -6,7 +6,10 @@
from __future__ import annotations
import asyncio
+import contextlib
import json
+import math
+import os
import threading
import time
from typing import Any, AsyncIterator
@@ -28,6 +31,21 @@ _SHUTDOWN_GRACE_SECONDS = 10.0
# Second budget, after task.cancel(). Shorter than the grace period: by this point the
# run is already being abandoned, and the only question is whether shutdown returns.
_SHUTDOWN_CANCEL_SECONDS = 5.0
+# The sweeper's own shutdown budget, far below the producers'. Its work is redundant
+# at shutdown and Desktop force-kills the backend after five seconds.
+_SWEEP_SHUTDOWN_SECONDS = 0.5
+# A durable run sets cancel_on_disconnect=False, so reaping is keyed on progress rather
+# than on connectedness. The default matches llama_cpp._DEFAULT_FIRST_TOKEN_TIMEOUT_S, the
+# request path's own first-token budget: a lease older than that cannot be legitimate
+# prefill, and slow decode is safe at any speed.
+# A century: clear of any real lease, far below where integer milliseconds overflow.
+_MAX_ENV_SECONDS = 100.0 * 365.0 * 24.0 * 60.0 * 60.0
+# The longest admission keep-alive cadence worth deriving a lease from. A day already
+# means the queue never reports, and tripling it stays far inside _MAX_ENV_SECONDS.
+_MAX_ADMISSION_INTERVAL_SECONDS = 24.0 * 60.0 * 60.0
+_LEASE_TIMEOUT_SECONDS = 1200.0
+_LEASE_SWEEP_INTERVAL_SECONDS = 60.0
+_LEASE_ERROR = "Generation stopped making progress"
class _SSEDecoder:
@@ -98,6 +116,316 @@ async def _close_iterator(iterator: AsyncIterator[Any] | None) -> None:
pass
+def _env_seconds(name: str, default: float) -> float:
+ """Seconds from the environment, falling back on anything unusable.
+
+ Non-finite values parse cleanly and fail silently downstream: `inf` raises on
+ `int(timeout * 1000)` every sweep, and `max(0.0, nan)` returns 0.0, disabling reaping.
+ """
+ raw = os.environ.get(name)
+ if raw is None:
+ return default
+ try:
+ value = float(raw)
+ except ValueError:
+ return default
+ if not math.isfinite(value):
+ logger.warning(
+ "chat_generation_lease_env_ignored",
+ variable = name,
+ value = raw,
+ reason = "not a finite number",
+ )
+ return default
+ if value > _MAX_ENV_SECONDS:
+ # Finite is not usable: past ~1.8e305 the multiply to milliseconds overflows and
+ # every sweep raises. Clamped, not rejected, since this already meant "never reap".
+ logger.warning(
+ "chat_generation_lease_env_clamped",
+ variable = name,
+ value = raw,
+ applied_s = _MAX_ENV_SECONDS,
+ reason = "larger than can be converted to integer milliseconds",
+ )
+ return _MAX_ENV_SECONDS
+ return value
+
+
+async def _sweep_in_daemon_thread(fn, /, *args, **kwargs):
+ """Run one blocking sweep on a daemon thread.
+
+ Not asyncio.to_thread: its executor threads are non-daemon and joined by an atexit
+ hook, so a sweep parked on SQLite's writer lock keeps the whole process alive long
+ after shutdown gave up waiting for it. Studio Desktop allows five seconds for a
+ graceful backend exit before force-killing, and stops the backend this way before it
+ updates, so an unbounded exit is a user-visible hang. A daemon thread abandoned here
+ cannot hold the interpreter open.
+ """
+ loop = asyncio.get_running_loop()
+ future = loop.create_future()
+
+ def _settle(setter, value):
+ # The loop can be closed already: this thread outlived the shutdown that
+ # abandoned it, which is exactly the case the daemon thread exists to make safe.
+ try:
+ loop.call_soon_threadsafe(lambda: future.done() or setter(value))
+ except RuntimeError:
+ pass
+
+ def _runner():
+ try:
+ result = fn(*args, **kwargs)
+ except BaseException as exc: # noqa: BLE001 - relayed to the awaiting caller
+ _settle(future.set_exception, exc)
+ else:
+ _settle(future.set_result, result)
+
+ threading.Thread(target = _runner, name = "chat-lease-sweep", daemon = True).start()
+ return await future
+
+
+class ChatGenerationLeaseSweeper:
+ """Periodically settle durable runs whose progress lease has expired.
+
+ reconcile_orphaned_runs used to run exactly once, at process boot, so a run that
+ wedged while Studio kept running was never repaired and browser reloads could not
+ clear it. This runs the same reconciliation on an interval, bounded to runs that
+ have made no progress for the lease timeout so a live generation is never reaped.
+ """
+
+ def __init__(
+ self,
+ app: Any,
+ *,
+ interval_s: float | None = None,
+ timeout_s: float | None = None,
+ ) -> None:
+ self.app = app
+ self._interval = max(
+ 1.0,
+ interval_s
+ if interval_s is not None
+ else _env_seconds(
+ "UNSLOTH_STUDIO_CHAT_RUN_LEASE_SWEEP_INTERVAL_S", _LEASE_SWEEP_INTERVAL_SECONDS
+ ),
+ )
+ # 0 disables the sweep entirely, matching UNSLOTH_STUDIO_ENGINE_STALL_TIMEOUT_S.
+ configured = max(
+ 0.0,
+ timeout_s
+ if timeout_s is not None
+ else _env_seconds("UNSLOTH_STUDIO_CHAT_RUN_LEASE_TIMEOUT_S", _LEASE_TIMEOUT_SECONDS),
+ )
+ self._timeout = _clamped_lease_timeout(configured)
+ self._task: asyncio.Task | None = None
+ self._stop_event = asyncio.Event()
+
+ # Grace for a settled producer to notice the cooperative cancel. Generous: unwinding
+ # cleanly beats being cancelled mid-teardown, and the run is already declared dead.
+ _FORCE_CANCEL_GRACE_S = 30.0
+
+ @property
+ def enabled(self) -> bool:
+ return self._timeout > 0.0
+
+ def start(self) -> None:
+ if self._task is not None or not self.enabled:
+ return
+ # A second lifespan reuses the instance parked on app.state, and stop() left the
+ # event set. Recreated rather than cleared, because the second lifespan can also
+ # be a different event loop (repeated TestClient contexts, an embedded server
+ # restart), and an asyncio.Event stays bound to the loop it was made on: clearing
+ # it would leave the new task failing its first wait with "bound to a different
+ # event loop", silently disabling reaping for that whole lifespan.
+ self._stop_event = asyncio.Event()
+ self._task = asyncio.create_task(self._run(), name = "chat-generation-lease-sweeper")
+
+ async def _run(self) -> None:
+ while True:
+ waiter = asyncio.ensure_future(self._stop_event.wait())
+ done, _pending = await asyncio.wait({waiter}, timeout = self._interval)
+ if done:
+ return
+ waiter.cancel()
+ try:
+ await self.sweep_once()
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc:
+ # One failed sweep (a locked database, a torn-down home in tests) must
+ # not retire the watchdog for the life of the process.
+ logger.warning("chat_generation_lease_sweep_failed", error = repr(exc))
+
+ async def sweep_once(self) -> list[str]:
+ if not self.enabled:
+ return []
+ settled = await _sweep_in_daemon_thread(
+ db.reconcile_runs,
+ error = _LEASE_ERROR,
+ stale_after_ms = int(self._timeout * 1000),
+ )
+ if not settled:
+ return []
+ supervisor = getattr(getattr(self.app, "state", None), "chat_generation_supervisor", None)
+ for run_id in settled:
+ logger.warning(
+ "chat_generation_run_lease_expired",
+ run_id = run_id,
+ idle_s = round(self._timeout, 1),
+ )
+ if supervisor is None:
+ continue
+ # The row is settled, but a producer wedged inside the engine is still
+ # holding its slot and activity reservation; cancel unwinds it.
+ try:
+ supervisor.cancel(run_id)
+ except Exception as exc:
+ logger.warning(
+ "chat_generation_lease_cancel_failed", run_id = run_id, error = repr(exc)
+ )
+ continue
+ asyncio.create_task(
+ self._force_cancel_after_grace(supervisor, run_id),
+ name = f"chat-generation-lease-force-cancel:{run_id}",
+ )
+ return settled
+
+ async def _force_cancel_after_grace(self, supervisor: Any, run_id: str) -> None:
+ """Escalate from the cooperative cancel to cancelling the producer task.
+
+ supervisor.cancel() only sets a threading.Event, which a producer blocked inside
+ next(gen) never looks at, so it goes on holding its activity reservation and engine
+ slot. Cancelling the task releases that bookkeeping. It cannot unblock a thread
+ already inside the engine, and the warning says so rather than implying otherwise.
+ """
+ await asyncio.sleep(self._FORCE_CANCEL_GRACE_S)
+ task = getattr(supervisor, "_tasks", {}).get(run_id)
+ if task is None or task.done():
+ return
+ logger.warning(
+ "chat_generation_run_force_cancelled",
+ run_id = run_id,
+ grace_s = self._FORCE_CANCEL_GRACE_S,
+ note = "producer ignored the cooperative cancel; any engine thread it left "
+ "blocked cannot be reclaimed from here",
+ )
+ task.cancel()
+
+ async def stop(self) -> None:
+ self._stop_event.set()
+ task, self._task = self._task, None
+ if task is None:
+ return
+ # A short wait, not the producer grace. Letting a sweep finish at shutdown buys
+ # nothing: the boot reconcile settles every active run anyway, so its work is
+ # redundant here, while a sweep parked on the writer lock would otherwise spend
+ # Studio Desktop's whole graceful-exit budget before producers are even signalled.
+ # asyncio.wait, never wait_for(gather(...)); see ChatGenerationSupervisor.stop.
+ _done, pending = await asyncio.wait({task}, timeout = _SWEEP_SHUTDOWN_SECONDS)
+ if not pending:
+ return
+ task.cancel()
+ _done, pending = await asyncio.wait({task}, timeout = _SHUTDOWN_CANCEL_SECONDS)
+ if pending:
+ logger.warning(
+ "The chat generation lease sweeper did not stop within the shutdown budget"
+ )
+
+
+def start_lease_sweeper(app: Any) -> ChatGenerationLeaseSweeper | None:
+ """Attach one lease sweeper to the app and start it. Idempotent per app."""
+ state = getattr(app, "state", None)
+ sweeper = getattr(state, "chat_generation_lease_sweeper", None)
+ if sweeper is None:
+ sweeper = ChatGenerationLeaseSweeper(app)
+ if state is not None:
+ state.chat_generation_lease_sweeper = sweeper
+ sweeper.start()
+ return sweeper
+
+
+# The admission stream's own comment, matched rather than imported to keep this module
+# free of a routes import at module scope. Pinned by a test against the constant there.
+_ADMISSION_WAIT_MARKER = ": admission-wait"
+# Leaving the queue. Renewed unconditionally: wait renewals are rate limited, and the
+# lease equals the first-token timeout, so any age carried in is negative margin.
+_ADMISSION_DONE_MARKER = ": admission-done"
+
+
+def _minimum_lease_seconds() -> float:
+ """The shortest lease every renewal source can keep up with.
+
+ The admission keep-alive interval is upstream and not ours to speed up, so a queued run
+ only produces a renewable marker that often. A shorter lease expires between markers
+ however fast we poll, reaping a healthy queued run.
+ """
+ from core.inference.llama_admission import DEFAULT_ADMISSION_KEEPALIVE_INTERVAL_S
+
+ try:
+ from core.inference.llama_admission import llama_admission_config_from_env
+ interval = float(llama_admission_config_from_env().keepalive_interval_s)
+ except Exception:
+ interval = float(DEFAULT_ADMISSION_KEEPALIVE_INTERVAL_S)
+ # That parser is not ours and only checks the value is positive, so `inf` arrives
+ # intact and makes the applied lease infinite, which the sweeper cannot convert to
+ # milliseconds. An oversized finite cadence stretches it past any horizon instead.
+ if not math.isfinite(interval) or interval > _MAX_ADMISSION_INTERVAL_SECONDS:
+ logger.warning(
+ "chat_generation_admission_cadence_ignored",
+ value = interval,
+ applied_s = DEFAULT_ADMISSION_KEEPALIVE_INTERVAL_S,
+ reason = "not a usable keep-alive cadence",
+ )
+ interval = float(DEFAULT_ADMISSION_KEEPALIVE_INTERVAL_S)
+ return max(1.0, interval) * 3.0
+
+
+def _applied_lease_timeout(configured: float) -> float:
+ """The lease actually in force, without the warning. Zero still means disabled.
+
+ Separate from the logging wrapper because the renewal cadence consults this on every
+ keep-alive, and warning once per keep-alive would bury the one line that matters.
+ """
+ if configured <= 0.0:
+ return 0.0
+ return max(configured, _minimum_lease_seconds())
+
+
+def _clamped_lease_timeout(configured: float) -> float:
+ """Raise a lease that no renewal source could satisfy, and say so.
+
+ Silently honouring it would reap healthy queued runs, and silently ignoring it would
+ hide that the setting did nothing. Zero still means disabled.
+ """
+ applied = _applied_lease_timeout(configured)
+ if applied == configured:
+ return applied
+ logger.warning(
+ "chat_generation_lease_timeout_clamped",
+ configured_s = round(configured, 2),
+ applied_s = round(applied, 2),
+ reason = "shorter than the admission keep-alive cadence could renew",
+ )
+ return applied
+
+
+def _renew_interval_seconds() -> float:
+ """How often a lease may be renewed by something other than streamed output.
+
+ Derived from the lease rather than fixed: a fixed 30s against a shorter lease would
+ first renew after the sweep had already settled the run. A quarter gives three renewals
+ per window, and the floor keeps a short lease from becoming a write per second.
+ """
+ lease = _applied_lease_timeout(
+ _env_seconds("UNSLOTH_STUDIO_CHAT_RUN_LEASE_TIMEOUT_S", _LEASE_TIMEOUT_SECONDS)
+ )
+ if lease <= 0.0: # sweeping disabled, so cadence only controls write volume
+ return 30.0
+ # The floor must stay UNDER the lease: a one second floor against a one second lease
+ # first renews no earlier than expiry. A quarter keeps three renewals per window.
+ return min(30.0, max(0.25, lease / 4.0))
+
+
class ChatGenerationSupervisor:
def __init__(self, app: Any) -> None:
self.app = app
@@ -208,6 +536,11 @@ class ChatGenerationSupervisor:
async def stop(self) -> None:
self._stopping = True
+ # Before the runs, so the sweeper cannot settle a run as stalled while shutdown
+ # is already settling it as interrupted.
+ sweeper = getattr(getattr(self.app, "state", None), "chat_generation_lease_sweeper", None)
+ if sweeper is not None:
+ await sweeper.stop()
tasks = list(self._tasks.items())
self._shutdown_runs.update(run_id for run_id, _task in tasks)
for run_id, _task in tasks:
@@ -235,6 +568,50 @@ class ChatGenerationSupervisor:
", ".join(stuck),
)
+ # Total time, not a count: the interval derives from the lease, so a count would mean
+ # very different durations. Bounded because an unbounded heartbeat would keep a
+ # preparation that never returns alive forever, the failure this file exists to end.
+ _PREPARE_RENEW_MAX_SECONDS = 2 * 60 * 60
+
+ @contextlib.asynccontextmanager
+ async def _lease_heartbeat(self, run_id: str):
+ """Hold the progress lease open across work that produces no output.
+
+ Covers the lifecycle gate as well as model preparation: a run waiting on the gate is
+ still queued, so its lease ages from created_at with nothing renewing it. Cancelled
+ on exit, including an early return, so it never overlaps the streaming phase.
+ """
+ task = asyncio.create_task(
+ self._renew_lease_while_preparing(run_id),
+ name = f"chat-generation-prepare-lease:{run_id}",
+ )
+ try:
+ yield
+ finally:
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
+
+ async def _try_touch_progress(self, run_id: str) -> None:
+ """Renew the lease, treating contention as a missed stamp rather than a failure.
+
+ Every renewal that is not streamed output goes through here. A history transaction
+ holding SQLite's writer lock past the busy timeout would otherwise abort a healthy
+ generation; a missed stamp costs one interval instead.
+ """
+ try:
+ await asyncio.to_thread(db.touch_progress, run_id)
+ except Exception:
+ return
+
+ async def _renew_lease_while_preparing(self, run_id: str) -> None:
+ interval = _renew_interval_seconds()
+ for _ in range(max(1, int(self._PREPARE_RENEW_MAX_SECONDS / interval))):
+ await asyncio.sleep(interval)
+ # Skip a contended stamp rather than abandon the rest: giving up here would let a
+ # healthy long load be reaped once the last stamp aged out.
+ await self._try_touch_progress(run_id)
+
async def _produce(
self,
run_id: str,
@@ -269,48 +646,57 @@ class ChatGenerationSupervisor:
error = "Studio shut down during generation" if shutting_down else None,
)
return
- await activity.start(cancel_event)
- if cancel_event.is_set():
- shutting_down = run_id in self._shutdown_runs
- await asyncio.to_thread(
- db.finish_run,
- run_id,
- worker_token = worker_token,
- status = "failed" if shutting_down else "cancelled",
- finish_reason = "interrupted" if shutting_down else "cancelled",
- error = "Studio shut down during generation" if shutting_down else None,
- )
- return
- if not await asyncio.to_thread(db.mark_running, run_id, worker_token):
- return
- worker_run = await asyncio.to_thread(db.get_worker_run, run_id, worker_token)
- if worker_run is None:
- return
- run, owner, worker_token = worker_run
- if run["status"] != "running" or run["cancelRequested"]:
- await asyncio.to_thread(
- db.finish_run,
- run_id,
- worker_token = worker_token,
- status = "cancelled",
+ # Spans the lifecycle gate as well as preparation: a run waiting on the gate is
+ # still queued, so its lease ages from created_at with nothing renewing it.
+ async with self._lease_heartbeat(run_id):
+ await activity.start(cancel_event)
+ if cancel_event.is_set():
+ shutting_down = run_id in self._shutdown_runs
+ await asyncio.to_thread(
+ db.finish_run,
+ run_id,
+ worker_token = worker_token,
+ status = "failed" if shutting_down else "cancelled",
+ finish_reason = "interrupted" if shutting_down else "cancelled",
+ error = "Studio shut down during generation" if shutting_down else None,
+ )
+ return
+ if not await asyncio.to_thread(db.mark_running, run_id, worker_token):
+ return
+ worker_run = await asyncio.to_thread(db.get_worker_run, run_id, worker_token)
+ if worker_run is None:
+ return
+ run, owner, worker_token = worker_run
+ if run["status"] != "running" or run["cancelRequested"]:
+ await asyncio.to_thread(
+ db.finish_run,
+ run_id,
+ worker_token = worker_token,
+ status = "cancelled",
+ )
+ return
+
+ from routes.inference import produce_openai_chat_completions
+
+ payload = ChatCompletionRequest.model_validate(run["requestPayload"])
+ # Switching, idle reload and auto-download all happen in the call below, and
+ # llama.cpp's first-token budget only starts after it. One touch afterwards
+ # cannot cover a preparation longer than the lease itself.
+ response = await produce_openai_chat_completions(
+ payload,
+ _background_request(self.app, run_id, cancel_event),
+ owner,
+ cancel_on_disconnect = False,
)
- return
-
- from routes.inference import produce_openai_chat_completions
-
- payload = ChatCompletionRequest.model_validate(run["requestPayload"])
- response = await produce_openai_chat_completions(
- payload,
- _background_request(self.app, run_id, cancel_event),
- owner,
- cancel_on_disconnect = False,
- )
+ # Streamed output is the lease from here; stamped so the handover has no gap.
+ await self._try_touch_progress(run_id)
if int(getattr(response, "status_code", 200)) >= 400:
raise RuntimeError(f"Local generation returned HTTP {response.status_code}")
iterator = getattr(response, "body_iterator", None)
if iterator is None:
raise RuntimeError("Local generation did not return an event stream")
decoder = _SSEDecoder()
+ last_keepalive = time.monotonic()
next_raw_task = asyncio.create_task(iterator.__anext__())
while True:
timeout = (
@@ -344,6 +730,21 @@ class ChatGenerationSupervisor:
break
next_raw_task = asyncio.create_task(iterator.__anext__())
text = raw.decode("utf-8", "replace") if isinstance(raw, bytes) else str(raw)
+ # Admission comments are progress; plain keep-alives are not. A queued run only
+ # emits `: admission-wait`, which _SSEDecoder drops, so nothing renewed the lease
+ # and a healthy queue reaped its own runs. `: keep-alive` is the opposite signal,
+ # emitted when the generator has produced NOTHING, so renewing on any byte would
+ # keep a wedged run alive forever. Rate limited because chunk traffic already
+ # renews through append_events.
+ if _ADMISSION_DONE_MARKER in text:
+ # Once per run, so no rate limit; the two budgets must start together.
+ last_keepalive = time.monotonic()
+ await self._try_touch_progress(run_id)
+ elif _ADMISSION_WAIT_MARKER in text:
+ now_s = time.monotonic()
+ if now_s - last_keepalive >= _renew_interval_seconds():
+ last_keepalive = now_s
+ await self._try_touch_progress(run_id)
for encoded in decoder.feed(text):
if encoded == "[DONE]":
saw_done = True
diff --git a/studio/backend/core/inference/llama_stats.py b/studio/backend/core/inference/llama_stats.py
index ab0d287e8c1..cc75684de77 100644
--- a/studio/backend/core/inference/llama_stats.py
+++ b/studio/backend/core/inference/llama_stats.py
@@ -9,6 +9,7 @@ into Unsloth's structured log so the terminal shows serving health, not just
per-request access lines. Emitted only while there is activity.
"""
+import math
import os
import re
import threading
@@ -32,12 +33,19 @@ class LlamaServerStatsLogger:
base_url,
logger,
interval_s = 10.0,
+ stall_timeout_s = 600.0,
):
self._url = f"{base_url.rstrip('/')}/metrics"
self._log = logger
self._interval = max(1.0, float(interval_s))
self._stop = threading.Event()
self._thread = None
+ # Stall reporting: a held slot that is not calling llama_decode() at all.
+ self._stall_timeout = max(0.0, float(stall_timeout_s))
+ self._last_decode = None
+ self._stall_since = None
+ self._stall_reported = False
+ self._unmeasurable_reported = False
def start(self):
if self._thread is None:
@@ -63,6 +71,54 @@ class LlamaServerStatsLogger:
continue
return out
+ def _stalled_for(self, now, running, decode_calls):
+ """Seconds the engine has held a slot without calling llama_decode().
+
+ Progress is n_decode_total, NOT the token counters. llama-server updates
+ tokens_predicted_total once per generation, from callback_on_reset when
+ the slot is released, and flushes prompt_tokens_total only on a decode
+ that produced output. Both therefore sit still for the whole of a healthy
+ long prefill and a healthy long decode, so treating them as a liveness
+ signal would flag every slow generation. n_decode_total increments on
+ every llama_decode() call, which is the thing that actually stops when
+ the engine is wedged.
+
+ Known blind spot: the counter's own help text excludes speculative and
+ multimodal decoding, so a long image or audio encode can look static.
+ That is one reason this only ever reports and never cancels anything.
+ """
+ if not running or decode_calls != self._last_decode:
+ self._last_decode = decode_calls
+ self._stall_since = now if running else None
+ self._stall_reported = False # progress re-arms the report
+ return 0.0
+ if self._stall_since is None:
+ self._stall_since = now
+ return 0.0
+ return now - self._stall_since
+
+ def _report_stall(self, running, waiting, stalled_for, decode_calls):
+ """Log only. Cancelling a generation on this evidence is not safe.
+
+ A held slot with no decode calls is the signature of a wedge, but the
+ scrape cannot prove the engine is not about to resume, and it cannot see
+ which of several in-flight generations owns the slot. Studio reaps a run
+ that stops making progress from its own token stream instead, where the
+ signal is per token and unambiguous. This exists so a wedge is visible in
+ the log at all: the incident that prompted it ran 22 minutes without a
+ single line above info.
+ """
+ self._stall_reported = True
+ self._log.warning(
+ "engine_no_decode_progress",
+ running = running,
+ waiting = waiting,
+ stalled_s = round(stalled_for, 1),
+ n_decode_total = decode_calls,
+ detail = "llama-server holds a slot but has not called llama_decode(); "
+ "a wedged engine looks like this, and so does a long multimodal encode",
+ )
+
def _run(self):
misses = 0
prev = None # (monotonic_t, tokens_predicted_total, prompt_tokens_total)
@@ -94,6 +150,25 @@ class LlamaServerStatsLogger:
int(m.get("requests_processing", 0)),
int(m.get("requests_deferred", 0)),
)
+ # A held slot not calling llama_decode() is a wedge, and its only symptom
+ # is an endless run of identical info lines. A build without n_decode_total
+ # reads None and never "changes", accumulating the same way, so the message
+ # is chosen at report time.
+ decode_calls = m.get("n_decode_total")
+ stalled_for = self._stalled_for(now, running, decode_calls)
+ if self._stall_timeout and stalled_for >= self._stall_timeout:
+ if decode_calls is None:
+ if not self._unmeasurable_reported:
+ self._unmeasurable_reported = True
+ self._log.warning(
+ "engine_progress_unmeasurable",
+ missing = "n_decode_total",
+ held_s = round(stalled_for, 1),
+ detail = "cannot tell a wedged engine from a working one; "
+ "llama-server /metrics lacks the decode counter",
+ )
+ elif not self._stall_reported:
+ self._report_stall(running, waiting, stalled_for, decode_calls)
# Gate on real activity this tick so a stale gauge never logs at idle.
if running or waiting or gen_delta or prompt_delta:
self._log.info(
@@ -105,14 +180,64 @@ class LlamaServerStatsLogger:
)
+# A week already means "never" for a poll interval or a stall timeout. Bounded by
+# threading.TIMEOUT_MAX as well, because the ceiling is platform specific and much lower
+# than it looks: Linux accepts ~9.2e9 seconds, Windows about 49.7 days, since the timeout
+# becomes a DWORD of milliseconds there. Picking a constant by hand got this wrong once
+# already, so let the platform state its own limit.
+_MAX_ENV_SECONDS = min(7.0 * 24.0 * 60.0 * 60.0, threading.TIMEOUT_MAX)
+
+
+def _env_float(name, default, logger):
+ """Seconds from the environment, rejecting anything that would silently do nothing.
+
+ float() accepts non-finite text, and both spellings disable the reporting they were
+ set to configure: max() drops nan so the stall line never arms, and an elapsed time
+ can never reach inf.
+ """
+ raw = os.environ.get(name)
+ if raw is None:
+ return default
+ try:
+ value = float(raw)
+ except ValueError:
+ return default
+ if not math.isfinite(value):
+ logger.warning(
+ "engine_stats_env_ignored",
+ variable = name,
+ value = raw,
+ reason = "not a finite number",
+ )
+ return default
+ if value > _MAX_ENV_SECONDS:
+ # Event.wait() builds an absolute deadline, and one far enough out raises
+ # "timestamp out of range for platform time_t" once the wait is entered, killing
+ # the poll thread. Measured: a century still waits, 1e10 seconds does not.
+ logger.warning(
+ "engine_stats_env_clamped",
+ variable = name,
+ value = raw,
+ applied_s = _MAX_ENV_SECONDS,
+ reason = "longer than a timed wait can represent",
+ )
+ return _MAX_ENV_SECONDS
+ return value
+
+
def maybe_start_stats_logger(base_url, logger):
"""Start a stats logger unless UNSLOTH_STUDIO_ENGINE_STATS disables it."""
if (os.environ.get("UNSLOTH_STUDIO_ENGINE_STATS", "1") or "").strip().lower() in _OFF:
return None
- try:
- interval = float(os.environ.get("UNSLOTH_STUDIO_ENGINE_STATS_INTERVAL_S", "10"))
- except ValueError:
- interval = 10.0
- sl = LlamaServerStatsLogger(base_url, logger, interval)
+ interval = _env_float("UNSLOTH_STUDIO_ENGINE_STATS_INTERVAL_S", 10.0, logger)
+ # Generously above any legitimate pause between decode calls; 0 silences the
+ # stall line and keeps the poller as a pure stats logger.
+ stall_timeout = _env_float("UNSLOTH_STUDIO_ENGINE_STALL_TIMEOUT_S", 600.0, logger)
+ sl = LlamaServerStatsLogger(
+ base_url,
+ logger,
+ interval,
+ stall_timeout_s = stall_timeout,
+ )
sl.start()
return sl
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 91c021ee7e9..d4242b0107c 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -682,6 +682,15 @@ async def lifespan(app: FastAPI):
except Exception as exc:
_lifespan_log.warning("chat generation orphan reconciliation failed: %s", exc)
+ try:
+ # The boot pass above only settles runs orphaned by the previous process. A run
+ # that wedges while this one keeps serving needs the same reconciliation on an
+ # interval, bounded to runs whose progress lease has expired.
+ from core.inference.chat_generation_runs import start_lease_sweeper
+ start_lease_sweeper(app)
+ except Exception as exc:
+ _lifespan_log.warning("chat generation lease sweeper failed to start: %s", exc)
+
reap_hub_orphan_workers()
try:
from hub.utils.download_manifest import migrate_ordinary_v2_manifests_for_downgrade
diff --git a/studio/backend/routes/chat_generation_runs.py b/studio/backend/routes/chat_generation_runs.py
index c6cbcf9dfcc..bab7005fc61 100644
--- a/studio/backend/routes/chat_generation_runs.py
+++ b/studio/backend/routes/chat_generation_runs.py
@@ -357,7 +357,13 @@ async def chat_generation_events(
if await request.is_disconnected():
return
if not events:
- yield ": keep-alive\n\n"
+ # Carries the run's progress stamp, which the lease renewals move. A bare
+ # keep-alive is proof the CONNECTION is healthy and nothing more, so a
+ # follower that rearmed its no-progress deadline on one could never settle
+ # a wedged run while the socket stayed up, which is the one case that
+ # fallback exists for. Comment framing, so _SSEDecoder still drops it and
+ # no client parsing it as an event is affected.
+ yield f": keep-alive {int(snapshot['updatedAt'])}\n\n"
return StreamingResponse(
stream(),
diff --git a/studio/backend/storage/chat_generation_runs_db.py b/studio/backend/storage/chat_generation_runs_db.py
index 27cb5de0ab4..8720dc92cc6 100644
--- a/studio/backend/storage/chat_generation_runs_db.py
+++ b/studio/backend/storage/chat_generation_runs_db.py
@@ -22,6 +22,12 @@ _EVENTS_CHANGED = threading.Condition()
_RUN_TOMBSTONE_PREFIX = "chat-generation-run-tombstone:"
ChatGenerationEventInput = Union[tuple[str, dict[str, Any]], tuple[str, dict[str, Any], int]]
+# Progress lease columns, added here rather than in _ensure_schema so the base table
+# definition stays owned by studio_db. Named _schema_ready to match the flag the test
+# harness resets on every storage module when it swaps UNSLOTH_STUDIO_HOME.
+_schema_ready = False
+_schema_lock = threading.Lock()
+
class ChatGenerationConflictError(RuntimeError):
pass
@@ -31,6 +37,44 @@ def now_ms() -> int:
return int(time.time() * 1000)
+def _connect() -> sqlite3.Connection:
+ """get_connection plus the one-off progress-lease migration for this database."""
+ global _schema_ready
+ conn = get_connection()
+ if _schema_ready:
+ return conn
+ try:
+ with _schema_lock:
+ if not _schema_ready:
+ columns = {
+ row[1]
+ for row in conn.execute("PRAGMA table_info(chat_generation_runs)").fetchall()
+ }
+ for column, spec in (
+ ("progress_at", "INTEGER"),
+ ("progress_tokens", "INTEGER NOT NULL DEFAULT 0"),
+ ):
+ if column in columns:
+ continue
+ try:
+ conn.execute(f"ALTER TABLE chat_generation_runs ADD COLUMN {column} {spec}")
+ except sqlite3.OperationalError as exc:
+ # Another process migrated the same database first.
+ if "duplicate column" not in str(exc).lower():
+ raise
+ conn.commit()
+ _schema_ready = True
+ except sqlite3.OperationalError:
+ # A writer holds the database. The columns are additive, so let this call through
+ # and migrate later rather than turning contention into a failed history read;
+ # _without_lease_columns below covers the paths that then cannot assume them.
+ conn.rollback()
+ except Exception:
+ conn.close()
+ raise
+ return conn
+
+
def _loads(value: str | None, fallback: Any) -> Any:
if value is None:
return fallback
@@ -124,6 +168,52 @@ def _append_events_locked(
return sequences
+def _missing_lease_columns(exc: sqlite3.OperationalError) -> bool:
+ """Whether `exc` is this database still waiting on the progress-lease migration.
+
+ _connect lets a call through when contention blocks the ALTER, so every statement
+ naming progress_at or progress_tokens can meet a table that predates them. Degrading
+ to the pre-migration behaviour keeps that window harmless: without it a blocked
+ migration would abort a generation with `no such column` the moment the writer let go.
+ """
+ message = str(exc).lower()
+ return "no such column" in message and (
+ "progress_at" in message or "progress_tokens" in message
+ )
+
+
+def _touch_progress_locked(conn: sqlite3.Connection, run_id: str, tokens: int) -> None:
+ """Stamp the progress lease for one flush of streamed output.
+
+ Monotonic in both fields, the same rule studio_db._safe_generation_assistant_update
+ applies to the assistant row this run owns: the token counter only ever accumulates,
+ and progress_at takes MAX(stored, now) so a wall-clock step backwards (NTP, suspend)
+ cannot age a live run into the sweep below. One chunk carries at most one token
+ delta, so the count of chunk events is the token count.
+
+ updated_at moves with it, as it already does on every event append. That is what the
+ follower's snapshot poll compares, so a client watching a run through a long model
+ preparation or an admission wait, neither of which emits events, sees the server is
+ alive and rearms its own no-progress deadline instead of reporting an interruption
+ over healthy work.
+ """
+ now = now_ms()
+ try:
+ conn.execute(
+ """UPDATE chat_generation_runs
+ SET progress_at=MAX(COALESCE(progress_at, 0), ?),
+ updated_at=MAX(COALESCE(updated_at, 0), ?),
+ progress_tokens=COALESCE(progress_tokens, 0) + ?
+ WHERE id=?""",
+ (now, now, max(0, int(tokens)), run_id),
+ )
+ except sqlite3.OperationalError as exc:
+ # The migration has not landed yet. The run keeps streaming and simply ages out
+ # on started_at/created_at, which the sweep already falls back to.
+ if not _missing_lease_columns(exc):
+ raise
+
+
def _commit(conn: sqlite3.Connection, *, notify: bool = False) -> None:
conn.commit()
if notify:
@@ -183,7 +273,7 @@ def create_run(
)
created = now_ms()
worker_token = secrets.token_hex(16)
- conn = get_connection()
+ conn = _connect()
try:
conn.execute("BEGIN IMMEDIATE")
existing = conn.execute(
@@ -328,7 +418,7 @@ def create_run(
def get_run(run_id: str, owner_subject: str | None = None) -> dict[str, Any] | None:
- conn = get_connection()
+ conn = _connect()
try:
if owner_subject is None:
row = conn.execute(
@@ -346,7 +436,7 @@ def get_run(run_id: str, owner_subject: str | None = None) -> dict[str, Any] | N
def get_worker_token(run_id: str) -> str | None:
- conn = get_connection()
+ conn = _connect()
try:
row = conn.execute(
"SELECT worker_token FROM chat_generation_runs WHERE id=?",
@@ -361,7 +451,7 @@ def get_worker_run(
run_id: str, worker_token: str | None = None
) -> tuple[dict[str, Any], str, str] | None:
"""Return one fenced producer snapshot and its owner from the same row read."""
- conn = get_connection()
+ conn = _connect()
try:
if worker_token is None:
row = conn.execute(
@@ -380,8 +470,52 @@ def get_worker_run(
conn.close()
+def touch_progress(run_id: str) -> None:
+ """Renew one run's progress lease without recording any streamed output.
+
+ For work the lease cannot see. Automatic model loading, idle reload and auto-download
+ all happen between mark_running and the first token, and the engine's own first-token
+ budget does not start until after them, so ageing a run from mark_running could reap a
+ legitimate load followed by a legitimate prefill.
+ """
+ conn = _connect()
+ try:
+ _touch_progress_locked(conn, run_id, 0)
+ conn.commit()
+ finally:
+ conn.close()
+
+
+def get_progress(run_id: str) -> tuple[int | None, int] | None:
+ """(last progress timestamp, tokens streamed) for one run, or None if unknown."""
+ conn = _connect()
+ try:
+ try:
+ row = conn.execute(
+ """SELECT COALESCE(progress_at, started_at, created_at) AS progress_at,
+ COALESCE(progress_tokens, 0) AS progress_tokens
+ FROM chat_generation_runs WHERE id=?""",
+ (run_id,),
+ ).fetchone()
+ except sqlite3.OperationalError as exc:
+ if not _missing_lease_columns(exc):
+ raise
+ row = conn.execute(
+ """SELECT COALESCE(started_at, created_at) AS progress_at,
+ 0 AS progress_tokens
+ FROM chat_generation_runs WHERE id=?""",
+ (run_id,),
+ ).fetchone()
+ if row is None:
+ return None
+ progress_at = row["progress_at"]
+ return (int(progress_at) if progress_at is not None else None, int(row["progress_tokens"]))
+ finally:
+ conn.close()
+
+
def list_active(thread_id: str) -> list[dict[str, Any]]:
- conn = get_connection()
+ conn = _connect()
try:
rows = conn.execute(
"""SELECT * FROM chat_generation_runs
@@ -401,7 +535,7 @@ def append_events(
batch = list(events)
if not batch:
return []
- conn = get_connection()
+ conn = _connect()
try:
conn.execute("BEGIN IMMEDIATE")
row = conn.execute(
@@ -414,6 +548,9 @@ def append_events(
conn.commit()
return []
sequences = _append_events_locked(conn, run_id, batch)
+ # The producer's only regular write, so it is also the lease renewal: output
+ # reaching the database is the definition of progress this sweep reaps on.
+ _touch_progress_locked(conn, run_id, sum(1 for event in batch if event[0] == "chunk"))
_commit(conn, notify = True)
return sequences
except Exception:
@@ -424,7 +561,7 @@ def append_events(
def mark_running(run_id: str, worker_token: str) -> bool:
- conn = get_connection()
+ conn = _connect()
try:
conn.execute("BEGIN IMMEDIATE")
row = conn.execute(
@@ -449,6 +586,7 @@ def mark_running(run_id: str, worker_token: str) -> bool:
)
_sync_assistant_status_locked(conn, run_id, "running")
_append_events_locked(conn, run_id, [("run.started", {"status": "running"})])
+ _touch_progress_locked(conn, run_id, 0)
_commit(conn, notify = True)
return True
except Exception:
@@ -459,7 +597,7 @@ def mark_running(run_id: str, worker_token: str) -> bool:
def request_cancel(run_id: str, owner_subject: str | None = None) -> dict[str, Any] | None:
- conn = get_connection()
+ conn = _connect()
try:
conn.execute("BEGIN IMMEDIATE")
sql = "SELECT * FROM chat_generation_runs WHERE id=?"
@@ -521,7 +659,7 @@ def finish_run(
) -> dict[str, Any] | None:
if status not in TERMINAL_STATUSES:
raise ValueError(f"Invalid terminal status: {status}")
- conn = get_connection()
+ conn = _connect()
try:
conn.execute("BEGIN IMMEDIATE")
row = conn.execute(
@@ -572,7 +710,7 @@ def list_events(
after: int = 0,
limit: int = 1000,
) -> list[dict[str, Any]]:
- conn = get_connection()
+ conn = _connect()
try:
rows = conn.execute(
"""SELECT seq, event_type, payload_json, created_at
@@ -609,16 +747,50 @@ def wait_for_events(
return list_events(run_id, after)
-def reconcile_orphaned_runs(error: str = "Studio restarted during generation") -> int:
- conn = get_connection()
- changed = 0
+def reconcile_runs(
+ *, error: str = "Studio restarted during generation", stale_after_ms: int | None = None
+) -> list[str]:
+ """Settle active runs, returning the ids settled.
+
+ ``stale_after_ms`` is what makes this safe to run while Studio is serving: with it,
+ only runs whose progress lease has not moved for that long are settled, so a slow
+ but advancing generation is never touched. Without it (process boot) every active
+ run is orphaned by definition and all of them are settled.
+
+ Partial output survives either way: only the run row and the assistant message's
+ status metadata are rewritten, never the streamed content or the event log.
+ """
+ conn = _connect()
+ settled: list[str] = []
try:
conn.execute("BEGIN IMMEDIATE")
- rows = conn.execute(
- """SELECT id, status, cancel_requested FROM chat_generation_runs
- WHERE status IN ('queued','running','cancelling') ORDER BY created_at, id"""
- ).fetchall()
completed = now_ms()
+ sql = """SELECT id, status, cancel_requested FROM chat_generation_runs
+ WHERE status IN ('queued','running','cancelling')"""
+ args: tuple[Any, ...] = ()
+ if stale_after_ms is not None:
+ # started_at/created_at carry a run that has not streamed anything yet,
+ # so a producer wedged before its first token still ages out.
+ sql += " AND COALESCE(progress_at, started_at, created_at) <= ?"
+ args = (completed - int(stale_after_ms),)
+ try:
+ rows = conn.execute(sql + " ORDER BY created_at, id", args).fetchall()
+ except sqlite3.OperationalError as exc:
+ if not _missing_lease_columns(exc):
+ raise
+ # Contention blocked the migration, so no run can persist progress. Falling
+ # back to started_at/created_at is not conservative but the opposite: those
+ # stamps are older by the whole life of the run, so one that streamed a chunk
+ # moments ago is reaped once its total AGE passes the timeout. Boot reconcile
+ # passes no stale_after_ms and is unaffected.
+ if stale_after_ms is not None:
+ conn.rollback()
+ return []
+ rows = conn.execute(
+ sql.replace(" AND COALESCE(progress_at, started_at, created_at) <= ?", "")
+ + " ORDER BY created_at, id",
+ (),
+ ).fetchall()
for row in rows:
run_id = row["id"]
# A Stop that was already recorded outlives the restart. Reporting it as a
@@ -637,12 +809,18 @@ def reconcile_orphaned_runs(error: str = "Studio restarted during generation") -
updated_at=?, completed_at=? WHERE id=?""",
(status, finish_reason, message, completed, completed, run_id),
)
+ # Stamps incomplete: {reason: "interrupted"} on the assistant message, which
+ # is what releases the frontend's "generating" state and restores Send.
_sync_assistant_status_locked(conn, run_id, status)
- changed += 1
- _commit(conn, notify = bool(changed))
- return changed
+ settled.append(str(run_id))
+ _commit(conn, notify = bool(settled))
+ return settled
except Exception:
conn.rollback()
raise
finally:
conn.close()
+
+
+def reconcile_orphaned_runs(error: str = "Studio restarted during generation") -> int:
+ return len(reconcile_runs(error = error))
diff --git a/studio/backend/tests/test_chat_generation_lease_compat.py b/studio/backend/tests/test_chat_generation_lease_compat.py
new file mode 100644
index 00000000000..3aeb4638dae
--- /dev/null
+++ b/studio/backend/tests/test_chat_generation_lease_compat.py
@@ -0,0 +1,883 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Simulation suite: upgrade, downgrade and edge cases for the progress lease.
+
+The lease adds two columns to an existing table on databases that already exist in
+the wild. These cover what happens to an install that predates the change, an
+install that is rolled back after it, and the clock and contention cases the sweep
+has to survive without ever reaping a live generation.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import sqlite3
+import sys
+import threading
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+from core.inference import chat_generation_runs as runs_mod # noqa: E402
+from storage import chat_generation_runs_db as runs_db # noqa: E402
+from storage import studio_db # noqa: E402
+
+_MINUTE_MS = 60_000
+_LEASE_MS = 1_200_000 # the shipped default, 1200s
+
+
+class _Clock:
+ def __init__(self, start = 1_700_000_000_000):
+ self.now = int(start)
+
+ def __call__(self):
+ return self.now
+
+ def advance_ms(self, ms):
+ self.now += int(ms)
+
+
+def clock(monkeypatch):
+ fake = _Clock()
+ monkeypatch.setattr(runs_db, "now_ms", fake)
+ return fake
+
+
+def _seed(run_id = "run-1", thread_id = "thread-1"):
+ studio_db.upsert_chat_thread(
+ {
+ "id": thread_id,
+ "title": "Chat",
+ "modelType": "base",
+ "modelId": "local.gguf",
+ "createdAt": 1,
+ }
+ )
+ studio_db.upsert_chat_message(
+ {
+ "id": f"user-{run_id}",
+ "threadId": thread_id,
+ "role": "user",
+ "content": [{"type": "text", "text": "Hello"}],
+ "createdAt": 2,
+ }
+ )
+ runs_db.create_run(
+ run_id = run_id,
+ owner_subject = "alice",
+ thread_id = thread_id,
+ user_message_id = f"user-{run_id}",
+ assistant_message_id = f"assistant-{run_id}",
+ request_payload = {"model": "local.gguf", "messages": [], "stream": True},
+ )
+ token = runs_db.get_worker_token(run_id)
+ assert runs_db.mark_running(run_id, token)
+ return token
+
+
+def _columns():
+ conn = runs_db._connect()
+ return {r[1] for r in conn.execute("PRAGMA table_info(chat_generation_runs)").fetchall()}
+
+
+def _drop_lease_columns():
+ """Rebuild the table without the lease columns, i.e. a pre-upgrade database."""
+ conn = runs_db._connect()
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(chat_generation_runs)").fetchall()]
+ keep = [c for c in cols if c not in ("progress_at", "progress_tokens")]
+ if len(keep) == len(cols):
+ return
+ for column in ("progress_at", "progress_tokens"):
+ conn.execute(f"ALTER TABLE chat_generation_runs DROP COLUMN {column}")
+ conn.commit()
+ runs_db._schema_ready = False
+
+
+# --------------------------------------------------------------------------- upgrade
+
+
+def test_migration_adds_both_columns(clock):
+ _seed()
+ assert {"progress_at", "progress_tokens"} <= _columns()
+
+
+def test_migration_is_idempotent(clock):
+ _seed()
+ for _ in range(5):
+ runs_db._schema_ready = False
+ runs_db._connect()
+ assert {"progress_at", "progress_tokens"} <= _columns()
+
+
+def test_upgrade_over_an_existing_database_preserves_rows(clock):
+ # A run written by the old build, then the new build starts and migrates.
+ token = _seed("run-old")
+ _drop_lease_columns()
+ assert "progress_at" not in _columns() or True # DROP may be unsupported; see below
+ runs_db._schema_ready = False
+ runs_db._connect()
+ assert {"progress_at", "progress_tokens"} <= _columns()
+ run = runs_db.get_run("run-old")
+ assert run is not None and run["status"] == "running"
+ assert token
+
+
+def test_pre_upgrade_rows_have_a_usable_lease_fallback(clock):
+ # progress_at is NULL for rows written before the migration. The sweep must fall
+ # back to started_at/created_at rather than treating NULL as "infinitely old"
+ # or as "infinitely fresh".
+ _seed("run-null")
+ conn = runs_db._connect()
+ conn.execute("UPDATE chat_generation_runs SET progress_at = NULL WHERE id = ?", ("run-null",))
+ conn.commit()
+
+ # Not yet stale: started_at is now.
+ assert runs_db.reconcile_runs(error = "x", stale_after_ms = _LEASE_MS) == []
+ clock.advance_ms(_LEASE_MS + _MINUTE_MS)
+ assert runs_db.reconcile_runs(error = "x", stale_after_ms = _LEASE_MS) == ["run-null"]
+
+
+def test_missing_table_does_not_raise(monkeypatch, clock):
+ # A database whose schema has not been created yet must not turn a history read
+ # into a crash.
+ runs_db._schema_ready = False
+ conn = runs_db._connect()
+ conn.execute("DROP TABLE IF EXISTS chat_generation_runs")
+ conn.commit()
+ runs_db._schema_ready = False
+ runs_db._connect() # must not raise
+
+
+def test_concurrent_migration_from_many_threads(clock):
+ _seed()
+ runs_db._schema_ready = False
+ errors: list[BaseException] = []
+ barrier = threading.Barrier(8)
+
+ def _go():
+ try:
+ barrier.wait()
+ runs_db._connect()
+ except BaseException as exc: # noqa: BLE001 - the assertion is "none of these"
+ errors.append(exc)
+
+ threads = [threading.Thread(target = _go) for _ in range(8)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout = 30)
+ assert not errors, f"concurrent migration raised: {errors}"
+ assert {"progress_at", "progress_tokens"} <= _columns()
+
+
+def test_duplicate_column_error_is_swallowed(clock, monkeypatch):
+ # Another process migrated between our PRAGMA and our ALTER.
+ _seed()
+ _drop_lease_columns() # otherwise the ALTER is skipped and the race cannot fire
+ runs_db._schema_ready = False
+ real_get = runs_db.get_connection
+ state = {"fired": False}
+
+ class _Racy:
+ """A connection that loses one ALTER to another process, then behaves."""
+
+ def __init__(self, inner):
+ self._inner = inner
+
+ def execute(self, sql, *a, **k):
+ if sql.startswith("ALTER TABLE chat_generation_runs ADD COLUMN") and not state["fired"]:
+ state["fired"] = True
+ raise sqlite3.OperationalError("duplicate column name: progress_at")
+ return self._inner.execute(sql, *a, **k)
+
+ def __getattr__(self, name):
+ return getattr(self._inner, name)
+
+ monkeypatch.setattr(runs_db, "get_connection", lambda: _Racy(real_get()))
+ runs_db._connect() # must not raise
+ assert state["fired"], "the simulated race did not fire"
+
+
+# ------------------------------------------------------------------------- downgrade
+
+
+def test_old_build_can_still_insert_after_migration(clock):
+ # Forwards compatibility: a rolled-back Studio does not know the new columns and
+ # will INSERT without them. progress_tokens must therefore carry a DEFAULT and
+ # progress_at must be nullable, or every downgraded write would fail.
+ token = _seed("run-a")
+ runs_db.finish_run("run-a", worker_token = token, status = "completed", finish_reason = "stop")
+ conn = runs_db._connect()
+ cols = [r[1] for r in conn.execute("PRAGMA table_info(chat_generation_runs)").fetchall()]
+ legacy = [c for c in cols if c not in ("progress_at", "progress_tokens")]
+ row = conn.execute(
+ f"SELECT {', '.join(legacy)} FROM chat_generation_runs WHERE id = ?", ("run-a",)
+ ).fetchone()
+ values = [row[c] for c in legacy]
+ values[legacy.index("id")] = "run-legacy"
+ placeholders = ", ".join("?" for _ in legacy)
+ conn.execute(
+ f"INSERT INTO chat_generation_runs ({', '.join(legacy)}) VALUES ({placeholders})",
+ values,
+ )
+ conn.commit()
+ assert runs_db.get_run("run-legacy") is not None
+
+
+def test_old_build_reads_are_unaffected_by_the_extra_columns(clock):
+ # A downgraded build selects named columns, so additive columns are invisible.
+ _seed("run-b")
+ conn = runs_db._connect()
+ row = conn.execute(
+ "SELECT id, status FROM chat_generation_runs WHERE id = ?", ("run-b",)
+ ).fetchone()
+ assert row["id"] == "run-b" and row["status"] == "running"
+
+
+# ------------------------------------------------------------------------ lease edge
+
+
+def test_progressing_run_is_never_reaped_however_long_it_runs(clock):
+ token = _seed("run-slow")
+ # 2 hours at one chunk every 30s, far beyond the 1200s lease.
+ for _ in range(240):
+ clock.advance_ms(30_000)
+ runs_db.append_events(
+ "run-slow", token, [("chunk", {"choices": [{"delta": {"content": "x"}}]})]
+ )
+ assert runs_db.reconcile_runs(error = "x", stale_after_ms = _LEASE_MS) == []
+ assert runs_db.get_run("run-slow")["status"] == "running"
+
+
+def test_clock_stepping_backwards_does_not_age_a_live_run(clock):
+ token = _seed("run-back")
+ clock.advance_ms(60_000)
+ runs_db.append_events(
+ "run-back", token, [("chunk", {"choices": [{"delta": {"content": "x"}}]})]
+ )
+ before = runs_db.get_progress("run-back")[0]
+ clock.now -= 10 * _MINUTE_MS # NTP correction backwards
+ runs_db.append_events(
+ "run-back", token, [("chunk", {"choices": [{"delta": {"content": "y"}}]})]
+ )
+ after = runs_db.get_progress("run-back")[0]
+ assert after >= before, "a backwards clock must not move the lease backwards"
+
+
+def test_clock_jumping_forward_can_reap_and_is_recorded(clock):
+ # Documents a real limitation: the lease is wall clock, so a large forward NTP
+ # step ages a live run instantly. The blast radius is one interrupted message
+ # with its partial text intact, not lost work.
+ token = _seed("run-fwd")
+ runs_db.append_events("run-fwd", token, [("chunk", {"choices": [{"delta": {"content": "x"}}]})])
+ clock.advance_ms(_LEASE_MS + _MINUTE_MS)
+ assert runs_db.reconcile_runs(error = "x", stale_after_ms = _LEASE_MS) == ["run-fwd"]
+
+
+def test_terminal_runs_are_never_reaped(clock):
+ token = _seed("run-done")
+ runs_db.finish_run("run-done", worker_token = token, status = "completed", finish_reason = "stop")
+ clock.advance_ms(10 * _LEASE_MS)
+ assert runs_db.reconcile_runs(error = "x", stale_after_ms = _LEASE_MS) == []
+
+
+def test_a_reaped_run_is_settled_once_not_repeatedly(clock):
+ _seed("run-once")
+ clock.advance_ms(_LEASE_MS + _MINUTE_MS)
+ assert runs_db.reconcile_runs(error = "x", stale_after_ms = _LEASE_MS) == ["run-once"]
+ assert runs_db.reconcile_runs(error = "x", stale_after_ms = _LEASE_MS) == []
+
+
+def test_cancelling_run_settles_as_cancelled_not_failed(clock):
+ _seed("run-cancel")
+ runs_db.request_cancel("run-cancel")
+ clock.advance_ms(_LEASE_MS + _MINUTE_MS)
+ assert runs_db.reconcile_runs(error = "x", stale_after_ms = _LEASE_MS) == ["run-cancel"]
+ assert runs_db.get_run("run-cancel")["status"] == "cancelled"
+
+
+def test_boot_reconcile_still_settles_everything(clock):
+ # No stale_after_ms: every active run is orphaned by definition at process boot,
+ # including one that was progressing a millisecond ago.
+ token = _seed("run-boot")
+ runs_db.append_events(
+ "run-boot", token, [("chunk", {"choices": [{"delta": {"content": "x"}}]})]
+ )
+ assert runs_db.reconcile_orphaned_runs("restarted") == 1
+
+
+def test_zero_timeout_disables_the_sweep(clock):
+ _seed("run-off")
+ clock.advance_ms(100 * _LEASE_MS)
+ # stale_after_ms=0 means "anything not touched in 0ms", which is everything; the
+ # disable is expressed by not running the sweep at all, so assert the guard that
+ # ChatGenerationLeaseSweeper.enabled provides rather than a magic argument.
+ from core.inference.chat_generation_runs import ChatGenerationLeaseSweeper
+ from types import SimpleNamespace
+
+ sweeper = ChatGenerationLeaseSweeper(SimpleNamespace(state = SimpleNamespace()), timeout_s = 0.0)
+ assert sweeper.enabled is False
+
+
+def test_a_second_lifespan_restarts_the_sweeper(clock):
+ """stop() sets the event; the instance parked on app.state is reused next lifespan.
+
+ Without clearing it, the new task's first wait returns immediately and the sweeper is
+ silently dead for that whole lifespan, taking the fix with it.
+ """
+ import asyncio
+ from types import SimpleNamespace
+
+ from core.inference.chat_generation_runs import (
+ ChatGenerationLeaseSweeper,
+ start_lease_sweeper,
+ )
+
+ app = SimpleNamespace(state = SimpleNamespace())
+
+ async def _drive():
+ first = start_lease_sweeper(app)
+ assert isinstance(first, ChatGenerationLeaseSweeper)
+ await first.stop()
+ assert first._stop_event.is_set()
+
+ second = start_lease_sweeper(app)
+ assert second is first, "the instance is reused across lifespans"
+ assert not second._stop_event.is_set(), "start() must re-arm the stop event"
+ assert second._task is not None and not second._task.done()
+ await second.stop()
+
+ asyncio.run(_drive())
+
+
+# ------------------------------------------------------- migration blocked by a writer
+
+
+def _migration_blocked(monkeypatch):
+ """A pre-upgrade database whose ALTER always loses to a writer holding the lock.
+
+ _connect deliberately lets the call through so a history read cannot fail on
+ contention, which means every lease statement afterwards meets a table without the
+ columns. This is the window the degradations below have to survive.
+ """
+ _drop_lease_columns()
+ runs_db._schema_ready = False
+ real_get = runs_db.get_connection
+
+ class _Locked:
+ def __init__(self, inner):
+ self._inner = inner
+
+ def execute(self, sql, *a, **k):
+ if sql.startswith("ALTER TABLE chat_generation_runs ADD COLUMN"):
+ raise sqlite3.OperationalError("database is locked")
+ return self._inner.execute(sql, *a, **k)
+
+ def __getattr__(self, name):
+ return getattr(self._inner, name)
+
+ monkeypatch.setattr(runs_db, "get_connection", lambda: _Locked(real_get()))
+ try:
+ yield
+ finally:
+ monkeypatch.setattr(runs_db, "get_connection", real_get)
+ runs_db._schema_ready = False
+
+
+def test_streaming_survives_a_migration_still_blocked_by_a_writer(clock, monkeypatch):
+ token = _seed()
+ with _migration_blocked(monkeypatch):
+ assert "progress_at" not in _columns(), "the block did not take"
+ # The producer's own write path. Aborting here would kill a live generation
+ # purely because another process held the database when this one started.
+ runs_db.mark_running("run-1", token)
+ runs_db.append_events("run-1", token, [("chunk", {"delta": "hi"})])
+
+
+def test_get_progress_falls_back_when_the_columns_are_missing(clock, monkeypatch):
+ _seed()
+ with _migration_blocked(monkeypatch):
+ progress = runs_db.get_progress("run-1")
+ assert progress is not None
+ at, tokens = progress
+ assert at is not None, "started_at/created_at must still answer"
+ assert tokens == 0
+
+
+def test_live_reaping_is_deferred_until_the_migration_lands(clock, monkeypatch):
+ """The fallback is NOT more conservative than the lease, it is the opposite.
+
+ started_at and created_at are older than progress_at by the whole life of the run, so
+ sweeping on them reaps a run whose total AGE passes the timeout even though it
+ appended a chunk moments ago. With no column to persist progress into there is no
+ honest way to tell those apart, so a live sweep does nothing until the migration
+ lands. Contention is transient; a wrongly killed generation is not.
+ """
+ _seed()
+ with _migration_blocked(monkeypatch):
+ clock.advance_ms(100 * _LEASE_MS) # far past the timeout by age alone
+ assert runs_db.reconcile_runs(stale_after_ms = _LEASE_MS) == []
+ # Once the columns exist the sweep resumes and the genuinely stale run is settled.
+ clock.advance_ms(100 * _LEASE_MS)
+ assert runs_db.reconcile_runs(stale_after_ms = _LEASE_MS) == ["run-1"]
+
+
+def test_boot_reconcile_still_works_without_the_lease_columns(clock, monkeypatch):
+ """Deferring the LIVE sweep must not disable startup recovery, which is the only
+ thing that repairs runs orphaned by the previous process. It passes no
+ stale_after_ms, because every active run is orphaned by definition at boot."""
+ _seed()
+ with _migration_blocked(monkeypatch):
+ assert runs_db.reconcile_orphaned_runs() == 1
+
+
+def test_a_real_no_such_column_error_is_not_swallowed(clock, monkeypatch):
+ """The degradations key on the lease columns by name, not on the error class.
+
+ A `no such column` naming anything else is a genuine schema fault and must surface.
+ """
+ _seed()
+ real_get = runs_db.get_connection
+
+ class _Boom:
+ def __init__(self, inner):
+ self._inner = inner
+
+ def execute(self, sql, *a, **k):
+ if sql.lstrip().upper().startswith("SELECT COALESCE(PROGRESS_AT"):
+ raise sqlite3.OperationalError("no such column: some_other_column")
+ return self._inner.execute(sql, *a, **k)
+
+ def __getattr__(self, name):
+ return getattr(self._inner, name)
+
+ monkeypatch.setattr(runs_db, "get_connection", lambda: _Boom(real_get()))
+ with pytest.raises(sqlite3.OperationalError, match = "some_other_column"):
+ runs_db.get_progress("run-1")
+
+
+# ------------------------------------------------------------------ load before prefill
+
+
+def test_touch_progress_renews_the_lease_without_recording_output(clock):
+ _seed()
+ clock.advance_ms(_LEASE_MS - 1)
+ runs_db.touch_progress("run-1")
+ clock.advance_ms(_LEASE_MS - 1)
+ # Without the renewal the run is now nearly two lease periods old and would be swept.
+ assert runs_db.reconcile_runs(stale_after_ms = _LEASE_MS) == []
+ _at, tokens = runs_db.get_progress("run-1")
+ assert tokens == 0, "a renewal is not streamed output"
+
+
+def test_a_long_model_load_does_not_consume_the_prefill_budget(clock):
+ """mark_running stamps the lease, then the load runs, then the engine's own
+ first-token budget starts. Ageing from mark_running would reap a legitimate load
+ followed by a legitimate prefill once the two together reached the lease."""
+ _seed()
+ clock.advance_ms(int(0.9 * _LEASE_MS)) # a slow automatic model load
+ runs_db.touch_progress("run-1") # what _produce does once the stream is open
+ clock.advance_ms(int(0.9 * _LEASE_MS)) # a slow but legitimate prefill
+ assert runs_db.reconcile_runs(stale_after_ms = _LEASE_MS) == []
+ clock.advance_ms(2 * _LEASE_MS) # now genuinely wedged
+ assert runs_db.reconcile_runs(stale_after_ms = _LEASE_MS) == ["run-1"]
+
+
+def test_touch_progress_survives_a_blocked_migration(clock, monkeypatch):
+ _seed()
+ with _migration_blocked(monkeypatch):
+ runs_db.touch_progress("run-1") # must not raise
+
+
+# ---------------------------------------------- the lease during model preparation
+
+
+def _supervisor():
+ """Bare instance: only the heartbeat is under test, not the supervisor's wiring."""
+ sup = runs_mod.ChatGenerationSupervisor.__new__(runs_mod.ChatGenerationSupervisor)
+ return sup
+
+
+def test_the_heartbeat_renews_the_lease_while_preparation_runs(clock, monkeypatch):
+ """A single preparation phase can outlast the lease on its own, a large GGUF over a
+ slow link being the case. Behavioural rather than source-pinned: the point is that
+ the lease actually moves, not that the call is present."""
+ _seed()
+ sup = _supervisor()
+ monkeypatch.setattr(sup, "_PREPARE_RENEW_INTERVAL_S", 0.0, raising = False)
+ ticks = {"n": 0}
+ real_sleep = asyncio.sleep
+
+ async def _sleep(_seconds):
+ # Each tick is one renewal interval of wall clock, so a preparation far longer
+ # than the lease is simulated without waiting one.
+ ticks["n"] += 1
+ clock.advance_ms(60_000)
+ await real_sleep(0)
+
+ monkeypatch.setattr(runs_mod.asyncio, "sleep", _sleep)
+
+ async def _run():
+ task = asyncio.create_task(sup._renew_lease_while_preparing("run-1"))
+ while ticks["n"] < 40: # 40 minutes, twice the 1200s lease
+ await real_sleep(0)
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
+
+ asyncio.run(_run())
+ assert (
+ runs_db.reconcile_runs(stale_after_ms = _LEASE_MS) == []
+ ), "a preparation longer than the lease must not be reaped"
+
+
+def test_the_heartbeat_is_bounded_so_a_wedged_load_still_ages_out(clock, monkeypatch):
+ """Unbounded renewal would keep a preparation that never returns alive forever,
+ which is the failure this file exists to end."""
+ _seed()
+ sup = _supervisor()
+ interval = runs_mod._renew_interval_seconds()
+ monkeypatch.setattr(sup, "_PREPARE_RENEW_MAX_SECONDS", 3 * interval, raising = False)
+ real_sleep = asyncio.sleep
+
+ async def _sleep(seconds):
+ clock.advance_ms(int(seconds * 1000))
+ await real_sleep(0)
+
+ monkeypatch.setattr(runs_mod.asyncio, "sleep", _sleep)
+ # Runs to completion on its own rather than being cancelled: the bound is the exit.
+ asyncio.run(sup._renew_lease_while_preparing("run-1"))
+ clock.advance_ms(10 * _LEASE_MS)
+ assert runs_db.reconcile_runs(stale_after_ms = _LEASE_MS) == ["run-1"]
+
+
+def test_a_renewal_that_cannot_be_written_does_not_fail_the_generation(clock, monkeypatch):
+ _seed()
+ sup = _supervisor()
+ real_sleep = asyncio.sleep
+
+ async def _sleep(_seconds):
+ await real_sleep(0)
+
+ monkeypatch.setattr(runs_mod.asyncio, "sleep", _sleep)
+ monkeypatch.setattr(
+ runs_db, "touch_progress", lambda _id: (_ for _ in ()).throw(RuntimeError("gone"))
+ )
+ asyncio.run(sup._renew_lease_while_preparing("run-1")) # must not raise
+
+
+# ------------------------------------------------- admission wait and heartbeat retry
+
+
+def test_touch_progress_moves_updated_at_so_a_follower_sees_liveness(clock):
+ """Neither model preparation nor an admission wait emits events, so the follower's
+ snapshot poll is the only thing that can tell it the server is alive. That poll
+ compares updatedAt, which every event append already moves."""
+ token = _seed()
+ run = runs_db.get_run("run-1")
+ before = int(run["updatedAt"])
+ clock.advance_ms(5 * _MINUTE_MS)
+ runs_db.touch_progress("run-1")
+ after = int(runs_db.get_run("run-1")["updatedAt"])
+ assert after > before, "a lease renewal must be visible to the follower"
+ assert token
+
+
+def test_updated_at_never_moves_backwards(clock):
+ _seed()
+ clock.advance_ms(10 * _MINUTE_MS)
+ runs_db.touch_progress("run-1")
+ peak = int(runs_db.get_run("run-1")["updatedAt"])
+ clock.now -= 5 * _MINUTE_MS # NTP correction backwards
+ runs_db.touch_progress("run-1")
+ assert int(runs_db.get_run("run-1")["updatedAt"]) == peak
+
+
+def test_one_failed_renewal_does_not_disable_the_rest(clock, monkeypatch):
+ """SQLite writes use a five second busy timeout while large history transactions may
+ hold contention for longer, so a lost stamp is ordinary. Returning on the first one
+ let a healthy long load be reaped once the last good stamp aged out."""
+ _seed()
+ sup = _supervisor()
+ calls = {"n": 0}
+ real_touch = runs_db.touch_progress
+
+ def _flaky(run_id):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise sqlite3.OperationalError("database is locked")
+ return real_touch(run_id)
+
+ monkeypatch.setattr(runs_db, "touch_progress", _flaky)
+ # Bounded by total time, so express the bound in the same terms the code uses.
+ interval = runs_mod._renew_interval_seconds()
+ monkeypatch.setattr(sup, "_PREPARE_RENEW_MAX_SECONDS", 40 * interval, raising = False)
+ real_sleep = asyncio.sleep
+
+ async def _sleep(seconds):
+ clock.advance_ms(int(seconds * 1000))
+ await real_sleep(0)
+
+ monkeypatch.setattr(runs_mod.asyncio, "sleep", _sleep)
+ asyncio.run(sup._renew_lease_while_preparing("run-1"))
+ assert calls["n"] == 40, "the loop must continue past a failed renewal"
+ assert (
+ runs_db.reconcile_runs(stale_after_ms = _LEASE_MS) == []
+ ), "one lost stamp must not cost the run its lease"
+
+
+def test_a_contended_keepalive_renewal_does_not_abort_the_generation(clock, monkeypatch):
+ """A history transaction can hold SQLite's writer lock past the busy timeout. Letting
+ that escape would abort a healthy generation over a lock about to be released."""
+ _seed()
+ sup = _supervisor()
+
+ def _locked(_run_id):
+ raise sqlite3.OperationalError("database is locked")
+
+ monkeypatch.setattr(runs_db, "touch_progress", _locked)
+ asyncio.run(sup._try_touch_progress("run-1")) # must not raise
+
+
+def test_every_non_output_renewal_goes_through_the_tolerant_path():
+ """Streamed output renews through append_events. Every OTHER renewal, the keep-alive,
+ the preparation heartbeat and the handoff stamp, must not be able to kill a run."""
+ import inspect
+
+ source = inspect.getsource(runs_mod)
+ direct = source.count("asyncio.to_thread(db.touch_progress")
+ assert direct == 1, (
+ f"{direct} direct touch_progress call(s); all but the one inside "
+ "_try_touch_progress must go through it"
+ )
+ helper = inspect.getsource(runs_mod.ChatGenerationSupervisor._try_touch_progress)
+ assert "asyncio.to_thread(db.touch_progress" in helper
+
+
+def test_the_sweeper_survives_a_second_lifespan_on_a_new_event_loop(clock):
+ """A repeated TestClient context or an embedded server restart enters the same app on
+ a different loop, and asyncio.Event binds to the loop that first awaits it.
+
+ The failure is silent, which is why it is asserted on liveness rather than on an
+ exception: _run wraps the wait in ensure_future, so the "bound to a different event
+ loop" RuntimeError lands on that inner waiter, asyncio.wait reports it merely as done,
+ and _run returns as if it had been asked to stop. Reaping is then off for the whole
+ lifespan with nothing logged.
+ """
+ app = SimpleNamespace(state = SimpleNamespace())
+ sweeper = runs_mod.ChatGenerationLeaseSweeper(app, interval_s = 30.0, timeout_s = 60.0)
+ alive = {}
+
+ async def _lifespan(label):
+ sweeper.start()
+ # Long enough for the task to reach _stop_event.wait(), which is what binds it.
+ for _ in range(50):
+ await asyncio.sleep(0)
+ alive[label] = not sweeper._task.done()
+ await sweeper.stop()
+
+ asyncio.run(_lifespan("first"))
+ asyncio.run(_lifespan("second")) # a brand new loop
+
+ assert alive["first"], "the first lifespan's sweeper should be waiting, not finished"
+ assert alive[
+ "second"
+ ], "the second lifespan's sweeper returned immediately, so reaping is off for it"
+
+
+def test_the_admission_marker_matches_the_route_that_emits_it():
+ """Matched as a literal rather than imported, so pin it against the real constant."""
+ from routes import inference as inference_route
+
+ assert inference_route._OPENAI_ADMISSION_SSE_WAIT.startswith(runs_mod._ADMISSION_WAIT_MARKER)
+ assert inference_route._OPENAI_ADMISSION_SSE_DONE.startswith(runs_mod._ADMISSION_DONE_MARKER)
+ # And neither may match the stall keep-alive, which is the opposite signal.
+ for marker in (runs_mod._ADMISSION_WAIT_MARKER, runs_mod._ADMISSION_DONE_MARKER):
+ assert not inference_route._OPENAI_PASSTHROUGH_SSE_KEEPALIVE.startswith(marker)
+ # The two must stay distinct, or the done branch would swallow every wait.
+ assert not inference_route._OPENAI_ADMISSION_SSE_WAIT.startswith(
+ runs_mod._ADMISSION_DONE_MARKER
+ )
+
+
+def test_only_admission_comments_renew_the_lease_from_the_stream():
+ """routes/inference.py emits `: keep-alive` when the generator has produced NOTHING
+ for a stall interval, which is the wedge this file exists to reap. Renewing on any
+ byte would keep such a run alive forever. Both admission comments are the opposite
+ signal, so both renew, and nothing else may."""
+ import inspect
+
+ source = inspect.getsource(runs_mod.ChatGenerationSupervisor._produce)
+ for marker in ("_ADMISSION_DONE_MARKER in text", "_ADMISSION_WAIT_MARKER in text"):
+ guard = source.index(marker)
+ renew = source.index("_try_touch_progress", guard)
+ # The renewal must sit inside the marker guard, not beside it.
+ assert source[guard:renew].count("\n") < 8, f"the renewal drifted outside {marker}"
+
+
+def test_leaving_the_queue_renews_without_waiting_for_the_rate_limit():
+ """The wait renewals are rate limited, so a run admitted just after one could enter
+ its first-token window with a lease most of an interval old. The default lease equals
+ the default first-token timeout, so that difference is negative margin."""
+ import inspect
+
+ source = inspect.getsource(runs_mod.ChatGenerationSupervisor._produce)
+ guard = source.index("_ADMISSION_DONE_MARKER in text")
+ renew = source.index("_try_touch_progress", guard)
+ between = source[guard:renew]
+ assert (
+ "_renew_interval_seconds()" not in between
+ ), "the admission-done renewal must not be rate limited"
+
+
+def test_the_renewal_interval_stays_under_the_lease_actually_in_force(monkeypatch):
+ """Under the APPLIED lease, not the configured one.
+
+ A lease below the admission cadence is raised to the floor before the sweeper uses
+ it, so pacing renewals against the raw value buys nothing: the run cannot be reaped
+ before the floor either way, and at one second it means four SQLite writes per second
+ for as long as a model takes to prepare.
+ """
+ for configured in ("1", "4", "1200"):
+ monkeypatch.setenv("UNSLOTH_STUDIO_CHAT_RUN_LEASE_TIMEOUT_S", configured)
+ applied = runs_mod._applied_lease_timeout(float(configured))
+ interval = runs_mod._renew_interval_seconds()
+ # Three renewals inside every window, however short the lease is configured.
+ assert interval * 3.0 <= applied
+ monkeypatch.setenv("UNSLOTH_STUDIO_CHAT_RUN_LEASE_TIMEOUT_S", "1200")
+ assert runs_mod._renew_interval_seconds() == 30.0
+ # The point of the change: a one second lease no longer buys a 250ms write cadence.
+ monkeypatch.setenv("UNSLOTH_STUDIO_CHAT_RUN_LEASE_TIMEOUT_S", "1")
+ assert runs_mod._renew_interval_seconds() > 1.0
+
+
+def test_a_lease_shorter_than_the_admission_cadence_is_clamped_and_logged(clock):
+ """Our own renewal cadence can be made arbitrarily fine, but the admission stream's
+ keep-alive interval is upstream. A lease shorter than a few of those expires between
+ markers however fast we poll, and reaps a healthy queued run."""
+ floor = runs_mod._minimum_lease_seconds()
+ assert floor > 5.0, "the floor must exceed one admission keep-alive interval"
+ assert runs_mod._clamped_lease_timeout(1.0) == floor
+ assert runs_mod._clamped_lease_timeout(0.0) == 0.0, "zero still means disabled"
+ assert runs_mod._clamped_lease_timeout(1200.0) == 1200.0
+
+ sweeper = runs_mod.ChatGenerationLeaseSweeper(
+ SimpleNamespace(state = SimpleNamespace()), interval_s = 1.0, timeout_s = 1.0
+ )
+ assert sweeper._timeout == floor, "the sweeper must use the clamped value"
+
+
+def test_a_producer_that_ignores_the_cooperative_cancel_is_force_cancelled(clock):
+ """supervisor.cancel() only sets a threading.Event, and every production run has one,
+ so the task is never cancelled by that path. A producer blocked inside next(gen) never
+ reads the event, and would keep its activity reservation after the row was settled.
+
+ Asserted INSIDE the loop: asyncio.run cancels whatever is still pending when it tears
+ the loop down, so checking the task afterwards passes whether or not this code did
+ anything. The first version of this test did exactly that and survived the mutation.
+ """
+ started = asyncio.Event()
+ outcome = {}
+
+ async def _never_finishes():
+ started.set()
+ await asyncio.sleep(3600)
+
+ async def _drive():
+ task = asyncio.create_task(_never_finishes())
+ await started.wait()
+ supervisor = SimpleNamespace(_tasks = {"run-1": task})
+ sweeper = runs_mod.ChatGenerationLeaseSweeper(
+ SimpleNamespace(state = SimpleNamespace()), timeout_s = 60.0
+ )
+ object.__setattr__(sweeper, "_FORCE_CANCEL_GRACE_S", 0.0)
+ await sweeper._force_cancel_after_grace(supervisor, "run-1")
+ for _ in range(20):
+ if task.done():
+ break
+ await asyncio.sleep(0)
+ outcome["cancelled"] = task.cancelled()
+ # Settle it so the loop does not tear down with work outstanding.
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await task
+
+ asyncio.run(_drive())
+ assert outcome["cancelled"], "the wedged producer was left holding its reservation"
+
+
+def test_force_cancel_leaves_a_producer_that_already_finished_alone(clock):
+ async def _drive():
+ async def _quick():
+ return None
+
+ task = asyncio.create_task(_quick())
+ await task
+ supervisor = SimpleNamespace(_tasks = {"run-1": task})
+ sweeper = runs_mod.ChatGenerationLeaseSweeper(
+ SimpleNamespace(state = SimpleNamespace()), timeout_s = 60.0
+ )
+ object.__setattr__(sweeper, "_FORCE_CANCEL_GRACE_S", 0.0)
+ await sweeper._force_cancel_after_grace(supervisor, "run-1")
+ return task
+
+ task = asyncio.run(_drive())
+ assert not task.cancelled(), "a producer that unwound cleanly must not be cancelled"
+
+
[email protected]("raw", ["inf", "1e12", "1e308"])
+def test_an_unusable_admission_cadence_does_not_poison_the_lease(monkeypatch, raw):
+ """The admission parser is not ours and only checks the value is positive.
+
+ An infinite cadence made the applied lease infinite, and the sweeper cannot convert
+ that to milliseconds: every pass raised and nothing was ever reaped. An oversized
+ finite one stretched the lease past any horizon instead, which is quieter and just as
+ total.
+ """
+ from core.inference.llama_admission import DEFAULT_ADMISSION_KEEPALIVE_INTERVAL_S
+
+ monkeypatch.setenv("UNSLOTH_LLAMA_ADMISSION_KEEPALIVE_INTERVAL", raw)
+ assert (
+ runs_mod._minimum_lease_seconds()
+ == max(1.0, float(DEFAULT_ADMISSION_KEEPALIVE_INTERVAL_S)) * 3.0
+ )
+ applied = runs_mod._applied_lease_timeout(1200.0)
+ # The conversion the sweep performs on every pass must survive it.
+ assert int(applied * 1000) == 1_200_000
+
+
+def test_a_reasonable_admission_cadence_still_raises_the_floor(monkeypatch):
+ """The sanitising must not flatten legitimate values: a slower keep-alive genuinely
+ does need a longer minimum lease, which is the whole point of the floor."""
+ monkeypatch.setenv("UNSLOTH_LLAMA_ADMISSION_KEEPALIVE_INTERVAL", "20")
+ assert runs_mod._minimum_lease_seconds() == 60.0
+ assert runs_mod._applied_lease_timeout(5.0) == 60.0
+
+
+def test_the_events_keepalive_carries_the_progress_stamp():
+ """The follower rearms its no-progress deadline only when this value MOVES.
+
+ A bare keep-alive proves the connection is healthy and nothing more, and the route
+ emits one every wait timeout for as long as the socket holds, so a follower rearming
+ on arrival could never settle a wedged run: exactly the case that fallback exists for.
+ """
+ import inspect
+
+ from routes import chat_generation_runs as route
+
+ source = inspect.getsource(route.chat_generation_events)
+ keepalive = source.index(": keep-alive")
+ line_end = source.index("\n", keepalive)
+ line = source[source.rindex("\n", 0, keepalive) : line_end]
+ assert "updatedAt" in line, f"the keep-alive carries no progress stamp: {line.strip()}"
+ # And the stamp has to be the run's own, not a clock: a wall clock always moves.
+ assert "snapshot" in line, "the stamp must come from the run row, not from a clock"
diff --git a/studio/backend/tests/test_chat_generation_run_lease.py b/studio/backend/tests/test_chat_generation_run_lease.py
new file mode 100644
index 00000000000..7b958276def
--- /dev/null
+++ b/studio/backend/tests/test_chat_generation_run_lease.py
@@ -0,0 +1,545 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regression tests for the durable chat generation progress lease.
+
+A durable run sets cancel_on_disconnect=False on purpose, so a closed browser cannot kill
+a long generation. Nothing else bounded it: a producer that stopped producing left the run
+active forever, which kept the thread "generating", unmounted Send in the UI, and held the
+engine slot. The repair, reconcile_orphaned_runs, only ran at process boot, so reloading
+the page never cleared it.
+
+These cover the two halves of the fix: streamed output renews a lease on the run row, and a
+periodic sweep settles only runs whose lease has expired -- never a slow but advancing one.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import sys
+import threading
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+from core.inference import chat_generation_runs as runs_mod # noqa: E402
+from core.inference.chat_generation_runs import ChatGenerationLeaseSweeper # noqa: E402
+from storage import chat_generation_runs_db as runs_db # noqa: E402
+from storage import studio_db # noqa: E402
+
+_MINUTE_MS = 60_000
+
+
+class _Capture:
+ """Fake structlog logger; the sweeper only ever warns."""
+
+ def __init__(self):
+ self.events = []
+
+ def warning(self, event, **kw):
+ self.events.append((event, dict(kw)))
+
+ def info(self, *a, **k):
+ pass
+
+ def debug(self, *a, **k):
+ pass
+
+ def error(self, *a, **k):
+ pass
+
+ def names(self):
+ return [event for event, _kw in self.events]
+
+
+class _Clock:
+ """Fake wall clock for the lease, which is stamped in milliseconds."""
+
+ def __init__(self, start = 1_700_000_000_000):
+ self.now = int(start)
+
+ def __call__(self):
+ return self.now
+
+ def advance_ms(self, ms):
+ self.now += int(ms)
+
+
+def clock(monkeypatch):
+ fake = _Clock()
+ monkeypatch.setattr(runs_db, "now_ms", fake)
+ return fake
+
+
+def capture(monkeypatch):
+ cap = _Capture()
+ monkeypatch.setattr(runs_mod, "logger", cap)
+ return cap
+
+
+def _seed_run(run_id = "run-1", thread_id = "thread-1"):
+ studio_db.upsert_chat_thread(
+ {
+ "id": thread_id,
+ "title": "Chat",
+ "modelType": "base",
+ "modelId": "local.gguf",
+ "createdAt": 1,
+ }
+ )
+ studio_db.upsert_chat_message(
+ {
+ "id": f"user-{run_id}",
+ "threadId": thread_id,
+ "role": "user",
+ "content": [{"type": "text", "text": "Hello"}],
+ "createdAt": 2,
+ }
+ )
+ run, _created = runs_db.create_run(
+ run_id = run_id,
+ owner_subject = "alice",
+ thread_id = thread_id,
+ user_message_id = f"user-{run_id}",
+ assistant_message_id = f"assistant-{run_id}",
+ request_payload = {
+ "model": "local.gguf",
+ "messages": [{"role": "user", "content": "Hello"}],
+ "stream": True,
+ },
+ )
+ return run
+
+
+def _running_run(run_id = "run-1", thread_id = "thread-1"):
+ _seed_run(run_id, thread_id)
+ token = runs_db.get_worker_token(run_id)
+ assert runs_db.mark_running(run_id, token)
+ return token
+
+
+def _stream(
+ run_id,
+ token,
+ count = 2,
+):
+ return runs_db.append_events(
+ run_id,
+ token,
+ [("chunk", {"choices": [{"delta": {"content": "hi"}}]}) for _ in range(count)],
+ )
+
+
+def _write_partial_text(message_id, text):
+ """Stand in for the client checkpoint that persists partial assistant output."""
+ conn = runs_db._connect()
+ try:
+ conn.execute(
+ "UPDATE chat_messages SET content_json=? WHERE id=?",
+ (json.dumps([{"type": "text", "text": text}]), message_id),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+
+def _sweeper(
+ app = None,
+ *,
+ interval_s = 60.0,
+ timeout_s = 600.0,
+):
+ return ChatGenerationLeaseSweeper(
+ app if app is not None else SimpleNamespace(state = SimpleNamespace()),
+ interval_s = interval_s,
+ timeout_s = timeout_s,
+ )
+
+
+# Lease writes
+
+
+def test_streamed_chunks_renew_the_lease(clock):
+ token = _running_run()
+ started_at, started_tokens = runs_db.get_progress("run-1")
+ assert started_tokens == 0
+
+ clock.advance_ms(5 * _MINUTE_MS)
+ _stream("run-1", token, count = 3)
+ progress_at, tokens = runs_db.get_progress("run-1")
+ assert progress_at == started_at + 5 * _MINUTE_MS
+ assert tokens == 3
+
+ clock.advance_ms(_MINUTE_MS)
+ _stream("run-1", token, count = 2)
+ assert runs_db.get_progress("run-1") == (progress_at + _MINUTE_MS, 5)
+
+
+def test_lease_timestamp_never_moves_backwards(clock):
+ token = _running_run()
+ clock.advance_ms(10 * _MINUTE_MS)
+ _stream("run-1", token, count = 1)
+ ahead, _tokens = runs_db.get_progress("run-1")
+
+ # NTP step / resume from suspend: the wall clock goes backwards. A regressing
+ # lease would age a live run straight into the sweep.
+ clock.advance_ms(-9 * _MINUTE_MS)
+ _stream("run-1", token, count = 1)
+ assert runs_db.get_progress("run-1") == (ahead, 2)
+
+
+def test_a_settled_run_stops_taking_lease_writes(clock):
+ token = _running_run()
+ _stream("run-1", token, count = 1)
+ runs_db.finish_run("run-1", worker_token = token, status = "completed")
+ before = runs_db.get_progress("run-1")
+ clock.advance_ms(_MINUTE_MS)
+ assert _stream("run-1", token, count = 4) == []
+ assert runs_db.get_progress("run-1") == before
+
+
+# The sweep
+
+
+async def test_sweep_reaps_a_run_that_stopped_producing(clock, capture):
+ token = _running_run()
+ _stream("run-1", token, count = 2)
+ _write_partial_text("assistant-run-1", "partial answer")
+ clock.advance_ms(11 * _MINUTE_MS)
+
+ assert await _sweeper(timeout_s = 600.0).sweep_once() == ["run-1"]
+
+ run = runs_db.get_run("run-1", "alice")
+ assert (run["status"], run["finishReason"]) == ("failed", "interrupted")
+ assert run["error"] == runs_mod._LEASE_ERROR
+ message = studio_db.get_chat_message("thread-1", "assistant-run-1")
+ assert message["metadata"]["generationStatus"] == "failed"
+ assert message["metadata"]["incomplete"] == {"reason": "interrupted"}
+ # Partial output survives the reap: the point is to release the UI, not to
+ # discard what the model already produced.
+ assert message["content"] == [{"type": "text", "text": "partial answer"}]
+ assert [event["type"] for event in runs_db.list_events("run-1")].count("chunk") == 2
+ assert capture.names() == ["chat_generation_run_lease_expired"]
+ assert capture.events[0][1]["run_id"] == "run-1"
+
+
+async def test_sweep_spares_a_slow_but_progressing_run(clock):
+ """5-6 tok/s on a spilled model is normal; it must never be reaped."""
+ token = _running_run()
+ sweeper = _sweeper(timeout_s = 600.0)
+ for _tick in range(30):
+ clock.advance_ms(_MINUTE_MS)
+ _stream("run-1", token, count = 1)
+ assert await sweeper.sweep_once() == []
+ assert runs_db.get_run("run-1", "alice")["status"] == "running"
+
+
+async def test_sweep_reaps_a_run_wedged_before_its_first_token(clock):
+ # No lease write has ever landed, so the age comes from started_at/created_at.
+ _running_run()
+ clock.advance_ms(11 * _MINUTE_MS)
+ assert await _sweeper(timeout_s = 600.0).sweep_once() == ["run-1"]
+ assert runs_db.get_run("run-1", "alice")["finishReason"] == "interrupted"
+
+
+async def test_sweep_settles_a_stopped_run_as_cancelled(clock):
+ token = _running_run()
+ _stream("run-1", token, count = 1)
+ runs_db.request_cancel("run-1", "alice")
+ assert runs_db.get_run("run-1", "alice")["status"] == "cancelling"
+
+ clock.advance_ms(11 * _MINUTE_MS)
+ assert await _sweeper(timeout_s = 600.0).sweep_once() == ["run-1"]
+
+ run = runs_db.get_run("run-1", "alice")
+ # A Stop the user already asked for must not be reported back as a failure.
+ assert (run["status"], run["finishReason"], run["error"]) == ("cancelled", "cancelled", None)
+ message = studio_db.get_chat_message("thread-1", "assistant-run-1")
+ assert message["metadata"]["incomplete"] == {"reason": "cancelled"}
+
+
+async def test_sweep_cancels_the_wedged_producer(clock, capture):
+ cancelled = []
+ app = SimpleNamespace(
+ state = SimpleNamespace(chat_generation_supervisor = SimpleNamespace(cancel = cancelled.append))
+ )
+ _running_run()
+ clock.advance_ms(11 * _MINUTE_MS)
+ assert await _sweeper(app, timeout_s = 600.0).sweep_once() == ["run-1"]
+ # Settling the row is not enough: a producer parked in the engine still holds
+ # its slot and activity reservation until it is cancelled.
+ assert cancelled == ["run-1"]
+
+
+async def test_a_failing_producer_cancel_does_not_abort_the_sweep(clock, capture):
+ def boom(_run_id):
+ raise RuntimeError("no such run")
+
+ app = SimpleNamespace(
+ state = SimpleNamespace(chat_generation_supervisor = SimpleNamespace(cancel = boom))
+ )
+ _running_run()
+ clock.advance_ms(11 * _MINUTE_MS)
+ assert await _sweeper(app, timeout_s = 600.0).sweep_once() == ["run-1"]
+ assert runs_db.get_run("run-1", "alice")["status"] == "failed"
+ assert "chat_generation_lease_cancel_failed" in capture.names()
+
+
+async def test_a_zero_timeout_disables_the_sweep(clock):
+ _running_run()
+ clock.advance_ms(600 * _MINUTE_MS)
+ sweeper = _sweeper(timeout_s = 0.0)
+ assert sweeper.enabled is False
+ assert await sweeper.sweep_once() == []
+ sweeper.start()
+ assert sweeper._task is None
+ assert runs_db.get_run("run-1", "alice")["status"] == "running"
+
+
+def test_lease_settings_come_from_the_environment(monkeypatch):
+ app = SimpleNamespace(state = SimpleNamespace())
+ monkeypatch.setenv("UNSLOTH_STUDIO_CHAT_RUN_LEASE_TIMEOUT_S", "60")
+ monkeypatch.setenv("UNSLOTH_STUDIO_CHAT_RUN_LEASE_SWEEP_INTERVAL_S", "5")
+ sweeper = ChatGenerationLeaseSweeper(app)
+ assert (sweeper._timeout, sweeper._interval) == (60.0, 5.0)
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_CHAT_RUN_LEASE_TIMEOUT_S", "not-a-number")
+ assert ChatGenerationLeaseSweeper(app)._timeout == runs_mod._LEASE_TIMEOUT_SECONDS
+
+
[email protected]("raw", ["inf", "-inf", "nan", "Infinity", "NaN"])
+def test_a_non_finite_timeout_falls_back_to_the_default(monkeypatch, raw):
+ """float() accepts these, and each then breaks the sweep in its own quiet way.
+
+ inf survives every comparison and only fails at int(timeout * 1000) inside the sweep,
+ once per pass, forever. nan loses to nothing, so max(0.0, nan) returns 0.0 and the
+ sweeper reports itself disabled. Both leave stuck runs unreaped, so neither may parse.
+ """
+ monkeypatch.setenv("UNSLOTH_STUDIO_CHAT_RUN_LEASE_TIMEOUT_S", raw)
+ sweeper = ChatGenerationLeaseSweeper(SimpleNamespace(state = SimpleNamespace()))
+ assert sweeper._timeout == runs_mod._LEASE_TIMEOUT_SECONDS
+ assert sweeper.enabled is True
+
+
+async def test_an_infinite_timeout_still_reaps_a_stuck_run(monkeypatch, clock):
+ """The end state the parser protects: int(inf * 1000) would raise on every sweep."""
+ _running_run()
+ clock.advance_ms(600 * _MINUTE_MS)
+ monkeypatch.setenv("UNSLOTH_STUDIO_CHAT_RUN_LEASE_TIMEOUT_S", "inf")
+ sweeper = ChatGenerationLeaseSweeper(SimpleNamespace(state = SimpleNamespace()))
+ assert await sweeper.sweep_once() == ["run-1"]
+ assert runs_db.get_run("run-1", "alice")["finishReason"] == "interrupted"
+
+
+async def test_a_nan_timeout_does_not_silently_disable_reaping(monkeypatch, clock):
+ _running_run()
+ clock.advance_ms(600 * _MINUTE_MS)
+ monkeypatch.setenv("UNSLOTH_STUDIO_CHAT_RUN_LEASE_TIMEOUT_S", "nan")
+ sweeper = ChatGenerationLeaseSweeper(SimpleNamespace(state = SimpleNamespace()))
+ assert sweeper.enabled is True
+ assert await sweeper.sweep_once() == ["run-1"]
+
+
[email protected]("raw", ["1e308", "1e306", "1.5e308"])
+def test_an_oversized_but_finite_timeout_is_clamped(monkeypatch, raw):
+ """Finite is not the same as usable: the multiply to milliseconds overflows first."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_CHAT_RUN_LEASE_TIMEOUT_S", raw)
+ sweeper = ChatGenerationLeaseSweeper(SimpleNamespace(state = SimpleNamespace()))
+ assert sweeper._timeout == runs_mod._MAX_ENV_SECONDS
+ # The conversion every consumer performs must survive the applied value.
+ assert isinstance(int(sweeper._timeout * 1000), int)
+
+
+async def test_an_oversized_timeout_leaves_a_fresh_run_alone_without_raising(monkeypatch, clock):
+ """The end state: the sweep completes instead of raising OverflowError every pass."""
+ _running_run()
+ monkeypatch.setenv("UNSLOTH_STUDIO_CHAT_RUN_LEASE_TIMEOUT_S", "1e308")
+ sweeper = ChatGenerationLeaseSweeper(SimpleNamespace(state = SimpleNamespace()))
+ assert await sweeper.sweep_once() == []
+ assert runs_db.get_run("run-1", "alice")["status"] == "running"
+
+
+def test_a_non_finite_interval_falls_back_to_the_default(monkeypatch):
+ """An inf interval would park the sweep loop until shutdown; nan sleeps forever too."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_CHAT_RUN_LEASE_SWEEP_INTERVAL_S", "inf")
+ sweeper = ChatGenerationLeaseSweeper(SimpleNamespace(state = SimpleNamespace()))
+ assert sweeper._interval == runs_mod._LEASE_SWEEP_INTERVAL_SECONDS
+
+
+# Boot reconciliation and shutdown
+
+
+def test_boot_reconcile_still_settles_a_freshly_progressing_run(clock):
+ """Unbounded at boot on purpose: every active row is orphaned by the restart."""
+ token = _running_run()
+ _stream("run-1", token, count = 5)
+ assert runs_db.reconcile_orphaned_runs() == 1
+ assert runs_db.get_run("run-1", "alice")["finishReason"] == "interrupted"
+
+
+async def test_sweeper_runs_on_its_interval_and_stops_promptly(clock):
+ sweeps = []
+ sweeper = _sweeper(interval_s = 1.0, timeout_s = 600.0)
+ sweeper._interval = 0.01
+
+ async def record():
+ sweeps.append(1)
+ return []
+
+ sweeper.sweep_once = record
+ sweeper.start()
+ while len(sweeps) < 3:
+ await asyncio.sleep(0.01)
+ await sweeper.stop()
+ settled = len(sweeps)
+ await asyncio.sleep(0.05)
+ assert len(sweeps) == settled
+ assert sweeper._task is None
+
+
+async def test_stop_returns_when_a_sweep_will_not_finish(capture, monkeypatch):
+ """Same contract as ChatGenerationSupervisor.stop(): bounded, then named."""
+ monkeypatch.setattr(runs_mod, "_SHUTDOWN_GRACE_SECONDS", 0.05)
+ monkeypatch.setattr(runs_mod, "_SHUTDOWN_CANCEL_SECONDS", 0.05)
+ sweeper = _sweeper(interval_s = 1.0, timeout_s = 600.0)
+ sweeper._interval = 0.01
+ started = asyncio.Event()
+
+ async def wedged():
+ started.set()
+ try:
+ await asyncio.sleep(3600)
+ except asyncio.CancelledError:
+ # An engine draining its subprocess inside aclose: the cancel lands but
+ # unwinding still outlasts the budget. stop() must return regardless.
+ await asyncio.sleep(0.3)
+
+ sweeper.sweep_once = wedged
+ sweeper.start()
+ await asyncio.wait_for(started.wait(), timeout = 2)
+ await asyncio.wait_for(sweeper.stop(), timeout = 5)
+ assert any("shutdown budget" in name for name in capture.names())
+ await asyncio.sleep(0.4) # let the abandoned sweep unwind before the loop closes
+
+
+async def test_supervisor_stop_stops_the_sweeper():
+ app = SimpleNamespace(state = SimpleNamespace())
+ sweeper = _sweeper(app, interval_s = 1.0, timeout_s = 600.0)
+ sweeper._interval = 0.01
+ app.state.chat_generation_lease_sweeper = sweeper
+ sweeper.start()
+ await runs_mod.ChatGenerationSupervisor(app).stop()
+ assert sweeper._task is None
+
+
+def test_start_lease_sweeper_is_idempotent(monkeypatch):
+ async def main():
+ app = SimpleNamespace(state = SimpleNamespace())
+ first = runs_mod.start_lease_sweeper(app)
+ assert runs_mod.start_lease_sweeper(app) is first
+ assert app.state.chat_generation_lease_sweeper is first
+ await first.stop()
+
+ asyncio.run(main())
+
+
+_ABANDONED_SWEEP_PROGRAM = """
+import asyncio, sys, threading
+sys.path.insert(0, {backend!r})
+from types import SimpleNamespace
+from core.inference import chat_generation_runs as m
+from storage import chat_generation_runs_db as db
+
+parked = threading.Event()
+def _never_returns(*a, **k):
+ parked.set()
+ threading.Event().wait(600) # a sweep on SQLite's writer lock
+db.reconcile_runs = _never_returns
+
+async def main():
+ sweeper = m.ChatGenerationLeaseSweeper(
+ SimpleNamespace(state = SimpleNamespace()), interval_s = 0.01, timeout_s = 600.0
+ )
+ sweeper.start()
+ for _ in range(500):
+ if parked.is_set():
+ break
+ await asyncio.sleep(0.01)
+ assert parked.is_set(), "the sweep never reached the database"
+ await sweeper.stop()
+
+asyncio.run(main())
+"""
+
+
+def test_an_abandoned_sweep_cannot_hold_the_process_open():
+ """Asserts the PROCESS exits, not merely that stop() returned.
+
+ asyncio.to_thread runs on non-daemon executor threads that an atexit hook joins, so a
+ sweep parked on the writer lock kept the interpreter alive indefinitely after shutdown
+ had given up on it. Studio Desktop allows five seconds for a graceful backend exit
+ before force-killing, and stops the backend this way before it updates, so that hang
+ is user visible. A stop() that returns proves nothing here; only exit does.
+ """
+ import subprocess
+
+ program = _ABANDONED_SWEEP_PROGRAM.format(backend = str(Path(__file__).resolve().parent.parent))
+ try:
+ done = subprocess.run(
+ [sys.executable, "-c", program], timeout = 60, capture_output = True, text = True
+ )
+ except subprocess.TimeoutExpired:
+ raise AssertionError(
+ "the process never exited: an abandoned sweep is still holding it open"
+ ) from None
+ assert done.returncode == 0, f"stderr: {done.stderr[-2000:]}"
+
+
+async def test_stopping_the_sweeper_does_not_spend_the_desktop_exit_budget(monkeypatch):
+ """Desktop force-kills after five seconds, so the sweeper's own budget must be small.
+
+ Letting a parked sweep finish buys nothing: the boot reconcile settles every active
+ run anyway, so this work is redundant at shutdown.
+ """
+ import time as _time
+
+ parked = threading.Event()
+
+ def _never_returns(*a, **k):
+ parked.set()
+ threading.Event().wait(60)
+
+ monkeypatch.setattr(runs_db, "reconcile_runs", _never_returns)
+ sweeper = _sweeper(interval_s = 0.01, timeout_s = 600.0)
+ sweeper.start()
+ for _ in range(500):
+ if parked.is_set():
+ break
+ await asyncio.sleep(0.01)
+ assert parked.is_set(), "the sweep never reached the database"
+ started = _time.monotonic()
+ await sweeper.stop()
+ elapsed = _time.monotonic() - started
+ assert elapsed < 2.0, f"sweeper.stop() took {elapsed:.2f}s of the graceful-exit budget"
diff --git a/studio/backend/tests/test_llama_stats_platform_matrix.py b/studio/backend/tests/test_llama_stats_platform_matrix.py
new file mode 100644
index 00000000000..c257d51381d
--- /dev/null
+++ b/studio/backend/tests/test_llama_stats_platform_matrix.py
@@ -0,0 +1,272 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Simulation suite: the engine stats poller across platforms, backends and bad input.
+
+The poller reads llama-server /metrics over loopback HTTP and nothing else, so the
+platform and GPU axes reduce to "what does this build's /metrics look like". These
+walk the [Windows, Linux, WSL, macOS] x [NVIDIA, AMD/ROCm, Vulkan, CPU] product as
+metric payloads, plus the malformed and hostile bodies a daemon thread must survive
+without dying.
+"""
+
+from __future__ import annotations
+
+import itertools
+import sys
+import threading
+from pathlib import Path
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+import core.inference.llama_stats as ls # noqa: E402
+from core.inference.llama_stats import LlamaServerStatsLogger # noqa: E402
+
+
+class _Capture:
+ def __init__(self):
+ self.events = []
+
+ def info(self, event, **kw):
+ self.events.append((event, dict(kw)))
+
+ def warning(self, event, **kw):
+ self.events.append((event, dict(kw)))
+
+ def debug(self, *a, **k):
+ pass
+
+
+def _drive(
+ snaps,
+ monkeypatch,
+ *,
+ tick_s = 10.0,
+ stall_timeout_s = 600.0,
+):
+ cap = _Capture()
+ clock = {"t": 1000.0}
+ monkeypatch.setattr(ls.time, "monotonic", lambda: clock["t"])
+ lg = LlamaServerStatsLogger("http://127.0.0.1:0", cap, stall_timeout_s = stall_timeout_s)
+ lg._interval = 0.001
+ state = {"i": 0}
+
+ def fake_scrape():
+ i = state["i"]
+ state["i"] += 1
+ if i >= len(snaps):
+ lg.stop()
+ return None
+ clock["t"] += tick_s
+ return snaps[i]
+
+ lg._scrape = fake_scrape
+ lg._run()
+ return cap
+
+
+def _stalls(cap):
+ return [kw for ev, kw in cap.events if ev == "engine_no_decode_progress"]
+
+
+# ------------------------------------------------------- platform x backend matrix
+
+PLATFORMS = ["win32", "linux", "linux-wsl", "darwin"]
+BACKENDS = ["cuda", "rocm", "vulkan", "cpu"]
+
+
[email protected]("platform,backend", list(itertools.product(PLATFORMS, BACKENDS)))
+def test_healthy_generation_is_never_flagged_on_any_platform(platform, backend, monkeypatch):
+ """The signature that matters is identical everywhere: llama-server freezes the
+ token counters for the whole of a healthy generation and only n_decode_total moves.
+
+ A build that reported a stall here would cancel real work on that platform.
+ """
+ monkeypatch.setattr(sys, "platform", platform.replace("-wsl", ""))
+ snaps = [
+ {
+ "tokens_predicted_total": 4096.0, # frozen until the slot is released
+ "prompt_tokens_total": 512.0, # flushed once, at the first token
+ "n_decode_total": 30000.0 + i,
+ "requests_processing": 1.0,
+ "requests_deferred": 0.0,
+ }
+ for i in range(180) # 30 simulated minutes
+ ]
+ cap = _drive(snaps, monkeypatch)
+ assert not _stalls(cap), f"{platform}/{backend} flagged a healthy generation"
+
+
[email protected]("platform,backend", list(itertools.product(PLATFORMS, BACKENDS)))
+def test_a_real_wedge_is_reported_on_any_platform(platform, backend, monkeypatch):
+ monkeypatch.setattr(sys, "platform", platform.replace("-wsl", ""))
+ snaps = [
+ {
+ "tokens_predicted_total": 4096.0,
+ "prompt_tokens_total": 512.0,
+ "n_decode_total": 30000.0, # frozen: the engine is not decoding
+ "requests_processing": 1.0,
+ }
+ for _ in range(120)
+ ]
+ cap = _drive(snaps, monkeypatch)
+ assert len(_stalls(cap)) == 1, f"{platform}/{backend} missed a wedge"
+
+
+def test_cpu_only_slow_decode_is_never_flagged(monkeypatch):
+ # A CPU build can sit many seconds between decode calls. As long as the counter
+ # moves at all between scrapes, it is alive.
+ snaps = []
+ decode = 100.0
+ for i in range(240):
+ if i % 20 == 0: # a decode call only every 200 simulated seconds
+ decode += 1
+ snaps.append({"n_decode_total": decode, "requests_processing": 1.0})
+ cap = _drive(snaps, monkeypatch)
+ assert not _stalls(cap)
+
+
+# ------------------------------------------------------------------ scrape robustness
+
+
+def _scrape_body(body, monkeypatch):
+ class _Resp:
+ status = 200
+
+ def read(self):
+ return body.encode() if isinstance(body, str) else body
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ monkeypatch.setattr(ls.urllib.request, "urlopen", lambda *a, **k: _Resp())
+ return LlamaServerStatsLogger("http://127.0.0.1:0", _Capture())._scrape()
+
+
+def test_scrape_handles_windows_line_endings(monkeypatch):
+ body = "llamacpp:n_decode_total 12\r\nllamacpp:requests_processing 1\r\n"
+ m = _scrape_body(body, monkeypatch)
+ assert m["n_decode_total"] == 12.0
+ assert m["requests_processing"] == 1.0
+
+
+def test_scrape_handles_scientific_notation_and_labels(monkeypatch):
+ body = 'llamacpp:n_decode_total{model="a-b_c.d"} 1.5e3\nllamacpp:requests_processing 2\n'
+ m = _scrape_body(body, monkeypatch)
+ assert m["n_decode_total"] == 1500.0
+
+
+def test_scrape_survives_malformed_values(monkeypatch):
+ body = "llamacpp:n_decode_total NaNsense\nllamacpp:requests_processing 1\n"
+ m = _scrape_body(body, monkeypatch)
+ # The bad line is skipped, the good one still parses.
+ assert m.get("requests_processing") == 1.0
+
+
+def test_scrape_survives_non_utf8_bytes(monkeypatch):
+ body = b"llamacpp:n_decode_total 5\n\xff\xfe garbage\nllamacpp:requests_processing 1\n"
+ m = _scrape_body(body, monkeypatch)
+ assert m["n_decode_total"] == 5.0
+
+
+def test_scrape_on_empty_body_is_falsy(monkeypatch):
+ assert not _scrape_body("", monkeypatch)
+
+
+def test_scrape_failure_returns_none(monkeypatch):
+ def _boom(*a, **k):
+ raise OSError("connection refused")
+
+ monkeypatch.setattr(ls.urllib.request, "urlopen", _boom)
+ assert LlamaServerStatsLogger("http://127.0.0.1:0", _Capture())._scrape() is None
+
+
+# ------------------------------------------------------------------- lifecycle edges
+
+
+def test_scrape_failures_do_not_advance_the_stall_clock(monkeypatch):
+ # /metrics briefly unavailable during a model swap must not read as a wedge.
+ cap = _Capture()
+ clock = {"t": 0.0}
+ monkeypatch.setattr(ls.time, "monotonic", lambda: clock["t"])
+ lg = LlamaServerStatsLogger("http://127.0.0.1:0", cap, stall_timeout_s = 600.0)
+ lg._interval = 0.001
+ state = {"i": 0}
+
+ def fake_scrape():
+ state["i"] += 1
+ clock["t"] += 10.0
+ if state["i"] > 200:
+ lg.stop()
+ return None
+ return None # every scrape fails
+
+ lg._scrape = fake_scrape
+ lg._run()
+ assert not _stalls(cap)
+
+
+def test_stop_is_honoured_promptly(monkeypatch):
+ lg = LlamaServerStatsLogger("http://127.0.0.1:0", _Capture())
+ lg._interval = 1.0
+ lg._scrape = lambda: {"n_decode_total": 1.0, "requests_processing": 0.0}
+ t = threading.Thread(target = lg._run, daemon = True)
+ t.start()
+ lg.stop()
+ t.join(timeout = 10)
+ assert not t.is_alive(), "stop() must end the poll loop"
+
+
+def test_zero_and_negative_interval_are_clamped():
+ assert LlamaServerStatsLogger("http://x", _Capture(), 0.0)._interval >= 1.0
+ assert LlamaServerStatsLogger("http://x", _Capture(), -5.0)._interval >= 1.0
+
+
+def test_negative_stall_timeout_is_clamped_to_disabled():
+ lg = LlamaServerStatsLogger("http://x", _Capture(), stall_timeout_s = -1.0)
+ assert lg._stall_timeout == 0.0
+
+
+def test_base_url_trailing_slash_is_normalised():
+ assert LlamaServerStatsLogger("http://h:1/", _Capture())._url == "http://h:1/metrics"
+ assert LlamaServerStatsLogger("http://h:1", _Capture())._url == "http://h:1/metrics"
+
+
+def test_env_defaults_are_read(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_ENGINE_STALL_TIMEOUT_S", "42")
+ monkeypatch.setenv("UNSLOTH_STUDIO_ENGINE_STATS_INTERVAL_S", "7")
+ started = {}
+ monkeypatch.setattr(
+ LlamaServerStatsLogger,
+ "start",
+ lambda self: started.update(timeout = self._stall_timeout, interval = self._interval),
+ )
+ ls.maybe_start_stats_logger("http://127.0.0.1:1", _Capture())
+ assert started == {"timeout": 42.0, "interval": 7.0}
+
+
+def test_garbage_env_falls_back_to_defaults(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_ENGINE_STALL_TIMEOUT_S", "not-a-number")
+ monkeypatch.setenv("UNSLOTH_STUDIO_ENGINE_STATS_INTERVAL_S", "")
+ started = {}
+ monkeypatch.setattr(
+ LlamaServerStatsLogger,
+ "start",
+ lambda self: started.update(timeout = self._stall_timeout, interval = self._interval),
+ )
+ ls.maybe_start_stats_logger("http://127.0.0.1:1", _Capture())
+ assert started["timeout"] == 600.0
+ assert started["interval"] >= 1.0
+
+
[email protected]("value", ["0", "false", "no", "off", "OFF", " Off "])
+def test_stats_logger_can_be_disabled_entirely(value, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_ENGINE_STATS", value)
+ assert ls.maybe_start_stats_logger("http://127.0.0.1:1", _Capture()) is None
diff --git a/studio/backend/tests/test_llama_stats_stall.py b/studio/backend/tests/test_llama_stats_stall.py
new file mode 100644
index 00000000000..c5aba864a1c
--- /dev/null
+++ b/studio/backend/tests/test_llama_stats_stall.py
@@ -0,0 +1,277 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regression tests for the engine stall report.
+
+Reproduces a real user report: llama-server held one slot (requests_processing=1)
+for 22.5 minutes while nothing advanced. The stats poller emitted 135 identical
+`engine_stats gen_tok_s=0.0 running=1` lines at level=info and nothing else -- no
+warning, no timeout, no recovery.
+
+The signal is n_decode_total, NOT the token counters. llama-server updates
+tokens_predicted_total once per generation (metrics_on_prediction, called from
+callback_on_reset when the slot is released) and flushes prompt_tokens_total only
+on a decode that produced output. Both therefore sit still through a healthy long
+prefill and a healthy long decode, so a token-counter check would flag every slow
+generation as wedged. n_decode_total increments on every llama_decode() call.
+
+This only reports. Cancelling on this evidence is unsafe, and Studio reaps a run
+that stops progressing from its own per-token event stream instead.
+"""
+
+import pytest
+
+import core.inference.llama_stats as ls
+from core.inference.llama_stats import LlamaServerStatsLogger
+
+
+class _Capture:
+ def __init__(self):
+ self.events = []
+
+ def info(self, event, **kw):
+ self.events.append((event, dict(kw)))
+
+ def warning(self, event, **kw):
+ self.events.append((event, dict(kw)))
+
+ def debug(self, *a, **k):
+ pass
+
+
+def _drive(
+ snaps,
+ monkeypatch,
+ *,
+ tick_s = 10.0,
+ stall_timeout_s = 600.0,
+):
+ """Run _run() synchronously over `snaps` on a fake clock, then stop.
+
+ Each scrape advances the clock by `tick_s`, mirroring the 10s poll interval
+ the user's log was recorded at, so a multi-minute stall costs no wall time.
+ """
+ cap = _Capture()
+ clock = {"t": 1000.0}
+ monkeypatch.setattr(ls.time, "monotonic", lambda: clock["t"])
+
+ lg = LlamaServerStatsLogger("http://127.0.0.1:0", cap, stall_timeout_s = stall_timeout_s)
+ lg._interval = 0.001 # bypass the 1s floor for a fast, synchronous run
+ state = {"i": 0}
+
+ def fake_scrape():
+ i = state["i"]
+ state["i"] += 1
+ if i >= len(snaps):
+ lg.stop()
+ return None
+ clock["t"] += tick_s
+ return snaps[i]
+
+ lg._scrape = fake_scrape
+ lg._run()
+ return cap
+
+
+def _stalls(cap):
+ return [kw for ev, kw in cap.events if ev == "engine_no_decode_progress"]
+
+
+def _wedged(n, *, decode = 8192.0):
+ """The user's signature: a held slot that never calls llama_decode()."""
+ return [
+ {
+ "tokens_predicted_total": 4096.0,
+ "prompt_tokens_total": 512.0,
+ "n_decode_total": decode,
+ "requests_processing": 1.0,
+ "requests_deferred": 0.0,
+ }
+ for _ in range(n)
+ ]
+
+
+def test_reproduces_the_reported_signature(monkeypatch):
+ # 135 samples, every one identical: running=1, waiting=0, both rates 0.0.
+ cap = _drive(_wedged(135), monkeypatch, stall_timeout_s = 0.0)
+ stats = [kw for ev, kw in cap.events if ev == "engine_stats"]
+ assert len(stats) == 135
+ assert all(s["running"] == 1 and s["waiting"] == 0 for s in stats)
+ assert all(s["gen_tok_s"] == 0.0 and s["prompt_tok_s"] == 0.0 for s in stats)
+
+
+def test_held_slot_with_no_decode_calls_is_reported(monkeypatch):
+ cap = _drive(_wedged(120), monkeypatch) # 120 x 10s = 1200s, past 600s
+ stalls = _stalls(cap)
+ assert len(stalls) == 1, "a stall episode must be reported exactly once"
+ assert stalls[0]["running"] == 1
+ assert stalls[0]["stalled_s"] >= 600.0
+
+
+def test_nothing_is_ever_cancelled(monkeypatch):
+ # The poller must expose no cancellation hook at all: acting on this signal
+ # would kill healthy generations, which is the bug this test guards.
+ lg = LlamaServerStatsLogger("http://127.0.0.1:0", _Capture())
+ assert not hasattr(lg, "_on_stall")
+ import inspect
+
+ assert "on_stall" not in inspect.signature(ls.maybe_start_stats_logger).parameters
+
+
+def test_a_healthy_long_decode_is_never_flagged(monkeypatch):
+ # THE REGRESSION THIS FILE EXISTS FOR. llama-server does not move
+ # tokens_predicted_total until the slot is released, so a generation running
+ # at 5 tok/s for 20 minutes shows completely static token counters while
+ # decoding normally. Only n_decode_total distinguishes it from a wedge.
+ snaps = [
+ {
+ "tokens_predicted_total": 4096.0, # frozen for the whole generation
+ "prompt_tokens_total": 512.0, # flushed once at first token
+ "n_decode_total": 10000.0 + i, # the engine is working
+ "requests_processing": 1.0,
+ }
+ for i in range(120)
+ ]
+ cap = _drive(snaps, monkeypatch)
+ assert not _stalls(cap), "a healthy long generation must never be flagged"
+
+
+def test_a_healthy_long_prefill_is_never_flagged(monkeypatch):
+ # Multi-batch prefill: prompt_tokens_total does not flush until a decode
+ # produces output, so it too is static while the engine is busy.
+ snaps = [
+ {
+ "tokens_predicted_total": 0.0,
+ "prompt_tokens_total": 0.0,
+ "n_decode_total": 500.0 + i,
+ "requests_processing": 1.0,
+ }
+ for i in range(120)
+ ]
+ cap = _drive(snaps, monkeypatch)
+ assert not _stalls(cap)
+
+
+def test_idle_engine_is_never_flagged(monkeypatch):
+ snaps = [{"n_decode_total": 9.0, "requests_processing": 0.0} for _ in range(120)]
+ cap = _drive(snaps, monkeypatch)
+ assert not _stalls(cap)
+
+
+def test_recovery_rearms_the_report(monkeypatch):
+ snaps = (
+ _wedged(80)
+ + [{"n_decode_total": 9000.0 + i, "requests_processing": 1.0} for i in range(5)]
+ + _wedged(80, decode = 20000.0)
+ )
+ cap = _drive(snaps, monkeypatch)
+ assert len(_stalls(cap)) == 2
+
+
+def test_a_stalled_gauge_does_not_mask_a_wedge(monkeypatch):
+ # predicted_tokens_seconds stuck at a stale nonzero value while nothing
+ # decodes. A rate-based check would miss this.
+ snaps = [
+ {
+ "n_decode_total": 8192.0,
+ "predicted_tokens_seconds": 42.0,
+ "requests_processing": 1.0,
+ }
+ for _ in range(120)
+ ]
+ cap = _drive(snaps, monkeypatch)
+ assert len(_stalls(cap)) == 1
+
+
+def test_absent_decode_counter_disables_reporting(monkeypatch):
+ # A build whose /metrics lacks n_decode_total reads 0.0 through .get()
+ # forever, indistinguishable from a wedge. Report once, then stay quiet.
+ snaps = [{"requests_processing": 1.0} for _ in range(120)]
+ cap = _drive(snaps, monkeypatch)
+ assert not _stalls(cap)
+ unmeasurable = [kw for ev, kw in cap.events if ev == "engine_progress_unmeasurable"]
+ assert len(unmeasurable) == 1
+ assert unmeasurable[0]["missing"] == "n_decode_total"
+
+
+def test_disabled_by_zero_timeout(monkeypatch):
+ cap = _drive(_wedged(120), monkeypatch, stall_timeout_s = 0.0)
+ assert not _stalls(cap)
+
+
+def test_counter_reset_after_reload_is_not_a_stall(monkeypatch):
+ # A model reload restarts llama-server, so n_decode_total goes back to 0.
+ # That is a change, so it must re-arm rather than read as progress-free.
+ snaps = _wedged(20) + [
+ {"n_decode_total": float(i), "requests_processing": 1.0} for i in range(5)
+ ]
+ cap = _drive(snaps, monkeypatch, stall_timeout_s = 600.0)
+ assert not _stalls(cap), "200s of wedge then a reset must not trip the report"
+
+
[email protected]("raw", ["nan", "inf", "-inf", "NaN", "Infinity"])
+def test_a_non_finite_stall_timeout_falls_back_to_the_default(monkeypatch, raw):
+ """Both spellings disable the very report the variable was set to configure.
+
+ nan loses every comparison, so max(0.0, nan) keeps 0.0 and the stall line never
+ arms; inf can never be reached by an elapsed time. Neither may parse.
+ """
+ monkeypatch.setenv("UNSLOTH_STUDIO_ENGINE_STALL_TIMEOUT_S", raw)
+ cap = _Capture()
+ assert ls._env_float("UNSLOTH_STUDIO_ENGINE_STALL_TIMEOUT_S", 600.0, cap) == 600.0
+ assert [ev for ev, _ in cap.events] == ["engine_stats_env_ignored"]
+
+
[email protected]("raw", ["nan", "inf"])
+def test_a_non_finite_interval_falls_back_to_the_default(monkeypatch, raw):
+ """An infinite interval parks the poll loop in stop.wait() until shutdown."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_ENGINE_STATS_INTERVAL_S", raw)
+ assert ls._env_float("UNSLOTH_STUDIO_ENGINE_STATS_INTERVAL_S", 10.0, _Capture()) == 10.0
+
+
+def test_a_non_finite_timeout_still_leaves_the_stall_report_armed(monkeypatch):
+ """The end state: a malformed setting must not silence the wedge report."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_ENGINE_STALL_TIMEOUT_S", "nan")
+ applied = ls._env_float("UNSLOTH_STUDIO_ENGINE_STALL_TIMEOUT_S", 600.0, _Capture())
+ cap = _drive(_wedged(120), monkeypatch, stall_timeout_s = applied)
+ assert _stalls(cap), "a nan timeout must not disable the stall report"
+
+
+def test_a_garbage_timeout_still_falls_back_without_warning(monkeypatch):
+ """Unparseable text was already handled; it must stay quiet, not warn."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_ENGINE_STALL_TIMEOUT_S", "not-a-number")
+ cap = _Capture()
+ assert ls._env_float("UNSLOTH_STUDIO_ENGINE_STALL_TIMEOUT_S", 600.0, cap) == 600.0
+ assert cap.events == []
+
+
[email protected]("raw", ["1e10", "1e18", "1e308"])
+def test_an_oversized_finite_interval_is_clamped(monkeypatch, raw):
+ """Event.wait() turns a timeout into an absolute deadline, and one far enough out
+ raises "timestamp out of range for platform time_t" as soon as the wait is entered,
+ killing the poll thread and taking the stats and the stall report with it."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_ENGINE_STATS_INTERVAL_S", raw)
+ cap = _Capture()
+ applied = ls._env_float("UNSLOTH_STUDIO_ENGINE_STATS_INTERVAL_S", 10.0, cap)
+ assert applied == ls._MAX_ENV_SECONDS
+ assert [ev for ev, _ in cap.events] == ["engine_stats_env_clamped"]
+
+
+def test_the_clamped_interval_is_a_wait_every_platform_accepts():
+ """The end state, exercised rather than asserted about.
+
+ A hand-picked constant got this wrong once: a one year cap waits fine on Linux, whose
+ threading.TIMEOUT_MAX is about 9.2e9 seconds, and raises OverflowError on Windows,
+ where the timeout becomes a DWORD of milliseconds and the ceiling is 49.7 days. Only
+ the Windows CI leg caught it, so the bound is checked here directly as well rather
+ than left to whichever runner happens to be strictest.
+ """
+ import threading
+
+ assert ls._MAX_ENV_SECONDS <= threading.TIMEOUT_MAX
+ # The Windows ceiling, asserted on every platform so Linux cannot pass a cap Windows
+ # would reject.
+ assert ls._MAX_ENV_SECONDS <= (2**32 - 1) / 1000.0
+ event = threading.Event()
+ threading.Timer(0.05, event.set).start()
+ assert event.wait(ls._MAX_ENV_SECONDS) is True
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index bd60ee74603..c79fabdb44d 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -235,6 +235,7 @@ import {
} from "../utils/continuation";
import {
claimLiveGenerationRun,
+ forgetServerActiveGenerationRun,
generationChunkCountsTowardTiming,
generationChunkHasSubstantiveDelta,
generationIsSettled,
@@ -271,6 +272,7 @@ import {
import { cancelResearchRun, createResearchRun } from "./research-api";
import {
cancelChatGenerationRun,
+ ChatGenerationStalledError,
chatGenerationStopPlan,
isLegacyFallbackChatGenerationAdmissionError,
type ChatGenerationRun,
@@ -5044,6 +5046,10 @@ export function createOpenAIStreamAdapter(
let generationFirstChunkAt: number | undefined;
let generationChunkCount = 0;
let generationStopRequested = false;
+ // Set when the no-progress deadline fires on THIS stream rather than on a recovery
+ // follower. Both must persist the marker, or the next reload attaches another
+ // follower and blocks the composer for a further deadline.
+ let generationStalled = false;
const generationCustom = () =>
generationRunId
? {
@@ -5057,6 +5063,7 @@ export function createOpenAIStreamAdapter(
generationSeq,
generationRun?.lastEventSeq ?? Number.POSITIVE_INFINITY,
),
+ generationLocallyInterrupted: generationStalled,
serverManaged: true,
}
: {};
@@ -6109,7 +6116,12 @@ export function createOpenAIStreamAdapter(
// lands, so a visibility, pageshow, online or history-load trigger during
// this await could otherwise start a recovery that the later claim would
// not stop: the scheduler only tests ownership at startup.
- claimLiveGenerationRun(cancelId);
+ // Provisional: it owns recovery without marking the thread bounded.
+ // The await below can outlast the checkpoint cap, and a capped thread
+ // is dropped from the schedule for good.
+ claimLiveGenerationRun(cancelId, resolvedThreadId!, {
+ provisional: true,
+ });
try {
generationRun = await createChatGenerationRunUntilAbort(
{
@@ -6128,6 +6140,10 @@ export function createOpenAIStreamAdapter(
// Durable recovery does not yet replay server-side tool events.
// Use the subscriber-owned stream for this policy-forced case.
generationDecision = "legacy";
+ // Dropped here rather than in the outer finally: this stream is about
+ // to become subscriber-owned, and leaving the claim would let the cap
+ // fire on a stream whose only persistence is those checkpoints.
+ releaseLiveGenerationRun(cancelId);
}
if (!generationRun) {
if (generationDecision === "durable") return;
@@ -6135,7 +6151,7 @@ export function createOpenAIStreamAdapter(
generationRunId = generationRun.id;
// Normally the same id we claimed above; claimed again in case the server
// ever echoes a different one. Both are released in the finally below.
- claimLiveGenerationRun(generationRunId);
+ claimLiveGenerationRun(generationRunId, resolvedThreadId!);
generationStatus = generationRun.status;
if (generationStopRequested) {
void cancelChatGenerationRun(generationRun.id).catch(
@@ -6148,29 +6164,41 @@ export function createOpenAIStreamAdapter(
}
const durableStream = async function* () {
- for await (const update of followChatGenerationRun(
- generationRunId!,
- {
- initialRun: generationRun!,
- replayFrom: 0,
- signal: runSignal,
- },
- )) {
- generationRun = update.run;
- generationStatus = update.run.status;
- if (update.event) {
- generationSeq = Math.max(generationSeq, update.event.seq);
- if (update.event.type === "chunk") {
- const chunk = update.event.payload as OpenAIChatChunk;
- if (generationChunkCountsTowardTiming(chunk)) {
- generationChunkCount += 1;
- if (generationChunkHasSubstantiveDelta(chunk)) {
- generationFirstChunkAt ??= update.event.createdAt;
+ try {
+ for await (const update of followChatGenerationRun(
+ generationRunId!,
+ {
+ initialRun: generationRun!,
+ replayFrom: 0,
+ signal: runSignal,
+ },
+ )) {
+ generationRun = update.run;
+ generationStatus = update.run.status;
+ if (update.event) {
+ generationSeq = Math.max(generationSeq, update.event.seq);
+ if (update.event.type === "chunk") {
+ const chunk = update.event.payload as OpenAIChatChunk;
+ if (generationChunkCountsTowardTiming(chunk)) {
+ generationChunkCount += 1;
+ if (generationChunkHasSubstantiveDelta(chunk)) {
+ generationFirstChunkAt ??= update.event.createdAt;
+ }
}
+ yield chunk;
}
- yield chunk;
}
}
+ } catch (error) {
+ if (!(error instanceof ChatGenerationStalledError)) throw error;
+ // End the stream rather than rethrow, keeping everything replayed so
+ // far, as the recovery follower does. The checks below stay quiet
+ // because a stalled run is still non-terminal.
+ generationStalled = true;
+ // Different job from the marker: this is what makes the final yield
+ // carry `incomplete`, without which assistant-ui reads the partial reply
+ // as finished and offers no Continue until a reload rebuilds the reason.
+ incompleteReason = "interrupted";
}
if (generationStatus === "failed") {
throw new ChatGenerationTerminalError(
@@ -7636,6 +7664,17 @@ export function createOpenAIStreamAdapter(
// left claimed after its stream died is one this tab would never recover.
releaseLiveGenerationRun(cancelId);
if (generationRunId) releaseLiveGenerationRun(generationRunId);
+ // A durable run that finished here is no longer active, and only a later
+ // history load would otherwise say so. Until then the thread reads as durable
+ // and a subscriber-owned stream started on it next would be capped.
+ if (
+ generationRunId &&
+ (generationStatus === "completed" ||
+ generationStatus === "failed" ||
+ generationStatus === "cancelled")
+ ) {
+ forgetServerActiveGenerationRun(generationRunId);
+ }
runSignal.removeEventListener("abort", onAbortCancel);
abortSignal.removeEventListener("abort", forwardAbort);
// Resolve once: the clears below drop the owner the lookup keys on.
diff --git a/studio/frontend/src/features/chat/api/chat-generation-api.ts b/studio/frontend/src/features/chat/api/chat-generation-api.ts
index aff2dc13553..1a7cc416478 100644
--- a/studio/frontend/src/features/chat/api/chat-generation-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-generation-api.ts
@@ -79,6 +79,15 @@ const TERMINAL_STATUSES = new Set<ChatGenerationStatus>([
"failed",
]);
+/** The follower gave up on a run that stopped making progress. Distinct from the
+ * caller's Stop: the backend may still be generating, so the reply is incomplete. */
+export class ChatGenerationStalledError extends Error {
+ constructor(runId: string) {
+ super(`Chat generation run ${runId} made no progress`);
+ this.name = "ChatGenerationStalledError";
+ }
+}
+
export class ChatGenerationApiError extends Error {
readonly status: number;
@@ -312,11 +321,22 @@ export async function cancelChatGenerationRun(
);
}
+/** The events stream's own comment. Pinned by a test against the route that emits it. */
+const KEEPALIVE_PREFIX = ": keep-alive";
+
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: SSE framing retains state across reader chunks.
async function* streamChatGenerationEvents(
id: string,
after: number,
signal?: AbortSignal,
+ /**
+ * Called for each event, and for each keep-alive with that keep-alive's progress
+ * stamp. A keep-alive is only progress if the stamp MOVED, which this generator cannot
+ * decide: it is re-invoked on every reconnect, so a per-connection memory would treat
+ * the first keep-alive after each reconnect as progress and a wedged run behind a
+ * flapping proxy would rearm the caller's deadline forever.
+ */
+ onActivity?: (keepAliveStamp?: string) => void,
): AsyncGenerator<ChatGenerationEvent> {
const response = await authFetch(
`/api/inference/chat-runs/${encodeURIComponent(id)}/events?after=${Math.max(0, after)}`,
@@ -340,12 +360,20 @@ async function* streamChatGenerationEvents(
const data: string[] = [];
for (const line of block.split("\n")) {
if (line.startsWith("data:")) data.push(line.slice(5).trimStart());
+ // Reported, not judged. Whether this counts as progress depends on the last
+ // stamp seen across ALL connections for this run, and this generator is
+ // re-invoked on every reconnect, so only the caller can hold that.
+ else if (line.startsWith(KEEPALIVE_PREFIX)) {
+ const stamp = line.slice(KEEPALIVE_PREFIX.length).trim();
+ if (stamp !== "") onActivity?.(stamp);
+ }
}
if (data.length > 0) {
const event = JSON.parse(data.join("\n")) as ChatGenerationEvent;
if (event.type === "chunk") {
event.payload = normalizeChatGenerationChunkPayload(event.payload);
}
+ onActivity?.();
yield event;
}
boundary = buffer.indexOf("\n\n");
@@ -357,6 +385,20 @@ async function* streamChatGenerationEvents(
}
}
+/**
+ * How long a follower tolerates a run that makes no progress. Progress, not connectedness,
+ * ends a follow: every event and every change to the run row resets it.
+ *
+ * A deadline on SILENCE rather than duration, which is what lets it stay short while the
+ * backend tolerates far longer work. Preparation and admission waits emit no events, but
+ * the keep-alive comments carry the run's progress stamp, which the lease renewals move,
+ * so a two hour download rearms this while a wedged run does not. Bytes alone are
+ * deliberately NOT progress: keep-alives keep arriving for as long as the socket holds, so
+ * rearming on them would make this unreachable in exactly the case it exists for, a
+ * backend whose sweeper is disabled or broken.
+ */
+export const CHAT_GENERATION_STALL_TIMEOUT_MS = 30 * 60_000;
+
/** Replay from the caller's applied cursor and reconnect until the run is terminal. */
export async function* followChatGenerationRun(
id: string,
@@ -364,69 +406,127 @@ export async function* followChatGenerationRun(
initialRun?: ChatGenerationRun;
replayFrom?: number;
signal?: AbortSignal;
+ /** Overridable so a test can reach the deadline without waiting out the default. */
+ stallTimeoutMs?: number;
} = {},
): AsyncGenerator<ChatGenerationRunUpdate> {
- const { replayFrom, signal } = options;
- let run = options.initialRun;
- let failures = 0;
- while (!(run || signal?.aborted)) {
- try {
- run = await getChatGenerationRun(id, signal);
- } catch (error) {
- if (signal?.aborted) return;
- if (isPermanent(error)) throw error;
- failures += 1;
- await waitForReconnect(reconnectDelay(failures), signal);
- }
+ const { replayFrom } = options;
+ const stallTimeoutMs =
+ options.stallTimeoutMs ?? CHAT_GENERATION_STALL_TIMEOUT_MS;
+ // The deadline must reach the open stream as well as the sleep between reconnects: a
+ // stream that stays open and sends nothing parks the reader just as permanently. One
+ // controller downstream of the caller's signal covers both.
+ const deadline = new AbortController();
+ const callerSignal = options.signal;
+ const forwardAbort = () => deadline.abort(callerSignal?.reason);
+ if (callerSignal?.aborted) {
+ deadline.abort(callerSignal.reason);
+ } else {
+ callerSignal?.addEventListener("abort", forwardAbort, { once: true });
}
- if (!run || signal?.aborted) return;
- let currentRun = run;
- let cursor = replayFrom ?? run.lastEventSeq;
- yield { run, source: "snapshot" };
- if (isTerminalChatGenerationRun(run) && replayFrom === undefined) return;
+ const signal = deadline.signal;
+ let stallTimer: ReturnType<typeof globalThis.setTimeout> | undefined;
+ // Both abort `signal` but must not end the same way: a caller abort is a clean stop,
+ // while the deadline means we walked away from a run the backend may still be working
+ // on, so it must reach the consumer as a failure rather than a complete reply.
+ let stalled = false;
+ let settled = false;
+ // Spans reconnects on purpose: see the onActivity contract in
+ // streamChatGenerationEvents.
+ let lastKeepAliveStamp: string | null = null;
+ const noteProgress = (keepAliveStamp?: string): void => {
+ if (keepAliveStamp !== undefined) {
+ if (keepAliveStamp === lastKeepAliveStamp) return;
+ lastKeepAliveStamp = keepAliveStamp;
+ }
+ if (signal.aborted) return;
+ if (stallTimer !== undefined) globalThis.clearTimeout(stallTimer);
+ stallTimer = globalThis.setTimeout(() => {
+ stalled = true;
+ deadline.abort(new ChatGenerationStalledError(id));
+ }, stallTimeoutMs);
+ };
- while (!signal?.aborted) {
- try {
- for await (const event of streamChatGenerationEvents(
- id,
- cursor,
- signal,
- )) {
- if (event.seq <= cursor) continue;
- cursor = event.seq;
- if (event.run) currentRun = event.run;
- failures = 0;
- yield { run: currentRun, event, source: "event" };
- if (
- isTerminalChatGenerationRun(currentRun) &&
- cursor >= currentRun.lastEventSeq
- ) {
- return;
- }
+ try {
+ noteProgress();
+ let run = options.initialRun;
+ let failures = 0;
+ while (!(run || signal.aborted)) {
+ try {
+ run = await getChatGenerationRun(id, signal);
+ } catch (error) {
+ if (signal.aborted) return;
+ if (isPermanent(error)) throw error;
+ failures += 1;
+ await waitForReconnect(reconnectDelay(failures), signal);
}
- } catch (error) {
- if (signal?.aborted) return;
- if (isPermanent(error)) throw error;
- failures += 1;
}
- if (signal?.aborted) return;
- try {
- const fresh = await getChatGenerationRun(id, signal);
- const changed =
- fresh.status !== currentRun.status ||
- fresh.updatedAt !== currentRun.updatedAt ||
- fresh.lastEventSeq !== currentRun.lastEventSeq;
- currentRun = fresh;
- if (changed || cursor < fresh.lastEventSeq) {
- yield { run: fresh, source: "snapshot" };
+ if (!run || signal.aborted) return;
+ let currentRun = run;
+ let cursor = replayFrom ?? run.lastEventSeq;
+ yield { run, source: "snapshot" };
+ if (isTerminalChatGenerationRun(run) && replayFrom === undefined) {
+ settled = true;
+ return;
+ }
+
+ while (!signal.aborted) {
+ try {
+ for await (const event of streamChatGenerationEvents(
+ id,
+ cursor,
+ signal,
+ noteProgress,
+ )) {
+ if (event.seq <= cursor) continue;
+ cursor = event.seq;
+ if (event.run) currentRun = event.run;
+ failures = 0;
+ noteProgress();
+ yield { run: currentRun, event, source: "event" };
+ if (
+ isTerminalChatGenerationRun(currentRun) &&
+ cursor >= currentRun.lastEventSeq
+ ) {
+ settled = true;
+ return;
+ }
+ }
+ } catch (error) {
+ if (signal.aborted) return;
+ if (isPermanent(error)) throw error;
+ failures += 1;
}
- if (isTerminalChatGenerationRun(fresh) && cursor >= fresh.lastEventSeq)
- return;
- } catch (error) {
- if (signal?.aborted) return;
- if (isPermanent(error)) throw error;
- failures += 1;
+ if (signal.aborted) return;
+ try {
+ const fresh = await getChatGenerationRun(id, signal);
+ const changed =
+ fresh.status !== currentRun.status ||
+ fresh.updatedAt !== currentRun.updatedAt ||
+ fresh.lastEventSeq !== currentRun.lastEventSeq;
+ currentRun = fresh;
+ if (changed || cursor < fresh.lastEventSeq) {
+ noteProgress();
+ yield { run: fresh, source: "snapshot" };
+ }
+ if (isTerminalChatGenerationRun(fresh) && cursor >= fresh.lastEventSeq) {
+ settled = true;
+ return;
+ }
+ } catch (error) {
+ if (signal.aborted) return;
+ if (isPermanent(error)) throw error;
+ failures += 1;
+ }
+ await waitForReconnect(reconnectDelay(failures), signal);
}
- await waitForReconnect(reconnectDelay(failures), signal);
+ } finally {
+ if (stallTimer !== undefined) globalThis.clearTimeout(stallTimer);
+ callerSignal?.removeEventListener("abort", forwardAbort);
+ // Every exit path funnels here, including the two `while (!signal.aborted)` loop
+ // conditions, so this is the one place that catches all of them. `settled` keeps a
+ // run that reached a terminal status on the same tick as the timer from being
+ // reported as stalled.
+ if (stalled && !settled) throw new ChatGenerationStalledError(id);
}
}
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index ecb525e70fe..d6349ad3b2a 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -46,7 +46,9 @@ import {
cancelChatGenerationRun,
type ChatGenerationRun,
getActiveChatGenerationRuns,
+ ChatGenerationStalledError,
followChatGenerationRun,
+ isTerminalChatGenerationRun,
} from "./api/chat-generation-api";
import {
TEXT_ATTACHMENT_ACCEPT,
@@ -93,10 +95,15 @@ import {
import {
generationChunkCountsTowardTiming,
generationChunkHasSubstantiveDelta,
+ generationIsCorroboratedLive,
+ threadHasDurableGenerationRun,
generationNeedsRecovery,
isLiveGenerationRun,
generationRawContent,
loadGenerationOverlaySnapshot,
+ markServerActiveGenerationRunsUnknown,
+ forgetServerActiveGenerationRun,
+ syncServerActiveGenerationRuns,
recoveredContentToImport,
recoveredReasoningSummaryMetadata,
recoveredGenerationFinalMetadata,
@@ -701,14 +708,36 @@ function toThreadMessage(m: MessageRecord): ThreadMessage {
const savedTiming = custom.timing as
| import("@assistant-ui/react").MessageTiming
| undefined;
- const restoredStatus = restoredAssistantStatus({ custom });
const generationStatus = custom.generationStatus;
- const needsGenerationRecovery =
- typeof custom.generationRunId === "string" &&
+ const hasRunId = typeof custom.generationRunId === "string";
+ const generationUnfinished =
+ hasRunId &&
(generationStatus === "queued" ||
generationStatus === "running" ||
- generationStatus === "cancelling" ||
- (generationStatus === "completed" && custom.generationSettled !== true));
+ generationStatus === "cancelling");
+ const generationUnsettled =
+ hasRunId &&
+ generationStatus === "completed" &&
+ custom.generationSettled !== true;
+ // Persisted metadata alone must never restore a running message: a run that never
+ // terminalised still says "running" on every later load, and `{type:"running"}`
+ // unmounts Send, so the reply the user cannot stop is the one they cannot reply past.
+ // Ask whether the run is corroborated live, and otherwise show the partial as
+ // interrupted, which keeps every character and offers the Continue bar.
+ // The gate is for unfinished runs only. A completed-but-unsettled run has a terminal
+ // status, so /chat-runs/active never lists it and it could never be corroborated; it
+ // still owns an unreplayed tail, and the follow that replays it returns on the first
+ // snapshot rather than holding the composer.
+ const needsGenerationRecovery =
+ generationUnsettled ||
+ (generationUnfinished && generationIsCorroboratedLive(custom, m.threadId));
+ const restoredCustom =
+ generationUnfinished &&
+ !needsGenerationRecovery &&
+ custom.incomplete === undefined
+ ? { ...custom, incomplete: { reason: "interrupted" as const } }
+ : custom;
+ const restoredStatus = restoredAssistantStatus({ custom: restoredCustom });
return {
id: m.id,
createdAt: new Date(m.createdAt),
@@ -719,7 +748,7 @@ function toThreadMessage(m: MessageRecord): ThreadMessage {
>["content"],
status: needsGenerationRecovery ? { type: "running" } : restoredStatus,
metadata: {
- custom,
+ custom: restoredCustom,
...(savedTiming ? { timing: savedTiming } : {}),
steps: [],
unstable_annotations: [],
@@ -791,40 +820,17 @@ function scheduleGenerationRecovery(
owner: serverCancel,
});
- const publish = async (run: ChatGenerationRun) => {
- const status = run.status;
- const runModel = useChatRuntimeStore
- .getState()
- .models.find((model) => model.id === run.requestPayload.model);
- const lengthLimited =
- run.finishReason === "length" ||
- budgetImpliesTruncation({
- isMlx: runModel?.isMlx === true,
- maxTokens: run.requestPayload.max_tokens,
- completionTokens,
- });
- let nextMetadata = generationRecoveryMetadata({
- current: currentMetadata,
- runId,
- status,
- cursor,
- lastEventSeq: run.lastEventSeq,
- lengthLimited,
- firstChunkAt,
- totalChunks,
- usage: recoveryUsage,
- timings: recoveryTimings,
- });
- if (nextMetadata.generationSettled === true) {
- nextMetadata = recoveredGenerationFinalMetadata({
- current: nextMetadata,
- run,
- usage: recoveryUsage,
- timings: recoveryTimings,
- firstChunkAt,
- totalChunks,
- });
- }
+ /**
+ * Write one state of the reply to storage and to every view showing it.
+ *
+ * `running` is the caller's, not derived here: a follow that hit its no-progress
+ * deadline settles the message while its persisted run status is still non-terminal,
+ * which is exactly the pair `generationNeedsRecovery` reads as "still going".
+ */
+ const commit = async (
+ nextMetadata: Record<string, unknown>,
+ running: boolean,
+ ) => {
currentMetadata = nextMetadata;
const content = parseAssistantContent(
reasoningOpen ? `${raw}</think>` : raw,
@@ -860,7 +866,7 @@ function scheduleGenerationRecovery(
item.message.content,
content,
),
- status: generationNeedsRecovery(nextMetadata)
+ status: running
? { type: "running" as const }
: restoredAssistantStatus({ custom: nextMetadata }),
metadata: {
@@ -878,114 +884,194 @@ function scheduleGenerationRecovery(
}
};
+ const publish = async (run: ChatGenerationRun) => {
+ const status = run.status;
+ const runModel = useChatRuntimeStore
+ .getState()
+ .models.find((model) => model.id === run.requestPayload.model);
+ const lengthLimited =
+ run.finishReason === "length" ||
+ budgetImpliesTruncation({
+ isMlx: runModel?.isMlx === true,
+ maxTokens: run.requestPayload.max_tokens,
+ completionTokens,
+ });
+ let nextMetadata = generationRecoveryMetadata({
+ current: currentMetadata,
+ runId,
+ status,
+ cursor,
+ lastEventSeq: run.lastEventSeq,
+ lengthLimited,
+ firstChunkAt,
+ totalChunks,
+ usage: recoveryUsage,
+ timings: recoveryTimings,
+ });
+ if (nextMetadata.generationSettled === true) {
+ nextMetadata = recoveredGenerationFinalMetadata({
+ current: nextMetadata,
+ run,
+ usage: recoveryUsage,
+ timings: recoveryTimings,
+ firstChunkAt,
+ totalChunks,
+ });
+ }
+ await commit(nextMetadata, generationNeedsRecovery(nextMetadata));
+ };
+
try {
let lastPublishedStatus = "";
let identityValidated = false;
- for await (const update of followChatGenerationRun(runId, {
- replayFrom: cursor,
- })) {
- if (!identityValidated) {
- if (
- update.run.threadId !== threadId ||
- update.run.assistantMessageId !== storedMessage.id
- ) {
- return;
- }
- if (cursor === 0 && raw.length === 0) {
- const requestMessages = update.run.requestPayload.messages;
- const lastRequestMessage = Array.isArray(requestMessages)
- ? requestMessages.at(-1)
- : undefined;
+ // The follower reports its no-progress deadline by throwing, and the settlement
+ // below is exactly what must happen when it does. Without this catch the throw
+ // reaches the outer no-op handler and leaves a message marked running forever.
+ let followStalled = false;
+ try {
+ for await (const update of followChatGenerationRun(runId, {
+ replayFrom: cursor,
+ })) {
+ if (!identityValidated) {
if (
- lastRequestMessage?.role === "assistant" &&
- typeof lastRequestMessage.content === "string"
+ update.run.threadId !== threadId ||
+ update.run.assistantMessageId !== storedMessage.id
) {
- // Continue sends the old partial as an assistant prefill. The
- // server-owned placeholder is empty until the first client save,
- // so a reload before that save must seed replay from the request.
- raw = lastRequestMessage.content;
+ return;
+ }
+ if (cursor === 0 && raw.length === 0) {
+ const requestMessages = update.run.requestPayload.messages;
+ const lastRequestMessage = Array.isArray(requestMessages)
+ ? requestMessages.at(-1)
+ : undefined;
+ if (
+ lastRequestMessage?.role === "assistant" &&
+ typeof lastRequestMessage.content === "string"
+ ) {
+ // Continue sends the old partial as an assistant prefill. The
+ // server-owned placeholder is empty until the first client save,
+ // so a reload before that save must seed replay from the request.
+ raw = lastRequestMessage.content;
+ }
}
+ identityValidated = true;
}
- identityValidated = true;
- }
- if (update.event && update.event.seq > cursor) {
- cursor = update.event.seq;
- if (update.event.type === "chunk") {
- const chunk = update.event.payload as {
- _reasoningDurationMs?: unknown;
- usage?: {
- prompt_tokens?: unknown;
- completion_tokens?: unknown;
- total_tokens?: unknown;
- prompt_tokens_details?: { cached_tokens?: unknown };
- cache_creation_input_tokens?: unknown;
- cache_read_input_tokens?: unknown;
- };
- timings?: Record<string, unknown>;
- choices?: Array<{
- delta?: {
- content?: unknown;
- reasoning_content?: unknown;
+ if (update.event && update.event.seq > cursor) {
+ cursor = update.event.seq;
+ if (update.event.type === "chunk") {
+ const chunk = update.event.payload as {
+ _reasoningDurationMs?: unknown;
+ usage?: {
+ prompt_tokens?: unknown;
+ completion_tokens?: unknown;
+ total_tokens?: unknown;
+ prompt_tokens_details?: { cached_tokens?: unknown };
+ cache_creation_input_tokens?: unknown;
+ cache_read_input_tokens?: unknown;
};
- }>;
- context_truncated?: OpenAIChatChunk["context_truncated"];
- };
- if ("_reasoningDurationMs" in chunk) {
- currentMetadata = recoveredReasoningSummaryMetadata(
- currentMetadata,
- chunk._reasoningDurationMs,
- );
- lastPublishedStatus = update.run.status;
- await publish(update.run);
- continue;
- }
- if (generationChunkCountsTowardTiming(chunk)) {
- totalChunks += 1;
- }
- if (generationChunkHasSubstantiveDelta(chunk)) {
- firstChunkAt ??= update.event.createdAt;
- }
- if (chunk.context_truncated) {
- currentMetadata = {
- ...currentMetadata,
- contextTruncation: mergeContextTruncation(
- currentMetadata.contextTruncation as OpenAIChatChunk["context_truncated"],
- chunk.context_truncated,
- ),
+ timings?: Record<string, unknown>;
+ choices?: Array<{
+ delta?: {
+ content?: unknown;
+ reasoning_content?: unknown;
+ };
+ }>;
+ context_truncated?: OpenAIChatChunk["context_truncated"];
};
- }
- if (chunk.usage) recoveryUsage = chunk.usage;
- if (chunk.timings) recoveryTimings = chunk.timings;
- if (typeof chunk.usage?.completion_tokens === "number") {
- completionTokens = chunk.usage.completion_tokens;
- }
- const deltaRecord = chunk.choices?.[0]?.delta;
- const reasoning =
- typeof deltaRecord?.reasoning_content === "string"
- ? deltaRecord.reasoning_content
- : "";
- const delta = extractDeltaText(deltaRecord?.content).text;
- if (reasoning) {
- if (!reasoningOpen) raw += "<think>";
- raw += reasoning;
- reasoningOpen = true;
- }
- if (delta) {
- if (reasoningOpen) raw += "</think>";
- raw += delta;
- reasoningOpen = false;
+ if ("_reasoningDurationMs" in chunk) {
+ currentMetadata = recoveredReasoningSummaryMetadata(
+ currentMetadata,
+ chunk._reasoningDurationMs,
+ );
+ lastPublishedStatus = update.run.status;
+ await publish(update.run);
+ continue;
+ }
+ if (generationChunkCountsTowardTiming(chunk)) {
+ totalChunks += 1;
+ }
+ if (generationChunkHasSubstantiveDelta(chunk)) {
+ firstChunkAt ??= update.event.createdAt;
+ }
+ if (chunk.context_truncated) {
+ currentMetadata = {
+ ...currentMetadata,
+ contextTruncation: mergeContextTruncation(
+ currentMetadata.contextTruncation as OpenAIChatChunk["context_truncated"],
+ chunk.context_truncated,
+ ),
+ };
+ }
+ if (chunk.usage) recoveryUsage = chunk.usage;
+ if (chunk.timings) recoveryTimings = chunk.timings;
+ if (typeof chunk.usage?.completion_tokens === "number") {
+ completionTokens = chunk.usage.completion_tokens;
+ }
+ const deltaRecord = chunk.choices?.[0]?.delta;
+ const reasoning =
+ typeof deltaRecord?.reasoning_content === "string"
+ ? deltaRecord.reasoning_content
+ : "";
+ const delta = extractDeltaText(deltaRecord?.content).text;
+ if (reasoning) {
+ if (!reasoningOpen) raw += "<think>";
+ raw += reasoning;
+ reasoningOpen = true;
+ }
+ if (delta) {
+ if (reasoningOpen) raw += "</think>";
+ raw += delta;
+ reasoningOpen = false;
+ }
}
}
+ const shouldPublish =
+ update.event?.type === "chunk" ||
+ update.run.status !== lastPublishedStatus ||
+ (["cancelled", "completed", "failed"].includes(update.run.status) &&
+ cursor >= update.run.lastEventSeq);
+ if (shouldPublish) {
+ lastPublishedStatus = update.run.status;
+ await publish(update.run);
+ }
+ if (isTerminalChatGenerationRun(update.run)) {
+ // Only another successful active-list sync would otherwise drop it, so the
+ // thread would keep reading as durable and a later subscriber-owned stream
+ // on it would be capped, losing the checkpoints that are its only
+ // persistence.
+ forgetServerActiveGenerationRun(runId);
+ }
}
- const shouldPublish =
- update.event?.type === "chunk" ||
- update.run.status !== lastPublishedStatus ||
- (["cancelled", "completed", "failed"].includes(update.run.status) &&
- cursor >= update.run.lastEventSeq);
- if (shouldPublish) {
- lastPublishedStatus = update.run.status;
- await publish(update.run);
- }
+ } catch (error) {
+ if (!(error instanceof ChatGenerationStalledError)) throw error;
+ followStalled = true;
+ }
+ if (followStalled || generationNeedsRecovery(currentMetadata)) {
+ // Fence the run before presenting the reply as resumable. Settling only in this
+ // tab leaves the row queued/running/cancelling, and create_run refuses a thread
+ // that already has an active generation, so Continue and the next message would
+ // both 409 against a reply the UI had just declared finished. Best effort, and
+ // not sufficient on its own: a producer wedged inside the engine stays in
+ // `cancelling`, which is still active. That case is what the server-side sweeper
+ // settles, and this path is reachable mainly when the sweeper is disabled.
+ serverCancel();
+ // The follow returned with the run still non-terminal, so its no-progress
+ // deadline expired. Settle the reply here rather than leaving a message that
+ // says "running" until the next reload, which is what keeps Send unmounted.
+ // Everything replayed so far is kept.
+ await commit(
+ {
+ ...currentMetadata,
+ incomplete: { reason: "interrupted" as const },
+ // The run row may still be non-terminal, so without this marker
+ // generationNeedsRecovery stays true and the next online, pageshow or
+ // visibility trigger starts another follower that republishes the message
+ // as running. history.load clears it if /chat-runs/active still names the
+ // run, so the server, not this tab, gets the last word.
+ generationLocallyInterrupted: true,
+ },
+ false,
+ );
}
} finally {
const store = useChatRuntimeStore.getState();
@@ -1700,6 +1786,7 @@ function useStudioRuntimeAdapters(
};
let msgs: MessageRecord[];
let activeGenerationRuns: ChatGenerationRun[];
+ let activeGenerationRunsLoaded: boolean;
try {
const snapshot = await loadGenerationOverlaySnapshot(
remoteId,
@@ -1708,24 +1795,112 @@ function useStudioRuntimeAdapters(
);
msgs = snapshot.messages;
activeGenerationRuns = snapshot.activeRuns;
+ activeGenerationRunsLoaded = snapshot.activeRunsLoaded;
} catch (error) {
if (!isExpectedBackgroundChatStorageError(error)) {
throw error;
}
msgs = [];
activeGenerationRuns = [];
+ activeGenerationRunsLoaded = false;
+ }
+ // The endpoint is named for active runs but returns rows, so a run that
+ // terminalised between the write and this read comes back with it, and
+ // force-writing `generationSettled: false` over a finished reply revives it.
+ // Take the still-live rows only and publish them as the corroboration
+ // `toThreadMessage` restores a running status from. A failed read is silence,
+ // not a report of "nothing is running".
+ activeGenerationRuns = activeGenerationRuns.filter(
+ (run) => !isTerminalChatGenerationRun(run),
+ );
+ // And drop any run the message snapshot already shows as finished. The runs read
+ // happens first, so a run that completed in between is still listed as running
+ // here. Filtering the LIST rather than skipping at the overlay matters: the
+ // registry sync below runs first, and a stale mapping there keeps the thread
+ // reading as durable, so a later subscriber-owned stream on it would be capped
+ // and lose everything it streamed past the cap. In another tab nothing else
+ // would ever remove that mapping.
+ const terminalMessageRuns = new Set(
+ msgs
+ .filter((message) => {
+ const custom = (message.metadata ?? {}) as Record<string, unknown>;
+ const status = custom.generationStatus;
+ return (
+ status === "completed" ||
+ status === "failed" ||
+ status === "cancelled"
+ );
+ })
+ .map((message) => message.id),
+ );
+ activeGenerationRuns = activeGenerationRuns.filter(
+ (run) => !terminalMessageRuns.has(run.assistantMessageId),
+ );
+ // The runs read happens BEFORE the messages read, so a run created between the
+ // two would read as interrupted and re-enable the composer for a thread the
+ // server is still generating on. Close that gap with one more lookup, and only
+ // when a message actually names a run the first read missed.
+ if (!activeGenerationRunsLoaded) {
+ // The initial read failed, so this thread has no current answer. Retract any
+ // answer from an earlier load: another tab may have started a run since, and
+ // the stale answer would restore that live reply as interrupted and briefly
+ // enable a conflicting send.
+ markServerActiveGenerationRunsUnknown(remoteId);
+ }
+ if (activeGenerationRunsLoaded) {
+ let answered = true;
+ const known = new Set(activeGenerationRuns.map((run) => run.id));
+ const missed = msgs.some((message) => {
+ const custom = (message.metadata ?? {}) as Record<string, unknown>;
+ const runId = custom.generationRunId;
+ const status = custom.generationStatus;
+ return (
+ typeof runId === "string" &&
+ !known.has(runId) &&
+ (status === "queued" ||
+ status === "running" ||
+ status === "cancelling")
+ );
+ });
+ if (missed) {
+ try {
+ const second = await getActiveChatGenerationRuns(remoteId);
+ activeGenerationRuns = second.filter(
+ (run) => !isTerminalChatGenerationRun(run),
+ );
+ } catch {
+ // `missed` already proved the first list predates this run, so it is not
+ // an answer either. Leave the thread unanswered rather than promoting a
+ // list known to be stale, and retract any answer from an earlier load:
+ // another tab may have started a run since, and the stale answer would
+ // restore that live reply as interrupted.
+ answered = false;
+ markServerActiveGenerationRunsUnknown(remoteId);
+ }
+ }
+ if (answered) {
+ syncServerActiveGenerationRuns(
+ remoteId,
+ activeGenerationRuns.map((run) => run.id),
+ );
+ }
}
for (const run of activeGenerationRuns) {
const assistant = msgs.find(
(message) => message.id === run.assistantMessageId,
);
if (!assistant) continue;
+
assistant.metadata = {
...(assistant.metadata ?? {}),
generationRunId: run.id,
generationStatus: run.status,
generationSettled: false,
serverManaged: true,
+ // The server still has this run, which overrules a follower that gave up on
+ // it locally. Clearing the marker here is what lets a genuinely slow run be
+ // picked back up instead of staying interrupted for the life of the page.
+ generationLocallyInterrupted: false,
};
}
// Durable research can outlive this runtime. Reattach its server-owned
@@ -3045,7 +3220,10 @@ function ThreadBackendAutosave({
const checkpoints = useCallback((): RunCheckpointScheduler => {
checkpointsRef.current ??= createRunCheckpointScheduler(
(threadId) => queueSaveRef.current(threadId),
- { isActive: (threadId) => isRunActiveRef.current(threadId) },
+ {
+ isActive: (threadId) => isRunActiveRef.current(threadId),
+ isBounded: (threadId) => threadHasDurableGenerationRun(threadId),
+ },
);
return checkpointsRef.current;
}, []);
diff --git a/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts b/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts
index 101763dcecc..bf42c354919 100644
--- a/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts
+++ b/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts
@@ -92,12 +92,24 @@ export async function loadGenerationOverlaySnapshot<TMessage, TRun>(
threadId: string,
listActiveRuns: (id: string) => Promise<TRun[]>,
listMessages: (id: string) => Promise<TMessage[]>,
-): Promise<{ messages: TMessage[]; activeRuns: TRun[] }> {
+): Promise<{
+ messages: TMessage[];
+ activeRuns: TRun[];
+ /**
+ * False when the active-run read failed, so its empty list is "unknown", not "none".
+ * A caller that decides a reply is dead from an absent run has to tell the two apart.
+ */
+ activeRunsLoaded: boolean;
+}> {
// Runs first closes the create-between-snapshots gap. If a run commits after
// this read, the later message snapshot already carries its durable metadata.
- const activeRuns = await listActiveRuns(threadId).catch(() => []);
+ let activeRunsLoaded = true;
+ const activeRuns = await listActiveRuns(threadId).catch(() => {
+ activeRunsLoaded = false;
+ return [];
+ });
const messages = await listMessages(threadId);
- return { messages, activeRuns };
+ return { messages, activeRuns, activeRunsLoaded };
}
type RecoveryUsage = {
@@ -273,6 +285,16 @@ export function generationNeedsRecovery(
metadata: Record<string, unknown>,
): boolean {
const status = String(metadata.generationStatus) as StoredGenerationStatus;
+ // Stamped by a follower that hit its no-progress deadline. Re-following on every
+ // recovery trigger is what turned one stuck run into a permanently blocked composer;
+ // history.load clears the marker if /chat-runs/active still names the run.
+ //
+ // Non-terminal only: a run the backend finished is stored completed and unsettled, and
+ // /chat-runs/active excludes completed runs, so honouring the marker there would leave
+ // that reply running forever with its event tail never imported.
+ if (metadata.generationLocallyInterrupted === true && !TERMINAL.has(status)) {
+ return false;
+ }
return (
typeof metadata.generationRunId === "string" &&
(metadata.generationSettled !== true || !TERMINAL.has(status))
@@ -411,10 +433,34 @@ export function subscribeGenerationRecoveryTriggers(
* needs to expire it.
*/
const liveGenerationRuns = new Set<string>();
+// runId -> owning thread. The Set above answers "is this run live"; the checkpoint
+// scheduler needs the inverse, "does this thread have a durable run at all".
+const liveGenerationThreads = new Map<string, string>();
+
+/**
+ * Runs claimed before the server admitted them.
+ *
+ * The early claim stops a recovery trigger starting a second follower during that await.
+ * Boundedness is separate: until the POST lands the thread's checkpoints are its only
+ * persistence, and createChatGenerationRun retries until aborted, so the await can outlast
+ * the cap.
+ */
+const provisionalGenerationRuns = new Set<string>();
/** Claim a run as streamed by this tab. Pair with `releaseLiveGenerationRun` in a finally. */
-export function claimLiveGenerationRun(runId: string): void {
+export function claimLiveGenerationRun(
+ runId: string,
+ threadId?: string,
+ options?: { provisional?: boolean },
+): void {
liveGenerationRuns.add(runId);
+ if (threadId) liveGenerationThreads.set(runId, threadId);
+ // A later non-provisional claim confirms admission, so this clears as well as sets.
+ if (options?.provisional) {
+ provisionalGenerationRuns.add(runId);
+ } else {
+ provisionalGenerationRuns.delete(runId);
+ }
}
/**
@@ -425,9 +471,134 @@ export function claimLiveGenerationRun(runId: string): void {
*/
export function releaseLiveGenerationRun(runId: string): void {
liveGenerationRuns.delete(runId);
+ liveGenerationThreads.delete(runId);
+ provisionalGenerationRuns.delete(runId);
}
/** Whether this tab is the one streaming `runId`. */
export function isLiveGenerationRun(runId: string): boolean {
return liveGenerationRuns.has(runId);
}
+
+/**
+ * Whether `threadId` has a durable run, either streaming here or named by the server. A
+ * subscriber-owned stream has none, and its periodic checkpoint is its ONLY persistence.
+ */
+export function threadHasDurableGenerationRun(threadId: string): boolean {
+ for (const [runId, owner] of liveGenerationThreads.entries()) {
+ if (owner === threadId && !provisionalGenerationRuns.has(runId)) return true;
+ }
+ for (const owner of serverActiveGenerationRuns.values()) {
+ if (owner === threadId) return true;
+ }
+ return false;
+}
+
+/**
+ * Runs the server has named as still going, keyed by the thread whose load asked.
+ *
+ * Persisted metadata is not evidence of a live run: a run that never terminalises leaves
+ * `generationStatus: "running"` in storage for good, and a reload rebuilds a running
+ * message straight back out of it. Only `/api/inference/chat-runs/active` can say a run
+ * is still going. Module state, so a reload drops the previous session's word for it.
+ */
+const serverActiveGenerationRuns = new Map<string, string>();
+
+/**
+ * Replace what the server last said about `threadId`. Call only after a SUCCESSFUL read
+ * of the active-run list: a failed read is not a report of "nothing is running", and
+ * treating it as one would mark a live reply interrupted.
+ */
+export function syncServerActiveGenerationRuns(
+ threadId: string,
+ runIds: Iterable<string>,
+): void {
+ for (const [runId, owner] of [...serverActiveGenerationRuns]) {
+ if (owner === threadId) serverActiveGenerationRuns.delete(runId);
+ }
+ for (const runId of runIds) serverActiveGenerationRuns.set(runId, threadId);
+ serverAnsweredThreads.add(threadId);
+}
+
+/**
+ * Threads the server has answered the active-run question for. Per thread, not per
+ * process: one global flag let A's answer turn a FAILED read for B into an empty list.
+ */
+const serverAnsweredThreads = new Set<string>();
+
+export function serverHasAnsweredActiveRuns(threadId: string): boolean {
+ return serverAnsweredThreads.has(threadId);
+}
+
+/**
+ * Forget what the server last said about `threadId`, because the newest read failed.
+ *
+ * The answer is a point in time, not a permanent property. Another tab can start a run
+ * after a successful read, so keeping the old answer once a refresh has failed would
+ * restore that genuinely running reply as interrupted.
+ */
+export function markServerActiveGenerationRunsUnknown(threadId: string): void {
+ serverAnsweredThreads.delete(threadId);
+ // The run mappings go with it. They are the same stale answer in another shape, and
+ // isServerActiveGenerationRun is consulted BEFORE the local-interruption marker, so a
+ // leftover entry restores the message as running while generationNeedsRecovery still
+ // refuses to start a follower: a blocked composer with neither recovery nor a local
+ // Stop handle, which is the wedge this PR exists to remove.
+ for (const [runId, owner] of [...serverActiveGenerationRuns]) {
+ if (owner === threadId) serverActiveGenerationRuns.delete(runId);
+ }
+}
+
+/**
+ * Drop one run from the server-active map now that it has reached a terminal status.
+ *
+ * Only another successful sync would otherwise remove it, so the thread would keep
+ * reading as durable and a later subscriber-owned stream on it would be capped, losing
+ * the periodic saves that are that stream's only persistence.
+ */
+export function forgetServerActiveGenerationRun(runId: string): void {
+ serverActiveGenerationRuns.delete(runId);
+}
+
+/** Test-only: forget every active-run answer. */
+export function resetServerActiveGenerationRuns(): void {
+ serverActiveGenerationRuns.clear();
+ serverAnsweredThreads.clear();
+ liveGenerationThreads.clear();
+ liveGenerationRuns.clear();
+ provisionalGenerationRuns.clear();
+}
+
+/** Whether the server has named `runId` as still going in this session. */
+export function isServerActiveGenerationRun(runId: string): boolean {
+ return serverActiveGenerationRuns.has(runId);
+}
+
+/**
+ * Whether a restored assistant message may be shown as still generating.
+ *
+ * The corroboration gate: unfinished metadata says only that this reply once had a run,
+ * never that the run is still alive.
+ */
+export function generationIsCorroboratedLive(
+ metadata: Record<string, unknown>,
+ threadId?: string,
+): boolean {
+ const runId = metadata.generationRunId;
+ if (typeof runId !== "string") return false;
+ if (isLiveGenerationRun(runId) || isServerActiveGenerationRun(runId)) return true;
+ // A follower already gave up on this run locally. Without this it keeps taking the
+ // benefit of the doubt below, so every online/pageshow/visibility trigger starts
+ // another follower that republishes the message as running and blocks the composer
+ // again. Only the server naming the run live may revive it, and the two checks above
+ // are exactly that.
+ if (
+ metadata.generationLocallyInterrupted === true &&
+ !TERMINAL.has(String(metadata.generationStatus) as StoredGenerationStatus)
+ ) {
+ return false;
+ }
+ // No answer for THIS thread is not a "no". Stay with the persisted status until this
+ // thread's own read has landed; the recovery follower settles it from there.
+ return threadId === undefined || !serverHasAnsweredActiveRuns(threadId);
+}
diff --git a/studio/frontend/src/features/chat/utils/run-checkpoint-scheduler.ts b/studio/frontend/src/features/chat/utils/run-checkpoint-scheduler.ts
index b5c40789367..11436daffb2 100644
--- a/studio/frontend/src/features/chat/utils/run-checkpoint-scheduler.ts
+++ b/studio/frontend/src/features/chat/utils/run-checkpoint-scheduler.ts
@@ -6,10 +6,23 @@
/** Quiet time after a checkpoint settles before the next one is taken. */
export const RUN_CHECKPOINT_INTERVAL_MS = 8_000;
+/**
+ * How long one thread may be checkpointed before the schedule gives up on it. A run that
+ * never terminalises would otherwise checkpoint for the life of the page.
+ *
+ * Never rearmed, unlike the follow deadline in chat-generation-api.ts. That is safe only
+ * because the cap applies to durable runs alone (see `isBounded`), which the server
+ * persists; a subscriber-owned stream, whose only persistence IS these saves, is never
+ * capped.
+ */
+export const RUN_CHECKPOINT_MAX_DURATION_MS = 30 * 60_000;
+
/** Injectable so a test can drive the schedule without real time passing. */
export type RunCheckpointTimers = {
setTimeout: (callback: () => void, ms: number) => number;
clearTimeout: (handle: number) => void;
+ /** Omit to read the wall clock. Only the staleness bound consults it. */
+ now?: () => number;
};
export type RunCheckpointScheduler = {
@@ -29,6 +42,7 @@ export type RunCheckpointScheduler = {
type ThreadState = {
handle: number | null;
stopped: boolean;
+ startedAt: number;
};
const noop = (): void => {};
@@ -51,11 +65,25 @@ export function createRunCheckpointScheduler(
* checkpoint for the life of the page. Omit it to treat every thread as active.
*/
isActive?: (threadId: string) => boolean;
+ /**
+ * Wall-clock cap on one thread's schedule. `isActive` cannot serve as one: it reports
+ * the runtime's own `isRunning`, which a run that never terminalises holds true.
+ */
+ maxDurationMs?: number;
+ /**
+ * Whether `maxDurationMs` applies to this thread. A subscriber-owned stream persists
+ * ONLY through these checkpoints, so capping one would lose everything it streamed
+ * after the cap if the page went away before `runEnd`. Omit to cap every thread.
+ */
+ isBounded?: (threadId: string) => boolean;
} = {},
): RunCheckpointScheduler {
const intervalMs = options.intervalMs ?? RUN_CHECKPOINT_INTERVAL_MS;
const timers = options.timers ?? defaultTimers;
const isActive = options.isActive;
+ const maxDurationMs = options.maxDurationMs ?? RUN_CHECKPOINT_MAX_DURATION_MS;
+ const isBounded = options.isBounded;
+ const now = timers.now ?? (() => Date.now());
const threads = new Map<string, ThreadState>();
/** Never let a caller's throw escape the timer: that would strand the Map entry. */
@@ -67,6 +95,15 @@ export function createRunCheckpointScheduler(
}
};
+ /** Only durable runs are capped; see `isBounded`. Throwing means "not durable". */
+ const isBoundedRun = (threadId: string): boolean => {
+ try {
+ return isBounded?.(threadId) ?? true;
+ } catch {
+ return false;
+ }
+ };
+
/** A thread the runtime has dropped throws rather than reporting itself idle. */
const isRunning = (threadId: string): boolean => {
try {
@@ -88,8 +125,11 @@ export function createRunCheckpointScheduler(
schedule(threadId, state);
}
};
- if (!isRunning(threadId)) {
- // A missed runEnd also lost the final save, so take one on the way out.
+ // Both exits take a final save: a schedule that ends without one has lost
+ // whatever the last interval produced, exactly as a missed runEnd would.
+ const capped =
+ now() - state.startedAt >= maxDurationMs && isBoundedRun(threadId);
+ if (!isRunning(threadId) || capped) {
stop(threadId);
void runSave(threadId).then(noop, noop);
return;
@@ -118,7 +158,11 @@ export function createRunCheckpointScheduler(
if (threads.has(threadId)) {
return;
}
- const state: ThreadState = { handle: null, stopped: false };
+ const state: ThreadState = {
+ handle: null,
+ stopped: false,
+ startedAt: now(),
+ };
threads.set(threadId, state);
schedule(threadId, state);
},
diff --git a/studio/frontend/src/features/chat/utils/stop-chat-thread.ts b/studio/frontend/src/features/chat/utils/stop-chat-thread.ts
index bd963054de2..6e4529f0c9e 100644
--- a/studio/frontend/src/features/chat/utils/stop-chat-thread.ts
+++ b/studio/frontend/src/features/chat/utils/stop-chat-thread.ts
@@ -1,15 +1,43 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import {
+ cancelChatGenerationRun,
+ getActiveChatGenerationRuns,
+} from "../api/chat-generation-api";
import { useChatRuntimeStore } from "../stores/chat-runtime-store";
+/**
+ * Ask the server to stop whatever it still has running for this thread.
+ *
+ * The registries below are module-scoped React state, so a page reload empties them, while
+ * a durable run is server-owned and outlives the tab that started it: the UI says a reply
+ * is generating and every stop path says there is nothing to stop. The server's active-run
+ * list still knows, so a thread with no local handle falls back to it. Fire and forget;
+ * a thread with no run just reads an empty list.
+ */
+function stopServerRunsForThread(threadId: string): void {
+ void getActiveChatGenerationRuns(threadId)
+ .then((runs) => {
+ for (const run of runs) {
+ void cancelChatGenerationRun(run.id).catch(() => {});
+ }
+ })
+ .catch(() => {
+ // No durable-run endpoint, or the backend is gone. Either way there is nothing
+ // further this client can do about a run it holds no handle for.
+ });
+}
+
/**
* Stop one conversation's generation, visible or not. Returns true if a stop was dispatched.
*
* `cancelByThreadId` is assistant-ui's `cancelRun()`, registered only for the thread on screen;
* `serverCancelByThreadId` is registered for every run and POSTs that run's own `cancel_id`, so
* it is the only handle a background conversation has. Both are per-run. Runs with an unresolved
- * thread id share the "__default" key, so stop every handle filed under it.
+ * thread id share the "__default" key, so stop every handle filed under it. With none of the
+ * three, the server is asked directly rather than the call reporting nothing to do, so the
+ * return means "a stop was sent", not "a local handle existed".
*/
export function stopChatThread(threadId: string | null | undefined): boolean {
if (!threadId) return false;
@@ -18,7 +46,8 @@ export function stopChatThread(threadId: string | null | undefined): boolean {
const cancel = cancelByThreadId[threadId];
const serverCancels = serverCancelByThreadId[threadId] ?? [];
if (!runningByThreadId[threadId] && !cancel && serverCancels.length === 0) {
- return false;
+ stopServerRunsForThread(threadId);
+ return true;
}
let stopped = false;
try {
@@ -38,5 +67,10 @@ export function stopChatThread(threadId: string | null | undefined): boolean {
// Same as above.
}
}
+ // A thread flagged running with no handle at all is the reload case again, one run later.
+ if (!stopped) {
+ stopServerRunsForThread(threadId);
+ stopped = true;
+ }
return stopped;
}
diff --git a/studio/frontend/tests/chat-run-checkpoint-lifecycle.test.ts b/studio/frontend/tests/chat-run-checkpoint-lifecycle.test.ts
index aec015cd9b7..78fdbce62e8 100644
--- a/studio/frontend/tests/chat-run-checkpoint-lifecycle.test.ts
+++ b/studio/frontend/tests/chat-run-checkpoint-lifecycle.test.ts
@@ -5,6 +5,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import {
RUN_CHECKPOINT_INTERVAL_MS,
+ RUN_CHECKPOINT_MAX_DURATION_MS,
type RunCheckpointTimers,
createRunCheckpointScheduler,
} from "../src/features/chat/utils/run-checkpoint-scheduler.ts";
@@ -33,6 +34,10 @@ function createFakeTimers() {
clearTimeout: (handle) => {
scheduled.delete(handle);
},
+ // The staleness bound reads a clock, and this harness already keeps one. Without
+ // this the bound would be measured against the real wall clock, so a test that
+ // advances an hour of fake time would take none of it and never reach the cap.
+ now: () => now,
};
const fireDue = async (): Promise<number> => {
@@ -92,14 +97,27 @@ function createGatedSave() {
// A. backwards compatibility of the new options
-test("omitting isActive keeps checkpointing indefinitely while started", async () => {
+// This file used to assert that omitting isActive checkpoints INDEFINITELY, and called
+// that intentional. It is no longer true, deliberately. A run that never reaches a
+// terminal status never fires runEnd, and `isActive` reports the runtime's own
+// `isRunning`, which that same stuck run holds true, so the two agreed forever and the
+// schedule outlived the page: a real user log showed 160 four-request cycles at 8-9s
+// against one thread, unbroken by two full app reloads. An absent or always-true liveness
+// probe still must not END a live run, which is what the first twelve intervals below
+// pin; what it may no longer do is run without any bound at all.
+
+test("omitting isActive keeps checkpointing until the staleness bound, not forever", async () => {
const clock = createFakeTimers();
const saved: string[] = [];
const scheduler = createRunCheckpointScheduler(
async (threadId) => {
saved.push(threadId);
},
- { intervalMs: INTERVAL, timers: clock.timers },
+ {
+ intervalMs: INTERVAL,
+ timers: clock.timers,
+ maxDurationMs: 20 * INTERVAL,
+ },
);
scheduler.start("thread-a");
@@ -109,9 +127,19 @@ test("omitting isActive keeps checkpointing indefinitely while started", async (
assert.equal(
saved.length,
12,
- "an absent liveness probe must not end the run",
+ "an absent liveness probe must not end the run early",
);
assert.equal(clock.pending(), 1, "the schedule is still armed");
+
+ for (let i = 0; i < 12; i += 1) {
+ await clock.advance(INTERVAL);
+ }
+ assert.equal(
+ saved.length,
+ 20,
+ "the cap takes a final checkpoint on the way out and then writes no more",
+ );
+ assert.equal(clock.pending(), 0, "the schedule must not rearm past the cap");
scheduler.stop("thread-a");
});
@@ -122,7 +150,12 @@ test("an isActive that always returns true behaves like no isActive at all", asy
async (threadId) => {
saved.push(threadId);
},
- { intervalMs: INTERVAL, timers: clock.timers, isActive: () => true },
+ {
+ intervalMs: INTERVAL,
+ timers: clock.timers,
+ isActive: () => true,
+ maxDurationMs: 20 * INTERVAL,
+ },
);
scheduler.start("thread-a");
@@ -134,6 +167,40 @@ test("an isActive that always returns true behaves like no isActive at all", asy
scheduler.stop("thread-a");
});
+test("the staleness bound is generous enough for a long legitimate run", () => {
+ // Thirty minutes, held at the follow deadline. Tripping it costs only the periodic
+ // partial saves, never the run's own writes, so the bound is set to outlast any answer
+ // a user waits through, including a prefill the backend still allows 1200s for.
+ assert.equal(RUN_CHECKPOINT_MAX_DURATION_MS, 30 * 60_000);
+ assert.ok(
+ RUN_CHECKPOINT_MAX_DURATION_MS / RUN_CHECKPOINT_INTERVAL_MS >= 100,
+ "the cap must leave room for a hundred checkpoints before it fires",
+ );
+});
+
+test("a thread restarted after the bound gets a fresh window", async () => {
+ const clock = createFakeTimers();
+ let saves = 0;
+ const scheduler = createRunCheckpointScheduler(
+ async () => {
+ saves += 1;
+ },
+ { intervalMs: INTERVAL, timers: clock.timers, maxDurationMs: 3 * INTERVAL },
+ );
+
+ scheduler.start("thread-a");
+ for (let i = 0; i < 6; i += 1) {
+ await clock.advance(INTERVAL);
+ }
+ const afterFirstRun = saves;
+ assert.equal(clock.pending(), 0, "the first window closed");
+
+ scheduler.start("thread-a");
+ await clock.advance(INTERVAL);
+ assert.equal(saves, afterFirstRun + 1, "the next run checkpoints again");
+ scheduler.stop("thread-a");
+});
+
test("an empty options object still uses the production interval", async () => {
const clock = createFakeTimers();
let saves = 0;
diff --git a/studio/frontend/tests/generation-recovery-own-run.test.ts b/studio/frontend/tests/generation-recovery-own-run.test.ts
index 8914d629658..878dd976e5f 100644
--- a/studio/frontend/tests/generation-recovery-own-run.test.ts
+++ b/studio/frontend/tests/generation-recovery-own-run.test.ts
@@ -80,7 +80,8 @@ test("the adapter claims the run BEFORE admission, not after the response", () =
// startup. The run id is the client's own (`cancelId` is passed as `runId`), so there is no
// reason to wait for the server to hand it back.
const adapter = read("../src/features/chat/api/chat-adapter.ts");
- const claim = adapter.indexOf("claimLiveGenerationRun(cancelId)");
+ // Matched without the closing paren: the call carries an options object and wraps.
+ const claim = adapter.indexOf("claimLiveGenerationRun(cancelId, resolvedThreadId!,");
const admission = adapter.indexOf("generationRun = await createChatGenerationRunUntilAbort(");
assert.ok(claim > 0, "nothing claims the run before admission");
@@ -89,6 +90,13 @@ test("the adapter claims the run BEFORE admission, not after the response", () =
claim < admission,
"the claim must precede the create POST, or the round trip is an open window",
);
+ // Provisional, so it owns recovery without marking the thread bounded: the await below
+ // can outlast the checkpoint cap, and a capped thread leaves the fallback stream with no
+ // persistence at all.
+ assert.ok(
+ adapter.slice(claim, admission).includes("provisional: true"),
+ "the pre-admission claim must not make the thread bounded",
+ );
// And the pre-admission id has to be released too, or a failed admission strands it.
assert.ok(
adapter.includes("releaseLiveGenerationRun(cancelId)"),
@@ -100,7 +108,7 @@ test("the adapter claims the run and releases it in a finally", () => {
const adapter = read("../src/features/chat/api/chat-adapter.ts");
assert.ok(
- adapter.includes("claimLiveGenerationRun(generationRunId)"),
+ adapter.includes("claimLiveGenerationRun(generationRunId, resolvedThreadId!)"),
"nothing claims the run, so the guard above can never fire",
);
// The release has to be inside a finally. Without that, an aborted or failed stream leaves
diff --git a/studio/frontend/tests/stuck-generation-run.test.ts b/studio/frontend/tests/stuck-generation-run.test.ts
new file mode 100644
index 00000000000..8c2c1e24d1b
--- /dev/null
+++ b/studio/frontend/tests/stuck-generation-run.test.ts
@@ -0,0 +1,898 @@
+// 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 durable run that never reaches a terminal status used to wedge the whole tab: the
+// reply stayed "running", which unmounts the composer's Send button, the checkpoint
+// schedule kept four requests moving every eight seconds, the follower reconnected
+// forever, and every stop path reported nothing to stop. Two full app reloads changed
+// none of it, because each one rebuilt the running status straight back out of the
+// persisted metadata. These are the frontend halves of that: nothing may derive "still
+// generating" from storage alone, and no loop may run without a bound.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { register } from "node:module";
+import test, { afterEach } from "node:test";
+import { fileURLToPath } from "node:url";
+
+import type { ChatGenerationRun } from "../src/features/chat/api/chat-generation-api.ts";
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+register("./helpers/settings-api-resolver.mjs", import.meta.url);
+registerBundlerResolver();
+installLocalStorageFake();
+
+const read = (relative: string): string =>
+ readFileSync(fileURLToPath(new URL(relative, import.meta.url)), "utf8");
+
+const originalFetch = globalThis.fetch;
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
+
+const {
+ generationIsCorroboratedLive,
+ isServerActiveGenerationRun,
+ loadGenerationOverlaySnapshot,
+ resetServerActiveGenerationRuns,
+ markServerActiveGenerationRunsUnknown,
+ forgetServerActiveGenerationRun,
+ threadHasDurableGenerationRun,
+ claimLiveGenerationRun,
+ releaseLiveGenerationRun,
+ generationNeedsRecovery,
+ serverHasAnsweredActiveRuns,
+ syncServerActiveGenerationRuns,
+} = await import("../src/features/chat/utils/chat-generation-recovery.ts");
+
+const { CHAT_GENERATION_STALL_TIMEOUT_MS, followChatGenerationRun } =
+ await import("../src/features/chat/api/chat-generation-api.ts");
+
+const run = (
+ status: ChatGenerationRun["status"],
+ seq: number,
+): ChatGenerationRun => ({
+ id: "run-1",
+ threadId: "thread-1",
+ userMessageId: "user-1",
+ assistantMessageId: "assistant-1",
+ requestHash: "hash",
+ requestPayload: { model: "local", messages: [], stream: true, max_tokens: 8 },
+ status,
+ cancelRequested: false,
+ lastEventSeq: seq,
+ finishReason: null,
+ error: null,
+ createdAt: 1,
+ updatedAt: seq + 1,
+ startedAt: 1,
+ completedAt: null,
+});
+
+// A. the corroboration gate
+
+test("before the server has answered, a live reply is not demoted", () => {
+ // First load with the backend briefly unreachable: there is no previous answer to
+ // leave standing, so an empty map must read as "never asked", not "nothing is
+ // running". Demoting here would mark a live generation interrupted.
+ resetServerActiveGenerationRuns();
+ assert.equal(serverHasAnsweredActiveRuns("thread-1"), false);
+ assert.equal(
+ generationIsCorroboratedLive(
+ { generationRunId: "run-unknown", generationStatus: "running" },
+ "thread-1",
+ ),
+ true,
+ "silence from the server is not a report that the run is dead",
+ );
+ // One successful read, and the gate becomes authoritative for THAT thread.
+ syncServerActiveGenerationRuns("thread-1", []);
+ assert.equal(serverHasAnsweredActiveRuns("thread-1"), true);
+ assert.equal(
+ generationIsCorroboratedLive(
+ { generationRunId: "run-unknown", generationStatus: "running" },
+ "thread-1",
+ ),
+ false,
+ );
+});
+
+test("one thread's successful read does not make another thread's failed read authoritative", () => {
+ // A answers, B's active-run request fails while its history succeeds. With a single
+ // process-wide flag, B's genuinely active reply was restored as interrupted.
+ resetServerActiveGenerationRuns();
+ syncServerActiveGenerationRuns("thread-A", []);
+ assert.equal(serverHasAnsweredActiveRuns("thread-A"), true);
+ assert.equal(serverHasAnsweredActiveRuns("thread-B"), false);
+ assert.equal(
+ generationIsCorroboratedLive(
+ { generationRunId: "run-B", generationStatus: "running" },
+ "thread-B",
+ ),
+ true,
+ "B has no answer of its own yet, so its reply must not be demoted",
+ );
+});
+
+test("persisted running metadata is not on its own evidence of a live run", () => {
+ syncServerActiveGenerationRuns("thread-1", []);
+ assert.equal(
+ generationIsCorroboratedLive(
+ {
+ generationRunId: "run-1",
+ generationStatus: "running",
+ generationSettled: false,
+ },
+ "thread-1",
+ ),
+ false,
+ "a stuck run says 'running' in storage for good; only the server may confirm it",
+ );
+});
+
+test("the server's active list corroborates a run, and a later list retracts it", () => {
+ syncServerActiveGenerationRuns("thread-1", ["run-1"]);
+ assert.equal(isServerActiveGenerationRun("run-1"), true);
+ assert.equal(
+ generationIsCorroboratedLive({ generationRunId: "run-1" }),
+ true,
+ );
+
+ syncServerActiveGenerationRuns("thread-1", []);
+ assert.equal(
+ isServerActiveGenerationRun("run-1"),
+ false,
+ "the thread's next load is the whole truth about that thread's runs",
+ );
+});
+
+test("one thread's active list does not retract another thread's runs", () => {
+ syncServerActiveGenerationRuns("thread-1", ["run-1"]);
+ syncServerActiveGenerationRuns("thread-2", ["run-2"]);
+ syncServerActiveGenerationRuns("thread-2", []);
+ assert.equal(isServerActiveGenerationRun("run-1"), true);
+ assert.equal(isServerActiveGenerationRun("run-2"), false);
+ syncServerActiveGenerationRuns("thread-1", []);
+});
+
+test("a message with no run id is never corroborated", () => {
+ assert.equal(generationIsCorroboratedLive({}), false);
+ assert.equal(generationIsCorroboratedLive({ generationRunId: 7 }), false);
+});
+
+test("a failed active-run read is reported as unknown, not as an empty list", async () => {
+ const failed = await loadGenerationOverlaySnapshot(
+ "thread-1",
+ () => Promise.reject(new Error("offline")),
+ () => Promise.resolve([{ id: "assistant-1" }]),
+ );
+ assert.deepEqual(failed.activeRuns, []);
+ assert.equal(
+ failed.activeRunsLoaded,
+ false,
+ "an unreachable backend must not be read as 'nothing is running'",
+ );
+
+ const loaded = await loadGenerationOverlaySnapshot(
+ "thread-1",
+ () => Promise.resolve([{ id: "run-1" }]),
+ () => Promise.resolve([{ id: "assistant-1" }]),
+ );
+ assert.equal(loaded.activeRunsLoaded, true);
+});
+
+test("the reload path gates the running status on corroboration", () => {
+ // Source-pinned: toThreadMessage needs a MessageRecord and the module's whole import
+ // graph, so the rule is asserted where it sits. Losing the call restores the wedge
+ // while every behavioural test stays green.
+ const provider = read("../src/features/chat/runtime-provider.tsx");
+ const gate = provider.indexOf("generationIsCorroboratedLive(custom, m.threadId)");
+ assert.ok(gate > 0, "toThreadMessage no longer asks whether the run is live");
+ assert.match(
+ provider,
+ /needsGenerationRecovery\s*=\s*generationUnsettled \|\|\s*\(generationUnfinished &&\s*generationIsCorroboratedLive\(custom, m\.threadId\)\)/,
+ "an unfinished run needs corroboration; a completed-but-unsettled one must not, "
+ + "because /chat-runs/active never lists a terminal run and its tail would be lost",
+ );
+ assert.match(
+ provider,
+ /incomplete: \{ reason: "interrupted" as const \}/,
+ "an uncorroborated partial must be restored as interrupted, not as complete",
+ );
+ assert.match(
+ provider,
+ /activeGenerationRuns\.filter\(\s*\(run\) => !isTerminalChatGenerationRun\(run\),\s*\)/,
+ "history.load must stamp generationSettled:false only for still-live runs",
+ );
+});
+
+test("the interrupted restore keeps the partial body untouched", () => {
+ const provider = read("../src/features/chat/runtime-provider.tsx");
+ // The only content assignment in toThreadMessage is the clone of the stored parts.
+ // Nothing between the gate and the return may drop or truncate it.
+ const start = provider.indexOf("function toThreadMessage(");
+ const body = provider.slice(start, provider.indexOf("\n}\n", start));
+ assert.ok(start > 0);
+ assert.match(body, /content: content as Extract</);
+ assert.equal(
+ /content:\s*\[\]/.test(body),
+ false,
+ "restoring an interrupted reply must never empty its content",
+ );
+});
+
+const stalledStreamFetch = (): typeof fetch =>
+ (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ if (url.includes("/events")) {
+ const body = new ReadableStream({
+ start(controller) {
+ init?.signal?.addEventListener("abort", () => {
+ controller.error(new Error("aborted"));
+ });
+ },
+ });
+ return new Response(body, {
+ status: 200,
+ headers: { "content-type": "text/event-stream" },
+ });
+ }
+ return new Response(JSON.stringify(run("running", 0)), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ }) as typeof fetch;
+
+test("the follower throws on its own deadline instead of returning silently", async () => {
+ // The live durable stream only throws for failed/cancelled. A silent return on our own
+ // deadline let a still-running run be finalized as a complete assistant reply while the
+ // backend kept generating with no follower.
+ globalThis.fetch = stalledStreamFetch();
+ await assert.rejects(
+ async () => {
+ for await (const _update of followChatGenerationRun("run-1", {
+ initialRun: run("running", 0),
+ replayFrom: 0,
+ stallTimeoutMs: 40,
+ })) {
+ // drain
+ }
+ },
+ (error: unknown) =>
+ error instanceof Error && error.name === "ChatGenerationStalledError",
+ "a deadline must surface as a stall, not as a clean end of stream",
+ );
+});
+
+test("a caller Stop still ends the follow cleanly", async () => {
+ // Only OUR deadline is a failure. The user pressing Stop stays a clean return, so a
+ // deliberate cancel is never reported to the user as an interrupted reply.
+ globalThis.fetch = stalledStreamFetch();
+ const controller = new AbortController();
+ globalThis.setTimeout(() => controller.abort(), 30);
+ for await (const _update of followChatGenerationRun("run-1", {
+ initialRun: run("running", 0),
+ replayFrom: 0,
+ signal: controller.signal,
+ stallTimeoutMs: 60_000,
+ })) {
+ // drain
+ }
+});
+
+// B. the follower's deadline
+
+test("the follower gives up on a run that makes no progress", async () => {
+ // The stream stays open and sends nothing, which is the shape a stuck durable run
+ // presents. The stub honours the abort signal exactly as fetch does, because that is
+ // the plumbing the deadline relies on to unblock a parked reader.
+ let opened = 0;
+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ if (url.includes("/events")) {
+ opened += 1;
+ const body = new ReadableStream({
+ start(controller) {
+ init?.signal?.addEventListener("abort", () => {
+ controller.error(new Error("aborted"));
+ });
+ },
+ });
+ return new Response(body, {
+ status: 200,
+ headers: { "content-type": "text/event-stream" },
+ });
+ }
+ return new Response(JSON.stringify(run("running", 0)), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ }) as typeof fetch;
+
+ const updates: string[] = [];
+ const started = Date.now();
+ await assert.rejects(async () => {
+ for await (const update of followChatGenerationRun("run-1", {
+ initialRun: run("running", 0),
+ replayFrom: 0,
+ stallTimeoutMs: 40,
+ })) {
+ updates.push(update.source);
+ }
+ }, /made no progress/);
+ assert.ok(
+ Date.now() - started < 5_000,
+ "the follow must end on its own rather than reconnect forever",
+ );
+ assert.deepEqual(updates, ["snapshot"], "no progress was ever made");
+ assert.ok(opened >= 1, "the follower did open the event stream");
+});
+
+test("progress rearms the deadline instead of ending the follow", async () => {
+ const frames = [1, 2, 3];
+ let follows = 0;
+ globalThis.fetch = (async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url.includes("/events")) {
+ const seq = frames[follows] ?? 0;
+ follows += 1;
+ const terminal = follows >= frames.length;
+ const encoder = new TextEncoder();
+ const snapshot = terminal ? run("completed", seq) : undefined;
+ const body = new ReadableStream({
+ async start(controller) {
+ // Each stream also pays the reconnect backoff before it, so the run lasts
+ // longer than the deadline in total, but never goes that long without progress.
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ controller.enqueue(
+ encoder.encode(
+ `data: ${JSON.stringify({
+ seq,
+ type: terminal ? "run.completed" : "chunk",
+ payload: { choices: [{ delta: { content: "x" } }] },
+ createdAt: seq,
+ ...(snapshot ? { run: snapshot } : {}),
+ })}\n\n`,
+ ),
+ );
+ controller.close();
+ },
+ });
+ return new Response(body, {
+ status: 200,
+ headers: { "content-type": "text/event-stream" },
+ });
+ }
+ return new Response(
+ JSON.stringify(
+ follows >= frames.length
+ ? run("completed", 3)
+ : run("running", follows),
+ ),
+ { status: 200, headers: { "content-type": "application/json" } },
+ );
+ }) as typeof fetch;
+
+ const seen: number[] = [];
+ for await (const update of followChatGenerationRun("run-1", {
+ initialRun: run("running", 0),
+ replayFrom: 0,
+ stallTimeoutMs: 1_500,
+ })) {
+ if (update.event) seen.push(update.event.seq);
+ }
+ assert.deepEqual(
+ seen,
+ [1, 2, 3],
+ "a run that keeps producing must not be cut off by the deadline",
+ );
+});
+
+test("the default deadline outlasts any reasonable generation", () => {
+ // The client has to be the more patient of the two. A prefill emits no events while it
+ // runs, the backend allows 1200s for a first token, and the lease sweeper needs another
+ // interval to settle a genuinely dead run. A deadline under roughly 21 minutes would
+ // report "interrupted" over a generation the server is still working on.
+ assert.equal(CHAT_GENERATION_STALL_TIMEOUT_MS, 30 * 60_000);
+ assert.ok(
+ CHAT_GENERATION_STALL_TIMEOUT_MS > 1_200_000 + 60_000,
+ "the follow deadline must outlast the backend first-token budget plus a sweep",
+ );
+});
+
+// C. the stop path after a reload
+
+test("stopChatThread falls back to the server when the registries are empty", () => {
+ const api = read("../src/features/chat/utils/stop-chat-thread.ts");
+ assert.match(
+ api,
+ /getActiveChatGenerationRuns/,
+ "a reloaded tab has no local handle; the server's list is the only one left",
+ );
+ assert.match(api, /cancelChatGenerationRun\(run\.id\)/);
+ const earlyReturn = api.indexOf("return false");
+ const fallback = api.indexOf("stopServerRunsForThread(threadId);");
+ assert.ok(fallback > 0, "the fallback is gone");
+ assert.ok(
+ earlyReturn < 0 || earlyReturn > 0,
+ "the only `return false` left is the missing-thread-id guard",
+ );
+ assert.equal(
+ api.split("return false").length - 1,
+ 1,
+ "an empty registry must no longer be a reason to give up",
+ );
+});
+
+test("a failed second active-run read leaves the thread unanswered", () => {
+ // Source-pinned for the same reason as the gate above. `missed` proves the first list
+ // predates the run, so keeping it AND recording it as an answer would restore a live
+ // reply as interrupted and re-enable a conflicting send.
+ const provider = read("../src/features/chat/runtime-provider.tsx");
+ assert.match(provider, /let answered = true;/);
+ assert.match(
+ provider,
+ /catch \{[^}]*answered = false;/s,
+ "a failed retry must not be promoted into an authoritative empty list",
+ );
+ assert.match(
+ provider,
+ /if \(answered\) \{\s*syncServerActiveGenerationRuns\(/,
+ "the sync must be gated on the read having actually answered",
+ );
+});
+
+test("the recovery follower settles when the follow throws a stall", () => {
+ const provider = read("../src/features/chat/runtime-provider.tsx");
+ assert.match(
+ provider,
+ /catch \(error\) \{\s*if \(!\(error instanceof ChatGenerationStalledError\)\) throw error;\s*followStalled = true;\s*\}/,
+ "the deadline throw must reach the settlement block, not the outer no-op catch",
+ );
+ assert.match(
+ provider,
+ /if \(followStalled \|\| generationNeedsRecovery\(currentMetadata\)\) \{/,
+ "a stall settles the reply even when the metadata already looks settled",
+ );
+ const start = provider.indexOf("for await (const update of followChatGenerationRun(");
+ const settle = provider.indexOf("generationNeedsRecovery(currentMetadata)", start);
+ const caught = provider.indexOf("instanceof ChatGenerationStalledError", start);
+ assert.ok(start > 0 && caught > start && settle > caught, "the catch must precede the settle");
+});
+
+test("a failed refresh retracts this thread's earlier answer", () => {
+ resetServerActiveGenerationRuns();
+ syncServerActiveGenerationRuns("t-1", ["run-a"]);
+ assert.equal(serverHasAnsweredActiveRuns("t-1"), true);
+ markServerActiveGenerationRunsUnknown("t-1");
+ assert.equal(
+ serverHasAnsweredActiveRuns("t-1"),
+ false,
+ "an answer is a point in time; a failed refresh must retract it",
+ );
+ // And a run another tab started since must keep the benefit of the doubt.
+ assert.equal(
+ generationIsCorroboratedLive({ generationRunId: "run-b" }, "t-1"),
+ true,
+ );
+});
+
+test("a terminal run stops making its thread durable", () => {
+ resetServerActiveGenerationRuns();
+ syncServerActiveGenerationRuns("t-2", ["run-c"]);
+ assert.equal(threadHasDurableGenerationRun("t-2"), true);
+ forgetServerActiveGenerationRun("run-c");
+ assert.equal(
+ threadHasDurableGenerationRun("t-2"),
+ false,
+ "a subscriber-owned stream started next must not inherit the durable cap",
+ );
+});
+
+test("a locally interrupted follower is not revived by the benefit of the doubt", () => {
+ resetServerActiveGenerationRuns();
+ const stalled = {
+ generationRunId: "run-d",
+ generationLocallyInterrupted: true,
+ };
+ // No answer for this thread, which is normally enough to keep a run running.
+ assert.equal(generationIsCorroboratedLive(stalled, "t-3"), false);
+ assert.equal(generationNeedsRecovery(stalled), false);
+ // The server still naming it live overrules the marker.
+ syncServerActiveGenerationRuns("t-3", ["run-d"]);
+ assert.equal(generationIsCorroboratedLive(stalled, "t-3"), true);
+});
+
+test("the marker is cleared when the server corroborates the run", () => {
+ const provider = read("../src/features/chat/runtime-provider.tsx");
+ assert.match(
+ provider,
+ /generationLocallyInterrupted: false,/,
+ "history.load must let the server overrule a follower that gave up locally",
+ );
+ assert.match(
+ provider,
+ /generationLocallyInterrupted: true,/,
+ "the stall settlement must stamp the marker",
+ );
+ assert.match(
+ provider,
+ /markServerActiveGenerationRunsUnknown\(remoteId\)/,
+ "a failed second read must retract this thread's answer",
+ );
+ assert.match(
+ provider,
+ /if \(isTerminalChatGenerationRun\(update\.run\)\) \{\s*\/\/[^]*?forgetServerActiveGenerationRun\(runId\)/,
+ "a terminal run must leave the server-active map",
+ );
+});
+
+test("a legacy fallback releases the durable claim at once", () => {
+ const adapter = read("../src/features/chat/api/chat-adapter.ts");
+ const fallback = adapter.indexOf('generationDecision = "legacy";\n //');
+ assert.ok(fallback > 0, "the legacy-fallback branch moved");
+ const release = adapter.indexOf("releaseLiveGenerationRun(cancelId);", fallback);
+ const nextClaim = adapter.indexOf("claimLiveGenerationRun(", fallback);
+ assert.ok(
+ release > 0 && (nextClaim === -1 || release < nextClaim),
+ "the pre-admission claim must go before the subscriber-owned stream starts",
+ );
+});
+
+test("the initial durable stream marks itself interrupted when it stalls", () => {
+ // The recovery follower is not the only one holding the deadline. The adapter runs its
+ // own follower for the first stream of a turn, and when THAT one gives up the persisted
+ // metadata still reads running and unsettled. Without the marker, generationNeedsRecovery
+ // stays true, the next reload attaches another follower, and the composer is blocked for
+ // another full deadline.
+ const adapter = read("../src/features/chat/api/chat-adapter.ts");
+ const stream = adapter.indexOf("const durableStream = async function* () {");
+ assert.ok(stream > 0, "the durable stream moved");
+ const caught = adapter.indexOf("instanceof ChatGenerationStalledError", stream);
+ assert.ok(caught > 0, "the adapter's own follower must catch the stall");
+ const marked = adapter.indexOf("generationStalled = true;", caught);
+ assert.ok(marked > 0, "catching the stall without recording it changes nothing");
+ // Recording it is only useful if it reaches the metadata that survives a reload.
+ const custom = adapter.indexOf("const generationCustom = ()");
+ assert.ok(custom > 0 && custom < stream, "the metadata builder moved");
+ const persisted = adapter.indexOf(
+ "generationLocallyInterrupted: generationStalled,",
+ custom,
+ );
+ assert.ok(
+ persisted > custom && persisted < stream,
+ "the stall marker must be persisted alongside generationSettled",
+ );
+ // The marker alone only stops the next reload reviving the run. Without an incomplete
+ // reason the final yield writes `incomplete: undefined`, assistant-ui reads the partial
+ // reply as finished, and there is no Continue until a reload rebuilds the reason.
+ const reason = adapter.indexOf('incompleteReason = "interrupted";', caught);
+ assert.ok(
+ reason > caught && reason < adapter.indexOf("if (generationStatus ===", caught),
+ "a stalled initial stream must settle as interrupted, not as completed",
+ );
+});
+
+test("a completed run overrides the local interruption marker", () => {
+ resetServerActiveGenerationRuns();
+ // The backend resumed and finished after the follower gave up. /chat-runs/active
+ // excludes completed runs, so it can never clear the marker for this one: honouring
+ // it here would leave the reply running forever with its event tail never imported.
+ const finished = {
+ generationRunId: "run-e",
+ generationStatus: "completed",
+ generationSettled: false,
+ generationLocallyInterrupted: true,
+ };
+ assert.equal(generationNeedsRecovery(finished), true);
+ assert.equal(generationIsCorroboratedLive(finished, "t-4"), true);
+ // Still non-terminal, so the marker still holds.
+ assert.equal(
+ generationNeedsRecovery({ ...finished, generationStatus: "running" }),
+ false,
+ );
+});
+
+test("a failed initial active-run read retracts the earlier answer too", () => {
+ const provider = read("../src/features/chat/runtime-provider.tsx");
+ assert.match(
+ provider,
+ /if \(!activeGenerationRunsLoaded\) \{[^]*?markServerActiveGenerationRunsUnknown\(remoteId\)/,
+ "the initial-read failure path must retract the stale answer, not only the retry",
+ );
+});
+
+test("the lease is renewed while the model is being prepared", () => {
+ const runs = read("../../backend/core/inference/chat_generation_runs.py");
+ assert.match(runs, /_renew_lease_while_preparing/);
+ assert.match(
+ runs,
+ /_PREPARE_RENEW_MAX_SECONDS = /,
+ "the renewal must be bounded, or a load that never returns is kept alive forever",
+ );
+ assert.match(
+ runs,
+ /def _renew_interval_seconds\(\)/,
+ "the cadence must derive from the configured lease, not a constant that can exceed it",
+ );
+ // The heartbeat has to span the lifecycle gate too: a run waiting on it is still
+ // queued and ages from created_at with nothing renewing it.
+ const guard = runs.indexOf("async with self._lease_heartbeat(run_id):");
+ const gate = runs.indexOf("await activity.start(cancel_event)", guard);
+ const produce = runs.indexOf("await produce_openai_chat_completions(", guard);
+ assert.ok(
+ guard > 0 && gate > guard && produce > gate,
+ "the heartbeat must open before the gate wait and still cover preparation",
+ );
+});
+test("retracting an answer also drops that thread's stale run mappings", () => {
+ resetServerActiveGenerationRuns();
+ syncServerActiveGenerationRuns("t-5", ["run-f"]);
+ const stalled = {
+ generationRunId: "run-f",
+ generationStatus: "running",
+ generationLocallyInterrupted: true,
+ };
+ // While the answer stands, the server's word wins and the message is live.
+ assert.equal(generationIsCorroboratedLive(stalled, "t-5"), true);
+ markServerActiveGenerationRunsUnknown("t-5");
+ // Once retracted it must not keep winning from the leftover mapping: that pairs a
+ // running message with generationNeedsRecovery=false, so nothing would ever settle it.
+ assert.equal(generationIsCorroboratedLive(stalled, "t-5"), false);
+ assert.equal(generationNeedsRecovery(stalled), false);
+ assert.equal(threadHasDurableGenerationRun("t-5"), false);
+});
+
+test("advancing keep-alive stamps hold the follower open through a long preparation", async () => {
+ // The stream stays open and sends only comments for the whole of a model load. Before
+ // this, the loop never advanced, so the snapshot poll that would have seen the lease
+ // move never ran, and a healthy run was reported interrupted at the deadline.
+ //
+ // The stamp is what makes them progress. This test used to send BARE keep-alives, which
+ // pinned the wrong rule: the server emits one every 15s for as long as the socket holds,
+ // so a follower that rearmed on arrival could never settle a wedged run. See the
+ // companion test below for that half.
+ const api = await import("../src/features/chat/api/chat-generation-api");
+ let push: ((chunk: Uint8Array) => void) | undefined;
+ let close: (() => void) | undefined;
+ const encoder = new TextEncoder();
+ const original = globalThis.fetch;
+ globalThis.fetch = (async (_url: string, init?: RequestInit) => {
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ push = (chunk) => controller.enqueue(chunk);
+ close = () => controller.close();
+ init?.signal?.addEventListener("abort", () =>
+ controller.error(new DOMException("aborted", "AbortError")),
+ );
+ },
+ });
+ return new Response(body, {
+ status: 200,
+ headers: { "content-type": "text/event-stream" },
+ });
+ }) as typeof fetch;
+
+ try {
+ const seen: string[] = [];
+ const run = { id: "r", status: "running", lastEventSeq: 0, updatedAt: 1 };
+ const follow = (async () => {
+ for await (const update of api.followChatGenerationRun("r", {
+ initialRun: run as never,
+ stallTimeoutMs: 200,
+ })) {
+ seen.push(update.source);
+ if (update.run.status !== "running") break;
+ }
+ })();
+ // Only comments, spaced so the deadline would have fired twice without them. The
+ // stamp advances, which is what a renewing lease looks like on the wire.
+ for (let i = 0; i < 4; i += 1) {
+ await new Promise((r) => setTimeout(r, 120));
+ push?.(encoder.encode(`: keep-alive ${1000 + i}\n\n`));
+ }
+ push?.(
+ encoder.encode(
+ `data: ${JSON.stringify({ seq: 1, type: "chunk", payload: {}, run: { ...run, status: "completed", lastEventSeq: 1 } })}\n\n`,
+ ),
+ );
+ close?.();
+ await follow;
+ assert.ok(seen.length > 0, "the follower must have survived to see the event");
+ } finally {
+ globalThis.fetch = original;
+ }
+});
+
+test("a run finished between the two reads never reaches the durable registry", () => {
+ // The registry sync runs BEFORE the overlay, so skipping only at the overlay left the
+ // thread reading as durable. In another tab nothing removes that mapping, and the next
+ // subscriber-owned stream on the thread would be capped and lose its tail.
+ const provider = read("../src/features/chat/runtime-provider.tsx");
+ const filter = provider.indexOf("terminalMessageRuns");
+ const sync = provider.indexOf("syncServerActiveGenerationRuns(", filter);
+ assert.ok(filter > 0, "the terminal-message filter is missing");
+ assert.ok(sync > filter, "the filter must run before the registry sync");
+ assert.match(
+ provider,
+ /activeGenerationRuns = activeGenerationRuns\.filter\(\s*\(run\) => !terminalMessageRuns\.has\(run\.assistantMessageId\),\s*\);/,
+ "the list itself must be filtered, so sync and overlay both see it",
+ );
+});
+
+
+test("a pre-admission claim does not make the thread bounded yet", () => {
+ resetServerActiveGenerationRuns();
+ // The claim is taken before the create POST so a recovery trigger during that await
+ // cannot start a second follower. It must not also cap the checkpoints: until the POST
+ // lands there is no server-side run, so those checkpoints are the only persistence, and
+ // createChatGenerationRun retries transient failures until aborted, so the await can
+ // outlast the 30 minute cap. A capped thread is dropped from the schedule for good.
+ claimLiveGenerationRun("run-1", "thread-1", { provisional: true });
+ assert.equal(threadHasDurableGenerationRun("thread-1"), false);
+
+ // Admission succeeded: the second, non-provisional claim confirms it.
+ claimLiveGenerationRun("run-1", "thread-1");
+ assert.equal(threadHasDurableGenerationRun("thread-1"), true);
+ releaseLiveGenerationRun("run-1");
+ assert.equal(threadHasDurableGenerationRun("thread-1"), false);
+});
+
+test("releasing a provisional claim clears it rather than leaving it bounded", () => {
+ resetServerActiveGenerationRuns();
+ // The legacy fallback path releases without ever admitting. A stale provisional entry
+ // would then make the NEXT claim of the same id read as unbounded.
+ claimLiveGenerationRun("run-2", "thread-2", { provisional: true });
+ releaseLiveGenerationRun("run-2");
+ claimLiveGenerationRun("run-2", "thread-2");
+ assert.equal(threadHasDurableGenerationRun("thread-2"), true);
+ releaseLiveGenerationRun("run-2");
+});
+
+
+test("a repeated keep-alive stamp does NOT hold the follower open", async () => {
+ // The other half of the rule above, and the case the whole frontend fallback exists for:
+ // a wedged producer with a healthy socket. The server keeps sending keep-alives, but the
+ // run's progress stamp is frozen, so the deadline must still fire.
+ const api = await import("../src/features/chat/api/chat-generation-api");
+ let push: ((chunk: Uint8Array) => void) | undefined;
+ const encoder = new TextEncoder();
+ const original = globalThis.fetch;
+ globalThis.fetch = (async (_url: string, init?: RequestInit) => {
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ push = (chunk) => controller.enqueue(chunk);
+ init?.signal?.addEventListener("abort", () =>
+ controller.error(new DOMException("aborted", "AbortError")),
+ );
+ },
+ });
+ return new Response(body, {
+ status: 200,
+ headers: { "content-type": "text/event-stream" },
+ });
+ }) as typeof fetch;
+
+ try {
+ const run = { id: "r", status: "running", lastEventSeq: 0, updatedAt: 1 };
+ let stalled = false;
+ const follow = (async () => {
+ try {
+ for await (const _u of api.followChatGenerationRun("r", {
+ initialRun: run as never,
+ stallTimeoutMs: 200,
+ })) {
+ // The run never progresses; only the deadline can end this.
+ }
+ } catch (error) {
+ stalled = error instanceof api.ChatGenerationStalledError;
+ }
+ })();
+ // The same stamp, forever, and STILL ARRIVING while we wait. Stopping the pushes
+ // would make this vacuous: the deadline fires on its own once the stream goes quiet,
+ // so a version that rearmed on every keep-alive would pass too. The pump only stops
+ // when the deadline aborts the stream and closes the controller.
+ const pump = setInterval(() => {
+ try {
+ push?.(encoder.encode(": keep-alive 1\n\n"));
+ } catch {
+ clearInterval(pump);
+ }
+ }, 40);
+ const timedOut = Symbol("timed out");
+ const outcome = await Promise.race([
+ follow.then(() => "settled"),
+ new Promise((r) => setTimeout(() => r(timedOut), 3_000)),
+ ]);
+ clearInterval(pump);
+ assert.notEqual(
+ outcome,
+ timedOut,
+ "the follower never gave up while keep-alives kept arriving",
+ );
+ assert.equal(stalled, true, "a frozen stamp must not keep the follower alive");
+ } finally {
+ globalThis.fetch = original;
+ }
+});
+
+test("a frozen stamp does not rearm across SSE reconnects", async () => {
+ // The stream generator is re-invoked on every reconnect, so a per-connection memory of
+ // the last stamp treats the FIRST keep-alive of each connection as progress. Behind a
+ // flapping proxy that reconnects more often than the deadline, a wedged run would rearm
+ // the follower forever. The memory therefore lives in the follower, not the stream.
+ const api = await import("../src/features/chat/api/chat-generation-api");
+ const encoder = new TextEncoder();
+ const original = globalThis.fetch;
+ let connections = 0;
+ globalThis.fetch = (async (url: string, init?: RequestInit) => {
+ if (String(url).includes("/events")) {
+ connections += 1;
+ // Each connection: one keep-alive carrying the SAME frozen stamp, then EOF, which
+ // sends the follower around the reconnect loop again.
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(encoder.encode(": keep-alive 7\n\n"));
+ controller.close();
+ },
+ });
+ init?.signal?.addEventListener("abort", () => {});
+ return new Response(body, {
+ status: 200,
+ headers: { "content-type": "text/event-stream" },
+ });
+ }
+ // The snapshot re-read between reconnects: still running, still frozen.
+ return new Response(
+ JSON.stringify({ id: "r", status: "running", lastEventSeq: 0, updatedAt: 7 }),
+ { status: 200, headers: { "content-type": "application/json" } },
+ );
+ }) as typeof fetch;
+
+ try {
+ let stalled = false;
+ const follow = (async () => {
+ try {
+ for await (const _u of api.followChatGenerationRun("r", {
+ initialRun: { id: "r", status: "running", lastEventSeq: 0, updatedAt: 7 } as never,
+ // Long enough for the 500ms-and-doubling reconnect backoff to produce several
+ // connections inside one deadline, which is the situation being tested.
+ stallTimeoutMs: 2_500,
+ })) {
+ // Never terminal; only the deadline can end this.
+ }
+ } catch (error) {
+ stalled = error instanceof api.ChatGenerationStalledError;
+ }
+ })();
+ const timedOut = Symbol("timed out");
+ const outcome = await Promise.race([
+ follow.then(() => "settled"),
+ new Promise((r) => setTimeout(() => r(timedOut), 20_000)),
+ ]);
+ assert.notEqual(outcome, timedOut, "reconnects kept the follower alive indefinitely");
+ assert.equal(stalled, true, "a frozen stamp must not rearm on reconnect");
+ assert.ok(connections > 1, `expected several reconnects, saw ${connections}`);
+ } finally {
+ globalThis.fetch = original;
+ }
+});
+
+test("a stalled follower fences the server run before offering Continue", () => {
+ // Settling only in this tab leaves the row queued/running/cancelling, and create_run
+ // refuses a thread that already has an active generation, so Continue and the next
+ // message would both 409 against a reply the UI had just declared finished.
+ const provider = read("../src/features/chat/runtime-provider.tsx");
+ const settle = provider.indexOf("followStalled || generationNeedsRecovery(currentMetadata)");
+ assert.ok(settle > 0, "the stall settle branch moved");
+ const commit = provider.indexOf("incomplete: { reason: \"interrupted\" as const }", settle);
+ assert.ok(commit > settle, "the interrupted commit moved");
+ const cancel = provider.indexOf("serverCancel();", settle);
+ assert.ok(
+ cancel > settle && cancel < commit,
+ "the run must be fenced server-side BEFORE the reply is presented as resumable",
+ );
+});