Skip to content

perf(chat): name indexed documents per turn, not in the system prompt - #4571

Closed
kovtcharov wants to merge 3 commits into
amd:mainfrom
kovtcharov:kalin/indexed-docs-per-turn
Closed

kovtcharov wants to merge 3 commits into
amd:mainfrom
kovtcharov:kalin/indexed-docs-per-turn

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

A new user's first document questions took minutes: "summarize the Fed rate decision file in my Documents" took 249 s and "what does the MIT license let me do?" 129 s, on local Gemma-4-E4B. Most of that was the model re-reading its entire ~19K-token instructions, because indexing a document rewrote the system prompt near its top. The list of indexed documents now travels with each turn ([Indexed documents: …], the same way memory already sends per-turn context), so the prompt never changes mid-conversation and stays cached: the same two questions now take 100 s and 98 s.

new-user session, Radeon 8060S, Gemma-4-E4B before after
Fed summary (find → index → query) 249 s 100 s
MIT license question 129 s 98 s
full-prompt re-reads after indexing 68 s + 57 s none (largest request 2,162 tokens)
one-time warm-up prompt 17,111 tokens 18,076 tokens

Needs reviewer sign-off: the RAG answering rules are now always present for profiles with document tools (+~965 tokens, read once at warm-up and then cached). They were held back until the first index to keep the prompt short for #1030, but that gate is itself a mid-session prompt change — keeping it would still cost one ~60 s full re-read on the first document of every session. test_tier2_rag_rules_absent_without_indexed_docs is rewritten to pin the new contract.

Draft until the rag_quality eval runs — this changes the system prompt, and the walkthrough box can't run an eval while it holds the Lemonade slot.

Test plan

  • pytest tests/unit/test_indexed_docs_per_turn.py — prompt is byte-identical with 0, 1 and 2 documents indexed; the turn names them; profiles without document tools never do (fails on main)
  • tests/test_chat_agent.py::test_indexed_document_reaches_the_next_turn replaces the old "system prompt lists the document" assertion
  • gaia eval agent --category rag_quality on this branch and on main, same machine
  • Note: tests/unit/test_profilespec_characterization.py goldens are already stale on main (they predate main's "Audio and video…" prompt line), so they are not updated here — re-capturing them needs the sign-off their docstring asks for
🔍 Technical details

indexed_docs_section was the first block after base_prompt in the full and doc profiles, and index_document / query_specific_file's auto-index call rebuild_system_prompt(). With the block now static, those rebuilds produce the same prompt. ChatAgent.get_memory_dynamic_context() appends the line, so MemoryMixin.process_query prepends it while still storing the user's clean text (ChatAgent precedes MemoryMixin in the MRO, so a process_query override would have leaked the prefix into memory).

@github-actions github-actions Bot added the tests Test changes label Oct 2, 2026
@kovtcharov

Copy link
Copy Markdown
Contributor Author

gaia_rag eval, same machine, back to back: a build with this PR (plus the other open walkthrough fixes) passed 8/8, average 9.6/10; main passed 7/8, average 9.1/10. No regression; the one main failure is rag_csv_via_retrieval (7.2).

🔍 Technical details

Local Gemma-4-E4B on Radeon 8060S, sandboxed fresh install with its own embedded Lemonade; two Agent UI servers (integration build on :4301, origin/main 842d014 on :4302) run serially, judge claude-opus-5. One run per scenario per build, so single-scenario deltas are within noise.

scenario this build main
rag_buried_fact_large_doc 9.6 9.8
rag_cross_doc_synthesis 9.7 9.4
rag_cross_turn_retention 9.2 8.8
rag_csv_via_retrieval 9.2 7.2 FAIL
rag_dont_know_absent_fact 9.8 9.7
rag_factual_report 9.8 9.8
rag_hallucination_pressure 9.7 9.8
rag_handbook_policy 9.8 9.8

The integration build was faster on 7 of 8 scenarios. It ran before the last wording tweak to the indexed-documents rule ("the latest message's line"), which is not reflected here.

@kovtcharov
kovtcharov force-pushed the kalin/indexed-docs-per-turn branch 3 times, most recently from 15a5946 to bad5554 Compare October 4, 2026 21:04
Indexing a document rebuilt the system prompt, and the list sat right
after the base prompt, so the next request re-read the whole ~19K-token
prompt: 68 s and 57 s of prompt processing on the two document questions
of a new user's first session (Gemma-4-E4B, Radeon 8060S). The rules for
indexed documents are now fixed text, and the current set is sent with
each turn as [Indexed documents: ...], the way memory's dynamic context
already is.
The RAG answering rules were held back until the first index to keep the
prompt short (amd#1030); that gate is what re-read the whole prompt mid-turn.
They are now read once at warm-up.
With memory on, the per-turn line follows the time context rather than
leading the message, and replayed turns carry older lines.
@kovtcharov
kovtcharov force-pushed the kalin/indexed-docs-per-turn branch from bad5554 to 32fa5b9 Compare October 4, 2026 22:09
kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Oct 5, 2026
…md#4698)

On a local model, a turn could stall for minutes while the server
re-read the whole conversation from the first token: 34,100 tokens (155
s) and 39,531 tokens (240 s) in the v0.25 RC TUI session on Gemma-4-E4B.
llama.cpp reuses only the prefix two requests share. On Gemma 4 and
Qwen3.6, any change to the system prompt or tool list throws away
everything after it. GAIA still rewrote the system prompt mid-session
for things that change every turn. This PR moves that content into the
turn, so each request extends the one before it.

**Stacked on amd#4571. Merge that first.** It fixes the cause behind both
RC stalls: indexing a document rewrote the system prompt, and the next
step re-read everything. This branch includes its commits until then.
Even with amd#4571, three causes still rewrite the prompt:

- **Learned procedures** recalled for the current goal were written into
the system prompt, so it was rebuilt every time the match changed. They
now ride in the turn's `[GAIA Memory Context]`, next to recalled
memories.
- **The "stable" memory section** was re-read from the store on every
recompose. A fact extracted after the last turn, an auto-stored tool
error, or a confidence bump therefore changed the prompt. That includes
the rebuild `index_document` still triggers under amd#4571, so amd#4571 alone
breaks again once memory extraction runs. The section is now rendered
once per session, which is what the memory docs already promised. A
`forget` or `update_memory` of an item it shows still takes effect
immediately.
- **The skill filter** recomposed the prompt whenever the always-on
`gaia-voice` skill flipped in the selection, even though its body
renders either way. Each needless recompose is what carried the memory
drift in.

Per-turn tool selection, the remaining cause, is amd#4554 (already in the
RC). The new test pins `dynamic_tools=False`.

## Test plan
- [x] `pytest
hub/agents/gaia/python/tests/test_prompt_prefix_stability.py`: builds
the real flagship with the model call captured and runs four turns
through the stdio history path. The turns cover a tool call,
`index_document`, a recalled procedure, a fact stored between turns, and
the RAG guard's re-ask. Each of the 7 requests extends the one before.
**Fails on main and on amd#4571 alone** at the first new turn.
- [x] `pytest tests/unit/test_memory_mixin.py` (331 passed, including
new frozen-section tests: mid-session writes stay out, forgetting a
shown memory removes it at once, forgetting an unshown one costs no
recompose).
- [x] `pytest tests/unit/test_agent_lazy_skill_prompt.py
tests/unit/test_indexed_docs_per_turn.py tests/test_chat_agent.py` plus
the other skill, memory and prompt-composition suites all pass.
- [x] `pytest hub/agents/gaia/python/tests`: 604 passed. The 3 failures
also fail on main (optional browser extra not installed).
- [ ] **`gaia eval agent`** on `gaia_memory`, `memory`, `gaia_rag`,
`context_retention`, on this branch and on main, same machine. This
changes prompt assembly, so CLAUDE.md requires it.
- [ ] Re-run the RC TUI walkthrough and check `lemond.log`. No step
after an `index_document` should start from `progress = 0.0x`, and new
turns should re-read only the new turn.

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

**How each cause was found.** A scratch harness captured every outgoing
`messages` + `tools` payload from the real `GaiaAgent`. It rendered each
payload the way the chat template lays it out (system, tools, then
turns) and reported the first diverging byte between consecutive
requests:

| cause | first diverging content |
|---|---|
| indexed docs (amd#4571) | `**CURRENTLY INDEXED DOCUMENTS:**\nNo documents
are currently indexed.` → `You have 1 document(s) already indexed…`, at
the step after `index_document` |
| recalled procedures | `==== LOADED SKILLS (active this turn) ====` →
`=== RECALLED PROCEDURES (learned from past successful runs) ===`, on
every turn whose match changed |
| memory drift | `No memories stored yet.` → `Known facts:\n - Sam works
on the safety team (confidence: 0.50…)`, then `0.50` → `0.52` the turn
after |
| no-op skill recompose | `_refresh_active_skill_filter` going `[]` →
`['gaia-voice']` → `[]`, recomposing on each flip (the trigger for the
drift above) |
| dynamic tools (amd#4554) | tools payload: `-[clear_code_index,
get_index_status, …] +[bookmark, find_files, …]` on every new turn |

**Why ordering didn't help.** `VOLATILE_PROMPT_FRAGMENTS` puts changing
fragments last in the system text. The template renders the tool
declarations after the system text, though, so a change there still
invalidates ~10K tokens of tools plus all history. And Gemma 4
(sliding-window) and Qwen3.6 (hybrid) can resume only from a llama.cpp
checkpoint, which sits near the end of an earlier prompt, never at that
boundary. In the RC log that shows up as 0% reuse.

**Not changed here, for follow-up:**
- Qwen3.6 thinking: the chat template drops `reasoning_content` from
messages before the last user turn, so each new turn re-reads the
previous turn's tool steps. The RC log shows 4–7K tokens per turn.
Fixing it needs `preserve_thinking` plus re-sending reasoning, which is
a design call. Gemma isn't run with thinking on, so it isn't affected.
- `extract_document_items` / `save_extracted_items` join the tool list
only on "extract every X" turns.
- User-loaded skill bodies still toggle in the system prompt (the amd#2848
size trade-off).
- The project map's index-status line still changes, but only when
something else recomposes.

Also: three pre-existing `except …: pass` handlers in the touched files
now log instead of swallowing.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Closing as superseded: #4698 was stacked on this branch and its squash merge brought every change here into main, so the branch has no diff left against main.

@kovtcharov kovtcharov closed this Oct 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant