Skip to content

perf(memory): new chats reuse the memory section so their prompt stays cached - #5288

Open
kovtcharov wants to merge 10 commits into
amd:mainfrom
kovtcharov:claude/perf-shared-memory-prompt
Open

kovtcharov wants to merge 10 commits into
amd:mainfrom
kovtcharov:claude/perf-shared-memory-prompt

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

On Gemma-4-E4B, the first message of a new chat re-read the whole ~19K-token prompt (45–50 s) whenever memory had changed since the last chat, which is almost always once memory is in use. Each chat rendered its memory section afresh. The chat template puts every tool schema after the system text, and Gemma's sliding-window layers can't rewind to an early change, so a different memory section discarded the entire cached prompt (cache_n = 0). New chats in the same agent process now reuse the section another chat rendered, for up to an hour and per chat model. Three chats in a row, with memories stored between them, got the same system prompt and reused the cached prefix on their first call. In the original after-run, new chats reused 18,600–19,200 cached tokens where the baseline reused 0.

A new chat still re-renders the section and shows the shared text only if nothing in it has become untrue. A memory pushed out by the section's size cap is fine, because it still exists unchanged. A memory forgotten or edited anywhere, the Memory page included, forces a fresh render. Memories learned since reach the chat through per-turn recall, as they already did within a chat.

A system prompt that changes mid-chat isn't this PR, and it still happens. Over two 20-turn chats on this branch, the memory section never changed within a chat. The skills section did: its per-turn skill selection alternated between three sizes (3.4K, 3.7K and 5.4K chars) from one turn to the next. Each change re-reads the prompt after that point, which on Gemma is the whole prompt. The same code is on main; #5021 covers skill changes invalidating the cache.

LLM-affecting: the memory text a new chat sees can miss up to an hour of newly learned facts. Eval categories to watch on the next RC: memory, gaia_memory.

Test plan

  • python -m pytest tests/unit/test_memory_shared_stable_prompt.py tests/unit/test_memory_mixin.py -q
  • With GAIA_TURN_LOG set, send a turn that stores a memory, then open a new chat in the same sidecar. Its record's prompt.system_sha matches the previous chat's, and the first call's server.cache_n covers the system prompt and tools.
  • Forget a memory on the Memory page, open a new chat, and confirm the memory isn't in its system prompt.

…s cached

Every new chat rendered the memory section of its system prompt afresh. On
Gemma-4-E4B the chat template places all tool schemas after the system text,
and its sliding-window layers cannot rewind a cached sequence far, so any
change in that section made the model re-read the whole ~19K-token prompt
(cache_n = 0): measured 45-50 s on the first message of every chat that
followed a memory write.

New sessions of the same process now reuse the rendered section for up to an
hour (SHARED_STABLE_TTL_S). What was stored since reaches them through the
per-turn recall, exactly as it already did within a session; a context
switch, a session reset, or forgetting/editing a shown item drops the shared
copy and re-renders. LLM-affecting: watch the memory eval categories.
…mory-prompt

# Conflicts:
#	hub/agents/gaia/npm/CHANGELOG.md
#	src/gaia/agents/base/memory.py
Main now re-renders the memory section per chat model, so the shared copy is
keyed by model too. A new chat re-renders the section and reuses the shared
text only while every line of it is still in the fresh render, so a memory
forgotten or edited anywhere (the Memory page included) never reaches a new
chat from the shared copy.
…ats sharing

The memory section shows only as many facts as fit its size budget, so one
new fact pushes an old line out. The shared copy required every one of its
lines to still be in a fresh render, which a displaced line failed, so a busy
memory store fell back to a fresh render and the new chat re-read its whole
prompt. A missing line is now accepted when its memory still exists unchanged
and only the cap dropped it; a removed, forgotten or edited memory still
forces a fresh render, and the "(N more stored memories ...)" count may be
stale.
@kovtcharov
kovtcharov marked this pull request as ready for review November 11, 2026 19:37
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes

New chats now reuse the memory section another chat already built, so on Gemma-4 they skip the ~45 s re-read of the whole prompt. The approach is sound and the tests cover forget, edit, expiry, contexts and models. One privacy hole needs closing first.

  • A memory hidden on the Memory page still reaches new chats for up to an hour. The reuse check asks only whether each dropped memory still exists unchanged. A memory marked sensitive, or moved to another context, passes that check, so new chats keep showing it from the shared copy. Treat any memory that was changed after the shared copy was made as a reason to render the section again.
  • The CHANGELOG gains a bullet from an earlier release. The "Full access in the Agent UI" entry already shipped and is listed further down, so it now appears twice and reads as unreleased. It also sits above the "Requires the gaia Python CLI 0.26.0+" line. Drop it.

Real-world evidence

N/A: no evidence bundle was produced for this run. The change is in the agent's prompt assembly, and proving the cache saving needs real inference on the Strix Halo lane. This verdict rests on static review. I couldn't run the PR's tests here because this runner has no Python test environment. The PR description reports cached-token counts from the author's own runs (18,600–19,200 cached tokens versus 0 before), which supports the performance claim.

🔍 Technical details

🟡 Sensitive / re-scoped memory passes the "still true" check (src/gaia/agents/base/memory.py:3694-3699)

_shared_section_still_true treats a missing line as harmless when its id is no longer shown, the row exists, isn't superseded, and its content is unchanged. But the fresh render also drops rows for other reasons. get_by_category_contexts filters sensitive = 0 and context IN (?, 'global'), and _fit_personal_memories also filters on category, consolidation notes and due dates. PUT /memory/{id} (KnowledgeUpdate) can set sensitive=True or change context / category without touching content or superseded_by.

Scenario: chat A shows "door code is 4417". The user marks it sensitive on the Memory page. Chat B opens within the hour: the fresh render omits the memory, the stored content still matches the missing line, and B's system prompt shows the sensitive fact. test_a_memory_erased_since_is_not_shown_to_a_new_chat covers forget only.

Minimal fix: reject the reuse when a kept row is now hidden for any reason other than the cap:

            item = self._memory_store.get_item(knowledge_id)
            if (
                item is None
                or item.get("superseded_by")
                or item.get("sensitive")
                or item.get("context") not in ("global", self._memory_context)
            ):
                return False

A more robust option: store a wall-clock rendered_at in the shared tuple and return False for any kept item whose updated_at is later. That covers category and due-date edits too. Add a test that marks a shown memory sensitive=True and opens a new chat.

🟡 Duplicate, already-released CHANGELOG bullet (hub/agents/gaia/npm/CHANGELOG.md:16-20)

"Full access in the Agent UI grants the folders you name" is already in a released section ("File access and privacy", ~line 850). Adding it under [Unreleased] re-announces a shipped change, and it is placed above the section's "Requires the gaia Python CLI 0.26.0+" line. This looks like a merge artifact; remove those five lines.

🟢 Any confirmation bump disables sharing (memory.py:3694-3699)

Personal lines carry their "last confirmed" date. When a shown memory is re-confirmed, its line changes but its id is still in shown_now, so it isn't in kept and the check fails. That is safe, but it means fewer cache hits than the PR describes once recall bumps dates during a day. It's worth checking whether that path is common in your GAIA_TURN_LOG runs.

Doc drift: both doc pages that describe the frozen section (docs/sdk/sdks/memory.mdx, docs/spec/agent-memory-architecture.md) were updated consistently. I found no other doc that still says the section is per-session only.

Strengths

  • The reuse is conservative by construction: any line it can't explain forces a fresh render.
  • The cache is keyed per store, context and model. That matters because tool-error memories are shown per model, and a test pins it.
  • Explicit edits (share=False) drop the shared entry, so in-chat forget and update still take effect at once.

…hared copy

The shared memory section accepted a dropped line when its memory still
existed with the same text. A memory marked sensitive, moved to another
context, or otherwise edited on the Memory page keeps its text, so a new chat
could still show it for up to an hour. A dropped memory now also has to be
non-sensitive, in a context the chat sees, and unchanged since the shared
copy was rendered; anything else forces a fresh render.

Also drops a CHANGELOG bullet the main merge re-added from an earlier
release, and moves this PR's entry below the section's requirements line.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Both fixed in 726a6cd.

  • Hidden or moved memories: a dropped memory now also has to be non-sensitive, in a context the chat sees, and unchanged since the shared copy was rendered (its updated_at against the render time), so category and due-date edits are covered too. New tests mark a shown memory sensitive and move one to another context; both fail without the fix.
  • CHANGELOG: removed the re-added "Full access" bullet (a merge artifact) and moved this entry below the requirements line.

Leaving the re-confirmation case as is: a re-confirmed memory changes its line, so that chat renders fresh. It costs a cache hit, never correctness.

