Skip to content

Studio: scale the token count timeout so long chats can compact - #15900

Merged
danielhanchen merged 4 commits into
unslothai:mainfrom
oobabooga:studio-count-timeout-15800
Oct 30, 2026
Merged

danielhanchen merged 4 commits into
unslothai:mainfrom
oobabooga:studio-count-timeout-15800

Conversation

@oobabooga

Copy link
Copy Markdown
Member

Fixes #15800.

Problem

Once a GGUF chat's stored transcript is several million tokens long, it stops compacting. Automatic compaction and "Compact conversation" both fail. Each send runs for about two minutes and then shows "Message too long", so the thread cannot be continued. The reporter's log:

Checkpoint fit failed; falling back to the rolling window
  ... count_chat_tokens -> RuntimeError: llama-server could not render the chat template
Could not preflight the rolling context window: llama-server could not render the chat template
llama-server returned 400: request (1684105 tokens) exceeds the available context size (200192 tokens)

Root cause

fit_checkpoint_context and fit_rolling_context both start with an exact count of the whole transcript (/apply-template, then /tokenize). count_chat_tokens gives each request a fixed 10 s timeout. llama-server renders and tokenizes on one thread, so past a CPU-dependent size the count times out. _render_count swallows the ReadTimeout and reports it as a template failure. Both fits fail, and the preflight sends the transcript unfitted.

The reporter's Xeon E5-4669 v4 took 11.1 s just to tokenize their 1.68M-token prompt. The reload in the report is incidental: the thread had grown past the threshold. /compact runs through the same fit, so it fails the same way.

Fix

  • count_chat_tokens sizes its read timeout to the prompt: 10 s plus 1 s per 100,000 characters of messages, system prompt and tools. That is a sixth of the reporter's measured rate, so a slow CPU can finish a long count while a stuck server still times out. Connect, write and pool timeouts stay at 10 s.
  • A timeout is now reported as llama-server timed out counting the prompt instead of blaming the template.

The fits and their counts are otherwise unchanged and stay exact.

Behavior boundaries

  • A long transcript is still counted whole on every send, so a send on a multi-million-token thread spends that time counting. In the runs below that is about as long as main took to fail. Avoiding the count would need lower bounds on how each chat template renders, which is not worth the risk here.
  • Cancellation is still checked only between a count's requests. A Stop pressed during a long count now waits for that request to finish rather than at most 10 s; against a stuck server that can be the full read allowance, about 710 s for 70M characters. This path is not exercised by the tests.
  • The preflight's fail-open behavior on other count failures (for example, llama-server going away) is unchanged.

Verification

Live A/B with unsloth/Qwen3.5-4B-MTP-GGUF UD-Q4_K_XL at a 16,384-token context. Each request was a 12.2M-token transcript followed by "What is 2+2?", with context_overflow: truncate_oldest:

Request main this PR
Tools, saved thread (checkpoint) "Message too long" after 121.6 s "4" after 120.4 s
Tools, saved thread, compact_context "Message too long" after 122.4 s "4" after 141.3 s
Tools, no thread (rolling) "Message too long" after 106.7 s "4" after 86.1 s
No tools, no thread (rolling) "Message too long" after 63.6 s "4" after 55.2 s

On main, the checkpoint runs logged the reporter's exact sequence. With this PR, no warnings or errors were logged, prompt_tokens_before was llama-server's exact 12,203,714, and 1-, 10- and 40-turn chats behaved as before.

New tests/test_count_chat_tokens_timeout.py drives the rolling fit, the checkpoint fit and /compact through count_chat_tokens, against a llama-server stand-in that renders at the reporter's measured speed and times out when the client's timeout is too short. With main's fixed 10 s, those tests fail. It also checks the timeout floor for short prompts and the timeout message. The 71 existing test files that exercise these fits or count_chat_tokens passed before the timeout was narrowed to reads, and the fit and count tests among them pass after it.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-29T04:13:02.793779Z
We couldn’t complete this review. Comment @codex review to try again.
4ae47aa PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@oobabooga

Copy link
Copy Markdown
Member Author

Reached Codex review convergence at oobabooga#431.

danielhanchen added a commit that referenced this pull request Oct 29, 2026
…che builds in the background (#16013)

## Summary


`studio/backend/tests/test_rag_store.py::test_dense_packs_float32_rows_without_struct_and_the_query_once`
(from #15859) fails now and then since #15961, on PRs that do not touch
RAG (seen on the `(Python 3.13, g-r)` shard for #15900):

```
tests/test_rag_store.py:619: in test_dense_packs_float32_rows_without_struct_and_the_query_once
    assert ranked == as_list and ranked[0][1] > 0.99
E   At index 4 diff: ('d1:2', 0.7071067988872528) != ('d1:2', 0.7071067690849304)
```

The test runs `search_dense` twice (numpy query, then the same query as
a list) and expects identical results. Since #15961 the first search
finds no in-memory matrix for the scope and queues a build on the
`rag-vec-cache` background thread. If that build lands before the second
search, the second answer comes from the numpy matrix instead of vec0,
and the two backends' cosine scores differ in the last few ulps.
Reproduced on main by pausing 1 s between the two calls: it fails every
time. What the test is about (the query is packed once, numpy and list
inputs answer alike) does not depend on the cache.

## What changed

The test sets `RAG_VEC_CACHE=0` through `monkeypatch`, so both searches
go through vec0 regardless of timing.

## Verification

- Main with a 1 s pause between the two searches: fails with the diff
above. Same pause with this change: passes.
- `tests/test_rag_store.py` and `tests/test_rag_vec_cache.py`: 45
passed.
- With `_search_dense` packing the query per scope instead of once, the
test fails with `assert 4 == 1`, so the guard it was written for still
bites.
@danielhanchen

Copy link
Copy Markdown
Member

Review record for #15900, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#587.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror f239da1474 (this PR's 825d6d424)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: f239da1474

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror f239da1474 (this PR's 825d6d424).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

fredjt added a commit to fredjt/unsloth that referenced this pull request Oct 30, 2026
Merge the two approaches for unslothai#15800:

1. Byte-count guard (our original fix): when the UTF-8 content
   exceeds n_ctx * 4 bytes, return an estimate (bytes // 3)
   without calling /apply-template. This bypasses the 2-3 minute
   wait on multi-million-token transcripts. The fit loop drops
   messages and re-counts; by then the list is below the threshold.

2. Scaled read timeout (from unslothai#15900): the httpx read timeout is
   now 10 s + 1 s per 100k characters of the serialized payload,
   so a slow CPU can finish an exact count that would have hit the
   old fixed 10 s ceiling. Connect, write, and pool timeouts stay
   at 10 s.

3. Timeout error reporting: a ReadTimeout during a count is now
   reported as 'llama-server timed out counting the prompt'
   instead of being swallowed as a template refusal.

The fit loop's first count is the estimate (fast, no HTTP);
subsequent counts are exact (scaled timeout). No changes to
fit_rolling_context, fit_checkpoint_context, or any caller.

Fixes unslothai#15800
@danielhanchen
danielhanchen merged commit 60dc72a into unslothai:main Oct 30, 2026
57 of 58 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Context does not compact when returning to long conversations, rendering them non-continuable

2 participants