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: harden background consumer loops and streaming paths against silent UI freezes (#6653)

Daniel Han2ef394137aef
diff --git a/studio/backend/auth/storage.py b/studio/backend/auth/storage.py
index 1f153699d79..a0da2b2096e 100644
--- a/studio/backend/auth/storage.py
+++ b/studio/backend/auth/storage.py
@@ -110,6 +110,17 @@ def get_connection() -> sqlite3.Connection:
except OSError:
pass
conn.row_factory = sqlite3.Row
+ # WAL lets token reads run concurrently with refresh-token writes;
+ # busy_timeout bounds lock waits. Matches the other Studio SQLite stores.
+ # Set busy_timeout first: switching journal_mode needs a lock, so if a
+ # refresh-token write already holds one, journal_mode=WAL raises SQLITE_BUSY;
+ # with busy_timeout already in effect it waits instead of failing and leaving
+ # this connection on SQLite's default zero lock wait.
+ try:
+ conn.execute("PRAGMA busy_timeout=5000")
+ conn.execute("PRAGMA journal_mode=WAL")
+ except sqlite3.Error:
+ pass
conn.execute(
"""
CREATE TABLE IF NOT EXISTS auth_user (
diff --git a/studio/backend/core/data_recipe/jobs/manager.py b/studio/backend/core/data_recipe/jobs/manager.py
index c238c250bdc..0e0044702e1 100644
--- a/studio/backend/core/data_recipe/jobs/manager.py
+++ b/studio/backend/core/data_recipe/jobs/manager.py
@@ -28,6 +28,9 @@ from .constants import (
from .parse import apply_update, coerce_event, parse_log_message
from .types import Job
from .worker import run_job_process
+from loggers import get_logger
+
+logger = get_logger(__name__)
_CTX = mp.get_context("spawn")
@@ -445,54 +448,86 @@ class JobManager:
events.append(coerce_event(q.get_nowait()))
except queue.Empty:
return events
- except (EOFError, OSError, ValueError):
+ except Exception:
+ # Return what we have so the run still finalizes rather than wedging "active".
+ logger.exception(
+ "Data-recipe job pump: queue drain failed; finalizing with drained events"
+ )
return events
+ def _safe_handle_event(self, job: Job, event: dict) -> None:
+ """Apply one event, swallowing any handler error so the pump can't die."""
+ try:
+ self._handle_event(job, event)
+ except Exception:
+ etype = event.get("type") if isinstance(event, dict) else type(event).__name__
+ logger.exception("Data-recipe job pump: failed to handle %s event; skipping", etype)
+
def _pump_loop(self) -> None:
- """Background thread: consumes worker events + updates job snapshot."""
+ """Background thread: consume worker events and update the job snapshot.
+
+ Guarded so no single event can end the loop; it is the sole writer of the
+ snapshot the UI polls, so its death would freeze status/SSE.
+ """
while True:
snap = self._snapshot()
if snap is None:
return
job, proc, mp_q = snap
- event = self._read_queue_with_timeout(mp_q, timeout_sec = 0.25)
+ try:
+ event = self._read_queue_with_timeout(mp_q, timeout_sec = 0.25)
+ except Exception:
+ # If a read keeps raising after the worker died, finalize instead
+ # of spinning forever; only retry while the worker is still alive.
+ logger.exception("Data-recipe job pump: queue read failed; continuing")
+ if proc.is_alive():
+ time.sleep(0.1)
+ continue
+ event = None
+
if event is not None:
- self._handle_event(job, event)
+ self._safe_handle_event(job, event)
continue
if proc.is_alive():
continue
- for e in self._drain_queue(mp_q):
- self._handle_event(job, e)
-
- retired_job: Job | None = None
- with self._lock:
- if self._job and self._job.status in {
- "pending",
- "active",
- "cancelling",
- }:
- if self._job.status == "cancelling":
- self._job.status = "cancelled"
- else:
- self._job.status = "error"
- self._job.error = self._job.error or "process exited"
- self._job.finished_at = time.time()
- event_type = (
- EVENT_JOB_CANCELLED if self._job.status == "cancelled" else EVENT_JOB_ERROR
- )
- self._emit(
- {
- "type": event_type,
- "ts": time.time(),
- "job_id": self._job.job_id,
- }
- )
- retired_job = self._job
- if retired_job is not None:
- self._retire_workflow_key(retired_job)
+ # Worker exited: drain + finalize, guarded so an error can't strand the run "active".
+ try:
+ for e in self._drain_queue(mp_q):
+ self._safe_handle_event(job, e)
+
+ retired_job: Job | None = None
+ with self._lock:
+ if self._job and self._job.status in {
+ "pending",
+ "active",
+ "cancelling",
+ }:
+ if self._job.status == "cancelling":
+ self._job.status = "cancelled"
+ else:
+ self._job.status = "error"
+ self._job.error = self._job.error or "process exited"
+ self._job.finished_at = time.time()
+ event_type = (
+ EVENT_JOB_CANCELLED
+ if self._job.status == "cancelled"
+ else EVENT_JOB_ERROR
+ )
+ self._emit(
+ {
+ "type": event_type,
+ "ts": time.time(),
+ "job_id": self._job.job_id,
+ }
+ )
+ retired_job = self._job
+ if retired_job is not None:
+ self._retire_workflow_key(retired_job)
+ except Exception:
+ logger.exception("Data-recipe job pump: finalization after worker exit failed")
return
def _handle_event(self, job: Job, event: dict) -> None:
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index cae001c34d7..20312e067c0 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -771,11 +771,9 @@ class ExternalProviderClient:
self.base_url = self.base_url[: -len("/openai")]
self.api_key = api_key
self._timeout = httpx.Timeout(timeout, connect = 10.0)
- # Disable read timeout on SSE streams: reasoning-heavy models pause
- # tens of seconds between bytes while thinking, and httpx's read
- # timeout is the per-byte gap, not wall clock. connect/write bounds
- # still surface real network failures.
- self._stream_timeout = httpx.Timeout(timeout, connect = 10.0, read = None)
+ # Generous per-byte read timeout: reasoning models pause tens of seconds
+ # between bytes, but a dead upstream must eventually error, not hang forever.
+ self._stream_timeout = httpx.Timeout(timeout, connect = 10.0, read = 300.0)
def _auth_headers(self) -> dict[str, str]:
"""Build authentication headers using the provider's registry config."""
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 152a3f19b2f..255fc4140f4 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -3147,9 +3147,10 @@ class LlamaCppBackend:
except (ValueError, OSError):
# Log file closed under us; tee silently.
pass
- except (ValueError, OSError):
- # Pipe closed -- process terminating.
- pass
+ except Exception:
+ # Never let the drain thread die: a full stdout pipe can deadlock
+ # llama-server (Windows). Pipe-closed on exit is the common case.
+ logger.debug("llama-server stdout drain stopped", exc_info = True)
# GGUF KV type sizes for fast skipping
_GGUF_TYPE_SIZE = {
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index c980dbde2d1..5dbd5fb4796 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -534,29 +534,34 @@ class InferenceOrchestrator:
except (EOFError, OSError, ValueError):
break
- rid = resp.get("request_id")
- rtype = resp.get("type", "")
-
- # Status messages — log and skip
- if rtype == "status":
- logger.info("Subprocess status: %s", resp.get("message", ""))
- continue
+ # Sole consumer of the response queue; if it died every in-flight
+ # stream would hang, so never let routing kill the dispatcher.
+ try:
+ rid = resp.get("request_id")
+ rtype = resp.get("type", "")
- # Route to mailbox if a matching request_id exists
- if rid:
- with self._mailbox_lock:
- mbox = self._mailboxes.get(rid)
- if mbox is not None:
- mbox.put(resp)
+ # Status messages: log and skip
+ if rtype == "status":
+ logger.info("Subprocess status: %s", resp.get("message", ""))
continue
- # No matching mailbox (a _gen_lock reader or orphaned). Can't
- # un-get from mp.Queue, so just log. (status was handled above.)
- logger.debug(
- "Dispatcher: no mailbox for request_id=%s type=%s, dropping",
- rid,
- rtype,
- )
+ # Route to mailbox if a matching request_id exists
+ if rid:
+ with self._mailbox_lock:
+ mbox = self._mailboxes.get(rid)
+ if mbox is not None:
+ mbox.put(resp)
+ continue
+
+ # No matching mailbox; can't un-get from mp.Queue, so just log.
+ logger.debug(
+ "Dispatcher: no mailbox for request_id=%s type=%s, dropping",
+ rid,
+ rtype,
+ )
+ except Exception:
+ logger.exception("Inference dispatcher: failed to route a response; continuing")
+ continue
def _generate_dispatched(
self,
diff --git a/studio/backend/core/rag/ingestion.py b/studio/backend/core/rag/ingestion.py
index c0c9a9f6563..77bbdc92f52 100644
--- a/studio/backend/core/rag/ingestion.py
+++ b/studio/backend/core/rag/ingestion.py
@@ -26,6 +26,11 @@ _jobs_lock = threading.Lock()
_EMBED_BATCH = 64 # bounds peak memory
+# Poll with a timeout so the generator wakes periodically to detect a gone
+# client or a terminal job whose worker died without the None sentinel.
+_SSE_POLL_SECONDS = 1.0
+_TERMINAL_JOB_STATUSES = {"completed", "failed"}
+
def _sha256_file(path: str) -> str:
h = hashlib.sha256()
@@ -178,6 +183,9 @@ def start_ingestion(
if ext not in config.UPLOAD_EXTS:
raise ValueError(f"unsupported file type: {ext}")
+ # Reclaim queues for finished jobs so the registry stays bounded.
+ _reap_finished_jobs()
+
sha = _sha256_file(stored_path)
conn = rag_db.get_connection()
try:
@@ -248,19 +256,86 @@ def _new_job(
return job_id
+def _reap_finished_jobs() -> None:
+ """Drop per-job queues whose DB row already reached a terminal status.
+
+ Otherwise removed only by ``job_events`` after the ``None`` sentinel, so a
+ caller that polls ``/jobs/{id}`` instead of streaming would grow ``_jobs``
+ forever. Safe while streaming: ``job_events`` holds its queue reference.
+ """
+ with _jobs_lock:
+ job_ids = list(_jobs.keys())
+ for jid in job_ids:
+ row = get_job_status(jid)
+ if row is not None and row.get("status") in _TERMINAL_JOB_STATUSES:
+ with _jobs_lock:
+ _jobs.pop(jid, None)
+
+
def job_events(job_id: str):
- """Yield job events for SSE; ends when the worker signals completion."""
+ """Yield job events for SSE; ends when the worker signals completion.
+
+ Timed ``get`` so the generator can't block forever: it wakes to heartbeat,
+ to notice a disconnected client, and to stop on a terminal DB status (a hard
+ worker death that skipped the ``None`` sentinel). Drops the queue only on a
+ terminal exit, never on an early client disconnect.
+
+ It deliberately does *not* end on idle alone: a long silent stage (e.g.
+ embedding a large doc) is not a failure, and ending there would send
+ ``[DONE]`` with the row still pending, which the client treats as completion.
+ The stream ends only on a terminal status, the ``None`` sentinel, or disconnect.
+ """
with _jobs_lock:
q = _jobs.get(job_id)
if q is None:
return
- while True:
- event = q.get()
- if event is None:
- break
- yield event
- with _jobs_lock:
- _jobs.pop(job_id, None)
+ terminal = False
+ try:
+ while True:
+ try:
+ event = q.get(timeout = _SSE_POLL_SECONDS)
+ except queue.Empty:
+ try:
+ row = get_job_status(job_id)
+ except Exception: # noqa: BLE001
+ # A transient status read (e.g. the DB momentarily locked) must
+ # not abort the stream: routes/rag.py would turn the raised
+ # exception into a terminal {type: error} frame and the UI would
+ # drop a document whose worker is still running. Heartbeat and
+ # retry on the next poll instead.
+ logger.warning(
+ "job_events status read failed for %s; continuing", job_id, exc_info = True
+ )
+ yield {"type": "heartbeat"}
+ continue
+ if row is None or row.get("status") in _TERMINAL_JOB_STATUSES:
+ # Worker finished (or row gone); stop and let the client reconcile via getJob.
+ terminal = True
+ break
+ yield {"type": "heartbeat"}
+ continue
+ if event is None:
+ terminal = True
+ break
+ yield event
+ finally:
+ # Drop the queue once nothing more will be emitted into it: either a
+ # terminal exit, or a disconnect after the job already finished (the UI
+ # stops on the terminal event, before [DONE], so terminal is still False
+ # here -- _run writes the terminal DB status before emitting it). Keep it
+ # only while the worker is still running, so an early disconnect can
+ # reconnect and resume its events.
+ if not terminal:
+ try:
+ row = get_job_status(job_id)
+ terminal = row is None or row.get("status") in _TERMINAL_JOB_STATUSES
+ except Exception: # noqa: BLE001
+ # Can't confirm terminality (transient DB error) -- keep the queue so
+ # a reconnect can resume rather than orphaning a live worker's events.
+ terminal = False
+ if terminal:
+ with _jobs_lock:
+ _jobs.pop(job_id, None)
def get_job_status(job_id: str) -> dict | None:
diff --git a/studio/backend/hub/services/download_lifecycle.py b/studio/backend/hub/services/download_lifecycle.py
index c2b99c0f187..44c39337fbd 100644
--- a/studio/backend/hub/services/download_lifecycle.py
+++ b/studio/backend/hub/services/download_lifecycle.py
@@ -314,25 +314,50 @@ def register_worker(
worker_token = hf_token
def _watch() -> None:
- finalize_worker_exit(
- registry,
- key,
- proc,
- hf_token = worker_token,
- label = label,
- log_prefix = log_prefix,
- logger = logger,
- repo_type = repo_type,
- repo_id = repo_id,
- transport = transport,
- )
- if registry.get_job(key).state in ("error", "cancelled"):
- download_registry.purge_empty_marker_dir(
- repo_type,
- repo_id,
- download_registry.variant_from_key(key),
+ try:
+ finalize_worker_exit(
+ registry,
+ key,
+ proc,
+ hf_token = worker_token,
+ label = label,
+ log_prefix = log_prefix,
+ logger = logger,
+ repo_type = repo_type,
+ repo_id = repo_id,
+ transport = transport,
)
- hf_cache_scan.invalidate_hf_cache_scans()
+ except Exception:
+ # finalize_worker_exit is the only thing that clears running/cancelling;
+ # if it raises, force a terminal state so claim() isn't blocked until restart.
+ logger.exception("download watcher crashed for %s", key)
+ # finalize may have raised before reaping the worker; terminate the
+ # still-registered Popen first, else the terminal set_job clears the
+ # repo guard and a live worker would race a retry on the same repo.
+ try:
+ kill_and_reap_process(proc, label = label, logger = logger)
+ except Exception:
+ logger.exception("failed to reap worker after watcher crash for %s", key)
+ try:
+ registry.drop_process(key, proc)
+ except Exception:
+ logger.exception("failed to drop worker after watcher crash for %s", key)
+ try:
+ registry.set_job(key, "error", "download watcher crashed")
+ except Exception:
+ logger.exception("failed to mark %s errored after watcher crash", key)
+ finally:
+ try:
+ if registry.get_job(key).state in ("error", "cancelled"):
+ download_registry.purge_empty_marker_dir(
+ repo_type,
+ repo_id,
+ download_registry.variant_from_key(key),
+ )
+ except Exception:
+ logger.exception("post-finalize marker cleanup failed for %s", key)
+ finally:
+ hf_cache_scan.invalidate_hf_cache_scans()
threading.Thread(target = _watch, name = watch_name, daemon = True).start()
return True
diff --git a/studio/backend/main.py b/studio/backend/main.py
index a8e81b68e68..731625ca740 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -487,6 +487,16 @@ async def lifespan(app: FastAPI):
import structlog
structlog.get_logger(__name__).warning("cleanup_orphaned_runs failed at startup: %s", exc)
+ # Same for RAG: fail ingestion jobs stranded mid-ingest by a crash.
+ try:
+ from storage.rag_db import reconcile_orphaned_ingestion_jobs
+ reconcile_orphaned_ingestion_jobs()
+ except Exception as exc:
+ import structlog
+ structlog.get_logger(__name__).warning(
+ "reconcile_orphaned_ingestion_jobs failed at startup: %s", exc
+ )
+
_start_helper_precache_if_enabled()
# Warm the RAG embedder so the first upload skips the cold load. Non-fatal.
diff --git a/studio/backend/routes/auth.py b/studio/backend/routes/auth.py
index d2b3bf94e91..92ecdbfb5b7 100644
--- a/studio/backend/routes/auth.py
+++ b/studio/backend/routes/auth.py
@@ -74,9 +74,81 @@ _LOGIN_WINDOW_SECONDS = 60.0
_LOGIN_MAX_FAILS = 5
_LOGIN_IP_MAX_FAILS = 30
_LOGIN_LOCKOUT_SECONDS = 60
-# Bucket-dict cap. On overflow, prune stale entries; if still full the failure
-# folds into the per-IP aggregate only.
+# Bucket-dict cap. On overflow, reclaim expired buckets; a new IP that still can't
+# fit falls back to a sharded overflow rather than evicting a hot bucket.
_LOGIN_MAX_BUCKETS = 4096
+# Last full stale-sweep time; rate-limits the O(n) sweep under a burst of new IPs.
+_LAST_IP_PRUNE = 0.0
+# Sharded overflow for per-IP failures that can't get their own bucket while the
+# dict is saturated. Each shard is a small fixed-capacity dict ``ip -> [count,
+# window_start]``: a per-IP count (so a source is throttled, and cleared on
+# success, by its own failures -- no cross-IP collateral) with hard-bounded
+# memory and O(1) lookups. When a shard is full a new IP evicts the lowest-count
+# entry (and starts clean, never inheriting its count) rather than growing without
+# bound, so a high-cardinality spray can't blow memory/CPU the way a per-failure
+# deque could; a persistent attacker keeps a high count and is never the one
+# evicted.
+_LOGIN_IP_OVERFLOW_SHARDS = 256
+_LOGIN_IP_OVERFLOW_MAX = 64 # distinct IPs tracked per shard
+_LOGIN_IP_OVERFLOW: list[dict] = [dict() for _ in range(_LOGIN_IP_OVERFLOW_SHARDS)]
+
+
+def _overflow_shard(ip: str) -> dict:
+ return _LOGIN_IP_OVERFLOW[hash(ip) % _LOGIN_IP_OVERFLOW_SHARDS]
+
+
+def _overflow_record(ip: str, now: float) -> int:
+ """Record an overflow failure for ``ip`` and return its windowed count."""
+ shard = _overflow_shard(ip)
+ entry = shard.get(ip)
+ if entry is not None:
+ if now - entry[1] > _LOGIN_WINDOW_SECONDS:
+ entry[0], entry[1] = 1, now
+ else:
+ # Only "at or above the per-IP threshold" matters for blocking, so cap
+ # the count there. This also keeps the migration into a per-IP bucket
+ # bounded -- without the cap a saturated source could accrue an
+ # unbounded count, then materialize one deque entry per failure
+ # (``[start] * carried``) on the next attempt, allocating an arbitrarily
+ # large deque while holding the login lock.
+ entry[0] = min(entry[0] + 1, _LOGIN_IP_MAX_FAILS)
+ return entry[0]
+ if len(shard) >= _LOGIN_IP_OVERFLOW_MAX:
+ # Make room by dropping the lowest-count entry, but the new source starts
+ # clean -- never inherit the evicted IP's failures, or an unrelated source
+ # could be 429'd after one attempt. Worst case under a saturated shard is
+ # that a heavy hitter briefly resets, not that a bystander is blocked.
+ del shard[min(shard, key = lambda k: shard[k][0])]
+ shard[ip] = [1, now]
+ return 1
+
+
+def _overflow_blocked(ip: str, now: float) -> int:
+ """Seconds this IP is throttled by its own overflow count, or 0."""
+ shard = _overflow_shard(ip)
+ entry = shard.get(ip)
+ if entry is None:
+ return 0
+ if now - entry[1] > _LOGIN_WINDOW_SECONDS:
+ del shard[ip]
+ return 0
+ if entry[0] >= _LOGIN_IP_MAX_FAILS:
+ return max(1, int(_LOGIN_WINDOW_SECONDS - (now - entry[1])))
+ return 0
+
+
+def _overflow_take(ip: str, now: float) -> tuple[int, float]:
+ """Pop ip's overflow entry, returning its ``(count, window_start)`` so the
+ count can migrate into a fresh per-IP bucket. ``(0, now)`` if none/expired."""
+ entry = _overflow_shard(ip).pop(ip, None)
+ if entry is None or now - entry[1] > _LOGIN_WINDOW_SECONDS:
+ return 0, now
+ # Cap the carried count so the bucket migration never allocates more than the
+ # per-IP threshold worth of deque entries (defensive; _overflow_record already
+ # clamps, but keep the bound at the consumption site too).
+ return min(entry[0], _LOGIN_IP_MAX_FAILS), entry[1]
+
+
# Unrepresentable as a real username (leading NUL); folds unknown-user attempts
# into one slot so attacker cardinality can't blow the bucket dict.
_UNKNOWN_LOGIN_USER = "\x00unknown-user"
@@ -169,13 +241,50 @@ def _prune_stale_buckets(now: float) -> None:
_LOGIN_BUCKETS.pop(key, None)
+def _prune_stale_ip_buckets(now: float) -> None:
+ """Drop empty / expired per-IP buckets to bound memory under spray.
+
+ The dict is otherwise reclaimed only on a successful login, so a failure-only
+ spray from many (or spoofed) IPs would grow it without bound.
+ """
+ stale: list[str] = []
+ for bucket_ip, bucket in _LOGIN_IP_BUCKETS.items():
+ _prune_bucket(bucket, now)
+ if not bucket:
+ stale.append(bucket_ip)
+ for bucket_ip in stale:
+ _LOGIN_IP_BUCKETS.pop(bucket_ip, None)
+
+
def _record_login_failure(key: tuple[str, str]) -> int:
+ global _LAST_IP_PRUNE
now = time.monotonic()
ip, _username = key
with _LOGIN_BUCKETS_LOCK:
- ip_bucket = _LOGIN_IP_BUCKETS.setdefault(ip, deque())
- _prune_bucket(ip_bucket, now)
- ip_bucket.append(now)
+ # Keep the dict bounded without disabling throttling and without letting a
+ # spray reset a hot bucket: for a new IP at the cap, reclaim expired buckets
+ # (rate-limited) to make room.
+ ip_bucket = _LOGIN_IP_BUCKETS.get(ip)
+ if ip_bucket is None and len(_LOGIN_IP_BUCKETS) >= _LOGIN_MAX_BUCKETS:
+ if now - _LAST_IP_PRUNE >= 1.0:
+ _prune_stale_ip_buckets(now)
+ _LAST_IP_PRUNE = now
+ if ip_bucket is None and len(_LOGIN_IP_BUCKETS) >= _LOGIN_MAX_BUCKETS:
+ # Still full -- every bucket is hot. Count this failure in the IP's
+ # bounded overflow shard instead of evicting a live one, so the spray
+ # stays throttled but can't push out (and reset) any IP's own counter.
+ ip_fails = _overflow_record(ip, now)
+ else:
+ if ip_bucket is None:
+ ip_bucket = _LOGIN_IP_BUCKETS[ip] = deque()
+ # Carry over any overflow failures this IP accrued while the dict
+ # was saturated, so straddling the overflow -> bucket transition
+ # can't double the effective per-IP limit.
+ carried, start = _overflow_take(ip, now)
+ ip_bucket.extend([start] * carried)
+ _prune_bucket(ip_bucket, now)
+ ip_bucket.append(now)
+ ip_fails = len(ip_bucket)
if key not in _LOGIN_BUCKETS and len(_LOGIN_BUCKETS) >= _LOGIN_MAX_BUCKETS:
_prune_stale_buckets(now)
@@ -184,8 +293,8 @@ def _record_login_failure(key: tuple[str, str]) -> int:
_prune_bucket(account_bucket, now)
account_bucket.append(now)
return len(account_bucket)
- # Bucket dict at cap; per-IP cap still applies via ip_bucket.
- return len(ip_bucket)
+ # Both dicts at cap (sustained spray): fall back to the per-IP count.
+ return ip_fails
def _blocked_for(bucket: deque | None, now: float, max_fails: int) -> int:
@@ -202,10 +311,16 @@ def _login_blocked(key: tuple[str, str]) -> int:
now = time.monotonic()
ip, _username = key
with _LOGIN_BUCKETS_LOCK:
- return max(
- _blocked_for(_LOGIN_BUCKETS.get(key), now, _LOGIN_MAX_FAILS),
+ # Honor the IP's overflow shard regardless of current dict capacity: a
+ # source counted there during saturation must stay throttled until those
+ # failures age out, even if a bucket later frees up -- otherwise a fresh
+ # bucket would reset it. Shards are empty outside saturation, so this is a
+ # no-op in the common case.
+ ip_blocked = max(
_blocked_for(_LOGIN_IP_BUCKETS.get(ip), now, _LOGIN_IP_MAX_FAILS),
+ _overflow_blocked(ip, now),
)
+ return max(_blocked_for(_LOGIN_BUCKETS.get(key), now, _LOGIN_MAX_FAILS), ip_blocked)
def _clear_login_bucket(key: tuple[str, str]) -> None:
@@ -213,6 +328,10 @@ def _clear_login_bucket(key: tuple[str, str]) -> None:
with _LOGIN_BUCKETS_LOCK:
_LOGIN_BUCKETS.pop(key, None)
_LOGIN_IP_BUCKETS.pop(ip, None)
+ # A successful login resets the IP's throttle, including any overflow it
+ # accumulated during saturation (drop only this IP's entry, so a
+ # shard-mate's throttle is untouched).
+ _overflow_shard(ip).pop(ip, None)
# Sync def (not async): compute_identity_proof touches SQLite on the first call,
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index e77616fb9f8..a9c85fa99ac 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -4486,6 +4486,14 @@ async def _proxy_to_external_provider(
except Exception as exc:
logger.error("external_provider.stream_error", error = str(exc))
api_monitor.fail(monitor_id, _friendly_error(exc))
+ # Surface the failure: a bare EOF (e.g. after a read timeout) is treated
+ # by the chat client as success, saving a partial answer with no error.
+ yield (
+ "data: "
+ + json.dumps({"error": {"message": _friendly_error(exc), "type": "server_error"}})
+ + "\n\n"
+ )
+ yield "data: [DONE]\n\n"
finally:
try:
await gen.aclose()
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index 38a2cab3893..3818fe9f732 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -847,6 +847,11 @@ async def stream_training_progress(
)
while backend.is_training_active():
+ # Client gone: end the generator without falling through to the final
+ # "complete" frame, which a buffered/proxy consumer could otherwise read
+ # as a finished run while training is still active.
+ if await request.is_disconnected():
+ return
try:
tp_inner = getattr(getattr(backend, "trainer", None), "training_progress", None)
live_step = (getattr(tp_inner, "step", 0) or 0) if tp_inner else 0
diff --git a/studio/backend/storage/rag_db.py b/studio/backend/storage/rag_db.py
index 564e3284f89..4da600d7683 100644
--- a/studio/backend/storage/rag_db.py
+++ b/studio/backend/storage/rag_db.py
@@ -156,3 +156,71 @@ def vec_table_exists(conn: sqlite3.Connection) -> bool:
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='chunks_vec'"
).fetchone()
return row is not None
+
+
+def _delete_document_chunks(conn, document_id: str) -> None:
+ """Delete a document's chunk rows (chunks/chunks_fts/chunks_vec), keeping the
+ documents row. Used when reconciling a half-ingested doc to failed: retrieval
+ filters by scope not status, so leftover chunks would stay citable."""
+ chunk_ids = [
+ r["id"]
+ for r in conn.execute(
+ "SELECT id FROM chunks WHERE document_id=?", (document_id,)
+ ).fetchall()
+ ]
+ if not chunk_ids:
+ return
+ has_vec = vec_table_exists(conn)
+ for chunk_id in chunk_ids:
+ conn.execute("DELETE FROM chunks_fts WHERE chunk_id=?", (chunk_id,))
+ if has_vec:
+ conn.execute("DELETE FROM chunks_vec WHERE chunk_id=?", (chunk_id,))
+ conn.execute("DELETE FROM chunks WHERE document_id=?", (document_id,))
+
+
+def reconcile_orphaned_ingestion_jobs() -> int:
+ """Fail ingestion jobs/documents left mid-flight by a crash so they stop
+ showing as stuck "processing" and become re-ingestible. Run at startup.
+ No-op without RAG. Returns the number of jobs reset.
+ """
+ if not RAG_AVAILABLE:
+ return 0
+ conn = get_connection()
+ try:
+ rows = conn.execute(
+ "SELECT id, document_id FROM ingestion_jobs "
+ "WHERE status NOT IN ('completed', 'failed')"
+ ).fetchall()
+ for row in rows:
+ doc = conn.execute(
+ "SELECT status FROM documents WHERE id=?", (row["document_id"],)
+ ).fetchone()
+ if doc is not None and doc["status"] == "completed":
+ # Worker finished indexing before the crash but didn't retire the
+ # job row. Mark the job completed (not failed) and keep its chunks,
+ # so the UI's getJob fallback after restart doesn't flag a
+ # searchable document as a failed ingestion.
+ conn.execute(
+ "UPDATE ingestion_jobs SET status='completed', stage='done', "
+ "progress=1.0, error=NULL WHERE id=?",
+ (row["id"],),
+ )
+ continue
+ conn.execute(
+ "UPDATE ingestion_jobs SET status='failed', stage='error', "
+ "error='Server restarted during ingestion' WHERE id=?",
+ (row["id"],),
+ )
+ conn.execute(
+ "UPDATE documents SET status='failed' "
+ "WHERE id=? AND status NOT IN ('completed', 'failed')",
+ (row["document_id"],),
+ )
+ # A failed or still-in-flight doc must not leave citable chunks
+ # (retrieval filters by scope, not status); also drops any chunks of a
+ # doc already 'failed' before the crash.
+ _delete_document_chunks(conn, row["document_id"])
+ conn.commit()
+ return len(rows)
+ finally:
+ conn.close()
diff --git a/studio/backend/tests/test_data_recipe_pump_resilience.py b/studio/backend/tests/test_data_recipe_pump_resilience.py
new file mode 100644
index 00000000000..e702be78110
--- /dev/null
+++ b/studio/backend/tests/test_data_recipe_pump_resilience.py
@@ -0,0 +1,152 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Data-recipe job pump resilience.
+
+The pump is the sole consumer of worker events and sole writer of the job
+snapshot the status/SSE endpoints read; a handler error must not kill it, or the
+job stays wedged "active" and the workflow key is never retired. Fakes only.
+"""
+
+from __future__ import annotations
+
+import queue
+import sys
+import threading
+import time
+from pathlib import Path
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+from core.data_recipe.jobs.manager import JobManager # noqa: E402
+from core.data_recipe.jobs.types import Job # noqa: E402
+
+
+class _FakeProc:
+ def __init__(self, alive: bool = True):
+ self._alive = alive
+
+ def is_alive(self):
+ return self._alive
+
+
+class _ScriptedQueue:
+ def __init__(self, events):
+ self._events = list(events)
+
+ def get(self, timeout = None):
+ if self._events:
+ return self._events.pop(0)
+ raise queue.Empty
+
+ def get_nowait(self):
+ if self._events:
+ return self._events.pop(0)
+ raise queue.Empty
+
+
+def _wait_until(predicate, timeout = 5.0):
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if predicate():
+ return True
+ time.sleep(0.01)
+ return predicate()
+
+
+def _manager_with_active_job():
+ m = JobManager.__new__(JobManager)
+ m._lock = threading.Lock()
+ job = Job(job_id = "job-test")
+ job.status = "active"
+ m._job = job
+ m._proc = _FakeProc(alive = True)
+ m._mp_q = _ScriptedQueue([])
+ return m
+
+
+def test_pump_survives_handler_exception_and_still_finalizes(monkeypatch):
+ m = _manager_with_active_job()
+ handled: list = []
+
+ def fake_handle(job, event):
+ if event.get("type") == "boom":
+ raise RuntimeError("malformed log line")
+ handled.append(event.get("type"))
+
+ emitted: list = []
+ retired: list = []
+ monkeypatch.setattr(m, "_handle_event", fake_handle)
+ monkeypatch.setattr(m, "_emit", lambda e: emitted.append(e))
+ monkeypatch.setattr(m, "_retire_workflow_key", lambda j: retired.append(j))
+
+ m._mp_q = _ScriptedQueue(
+ [{"type": "boom"}, {"type": "log"}, {"type": "boom"}, {"type": "progress"}]
+ )
+
+ pump = threading.Thread(target = m._pump_loop, daemon = True)
+ pump.start()
+ try:
+ assert _wait_until(
+ lambda: handled == ["log", "progress"]
+ ), "pump must keep processing events after a handler raises"
+ assert pump.is_alive()
+ finally:
+ m._proc._alive = False # worker exits -> pump should finalize and stop
+ pump.join(timeout = 5)
+
+ assert not pump.is_alive()
+ # The exited worker is finalized as error (not left wedged "active") and the
+ # workflow key is retired despite the earlier handler exceptions.
+ assert m._job.status == "error"
+ assert retired and retired[0] is m._job
+
+
+def test_pump_finalizes_when_drain_raises(monkeypatch):
+ m = _manager_with_active_job()
+ monkeypatch.setattr(m, "_emit", lambda e: None)
+ retired: list = []
+ monkeypatch.setattr(m, "_retire_workflow_key", lambda j: retired.append(j))
+
+ class _BadDrainQueue:
+ def get(self, timeout = None):
+ raise queue.Empty
+
+ def get_nowait(self):
+ raise RuntimeError("corrupt drain payload")
+
+ m._proc = _FakeProc(alive = False)
+ m._mp_q = _BadDrainQueue()
+
+ m._pump_loop() # returns once it sees the dead worker
+
+ assert m._job.status == "error"
+ assert retired and retired[0] is m._job
+
+
+def test_pump_finalizes_when_read_keeps_raising_on_dead_worker(monkeypatch):
+ # A read that keeps raising after the child died must not spin the pump
+ # forever: once the worker is gone it falls through to finalize.
+ m = _manager_with_active_job()
+ monkeypatch.setattr(m, "_emit", lambda e: None)
+ retired: list = []
+ monkeypatch.setattr(m, "_retire_workflow_key", lambda j: retired.append(j))
+
+ class _BrokenReadQueue:
+ def get(self, timeout = None):
+ raise RuntimeError("broken queue pipe")
+
+ def get_nowait(self):
+ raise queue.Empty
+
+ m._proc = _FakeProc(alive = False)
+ m._mp_q = _BrokenReadQueue()
+
+ pump = threading.Thread(target = m._pump_loop, daemon = True)
+ pump.start()
+ pump.join(timeout = 5)
+ assert not pump.is_alive(), "pump must finalize a dead worker even when reads keep raising"
+ assert m._job.status == "error"
+ assert retired and retired[0] is m._job
diff --git a/studio/backend/tests/test_inference_dispatcher_resilience.py b/studio/backend/tests/test_inference_dispatcher_resilience.py
new file mode 100644
index 00000000000..2de833db0eb
--- /dev/null
+++ b/studio/backend/tests/test_inference_dispatcher_resilience.py
@@ -0,0 +1,91 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Inference dispatcher resilience.
+
+The dispatcher thread is the sole consumer of the response queue; if a malformed
+response killed it, every in-flight generation would hang forever. A bad response
+must be logged and skipped, not fatal. Fakes only.
+"""
+
+from __future__ import annotations
+
+import queue
+import sys
+import threading
+import time
+from pathlib import Path
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+from core.inference.orchestrator import InferenceOrchestrator # noqa: E402
+
+
+class _ScriptedQueue:
+ def __init__(self, items):
+ self._items = list(items)
+
+ def get(self, timeout = None):
+ if self._items:
+ return self._items.pop(0)
+ raise queue.Empty
+
+
+def _dispatcher():
+ o = InferenceOrchestrator.__new__(InferenceOrchestrator)
+ o._dispatcher_stop = threading.Event()
+ o._mailbox_lock = threading.Lock()
+ o._mailboxes = {}
+ return o
+
+
+def test_dispatcher_survives_malformed_response_and_routes_next():
+ o = _dispatcher()
+ rid = "req-1"
+ mbox = queue.Queue()
+ o._mailboxes = {rid: mbox}
+ # A non-dict response (resp.get -> AttributeError) must not kill the loop;
+ # the following valid response must still reach its mailbox.
+ o._resp_queue = _ScriptedQueue([12345, {"request_id": rid, "type": "token", "text": "hi"}])
+
+ t = threading.Thread(target = o._dispatcher_loop, daemon = True)
+ t.start()
+ try:
+ got = mbox.get(timeout = 5)
+ assert got["text"] == "hi", "valid response must route despite the prior bad one"
+ assert t.is_alive(), "dispatcher must survive a malformed response"
+ finally:
+ o._dispatcher_stop.set()
+ t.join(timeout = 5)
+ assert not t.is_alive()
+
+
+def test_dispatcher_survives_mailbox_put_error():
+ o = _dispatcher()
+ rid = "req-2"
+
+ class _BadMailbox:
+ def put(self, _resp):
+ raise RuntimeError("mailbox is broken")
+
+ good = queue.Queue()
+ o._mailboxes = {rid: _BadMailbox(), "req-3": good}
+ o._resp_queue = _ScriptedQueue(
+ [
+ {"request_id": rid, "type": "token", "text": "boom"},
+ {"request_id": "req-3", "type": "token", "text": "ok"},
+ ]
+ )
+
+ t = threading.Thread(target = o._dispatcher_loop, daemon = True)
+ t.start()
+ try:
+ got = good.get(timeout = 5)
+ assert got["text"] == "ok"
+ assert t.is_alive()
+ finally:
+ o._dispatcher_stop.set()
+ t.join(timeout = 5)
+ assert not t.is_alive()
diff --git a/studio/backend/tests/test_login_rate_limit.py b/studio/backend/tests/test_login_rate_limit.py
index 14b10576dab..6f9635e41e3 100644
--- a/studio/backend/tests/test_login_rate_limit.py
+++ b/studio/backend/tests/test_login_rate_limit.py
@@ -29,9 +29,15 @@ def _reset_buckets():
auth_routes._LOGIN_BUCKETS.clear()
auth_routes._LOGIN_IP_BUCKETS.clear()
+ for _shard in auth_routes._LOGIN_IP_OVERFLOW:
+ _shard.clear()
+ auth_routes._LAST_IP_PRUNE = 0.0
yield
auth_routes._LOGIN_BUCKETS.clear()
auth_routes._LOGIN_IP_BUCKETS.clear()
+ for _shard in auth_routes._LOGIN_IP_OVERFLOW:
+ _shard.clear()
+ auth_routes._LAST_IP_PRUNE = 0.0
@pytest.fixture
@@ -215,6 +221,245 @@ class TestBucketKeyAndBlocking:
# Hard cap respected; further keys don't allocate.
assert len(auth_routes._LOGIN_BUCKETS) <= 10
+ def test_ip_bucket_cap_bounds_without_disabling_throttling(self, env_no_proxy, monkeypatch):
+ """The per-IP dict is bounded, but saturating it must NOT disable
+ throttling: a new IP that keeps failing after the cap is hit is still
+ blocked (now via the shared overflow counter)."""
+ from routes import auth as auth_routes
+
+ monkeypatch.setattr(auth_routes, "_LOGIN_MAX_BUCKETS", 10)
+ monkeypatch.setattr(auth_routes, "_LOGIN_IP_MAX_FAILS", 5)
+ # Saturate the per-IP dict with distinct source IPs.
+ for idx in range(50):
+ auth_routes._record_login_failure((f"198.51.100.{idx}", "admin"))
+ assert len(auth_routes._LOGIN_IP_BUCKETS) <= 10 # bounded
+
+ # A brand-new IP arriving after saturation is still throttled: it can't get
+ # its own bucket, so its failures land in the shared overflow counter.
+ victim = ("203.0.113.99", "admin")
+ for _ in range(5):
+ auth_routes._record_login_failure(victim)
+ assert auth_routes._login_blocked(victim) > 0
+
+ def test_saturating_spray_cannot_reset_a_hot_ip_bucket(self, env_no_proxy, monkeypatch):
+ """An IP flooding the dict must not evict (and reset) its own hot bucket.
+
+ With FIFO eviction the oldest-inserted bucket -- the attacker's own, now
+ blocked -- was popped once enough fresh IPs arrived, letting the attacker
+ retry as first-seen. The overflow counter must keep it throttled.
+ """
+ from routes import auth as auth_routes
+
+ monkeypatch.setattr(auth_routes, "_LOGIN_MAX_BUCKETS", 10)
+ monkeypatch.setattr(auth_routes, "_LOGIN_IP_MAX_FAILS", 5)
+ # Neutralize account-bucket blocking so this isolates the per-IP path.
+ monkeypatch.setattr(auth_routes, "_LOGIN_MAX_FAILS", 100)
+
+ attacker = ("203.0.113.7", "admin")
+ for _ in range(5):
+ auth_routes._record_login_failure(attacker)
+ assert auth_routes._login_blocked(attacker) > 0 # attacker is throttled
+
+ # Attacker sprays many distinct IPs to try to push its own bucket out.
+ for idx in range(100):
+ auth_routes._record_login_failure((f"198.51.100.{idx}", "admin"))
+
+ # Still throttled: its hot bucket survived rather than being evicted.
+ assert auth_routes._login_blocked(attacker) > 0
+
+ def test_overflow_is_sharded_so_a_hot_ip_does_not_block_unrelated_ips(
+ self, env_no_proxy, monkeypatch
+ ):
+ """A saturating spray must not globally deny login: a hot overflow shard
+ throttles only the IPs that hash to it, not every new unbucketed client.
+ """
+ from routes import auth as auth_routes
+
+ monkeypatch.setattr(auth_routes, "_LOGIN_MAX_BUCKETS", 10)
+ monkeypatch.setattr(auth_routes, "_LOGIN_IP_MAX_FAILS", 5)
+ # Neutralize account-bucket blocking so this isolates the per-IP path.
+ monkeypatch.setattr(auth_routes, "_LOGIN_MAX_FAILS", 100)
+
+ # Saturate the bucket dict so further new IPs fall through to overflow.
+ for idx in range(10):
+ auth_routes._record_login_failure((f"10.0.0.{idx}", "admin"))
+
+ # Drive one IP's real overflow shard hot.
+ attacker_ip = "198.51.100.7"
+ for _ in range(5):
+ auth_routes._record_login_failure((attacker_ip, "admin"))
+ assert auth_routes._login_blocked((attacker_ip, "admin")) > 0
+
+ # A new IP in a *different* shard must not be denied (a single global
+ # counter would block it; a sharded one preserves per-source isolation).
+ attacker_shard = auth_routes._overflow_shard(attacker_ip)
+ victim_ip = next(
+ f"203.0.113.{i}"
+ for i in range(256)
+ if auth_routes._overflow_shard(f"203.0.113.{i}") is not attacker_shard
+ )
+ assert auth_routes._login_blocked((victim_ip, "admin")) == 0
+
+ def test_overflow_throttle_survives_capacity_freeing(self, env_no_proxy, monkeypatch):
+ """A source throttled via overflow must stay throttled even if a bucket
+ frees up before the window expires; otherwise a fresh bucket resets it.
+ """
+ from routes import auth as auth_routes
+
+ monkeypatch.setattr(auth_routes, "_LOGIN_MAX_BUCKETS", 10)
+ monkeypatch.setattr(auth_routes, "_LOGIN_IP_MAX_FAILS", 5)
+ # Neutralize account-bucket blocking so this isolates the per-IP path.
+ monkeypatch.setattr(auth_routes, "_LOGIN_MAX_FAILS", 100)
+
+ # Saturate the dict, then drive a source's overflow shard hot.
+ for idx in range(10):
+ auth_routes._record_login_failure((f"10.0.0.{idx}", "admin"))
+ attacker = ("198.51.100.7", "admin")
+ for _ in range(5):
+ auth_routes._record_login_failure(attacker)
+ assert auth_routes._login_blocked(attacker) > 0
+
+ # A successful login from another IP frees a bucket slot.
+ auth_routes._clear_login_bucket(("10.0.0.0", "admin"))
+ assert len(auth_routes._LOGIN_IP_BUCKETS) < auth_routes._LOGIN_MAX_BUCKETS
+
+ # Still throttled (overflow shard still hot), and a new failure that now
+ # gets a fresh per-IP bucket must not reset the throttle.
+ assert auth_routes._login_blocked(attacker) > 0
+ auth_routes._record_login_failure(attacker)
+ assert auth_routes._login_blocked(attacker) > 0
+
+ def test_overflow_shard_is_memory_bounded_under_cardinality_spray(
+ self, env_no_proxy, monkeypatch
+ ):
+ """A high-cardinality spray must not grow overflow memory without bound:
+ each shard tracks at most _LOGIN_IP_OVERFLOW_MAX distinct IPs.
+ """
+ from routes import auth as auth_routes
+
+ monkeypatch.setattr(auth_routes, "_LOGIN_MAX_BUCKETS", 10)
+ monkeypatch.setattr(auth_routes, "_LOGIN_IP_OVERFLOW_MAX", 8)
+
+ # Saturate the dict, then spray thousands of distinct one-off IPs.
+ for idx in range(10):
+ auth_routes._record_login_failure((f"10.0.0.{idx}", "admin"))
+ for idx in range(5000):
+ auth_routes._record_login_failure((f"198.51.{idx // 256}.{idx % 256}", "admin"))
+
+ assert all(len(shard) <= 8 for shard in auth_routes._LOGIN_IP_OVERFLOW)
+
+ def test_overflow_eviction_does_not_inherit_count_onto_new_ip(self, env_no_proxy, monkeypatch):
+ """Evicting a hot entry to make room must not hand its failure count to the
+ new source; one attempt from an unrelated IP must not 429 it.
+ """
+ from routes import auth as auth_routes
+
+ monkeypatch.setattr(auth_routes, "_LOGIN_MAX_BUCKETS", 10)
+ monkeypatch.setattr(auth_routes, "_LOGIN_IP_MAX_FAILS", 5)
+ monkeypatch.setattr(auth_routes, "_LOGIN_IP_OVERFLOW_MAX", 2)
+ monkeypatch.setattr(auth_routes, "_LOGIN_MAX_FAILS", 100)
+ # Force every overflow IP into one shard so we can saturate it.
+ shard0 = auth_routes._LOGIN_IP_OVERFLOW[0]
+ monkeypatch.setattr(auth_routes, "_overflow_shard", lambda _ip: shard0)
+
+ for idx in range(10):
+ auth_routes._record_login_failure((f"10.0.0.{idx}", "admin"))
+ # Fill the shard (cap 2) with two hot IPs at/over the threshold.
+ for _ in range(5):
+ auth_routes._record_login_failure(("198.51.100.1", "admin"))
+ for _ in range(5):
+ auth_routes._record_login_failure(("198.51.100.2", "admin"))
+ assert len(shard0) == 2
+
+ # A new IP evicts the lowest-count entry; it must start clean, so one
+ # failure leaves it below the threshold and unblocked.
+ new_ip = ("203.0.113.50", "admin")
+ auth_routes._record_login_failure(new_ip)
+ assert auth_routes._login_blocked(new_ip) == 0
+
+ def test_overflow_count_migrates_into_new_bucket(self, env_no_proxy, monkeypatch):
+ """Straddling the overflow -> bucket transition must not double the per-IP
+ limit: the overflow count carries into the freshly created bucket.
+ """
+ from routes import auth as auth_routes
+
+ monkeypatch.setattr(auth_routes, "_LOGIN_MAX_BUCKETS", 10)
+ monkeypatch.setattr(auth_routes, "_LOGIN_IP_MAX_FAILS", 5)
+ monkeypatch.setattr(auth_routes, "_LOGIN_MAX_FAILS", 100)
+
+ # Saturate, then push one IP to 4 overflow failures (one below threshold).
+ for idx in range(10):
+ auth_routes._record_login_failure((f"10.0.0.{idx}", "admin"))
+ attacker = ("198.51.100.7", "admin")
+ for _ in range(4):
+ auth_routes._record_login_failure(attacker)
+ assert auth_routes._login_blocked(attacker) == 0 # 4 < 5
+
+ # Free a slot so the next failure lands in a fresh per-IP bucket.
+ auth_routes._clear_login_bucket(("10.0.0.0", "admin"))
+ # One more failure must throttle (4 carried + 1 = 5), not reset to 1.
+ auth_routes._record_login_failure(attacker)
+ assert auth_routes._login_blocked(attacker) > 0
+
+ def test_overflow_migration_is_bounded_not_one_entry_per_failure(
+ self, env_no_proxy, monkeypatch
+ ):
+ """A saturated IP can rack up many overflow failures; migrating them into a
+ fresh bucket must allocate at most the per-IP threshold worth of entries,
+ not one deque entry per recorded failure (which would let a single later
+ attempt allocate an arbitrarily large deque under the login lock).
+ """
+ from routes import auth as auth_routes
+
+ monkeypatch.setattr(auth_routes, "_LOGIN_MAX_BUCKETS", 10)
+ monkeypatch.setattr(auth_routes, "_LOGIN_IP_MAX_FAILS", 5)
+ monkeypatch.setattr(auth_routes, "_LOGIN_MAX_FAILS", 100000)
+
+ # Saturate the dict, then hammer one IP far past the threshold in overflow.
+ for idx in range(10):
+ auth_routes._record_login_failure((f"10.0.0.{idx}", "admin"))
+ attacker_ip = "198.51.100.7"
+ attacker = (attacker_ip, "admin")
+ for _ in range(5000):
+ auth_routes._record_login_failure(attacker)
+ # The stored overflow count is clamped at the threshold, not 5000.
+ entry = auth_routes._overflow_shard(attacker_ip).get(attacker_ip)
+ assert entry is not None and entry[0] <= auth_routes._LOGIN_IP_MAX_FAILS
+
+ # Free a slot so the next failure migrates the overflow count into a bucket.
+ auth_routes._clear_login_bucket(("10.0.0.0", "admin"))
+ auth_routes._record_login_failure(attacker)
+ bucket = auth_routes._LOGIN_IP_BUCKETS[attacker_ip]
+ # Bounded by the threshold (+1 for the triggering failure), not ~5000.
+ assert len(bucket) <= auth_routes._LOGIN_IP_MAX_FAILS + 1
+ # Still throttled -- bounding the migration must not weaken the limit.
+ assert auth_routes._login_blocked(attacker) > 0
+
+ def test_successful_login_clears_overflow_throttle(self, env_no_proxy, monkeypatch):
+ """A successful login resets the IP's throttle, including overflow, so a
+ single later typo is not immediately blocked.
+ """
+ from routes import auth as auth_routes
+
+ monkeypatch.setattr(auth_routes, "_LOGIN_MAX_BUCKETS", 10)
+ monkeypatch.setattr(auth_routes, "_LOGIN_IP_MAX_FAILS", 5)
+ monkeypatch.setattr(auth_routes, "_LOGIN_MAX_FAILS", 100)
+
+ # Saturate the dict, then push one IP into overflow until it is throttled.
+ for idx in range(10):
+ auth_routes._record_login_failure((f"10.0.0.{idx}", "admin"))
+ ip = ("198.51.100.7", "admin")
+ for _ in range(5):
+ auth_routes._record_login_failure(ip)
+ assert auth_routes._login_blocked(ip) > 0
+
+ # A successful login from that IP clears its overflow entries...
+ auth_routes._clear_login_bucket(ip)
+ assert auth_routes._login_blocked(ip) == 0
+ # ...and a single subsequent failure does not immediately re-block it.
+ auth_routes._record_login_failure(ip)
+ assert auth_routes._login_blocked(ip) == 0
+
# ---------- /login 429 body ----------
diff --git a/studio/backend/tests/test_rag_job_events_queue_lifecycle.py b/studio/backend/tests/test_rag_job_events_queue_lifecycle.py
new file mode 100644
index 00000000000..0eb115c562a
--- /dev/null
+++ b/studio/backend/tests/test_rag_job_events_queue_lifecycle.py
@@ -0,0 +1,114 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""job_events keeps the per-job queue registered only while the worker runs.
+
+``_emit()`` writes to ``_jobs[job_id]`` while the worker runs; if an early SSE
+disconnect removed that queue, later events would be dropped and a reconnect
+would see only ``[DONE]`` and mark a running job complete. So keep it on an early
+disconnect of a running job, but drop it on a terminal exit or a disconnect after
+the job already finished; ``_reap_finished_jobs`` sweeps any leftovers.
+"""
+
+import queue
+import sqlite3
+import sys
+from pathlib import Path
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+import core.rag.ingestion as ing
+
+
+def test_early_disconnect_keeps_queue_registered(monkeypatch):
+ monkeypatch.setattr(ing, "_SSE_POLL_SECONDS", 0.01)
+ # Job is still running; nothing terminal has happened.
+ monkeypatch.setattr(ing, "get_job_status", lambda _jid: {"status": "running"})
+ jid = "job-early-disconnect"
+ ing._jobs[jid] = queue.Queue()
+ try:
+ gen = ing.job_events(jid)
+ next(gen) # enter loop: Empty -> non-terminal -> heartbeat
+ gen.close() # client disconnects before the job finishes
+ assert (
+ jid in ing._jobs
+ ), "queue must survive an early disconnect so the worker can still emit"
+ finally:
+ ing._jobs.pop(jid, None)
+
+
+def test_terminal_sentinel_removes_queue(monkeypatch):
+ monkeypatch.setattr(ing, "_SSE_POLL_SECONDS", 0.01)
+ jid = "job-terminal-sentinel"
+ q = queue.Queue()
+ q.put({"type": "progress", "stage": "embedding", "progress": 0.5})
+ q.put(None) # worker finished -> sentinel
+ ing._jobs[jid] = q
+ try:
+ events = list(ing.job_events(jid)) # drains progress, then None -> terminal
+ assert any(e.get("type") == "progress" for e in events)
+ assert jid not in ing._jobs, "queue must be removed once the job is terminal"
+ finally:
+ ing._jobs.pop(jid, None)
+
+
+def test_disconnect_after_terminal_event_removes_queue(monkeypatch):
+ monkeypatch.setattr(ing, "_SSE_POLL_SECONDS", 0.01)
+ # Worker finished: the DB row is terminal and a complete event is queued. The
+ # UI reads that event and disconnects (reader.cancel) before the None sentinel,
+ # so the queue must still drop rather than linger until the next reap.
+ monkeypatch.setattr(ing, "get_job_status", lambda _jid: {"status": "completed"})
+ jid = "job-disconnect-after-complete"
+ q = queue.Queue()
+ q.put({"type": "complete", "num_chunks": 3})
+ q.put(None)
+ ing._jobs[jid] = q
+ try:
+ gen = ing.job_events(jid)
+ assert next(gen)["type"] == "complete" # client receives the terminal event
+ gen.close() # disconnects before draining the sentinel
+ assert jid not in ing._jobs, "a finished job's queue must drop on disconnect"
+ finally:
+ ing._jobs.pop(jid, None)
+
+
+def test_transient_status_read_failure_does_not_end_stream(monkeypatch):
+ monkeypatch.setattr(ing, "_SSE_POLL_SECONDS", 0.01)
+ # The heartbeat poll hits a momentarily-locked DB. That must not propagate: the
+ # SSE route would turn the raised error into a terminal {type: error} frame and
+ # the UI would drop a document whose worker is still running. The stream should
+ # heartbeat and keep the queue so the worker can finish / a reconnect can resume.
+ calls = {"n": 0}
+
+ def flaky_status(_jid):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise sqlite3.OperationalError("database is locked")
+ return {"status": "running"}
+
+ monkeypatch.setattr(ing, "get_job_status", flaky_status)
+ jid = "job-transient-read-failure"
+ ing._jobs[jid] = queue.Queue()
+ try:
+ gen = ing.job_events(jid)
+ assert next(gen) == {"type": "heartbeat"} # transient error -> heartbeat, no raise
+ gen.close()
+ assert jid in ing._jobs, "an unconfirmed (transient-error) status must keep the queue"
+ finally:
+ ing._jobs.pop(jid, None)
+
+
+def test_terminal_db_status_removes_queue(monkeypatch):
+ monkeypatch.setattr(ing, "_SSE_POLL_SECONDS", 0.01)
+ # No events arrive, but the DB row reports the job finished (hard worker death
+ # that skipped the sentinel): the stream ends and the queue is reaped.
+ monkeypatch.setattr(ing, "get_job_status", lambda _jid: {"status": "completed"})
+ jid = "job-terminal-db"
+ ing._jobs[jid] = queue.Queue()
+ try:
+ list(ing.job_events(jid))
+ assert jid not in ing._jobs, "a terminal DB status must remove the queue"
+ finally:
+ ing._jobs.pop(jid, None)
diff --git a/studio/backend/tests/test_rag_reconcile_orphaned.py b/studio/backend/tests/test_rag_reconcile_orphaned.py
new file mode 100644
index 00000000000..c6932e4588c
--- /dev/null
+++ b/studio/backend/tests/test_rag_reconcile_orphaned.py
@@ -0,0 +1,114 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Startup reconciliation must not strip chunks from already-completed docs.
+
+A crash can leave an ingestion_jobs row non-terminal after the worker already
+committed the document as ``completed`` with all its chunks. Reconciliation flips
+the orphaned job to ``failed`` but must touch the document (and its chunks) only
+when it actually transitions the document to ``failed`` -- otherwise a completed
+source loses every chunk yet still reports ``completed``, so retrieval finds
+nothing and dedup (``status != 'failed'``) blocks re-ingest.
+"""
+
+import math
+
+from core.rag import store
+from core.rag.chunking import Chunk
+from storage import rag_db
+
+VOCAB = ["alpha", "bravo", "charlie", "delta"]
+
+
+def _embed(text):
+ v = [float(text.lower().count(w)) for w in VOCAB]
+ n = math.sqrt(sum(x * x for x in v)) or 1.0
+ return [x / n for x in v]
+
+
+def _chunk(text, index = 0):
+ return Chunk(
+ text = text,
+ token_count = len(text.split()),
+ page_number = None,
+ source_page_index = 0,
+ chunk_index = index,
+ page_char_start = 0,
+ page_char_end = len(text),
+ )
+
+
+def _add_doc(conn, scope, doc_id, status, texts):
+ store.create_document(
+ conn, scope = scope, filename = f"{doc_id}.txt", sha256 = doc_id, document_id = doc_id
+ )
+ store.add_chunks(
+ conn, scope, doc_id, [_chunk(t, i) for i, t in enumerate(texts)], [_embed(t) for t in texts]
+ )
+ store.set_document_status(conn, doc_id, status, num_chunks = len(texts))
+
+
+def _orphan_job(
+ conn,
+ doc_id,
+ scope,
+ status = "running",
+):
+ conn.execute(
+ "INSERT INTO ingestion_jobs(id, document_id, scope, status, stage, progress, created_at) "
+ "VALUES(?,?,?,?,?,?,datetime('now'))",
+ (f"job-{doc_id}", doc_id, scope, status, "embedding", 0.5),
+ )
+ conn.commit()
+
+
+def _chunk_count(conn, doc_id):
+ return conn.execute("SELECT COUNT(*) FROM chunks WHERE document_id=?", (doc_id,)).fetchone()[0]
+
+
+def _job_status(conn, doc_id):
+ return conn.execute(
+ "SELECT status FROM ingestion_jobs WHERE id=?", (f"job-{doc_id}",)
+ ).fetchone()["status"]
+
+
+def test_completed_doc_keeps_chunks_when_its_job_is_orphaned(rag_conn):
+ # Worker finished the document but crashed before retiring the job row.
+ _add_doc(rag_conn, "kb_a", "done", "completed", ["alpha bravo", "charlie delta"])
+ _orphan_job(rag_conn, "done", "kb_a")
+
+ assert rag_db.reconcile_orphaned_ingestion_jobs() == 1
+
+ # Document stays completed with all chunks; dedup still finds it.
+ assert store.get_document(rag_conn, "done")["status"] == "completed"
+ assert _chunk_count(rag_conn, "done") == 2
+ assert store.document_by_hash(rag_conn, "kb_a", "done") == "done"
+ # The orphaned job is reconciled to completed (not failed), so the UI's getJob
+ # fallback doesn't flag a searchable document as a failed ingestion.
+ assert _job_status(rag_conn, "done") == "completed"
+
+
+def test_in_flight_doc_is_failed_and_its_chunks_dropped(rag_conn):
+ # Partial chunks committed, document never marked terminal -> genuine orphan.
+ _add_doc(rag_conn, "kb_a", "partial", "processing", ["alpha bravo"])
+ _orphan_job(rag_conn, "partial", "kb_a")
+
+ assert rag_db.reconcile_orphaned_ingestion_jobs() == 1
+
+ assert store.get_document(rag_conn, "partial")["status"] == "failed"
+ assert _chunk_count(rag_conn, "partial") == 0
+ # Failed doc is re-ingestible (not deduped).
+ assert store.document_by_hash(rag_conn, "kb_a", "partial") is None
+
+
+def test_already_failed_doc_has_its_chunks_dropped(rag_conn):
+ # Worker committed chunks then marked the doc 'failed', but crashed before
+ # retiring the job row. Reconcile won't re-flip the doc (already failed), but
+ # its chunks must still be purged so they aren't retrievable/citable.
+ _add_doc(rag_conn, "kb_a", "failed_doc", "failed", ["alpha bravo"])
+ _orphan_job(rag_conn, "failed_doc", "kb_a")
+
+ assert rag_db.reconcile_orphaned_ingestion_jobs() == 1
+
+ assert store.get_document(rag_conn, "failed_doc")["status"] == "failed"
+ assert _chunk_count(rag_conn, "failed_doc") == 0
diff --git a/studio/backend/tests/test_training_progress_prep_timeout.py b/studio/backend/tests/test_training_progress_prep_timeout.py
index a7e6d4f839f..28e2ee37b93 100644
--- a/studio/backend/tests/test_training_progress_prep_timeout.py
+++ b/studio/backend/tests/test_training_progress_prep_timeout.py
@@ -71,11 +71,17 @@ class _Backend:
class _FakeRequest:
headers = {}
+ async def is_disconnected(self):
+ return False
+
class _ReconnectRequest:
# Reconnect carrying the last step the client already received.
headers = {"last-event-id": "10"}
+ async def is_disconnected(self):
+ return False
+
def _raw(response):
async def _drain():
diff --git a/studio/backend/tests/test_training_progress_stream_nan.py b/studio/backend/tests/test_training_progress_stream_nan.py
index 899527a04d3..5cd84bbca5b 100644
--- a/studio/backend/tests/test_training_progress_stream_nan.py
+++ b/studio/backend/tests/test_training_progress_stream_nan.py
@@ -62,6 +62,16 @@ class _FakeBackend:
class _FakeRequest:
headers = {}
+ async def is_disconnected(self):
+ return False
+
+
+class _DisconnectedRequest:
+ headers = {}
+
+ async def is_disconnected(self):
+ return True
+
def _collect_events(response, timeout = 15):
async def _drain():
@@ -116,6 +126,20 @@ def test_inactive_stream_completes_with_live_step_and_null_loss(monkeypatch):
assert final["loss"] is None
+def test_disconnect_while_active_does_not_emit_complete(monkeypatch):
+ # Client drops mid-run: the stream must end without a terminal "complete"
+ # frame, which a buffered/proxy consumer could otherwise read as a finished
+ # run while training is still active.
+ backend = _FakeBackend(active_polls = 5)
+ monkeypatch.setattr(rt, "get_training_backend", lambda: backend)
+
+ response = asyncio.run(
+ rt.stream_training_progress(_DisconnectedRequest(), current_subject = "tester")
+ )
+ raw = _collect_events(response)
+ assert "event: complete" not in raw
+
+
def test_stream_uses_finite_history_when_progress_in_sync(monkeypatch):
backend = _FakeBackend(active_polls = 2)
# Live progress agrees with the history tail: normal finite behavior.
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 7112a7877cf..15066caa8fd 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -844,79 +844,96 @@ export async function* streamChatCompletions(
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
-
- while (true) {
- const { done, value } = await reader.read();
- if (done) {
- break;
- }
-
- buffer += decoder.decode(value, { stream: true });
-
- let separatorIndex = buffer.search(/\r?\n\r?\n/);
- while (separatorIndex >= 0) {
- const rawEvent = buffer.slice(0, separatorIndex);
- const separatorLength = buffer[separatorIndex] === "\r" ? 4 : 2;
- buffer = buffer.slice(separatorIndex + separatorLength);
-
- const dataLines = parseSseEvent(rawEvent);
- if (dataLines.length === 0) {
- separatorIndex = buffer.search(/\r?\n\r?\n/);
- continue;
- }
-
- const dataText = dataLines.join("\n");
- if (dataText === "[DONE]") {
- return;
+ let completed = false;
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) {
+ completed = true;
+ break;
}
- const parsed = JSON.parse(dataText) as
- | OpenAIChatChunk
- | { type?: string; content?: string; error?: { message?: string } };
- if ("error" in parsed && parsed.error) {
- throw new Error(parsed.error.message || "Stream error");
- }
- // Tool status events are custom SSE payloads, not OpenAI chunks
- if ("type" in parsed && parsed.type === "tool_status") {
- yield {
- _toolStatus: parsed.content ?? "",
- } as unknown as OpenAIChatChunk;
- separatorIndex = buffer.search(/\r?\n\r?\n/);
- continue;
- }
- // Diffusion frame: a per-step canvas snapshot. Custom SSE payload (not an OpenAI chunk) with
- // no assistant text, surfaced as a transient marker for the in-place renderer, never the transcript.
- if ("type" in parsed && parsed.type === "diffusion_frame") {
- yield {
- _diffusionFrame: parsed,
- } as unknown as OpenAIChatChunk;
+ buffer += decoder.decode(value, { stream: true });
+
+ let separatorIndex = buffer.search(/\r?\n\r?\n/);
+ while (separatorIndex >= 0) {
+ const rawEvent = buffer.slice(0, separatorIndex);
+ const separatorLength = buffer[separatorIndex] === "\r" ? 4 : 2;
+ buffer = buffer.slice(separatorIndex + separatorLength);
+
+ const dataLines = parseSseEvent(rawEvent);
+ if (dataLines.length === 0) {
+ separatorIndex = buffer.search(/\r?\n\r?\n/);
+ continue;
+ }
+
+ const dataText = dataLines.join("\n");
+ if (dataText === "[DONE]") {
+ completed = true;
+ return;
+ }
+
+ const parsed = JSON.parse(dataText) as
+ | OpenAIChatChunk
+ | { type?: string; content?: string; error?: { message?: string } };
+ if ("error" in parsed && parsed.error) {
+ throw new Error(parsed.error.message || "Stream error");
+ }
+ // Tool status events are custom SSE payloads, not OpenAI chunks
+ if ("type" in parsed && parsed.type === "tool_status") {
+ yield {
+ _toolStatus: parsed.content ?? "",
+ } as unknown as OpenAIChatChunk;
+ separatorIndex = buffer.search(/\r?\n\r?\n/);
+ continue;
+ }
+ // Diffusion frame: a per-step canvas snapshot. Custom SSE payload (not an OpenAI chunk) with
+ // no assistant text, surfaced as a transient marker for the in-place renderer, never the transcript.
+ if ("type" in parsed && parsed.type === "diffusion_frame") {
+ yield {
+ _diffusionFrame: parsed,
+ } as unknown as OpenAIChatChunk;
+ separatorIndex = buffer.search(/\r?\n\r?\n/);
+ continue;
+ }
+ // Tool start/end events carry full input/output for the tool outputs panel
+ if (
+ "type" in parsed &&
+ (parsed.type === "tool_start" || parsed.type === "tool_end")
+ ) {
+ yield { _toolEvent: parsed } as unknown as OpenAIChatChunk;
+ separatorIndex = buffer.search(/\r?\n\r?\n/);
+ continue;
+ }
+ // Relay server-side reasoning duration.
+ if (
+ parsed &&
+ typeof parsed === "object" &&
+ "type" in parsed &&
+ parsed.type === "reasoning_summary"
+ ) {
+ yield {
+ _reasoningDurationMs: (parsed as { duration_ms?: number }).duration_ms,
+ } as unknown as OpenAIChatChunk;
+ separatorIndex = buffer.search(/\r?\n\r?\n/);
+ continue;
+ }
+ yield parsed as OpenAIChatChunk;
separatorIndex = buffer.search(/\r?\n\r?\n/);
- continue;
}
- // Tool start/end events carry full input/output for the tool outputs panel
- if (
- "type" in parsed &&
- (parsed.type === "tool_start" || parsed.type === "tool_end")
- ) {
- yield { _toolEvent: parsed } as unknown as OpenAIChatChunk;
- separatorIndex = buffer.search(/\r?\n\r?\n/);
- continue;
- }
- // Relay server-side reasoning duration.
- if (
- parsed &&
- typeof parsed === "object" &&
- "type" in parsed &&
- parsed.type === "reasoning_summary"
- ) {
- yield {
- _reasoningDurationMs: (parsed as { duration_ms?: number }).duration_ms,
- } as unknown as OpenAIChatChunk;
- separatorIndex = buffer.search(/\r?\n\r?\n/);
- continue;
+ }
+ } finally {
+ // Only abort on an early/abnormal exit. After a natural [DONE] (or server
+ // EOF) the request is logically complete and the backend finalizes its
+ // api-monitor entry right after the sentinel; cancelling here can be seen as
+ // a disconnect and mark a successful request as cancelled.
+ if (!completed) {
+ try {
+ await reader.cancel();
+ } catch {
+ // already closed
}
- yield parsed as OpenAIChatChunk;
- separatorIndex = buffer.search(/\r?\n\r?\n/);
}
}
}
diff --git a/studio/frontend/src/features/export/api/export-api.ts b/studio/frontend/src/features/export/api/export-api.ts
index 659dd44f885..f055f1bd618 100644
--- a/studio/frontend/src/features/export/api/export-api.ts
+++ b/studio/frontend/src/features/export/api/export-api.ts
@@ -425,5 +425,12 @@ export async function streamExportLogs(options: {
} catch (err) {
if (isAbortError(err)) return;
throw err;
+ } finally {
+ // Release the stream lock now instead of leaking the reader until GC.
+ try {
+ await reader.cancel();
+ } catch {
+ // already closed
+ }
}
}
diff --git a/studio/frontend/src/features/rag/api/rag-api.ts b/studio/frontend/src/features/rag/api/rag-api.ts
index 34ded24ac3e..b1215d2d461 100644
--- a/studio/frontend/src/features/rag/api/rag-api.ts
+++ b/studio/frontend/src/features/rag/api/rag-api.ts
@@ -197,31 +197,40 @@ export async function* streamJobEvents(
const decoder = new TextDecoder();
let buffer = "";
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
-
- let separatorIndex = buffer.search(/\r?\n\r?\n/);
- while (separatorIndex >= 0) {
- const rawEvent = buffer.slice(0, separatorIndex);
- const separatorLength = buffer[separatorIndex] === "\r" ? 4 : 2;
- buffer = buffer.slice(separatorIndex + separatorLength);
-
- const dataLines: string[] = [];
- for (const line of rawEvent.split(/\r?\n/)) {
- if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
- }
- if (dataLines.length > 0) {
- const dataText = dataLines.join("\n");
- if (dataText === "[DONE]") return;
- try {
- yield JSON.parse(dataText) as JobEvent;
- } catch {
- // Ignore unparseable frames; [DONE] still ends the loop.
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+
+ let separatorIndex = buffer.search(/\r?\n\r?\n/);
+ while (separatorIndex >= 0) {
+ const rawEvent = buffer.slice(0, separatorIndex);
+ const separatorLength = buffer[separatorIndex] === "\r" ? 4 : 2;
+ buffer = buffer.slice(separatorIndex + separatorLength);
+
+ const dataLines: string[] = [];
+ for (const line of rawEvent.split(/\r?\n/)) {
+ if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
}
+ if (dataLines.length > 0) {
+ const dataText = dataLines.join("\n");
+ if (dataText === "[DONE]") return;
+ try {
+ yield JSON.parse(dataText) as JobEvent;
+ } catch {
+ // Ignore unparseable frames; [DONE] still ends the loop.
+ }
+ }
+ separatorIndex = buffer.search(/\r?\n\r?\n/);
}
- separatorIndex = buffer.search(/\r?\n\r?\n/);
+ }
+ } finally {
+ // Release the stream lock now instead of leaking the reader until GC.
+ try {
+ await reader.cancel();
+ } catch {
+ // already closed
}
}
}
diff --git a/studio/frontend/src/features/recipe-studio/api/index.ts b/studio/frontend/src/features/recipe-studio/api/index.ts
index b227b960d17..4fe24b1f6d6 100644
--- a/studio/frontend/src/features/recipe-studio/api/index.ts
+++ b/studio/frontend/src/features/recipe-studio/api/index.ts
@@ -400,28 +400,37 @@ export async function streamRecipeJobEvents(options: {
const decoder = new TextDecoder();
let buffer = "";
- while (true) {
- const { value, done } = await reader.read();
- if (done) {
- break;
- }
- buffer += decoder.decode(value, { stream: true });
- let separatorIndex = buffer.search(/\r?\n\r?\n/);
- while (separatorIndex >= 0) {
- const rawEvent = buffer.slice(0, separatorIndex);
- const separatorLength = buffer[separatorIndex] === "\r" ? 4 : 2;
- buffer = buffer.slice(separatorIndex + separatorLength);
-
- if (rawEvent.startsWith("retry:")) {
- separatorIndex = buffer.search(/\r?\n\r?\n/);
- continue;
+ try {
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) {
+ break;
}
-
- const parsed = parseJobEvent(rawEvent);
- if (parsed) {
- options.onEvent(parsed);
+ buffer += decoder.decode(value, { stream: true });
+ let separatorIndex = buffer.search(/\r?\n\r?\n/);
+ while (separatorIndex >= 0) {
+ const rawEvent = buffer.slice(0, separatorIndex);
+ const separatorLength = buffer[separatorIndex] === "\r" ? 4 : 2;
+ buffer = buffer.slice(separatorIndex + separatorLength);
+
+ if (rawEvent.startsWith("retry:")) {
+ separatorIndex = buffer.search(/\r?\n\r?\n/);
+ continue;
+ }
+
+ const parsed = parseJobEvent(rawEvent);
+ if (parsed) {
+ options.onEvent(parsed);
+ }
+ separatorIndex = buffer.search(/\r?\n\r?\n/);
}
- separatorIndex = buffer.search(/\r?\n\r?\n/);
+ }
+ } finally {
+ // Release the stream lock now instead of leaking the reader until GC.
+ try {
+ await reader.cancel();
+ } catch {
+ // already closed
}
}
}
diff --git a/studio/frontend/src/features/training/api/train-api.ts b/studio/frontend/src/features/training/api/train-api.ts
index af3ea347c22..609e4f85910 100644
--- a/studio/frontend/src/features/training/api/train-api.ts
+++ b/studio/frontend/src/features/training/api/train-api.ts
@@ -143,37 +143,46 @@ export async function streamTrainingProgress(options: {
const decoder = new TextDecoder();
let buffer = "";
- while (true) {
- const { value, done } = await reader.read();
- if (done) {
- break;
- }
-
- buffer += decoder.decode(value, { stream: true });
+ try {
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) {
+ break;
+ }
- let separatorIndex = buffer.search(/\r?\n\r?\n/);
- while (separatorIndex >= 0) {
- const rawEvent = buffer.slice(0, separatorIndex);
- const separatorLength = buffer[separatorIndex] === "\r" ? 4 : 2;
- buffer = buffer.slice(separatorIndex + separatorLength);
+ buffer += decoder.decode(value, { stream: true });
- if (rawEvent.startsWith("retry:")) {
- separatorIndex = buffer.search(/\r?\n\r?\n/);
- continue;
- }
+ let separatorIndex = buffer.search(/\r?\n\r?\n/);
+ while (separatorIndex >= 0) {
+ const rawEvent = buffer.slice(0, separatorIndex);
+ const separatorLength = buffer[separatorIndex] === "\r" ? 4 : 2;
+ buffer = buffer.slice(separatorIndex + separatorLength);
- try {
- const event = parseSseEvent(rawEvent);
- if (event) {
- options.onEvent(event);
+ if (rawEvent.startsWith("retry:")) {
+ separatorIndex = buffer.search(/\r?\n\r?\n/);
+ continue;
}
- } catch (error) {
- if (!isAbortError(error)) {
- throw error;
+
+ try {
+ const event = parseSseEvent(rawEvent);
+ if (event) {
+ options.onEvent(event);
+ }
+ } catch (error) {
+ if (!isAbortError(error)) {
+ throw error;
+ }
}
- }
- separatorIndex = buffer.search(/\r?\n\r?\n/);
+ separatorIndex = buffer.search(/\r?\n\r?\n/);
+ }
+ }
+ } finally {
+ // Release the stream lock now instead of leaking the reader until GC.
+ try {
+ await reader.cancel();
+ } catch {
+ // already closed
}
}
}