Repository navigation
Studio: keep and search the turns rolling context evicts - #9074
Conversation
…feat/rolling-context-window
…feat/rolling-context-window
…feat/rolling-context-window
…window # Conflicts: # studio/backend/tests/test_gguf_completion_usage.py
Rolling context eviction currently drops turns with no way for a caller to learn which ones went. Extract the turn grouping so the eviction unit is reusable, add an identity-based diff of what a fit removed, and let a caller reserve room for content it intends to add back after fitting. The reserve deliberately does not affect whether trimming happens at all, only how far it goes once it is already required, so a conversation that fits today is still returned untouched.
An evicted turn is currently gone for the rest of the session, so the model will state the conversation began wherever its visible context begins. Keep the turns the rolling window drops in a searchable scope built on the existing store, chunker, embedder and hybrid retrieval. The archive is cumulative: every compaction adds to it and nothing is cleared, so a later compaction can still find what an earlier one evicted. It lives in its own scope rather than the thread's document scope, because thread documents are injected in full on every request and would re-inject the whole history. Idempotent by content hash, since the same turns are evicted again on every later request. Every entry point degrades to a no-op rather than raising.
Given only a search tool, a model decides for itself whether to look, and mostly does not. Measured on MRCR v2, a 35B declined on 56% of rows, scoring 0.099 when it skipped against 0.461 when it searched. Forcing one retrieval on the compaction turn took tool-only 0.258 to 0.604, and the model then called the tool on 0% of rows, so the common path costs nothing extra. Recall fires at most once per request, since the tool loop refits on every iteration. The tool loop renders it as an ordinary tool exchange through the builder shared with document auto-inject; the plain path prefixes the latest user message instead, because it sends no tools array and a tool role without one breaks strict chat templates. Only scalar counts join the context_truncated event, so no message content reaches the wire.
Forced recall answers the turn that evicted, but a later turn can refer to something the forced pass had no reason to fetch. Add search_conversation so the model can go looking, scoped to the thread's own archive and sharing the admission slot with document search so the two cannot race for the embedder. The tool is offered only once a thread has actually had turns archived, so an ordinary short chat never pays for the schema, and it is classified read-only so auto mode does not prompt on every call. A matching system-prompt note tells the model the session was compacted, since otherwise it assumes the conversation began where its visible context begins. Deleting a thread now drops its archive rather than leaking a scope per chat.
_select_request_tools also serves the token-count request model, which has no thread_id field, so the archive gate raised there.
Recalling your own conversation is mostly an exact-match problem: a name, a number, an identifier someone pasted twenty turns ago. Those live or die on rare-token matching, and hybrid fusion was losing them. Measured on a 30-turn walkthrough of a 230k-character document at a 16k window, where every turn shared the same wrapper text. The chunk holding the needle ranked 3rd lexically at any k, was never returned by dense retrieval at all, and RRF pushed it to 16th because it had 30 useless dense hits to fuse with. End to end the model answered with the exact code once lexical leads, and could not answer at all before. Dense still fills whatever the lexical pass leaves, for paraphrased recall.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f4f35e8d47
ℹ️ 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".
| digest = hashlib.sha256(text.encode("utf-8", "ignore")).hexdigest() | ||
| if store.document_by_hash(conn, scope, digest): | ||
| continue |
There was a problem hiding this comment.
Invalidate archives when transcript messages change
When an archived message is edited or pruned through the supported message PUT/sync endpoints, its old hash and chunks remain permanently in this cumulative scope; a later compaction merely adds the replacement under a new digest. Consequently search_conversation can return deleted text or conflicting pre-edit and post-edit versions as though both were still turns in the current conversation. Clear or rebuild the thread archive when transcript content is replaced or pruned.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The read-side branch filter already prevents returning deleted or pre-edit text, and with the fix to the sibling item it now requires the whole archived turn to still be present, so an edited or pruned turn is retired at query time. Invalidating or rebuilding on every message PUT would cost a rewrite on an ordinary edit and would work against the cumulative property the benchmark showed this depends on (an epoch-scoped archive scored 0.058 against 0.450). What is left is stale rows taking space, which is a storage question rather than a correctness one.
…nothing was trimmed archive_messages bounds the branch check's run, and it was recording the number of messages ARCHIVED rather than the span of the turn. The two differ whenever _archivable drops something: an assistant batch that called search_conversation alongside an ordinary tool archives three messages while the live transcript holds four. Measured, validation failed at three and passed at four, so a perfectly valid ordinary-tool exchange and the answer that followed were rejected as off-branch and could never be recalled. fit_rolling_context returns None when it drops nothing, so a prompt that simply fits, after a context-length increase or on a shorter branch, left the recall budget to a character estimate that cannot see the template's own framing. Measured on a request whose real prompt is about 2800 tokens of a 3584 budget: the budget came back 3512, nearly the whole window, so the recall could append a passage that does not fit and the next iteration cannot evict it again, since the current tool exchange is protected. Priced exactly instead, once per request and only when the model actually reaches for a retrieval tool on a request that did not truncate. A failure falls back to the old estimate.
…hai/unsloth into r9074 # Conflicts: # studio/backend/tests/test_conversation_archive.py
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 070405cec7
ℹ️ 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".
| has_archive = _thread_has_conversation_archive(getattr(payload, "thread_id", None)) | ||
| tools = [t for t in tools if t["function"]["name"] != "search_conversation"] | ||
| if has_archive and tools_on: | ||
| tools = tools + [t for t in ALL_TOOLS if t["function"]["name"] == "search_conversation"] |
There was a problem hiding this comment.
Include archived-thread state in token counts
For Studio's background /chat/count_tokens request, the frontend does not include thread_id, so this archive check is false even when the actual completion for the same thread will add search_conversation. The count therefore omits both that tool schema and _COMPACTED_SESSION_NUDGE, causing the context-usage display and preflight guidance to undercount compacted conversations. Pass the thread ID through the token-count payload so it selects the same prompt as generation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining, same as the identical item on the stacked PR, and for the same measured reason.
The particulars are right: ChatCountTokensRequest carries no thread_id, the count route enters tool selection only when tools or MCP are on, and has_archive is therefore always False there. One more in your favour that the item misses: the count route never calls _apply_compaction_nudge at all, so even a tools-on count under-reports the nudge.
The direction of the net error is what decides it. The omitted search_conversation schema is about 103 tokens compact and the compacted-session nudge 71, so roughly 175. On exactly these threads the bar already OVERstates by the whole evicted region: count_tokens tokenizes the full branch with no truncation awareness while the completion fits first, which is thousands of tokens. The missing 175 cancels part of that overstatement rather than adding to it.
The consumer gates on nothing: countChatInputTokens -> refreshContextUsage -> setContextUsage renders the usage bar, every trigger is fire and forget inside a catch, and the store is overwritten with real usage after each turn.
Passing the thread id would put blocking DB I/O and a DAG walk on a background path that fires on every model load and thread switch, for a number that would still be wrong in the larger direction. Making the count truncation-aware is the honest fix and is a bigger change than this PR.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7cd76bf863
ℹ️ 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".
| needs the probe splitter to carry offsets, which is a bigger change than this bug | ||
| warrants. Lexical search does its own tokenising and never reads this. | ||
| """ | ||
| return (text or "").strip() |
There was a problem hiding this comment.
Preserve indentation when validating archived turns
When code, YAML, or another indentation-sensitive turn is edited only by changing leading whitespace, the archived pre-edit document still validates because each probe is normalized with strip() and whitespace-only gaps are accepted. Recall can therefore return obsolete indentation as if it were still on the active branch. Fresh evidence in the current code is that _normalise still strips each probe and its accompanying comment explicitly states that indentation-only edits remain tolerated; retain line offsets or otherwise compare leading whitespace during branch validation.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining, with the measurement. The suggested change is the one I tried first and reverted.
render_turn strips each message before it is indexed, so the stored side never carries leading whitespace. Comparing it against unstripped probes retires turns nobody edited. Re-ran it just now against the current tree by swapping _normalise back to rstrip(): hello there on a live branch stops matching its own archived document (_document_matches_one_run([...], [' hello there', 'ok'], 2) returns False), so a pasted block that opens on a newline goes live -> retired and its recall is lost silently.
That is the trade: an indentation-only edit can leave a stale document live, against losing recall on exactly the pasted code that tends to matter. Closing the first without opening the second means carrying line offsets through the probe splitter, which is a larger change than this warrants and is written up in the _normalise docstring so the next reader does not repeat the swap.
…h, and anchor on tool calls Count the search result with the caller's own token counter instead of the ASCII heuristic, recompute the exact prompt count on every search rather than once per turn, and take the boundary anchor from a message's tool calls when it has no text, so a tool-call message no longer records an empty anchor and disables the rebase.
…rch exactly A three-message tool exchange and a four-message batch holding the same exchange render identically, so the second is skipped as a duplicate and inherited the shorter window, which the branch check then used to reject it. Grow the stored span instead, upwards only. Count the prompt exactly on every conversation search rather than only when the fit dropped nothing.
… messages A chunk's leading overlap is the previous chunk's tail, and it can carry a whole short message with it, so resuming the scan at the message the previous chunk finished in could never match it and retired unedited turns as off-branch. The forward position is still tried first and the walk back stops at the previous chunk's own opening.
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Both turns can arrive in one compaction: the pre-check clears both before either is written, the shorter is written first, and the longer then met the re-check under the write lock and left the window at the shorter figure.
…ttempt The anchor rides in every truncation event and every assistant turn's metadata while the boundary stays sticky, so a large pasted message was copied across the thread; cap it at a head on both sides, where the read side already clamps only shallower. And a budget below one chunk is not no budget: CHUNK_TOKENS is a ceiling, not the size of a turn, so try one and let the exact recount reject it.
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
The rolling window was squashed onto main, so every file both sides touched collides with our own copy of the same work. Resolved in favour of this branch, which already contains that PR's head, keeping main's unrelated changes to routes/inference.py.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2abacbb201
ℹ️ 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".
| style = ( | ||
| "tool" if "search_conversation" in _enabled_tool_names else "inline" | ||
| ), |
There was a problem hiding this comment.
Keep the recall schema on the final synthesis pass
When an existing archive makes this choose tool style, the synthetic search_conversation call and result remain in conversation and are protected from later refits. If the loop reaches its budget-exhausted final synthesis, that request is counted with tools=None and its payload omits the tools catalog, even though this block notes that strict templates reject a tool role without a matching catalog entry; those models therefore fail after completing the preceding tool work. Convert the retained recall exchange to inline form before final synthesis or keep the matching schema on that pass.
Useful? React with 👍 / 👎.
| kwargs["conversation_budget_tokens"] = max( | ||
| 1, int(rag_config.CHUNK_TOKENS) | ||
| ) * max(1, int(rag_config.CONVERSATION_ARCHIVE_TOP_K)) |
There was a problem hiding this comment.
Reserve only the provider's actual remaining headroom
For provider-routed chats, this fixed chunk allowance is unrelated to how much context remains. A custom OpenAI-compatible model whose current conversation has only a small amount of free space can still have a multi-chunk result admitted against this larger synthetic budget; the loop appends that result and the next provider request then exceeds the model's context window. Pass a budget derived from the provider/model context and current conversation when available, or use a conservative fallback that cannot authorize several chunks regardless of prompt size.
Useful? React with 👍 / 👎.
Stacked on #8961. Base branch is
feat/rolling-context-window, which is that PR's head pushed here so this can sit on top of it. Please merge #8961 first; this becomes amaindiff afterwards.Why
#8961 keeps a long chat working by dropping the oldest complete turns once the prompt overflows. That is a clear improvement on the hard error it replaces, but it is pure eviction: a dropped turn is gone for the rest of the session, and the model will state the conversation began wherever its visible context begins. Issue #7472 asked for compaction rather than plain forgetting.
This keeps the evicted turns in a per-thread searchable scope and pulls the relevant ones back on the turn that evicted them.
What the measurements say
Benchmarked on MRCR v2 (verbatim recall of a specific past assistant turn, so a summary can never pass it) with
unsloth/Qwen3.5-4B-MTP-GGUFandunsloth/Qwen3.6-35B-A3B-MTP-GGUF, both UD-Q4_K_XL, at 8k/16k/32k. Four results shaped the design.1. Retrieval is not the hard part; deciding to retrieve is. Whenever the model chose to search, the gold turn came back 100% of the time, in every cell of both models. But given only a search tool, the 35B declined to call it on 56% of rows:
2. So the first retrieval is forced, not left to the model. Same cell, same archive, 8k with 8 needles:
After the forced pass the model called the tool on 0% of rows, so the common path costs no extra round trip.
3. The archive has to be cumulative. Replaying a 32k transcript into an 8k window fires 11 compaction events. Searching every epoch scored 0.450; searching only what the latest compaction evicted scored 0.058, reaching 0.40 of 8 needles instead of 5.44. Clearing the archive per compaction is the obvious-looking simplification that reduces the feature to nothing, so there is a test pinning it.
4. No summarisation. Adding a head summary on top, the opencode/pi shape, bought nothing on the 35B (0.603 against 0.604) and hurt the 4B (0.222 against 0.373), while costing a summarisation call that took ~190s on the compaction turn. It is not in this PR.
What it does
convarchive_<thread_id>using the existing store, chunker, embedder and hybrid retrieval. Idempotent by content hash, since the same turns are evicted again on every later request.search_conversationlets the model look for anything the forced pass had no reason to fetch. It is offered only once a thread has an archive, and classified read-only so auto mode does not prompt on every call.metadata.custom.contextTruncationinside the assistant message, so it is never sent to the model, never editable and never exported as content, but it survives a reload. The toast that was the only signal before does not.The stored transcript is never modified. Everything happens on the per-request projection, and there is a test asserting it.
Compaction is an event, not a running cost
The fit #8961 shipped is stateless. The client re-sends the whole saved transcript on every request, so "keep the newest N tokens" recomputes from scratch each time and slides forward a turn or two at a time. Measured on a 40-turn thread against an 8k window, the eviction boundary moved on 12 of 40 turns. That costs three ways: the conversation quietly loses a little more every few replies, llama-server's prefix cache is discarded every time the head of the prompt moves, and there is no discrete event to tell the user about, only a permanent state of "still compacting".
Two changes make it discrete.
The boundary is now sticky. The fit reads back how many leading messages this thread last compacted away, from the newest assistant turn's own persisted truncation, and reapplies it before deciding anything. Nothing new is stored, and it survives a restart.
When the boundary does have to move, the trim takes headroom out rather than skimming to the brim, so the new boundary has room to stay put.
ROLLING_COMPACTION_HEADROOM_RATIOdefaults to 0.25.Same 40-turn thread and window, counting compactions over the following 60 turns:
Neither change alone is enough: stickiness without headroom re-compacts as soon as one turn-group of growth lands, and headroom without stickiness just moves where the sliding boundary sits.
Both are gated on the prompt not already fitting, exactly as the recall reserve is, so a conversation inside its window is never evicted to satisfy either, and a stale boundary from a branch that was rolled back cannot evict a chat that now fits. Both have their own tests.
Reuse
Nothing new was written where something existed.
core/rag/store.py,chunking.py,embeddings.py,retrieval.pyandtool._formatdo the indexing and search; the raw-text ingest followscore/rag/web_rank.py, which already ingests text with no file on disk. The synthetic tool exchange is extracted frombuild_rag_autoinjectand shared, with a golden-shape test pinning that the existing path is unchanged. The archive search reuses the document search's admission slot so the two cannot race for the embedder.The archive is a separate scope rather than the thread's document scope on purpose: with
RAG_THREAD_WHOLE_DOCon,whole_document_contextrenders every chunk of a thread's documents into every request, so archiving there would re-inject the whole history each turn and undo the compaction that produced it. There is a test for that too.Safety and configuration
RAG_CONVERSATION_ARCHIVE=0is a complete kill switch and restores #8961 behaviour exactly. AlsoRAG_CONVERSATION_ARCHIVE_TOP_K(4),RAG_CONVERSATION_RECALL_RESERVE_TOKENS(2048) andROLLING_COMPACTION_HEADROOM_RATIO(0.25, set it to 0 for the old skim-to-the-brim fit). Default on, and it only does anything once the rolling window actually evicts, which is already opt-in per request viacontext_overflow="truncate_oldest".Degradation, since none of this may break a chat: no sqlite-vec is a no-op before any connection is opened; an embedder that cannot start logs and writes nothing, and recall retries lexically so the FTS rows from earlier compactions still answer; any other exception falls back to the plain fitted messages.
The
reserve_tokensaddition tofit_rolling_contextis applied only after the "does it already fit?" check, so it can never cause eviction in a chat that fits today. That is the regression I was most worried about and it has its own test.Tests
pytest tests/on this branch and on the base commit, same command and same machine: 112 failed, 25756 passed here against 112 failed, 25716 passed on the base. The failing sets are byte-identical, so there are no regressions and 40 net new tests. Those 112 are pre-existing environment failures on this box (ahuggingface-hub1.27 vstransformerspin, and GPU-state-dependent suites); they fail the same way without this change.New:
tests/test_conversation_archive.py,tests/test_conversation_recall_injection.py, plus rolling-fit cases intests/test_context_overflow_truncation.py.Not in this PR
routes/inference.py_apply_overflow_truncation) operates on an opaque provider body after a 400 and has no thread-scoped ingest point.search_conversationtool card; it currently falls back to the raw tool name.refresh-context-usage.tsis untouched here, so it belongs in its own change.