Repository navigation
fix(memory): extract memories after the answer, not before it - #4034
kovtcharov wants to merge 3 commits into
Conversation
Every turn paid 7-17s for a memory-extraction model call that ran after the answer was already on screen but before process_query returned — 169s of a 437s 14-task run, 39% of wall time. In 12 of those 14 turns the call stored nothing at all, so the wait bought the user nothing. Extraction now runs on a background thread, one job at a time per agent, with up to four turns queued behind a running one (oldest dropped, logged). Each job freezes the turn's text and context at turn end rather than reading them back off the agent later. The timeout was dead code: a ThreadPoolExecutor context manager calls shutdown(wait=True) on the way out, so returning [] at the deadline still blocked until the model answered. The call now runs on a daemon thread that nothing joins, so abandoning it is real — an executor would also re-join it at interpreter exit. Two causes for the empty results: the 8s deadline was under the 7-17s the call actually took, so most results were discarded on arrival; and a reasoning model bills its hidden chain-of-thought against max_tokens, so a 1024-token budget was spent thinking and the provider handed back prose instead of JSON. Nobody waits on this call now, so both budgets are sized for the work: 60s, 4096 tokens. An invalid-JSON warning now prints the response length and opening characters so the two failures are told apart. Callers that exit right after a turn would lose the memory, so they drain first: the one-shot `gaia chat -q` path, the flagship sidecar's close_agent(), and the eval harnesses. The Agent UI and TUI need no change — their turn-done signal follows process_query, which no longer waits. FAISS knowledge-index mutation and search are now serialized, since the background worker adds vectors while a turn may be searching.
Request changesMoving memory extraction off the answer path is the right call and the root-cause analysis behind it is genuinely good — the old Quitting an interactive chat now silently throws away the last turn's facts. Today extraction finishes before the turn returns, so "my name is Priya" is on disk by the time you see the reply. After this change it finishes seconds later — and the interactive Background extraction now talks to the model through the same chat object the live turn uses. Ask a follow-up while the previous turn's extraction is still running and two requests hit the single-slot local server at once. Answers stay correct, but per-turn timing and token numbers get scrambled when turn recording is on, and the seconds this PR removes from turn N can reappear as queueing on turn N+1. Worth measuring back-to-back turns before claiming the win, and worth one test that overlaps an extraction with a live turn. Also: the SDK memory doc still describes extraction as synchronous with a 3s timeout and doesn't mention the new wait helper. The spec and user guide were updated; that page describes the same behaviour and needs the same edit. Real-world evidenceNo evidence bundle was produced for this PR, and the PR's own test plan leaves both runtime boxes unchecked — the 🔍 Technical detailsIssues🔴 Interactive chat exit drops the last turn's extraction, silently (
Draining in ( 🟡 The extraction worker shares
Scoping extraction to its own SDK/client instance would remove all three. At minimum, a test that starts a turn while an extraction is in flight would pin the intended behaviour — every new test currently drives 🟡 Line 387: "Timeout (3s) → logged warning, skip." Line 452 describes Nits🟢
🟢 The docstring says callers are off the critical path, and the PR says every call site is outside the lock — but line 221 runs inside 🟢 Serial drains add up on bulk teardown (
🟢 Per-turn INFO line when auto-extraction is off (
Strengths
|
|
Merged current 🔍 Technical detailsMerge commit Tests: |
Quitting an interactive chat threw away the last turn's memories. Extraction now finishes after the answer, so the final turn's model call is still in flight when the session ends — and the drain was wired only into the one-shot `-q` branch. The interactive, Ctrl-C and error exits returned through a cleanup block that stopped the file watcher and nothing else, so the facts died with the process and the "not stored" warning never fired because it was never called. The drain moved into that cleanup block in both CLI chat entry points and in the hub chat app, which covers all four exits in one place. New tests drive the real entry point and assert the drain runs on a normal return, on Ctrl-C, and on an error; they fail if the drain is removed. Also from review: - `raw_text` could be unbound in the JSON-decode handler. requests' JSONDecodeError subclasses the stdlib one, so a truncated response body reaches the handler before the assignment, and `len(raw_text)` raised UnboundLocalError inside the error path. Bound before the call. - `close_agent` ran inside the session registry's lock on the create-race branch, which made it a path that could hold the lock for the whole 15s drain. The close now happens after the critical section; one lock block still decides the winner. - The auto-extraction-off skip logged at INFO on every turn for anyone who turned it off. DEBUG. - `docs/sdk/sdks/memory.mdx` still described extraction as synchronous with a 3s timeout and a 20-word floor, and never mentioned the new wait helpers. It now documents the background model, the five constants, and how to drain before exiting. Merge resolutions: both sides added imports to `flagship_tasks.py` and appended independent tests to `test_memory_mixin.py`; kept both in each.
|
Fixed the blocking finding and three of the nits. The shared- Quitting an interactive chat no longer throws away the last turn's memories. The review was right that this was the one that mattered: the drain was wired only into the one-shot The tests drive the real entry point, not a mock of it. They fail if the drain is removed — I checked by removing it. Ctrl-C has its own case, since an interrupt is exactly when an unfinished extraction is likeliest. 🟡 Still open, and it is yours to decide: extraction shares the live turn's 🔍 Technical details1. The drain ( Removed the inline call beside the one-shot return and put it in each
2. 3. 4. Per-turn INFO line — now DEBUG. A setting the user chose is not news on every turn; the word-floor skip below it stays at INFO. 5. 6. Not done — the shared SDK. Of the review's three symptoms, a separate SDK instance fixes the first two (the single Merge resolutions. Validation. Still unchecked, unchanged from the original review: |
|
Holding this one. The memory change itself looks right, but the per-message token and latency numbers GAIA reports go wrong as soon as extraction runs alongside a turn — and those numbers surface in the Agent UI, On the memory behaviour I have no concerns: in a flagship run of This is the shared- 🔍 Technical detailsMechanism. Measurement. One box, one Lemonade backend, flagship
n=1 per side — the score difference is noise, the telemetry difference is not. Slot contention shows in the backend log, and is the second-order effect worth a decision too: turn 3's request logs Everything else checked out. Five merge conflicts resolved against current main (the notable one: the extraction job must freeze Separately, and not caused by this PR: the |
|
Folded into #4406, which combines this with the other three memory PRs so they can be tested as one change. This one is fully contained there — GitHub refuses to repoint the base at the combined branch precisely because there are no commits left between them. Closing this once #4406 merges; nothing here is dropped. 🔍 Why it was combined rather than merged on its ownAll four memory PRs edit the same |
Combining #4034's background extraction with main's grounding tests crashed the interpreter, not just the four tests: MemoryStore.close() took no lock, so teardown freed the sqlite3 connection while the extraction thread was mid statement. A segfault aborts the whole pytest process, so this took the Linux unit job down with it. The same race exists at runtime. drain_memory_extraction returns False after 15s and every caller closes anyway, so a slow backend on a busy box means close_agent closes the store under a live thread. close() now holds the connection lock and is idempotent, and every DB method goes through a _locked() guard that raises MemoryStoreClosedError rather than running on a freed connection. The old close() also swallowed every exception, which the no-silent-fallbacks rule forbids. The grounding tests' harness now drains before asserting, matching what the real CLI paths already do.
Three of the four consolidated PRs were merged to main directly while this branch was under test, so most conflicts here are the same work arriving twice. Took main's arrangement of the lesson constants and the session-lessons block, and kept this branch's two things main does not have: #4034's background extraction, and the lesson-scope fixes the hardware run found.
…n their workspace (amd#4406) Memory extraction used to run *before* the answer reached the screen, so every turn that stated a fact paid the model call twice over — once for the answer, once to decide what to remember. This moves extraction to a background worker: the answer lands, the turn returns, and the extraction follows. On a Ryzen AI machine that was measured at 19 seconds of the user's time given back on a single turn. It also carries four fixes found while testing this against the memory work that landed on main (amd#4061, amd#4062, amd#4066) — two of which only exist *because* those changes now run together. Closes amd#4034. The other three memory PRs merged to main directly; this branch has been merged with main and carries only what main lacks. ### What's fixed here that isn't on main - **A closed memory store could segfault the process.** `MemoryStore.close()` took no lock, so agent teardown freed the SQLite connection while the extraction thread was mid-statement. A segfault aborts the whole process, so this would have taken the Linux unit job down rather than failing four tests. `close()` now holds the connection lock and every DB method refuses a call that lost the race. - **A workspace lesson could reach another project.** amd#4066 scopes lessons to one workspace and frames them against injection because their content is raw tool output; amd#4061's per-turn recall reads every context in a default `global` session. A lesson from project A could surface in project B, unframed. **This one is live on main today.** - **The same leak, one call further in.** The background extraction job builds its "existing memory" list from the same unfiltered scope, so another workspace's lessons reached that prompt too. Observed on hardware, then fixed. - **An ordinary fact could be silenced forever.** The lesson filter keyed on `domain`, which the *extraction model* picks — so a turn that merely mentioned a lesson got its ordinary facts tagged `domain='lesson'` and suppressed from recall permanently. It now keys on `source`, which only the write path sets. ### Test plan - [x] `pytest tests/unit/test_memory_mixin.py tests/unit/test_memory_turn_recall.py tests/unit/test_memory_heal_lessons.py tests/unit/test_memory_context_visibility.py tests/unit/test_cli_memory_drain_on_exit.py tests/unit/test_memory_extraction_grounding.py` — **389 passed** - [x] `pytest tests/unit/` — 17,198 passed, 33 failed, **all 33 reproduce identically on main** (verified in a separate main worktree, not via `PYTHONPATH`, which cannot baseline in this repo) - [x] Real-world run on AMD Ryzen AI MAX+ 395 (Radeon 8060S, Vulkan, all three models on GPU) - [ ] `gaia eval agent` — not run; see note below ### Evidence Every fix has a test verified to fail without it — each was disabled in turn and the test watched go red. **Extraction is off the answer path.** Answer rendered at `13:20:15`; extraction finished at `13:20:34`. 19 seconds returned to the user on one turn. ``` 13:20:15 PERF process_query session=a1997a20 took=5.084s 13:20:15 [MemoryMixin] extraction started (context=global, waited 0.0s) 13:20:34 [MemoryMixin] extraction finished in 19.0s ``` **A lesson does not leave its workspace.** A real `tool_lesson` row in workspace A, then a turn from workspace B — absent from both the user-visible chat prompt and the extraction job's internal prompt. Before the fix it appeared in the latter; after, the "existing memory" list carries nine items and the lesson's id is not among them. **A fact the model mislabelled still surfaces.** A row with `domain=lesson` but `source=llm_extract` now reaches the turn: ``` Stored memories that may bear on this message: - [note] Tool call list_files on /tmp/gaia-scratch-… reported 0 total files. (learned 2026-09-28) ``` <details> <summary>🔍 Full evidence table and method</summary> Driven through the Agent UI in a real browser on `t-nx-strx-halo`, against a Lemonade already serving Gemma-4-E4B. Proof for prompt-content claims is the literal prompt sent to the model (llama-server `--log-prompts-dir`), not the answer text — an answer can be right for the wrong reason, and absence claims cannot be proven from an answer at all. | Claim | Verdict | Artifact | |---|---|---| | Answer renders before extraction finishes | CONFIRMED | `backend.log` timestamps above | | A memory outside the stable prompt still surfaces per-turn, with its age | CONFIRMED | One prompt dump showing both halves: the stable `Known facts` list (5 highest-confidence decoys) and the dynamic `Stored memories that may bear on this message:` block carrying the target fact | | A memory under a non-global context label is visible | CONFIRMED | Dashboard row with `CONTEXT=work-project` | | A same-operation fail→fix in one turn is stored as a workspace-scoped lesson | CONFIRMED | `knowledge` row, `domain=lesson`, `source=tool_lesson`, `context=workspace:/…` | | That lesson is absent from another workspace's chat prompt AND extraction prompt | CONFIRMED | Both prompt dumps, zero hits; extraction half required this branch's fix | Two findings worth knowing, neither a defect in this PR: - **Per-turn recall is invisible on a small store.** The stable prompt records every memory it renders and recall skips exactly those, so with only a handful of memories recall correctly has nothing left to surface. Proving it needs enough memories to overflow the 4000-char stable cap. This cost two test rounds before the mechanism was understood. - **Nothing in the product sets a non-global memory context except the email sidecar.** `set_memory_context()` has no callers, and `remember()`'s docstring advertises a `context` parameter its signature lacks. Two unrelated bugs found along the way are filed separately as amd#4409 and amd#4410. **On the eval:** this branch changes no prompt wording, no tool schema, and no tool registration — it adds none. The dynamic-context sections it touches came from amd#4061/amd#4066, which are already on main. A scorecard run would measure main's behaviour, not this diff, and there is no committed flagship baseline to compare against. </details> --------- Co-authored-by: Kalin Ovtcharov <[email protected]> Co-authored-by: Kalin Ovtcharov <[email protected]> Co-authored-by: Ovtcharov <[email protected]> Co-authored-by: Kalin Ovtcharov <[email protected]>
|
Merged via #4406 (commit #4406 consolidated the memory work so it could be tested as one change. The other three (#4061, #4062, #4066) merged to main directly, so this one's background-extraction change was all that remained, and it went in with them. 🔍 What changed on the way inThree things had to be resolved that neither this PR nor main could see alone:
Verified on a Ryzen AI machine: the answer rendered at 13:20:15 and extraction finished at 13:20:34 — 19 seconds of the user's time given back on one turn. |
Every chat turn made the user wait for a memory-extraction model call that ran after the answer was already on screen — 7-17s per turn, 169s of a 437s 14-task run (39% of wall time), and in 12 of those 14 turns it stored nothing at all. The Agent UI and TUI held the turn open for it too. Extraction now runs in the background, so the turn ends when the answer does, and the calls that used to be thrown away land instead.
Test plan
python -m pytest tests/unit/test_memory_mixin.py -q— 317 pass, including 15 new tests asserting elapsed time, not just return valuespython -m pytest tests/integration/test_memory_eval.py hub/agents/gaia/python/tests/test_session_registry.py -qtests/unitrun: only the failures already red onmainfor this machineblack/isort/flake8on every changed filegaia chat -q "My name is X and I work on Y"thengaia memory— the fact is stored, and the command does not hanggaia eval agent --category context_retentionshows no regression against the committed baseline🔍 Technical details
The timeout never bounded anything.
_extract_via_llmran the call in awith ThreadPoolExecutor(...)block and returned[]onfuture.result(timeout=...)— but leaving the block callsshutdown(wait=True), so it blocked until the model answered anyway. The call now runs on a daemon thread that nothing joins; an executor would also re-join it at interpreter exit, which would un-abandon it.Why 12 of 14 stored nothing. Two causes, both now addressed:
max_tokens, so the 1024-token budget went on thinking; withcontentempty the Lemonade provider falls back toreasoning_content, and the extractor got prose where it wanted JSON. No model-name matching was added — the budget is simply sized for the work now that nobody waits on it (60s, 4096 tokens). The invalid-JSON warning now prints the response length and opening characters so "spent it thinking" and "emits bad JSON" are told apart in a log.Overlapping turns. One extraction thread per agent; up to 4 turns queue behind a running job, oldest dropped with a log line. A bounded FIFO rather than "keep only the newest" because back-to-back turns are exactly the benchmark shape, and the queue is only reachable when a turn finishes inside ~15s of the previous one. Each job freezes the turn's text and context at turn end instead of reading them back off the agent later.
Shutdown. Anything that exits right after a turn drains first via
drain_memory_extraction(agent)— the one-shotgaia chat -qpath, the flagship sidecar'sclose_agent(), and both eval harnesses. It waits 15s and then says out loud that the turn's facts were dropped. Everyclose_agent()call site already runs outside the session registry's lock, so this adds no lock-holding. The Agent UI and TUI needed no change:signal_done()followsprocess_query, which no longer waits.FAISS. Knowledge-index add/remove/rebuild and search are now serialized behind a reentrant lock — the background worker adds vectors while a turn may be searching, which was not previously possible.