Skip to content

Studio: make stop button actually stop generation - #5069

Merged
danielhanchen merged 41 commits into
mainfrom
fix/studio-stop-button
Apr 24, 2026
Merged

danielhanchen merged 41 commits into
mainfrom
fix/studio-stop-button

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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:

  1. Proxies don't propagate fetch aborts. On Colab (and likely other proxy setups) the browser's AbortController.abort() does not reach Studio — so request.is_disconnected() never fires, and cancel_event never gets set.
  2. No max_tokens cap. Studio omits max_tokens on chat completions when the user hasn't set one, so llama-server defaults to n_predict = n_ctx, which can be 262144 for Qwen3.5. Even when cancel does fire, a runaway is already queued.
  3. httpx keep-alive hides disconnects. httpx.Client pools TCP connections, so even after Studio closes the stream, the socket stays ESTABLISHED. llama-server's 1 s liveness poll never sees a disconnect.
  4. No explicit cancel route. Every cancel path relied on is_disconnected(). With (1) this meant users had no way to signal the backend.

Changes

File Change
studio/backend/routes/inference.py Add POST /api/inference/cancel (body: {session_id?, completion_id?}) with a _CANCEL_REGISTRY populated for the lifetime of each streaming response.
studio/backend/routes/inference.py Register the tool-loop and non-tool GGUF streams in the registry via _TrackedCancel.
studio/backend/core/inference/llama_cpp.py Default max_tokens=4096 and t_max_predict_ms=120000 on all three llama-server payloads (initial, tool-loop iteration, and final pass). User-supplied values still win.
studio/backend/core/inference/llama_cpp.py httpx.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.ts On abortSignal, POST /api/inference/cancel with session_id alongside 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

  • Backend starts cleanly with the patches applied (studio/backend/run.py).
  • POST /api/inference/cancel returns 401 without auth and 200 {"cancelled": 0} with auth when nothing is running.
  • Manually: load Qwen3.5-4B-GGUF, prompt "1" to trigger a web_search tool-loop, click stop in the UI, verify slot goes idle within ~1 s and no further Parsed 1 tool call events appear in studio.log.
  • Verify max_tokens=4096 and t_max_predict_ms=120000 appear in llama-server requests when user doesn't override them.
  • Verify user-supplied max_tokens still takes precedence.
  • Verify that completing a request naturally still works and /inference/cancel does not fire stale cancels on subsequent requests (registry cleanup via _TrackedCancel.__exit__).

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.
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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 } : {};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +164 to +165
else:
events.extend(_CANCEL_REGISTRY.values())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@danielhanchen danielhanchen added the auto-reviewing Auto-review in progress label Apr 17, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Apr 17, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Apr 17, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Apr 17, 2026
@danielhanchen danielhanchen added auto-review-failed Auto-review rejected the PR and removed auto-reviewing Auto-review in progress labels Apr 17, 2026
Comment thread studio/backend/routes/inference.py Fixed
Comment thread studio/backend/routes/inference.py Fixed
Comment thread studio/backend/routes/inference.py Fixed

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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 }),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@danielhanchen danielhanchen added the auto-reviewing Auto-review in progress label Apr 18, 2026
- 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]].
@danielhanchen danielhanchen added the auto-approved Auto-review approved the PR label Apr 18, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Auto-review verdict: Approved

Reason: no verdict parsed; defaulted from last-iteration severity={'high': 0, 'medium': 0}

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

@danielhanchen danielhanchen removed the auto-review-failed Auto-review rejected the PR label Apr 18, 2026
@danielhanchen danielhanchen removed the auto-reviewing Auto-review in progress label Apr 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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", {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@Imagineer99

Copy link
Copy Markdown
Member

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

Stop button mechanism: verified working

Re-loaded PR head locally with gemma-4-E2B-it-GGUF Q8_0, kicked off a 50000-token streaming /api/inference/chat/completions (no thinking, prompt asking the model to never stop), then issued POST /api/inference/cancel with the matching session_id. Stream terminated 24 ms after the cancel arrived, registry returned {"cancelled": 1}, no zombie tokens after the cancel boundary. Cancel registry, _TrackedCancel.__exit__ cleanup, and the no-keepalive httpx client all do what the description claims.

_DEFAULT_MAX_TOKENS = 4096 is too low for a one-size default

Quick clarification first since the constant name is suggestive: this caps OUTPUT tokens (n_predict in llama.cpp), not the model's context length (n_ctx). Different parameters; the model can still attend to its full configured context. So this does not "force a maximum context length of 4096".

