Skip to content

fix(agent): preserve tool evidence across TUI turns and restarts - #3666

Merged
itomek merged 31 commits into
amd:mainfrom
kovtcharov:codex/3628-persist-tool-history
Sep 25, 2026
Merged

itomek merged 31 commits into
amd:mainfrom
kovtcharov:codex/3628-persist-tool-history

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

GAIA can now answer follow-ups using prior tool evidence in the TUI, including after reopening its transcript. Previously the saved conversation could retain only the final prose, losing facts the tools had read. Complete turns are archived locally and replayed within a budget that reserves room for the current prompt, tools, and answer.

Closes #3628. Depends on #3669 (included here); also includes the SDK null-content normalization from #3758 with original authorship.

🔍 Technical details

The TUI stores its transcript under GAIA_TUI_HOME/history/; --history-file or GAIA_HISTORY_FILE reopens an explicit transcript. Whole tool groups stay intact when older turns leave the active window. Persistence completes before the terminal response, and clearing the history deletes its archive. Legacy chat persistence uses the same budget calculation.

Test plan

  • 219 integrated configuration, SDK, history, and stdio tests passed; 106 history/stdio tests passed after the final error-handler cleanup.
  • CI runs the history/stdio regression coverage and context-resolution tests.
  • Real TUI with local Gemma-4-E4B and memory disabled: read a file, omit its facts from the final answer, delete the file, then recover its code in a follow-up without a tool call.
  • Restart the TUI with the same transcript and recover ledger number 7319, which appeared only in the deleted file's tool result.
  • Formal agent quality evaluation and human review. One initial live follow-up hit a backend timeout; the retry and restart checks passed. These checks establish evidence retention, not a latency or quality benchmark.

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

Copy link
Copy Markdown
Contributor

Request changes — the feature itself is well built, but one edge case turns a long message into a failed turn, and the eval this change requires hasn't run yet.

This makes the chat agent remember its actual tool calls and results across turns (and across restarts) instead of replaying five truncated text pairs. That's a real capability win, and the persistence, migration and restart paths are carefully tested.

Three things to settle before merge:

  • A long message can break the turn outright. The history budget is computed as "what's left after the system prompt, tools and the user's message"; when the user pastes something big — or dials the context window down with the newly documented GAIA_CTX_SIZE — that number goes negative and the code raises before the model is ever called. The user sees a generic "something went wrong" even though there's no history to drop. Dropping history (with the warning that already exists) is the right answer here; the model's own overflow error is the loud failure that should surface.
  • Switching a session's model can replay tool calls a model can't read. Saved turns keep native tool-call structure. If the user switches that session to a model without native tool calling, that structure gets replayed verbatim with no downgrade step — the same prose conversion already applied to legacy tool results would cover it.
  • The eval is still unchecked. This changes what every turn sends to the model, which is exactly the surface the repo requires gaia eval agent --category context_retention for. Your own test plan flags it; it needs to run and be compared to the committed baseline before merge.

There's also a performance cost worth a look: every streaming turn now reads and JSON-parses the whole session's stored traces twice, then token-counts every turn including ones that will be evicted.

Real-world evidence

No evidence-bundle.md was produced for this run, so the automated lane captured nothing. The PR description does carry its own evidence — a browser/HTTP/SQLite restart journey with a rendered screenshot showing a restored fact surviving a backend restart — which covers the persistence and restore surface. It does not cover local-model behaviour: the context_retention eval is explicitly unchecked. So the verdict above rests on static review plus the author's transport-level evidence, with the LLM-behaviour surface unverified.

🔍 Technical details

🟡 Important

1. Negative history budget raises instead of dropping history (src/gaia/agents/base/history.py:328, src/gaia/ui/_chat_helpers.py:1048)

budget = min(ctx // 2, ctx - overhead - output - 2048) goes negative when overhead (system prompt + tool schemas + the user's message) approaches the window, and select_history raises ValueError unconditionally — before looking at whether there are any turns to select. An empty session with a large pasted message fails the same way. On a 32K NPU window a ~50K-char paste is enough; with GAIA_CTX_SIZE=16384 (the tight-RAM case docs/sdk/configuration.mdx now advertises) a large system prompt alone can do it. In the streaming path this lands in the generic except and the user gets "Sorry, something went wrong on my end."

Dropping history is the correct degradation and already has a warning channel; the loud failure should stay with the model's own context-overflow classification.

    if budget <= 0:
        logger.warning(
            "No context budget remains for history; replaying none of the %d "
            "stored turn(s). Full evidence remains in the session database.",
            len(turns),
        )
        return []

2. Native tool history replayed into a non-tool-calling model (src/gaia/ui/_chat_helpers.py:1049)

_restore_model_history assigns the stored trace to agent.conversation_history verbatim, including role: "tool" entries and assistants carrying tool_calls. The Agent UI lets a session change models, and is_tool_calling_model() (lemonade_client.py:602) returns False for several registered models — Agent._uses_native_tool_calls() then composes a prose/JSON prompt while the replayed history still contains native call structure. TurnMessages.finish already has the downgrade for orphaned legacy results; gating on agent._uses_native_tool_calls() and applying that same conversion during restore would close it.

3. Whole-session read + parse twice per streaming turn (src/gaia/ui/_chat_helpers.py:1755, database.py:756)

_stream_chat_impl now calls db.get_context_messages(...) — unbounded, and it json.loads every stored trace — solely to build history_pairs, which is only consumed by the email sidecar path (_dispatch_email_query). _restore_model_history then reads and parses the same rows again. select_history afterwards json.dumps + count_tokens every turn, including the old ones it is about to evict. Tool results are capped at ~30K chars each, so a long session's traces reach multiple MB; this is O(entire session) CPU on the per-turn hot path. Passing the already-read rows into _restore_model_history, and skipping the email-only history_pairs build for in-process sessions, removes most of it.

Related: _build_history_pairs now receives autonomous rows too, which breaks user→assistant adjacency for the email path when a tick lands mid-conversation.

4. Missing mandated eval for an LLM-affecting change

Per CLAUDE.md, changes to what the agent sends the model require gaia eval agent against the relevant category with a baseline comparison. This replaces 5 truncated text pairs with up to half the context window of native tool evidence — a large behavioural change. --category context_retention --agent-type chat is the matching run; the PR's own test plan leaves it unchecked.

🟢 Minor

5. messages.recorded.clear() is the linchpin of "current turn only" but has no comment (src/gaia/agents/base/agent.py:4892) — it reads as a no-op; it's what drops the prior conversation_history from the saved trace.

        # Drop the replayed prior history: only this turn gets recorded.
        messages.recorded.clear()

6. finish() assumes every tool call carries id and function.name (history.py:290) — a KeyError here fires at the very end of process_query, converting a completed answer into a failed turn. call.get("id") / call.get("function", {}).get("name", "unknown") is cheap insurance.

7. resolve_ctx_size reads GaiaConfig.load() from disk whenever device is None (lemonade_client.py:262) — now on the per-turn path via both _ensure_model_loaded and _restore_model_history. Worth caching.

8. The select_history error text says "shorten the prompt" (history.py:328) — the usual cause is the system prompt plus tool schemas, which the user can't shorten. Moot if finding 1 is applied.

Also noting without flagging: removing the policy-block dedup in _stream_chat_impl (so the block row can carry model_messages) means that row is now deleted and reinserted with a new id each time. Looks intentional and harmless, but it isn't mentioned in the description.

Strengths

  • The migration is genuinely careful. _migrate_autonomous_role preserves ids, indexes and sqlite_sequence, and test_role_migration_failure_rolls_back_ddl_and_can_retry proves the DDL rolls back and the retry succeeds — that's the test most schema-rewrite PRs skip. It also fixes a real latent bug: autonomous rows were being written against a CHECK that rejected them, with the IntegrityError swallowed by except Exception: pass.
  • TurnMessages solves the overflow-trimming problem cleanly. Deep-copying on append and using messages[:] = ... for the shrink means overflow recovery narrows what the model sees without destroying what gets persisted — and finish() refuses to claim an interrupted tool call succeeded.
  • resolve_ctx_size consolidates context resolution that was previously duplicated between cli.py and _ensure_model_loaded, with the invalid-override case now failing loudly and tested end-to-end against a real loopback HTTP server rather than a mock.
  • Good pass on the silent-fallback debt — the except Exception: pass blocks touched along the way were converted to logged handlers rather than left as precedent.

kovtcharov and others added 13 commits September 14, 2026 15:56
On every non-Claude backend, the history sent to the model before each
request rewrote each tool-call turn as an assistant message whose content
was the word "None", and dropped the call. _structure_history_message
normalised content with str(), msg.get("content", "") returns None when
the key exists, and only the Claude branch kept tool_calls. The model
never saw which tools it had called or with what arguments.

minimax-m3 copied it: on 2 of 4 coding tasks it replied "None", which
became the final answer. No other model printed it across ~90 runs, but
all of them received the same history.

A tool-call turn is now rendered as "[Tool call: name(args)]", the same
text convention tool results already use, with any text the model sent
alongside it kept. None content becomes an empty string, never "None".
The Claude path is unchanged.

Closes amd#3757

Co-Authored-By: Claude Opus 5 <[email protected]>
Replaying a tool-call turn as "[Tool call: name(args)]" taught non-Claude
models to write calls in that text format instead of calling tools, so the
parser rejected them and the turn gave up. On the same 144-run battery that
went from 0 to 58 runs ending in "I had trouble formatting my tool call".

The turn is now just its own text (empty when it had none). The None -> ""
guard stays, so the word "None" is still never replayed.

Co-Authored-By: Claude Opus 5 <[email protected]>
@github-actions github-actions Bot added the chat Chat SDK changes label Sep 15, 2026
# Conflicts:
#	src/gaia/agents/base/agent.py
#	tests/unit/test_sdk_history_tool_calls.py
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Merged main to clear the conflict — the branch is mergeable again, and the merge introduced no new failures.

Both conflicts turned out to be easy. The one in the agent was two unrelated additions landing on the same line, so both are kept. The test file was an add/add: main had already landed #3758 on its own, with a fuller version of the same tests than the copy this branch carried, so main's won.

🔍 Technical details
  • src/gaia/agents/base/agent.py — union merge: this branch's result["model_messages"] = messages.finish(...) alongside main's turn_record sealing. Both sit before the trace write, which is the ordering main's comment requires.
  • tests/unit/test_sdk_history_tool_calls.py — add/add. Main's version is a strict superset (7 tests vs this branch's 2), so it was taken whole. The PR body already noted it bundled fix(chat): stop replaying tool calls to the model as "None" #3758; that bundling is now redundant.
  • .github/workflows/test_chat_agent.yml shows in the diff against main, but main never touched it since the merge base — the branch's own edit carried through unmodified.

Verified against a baseline rather than eyeballed: tests/unit/chat/ui/ fails 228 on origin/main in this environment (a local network-guard quirk, not this branch). This branch fails 225 and passes 66 more. Six tests fail here that don't on main; all six fail identically on the unmerged branch, so none are merge damage — five are in this branch's own new test_model_history.py and one is a test_document_monitor.py error.

Plain merge commits, no rebase or force-push.

kovtcharov and others added 2 commits September 21, 2026 23:11
…ol-history

One conflicted file, src/gaia/llm/lemonade_client.py: both sides added a
different context helper at the same spot. Kept both — they answer different
questions and each has live callers.

  resolve_ctx_size()        decides what window to REQUEST at startup and on
                            reload; honors the GAIA_CTX_SIZE override.
  active_profile_ctx_size() REPORTS the device profile's window with no
                            override applied, for the overflow classifiers.

Collapsing them would have either made the classifiers follow a user override
(so a deliberately small window reads as a broken load) or dropped the override
from startup entirely.

cli.py, agents/base/agent.py and ui/_chat_helpers.py auto-merged; audited in
both directions. The branch's history/evidence work and main's move of the
Lemonade error classifier into providers/lemonade.py touch disjoint regions and
both survive intact.
# Conflicts:
#	hub/agents/gaia/python/tests/test_stdio.py
@itomek itomek self-assigned this Sep 24, 2026
@itomek

itomek commented Sep 24, 2026

Copy link
Copy Markdown
Collaborator

Reviewed this end-to-end. It's real work and it's close — the remaining blockers are the conflict, the bundled #3669 lines, and the eval, and only one of those needs a judgement call from you.

The conflict is trivial. Only two files actually conflict, and none of the hard parts do — lemonade_client.py, lemonade_manager.py and the model_messages/turn_record union in agent.py all auto-merge, because git replays your own earlier resolutions. Three hunks, none of them a judgement call. Resolved locally against main @ 06078dee: 1311 passed across the touched suites, zero failures, and zero tests failing on the merge that pass on pristine main. util/lint.py --black --isort clean.

Every review-bot finding is addressed except one, and that one is yours to call. The per-turn history read is unbounded — get_context_messages has no LIMIT or role filter, and select_history token-counts every turn including the ones it's about to evict. Main used get_recent_messages(limit=20), so per-turn latency now grows with session length. It isn't a few lines: a row cap can't be proven ≥ what a token budget would keep, so capping silently truncates exactly the long-session case this PR exists to fix. Memoizing the per-turn token cost is the behaviour-preserving alternative.

The eval still hasn't run, and not for lack of trying. gaia eval agent can't start in this environment at all — mcp>=2.0.0,<3.0 isn't installed, so the MCP server dies on import and every scenario returns INFRA_ERROR. That's pre-existing and unrelated to this branch; main fails identically. Filed separately. No score exists for this PR — please don't read the failed runs as one.

🔍 Technical details

Verified against head 4b1ced3a and the resolved merge 1b0fe4ff (parents 4b1ced3a + 06078dee). Re-merge against current main when you apply it, since main moves.

The three conflict hunks

1. .github/workflows/test_chat_agent.yml — add/add path-filter list, in both the push and pull_request blocks. Union both:

      - 'src/gaia/llm/**'
      - 'src/gaia/ui/**'
      - 'tests/unit/chat/ui/**'
      - 'tests/unit/agents/test_model_history.py'

2. src/gaia/agents/base/agent.py ~1213 — docstring; the branch and main rewrote different lines. Take one from each:

            max_consecutive_repeats: Maximum consecutive identical tool calls before stopping (default: 4; at least 2, or ValueError)
            min_context_size: Minimum context size required; unset uses the model/device resolver.

3. src/gaia/agents/base/agent.py ~1295 — main's condition (drops the retired use_chatgpt, #3899) plus the branch's import list; resolve_ctx_size is required by the auto-merged body at :1310:

        if not (use_claude or skip_lemonade):
            from gaia.llm.lemonade_client import (
                LemonadeClient,
                cloud_model_provider,
                resolve_ctx_size,
            )

Bot findings, adjudicated at 4b1ced3a

Finding Status
Negative budget raises instead of dropping history Fixed — history.py:92-97 warns and returns []
Native tool history into a non-tool-calling model Fixed — gated on _uses_native_tool_calls() (_chat_helpers.py:1059-1065)
Double read per streaming turn Half fixed — pairs build now gated on agent_type == "email" (_chat_helpers.py:1805-1809); the unbounded read remains
Over-wide except Exception in run_turn Fixed — stdio.py:1084-1090, 1109-1114 wrap only _record_turn
Migration idempotency + test isolation Fixed in 7029ca71

Two nits still open, neither user-visible: finish() indexes call["id"]/call["function"]["name"] (history.py:54-57) — unreachable, since _build_assistant_message raises a frame earlier; and resolve_ctx_size re-reads ~/.gaia/config.json per turn when device is None (lemonade_client.py:329-332).

One inherited issue, not introduced here: get_context_messages has no role filter, so autonomous rows still reach _build_history_pairs, which only pairs a user immediately followed by an assistant — an interleaved tick silently drops the pair around it. Main's get_recent_messages didn't filter either.

Three things worth a follow-up

  • TUI transcripts accumulate without bound. ~/.gaia/tui/history/<uuid4>.sqlite3, a new file per launch, carrying full tool output including local file contents. Mode 0600, but nothing prunes them.
  • The title overstates the shipped behaviour. "across restarts" holds only with --history-file/GAIA_HISTORY_FILE; the default starts a fresh session each launch, which the docs say but the title doesn't.
  • text_tool_history's [Recorded tool calls] branch is reachable only on a cross-model replay — turns recorded under a native model, then the session switched to gemma4-it-e2b-FLM (the only chat-capable model with tool_calling=False). It can't fire from same-model history, since _build_assistant_message only attaches tool_calls on the native path. The tool-result branch is main's own sdk.py:238 fallback relocated, so nothing to change there. Narrow and unmeasured either way; deleting the one line to match sdk.py:238 would settle it.

On the eval

eval/mcp-config.json → mcp_server_launcher.py → from mcp.server import MCPServer (agent_ui_mcp.py:282) → ModuleNotFoundError → the gaia-agent-ui server dies → claude -p gets zero tools → INFRA_ERROR on all four scenarios in 10–17s each. The judge itself authenticates fine, so that's not the issue.

Worth noting for whenever it does run: --agent-type chat exercises the UI path (agent_loop.py, _chat_helpers.py, routers/chat.py — all in this PR) but not hub/agents/gaia/python/gaia_agent/stdio.py, which carries the headline budgeted-replay change. That surface stays unmeasured by this category.

The committed baseline is 4/4 PASS, avg 9.25 — scored on the old 5-pair clamp, so it can only move.

@itomek

itomek commented Sep 24, 2026

Copy link
Copy Markdown
Collaborator

Correcting my earlier comment, and posting the eval it was missing. The eval passes — but I was wrong that this introduces no user-visible defect, and that correction matters more than the eval does.

The regression: a heavy turn can wipe the whole conversation

After a document- or code-heavy turn, the agent can lose the entire conversation, not just its oldest part.

The new selector admits whole turns. When the newest turn alone doesn't fit the budget, it throws away everything — including short earlier exchanges that fit fine. Main always re-injected the last 5 exchanges truncated to 2000 chars, so the previous turn was guaranteed to survive. Nothing guarantees that now.

This was reproduced against the merged tree by running the real select_history, not by reading it. On a 32K NPU context, using the numbers the code sets itself — 8192 reserved for output, a system prompt the code's own comments peg at ~7.7K — the budget lands near 10,600 tokens. One turn carrying three tool results at the repo's own 20,000-char NPU truncation cap measures ~15,500 tokens, and the selector returns zero messages. Two results (~10,500) still fit, so this is one ordinary step past the edge, not a pathological input.

There's a deterministic variant too. A turn that overflowed mid-run and was rescued by shrinking persists its pre-shrink trace, which by construction exceeds the whole window — so the very next turn wipes history every time. That makes long, valuable sessions the most likely to hit it.

What the user sees: they ask a follow-up and the agent has forgotten the task, the file under discussion, and their name. The only trace is a log warning that never reaches the UI. NPU users hit it first, and it's close to unreportable from the field.

Related, same place: resolving the negative-budget finding by returning an empty history instead of raising swaps a loud error for a silent total loss, which reads against the no-silent-fallbacks rule.

The eval passes

context_retention now runs against the merged tree and comes back 4/4 PASS with no status changes against the committed baseline — a clean no-regression signal.

The absolute scores are not comparable and the apparent +0.6 should not be read as an improvement: the committed baseline was scored by Sonnet 4.6 and this run by Opus 5, so the delta mixes a judge change with any behaviour change. --compare says so itself. Regenerating the baseline under Opus 5 is what it would take to claim anything stronger.

Two limits on that evidence. It was measured on a local, never-pushed merge of this PR with main, so it isn't reproducible from any ref here. And --agent-type chat exercises the Agent UI path only — it never touches the TUI sidecar that carries the budgeted-replay change, which stays unmeasured.

Also correcting: my "lint clean, 1311 passed" overstated its coverage

Both statements were true of what they covered, but they read as covering the whole PR, and they exclude the hub half of it.

util/lint.py only scans src/gaia and tests, so the ~190 changed lines under hub/agents/gaia/python/ have never been through black or isort — and CI won't catch it either, since the unit-test workflow doesn't watch hub/**. Separately, pytest's configured test path is tests, so the 73-test suite covering this PR's stdio.py rewrite isn't collected by a plain pytest run.

Both hub gaps are worth a follow-up issue on their own — adding hub to the lint dirs and hub/** to the unit-test path filter.

🔍 Technical details

The wipe

src/gaia/agents/base/history.py:106-115. The len(retained) > 1 guard stops the eviction loop with the oversized turn still in the deque, then retained.clear() drops that too:

if used > budget:
    target = budget // 2
    while len(retained) > 1 and used > target:
        _, removed = retained.popleft()
        used -= removed
    if used > budget:
        retained.clear()

Measured with the real select_history and count_tokens, budget 10643 (= min(32768//2, 32768 − overhead − 8192 − 2048)):

1 capped tool result  =  5,323 tokens -> 10 history messages retained
2 capped tool results = 10,466 tokens -> 12 retained
3 capped tool results = 15,529 tokens ->  0 retained   <-- everything gone

Only fires when the oversized turn is the most recent one; with it earlier, later small turns survive.

  • Budget: history_budget → min(ctx // 2, ctx - overhead - output - 2048) (history.py:210); output is chat.config.max_tokens = 8192 (agent.py:1403); NPU_CTX_SIZE = 32768 (lemonade_client.py:310).
  • Tool-result cap: budget_for_ctx (lemonade_client.py:426-435) — 30000/20000 chars for a 32768 window.
  • Even with zero prompt overhead the budget caps at ctx // 2 = 16384, so ~4 capped results in one turn wipes history regardless of prompt size.
  • Why turns are this large: the PR persists the full model trace (model_messages, database.py:805-812) and replays it via transcript_turns, so tool results count toward a turn's cost — unlike main, which stored text pairs only.
  • Pre-shrink persistence: messages[:] = self._shrink_messages_for_overflow(messages) (agent.py:6169, 6327) is a slice assignment, so it bypasses TurnMessages.append and recorded keeps the oversized copies that finish() persists.
  • Main's floor: _chat_helpers.py:1635-1644 on 06078dee, _MAX_PAIRS = 5 / _MAX_CHARS = 2000, on both paths. The PR replaces both with select_history(turns, history_budget(agent, query)) (_chat_helpers.py:1065), which has no floor.
  • Fix shape: keep at least the most recent completed turn (or a text-truncated fallback pair) instead of clearing, and surface the drop rather than only logging it at history.py:117.

One caveat on the numbers: the estimator is turn_metrics._Tokenizer, whose own docstring says absolute counts differ from Gemma's tokenizer and that it's meant for ratios. That moves the margins, not the conclusion.

Coverage gaps

  • util/lint.py:29-30, 47 — LINT_DIRS = [SRC_DIR, TEST_DIR] = src/gaia, tests. The string hub appears nowhere in the file; those are the only paths passed to black (:142) and isort (:213-220).
  • .github/workflows/test_unit.yml:15-23 — path filters carry no hub/**.
  • pyproject.toml:51 — testpaths = ["tests"], so hub/agents/gaia/python/tests/ is outside default collection.
  • stdio.py is black-dirty right now (around :142), but identically so on pristine main — pre-existing, not introduced here.
  • "No test fails on the merge that passes on main" is a set difference: anything failing on both sides drops out, so it can't prove absence of a regression. feat(email): the flagship can only read Outlook — Gmail has no backend, so the first-choice mailbox is untestable #4052 reported "zero unique failures" from that same comparison with a real regression inside it.

Corrections to line citations in my earlier comment

  • The except narrowing in stdio.py is at 1098-1103 and 1124-1129 in the merged tree (1086-1091 / 1112-1117 at PR head), not the 1084-1090 / 1109-1114 I posted. The fix itself is real and correctly described.
  • I called finding 3 "half fixed" — the double read is in fact fully gone. The two get_context_messages call sites (_chat_helpers.py:1059 and :1806) are mutually exclusive per turn. The unbounded SELECT at database.py:806-812 is a separate open item, not the unfixed half.
  • select_history's return [] is at history.py:98; max_consecutive_repeats < 2 starts at agent.py:1260.
  • The four workflow paths: lines I quoted are the conflict hunk, not the complete list — 18 other entries surround them and stay.

@itomek

itomek commented Sep 24, 2026

Copy link
Copy Markdown
Collaborator

Two things from the review, with the numbers behind them.

The eval is clean. context_retention runs 4/4 with no status change against the committed baseline. Treat the +0.6 average as unattributable rather than as an improvement — the baseline was scored by Sonnet 4.6 and this run by Opus 5, and the compare tool warns about that itself. Two further limits worth stating: it ran against a local merge of this branch with main that was never pushed, so it is not reproducible from a ref, and --agent-type chat never exercises the TUI sidecar this PR is actually for.

The history wipe is real, and it is one branch. When a single turn is over the history budget on its own, history selection returns an empty list — it discards the oversized turn and the earlier turns that would have fit. On an NPU box (32K context, a 16,384-token budget) three tool results at the repo's own truncation target is enough; on a GPU box it takes four. That size is not a worst case picked to make it fire: a single query_documents call on a 50+-chunk corpus returns ten ~2,000-char chunks, which is exactly the size used.

Worth saying plainly, because it makes the ask smaller than the headline: the code degrades correctly right up to that point. At GPU with three results — 32,557 tokens against a 32,768 budget — it drops the five earlier turns and keeps the newest turn whole, which is what it is designed to do. Only the last resort is wrong: it should return the newest turn alone, or the earlier turns that fit, instead of clearing both.

One thing the existing unit test misses: it places the oversized turn in the middle of the history, which is the one position where this branch is harmless because a later turn gets appended after it. Move that turn to the newest position — the only position a just-completed turn ever occupies — and it fails.

And one correction to my own earlier framing: this is not like-for-like with main. Main's floor kept five user/assistant pairs truncated to 2,000 chars each and never carried tool results at all. "Main could not return an empty history" is literally true, but what main guaranteed to survive was ~5K tokens of prose, not a tool-bearing turn.

Repro from a checkout of this branch — no server, no model, runs in a second:

# save as mini_repro.py at the repo root, then: python mini_repro.py
import sys
sys.path.insert(0, "src")
from gaia.agents.base.history import select_history
from gaia.llm.lemonade_client import NPU_CTX_SIZE

budget = NPU_CTX_SIZE // 2      # what history_budget() returns on an NPU box
result = "log line\n" * 2500    # 20,000 chars = one truncated tool result

earlier = [[{"role": "user", "content": f"q{i}"},
            {"role": "assistant", "content": f"a{i}"}] for i in range(5)]
newest = [{"role": "user", "content": "compare the three reports"},
          {"role": "assistant", "content": "", "tool_calls": [
              {"id": f"c{i}", "type": "function",
               "function": {"name": "search_documents", "arguments": "{}"}}
              for i in range(3)]}]
newest += [{"role": "tool", "tool_call_id": f"c{i}", "name": "search_documents",
            "content": result} for i in range(3)]
newest += [{"role": "assistant", "content": "here you go"}]

kept = select_history(earlier + [newest], budget)
print("budget        :", budget, "tokens")
print("messages in   :", sum(len(t) for t in earlier) + len(newest))
print("messages kept :", len(kept))
WARNING | gaia.agents.base.history.select_history | history.py:117 | Context budget
excluded 6 older turn(s); full evidence remains in the session database
(history budget: 16384 estimated tokens).
budget        : 16384 tokens
messages in   : 16
messages kept : 0
🔍 Technical details

Where the wipe comes from

src/gaia/agents/base/history.py:102-115. The loop appends the newest turn, sees used > budget, evicts older turns down to while len(retained) > 1, so it stops with the newest turn alone. It then re-checks if used > budget and, if that lone turn is still over, calls retained.clear() at :113. The turn it was trying to save is discarded along with everything else, and select_history returns [].

There is no compensating floor downstream. _chat_helpers.py:1065 assigns the result straight to agent.conversation_history, and agent.py:5581 guards with if hasattr(...) and self.conversation_history: — an empty list extends nothing. Same for the TUI path via SessionHistory.prepare (history.py:263).

The budget, and why the harness could not have rigged it

history.py:210 — min(ctx // 2, ctx - overhead - output - 2048), with output = 8192 read live from AgentConfig.max_tokens (agent.py:1403).

Measured on both profiles: NPU min(16384, 16518), GPU min(32768, 49286). ctx // 2 binds in both, so the system-prompt size cannot move the result at all — any overhead below 6,144 (NPU) / 22,528 (GPU) tokens gives the same budget. Substituting the repo's own measured flagship prompt (6,757 tokens, turn_metrics.py:52) makes the second term bind on NPU and drops the budget to 15,771 — i.e. production is tighter than the repro ran, not looser.

Correcting a label in my own output

The driver script prints target 20000 chars <- per-tool-result cap. "Cap" is the wrong word. agent.py:4724 truncates only when len(result_str) > threshold (30,000 NPU / 60,000 GPU), so 20,000/40,000 is the post-truncation target — a 25,000-char result passes through whole. That cuts in favour of the finding: at the true untruncated ceiling the GPU wipe moves from four results down to three.

Sensitivity — it is not knife-edge on one filler

Swept through the real select_history, varying the tool-result text between log-like output (3.85 chars/token) and plain English prose (5.68 chars/token), and the per-result size between the truncation target and the largest untruncated payload:

### NPU  ctx=32768  budget=16384
  log-like  20000 ch/result -> first wipe at N=3
  log-like  29999 ch/result -> first wipe at N=3
  prose     20000 ch/result -> first wipe at N=5
  prose     29999 ch/result -> first wipe at N=4

### GPU  ctx=65536  budget=32768
  log-like  40000 ch/result -> first wipe at N=4
  log-like  59999 ch/result -> first wipe at N=3
  prose     40000 ch/result -> first wipe at N=5
  prose     59999 ch/result -> first wipe at N=4

It wipes in all eight cells; only the trigger count moves. Sweeping turn size continuously puts the NPU boundary at roughly 62,000 chars of turn content — and since one result contributes at most ~30,000 chars before truncation, three is the arithmetic minimum, not a chosen number.

Input-size provenance: chunk_size = 500 tokens (rag/sdk.py:92), converted by the SDK's own comment at sdk.py:1419 to ~2,000 chars/chunk; query_documents returns an adaptive 5 / 10 / 20 / 25 chunks (rag_tools.py:362-380). Ten chunks is 20,000 chars. Nothing caps tool calls per turn anywhere near three — DEFAULT_MAX_STEPS = 50 (agent.py:122) — and transcript_turns (history.py:135-136) appends a whole persisted model_messages as one indivisible turn, so eviction granularity cannot split it.

Position is decisive, and the test picks the benign one

oversized turn is NEWEST (last)  -> 0 messages returned
oversized turn is in the MIDDLE  -> 2 messages returned

tests/unit/agents/test_model_history.py:43-47 (test_oversized_turn_is_not_split_or_silently_truncated) builds [_turn(0), oversized, _turn(2)]. Depth does not rescue it either — 1, 5, 20 and 50 prior turns all return 0 when the oversized turn is newest.

The size-independent variant

messages[:] = self._shrink_messages_for_overflow(messages) (agent.py:6169 streaming, :6327 non-streaming) is a slice assignment, so TurnMessages.recorded keeps the pre-shrink trace — deliberately; that is what its docstring at history.py:18 is for. The consequence is the problem: an overflow only fires when the prompt exceeds the full context (32,768 on NPU), so any turn reaching that recovery path is by construction far above the ~15.8K history budget. It is persisted at full size, and database.py:838 only NULLs model_messages on an explicit message delete. Every later turn in that session re-reads it, hits clear(), and gets []. One overflow poisons the session permanently, with no assumption about tool-result sizes at all.

The caveat that cuts the other way

A plain long assistant answer does not realistically trigger this — it needs ~100,000 chars (18,538 tokens) on NPU, and max_tokens = 8192 forbids it. Tool output is the only realistic driver. "Any long turn wipes history" would be an overstatement.

What main actually did

git show 06078dee:src/gaia/ui/_chat_helpers.py, lines 1635-1643 — _MAX_PAIRS = 5, _MAX_CHARS = 2000, and an unconditional loop with no budget term anywhere in the block. Pushed to 4,000,000 chars it still emits 2 messages, largest 2,015 chars. history.py does not exist on 06078dee at all, so the selector is wholly new here. The PR also widens the intake: main read get_recent_messages(session_id, limit=20), the PR reads get_context_messages(session_id) — a full-session SELECT ... ORDER BY created_at ASC with no LIMIT (database.py:805-812).

Eval — full compare output

==============================================================================
WARNING: judge mismatch — these scorecards are not directly comparable.
  baseline scored by: claude-sonnet-4-6
  current  scored by: claude-opus-5
Deltas below mix real behavior changes with the judge change. Regenerate
the baseline under the current judge (`gaia eval agent --save-baseline`)
before treating any of them as a regression.
==============================================================================

METRIC                           BASELINE    CURRENT      DELTA
--------------------------------------------------------------
Pass rate (all)                      100%       100%        +0%
Pass rate (judged)                   100%       100%        +0%
Avg score                             9.2        9.8       +0.6
Scenarios                               4          4

[~] SCORE CHANGED, STATUS SAME (4 scenario(s)):
    conversation_summary                     PASS  9.8 → 9.9 (+0.1)
    cross_turn_file_recall                   PASS  8.8 → 9.6 (+0.9)
    multi_doc_context                        PASS  9.2 → 9.8 (+0.6)
    pronoun_resolution                       PASS  9.2 → 9.8 (+0.7)

[OK]   No status changes between runs.

The tool rounds for display. JSON values: current 9.92 / 9.63 / 9.82 / 9.83, avg 9.8 (run_id eval-20260924-230332, 4 passed / 0 failed / 0 infra_error); baseline 9.8 / 8.78 / 9.25 / 9.17, avg 9.25 (run_id eval-20260424-221542, judged by claude-sonnet-4-6).

Run identity, since earlier attempts existed: four other runs that session were infra-error runs (eval-20260924-225620 0/4, eval-20260924-224310 2/4, eval-20260924-222522 0/4, eval-20260924-222830 0/4) and are explicitly not what is reported above.

Full driver script behind the sweep numbers

The mini_repro.py above is the finding in isolation. The sweep rows come from the same imports driven over N=1..4 and both device profiles, with the budget taken from the real history_budget() rather than assumed:

import json, sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent / "src"))

from gaia.agents.base.history import select_history, history_budget
from gaia.agents.base.turn_metrics import count_tokens
from gaia.llm.lemonade_client import (
    DEFAULT_MODEL_NAME, GPU_CTX_SIZE, NPU_CTX_SIZE,
    budget_for_ctx, resolve_ctx_size,
)

QUERY = "Compare the three reports you just read and tell me which one to act on."
PROMPT_CHARS = 28957   # turn_metrics.py:52 — the flagship's measured prompt size

class _Cfg:  max_tokens = 8192          # agent.py:1403
class _Chat: config = _Cfg(); llm_client = None
class _Agent:                            # attribute bag only — computes nothing
    def __init__(self, device, prompt):
        self.model_id, self.device = DEFAULT_MODEL_NAME, device
        self.system_prompt, self._openai_tools = prompt, []
        self.chat, self._use_claude = _Chat(), False

def sweep(device):
    ctx = resolve_ctx_size(DEFAULT_MODEL_NAME, device)
    _, target = budget_for_ctx(ctx)      # post-truncation size of one result
    budget = history_budget(_Agent(device, "…" * PROMPT_CHARS), QUERY)
    earlier = [[{"role": "user", "content": f"q{i}"},
                {"role": "assistant", "content": f"a{i}"}] for i in range(5)]
    for n in (1, 2, 3, 4):
        calls = [{"id": f"c{i}", "type": "function",
                  "function": {"name": "search_documents", "arguments": "{}"}}
                 for i in range(n)]
        newest = ([{"role": "user", "content": QUERY},
                   {"role": "assistant", "content": "", "tool_calls": calls}]
                  + [{"role": "tool", "tool_call_id": f"c{i}",
                      "name": "search_documents", "content": "x" * target}
                     for i in range(n)]
                  + [{"role": "assistant", "content": "done"}])
        cost = count_tokens(json.dumps(newest, ensure_ascii=False))
        kept = select_history(earlier + [newest], budget)
        print(f"{device} N={n}  newest={cost:>6}  budget={budget}  kept={len(kept)}")

sweep("npu"); sweep("gpu")

Substituting prose filler for "x" * target is what produces the prose rows; using 29999 / 59999 instead of target produces the untruncated rows.

A turn whose tool evidence is larger than the whole history budget wiped the
entire conversation instead of just itself. The eviction loop popped every
earlier turn chasing half the budget for a turn that could never get under it,
and the clear() that followed dropped the oversized turn left standing alone --
on a 32K-ctx NPU box, a turn carrying three ~20,000-char tool results left the
agent with zero replayed messages while five short earlier turns were sitting
there.

A turn that cannot fit alone is now skipped before any eviction runs, so the
budget is never spent evicting for a turn that can never be replayed. Replay
still stays contiguous: turns before a dropped one are released only once a
later turn is admitted, which is what keeps an oversized turn in the middle
from stitching a hole into the transcript. The warning now reports both
counts, so an empty replay is always accounted for.
Eviction works on whole turns today, so a tool call and its result can never be
separated -- but nothing held that line. Move eviction to per-message and the
replay window can open on a tool result whose call was evicted out behind it,
which models either reject outright or hallucinate around.

The neighbouring block-eviction test does not cover this. Its expectations
encode turn granularity, so the same refactor that introduces the bug also
breaks that test for an unrelated reason and gets it updated as expected churn;
rewrite it to match per-message output and this test is the only one still
failing.

Sweeps real budgets with the real tokenizer rather than pinning one. Under
per-message eviction only 38 of the 100 overflowing budgets in the swept range
land the cut between a call and its result, so a single pinned budget passes by
luck more often than not. A constant-cost mock would be worse still -- it makes
a partial turn cost the same as a full one, erasing the only dimension this can
go wrong in.
@itomek

itomek commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator

Pushed three commits to your branch — the conflict is cleared and the history-wipe regression is fixed. Revert any of it freely if you'd rather take a different line; the code is yours.

  • Merge with current main (e295c4cc). Only two files actually conflicted — a path-filter list and two independent one-line picks in agent.py. The parts that looked risky replayed your own earlier resolutions automatically.
  • The fix. When a turn's tool evidence is larger than the whole history budget, that turn is now skipped before eviction runs, instead of the eviction loop burning the budget chasing a target it can never reach and clear() finishing the job. A 6,000-case differential of new against old: 4,806 identical, 1,194 strictly better, 0 worse. Worst window is exactly 1.000 × budget, so nothing was traded for an overflow.
  • A guard test for the one promise in your description that nothing checked: eviction never separating a tool call from its result. Turn-granular eviction holds that line today, so the test is green on merge — its job is to break the day someone tries the per-message refactor, which is a reasonable thing to try since dropping a 110-token turn to reclaim 40 is wasteful.

Correcting myself: my earlier description of the cause was wrong. I said clear() dropped the oversized turn "along with every earlier turn that would have fit." It didn't — clear() only ever ran with one turn left. Your eviction loop had already popped the rest, chasing half a budget the oversized turn could never get under. The empty-history outcome was real; my account of how it got there wasn't, and the commit message says the right thing now.

And a second correction: I implied the hub stdio.py tests don't run in CI. They do — test_gaia_agent.yml names them explicitly and path-filters on src/gaia/**.

Two things that are yours to call, neither blocking:

  • The comment on the new contiguity branch promises slightly more than it delivers. It's true of stored turns, but the live query is appended straight after the replayed window — so when the newest turn is the dropped one, turn N-1 sits next to the live query with turn N invisible. That's the deliberate trade (the alternative is the wipe), just not what the wording says.
  • The contiguity release drops turns that would have fit, and the tool-call protocol doesn't force it — each turn is self-contained. It's a semantic choice, and it's yours: your own test_oversized_turn_is_not_split_or_silently_truncated pins it.
🔍 Technical details

Head is now d52ad3e2. Plain merge commit, no rebase, no force.

d52ad3e2  test(history): guard tool-call/result pairing through eviction
84c7250f  fix(agent): keep earlier turns when the newest one blows the budget
0a270a8b  Merge branch 'main' into codex/3628-persist-tool-history

The fix

src/gaia/agents/base/history.py. A turn whose cost exceeds the budget is skipped before any eviction; retained.clear() is gone. A hole flag keeps replay contiguous — turns before a dropped one are released only once a later turn is admitted, which is what preserves the behaviour your test_oversized_turn_is_not_split_or_silently_truncated already pins. Deleting that block makes it return ['question-0', 'question-2'] where it expects question-2, so it's load-bearing rather than belt-and-braces.

Worth noting: docs/sdk/sdks/agent-ui.mdx:189 already says "the newest turn is retained if it fits." Pre-fix that was false in exactly the failure case. Post-fix it's accurate, so this restores documented intent rather than introducing new policy.

The warning now reports evicted and unreplayable counts separately. Minor wart: turns released by the contiguity branch are counted as evicted, which renders as "excluded N older turn(s)" when the budget actually had room.

On the corrected cause

Instrumented the pre-fix body over 19,530 cost sequences (lengths 1–6 from {10, 40, 60, 101, 1000}, budget 100):

len(retained) when clear() fires: {1: 44922}

44,922 firings, length 1 every time. It also falls out of the guard: after the loop, used > budget >= budget // 2 == target, so while len(retained) > 1 and used > target can only have exited on the length condition. evicted += 1 was correct for what clear() actually did.

Same harness also settles a question I'd raised and got wrong — whether a mid-history oversized turn behaves differently now. It doesn't:

identical: 11844
differ, trailing turn oversized: 7686
differ, trailing turn NOT oversized: 0
cases where new retains less than old: 0

Verification

tests/unit/agents/test_model_history.py          15 passed
tests/unit/chat/ui                             1035 passed
tests/unit/test_context_size_resolution.py       29 passed
hub/agents/gaia/python/tests/test_stdio.py       77 collected, 77 passed
util/lint.py --black --isort                     OK

The guard test was re-proved non-vacuous in a copy of this tree: under a message-granular eviction mutation it fails naming the orphaned call id, and reverts clean. It sweeps range(200, 1200, 10) rather than pinning one budget — an earlier draft pinned 500 and passed the mutation, because ~42% of budgets orphan and 500 isn't one of them.

gaia eval agent --category context_retention on this tree: 4/4 PASS, avg 9.76, no status changes. Against the same tree without the fix (4/4, 9.80, same judge, so attributable) every scenario moved ≤0.11. That shows no regression — it does not show the fix works, since none of those four scenarios overflow the budget. The unit test is what covers that.

Merge audit

Every line you added between merge-base f136d1c8 and 4b1ced3a, checked against the merged tree. Two files surfaced: history.py (6 lines, the ones the fix replaces) and test_recent_chat_history.py (2 lines, adapted for main's rename of _dispatch_email_query → _dispatch_sidecar_query at _chat_helpers.py:1141). test_switching_to_email_preserves_prior_pairs and its assertion survive intact.

@github-actions

Copy link
Copy Markdown
Contributor

🟡 The gaia flagship agent loses conversation context on session eviction in the Agent UI.

The streaming path now builds history_pairs only for agent_type == "email"; for the gaia sidecar it's always []. The sidecar receives context=[], so the guard in server.py (if request.context and ...) skips the history repopulation. _restore_model_history is never reached either — the sidecar path does an early return at line 2184 before it. In normal runs the in-memory session registry keeps conversation_history alive, but on LRU eviction or process restart the session is reclaimed with an empty history and nothing repopulates it.

Previously the UI always pushed up to 5 truncated text pairs (one call to get_recent_messages); removing that for all non-email sidecars silently regresses the gaia sidecar's recovery path. The code comment "other agents restore traces below" is only true for in-process chat agents, not sidecar agents.

🔍 Technical details

src/gaia/ui/_chat_helpers.py:1909–1914 — the new guard:

history_pairs = (
    _build_history_pairs(db.get_context_messages(request.session_id))
    if (request.agent_type or session.get("agent_type")) == "email"
    else []
)

src/gaia/ui/_chat_helpers.py:2163–2184 — sidecar early-exit before _restore_model_history:

elif _should_relay_to_sidecar(agent_type, _agent_registry):
    _dispatch_sidecar_query(..., history_pairs, ...)  # history_pairs=[]
    return  # ← never reaches _restore_model_history at line 2302

hub/agents/gaia/python/gaia_agent/server.py:722 — push is skipped when context is empty:

if request.context and hasattr(agent, "conversation_history"):
    agent.conversation_history = [...]  # never runs with context=[]

hub/agents/gaia/python/gaia_agent/session_registry.py:93 — reclaimed_after_eviction is a user-visible warning, not a history restore; conversation_history stays empty.

Fix: extend the history_pairs guard to also cover agent_type == "gaia", or — better — wire the gaia sidecar's HTTP server to restore history from the UI database via _restore_model_history by passing the built turns as context on a reclaim event (reclaimed_after_eviction is already set on that path).

@itomek

itomek commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator

Real-world proof that the fix works, on hardware, through the real API — everything before this was synthetic.

Same machine, same model, same script, two arms differing by exactly one file (diff -rq reports history.py and nothing else). Turn 1 plants a token the model cannot guess; turn 2 pushes the turn past the history budget; turn 3 asks a question only turn 1 can answer.

Arm Turn-3 answer, verbatim Recalled
before, run 1 No project codename was given at the start of this conversation; there are no memories stored regarding one. no
before, run 2 No project codename has been shared with me yet. no
after, run 1 violet-otter-92 yes
after, run 2 violet-otter-92 yes

The logs show which branch actually ran, so this isn't inferred from the answers:

before   history.py:117   Context budget excluded 2 older turn(s); ...
after    history.py:126   Context budget excluded 0 older turn(s) and 1 turn(s) larger
                          than the whole history budget; ...

Before drops turn 1 along with the oversized turn. After drops only the oversized turn.

Memory is ruled out as an explanation: all four runs were private sessions, turn 1's remember returned "Memory is paused — this is a private session", turn 3's recall returned {"status":"empty","count":0,"results":[]}, and memory.db held zero rows. The passing arm answered correctly off an empty memory lookup, so only replayed history explains it.

One limitation, stated plainly: turn 2 was oversized by a large user paste, not by oversized tool evidence. Same branch, same trigger, and the log fingerprint proves the branch executed — but it isn't the literal scenario in the title. Driving tool evidence past the budget wasn't reachable here: one tool result caps at 40,000 chars, and the turns that would have needed several didn't persist tool messages. By the time control reaches the selector the only input is the turn's token cost, so the paths converge — but that's an argument, not a measurement, and worth saying so.

Separately, and possibly bigger than the bug this PR fixes: the history budget is computed with a cl100k estimator while the model is Gemma. On one measured prompt Gemma counted 78,736 tokens where the estimator said ~38K — roughly 2×. If that ratio is systematic, the budget is wrong for every Gemma user, and a turn can overflow a window the budget math believes has room. Filing separately; it predates this PR.

🔍 Technical details

Ryzen AI box, Gemma-4-E4B-it-GGUF, 64K context, so history_budget = ctx // 2 = 32,768 tokens.

Turn 2 persisted at 38,443–38,603 estimated tokens against that 32,768 budget — 17% over. Turn 1 was ~290–300 tokens, comfortably fitting, which is the whole point: it was discarded despite fitting.

Both arms are the PR head d52ad3e2 with one file swapped to its pre-fix version. Per-arm import verification confirmed gaia, gaia_agent_chat, gaia_agent and gaia.agents.base.history all resolve inside the intended tree, with has_unreplayable False in the before arm and True in the after arm.

Note on environment: PYTHONPATH alone is not sufficient in this repo — the two hub packages install as meta-path finders that outrank it, so a PYTHONPATH-only setup silently keeps serving another tree's hub agents. Editable installs per tree were used instead.

Turn 2 itself returned 500 (Context size has been exceeded) in two of the four runs — once in each arm, so it's environment noise rather than a behaviour difference. Those two runs pair like-for-like on their own: both failed turn 2, opposite turn-3 outcomes.

Artifacts: VERDICT.md, four transcript.json, four backend logs, proof-{before,after}.txt, tree-delta.txt, timings.txt, memory-control.txt, and every script that ran.

CI

42 passed, 14 skipped, 3 failed — none caused by this PR:

  • Test Lemonade Embeddings API — infrastructure. The runner's setup printed Server ready … Port: 13305, then the client dialled port 50908 and got WinError 10061. No test ran. The identical signature appeared the same hour on an unrelated branch (run 36077766689, client port 58491).
  • Test Agent SDK on Windows (Lemonade Integration) — same port-resolution fault, and it fails on main at 9e3a5752 (run 36075879921, port 57080).
  • Unit Tests (macOS smoke) — continue-on-error: true by design (test_unit.yml:253, "experimental … until the full suite is macOS-clean"), so the Unit Tests run itself concluded success; gh pr checks renders the soft job as fail. The single failure is test_cli_imports_every_starter_skill hitting a 60s pytest-timeout — it spawns 18 cold CLI subprocesses and took 42.4s of that 60s on the last green macOS run. Both Linux unit matrices are green, and all 36 test_model_history.py results passed on that same macOS runner.

@itomek itomek left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Conflict cleared, history-wipe regression fixed with a guard test, and verified end-to-end on hardware: the planted fact survives an over-budget turn after the fix and is lost before it, with the selector's own log line confirming which branch ran. Eval 4/4 with no status changes. The three red checks are infrastructure or a non-blocking soft job — details in the comments above.

@itomek
itomek added this pull request to the merge queue Sep 25, 2026
Merged via the queue into amd:main with commit 7a8fea5 Sep 25, 2026
56 of 59 checks passed
@itomek

itomek commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator

Post-merge addendum: the same A/B was repeated on a second Ryzen AI machine and reproduces cleanly. Turn 2 succeeded in all four runs there, so the arms are matched with no failed-turn confound — this run is tighter than the one posted above.

Arm Turn-3 answer, verbatim Recalled
before, s2 No codename has been shared yet. no
before, s3 No project codename has been saved or mentioned yet in our current session. no
after, s2 violet-otter-92 yes
after, s3 violet-otter-92 yes

Same log fingerprint as before: the pre-fix arm reports excluded 2 older turn(s), the fixed arm excluded 0 older turn(s) and 1 turn(s) larger than the whole history budget. Memory ruled out again — recall empty, memory.db zero rows in all four.

Two things this second run turned up that are worth having, neither a problem with this PR:

The first attempt didn't meet its own precondition, and is reported as-is. An 80,000-char paste persisted at only 21,048 tokens — under the 32,768 budget — so no eviction happened, no warning fired, and the pre-fix arm recalled correctly. That's the expected result when the turn fits; the payload was then sized to actually cross the budget, identically for both arms.

The budget on that machine is 32,768, not the 16,384 its device profile implies — filed as #4287. MODELS[Gemma-4-E4B].min_ctx_size overrides the device profile inside resolve_ctx_size, and the NPU ceiling is applied only on the load path, so the budget sizes itself against a context the box won't actually serve. Combined with #4285 that compounds.

🔍 Technical details

Turn 2 measured 38,425–39,240 estimated tokens against the 32,768 budget (+17–20%). Timings: turn 1 ~54 s, turn 2 198–250 s, turn 3 33–48 s.

On the first turn GAIA reloaded the pre-loaded model by itself: lemonade_manager.py:1234 — Auto-reloading … with ctx_size=65536 (was 32768), while lemonade_client.py:356 separately logs Requested context 65536 exceeds the NPU ceiling; using 32768. The two paths disagree, and only the load path knows about the device.

The limitation from the earlier comment is unchanged: turn 2 is oversized by user paste, not by tool evidence. One tool result caps at 40,000 chars and this agent persists no tool messages on the turns that would have needed several, so the literal tool-evidence scenario still hasn't been driven end-to-end. The branch and trigger are the same and the fingerprint confirms the branch ran.

Artifacts: VERDICT-SWIFT.md, four transcript.json, per-arm backend logs, swift-evidence.txt, proof-{before,after}.txt, tree-delta.txt.

kovtcharov pushed a commit to kovtcharov/gaia that referenced this pull request Sep 25, 2026
…amd#4370)

`main` has been red since 2026-09-25 18:29, so nothing can leave the
merge queue. Three separate regressions landed within minutes of each
other; this clears all three. The worst is a literal `SyntaxError` —
`ChatAgentConfig(...)` was passed `device=` twice, so the Agent UI
backend and everything importing it failed at module load, taking out
the Linux, Windows and macOS unit-test jobs. Nobody wrote that
duplicate: amd#3666 and amd#4275 each added the same kwarg a few lines apart,
neither diff conflicted textually, and the merge queue merged both
cleanly into a file that does not parse.

The other two are one-liners: amd#3402 re-imported `tool_cancelled` over a
name the module already imports (failing the pylint gate) and shipped
`wait_for_condition` with no UI label, and amd#4271 landed an over-long
assertion (failing the black gate).

**Worth knowing:** the ~13 "new pylint errors" that appear in the
failing job's log are not pylint errors. They are the first 20 lines of
the **non-blocking MyPy** output (1224 warnings, truncated for display)
and have never gated anything. Only one pylint hit was real. No
dependency or tool-version drift was involved — pylint 4.0.9 and black
26.5.1 both predate the last green run.

## Test plan

- [ ] `python util/lint.py --black` — clean (1180 files unchanged)
- [ ] `uvx pylint src/gaia --rcfile .pylintrc --disable
C0103,C0301,W0246,W0221,E1102,R0401,E0401,W0718,W0212` — clean on Linux
- [ ] `python -m compileall -q src/gaia tests` — no syntax errors
- [ ] `python -m pytest tests/unit/test_schedule_daemon.py -q` — 28
passed
- [ ] `python -m pytest tests/unit/chat/ui -q` — 1040 passed (was 17
collection errors)

<details>
<summary>🔍 Technical details</summary>

**`src/gaia/ui/agent_loop.py`** — the two `device=session.get("device")`
lines were textually identical, so deleting the later one restores
exactly the intended call. `git blame` attributes line 461 to
`1caad2ade5` (amd#4275) and line 465 to `7a8fea58b1` (amd#3666); amd#3666 is an
ancestor of the last green commit `69f76ab57`, so amd#4275 is the one that
created the duplicate.

**`src/gaia/agents/tools/shell_tools.py`** —
`gaia.agents.base.tools.tool_cancelled` is a pure re-export of
`gaia.tool_cancellation.tool_cancelled`, which the module already
imports at line 31. Verified the bindings are the same object, so
dropping the function-local import is a no-op rather than a behaviour
change.

**Follow-up worth a maintainer's eye, deliberately not bundled here:**
`wait_for_condition` executes arbitrary commands against the same
allowlist as `run_shell_command`, but unlike `run_shell_command` it is
not in `_GAIA_MUTATING_TOOLS`. By that set's own stated criterion ("or
execute code") it looks like it belongs there, and omitting it means the
tool skips the confirmation gating its sibling gets. That is a behaviour
change, not a CI fix, so it should be reviewed on its own rather than
smuggled into an unblock PR.

**Also noted:** `.pylintrc` uses `disable = all` plus an explicit
`enable` list that does not include `syntax-error`, which is why the
pylint gate walked past a file it could not parse. Enabling `E0001`
would have caught this at PR time.
</details>
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 chat Chat SDK changes cli CLI changes devops DevOps/infrastructure changes documentation Documentation changes llm LLM backend changes performance Performance-critical changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(agent): the agent forgets every tool result between turns — cross-turn context caps at ~5K tokens

3 participants