Skip to content

feat(agent): move already-read tool results out of the prompt before the window fills (opt-in) - #5310

Draft
kovtcharov wants to merge 5 commits into
amd:mainfrom
kovtcharov:claude/proactive-result-eviction-0dc965
Draft

kovtcharov wants to merge 5 commits into
amd:mainfrom
kovtcharov:claude/proactive-result-eviction-0dc965

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Long, tool-heavy turns used to overflow GAIA's 32K–64K windows and then lose their evidence. The overflow retry kept only the latest tool result, so a research turn that read many documents carried on with one and answered confidently from the rest (#2780). Now, before each model call, the agent measures the request. When the next call plus one more capped result would not fit, it moves tool results the model has already read out of the prompt, oldest first, in one batch. That's the headroom-triggered reducer from the context efficiency plan (#5263). Each result is archived whole under the run, replaced by a one-line stub naming the call that re-reads it, and announced in the Agent UI and the TUI. Conversation turns are never summarized or rewritten. Opt-in for now (GAIA_CONTEXT_EVICTION=on). The on-by-default part, an overflow retry that archives instead of dropping plus the token-count fix, already merged separately as #5396; this PR is now only the opt-in eviction on top of it.

Stress test, 46 tool steps (one 3 MB result), then six facts from the earliest documents (deterministic tier):

Window, fixed prompt main: overflows · facts this PR: overflows · facts · batches · prefix reuse
32K, bare prompt 2 · 2/6 0 · 6/6 · 11 of 53 calls · 0.76 (main 0.83)
32K, flagship's 17.9K 6 · 1/6 0 · 6/6 · 50 of 53 · 0.87 (main 0.94)
64K, flagship's 17.9K 1 · 2/6 0 · 6/6 · 8 of 51 · 0.88 (main 0.95)

With eviction off, the overflow retry (now on main via #5396) recovers 6/6 at every window. Prefix reuse drops 7 points because each batch breaks the cached prefix at the first stub. At 32K the flagship's fixed prompt leaves less than one capped result of room, so a batch fires on almost every call. That case needs the plan's smaller fixed prompt.

Real model, N=10 per arm (Gemma-4-E4B on this machine, a 10-document chain under a 16K budget, then "what code did document 1 state?"):

Arm Correct Re-read doc 1 Peak request
Eviction off 10/10 — 18.3–18.5K (over budget on 2 calls)
On, no re-read guard 8/10 7/10 6.6–8.8K
On, with the guard (this PR) 10/10 10/10 6.8–7.6K

Without the guard, one run answered with another document's text and one invented a code. The guard is a one-time reminder sent only when the model answers over stubs made this turn without re-reading any. It cost about one extra model call per run.

Same-machine agent eval A/B (merge base vs. this branch, eviction off vs. on; Gemma-4-E4B at 64K):

Category main branch, off branch, on
rag_quality 9/12 8/12 (re-run; the first run was void with 7 harness errors) 9/12
tool_selection 4/7, re-run 4/7 3/7 3/7

No regression from the branch. Eviction never fired in either category, since these scenarios stay under the 64K trigger, so the "on" column tests only the changes that are on by default. Each flip failed to reproduce:

  • multi_step_plan passed main's first run (7.9) and failed its re-run (7.8). Every run on both trees fails it the same way, by folding three topics into one search query.
  • skill_file_ops_discovery failed main's first run (2.7) and passed its re-run.
  • cross_section_rag failed once on the branch with eviction off (6.8) and passed every other branch run.

Timeouts (csv_analysis, skill_document_brief_gaps, skill_file_ops_guardrails, smart_discovery) hit both trees. In the earlier six-category run with eviction on, it fired once (files_large_file_needle: request 51.6K → 29.6K, passed 9.1/10).

Test tiers:

Tier Status What it covers
Unit edge cases ✅ trigger math at 4K–128K windows, positional keys, protected results, Unicode/surrogates, tokenizer fallback
Contract ✅ SSE vs. daemon sidecar vs. stdio carry the same context_reduced detail; a reattaching UI client replays it; a reloaded chat keeps the notice row
Integration ✅ undo leaves no stale stub; a queued follow-up is never evicted; Stop leaves every put-away result readable; model switch resizes the marks; closing-answer batches reach stats
Stress ✅ concurrent chats keep separate archives; disk full and read-only archive keep results whole and finish the turn; 500 steps reach a loud ceiling with bounded growth (~1–1.4 MB archive, under 50 MB peak memory)
Adversarial ✅ re-read guard measured above; path-traversal and look-alike handles read nothing; tampered or corrupted archives refuse loudly; an injected "read this file" handle can't reach files
Real model N≥10 ✅ table above
Review ✅ code-reviewer + /code-review high; every finding fixed except one, rejected with a measurement (a duplicate schema build costs 0.22 ms)
Same-machine eval A/B ✅ table above; no flip reproduces

Open decisions for the user (how plan #5263 meets the newer requirements):

  1. "Never require a new chat." docs(plans): context efficiency and graceful overflow plan #5263 ends a run with context_exhausted after at most two rollovers, and this PR's last-resort message still says "start a fresh conversation" (reached at ~195 tool steps at 32K, ~290 at 64K). Should rollover be uncapped?
  2. Old conversation turns still leave by recency. Should earlier turns be indexed per session and retrieved by relevance?
  3. "Earlier messages summarized" (the feat(ui): a context and performance panel: what fills the window, where the time goes #5262 panel copy) has nothing producing it under docs(plans): context efficiency and graceful overflow plan #5263, so context_state()["summarized"] is always None. Should the copy change, or the plan?
  4. Stubs in saved history (plan §2) aren't written yet; results are re-stubbed each turn with identical bytes. The TUI replays no earlier tool results at all.
  5. When to turn this on by default: after the planted-fact gate on E4B, or after the Phase 2 fixed-load cut.

Implements the reducer part of plan #5263 (§2), ahead of its Phase 0 constants. Refs #5070, #2780, #686, #1973, #5065. Found while testing: #5284.

Test plan

  • python -m pytest tests/unit/agents/test_context_eviction.py tests/unit/agents/test_context_eviction_hardening.py tests/unit/agents/test_context_eviction_integration.py tests/unit/agents/test_context_overflow_stress.py tests/unit/chat/ui/test_context_reduced_events.py tests/unit/test_token_estimator_fallback.py (275 pass with the regression files below)
  • python -m pytest tests/unit/agents/test_parse_error_recovery.py tests/unit/agents/test_model_unreachable_retry.py tests/unit/test_memory_heal_lessons.py hub/agents/gaia/python/tests/test_context_eviction_wiring.py hub/agents/gaia/python/tests/test_stdio_wire_contract.py
  • cd tui && go test ./internal/event/ ./internal/ui/chat/
  • cd src/gaia/apps/webui && npx vitest run src/components/__tests__/AgentActivity.contextReduced.test.tsx
  • With Lemonade running: GAIA_STRESS_LEMONADE=1 pytest tests/integration/test_context_overflow_lemonade.py -s
  • Dispatch eval_flagship.yml on this branch with GAIA_CONTEXT_EVICTION=on and compare against tests/fixtures/eval_baselines/gaia-flagship/
🔍 Technical details
  • Policy: src/gaia/agents/base/context_eviction.py (ContextEvictor.before_call, shrink_for_overflow), called once per model call from Agent._evict_before_model_call, including the step-cap closing answer and plan requests.
  • Trigger (plan §2): U = window − min(reply_reserve, window/4) − min(2048, window/16), headroom F = min(5000, U/4). A batch fires when estimate > U − F and runs until estimate ≤ U − 2F. Batches smaller than 5% of the window wait unless the request is past min(0.85·window, U − F/2).
  • Measurement: the backend's prompt_tokens for the previous request plus max(cl100k, utf8_bytes/3) for what changed. A reported count under a quarter of our estimate is ignored as not a whole prompt.
  • Never evicted: the latest tool step; results seen by fewer than keep_steps (2) calls; status: denied, executed: false, governance_decision, status: error; delegate_task; non-text; gains under 200 tokens. Results are keyed by position, because some backends reuse tool_call_id per response.
  • Archive: content-addressed (output_ + sha256), written atomically to ~/.gaia/runs/<run_id>/results/ only when eviction is on. Each file is hash-checked when read back, and handles must match a strict pattern. In-memory copies are capped, and runs older than 7 days are swept. A failed write leaves the result in the prompt and logs a warning. A bare read_tool_output(artifact=…) on a whole result reads entry 1.
  • Re-read guard: REREAD_PROMPT, sent as a transient message (never saved) when the reply cites none of this turn's stubs and no read_tool_output came after them.
  • Overflow retry (_retry_after_overflow_shrink): sized by a dry run first. It retries only if requested − freed × (requested / our count) ≤ 0.95 × available, or, with no numbers in the error, if the dry run frees 10%. Otherwise it records llm_context_overflow_unrecoverable with the numbers and writes nothing.
  • Events: SSE {"type":"status","status":"context_reduced","message":…,"context_reduced":{"reason":"proactive"|"overflow","results","tokens_freed","prompt_tokens_before","prompt_tokens_after","context_window","items":[…]}}, persisted as an AgentStep with notice: true; the TUI gets the same dict on its canonical status. agent.context_state() serves the feat(ui): a context and performance panel: what fills the window, where the time goes #5262 panel.
  • Config: context_eviction stays "off"; "on"/"auto" run it. New context_eviction_headroom_tokens (GAIA_EVICT_HEADROOM); keep_steps default 2 (was 8). gaia.llm.cache_pricing is removed since "auto" no longer reads cloud prices.
  • Full unit suite: the remaining 48 failures and 18 errors also fail on a clean origin/main checkout on this machine (launcher, packaging, installer, cloud gateway, profile goldens).
  • Seen while testing, not changed here: LemonadeManager._try_reload_with_ctx takes context_size from a status that also lists a co-loaded 4K cloud model, so it report "effective=4096" and reload Gemma needlessly on every run.

…the window fills (opt-in)

Long tool-heavy turns overflowed 32K-64K windows, and the overflow retry
then kept only the latest result, so answers were built on a fraction of
the evidence (amd#2780). With GAIA_CONTEXT_EVICTION=on, the agent measures each
request and, when the next call plus one more capped result would not fit,
moves tool results the model has already read out of the prompt, oldest
first, behind content-hash handles archived under ~/.gaia/runs/<run_id>/.
Each batch is announced in the Agent UI and the TUI; conversation turns are
never touched. This is the headroom-triggered reducer from plan amd#5263.

On by default: the overflow retry now archives instead of dropping and only
retries when the request will then fit, and token counts lean high when the
tokenizer can't load (amd#5066). Opt-in until the planted-fact retrieval gate
passes: at a 16K budget a 4B model re-read correctly in 4 of 6 runs.

Refs amd#5070, amd#2780, amd#5066, amd#5263
@github-actions github-actions Bot added documentation Documentation changes llm LLM backend changes tests Test changes electron Electron app changes performance Performance-critical changes agents tui Go terminal UI (gaia-tui) labels Oct 18, 2026
…, re-read guard

A test battery and two reviews of the opt-in eviction turned up crashes
and gaps on paths every user can hit:

- A tool result with lone surrogates crashed the overflow retry's token
  count (default path). Counting and archiving now handle them.
- A full or read-only ~/.gaia/runs crashed the turn; the result now stays in
  the prompt with a warning. Archive files are verified against their hash
  on reload, handles are exactly output_ + 32 hex, and folders untouched for
  7 days are swept.
- With eviction off, nothing is written to disk; the overflow retry is sized
  in memory first and archives only when it will retry.
- Windows of 4K-16K now keep a positive trigger: the reply reserve, margin
  and headroom are capped by window size. The batch floor applies again.
- A one-shot nudge asks the model to re-read a moved-out result before
  answering over it, instead of inventing what it said. It is transient and
  only counts stubs made this turn.
- The step-cap closing answer measures the request it sends and records its
  batch.

Refs amd#5310, amd#5066
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…them (amd#5396)

When a long, tool-heavy turn overflowed the model's context window, the
retry threw away every tool result but the latest, so a research turn
that had read many documents carried on with one and answered
confidently from the rest (amd#2780). Now the retry archives each older
result whole and leaves a stub naming the `read_tool_output` call that
reads it back, so the evidence stays one call away. It also retries only
when the shrink actually frees enough to fit, instead of repeating a
refusal. Separately, on machines where the tokenizer data can't load,
token counts no longer undercount JSON and CJK text into a window they
don't fit (amd#5066).

These are the on-by-default bug fixes split out of amd#5310, so they can
land without the opt-in eviction feature.

## Test plan
- [ ] `python -m pytest
tests/unit/agents/test_overflow_retry_archives.py
tests/unit/test_token_estimator_fallback.py
tests/unit/agents/test_overflow_shrink_tool_history.py
tests/unit/agents/test_parse_error_recovery.py
tests/unit/agents/test_model_unreachable_retry.py
tests/unit/test_memory_heal_lessons.py
tests/unit/agents/test_context_eviction.py
tests/unit/test_turn_metrics.py`
- [ ] `python util/lint.py --black --isort`
- [ ] Dispatch `eval_flagship.yml` on this branch and compare
`rag_quality` and `tool_selection` against
`tests/fixtures/eval_baselines/gaia-flagship/` (the overflow path
changes what the model sees after an overflow)

<details>
<summary>🔍 Technical details</summary>

- `shrink_for_overflow` (`context_eviction.py`) replaces the old
stub-everything loop in `Agent._shrink_messages_for_overflow`. Never
stubbed: refusals (`status: denied`, `executed: false`,
`governance_decision`), `delegate_task`, results already stubbed,
results under 500 chars (older) / 2,000 chars (latest), and a
`read_tool_output` page from the latest step. An older
`read_tool_output` page is re-stubbed with a call that re-reads its own
span, not re-archived. A full archive keeps the result whole and logs a
warning.
- `_retry_after_overflow_shrink` sizes the shrink in a throwaway store
first. With numbers in the error (`request (N tokens) exceeds … (M
tokens)` or `n_prompt_tokens … n_ctx`) it retries when the projected
request is ≤ 95% of available; without numbers, when it frees ≥ 10%.
Otherwise it records `llm_context_overflow_unrecoverable` and writes
nothing. `test_context_overflow_path_is_unchanged` now expects one call,
not a doomed second one.
- `ArtifactStore.put_result` is content-addressed (`output_` + sha256),
so the same result gets a byte-identical stub; a bare
`read_tool_output(artifact=…)` on a whole result pages from 0. In memory
only; amd#5310's on-disk archive builds on it.
- The opt-in evictor now also skips overflow stubs (`is_stub`), so it
never re-archives a stub.
</details>
github-merge-queue Bot pushed a commit that referenced this pull request Oct 19, 2026
An overnight end-to-end test of the Agent UI, run against a live backend
with every open UI PR merged, turned up these bugs in code already on
main. Each one wasted the user's time or misled them.
- **Approval that meant nothing:** GAIA asked "Allow writing file?" for
a path in the system temp folder, then refused the write anyway after
the user clicked Allow.
- **A dozen drive-wide searches:** given a wrong file path, the agent
searched the whole drive a dozen times over nearly three minutes before
saying the file wasn't there.
- **A stranger's file in an unrelated chat:** a file named in a past
chat's error, stored in memory, came back as "read it now" in a chat
that had nothing to do with it.
- **History lost early on cloud models:** Fireworks chats dropped older
messages after two short turns.
- **Silent or garbled send failures:** a send that died early showed
nothing at all, and a server error showed a raw JSON body.

After this PR, each of these works as the user would expect.

- **Agent and tools:**
- A write to a path no approval can grant is refused before the approval
card appears.
  - A missing file allows one search, then the agent asks the user.
- The answer check reads the user's own words, not the recalled memory
prepended to them.
- A cloud model's reply no longer takes space from its 64K history
budget: about 12K of history before, about 32K now.
- The summarize skill keeps its 3-bullet cap when asked to reformat an
earlier answer.
- Each indexed document is listed with its path, so the agent stops
searching the disk for a file the user already attached.
- A document query counts as the search an answer reports, ending false
"no search ran" corrections.
- Every file tool's missing-file error carries the one-search stop rule.
- An access prompt that is declined or left unanswered isn't asked again
for the same folder in that turn. One unanswered prompt used to cost
three 10-minute waits.
- **Agent UI:**
  - A send's errors read as sentences.
  - A stream that closes before any answer shows an error.
- A message sent while a chat is still loading is no longer wiped by the
late history load.
  - The live line names the running tool in words.
  - Status and message polling pause while the window is hidden.
  - Escape closes Scheduled tasks.
  - `.mdx`, `.markdown` and `.rst` can be added to the document library.
  - Mobile access drops its QR box when ngrok is missing.
  - Privacy shows the real data folder.
  - The memory list's page buttons have names for screen readers.

Several of these change what the model sees: the tool error wording, the
grounding input, the history budget and the summarize skill. Categories
to watch on the next RC: `error_recovery`, `rag_quality`,
`context_retention`, `tool_selection`. A local run on Fireworks scored
`tool_selection` 7/7 and `context_retention` 4/4. With the document and
access-prompt fixes, all 12 `rag_quality` scenarios passed
(`csv_analysis` went from 5.4 to 10/10), where this morning's run passed
9 of 12.

## Test plan

- [ ] `python -m pytest tests/unit/agents tests/unit/chat` passes
- [ ] `npx vitest run` and `npx tsc --noEmit -p .` in
`src/gaia/apps/webui` pass
- [ ] `python util/lint.py --black --isort` passes
- [ ] `gaia chat --ui`: ask GAIA to write a file under `%TEMP%`; it
refuses without showing an approval card
- [ ] `gaia chat --ui`: open a chat and send immediately; the message
stays after the history loads
- [ ] `gaia chat --ui` on a Fireworks model: after four or five turns,
the earliest messages are still in view

<details>
<summary>🔍 Technical details</summary>

- `read_first_preflight` refuses when `PathValidator.unaskable_reason()`
is non-empty (temp dir, blocked or secret dirs, env scope), and the
refusal is still audited as denied. Askable out-of-scope paths are
unchanged.
- `missing_file_error()` in `path_access.py` is shared by `read_file`
and `index_document`; the old error told the model to search elsewhere.
- `_grounding_findings` and `_note_ungrounded` use
`_original_user_input`, as the plan executor already does.
- `history_budget` subtracts no reply reserve for Lemonade cloud models.
Local models and Claude are unchanged, and the doc in `agent-ui.mdx` is
updated. #5310 also edits `history.py`, so whichever lands second has a
small conflict.
- `consumeSSEResponse` takes `silentCloseIsError` from
`sendMessageStream` only, so re-attach still treats an empty replay as
done.
- `setVisibleInterval` pauses the system-status and message-count polls
only. The chat list and active-run polls keep running, because they
drive notifications while the user is in another app.
- System status gains `data_dir`; `api.gen.ts` and `api.schemas.json`
are regenerated.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Main now carries the on-by-default half of this branch (amd#5396: the overflow
retry archives instead of dropping, and the tokenizer fallback), so this
branch keeps only the opt-in eviction on top of it.

- Kept this branch's context_eviction and artifacts modules; they are the
  newer form of what amd#5396 shipped. Old "[evicted: " stubs still count as
  stubs, so a legacy stub is never archived again.
- Took main's history, turn_metrics and tokenizer-fallback tests, which
  already contain the same context_window and surrogate fixes.
- Step stats go through main's _record_step_stats, which now hands off to
  _take_pending_eviction.
- Agent UI: the context notice rule moved into main's consolidateSteps;
  api types regenerated from the merged models.
- agent-system.mdx: one overflow-retry paragraph instead of two.
Main has moved a long way since the last update; this keeps the branch's
opt-in eviction on top of it. Nothing main ships duplicates it: main still
carries only the defaults-on overflow retry from amd#5396.

- The chat package was folded into the flagship (amd#7035): the eviction
  settings move into gaia_agent/chat_agent.py, beside main's new
  resend_reasoning_across_requests, and the CHANGELOG entry moves to the
  gaia npm package's Unreleased section.
- Kept main's tool_scope argument and its unsaved-memory nudge next to the
  re-read reminder.
- Agent UI: main's timeline (amd#5966) hides finished status rows, so a
  context notice now draws its own row and stays after the turn ends.
  Status handling moved into applyStatusEvent, so the notice is added there.
- The closing-answer overflow tests from amd#6875 now patch the evictor's
  counter, which this branch sizes the trim with.
- Two second-turn tests now run at a 64K window: at 16K, main's history
  fitting drops the whole earlier turn, so there is nothing to replay.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes electron Electron app changes enhancement New feature or request llm LLM backend changes performance Performance-critical changes tests Test changes tui Go terminal UI (gaia-tui)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants