Skip to content

Studio: keep and search the turns rolling context evicts - #9074

Merged
danielhanchen merged 108 commits into
mainfrom
feat/conversation-archive
Aug 20, 2026
Merged

danielhanchen merged 108 commits into
mainfrom
feat/conversation-archive

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 17, 2026 •

Copy link
Copy Markdown
Member

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 a main diff 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-GGUF and unsloth/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:

score
35B, rows where it searched 0.461
35B, rows where it did not 0.099

2. So the first retrieval is forced, not left to the model. Same cell, same archive, 8k with 8 needles:

arm 4B 35B
plain eviction (#8961 today) 0.169 -
search tool only 0.216 0.258
forced recall on the compaction turn + tool 0.373 0.604
oracle (gold turn injected directly) 0.567 0.960

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

  • When the rolling window evicts turns, they are indexed into 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.
  • On the turn that evicted, one retrieval runs against the archive and is attached to the request. The tool loop renders it as an ordinary tool exchange through the builder now shared with document auto-inject, so it appears as a normal tool card with citations. 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.
  • search_conversation lets 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.
  • A system-prompt note tells the model the session was compacted, gated on the tool being present.
  • Deleting a thread drops its archive.
  • The transcript carries a notice on each turn where the boundary moved, rendered from metadata.custom.contextTruncation inside 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_RATIO defaults to 0.25.

Same 40-turn thread and window, counting compactions over the following 60 turns:

headroom compactions prompt kept
0 (today) 14 6801
0.10 7 6401
0.25 (default) 4 5601
0.40 3 4521

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.py and tool._format do the indexing and search; the raw-text ingest follows core/rag/web_rank.py, which already ingests text with no file on disk. The synthetic tool exchange is extracted from build_rag_autoinject and 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_DOC on, whole_document_context renders 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=0 is a complete kill switch and restores #8961 behaviour exactly. Also RAG_CONVERSATION_ARCHIVE_TOP_K (4), RAG_CONVERSATION_RECALL_RESERVE_TOKENS (2048) and ROLLING_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 via context_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_tokens addition to fit_rolling_context is 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 (a huggingface-hub 1.27 vs transformers pin, 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 in tests/test_context_overflow_truncation.py.

Not in this PR

  • The provider-passthrough overflow path (routes/inference.py _apply_overflow_truncation) operates on an opaque provider body after a 400 and has no thread-scoped ingest point.
  • A frontend label for the search_conversation tool card; it currently falls back to the raw tool name.
  • The context readout after a page reload races between the exact restored usage and a whole-thread estimate. It predates this branch and reproduces on the base, and refresh-context-usage.ts is untouched here, so it belongs in its own change.

alkinun and others added 27 commits August 16, 2026 09:24
…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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.

@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: 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".

Comment on lines +149 to +151
digest = hashlib.sha256(text.encode("utf-8", "ignore")).hexdigest()
if store.document_by_hash(conn, scope, digest):
continue

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

danielhanchen and others added 3 commits August 19, 2026 19:20
…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.

@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: 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".

Comment on lines +3408 to +3411
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"]

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex 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: 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()

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

danielhanchen and others added 3 commits August 19, 2026 20:30
…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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 19, 2026 21:54
… 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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 43fb8de953

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

danielhanchen and others added 3 commits August 19, 2026 22:19
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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 2b4df6aebd

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

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.

@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: 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".

Comment on lines +22535 to +22537
style = (
"tool" if "search_conversation" in _enabled_tool_names else "inline"
),

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

Comment on lines +1239 to +1241
kwargs["conversation_budget_tokens"] = max(
1, int(rag_config.CHUNK_TOKENS)
) * max(1, int(rag_config.CONVERSATION_ARCHIVE_TOP_K))

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

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.

1 participant