Repository navigation
Studio: make stop button actually stop generation - #5069
Conversation
The UI stop button routes through assistant-ui's cancelRun, which aborts the frontend fetch. Four issues combined to let llama-server keep decoding long after the user clicked stop: 1. request.is_disconnected() does not fire reliably behind proxies (e.g. Colab) that don't propagate fetch aborts. 2. llama-server defaults n_predict to n_ctx when max_tokens is not sent, so a cancelled request keeps producing tokens up to 262144. 3. The httpx.Client pool keeps TCP keep-alive, so even a cleanly closed stream reuses the same connection and llama-server's liveness poll never sees a disconnect. 4. No explicit backend route to cancel - every cancel path relied on is_disconnected. Changes: - Add POST /api/inference/cancel keyed by session_id/completion_id, with a registry populated for the lifetime of each streaming response. - Have the frontend (chat-adapter.ts) POST /inference/cancel on AbortController abort, alongside the existing fetch teardown. - Send max_tokens=4096 + t_max_predict_ms=120000 as defaults on every outbound chat completion to llama-server; honoured by user overrides. - Disable httpx keep-alive on the streaming client so connection close reaches llama-server and its 1s liveness check fires. No behaviour changes for non-streaming paths or for existing callers that already pass max_tokens/session_id.
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5dfbf37aa1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| // and the tool-loop keeps running. Explicitly POST /inference/cancel | ||
| // on abort so the backend can signal its cancel_event. | ||
| const onAbortCancel = () => { | ||
| const body = resolvedThreadId ? { session_id: resolvedThreadId } : {}; |
There was a problem hiding this comment.
Send a cancel key that matches non-tool stream registrations
The abort handler now posts only session_id, but standard (non-tool) chat requests still do not include session_id, so the backend registers those streams only under completion_id (openai_chat_completions uses _TrackedCancel(cancel_event, payload.session_id, completion_id)). In the proxy scenario this patch targets (where disconnect isn’t observed), pressing Stop on a normal chat will often return {"cancelled": 0} and generation continues. Include a key that is always registered (e.g., always send session_id with chat requests, or cancel by completion_id once known).
Useful? React with 👍 / 👎.
| else: | ||
| events.extend(_CANCEL_REGISTRY.values()) |
There was a problem hiding this comment.
Reject empty-key cancel requests instead of cancelling all
When no session_id/completion_id is provided, _cancel_by_keys falls back to events.extend(_CANCEL_REGISTRY.values()), so a single /api/inference/cancel with an empty body cancels every in-flight generation. The new frontend path explicitly sends {} when no thread id is resolved, so this can terminate unrelated concurrent requests (other tabs/sessions) rather than just the caller’s stream.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 20aec6cb16
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| authFetch("/api/inference/cancel", { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/json" }, | ||
| body: JSON.stringify({ session_id: resolvedThreadId }), |
There was a problem hiding this comment.
Scope cancel requests to a single generation id
The abort handler posts only session_id, and the backend cancellation logic fans out to every in-flight event registered under that session key, so a delayed stop request can cancel the wrong run. This is reproducible when a user clicks Stop and immediately starts a new reply in the same thread (or has two tabs on the same thread): the late /inference/cancel can terminate the newer generation instead of only the aborted one. Using a per-request key (for example the active completion id) in the cancel payload would prevent this over-cancel behavior.
Useful? React with 👍 / 👎.
| if not keys: | ||
| return {"cancelled": 0} | ||
|
|
||
| n = _cancel_by_keys(keys) |
There was a problem hiding this comment.
Namespace cancel lookups by authenticated subject
/cancel is authenticated but current_subject is never used to scope the lookup, and _cancel_by_keys reads from a process-global registry keyed only by session_id/completion_id. In a multi-user deployment, any authenticated user who learns another user's key can cancel that user's active generation. The cancel key should be namespaced by subject (both when registering and when cancelling) so cancellation cannot cross account boundaries.
Useful? React with 👍 / 👎.
20aec6c to
5dfbf37
Compare
- Require at least one identifier for /api/inference/cancel so a missing thread id cannot silently cancel every in-flight generation. - Scope /cancel to a dedicated studio_router so it is not exposed under the /v1 OpenAI-compat prefix as a surprise endpoint. - Store a set of cancel events per key in _CANCEL_REGISTRY so concurrent requests on the same session_id do not overwrite each other, and deduplicate in _cancel_by_keys so the cancelled count reflects unique requests. - Always send session_id with chat completions (not only when tools are enabled) so non-tool GGUF streams register under it and are reachable from /cancel. - Register the non-GGUF stream_chunks path in the cancel registry too, so transformers-based stop-button works behind proxies that swallow fetch aborts. - Only apply the 2-minute t_max_predict_ms wall-clock cap when the caller did not pass max_tokens, so legitimate long generations on slow CPU/macOS/Windows supported installs are not silently truncated. - Remove the abort listener on normal stream completion so reused AbortSignals cannot fire a spurious cancel POST after the fact.
- Register the cancel tracker before returning StreamingResponse so a stop POST that arrives during prefill / warmup / proxy buffering finds an entry in _CANCEL_REGISTRY. Cleanup now runs via a Starlette BackgroundTask instead of a finally inside the async generator body. - Add a per-run cancel_id on the frontend (crypto.randomUUID) and in ChatCompletionRequest so /api/inference/cancel matches one specific generation. Removes the stale-cancel bug where pressing stop then starting a new run in the same thread would cancel the retry. - Apply t_max_predict_ms unconditionally in all three llama-server payload builders (previously gated on max_tokens=None, which made it dead code for UI callers that always send params.maxTokens). Raise the default to 10 minutes so slow CPU / macOS / Windows installs are not cut off mid-generation. - Make _cancel_by_keys refuse empty input (return 0) so a future internal caller can not accidentally mass-cancel every in-flight request. - Accept cancel_id (primary), session_id, and completion_id on the /api/inference/cancel route. Unify the three streaming sites on the same _cancel_keys / _tracker variable names. - Annotate _CANCEL_REGISTRY as dict[str, set[threading.Event]].
|
Auto-review verdict: Approved Reason: no verdict parsed; defaulted from last-iteration severity={'high': 0, 'medium': 0} |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 163052a734
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| // on abort so the backend can signal its cancel_event. | ||
| const onAbortCancel = () => { | ||
| const body: Record<string, string> = { cancel_id: cancelId }; | ||
| if (resolvedThreadId) body.session_id = resolvedThreadId; |
There was a problem hiding this comment.
Drop session-scoped key from stop-button cancel payload
Including session_id in the abort POST defeats the per-run cancel_id isolation because cancel_inference calls _cancel_by_keys, which unions all registry entries for every provided key. In practice, if a Stop request for run A is delayed and run B has already started on the same thread (or another tab), the stale request will still match session_id and cancel run B. This line should avoid sending the broader thread key (or backend should ignore broader keys when cancel_id is present).
Useful? React with 👍 / 👎.
|
Auto-review verdict: Approved PR #5069 makes the Studio stop button actually stop GGUF generation by adding an explicit /api/inference/cancel endpoint with a per-run cancel_id, disabling httpx keep-alive so TCP FINs reach llama-server, and adding max_tokens / t_max_predict_ms backstops to bound zombie decodes. Review fixed the non-streaming passthrough regression, raised the wall-clock default to 30 min so slow-CPU paths aren't truncated, added audio_input_stream backend reset parity, and removed a redundant guard. Reason: All real regressions fixed; cancel mechanism and wall-clock backstop work correctly after fixes. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e9313d12f3
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| // Plain fetch, not authFetch: authFetch redirects to login on | ||
| // 401, which would kick the user out mid-stop. | ||
| const token = getAuthToken(); | ||
| void fetch("/api/inference/cancel", { |
There was a problem hiding this comment.
Route cancel POST through apiUrl
The new stop-handler uses fetch("/api/inference/cancel", ...), which bypasses the app’s API base resolution used everywhere else. I checked studio/frontend/src/lib/api-base.ts, and in Tauri production requests must go to http://127.0.0.1:8888; a relative /api/... URL targets the webview origin instead, so the explicit cancel call can silently miss the backend and leave stop dependent on disconnect propagation only.
Useful? React with 👍 / 👎.
|
Manually tested stopping for gguf and non gguf, works as expected. One issue case occurred where stop happens before first token malforms history leading to (422), perhaps worth scoping to separate pr for fix. |
Stop button mechanism: verified workingRe-loaded PR head locally with gemma-4-E2B-it-GGUF Q8_0, kicked off a 50000-token streaming
|
…5069) (#5174) * Studio: stop default-capping responses at 4096 tokens Follow-up to #5069. The 4096 default introduced for runaway-decode defense silently truncates any caller that omits max_tokens. The Studio chat UI sets params.maxTokens = loadResp.context_length after a GGUF load, so it's fine, but every other consumer is not: - OpenAI-API direct callers (/v1/chat/completions, /v1/responses, /v1/messages, /v1/completions) where the OpenAI default is effectively unlimited per response. langchain, llama-index, raw curl, and the openai SDK all rely on that. - Reasoning models. Qwen3 / gpt-oss reasoning traces routinely exceed 4096 tokens before the model emits a single visible content token. The user sees the trace cut off mid-thought. - Long-form generation ("write a chapter", "produce a full SVG"). Reproduced on this branch: gemma-4-E2B-it-GGUF Q8_0, prompt asking for a 10000-word story, no max_tokens in the request: finish_reason: stop (misleading -- should be 'length') content_chars: 19772 content_tail: ...'a comforting, yet immense, pressure.\n\n*"' Body ended mid-sentence on a stray opening quote, right at the 4096 token mark. After this patch the same request returns 38357 chars ending with '...held in a perfect, dynamic equilibrium.' -- a natural stop, not a truncation. Implementation: rename the constant to _DEFAULT_MAX_TOKENS_FLOOR and set it to 32768. Each call site now uses the model's effective context length when known, falling back to the floor: default_cap = self._effective_context_length or _DEFAULT_MAX_TOKENS_FLOOR The 10-minute t_max_predict_ms wall-clock backstop from #5069 is preserved as the second line of defense. Plumbed _build_passthrough_payload + _build_openai_passthrough_body through the routes layer so the Anthropic and OpenAI passthrough paths also respect the model's context length. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
# Conflicts: # studio/backend/core/inference/llama_cpp.py # studio/backend/routes/inference.py # studio/frontend/src/features/chat/api/chat-adapter.ts
|
/gemini review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4fdec48887
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| _cancel_keys = (payload.cancel_id, payload.session_id, completion_id) | ||
| _tracker = _TrackedCancel(cancel_event, *_cancel_keys) | ||
| _tracker.__enter__() |
There was a problem hiding this comment.
Key passthrough cancellation by upstream completion ID
_openai_passthrough_stream registers _TrackedCancel with the locally generated completion_id, but this path relays llama-server SSE chunks verbatim, so clients only see llama-server's id value. In the no-cancel_id/no-session_id case, a client that calls /api/inference/cancel with the completion id it received from the stream will miss the registry entry and get {"cancelled": 0}, so generation continues. The cancellation key for this path needs to be one the client can actually provide (or the local id must be surfaced to the client).
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Code Review
This pull request introduces a robust per-request cancellation mechanism to prevent 'zombie' decodes when client-side aborts are swallowed by proxies. It adds a frontend-generated cancel_id (UUID), a backend cancellation registry with atomicity guards, and updates all streaming endpoints to monitor cancellation events. Additionally, it implements an unconditional wall-clock backstop (t_max_predict_ms) and a default token floor for llama.cpp to prevent unbounded generation. Review feedback suggests adding an exception guard in the Anthropic passthrough to prevent potential registry leaks and reconsidering the global disabling of HTTP keep-alives to avoid latency overhead from repeated handshakes.
| _tracker = _TrackedCancel(cancel_event, session_id, message_id) | ||
| _tracker.__enter__() |
There was a problem hiding this comment.
The _anthropic_passthrough_stream function lacks an outer try...except BaseException guard around the return StreamingResponse call. While the generator itself has a finally block for cleanup, if an exception occurs after _tracker.__enter__() but before the generator is successfully returned and managed by Starlette (e.g., if emitter.start or StreamingResponse instantiation fails), the cancel registry entry will leak. This pattern is correctly implemented in _openai_passthrough_stream (lines 3994-4108) and should be mirrored here for robustness.
References
- Prioritize consistency with established coding patterns within a module.
| ) | ||
| with httpx.Client(timeout = stream_timeout) as client: | ||
| with httpx.Client( | ||
| timeout = stream_timeout, limits = httpx.Limits(max_keepalive_connections = 0) |
There was a problem hiding this comment.
Disabling keep-alive connections (max_keepalive_connections = 0) is an effective way to ensure TCP FIN packets reach the upstream server on client disconnect. However, creating a new httpx.Client for every streaming request can introduce significant latency and overhead due to repeated TCP and TLS handshakes. Per repository guidelines, architectural changes to resource management strategies like HTTP client lifecycles should be handled consistently across the codebase rather than as one-off changes. Consider if a more balanced limit or a global strategy is more appropriate.
References
- Architectural changes, like resource management strategies (e.g., HTTP client lifecycle), should be applied consistently across the codebase via a dedicated refactoring effort, not as one-off changes.
…e through apiUrl for Tauri
Three reviewer-flagged correctness gaps in the stop-button mechanism.
1) `_openai_passthrough_stream` could not honor cancel during prefill.
The cancel check ran inside the `async for raw_line in lines_iter`
body, so a cancel POST that arrived before llama-server emitted the
first SSE line was unobservable until prefill completed. With a long
prompt under proxy/Colab conditions -- the exact target scenario for
this PR -- that left the model decoding for a long time after the
user clicked Stop. Add an asyncio watcher task that closes `resp` as
soon as `cancel_event` is set, raising in `aiter_lines` so the
generator can exit. The watcher polls a threading.Event because the
cancel registry is keyed by threading.Event for the synchronous
/cancel handler.
2) `_anthropic_passthrough_stream` had the same blocking-prefill pattern.
Same fix.
3) The frontend's stop-button cancel POST used a bare relative
`fetch("/api/inference/cancel", ...)`, which targets the webview
origin in Tauri production builds (where the backend is at
`http://127.0.0.1:8888`). Route through the existing `apiUrl()`
helper from `lib/api-base.ts` to match every other Studio call.
Browser/dev builds get the empty base, so behavior is unchanged
there.
Verified via temp/pr_simulation/sim_5069_prefill_cancel.py: cancel
during prefill terminates within ~250ms on both passthrough paths
(was 145s+ on the Anthropic path before this change), and the standard
non-passthrough chat path still cancels with no regression.
|
Pushed 2fe0ff5 addressing the three real-world findings from the latest review pass. Fixed: The cancel check ran inside the Fixed: Same blocking-prefill pattern. Same watcher fix applied symmetrically. Fixed: cancel POST bypasses Tauri apiUrl (Codex P2, line 726) The bare Verified via
Deferred (low real-world impact):
|
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces a robust per-request cancellation mechanism for inference by adding a unique cancel_id to the request lifecycle. It implements a backend cancellation registry with atomicity guards, a new /api/inference/cancel endpoint, and updates the frontend to trigger this endpoint upon abort. Additionally, the PR enforces an unconditional wall-clock timeout (t_max_predict_ms) and a default token floor for llama.cpp backends to prevent unbounded decodes. Feedback was provided to improve exception handling in the cancellation route by logging parsing errors instead of silently ignoring them.
| try: | ||
| body = await request.json() | ||
| if not isinstance(body, dict): | ||
| body = {} | ||
| except Exception: | ||
| body = {} |
There was a problem hiding this comment.
The exception handling here is too broad. It catches all exceptions, including potential system-level errors, and silently defaults to an empty body. It is better to log the exception, even at a debug level, to aid in future debugging.
| try: | |
| body = await request.json() | |
| if not isinstance(body, dict): | |
| body = {} | |
| except Exception: | |
| body = {} | |
| try: | |
| body = await request.json() | |
| if not isinstance(body, dict): | |
| body = {} | |
| except Exception as e: | |
| logger.debug(f"Failed to parse cancel request body: {e}") | |
| body = {} |
References
- Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.
Reviewer-flagged defensive logging gap. The bare `except Exception: pass`
in `cancel_inference` would mask malformed payloads that hint at a buggy
client or a transport issue. Log at debug so future investigation isn't
left guessing whether `body={}` came from a missing body or a parse
failure. Behavior is unchanged: an unparseable body still falls through
to the empty-dict path and the cancel call returns `{"cancelled": 0}`.
|
Pushed 77f2fb1 addressing the Gemini-medium finding. Fixed: silent parse failure in cancel handler The bare |
|
/gemini review |
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request implements a robust cancellation mechanism for inference requests to prevent "zombie decodes," specifically addressing scenarios where client-side aborts are swallowed by proxies. It introduces a per-request cancel_id, a backend cancellation registry, and a new /api/inference/cancel endpoint. The implementation ensures that cancellation events are tracked even if they arrive before the stream starts and that resources are cleaned up via finally blocks in async generators. Additionally, it updates default token limits and applies wall-clock timeouts unconditionally. Feedback focuses on improving consistency for Anthropic-style requests by including message_id in the cancellation lookup and ensuring cancel_id is registered in the Anthropic passthrough tracker.
| for k in ("completion_id", "session_id"): | ||
| v = body.get(k) | ||
| if isinstance(v, str) and v: | ||
| keys.append(v) |
There was a problem hiding this comment.
The /cancel endpoint should also check for message_id when falling back from cancel_id. The Anthropic passthrough route registers its streams using message_id (line 3721), but this handler currently only looks for completion_id and session_id. Adding message_id ensures that Anthropic-style requests can be cancelled by their native identifier. Additionally, ensure that both streaming and non-streaming versions of this cancellation logic have dedicated unit test coverage.
| for k in ("completion_id", "session_id"): | |
| v = body.get(k) | |
| if isinstance(v, str) and v: | |
| keys.append(v) | |
| keys = [] | |
| for k in ("completion_id", "session_id", "message_id"): | |
| v = body.get(k) | |
| if isinstance(v, str) and v: | |
| keys.append(v) |
References
- Prioritize consistency with established coding patterns within a module.
- Ensure both streaming and non-streaming versions of an API endpoint have dedicated unit test coverage to prevent bugs in one path from being missed.
| backend_ctx = llama_backend.context_length, | ||
| ) | ||
|
|
||
| _tracker = _TrackedCancel(cancel_event, session_id, message_id) |
There was a problem hiding this comment.
The Anthropic passthrough stream should also register under payload.cancel_id if present, mirroring the OpenAI passthrough logic (line 4034). While the Studio UI currently relies on session_id, supporting cancel_id provides a more precise per-run cancellation mechanism. Please ensure this streaming path is covered by dedicated unit tests.
| _tracker = _TrackedCancel(cancel_event, session_id, message_id) | |
| _tracker = _TrackedCancel(cancel_event, getattr(payload, "cancel_id", None), session_id, message_id) |
References
- Prioritize consistency with established coding patterns within a module.
- Ensure both streaming and non-streaming versions of an API endpoint have dedicated unit test coverage to prevent bugs in one path from being missed.
Two reviewer-flagged consistency gaps in the cancel surface for /v1/messages. 1) Anthropic passthrough did not register cancel_id, so a per-run cancel POST (the cleanest Studio-style cancel path) silently missed when the route hit `_anthropic_passthrough_stream`. The OpenAI passthrough has registered (cancel_id, session_id, completion_id) since this PR was first opened; mirror that here. Also add `cancel_id` to `AnthropicMessagesRequest` so the route handler can plumb it through. 2) The cancel handler's fallback key list checked only completion_id and session_id, never message_id. Anthropic clients that send their native `id` (returned in the SSE message_start event) for cancel had no way to hit the registry. Add message_id to the fallback list. Verified via temp/pr_simulation/sim_5069_prefill_cancel.py: P2 now cancels by cancel_id in 137ms (was hanging pre-fix), and the new P2b case cancels by message_id in 77ms. P1 (OpenAI) and P3 (standard chat) still pass with no regression.
|
Pushed 75345ff addressing both findings. Fixed: Anthropic passthrough now registers Mirrors the OpenAI passthrough's Fixed: cancel handler now checks Added Verified via
|
There was a problem hiding this comment.
Code Review
This pull request introduces a per-request cancellation mechanism and safety backstops for inference, accompanied by a comprehensive test suite. Key changes include the addition of a cancel_id for request tracking, a backend registry for managing cancellations, and a wall-clock timeout (t_max_predict_ms) to prevent zombie decodes. Feedback suggests using a more conservative default token cap for models with extremely large context lengths to better handle runaway generations and notes that the per-request httpx.AsyncClient instantiation should be applied consistently across the codebase rather than as an isolated modification.
| payload["max_tokens"] = ( | ||
| max_tokens | ||
| if max_tokens is not None | ||
| else (self._effective_context_length or _DEFAULT_MAX_TOKENS_FLOOR) |
There was a problem hiding this comment.
The default max_tokens is set to self._effective_context_length if not provided. If the model has a very large context (e.g., Qwen3.5 with 262k tokens), this doesn't effectively 'cap' a runaway generation if the cancel signal fails. Consider using a more conservative hard cap for the default value, or ensure that t_max_predict_ms is always reliable as the primary backstop.
| # this the tracker leaks. The generator's finally only runs once | ||
| # iteration starts. | ||
| try: | ||
| # Dispatch BEFORE returning StreamingResponse so transport errors |
There was a problem hiding this comment.
Creating a new httpx.AsyncClient for every streaming request to ensure TCP connections are closed introduces a one-off architectural change to the HTTP client lifecycle. According to repository rules, such changes to resource management strategies should be applied consistently across the codebase via a dedicated refactoring effort, rather than as isolated changes in specific routes.
References
- Prioritize consistency with established coding patterns. Architectural changes, like resource management strategies (e.g., HTTP client lifecycle), should be applied consistently across the codebase via a dedicated refactoring effort, not as one-off changes.
|
Both findings are deliberate design choices, not bugs. Declining both with rationale: Default max_tokens = effective_context_length (Gemini medium) This is the exact behaviour PR #5174 (the follow-up to this PR) shipped, intentionally. The original The runaway-decode defense is now layered:
Re-introducing a hard cap below the model context would resurrect the silent-truncation bug PR #5174 was filed to fix. Per-request httpx.AsyncClient (Gemini medium, repeated)
The architectural-consistency rule the reviewer cites is good advice for code that picks an HTTP-client pattern arbitrarily. This one is load-bearing for the cancel mechanism. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 75345ff105
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| _tracker = _TrackedCancel(cancel_event, cancel_id, session_id, message_id) | ||
| _tracker.__enter__() |
There was a problem hiding this comment.
Register cancel tracking in all Anthropic streaming paths
This commit wires _TrackedCancel only for _anthropic_passthrough_stream, but /v1/messages also has streaming branches via _anthropic_tool_stream and _anthropic_plain_stream that never register their cancel_event keys. In those branches, /api/inference/cancel cannot match cancel_id/message_id and returns {"cancelled": 0}, so generation keeps running whenever request.is_disconnected() is masked by a proxy (the same environment this patch is targeting).
Useful? React with 👍 / 👎.
Summary
The UI stop button currently aborts the frontend fetch but llama-server keeps decoding, sometimes for tens of minutes (observed 200k+ tokens of zombie generation on a simple "Hi" prompt that triggered a tool-call loop). Four independent issues combined to cause this; this PR addresses each:
AbortController.abort()does not reach Studio — sorequest.is_disconnected()never fires, andcancel_eventnever gets set.max_tokenscap. Studio omitsmax_tokenson chat completions when the user hasn't set one, so llama-server defaults ton_predict = n_ctx, which can be 262144 for Qwen3.5. Even when cancel does fire, a runaway is already queued.httpx.Clientpools TCP connections, so even after Studio closes the stream, the socket stays ESTABLISHED. llama-server's 1 s liveness poll never sees a disconnect.is_disconnected(). With (1) this meant users had no way to signal the backend.Changes
studio/backend/routes/inference.pyPOST /api/inference/cancel(body:{session_id?, completion_id?}) with a_CANCEL_REGISTRYpopulated for the lifetime of each streaming response.studio/backend/routes/inference.py_TrackedCancel.studio/backend/core/inference/llama_cpp.pymax_tokens=4096andt_max_predict_ms=120000on all three llama-server payloads (initial, tool-loop iteration, and final pass). User-supplied values still win.studio/backend/core/inference/llama_cpp.pyhttpx.Client(..., limits=httpx.Limits(max_keepalive_connections=0))on all three streaming call sites so the TCP FIN actually reaches llama-server on disconnect.studio/frontend/src/features/chat/api/chat-adapter.tsabortSignal, POST/api/inference/cancelwithsession_idalongside the existing fetch teardown.No behaviour changes for callers that already pass explicit
max_tokens/session_id. Non-streaming paths and audio/generate paths are unchanged for this PR (same fix applies but they're out of scope).Test plan
studio/backend/run.py).POST /api/inference/cancelreturns 401 without auth and 200{"cancelled": 0}with auth when nothing is running.Parsed 1 tool callevents appear instudio.log.max_tokens=4096andt_max_predict_ms=120000appear in llama-server requests when user doesn't override them.max_tokensstill takes precedence./inference/canceldoes not fire stale cancels on subsequent requests (registry cleanup via_TrackedCancel.__exit__).