The shared memory section stamped its render time after rendering, so a memory
edited during the render (a due date passed, a category changed) looked older
than the copy and a new chat could keep showing it. The stamp is now taken
before the render. A row whose updated_at has no offset or doesn't parse is
treated as edited since, so it re-renders instead of raising on start.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Merged main in (no conflicts) and closed one more gap in the shared-copy check: an edit made while the shared section was being rendered could still be shown to a new chat.

🔍 Technical details
  • The wall-clock render time was stamped after _build_stable_memory_prompt(), so a row edited during the render (due date moved into the past, category change) had updated_at earlier than the stamp and passed _shared_section_still_true. The stamp is now taken before the render.
  • A row whose updated_at has no UTC offset or doesn't parse raised TypeError/ValueError on chat start; it now counts as edited since, so the chat renders fresh.
  • New tests: a due-date edit hides a note from the shared copy; an edit landing mid-render; offset-less, garbled and empty stamps. The mid-render and stamp tests fail on the previous head.
  • Unaddressed and harmless: a note whose due date passes with no edit can stay in the shared copy for up to the 1 h TTL.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

An edited memory can still reach new chats in its old wording when another memory was pushed out by the size cap at the same time. The reuse check matches dropped lines by substring, so if the pushed-out memory's text appears inside the edited memory's old line, the stale line passes as "pushed out" and the edit is hidden for up to an hour.

Example: "Door code 4417. The juliet 9 project uses lima widgets." is edited to "Door code is private." while "The juliet 9 project uses lima widgets." drops off the list. The next chat still shows "Door code 4417".

🔍 Technical details
  • _shared_section_still_true only runs the _edited_before check on ids that are no longer shown (shared ids - shown_now). An item that is still shown but was edited is never checked, so its old line counts as harmless whenever any(content in line for content in kept) matches.
  • Reproducer: store 30 facts as in test_a_memory_pushed_out_by_the_size_cap_still_shares, plus X = "Door code 4417. " + <content of the fact the next store pushes out>. Render a chat, store one more fact, store.update(X, content="Door code is private."), open a new chat: "4417" in get_memory_system_prompt() is True.
  • Possible fixes: run _edited_before on every id in the shared copy, not just the dropped ones, or require each missing line to equal a kept item's rendered line rather than contain its content.

…nchanged

An edited memory could reach new chats in its old wording for up to an hour
when another memory was pushed off by the size cap at the same time and that
memory's text sat inside the edited memory's old line: dropped lines were
matched by substring, and only memories no longer shown were checked for edits.

The shared copy now records each memory row it rendered (every field that
decides whether and how it shows) with its exact line. A new chat reuses it
only if every one of those rows is unchanged, and every line missing from a
fresh render is the exact line of a memory only pushed out by the cap. A
forget, a sensitive mark, a context move or any edit therefore invalidates it
at once, and an edited profile or system line can no longer pass as dropped.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Fixed in 48d4f4a: an edited memory can no longer reach a new chat in its old wording, with or without a size-cap drop at the same moment. The reuse check no longer matches text by substring.

🔍 Technical details
  • The shared copy now stores, for every memory and lesson row it rendered, a version (content, category, context, sensitive, superseded_by, due_at, source, created/updated stamps, metadata; plus confidence for lessons) and the row's exact rendered line.
  • A new chat reuses the copy only if every one of those rows is still in the store with the same version, so any forget, sensitive mark, context move or edit (shown or pushed out) invalidates it on the spot. Lines missing from the fresh render must equal the exact line of a row that was only pushed out by the cap.
  • This also closes a sibling gap: profile/system rows aren't tracked by id, so an edited profile line containing a pushed-out memory's text passed the old substring check too.
  • The wall-clock _edited_before comparison is gone, so legacy or garbled updated_at stamps no longer matter (they still render fresh when changed).
  • New tests: your reproducer and the profile variant (both fail on 4af5f7e), plus a shown memory edited during a cap drop, a pushed-out memory edited, forgotten or marked sensitive, a shown memory forgotten or marked sensitive during a cap drop, and a plain cap drop still reusing the copy.
  • Memory unit tests: 2401 passed. Lint clean. Merged main in (no conflicts).

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes

Both earlier findings are fixed: hidden or moved memories no longer reach new chats, and the duplicate CHANGELOG bullet is gone. The new shared copy has one more leak.

🟡 Lessons from one project can show up in a chat about another project. The shared copy is keyed by store, memory context and model, but lessons are scoped by project folder, and that folder isn't part of the key. When two chats in the same process point at different projects and both have lessons, the other project's lessons look like they were "pushed out by the cap", so the second chat reuses the first chat's copy. It then shows project A's lessons and hides its own. Add the lesson workspace to the cache key, and add a test with two project roots.

🔍 Technical details
  • _shared_stable_key() returns (db_path, _memory_context, model_id). Lessons come from _workspace_lessons() → context=self._lesson_context() (workspace:<root>), which can differ per session through config.project_root, GAIA_PROJECT_ROOT or the cwd.
  • In _shared_section_still_true, project A's lesson rows still exist unchanged, so the version loop passes. Their lines are missing from B's fresh render, and their ids aren't in B's shown_now, so they end up in pushed_out and missing <= pushed_out holds. The shared section headers ("Lessons learned in this workspace…") match when both projects have lessons of the same kind, so nothing else forces a fresh render.
  • Fix: include the lesson context in the key:
        return (
            str(getattr(store, "_db_path", id(store))),
            getattr(self, "_memory_context", "global"),
            self._lesson_context(),
            getattr(self, "model_id", None),
        )

A chat in project B could reuse the memory section a chat in project A
rendered, showing A's lessons and hiding its own: lessons are scoped to the
project folder, but the shared copy was keyed only on store, memory context
and model, so A's unchanged lessons passed as "pushed out by the size cap".
The key now includes the lesson workspace.

It also includes the local date, the only other input that changes which
rows render: a reminder whose day passed overnight with no edit stayed in
the shared copy for up to the hour-long TTL.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Fixed in cbad174: a chat in one project no longer shows another project's lessons. The shared copy is now keyed on the project too, plus the local date, which was the only other input that changes which memories a chat sees.

🔍 Technical details
  • _shared_stable_key() now adds self._lesson_context() and today's local date (_local_today(), which _fit_personal_memories also uses for its past-due filter, so the two can't disagree).
  • The date closes the gap noted earlier as harmless: a reminder whose day passed overnight with no edit could stay in the shared copy for up to the 1 h TTL.
  • Checked the rest of the render path for other per-chat filters: system and profile rows are global, personal rows filter on memory context (keyed), sensitive/superseded (row version), and the chat model for tool errors (keyed). No agent, connector or person scoping applies there.
  • New tests: two project roots, where A's lesson never shows in B and B's own does; a project with no lessons shows none of another's; two chats in one project still share; a reminder whose day passes overnight drops out. The two-project and overnight tests fail without the fix.
  • Memory unit tests: 2686 passed, 68 skipped. Lint clean.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Holding this for an eval run: the privacy checks now hold up, but the PR changes what a new chat's system prompt contains and has no eval results yet.

A fact stored in one chat (say, the user's name) no longer appears in the next chat's system prompt for up to an hour; it only reaches that chat if per-turn recall happens to match the message. A plain "hi" in the second chat can therefore lose the personalized greeting the memory instructions ask for. That is the cross-session behavior the memory and gaia_memory categories score, and the PR body already marks it LLM-affecting. Please dispatch eval_flagship.yml for those two categories on this branch and post the comparison against the flagship baseline before merge.

🔍 Technical details
  • Privacy re-verified on cbad174 with fresh adversarial reproducers: edited "Door code 4417" text, project A/B lessons, mid-session context switch, two chat models sharing one store, memory disabled, a shifted due-day render (timezone), a lesson moved out of the lesson domain, a profile row deleted, a superseded row, a lesson edited in place, and app-style scoped contexts. Each one either rendered fresh or matched the fresh render.
  • Every render input is now covered: memory context, lesson workspace, model and local date are in _shared_stable_key(). Per-row fields are in _row_version. Untracked system and profile lines go through the exact-line diff.
  • Memory unit tests: 2088 passed, 6 skipped.
  • Mechanism: _run_memory_post_init calls _refresh_stable_memory_prompt(share=True), and remember of a new item doesn't pop the shared key because _refresh_if_shown only fires for shown ids (this is what test_a_new_chat_keeps_the_section_after_memory_changed asserts).

@kovtcharov-amd kovtcharov-amd added enhancement New feature or request performance Performance-critical changes labels Nov 12, 2026

This branch has not been deployed

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

Labels

agents documentation Documentation changes enhancement New feature or request performance Performance-critical changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants