Skip to content

fix(memory): isolate stored memories from caller mutations - #7213

Open
Shy7777 wants to merge 1 commit into
google:mainfrom
Shy7777:fix/memory-event-snapshots
Open

Shy7777 wants to merge 1 commit into
google:mainfrom
Shy7777:fix/memory-event-snapshots

Conversation

@Shy7777

@Shy7777 Shy7777 commented Sep 19, 2026

Copy link
Copy Markdown

Link to Issue or Description of Change

Problem: InMemoryMemoryService shares mutable event content across its write and read boundaries. Mutating an event after either ingestion API silently changes future recall. Editing the Content in a search result can also erase the stored memory and modify the source session history.

Solution: Snapshot each ingested Event's metadata and Content, then return a separate Content for each selected search result. The Event copy is shallow except for Content, so unrelated opaque outputs/actions are not traversed. Search-result copying happens after ranking and the top-ten limit. Existing session replacement, event-ID deduplication and search behavior stay intact.

Reproduction

On main 665ec9835bee154f6d30ff49fb5125d79ef57e8c, both printed counts are 0; with this patch, they are 1. ADK 2.9.0, macOS, Python 3.12.13; no model, LiteLLM or credentials. This reproduces consistently; whether it worked in an older release is not established.

import asyncio

from google.adk.events import Event
from google.adk.memory import InMemoryMemoryService
from google.adk.sessions import Session
from google.genai import types


async def main():
    event = Event(
        author="user",
        content=types.Content(parts=[types.Part(text="I prefer jasmine tea.")]),
    )
    session = Session(app_name="app", user_id="alice", id="session", events=[event])
    service = InMemoryMemoryService()
    await service.add_session_to_memory(session)
    first = await service.search_memory(app_name="app", user_id="alice", query="jasmine")
    first.memories[0].content.parts.clear()
    second = await service.search_memory(app_name="app", user_id="alice", query="jasmine")
    print("Recalled memories:", len(second.memories))
    print("Source parts:", len(event.content.parts))


asyncio.run(main())

The same aliasing occurs with add_events_to_memory. Four new regressions exercise both ingestion APIs and both mutation directions through actual public calls.

Testing Plan

Unit tests:

  • I have added unit tests for my change.
  • All unit tests pass locally.
pytest tests/unittests/memory/test_in_memory_memory_service.py \
  tests/unittests/tools/test_load_memory_tool.py \
  tests/unittests/tools/test_preload_memory_tool.py -q
56 passed, 1 warning

All four new cases fail on the unmodified upstream service and pass with the fix. Changed-file pre-commit hooks pass. Mypy reports no issues in the changed production file; the repository's configured mypy scope excludes tests.

The configured tox run attempted Python 3.10–3.14 after generating a local lock with uv lock. It was not fully green:

  • 3.10: 15,216 passed, 5 failed, 87 skipped, 27 xfailed, 2 xpassed. The five failures are the Agent import allowlist case in test_import_loading.py and four cases in test_load_web_page.py. Running those exact five cases on pristine base 665ec98, with the same interpreter/dependencies and proxy settings, reproduced all five failures.
  • 3.11: setup failed downloading pypdfium2==5.13.0 after TLS handshake EOF/retries.
  • 3.12: setup failed downloading google-crc32c==1.8.0 after TLS handshake EOF/retries.
  • 3.13 and 3.14: setup failed downloading the Python interpreters after TLS handshake EOF/retries.

The 56-test memory/tool suite passed separately on Python 3.12; the memory service tests also passed within the 3.10 full run. The full-matrix checkboxes remain unchecked.

Manual end-to-end test:

An offline custom BaseAgent uses load_memory twice within a real Runner invocation, clearing the first response's Content between the calls. On upstream the Runner returns MEMORY LOST; after the fix it recalls the original text, and the source session remains unchanged. Save the following as memory_probe.py and run python memory_probe.py in the development environment:

Runner reproduction
"""Offline Runner -> load_memory -> InMemoryMemoryService ownership check."""
import asyncio
from collections.abc import AsyncGenerator

from google.adk.agents.base_agent import BaseAgent
from google.adk.agents.invocation_context import InvocationContext
from google.adk.events.event import Event
from google.adk.memory.in_memory_memory_service import InMemoryMemoryService
from google.adk.runners import Runner
from google.adk.sessions.in_memory_session_service import InMemorySessionService
from google.adk.sessions.session import Session
from google.adk.tools.load_memory_tool import load_memory
from google.adk.tools.tool_context import ToolContext
from google.genai import types


class MemoryReader(BaseAgent):
    async def _run_async_impl(self, ctx: InvocationContext) -> AsyncGenerator[Event, None]:
        tool_context = ToolContext(ctx)
        first = await load_memory("jasmine", tool_context)
        first.memories[0].content.parts.clear()
        second = await load_memory("jasmine", tool_context)
        text = second.memories[0].content.parts[0].text if second.memories else "MEMORY LOST"
        yield Event(invocation_id=ctx.invocation_id, author=self.name,
                    content=types.Content(role="model", parts=[types.Part(text=text)]))


async def main() -> None:
    source = Session(app_name="memory_probe", user_id="alice", id="prior", events=[
        Event(author="user", content=types.Content(parts=[types.Part(text="I prefer jasmine tea.")]))
    ])
    memory = InMemoryMemoryService()
    await memory.add_session_to_memory(source)
    sessions = InMemorySessionService()
    await sessions.create_session(app_name="memory_probe", user_id="alice", session_id="current")
    runner = Runner(app_name="memory_probe", agent=MemoryReader(name="reader"),
                    session_service=sessions, memory_service=memory)
    recalled = []
    async for event in runner.run_async(user_id="alice", session_id="current",
            new_message=types.Content(role="user", parts=[types.Part(text="Recall jasmine")])):
        if event.content and event.content.parts:
            print("Runner:", event.content.parts[0].text)
            recalled.append(event.content.parts[0].text)
    await runner.close()
    assert recalled == ["I prefer jasmine tea."], recalled
    print("Source session:", source.events[0].content.parts[0].text)
    assert source.events[0].content.parts[0].text == "I prefer jasmine tea."


asyncio.run(main())

Output after the fix:

Runner: I prefer jasmine tea.
Source session: I prefer jasmine tea.

Checklist

  • I have read CONTRIBUTING.md.
  • I have performed a self-review of the code.
  • I have commented the non-obvious copy boundary.
  • I have added tests that demonstrate the fix.
  • All new and existing unit tests pass locally.
  • I have manually tested the change end-to-end.
  • No dependent downstream change is required.

Additional context

#6380 protects iteration by copying dictionary/list containers. This change addresses the separate nested Content ownership issue. It introduces no new dependency or public API.

@google-cla

google-cla Bot commented Sep 19, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants