Skip to content

InMemoryMemoryService.add_session_to_memory deletes older turns when the session is loaded with num_recent_events #8353

Description

@chaitanya0305

Summary

InMemoryMemoryService.add_session_to_memory replaces everything stored for a session with the events of the Session it is given. A session loaded with GetSessionConfig(num_recent_events=N) holds only its latest events, so each call silently deletes the memories of every older turn in that session. With num_recent_events=0 it deletes all of them.

This hits the setup the docstrings show: a RunConfig with get_session_config=GetSessionConfig(num_recent_events=...) plus an after_agent_callback that calls ctx.add_session_to_memory(). After a few turns, search_memory / preload_memory no longer find facts the user gave earlier.

SqliteMemoryService and FirestoreMemoryService keep those entries. #7571 (commit 2591397) made that the intended behaviour ("Entries for events that are not in session.events at all, such as turns outside a session loaded with num_recent_events, are kept"), but the in-memory service was not changed.

Reproduction

Run on current main (3e322e9):

import asyncio, os, tempfile
from google.adk.events.event import Event
from google.adk.memory.in_memory_memory_service import InMemoryMemoryService
from google.adk.memory._sqlite_memory_service import SqliteMemoryService
from google.adk.sessions.in_memory_session_service import InMemorySessionService
from google.adk.sessions.base_session_service import GetSessionConfig
from google.genai import types

def ev(inv, author, text):
  return Event(invocation_id=inv, author=author,
               content=types.Content(role='user' if author == 'user' else 'model',
                                     parts=[types.Part(text=text)]))

async def run(mem, label):
  ss = InMemorySessionService()
  s = await ss.create_session(app_name='app', user_id='u')
  await ss.append_event(s, ev('i1', 'user', 'My favourite city is Paris'))
  await ss.append_event(s, ev('i1', 'agent', 'Noted Paris'))
  await mem.add_session_to_memory(
      await ss.get_session(app_name='app', user_id='u', session_id=s.id))
  await ss.append_event(s, ev('i2', 'user', 'I also like London'))
  await ss.append_event(s, ev('i2', 'agent', 'Noted London'))
  recent = await ss.get_session(app_name='app', user_id='u', session_id=s.id,
                                config=GetSessionConfig(num_recent_events=2))
  await mem.add_session_to_memory(recent)
  r = await mem.search_memory(app_name='app', user_id='u', query='Paris')
  print(label, "search 'Paris':", [m.content.parts[0].text for m in r.memories])

async def main():
  await run(InMemoryMemoryService(), 'InMemory')
  await run(SqliteMemoryService(db_path=os.path.join(tempfile.mkdtemp(), 'm.db')), 'Sqlite')

asyncio.run(main())

Actual

InMemory search 'Paris': []
Sqlite search 'Paris': ['Noted Paris', 'My favourite city is Paris']

Expected

InMemory search 'Paris': ['My favourite city is Paris', 'Noted Paris']

That is, the same result as SqliteMemoryService: the turn-1 memories survive.

Cause

In src/google/adk/memory/in_memory_memory_service.py, add_session_to_memory sets the session's bucket to _apply_rewinds(session.events). Stored events that are not in session.events (turns outside the truncated window) are dropped.

Proposed fix

Keep stored events for the session whose ids are not in session.events at all, and replace the rest from _apply_rewinds(session.events) as now. Turns removed by a rewind are still removed, and repeated adds don't duplicate. This matches the Sqlite and Firestore behaviour. The change is about 10 lines, plus a regression test in tests/unittests/memory/test_in_memory_memory_service.py.

I used an AI coding assistant (Claude) to find and analyse this; I reproduced it and checked the fix myself.

I've tested a fix with a regression test: chaitanya0305/adk-python@main...chaitanya0305:adk-python:fix/in-memory-memory-truncated-session. If this is accepted, I'll open the PR straight away.

Activity

  1. surajksharma07 commented on Nov 27, 2026

    @surajksharma07
    Collaborator

    Thanks @chaitanya0305. Reproduced on main (03725e8) and on the 2.15.1 wheel: InMemory comes back empty for "Paris" while Sqlite keeps both turn-1 entries.

    Your approach worked for me as a workaround: keep stored events whose ids aren't in session.events, and rebuild the rest from _apply_rewinds. Locally it matched Sqlite for windowed adds, num_recent_events=0, repeated full adds, and a rewind inside the window.

    Could you confirm it behaves the same on your side? Please also check that delete-memory followed by a re-add still works. If everything holds up after thorough testing, feel free to open the PR from your branch.

    Small thing: #8355 looks like an accidental duplicate of this one. Could you close it if it's still open?

  2. chaitanya0305 commented on Nov 27, 2026

    @chaitanya0305
    Author

    Thanks @surajksharma07 for reproducing and testing it. Confirmed on my side, on main (03725e8) with the branch rebased:

    • Windowed adds: turn-1 memories survive a later add from a session loaded with num_recent_events, same as Sqlite.
    • num_recent_events=0: nothing is removed.
    • Repeated full adds: each event is stored once.
    • Rewind inside the window: the rewound turn is dropped, older turns are kept.
    • delete_memory then re-add: the deleted memory stays deleted, both when the deleted event is inside the re-added window and when it is outside it; the other memories are kept.

    The windowed cases now run on both InMemory and Sqlite through one fixture, and 4 of the new tests fail without the fix. #8355 is already closed. Opening the PR now.

  3. surajksharma07 commented on Nov 27, 2026

    @surajksharma07
    Collaborator

    Thanks @chaitanya0305, and thanks for closing #8355. I pulled #8387 locally: the test file passes on the branch (73), the same 4 tests fail against current main, and the original repro now finds both Paris entries.

    Running the windowed cases against Sqlite too is a nice touch, since it keeps the two services honest with each other.

    One thing worth keeping in mind with #8141: the conflict is only in the tests, but both write to the same per-session bucket. A small test that mixes add_events_to_memory and add_session_to_memory on one session would help, whichever lands second.

    From my side this looks good. Next it needs a maintainer to approve the workflows and review it.

  4. chaitanya0305 commented on Nov 27, 2026

    @chaitanya0305
    Author

    Thanks @surajksharma07. I added the mixed test to #8387 (c2a69fe): test_add_events_and_windowed_session_adds_share_one_session puts an event in the session with add_events_to_memory, then does windowed add_session_to_memory calls and re-adds through both methods. It runs on InMemory and Sqlite: both keep the directly added event and the older turn, and store each event once. On current main the InMemory variant fails (the windowed add drops both earlier entries), Sqlite passes. tests/unittests/memory/ is 241 passed.

  5. surajksharma07 commented on Nov 27, 2026

    @surajksharma07
    Collaborator

    Thanks @chaitanya0305, that's exactly the test I had in mind. On c2a69fe the test file is 75 passed, the new mixed test fails on main for InMemory only (Sqlite passes), and tests/unittests/memory/ comes out at 241 on my side too.

    One note for later: this test uses the current add_events_to_memory. #8141 would also store content-less anchor events in the same bucket, so whichever of the two lands second should rerun this test on top of the other. Nothing to change here for now.

    #8387 looks complete from my side. It now needs a maintainer to approve the workflows and review it.

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

Metadata

Metadata

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions