Repository navigation
feat(agent): evict stale tool results from the sent context, price-gated - #4397
kovtcharov wants to merge 9 commits into
Conversation
Every tool result is re-sent on every later step, and on a real 144K-line repository accumulated results were 83% of the conversation. An over-budget result now reaches the model as the parts that fit plus an index of the rest, split where the document splits: functions and methods, headings, JSON records, a search's files, test sections, diff hunks, paragraphs. Each index entry is an exact offset/length that read_tool_output returns verbatim, so nothing is lost and no new tool is needed. check_result and the other result fields stay in view. A remote model reached through Lemonade gets its own budget (8,000/6,000 chars) sized by re-send cost; 46% of the benchmark's result bytes sat above 8,000. Local NPU/GPU budgets are unchanged. Replaying 12 benchmark transcripts offline, tool-result characters re-sent fall 29.7% (23.9% if every condensed result is read back once). The message backstop now caps at the threshold the gate passes, not the smaller target, so results between the two are no longer cut unarchived; a read_tool_output page is never condensed again.
…n view Index entries could be longer than the 8,000-char page read_tool_output allowed, so the model was told to make a call that failed: a 1 MB Python file had every entry over the limit, and a 50,000-char stdout line was one. A read now takes any length, returns at most one page, and reports `remaining` with `next_offset` to continue, so every entry reads back exactly. When one line too long to split is most of a result, the result keeps its head and tail in view with the middle indexed, instead of showing only the first line. Search matches with no file group under "(no file)" instead of crashing, and a text `context` is one line, not one per character. On NPU, a non-string tool result between 20,000 and 30,000 chars now reaches the model whole, where the message backstop used to cut it to 20,000 without archiving it; that path wants an NPU eval before merge.
On a live GLM run the model ignored the index and paged through whole archived outputs 8,000 chars at a time, re-sending every file on top of its condensed copy, because the reader advertised offset/limit with 8,000 as the page size. Index entries are now numbered, read_tool_output(artifact, entry=n) returns exactly that part, and every condensed result carries a `fetch` line saying so. The docstring leads with the entry, lets limit default to the entry's length, and says paging through a whole output is almost never needed. offset/limit still work; an entry number outside the index is an error that names the valid range.
The 8,000-char cloud threshold made files of 20-30K chars, which the model needs whole to edit, arrive indexed; it then read them back one entry per round trip, so steps rose and tokens did not fall (GLM, 4 tasks: 8.39M vs 8.29M; DeepSeek's worst task: 77 vs 72 steps, 20 entry reads). A remote model reached through Lemonade again gets truncation_budget(None), as before. The index, numbered entry reads, the fetch field, paging and the message-backstop change stay: the index now applies only to results over the device threshold, where it keeps every omitted byte reachable.
On a 144K-line repository the context the agent re-sends each step reaches
130-195K tokens, 83% of it old tool results the model has already acted on.
Whether dropping them saves money depends on the provider's cached-versus-
uncached input price: every eviction changes the prompt prefix, so the next
call re-reads everything after the eviction point uncached once. Simulated
on real per-step counts, Kimi K2.7 (cached $0.19/M vs $0.95/M) saves 27%,
GLM-5.3 Flash 11%, and DeepSeek V4.1 Flash (0.006 vs 0.30) loses.
This is not the context compaction the roadmap rules out ("memory + RAG
handles long conversations"): nothing is summarised or dropped. An evicted
result is archived whole in the agent's ArtifactStore and its message in the
list sent to the model becomes a one-line stub naming the read_tool_output
call that fetches it; a result that already arrived as a chunk index keeps
its handle and index. The turn's conversation log is never touched. It is
off by default.
context_eviction is off | on | auto (GAIA_CONTEXT_EVICTION wins). auto is
on only for a cloud model whose cached/uncached input price ratio, from the
table in gaia.llm.cache_pricing, is at least 0.1; a local or unknown model
is off, said once at info level, never guessed. Eviction fires at the head
of a step only when the previous step's measured prompt_tokens exceed
context_eviction_threshold_tokens (60000, GAIA_EVICT_THRESHOLD) and the
results older than context_eviction_keep_steps (8, GAIA_EVICT_KEEP) add up
to context_eviction_min_batch_tokens (30000, GAIA_EVICT_MIN_BATCH); then all
of them go in one batch and stay evicted, so the prefix is deterministic
afterwards. read_tool_output pages and delegate_task results are never
evicted; user and assistant messages are never changed. Each batch adds
evicted_results and evicted_tokens_est to that step's stats record and logs
one info line. Malformed env values or arguments fail at construction.
Kimi K3 lists at $3.00 input, $0.30 cached, $15 output on Fireworks (2026-09-26), a 0.10 ratio, so auto eviction turns on for it.
# Conflicts: # src/gaia/agents/base/agent.py
|
Resynced onto current main and pushed — the branch is mergeable again (no more merge conflict), still a draft. Note for the record: #4379 is still open, not merged, so the conflict here wasn't from that landing — it was regular drift on Tests: Before this can merge: a |
|
Verdict: Request changes This adds an opt-in, price-aware policy that swaps old tool results in the context sent to the model for one-line stubs, with the full text kept in the artifact store and readable through One blocking issue: in a multi-turn chat, eviction stops working after the first turn. The agent remembers which results it already evicted, but the next turn reloads the saved history with those results back at full size. Because they're still marked "already evicted", they're never evicted again. In the Agent UI, which keeps one agent per session and replays full history, a long session drifts back to the context size this PR is meant to cut. Decide "already evicted" from the message itself (is it a stub?) rather than from the remembered IDs, and add a two-turn test. Real-world evidenceN/A — no evidence bundle was produced for this run. The change is an internal, off-by-default agent-loop policy with no new CLI, REST, MCP, or UI surface. The PR description reports live cost runs (Kimi K3 −30%, GLM-5.3 Flash −22%, DeepSeek worse as predicted), but those were single-turn tasks, so they don't cover the multi-turn issue above. This verdict rests on static review. 🔍 Technical details🟡 ImportantResults evicted in one turn come back at full size, and stay pinned, from the next turn on (
(Remove the later
🟢 Minor
Strengths
|
…pick (amd#4414) Picking a Fireworks model in the TUI showed a rank and a three-word label — "best overall, cheapest" — with nothing to say what that was measured on or what a run costs. Focusing a ranked model now shows the measurement behind its label: tasks solved, judged quality, and the dollar cost of one pass. Every figure on that line is the model's own row in the benchmark table published in amd#4335, and a test fails if the two ever drift apart. This replaces amd#4385 (@kovtcharov's `feat/tui-benchmarked-fireworks-models`). All three of its commits are ancestors here, authorship intact; the difference is that the TheRock half of each line is gone. Neither TheRock quality score — 3.69/5 for GLM, 4.44/5 for DeepSeek — is published anywhere a reader can reach, and amd#4335 says so itself: "TheRock tier results will be added once its reruns complete." A line labelled `Measured:` that a user cannot trace is the thing this repo's evidence rule exists to prevent, so the untraceable half was removed rather than sourced. The everyday-suite figures stay, because they match amd#4335's table cell for cell. ## Test plan - [x] `go build ./...` and `go vet` clean on the whole `tui` module (Go 1.26.3, Strix Halo) - [x] `go test ./...` — 21 of 23 packages pass; the two that don't are `internal/ui/chat` and `internal/ui/preflight`, which fail identically on plain `main` (a headless clipboard read and a Lemonade autostart, both hanging until the timeout, neither touched by this change) - [x] Drift guard proven by breaking it: changing `4.89` to `4.95` fails `TestEvidenceIsTranscribed` with the published cell named - [x] Rendered panel captured: rank 1 and 2 show their `Measured:` line, rank 3 (no published figures) and an unranked model show none - [x] `python util/check_doc_links.py --internal-only` — 1042 links, 0 broken - [ ] With a Fireworks key: `/provider` → Fireworks AI → focus `glm-5p3-flash` against a live account <details> <summary>🔍 Provenance check: which figures have a source</summary> Every figure in amd#4385 was searched for across the whole tree, every PR body in the repo's last 120 PRs, and every issue comment on the last 60. | Figure | Model | Source | | |---|---|---|---| | 14/14, 4.89, $0.09, 7:04 | GLM-5.3 Flash, everyday | amd#4335 merged body, GAIA row | traceable | | 14/14, 4.92, $0.10, 5:39 | DeepSeek V4.1 Flash, everyday | amd#4335 merged body, GAIA row | traceable | | 4/4, 3.69, $0.42 | GLM-5.3 Flash, TheRock | only amd#4397, still open | not citable | | 4/4, 4.44, $0.47 | DeepSeek V4.1 Flash, TheRock | cost only — `docs/plans/nightly-benchmarks.mdx` puts DeepSeek's `therock` pass at `~$0.47`; the 4.44 quality score nowhere | not citable | `14/14` and `4/4` denominators are independently checkable: `eval/tasks/tasks.json` defines `everyday` as 14 tasks and `therock` as 4. ``` $ rg -n --fixed-strings 4.89 . ./tui/internal/lemonade/cloud.go:39: Evidence: "14/14 tasks · quality 4.89/5 · $0.09 per 14-task run · TheRock 4/4, 3.69/5, $0.42", ./docs/guides/ai-providers.mdx:55:| GLM-5.3 Flash | `fireworks.glm-5p3-flash` | 14/14 solved, quality 4.89/5, $0.09 per run, 7:04 | 4/4, quality 3.69/5, $0.42 | $ gh pr list -R amd/gaia --state all --limit 120 --json number,title,body | python -c "<scan for 3.69 / 4.44 / \$0.42 / \$0.47>" scanned 120 PRs 4397 feat(agent): evict stale tool results from the sent context, ['3.69', '$0.42'] 4385 feat(tui): show the measurement behind each ranked Fireworks ['3.69', '$0.42'] $ <same scan over issue comments on the 60 most recent PRs> no comment on the last 60 PRs contains 4.44 / $0.47 / 3.69 / $0.42 ``` Corrected after review: an earlier version of this table said `$0.47` was sourced nowhere. It is in `docs/plans/nightly-benchmarks.mdx` on `main` (line 37 and the `therock` row), attributed to DeepSeek V4.1 Flash under a column headed "Cost per pass (measured)". That is a planning estimate for the suite rather than a published per-model cell, and the `4.44/5` quality score in the same trailer still has no source, so the trailer still cannot ship — but the claim as written was wrong. `$0.42` does have zero occurrences anywhere. amd#4397 is open, and carries the GLM row only, as an aside: "the earlier GLM TheRock row without eviction: 3.69, $0.42". The DeepSeek TheRock figures have no public source at all. </details> <details> <summary>🔍 Ancestry, build, tests, and the rendered panel</summary> Every commit of amd#4385 is an ancestor of this branch: ``` $ git merge-base --is-ancestor e472abc HEAD; echo $? 0 $ git merge-base --is-ancestor 56eadd4 HEAD; echo $? 0 $ git merge-base --is-ancestor bfa1070 HEAD; echo $? 0 ``` Build and vet, on Strix Halo (no Go toolchain on the authoring machine): ``` $ go version go version go1.26.3 linux/amd64 $ gofmt -l internal/lemonade internal/ui/providers $ go build ./... ; echo BUILD_EXIT=$? BUILD_EXIT=0 $ go vet ./internal/lemonade/... ./internal/ui/providers/... VET_OK ``` Full module, this branch: ``` $ go test -timeout 150s ./... ok github.com/amd/gaia/tui/internal/catalog 0.004s ok github.com/amd/gaia/tui/internal/cli 0.012s ok github.com/amd/gaia/tui/internal/client 9.834s ok github.com/amd/gaia/tui/internal/control 0.859s ok github.com/amd/gaia/tui/internal/daemon 0.325s ok github.com/amd/gaia/tui/internal/event 0.011s ok github.com/amd/gaia/tui/internal/gaiainit 0.007s ok github.com/amd/gaia/tui/internal/gaiaslack 0.018s ok github.com/amd/gaia/tui/internal/lemonade 0.014s ok github.com/amd/gaia/tui/internal/ui 0.169s ok github.com/amd/gaia/tui/internal/ui/agents 0.009s ok github.com/amd/gaia/tui/internal/ui/brand 0.010s ok github.com/amd/gaia/tui/internal/ui/cards 0.040s FAIL github.com/amd/gaia/tui/internal/ui/chat 150.015s ok github.com/amd/gaia/tui/internal/ui/components 1.096s ok github.com/amd/gaia/tui/internal/ui/gateway 0.005s FAIL github.com/amd/gaia/tui/internal/ui/preflight 150.007s ok github.com/amd/gaia/tui/internal/ui/providers 0.003s ok github.com/amd/gaia/tui/internal/ui/root 0.015s ok github.com/amd/gaia/tui/internal/ui/status 0.001s ok github.com/amd/gaia/tui/internal/ui/theme 0.104s ok github.com/amd/gaia/tui/test 112.666s ok github.com/amd/gaia/tui/test/mockagent 0.001s ``` Same two packages, same two tests, on plain `origin/main` — pre-existing and environmental, not from this change: ``` this branch: origin/main: running tests: running tests: TestCtrlVReadsTheClipboard (2m30s) TestCtrlVReadsTheClipboard (2m30s) running tests: running tests: TestADownLemonadeOffersTheOneKeySetup TestADownLemonadeOffersTheOneKeySetup FAIL .../internal/ui/chat 150.015s FAIL .../internal/ui/chat 150.016s FAIL .../internal/ui/preflight 150.007s FAIL .../internal/ui/preflight 150.008s ``` The drift guard, proven by breaking it: ``` $ sed -i 's|quality 4.89/5|quality 4.95/5|' internal/lemonade/cloud.go $ go test -run TestEvidenceIsTranscribed ./internal/lemonade/... --- FAIL: TestEvidenceIsTranscribed (0.00s) cloud_test.go:210: fireworks.glm-5p3-flash: evidence "14/14 tasks · quality 4.95/5 · $0.09 per 14-task run" dropped published cell "4.89" FAIL $ <restore> ok github.com/amd/gaia/tui/internal/lemonade 0.002s ``` The panel as rendered, walking focus down the list: ``` › glm-5p3-flash · #1 best overall, cheapest deepseek-v4p1-flash · #2 fastest deepseek-v4-pro-0813 · #3 most truthful plain-model 1 of 4 Measured: 14/14 tasks · quality 4.89/5 · $0.09 per 14-task run glm-5p3-flash · #1 best overall, cheapest › deepseek-v4p1-flash · #2 fastest deepseek-v4-pro-0813 · #3 most truthful plain-model 2 of 4 Measured: 14/14 tasks · quality 4.92/5 · $0.10 per 14-task run glm-5p3-flash · #1 best overall, cheapest deepseek-v4p1-flash · #2 fastest › deepseek-v4-pro-0813 · #3 most truthful plain-model 3 of 4 ← no published figures, so no line ``` </details> <details> <summary>🔍 Merge-order note for amd#4176 and amd#4265</summary> Both rewrite `RecommendedModels` into a registry-populated slice whose populating line copies only two fields (`tui/internal/lemonade/recommended.go:70` — `Recommendation{ID: r.ID, Note: r.Note}`) and drop `Evidence` from the struct entirely. Landing this first does **not** silently drop the evidence: it produces a hard conflict a human has to resolve. ``` $ git merge-tree --write-tree itomek/tui-measured-evidence pr4176 CONFLICT (content): Merge conflict in tui/internal/lemonade/cloud.go CONFLICT (content): Merge conflict in tui/internal/ui/providers/model.go $ git merge-tree --write-tree itomek/tui-measured-evidence pr4265 CONFLICT (content): Merge conflict in tui/internal/lemonade/cloud.go CONFLICT (content): Merge conflict in tui/internal/ui/providers/model.go CONFLICT (content): Merge conflict in tui/internal/ui/providers/model_test.go ``` Stages 1, 2 and 3 are all present, so it is an ordinary content conflict with a shared base, not an add/add. Whoever resolves it needs to carry `Evidence` and `EvidenceSource` into the registry shape, or `TestEvidenceIsTranscribed` and the `Measured:` line go with it. Both PRs already conflict with `main` on `hub/agents/gaia/npm/CHANGELOG.md` independently of this. </details> Replaces amd#4385 — leave that one open for @kovtcharov to close or keep. --------- Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov-amd
left a comment
There was a problem hiding this comment.
Independent review, confirming and extending the earlier automated finding.
Confirmed: eviction is permanently disabled for every result after turn 1, in exactly the use case this PR targets (long Agent UI sessions).
Traced the actual mechanism in the current HEAD (f50f493a4):
ContextEvictor.begin_turn()(context_eviction.py:210) clears_result_stepbut never_evicted.TurnMessages.append()(history.py:24) deep-copies each message intoself.recordedbeforeevict()runs.evict()mutates the livemessageslist viamessages[i] = {...}(context_eviction.py:274), which — sinceTurnMessagesdoesn't override__setitem__— never touchesself.recorded. Sofinish()(history.py:31) always returns the full, un-evicted text, and that's what becomesresult["model_messages"].- On the next turn,
messages.extend(self.conversation_history)(agent.py) replays those full-content messages back intomessagesunder their originaltool_call_ids — which are already sitting inself._evictedfrom turn 1'sevict()call.evict()'s candidate filter (context_eviction.py:243) skips any key already in_evicted, so these full-size results are never eligible for eviction again, on any future turn.
Net effect: the first eviction batch is the last one a session ever gets. Every result evicted on turn 1 comes back at full size on turn 2 and stays that way for the rest of the session — the exact context-growth pattern (130-195K tokens on a long-running session) that motivates this PR. Single-turn tests all pass because none of them exercise a second process_query call with conversation_history seeded from the first — there's no test in test_context_eviction.py that does this.
Confirmed this is still present on the branch tip and wasn't addressed after the earlier review flagged it (no commits since 2026-09-26T17:38 PDT).
Two smaller points, both already noted, still open:
- The re-fetch hint on an already-indexed result (
context_eviction.py:266,offset=0, limit=8000) drops the index/entry numbering, so the model can no longer address a specific entry by number — only re-page the whole archive. key = call_id if isinstance(call_id, str) else f"#{i}"(context_eviction.py:240) is position-based when a tool message lacks a string id; low risk today since_create_tool_messagealways sets one, but worth a comment noting the assumption.
Not a bug, but worth being explicit about in the description: NEVER_EVICTED_TOOLS exempts read_tool_output and delegate_task but not ordinary file-read tools. A read-then-edit pattern that's more than keep_steps (default 8) steps apart will see the read result replaced by a stub before the edit step — recoverable (the model can re-fetch via the stub's handle, and edits presumably re-read the file from disk rather than trusting stale context), but it does mean an edit decision made off the stub alone, without re-fetching, is working from a one-line summary instead of the real content. Given keep_steps=8 this should be rare in practice, but it's the kind of thing an eval run (not unit tests) would actually surface.
Also worth flagging: the branch's stacked dependency, #4379 (chunk index), merged to main today. Re-merging main now produces real content conflicts in chunk_index.py/test_chunk_index.py (5 separate hunks in a 1160-line file) — no longer the trivial adjacent-line drift from the last resync, since main now carries its own independently-evolved copy of the file this PR was stacked on. That reconciliation needs to happen before CI signal here means anything current.
Given the above, and that this changes what context reaches the model on every step, I'd want the multi-turn fix plus a two-turn regression test, the post-#4379 rebase, and a gaia eval agent run (blocked by #4080 until 2026-09-30) before this merges.
The turn log always keeps a result's pre-eviction copy, so a session that persists conversation_history across turns (the Agent UI's per-session cached agent) replays every evicted result at full size on the next turn, under its original tool_call_id. ContextEvictor tracked "already evicted" by that id in a set that begin_turn() never cleared, so once a result was evicted once it was exempt forever -- every following turn re-sent it in full, and a long session drifted back to the context size eviction exists to cut. Judge eligibility from each message's own text (a stub already, or not) instead of a remembered id. A result replayed at full size is treated as a fresh candidate and gets evicted again once it re-ages past keep_steps, so eviction keeps working for the life of the session rather than just its first turn. Adds a regression test with two process_query calls on one agent, feeding turn 1's model_messages back as conversation_history -- it fails against the old id-keyed set and passes with the content-keyed check.
|
Keeping this open — it's current, it's additive, and the multi-turn problem from the last review is fixed here. Worth flagging: #4384 and #4399 both carry this same eviction module, and both are carrying the pre-fix copy — byte-identical to each other and older than what's on this branch. So whichever order these land in, this branch's version is the one to keep. One catch if this goes first: the copy here drops the session-findings tool from the never-evict list, because that tool doesn't exist on main yet. #4384 will need to add it back when it brings the delegation tools in, or its own subtask digests become evictable. The red checks aren't yours. All three unit lanes fail on the same single test in the API streaming path — nothing this change touches, and the policy is off by default and off for local models regardless, so it can't be reached from there. Two things before it goes in. The eval run this needs is still blocked by #4080, and the two minor points from the review are still open: the re-fetch hint on an already-indexed result loses the entry numbering, and the positional fallback key could use a one-line comment naming its assumption. Neither blocks — fold them in or tell me you'd rather not, and I'll take it as is once the judge credit is back. 🔍 Technical detailsCurrent, and additive. Tip The fix. Diffing the module against the copy on #4384/#4399: the Main has none of it. Duplication, not a stack.
Red checks. Linux, Windows smoke and macOS smoke each fail on exactly Inert when off. Open minors. |
|
Landed on The content went in whole — all five files are byte-identical between this branch's head and Worth saying plainly: the merge squashed to a single parent, so the individual commit SHAs from this branch aren't ancestors of Your multi-turn fix ( Two things carried forward rather than resolved:
|
…ted (amd#4465) A long session re-sends every tool result in full on every step, so the context the model is charged for grows without bound — a big `grep` early in a session keeps costing on every turn after it. This swaps results the model has already moved past for a one-line stub, keeping the full text in the artifact store and reachable through `read_tool_output` if the model wants it back. Off by default. `auto` only fires where the saving is worth more than the re-read, using the provider's cached-input price ratio, and a mode it doesn't recognise raises rather than quietly falling back. Replaces amd#4397. Every commit from that branch is an ancestor here, authorship intact. ### Test plan - [x] `pytest tests/unit/agents/` — **1982 passed, 50 skipped, 0 failed** - [x] Purely additive: `git diff --stat origin/main...HEAD` is **7 files, +984/−0** - [x] Off by default confirmed in source: `context_eviction: str = "off"` (`agent.py:1364`), and `context_eviction_from_env()` returns `None` when `GAIA_CONTEXT_EVICTION` is unset - [ ] `gaia eval agent` — this changes what context reaches the model, so CLAUDE.md's eval gate applies before this is relied on in anger <details> <summary>🔍 Technical details</summary> **Why now.** Three open PRs were shipping byte-identical copies of this module — amd#4384 and amd#4399 alongside amd#4397. Those two are closed; this is the surviving copy, and the only one carrying the multi-turn fix. **The bug that was blocking it is fixed.** The first review found that eviction stopped working after turn one: the agent remembered which results it had evicted by `tool_call_id`, but the next turn reloaded saved history with those results back at full size and still marked "already evicted", so they were never re-stubbed. `18a7917b2` ("keep evicting stale tool results past a session's first turn") fixes it, and the suite covers it. **Ancestry**, with original authorship preserved by merge rather than squash: ``` $ for c in 18a7917 f4924e3 2c21f48; do git merge-base --is-ancestor $c HEAD && echo "$c ANCESTOR"; done 18a7917 ANCESTOR f4924e3 ANCESTOR 2c21f48 ANCESTOR ``` **One thing to watch.** `cache_pricing.py` hardcodes vendor list prices captured 2026-09-26. Nothing detects drift. The design is deliberate under the no-silent-fallbacks rule — an unknown model logs once and stays off rather than guessing a ratio — but whether a hand-maintained price table belongs in-tree is worth a separate decision. </details> --------- Co-authored-by: Kalin Ovtcharov <[email protected]> Co-authored-by: Kalin Ovtcharov <[email protected]> Co-authored-by: Kalin Ovtcharov <[email protected]>
On a large repository the context GAIA re-sends to the model on every step grows to 130–195K tokens, most of it old tool results the model no longer needs in front of it. This adds an opt-in policy that evicts tool results older than a few steps out of the sent context into the session artifact store, where every byte stays fetchable with
read_tool_output, and replaces each with a one-line stub naming what it was and how to get it back. Transcripts keep the full results. Nothing is summarised, so this is not the context compaction the project rules out; it is an index pointer where a stale result used to be.The policy is price-aware because every eviction changes the prompt prefix and the next call re-reads the rest uncached once. Whether that pays depends on the provider's cached-vs-uncached input price: simulated with real per-step counts, Kimi K2.7 Code saves 27% and GLM-5.3 Flash 11%, while DeepSeek V4.1 Flash (cached input at 2% of the uncached price) loses.
autotherefore turns it on only for models whose cached price is at least a tenth of the uncached one; unknown or local models stay off, and it is off by default. Evictions happen in batches (default: when the context passes 60K tokens and at least 30K tokens can go), so the cache is broken rarely.Stacked on #4379 (chunk index: the archive and paging the stubs point to).
Test plan
pytest tests/unit/agentsplus the flagship wiring test — 1579 passed, 50 skipped on this branch; 21 eviction tests: off by default sends identical messages; batches fire only past the threshold and minimum batch, only for results older than the keep window; stubs read back the exact original from the store; already-indexed results keep their handle;read_tool_outputand delegation results are never evicted; user and assistant messages untouched; the transcript log keeps every result;autoper the price table incl. unknown models; env overrides and malformed values fail loudly; evictions recorded in the step's statsautokeeps it off there). Short task, three pairs on GLM and DeepSeek: differences inside the run spread. Context peak −40% on every model. Off by default;autoapplies the ratio rule.Validation pass (2026-09-26, integration build with this and #4399 on,
GAIA_CONTEXT_EVICTION=auto). GLM-5.3 Flash, whereautoturns eviction on: 14 everyday tasks 13/14, quality 4.71, $0.095; TheRock 4/4, closed-book quality 4.75, $0.27 (the earlier GLM TheRock row without eviction: 3.69, $0.42); eviction fired twice per open-book task, ~30K tokens each, never on the closed-book tasks (peak prompt under the 60K threshold). DeepSeek V4.1 Flash, whereautokeeps it off: 14/14, 4.96, $0.086 and 4/4, closed-book 3.62, $0.31 — within one-run spread of its baselines. The one everyday miss (GLM code review) was traced to the test-claim correction, not eviction; fixed in #4401.