Skip to content

feat(agent): evict stale tool results from the sent context, price-gated - #4465

Merged
itomek merged 10 commits into
mainfrom
itomek/context-eviction
Sep 29, 2026
Merged

itomek merged 10 commits into
mainfrom
itomek/context-eviction

Conversation

@itomek

@itomek itomek commented Sep 29, 2026

Copy link
Copy Markdown
Collaborator

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 #4397. Every commit from that branch is an ancestor here, authorship intact.

Test plan

  • pytest tests/unit/agents/ — 1982 passed, 50 skipped, 0 failed
  • Purely additive: git diff --stat origin/main...HEAD is 7 files, +984/−0
  • 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
🔍 Technical details

Why now. Three open PRs were shipping byte-identical copies of this module — #4384 and #4399 alongside #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 18a7917b2 f4924e35a 2c21f486e; do git merge-base --is-ancestor $c HEAD && echo "$c ANCESTOR"; done
18a7917b2 ANCESTOR
f4924e35a ANCESTOR
2c21f486e 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.

Kalin Ovtcharov and others added 10 commits September 25, 2026 15:57
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.
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.
Folds in #4397. A long session re-sends every tool result whole on every
step, so the context the model is charged for grows without bound. This
swaps results the model has moved past for a one-line stub, keeping the
full text in the artifact store and reachable through read_tool_output.

Off by default and price-gated: the 'auto' rule only fires where the
saving is worth more than the re-read.
@github-actions github-actions Bot added documentation Documentation changes llm LLM backend changes tests Test changes performance Performance-critical changes agents labels Sep 29, 2026
@itomek

itomek commented Sep 29, 2026

Copy link
Copy Markdown
Collaborator Author

41 checks pass. The 11 that don't are all either repo-wide infrastructure or pre-existing on main — none can be caused by this diff, which adds seven files and changes no existing behaviour by default.

🔍 Check-by-check
Check Cause This PR's?
8 × Scenario eval - * QUOTA EXHAUSTED (402/429-class) — the judge credential is valid but the org is out of weekly budget, resets Sep 30 08:00 PT. Every lane fails identically at the preflight step. No — repo-wide. Runs on other branches before ~11:00 today passed; everything after fails.
gaia_* judged categories vs committed baselines Downstream of the above: no baseline at tests/fixtures/eval_baselines/gaia-flagship, so nothing was compared, then no scorecards to gate on. No.
Unit Tests (Windows smoke) test_chat_completion_stream.py::test_client_disconnect_cancels_the_agent — a threading.Event.wait(timeout=5) race. Reproduced on a clean origin/main checkout locally: 1 failed, 19 passed. Result here: 1 failed, 1969 passed. No.
pr-review / run Same exhausted credential. No.

The eval gate in the test plan stays unticked on purpose — this changes what context reaches the model, so CLAUDE.md's gaia eval agent requirement genuinely applies. It cannot run until the quota resets, and it has no committed flagship baseline to compare against even then. Worth running before anyone turns eviction on in anger; not a reason to hold a default-off, purely additive change.

Local evidence: pytest tests/unit/agents/ → 1982 passed, 50 skipped, 0 failed.

@itomek
itomek added this pull request to the merge queue Sep 29, 2026
Merged via the queue into main with commit 86fb455 Sep 29, 2026
52 of 65 checks passed
@itomek
itomek deleted the itomek/context-eviction branch September 29, 2026 13:41
@kovtcharov-amd kovtcharov-amd mentioned this pull request Oct 6, 2026
5 of 10 tasks
grtninja pushed a commit to grtninja/gaia that referenced this pull request Oct 6, 2026
# GAIA v0.25.0 Release Notes

## Breaking Changes