What it DOES do: any caller who omits max_tokens gets their response silently truncated at 4096. The Studio chat UI itself is fine because it sets params.maxTokens = loadResp.context_length after a GGUF load (studio/frontend/src/features/chat/api/chat-adapter.ts:367), so the payload always carries an explicit value. The regression hits any caller that doesn't set max_tokens:

  • OpenAI-API direct callers (/v1/chat/completions, /v1/completions, /v1/responses, /v1/messages)
  • The Studio backend itself when fed by anything other than the bundled chat UI

Repro on the PR head, gemma-4-E2B-it-GGUF Q8_0, no max_tokens in payload, no thinking, prompt: "Write a 10000-word story about a dragon and a wizard. Be very verbose. Add lots of detail to every scene.":

finish_reason: stop
usage: {'prompt_tokens': 0, 'completion_tokens': 0, 'total_tokens': 0}
content_chars: 19772
content_tail: ...'e was a pervasive, intelligent awareness that permeated the cavern. She perceived his attention as a slow, deep warmth, a comforting, yet immense, pressure.\n\n*"'

19772 chars is right at the 4096 token mark for English prose, and the body ends mid-sentence on a stray opening quote. Two secondary issues fall out of the same path:

  • finish_reason should be "length" when max_tokens triggers, not "stop". The Studio path is rewriting it.
  • usage is zeroed out, so the caller can't even tell from token counts that they were truncated.

t_max_predict_ms = 600_000 is a good wall-clock backstop, but per the llama.cpp README it ONLY triggers "if a new-line character has already been generated" (tools/server/README.md:482). A model stuck producing a long unbroken sequence of non-newline tokens (precisely the original tool-loop scenario) won't be bounded by it, so we still want SOME token cap as the front-line limiter.

Concrete cases where 4096 will silently truncate:

  1. Reasoning models. Qwen3 / gpt-oss reasoning traces routinely exceed 4096 tokens for hard problems before the model emits a single visible content token. The user sees the trace cut off mid-thought.
  2. Long-form generation. "Write a chapter", "produce a full SVG", "generate this 6 file diff" all blow past 4096.
  3. OpenAI API parity. The OpenAI default when max_tokens is omitted is "model max minus prompt", effectively unlimited per response. langchain, llama-index, raw curl, openai Python SDK callers all rely on that.

Suggested default

Raise the default to the model's effective context length when available, with a generous floor when metadata is unavailable:

# studio/backend/core/inference/llama_cpp.py
_DEFAULT_MAX_TOKENS_FLOOR = 32768  # was: _DEFAULT_MAX_TOKENS = 4096

# At each of the three call sites (currently lines 2353-2354, 2572-2573, 3229-3230):
default_cap = self._effective_context_length or _DEFAULT_MAX_TOKENS_FLOOR
payload["max_tokens"] = max_tokens if max_tokens is not None else default_cap

