From 81a9dc9c59c1ea071f3a7efeb2e6b5560db11bf1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 08:29:53 +0000 Subject: [PATCH 1/3] Stop analysis outrunning the serverless function limit A real job (ResNet) sat in "analyzing" for 83 minutes. Each analyze call on the free Nemotron endpoint ran past Vercel's 300s function limit and was killed mid-call, so no error handler ran; the attempt counter climbed to 5 (max 3) without the job ever failing, and every advance restarted the same doomed call. The HTTP read timeout never fired because OpenRouter answers 200 at once and keeps a slow non-streaming request alive with periodic bytes. Measured from a Vercel Sandbox on the free endpoint (~86 tokens/s), the same 67k-character analysis took 112s with reasoning (7,272 reasoning tokens) and 30s without. - Analysis no longer reasons (LLM_REASONING_ANALYZE=1 opts back in); diagram codegen still does. - Every long-context call is streamed and stopped at a wall-clock budget: LLM_CALL_TIMEOUT_S (120s) and never past the step's end plus the scene grace, which the stepper now hands the provider. A free model that misses it hands over to the next model in the chain; with too little time left no call starts at all. - Analysis asks for at most 12 concepts (LLM_ANALYSIS_ITEMS), bounding the reply. - The stepper fails a job whose analyze attempts died without recording a failure, instead of looping forever. - ProviderErrors raised while sending pass through _chat unchanged rather than being rewrapped as a generic retryable failure. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BgiEmhLGtyG2FWJkiiwD1M --- .env.example | 5 +- README.md | 14 +- arcvisual/config.py | 22 ++- arcvisual/providers/longcontext_provider.py | 121 ++++++++++++++- arcvisual/providers/openai_compat.py | 13 +- arcvisual/render/stepper.py | 41 ++++- tests/test_longcontext.py | 157 +++++++++++++++++++- tests/test_serverless.py | 52 +++++++ 8 files changed, 409 insertions(+), 16 deletions(-) diff --git a/.env.example b/.env.example index 7a4dba6..d1ccceb 100644 --- a/.env.example +++ b/.env.example @@ -85,7 +85,10 @@ CEREBRAS_API_KEY= # LLM_MAX_TOKENS=16384 # reasoning models bill thinking as output # LLM_JSON_SCHEMA=1 # 0 = prompt the schema instead of enforcing it # LLM_REASONING_EFFORT= # sent as reasoning_effort when set -# LLM_REASONING=1 # OpenRouter: reasoning {enabled: true}; 0 turns it off +# LLM_REASONING=1 # OpenRouter: reasoning {enabled: true} on diagram calls +# LLM_REASONING_ANALYZE=0 # also reason during analysis (slow: 112s vs 30s measured) +# LLM_CALL_TIMEOUT_S=120 # wall-clock cap per model call (replies are streamed) +# LLM_ANALYSIS_ITEMS=12 # concepts analysis asks for; bounds the reply's length # LLM_RATE_IN= / LLM_RATE_OUT= # USD per million tokens; empty = unattributed # Formula-chain scenes allowed per paper. Past this, transform_chain proposals are diff --git a/README.md b/README.md index 0ddee93..175c446 100644 --- a/README.md +++ b/README.md @@ -357,8 +357,18 @@ silently ignores it (an OpenRouter upstream) falls back to the prompted path for call rather than failing it. OpenRouter requests carry `require_parameters` so they are only routed to upstreams that honour the schema. -On OpenRouter the Nemotron free endpoint leads the chain and is asked to reason -(`reasoning: {"enabled": true}`; `LLM_REASONING=0` turns it off). Every pipeline call +On OpenRouter the Nemotron free endpoint leads the chain. It reasons while drawing +diagrams (`reasoning: {"enabled": true}`; `LLM_REASONING=0` turns it off) but not while +analysing the paper, unless `LLM_REASONING_ANALYZE=1`. Measured on the free endpoint +(~86 tokens/s), the same analysis took 112 s with reasoning and 30 s without, and the +real one with reasoning ran past Vercel's 300 s function limit. + +Every call is streamed and stopped at a wall-clock limit (`LLM_CALL_TIMEOUT_S`, +default 120 s, and never past the end of the current step). A plain read timeout +can't bound it: OpenRouter keeps a slow request alive with periodic bytes. A free +model that misses the limit hands over to the next model in the chain. If analysis +attempts keep dying without recording a failure, the job is failed after three +tries rather than retried forever. Every pipeline call is a single turn, so there are no `reasoning_details` to pass back. A free host that cannot enforce the schema answers 404 under `require_parameters`; that call falls back to prompted JSON on the same model. If the free endpoint is withdrawn, the call diff --git a/arcvisual/config.py b/arcvisual/config.py index 337f85e..18fe3e5 100644 --- a/arcvisual/config.py +++ b/arcvisual/config.py @@ -453,9 +453,22 @@ class LongContext: timeout_s: float = 300.0 #: Sent as ``reasoning_effort`` when set; empty omits the parameter. reasoning_effort: str = "" - #: OpenRouter only: send ``reasoning: {"enabled": true}``. A reasoning model plans - #: the layout of a diagram before writing it, which is the hard part of the job. + #: OpenRouter only: send ``reasoning: {"enabled": true}`` on CODEGEN calls. A + #: reasoning model plans the layout of a diagram before writing it, which is the + #: hard part of the job. reasoning: bool = False + #: Also reason during ANALYZE. Off by default: measured on the free Nemotron + #: endpoint (~86 tokens/s), a 67k-character analysis took 112s with reasoning + #: (7,272 reasoning tokens) and 30s without — and the real one, with a schema and + #: up to 40 concepts, ran past Vercel's 300s function limit every time. + reasoning_analyze: bool = False + #: Wall-clock ceiling on one model call, in seconds. A read timeout cannot bound + #: it: OpenRouter keeps a slow non-streaming request alive with periodic bytes, so + #: a call outlived the serverless function and was killed instead of failing. + call_timeout_s: float = 120.0 + #: Concepts to ask ANALYZE for. Bounds the reply, and with it the call's duration; + #: twelve covers the twelve-scene cap. + analysis_item_budget: int = 12 rate_in: float | None = None rate_out: float | None = None @@ -495,6 +508,11 @@ def long_context_from_env(preset: str, env=os.environ.get) -> LongContext: timeout_s=float(env("LLM_TIMEOUT_S") or 300), reasoning_effort=env("LLM_REASONING_EFFORT", "") or "", reasoning=_flag(env("LLM_REASONING"), base.reasoning), + reasoning_analyze=_flag(env("LLM_REASONING_ANALYZE"), False), + call_timeout_s=float(env("LLM_CALL_TIMEOUT_S") or LongContext.call_timeout_s), + analysis_item_budget=int( + env("LLM_ANALYSIS_ITEMS") or LongContext.analysis_item_budget + ), rate_in=_opt_float(env("LLM_RATE_IN")), rate_out=_opt_float(env("LLM_RATE_OUT")), ) diff --git a/arcvisual/providers/longcontext_provider.py b/arcvisual/providers/longcontext_provider.py index 01cda6f..1604135 100644 --- a/arcvisual/providers/longcontext_provider.py +++ b/arcvisual/providers/longcontext_provider.py @@ -26,8 +26,11 @@ from __future__ import annotations +import json import logging import re +import threading +import time from typing import Any from pydantic import BaseModel @@ -38,6 +41,7 @@ ModelUnavailable, ProviderError, ProviderNotConfigured, + RetryableProviderError, StructuredResult, Task, TextBlock, @@ -55,6 +59,9 @@ #: Model ids the server reported as gone, per process — shared across scene lanes. _UNAVAILABLE: set[str] = set() +#: Below this many seconds left there is no point starting a call: it cannot finish. +_MIN_CALL_S = 10.0 + class LongContextProvider(OpenAICompatProvider): name = "longcontext" @@ -82,6 +89,10 @@ def __init__( ) self._cfg = cfg self._http = client + #: time.monotonic() instant no call may run past; None = only call_timeout_s. + self._deadline: float | None = None + #: The task of the call in flight, per thread (scene lanes share a provider). + self._local = threading.local() # Reports read "openrouter" or "gemini", not a generic label: a cost anomaly # is investigated per host. self.name = cfg.preset if cfg.preset in LONG_CONTEXT_PRESETS else "longcontext" @@ -116,7 +127,7 @@ def _extra_payload(self, response_format: dict | None) -> dict[str, Any]: if self._cfg.preset != "openrouter": return {} extra: dict[str, Any] = {} - if self._cfg.reasoning: + if self._reasons(): # Every call here is a single turn, so there is no `reasoning_details` to # pass back: the model reasons, answers, and the next call starts fresh. extra["reasoning"] = {"enabled": True} @@ -126,6 +137,91 @@ def _extra_payload(self, response_format: dict | None) -> dict[str, Any]: extra["provider"] = {"require_parameters": True} return extra + def _reasons(self) -> bool: + """Reason on this call? Diagrams yes; analysis only when asked for.""" + if not self._cfg.reasoning: + return False + task = getattr(self._local, "task", None) + return task is not Task.CLASSIFY or self._cfg.reasoning_analyze + + def set_deadline(self, deadline: float | None) -> None: + """No model call may run past this ``time.monotonic()`` instant. + + The stepped deployment calls this with the end of its step: a call still + running when the platform kills the function never reaches an error handler, + so the job re-runs the same doomed call on every step, forever. + """ + self._deadline = deadline + + def _call_budget(self) -> float: + budget = self._cfg.call_timeout_s + if self._deadline is not None: + budget = min(budget, self._deadline - time.monotonic()) + return budget + + def _post(self, payload: dict[str, Any]) -> Any: + """Stream the reply and stop at a wall-clock budget. + + Non-streaming is unboundable here: OpenRouter answers 200 at once and keeps + the connection alive with periodic bytes until the model finishes, so the + HTTP read timeout never fires. Streaming yields a line at a time, and the + clock is checked on each one. + """ + model = payload.get("model", "") + budget = self._call_budget() + if budget < _MIN_CALL_S: + # Not retryable within this step: a retry would start with even less. + raise ProviderError( + f"{self.name}: only {max(budget, 0):.0f}s left in this step, too " + "little for another model call; the next step continues" + ) + client = self._client() + if not hasattr(client, "stream"): + return client.post("/chat/completions", json=payload) + started = time.monotonic() + with client.stream( + "POST", "/chat/completions", json={**payload, "stream": True} + ) as response: + if response.status_code != 200: + response.read() + return response + content: list[str] = [] + finish = None + usage: dict[str, Any] | None = None + for line in response.iter_lines(): + if time.monotonic() - started > budget: + self._too_slow(model, budget) + if not line.startswith("data:"): + continue # SSE comments are OpenRouter's keep-alives + data = line[5:].strip() + if data == "[DONE]": + break + chunk = json.loads(data) + if "error" in chunk: + error = chunk["error"] or {} + code = error.get("code") + return _Reply(code if isinstance(code, int) else 502, chunk) + usage = chunk.get("usage") or usage + for choice in chunk.get("choices") or []: + delta = choice.get("delta") or {} + if delta.get("content"): + content.append(delta["content"]) + finish = choice.get("finish_reason") or finish + message = {"content": "".join(content) if content else None} + return _Reply( + 200, + {"choices": [{"message": message, "finish_reason": finish}], "usage": usage}, + ) + + def _too_slow(self, model: str, budget: float) -> None: + if model.endswith(":free"): + # A free endpoint this slow now is no faster on the next attempt; the + # paid models behind it in the chain are the way to finish in time. + raise ModelUnavailable(model, f"no complete answer within {budget:.0f}s") + raise RetryableProviderError( + f"{self.name}: {model} gave no complete answer within {budget:.0f}s" + ) + def _model_exhausted(self, model: str, body: str) -> None: # OpenRouter caps ':free' models per day ("Rate limit exceeded: # free-models-per-day", ~50 requests without credits). Retrying cannot clear @@ -160,6 +256,7 @@ def _structured_with( max_tokens: int, max_attempts: int, ) -> StructuredResult: + self._local.task = task budget = self._budget(max_tokens, model, task.value) schema_key = (model, output_model.__name__, _schema_digest(output_model)) first: StructuredResult | None = None @@ -223,7 +320,7 @@ def capabilities(self) -> Capabilities: vision=False, cost_attributed=attributed, prompt_char_budget=self._cfg.prompt_char_budget, - analysis_item_budget=None, + analysis_item_budget=self._cfg.analysis_item_budget or None, analysis_passes=1, note=( f"{self.model_for(Task.CLASSIFY)} for analyze / " @@ -235,7 +332,12 @@ def capabilities(self) -> Capabilities: if self._cfg.json_schema else "JSON prompted and validated client-side. " ) - + ("Reasoning enabled. " if self._cfg.reasoning else "") + + ( + "Reasoning enabled for diagrams" + + (" and analysis. " if self._cfg.reasoning_analyze else ". ") + if self._cfg.reasoning + else "" + ) + (preset.note + " " if preset and preset.note else "") + ( "Cost attributed from LLM_RATE_IN/OUT." @@ -283,3 +385,16 @@ def _is_schema_refusal(exc: ProviderError) -> bool: return any(f"returned {code}" in text for code in (400, 422)) or ( "invalid JSON schema" in text ) + + +class _Reply: + """A response assembled from a stream, shaped like the httpx one `_chat` reads.""" + + def __init__(self, status_code: int, body: dict[str, Any]) -> None: + self.status_code = status_code + self._body = body + self.text = json.dumps(body) + self.headers: dict[str, str] = {} + + def json(self) -> dict[str, Any]: + return self._body diff --git a/arcvisual/providers/openai_compat.py b/arcvisual/providers/openai_compat.py index a4e5c46..b6f2b56 100644 --- a/arcvisual/providers/openai_compat.py +++ b/arcvisual/providers/openai_compat.py @@ -110,6 +110,11 @@ def _extra_payload(self, response_format: dict | None) -> dict[str, Any]: """Host-specific request fields, merged into every chat payload.""" return {} + def _post(self, payload: dict[str, Any]) -> Any: + """Send one chat request and return a response with ``status_code``, + ``headers``, ``text`` and ``json()``. Plain, unbounded POST by default.""" + return self._client().post("/chat/completions", json=payload) + def _model_exhausted(self, model: str, body: str) -> None: """Raise :class:`ModelUnavailable` if a 429 body means `model` is spent for the day, so the next configured model is tried. No-op by default.""" @@ -363,7 +368,13 @@ def _chat( if meter is not None: reserved = meter.acquire(max_tokens + prompt_tokens) try: - response = self._client().post("/chat/completions", json=payload) + response = self._post(payload) + except ProviderError: + # Already a verdict (out of time, model unavailable): pass it on as is, + # or the fallback chain would see a generic retryable failure instead. + if meter is not None: + meter.settle(reserved, 0) + raise except Exception as exc: if meter is not None: meter.settle(reserved, 0) # nothing was spent; give it all back diff --git a/arcvisual/render/stepper.py b/arcvisual/render/stepper.py index 3a3ba9f..1370485 100644 --- a/arcvisual/render/stepper.py +++ b/arcvisual/render/stepper.py @@ -100,6 +100,12 @@ def advance( try: if provider is None: provider = _select_provider() + set_deadline = getattr(provider, "set_deadline", None) + if set_deadline is not None: + # Model calls may run into the grace period a started scene gets, and no + # further: past it the platform kills the function mid-call, and a killed + # call never reaches the error handling that would record it. + set_deadline(deadline + ATTEMPT_GRACE_S) while time.monotonic() < deadline: with sf() as session: job = session.get(Job, job_id) @@ -235,12 +241,35 @@ def _step_analyze(sf, job_id, provider, deadline: float | None = None) -> bool: job = session.get(Job, job_id) sb = Storyboard.model_validate(job.storyboard) attempts = int((job.stage_progress or {}).get("analyze_attempts") or 0) + 1 - job.stage_progress = { - **(job.stage_progress or {}), - "stage": "analyzing", - "analyze_attempts": attempts, - } - session.commit() + if attempts <= MAX_ANALYZE_ATTEMPTS: + job.stage_progress = { + **(job.stage_progress or {}), + "stage": "analyzing", + "analyze_attempts": attempts, + } + session.commit() + + if attempts > MAX_ANALYZE_ATTEMPTS: + # Every earlier attempt was counted on entry, yet none was failed on its way + # out — so each one died with its function, killed by the platform mid-call. + # Retrying would die the same way, forever: this is how a job sat in + # "analyzing" for 83 minutes. + _fail( + sf, + job_id, + { + "code": "analyze_timeout", + "message": ( + f"{attempts - 1} analyze attempts ended without finishing; each " + "ran past the platform's function time limit" + ), + "user_facing": ( + "Reading this paper took longer than we are allowed to run. This " + "is on us, not the paper — please try again later." + ), + }, + ) + return False before = sb.model_copy(deep=True) if cfg.strict_ownership else None t0 = time.perf_counter() diff --git a/tests/test_longcontext.py b/tests/test_longcontext.py index 221b5ab..c55c861 100644 --- a/tests/test_longcontext.py +++ b/tests/test_longcontext.py @@ -140,7 +140,8 @@ def test_the_whole_paper_fits_in_one_analyze_pass(reset_settings) -> None: caps = provider.capabilities() assert caps.prompt_char_budget >= 200_000 assert caps.analysis_passes == 1 - assert caps.analysis_item_budget is None + # Bounded, so the reply (and with it the call) fits inside one serverless step. + assert caps.analysis_item_budget == 12 assert caps.prompt_char_budget > settings().groq.prompt_char_budget * 20 @@ -268,6 +269,24 @@ def test_openrouter_leads_with_nemotron_and_asks_it_to_reason(reset_settings) -> assert http.sent[0]["reasoning"] == {"enabled": True} +def test_analysis_does_not_reason_unless_asked(reset_settings) -> None: + """Measured on the free endpoint: 112s with reasoning, 30s without, for the same + analysis. With reasoning the real one outran the 300s function limit.""" + http = _Http(_ok('{"answer": "ok"}'), _ok('{"answer": "ok"}')) + provider = _provider(reset_settings, http) + provider.structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CLASSIFY + ) + assert "reasoning" not in http.sent[0] + + http = _Http(_ok('{"answer": "ok"}')) + provider = _provider(reset_settings, http, LLM_REASONING_ANALYZE="1") + provider.structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CLASSIFY + ) + assert http.sent[0]["reasoning"] == {"enabled": True} + + def test_reasoning_can_be_turned_off(reset_settings) -> None: http = _Http(_ok('{"answer": "ok"}')) provider = _provider(reset_settings, http, LLM_REASONING="0") @@ -355,3 +374,139 @@ def test_a_paid_models_daily_limit_is_not_mistaken_for_a_free_quota( provider.structured( system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN ) + + +# --------------------------------------------------------------------------- # +# A call must end before the function does +# --------------------------------------------------------------------------- # + + +class _Stream: + """An httpx streaming response: SSE lines, optionally slow.""" + + def __init__(self, lines: list[str], status: int = 200, delay_s: float = 0.0): + self.status_code = status + self.headers: dict = {} + self._lines = lines + self._delay = delay_s + self.text = "\n".join(lines) + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def read(self): + return self.text.encode() + + def json(self): + return json.loads(self.text) + + def iter_lines(self): + import time + + for line in self._lines: + if self._delay: + time.sleep(self._delay) + yield line + + +class _StreamingHttp: + def __init__(self, *streams: _Stream): + self.streams = list(streams) + self.sent: list[dict] = [] + + def stream(self, method: str, path: str, json: dict): + self.sent.append(json) + return self.streams.pop(0) + + +def _sse(content: str) -> list[str]: + chunks = [content[i : i + 5] for i in range(0, len(content), 5)] + lines = [": OPENROUTER PROCESSING"] + for c in chunks: + lines.append("data: " + json.dumps({"choices": [{"delta": {"content": c}}]})) + lines.append( + "data: " + + json.dumps( + { + "choices": [{"delta": {}, "finish_reason": "stop"}], + "usage": {"prompt_tokens": 7, "completion_tokens": 3}, + } + ) + ) + lines.append("data: [DONE]") + return lines + + +def test_a_streamed_reply_is_assembled_and_billed(reset_settings) -> None: + http = _StreamingHttp(_Stream(_sse('{"answer": "ok"}'))) + provider = _provider(reset_settings, http) + result = provider.structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN + ) + assert result.ok and result.value.answer == "ok" + assert http.sent[0]["stream"] is True + assert result.usage.input_tokens == 7 and result.usage.output_tokens == 3 + + +def test_a_too_slow_free_model_hands_over_to_the_next(reset_settings) -> None: + """The failure that stalled a real job for 83 minutes: a slow call ran past the + function limit. Bounded by wall clock, it now ends in time, and a free model that + slow is passed over for the paid one behind it.""" + slow = _Stream(_sse('{"answer": "too late"}'), delay_s=0.05) + fast = _Stream(_sse('{"answer": "ok"}')) + http = _StreamingHttp(slow, fast) + provider = _provider( + reset_settings, http, LLM_CALL_TIMEOUT_S="0.1", LLM_JSON_SCHEMA="0" + ) + import arcvisual.providers.longcontext_provider as lc + + old, lc._MIN_CALL_S = lc._MIN_CALL_S, 0.0 + try: + result = provider.structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN + ) + finally: + lc._MIN_CALL_S = old + assert result.ok and result.model == "qwen/qwen3-235b-a22b-2507" + + +def test_no_call_starts_when_the_step_is_out_of_time(reset_settings) -> None: + import time + + from arcvisual.providers.base import ProviderError, RetryableProviderError + + http = _StreamingHttp(_Stream(_sse('{"answer": "ok"}'))) + provider = _provider(reset_settings, http) + provider.set_deadline(time.monotonic() + 1.0) + with pytest.raises(ProviderError, match="too little for another model call") as info: + provider.structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN + ) + # Not retryable: a retry would start with even less time. + assert not isinstance(info.value, RetryableProviderError) + assert http.sent == [] + + +def test_an_error_inside_the_stream_is_reported_with_its_status(reset_settings) -> None: + quota = _Stream( + [ + "data: " + + json.dumps( + { + "error": { + "code": 429, + "message": "Rate limit exceeded: free-models-per-day", + } + } + ) + ] + ) + http = _StreamingHttp(quota, _Stream(_sse('{"answer": "ok"}'))) + provider = _provider(reset_settings, http, LLM_JSON_SCHEMA="0") + result = provider.structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN + ) + assert result.ok and result.model == "qwen/qwen3-235b-a22b-2507" diff --git a/tests/test_serverless.py b/tests/test_serverless.py index a39fde5..a751e47 100644 --- a/tests/test_serverless.py +++ b/tests/test_serverless.py @@ -477,3 +477,55 @@ def fake_call(sub, provider): assert calls["n"] == len(groups) assert len(out.concepts) == len(groups) - 1 assert any("passes" in n for n in report.notes) + + +# -- an attempt killed by the platform -------------------------------------- # + + +def test_analyze_attempts_killed_mid_call_fail_the_job_instead_of_looping(api) -> None: + """A real job sat in "analyzing" for 83 minutes: each attempt outran the 300s + function limit and was killed, so no error handler ever ran and every advance + started the same doomed call again. Counted on entry, the attempts give it away.""" + from arcvisual.render import stepper + + job_id = api.post("/api/jobs", json={"url": URL}).json()["job_id"] + sf = repo.session_factory() + stepper._step_ingest(sf, job_id) + with sf() as s: + job = s.get(Job, job_id) + assert job.state == "analyzing" + # Three attempts counted on entry, none of them recorded as failed. + job.stage_progress = { + **(job.stage_progress or {}), + "analyze_attempts": stepper.MAX_ANALYZE_ATTEMPTS, + } + s.commit() + + assert stepper._step_analyze(sf, job_id, None) is False + with sf() as s: + job = s.get(Job, job_id) + assert job.state == "failed" + assert job.failure["code"] == "analyze_timeout" + assert "try again" in job.failure["user_facing"] + + +def test_each_step_bounds_the_providers_model_calls(api, monkeypatch) -> None: + from arcvisual.render import stepper + + seen: list[float] = [] + + class _Provider: + name = "stub" + + def set_deadline(self, deadline: float) -> None: + seen.append(deadline) + + monkeypatch.setattr(stepper, "_select_provider", lambda: _Provider()) + job_id = api.post("/api/jobs", json={"url": URL}).json()["job_id"] + import time + + before = time.monotonic() + stepper.advance(job_id, session_factory=repo.session_factory(), budget_s=0) + assert seen, "the provider was never told when the step ends" + # The step's end plus the grace a started scene gets — and no more. + assert seen[0] <= before + 1 + stepper.ATTEMPT_GRACE_S From 52fc76655b7e3fe21df2ca754aa11a3e43d6d139 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 08:34:00 +0000 Subject: [PATCH 2/3] Cut off silent streams at the budget, and ask OpenRouter for stream usage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two review findings on the streaming call: - The elapsed-time check ran between lines, so a host that accepted the request and then went silent blocked the read itself until the 300s HTTP read timeout — past the function limit, the failure this change exists to prevent. A watchdog timer now closes the stream at the call budget, which unblocks the read; it is reported as too slow, so a ':free' model hands over to the next one. - Usage on an OpenRouter stream is opt-in. Without it a call bills as zero tokens and the job's dollar ceiling cannot trip. OpenRouter streams now send stream_options.include_usage; other hosts (Mistral rejects unknown fields) are not sent it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BgiEmhLGtyG2FWJkiiwD1M --- arcvisual/providers/longcontext_provider.py | 50 ++++++++++++--- tests/test_longcontext.py | 69 ++++++++++++++++++++- 2 files changed, 109 insertions(+), 10 deletions(-) diff --git a/arcvisual/providers/longcontext_provider.py b/arcvisual/providers/longcontext_provider.py index 1604135..f19bbcc 100644 --- a/arcvisual/providers/longcontext_provider.py +++ b/arcvisual/providers/longcontext_provider.py @@ -178,18 +178,43 @@ def _post(self, payload: dict[str, Any]) -> Any: client = self._client() if not hasattr(client, "stream"): return client.post("/chat/completions", json=payload) - started = time.monotonic() - with client.stream( - "POST", "/chat/completions", json={**payload, "stream": True} - ) as response: + body: dict[str, Any] = {**payload, "stream": True} + if self._cfg.preset == "openrouter": + # Usage on a stream is opt-in there, and without it a call is billed as + # zero tokens: the job's dollar ceiling would never trip. Other hosts + # (Mistral) reject unknown request fields, so this is not sent to them. + body["stream_options"] = {"include_usage": True} + with client.stream("POST", "/chat/completions", json=body) as response: if response.status_code != 200: response.read() return response - content: list[str] = [] - finish = None - usage: dict[str, Any] | None = None + # The elapsed check below runs between lines, so it cannot end a stream + # that has gone silent: one blocked read would wait out the HTTP read + # timeout (300s) — past the function's own limit. The watchdog closes + # the stream at the budget, which unblocks that read. + expired = threading.Event() + + def _expire() -> None: + expired.set() + response.close() + + watchdog = threading.Timer(budget, _expire) + watchdog.daemon = True + watchdog.start() + try: + return self._read_stream(response, model, budget, expired) + finally: + watchdog.cancel() + + def _read_stream( + self, response: Any, model: str, budget: float, expired: threading.Event + ) -> _Reply: + content: list[str] = [] + finish = None + usage: dict[str, Any] | None = None + try: for line in response.iter_lines(): - if time.monotonic() - started > budget: + if expired.is_set(): self._too_slow(model, budget) if not line.startswith("data:"): continue # SSE comments are OpenRouter's keep-alives @@ -207,6 +232,15 @@ def _post(self, payload: dict[str, Any]) -> Any: if delta.get("content"): content.append(delta["content"]) finish = choice.get("finish_reason") or finish + except ProviderError: + raise + except Exception: + if expired.is_set(): + # The watchdog closed the stream mid-read. + self._too_slow(model, budget) + raise + if expired.is_set(): + self._too_slow(model, budget) message = {"content": "".join(content) if content else None} return _Reply( 200, diff --git a/tests/test_longcontext.py b/tests/test_longcontext.py index c55c861..dc6032b 100644 --- a/tests/test_longcontext.py +++ b/tests/test_longcontext.py @@ -382,15 +382,32 @@ def test_a_paid_models_daily_limit_is_not_mistaken_for_a_free_quota( class _Stream: - """An httpx streaming response: SSE lines, optionally slow.""" + """An httpx streaming response: SSE lines, optionally slow, optionally stalled. + + ``stall_s`` blocks before the first line the way a silent host does; like a + real socket, the block ends early when the stream is closed from elsewhere. + """ + + def __init__( + self, + lines: list[str], + status: int = 200, + delay_s: float = 0.0, + stall_s: float = 0.0, + ): + import threading - def __init__(self, lines: list[str], status: int = 200, delay_s: float = 0.0): self.status_code = status self.headers: dict = {} self._lines = lines self._delay = delay_s + self._stall = stall_s + self._closed = threading.Event() self.text = "\n".join(lines) + def close(self): + self._closed.set() + def __enter__(self): return self @@ -406,6 +423,8 @@ def json(self): def iter_lines(self): import time + if self._stall and self._closed.wait(self._stall): + raise OSError("stream closed while reading") for line in self._lines: if self._delay: time.sleep(self._delay) @@ -510,3 +529,49 @@ def test_an_error_inside_the_stream_is_reported_with_its_status(reset_settings) system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN ) assert result.ok and result.model == "qwen/qwen3-235b-a22b-2507" + + +def test_a_silent_stream_is_cut_off_at_the_budget(reset_settings) -> None: + """A host that accepts the request and then sends nothing blocks the read + itself; the elapsed check between lines never runs. The watchdog closes the + stream at the budget instead of waiting out the 300s read timeout.""" + import time + + import arcvisual.providers.longcontext_provider as lc + + stalled = _Stream(_sse('{"answer": "never"}'), stall_s=30) + http = _StreamingHttp(stalled, _Stream(_sse('{"answer": "ok"}'))) + provider = _provider( + reset_settings, http, LLM_CALL_TIMEOUT_S="0.3", LLM_JSON_SCHEMA="0" + ) + old, lc._MIN_CALL_S = lc._MIN_CALL_S, 0.0 + started = time.monotonic() + try: + result = provider.structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN + ) + finally: + lc._MIN_CALL_S = old + assert time.monotonic() - started < 5, "the stalled read was not cut off" + assert result.ok and result.model == "qwen/qwen3-235b-a22b-2507" + + +def test_openrouter_streams_ask_for_usage(reset_settings) -> None: + """Usage on an OpenRouter stream is opt-in; without it a call bills as zero.""" + http = _StreamingHttp(_Stream(_sse('{"answer": "ok"}'))) + provider = _provider(reset_settings, http) + provider.structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN + ) + assert http.sent[0]["stream_options"] == {"include_usage": True} + + +def test_other_hosts_are_not_sent_openrouter_stream_options(reset_settings) -> None: + from arcvisual.providers.longcontext_provider import LongContextProvider + + reset_settings(ARCVISUAL_PROVIDER="mistral", MISTRAL_API_KEY="k") + http = _StreamingHttp(_Stream(_sse('{"answer": "ok"}'))) + LongContextProvider(client=http).structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN + ) + assert "stream_options" not in http.sent[0] From ba847a9e225d48ca4c547cc5bbdb73c5b5f4b863 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 06:27:49 +0000 Subject: [PATCH 3/3] Cap reasoning at 800 tokens per call: diagrams about four times faster Measured from a Vercel Sandbox, four diagram-sized calls side by side on the free Nemotron endpoint (all four completed, so parallel scenes are fine there): unbounded reasoning 66s (2,923 reasoning tokens), effort "low" 49s, capped at 800 tokens 15s (799 used: the cap is honoured), reasoning off 8s. OpenRouter requests now send reasoning.max_tokens (LLM_REASONING_MAX_TOKENS, default 800; 0 restores unbounded reasoning). The model still plans the diagram's layout before writing it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BgiEmhLGtyG2FWJkiiwD1M --- .env.example | 1 + README.md | 5 ++++- arcvisual/config.py | 9 +++++++++ arcvisual/providers/longcontext_provider.py | 3 ++- tests/test_longcontext.py | 12 +++++++++++- 5 files changed, 27 insertions(+), 3 deletions(-) diff --git a/.env.example b/.env.example index d1ccceb..44452a8 100644 --- a/.env.example +++ b/.env.example @@ -87,6 +87,7 @@ CEREBRAS_API_KEY= # LLM_REASONING_EFFORT= # sent as reasoning_effort when set # LLM_REASONING=1 # OpenRouter: reasoning {enabled: true} on diagram calls # LLM_REASONING_ANALYZE=0 # also reason during analysis (slow: 112s vs 30s measured) +# LLM_REASONING_MAX_TOKENS=800 # reasoning cap per call; 0 = unbounded (66s vs 15s per diagram) # LLM_CALL_TIMEOUT_S=120 # wall-clock cap per model call (replies are streamed) # LLM_ANALYSIS_ITEMS=12 # concepts analysis asks for; bounds the reply's length # LLM_RATE_IN= / LLM_RATE_OUT= # USD per million tokens; empty = unattributed diff --git a/README.md b/README.md index 175c446..3abc5f8 100644 --- a/README.md +++ b/README.md @@ -361,7 +361,10 @@ On OpenRouter the Nemotron free endpoint leads the chain. It reasons while drawi diagrams (`reasoning: {"enabled": true}`; `LLM_REASONING=0` turns it off) but not while analysing the paper, unless `LLM_REASONING_ANALYZE=1`. Measured on the free endpoint (~86 tokens/s), the same analysis took 112 s with reasoning and 30 s without, and the -real one with reasoning ran past Vercel's 300 s function limit. +real one with reasoning ran past Vercel's 300 s function limit. Reasoning is also capped at +800 tokens per call (`LLM_REASONING_MAX_TOKENS`, 0 for no cap). Measured on four +diagram calls running side by side, a diagram took 66 s with unlimited reasoning, +49 s with `effort: low`, 15 s with the 800-token cap and 8 s with reasoning off. Every call is streamed and stopped at a wall-clock limit (`LLM_CALL_TIMEOUT_S`, default 120 s, and never past the end of the current step). A plain read timeout diff --git a/arcvisual/config.py b/arcvisual/config.py index 18fe3e5..b2e1432 100644 --- a/arcvisual/config.py +++ b/arcvisual/config.py @@ -462,6 +462,12 @@ class LongContext: #: (7,272 reasoning tokens) and 30s without — and the real one, with a schema and #: up to 40 concepts, ran past Vercel's 300s function limit every time. reasoning_analyze: bool = False + #: Ceiling on reasoning tokens per call (OpenRouter's `reasoning.max_tokens`); 0 + #: lets the model reason as long as it likes. Measured on the free Nemotron + #: endpoint, four diagram calls side by side: unbounded 66s (2,923 reasoning + #: tokens), `effort: low` 49s, capped at 800 15s, off 8s. The cap keeps the model + #: planning the layout and makes a diagram about four times faster. + reasoning_max_tokens: int = 800 #: Wall-clock ceiling on one model call, in seconds. A read timeout cannot bound #: it: OpenRouter keeps a slow non-streaming request alive with periodic bytes, so #: a call outlived the serverless function and was killed instead of failing. @@ -509,6 +515,9 @@ def long_context_from_env(preset: str, env=os.environ.get) -> LongContext: reasoning_effort=env("LLM_REASONING_EFFORT", "") or "", reasoning=_flag(env("LLM_REASONING"), base.reasoning), reasoning_analyze=_flag(env("LLM_REASONING_ANALYZE"), False), + reasoning_max_tokens=int( + env("LLM_REASONING_MAX_TOKENS") or LongContext.reasoning_max_tokens + ), call_timeout_s=float(env("LLM_CALL_TIMEOUT_S") or LongContext.call_timeout_s), analysis_item_budget=int( env("LLM_ANALYSIS_ITEMS") or LongContext.analysis_item_budget diff --git a/arcvisual/providers/longcontext_provider.py b/arcvisual/providers/longcontext_provider.py index f19bbcc..90df1af 100644 --- a/arcvisual/providers/longcontext_provider.py +++ b/arcvisual/providers/longcontext_provider.py @@ -130,7 +130,8 @@ def _extra_payload(self, response_format: dict | None) -> dict[str, Any]: if self._reasons(): # Every call here is a single turn, so there is no `reasoning_details` to # pass back: the model reasons, answers, and the next call starts fresh. - extra["reasoning"] = {"enabled": True} + cap = self._cfg.reasoning_max_tokens + extra["reasoning"] = {"max_tokens": cap} if cap > 0 else {"enabled": True} if response_format is not None: # Route only to upstream hosts that honour `response_format`. Without it # OpenRouter may pick one that silently ignores the schema. diff --git a/tests/test_longcontext.py b/tests/test_longcontext.py index dc6032b..f319b58 100644 --- a/tests/test_longcontext.py +++ b/tests/test_longcontext.py @@ -266,7 +266,8 @@ def test_openrouter_leads_with_nemotron_and_asks_it_to_reason(reset_settings) -> system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN ) assert http.sent[0]["model"] == "nvidia/nemotron-3.5-lightning:free" - assert http.sent[0]["reasoning"] == {"enabled": True} + # Bounded: measured 15s per diagram with an 800-token cap against 66s without. + assert http.sent[0]["reasoning"] == {"max_tokens": 800} def test_analysis_does_not_reason_unless_asked(reset_settings) -> None: @@ -284,6 +285,15 @@ def test_analysis_does_not_reason_unless_asked(reset_settings) -> None: provider.structured( system=[TextBlock("s")], user="u", output_model=Out, task=Task.CLASSIFY ) + assert http.sent[0]["reasoning"] == {"max_tokens": 800} + + +def test_reasoning_can_be_unbounded(reset_settings) -> None: + http = _Http(_ok('{"answer": "ok"}')) + provider = _provider(reset_settings, http, LLM_REASONING_MAX_TOKENS="0") + provider.structured( + system=[TextBlock("s")], user="u", output_model=Out, task=Task.CODEGEN + ) assert http.sent[0]["reasoning"] == {"enabled": True}