- **`gaia chat` runs the flagship GAIA agent**, the same agent as the
TUI and Agent UI, instead of the retired ChatAgent. `gaia chat -q "…"`
queries it once. (PR [amd#4520](amd#4520))
- **`gaia talk` transcribes and speaks through Lemonade** — it uses
Lemonade's Whisper and `kokoro-v1`, and stops with the reason if
Lemonade is down. The `[audio]` extra is gone; `pip install
amd-gaia[audio]` only warns. (PR
[amd#4665](amd#4665))
- **The Agent UI runs only the GAIA agent** — the Agent Hub home, agent
picker, and custom-agent export/import are removed from the UI. The CLI
and eval harness can still run other agents. (PR
[amd#4509](amd#4509))
- **The retired nomic embedder is removed** — memory saved with it is
re-embedded on first start. (PR
[amd#4489](amd#4489))
- **Indexed documents are re-indexed once** — the document cache is now
keyed on chunking settings, so the first query after upgrading rebuilds
it. (PR [amd#4624](amd#4624))
- **A skill that asks for more than its tier allows no longer loads** —
the permission ceiling is checked at every load, so a skill already on
disk that exceeds it is refused with the reason. (PR
[amd#4849](amd#4849))

## What's New

- **A larger local model where the GPU holds it** — `gaia init` picks
Qwen3.6-35B-A3B on a 64 GB+ Strix Halo or a 32 GB GPU and keeps
Gemma-4-E4B elsewhere, with each context window sized to available
memory. Qwen3.8 Flash Next is opt-in on 128 GB Strix Halo. (PRs
[amd#4479](amd#4479),
[amd#4670](amd#4670),
[amd#4671](amd#4671),
[amd#4658](amd#4658),
[amd#4655](amd#4655))
- **The Agent UI opens straight to a chat and sets itself up** — a fresh
install runs the same setup steps as the TUI in the window, with
provider, key and model settings, permission modes, and revocable
"always allow" grants. (PR
[amd#4509](amd#4509))
- **A much smaller install** — PyTorch, transformers and accelerate are
gone from the core, `[ui]` and `[talk]` installs; the desktop app's
Python environment drops from ~0.9 GB to ~0.1 GB on Windows. (PRs
[amd#4666](amd#4666),
[amd#4621](amd#4621),
[amd#4665](amd#4665))
- **One Windows installer for the desktop app and the terminal**, with a
GAIA Windows Terminal profile. (PRs
[amd#4720](amd#4720),
[amd#4707](amd#4707))
- **A "no" holds** — a declined action isn't retried through another
tool; the agent asks again with the exact command. The TUI gains
Shift+Tab permission modes. (PRs
[amd#4460](amd#4460),
[amd#4461](amd#4461))
- **Answers are checked against what the tools actually did** — the
agent looks at files you name before answering about them, and a short
plain-English note appears only when work isn't confirmed. (PRs
[amd#4532](amd#4532),
[amd#4501](amd#4501),
[amd#4508](amd#4508))
- **One shell session** — commands share a persistent shell, risky ones
ask instead of being refused, and "full access" is one setting
everywhere. (PR [amd#4408](amd#4408))
- **Memory surfaces what's relevant to each request, with its age**,
keeps what fixed a failure as a lesson for that workspace, and extracts
after the answer instead of before it. (PRs
[amd#4061](amd#4061),
[amd#4066](amd#4066),
[amd#4406](amd#4406))
- **`gaia.log` stays bounded** — it rotates at 10 MB with three backups
(`GAIA_LOG_MAX_MB`, `GAIA_LOG_BACKUPS`). (PRs
[amd#4668](amd#4668),
[amd#4760](amd#4760))
- **Child processes get a trimmed environment** — shell, MCP and skill
children no longer inherit GAIA's internal credentials; `GAIA_NO_DOTENV`
skips loading `.env`. (PRs
[amd#4635](amd#4635),
[amd#4659](amd#4659))
- **Every file tool checks the allowed-folders rule**, and paths inside
an inline shell script are checked one by one. (PRs
[amd#4656](amd#4656),
[amd#4758](amd#4758))

## Bug Fixes

A selection of the user-visible fixes; the full list is in the changelog
below.

- **Local Qwen models no longer loop on repeated tool calls** — they run
with their model card's sampling instead of near-greedy settings. (PR
[amd#4655](amd#4655))
- **Qwen3.6 runs on a Strix Halo with an older AMD driver** — it used to
crash on its first token, so `gaia init` failed; GAIA now turns off the
Vulkan path that crashes on those drivers only, and newer drivers keep
the faster path. (PR [amd#4674](amd#4674))
- **A long PDF no longer hangs or times out while indexing** — big
documents index in the background, and PDFs that only carry
owner-password restrictions now index. (PRs
[amd#4754](amd#4754),
[amd#4679](amd#4679),
[amd#4734](amd#4734))
- **Document answers cite the right document and page**, and every chunk
is embedded whole instead of its first 1,200 characters. (PRs
[amd#4688](amd#4688),
[amd#4723](amd#4723))
- **`gaia init` fails when model verification fails**, shows downloads
live, and no longer hangs while Lemonade hashes a large model. (PRs
[amd#4620](amd#4620),
[amd#4564](amd#4564),
[amd#4673](amd#4673))
- **`gaia init` adds a profile's extras without reinstalling GAIA**,
which failed on Windows while `gaia.exe` was running. (PR
[amd#4672](amd#4672))
- **Every SDK and CLI entry point starts GAIA's own Lemonade**, and
every call goes to the resolved URL with its API key. (PRs
[amd#4657](amd#4657),
[amd#4627](amd#4627))
- **Local chat stays cached across turns** — the system prompt is fixed
and side requests no longer evict the conversation. (PRs
[amd#4698](amd#4698),
[amd#4543](amd#4543))
- **A cloud model selection never preloads a local model**, and cloud
models no longer get llama.cpp-only fields. (PRs
[amd#4757](amd#4757),
[amd#4709](amd#4709))
- **The Agent UI stops claiming "100% local" while chat goes to a cloud
model**, and the chat header names the session's real model. (PRs
[amd#4711](amd#4711),
[amd#4550](amd#4550))
- **Enter can't approve a permission prompt**, and prompts wait 10
minutes before timing out. (PRs
[amd#4700](amd#4700),
[amd#4699](amd#4699))
- **Stopping a run keeps the turn and its steps visible.** (PR
[amd#4743](amd#4743))
- **A file edit keeps the file's line endings** — a one-line edit on
Windows used to rewrite every line ending, so a small change showed up
as the whole file changed. (PR
[amd#4864](amd#4864))
- **A broken agent install is reported as broken, not as missing** — the
error names both package versions and the real import error, and
suggests a reinstall that works. (PR
[amd#4588](amd#4588))
- **A meeting or document summary is never cut off mid-sentence** — a
thinking model used to spend the summary's output budget reasoning, so a
long meeting lost its second half. (PR
[amd#4827](amd#4827))
- **"What can you do?" gets an answer** instead of an attempt to
generate an image of the question. (PR
[amd#4809](amd#4809))
- **Writes and approved edits can't reach credential folders**
(`~/.ssh`, `~/.aws`, `~/.kube` and others), and shell option values and
script arguments get the same path check as plain paths. (PRs
[amd#4848](amd#4848),
[amd#4847](amd#4847))
- **`gaia connectors connect google --grant-agent installed:gaia`
works** — it used to fail with no sign-in link for the shipped agent; it
now asks for read-only Gmail and grants exactly that. (PR
[amd#4859](amd#4859))
- **A "no" to creating a folder also covers writing into it** — GAIA no
longer asks again to create the same folder a different way. (PR
[amd#4857](amd#4857))
- **`gaia skill import` runs the same checks as a hub install** — https
only, the audit, the permission ceiling, and an explicit opt-in for
skills that ship code. (PR
[amd#4849](amd#4849))
- **Memory off and private chats apply to scheduled and background runs
too.** (PRs [amd#4842](amd#4842),
[amd#4821](amd#4821))
- **Memory stops false apologies and reusing deleted values**, saves
"remember this" requests, and skips loading the embedder when memory is
off. (PRs [amd#4708](amd#4708),
[amd#4756](amd#4756))
- **A reply cut off by the token limit is continued** instead of ending
mid-sentence, and a tool call cut off at the output cap is retried
shorter. (PRs [amd#4054](amd#4054),
[amd#4556](amd#4556))
- **The TUI remembers the chosen model** across restarts and
agent-process restarts. (PRs
[amd#4497](amd#4497),
[amd#4710](amd#4710))
- **`gaia uninstall --purge` removes installer binaries, PATH edits and
daemon state.** (PR [amd#4413](amd#4413))

## Contributors

Thanks to the community members who contributed to this release:

- [@itomek](https://github.com/itomek) — the flagship's browser and tool
picker, one shell session, memory extraction off the answer path, stale
tool-result eviction, the TUI's sourced Fireworks rankings, and
`--purge` cleanup (PRs [amd#4407](amd#4407),
[amd#4408](amd#4408),
[amd#4406](amd#4406),
[amd#4465](amd#4465),
[amd#4414](amd#4414),
[amd#4413](amd#4413))
- [@mikemikimike](https://github.com/mikemikimike) — chained shell
command timeouts, bundled skills in frozen builds, and sidecar cleanup
reporting (PRs [amd#4463](amd#4463),
[amd#4467](amd#4467),
[amd#4419](amd#4419))
- [@Hashim1999164](https://github.com/Hashim1999164) — honoring
`GAIA_HOME` for cache, chat and index paths (PR
[amd#4381](amd#4381))
- [@krtadev](https://github.com/krtadev) — `~` expansion in file and
document tool paths (PR [amd#4576](amd#4576))
- [@aksh8b](https://github.com/aksh8b) — telling a broken agent install
apart from a missing one, with a reinstall hint that works (PR
[amd#4588](amd#4588))
- [@Dev-next-gen](https://github.com/Dev-next-gen) — numeric prerelease
ordering in the hub (PR [amd#4517](amd#4517))
- [@vianmangal](https://github.com/vianmangal) — recording denied tool
calls as unsuccessful in memory (PR
[amd#4412](amd#4412))
- [@GaetanVDB07](https://github.com/GaetanVDB07) — links to upstream
credential setup guides for connectors (PR
[amd#4669](amd#4669))
- [@rradjabi](https://github.com/rradjabi) — moving self-hosted CI jobs
to the xsj-dispatch runner pool (PR
[amd#4534](amd#4534))




## Also in this PR

- **Hub floors raised to core 0.25.0** — the chat agent imports the
allowed-folders check that only 0.25.0 ships (amd#4656), so
`gaia-agent-chat` goes to 0.2.0 with `amd-gaia>=0.25.0`, and the
flagship requires `amd-gaia>=0.25.0` and `gaia-agent-chat>=0.2.0`.
- **Two follow-ups held back until that floor could rise** —
`~/.gaia/logs/gaia-agent.log` now rotates like `gaia.log` (amd#4668), and
the chat agent's Python runners and Windows notification start their
children without GAIA's internal credentials (amd#4659).

The full changelog (300 commits) is in `docs/releases/v0.25.0.mdx`.

## Test plan

- [x] `util/validate_release_notes.py docs/releases/v0.25.0.mdx --tag
v0.25.0` passes; narrative is 590 words (cap 600)
- [x] `util/check_component_core_api.py --release-version 0.25.0` passes
- [x] `pytest tests/unit/test_docs_json_release.py
tests/unit/test_check_component_core_api.py
hub/agents/chat/python/tests/test_chat_dependency_floor.py
hub/agents/chat/python/tests/test_dependency_floor.py
hub/agents/gaia/python/tests/test_gen_binaries_lock.py` (72 passed)
- [x] `pytest hub/agents/gaia/python/tests/test_stdio.py` (91 passed,
incl. the new rotation test); `pytest
tests/unit/test_execute_python_file_cwd.py
tests/unit/test_run_python_tool.py` (42 passed)
- [ ] `mintlify validate` (docs CI job) — timed out locally, relying on
CI
- [x] Full flagship eval on main 9ce6598
(https://github.com/amd/gaia/actions/runs/37436249503): 181/308
scenarios pass vs 100/183 for the same categories in the baseline, 39
FAIL→PASS, 13 PASS→FAIL (two fixed in amd#4878, held until after rc1);
retrieval lane still finishing at merge time
- [ ] CI green

## Release checklist

- [ ] Publish `gaia-agent-chat` 0.2.0 only after core 0.25.0 is on PyPI
— it fails at import on an older core
- [ ] Build Installers on the merged SHA (pre-tag verification) before
pushing `v0.25.0`
- [ ] terminal-hub 0.25.0 published before the flagship npm release
consumes `binaries.lock.json`

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: Kalin Ovtcharov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes llm LLM backend changes performance Performance-critical changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants