Repository navigation
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
Draft
kovtcharov wants to merge 5 commits into
kovtcharov wants to merge 5 commits into
Conversation
…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
6 tasks
…, 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
3 tasks
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.
…lt-eviction-0dc965
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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):
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?"):
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):
rag_qualitytool_selectionNo 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_planpassed 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_discoveryfailed main's first run (2.7) and passed its re-run.cross_section_ragfailed 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:
context_reduceddetail; a reattaching UI client replays it; a reloaded chat keeps the notice rowcode-reviewer+/code-review high; every finding fixed except one, rejected with a measurement (a duplicate schema build costs 0.22 ms)Open decisions for the user (how plan #5263 meets the newer requirements):
context_exhaustedafter 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?context_state()["summarized"]is alwaysNone. Should the copy change, or the plan?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.pycd tui && go test ./internal/event/ ./internal/ui/chat/cd src/gaia/apps/webui && npx vitest run src/components/__tests__/AgentActivity.contextReduced.test.tsxGAIA_STRESS_LEMONADE=1 pytest tests/integration/test_context_overflow_lemonade.py -seval_flagship.ymlon this branch withGAIA_CONTEXT_EVICTION=onand compare againsttests/fixtures/eval_baselines/gaia-flagship/🔍 Technical details
src/gaia/agents/base/context_eviction.py(ContextEvictor.before_call,shrink_for_overflow), called once per model call fromAgent._evict_before_model_call, including the step-cap closing answer and plan requests.U = window − min(reply_reserve, window/4) − min(2048, window/16), headroomF = min(5000, U/4). A batch fires whenestimate > U − Fand runs untilestimate ≤ U − 2F. Batches smaller than 5% of the window wait unless the request is pastmin(0.85·window, U − F/2).prompt_tokensfor the previous request plusmax(cl100k, utf8_bytes/3)for what changed. A reported count under a quarter of our estimate is ignored as not a whole prompt.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 reusetool_call_idper response.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 bareread_tool_output(artifact=…)on a whole result reads entry 1.REREAD_PROMPT, sent as a transient message (never saved) when the reply cites none of this turn's stubs and noread_tool_outputcame after them._retry_after_overflow_shrink): sized by a dry run first. It retries only ifrequested − freed × (requested / our count) ≤ 0.95 × available, or, with no numbers in the error, if the dry run frees 10%. Otherwise it recordsllm_context_overflow_unrecoverablewith the numbers and writes nothing.{"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 withnotice: 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.context_evictionstays"off";"on"/"auto"run it. Newcontext_eviction_headroom_tokens(GAIA_EVICT_HEADROOM);keep_stepsdefault 2 (was 8).gaia.llm.cache_pricingis removed since"auto"no longer reads cloud prices.origin/maincheckout on this machine (launcher, packaging, installer, cloud gateway, profile goldens).LemonadeManager._try_reload_with_ctxtakescontext_sizefrom a status that also lists a co-loaded 4K cloud model, so it report "effective=4096" and reload Gemma needlessly on every run.