Skip to content

fix(agent): overflow retry archives tool results instead of dropping them - #5396

Merged
kovtcharov-amd merged 6 commits into
amd:mainfrom
kovtcharov:fix/overflow-retry-archives
Oct 19, 2026
Merged

kovtcharov-amd merged 6 commits into
amd:mainfrom
kovtcharov:fix/overflow-retry-archives

Conversation

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

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_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 (#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.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)
🔍 Technical details
  • 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; 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.
  • The opt-in evictor now also skips overflow stubs (is_stub), so it never re-archives a stub.

…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.
@github-actions github-actions Bot added documentation Documentation changes tests Test changes agents labels Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

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.

  • Run the eval before merge. The test plan already lists dispatching eval_flagship.yml for rag_quality and tool_selection. That step matters, because this changes what the model sees after every overflow. Unit tests can't show whether a small model actually follows the "call read_tool_output to read it" note.
  • Offline machines will trim history sooner. Plain English text now counts about 40% higher when the tokenizer is missing. This is intended, and the changelog describes the new floor. It's still worth knowing if offline users report shorter-than-expected memory.

Real-world evidence

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

Issues found

🟢 Unlocked read of _whole (src/gaia/agents/base/artifacts.py:118). read() checks handle in self._whole before it takes self._lock, while put_result rebuilds the set under the lock (self._whole &= ...). Membership checks on a set are safe in CPython, but this is the only access to the store's state that skips the lock. Moving the check inside the lock, or snapshotting it there, would keep the class consistent.

🟢 The trial and the real shrink can produce slightly different stubs (src/gaia/agents/base/agent.py:7612). The trial uses a fresh ArtifactStore(), so _reread_page and _existing_handle never find an existing handle. Older read_tool_output pages and results that already carry an artifact get re-archived in the trial, but re-pointed in the real run. The size difference is a few dozen characters per stub, well inside the 95% margin, so the fit decision is unaffected in practice. One comment there would stop a later reader from "fixing" it into a real-store trial, which would archive results for a retry that never runs.

🟢 Behaviour change for errors without numbers (agent.py:7631). The old code always retried once. Now a backend overflow message with no token counts retries only when the shrink frees at least 10%. test_context_overflow_path_is_unchanged was updated to match (one call instead of two), and the result is the same _CONTEXT_STILL_OVERFLOWING_MESSAGE the user saw before, so this is intended. The test's name no longer describes what it checks, though; renaming it would help.

Strengths

  • shrink_for_overflow is a pure function that returns (messages, items) and never mutates its input. That makes the behaviour easy to test directly, and the tests do: refusals, delegate_task, short results, idempotence, a full archive, reused call ids, and forged stubs.
  • Handles are derived from a hash of the content (put_result), so the same result always gets a byte-identical stub, which keeps the prompt cache warm across retries. The bare-read fallback to entry=1 is a practical fix for small models that drop arguments.
  • The not-retrying path is correctly fail-loud: it records llm_context_overflow_unrecoverable with the numbers behind the decision and falls through to the existing overflow message, with no silent second request.

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.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 194363f Oct 19, 2026
43 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the fix/overflow-retry-archives branch October 19, 2026 18:31
grtninja pushed a commit to grtninja/gaia that referenced this pull request Oct 20, 2026
…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`
kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Oct 21, 2026
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.
kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Nov 11, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant