Skip to content

fix(agent): bound tool output and recover omitted evidence - #3670

Merged
kovtcharov-amd merged 12 commits into
amd:mainfrom
kovtcharov:codex/3632-bound-string-tool-results
Sep 18, 2026
Merged

kovtcharov-amd merged 12 commits into
amd:mainfrom
kovtcharov:codex/3632-bound-string-tool-results

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Large tool results now keep a bounded preview while letting the agent retrieve the exact omitted evidence. Previously plain text could flood a small local context window, and early tool-specific truncation could destroy facts before the agent saw them. This completes #3632 with session-local continuation reads and file paging, while preserving whole records in structured output. Unspecified local devices now use the configured profile; FLM retains the NPU budget.

Closes #3632.

🔍 Technical details

Shell, browser, and Python execution results are retained before their local display caps. The continuation reader is registered only on its owning agent, and deliberately tool-free agents stay tool-free. read_tool_output reads up to 8,000 characters per page from a session-owned handle; file readers support bounded character offsets. Archives expire after one hour and have a 64 MiB quota, with explicit errors for exhaustion, expiry, and cross-session access. Handles are process-local: restarting requires rerunning the source tool. This does not implement adaptive allocation of every remaining context token or the broader work in #3378.

Test plan

  • Expanded CI step: 546 artifact, truncation, native schema, API permission-gate, browser, file paging, and packaged-agent integration tests passed after merging current main and fixing CI compatibility findings (one existing connectors-demo skip).
  • Flagship package: 329 tests passed in the full run; its one manifest-count failure was fixed, then all 31 manifest/discovery tests passed.
  • Local Gemma-4-E4B: an 80,017-character tool result omitted the middle; the model called read_tool_output with offset 40,000 and limit 16, then returned the exact requested text. The trace confirms real tool execution.
  • Formatting, scoped lint, code review, and architecture review completed.
  • Formal agent quality evaluation and human review. The live recovery check is a functional check, not a quality benchmark; the configured external judge is quota-blocked.

@kovtcharov
kovtcharov marked this pull request as ready for review September 11, 2026 19:53
@github-actions github-actions Bot added documentation Documentation changes devops DevOps/infrastructure changes tests Test changes agents labels Sep 11, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes — small, careful change; two things to settle first.

This closes a real gap: a single huge string result (a log, a transcript, a JSON blob a tool returns as text) could previously eat the whole context window. It now becomes a bounded head-and-tail excerpt that states exactly how much was dropped, and short strings are untouched. The mechanism itself checks out — I fuzzed the eliding helper across quotes, backslashes, newlines, NUL bytes and multi-byte characters and it never exceeds its budget, never splits a character, and always reports the omitted count correctly.

Two items before merge:

  1. Some tools return JSON as a plain string, and those now get cut through the middle of a record. Code search and index-status results are JSON text, not structured objects, so they take the head/tail path and the model reads half a record at each end — the same mid-record corruption the earlier truncation work deliberately removed for structured results. Detecting that a string is JSON and sending it down the existing whole-item-dropping path would close it.

  2. The model-behaviour check the PR itself lists as required hasn't run. This changes what every oversized tool result looks like to the model, which is exactly the class of change the repo gates on an agent eval against the committed baseline. The description marks that item unchecked and says it's still required — agreed, and that's the merge gate here rather than anything wrong in the code.

Also worth considering: the excerpt tells the model that content was dropped but not how to get it back. A one-line hint in the envelope would keep the model from guessing at the gap.

Real-world evidence

No automated evidence bundle was produced for this PR (evidence-bundle.md absent), so the surface evidence is what the description carries: a rendered screenshot of a controlled-transport run (140,067 input characters → 40,000-character excerpt, both planted boundary facts retained, 102,818 characters disclosed as omitted) and the new CI command running the string, escaping and native-tool-loop tests. That covers the data path well. It does not cover model behaviour — the real-model retention/quality eval is the unchecked box above, and my verdict rests on static review plus my own local fuzzing of the helper for everything beyond the data path. I could not run the suite here (no pytest in this environment).

🔍 Technical details

Issues

🟡 JSON-string tool results are sliced mid-record (src/gaia/agents/base/agent.py:4091)

Tools that return json.dumps(...) as a str — code_index_tools.py:106 index_codebase, :208 search, :239 get_index_status, and any tool following that pattern — are isinstance(str), so they take the elide_text branch instead of _drop_items_to_fit. The model receives a valid envelope whose head/tail contain truncated JSON fragments. That is the #2620 failure mode one level up: the outer object parses, the payload the model actually reasons over does not.

Parsing first keeps the existing invariant test (as_json=True appears exactly once in the module) satisfied:

                payload = tool_result
                if isinstance(tool_result, str):
                    try:
                        candidate = json.loads(tool_result)
                    except json.JSONDecodeError:
                        candidate = None
                    if isinstance(candidate, (dict, list)):
                        payload = candidate
                if isinstance(payload, str):
                    truncated_result = elide_text(payload, target)
                else:
                    # Structured results must remain valid JSON for the model.
                    truncated_str = self._truncate_large_content(
                        payload, max_chars=target, as_json=True
                    )
                    truncated_result = json.loads(truncated_str)

🟡 Agent eval not run — per CLAUDE.md, changes to what reaches the model require gaia eval agent against the matching committed baseline in tests/fixtures/eval_baselines/. The description already flags this as outstanding; naming it here so the gate is explicit.

🟢 Local import (agent.py:4092) — tool_output imports only json, so there's no cycle to dodge; a module-level import matches the file's other helpers.

🟢 Docs restate the budgets as literals (docs/sdk/core/agent-system.mdx:477) — 30,000/20,000 and 60,000/40,000 live in truncation_budget (src/gaia/llm/lemonade_client.py); pointing at the function keeps the page from drifting when the profiles are retuned.

🟢 No recovery hint in the envelope — the model learns omitted_chars but has no stated way to retrieve the middle. A short note field ("re-run with a narrower range to see the omitted section") would reduce the odds it fabricates over the gap; the tracking issues for paging are already referenced in the description.

🟢 Cross-test-module coupling (tests/unit/agents/test_large_tool_result_truncation.py:218) — reaching into test_parallel_tool_calls' private helpers ties the two files together. Workable given the new CI step runs them as a pair, but promoting _DummyAgent / _stub_chat / _native_envelope into a shared helper would be sturdier.

Verified, not findings

  • Dropping the json.JSONDecodeError guard is safe. Every as_json=True return path in _truncate_large_content (test_results early return, compact_str, the chunks branch, _drop_items_to_fit, _truncate_fallback_text) is json.dumps output, and TestAlwaysValidJson pins that. Matches the fail-loudly rule.
  • elide_text's binary search is sound. cost(keep) is non-decreasing (a retained character adds ≥1 serialized char; omitted_chars can shed at most one digit per step), high is clamped to min(len(text), max_chars) so head and tail never overlap, and slicing is by code point so astral characters aren't split. Local fuzz over 300 random payloads of " \ \n NUL λ € 𝄞 at budgets 60–600: zero budget violations, zero accounting errors.
  • Downstream consumers are unaffected. All three call sites keep using the original tool_result for error classification and _post_process_tool_result; only previous_outputs and _create_tool_message see the envelope, and both already handle dicts (the envelope serializes within target, so the _create_tool_message backstop is a no-op).

Strengths

  • Counting serialized length against the budget is the right call — the envelope reaches the model as json.dumps text, so escaping is visible to it, and the tests pin exactly that with quote/backslash/NUL payloads.
  • Failing loudly on an impossibly small budget instead of emitting a malformed excerpt.
  • The CI workflow's path filters were updated alongside the new step, so these tests actually run on the paths that can break them.

Ovtcharov added 3 commits September 14, 2026 09:41
Tools that hand back `json.dumps(...)` as a str — code search, index status
— were `isinstance(str)`, so an oversized result took the head-and-tail path
and the model read half a record at each end. That is the corruption the
structured path was built to avoid, one level up: the envelope parses, the
payload the model reasons over does not.

`_as_structured_payload` parses a str first and routes it to the existing
item-dropping path when it turns out to be an object or an array, so every
record that survives is whole and the tail marker says how many were left
out. A str still comes back as a str — the tool's declared result type is
part of its contract with whatever reads it next.

A bare JSON scalar stays prose: `"null"` or a quoted word parses, but there
are no records in it to drop, and a log that happens to be valid JSON should
still read as a log.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Fixed the JSON-string slicing. A tool result that parses as an object or array now goes down the whole-item-dropping path regardless of whether it arrived as a str, so the model never sees half a record.

I checked the end-to-end behaviour rather than just the branch: a 182KB code-search result now comes back as 43 complete records plus the existing {"truncated": true, "returned": 43, "total": 400} marker, and the whole thing re-parses. Before, it was a head-and-tail excerpt with a broken record at each end.

A string still comes back as a string — the tool declared a text result and whatever reads it next is entitled to that. And prose that happens to be a valid JSON scalar ("null", a quoted word, a bare number) stays on the eliding path, since there are no records in it to drop and a log shouldn't stop reading like a log because it parses.

Not done: the agent eval. @kovtcharov-amd is running those separately, so the box stays unchecked — this does change what every oversized tool result looks like to the model, and your point that it's the merge gate stands.

I left the "how to get the dropped content back" hint alone — it's a good idea, but it's new prompt text on the same surface the eval would be measuring, so it's better landed with a measurement than bundled in here.

🔍 Technical details

New Agent._as_structured_payload returns the dict/list to truncate, or None for genuine prose. _handle_large_tool_result branches on that instead of isinstance(tool_result, str); the as_json=True call site stays single, so the module invariant test is untouched.

json array str  -> list      json object str -> dict
plain prose     -> None      json scalar str -> None
real dict       -> dict      bytes           -> None

Two tests added to TestStringResults: one asserting whole records survive with the tail marker intact and the result still being a str, one asserting a huge JSON-scalar string still produces the head/tail/omitted_chars envelope. tests/unit/agents/test_large_tool_result_truncation.py → 55 passed. (Two setup errors on the unicode-parametrized case are a Windows console artifact and predate this change.)

@kovtcharov kovtcharov changed the title fix(agent): bound plain-string tool results with head and tail fix(agent): bound tool output and recover omitted evidence Sep 15, 2026
@github-actions github-actions Bot added the agent::email Email agent changes label Sep 15, 2026
Kalin Ovtcharov added 3 commits September 15, 2026 15:42
@github-actions github-actions Bot added the sidecar Agent sidecar contract / harness label Sep 15, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

⚠️ Note: Bash was completely non-functional in this CI environment (bwrap failure on every command), so I could not verify whether a prior Claude review exists. Treating this as the first review per the protocol.

This is a solid implementation of session-scoped artifact storage for large tool outputs. Replacing silent head-truncation with an explicit head+tail excerpt plus a read_tool_output continuation reader is the right design. The ChainMap approach for per-instance tool isolation, the fail-loud quota and TTL errors, and the test coverage across all changed surfaces are all well done.

One 🟡 concern, then a handful of minor nits.


🟡 Browser link enumeration: unbounded memory allocation before truncation

browser_tools.py removed the links[:100] cap, so every link on a page is now formatted into a string before retain_excerpt discards the excess. For a typical page (10–200 links) this is fine. For a sitemap or link-heavy aggregator (thousands of links), this builds a 500 KiB–2 MiB working string just to throw most of it away. The old behavior silently dropped links; the new behavior is strictly better for the model (it can page through all of them), but the peak allocation is new. If this tradeoff is intentional — and it probably is — a short comment on the call site would head off a future "why no cap?" question.


🟢 Nit 1 — read_text_page offset-skip semantics: when offset == len(file) the seeking loop completes normally and the subsequent read returns empty content (no error). ArtifactStore.read has the same behaviour for offset == len(text) because the guard uses > not >=. Both are consistent with each other; just verify this silent-empty-page is the intended contract for end-of-stream callers.

🟢 Nit 2 — section placement in agent-system.mdx: "Recovering large tool outputs" was appended after the copyright <small> block (line 1059→1083). On the rendered page it appears below the footer. Moving both new sections (## Large tool results and ## Recovering large tool outputs) before the --- separator above ## Common Pitfalls keeps the narrative flow intact.

🟢 Nit 3 — retain_excerpt budget floor: the max(200, budget - reserve) floor means the returned JSON can exceed budget when budget < ~70 chars. Production budgets are 8000–40000, so this never fires, but a brief inline comment (# floor: reserve cannot underflow for prod budgets) makes the intent explicit.

🔍 Technical details

Browser links (browser_tools.py:797)

# OLD
for i, link in enumerate(links[:100], 1):
# NEW — allocates len(links) * ~80 chars before retain_excerpt
for i, link in enumerate(links, 1):

The allocation is bounded by the page's link density, not by anything GAIA controls. A one-liner cap (links = links[:5000] or equivalent) would be a cheap ceiling; alternatively just add a comment acknowledging the tradeoff.

End-of-stream consistency

  • ArtifactStore.read: guard is if offset > len(text) — offset == len(text) returns {"content": "", "next_offset": None, ...}
  • read_text_page: same behaviour by construction (seek completes, read returns empty)
    Both agree; confirming this is deliberate avoids a future bug report.

agent-system.mdx placement — the diff lands both new sections after the final </small> at line 1059. The sections should move to just before ## Common Pitfalls and Solutions at line 468 (already done for the first section; the "Recovering" section needs to follow it).

retain_excerpt budget
reserve = len(json.dumps(metadata)) + 2 ≈ 70 chars. For budget=50: max(200, 50-70) = 200. elide_text(text, 200) returns ~200 chars of JSON; adding metadata gives ~270. So the returned string exceeds the caller's budget=50. Harmless at prod scale, but worth documenting.

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This PR adds session-scoped tool output archiving: large results get a head/tail excerpt in the LLM context while the full text is retrievable page-by-page via a new read_tool_output tool. The ArtifactStore is correctly per-agent (not shared across sessions), handles TTL and quota with explicit errors, and is thread-safe. The structured-vs-plain dispatch logic (_as_structured_payload) correctly prevents mid-record slicing on JSON strings. Test coverage is thorough across the new primitives, integration paths, and edge cases.

🟢 The "Recovering large tool outputs" section in docs/sdk/core/agent-system.mdx lands at the bottom of the file, past "Common Pitfalls and Solutions" — separated from the "Large tool results" overview by ~600 lines. A reader who finds the overview will have to scroll past the pitfalls section to find the continuation API. These are one topic; placing them adjacent (or merging them) would make the doc usable as a reference.

🟢 shell_tools.py now always calls retain_excerpt(self, stdout/stderr, max_output) even when output is within budget — retain_excerpt returns the original string unchanged in that case, so there's no functional problem. However, the from gaia.agents.base.artifacts import retain_excerpt import is now inside the hot path of every shell command rather than guarded by the truncation condition. Moving the import to the module top or outside the per-invocation code path would be cleaner.

🔍 Technical details

Doc placement — agent-system.mdx inserts "Large tool results" at ~line 490 and "Recovering large tool outputs" at the end of the file (~line 1060, after "Common Pitfalls and Solutions"). Both sections describe the same feature and should be adjacent.

Import location — src/gaia/agents/tools/shell_tools.py line ~1019: from gaia.agents.base.artifacts import retain_excerpt is inside the function body, executed on every run_shell_command call. Module-level import (or at minimum outside the result-assembly loop) avoids repeated module lookups.

No architectural violations or missing test coverage found. The ChainMap-based pre-snapshot registry, the _tool_overrides isolation pattern, and the was_text round-trip in _handle_large_tool_result all look correct. The read_text_page character-offset loop handles EOF correctly for all boundary cases.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 18, 2026
Merged via the queue into amd:main with commit 482390a Sep 18, 2026
44 checks passed
kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Sep 22, 2026
…l count

The guard this PR re-pins has never executed in any CI lane, so the numbers
it protects drifted unchallenged and it is red on main today. Wiring it into
the one lane that installs gaia-agent-chat makes the budget this PR enforces
actually enforceable.

The module opens with importorskip("gaia_agent_chat"); test_unit.yml installs
only ".[api]", so it skipped there, and none of the lanes that do install that
wheel ran the file. test_gaia_agent.yml already installs it and triggers on
src/gaia/** and tests/**.

The doc-profile tool count has been 38 since amd#3670 added read_tool_output to
the bundle; the pin still said 37. With the description budget's re-pinned
token numbers, that was the last failing assertion in the file.

Part of amd#3294.
kovtcharov-amd pushed a commit that referenced this pull request Sep 22, 2026
The doc profile has had 38 tools since #3670 added `read_tool_output` on
2026-09-18, so the pinned 37 is a stale measurement rather than a
regression. It registers unconditionally — there is no platform gate and
no optional-import gate anywhere in the doc profile's registration path —
so the count is the same on every machine.

Only the count. The char and token pins stay where they are: #4038
re-pins them on the same lines and earns those numbers by trimming the
docstrings they measure, so a value pinned here would be ~18% outside the
band the moment it lands. A docstring trim cannot move a count, so both
PRs make the identical edit to this line and neither side can lose it.
kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Sep 25, 2026
…ne (amd#4125)

The tool-loader budget tests went red on `main` without anything
regressing. Four
tests failed at once, three of them pointing at CORE bloat that never
happened —
CORE's share of the registry moved from ~40% to ~43% while the registry
itself
grew. The cause is that the reduction guards divided a freshly-measured
numerator
by a constant frozen in June, so any registry-wide edit trips every
guard
simultaneously and buries the one failure that actually means something.
Those
guards now take their baseline from the same run, so a real CORE
regression fails
the CORE test and a schema-wide change fails only the pin test.

**This PR does not turn the file green, and that is deliberate.** The
tool *count*
is re-pinned to 38, because amd#3670 added `read_tool_output` to the doc
profile on
2026-09-18 — an unconditional 12th CORE tool, so the old 37 is a stale
measurement, not a regression. The char and token pins are left alone:
amd#4038
re-pins them on the same lines and earns those numbers by trimming the
very
docstrings they measure (~17% smaller), so any value pinned here is
wrong the
moment it lands. One failure therefore survives this PR —
`test_token_baseline_when_tiktoken_available` — and it is amd#4038's to
fix. The
share ceilings hold on both sides: CORE measures 42.8% native today and
41.0%
with amd#4038 applied, against a 45% ceiling.

**A green check on this PR verifies none of the above.** No CI lane
executes this
file: `test_unit.yml` collects it but never installs the chat wheel, so
the root
`conftest.py` leaves `gaia_agent_chat` unimportable and
`pytest.importorskip`
skips the whole module at collection without printing a line. That is
why the
pins rotted unnoticed — tracked in amd#4121, not fixed here. Every result
below was
produced locally.

## Test plan

- [x] `pytest tests/unit/test_tool_loader_token_budget.py` on this
branch at current `main` → **1 failed, 9 passed** (was 2 failed, 8
passed before the count re-pin); the survivor is the native-token pin
amd#4038 owns
- [x] Test-merged with amd#4038: clean merge, no conflict;
`test_tool_loader_token_budget.py` + `test_tool_description_budget.py` →
**19 passed**
- [x] Guard still bites: temporarily inflated a CORE docstring by ~370
tokens (inside the absolute band, so only the share guard can see it) →
**1 failed, 9 passed**, `CORE native tokens 3104 exceeded 45% of the
6762-token registry measured in this run`. Reverted; not committed.
- [x] Guard stays quiet on registry-wide growth: temporarily grew a
non-CORE docstring past the band → **2 failed, 8 passed**, both ratio
guards silent. Before this change the same edit took down all four.
Reverted; not committed.
- [x] Count is not platform-conditional: read the doc profile's whole
registration path — every gate in `_register_tools()` is profile,
config, or constructor-arg; `platform.system()` appears only in prompt
text and tool bodies, never around a registration.
- [x] `python util/lint.py --all` → exit 0.

---------

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

agent::email Email agent changes agents devops DevOps/infrastructure changes documentation Documentation changes sidecar Agent sidecar contract / harness tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(tools): truncated tool output is unrecoverable, and bare strings bypass the budget

2 participants