Skip to content

Clamp Deep Research max_tokens to loaded context window - #7985

Merged
Etherll merged 7 commits into
unslothai:mainfrom
Souravrajvi0:feat/research-max-tokens-clamp-7965-c8fc
Aug 7, 2026
Merged

Etherll merged 7 commits into
unslothai:mainfrom
Souravrajvi0:feat/research-max-tokens-clamp-7965-c8fc

Conversation

@Souravrajvi0

Copy link
Copy Markdown
Contributor

Fixes #7965.

Deep Research clamped max_tokens against fixed 8k/16k ceilings while _loaded_context_length() already sized evidence and auto-scrape gates. Synthesis could request 16384 completion tokens on a 12288 context model; the server truncated at the wall, returned finish_reason: length, and the worker blamed a non-existent output cap.

Fix

area change
research_runs.py _resolve_max_tokens() clamps to context_length - estimated_prompt_tokens (same chars/token heuristic as synthesis budgeting)
_stream_completion / _completion Use resolved budget; capture stream usage
Synthesis failure _synthesis_length_limit_error() names Context Length when usage shows context exhaustion vs a true output-cap hit

Testing

pytest tests/test_research_runs_hardening.py -q
100 passed

New tests cover context clamping, live-probe usage shape, and the updated error message.

Not run here: end-to-end Deep Research on a large HF cache with a loaded local model.

@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: c7534dca9a

ℹ️ 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".

Comment thread studio/backend/core/research_runs.py Outdated
)
config = run["config"]
inference = config.get("inferenceRequest") or {}
resolved_max_tokens = _resolve_max_tokens(max_tokens, inference, messages)

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 Recompute the token cap after waiting for a model

When the first send hits the existing no-model retry path, _resolve_max_tokens() runs before _wait_for_local_model() can observe the newly loaded model, so _loaded_context_length() can be None and the retry reuses an unclamped payload["max_tokens"] (for example, 16,384 after a Studio restart, then a 12,288-context GGUF is loaded). That leaves resumed durable Deep Research runs on the original context-wall failure this commit is meant to prevent; recompute payload["max_tokens"] after a successful model wait or immediately before each send.

Useful? React with 👍 / 👎.

Comment thread studio/backend/core/research_runs.py Outdated
int(max_tokens or inference.get("maxTokens") or 4096),
16384 if max_tokens is not None else 8192,
),
"max_tokens": resolved_max_tokens,

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 Request stream usage before relying on it

This stream path now uses final usage to decide whether finish_reason == "length" was context exhaustion, but the Studio chat route only emits the final usage chunk when stream_options.include_usage is true (routes/inference.py lines 777-784). Because this payload sets stream/max_tokens but never opts in, local GGUF/safetensors streams leave usage as None, so the new context-window error path is effectively unreachable for Deep Research synthesis recovery.

Useful? React with 👍 / 👎.

max_tokens: int | None = None,
enable_thinking: bool | None = None,
) -> tuple[str, str, str | None]:
) -> tuple[str, str, str | None, dict[str, int] | None]:

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 Update all _stream_completion test doubles

Changing this helper to return four values means every fake used by _process tests must do the same, but several storage tests still monkeypatch _stream_completion with 3-tuples (for example tests/test_research_runs_storage.py returns at lines 1434, 1546/1548/1570/1573, and 1773/1775/1800). When _process hits the changed unpack sites, those tests raise ValueError: not enough values to unpack, so backend CI fails even though the production helper itself returns four values.

Useful? React with 👍 / 👎.

@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: a1f8127e54

ℹ️ 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".

Comment thread studio/backend/core/research_runs.py Outdated
)
config = run["config"]
inference = config.get("inferenceRequest") or {}
resolved_max_tokens = _resolve_max_tokens(max_tokens, inference, messages)

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 Clamp after the endpoint auto-loads the target model

When no model is loaded, or when a larger model is currently loaded but the run's payload["model"] names a smaller downloaded GGUF, this resolves max_tokens before the Studio chat route has a chance to auto-switch/reload the requested model (routes/inference.py calls _maybe_auto_switch_model(_switch_model_for_payload(payload)) before serving). In that path _loaded_context_length() reflects None or the old model, so a 12k target can still receive the 16,384 synthesis cap and hit the same context-wall failure this change is meant to avoid; recompute the cap after the requested model has been loaded or retry/re-resolve after an auto-switch/context-overflow response.

Useful? React with 👍 / 👎.

@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: 408179f4a0

ℹ️ 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".

assert navigation.count('aria-label="Go forward"') == 1

assert "inline-flex size-[33px] shrink-0" in navigation
assert "inline-flex size-[30px] shrink-0" in navigation

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 Update the companion new-chat size assertion

This updates the navigation hard-code to 30px, but the same test still asserts the collapsed New chat button is !size-[33px] while studio/frontend/src/features/chat/chat-page.tsx currently uses !size-[30px]; running python -m pytest tests/studio/test_desktop_reliability_frontend_contract.py::test_collapsed_tauri_keeps_history_arrows_and_adds_new_chat_by_model_picker -q now fails at that later assertion, so CI remains red.

Useful? React with 👍 / 👎.

Souravrajvi0 and others added 7 commits August 7, 2026 15:24
…hai#7965)

Size completion budgets from the active context length and prompt estimate
instead of fixed 8k/16k ceilings. Capture stream usage and distinguish
context-window exhaustion from a genuine output-cap failure in synthesis
errors.
Request stream usage from the local model, recompute max_tokens after
waiting for a model reload, and update storage test doubles for the
four-value _stream_completion return type.
Re-resolve max_tokens at the start of every completion retry so endpoint
auto-loaded models get a fresh context clamp. Drop the unused hardening
test import and align the desktop reliability contract with 30px controls.
Refresh package-lock.json so @tauri-apps/plugin-deep-link resolves in
CI builds. Align the New chat button size assertion with chat-page.tsx.
Tell users to increase context length (not lower it) when Deep Research
hits the loaded context window. Rebased onto main.
@Souravrajvi0
Souravrajvi0 force-pushed the feat/research-max-tokens-clamp-7965-c8fc branch from ea92d22 to 65749f1 Compare August 7, 2026 15:24
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Deep Research: max_tokens is never clamped to the context window, and the failure blames the wrong limit

2 participants