Repository navigation
fix(agent): overflow retry archives tool results instead of dropping them - #5396
Conversation
…them A context overflow used to replace every tool result but the latest with "[tool result omitted]", so a turn that had read many documents answered from whatever was left (amd#2780). The retry now archives each older result whole behind a stub naming the read_tool_output call that reads it back, cuts a large latest result to a 2,000-character preview plus a handle, keeps refusals and delegate_task answers whole, and retries only when the shrink frees enough for the request to fit; otherwise it archives nothing and ends the turn with the existing "still overflowing" message. The token counter's fallback (no tiktoken data) now warns and counts at least one token per three UTF-8 bytes, so JSON and CJK text are no longer undercounted into a window they don't fit (amd#5066). Lone surrogates no longer crash the cl100k count.
|
Verdict: Approve with suggestions When a long research turn overflows the context window, the agent no longer throws away the documents it already read. Each older result is saved whole and replaced with a short note that tells the model how to read it back. The agent now retries only when the smaller request will actually fit, instead of sending a request it knows will be refused again. On machines where the tokenizer can't load, token counts now come out high instead of low. Nothing blocks merge. The new path keeps refusals and worker answers intact, never edits the caller's message list, and archives nothing when it decides not to retry. Tests cover each of these cases.
Real-world evidenceN/A: this change is inside the agent loop and only fires when the backend refuses an oversized request. It changes no CLI, REST, MCP or Agent UI surface that this lane could exercise. The verdict rests on static review. I also couldn't run the listed unit tests here because pytest isn't installed on this runner, so the CI result is the source of truth for them. 🔍 Technical detailsIssues found 🟢 Unlocked read of 🟢 The trial and the real shrink can produce slightly different stubs ( 🟢 Behaviour change for errors without numbers ( Strengths
|
CI runners block the cl100k download, so the test saw the fallback. A stub encoding that rejects surrogates also covers the lone-surrogate retry.
Also notes why the overflow trial uses a throwaway store, and renames the overflow test to what it now checks.
The prompt is posted before the waiting turn releases the model on the event loop, so on a slow runner the check could see the slot still held.
…ming them (amd#5409) Two unit tests failed whenever a CI runner was busy, so unrelated PRs went red (the envelope test on amd#5282 and amd#5337; the ping test timed out on loaded machines). Before: the envelope "not quadratic" test raced a 5 s wall clock, and the ping test needed a ping to land in a 0.5 s window that the stub's own start-up ate into. After: both assert what they claim directly, so they pass or fail the same way on any machine. Under a 40-process CPU burn they went from 16/16 and 10/16 failing to 0 of 120. The third test from the report, `test_turn_waiting_on_the_user_lets_other_chats_run`, was already fixed on main by amd#5396. Both of its CI failures predate that fix, and it passed 325/325 under the same burn. <details> <summary>🔍 Technical details</summary> - **Envelope test:** the test now counts the characters `_json_object_end` examines. A 400,089-char envelope scans exactly 400,089 characters. A per-token rescan scans ~2e10 and fails the `≤ 2×len` bound; I checked this on a 20 KB envelope, where a rescan was 2,500× over. - **Ping test:** the stub is now warmed with a first request so its boot time sits outside the deadline window. The test spies `_write` and asserts the ping reply gets the same deadline as the request. If the product gives the ping reply a fresh `self.timeout`, the test fails deterministically. - **Not a product race:** the remaining superlinear cost in the envelope path is `self._stream_buffer += chunk` copying the held buffer per token. That is microseconds per token at real generation rates. - **Follow-ups:** other tests in `test_stdio_hung_server.py` also fail under heavy load. `test_redaction_stays_fast_on_dense_escapes` and `..._linear_on_long_non_ascii_secrets` use a `< 0.25 s` wall-clock assert. `test_a_server_that_misses_the_connect_deadline_is_stopped` and `test_a_timed_out_request_is_cancelled_on_the_server` read marker files before the stub writes them. </details> ## Test plan - [x] `pytest -p no:randomly --count 60 -n 8` on both fixed tests: 120/120 idle, 120/120 under a 40-process CPU burn (before: 16/16 and 10/16 failing under the same burn) - [x] Adversarial: dropping the scanner's resume or giving the ping reply a fresh timeout makes the respective test fail - [x] `test_sse_handler.py`, `test_stdio_hung_server.py`, `test_turn_slot_reliability.py` in full: 521 passed - [x] `python util/lint.py --black --isort`
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.
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 (#2780). Now the retry archives each older result whole and leaves a stub naming the
read_tool_outputcall 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 (#5066).These are the on-by-default bug fixes split out of #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.pypython util/lint.py --black --isorteval_flagship.ymlon this branch and comparerag_qualityandtool_selectionagainsttests/fixtures/eval_baselines/gaia-flagship/(the overflow path changes what the model sees after an overflow)🔍 Technical details
shrink_for_overflow(context_eviction.py) replaces the old stub-everything loop inAgent._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 aread_tool_outputpage from the latest step. An olderread_tool_outputpage 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_shrinksizes the shrink in a throwaway store first. With numbers in the error (request (N tokens) exceeds … (M tokens)orn_prompt_tokens … n_ctx) it retries when the projected request is ≤ 95% of available; without numbers, when it frees ≥ 10%. Otherwise it recordsllm_context_overflow_unrecoverableand writes nothing.test_context_overflow_path_is_unchangednow expects one call, not a doomed second one.ArtifactStore.put_resultis content-addressed (output_+ sha256), so the same result gets a byte-identical stub; a bareread_tool_output(artifact=…)on a whole result pages from 0. In memory only; feat(agent): move already-read tool results out of the prompt before the window fills (opt-in) #5310's on-disk archive builds on it.is_stub), so it never re-archives a stub.