Skip to content

fix(memory): extract memories after the answer, not before it - #4034

Closed
kovtcharov wants to merge 3 commits into
amd:mainfrom
kovtcharov:claude/memory-extraction-off-the-answer-path
Closed

kovtcharov wants to merge 3 commits into
amd:mainfrom
kovtcharov:claude/memory-extraction-off-the-answer-path

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

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 values
  • python -m pytest tests/integration/test_memory_eval.py hub/agents/gaia/python/tests/test_session_registry.py -q
  • Full tests/unit run: only the failures already red on main for this machine
  • black / isort / flake8 on every changed file
  • gaia chat -q "My name is X and I work on Y" then gaia memory — the fact is stored, and the command does not hang
  • gaia eval agent --category context_retention shows no regression against the committed baseline
🔍 Technical details

The timeout never bounded anything. _extract_via_llm ran the call in a with ThreadPoolExecutor(...) block and returned [] on future.result(timeout=...) — but leaving the block calls shutdown(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:

  • The 8s deadline sat under the 7-17s the call actually took, so most results were discarded the moment they arrived.
  • A reasoning model bills its hidden chain-of-thought against max_tokens, so the 1024-token budget went on thinking; with content empty the Lemonade provider falls back to reasoning_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-shot gaia chat -q path, the flagship sidecar's close_agent(), and both eval harnesses. It waits 15s and then says out loud that the turn's facts were dropped. Every close_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() follows process_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.

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.
@github-actions github-actions Bot added documentation Documentation changes cli CLI changes eval Evaluation framework changes tests Test changes performance Performance-critical changes agents labels Sep 20, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Request changes

Moving memory extraction off the answer path is the right call and the root-cause analysis behind it is genuinely good — the old ThreadPoolExecutor block re-joined the worker on exit, so the "timeout" never bounded anything, and the token budget went on hidden reasoning instead of JSON. Two things should be sorted before this merges.

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 gaia chat exit path never waits for it, nor warns. The one-shot -q path got the wait; the interactive path (the one people actually use) didn't. Putting the drain in the cleanup block instead of inline covers the one-shot, interactive, Ctrl-C and error exits in one place.

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 evidence

No evidence bundle was produced for this PR, and the PR's own test plan leaves both runtime boxes unchecked — the gaia chat -q → gaia memory check and the context_retention eval comparison. Those are exactly the two surfaces this change moves: a CLI exit path that now has to wait for a background thread, and memory recall quality once extraction lands late. Unit tests here are strong but they gate the threading logic, not the surface. The verdict above rests on static review alone for both; please attach the real CLI output and the eval-vs-baseline diff (unchecked boxes on a performance claim of this size are the gap, not the thread tests).

🔍 Technical details

Issues

🔴 Interactive chat exit drops the last turn's extraction, silently (src/gaia/cli.py:753, src/gaia/cli.py:957, hub/agents/chat/python/gaia_agent_chat/app.py:1070)

drain_memory_extraction was added to the single-query branch only. interactive_mode(agent) returns and the process exits through the finally block, which calls stop_watching() and nothing else — an in-flight extraction (7–17s by the PR's own numbers) dies with the process and drain_memory_extraction's "not stored" warning never fires because it is never called. Pre-PR this could not happen: _extract_via_llm's executor re-joined the worker, so the turn didn't return until extraction had.

Draining in finally subsumes the inline one-shot call and also covers KeyboardInterrupt:

        finally:
            # Cleanup
            try:
                if "agent" in locals():
                    from gaia.agents.base.memory import drain_memory_extraction

                    drain_memory_extraction(agent)
                    agent.stop_watching()
            except Exception:  # pylint: disable=broad-except
                pass

(src/gaia/cli.py:763-770. Apply the same shape at app.py:1079-1085, and add a drain after interactive_mode(agent) at cli.py:957, which has no finally at all.)

🟡 The extraction worker shares self.chat with the live turn (src/gaia/agents/base/memory.py:1607)

self.chat is the agent's own AgentSDK (agent.py:1173, used for every turn at agent.py:5792/5970/6262/6304). send_messages mutates instance-scoped state that assumes one caller:

  • _recorder_begin/_recorder_end (chat/sdk.py:403-412) drive a single _open_call slot and a single _prev_rendered (turn_metrics.py:193-204). An extraction call landing mid-turn replaces the user turn's open record — and _recorder_end is a no-op once closed, so the real call goes unrecorded — then poisons the next call's cache_hit_ratio by overwriting the prefix baseline. Gated behind turn_log_path() so it's off by default, but that is precisely the mode used when investigating latency.
  • llm_client.get_last_usage() (chat/sdk.py:420, providers/lemonade.py:538) is a last-write-wins attribute, so a turn can report the extraction's token counts — the accounting fix(llm): count a local call's tokens from its own usage, not /stats #4005 just fixed.
  • Lemonade serves one slot per model, so the extraction and the next turn's generation queue against each other. The 7–17s isn't removed from a back-to-back session, it's relocated.

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 _after_process_query with no concurrent turn.

🟡 docs/sdk/sdks/memory.mdx still documents the old behaviour (docs/sdk/sdks/memory.mdx:387, :452)

Line 387: "Timeout (3s) → logged warning, skip." Line 452 describes _after_process_query as running extraction inline, and the ≥20-word floor (MIN_EXTRACTION_WORDS is 5). wait_for_memory_extraction / drain_memory_extraction are new public surface and appear nowhere on that page. Per CLAUDE.md, a functional change updates every doc that describes it — docs/spec/ and docs/guides/memory.mdx were updated, this one wasn't.

Nits

🟢 raw_text can be unbound in the JSON-decode handler (memory.py:1690-1699)

raise outcome["error"] (line 1620) re-raises the worker's exception inside the same try. requests.exceptions.JSONDecodeError subclasses json.JSONDecodeError, so a truncated Lemonade response body enters the handler before line 1635 ever ran — len(raw_text) then raises UnboundLocalError, which _run_extraction_job logs as a generic "extraction failed". Initialise raw_text = "" before the LLM call.

🟢 close_agent inside the registry lock (hub/agents/gaia/python/gaia_agent/session_registry.py:221)

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 with self._lock. Harmless today (that agent lost a create race and never ran a turn, so the drain returns instantly), yet it is now a path that could hold the registry lock for 15s. Worth a word in the docstring, or moving the close out of the lock like the other sites do.

🟢 Serial drains add up on bulk teardown (session_registry.py:283, :307)

reap() and clear() close sessions in a loop, each now up to EXTRACTION_EXIT_WAIT_S. reap() runs on every get_or_create. Idle-expired sessions won't have live extractions in practice, so this is latent rather than broken — but a per-batch budget would be more honest than 15s × N.

🟢 Per-turn INFO line when auto-extraction is off (memory.py:2861)

"extraction skipped: auto-extraction is off" logs on every single turn for anyone who disabled it. DEBUG fits an unconditional per-turn line better; the word-floor skip below it is the one worth seeing at INFO.

Strengths

  • The diagnosis is the valuable part of this PR: shutdown(wait=True) meant the 8s deadline never abandoned anything, and a reasoning model spending a 1024-token budget on hidden thought explains "12 of 14 stored nothing" far better than the timeout alone. Both are fixed at the cause.
  • _ExtractionJob freezing the turn's text and context at turn end — rather than reading them back off the instance later — pre-empts the misfiling bug this design would otherwise have shipped with, and test_extraction_reads_the_turn_captured_at_turn_end actually proves it.
  • FAISS add/remove/rebuild/search serialised behind a reentrant lock, added proactively for a race the background thread newly makes possible, with _rebuild_faiss_index_locked handling the re-entry from the remove fallback.
  • The new tests assert elapsed time and live thread counts, not just return values, and the queue-full / drain-gave-up paths are loud rather than silent.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Merged current main into this branch to clear the drift. Nothing in the PR's own change had to move — the only overlap with main was in the memory guide and memory.py, and both auto-merged.

🔍 Technical details

Merge commit 61bbb3e50 (git merge origin/main, no rebase/force-push). Auto-merged: docs/guides/memory.mdx, src/gaia/agents/base/memory.py. PR content vs main: 9 files, +698/-111.

Tests: python -m pytest tests/unit/test_memory_mixin.py tests/unit/test_starter_skills.py -q → 505 passed, 15 skipped.

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.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Fixed the blocking finding and three of the nits. The shared-self.chat finding I have deliberately not implemented — it changes what the PR claims, and that is a call to make rather than guess at.

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 -q branch, which is the path people use least, while interactive, Ctrl-C and error exits returned through a cleanup block that stopped the file watcher and nothing else. The drain moved into that cleanup block in all three entry points, so one place covers all four exits.

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 self.chat. The review's third point is the one with teeth — Lemonade serves one slot per model, so on back-to-back turns the 7–17s is relocated rather than removed. Giving extraction its own SDK instance fixes the metrics corruption but cannot fix the queueing, which is inherent to one local model server. Either way the "39% of wall time" claim needs a back-to-back measurement to stand. I have not touched it, because writing a test to pin the current behaviour would cement something nobody has chosen.

🔍 Technical details

1. The drain (src/gaia/cli.py ×2, hub/agents/chat/python/gaia_agent_chat/app.py).

Removed the inline call beside the one-shot return and put it in each finally, guarded so a wedged drain cannot turn a clean exit into a traceback. _launch_interactive_cli had no finally at all and now has one; its guard is if "agent" in locals(), because a failed Lemonade pre-flight exits before the agent is built.

tests/unit/test_cli_memory_drain_on_exit.py — five cases against the real _launch_interactive_cli with the chat wheel and pre-flight stubbed: normal exit, KeyboardInterrupt, an exception (still drains, still exits non-zero), a drain that itself raises (logged, exit stays clean), and a pre-flight failure (drain correctly skipped). Verified the first four fail when the finally is deleted.

2. raw_text unbound — fixed (memory.py). Confirmed the path: raise outcome["error"] re-raises the worker's exception inside the same try, before the raw_text = response.text assignment. requests.exceptions.JSONDecodeError subclasses json.JSONDecodeError, so a truncated body lands in the handler and len(raw_text) raises UnboundLocalError — which _run_extraction_job then logs as a generic failure, hiding the real cause. Bound to "" before the call.

3. close_agent inside the registry lock — moved out (session_registry.py:264). It is now the only close_agent site not called outside the lock, and with the drain inside it that is a path that could hold the registry lock for EXTRACTION_EXIT_WAIT_S (15s). Restructured so the create-race branch records the losing agent and closes it after the critical section — deliberately not by splitting into two lock acquisitions, which would have reopened the install race the block exists to prevent. One lock block still decides the winner. hub/agents/gaia/python/tests/test_session_registry.py: 24 passed.

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. docs/sdk/sdks/memory.mdx — updated. It still said "Timeout (3s) → logged warning, skip" and described _after_process_query as running extraction inline for turns "≥ 20 words" (the floor is 5). Added a Background extraction section with the five real constants (MIN_EXTRACTION_WORDS 5, EXTRACTION_TIMEOUT_S 60, EXTRACTION_MAX_TOKENS 4096, EXTRACTION_QUEUE_MAX 4, EXTRACTION_EXIT_WAIT_S 15), the one-thread-per-agent rule, and both wait helpers with the note that drain_memory_extraction() is a safe no-op on an agent without memory. Corrected the Hook-3 description to say the transcript is stored synchronously and only extraction is deferred.

6. Not done — the shared SDK. Of the review's three symptoms, a separate SDK instance fixes the first two (the single _open_call recorder slot, and get_last_usage() being last-write-wins) but not the third: one Lemonade slot per model means an in-flight extraction and the next turn's generation still queue. Worth deciding together with whether the PR's timing claim is measured back-to-back or single-shot.

Merge resolutions. flagship_tasks.py — both sides added imports; kept both. test_memory_mixin.py — both sides appended independent tests (TestBackgroundExtraction here, three standalone tests on main); kept both.

Validation. tests/unit/test_memory_mixin.py + the new file: 329 passed. tests/integration/test_memory_eval.py: 38 passed. test_session_registry.py: 24 passed. util/lint.py --black --isort --fix and --flake8 clean; check_doc_links.py --internal-only passes. tests/unit/cli/test_cli_smoke.py has 11 failures, all gaia-cli/gaia-mcp/gaia-agent/gaia-code/gaia-emr not on PATH — this box installs only the gaia console script, the same environmental set noted earlier on this PR.

Still unchecked, unchanged from the original review: gaia eval agent --category context_retention against the committed baseline.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

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, gaia stats, and the eval's own performance flags.

On the memory behaviour I have no concerns: in a flagship run of memory_multi_fact_accumulation with memory enabled, the recall turn scored higher than main's (9.9 vs 8.85), and the background worker verifiably stored each fact as the conversation went. What changed is that a turn and its extraction now share one LLM client, and a turn's usage is read from a single "last call" slot on that client after the turn finishes. Same run, same box, same backend: this branch reported 205 / 112 / 17,113 / 1,825 input tokens across four turns where main reported a steady 526 / 528 / 534 / 599. Two of those are smaller than the system prompt alone, and the 17k one tripped token_explosion and high_latency on a turn that called no tools at all.

This is the shared-self.chat question you left open, so it is yours to decide rather than mine — but it now has a measurement behind it instead of a theory. Either giving extraction its own client, or capturing usage inside the turn's own call rather than reading it back afterwards, would settle it. I have the merge-conflict resolution against current main ready and every touched test passing, so this is the only thing standing in the way.

🔍 Technical details

Mechanism. _extract_via_llm calls self.chat.send_messages(...) — the same AgentSDK instance, so the same client. LemonadeProvider captures usage into a single self._last_usage (and _last_ttft_seconds), and AgentSDK reads it back after the call returns (src/gaia/chat/sdk.py:353 and :482). While extraction ran before the answer, the turn's own call was always the last writer, which is why main's numbers are flat. Off the answer path, whichever call finishes last wins the slot.

Measurement. One box, one Lemonade backend, flagship gaia agent, memory_enabled on, isolated GAIA_MEMORY_DB per side, runs back to back:

score elapsed input tokens per turn
this branch 9.45 PASS 317.6s 205 / 112 / 17113 / 1825
main (d33ae5736) 9.65 PASS 241.5s 526 / 528 / 534 / 599

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 waiting for the model slot… while turn 2's extraction is still in flight (extraction started 10:10:46 → extraction finished: 1 memory stored in 17.4s 10:11:04). That turn came back with a 44s TTFT. Inline extraction could never contend with a turn; background extraction can, and the cost lands on the next turn.

Everything else checked out. Five merge conflicts resolved against current main (the notable one: the extraction job must freeze _turn_tool_record at turn end, since process_query clears it at the start of the next turn and a worker reading it live would drop every grounded: "tool" op from #4060). No duplicate blocks introduced, all touched files compile, python util/lint.py --all passes, and no memory test fails on this branch. The three memory docs match the merged behaviour.

Separately, and not caused by this PR: the memory eval category scores 9+/10 while global memory is off, because memory_enabled defaults to false and every eval session therefore runs incognito and stores nothing. Both of my first-round runs passed without exercising memory at all. Worth its own issue.

@itomek

itomek commented Sep 28, 2026

Copy link
Copy Markdown
Collaborator

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 own

All four memory PRs edit the same MemoryMixin, so every pair conflicted and none could be validated without the others. Two behaviours only survived because the fold was done deliberately rather than by taking one side: the turn's tool record and the extraction read scope both sat on lines that moved to the background worker, and a plain merge dropped them. Details are in #4406's description.

itomek added a commit that referenced this pull request Sep 28, 2026
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.
itomek added a commit that referenced this pull request Sep 28, 2026
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.
@itomek itomek self-assigned this Sep 28, 2026
@itomek itomek closed this in #4406 Sep 28, 2026
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Sep 28, 2026
…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]>
@itomek

itomek commented Sep 28, 2026

Copy link
Copy Markdown
Collaborator

Merged via #4406 (commit 143c697f) — closing this as landed, not dropped.

#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 in

Three things had to be resolved that neither this PR nor main could see alone:

  • The turn's tool record was being dropped. _extract_via_llm gained a tool_record parameter on main after this branch forked; the background worker called it without one, so every op grounded in a tool result would have been discarded by the grounding gate. _ExtractionJob now freezes the record with the turn.
  • MemoryStore.close() could segfault the process. It took no lock, so teardown freed the SQLite connection while the extraction thread was mid-statement. It now holds the lock, and every DB method refuses a call that lost the race to close.
  • The extraction read scope moved with the call into the worker; read_scope is frozen on the job separately from context, so a turn filed under global still reads across every label.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents cli CLI changes documentation Documentation changes eval Evaluation framework changes performance Performance-critical changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants