Skip to content

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

Closed
kovtcharov wants to merge 9 commits into
amd:mainfrom
kovtcharov:feat/context-eviction
Closed

kovtcharov wants to merge 9 commits into
amd:mainfrom
kovtcharov:feat/context-eviction

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

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. auto therefore 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/agents plus 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_output and delegation results are never evicted; user and assistant messages untouched; the transcript log keeps every result; auto per the price table incl. unknown models; env overrides and malformed values fail loudly; evictions recorded in the step's stats
  • black, isort, flake8, pylint clean on changed files
  • Live, TheRock, same judge and meter (Kimi K2.7 Code was undeployed by Fireworks on 2026-09-26; Kimi K3, ratio 0.10, stood in). Heavy task, one pair per model: Kimi K3 $1.83 → $1.27 (−30%, quality 3.50 → 4.25), GLM-5.3 Flash $0.105 → $0.082 (−22%, 4.25 → 4.50), DeepSeek V4.1 Flash $0.08–0.16 across three off runs → $0.23 (loses, as the price ratio predicts; auto keeps 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; auto applies the ratio rule.

Validation pass (2026-09-26, integration build with this and #4399 on, GAIA_CONTEXT_EVICTION=auto). GLM-5.3 Flash, where auto turns 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, where auto keeps 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.

Kalin Ovtcharov added 5 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.
@github-actions github-actions Bot added documentation Documentation changes llm LLM backend changes tests Test changes performance Performance-critical changes agents labels Sep 26, 2026
kovtcharov and others added 2 commits September 26, 2026 04:08
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.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

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 main (a step_timer-based stats-recording change unrelated to eviction). The one real conflict was in agent.py, where both sides touched the per-step stats block; resolved so the new step-timer accounting and the eviction stats (_pending_eviction, _context_evictor.note_prompt_tokens) both run.

Tests: tests/unit/agents (1677 passed, 55 skipped) plus the flagship wiring test (test_context_eviction_wiring.py) all pass. One pre-existing failure, test_chunk_index.py::test_search_groups_by_file_and_leads_with_each_files_first_match — a Windows path-separator mismatch (/ vs \) — reproduces identically on the pre-resync branch, so it's unrelated to this merge. black/isort/flake8 clean on the changed files.

Before this can merge: a gaia eval agent run, since it changes what context reaches the model on every step.

@github-actions

Copy link
Copy Markdown
Contributor

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 read_tool_output. It's off by default, the auto rule is conservative, and the single-turn behaviour is well tested.

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 evidence

N/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

🟡 Important

Results evicted in one turn come back at full size, and stay pinned, from the next turn on (src/gaia/agents/base/context_eviction.py:2133, the key in self._evicted skip)

  • ContextEvictor.evict rewrites messages[i] through list.__setitem__, so TurnMessages.recorded (history.py:26) still holds the full result. messages.finish() → result["model_messages"] stores that full copy, and the UI replays it as agent.conversation_history (ui/_chat_helpers.py:1106) on a cached agent (_get_cached_agent).
  • On turn 2, messages.extend(self.conversation_history) brings back the full results under the same tool_call_ids. begin_turn() clears _result_step but not _evicted, so those IDs are skipped forever. Every large result from turn 1 is re-sent in full on every later turn.
  • The fix is to key "already evicted" off the content, not the ID. For example:
            text = _message_text(message)
            if (
                message.get("name") in NEVER_EVICTED_TOOLS
                or text is None
                or text.startswith("[evicted: ")
            ):
                continue
            if step - self._result_step[key] <= self.keep_steps:
                continue
            candidates.append((i, key, text))

(Remove the later if text is not None block. _evicted can then go, or be kept only for stats.)

  • Related: begin_turn() gives history results step 0 at step 1, so prior-turn results get a fresh keep_steps grace window every turn. That may be intended, but say so if it is.
  • Add a test with two process_query calls on one agent, feeding turn 1's model_messages back as conversation_history.

🟢 Minor

  • The stub for an already-indexed result drops the index the model relied on (context_eviction.py:2157). The model gets offset=0, limit=8000 on the original archive, but can no longer see the entry labels, so entry=n becomes guesswork. The docs say it "keeps its handle and index", which is true in the store but not for the model. Consider naming the entry count in the stub (e.g. …; N index entries, read_tool_output(artifact=…, entry=n)).
  • The #{i} fallback key is position-based (context_eviction.py:2130). If a tool message lacks a string tool_call_id, the key shifts whenever history is trimmed or messages are inserted ahead of it. _create_tool_message always sets an ID, so this is low risk.

Strengths

  • It fails loudly throughout: malformed env values and constructor args raise at construction, and auto logs why it stayed off instead of guessing for unknown or local models.
  • Eviction only touches the sent list; conversation and transcripts keep every result, and read_tool_output / delegate_task results are exempt.
  • The single-turn tests are thorough (threshold, batch minimum, keep window, exact read-back, stats recording).

kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Sep 29, 2026
…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 kovtcharov-amd left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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_step but never _evicted.
  • TurnMessages.append() (history.py:24) deep-copies each message into self.recorded before evict() runs. evict() mutates the live messages list via messages[i] = {...} (context_eviction.py:274), which — since TurnMessages doesn't override __setitem__ — never touches self.recorded. So finish() (history.py:31) always returns the full, un-evicted text, and that's what becomes result["model_messages"].
  • On the next turn, messages.extend(self.conversation_history) (agent.py) replays those full-content messages back into messages under their original tool_call_ids — which are already sitting in self._evicted from turn 1's evict() 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_message always 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.
@itomek

itomek commented Sep 29, 2026

Copy link
Copy Markdown
Collaborator

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 details

Current, and additive. Tip 18a7917b2; git rev-list --count pr4397..origin/main → 0; mergeable: MERGEABLE. git diff --stat origin/main...18a7917b2 → 7 files, +984, −0.

The fix. Diffing the module against the copy on #4384/#4399: the _evicted set is gone as an eligibility key, and evict() now decides from the message's own text (_EVICTED_STUB_PREFIX). That's what lets a result replayed full-size from history on a later turn be judged fresh instead of skipped as already handled. test_eviction_still_fires_in_a_second_turn_on_replayed_history covers it.

Main has none of it. git grep -nE 'ContextEvictor|GAIA_CONTEXT_EVICTION|context_eviction|cache_pricing' origin/main -- src tests hub docs → one hit, test_stdio.py:1633, which is history-budget trimming. git ls-tree -r origin/main | grep -Ei 'context_eviction|cache_pricing' → exit 1.

Duplication, not a stack. context_eviction.py: d35efaab here vs 48786b61 on both #4384 and #4399. Test file: 4e50abf9 vs e6aff330. cache_pricing.py: e39ea488 on all three. git merge-base --is-ancestor fails in both directions.

session_findings. Dropped from NEVER_EVICTED_TOOLS here; neither it nor delegate_task exists on main — both come from #4384.

Red checks. Linux, Windows smoke and macOS smoke each fail on exactly tests/unit/api/test_chat_completion_stream.py::test_client_disconnect_cancels_the_agent. It passed on #4399's Linux lane, so it looks flaky rather than pinned to either branch. Windows Lemonade Integration fails in test_performance_integration on an empty response from the local server. Code Quality Checks pass.

Inert when off. context_eviction: str = "off" (agent.py:1364); resolve_context_eviction returns False for any non-cloud model under auto; all three call sites (:6762, :6828, :8467) guard on self._context_evictor is not None.

Open minors. context_eviction.py:285 uses offset=0, limit=8000 where the sibling branch at :282 keeps entry=1; :255 key = call_id if isinstance(call_id, str) else f"#{i}" with no comment.

@itomek

itomek commented Sep 29, 2026

Copy link
Copy Markdown
Collaborator

Landed on main as #4465 (86fb455b1). Closing this one.

The content went in whole — all five files are byte-identical between this branch's head and main:

$ for f in context_eviction.py cache_pricing.py test_context_eviction.py \
           test_context_eviction_wiring.py agent-system.mdx; do
    git diff --stat <this-head> origin/main -- "$f"; done
(no output — identical)

Worth saying plainly: the merge squashed to a single parent, so the individual commit SHAs from this branch aren't ancestors of main even though every line is. The branch stays on your fork if you want the history.

Your multi-turn fix (18a7917b2) is what unblocked it — the first review's blocking finding was that eviction stopped after turn one, and that commit is the reason this could land. pytest tests/unit/agents/ is 1982 passed, 0 failed on the merged result.

Two things carried forward rather than resolved:

  • The eval gate is still open. This changes what context reaches the model, so CLAUDE.md's gaia eval agent requirement applies. It couldn't run — the judge credential is out of weekly budget repo-wide until Sep 30 — and there's no committed flagship baseline to compare against regardless. Worth running before eviction is turned on anywhere real. It ships off by default, which is why that wasn't a merge blocker.
  • cache_pricing.py hardcodes vendor list prices captured 2026-09-26, and nothing detects drift. Failing loud on an unknown model rather than guessing is the right call; whether a hand-maintained price table belongs in-tree is a separate decision.

@itomek itomek closed this Sep 29, 2026
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Sep 29, 2026
…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]>
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