Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: bound Deep Research first output waits (#7998)
alkinun5342a33e3595
diff --git a/studio/backend/core/research_runs.py b/studio/backend/core/research_runs.pyindex 087b5de230a..406819d33af 100644--- a/studio/backend/core/research_runs.py+++ b/studio/backend/core/research_runs.py@@ -147,10 +147,15 @@ _MODEL_WAIT_POLL_SECONDS = 2.0# otherwise re-send forever, so cap how many times one call may wait._MAX_MODEL_WAITS = 3_NO_MODEL_LOADED_DETAIL = "No model loaded"-# Transport keepalives prevent HTTP read timeouts without proving that a model which already-# started answering is still progressing. Prefill remains governed by modelTimeoutSeconds because-# CPU and offloaded models can legitimately take many minutes to produce their first token.+# Transport keepalives prevent HTTP read timeouts without proving that a model is progressing.+_MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS = 120.0_MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS = 120.0+# Cancellation is cooperative, so bound the wait for a cancelled iterator to unwind;+# otherwise a stuck one holds a timed-out call open for the rest of the wall clock.+_STREAM_CLEANUP_TIMEOUT_SECONDS = 5.0+# The SSE comment routes/inference.py sends while queued, not while the backend is silent.+_ADMISSION_WAIT_COMMENT = ": admission-wait"+_ADMISSION_DONE_COMMENT = ": admission-done"def _auto_scrape_default() -> int:@@ -573,7 +578,14 @@ class LeaseLost(Exception):class ModelOutputIdleTimeout(httpx.ReadTimeout):- pass+ # Default message: the stream reader raises the class the deadline names.+ def __init__(self, message: str = "Local model stopped producing output"):+ super().__init__(message)+++class ModelFirstOutputTimeout(httpx.ReadTimeout):+ def __init__(self, message: str = "Local model never produced output"):+ super().__init__(message)class ModelWallClockTimeout(httpx.ReadTimeout):@@ -581,6 +593,8 @@ class ModelWallClockTimeout(httpx.ReadTimeout):def _safe_error(exc: BaseException) -> str:+ if isinstance(exc, ModelFirstOutputTimeout):+ return "Local model never started producing output"if isinstance(exc, ModelOutputIdleTimeout):return "Local model stopped producing output before completion"if isinstance(exc, ModelWallClockTimeout):@@ -1623,11 +1637,55 @@ class ResearchSupervisor:"research.api_key_cleanup_failed run_id=%s", run["id"], exc_info = True)+ @staticmethod+ def _absorb_late_task(run_id: str, what: str, task: asyncio.Task) -> None:+ """Retrieve the outcome of a task that outlived the cleanup bound."""+ if task.cancelled():+ return+ error = task.exception()+ if error is not None:+ logger.warning(+ "research.%s_late_cleanup_failed run_id=%s", what, run_id, exc_info = error+ )++ def _absorb_when_done(self, run_id: str, task: asyncio.Task, what: str) -> None:+ """Arrange for a task still running past cleanup to have its outcome retrieved."""+ if task.done():+ self._absorb_late_task(run_id, what, task)+ return+ task.add_done_callback(lambda finished: self._absorb_late_task(run_id, what, finished))++ async def _discard_task(self, run_id: str, task: asyncio.Task, what: str) -> None:+ """Cancel a pending task and absorb its outcome, without waiting forever.++ Awaiting it keeps a late error from surfacing as an unretrieved task exception;+ bounding the wait keeps an iterator that declines cancellation from pinning the+ caller here, and swallowing only its own outcome keeps the real error intact.+ """+ task.cancel()+ try:+ await asyncio.wait({task}, timeout = _STREAM_CLEANUP_TIMEOUT_SECONDS)+ except asyncio.CancelledError:+ # Must keep propagating, but the child outlives this frame, so hand it over first.+ self._absorb_when_done(run_id, task, what)+ raise+ if not task.done():+ logger.warning("research.%s_cleanup_timed_out run_id=%s", what, run_id)+ # Bound expired but the task lives on: absorb its outcome when it cooperates.+ self._absorb_when_done(run_id, task, what)+ return+ try:+ task.result()+ except (asyncio.CancelledError, StopAsyncIteration):+ pass+ except Exception:+ logger.warning("research.%s_cleanup_failed run_id=%s", what, run_id, exc_info = True)+async def _iter_stream_lines(self,run_id: str,response: httpx.Response,- semantic_deadline: Callable[[], float | None] | None = None,+ semantic_deadline: Callable[[], tuple[float, type[BaseException]] | None] | None = None,) -> AsyncIterator[str]:iterator = response.aiter_lines().__aiter__()@@ -1637,36 +1695,39 @@ class ResearchSupervisor:deadline = semantic_deadline()if deadline is None:return 0.2- remaining = deadline - asyncio.get_running_loop().time()+ at, expired = deadline+ remaining = at - asyncio.get_running_loop().time()if remaining > 0:return min(0.2, remaining)- raise ModelOutputIdleTimeout("Local model stopped producing output")+ # Named by the caller, so a first-output deadline is never reported as a stall.+ raise expired()while True:+ if self._cancel_event(run_id).is_set():+ await self._check_active(run_id)timeout = wait_timeout()line_task = asyncio.create_task(anext(iterator))+ discarded = Falsetry:while not line_task.done():await asyncio.wait({line_task}, timeout = timeout)if self._cancel_event(run_id).is_set():- line_task.cancel()- try:- await line_task- except asyncio.CancelledError:- pass+ # Set first: the finally must not spend the bound on it again.+ discarded = True+ await self._discard_task(run_id, line_task, "stream_iterator")await self._check_active(run_id)+ # A line that arrived during the wait is earned; recomputing the+ # deadline first would let an expiry in the same turn discard it.+ if line_task.done():+ breaktimeout = wait_timeout()try:line = line_task.result()except StopAsyncIteration:returnfinally:- if not line_task.done():- line_task.cancel()- try:- await line_task- except asyncio.CancelledError:- pass+ if not discarded and not line_task.done():+ await self._discard_task(run_id, line_task, "stream_iterator")yield lineasync def _stream_completion(@@ -1722,6 +1783,7 @@ class ResearchSupervisor:last_progress_flush = asyncio.get_running_loop().time()finish_reason: str | None = Nonesemantic_output_at: float | None = None+ first_output_deadline: float | None = Noneasync def flush_progress() -> None:nonlocal pending_report, pending_reasoning, pending_reasoning_offset@@ -1782,13 +1844,27 @@ class ResearchSupervisor:try:model_timeout = float(config["budgets"]["modelTimeoutSeconds"])+ # Configurable, capped by the run's wall clock; legacy runs use the default.+ first_output_budget = min(+ float(+ config["budgets"].get(+ "firstOutputTimeoutSeconds", _MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS+ )+ ),+ model_timeout,+ )timeout = httpx.Timeout(model_timeout)loop = asyncio.get_running_loop()- def semantic_deadline() -> float | None:+ def semantic_deadline() -> tuple[float, type[BaseException]] | None:if semantic_output_at is None:- return None- return semantic_output_at + _MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS+ if first_output_deadline is None:+ return None+ return first_output_deadline, ModelFirstOutputTimeout+ return (+ semantic_output_at + _MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS,+ ModelOutputIdleTimeout,+ )async with (_wall_clock_timeout(model_timeout),@@ -1796,6 +1872,7 @@ class ResearchSupervisor:):response: httpx.Response | None = Nonesend_task: asyncio.Task | None = None+ send_discarded = Falsemodel_waits = 0attempt = 0try:@@ -1808,17 +1885,18 @@ class ResearchSupervisor:)try:send_task = asyncio.create_task(client.send(request, stream = True))+ # A retry builds a fresh task, so the guard starts over with it.+ send_discarded = Falsewhile not send_task.done():await asyncio.wait({send_task}, timeout = 0.2)if self._cancel_event(run["id"]).is_set():- send_task.cancel()- try:- await send_task- except asyncio.CancelledError:- pass+ # Set first: a send outlasting the bound is not waited on twice.+ send_discarded = True+ await self._discard_task(run["id"], send_task, "send")await self._check_active(run["id"])response = await send_taskresponse.raise_for_status()+ first_output_deadline = loop.time() + first_output_budgetbreakexcept (httpx.TransportError, httpx.HTTPStatusError) as exc:# Only reachable before a body byte is touched (the stream is consumed@@ -1857,6 +1935,13 @@ class ResearchSupervisor:if self._cancel_event(run["id"]).is_set():await self._check_active(run["id"])if not line.startswith("data:"):+ # Queueing has no timeout by design, so it is not charged: suspend+ # for it, and start the budget when the slot is granted. A plain+ # ": keep-alive" means a silent backend, which is what we bound.+ if line.startswith(_ADMISSION_WAIT_COMMENT):+ first_output_deadline = None+ elif line.startswith(_ADMISSION_DONE_COMMENT):+ first_output_deadline = loop.time() + first_output_budgetcontinuedata = line[5:].strip()if data == "[DONE]":@@ -1892,13 +1977,11 @@ class ResearchSupervisor:and asyncio.get_running_loop().time() - last_progress_flush >= 0.25):await flush_progress()+ if semantic_output_at is None:+ raise ModelFirstOutputTimeout("Local model never produced output")finally:- if send_task is not None and not send_task.done():- send_task.cancel()- try:- await send_task- except asyncio.CancelledError:- pass+ if send_task is not None and not send_discarded and not send_task.done():+ await self._discard_task(run["id"], send_task, "send")if (response is Noneand send_task is not Nonediff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 3a8127ddb42..d9e2916fb83 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -1129,6 +1129,10 @@ _STREAM_DISCONNECT_POLL_TIMEOUT_S = 0.25_OPENAI_PASSTHROUGH_PREHEADER_STATUS_WINDOW_S = 0.1_OPENAI_PASSTHROUGH_PENDING_RESPONSE_KEEPALIVE_S = 5.0_OPENAI_PASSTHROUGH_SSE_KEEPALIVE = ": keep-alive\n\n"+# Lets a client tell "queued" from "backend silent"; SSE comments, so readers ignore both.+_OPENAI_ADMISSION_SSE_WAIT = ": admission-wait\n\n"+# Paired with the above: the slot is ours, so a suspended client clock starts now.+_OPENAI_ADMISSION_SSE_DONE = ": admission-done\n\n"_OPENAI_LLAMA_ADMISSION_POLL_S = 0.25# Cap on waiting for a cancelled teardown task. Request.is_disconnected() can swallow# cancel() (#7617), so teardown abandons the task rather than hold the response, and@@ -1365,6 +1369,8 @@ async def _openai_admission_wait_stream_chunks()deadline = None if config.queue_timeout_s is None else time.monotonic() + config.queue_timeout_skeepalive_interval_s = max(0.001, config.keepalive_interval_s)+ # At once, not after a full interval: a caller must not wait one out to learn it queued.+ yield _OPENAI_ADMISSION_SSE_WAITnext_keepalive_at = time.monotonic() + keepalive_interval_stry:while True:@@ -1375,6 +1381,7 @@ async def _openai_admission_wait_stream_chunks()lease = reservation.lease_nowait()if lease is not None:+ yield _OPENAI_ADMISSION_SSE_DONEyield leasereturn@@ -1391,6 +1398,7 @@ async def _openai_admission_wait_stream_chunks(except asyncio.TimeoutError:lease = Noneif lease is not None:+ yield _OPENAI_ADMISSION_SSE_DONEyield leasereturnawait _raise_if_openai_admission_cancelled(@@ -1401,7 +1409,7 @@ async def _openai_admission_wait_stream_chunks(now = time.monotonic()if now >= next_keepalive_at:next_keepalive_at = now + keepalive_interval_s- yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE+ yield _OPENAI_ADMISSION_SSE_WAITexcept asyncio.CancelledError:reservation.cancel()raisediff --git a/studio/backend/routes/research_runs.py b/studio/backend/routes/research_runs.pyindex ae7239d090a..77378ade221 100644--- a/studio/backend/routes/research_runs.py+++ b/studio/backend/routes/research_runs.py@@ -245,6 +245,7 @@ def _sanitize_config(payload: CreateResearchRun, thread: dict) -> dict:"maxSources": 40,"modelTimeoutSeconds": 900,"toolTimeoutSeconds": 120,+ "firstOutputTimeoutSeconds": 120,}for key, value in (payload.budgets or {}).items():if key not in budgets:@@ -255,6 +256,8 @@ def _sanitize_config(payload: CreateResearchRun, thread: dict) -> dict:"maxSources": (1, 100),"modelTimeoutSeconds": (10, 3600),"toolTimeoutSeconds": (5, 600),+ # Same range as its parent: slow CPU and offloaded models need minutes to first token.+ "firstOutputTimeoutSeconds": (10, 3600),}for key, (minimum, maximum) in limits.items():if not minimum <= budgets[key] <= maximum:diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.pyindex e5a489d6fd7..0d4692c63a4 100644--- a/studio/backend/tests/test_openai_tool_passthrough.py+++ b/studio/backend/tests/test_openai_tool_passthrough.py@@ -2323,7 +2323,7 @@ class TestGgufVisionToolRouting:iterator = response.body_iteratortry:chunk = await asyncio.wait_for(iterator.__anext__(), timeout = 0.2)- assert chunk == ": keep-alive\n\n"+ assert chunk == ": admission-wait\n\n"snapshot = queue.snapshot()assert snapshot.active == 1assert snapshot.queued == 1@@ -2512,7 +2512,7 @@ class TestGgufVisionToolRouting:iterator = response.body_iteratortry:chunk = await asyncio.wait_for(iterator.__anext__(), timeout = 0.2)- assert chunk == ": keep-alive\n\n"+ assert chunk == ": admission-wait\n\n"snapshot = queue.snapshot()assert snapshot.active == 1assert snapshot.queued == 1@@ -5168,10 +5168,15 @@ class TestApiMonitorProviderAndCompletionStreams:iterator = response.body_iteratortry:chunk = await asyncio.wait_for(iterator.__anext__(), timeout = 0.2)- assert chunk == ": keep-alive\n\n"+ assert chunk == ": admission-wait\n\n"assert cancel_id in inf_mod._CANCEL_REGISTRYblocker.release()+ # The lease is announced before handover, so drain that marker first.+ assert (+ await asyncio.wait_for(iterator.__anext__(), timeout = 1.0)+ == ": admission-done\n\n"+ )pending = asyncio.create_task(iterator.__anext__())for _ in range(100):if "body" in body_holder:@@ -5275,10 +5280,15 @@ class TestApiMonitorProviderAndCompletionStreams:iterator = response.body_iteratortry:chunk = await asyncio.wait_for(iterator.__anext__(), timeout = 0.2)- assert chunk == ": keep-alive\n\n"+ assert chunk == ": admission-wait\n\n"blocker.release()- first = await asyncio.wait_for(iterator.__anext__(), timeout = 0.2)+ # The lease is announced before handover, so the payload is the next chunk.+ assert (+ await asyncio.wait_for(iterator.__anext__(), timeout = 1.0)+ == ": admission-done\n\n"+ )+ first = await asyncio.wait_for(iterator.__anext__(), timeout = 1.0)assert "hello" in firstpending = asyncio.create_task(iterator.__anext__())@@ -5454,7 +5464,7 @@ class TestApiMonitorProviderAndCompletionStreams:iterator = response.body_iteratortry:chunk = await asyncio.wait_for(iterator.__anext__(), timeout = 0.2)- assert chunk == ": keep-alive\n\n"+ assert chunk == ": admission-wait\n\n"snapshot = queue.snapshot()assert snapshot.active == 1assert snapshot.queued == 1@@ -6997,7 +7007,7 @@ class TestResponsesChatTemplateKwargs:iterator = response.body_iteratortry:chunk = await asyncio.wait_for(iterator.__anext__(), timeout = 0.2)- assert chunk == ": keep-alive\n\n"+ assert chunk == ": admission-wait\n\n"snapshot = queue.snapshot()assert snapshot.active == 1assert snapshot.queued == 1diff --git a/studio/backend/tests/test_research_runs_hardening.py b/studio/backend/tests/test_research_runs_hardening.pyindex c7826dc5cab..75198e493c6 100644--- a/studio/backend/tests/test_research_runs_hardening.py+++ b/studio/backend/tests/test_research_runs_hardening.py@@ -885,6 +885,496 @@ def test_stream_completion_times_out_when_output_stalls(monkeypatch):_run_stream(supervisor, timeout_seconds = 1.0)+def test_stream_completion_times_out_when_output_never_starts(monkeypatch):+ """#7964: headers arrive, then the backend goes silent. Silence is the fault signal."""+ monkeypatch.setattr(research_runs, "_MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS", 0.05)++ class _SilentStream:+ status_code = 200++ def raise_for_status(self):+ return self++ async def aclose(self):+ return None++ async def aiter_lines(self):+ await asyncio.sleep(30)+ yield "data: [DONE]"++ _install_fake_client(monkeypatch, [_SilentStream()])+ supervisor = _make_supervisor(_noop_check_active)++ with pytest.raises(research_runs.ModelFirstOutputTimeout):+ _run_stream(supervisor, timeout_seconds = 1.0)+++def test_admission_keepalives_do_not_spend_the_first_output_budget(monkeypatch):+ """A run queued behind another generation must still be served, not failed.++ The admission queue has no default timeout and marks the wait with its own SSE+ comment, so a queued Deep Research run outlives any fixed first-output budget+ through no fault of the model.+ """+ monkeypatch.setattr(research_runs, "_MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS", 0.05)++ class _QueuedThenServedStream:+ status_code = 200++ def raise_for_status(self):+ return self++ async def aclose(self):+ return None++ async def aiter_lines(self):+ # Ten periods, each under the budget but far over it in total; none may end the run.+ for _ in range(10):+ await asyncio.sleep(0.02)+ yield ": admission-wait"+ yield 'data: {"choices":[{"delta":{"content":"report"}}]}'+ yield 'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}'+ yield "data: [DONE]"++ _install_fake_client(monkeypatch, [_QueuedThenServedStream()])+ supervisor = _make_supervisor(_noop_check_active)++ assert _run_stream(supervisor, timeout_seconds = 5.0) == ("report", "", "stop")+++def _comment_only_stream(comment: str):+ class _CommentOnly:+ status_code = 200++ def raise_for_status(self):+ return self++ async def aclose(self):+ return None++ async def aiter_lines(self):+ while True:+ await asyncio.sleep(0.01)+ yield comment++ return _CommentOnly()+++def test_plain_keepalives_mean_a_silent_backend_and_spend_the_budget(monkeypatch):+ """A backend that only ever sends keepalives is stalled, whatever the phase.++ routes/inference.py sends the plain comment while llama-server is silent, both+ before its headers and mid-generation, so it must not defer the budget.+ """+ monkeypatch.setattr(research_runs, "_MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS", 0.05)+ _install_fake_client(monkeypatch, [_comment_only_stream(": keep-alive")])+ supervisor = _make_supervisor(_noop_check_active)++ started = time.monotonic()+ with pytest.raises(research_runs.ModelFirstOutputTimeout):+ _run_stream(supervisor, timeout_seconds = 30.0)+ assert time.monotonic() - started < 5.0, "must end on the budget, not the wall clock"+++def test_the_queue_wait_is_not_charged_to_the_model_budget(monkeypatch):+ """The tail of a queue wait must not eat into the model's own budget.++ Markers are interval-spaced, so anchoring the deadline to the last one charges up to+ a full interval of queueing against the model. The wait is suspended instead, and the+ budget starts when the queue says the slot is ours.+ """+ monkeypatch.setattr(research_runs, "_MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS", 0.3)++ class _QueuedThenAdmitted:+ status_code = 200++ def raise_for_status(self):+ return self++ async def aclose(self):+ return None++ async def aiter_lines(self):+ # One marker, then a queue wait far longer than the budget between markers.+ yield ": admission-wait"+ await asyncio.sleep(1.0)+ yield ": admission-done"+ yield 'data: {"choices":[{"delta":{"content":"report"}}]}'+ yield 'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}'+ yield "data: [DONE]"++ _install_fake_client(monkeypatch, [_QueuedThenAdmitted()])+ supervisor = _make_supervisor(_noop_check_active)++ assert _run_stream(supervisor, timeout_seconds = 10.0) == ("report", "", "stop")+++def test_the_budget_starts_when_admission_ends(monkeypatch):+ """Once the slot is granted, a silent model is on its own budget again."""+ monkeypatch.setattr(research_runs, "_MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS", 0.1)++ class _AdmittedThenSilent:+ status_code = 200++ def raise_for_status(self):+ return self++ async def aclose(self):+ return None++ async def aiter_lines(self):+ yield ": admission-wait"+ yield ": admission-done"+ await asyncio.sleep(30)+ yield "data: [DONE]"++ _install_fake_client(monkeypatch, [_AdmittedThenSilent()])+ supervisor = _make_supervisor(_noop_check_active)++ started = time.monotonic()+ with pytest.raises(research_runs.ModelFirstOutputTimeout):+ _run_stream(supervisor, timeout_seconds = 30.0)+ assert time.monotonic() - started < 5.0, "the budget must run from admission end"+++def test_endless_admission_waits_still_end_at_the_wall_clock(monkeypatch):+ """Deferring on the admission marker must not make a stream unbounded."""+ monkeypatch.setattr(research_runs, "_MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS", 0.05)+ _install_fake_client(monkeypatch, [_comment_only_stream(": admission-wait")])+ supervisor = _make_supervisor(_noop_check_active)++ with pytest.raises(research_runs.ModelWallClockTimeout):+ _run_stream(supervisor, timeout_seconds = 0.4)+++def test_a_task_outliving_cleanup_has_its_outcome_absorbed(monkeypatch):+ """A task that ignores the cleanup bound must not later log an unretrieved exception."""+ monkeypatch.setattr(research_runs, "_STREAM_CLEANUP_TIMEOUT_SECONDS", 0.05)+ supervisor = _make_supervisor(_noop_check_active)++ absorbed = []+ real_absorb = research_runs.ResearchSupervisor._absorb_late_task++ def _spy(run_id, what, task):+ absorbed.append(what)+ return real_absorb(run_id, what, task)++ monkeypatch.setattr(research_runs.ResearchSupervisor, "_absorb_late_task", staticmethod(_spy))++ async def _drive():+ gate = asyncio.get_running_loop().create_future()++ async def _stubborn():+ try:+ await asyncio.sleep(10)+ except asyncio.CancelledError:+ pass # declines cancellation, then keeps running on its own terms+ await gate+ raise RuntimeError("late failure")++ task = asyncio.create_task(_stubborn())+ await asyncio.sleep(0)+ await supervisor._discard_task("run-1", task, "stream_iterator")+ assert not task.done(), "the bound must have expired with the task still running"++ gate.set_result(None)+ await asyncio.sleep(0.05)+ assert task.done()+ # Retrieved by the callback; asyncio only warns for exceptions never retrieved.+ assert absorbed == ["stream_iterator"], f"outcome was not absorbed: {absorbed}"+ assert isinstance(task.exception(), RuntimeError)++ asyncio.run(_drive())+++def test_first_output_budget_is_configurable_and_clamped(monkeypatch):+ """The budget is a run budget, not a constant, and never outlives its own wall clock."""+ monkeypatch.setattr(research_runs, "_MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS", 0.05)++ def _budget(budgets):+ model_timeout = float(budgets["modelTimeoutSeconds"])+ return min(+ float(+ budgets.get(+ "firstOutputTimeoutSeconds",+ research_runs._MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS,+ )+ ),+ model_timeout,+ )++ # A run created before this budget existed keeps the shipped default.+ assert _budget({"modelTimeoutSeconds": 900}) == 0.05+ # An explicit budget is honoured.+ assert _budget({"modelTimeoutSeconds": 900, "firstOutputTimeoutSeconds": 600}) == 600.0+ # And can never exceed the run's own wall clock.+ assert _budget({"modelTimeoutSeconds": 30, "firstOutputTimeoutSeconds": 600}) == 30.0+++def test_a_configured_first_output_budget_reaches_the_stream(monkeypatch):+ """The value in the run config, not the module constant, is what bounds the wait."""+ monkeypatch.setattr(research_runs, "_MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS", 30.0)+ _install_fake_client(monkeypatch, [_comment_only_stream(": keep-alive")])+ supervisor = _make_supervisor(_noop_check_active)++ run = _waiting_run(30.0)+ run["config"]["budgets"]["firstOutputTimeoutSeconds"] = 0.05++ started = time.monotonic()+ with pytest.raises(research_runs.ModelFirstOutputTimeout):+ asyncio.run(supervisor._stream_completion(run, [{"role": "user"}], report_progress = False))+ assert time.monotonic() - started < 5.0, "the configured budget must win over the constant"+++def test_stall_keepalives_after_the_first_frame_do_not_renew_the_budget(monkeypatch):+ """A wedged local GGUF model must still time out.++ routes/inference.py sends the role frame once generation starts and then a+ ": keep-alive" every 15 s while next(gen) stays silent. A role-only delta is not+ semantic output, so those comments must not keep renewing the first-output budget.+ """+ monkeypatch.setattr(research_runs, "_MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS", 0.2)++ class _RoleThenWedged:+ status_code = 200++ def raise_for_status(self):+ return self++ async def aclose(self):+ return None++ async def aiter_lines(self):+ yield 'data: {"choices":[{"delta":{"role":"assistant"}}]}'+ while True:+ await asyncio.sleep(0.01)+ yield ": keep-alive"++ _install_fake_client(monkeypatch, [_RoleThenWedged()])+ supervisor = _make_supervisor(_noop_check_active)++ started = time.monotonic()+ with pytest.raises(research_runs.ModelFirstOutputTimeout):+ _run_stream(supervisor, timeout_seconds = 30.0)+ assert time.monotonic() - started < 5.0, "must end on the budget, not the wall clock"+++def test_outer_cancellation_still_hands_off_the_child_task(monkeypatch):+ """Shutdown or the wall clock must not strand the child with nobody reading it.++ _discard_task re-raises an outer cancellation, but the child outlives the frame+ either way, so its outcome still has to be claimed before the caller leaves.+ """+ monkeypatch.setattr(research_runs, "_STREAM_CLEANUP_TIMEOUT_SECONDS", 30.0)+ absorbed = []+ real_absorb = research_runs.ResearchSupervisor._absorb_late_task++ def _spy(run_id, what, task):+ absorbed.append(what)+ return real_absorb(run_id, what, task)++ monkeypatch.setattr(research_runs.ResearchSupervisor, "_absorb_late_task", staticmethod(_spy))+ supervisor = _make_supervisor(_noop_check_active)++ async def _drive():+ gate = asyncio.get_running_loop().create_future()++ async def _stubborn():+ try:+ await asyncio.sleep(10)+ except asyncio.CancelledError:+ pass # declines the first cancellation+ await gate+ raise RuntimeError("late failure")++ child = asyncio.create_task(_stubborn())+ await asyncio.sleep(0)+ cleanup = asyncio.create_task(supervisor._discard_task("run-1", child, "stream_iterator"))+ await asyncio.sleep(0.05)+ # Cancel the cleanup itself, standing in for the wall clock or a shutdown.+ cleanup.cancel()+ with pytest.raises(asyncio.CancelledError):+ await cleanup++ gate.set_result(None)+ await asyncio.sleep(0.05)+ assert child.done()+ assert absorbed == ["stream_iterator"], f"child was stranded: {absorbed}"+ assert isinstance(child.exception(), RuntimeError)++ asyncio.run(_drive())+++def test_a_cancelled_send_is_only_discarded_once(monkeypatch):+ """The pre-header send needs the same single-cleanup guarantee as the iterator.++ A send that declines cancellation past the bound would otherwise be waited on again+ by the enclosing finally, doubling how long a user cancellation takes.+ """+ monkeypatch.setattr(research_runs, "_STREAM_CLEANUP_TIMEOUT_SECONDS", 0.2)+ discards = []+ real_discard = research_runs.ResearchSupervisor._discard_task++ async def _counting_discard(self, run_id, task, what):+ discards.append(what)+ return await real_discard(self, run_id, task, what)++ monkeypatch.setattr(research_runs.ResearchSupervisor, "_discard_task", _counting_discard)++ supervisor = _make_supervisor(_noop_check_active)+ run = _waiting_run(30.0)++ class _StubbornClient:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *exc_info):+ return False++ def build_request(self, *args, **kwargs):+ return SimpleNamespace(headers = {})++ async def send(+ self,+ request,+ stream = False,+ ):+ supervisor._cancel_event(run["id"]).set()+ try:+ await asyncio.sleep(10)+ except asyncio.CancelledError:+ await asyncio.sleep(10) # declines cancellation past the bound++ monkeypatch.setattr(research_runs.httpx, "AsyncClient", lambda **kwargs: _StubbornClient())++ async def _cancelled(run_id):+ if supervisor._cancel_event(run_id).is_set():+ raise research_runs.RunCancelled()++ supervisor._check_active = _cancelled++ started = time.monotonic()+ with pytest.raises(research_runs.RunCancelled):+ asyncio.run(supervisor._stream_completion(run, [{"role": "user"}], report_progress = False))+ elapsed = time.monotonic() - started+ assert [w for w in discards if w == "send"] == ["send"], f"discards: {discards}"+ assert elapsed < 1.0, f"cancellation took {elapsed:.2f}s, more than one cleanup bound"+++def test_a_cancelled_stream_iterator_is_only_discarded_once(monkeypatch):+ """Cancellation must stay inside one cleanup bound, not two.++ An iterator that outlasts _STREAM_CLEANUP_TIMEOUT_SECONDS leaves the task pending,+ and cleaning it up a second time in the finally would double the advertised wait.+ """+ monkeypatch.setattr(research_runs, "_STREAM_CLEANUP_TIMEOUT_SECONDS", 0.2)+ discards = []+ real_discard = research_runs.ResearchSupervisor._discard_task++ async def _counting_discard(self, run_id, task, what):+ discards.append(what)+ return await real_discard(self, run_id, task, what)++ monkeypatch.setattr(research_runs.ResearchSupervisor, "_discard_task", _counting_discard)++ supervisor = _make_supervisor(_noop_check_active)+ run = _waiting_run(30.0)++ class _UncancellableStream:+ status_code = 200++ def raise_for_status(self):+ return self++ async def aclose(self):+ return None++ async def aiter_lines(self):+ # Cancel once the stream loop owns the task, not the send phase.+ supervisor._cancel_event(run["id"]).set()+ while True:+ try:+ await asyncio.sleep(30)+ except asyncio.CancelledError:+ # Swallows cancellation: exactly what the cleanup bound exists for.+ await asyncio.sleep(30)+ yield ": keep-alive"++ _install_fake_client(monkeypatch, [_UncancellableStream()])++ async def _cancelled(run_id):+ if supervisor._cancel_event(run_id).is_set():+ raise research_runs.RunCancelled()++ supervisor._check_active = _cancelled++ started = time.monotonic()+ with pytest.raises(research_runs.RunCancelled):+ asyncio.run(supervisor._stream_completion(run, [{"role": "user"}], report_progress = False))+ elapsed = time.monotonic() - started+ iterator_discards = [w for w in discards if w == "stream_iterator"]+ assert len(iterator_discards) == 1, f"discarded {len(iterator_discards)} times: {discards}"+ assert elapsed < 1.0, f"cancellation took {elapsed:.2f}s, more than one cleanup bound"+++def test_stream_completion_first_output_timeout_survives_iterator_cleanup(monkeypatch):+ monkeypatch.setattr(research_runs, "_MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS", 0.01)++ class _BrokenSilentStream:+ status_code = 200++ def raise_for_status(self):+ return self++ async def aclose(self):+ return None++ async def aiter_lines(self):+ try:+ await asyncio.Event().wait()+ yield ""+ except asyncio.CancelledError as exc:+ raise httpx.ReadError("cleanup failed") from exc++ _install_fake_client(monkeypatch, [_BrokenSilentStream()])+ supervisor = _make_supervisor(_noop_check_active)++ with pytest.raises(research_runs.ModelFirstOutputTimeout):+ _run_stream(supervisor, timeout_seconds = 1.0)++[email protected]("body", ("data: [DONE]\n\n", ""))+def test_stream_completion_rejects_zero_output_terminal_stream(monkeypatch, body):+ _install_fake_client(monkeypatch, [_response(200, body = body)])+ supervisor = _make_supervisor(_noop_check_active)++ with pytest.raises(research_runs.ModelFirstOutputTimeout):+ _run_stream(supervisor, timeout_seconds = 1.0)+++def test_stream_cancellation_wins_at_first_output_deadline():+ async def _cancelled(run_id: str) -> None:+ raise RunCancelled()++ async def run():+ supervisor = _make_supervisor(_cancelled)+ supervisor._cancel_event("run-1").set()+ response = _response(200, body = "")++ def expired_deadline() -> float:+ raise research_runs.ModelFirstOutputTimeout()++ iterator = supervisor._iter_stream_lines(+ "run-1",+ response,+ expired_deadline,+ )+ await anext(iterator)++ with pytest.raises(RunCancelled):+ asyncio.run(run())++def test_stream_cleanup_error_does_not_replace_output_stall(monkeypatch):monkeypatch.setattr(research_runs, "_MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS", 0.05)@@ -938,7 +1428,9 @@ def test_stream_completion_semantic_output_resets_the_idle_timeout(monkeypatch):assert _run_stream(supervisor, timeout_seconds = 1.0) == ("report", "thinking", "stop")-def test_stream_completion_does_not_apply_idle_timeout_during_prefill(monkeypatch):+def test_stream_completion_allows_output_before_first_output_timeout(monkeypatch):+ # Clear of the 0.10 s prefill: a 15.625 ms tick would stretch it to 0.15625 s.+ monkeypatch.setattr(research_runs, "_MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS", 1.0)monkeypatch.setattr(research_runs, "_MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS", 0.03)class _SlowPrefillStream:@@ -964,6 +1456,81 @@ def test_stream_completion_does_not_apply_idle_timeout_during_prefill(monkeypatcassert _run_stream(supervisor, timeout_seconds = 1.0) == ("report", "", "stop")+def test_first_output_deadline_disarms_once_output_starts(monkeypatch):+ """The budget bounds the wait for the FIRST token, never total generation time."""+ monkeypatch.setattr(research_runs, "_MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS", 0.15)+ monkeypatch.setattr(research_runs, "_MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS", 5.0)++ class _LongGenerationStream:+ status_code = 200++ def raise_for_status(self):+ return self++ async def aclose(self):+ return None++ async def aiter_lines(self):+ await asyncio.sleep(0.05)+ yield 'data: {"choices":[{"delta":{"content":"start"}}]}'+ for index in range(12):+ await asyncio.sleep(0.05)+ yield 'data: {"choices":[{"delta":{"content":" w%d"}}]}' % index+ yield 'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}'+ yield "data: [DONE]"++ _install_fake_client(monkeypatch, [_LongGenerationStream()])+ supervisor = _make_supervisor(_noop_check_active)++ report, _reasoning, finish_reason = _run_stream(supervisor, timeout_seconds = 30.0)+ assert finish_reason == "stop"+ assert report.startswith("start w0 w1")+ assert report.endswith("w11")+++def test_reasoning_only_prefix_disarms_the_first_output_deadline(monkeypatch):+ """A thinking model may reason for longer than the budget before any content."""+ monkeypatch.setattr(research_runs, "_MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS", 0.15)+ monkeypatch.setattr(research_runs, "_MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS", 5.0)+ # Reasoning deltas flush to storage whatever report_progress says.+ monkeypatch.setattr(research_runs.db, "append_worker_event", lambda *args, **kwargs: 1)++ class _LongThinkStream:+ status_code = 200++ def raise_for_status(self):+ return self++ async def aclose(self):+ return None++ async def aiter_lines(self):+ await asyncio.sleep(0.05)+ for index in range(10):+ yield 'data: {"choices":[{"delta":{"reasoning_content":"t%d "}}]}' % index+ await asyncio.sleep(0.05)+ yield 'data: {"choices":[{"delta":{"content":"answer"}}]}'+ yield 'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}'+ yield "data: [DONE]"++ _install_fake_client(monkeypatch, [_LongThinkStream()])+ supervisor = _make_supervisor(_noop_check_active)++ report, reasoning, _finish = _run_stream(supervisor, timeout_seconds = 30.0)+ assert report == "answer"+ assert reasoning.startswith("t0 ")+++def test_shipped_stream_deadline_constants_are_pinned():+ """Every other test monkeypatches these, so nothing else would notice a change."""+ assert research_runs._MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS == 120.0+ assert research_runs._MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS == 120.0+ assert (+ research_runs._MODEL_FIRST_OUTPUT_TIMEOUT_SECONDS+ >= research_runs._MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS+ )++def test_stream_completion_counts_whitespace_tokens_as_output(monkeypatch):monkeypatch.setattr(research_runs, "_MODEL_OUTPUT_IDLE_TIMEOUT_SECONDS", 0.15)@@ -1021,6 +1588,10 @@ def test_stream_completion_stops_at_done_even_if_socket_stays_open(monkeypatch):@pytest.mark.parametrize(("exc", "message"),(+ (+ research_runs.ModelFirstOutputTimeout("first"),+ "Local model never started producing output",+ ),(research_runs.ModelOutputIdleTimeout("idle"),"Local model stopped producing output before completion",diff --git a/studio/backend/tests/test_research_runs_storage.py b/studio/backend/tests/test_research_runs_storage.pyindex a8d097ae0f4..8d1be54f330 100644--- a/studio/backend/tests/test_research_runs_storage.py+++ b/studio/backend/tests/test_research_runs_storage.py@@ -1313,6 +1313,7 @@ def test_research_budget_defaults_support_long_runs():"maxSources": 40,"modelTimeoutSeconds": 900,"toolTimeoutSeconds": 120,+ "firstOutputTimeoutSeconds": 120,}assert config["instructions"] == "Answer in Spanish."ResearchPlan(@@ -1334,6 +1335,7 @@ def test_research_budget_ceilings_allow_depth_but_remain_bounded():"maxSources": 100,"modelTimeoutSeconds": 3600,"toolTimeoutSeconds": 600,+ "firstOutputTimeoutSeconds": 3600,},)assert _sanitize_config(payload, {"modelId": "local-model"})["budgets"] == payload.budgetsdiff --git a/studio/frontend/src/features/chat/types/research.ts b/studio/frontend/src/features/chat/types/research.tsindex 5924f213b8d..8718a625d9d 100644--- a/studio/frontend/src/features/chat/types/research.ts+++ b/studio/frontend/src/features/chat/types/research.ts@@ -88,6 +88,8 @@ export interface ResearchBudgets {maxSources: number;modelTimeoutSeconds: number;toolTimeoutSeconds: number;+ // Optional: runs created before this budget existed do not carry it.+ firstOutputTimeoutSeconds?: number;}export interface ResearchWebsitePolicy {