That keeps the runaway defense (the wall-clock backstop is still 10 min, and the cap is still bounded by the model's own context) without silently truncating reasoning models or breaking OpenAI API parity. Happy to push a follow-up PR if you want.

Also worth a follow-up: the finish_reason rewrite to "stop" and the zeroed usage are independent UX bugs that show up in this same path.

danielhanchen and others added 2 commits April 24, 2026 08:58
…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
@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +3990 to +3992
_cancel_keys = (payload.cancel_id, payload.session_id, completion_id)
_tracker = _TrackedCancel(cancel_event, *_cancel_keys)
_tracker.__enter__()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +3694 to +3695
_tracker = _TrackedCancel(cancel_event, session_id, message_id)
_tracker.__enter__()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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
  1. 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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
  1. 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.
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed 2fe0ff5 addressing the three real-world findings from the latest review pass.

Fixed: _openai_passthrough_stream cancel-during-prefill (Codex P1, line 4058)

The cancel check ran inside the async for raw_line body, so a /api/inference/cancel POST that arrived BEFORE llama-server emitted the first SSE chunk was unobservable until prefill completed. With a long prompt under proxy/Colab conditions (the target scenario), the model kept decoding for a long time after the user hit Stop. Added an asyncio watcher task that closes resp as soon as cancel_event fires, unblocking aiter_lines() with a RemoteProtocolError we catch silently when cancel is set.

Fixed: _anthropic_passthrough_stream cancel-during-prefill (Codex P1, line 3742)

Same blocking-prefill pattern. Same watcher fix applied symmetrically.

Fixed: cancel POST bypasses Tauri apiUrl (Codex P2, line 726)

The bare fetch("/api/inference/cancel", ...) targeted the webview origin in Tauri production builds where the backend is at 127.0.0.1:8888. Routed through the existing apiUrl() helper from lib/api-base.ts to match every other Studio API call. Browser/dev builds get the empty base so behavior is unchanged there.

Verified via temp/pr_simulation/sim_5069_prefill_cancel.py:

  • _openai_passthrough_stream prefill cancel: closes in ~230ms
  • _anthropic_passthrough_stream prefill cancel: closes in ~89ms (was hanging 145s+ before this change)
  • standard non-passthrough chat cancel: still ~170ms (no regression)

Deferred (low real-world impact):

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +854 to +859
try:
body = await request.json()
if not isinstance(body, dict):
body = {}
except Exception:
body = {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
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
  1. 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}`.
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed 77f2fb1 addressing the Gemini-medium finding.

Fixed: silent parse failure in cancel handler

The bare except Exception: pass would mask malformed cancel payloads (a hint of a buggy client or transport issue). Now logs at debug. Behavior is unchanged: an unparseable body still falls through to the empty-dict path and the cancel call returns {"cancelled": 0}.

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +867 to +870
for k in ("completion_id", "session_id"):
v = body.get(k)
if isinstance(v, str) and v:
keys.append(v)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
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
  1. Prioritize consistency with established coding patterns within a module.
  2. 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.

Comment thread studio/backend/routes/inference.py Outdated
backend_ctx = llama_backend.context_length,
)

_tracker = _TrackedCancel(cancel_event, session_id, message_id)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
_tracker = _TrackedCancel(cancel_event, session_id, message_id)
_tracker = _TrackedCancel(cancel_event, getattr(payload, "cancel_id", None), session_id, message_id)
References
  1. Prioritize consistency with established coding patterns within a module.
  2. 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.
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed 75345ff addressing both findings.

Fixed: Anthropic passthrough now registers cancel_id

Mirrors the OpenAI passthrough's _TrackedCancel(cancel_event, cancel_id, session_id, completion_id) registration. Also added cancel_id: Optional[str] = None to AnthropicMessagesRequest so the route handler can plumb it through. A per-run cancel POST now actually hits when the route lands on _anthropic_passthrough_stream.

Fixed: cancel handler now checks message_id

Added message_id to the fallback key list ("completion_id", "session_id", "message_id"). Anthropic clients that cancel by their native message id (returned in message_start SSE) now hit the registry instead of getting a silent cancelled: 0.

Verified via temp/pr_simulation/sim_5069_prefill_cancel.py:

  • P1 OpenAI passthrough cancel by cancel_id during prefill: 769ms (no regression)
  • P2 Anthropic passthrough cancel by cancel_id during prefill: 137ms (was returning cancelled: 0 pre-fix)
  • P2b Anthropic cancel by message_id from SSE stream: 77ms (was returning cancelled: 0 pre-fix)
  • P3 standard chat cancel: 437ms (no regression)

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Comment on lines +4046 to +4049
# this the tracker leaks. The generator's finally only runs once
# iteration starts.
try:
# Dispatch BEFORE returning StreamingResponse so transport errors

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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
  1. 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

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 _DEFAULT_MAX_TOKENS = 4096 was a runaway-decode floor that silently truncated every OpenAI-API direct caller (langchain, openai SDK, raw curl, llama-index, etc.) because their convention is to omit max_tokens and rely on the model's context window. PR #5174 reproduced the regression on gemma at 19772 chars (mid-sentence cut, finish_reason=stop misleadingly), then fixed it by routing the default through self._effective_context_length with a 32768 floor when context is unknown.

The runaway-decode defense is now layered:

  1. Effective context length (model-specific upper bound)
  2. t_max_predict_ms = 600_000 (10-minute wall-clock backstop, applied unconditionally)
  3. Explicit POST /api/inference/cancel (the new mechanism this PR adds)

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)

max_keepalive_connections = 0 is the actual mechanism that makes the stop button work in proxy environments. Without it, closing the client-side response doesn't tear down the upstream socket -- llama-server keeps generating until natural stop or t_max_predict_ms. That's the bug this PR exists to fix. Sharing a pooled AsyncClient across requests would defeat the purpose. The handshake overhead the reviewer flags is real but only fires per-call; the alternative is a wedged stream after every Stop click.

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.

@danielhanchen
danielhanchen merged commit eb8b0de into main Apr 24, 2026
6 checks passed
@danielhanchen
danielhanchen deleted the fix/studio-stop-button branch April 24, 2026 17:09

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +3727 to +3728
_tracker = _TrackedCancel(cancel_event, cancel_id, session_id, message_id)
_tracker.__enter__()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auto-approved Auto-review approved the PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants