Skip to content

fix(email): bound mail reads per turn, not just per message - #4111

Merged
itomek merged 5 commits into
mainfrom
issue-4086
Sep 22, 2026
Merged

itomek merged 5 commits into
mainfrom
issue-4086

Conversation

@itomek

@itomek itomek commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator

Closes #4086

Asking the agent "what needs me today?" makes it read several emails in one go. Each single message was already capped at 12,000 characters, but nothing capped the pile — read four or five long quoted threads and the model quietly ran out of room, losing the earlier half of its own conversation and answering from a partial view with no error anywhere. Mail reading now has a per-turn character budget sized from the machine's real context window, and once a turn has spent it the next read is refused with a result that tells the model to stop, answer from what it already read, and say so. The budget resets on the next turn.

The bound sits in the shared mixin, above both mailbox backends, so Gmail and Outlook behave identically; neither backend file is touched.

🔍 Technical details

No new tuning constant. The turn budget is Agent._truncation_budget()[0] — the same per-tool-result character cap already applied to any other large tool output, derived from the device profile via budget_for_ctx. Policy in one sentence: all the mail bodies a turn pulls in together may occupy what one large tool result is allowed to. It is therefore profile-derived by construction, and already correct for a -FLM NPU model, a cloud/gateway session, and Claude's 200K window.

profile ctx turn budget measured spend at refusal % of window at the issue's worst ratio (3.02)
NPU 32,768 30,000 chars 36,000 chars after 3 reads 36%
GPU/CPU 65,536 60,000 chars 60,000 chars after 5 reads 30%

Admission rule. A read is admitted while used < budget, so at most one message crosses the line and that one is itself capped at _MAX_BODY_CHARS — a turn can never admit an unbounded pile. Refusing earlier (when budget - used < _MAX_BODY_CHARS) would make the bound strictly ≤ budget but costs a whole read whenever bodies are small: two reads on NPU, too stingy for the triage case the issue is about.

Turn detection. Agent gains a monotonic _turn_seq, incremented in _process_query_impl — the single path every entry point (CLI, UI, API server, sidecar, hub servers) goes through. The mixin reads it with getattr and resets its ledger when it moves. _on_task_start was not usable: EmailToolsMixin is listed after ChatAgent in GaiaAgent's bases, so Agent's no-op would win the MRO — the exact trap ProjectMapMixin.__init_subclass__ exists to catch — and reordering would put a tool mixin ahead of the base agent, which the comment at gaia_agent/agent.py:236 warns against.

Replaced rather than adapted the retired sidecar's context_budget.py. The flagship wheel cannot import it (hub package, not a dependency) and its numbers are pinned to that sidecar's 16K eval target. What carried over is the method: derive from the device profile, and be pessimistic about chars per token.

Out of scope, stated: list_inbox / search_email return previews bounded by limit <= 100 and are not charged; _MAX_BODY_CHARS (#4085's constant) is unchanged; neither message-id guard was touched — they differ deliberately between the two backends.

Test plan

  • pytest tests/unit/agents/ — 1234 passed, 50 skipped
  • python util/lint.py --black --isort — both PASS
  • Mutation check: the guard was disabled (if used >= budget → if False) and 5 of the 6 new tests failed; reverted to a byte-identical tree (git status clean). The sixth is the profile-derivation test, which correctly does not depend on the guard.
  • The budget observed firing, driving 14,000-char bodies through one turn on each profile:
=== NPU profile: ctx 32768 tokens, turn budget 30000 chars ===
  read #1: OK  body 12000 chars (truncated=True), turn total 12000/30000
  read #2: OK  body 12000 chars (truncated=True), turn total 24000/30000
  read #3: OK  body 12000 chars (truncated=True), turn total 36000/30000
  read #4: REFUSED  {"action": "read_email", "success": false, "turn_budget_exhausted": true,
                     "messages_read_this_turn": 3, "budget_chars": 30000, "budget_used_chars": 36000}
    error -> This turn has already read 3 message body(ies), filling this turn's mail-reading
             budget (36000 of 30000 chars) — further reads are refused so the conversation does
             not silently overflow the context window. Answer from the messages already read,
             tell the user reading stopped here, and ask them to narrow the request or continue
             in a new turn. See https://amd-gaia.ai/docs/guides/email
  turn charged 36000 chars = ~11921 tokens at the worst measured ratio = 36% of the window
  invariant: charged (36000) <= budget + per-message cap (42000) -> True
  new turn (_turn_seq 1 -> 2): reading resumes

=== GPU/CPU profile: ctx 65536 tokens, turn budget 60000 chars ===
  read #1..#5: OK, turn total 60000/60000
  read #6: REFUSED  budget_chars 60000, budget_used_chars 60000, messages_read_this_turn 5
  turn charged 60000 chars = ~19868 tokens at the worst measured ratio = 30% of the window
  new turn (_turn_seq 1 -> 2): reading resumes
  • Not run: gaia eval — the judge credential is failing intermittently in CI and would not produce an attributable signal.

…r-message

A triage turn could read several long emails in a row with no combined
limit, quietly filling the context window and leaving the model answering
from a partial conversation with no error anywhere.

read_email now tracks the bounded body chars it has pulled into the current
turn and refuses once that reaches the same per-tool-result budget the
agent already uses for large results (Agent._truncation_budget, scaled off
the device's real context window). The refusal is a structured result the
model must relay, naming what stopped, what to do, and where to look.

The base Agent gains a monotonic _turn_seq counter so the per-turn ledger
knows when a new turn has started.
@github-actions github-actions Bot added tests Test changes agents labels Sep 22, 2026
@itomek

itomek commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Evidence

Real-world tier excluded up front: proving a character budget needs no mailbox and no inference, and this session holds no live Gmail/Graph grant. The strongest available surface is the real Agent.process_query loop, which is what the integration tier below drives — that is where the per-turn reset actually has to work.

Integration — the budget driven through a real Agent.process_query

A real Agent subclass composing the real EmailToolsMixin, with the LLM stubbed to keep asking for read_email and the mailbox behind a real httpx transport serving 14,000-char bodies. Each body carries an unguessable marker so an admitted read can be told from a fabricated one.

real Agent built: MailAgent, turn budget 30000 chars (NPU profile)

--- turn 1: the model tries to read 6 messages ---
  Tool: read_email   (x4 — the 4th is the refusal)
  turn-1: _turn_seq 0 -> 1, ledger reads=3, chars=36000/30000

--- turn 2: a fresh user turn ---
  Tool: read_email   (x2)
  turn-2: _turn_seq 1 -> 2, ledger reads=2, chars=24000/30000

--- planted-fact check on the raw tool results ---
  markers echoed by admitted reads: ['violet-otter-06', 'violet-otter-07', 'violet-otter-08']
  refusal carries a body: False
  refusal carries any marker: False
  refusal payload: {"action": "read_email", "success": false, "turn_budget_exhausted": true,
                    "messages_read_this_turn": 3, "budget_chars": 30000, "budget_used_chars": 36000}

Three things this proves that the unit tests alone do not: the turn counter really does move once per user turn through the live agent loop; the ledger really does reset on the next turn (turn 2 read again from zero); and the refusal carries no body and no marker, so a partial read can never be relayed as a complete one.

Unit

$ pytest tests/unit/agents/ -q
1234 passed, 50 skipped, 1 warning in 57.40s

$ python util/lint.py --black --isort
| Code Formatting (Black)        | [OK] PASS  | - |
| Import Sorting (isort)         | [OK] PASS  | - |
[SUCCESS] ALL QUALITY CHECKS PASSED!

No failures to attribute, so no base-vs-patch differential was needed.

Mutation check — the tests fail without the guard

The admission check was disabled (if used >= budget → if False) and the suite re-run:

FAILED test_turn_budget_refuses_once_the_turn_is_full
FAILED test_turn_budget_refusal_tells_the_model_to_stop_and_say_so
FAILED test_turn_budget_resets_on_a_new_turn
FAILED test_turn_budget_guard_runs_before_the_backend_call
FAILED test_turn_budget_guard_would_fail_if_the_admission_check_were_removed
5 failed, 1 passed

The one that passes is the profile-derivation test, which correctly does not depend on the guard. The tree was reverted byte-identically (git status clean) before any commit.

Not exercised

  • No live mailbox: neither backend's HTTP layer was driven against a real Gmail or Graph endpoint. The guard sits above both and refuses before any backend call — a test asserts exactly that — but the end-to-end read against a real provider is untested here.
  • gaia eval was not run: the judge credential is failing intermittently and would not produce an attributable signal.

The per-turn counter was created in Agent.__init__, so any subclass or
test double that builds an instance directly hit AttributeError the
moment a turn started — three unit-test jobs went red on it. Declaring
it on the class gives every instance a starting value; the increment
still writes per-instance.
@itomek

itomek commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Three unit-test jobs went red after this went ready for review. The per-turn counter only existed once an agent had run through its normal constructor, so any lightweight subclass or test double that skips it errored out the moment a turn began. It is now a class-level default, so every instance starts at zero and the increment still stays per-instance. A test pins that an __init__-bypassing subclass still counts turns.

Evidence below is measured on 63732fbc, on top of base 83aa69dd (branch is not behind main).

🔍 Technical details

Discriminated against main in a separate baseline worktree rather than asserting it:
tests/unit/test_skill_discovery_integration.py::test_discovery_runs_before_the_turn_tool_filter
passes on 83aa69dd, failed on the branch, and the traceback named the attribute directly:

self._turn_seq += 1
E   AttributeError: '_Agent' object has no attribute '_turn_seq'
src/gaia/agents/base/agent.py:5540

After the fix:

$ pytest tests/unit/agents/ -q
1235 passed, 50 skipped, 1 warning in 57.32s

$ python util/lint.py --black --isort
[SUCCESS] ALL QUALITY CHECKS PASSED!

CI at this head: Unit Tests py3.10 / py3.12 / macOS smoke all pass, alongside Code Quality, CodeQL, Email Agent, Chat Agent, Gaia Agent, Security, build.

The earlier turn-budget evidence is unaffected — this change alters only where the counter's initial value lives, not when it moves or what the budget does.

The red pr-review / run is the known harness failure, not a verdict: its result JSON reports total_cost_usd: 0 with is_error: true and no review was produced.

@itomek

itomek commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Rebuilt on current main after #4109 and #4095 landed, and re-verified there — the earlier evidence was measured on the older base, so it does not carry over on its own.

main merged in cleanly with no conflicts, and the one real overlap was checked rather than assumed: #4095 reworked context-overflow sizing, but it added active_profile_ctx_size() for the error classifiers, which is a different function from the truncation_budget this PR's mail-reading budget derives from. Both still exist and neither call site changed.

Measured on 28affca1, base 4fe3f606, branch zero commits behind main:

$ pytest tests/unit/agents/ tests/unit/test_skill_discovery_integration.py tests/unit/test_ctx_overflow_device_profile_2884.py -q
1279 passed, 50 skipped, 1 warning in 59.89s

$ python util/lint.py --black --isort
[SUCCESS] ALL QUALITY CHECKS PASSED!

CI at this head: 30 checks green, including all three Unit Tests legs, Code Quality, CodeQL, Security, and the Email / Chat / Gaia agent suites. The review bot also ran clean here (pr-rereview), unlike the earlier run.

🔍 Technical details

tests/unit/test_ctx_overflow_device_profile_2884.py is #4095's new suite; it is included above to confirm this branch does not disturb the overflow sizing it pins.

Five self-hosted hardware lanes remain queued and have not started: API Server Tests, GAIA CLI on Windows, Agent SDK on Windows (Lemonade), Example Agents Integration (stx), and behavior-e2e. That pool has been saturated repo-wide for several hours — #4109 merged with the same four lanes still pending, so they are not gating and re-queueing would not change it. None of them exercise this diff, which is pure Python in the agent base and the email tool mixin; the lanes that do cover it are green above.

@itomek
itomek added this pull request to the merge queue Sep 22, 2026
Merged via the queue into main with commit 88441a0 Sep 22, 2026
43 of 44 checks passed
@itomek
itomek deleted the issue-4086 branch September 22, 2026 07:21
kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Sep 22, 2026
The budget lint this PR adds fails the moment it meets current main:
amd#4111 landed a fourth paragraph on `read_email` while this branch was
open, taking its schema description to 590 chars against a 400 budget.
The failure is real — that text is re-sent on every model call of every
turn — so the fix is to trim it, not to widen the budget.

Both contracts the paragraphs carried are kept: a truncated body still
announces itself with its original length, and a turn that has spent its
mail budget still tells the model to stop rather than retry.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(email): mail reads are bounded per message but not per turn, so a triage turn can exhaust the context window

1 participant