From f6fbf008438f621497d1e3deee98c0acd6241dc9 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 15 Nov 2026 08:34:47 +0000 Subject: [PATCH 01/21] The Python SDK ships a Google ADK memory service LoomMemoryService implements google.adk.memory.BaseMemoryService: a saved session or turn goes to memory.set_from_messages, add_memory to memory.set, search_memory to memory.search scoped to the ADK app (the Loom agent) and user, and delete_memory to memory.delete. Installed as the google-adk extra. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- Makefile | 2 +- docs/features/integrations/frameworks.md | 62 ++++ docs/features/integrations/index.md | 50 +-- docs/reference/python-sdk.md | 5 + pyproject.toml | 4 + sdk/python/README.md | 2 +- sdk/python/loom/integrations/google_adk.py | 220 +++++++++++++ sdk/python/pyproject.toml | 3 + sdk/python/tests/test_google_adk.py | 294 ++++++++++++++++++ .../integration/test_sdk_google_adk_memory.py | 103 ++++++ 10 files changed, 718 insertions(+), 27 deletions(-) create mode 100644 sdk/python/loom/integrations/google_adk.py create mode 100644 sdk/python/tests/test_google_adk.py create mode 100644 tests/integration/test_sdk_google_adk_memory.py diff --git a/Makefile b/Makefile index e61f2fa524..61632644f2 100644 --- a/Makefile +++ b/Makefile @@ -148,7 +148,7 @@ test-integration: # may pin one package incompatibly. SDK_ADAPTERS_RESOLUTION=lowest-direct installs # every direct requirement (the SDK's own, the extra's, pytest) at its lower bound. # mypy is the [dev] pin. `make test-sdk-adapter-crewai` runs one. -SDK_ADAPTER_EXTRAS := langchain llamaindex openai-agents crewai autogen pydantic-ai ag2 +SDK_ADAPTER_EXTRAS := langchain llamaindex openai-agents crewai autogen pydantic-ai ag2 google-adk SDK_ADAPTERS_VENV ?= .venv-sdk-adapters SDK_ADAPTERS_PYTHON ?= 3.12 SDK_ADAPTERS_RESOLUTION ?= highest diff --git a/docs/features/integrations/frameworks.md b/docs/features/integrations/frameworks.md index b642ff7dec..5474101e69 100644 --- a/docs/features/integrations/frameworks.md +++ b/docs/features/integrations/frameworks.md @@ -20,6 +20,7 @@ or needs another database, vector store or cache. | CrewAI | `LoomCrewMemory` | Python, `loom.integrations.crewai` | `crewai.memory.Memory` | | AutoGen | `LoomMemory` | Python, `loom.integrations.autogen` | `autogen_core.memory.Memory` | | AG2 | `LoomRecallPolicy`, `loom_tools` | Python, `loom.integrations.ag2` | `ag2.assembly.AssemblyPolicy`, `tool()` from `ag2.tools` | +| Google ADK | `LoomMemoryService` | Python, `loom.integrations.google_adk` | `google.adk.memory.BaseMemoryService` | | Pydantic AI | `loom_toolset` | Python, `loom.integrations.pydantic_ai` | `FunctionToolset` | | Mastra | `loomTools` | TypeScript, `@clickhouse/loom/integrations/mastra` | `createTool` from `@mastra/core` | | AI SDK | `loomTools` | TypeScript, `@clickhouse/loom/integrations/ai-sdk` | `tool()` from `ai` | @@ -342,6 +343,64 @@ trimming policy (`SlidingWindowPolicy`, `TokenBudgetPolicy`), which can cut the request out of the events the policy reads. Those policies trim events, not the prompt, so `top_k` is what bounds the memory block. +## Google ADK + +`LoomMemoryService` implements ADK's `BaseMemoryService`, which a `Runner` takes as +`memory_service=`. ADK's own memory tools read it: `preload_memory` searches with the +user's message before each model call and adds the matches to the prompt, and +`load_memory` lets the model search. A callback saves a session or a turn. Install with +`pip install 'clickhouse-loom[google-adk]'` (`google-adk` 2.14 or later 2.x). + +```python +from google.adk.agents import LlmAgent +from google.adk.runners import Runner +from google.adk.sessions import InMemorySessionService +from google.adk.tools import preload_memory +from loom import Agent +from loom.integrations.google_adk import LoomMemoryService + + +async def save_session(callback_context): + await callback_context.add_session_to_memory() + + +async with Agent(org="acme", namespace="support") as loom_agent: + runner = Runner( + app_name="support", + agent=LlmAgent( + name="assistant", + model="gemini-flash-latest", + tools=[preload_memory], + after_agent_callback=save_session, + ), + session_service=InMemorySessionService(), + memory_service=LoomMemoryService(loom_agent), + ) +``` + +ADK scopes memory by app and user. The app name is the Loom `agent` of every write and +narrows every search, and the ADK user is the Loom `user_id`; a search reads every session +of that user. The namespace comes from the Loom agent. + +| ADK | Loom | +| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages` with the session id; Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn should save that turn's events | +| `add_events_to_memory` | the same for the events given, such as the latest turn | +| `add_memory` | one `memory.set` per entry under `adk/`, its `timestamp` as the memory's `valid_at` | +| `search_memory` | `memory.search` of the namespace it writes to; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | +| `delete_memory` | `memory.delete` of the entry's `id`: the memory's key, or for a verbatim chunk the key of the memory it was written under. A session summary has no `id`; [erasure](../memory/retention-and-erasure.md) removes it | + +Events keep their text parts only: the model's thoughts and tool calls and results are not +sent, and neither is `custom_metadata`. + +| `LoomMemoryService` argument | Default | Effect | +| ---------------------------- | -------- | ---------------------------------------------------------------------------------------------- | +| `agent` | required | the `loom.Agent` the service calls; ADK awaits its memory service, so a `SyncAgent` is refused | +| `top_k` | 10 | memories per search, from 1 to 500 | +| `honour_abstain` | `True` | leave out memories below Loom's floor; nothing when Loom abstains | +| `defer` | `True` | queue the extraction on the server instead of waiting for it | +| `key_prefix` | `adk` | the prefix of `add_memory`'s keys | + ## Pydantic AI Pydantic AI extends an agent through tools and toolsets. `loom_toolset` returns Loom's @@ -550,6 +609,9 @@ client can speak for several agents. silent. - **An AG2 turn fails when Loom is unreachable.** `LoomRecallPolicy` runs before each model call of the turn, and `AssemblerMiddleware` does not catch a policy's error. +- **ADK carries on without memory when `preload_memory`'s search fails.** It logs a + warning and the model call goes on; a failed `load_memory` search or save callback fails + the run. - **An AutoGen turn fails when Loom is unreachable.** `AssistantAgent` calls `update_context` once per turn, before its first model call, and does not catch its errors. diff --git a/docs/features/integrations/index.md b/docs/features/integrations/index.md index 644f72ed12..c012667fc4 100644 --- a/docs/features/integrations/index.md +++ b/docs/features/integrations/index.md @@ -12,31 +12,31 @@ opt-in; one you leave unconfigured does nothing. They fall into three groups: ## Map -| Integration | Kind | Where | -| ---------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | -| Claude Code | plugin: MCP tools, hooks, code shunt, skills | `integrations/claude-code-plugin/`: [claude-code.md](claude-code.md) | -| Codex | plugin: MCP tools, hooks, code shunt, skills | `integrations/codex-plugin/`: [codex.md](codex.md) | -| Claude Desktop, Cursor, VS Code, Cline, Windsurf, Zed | MCP client config | `loom install --client …`: [mcp-clients.md](mcp-clients.md) | -| VS Code agent mode | MCP tools | install links and `mcp.json`: [vscode.md](vscode.md) | -| Any MCP client without a plugin | an instruction block for the client's rule file | [agent-instructions.md](agent-instructions.md) | -| Gemini CLI | extension: MCP tools and the `loom`, `loom-code` skills | `gemini extensions install`: [mcp-clients.md](mcp-clients.md#other-editors-and-agents) | -| JetBrains, Visual Studio, Neovim, Emacs and other agents | MCP client config | [other editors and agents](mcp-clients.md#other-editors-and-agents) | -| Cline CLI (experimental) | hooks: session primer, prompt recall, a file's memories on a read | `integrations/cline/`: [README](../../../integrations/cline/README.md) | -| Cursor | MCP tools, skills (untested plugin) + `sessionEnd` capture hook | `.cursor-plugin/`, `integrations/cursor/`: [cursor.md](cursor.md) | -| Any Agent-Skills client | the `loom` and `loom-code` skills, no hooks | `skills/loom/`, `skills/loom-code/`: [below](#coding-agents) | -| Aider, Continue, OpenCode, JetBrains AI | transcript capture template | `integrations/generic/`: [below](#transcript-capture-hooks) | -| Agents that only use shell grep | the grep shim | `integrations/grep-shim/`: [grep-shim.md](grep-shim.md) | -| LibreChat v0.8.8 | chat client on the assistant toolset, per-user token | `integrations/librechat/`: [librechat.md](librechat.md) | -| LangChain, LlamaIndex, OpenAI Agents SDK, CrewAI, AutoGen, AG2, Pydantic AI, Mastra, AI SDK, LangGraph, Strands Agents | SDK retrievers, memory adapters and tools | `loom.integrations.*` in Python, `@clickhouse/loom/integrations/*` in TypeScript: [frameworks.md](frameworks.md) | -| Agent orchestrators | shared MCP mount | [frameworks.md](frameworks.md) | -| Agent Substrate | MCP through the egress gateway, per-agent token | [agent-substrate.md](agent-substrate.md) | -| AX (sandboxed agent tasks) | Workspace manifest: MCP config, `AGENTS.md`, run budget | `integrations/ax/`: [README](../../../integrations/ax/README.md) | -| Langfuse | traces, retrieval scores, erasure; needs Langfuse | [langfuse.md](langfuse.md) | -| ClickStack / HyperDX | OpenTelemetry spans, logs, metrics; erasure | [clickstack.md](clickstack.md) | -| Git repositories (OKF bundles) | export, import, CI lint gate | `integrations/okf-ci/`: [okf.md](okf.md) | -| Shell pipelines | `loom memory-search --json-agent` | [below](#command-line-search-for-pipelines) | -| Provider prompt caches | byte-stable `context.pack` prefix | [below](#prompt-caching) | -| GitHub | code index, PR history; needs the code workers enabled | [code index overview](../code-index/overview.md) | +| Integration | Kind | Where | +| ---------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| Claude Code | plugin: MCP tools, hooks, code shunt, skills | `integrations/claude-code-plugin/`: [claude-code.md](claude-code.md) | +| Codex | plugin: MCP tools, hooks, code shunt, skills | `integrations/codex-plugin/`: [codex.md](codex.md) | +| Claude Desktop, Cursor, VS Code, Cline, Windsurf, Zed | MCP client config | `loom install --client …`: [mcp-clients.md](mcp-clients.md) | +| VS Code agent mode | MCP tools | install links and `mcp.json`: [vscode.md](vscode.md) | +| Any MCP client without a plugin | an instruction block for the client's rule file | [agent-instructions.md](agent-instructions.md) | +| Gemini CLI | extension: MCP tools and the `loom`, `loom-code` skills | `gemini extensions install`: [mcp-clients.md](mcp-clients.md#other-editors-and-agents) | +| JetBrains, Visual Studio, Neovim, Emacs and other agents | MCP client config | [other editors and agents](mcp-clients.md#other-editors-and-agents) | +| Cline CLI (experimental) | hooks: session primer, prompt recall, a file's memories on a read | `integrations/cline/`: [README](../../../integrations/cline/README.md) | +| Cursor | MCP tools, skills (untested plugin) + `sessionEnd` capture hook | `.cursor-plugin/`, `integrations/cursor/`: [cursor.md](cursor.md) | +| Any Agent-Skills client | the `loom` and `loom-code` skills, no hooks | `skills/loom/`, `skills/loom-code/`: [below](#coding-agents) | +| Aider, Continue, OpenCode, JetBrains AI | transcript capture template | `integrations/generic/`: [below](#transcript-capture-hooks) | +| Agents that only use shell grep | the grep shim | `integrations/grep-shim/`: [grep-shim.md](grep-shim.md) | +| LibreChat v0.8.8 | chat client on the assistant toolset, per-user token | `integrations/librechat/`: [librechat.md](librechat.md) | +| LangChain, LlamaIndex, OpenAI Agents SDK, CrewAI, AutoGen, AG2, Google ADK, Pydantic AI, Mastra, AI SDK, LangGraph, Strands Agents | SDK retrievers, memory adapters and tools | `loom.integrations.*` in Python, `@clickhouse/loom/integrations/*` in TypeScript: [frameworks.md](frameworks.md) | +| Agent orchestrators | shared MCP mount | [frameworks.md](frameworks.md) | +| Agent Substrate | MCP through the egress gateway, per-agent token | [agent-substrate.md](agent-substrate.md) | +| AX (sandboxed agent tasks) | Workspace manifest: MCP config, `AGENTS.md`, run budget | `integrations/ax/`: [README](../../../integrations/ax/README.md) | +| Langfuse | traces, retrieval scores, erasure; needs Langfuse | [langfuse.md](langfuse.md) | +| ClickStack / HyperDX | OpenTelemetry spans, logs, metrics; erasure | [clickstack.md](clickstack.md) | +| Git repositories (OKF bundles) | export, import, CI lint gate | `integrations/okf-ci/`: [okf.md](okf.md) | +| Shell pipelines | `loom memory-search --json-agent` | [below](#command-line-search-for-pipelines) | +| Provider prompt caches | byte-stable `context.pack` prefix | [below](#prompt-caching) | +| GitHub | code index, PR history; needs the code workers enabled | [code index overview](../code-index/overview.md) | ## Coding agents diff --git a/docs/reference/python-sdk.md b/docs/reference/python-sdk.md index daed457946..d4e8c52e52 100644 --- a/docs/reference/python-sdk.md +++ b/docs/reference/python-sdk.md @@ -255,6 +255,11 @@ system prompt of an agent with no plugin; `part="reference"` lists every plane. assembly policy that adds the memories `memory.search` finds for the latest user message to the prompt, and `loom_tools(agent, user_id=...)` returns `AgentTools` as AG2 tools; install the `[ag2]` extra. +- `loom.integrations.google_adk.LoomMemoryService(agent)` is a Google ADK + `BaseMemoryService`: a saved session or turn goes to + `memory.set_from_messages`, `search_memory` is `memory.search` scoped to the + ADK app and user, and `delete_memory` is `memory.delete`; install the + `[google-adk]` extra. - `loom.integrations.pydantic_ai.loom_toolset(agent, user_id=...)` returns `AgentTools` as a Pydantic AI `FunctionToolset`; install the `[pydantic-ai]` extra. diff --git a/pyproject.toml b/pyproject.toml index ab417a3c47..33a3aebb36 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -263,6 +263,10 @@ module = [ "pydantic_ai.*", "ag2", "ag2.*", + "google.adk", + "google.adk.*", + "google.genai", + "google.genai.*", "langgraph", "langgraph.*", "strands", diff --git a/sdk/python/README.md b/sdk/python/README.md index 333814bb23..e6ff1c62f9 100644 --- a/sdk/python/README.md +++ b/sdk/python/README.md @@ -51,7 +51,7 @@ services. The `Agent` exposes 28 client modules: `client`, `account`, `deployment`, `assistant`, `memory`, `working_memory`, `knowledge`, `conversations`, `profile`, `context`, `facts`, `learnings`, `conflicts`, `blacklist`, `grants`, `erasure`, `cost`, `audit`, `namespaces`, `procedure`, `run`, `tasks`, `policy`, `decision`, `calibration`, `briefs`, `code`, `tracker`. Each of the named ones is the hand-written layer over a wire-op group on the Loom server (`account`, `deployment` and `assistant` cover the routes outside the op registry: service accounts, MCP setup, model settings, worker health, the assistant's streamed chat); `client` holds every served op as a generated method (below). -Framework adapters live under `loom.integrations`: LangChain retrievers (`pip install 'clickhouse-loom[langchain]'`), a LlamaIndex retriever and memory block (`[llamaindex]`), OpenAI Agents SDK tools (`[openai-agents]`), CrewAI crew memory (`[crewai]`), an AutoGen memory (`[autogen]`), an AG2 recall policy and tools (`[ag2]`), a Pydantic AI toolset (`[pydantic-ai]`), a LangGraph store and a Strands Agents memory store ([frameworks](https://github.com/ClickHouse/loom/blob/main/docs/features/integrations/frameworks.md)). +Framework adapters live under `loom.integrations`: LangChain retrievers (`pip install 'clickhouse-loom[langchain]'`), a LlamaIndex retriever and memory block (`[llamaindex]`), OpenAI Agents SDK tools (`[openai-agents]`), CrewAI crew memory (`[crewai]`), an AutoGen memory (`[autogen]`), an AG2 recall policy and tools (`[ag2]`), a Google ADK memory service (`[google-adk]`), a Pydantic AI toolset (`[pydantic-ai]`), a LangGraph store and a Strands Agents memory store ([frameworks](https://github.com/ClickHouse/loom/blob/main/docs/features/integrations/frameworks.md)). Full guide: [docs/reference/python-sdk.md](https://github.com/ClickHouse/loom/blob/main/docs/reference/python-sdk.md). Deployment paths (how an operator stands up the server): [docs/operations/deployment.md](https://github.com/ClickHouse/loom/blob/main/docs/operations/deployment.md). diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py new file mode 100644 index 0000000000..b50f6c28fb --- /dev/null +++ b/sdk/python/loom/integrations/google_adk.py @@ -0,0 +1,220 @@ +"""Loom as a Google ADK memory service. + +``LoomMemoryService`` implements ``google.adk.memory.BaseMemoryService``, the +service a ``Runner`` takes as ``memory_service=``. ADK's memory tools read it: +``preload_memory`` searches with the user's message before each model call, +``load_memory`` lets the model search. A callback saves a session or a turn:: + + from google.adk.agents import LlmAgent + from google.adk.runners import Runner + from google.adk.sessions import InMemorySessionService + from google.adk.tools import preload_memory + from loom import Agent + from loom.integrations.google_adk import LoomMemoryService + + + async def save_session(callback_context): + await callback_context.add_session_to_memory() + + + async with Agent(org="acme", namespace="support") as loom_agent: + runner = Runner( + app_name="support", + agent=LlmAgent( + name="assistant", + model="gemini-flash-latest", + tools=[preload_memory], + after_agent_callback=save_session, + ), + session_service=InMemorySessionService(), + memory_service=LoomMemoryService(loom_agent), + ) + +ADK scopes memory by app and user: the app name becomes the Loom ``agent`` of +each write and narrows each search, and the ADK user is the Loom ``user_id``. +The namespace and isolation come from the Loom agent. Install with +``pip install 'clickhouse-loom[google-adk]'``. +""" + +from __future__ import annotations + +import hashlib +from collections.abc import Mapping, Sequence +from datetime import UTC, datetime +from typing import TYPE_CHECKING + +try: + from google.adk.events import Event, get_active_events + from google.adk.memory import BaseMemoryService + from google.adk.memory.base_memory_service import SearchMemoryResponse + from google.adk.memory.memory_entry import MemoryEntry + from google.adk.sessions import Session + from google.genai import types +except ImportError as e: # the framework is an optional extra + raise ImportError( + "loom.integrations.google_adk needs google-adk: pip install 'clickhouse-loom[google-adk]'" + ) from e + +from loom.sync import SyncAgent + +if TYPE_CHECKING: + from loom.agent import Agent + from loom.memory import MemorySearchHit + + +class LoomMemoryService(BaseMemoryService): + """ADK ``BaseMemoryService`` over a Loom ``Agent``. + + ``add_session_to_memory`` and ``add_events_to_memory`` send the text of the + events to ``memory.set_from_messages``, where Loom extracts the facts and + resolves duplicates and conflicts; a session added again is extracted + again, so a callback that runs every turn should add only that turn's + events. Events a rewind took back are left out. ``add_memory`` writes each + entry with ``memory.set`` under a key derived from its text + (``/``), its ``timestamp`` as the + memory's ``valid_at``. ``search_memory`` runs ``memory.search`` of the + namespace it writes to; with ``honour_abstain`` it leaves out memories + below Loom's floor and returns nothing when Loom abstains. A returned + entry's ``id`` is the Loom key ``delete_memory`` deletes: the memory's, or + for a verbatim chunk the memory it was written under. A session summary + has no key (``id`` is None); Loom's erasure removes it. + ``custom_metadata`` is not kept. ADK awaits its memory service, so the + service takes a ``loom.Agent``. + """ + + def __init__( + self, + agent: Agent, + *, + top_k: int = 10, + honour_abstain: bool = True, + defer: bool = True, + key_prefix: str = "adk", + ) -> None: + if isinstance(agent, SyncAgent): + raise TypeError("LoomMemoryService needs a loom.Agent: ADK awaits its memory service") + if not 1 <= top_k <= 500: # memory.search's bounds + raise ValueError("top_k must be between 1 and 500") + self._agent = agent + self._top_k = top_k + self._honour_abstain = honour_abstain + self._defer = defer + self._key_prefix = key_prefix.strip("/") or "adk" + + async def add_session_to_memory(self, session: Session) -> None: + await self._extract( + session.app_name, session.user_id, session.id, get_active_events(session.events) + ) + + async def add_events_to_memory( + self, + *, + app_name: str, + user_id: str, + events: Sequence[Event], + session_id: str | None = None, + custom_metadata: Mapping[str, object] | None = None, + ) -> None: + await self._extract(app_name, user_id, session_id, events) + + async def add_memory( + self, + *, + app_name: str, + user_id: str, + memories: Sequence[MemoryEntry], + custom_metadata: Mapping[str, object] | None = None, + ) -> None: + for memory in memories: + text = _text(memory.content) + if not text: + continue + digest = hashlib.sha256(text.encode("utf-8")).hexdigest()[:20] + await self._agent.memory.set( + f"{self._key_prefix}/{digest}", + text, + user_id=user_id, + agent_id=app_name, + valid_at=datetime.fromisoformat(memory.timestamp) if memory.timestamp else None, + ) + + async def search_memory( + self, *, app_name: str, user_id: str, query: str + ) -> SearchMemoryResponse: + if not query.strip(): + return SearchMemoryResponse() + result = await self._agent.memory.search( + query, + top_k=self._top_k, + user_id=user_id, + agent_id=app_name, + # Read the namespace this service writes to, whatever the deployment's default. + namespace_scope="this", + # Unpinned, a large top_k serves excerpts (above 15 by default) + # and drops each hit's explanation. + bodies="full", + explain=False, + ) + hits = list(result) + if self._honour_abstain: + if result.abstain: + return SearchMemoryResponse() + # A response that does not abstain can still carry rows below the floor. + hits = [hit for hit in hits if not hit.below_threshold] + return SearchMemoryResponse( + memories=[ + MemoryEntry( + id=_deletable_key(hit), + content=types.Content( + role="user", parts=[types.Part(text=hit.content_excerpt)] + ), + custom_metadata={"similarity": hit.similarity, "source": hit.source}, + timestamp=hit.valid_at or None, + ) + # Derived rows may come back above the top_k slice: cut after filtering. + for hit in hits[: self._top_k] + ] + ) + + async def delete_memory( + self, *, app_name: str, user_id: str, memory_id: str | None = None + ) -> None: + if not memory_id: + raise ValueError("delete_memory needs the memory_id a search returned") + await self._agent.memory.delete(memory_id, user_id=user_id) + + async def _extract( + self, app_name: str, user_id: str, session_id: str | None, events: Sequence[Event] + ) -> None: + messages: list[dict[str, object]] = [] + for event in events: + text = _text(event.content) + if text: + messages.append( + { + "role": "user" if event.author == "user" else "assistant", + "content": text, + "timestamp": datetime.fromtimestamp(event.timestamp, UTC).isoformat(), + } + ) + if messages: + await self._agent.memory.set_from_messages( + messages, + user_id=user_id, + session_id=session_id, + agent_id=app_name, + defer=self._defer, + ) + + +def _deletable_key(hit: MemorySearchHit) -> str | None: + if hit.source == "fact": + return hit.memory_key + return hit.parent_memory_key or None + + +def _text(content: types.Content | None) -> str: + """The text of a content, without the model's thoughts or tool calls.""" + if content is None or not content.parts: + return "" + return " ".join(p.text for p in content.parts if p.text and not p.thought).strip() diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml index 4e707a6563..2f23597bc8 100644 --- a/sdk/python/pyproject.toml +++ b/sdk/python/pyproject.toml @@ -69,6 +69,9 @@ pydantic-ai = ["pydantic-ai-slim>=2.68,<3"] # AG2 1.3 has the assembly policies and tool(schema=...) the adapter uses; AG2 changes # its agent and tool APIs between minor versions. ag2 = ["ag2>=1.3,<1.4"] +# ADK 2.14 has get_active_events and the memory service's add_memory and delete_memory; +# 3.0 may change the memory service. +google-adk = ["google-adk>=2.14,<3"] [project.urls] Homepage = "https://clickhouse.github.io/loom/" diff --git a/sdk/python/tests/test_google_adk.py b/sdk/python/tests/test_google_adk.py new file mode 100644 index 0000000000..1798c18d31 --- /dev/null +++ b/sdk/python/tests/test_google_adk.py @@ -0,0 +1,294 @@ +"""LoomMemoryService: ADK's memory service over a fake Loom agent — what each +method sends, abstention, and what an ADK Runner's model sees through +preload_memory and load_memory.""" + +from __future__ import annotations + +import asyncio +from collections.abc import AsyncGenerator +from typing import Any + +import pytest +from google.adk.agents import LlmAgent +from google.adk.memory import BaseMemoryService +from google.adk.memory.memory_entry import MemoryEntry +from google.adk.models.base_llm import BaseLlm +from google.adk.models.llm_request import LlmRequest +from google.adk.models.llm_response import LlmResponse +from google.adk.runners import Runner +from google.adk.sessions import InMemorySessionService +from google.adk.tools import load_memory, preload_memory +from google.genai import types +from loom import SyncAgent +from loom.integrations.google_adk import LoomMemoryService +from loom.memory import MemorySearchHit, MemorySearchResult +from pydantic import Field + + +class _FakeMemory: + def __init__(self, hits: list[MemorySearchHit] | None = None, abstain: bool = False) -> None: + self.calls: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = [] + self._hits = hits or [] + self._abstain = abstain + + async def search(self, query: str, **kw: Any) -> MemorySearchResult: + self.calls.append(("search", (query,), kw)) + result = MemorySearchResult(self._hits) + result.abstain = self._abstain + return result + + async def set(self, key: str, value: str, **kw: Any) -> dict[str, Any]: + self.calls.append(("set", (key, value), kw)) + return {} + + async def set_from_messages(self, messages: list[dict[str, object]], **kw: Any) -> dict: + self.calls.append(("set_from_messages", (messages,), kw)) + return {} + + async def delete(self, key: str, **kw: Any) -> bool: + self.calls.append(("delete", (key,), kw)) + return True + + +class _Agent: + def __init__(self, memory: _FakeMemory) -> None: + self.memory = memory + + +class _ScriptedLlm(BaseLlm): + """Answers each model call with the next scripted content; keeps the requests.""" + + model: str = "scripted" + script: list[types.Content] = Field(default_factory=list) + requests: list[LlmRequest] = Field(default_factory=list) + + async def generate_content_async( + self, llm_request: LlmRequest, stream: bool = False + ) -> AsyncGenerator[LlmResponse, None]: + self.requests.append(llm_request) + yield LlmResponse(content=self.script.pop(0)) + + +def _hit(key: str, text: str, **kw: Any) -> MemorySearchHit: + return MemorySearchHit( + memory_key=key, memory_type="semantic", content_excerpt=text, similarity=0.9, **kw + ) + + +def _model(text: str) -> types.Content: + return types.Content(role="model", parts=[types.Part(text=text)]) + + +def _service(fake: _FakeMemory, **kw: Any) -> LoomMemoryService: + return LoomMemoryService(_Agent(fake), **kw) # type: ignore[arg-type] + + +async def _run( + service: LoomMemoryService, llm: _ScriptedLlm, *texts: str, **agent_kw: Any +) -> InMemorySessionService: + sessions = InMemorySessionService() + runner = Runner( + app_name="travel", + agent=LlmAgent(name="assistant", model=llm, **agent_kw), + session_service=sessions, + memory_service=service, + ) + session = await sessions.create_session(app_name="travel", user_id="alice") + for text in texts: + message = types.Content(role="user", parts=[types.Part(text=text)]) + async for _ in runner.run_async( + user_id="alice", session_id=session.id, new_message=message + ): + pass + return sessions + + +def _prompt(request: LlmRequest) -> str: + return " ".join(p.text or "" for c in request.contents for p in c.parts or []) + + +def test_it_is_an_adk_memory_service() -> None: + assert issubclass(LoomMemoryService, BaseMemoryService) + + +def test_it_refuses_a_sync_agent_and_a_top_k_out_of_bounds() -> None: + with pytest.raises(TypeError, match="ADK awaits"): + LoomMemoryService(SyncAgent(org="o", namespace="n", base_url="http://127.0.0.1:9")) + for top_k in (0, 501): + with pytest.raises(ValueError, match="top_k"): + _service(_FakeMemory(), top_k=top_k) + + +def test_preload_memory_puts_the_matches_in_the_prompt() -> None: + fake = _FakeMemory([_hit("adk/1", "Alice prefers aisle seats", valid_at="2026-11-01")]) + llm = _ScriptedLlm(script=[_model("An aisle seat.")]) + asyncio.run(_run(_service(fake), llm, "Which seat for alice?", tools=[preload_memory])) + (search,) = [c for c in fake.calls if c[0] == "search"] + assert search[1] == ("Which seat for alice?",) + assert search[2] == { + "top_k": 10, + "user_id": "alice", + "agent_id": "travel", + "namespace_scope": "this", + "bodies": "full", + "explain": False, + } + prompt = _prompt(llm.requests[0]) + assert "Alice prefers aisle seats" in prompt and "Time: 2026-11-01" in prompt + + +def test_the_model_reads_load_memory_results() -> None: + fake = _FakeMemory([_hit("adk/1", "Alice prefers aisle seats")]) + call = types.Content( + role="model", + parts=[ + types.Part(function_call=types.FunctionCall(name="load_memory", args={"query": "seat"})) + ], + ) + llm = _ScriptedLlm(script=[call, _model("An aisle seat.")]) + asyncio.run(_run(_service(fake), llm, "Which seat?", tools=[load_memory])) + (response,) = [ + p.function_response + for c in llm.requests[1].contents + for p in c.parts or [] + if p.function_response + ] + (memory,) = response.response["result"].memories + assert memory.id == "adk/1" + assert memory.content.parts[0].text == "Alice prefers aisle seats" + + +def test_search_leaves_out_rows_below_the_floor_and_an_abstention() -> None: + hits = [_hit("adk/1", "kept"), _hit("adk/2", "weak", below_threshold=True)] + found = asyncio.run( + _service(_FakeMemory(hits)).search_memory(app_name="a", user_id="u", query="q") + ) + assert [m.id for m in found.memories] == ["adk/1"] + everything = _service(_FakeMemory(hits), honour_abstain=False) + found = asyncio.run(everything.search_memory(app_name="a", user_id="u", query="q")) + assert [m.id for m in found.memories] == ["adk/1", "adk/2"] + abstained = _service(_FakeMemory(hits, abstain=True)) + assert not asyncio.run(abstained.search_memory(app_name="a", user_id="u", query="q")).memories + + +def test_search_cuts_to_top_k_and_skips_an_empty_query() -> None: + fake = _FakeMemory([_hit(f"adk/{i}", f"fact {i}") for i in range(4)]) + found = asyncio.run(_service(fake, top_k=2).search_memory(app_name="a", user_id="u", query="q")) + assert [m.id for m in found.memories] == ["adk/0", "adk/1"] + assert not asyncio.run( + _service(fake).search_memory(app_name="a", user_id="u", query=" ") + ).memories + assert len(fake.calls) == 1 + + +def test_a_saved_session_goes_to_extraction() -> None: + fake = _FakeMemory() + + async def save(callback_context: Any) -> None: + await callback_context.add_session_to_memory() + + llm = _ScriptedLlm(script=[_model("Noted.")]) + sessions = asyncio.run( + _run(_service(fake), llm, "I prefer aisle seats", after_agent_callback=save) + ) + (extract,) = [c for c in fake.calls if c[0] == "set_from_messages"] + (session,) = asyncio.run(sessions.list_sessions(app_name="travel", user_id="alice")).sessions + messages = extract[1][0] + assert [(m["role"], m["content"]) for m in messages] == [ + ("user", "I prefer aisle seats"), + ("assistant", "Noted."), + ] + assert all(str(m["timestamp"]).endswith("+00:00") for m in messages) + assert extract[2] == { + "user_id": "alice", + "session_id": session.id, + "agent_id": "travel", + "defer": True, + } + + +def test_extraction_leaves_out_thoughts_tool_calls_and_rewound_turns() -> None: + from google.adk.events import Event, EventActions + from google.adk.sessions import Session + + def event(inv: str, author: str, *parts: types.Part, **kw: Any) -> Event: + return Event( + invocation_id=inv, author=author, content=types.Content(parts=list(parts)), **kw + ) + + session = Session( + id="s1", + app_name="travel", + user_id="alice", + events=[ + event("i1", "user", types.Part(text="I live in Lisbon")), + event( + "i1", + "assistant", + types.Part(text="planning", thought=True), + types.Part(function_call=types.FunctionCall(name="f", args={})), + types.Part(text="Lisbon it is"), + ), + event("i2", "user", types.Part(text="Actually Porto")), + Event( + invocation_id="i3", + author="user", + actions=EventActions(rewind_before_invocation_id="i2"), + ), + ], + ) + fake = _FakeMemory() + asyncio.run(_service(fake).add_session_to_memory(session)) + (extract,) = fake.calls + assert [m["content"] for m in extract[1][0]] == ["I live in Lisbon", "Lisbon it is"] + + +def test_events_without_text_send_nothing() -> None: + from google.adk.events import Event + + fake = _FakeMemory() + silent = Event(author="user", content=types.Content(parts=[types.Part(text=" ")])) + asyncio.run( + _service(fake, defer=False).add_events_to_memory(app_name="a", user_id="u", events=[silent]) + ) + assert fake.calls == [] + + +def test_add_memory_writes_content_keyed_memories() -> None: + fake = _FakeMemory() + entries = [ + MemoryEntry( + content=_model("Alice prefers aisle seats"), timestamp="2026-11-01T09:00:00+00:00" + ), + MemoryEntry(content=_model(" Alice prefers aisle seats ")), + MemoryEntry(content=types.Content(parts=[types.Part(text="hidden", thought=True)])), + ] + asyncio.run(_service(fake).add_memory(app_name="travel", user_id="alice", memories=entries)) + (first, again) = fake.calls + assert first[1][0] == again[1][0] and first[1][0].startswith("adk/") + assert first[1][1] == "Alice prefers aisle seats" + assert first[2]["user_id"] == "alice" and first[2]["agent_id"] == "travel" + assert first[2]["valid_at"].isoformat() == "2026-11-01T09:00:00+00:00" + assert again[2]["valid_at"] is None + + +def test_delete_memory_deletes_the_key_and_needs_one() -> None: + fake = _FakeMemory() + service = _service(fake) + asyncio.run(service.delete_memory(app_name="travel", user_id="alice", memory_id="adk/1")) + assert fake.calls == [("delete", ("adk/1",), {"user_id": "alice"})] + with pytest.raises(ValueError, match="memory_id"): + asyncio.run(service.delete_memory(app_name="travel", user_id="alice")) + + +def test_an_entry_id_is_the_key_delete_memory_deletes() -> None: + hits = [ + _hit("adk/1", "a fact"), + _hit("chunk:s1:0", "a turn", source="chunk", parent_memory_key="adk/1"), + _hit("summary:s1", "a session", source="summary"), + ] + found = asyncio.run( + _service(_FakeMemory(hits)).search_memory(app_name="a", user_id="u", query="q") + ) + assert [m.id for m in found.memories] == ["adk/1", "adk/1", None] + assert [m.custom_metadata["source"] for m in found.memories] == ["fact", "chunk", "summary"] diff --git a/tests/integration/test_sdk_google_adk_memory.py b/tests/integration/test_sdk_google_adk_memory.py new file mode 100644 index 0000000000..7e887a0055 --- /dev/null +++ b/tests/integration/test_sdk_google_adk_memory.py @@ -0,0 +1,103 @@ +"""LoomMemoryService against a running Loom: a session an ADK Runner saves is +extracted, and preload_memory puts it in a later session's prompt for the same +app and user only; a memory, extracted or explicit, is deleted by the id a search +returned.""" + +from __future__ import annotations + +from collections.abc import AsyncGenerator +from typing import Any + +import pytest + +from tests.integration._eventually import eventually + +# An SDK extra, outside the server's environment: install google-adk to run these. +pytest.importorskip("google.adk") + +from google.adk.agents import LlmAgent +from google.adk.memory.memory_entry import MemoryEntry +from google.adk.models.base_llm import BaseLlm +from google.adk.models.llm_request import LlmRequest +from google.adk.models.llm_response import LlmResponse +from google.adk.runners import Runner +from google.adk.sessions import InMemorySessionService +from google.adk.tools import preload_memory +from google.genai import types +from loom.integrations.google_adk import LoomMemoryService +from pydantic import Field + + +class _EchoLlm(BaseLlm): + """Answers "Noted." to every call and keeps the requests.""" + + model: str = "echo" + requests: list[LlmRequest] = Field(default_factory=list) + + async def generate_content_async( + self, llm_request: LlmRequest, stream: bool = False + ) -> AsyncGenerator[LlmResponse, None]: + self.requests.append(llm_request) + yield LlmResponse(content=types.Content(role="model", parts=[types.Part(text="Noted.")])) + + +async def _save(callback_context: Any) -> None: + await callback_context.add_session_to_memory() + + +async def _turn(service: LoomMemoryService, app: str, user: str, text: str) -> str: + """One turn in a new session; returns the text of the model's prompt.""" + llm = _EchoLlm() + sessions = InMemorySessionService() + runner = Runner( + app_name=app, + agent=LlmAgent( + name="assistant", model=llm, tools=[preload_memory], after_agent_callback=_save + ), + session_service=sessions, + memory_service=service, + ) + session = await sessions.create_session(app_name=app, user_id=user) + message = types.Content(role="user", parts=[types.Part(text=text)]) + async for _ in runner.run_async(user_id=user, session_id=session.id, new_message=message): + pass + return " ".join(p.text or "" for c in llm.requests[0].contents for p in c.parts or []) + + +async def test_a_saved_session_reaches_a_later_prompt(agent) -> None: + # defer=False: extraction inline, since the test server runs no background workers + service = LoomMemoryService(agent, honour_abstain=False, defer=False) + await _turn(service, "travel", "alice", "I fly to Lisbon every month.") + + async def recalled() -> bool: + prompt = await _turn(service, "travel", "alice", "Where does Alice fly every month?") + return "lisbon" in prompt.lower() + + # A write is searchable once its embedding lands; eventually raises on timeout. + await eventually(recalled, description="'lisbon' in the next session's prompt") + for app, user in (("travel", "bob"), ("billing", "alice")): + found = await service.search_memory(app_name=app, user_id=user, query="Lisbon") + assert not found.memories, (app, user) + # The extracted facts carry the session; the ids a search returns still delete them. + found = await service.search_memory(app_name="travel", user_id="alice", query="Lisbon") + facts = {m.id for m in found.memories if m.custom_metadata["source"] == "fact"} + assert facts + for memory_id in facts: + await service.delete_memory(app_name="travel", user_id="alice", memory_id=memory_id) + found = await service.search_memory(app_name="travel", user_id="alice", query="Lisbon") + assert not {m.id for m in found.memories if m.custom_metadata["source"] == "fact"} & facts + + +async def test_add_memory_then_delete_by_id(agent) -> None: + service = LoomMemoryService(agent, honour_abstain=False) + entry = MemoryEntry(content=types.Content(parts=[types.Part(text="Alice prefers aisle seats")])) + await service.add_memory(app_name="travel", user_id="alice", memories=[entry]) + + async def ids() -> list[str | None]: + found = await service.search_memory(app_name="travel", user_id="alice", query="aisle seat") + return [m.id for m in found.memories] + + await eventually(ids, description="the memory found") + (memory_id,) = await ids() + await service.delete_memory(app_name="travel", user_id="alice", memory_id=memory_id) + assert await ids() == [] From 5a3ca9505aa531750526ce26759086fb40813325 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 15 Nov 2026 08:50:01 +0000 Subject: [PATCH 02/21] ADK delete_memory deletes only its own app's row; save each turn once delete_memory reads the version under the exact app and user and deletes that version, since memory.delete falls back to any agent's row of the key. Rows carry no session, so the exact identity addresses them. The example saves each turn's events instead of the whole session every turn. A non-ISO timestamp leaves valid_at unset; an empty key_prefix is refused. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/integrations/frameworks.md | 32 ++++---- sdk/python/loom/integrations/google_adk.py | 58 ++++++++++----- sdk/python/tests/test_google_adk.py | 74 +++++++++++++++---- .../integration/test_sdk_google_adk_memory.py | 36 +++++---- 4 files changed, 135 insertions(+), 65 deletions(-) diff --git a/docs/features/integrations/frameworks.md b/docs/features/integrations/frameworks.md index 5474101e69..ebe6c3148c 100644 --- a/docs/features/integrations/frameworks.md +++ b/docs/features/integrations/frameworks.md @@ -348,7 +348,7 @@ request out of the events the policy reads. Those policies trim events, not the `LoomMemoryService` implements ADK's `BaseMemoryService`, which a `Runner` takes as `memory_service=`. ADK's own memory tools read it: `preload_memory` searches with the user's message before each model call and adds the matches to the prompt, and -`load_memory` lets the model search. A callback saves a session or a turn. Install with +`load_memory` lets the model search. A callback saves each turn. Install with `pip install 'clickhouse-loom[google-adk]'` (`google-adk` 2.14 or later 2.x). ```python @@ -360,8 +360,9 @@ from loom import Agent from loom.integrations.google_adk import LoomMemoryService -async def save_session(callback_context): - await callback_context.add_session_to_memory() +async def save_turn(ctx): + turn = [e for e in ctx.session.events if e.invocation_id == ctx.invocation_id] + await ctx.add_events_to_memory(events=turn) async with Agent(org="acme", namespace="support") as loom_agent: @@ -371,7 +372,7 @@ async with Agent(org="acme", namespace="support") as loom_agent: name="assistant", model="gemini-flash-latest", tools=[preload_memory], - after_agent_callback=save_session, + after_agent_callback=save_turn, ), session_service=InMemorySessionService(), memory_service=LoomMemoryService(loom_agent), @@ -379,16 +380,17 @@ async with Agent(org="acme", namespace="support") as loom_agent: ``` ADK scopes memory by app and user. The app name is the Loom `agent` of every write and -narrows every search, and the ADK user is the Loom `user_id`; a search reads every session -of that user. The namespace comes from the Loom agent. - -| ADK | Loom | -| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages` with the session id; Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn should save that turn's events | -| `add_events_to_memory` | the same for the events given, such as the latest turn | -| `add_memory` | one `memory.set` per entry under `adk/`, its `timestamp` as the memory's `valid_at` | -| `search_memory` | `memory.search` of the namespace it writes to; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | -| `delete_memory` | `memory.delete` of the entry's `id`: the memory's key, or for a verbatim chunk the key of the memory it was written under. A session summary has no `id`; [erasure](../memory/retention-and-erasure.md) removes it | +narrows every search, and the ADK user is the Loom `user_id`. ADK's memory spans sessions, +so rows carry no session and a search reads all of the user's memories in the app. The +namespace comes from the Loom agent. + +| ADK | Loom | +| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages`; Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | +| `add_events_to_memory` | the same for the events given, such as the latest turn | +| `add_memory` | one `memory.set` per entry under `adk/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 | +| `search_memory` | `memory.search` of the namespace it writes to; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | +| `delete_memory` | the entry's `id` deleted in the app and user given, never another app's row of the same key: the memory's key, or for a verbatim chunk the key of the memory it was written under. An entry Loom cannot delete by key, such as a session summary, has no `id`; [erasure](../memory/retention-and-erasure.md) removes it | Events keep their text parts only: the model's thoughts and tool calls and results are not sent, and neither is `custom_metadata`. @@ -399,7 +401,7 @@ sent, and neither is `custom_metadata`. | `top_k` | 10 | memories per search, from 1 to 500 | | `honour_abstain` | `True` | leave out memories below Loom's floor; nothing when Loom abstains | | `defer` | `True` | queue the extraction on the server instead of waiting for it | -| `key_prefix` | `adk` | the prefix of `add_memory`'s keys | +| `key_prefix` | `adk` | the prefix of `add_memory`'s keys; an empty one is refused | ## Pydantic AI diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py index b50f6c28fb..db48e08c23 100644 --- a/sdk/python/loom/integrations/google_adk.py +++ b/sdk/python/loom/integrations/google_adk.py @@ -3,7 +3,7 @@ ``LoomMemoryService`` implements ``google.adk.memory.BaseMemoryService``, the service a ``Runner`` takes as ``memory_service=``. ADK's memory tools read it: ``preload_memory`` searches with the user's message before each model call, -``load_memory`` lets the model search. A callback saves a session or a turn:: +``load_memory`` lets the model search. A callback saves each turn:: from google.adk.agents import LlmAgent from google.adk.runners import Runner @@ -13,8 +13,9 @@ from loom.integrations.google_adk import LoomMemoryService - async def save_session(callback_context): - await callback_context.add_session_to_memory() + async def save_turn(ctx): + turn = [e for e in ctx.session.events if e.invocation_id == ctx.invocation_id] + await ctx.add_events_to_memory(events=turn) async with Agent(org="acme", namespace="support") as loom_agent: @@ -24,7 +25,7 @@ async def save_session(callback_context): name="assistant", model="gemini-flash-latest", tools=[preload_memory], - after_agent_callback=save_session, + after_agent_callback=save_turn, ), session_service=InMemorySessionService(), memory_service=LoomMemoryService(loom_agent), @@ -32,7 +33,8 @@ async def save_session(callback_context): ADK scopes memory by app and user: the app name becomes the Loom ``agent`` of each write and narrows each search, and the ADK user is the Loom ``user_id``. -The namespace and isolation come from the Loom agent. Install with +ADK's memory spans sessions, so rows carry no session. The namespace and +isolation come from the Loom agent. Install with ``pip install 'clickhouse-loom[google-adk]'``. """ @@ -72,12 +74,13 @@ class LoomMemoryService(BaseMemoryService): events. Events a rewind took back are left out. ``add_memory`` writes each entry with ``memory.set`` under a key derived from its text (``/``), its ``timestamp`` as the - memory's ``valid_at``. ``search_memory`` runs ``memory.search`` of the + memory's ``valid_at`` when it is ISO 8601. ``search_memory`` runs ``memory.search`` of the namespace it writes to; with ``honour_abstain`` it leaves out memories below Loom's floor and returns nothing when Loom abstains. A returned - entry's ``id`` is the Loom key ``delete_memory`` deletes: the memory's, or - for a verbatim chunk the memory it was written under. A session summary - has no key (``id`` is None); Loom's erasure removes it. + entry's ``id`` is the Loom key ``delete_memory`` deletes, in the app and + user given: the memory's, or for a verbatim chunk the memory it was + written under. An entry Loom cannot delete by key, such as a session + summary, has no ``id``; Loom's erasure removes it. ``custom_metadata`` is not kept. ADK awaits its memory service, so the service takes a ``loom.Agent``. """ @@ -99,12 +102,12 @@ def __init__( self._top_k = top_k self._honour_abstain = honour_abstain self._defer = defer - self._key_prefix = key_prefix.strip("/") or "adk" + if not key_prefix.strip("/"): + raise ValueError("key_prefix must not be empty") + self._key_prefix = key_prefix.strip("/") async def add_session_to_memory(self, session: Session) -> None: - await self._extract( - session.app_name, session.user_id, session.id, get_active_events(session.events) - ) + await self._extract(session.app_name, session.user_id, get_active_events(session.events)) async def add_events_to_memory( self, @@ -115,7 +118,7 @@ async def add_events_to_memory( session_id: str | None = None, custom_metadata: Mapping[str, object] | None = None, ) -> None: - await self._extract(app_name, user_id, session_id, events) + await self._extract(app_name, user_id, events) async def add_memory( self, @@ -135,7 +138,7 @@ async def add_memory( text, user_id=user_id, agent_id=app_name, - valid_at=datetime.fromisoformat(memory.timestamp) if memory.timestamp else None, + valid_at=_iso_time(memory.timestamp), ) async def search_memory( @@ -181,11 +184,19 @@ async def delete_memory( ) -> None: if not memory_id: raise ValueError("delete_memory needs the memory_id a search returned") - await self._agent.memory.delete(memory_id, user_id=user_id) + # memory.delete falls back to the key under any agent, which could be another + # app's row. Read the version this app's row holds, then delete that version + # under the exact identity; a row of another app is never touched. + row = await self._agent.memory.get(memory_id, user_id=user_id, agent_id=app_name) + if row is not None: + await self._agent.call( + "memory.delete_version", + {"memory_key": memory_id, "version": row["version"]}, + user_id=user_id, + agent_id=app_name, + ) - async def _extract( - self, app_name: str, user_id: str, session_id: str | None, events: Sequence[Event] - ) -> None: + async def _extract(self, app_name: str, user_id: str, events: Sequence[Event]) -> None: messages: list[dict[str, object]] = [] for event in events: text = _text(event.content) @@ -201,7 +212,6 @@ async def _extract( await self._agent.memory.set_from_messages( messages, user_id=user_id, - session_id=session_id, agent_id=app_name, defer=self._defer, ) @@ -213,6 +223,14 @@ def _deletable_key(hit: MemorySearchHit) -> str | None: return hit.parent_memory_key or None +def _iso_time(text: str | None) -> datetime | None: + """An ISO 8601 timestamp; ADK allows any text, which is not a ``valid_at``.""" + try: + return datetime.fromisoformat(text) if text else None + except ValueError: + return None + + def _text(content: types.Content | None) -> str: """The text of a content, without the model's thoughts or tool calls.""" if content is None or not content.parts: diff --git a/sdk/python/tests/test_google_adk.py b/sdk/python/tests/test_google_adk.py index 1798c18d31..bcf8aaf274 100644 --- a/sdk/python/tests/test_google_adk.py +++ b/sdk/python/tests/test_google_adk.py @@ -30,6 +30,7 @@ def __init__(self, hits: list[MemorySearchHit] | None = None, abstain: bool = Fa self.calls: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = [] self._hits = hits or [] self._abstain = abstain + self.rows: dict[str, dict[str, Any]] = {} async def search(self, query: str, **kw: Any) -> MemorySearchResult: self.calls.append(("search", (query,), kw)) @@ -45,15 +46,19 @@ async def set_from_messages(self, messages: list[dict[str, object]], **kw: Any) self.calls.append(("set_from_messages", (messages,), kw)) return {} - async def delete(self, key: str, **kw: Any) -> bool: - self.calls.append(("delete", (key,), kw)) - return True + async def get(self, key: str, **kw: Any) -> dict[str, Any] | None: + self.calls.append(("get", (key,), kw)) + return self.rows.get(key) class _Agent: def __init__(self, memory: _FakeMemory) -> None: self.memory = memory + async def call(self, op: str, body: dict[str, Any], **kw: Any) -> dict[str, Any]: + self.memory.calls.append((op, (body,), kw)) + return {} + class _ScriptedLlm(BaseLlm): """Answers each model call with the next scripted content; keeps the requests.""" @@ -111,12 +116,15 @@ def test_it_is_an_adk_memory_service() -> None: assert issubclass(LoomMemoryService, BaseMemoryService) -def test_it_refuses_a_sync_agent_and_a_top_k_out_of_bounds() -> None: +def test_it_refuses_a_sync_agent_a_top_k_out_of_bounds_and_an_empty_prefix() -> None: with pytest.raises(TypeError, match="ADK awaits"): LoomMemoryService(SyncAgent(org="o", namespace="n", base_url="http://127.0.0.1:9")) for top_k in (0, 501): with pytest.raises(ValueError, match="top_k"): _service(_FakeMemory(), top_k=top_k) + for prefix in ("", "/"): + with pytest.raises(ValueError, match="key_prefix"): + _service(_FakeMemory(), key_prefix=prefix) def test_preload_memory_puts_the_matches_in_the_prompt() -> None: @@ -188,23 +196,37 @@ async def save(callback_context: Any) -> None: await callback_context.add_session_to_memory() llm = _ScriptedLlm(script=[_model("Noted.")]) - sessions = asyncio.run( - _run(_service(fake), llm, "I prefer aisle seats", after_agent_callback=save) - ) + asyncio.run(_run(_service(fake), llm, "I prefer aisle seats", after_agent_callback=save)) (extract,) = [c for c in fake.calls if c[0] == "set_from_messages"] - (session,) = asyncio.run(sessions.list_sessions(app_name="travel", user_id="alice")).sessions messages = extract[1][0] assert [(m["role"], m["content"]) for m in messages] == [ ("user", "I prefer aisle seats"), ("assistant", "Noted."), ] assert all(str(m["timestamp"]).endswith("+00:00") for m in messages) - assert extract[2] == { - "user_id": "alice", - "session_id": session.id, - "agent_id": "travel", - "defer": True, - } + # ADK's memory spans sessions: the rows carry none, so a delete can address them. + assert extract[2] == {"user_id": "alice", "agent_id": "travel", "defer": True} + + +def test_the_documented_turn_callback_sends_each_turn_once() -> None: + fake = _FakeMemory() + + async def save_turn(ctx: Any) -> None: + turn = [e for e in ctx.session.events if e.invocation_id == ctx.invocation_id] + await ctx.add_events_to_memory(events=turn) + + llm = _ScriptedLlm(script=[_model("Noted."), _model("Lisbon, then.")]) + asyncio.run( + _run( + _service(fake), + llm, + "I prefer aisle seats", + "I fly to Lisbon", + after_agent_callback=save_turn, + ) + ) + sent = [[m["content"] for m in c[1][0]] for c in fake.calls if c[0] == "set_from_messages"] + assert sent == [["I prefer aisle seats", "Noted."], ["I fly to Lisbon", "Lisbon, then."]] def test_extraction_leaves_out_thoughts_tool_calls_and_rewound_turns() -> None: @@ -272,11 +294,31 @@ def test_add_memory_writes_content_keyed_memories() -> None: assert again[2]["valid_at"] is None -def test_delete_memory_deletes_the_key_and_needs_one() -> None: +def test_a_timestamp_that_is_not_iso_is_no_valid_at() -> None: + fake = _FakeMemory() + entry = MemoryEntry(content=_model("Alice moved to Porto"), timestamp="last spring") + asyncio.run(_service(fake).add_memory(app_name="travel", user_id="alice", memories=[entry])) + ((_, _, kw),) = fake.calls + assert kw["valid_at"] is None + + +def test_delete_memory_deletes_this_apps_version_of_the_key() -> None: + fake = _FakeMemory() + fake.rows["adk/1"] = {"memory_key": "adk/1", "version": 7} + service = _service(fake) + asyncio.run(service.delete_memory(app_name="travel", user_id="alice", memory_id="adk/1")) + scope = {"user_id": "alice", "agent_id": "travel"} + assert fake.calls == [ + ("get", ("adk/1",), scope), + ("memory.delete_version", ({"memory_key": "adk/1", "version": 7},), scope), + ] + + +def test_delete_memory_of_a_missing_key_deletes_nothing_and_needs_a_key() -> None: fake = _FakeMemory() service = _service(fake) asyncio.run(service.delete_memory(app_name="travel", user_id="alice", memory_id="adk/1")) - assert fake.calls == [("delete", ("adk/1",), {"user_id": "alice"})] + assert [c[0] for c in fake.calls] == ["get"] with pytest.raises(ValueError, match="memory_id"): asyncio.run(service.delete_memory(app_name="travel", user_id="alice")) diff --git a/tests/integration/test_sdk_google_adk_memory.py b/tests/integration/test_sdk_google_adk_memory.py index 7e887a0055..037aef865f 100644 --- a/tests/integration/test_sdk_google_adk_memory.py +++ b/tests/integration/test_sdk_google_adk_memory.py @@ -1,7 +1,7 @@ -"""LoomMemoryService against a running Loom: a session an ADK Runner saves is +"""LoomMemoryService against a running Loom: a turn an ADK Runner saves is extracted, and preload_memory puts it in a later session's prompt for the same app and user only; a memory, extracted or explicit, is deleted by the id a search -returned.""" +returned, in its own app only.""" from __future__ import annotations @@ -41,8 +41,9 @@ async def generate_content_async( yield LlmResponse(content=types.Content(role="model", parts=[types.Part(text="Noted.")])) -async def _save(callback_context: Any) -> None: - await callback_context.add_session_to_memory() +async def _save_turn(ctx: Any) -> None: + turn = [e for e in ctx.session.events if e.invocation_id == ctx.invocation_id] + await ctx.add_events_to_memory(events=turn) async def _turn(service: LoomMemoryService, app: str, user: str, text: str) -> str: @@ -52,7 +53,7 @@ async def _turn(service: LoomMemoryService, app: str, user: str, text: str) -> s runner = Runner( app_name=app, agent=LlmAgent( - name="assistant", model=llm, tools=[preload_memory], after_agent_callback=_save + name="assistant", model=llm, tools=[preload_memory], after_agent_callback=_save_turn ), session_service=sessions, memory_service=service, @@ -78,7 +79,6 @@ async def recalled() -> bool: for app, user in (("travel", "bob"), ("billing", "alice")): found = await service.search_memory(app_name=app, user_id=user, query="Lisbon") assert not found.memories, (app, user) - # The extracted facts carry the session; the ids a search returns still delete them. found = await service.search_memory(app_name="travel", user_id="alice", query="Lisbon") facts = {m.id for m in found.memories if m.custom_metadata["source"] == "fact"} assert facts @@ -88,16 +88,24 @@ async def recalled() -> bool: assert not {m.id for m in found.memories if m.custom_metadata["source"] == "fact"} & facts -async def test_add_memory_then_delete_by_id(agent) -> None: +async def test_add_memory_then_delete_by_id_in_one_app(agent) -> None: service = LoomMemoryService(agent, honour_abstain=False) entry = MemoryEntry(content=types.Content(parts=[types.Part(text="Alice prefers aisle seats")])) - await service.add_memory(app_name="travel", user_id="alice", memories=[entry]) + # The same text in two apps is the same key, one row in each. + for app in ("travel", "billing"): + await service.add_memory(app_name=app, user_id="alice", memories=[entry]) - async def ids() -> list[str | None]: - found = await service.search_memory(app_name="travel", user_id="alice", query="aisle seat") + async def ids(app: str) -> list[str | None]: + found = await service.search_memory(app_name=app, user_id="alice", query="aisle seat") return [m.id for m in found.memories] - await eventually(ids, description="the memory found") - (memory_id,) = await ids() - await service.delete_memory(app_name="travel", user_id="alice", memory_id=memory_id) - assert await ids() == [] + await eventually(lambda: ids("travel"), description="the travel memory found") + await eventually(lambda: ids("billing"), description="the billing memory found") + (memory_id,) = await ids("billing") + await service.delete_memory(app_name="billing", user_id="alice", memory_id=memory_id) + assert await ids("billing") == [] + assert await ids("travel") == [memory_id] + # Another user, or an app that holds no row of the key, deletes nothing. + await service.delete_memory(app_name="travel", user_id="bob", memory_id=memory_id) + await service.delete_memory(app_name="billing", user_id="alice", memory_id=memory_id) + assert await ids("travel") == [memory_id] From 2d0d3143edaa74f2e891606f1663cca295d8470f Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 15 Nov 2026 09:12:00 +0000 Subject: [PATCH 03/21] One LoomMemoryService serves one ADK app in its namespace Loom merges a write into a matching memory of the namespace whichever agent wrote it, so narrowing by agent cannot isolate two ADK apps in one namespace: the second app's write merges into the first's row and its search misses it. The service now takes app_name and refuses another app's calls; rows carry the Loom agent's identity, and delete_memory is memory.delete again. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/integrations/frameworks.md | 18 +++-- docs/reference/python-sdk.md | 8 +- sdk/python/loom/integrations/google_adk.py | 79 ++++++++++--------- sdk/python/tests/test_google_adk.py | 73 +++++++++-------- .../integration/test_sdk_google_adk_memory.py | 51 ++++++------ 5 files changed, 119 insertions(+), 110 deletions(-) diff --git a/docs/features/integrations/frameworks.md b/docs/features/integrations/frameworks.md index ebe6c3148c..e3bf1fc706 100644 --- a/docs/features/integrations/frameworks.md +++ b/docs/features/integrations/frameworks.md @@ -375,22 +375,25 @@ async with Agent(org="acme", namespace="support") as loom_agent: after_agent_callback=save_turn, ), session_service=InMemorySessionService(), - memory_service=LoomMemoryService(loom_agent), + memory_service=LoomMemoryService(loom_agent, app_name="support"), ) ``` -ADK scopes memory by app and user. The app name is the Loom `agent` of every write and -narrows every search, and the ADK user is the Loom `user_id`. ADK's memory spans sessions, -so rows carry no session and a search reads all of the user's memories in the app. The -namespace comes from the Loom agent. +ADK scopes memory by app and user. Loom's boundary is the namespace: a Loom write that +matches a memory of the namespace merges into it, whichever agent wrote that memory, so two +apps sharing a namespace would share and lose memories. A service therefore serves one ADK +app, named by `app_name`, in the namespace of its Loom agent, and refuses a call for +another app; give each app its own namespace and service. The ADK user is the Loom +`user_id`. ADK's memory spans sessions, so rows carry no session and a search reads all of +the user's memories in the namespace. | ADK | Loom | | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages`; Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | | `add_events_to_memory` | the same for the events given, such as the latest turn | | `add_memory` | one `memory.set` per entry under `adk/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 | -| `search_memory` | `memory.search` of the namespace it writes to; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | -| `delete_memory` | the entry's `id` deleted in the app and user given, never another app's row of the same key: the memory's key, or for a verbatim chunk the key of the memory it was written under. An entry Loom cannot delete by key, such as a session summary, has no `id`; [erasure](../memory/retention-and-erasure.md) removes it | +| `search_memory` | `memory.search` of the namespace; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | +| `delete_memory` | `memory.delete` of the entry's `id`: the memory's key, or for a verbatim chunk the key of the memory it was written under. An entry Loom cannot delete by key, such as a session summary, has no `id`; [erasure](../memory/retention-and-erasure.md) removes it | Events keep their text parts only: the model's thoughts and tool calls and results are not sent, and neither is `custom_metadata`. @@ -398,6 +401,7 @@ sent, and neither is `custom_metadata`. | `LoomMemoryService` argument | Default | Effect | | ---------------------------- | -------- | ---------------------------------------------------------------------------------------------- | | `agent` | required | the `loom.Agent` the service calls; ADK awaits its memory service, so a `SyncAgent` is refused | +| `app_name` | required | the ADK app the service serves; a call for another app raises `ValueError` | | `top_k` | 10 | memories per search, from 1 to 500 | | `honour_abstain` | `True` | leave out memories below Loom's floor; nothing when Loom abstains | | `defer` | `True` | queue the extraction on the server instead of waiting for it | diff --git a/docs/reference/python-sdk.md b/docs/reference/python-sdk.md index d4e8c52e52..72dacf7439 100644 --- a/docs/reference/python-sdk.md +++ b/docs/reference/python-sdk.md @@ -255,10 +255,10 @@ system prompt of an agent with no plugin; `part="reference"` lists every plane. assembly policy that adds the memories `memory.search` finds for the latest user message to the prompt, and `loom_tools(agent, user_id=...)` returns `AgentTools` as AG2 tools; install the `[ag2]` extra. -- `loom.integrations.google_adk.LoomMemoryService(agent)` is a Google ADK - `BaseMemoryService`: a saved session or turn goes to - `memory.set_from_messages`, `search_memory` is `memory.search` scoped to the - ADK app and user, and `delete_memory` is `memory.delete`; install the +- `loom.integrations.google_adk.LoomMemoryService(agent, app_name=...)` is a + Google ADK `BaseMemoryService` for one ADK app: a saved session or turn goes + to `memory.set_from_messages`, `search_memory` is `memory.search` scoped to + the ADK user, and `delete_memory` is `memory.delete`; install the `[google-adk]` extra. - `loom.integrations.pydantic_ai.loom_toolset(agent, user_id=...)` returns `AgentTools` as a Pydantic AI `FunctionToolset`; install the `[pydantic-ai]` diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py index db48e08c23..e181e13d30 100644 --- a/sdk/python/loom/integrations/google_adk.py +++ b/sdk/python/loom/integrations/google_adk.py @@ -28,13 +28,13 @@ async def save_turn(ctx): after_agent_callback=save_turn, ), session_service=InMemorySessionService(), - memory_service=LoomMemoryService(loom_agent), + memory_service=LoomMemoryService(loom_agent, app_name="support"), ) -ADK scopes memory by app and user: the app name becomes the Loom ``agent`` of -each write and narrows each search, and the ADK user is the Loom ``user_id``. -ADK's memory spans sessions, so rows carry no session. The namespace and -isolation come from the Loom agent. Install with +ADK scopes memory by app and user. Loom's boundary is the namespace, so a +service serves one ADK app, the namespace of its Loom agent, and refuses a +call for another app; the ADK user is the Loom ``user_id``. ADK's memory +spans sessions, so rows carry no session. Install with ``pip install 'clickhouse-loom[google-adk]'``. """ @@ -65,7 +65,7 @@ async def save_turn(ctx): class LoomMemoryService(BaseMemoryService): - """ADK ``BaseMemoryService`` over a Loom ``Agent``. + """ADK ``BaseMemoryService`` over a Loom ``Agent``, for one ADK app. ``add_session_to_memory`` and ``add_events_to_memory`` send the text of the events to ``memory.set_from_messages``, where Loom extracts the facts and @@ -74,21 +74,21 @@ class LoomMemoryService(BaseMemoryService): events. Events a rewind took back are left out. ``add_memory`` writes each entry with ``memory.set`` under a key derived from its text (``/``), its ``timestamp`` as the - memory's ``valid_at`` when it is ISO 8601. ``search_memory`` runs ``memory.search`` of the - namespace it writes to; with ``honour_abstain`` it leaves out memories - below Loom's floor and returns nothing when Loom abstains. A returned - entry's ``id`` is the Loom key ``delete_memory`` deletes, in the app and - user given: the memory's, or for a verbatim chunk the memory it was - written under. An entry Loom cannot delete by key, such as a session - summary, has no ``id``; Loom's erasure removes it. - ``custom_metadata`` is not kept. ADK awaits its memory service, so the - service takes a ``loom.Agent``. + memory's ``valid_at`` when it is ISO 8601. ``search_memory`` runs + ``memory.search`` of the namespace; with ``honour_abstain`` it leaves out + memories below Loom's floor and returns nothing when Loom abstains. A + returned entry's ``id`` is the Loom key ``delete_memory`` deletes: the + memory's, or for a verbatim chunk the memory it was written under. An + entry Loom cannot delete by key, such as a session summary, has no ``id``; + Loom's erasure removes it. ``custom_metadata`` is not kept. ADK awaits its + memory service, so the service takes a ``loom.Agent``. """ def __init__( self, agent: Agent, *, + app_name: str, top_k: int = 10, honour_abstain: bool = True, defer: bool = True, @@ -96,18 +96,23 @@ def __init__( ) -> None: if isinstance(agent, SyncAgent): raise TypeError("LoomMemoryService needs a loom.Agent: ADK awaits its memory service") + if not app_name: + raise ValueError("app_name must name the ADK app this service serves") if not 1 <= top_k <= 500: # memory.search's bounds raise ValueError("top_k must be between 1 and 500") + key_prefix = key_prefix.strip("/") + if not key_prefix: + raise ValueError("key_prefix must not be empty") self._agent = agent + self._app_name = app_name self._top_k = top_k self._honour_abstain = honour_abstain self._defer = defer - if not key_prefix.strip("/"): - raise ValueError("key_prefix must not be empty") - self._key_prefix = key_prefix.strip("/") + self._key_prefix = key_prefix async def add_session_to_memory(self, session: Session) -> None: - await self._extract(session.app_name, session.user_id, get_active_events(session.events)) + self._check_app(session.app_name) + await self._extract(session.user_id, get_active_events(session.events)) async def add_events_to_memory( self, @@ -118,7 +123,8 @@ async def add_events_to_memory( session_id: str | None = None, custom_metadata: Mapping[str, object] | None = None, ) -> None: - await self._extract(app_name, user_id, events) + self._check_app(app_name) + await self._extract(user_id, events) async def add_memory( self, @@ -128,6 +134,7 @@ async def add_memory( memories: Sequence[MemoryEntry], custom_metadata: Mapping[str, object] | None = None, ) -> None: + self._check_app(app_name) for memory in memories: text = _text(memory.content) if not text: @@ -137,20 +144,19 @@ async def add_memory( f"{self._key_prefix}/{digest}", text, user_id=user_id, - agent_id=app_name, valid_at=_iso_time(memory.timestamp), ) async def search_memory( self, *, app_name: str, user_id: str, query: str ) -> SearchMemoryResponse: + self._check_app(app_name) if not query.strip(): return SearchMemoryResponse() result = await self._agent.memory.search( query, top_k=self._top_k, user_id=user_id, - agent_id=app_name, # Read the namespace this service writes to, whatever the deployment's default. namespace_scope="this", # Unpinned, a large top_k serves excerpts (above 15 by default) @@ -182,21 +188,21 @@ async def search_memory( async def delete_memory( self, *, app_name: str, user_id: str, memory_id: str | None = None ) -> None: + self._check_app(app_name) if not memory_id: raise ValueError("delete_memory needs the memory_id a search returned") - # memory.delete falls back to the key under any agent, which could be another - # app's row. Read the version this app's row holds, then delete that version - # under the exact identity; a row of another app is never touched. - row = await self._agent.memory.get(memory_id, user_id=user_id, agent_id=app_name) - if row is not None: - await self._agent.call( - "memory.delete_version", - {"memory_key": memory_id, "version": row["version"]}, - user_id=user_id, - agent_id=app_name, + await self._agent.memory.delete(memory_id, user_id=user_id) + + def _check_app(self, app_name: str) -> None: + # Loom merges a write into a matching memory of the namespace whichever agent + # wrote it, so two apps in one namespace would share and lose memories. + if app_name != self._app_name: + raise ValueError( + f"this LoomMemoryService serves the ADK app {self._app_name!r}, not " + f"{app_name!r}: give each app its own Loom namespace and service" ) - async def _extract(self, app_name: str, user_id: str, events: Sequence[Event]) -> None: + async def _extract(self, user_id: str, events: Sequence[Event]) -> None: messages: list[dict[str, object]] = [] for event in events: text = _text(event.content) @@ -209,12 +215,7 @@ async def _extract(self, app_name: str, user_id: str, events: Sequence[Event]) - } ) if messages: - await self._agent.memory.set_from_messages( - messages, - user_id=user_id, - agent_id=app_name, - defer=self._defer, - ) + await self._agent.memory.set_from_messages(messages, user_id=user_id, defer=self._defer) def _deletable_key(hit: MemorySearchHit) -> str | None: diff --git a/sdk/python/tests/test_google_adk.py b/sdk/python/tests/test_google_adk.py index bcf8aaf274..8d3819c092 100644 --- a/sdk/python/tests/test_google_adk.py +++ b/sdk/python/tests/test_google_adk.py @@ -30,7 +30,6 @@ def __init__(self, hits: list[MemorySearchHit] | None = None, abstain: bool = Fa self.calls: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = [] self._hits = hits or [] self._abstain = abstain - self.rows: dict[str, dict[str, Any]] = {} async def search(self, query: str, **kw: Any) -> MemorySearchResult: self.calls.append(("search", (query,), kw)) @@ -46,19 +45,15 @@ async def set_from_messages(self, messages: list[dict[str, object]], **kw: Any) self.calls.append(("set_from_messages", (messages,), kw)) return {} - async def get(self, key: str, **kw: Any) -> dict[str, Any] | None: - self.calls.append(("get", (key,), kw)) - return self.rows.get(key) + async def delete(self, key: str, **kw: Any) -> bool: + self.calls.append(("delete", (key,), kw)) + return True class _Agent: def __init__(self, memory: _FakeMemory) -> None: self.memory = memory - async def call(self, op: str, body: dict[str, Any], **kw: Any) -> dict[str, Any]: - self.memory.calls.append((op, (body,), kw)) - return {} - class _ScriptedLlm(BaseLlm): """Answers each model call with the next scripted content; keeps the requests.""" @@ -85,6 +80,7 @@ def _model(text: str) -> types.Content: def _service(fake: _FakeMemory, **kw: Any) -> LoomMemoryService: + kw.setdefault("app_name", "travel") return LoomMemoryService(_Agent(fake), **kw) # type: ignore[arg-type] @@ -118,10 +114,14 @@ def test_it_is_an_adk_memory_service() -> None: def test_it_refuses_a_sync_agent_a_top_k_out_of_bounds_and_an_empty_prefix() -> None: with pytest.raises(TypeError, match="ADK awaits"): - LoomMemoryService(SyncAgent(org="o", namespace="n", base_url="http://127.0.0.1:9")) + LoomMemoryService( + SyncAgent(org="o", namespace="n", base_url="http://127.0.0.1:9"), app_name="travel" + ) for top_k in (0, 501): with pytest.raises(ValueError, match="top_k"): _service(_FakeMemory(), top_k=top_k) + with pytest.raises(ValueError, match="app_name"): + _service(_FakeMemory(), app_name="") for prefix in ("", "/"): with pytest.raises(ValueError, match="key_prefix"): _service(_FakeMemory(), key_prefix=prefix) @@ -136,7 +136,6 @@ def test_preload_memory_puts_the_matches_in_the_prompt() -> None: assert search[2] == { "top_k": 10, "user_id": "alice", - "agent_id": "travel", "namespace_scope": "this", "bodies": "full", "explain": False, @@ -169,22 +168,26 @@ def test_the_model_reads_load_memory_results() -> None: def test_search_leaves_out_rows_below_the_floor_and_an_abstention() -> None: hits = [_hit("adk/1", "kept"), _hit("adk/2", "weak", below_threshold=True)] found = asyncio.run( - _service(_FakeMemory(hits)).search_memory(app_name="a", user_id="u", query="q") + _service(_FakeMemory(hits)).search_memory(app_name="travel", user_id="u", query="q") ) assert [m.id for m in found.memories] == ["adk/1"] everything = _service(_FakeMemory(hits), honour_abstain=False) - found = asyncio.run(everything.search_memory(app_name="a", user_id="u", query="q")) + found = asyncio.run(everything.search_memory(app_name="travel", user_id="u", query="q")) assert [m.id for m in found.memories] == ["adk/1", "adk/2"] abstained = _service(_FakeMemory(hits, abstain=True)) - assert not asyncio.run(abstained.search_memory(app_name="a", user_id="u", query="q")).memories + assert not asyncio.run( + abstained.search_memory(app_name="travel", user_id="u", query="q") + ).memories def test_search_cuts_to_top_k_and_skips_an_empty_query() -> None: fake = _FakeMemory([_hit(f"adk/{i}", f"fact {i}") for i in range(4)]) - found = asyncio.run(_service(fake, top_k=2).search_memory(app_name="a", user_id="u", query="q")) + found = asyncio.run( + _service(fake, top_k=2).search_memory(app_name="travel", user_id="u", query="q") + ) assert [m.id for m in found.memories] == ["adk/0", "adk/1"] assert not asyncio.run( - _service(fake).search_memory(app_name="a", user_id="u", query=" ") + _service(fake).search_memory(app_name="travel", user_id="u", query=" ") ).memories assert len(fake.calls) == 1 @@ -205,7 +208,7 @@ async def save(callback_context: Any) -> None: ] assert all(str(m["timestamp"]).endswith("+00:00") for m in messages) # ADK's memory spans sessions: the rows carry none, so a delete can address them. - assert extract[2] == {"user_id": "alice", "agent_id": "travel", "defer": True} + assert extract[2] == {"user_id": "alice", "defer": True} def test_the_documented_turn_callback_sends_each_turn_once() -> None: @@ -271,7 +274,9 @@ def test_events_without_text_send_nothing() -> None: fake = _FakeMemory() silent = Event(author="user", content=types.Content(parts=[types.Part(text=" ")])) asyncio.run( - _service(fake, defer=False).add_events_to_memory(app_name="a", user_id="u", events=[silent]) + _service(fake, defer=False).add_events_to_memory( + app_name="travel", user_id="u", events=[silent] + ) ) assert fake.calls == [] @@ -289,7 +294,7 @@ def test_add_memory_writes_content_keyed_memories() -> None: (first, again) = fake.calls assert first[1][0] == again[1][0] and first[1][0].startswith("adk/") assert first[1][1] == "Alice prefers aisle seats" - assert first[2]["user_id"] == "alice" and first[2]["agent_id"] == "travel" + assert first[2]["user_id"] == "alice" assert first[2]["valid_at"].isoformat() == "2026-11-01T09:00:00+00:00" assert again[2]["valid_at"] is None @@ -302,25 +307,31 @@ def test_a_timestamp_that_is_not_iso_is_no_valid_at() -> None: assert kw["valid_at"] is None -def test_delete_memory_deletes_this_apps_version_of_the_key() -> None: +def test_delete_memory_deletes_the_key_and_needs_one() -> None: fake = _FakeMemory() - fake.rows["adk/1"] = {"memory_key": "adk/1", "version": 7} service = _service(fake) asyncio.run(service.delete_memory(app_name="travel", user_id="alice", memory_id="adk/1")) - scope = {"user_id": "alice", "agent_id": "travel"} - assert fake.calls == [ - ("get", ("adk/1",), scope), - ("memory.delete_version", ({"memory_key": "adk/1", "version": 7},), scope), - ] + assert fake.calls == [("delete", ("adk/1",), {"user_id": "alice"})] + with pytest.raises(ValueError, match="memory_id"): + asyncio.run(service.delete_memory(app_name="travel", user_id="alice")) -def test_delete_memory_of_a_missing_key_deletes_nothing_and_needs_a_key() -> None: +def test_a_call_for_another_app_is_refused() -> None: + from google.adk.sessions import Session + fake = _FakeMemory() service = _service(fake) - asyncio.run(service.delete_memory(app_name="travel", user_id="alice", memory_id="adk/1")) - assert [c[0] for c in fake.calls] == ["get"] - with pytest.raises(ValueError, match="memory_id"): - asyncio.run(service.delete_memory(app_name="travel", user_id="alice")) + calls = [ + service.search_memory(app_name="billing", user_id="alice", query="q"), + service.add_memory(app_name="billing", user_id="alice", memories=[]), + service.add_events_to_memory(app_name="billing", user_id="alice", events=[]), + service.add_session_to_memory(Session(id="s", app_name="billing", user_id="alice")), + service.delete_memory(app_name="billing", user_id="alice", memory_id="adk/1"), + ] + for call in calls: + with pytest.raises(ValueError, match="its own Loom namespace"): + asyncio.run(call) + assert fake.calls == [] def test_an_entry_id_is_the_key_delete_memory_deletes() -> None: @@ -330,7 +341,7 @@ def test_an_entry_id_is_the_key_delete_memory_deletes() -> None: _hit("summary:s1", "a session", source="summary"), ] found = asyncio.run( - _service(_FakeMemory(hits)).search_memory(app_name="a", user_id="u", query="q") + _service(_FakeMemory(hits)).search_memory(app_name="travel", user_id="u", query="q") ) assert [m.id for m in found.memories] == ["adk/1", "adk/1", None] assert [m.custom_metadata["source"] for m in found.memories] == ["fact", "chunk", "summary"] diff --git a/tests/integration/test_sdk_google_adk_memory.py b/tests/integration/test_sdk_google_adk_memory.py index 037aef865f..4db3a054a6 100644 --- a/tests/integration/test_sdk_google_adk_memory.py +++ b/tests/integration/test_sdk_google_adk_memory.py @@ -1,7 +1,7 @@ """LoomMemoryService against a running Loom: a turn an ADK Runner saves is extracted, and preload_memory puts it in a later session's prompt for the same -app and user only; a memory, extracted or explicit, is deleted by the id a search -returned, in its own app only.""" +user only; a memory, extracted or explicit, is deleted by the id a search +returned.""" from __future__ import annotations @@ -46,39 +46,38 @@ async def _save_turn(ctx: Any) -> None: await ctx.add_events_to_memory(events=turn) -async def _turn(service: LoomMemoryService, app: str, user: str, text: str) -> str: - """One turn in a new session; returns the text of the model's prompt.""" +async def _turn(service: LoomMemoryService, user: str, text: str) -> str: + """One turn in a new session of the app "travel"; returns the model's prompt text.""" llm = _EchoLlm() sessions = InMemorySessionService() runner = Runner( - app_name=app, + app_name="travel", agent=LlmAgent( name="assistant", model=llm, tools=[preload_memory], after_agent_callback=_save_turn ), session_service=sessions, memory_service=service, ) - session = await sessions.create_session(app_name=app, user_id=user) + session = await sessions.create_session(app_name="travel", user_id=user) message = types.Content(role="user", parts=[types.Part(text=text)]) async for _ in runner.run_async(user_id=user, session_id=session.id, new_message=message): pass return " ".join(p.text or "" for c in llm.requests[0].contents for p in c.parts or []) -async def test_a_saved_session_reaches_a_later_prompt(agent) -> None: +async def test_a_saved_turn_reaches_a_later_prompt(agent) -> None: # defer=False: extraction inline, since the test server runs no background workers - service = LoomMemoryService(agent, honour_abstain=False, defer=False) - await _turn(service, "travel", "alice", "I fly to Lisbon every month.") + service = LoomMemoryService(agent, app_name="travel", honour_abstain=False, defer=False) + await _turn(service, "alice", "I fly to Lisbon every month.") async def recalled() -> bool: - prompt = await _turn(service, "travel", "alice", "Where does Alice fly every month?") + prompt = await _turn(service, "alice", "Where does Alice fly every month?") return "lisbon" in prompt.lower() # A write is searchable once its embedding lands; eventually raises on timeout. await eventually(recalled, description="'lisbon' in the next session's prompt") - for app, user in (("travel", "bob"), ("billing", "alice")): - found = await service.search_memory(app_name=app, user_id=user, query="Lisbon") - assert not found.memories, (app, user) + found = await service.search_memory(app_name="travel", user_id="bob", query="Lisbon") + assert not found.memories found = await service.search_memory(app_name="travel", user_id="alice", query="Lisbon") facts = {m.id for m in found.memories if m.custom_metadata["source"] == "fact"} assert facts @@ -88,24 +87,18 @@ async def recalled() -> bool: assert not {m.id for m in found.memories if m.custom_metadata["source"] == "fact"} & facts -async def test_add_memory_then_delete_by_id_in_one_app(agent) -> None: - service = LoomMemoryService(agent, honour_abstain=False) +async def test_add_memory_then_delete_by_id(agent) -> None: + service = LoomMemoryService(agent, app_name="travel", honour_abstain=False) entry = MemoryEntry(content=types.Content(parts=[types.Part(text="Alice prefers aisle seats")])) - # The same text in two apps is the same key, one row in each. - for app in ("travel", "billing"): - await service.add_memory(app_name=app, user_id="alice", memories=[entry]) + await service.add_memory(app_name="travel", user_id="alice", memories=[entry]) - async def ids(app: str) -> list[str | None]: - found = await service.search_memory(app_name=app, user_id="alice", query="aisle seat") + async def ids(user: str) -> list[str | None]: + found = await service.search_memory(app_name="travel", user_id=user, query="aisle seat") return [m.id for m in found.memories] - await eventually(lambda: ids("travel"), description="the travel memory found") - await eventually(lambda: ids("billing"), description="the billing memory found") - (memory_id,) = await ids("billing") - await service.delete_memory(app_name="billing", user_id="alice", memory_id=memory_id) - assert await ids("billing") == [] - assert await ids("travel") == [memory_id] - # Another user, or an app that holds no row of the key, deletes nothing. + await eventually(lambda: ids("alice"), description="the memory found") + (memory_id,) = await ids("alice") await service.delete_memory(app_name="travel", user_id="bob", memory_id=memory_id) - await service.delete_memory(app_name="billing", user_id="alice", memory_id=memory_id) - assert await ids("travel") == [memory_id] + assert await ids("alice") == [memory_id] # another user's delete reaches nothing + await service.delete_memory(app_name="travel", user_id="alice", memory_id=memory_id) + assert await ids("alice") == [] From 594be301242a8cc7d7873228cf2ff2734d4b31fa Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 04:07:59 +0000 Subject: [PATCH 04/21] The ADK service sends the session, keys add_memory by user, and gives only memories a deletable id Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- sdk/python/loom/integrations/google_adk.py | 53 ++++++++++--------- sdk/python/tests/test_google_adk.py | 38 +++++++++++-- .../integration/test_sdk_google_adk_memory.py | 18 ++++++- 3 files changed, 77 insertions(+), 32 deletions(-) diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py index e181e13d30..200e220045 100644 --- a/sdk/python/loom/integrations/google_adk.py +++ b/sdk/python/loom/integrations/google_adk.py @@ -33,8 +33,8 @@ async def save_turn(ctx): ADK scopes memory by app and user. Loom's boundary is the namespace, so a service serves one ADK app, the namespace of its Loom agent, and refuses a -call for another app; the ADK user is the Loom ``user_id``. ADK's memory -spans sessions, so rows carry no session. Install with +call for another app; the ADK user is the Loom ``user_id``, and extraction +runs under the ADK session. Install with ``pip install 'clickhouse-loom[google-adk]'``. """ @@ -61,7 +61,6 @@ async def save_turn(ctx): if TYPE_CHECKING: from loom.agent import Agent - from loom.memory import MemorySearchHit class LoomMemoryService(BaseMemoryService): @@ -71,17 +70,19 @@ class LoomMemoryService(BaseMemoryService): events to ``memory.set_from_messages``, where Loom extracts the facts and resolves duplicates and conflicts; a session added again is extracted again, so a callback that runs every turn should add only that turn's - events. Events a rewind took back are left out. ``add_memory`` writes each - entry with ``memory.set`` under a key derived from its text + events. Events a rewind took back are left out; a turn saved before a + later rewind keeps its memories, which the app deletes by the ids a search + returns. ``add_memory`` writes each entry with ``memory.set`` under a key + derived from the user and the text (``/``), its ``timestamp`` as the memory's ``valid_at`` when it is ISO 8601. ``search_memory`` runs - ``memory.search`` of the namespace; with ``honour_abstain`` it leaves out - memories below Loom's floor and returns nothing when Loom abstains. A - returned entry's ``id`` is the Loom key ``delete_memory`` deletes: the - memory's, or for a verbatim chunk the memory it was written under. An - entry Loom cannot delete by key, such as a session summary, has no ``id``; - Loom's erasure removes it. ``custom_metadata`` is not kept. ADK awaits its - memory service, so the service takes a ``loom.Agent``. + ``memory.search`` of the user's memories; with ``honour_abstain`` it leaves + out memories below Loom's floor and returns nothing when Loom abstains. A + returned memory's ``id`` is the Loom key ``delete_memory`` deletes. A + verbatim chunk of a conversation or a session summary has no ``id``: no + key deletes it, and Loom's erasure removes it. ``custom_metadata``, and an + entry's ``author`` and ``id``, are not kept. ADK awaits its memory service, + so the service takes a ``loom.Agent``. """ def __init__( @@ -112,7 +113,7 @@ def __init__( async def add_session_to_memory(self, session: Session) -> None: self._check_app(session.app_name) - await self._extract(session.user_id, get_active_events(session.events)) + await self._extract(session.user_id, session.id, get_active_events(session.events)) async def add_events_to_memory( self, @@ -124,7 +125,7 @@ async def add_events_to_memory( custom_metadata: Mapping[str, object] | None = None, ) -> None: self._check_app(app_name) - await self._extract(user_id, events) + await self._extract(user_id, session_id, get_active_events(list(events))) async def add_memory( self, @@ -139,7 +140,8 @@ async def add_memory( text = _text(memory.content) if not text: continue - digest = hashlib.sha256(text.encode("utf-8")).hexdigest()[:20] + # The user is in the key: Loom files a long value's passages by key alone. + digest = hashlib.sha256(f"{user_id}\0{text}".encode()).hexdigest()[:20] await self._agent.memory.set( f"{self._key_prefix}/{digest}", text, @@ -159,8 +161,8 @@ async def search_memory( user_id=user_id, # Read the namespace this service writes to, whatever the deployment's default. namespace_scope="this", - # Unpinned, a large top_k serves excerpts (above 15 by default) - # and drops each hit's explanation. + # Pinned so every top_k gets full bodies and no per-hit explanation + # (the server's defaults switch at 15). bodies="full", explain=False, ) @@ -173,7 +175,8 @@ async def search_memory( return SearchMemoryResponse( memories=[ MemoryEntry( - id=_deletable_key(hit), + # Only a memory has a key memory.delete takes. + id=hit.memory_key if hit.source == "fact" else None, content=types.Content( role="user", parts=[types.Part(text=hit.content_excerpt)] ), @@ -202,7 +205,7 @@ def _check_app(self, app_name: str) -> None: f"{app_name!r}: give each app its own Loom namespace and service" ) - async def _extract(self, user_id: str, events: Sequence[Event]) -> None: + async def _extract(self, user_id: str, session_id: str | None, events: Sequence[Event]) -> None: messages: list[dict[str, object]] = [] for event in events: text = _text(event.content) @@ -215,13 +218,11 @@ async def _extract(self, user_id: str, events: Sequence[Event]) -> None: } ) if messages: - await self._agent.memory.set_from_messages(messages, user_id=user_id, defer=self._defer) - - -def _deletable_key(hit: MemorySearchHit) -> str | None: - if hit.source == "fact": - return hit.memory_key - return hit.parent_memory_key or None + # The session keys Loom's evidence of the turns (chunks, summary), so + # it is sent; without one, every user's evidence shares one key. + await self._agent.memory.set_from_messages( + messages, user_id=user_id, session_id=session_id, defer=self._defer + ) def _iso_time(text: str | None) -> datetime | None: diff --git a/sdk/python/tests/test_google_adk.py b/sdk/python/tests/test_google_adk.py index 8d3819c092..8f51c821f3 100644 --- a/sdk/python/tests/test_google_adk.py +++ b/sdk/python/tests/test_google_adk.py @@ -199,7 +199,10 @@ async def save(callback_context: Any) -> None: await callback_context.add_session_to_memory() llm = _ScriptedLlm(script=[_model("Noted.")]) - asyncio.run(_run(_service(fake), llm, "I prefer aisle seats", after_agent_callback=save)) + sessions = asyncio.run( + _run(_service(fake), llm, "I prefer aisle seats", after_agent_callback=save) + ) + (session,) = asyncio.run(sessions.list_sessions(app_name="travel", user_id="alice")).sessions (extract,) = [c for c in fake.calls if c[0] == "set_from_messages"] messages = extract[1][0] assert [(m["role"], m["content"]) for m in messages] == [ @@ -207,8 +210,8 @@ async def save(callback_context: Any) -> None: ("assistant", "Noted."), ] assert all(str(m["timestamp"]).endswith("+00:00") for m in messages) - # ADK's memory spans sessions: the rows carry none, so a delete can address them. - assert extract[2] == {"user_id": "alice", "defer": True} + # The session keys Loom's evidence of the turns. + assert extract[2] == {"user_id": "alice", "session_id": session.id, "defer": True} def test_the_documented_turn_callback_sends_each_turn_once() -> None: @@ -268,6 +271,29 @@ def event(inv: str, author: str, *parts: types.Part, **kw: Any) -> Event: assert [m["content"] for m in extract[1][0]] == ["I live in Lisbon", "Lisbon it is"] +def test_events_given_leave_out_a_turn_rewound_among_them() -> None: + from google.adk.events import Event, EventActions + + events = [ + Event(invocation_id="i1", author="user", content=_model("I live in Lisbon")), + Event(invocation_id="i2", author="user", content=_model("Actually Porto")), + Event( + invocation_id="i3", + author="user", + actions=EventActions(rewind_before_invocation_id="i2"), + ), + ] + fake = _FakeMemory() + asyncio.run( + _service(fake).add_events_to_memory( + app_name="travel", user_id="alice", events=events, session_id="s1" + ) + ) + ((_, (messages,), kw),) = fake.calls + assert [m["content"] for m in messages] == ["I live in Lisbon"] + assert kw["session_id"] == "s1" + + def test_events_without_text_send_nothing() -> None: from google.adk.events import Event @@ -295,6 +321,10 @@ def test_add_memory_writes_content_keyed_memories() -> None: assert first[1][0] == again[1][0] and first[1][0].startswith("adk/") assert first[1][1] == "Alice prefers aisle seats" assert first[2]["user_id"] == "alice" + # The user is in the key: Loom files a long value's passages by key alone. + bob = _FakeMemory() + asyncio.run(_service(bob).add_memory(app_name="travel", user_id="bob", memories=entries[:1])) + assert bob.calls[0][1][0] != first[1][0] assert first[2]["valid_at"].isoformat() == "2026-11-01T09:00:00+00:00" assert again[2]["valid_at"] is None @@ -343,5 +373,5 @@ def test_an_entry_id_is_the_key_delete_memory_deletes() -> None: found = asyncio.run( _service(_FakeMemory(hits)).search_memory(app_name="travel", user_id="u", query="q") ) - assert [m.id for m in found.memories] == ["adk/1", "adk/1", None] + assert [m.id for m in found.memories] == ["adk/1", None, None] assert [m.custom_metadata["source"] for m in found.memories] == ["fact", "chunk", "summary"] diff --git a/tests/integration/test_sdk_google_adk_memory.py b/tests/integration/test_sdk_google_adk_memory.py index 4db3a054a6..9a00890ac3 100644 --- a/tests/integration/test_sdk_google_adk_memory.py +++ b/tests/integration/test_sdk_google_adk_memory.py @@ -84,12 +84,16 @@ async def recalled() -> bool: for memory_id in facts: await service.delete_memory(app_name="travel", user_id="alice", memory_id=memory_id) found = await service.search_memory(app_name="travel", user_id="alice", query="Lisbon") - assert not {m.id for m in found.memories if m.custom_metadata["source"] == "fact"} & facts + # The deleted facts do not come back. + assert not {m.id for m in found.memories} & facts async def test_add_memory_then_delete_by_id(agent) -> None: service = LoomMemoryService(agent, app_name="travel", honour_abstain=False) - entry = MemoryEntry(content=types.Content(parts=[types.Part(text="Alice prefers aisle seats")])) + entry = MemoryEntry( + content=types.Content(parts=[types.Part(text="Alice prefers aisle seats")]), + timestamp="2026-03-01T09:00:00+00:00", + ) await service.add_memory(app_name="travel", user_id="alice", memories=[entry]) async def ids(user: str) -> list[str | None]: @@ -98,6 +102,16 @@ async def ids(user: str) -> list[str | None]: await eventually(lambda: ids("alice"), description="the memory found") (memory_id,) = await ids("alice") + assert memory_id is not None + row = await agent.memory.get(memory_id, user_id="alice") + assert row is not None + assert (row["value"], row["agent"], row["user_id"], row["session_id"]) == ( + "Alice prefers aisle seats", + agent.agent, + "alice", + "-", + ) + assert row["valid_at"].startswith("2026-03-01") await service.delete_memory(app_name="travel", user_id="bob", memory_id=memory_id) assert await ids("alice") == [memory_id] # another user's delete reaches nothing await service.delete_memory(app_name="travel", user_id="alice", memory_id=memory_id) From bb7662fe478b6f603cf3f9d98a37592cbfbc495f Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 04:09:26 +0000 Subject: [PATCH 05/21] The ADK docs say extraction runs under the session and only memories carry an id Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/integrations/frameworks.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/features/integrations/frameworks.md b/docs/features/integrations/frameworks.md index e3bf1fc706..c6fd21559e 100644 --- a/docs/features/integrations/frameworks.md +++ b/docs/features/integrations/frameworks.md @@ -384,19 +384,19 @@ matches a memory of the namespace merges into it, whichever agent wrote that mem apps sharing a namespace would share and lose memories. A service therefore serves one ADK app, named by `app_name`, in the namespace of its Loom agent, and refuses a call for another app; give each app its own namespace and service. The ADK user is the Loom -`user_id`. ADK's memory spans sessions, so rows carry no session and a search reads all of -the user's memories in the namespace. +`user_id`. Extraction runs under the ADK session, which keys Loom's record of the turns, +and a search reads all of the user's memories in the namespace, from every session. | ADK | Loom | | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages`; Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | -| `add_events_to_memory` | the same for the events given, such as the latest turn | -| `add_memory` | one `memory.set` per entry under `adk/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 | -| `search_memory` | `memory.search` of the namespace; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | -| `delete_memory` | `memory.delete` of the entry's `id`: the memory's key, or for a verbatim chunk the key of the memory it was written under. An entry Loom cannot delete by key, such as a session summary, has no `id`; [erasure](../memory/retention-and-erasure.md) removes it | +| `add_events_to_memory` | the same for the events given, such as the latest turn; a turn saved before a later rewind keeps its memories, which the app deletes by the ids a search returns | +| `add_memory` | one `memory.set` per entry under `adk/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 | +| `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | +| `delete_memory` | `memory.delete` of the entry's `id`, the memory's key. A verbatim chunk of a conversation or a session summary has no `id`: no key deletes it, and [erasure](../memory/retention-and-erasure.md) removes it | Events keep their text parts only: the model's thoughts and tool calls and results are not -sent, and neither is `custom_metadata`. +sent, and neither is `custom_metadata` or an entry's `author` and `id`. | `LoomMemoryService` argument | Default | Effect | | ---------------------------- | -------- | ---------------------------------------------------------------------------------------------- | From ffb4458af680feaa2e73b89ac766b309b379e769 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 04:18:11 +0000 Subject: [PATCH 06/21] The ADK service refuses events without a session; tests pin the session and the stored row Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/integrations/frameworks.md | 2 +- sdk/python/loom/integrations/google_adk.py | 9 +++-- sdk/python/tests/test_google_adk.py | 36 ++++++++++++++----- .../integration/test_sdk_google_adk_memory.py | 8 +++-- 4 files changed, 41 insertions(+), 14 deletions(-) diff --git a/docs/features/integrations/frameworks.md b/docs/features/integrations/frameworks.md index c6fd21559e..6b02b091ac 100644 --- a/docs/features/integrations/frameworks.md +++ b/docs/features/integrations/frameworks.md @@ -390,7 +390,7 @@ and a search reads all of the user's memories in the namespace, from every sessi | ADK | Loom | | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages`; Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | -| `add_events_to_memory` | the same for the events given, such as the latest turn; a turn saved before a later rewind keeps its memories, which the app deletes by the ids a search returns | +| `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom keys a turn's chunks and summary by session. A turn saved before a later rewind keeps its memories, which the app deletes by the ids a search returns | | `add_memory` | one `memory.set` per entry under `adk/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 | | `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | | `delete_memory` | `memory.delete` of the entry's `id`, the memory's key. A verbatim chunk of a conversation or a session summary has no `id`: no key deletes it, and [erasure](../memory/retention-and-erasure.md) removes it | diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py index 200e220045..fcbe197927 100644 --- a/sdk/python/loom/integrations/google_adk.py +++ b/sdk/python/loom/integrations/google_adk.py @@ -70,7 +70,8 @@ class LoomMemoryService(BaseMemoryService): events to ``memory.set_from_messages``, where Loom extracts the facts and resolves duplicates and conflicts; a session added again is extracted again, so a callback that runs every turn should add only that turn's - events. Events a rewind took back are left out; a turn saved before a + events; ``add_events_to_memory`` needs the ``session_id``, which ADK's + callback context passes. Events a rewind took back are left out; a turn saved before a later rewind keeps its memories, which the app deletes by the ids a search returns. ``add_memory`` writes each entry with ``memory.set`` under a key derived from the user and the text @@ -125,6 +126,9 @@ async def add_events_to_memory( custom_metadata: Mapping[str, object] | None = None, ) -> None: self._check_app(app_name) + if not session_id: + # Loom keys a turn's chunks and summary by session, not by user. + raise ValueError("add_events_to_memory needs the ADK session_id") await self._extract(user_id, session_id, get_active_events(list(events))) async def add_memory( @@ -218,8 +222,7 @@ async def _extract(self, user_id: str, session_id: str | None, events: Sequence[ } ) if messages: - # The session keys Loom's evidence of the turns (chunks, summary), so - # it is sent; without one, every user's evidence shares one key. + # The session keys Loom's evidence of the turns (chunks, summary). await self._agent.memory.set_from_messages( messages, user_id=user_id, session_id=session_id, defer=self._defer ) diff --git a/sdk/python/tests/test_google_adk.py b/sdk/python/tests/test_google_adk.py index 8f51c821f3..a71364f8d3 100644 --- a/sdk/python/tests/test_google_adk.py +++ b/sdk/python/tests/test_google_adk.py @@ -75,6 +75,10 @@ def _hit(key: str, text: str, **kw: Any) -> MemorySearchHit: ) +def _user(text: str) -> types.Content: + return types.Content(role="user", parts=[types.Part(text=text)]) + + def _model(text: str) -> types.Content: return types.Content(role="model", parts=[types.Part(text=text)]) @@ -222,7 +226,7 @@ async def save_turn(ctx: Any) -> None: await ctx.add_events_to_memory(events=turn) llm = _ScriptedLlm(script=[_model("Noted."), _model("Lisbon, then.")]) - asyncio.run( + sessions = asyncio.run( _run( _service(fake), llm, @@ -231,8 +235,12 @@ async def save_turn(ctx: Any) -> None: after_agent_callback=save_turn, ) ) - sent = [[m["content"] for m in c[1][0]] for c in fake.calls if c[0] == "set_from_messages"] + (session,) = asyncio.run(sessions.list_sessions(app_name="travel", user_id="alice")).sessions + calls = [c for c in fake.calls if c[0] == "set_from_messages"] + sent = [[m["content"] for m in c[1][0]] for c in calls] assert sent == [["I prefer aisle seats", "Noted."], ["I fly to Lisbon", "Lisbon, then."]] + # ADK's context passes the session, which keys Loom's evidence of each turn. + assert [c[2]["session_id"] for c in calls] == [session.id, session.id] def test_extraction_leaves_out_thoughts_tool_calls_and_rewound_turns() -> None: @@ -275,8 +283,8 @@ def test_events_given_leave_out_a_turn_rewound_among_them() -> None: from google.adk.events import Event, EventActions events = [ - Event(invocation_id="i1", author="user", content=_model("I live in Lisbon")), - Event(invocation_id="i2", author="user", content=_model("Actually Porto")), + Event(invocation_id="i1", author="user", content=_user("I live in Lisbon")), + Event(invocation_id="i2", author="user", content=_user("Actually Porto")), Event( invocation_id="i3", author="user", @@ -301,19 +309,31 @@ def test_events_without_text_send_nothing() -> None: silent = Event(author="user", content=types.Content(parts=[types.Part(text=" ")])) asyncio.run( _service(fake, defer=False).add_events_to_memory( - app_name="travel", user_id="u", events=[silent] + app_name="travel", user_id="u", events=[silent], session_id="s1" ) ) assert fake.calls == [] +def test_events_without_a_session_are_refused() -> None: + from google.adk.events import Event + + fake = _FakeMemory() + event = Event(author="user", content=_user("I live in Lisbon")) + with pytest.raises(ValueError, match="session_id"): + asyncio.run( + _service(fake).add_events_to_memory(app_name="travel", user_id="u", events=[event]) + ) + assert fake.calls == [] + + def test_add_memory_writes_content_keyed_memories() -> None: fake = _FakeMemory() entries = [ MemoryEntry( - content=_model("Alice prefers aisle seats"), timestamp="2026-11-01T09:00:00+00:00" + content=_user("Alice prefers aisle seats"), timestamp="2026-11-01T09:00:00+00:00" ), - MemoryEntry(content=_model(" Alice prefers aisle seats ")), + MemoryEntry(content=_user(" Alice prefers aisle seats ")), MemoryEntry(content=types.Content(parts=[types.Part(text="hidden", thought=True)])), ] asyncio.run(_service(fake).add_memory(app_name="travel", user_id="alice", memories=entries)) @@ -331,7 +351,7 @@ def test_add_memory_writes_content_keyed_memories() -> None: def test_a_timestamp_that_is_not_iso_is_no_valid_at() -> None: fake = _FakeMemory() - entry = MemoryEntry(content=_model("Alice moved to Porto"), timestamp="last spring") + entry = MemoryEntry(content=_user("Alice moved to Porto"), timestamp="last spring") asyncio.run(_service(fake).add_memory(app_name="travel", user_id="alice", memories=[entry])) ((_, _, kw),) = fake.calls assert kw["valid_at"] is None diff --git a/tests/integration/test_sdk_google_adk_memory.py b/tests/integration/test_sdk_google_adk_memory.py index 9a00890ac3..79f8873440 100644 --- a/tests/integration/test_sdk_google_adk_memory.py +++ b/tests/integration/test_sdk_google_adk_memory.py @@ -105,12 +105,16 @@ async def ids(user: str) -> list[str | None]: assert memory_id is not None row = await agent.memory.get(memory_id, user_id="alice") assert row is not None - assert (row["value"], row["agent"], row["user_id"], row["session_id"]) == ( + fields = ("value", "agent", "user_id", "session_id", "memory_type", "source_class", "tags") + assert [row[f] for f in fields] == [ "Alice prefers aisle seats", agent.agent, "alice", "-", - ) + "semantic", + "asserted", + [], + ] assert row["valid_at"].startswith("2026-03-01") await service.delete_memory(app_name="travel", user_id="bob", memory_id=memory_id) assert await ids("alice") == [memory_id] # another user's delete reaches nothing From b5319ee4187abffe6c1b9bc0f2af624230f9d0b1 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 04:39:48 +0000 Subject: [PATCH 07/21] The ADK tests check the import error, the real Agent's requests and two users' memories Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- sdk/python/loom/integrations/google_adk.py | 11 ++-- sdk/python/tests/test_google_adk.py | 52 +++++++++++++++++-- .../integration/test_sdk_google_adk_memory.py | 22 ++++++++ 3 files changed, 75 insertions(+), 10 deletions(-) diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py index fcbe197927..fc793eb939 100644 --- a/sdk/python/loom/integrations/google_adk.py +++ b/sdk/python/loom/integrations/google_adk.py @@ -71,10 +71,10 @@ class LoomMemoryService(BaseMemoryService): resolves duplicates and conflicts; a session added again is extracted again, so a callback that runs every turn should add only that turn's events; ``add_events_to_memory`` needs the ``session_id``, which ADK's - callback context passes. Events a rewind took back are left out; a turn saved before a - later rewind keeps its memories, which the app deletes by the ids a search - returns. ``add_memory`` writes each entry with ``memory.set`` under a key - derived from the user and the text + callback context passes. Events a rewind took back are left out; a turn + saved before a later rewind keeps its memories, which the app deletes by + the ids a search returns. ``add_memory`` writes each entry with + ``memory.set`` under a key derived from the user and the text (``/``), its ``timestamp`` as the memory's ``valid_at`` when it is ISO 8601. ``search_memory`` runs ``memory.search`` of the user's memories; with ``honour_abstain`` it leaves @@ -209,7 +209,7 @@ def _check_app(self, app_name: str) -> None: f"{app_name!r}: give each app its own Loom namespace and service" ) - async def _extract(self, user_id: str, session_id: str | None, events: Sequence[Event]) -> None: + async def _extract(self, user_id: str, session_id: str, events: Sequence[Event]) -> None: messages: list[dict[str, object]] = [] for event in events: text = _text(event.content) @@ -222,7 +222,6 @@ async def _extract(self, user_id: str, session_id: str | None, events: Sequence[ } ) if messages: - # The session keys Loom's evidence of the turns (chunks, summary). await self._agent.memory.set_from_messages( messages, user_id=user_id, session_id=session_id, defer=self._defer ) diff --git a/sdk/python/tests/test_google_adk.py b/sdk/python/tests/test_google_adk.py index a71364f8d3..211ab8d6d0 100644 --- a/sdk/python/tests/test_google_adk.py +++ b/sdk/python/tests/test_google_adk.py @@ -5,6 +5,8 @@ from __future__ import annotations import asyncio +import importlib +import sys from collections.abc import AsyncGenerator from typing import Any @@ -19,7 +21,7 @@ from google.adk.sessions import InMemorySessionService from google.adk.tools import load_memory, preload_memory from google.genai import types -from loom import SyncAgent +from loom import Agent, SyncAgent from loom.integrations.google_adk import LoomMemoryService from loom.memory import MemorySearchHit, MemorySearchResult from pydantic import Field @@ -118,9 +120,7 @@ def test_it_is_an_adk_memory_service() -> None: def test_it_refuses_a_sync_agent_a_top_k_out_of_bounds_and_an_empty_prefix() -> None: with pytest.raises(TypeError, match="ADK awaits"): - LoomMemoryService( - SyncAgent(org="o", namespace="n", base_url="http://127.0.0.1:9"), app_name="travel" - ) + LoomMemoryService(object.__new__(SyncAgent), app_name="travel") for top_k in (0, 501): with pytest.raises(ValueError, match="top_k"): _service(_FakeMemory(), top_k=top_k) @@ -395,3 +395,47 @@ def test_an_entry_id_is_the_key_delete_memory_deletes() -> None: ) assert [m.id for m in found.memories] == ["adk/1", None, None] assert [m.custom_metadata["source"] for m in found.memories] == ["fact", "chunk", "summary"] + + +def test_without_google_adk_the_import_names_the_extra(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setitem(sys.modules, "google.adk.events", None) + monkeypatch.delitem(sys.modules, "loom.integrations.google_adk") + with pytest.raises(ImportError, match=r"clickhouse-loom\[google-adk\]"): + importlib.import_module("loom.integrations.google_adk") + + +def test_a_real_agent_posts_the_service_calls() -> None: + posts: list[tuple[str, dict[str, Any]]] = [] + + async def post(path: str, payload: dict[str, Any], *a: Any, **kw: Any) -> dict[str, Any]: + posts.append((path, dict(payload))) + return {"results": []} + + from google.adk.events import Event + + agent = Agent(org="acme", namespace="travel", agent="bot", base_url="http://x", api_key="k") + agent.transport.post = post # type: ignore[method-assign] + service = LoomMemoryService(agent, app_name="travel", top_k=3) + event = Event(author="user", content=_user("I prefer aisle seats")) + entry = MemoryEntry(content=_user("Alice prefers aisle seats")) + + async def calls() -> None: + await service.search_memory(app_name="travel", user_id="alice", query="seat") + await service.add_events_to_memory( + app_name="travel", user_id="alice", events=[event], session_id="s1" + ) + await service.add_memory(app_name="travel", user_id="alice", memories=[entry]) + + asyncio.run(calls()) + paths = [p for p, _ in posts] + assert paths == ["/v1/memory.search", "/v1/memory.set_from_messages", "/v1/memory.set"] + search, extract, write = (body for _, body in posts) + assert (search["query"], search["top_k"], search["user_id"]) == ("seat", 3, "alice") + assert (search["namespace_scope"], search["bodies"], search["explain"]) == ( + "this", + "full", + False, + ) + assert (extract["user_id"], extract["session_id"]) == ("alice", "s1") + assert [m["content"] for m in extract["messages"]] == ["I prefer aisle seats"] + assert write["memory_key"].startswith("adk/") and write["user_id"] == "alice" diff --git a/tests/integration/test_sdk_google_adk_memory.py b/tests/integration/test_sdk_google_adk_memory.py index 79f8873440..17e6cd9b45 100644 --- a/tests/integration/test_sdk_google_adk_memory.py +++ b/tests/integration/test_sdk_google_adk_memory.py @@ -120,3 +120,25 @@ async def ids(user: str) -> list[str | None]: assert await ids("alice") == [memory_id] # another user's delete reaches nothing await service.delete_memory(app_name="travel", user_id="alice", memory_id=memory_id) assert await ids("alice") == [] + + +async def test_two_users_saving_the_same_text_each_find_their_own(agent) -> None: + service = LoomMemoryService(agent, app_name="travel", honour_abstain=False) + entry = MemoryEntry(content=types.Content(parts=[types.Part(text="Prefers window seats")])) + + async def ids(user: str) -> list[str | None]: + found = await service.search_memory(app_name="travel", user_id=user, query="window seat") + return [m.id for m in found.memories] + + await service.add_memory(app_name="travel", user_id="carol", memories=[entry]) + + async def carols_vector() -> list[str]: + hits = await agent.memory.search("window seats", memory_type="semantic", top_k=5) + return [h.memory_key for h in hits] + + # Loom's write-time check reads vectors: dave saves once carol's is searchable. + await eventually(carols_vector, description="carol's vector") + await service.add_memory(app_name="travel", user_id="dave", memories=[entry]) + carol = await ids("carol") + dave = await eventually(lambda: ids("dave"), description="dave's memory") + assert len(carol) == len(dave) == 1 and carol != dave From 1f6efc5f8ac88ef4858cb740b042796bf9f579e4 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 04:57:28 +0000 Subject: [PATCH 08/21] The ADK service refuses a user_id that names no Loom user, and its docstring points at the docs Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/integrations/frameworks.md | 5 +-- sdk/python/loom/integrations/google_adk.py | 38 ++++++++-------------- sdk/python/tests/test_google_adk.py | 27 ++++++++++++++- 3 files changed, 43 insertions(+), 27 deletions(-) diff --git a/docs/features/integrations/frameworks.md b/docs/features/integrations/frameworks.md index 6b02b091ac..1e2395b092 100644 --- a/docs/features/integrations/frameworks.md +++ b/docs/features/integrations/frameworks.md @@ -384,8 +384,9 @@ matches a memory of the namespace merges into it, whichever agent wrote that mem apps sharing a namespace would share and lose memories. A service therefore serves one ADK app, named by `app_name`, in the namespace of its Loom agent, and refuses a call for another app; give each app its own namespace and service. The ADK user is the Loom -`user_id`. Extraction runs under the ADK session, which keys Loom's record of the turns, -and a search reads all of the user's memories in the namespace, from every session. +`user_id`; an empty or `-` user, which names no user in Loom, raises `ValueError`. +Extraction runs under the ADK session, which keys Loom's record of the turns, and a search +reads all of the user's memories in the namespace, from every session. | ADK | Loom | | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py index fc793eb939..9636bc8e1f 100644 --- a/sdk/python/loom/integrations/google_adk.py +++ b/sdk/python/loom/integrations/google_adk.py @@ -66,24 +66,11 @@ async def save_turn(ctx): class LoomMemoryService(BaseMemoryService): """ADK ``BaseMemoryService`` over a Loom ``Agent``, for one ADK app. - ``add_session_to_memory`` and ``add_events_to_memory`` send the text of the - events to ``memory.set_from_messages``, where Loom extracts the facts and - resolves duplicates and conflicts; a session added again is extracted - again, so a callback that runs every turn should add only that turn's - events; ``add_events_to_memory`` needs the ``session_id``, which ADK's - callback context passes. Events a rewind took back are left out; a turn - saved before a later rewind keeps its memories, which the app deletes by - the ids a search returns. ``add_memory`` writes each entry with - ``memory.set`` under a key derived from the user and the text - (``/``), its ``timestamp`` as the - memory's ``valid_at`` when it is ISO 8601. ``search_memory`` runs - ``memory.search`` of the user's memories; with ``honour_abstain`` it leaves - out memories below Loom's floor and returns nothing when Loom abstains. A - returned memory's ``id`` is the Loom key ``delete_memory`` deletes. A - verbatim chunk of a conversation or a session summary has no ``id``: no - key deletes it, and Loom's erasure removes it. ``custom_metadata``, and an - entry's ``author`` and ``id``, are not kept. ADK awaits its memory service, - so the service takes a ``loom.Agent``. + Saved sessions and turns go to ``memory.set_from_messages``, ``add_memory`` to + ``memory.set`` and ``search_memory`` to ``memory.search`` of the ADK user's + memories; a returned memory's ``id`` is the key ``delete_memory`` deletes. ADK + awaits its memory service, so the service takes a ``loom.Agent``. The mapping of + each method is in ``docs/features/integrations/frameworks.md`` (Google ADK). """ def __init__( @@ -113,7 +100,7 @@ def __init__( self._key_prefix = key_prefix async def add_session_to_memory(self, session: Session) -> None: - self._check_app(session.app_name) + self._check(session.app_name, session.user_id) await self._extract(session.user_id, session.id, get_active_events(session.events)) async def add_events_to_memory( @@ -125,7 +112,7 @@ async def add_events_to_memory( session_id: str | None = None, custom_metadata: Mapping[str, object] | None = None, ) -> None: - self._check_app(app_name) + self._check(app_name, user_id) if not session_id: # Loom keys a turn's chunks and summary by session, not by user. raise ValueError("add_events_to_memory needs the ADK session_id") @@ -139,7 +126,7 @@ async def add_memory( memories: Sequence[MemoryEntry], custom_metadata: Mapping[str, object] | None = None, ) -> None: - self._check_app(app_name) + self._check(app_name, user_id) for memory in memories: text = _text(memory.content) if not text: @@ -156,7 +143,7 @@ async def add_memory( async def search_memory( self, *, app_name: str, user_id: str, query: str ) -> SearchMemoryResponse: - self._check_app(app_name) + self._check(app_name, user_id) if not query.strip(): return SearchMemoryResponse() result = await self._agent.memory.search( @@ -195,12 +182,12 @@ async def search_memory( async def delete_memory( self, *, app_name: str, user_id: str, memory_id: str | None = None ) -> None: - self._check_app(app_name) + self._check(app_name, user_id) if not memory_id: raise ValueError("delete_memory needs the memory_id a search returned") await self._agent.memory.delete(memory_id, user_id=user_id) - def _check_app(self, app_name: str) -> None: + def _check(self, app_name: str, user_id: str) -> None: # Loom merges a write into a matching memory of the namespace whichever agent # wrote it, so two apps in one namespace would share and lose memories. if app_name != self._app_name: @@ -208,6 +195,9 @@ def _check_app(self, app_name: str) -> None: f"this LoomMemoryService serves the ADK app {self._app_name!r}, not " f"{app_name!r}: give each app its own Loom namespace and service" ) + # In Loom an empty or "-" user is no user: writes would land outside the user's reads. + if user_id in ("", "-"): + raise ValueError(f"an ADK user_id names a Loom user; {user_id!r} names none") async def _extract(self, user_id: str, session_id: str, events: Sequence[Event]) -> None: messages: list[dict[str, object]] = [] diff --git a/sdk/python/tests/test_google_adk.py b/sdk/python/tests/test_google_adk.py index 211ab8d6d0..2380d74192 100644 --- a/sdk/python/tests/test_google_adk.py +++ b/sdk/python/tests/test_google_adk.py @@ -118,7 +118,7 @@ def test_it_is_an_adk_memory_service() -> None: assert issubclass(LoomMemoryService, BaseMemoryService) -def test_it_refuses_a_sync_agent_a_top_k_out_of_bounds_and_an_empty_prefix() -> None: +def test_it_refuses_bad_construction() -> None: with pytest.raises(TypeError, match="ADK awaits"): LoomMemoryService(object.__new__(SyncAgent), app_name="travel") for top_k in (0, 501): @@ -439,3 +439,28 @@ async def calls() -> None: assert (extract["user_id"], extract["session_id"]) == ("alice", "s1") assert [m["content"] for m in extract["messages"]] == ["I prefer aisle seats"] assert write["memory_key"].startswith("adk/") and write["user_id"] == "alice" + + +@pytest.mark.parametrize("user", ["", "-"]) +def test_a_user_id_that_names_no_loom_user_is_refused(user: str) -> None: + from google.adk.events import Event + + fake = _FakeMemory() + service = _service(fake) + entry = MemoryEntry(content=_user("Alice prefers aisle seats")) + event = Event(author="user", content=_user("I prefer aisle seats")) + from google.adk.sessions import Session + + calls = [ + service.add_session_to_memory(Session(id="s", app_name="travel", user_id=user)), + service.search_memory(app_name="travel", user_id=user, query="seat"), + service.add_memory(app_name="travel", user_id=user, memories=[entry]), + service.add_events_to_memory( + app_name="travel", user_id=user, events=[event], session_id="s1" + ), + service.delete_memory(app_name="travel", user_id=user, memory_id="adk/1"), + ] + for call in calls: + with pytest.raises(ValueError, match="names none"): + asyncio.run(call) + assert fake.calls == [] From b5a96a08411b2db1f9bafa003d58a9fe58eb12bc Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 05:17:10 +0000 Subject: [PATCH 09/21] The ADK service extracts under a per-user Loom session; tests read the actor and poll search, not turns Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/integrations/frameworks.md | 5 +-- sdk/python/loom/integrations/google_adk.py | 10 ++++-- sdk/python/tests/test_google_adk.py | 31 +++++-------------- .../integration/test_sdk_google_adk_memory.py | 17 +++++++--- 4 files changed, 31 insertions(+), 32 deletions(-) diff --git a/docs/features/integrations/frameworks.md b/docs/features/integrations/frameworks.md index 1e2395b092..d8fa3d071f 100644 --- a/docs/features/integrations/frameworks.md +++ b/docs/features/integrations/frameworks.md @@ -385,13 +385,14 @@ apps sharing a namespace would share and lose memories. A service therefore serv app, named by `app_name`, in the namespace of its Loom agent, and refuses a call for another app; give each app its own namespace and service. The ADK user is the Loom `user_id`; an empty or `-` user, which names no user in Loom, raises `ValueError`. -Extraction runs under the ADK session, which keys Loom's record of the turns, and a search +Extraction runs under the Loom session `/`: Loom files a turn's +verbatim chunks by session alone, and ADK makes a session id unique per user only. A search reads all of the user's memories in the namespace, from every session. | ADK | Loom | | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages`; Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | -| `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom keys a turn's chunks and summary by session. A turn saved before a later rewind keeps its memories, which the app deletes by the ids a search returns | +| `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom files a turn's verbatim chunks by session. A turn saved before a later rewind keeps its memories, which the app deletes by the ids a search returns | | `add_memory` | one `memory.set` per entry under `adk/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 | | `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | | `delete_memory` | `memory.delete` of the entry's `id`, the memory's key. A verbatim chunk of a conversation or a session summary has no `id`: no key deletes it, and [erasure](../memory/retention-and-erasure.md) removes it | diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py index 9636bc8e1f..519cd1afd0 100644 --- a/sdk/python/loom/integrations/google_adk.py +++ b/sdk/python/loom/integrations/google_adk.py @@ -34,7 +34,7 @@ async def save_turn(ctx): ADK scopes memory by app and user. Loom's boundary is the namespace, so a service serves one ADK app, the namespace of its Loom agent, and refuses a call for another app; the ADK user is the Loom ``user_id``, and extraction -runs under the ADK session. Install with +runs under the Loom session ``/``. Install with ``pip install 'clickhouse-loom[google-adk]'``. """ @@ -114,7 +114,7 @@ async def add_events_to_memory( ) -> None: self._check(app_name, user_id) if not session_id: - # Loom keys a turn's chunks and summary by session, not by user. + # Loom files a turn's verbatim chunks by session alone, not by user. raise ValueError("add_events_to_memory needs the ADK session_id") await self._extract(user_id, session_id, get_active_events(list(events))) @@ -213,7 +213,11 @@ async def _extract(self, user_id: str, session_id: str, events: Sequence[Event]) ) if messages: await self._agent.memory.set_from_messages( - messages, user_id=user_id, session_id=session_id, defer=self._defer + messages, + user_id=user_id, + # ADK makes a session id unique per user only; Loom files chunks by session alone. + session_id=f"{user_id}/{session_id}", + defer=self._defer, ) diff --git a/sdk/python/tests/test_google_adk.py b/sdk/python/tests/test_google_adk.py index 2380d74192..df29147358 100644 --- a/sdk/python/tests/test_google_adk.py +++ b/sdk/python/tests/test_google_adk.py @@ -12,13 +12,14 @@ import pytest from google.adk.agents import LlmAgent +from google.adk.events import Event, EventActions from google.adk.memory import BaseMemoryService from google.adk.memory.memory_entry import MemoryEntry from google.adk.models.base_llm import BaseLlm from google.adk.models.llm_request import LlmRequest from google.adk.models.llm_response import LlmResponse from google.adk.runners import Runner -from google.adk.sessions import InMemorySessionService +from google.adk.sessions import InMemorySessionService, Session from google.adk.tools import load_memory, preload_memory from google.genai import types from loom import Agent, SyncAgent @@ -215,7 +216,7 @@ async def save(callback_context: Any) -> None: ] assert all(str(m["timestamp"]).endswith("+00:00") for m in messages) # The session keys Loom's evidence of the turns. - assert extract[2] == {"user_id": "alice", "session_id": session.id, "defer": True} + assert extract[2] == {"user_id": "alice", "session_id": f"alice/{session.id}", "defer": True} def test_the_documented_turn_callback_sends_each_turn_once() -> None: @@ -239,14 +240,11 @@ async def save_turn(ctx: Any) -> None: calls = [c for c in fake.calls if c[0] == "set_from_messages"] sent = [[m["content"] for m in c[1][0]] for c in calls] assert sent == [["I prefer aisle seats", "Noted."], ["I fly to Lisbon", "Lisbon, then."]] - # ADK's context passes the session, which keys Loom's evidence of each turn. - assert [c[2]["session_id"] for c in calls] == [session.id, session.id] + # ADK's context passes the session; Loom's session is per user. + assert [c[2]["session_id"] for c in calls] == [f"alice/{session.id}"] * 2 def test_extraction_leaves_out_thoughts_tool_calls_and_rewound_turns() -> None: - from google.adk.events import Event, EventActions - from google.adk.sessions import Session - def event(inv: str, author: str, *parts: types.Part, **kw: Any) -> Event: return Event( invocation_id=inv, author=author, content=types.Content(parts=list(parts)), **kw @@ -280,8 +278,6 @@ def event(inv: str, author: str, *parts: types.Part, **kw: Any) -> Event: def test_events_given_leave_out_a_turn_rewound_among_them() -> None: - from google.adk.events import Event, EventActions - events = [ Event(invocation_id="i1", author="user", content=_user("I live in Lisbon")), Event(invocation_id="i2", author="user", content=_user("Actually Porto")), @@ -299,16 +295,14 @@ def test_events_given_leave_out_a_turn_rewound_among_them() -> None: ) ((_, (messages,), kw),) = fake.calls assert [m["content"] for m in messages] == ["I live in Lisbon"] - assert kw["session_id"] == "s1" + assert kw["session_id"] == "alice/s1" def test_events_without_text_send_nothing() -> None: - from google.adk.events import Event - fake = _FakeMemory() silent = Event(author="user", content=types.Content(parts=[types.Part(text=" ")])) asyncio.run( - _service(fake, defer=False).add_events_to_memory( + _service(fake).add_events_to_memory( app_name="travel", user_id="u", events=[silent], session_id="s1" ) ) @@ -316,8 +310,6 @@ def test_events_without_text_send_nothing() -> None: def test_events_without_a_session_are_refused() -> None: - from google.adk.events import Event - fake = _FakeMemory() event = Event(author="user", content=_user("I live in Lisbon")) with pytest.raises(ValueError, match="session_id"): @@ -367,8 +359,6 @@ def test_delete_memory_deletes_the_key_and_needs_one() -> None: def test_a_call_for_another_app_is_refused() -> None: - from google.adk.sessions import Session - fake = _FakeMemory() service = _service(fake) calls = [ @@ -411,8 +401,6 @@ async def post(path: str, payload: dict[str, Any], *a: Any, **kw: Any) -> dict[s posts.append((path, dict(payload))) return {"results": []} - from google.adk.events import Event - agent = Agent(org="acme", namespace="travel", agent="bot", base_url="http://x", api_key="k") agent.transport.post = post # type: ignore[method-assign] service = LoomMemoryService(agent, app_name="travel", top_k=3) @@ -436,20 +424,17 @@ async def calls() -> None: "full", False, ) - assert (extract["user_id"], extract["session_id"]) == ("alice", "s1") + assert (extract["user_id"], extract["session_id"]) == ("alice", "alice/s1") assert [m["content"] for m in extract["messages"]] == ["I prefer aisle seats"] assert write["memory_key"].startswith("adk/") and write["user_id"] == "alice" @pytest.mark.parametrize("user", ["", "-"]) def test_a_user_id_that_names_no_loom_user_is_refused(user: str) -> None: - from google.adk.events import Event - fake = _FakeMemory() service = _service(fake) entry = MemoryEntry(content=_user("Alice prefers aisle seats")) event = Event(author="user", content=_user("I prefer aisle seats")) - from google.adk.sessions import Session calls = [ service.add_session_to_memory(Session(id="s", app_name="travel", user_id=user)), diff --git a/tests/integration/test_sdk_google_adk_memory.py b/tests/integration/test_sdk_google_adk_memory.py index 17e6cd9b45..6995618148 100644 --- a/tests/integration/test_sdk_google_adk_memory.py +++ b/tests/integration/test_sdk_google_adk_memory.py @@ -5,6 +5,9 @@ from __future__ import annotations +import base64 +import json +import os from collections.abc import AsyncGenerator from typing import Any @@ -70,12 +73,14 @@ async def test_a_saved_turn_reaches_a_later_prompt(agent) -> None: service = LoomMemoryService(agent, app_name="travel", honour_abstain=False, defer=False) await _turn(service, "alice", "I fly to Lisbon every month.") - async def recalled() -> bool: - prompt = await _turn(service, "alice", "Where does Alice fly every month?") - return "lisbon" in prompt.lower() + async def saved() -> bool: + found = await service.search_memory(app_name="travel", user_id="alice", query="Lisbon") + return any(m.custom_metadata["source"] == "fact" for m in found.memories) # A write is searchable once its embedding lands; eventually raises on timeout. - await eventually(recalled, description="'lisbon' in the next session's prompt") + await eventually(saved, description="the saved turn's fact") + prompt = await _turn(service, "alice", "Where does Alice fly every month?") + assert "lisbon" in prompt.lower() found = await service.search_memory(app_name="travel", user_id="bob", query="Lisbon") assert not found.memories found = await service.search_memory(app_name="travel", user_id="alice", query="Lisbon") @@ -116,6 +121,10 @@ async def ids(user: str) -> list[str | None]: [], ] assert row["valid_at"].startswith("2026-03-01") + # The server stamps the actor from the token: its subject, as `:`. + claims = os.environ["LOOM_API_KEY"].split(".")[1] + subject = json.loads(base64.urlsafe_b64decode(claims + "=" * (-len(claims) % 4)))["sub"] + assert row["actor"].endswith(f":{subject}") await service.delete_memory(app_name="travel", user_id="bob", memory_id=memory_id) assert await ids("alice") == [memory_id] # another user's delete reaches nothing await service.delete_memory(app_name="travel", user_id="alice", memory_id=memory_id) From 01dd5dfc85c9ab987d21e20c7cf64f530fca7b15 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 05:34:34 +0000 Subject: [PATCH 10/21] The ADK service ids a long value's passage by its memory, skips a delete without an id, and digests its Loom session Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/integrations/frameworks.md | 19 +++++------ sdk/python/loom/integrations/google_adk.py | 35 ++++++++++++-------- sdk/python/tests/test_google_adk.py | 37 +++++++++++++++------- 3 files changed, 56 insertions(+), 35 deletions(-) diff --git a/docs/features/integrations/frameworks.md b/docs/features/integrations/frameworks.md index d8fa3d071f..fdd14cb0a4 100644 --- a/docs/features/integrations/frameworks.md +++ b/docs/features/integrations/frameworks.md @@ -385,17 +385,18 @@ apps sharing a namespace would share and lose memories. A service therefore serv app, named by `app_name`, in the namespace of its Loom agent, and refuses a call for another app; give each app its own namespace and service. The ADK user is the Loom `user_id`; an empty or `-` user, which names no user in Loom, raises `ValueError`. -Extraction runs under the Loom session `/`: Loom files a turn's -verbatim chunks by session alone, and ADK makes a session id unique per user only. A search +Extraction runs under a Loom session derived from the user and the ADK session (`adk-` +and a digest of the pair): Loom files a turn's verbatim chunks by session alone, and ADK +makes a session id unique per user only. A search reads all of the user's memories in the namespace, from every session. -| ADK | Loom | -| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages`; Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | -| `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom files a turn's verbatim chunks by session. A turn saved before a later rewind keeps its memories, which the app deletes by the ids a search returns | -| `add_memory` | one `memory.set` per entry under `adk/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 | -| `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | -| `delete_memory` | `memory.delete` of the entry's `id`, the memory's key. A verbatim chunk of a conversation or a session summary has no `id`: no key deletes it, and [erasure](../memory/retention-and-erasure.md) removes it | +| ADK | Loom | +| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages`; Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | +| `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom files a turn's verbatim chunks by session. A turn saved before a later rewind keeps its memories, which the app deletes by the ids a search returns | +| `add_memory` | one `memory.set` per entry under `adk/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 | +| `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | +| `delete_memory` | `memory.delete` of the entry's `id`: the memory's key, or for a passage of a long value the key it was written under. A verbatim chunk of a conversation or a session summary has no `id`: no key deletes it, and [erasure](../memory/retention-and-erasure.md) removes it; a call without an id does nothing, as in ADK's own memory service | Events keep their text parts only: the model's thoughts and tool calls and results are not sent, and neither is `custom_metadata` or an entry's `author` and `id`. diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py index 519cd1afd0..357593bba2 100644 --- a/sdk/python/loom/integrations/google_adk.py +++ b/sdk/python/loom/integrations/google_adk.py @@ -34,13 +34,14 @@ async def save_turn(ctx): ADK scopes memory by app and user. Loom's boundary is the namespace, so a service serves one ADK app, the namespace of its Loom agent, and refuses a call for another app; the ADK user is the Loom ``user_id``, and extraction -runs under the Loom session ``/``. Install with +runs under a Loom session derived from the user and the ADK session. Install with ``pip install 'clickhouse-loom[google-adk]'``. """ from __future__ import annotations import hashlib +import json from collections.abc import Mapping, Sequence from datetime import UTC, datetime from typing import TYPE_CHECKING @@ -100,7 +101,7 @@ def __init__( self._key_prefix = key_prefix async def add_session_to_memory(self, session: Session) -> None: - self._check(session.app_name, session.user_id) + self._check_scope(session.app_name, session.user_id) await self._extract(session.user_id, session.id, get_active_events(session.events)) async def add_events_to_memory( @@ -112,7 +113,7 @@ async def add_events_to_memory( session_id: str | None = None, custom_metadata: Mapping[str, object] | None = None, ) -> None: - self._check(app_name, user_id) + self._check_scope(app_name, user_id) if not session_id: # Loom files a turn's verbatim chunks by session alone, not by user. raise ValueError("add_events_to_memory needs the ADK session_id") @@ -126,7 +127,7 @@ async def add_memory( memories: Sequence[MemoryEntry], custom_metadata: Mapping[str, object] | None = None, ) -> None: - self._check(app_name, user_id) + self._check_scope(app_name, user_id) for memory in memories: text = _text(memory.content) if not text: @@ -143,7 +144,7 @@ async def add_memory( async def search_memory( self, *, app_name: str, user_id: str, query: str ) -> SearchMemoryResponse: - self._check(app_name, user_id) + self._check_scope(app_name, user_id) if not query.strip(): return SearchMemoryResponse() result = await self._agent.memory.search( @@ -166,8 +167,9 @@ async def search_memory( return SearchMemoryResponse( memories=[ MemoryEntry( - # Only a memory has a key memory.delete takes. - id=hit.memory_key if hit.source == "fact" else None, + # The key memory.delete takes: a memory's, or for a passage of a long + # value the key it was written under; a conversation's chunks have none. + id=hit.memory_key if hit.source == "fact" else (hit.parent_memory_key or None), content=types.Content( role="user", parts=[types.Part(text=hit.content_excerpt)] ), @@ -182,12 +184,11 @@ async def search_memory( async def delete_memory( self, *, app_name: str, user_id: str, memory_id: str | None = None ) -> None: - self._check(app_name, user_id) - if not memory_id: - raise ValueError("delete_memory needs the memory_id a search returned") - await self._agent.memory.delete(memory_id, user_id=user_id) + self._check_scope(app_name, user_id) + if memory_id: # an entry with no id has nothing a key deletes, as in ADK's own service + await self._agent.memory.delete(memory_id, user_id=user_id) - def _check(self, app_name: str, user_id: str) -> None: + def _check_scope(self, app_name: str, user_id: str) -> None: # Loom merges a write into a matching memory of the namespace whichever agent # wrote it, so two apps in one namespace would share and lose memories. if app_name != self._app_name: @@ -215,12 +216,18 @@ async def _extract(self, user_id: str, session_id: str, events: Sequence[Event]) await self._agent.memory.set_from_messages( messages, user_id=user_id, - # ADK makes a session id unique per user only; Loom files chunks by session alone. - session_id=f"{user_id}/{session_id}", + session_id=_loom_session(user_id, session_id), defer=self._defer, ) +def _loom_session(user_id: str, session_id: str) -> str: + """The Loom session of an ADK user's session: ADK makes a session id unique per + user only, and Loom files a turn's verbatim chunks by session alone.""" + pair = json.dumps([user_id, session_id]) + return f"adk-{hashlib.sha256(pair.encode()).hexdigest()[:20]}" + + def _iso_time(text: str | None) -> datetime | None: """An ISO 8601 timestamp; ADK allows any text, which is not a ``valid_at``.""" try: diff --git a/sdk/python/tests/test_google_adk.py b/sdk/python/tests/test_google_adk.py index df29147358..50f8c536f9 100644 --- a/sdk/python/tests/test_google_adk.py +++ b/sdk/python/tests/test_google_adk.py @@ -23,7 +23,7 @@ from google.adk.tools import load_memory, preload_memory from google.genai import types from loom import Agent, SyncAgent -from loom.integrations.google_adk import LoomMemoryService +from loom.integrations.google_adk import LoomMemoryService, _loom_session from loom.memory import MemorySearchHit, MemorySearchResult from pydantic import Field @@ -216,7 +216,11 @@ async def save(callback_context: Any) -> None: ] assert all(str(m["timestamp"]).endswith("+00:00") for m in messages) # The session keys Loom's evidence of the turns. - assert extract[2] == {"user_id": "alice", "session_id": f"alice/{session.id}", "defer": True} + assert extract[2] == { + "user_id": "alice", + "session_id": _loom_session("alice", session.id), + "defer": True, + } def test_the_documented_turn_callback_sends_each_turn_once() -> None: @@ -241,7 +245,7 @@ async def save_turn(ctx: Any) -> None: sent = [[m["content"] for m in c[1][0]] for c in calls] assert sent == [["I prefer aisle seats", "Noted."], ["I fly to Lisbon", "Lisbon, then."]] # ADK's context passes the session; Loom's session is per user. - assert [c[2]["session_id"] for c in calls] == [f"alice/{session.id}"] * 2 + assert [c[2]["session_id"] for c in calls] == [_loom_session("alice", session.id)] * 2 def test_extraction_leaves_out_thoughts_tool_calls_and_rewound_turns() -> None: @@ -289,13 +293,14 @@ def test_events_given_leave_out_a_turn_rewound_among_them() -> None: ] fake = _FakeMemory() asyncio.run( - _service(fake).add_events_to_memory( + _service(fake, defer=False).add_events_to_memory( app_name="travel", user_id="alice", events=events, session_id="s1" ) ) ((_, (messages,), kw),) = fake.calls assert [m["content"] for m in messages] == ["I live in Lisbon"] - assert kw["session_id"] == "alice/s1" + assert kw["session_id"] == _loom_session("alice", "s1") + assert kw["defer"] is False # extraction inline, as the service was built def test_events_without_text_send_nothing() -> None: @@ -349,13 +354,19 @@ def test_a_timestamp_that_is_not_iso_is_no_valid_at() -> None: assert kw["valid_at"] is None -def test_delete_memory_deletes_the_key_and_needs_one() -> None: +def test_delete_memory_deletes_the_key_and_skips_an_entry_without_one() -> None: fake = _FakeMemory() service = _service(fake) asyncio.run(service.delete_memory(app_name="travel", user_id="alice", memory_id="adk/1")) + asyncio.run(service.delete_memory(app_name="travel", user_id="alice")) assert fake.calls == [("delete", ("adk/1",), {"user_id": "alice"})] - with pytest.raises(ValueError, match="memory_id"): - asyncio.run(service.delete_memory(app_name="travel", user_id="alice")) + + +def test_the_loom_session_is_per_user_and_unambiguous() -> None: + assert _loom_session("alice", "main") != _loom_session("bob", "main") + assert _loom_session("a/b", "c") != _loom_session("a", "b/c") + assert _loom_session("alice", "main") == _loom_session("alice", "main") + assert ":" not in _loom_session("a:b", "c") # Loom's chunk keys are `chunk::` def test_a_call_for_another_app_is_refused() -> None: @@ -377,14 +388,16 @@ def test_a_call_for_another_app_is_refused() -> None: def test_an_entry_id_is_the_key_delete_memory_deletes() -> None: hits = [ _hit("adk/1", "a fact"), - _hit("chunk:s1:0", "a turn", source="chunk", parent_memory_key="adk/1"), + _hit("chunk:adk/1:0", "a passage", source="chunk", parent_memory_key="adk/1"), + _hit("chunk:s1:0", "a turn", source="chunk"), _hit("summary:s1", "a session", source="summary"), ] found = asyncio.run( _service(_FakeMemory(hits)).search_memory(app_name="travel", user_id="u", query="q") ) - assert [m.id for m in found.memories] == ["adk/1", None, None] - assert [m.custom_metadata["source"] for m in found.memories] == ["fact", "chunk", "summary"] + assert [m.id for m in found.memories] == ["adk/1", "adk/1", None, None] + sources = ["fact", "chunk", "chunk", "summary"] + assert [m.custom_metadata["source"] for m in found.memories] == sources def test_without_google_adk_the_import_names_the_extra(monkeypatch: pytest.MonkeyPatch) -> None: @@ -424,7 +437,7 @@ async def calls() -> None: "full", False, ) - assert (extract["user_id"], extract["session_id"]) == ("alice", "alice/s1") + assert (extract["user_id"], extract["session_id"]) == ("alice", _loom_session("alice", "s1")) assert [m["content"] for m in extract["messages"]] == ["I prefer aisle seats"] assert write["memory_key"].startswith("adk/") and write["user_id"] == "alice" From 6ba72f1a624080495aafcf6f0f231e3f58480448 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 05:36:54 +0000 Subject: [PATCH 11/21] A conversation's passage keeps no id: deleting the fact it names leaves it Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/integrations/frameworks.md | 14 +++++++------- sdk/python/loom/integrations/google_adk.py | 6 +++--- sdk/python/tests/test_google_adk.py | 4 ++-- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/features/integrations/frameworks.md b/docs/features/integrations/frameworks.md index fdd14cb0a4..553908a9ea 100644 --- a/docs/features/integrations/frameworks.md +++ b/docs/features/integrations/frameworks.md @@ -390,13 +390,13 @@ and a digest of the pair): Loom files a turn's verbatim chunks by session alone, makes a session id unique per user only. A search reads all of the user's memories in the namespace, from every session. -| ADK | Loom | -| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages`; Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | -| `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom files a turn's verbatim chunks by session. A turn saved before a later rewind keeps its memories, which the app deletes by the ids a search returns | -| `add_memory` | one `memory.set` per entry under `adk/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 | -| `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | -| `delete_memory` | `memory.delete` of the entry's `id`: the memory's key, or for a passage of a long value the key it was written under. A verbatim chunk of a conversation or a session summary has no `id`: no key deletes it, and [erasure](../memory/retention-and-erasure.md) removes it; a call without an id does nothing, as in ADK's own memory service | +| ADK | Loom | +| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages`; Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | +| `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom files a turn's verbatim chunks by session. A turn saved before a later rewind keeps its memories, which the app deletes by the ids a search returns | +| `add_memory` | one `memory.set` per entry under `adk/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 | +| `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | +| `delete_memory` | `memory.delete` of the entry's `id`, the memory's key. A verbatim passage or a session summary has no `id`: a conversation's passage outlives the facts extracted from it, and [erasure](../memory/retention-and-erasure.md) removes it; a call without an id does nothing, as in ADK's own memory service | Events keep their text parts only: the model's thoughts and tool calls and results are not sent, and neither is `custom_metadata` or an entry's `author` and `id`. diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py index 357593bba2..39c0a7fd29 100644 --- a/sdk/python/loom/integrations/google_adk.py +++ b/sdk/python/loom/integrations/google_adk.py @@ -167,9 +167,9 @@ async def search_memory( return SearchMemoryResponse( memories=[ MemoryEntry( - # The key memory.delete takes: a memory's, or for a passage of a long - # value the key it was written under; a conversation's chunks have none. - id=hit.memory_key if hit.source == "fact" else (hit.parent_memory_key or None), + # Only a memory has a key memory.delete takes. A conversation's passage + # names the fact extracted from it, yet deleting that fact keeps it. + id=hit.memory_key if hit.source == "fact" else None, content=types.Content( role="user", parts=[types.Part(text=hit.content_excerpt)] ), diff --git a/sdk/python/tests/test_google_adk.py b/sdk/python/tests/test_google_adk.py index 50f8c536f9..5b525a1b30 100644 --- a/sdk/python/tests/test_google_adk.py +++ b/sdk/python/tests/test_google_adk.py @@ -389,13 +389,13 @@ def test_an_entry_id_is_the_key_delete_memory_deletes() -> None: hits = [ _hit("adk/1", "a fact"), _hit("chunk:adk/1:0", "a passage", source="chunk", parent_memory_key="adk/1"), - _hit("chunk:s1:0", "a turn", source="chunk"), + _hit("chunk:s1:0", "a turn", source="chunk", parent_memory_key="adk/1"), _hit("summary:s1", "a session", source="summary"), ] found = asyncio.run( _service(_FakeMemory(hits)).search_memory(app_name="travel", user_id="u", query="q") ) - assert [m.id for m in found.memories] == ["adk/1", "adk/1", None, None] + assert [m.id for m in found.memories] == ["adk/1", None, None, None] sources = ["fact", "chunk", "chunk", "summary"] assert [m.custom_metadata["source"] for m in found.memories] == sources From f3cb1986496dbc5c01056ef9372e5b7d7d7cdfc8 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 05:42:50 +0000 Subject: [PATCH 12/21] The ADK docs say a rewound turn's passages stay until erasure Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/integrations/frameworks.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/features/integrations/frameworks.md b/docs/features/integrations/frameworks.md index 553908a9ea..adfa45a117 100644 --- a/docs/features/integrations/frameworks.md +++ b/docs/features/integrations/frameworks.md @@ -387,16 +387,16 @@ another app; give each app its own namespace and service. The ADK user is the Lo `user_id`; an empty or `-` user, which names no user in Loom, raises `ValueError`. Extraction runs under a Loom session derived from the user and the ADK session (`adk-` and a digest of the pair): Loom files a turn's verbatim chunks by session alone, and ADK -makes a session id unique per user only. A search -reads all of the user's memories in the namespace, from every session. - -| ADK | Loom | -| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages`; Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | -| `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom files a turn's verbatim chunks by session. A turn saved before a later rewind keeps its memories, which the app deletes by the ids a search returns | -| `add_memory` | one `memory.set` per entry under `adk/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 | -| `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | -| `delete_memory` | `memory.delete` of the entry's `id`, the memory's key. A verbatim passage or a session summary has no `id`: a conversation's passage outlives the facts extracted from it, and [erasure](../memory/retention-and-erasure.md) removes it; a call without an id does nothing, as in ADK's own memory service | +makes a session id unique per user only. A search reads all of the user's memories in the +namespace, from every session. + +| ADK | Loom | +| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages`; Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | +| `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom files a turn's verbatim chunks by session. A turn saved before a later rewind keeps its memories: the app deletes its facts by the ids a search returns, and its verbatim passages stay until [erasure](../memory/retention-and-erasure.md) removes them | +| `add_memory` | one `memory.set` per entry under `adk/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 | +| `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | +| `delete_memory` | `memory.delete` of the entry's `id`, the memory's key. A verbatim passage or a session summary has no `id`: a conversation's passage outlives the facts extracted from it, and [erasure](../memory/retention-and-erasure.md) removes it; a call without an id does nothing, as in ADK's own memory service | Events keep their text parts only: the model's thoughts and tool calls and results are not sent, and neither is `custom_metadata` or an entry's `author` and `id`. From 6685e09b063bf8b48414fbe6101ffe6795943a0e Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 05:52:39 +0000 Subject: [PATCH 13/21] The ADK service reads a zoneless timestamp as local time; a test keeps each per-turn passage findable Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/integrations/frameworks.md | 2 +- sdk/python/loom/integrations/google_adk.py | 6 ++-- sdk/python/tests/test_google_adk.py | 10 ++++++ .../integration/test_sdk_google_adk_memory.py | 35 +++++++++++++++++++ 4 files changed, 50 insertions(+), 3 deletions(-) diff --git a/docs/features/integrations/frameworks.md b/docs/features/integrations/frameworks.md index adfa45a117..0cebeddb70 100644 --- a/docs/features/integrations/frameworks.md +++ b/docs/features/integrations/frameworks.md @@ -394,7 +394,7 @@ namespace, from every session. | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages`; Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | | `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom files a turn's verbatim chunks by session. A turn saved before a later rewind keeps its memories: the app deletes its facts by the ids a search returns, and its verbatim passages stay until [erasure](../memory/retention-and-erasure.md) removes them | -| `add_memory` | one `memory.set` per entry under `adk/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 | +| `add_memory` | one `memory.set` per entry under `/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 (one without a zone is read as local time, as ADK writes its own) | | `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | | `delete_memory` | `memory.delete` of the entry's `id`, the memory's key. A verbatim passage or a session summary has no `id`: a conversation's passage outlives the facts extracted from it, and [erasure](../memory/retention-and-erasure.md) removes it; a call without an id does nothing, as in ADK's own memory service | diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py index 39c0a7fd29..f13bcce00a 100644 --- a/sdk/python/loom/integrations/google_adk.py +++ b/sdk/python/loom/integrations/google_adk.py @@ -229,11 +229,13 @@ def _loom_session(user_id: str, session_id: str) -> str: def _iso_time(text: str | None) -> datetime | None: - """An ISO 8601 timestamp; ADK allows any text, which is not a ``valid_at``.""" + """An ISO 8601 timestamp; ADK allows any text, which is not a ``valid_at``. One + without a zone is local time, as ADK formats its own entries' timestamps.""" try: - return datetime.fromisoformat(text) if text else None + moment = datetime.fromisoformat(text) if text else None except ValueError: return None + return moment.astimezone() if moment and moment.tzinfo is None else moment def _text(content: types.Content | None) -> str: diff --git a/sdk/python/tests/test_google_adk.py b/sdk/python/tests/test_google_adk.py index 5b525a1b30..5b002ed926 100644 --- a/sdk/python/tests/test_google_adk.py +++ b/sdk/python/tests/test_google_adk.py @@ -8,6 +8,7 @@ import importlib import sys from collections.abc import AsyncGenerator +from datetime import datetime from typing import Any import pytest @@ -346,6 +347,15 @@ def test_add_memory_writes_content_keyed_memories() -> None: assert again[2]["valid_at"] is None +def test_a_timestamp_without_a_zone_is_local_time() -> None: + fake = _FakeMemory() + entry = MemoryEntry(content=_user("Alice moved to Porto"), timestamp="2026-11-01T09:00:00") + asyncio.run(_service(fake).add_memory(app_name="travel", user_id="alice", memories=[entry])) + ((_, _, kw),) = fake.calls + assert kw["valid_at"] == datetime(2026, 11, 1, 9).astimezone() + assert kw["valid_at"].tzinfo is not None + + def test_a_timestamp_that_is_not_iso_is_no_valid_at() -> None: fake = _FakeMemory() entry = MemoryEntry(content=_user("Alice moved to Porto"), timestamp="last spring") diff --git a/tests/integration/test_sdk_google_adk_memory.py b/tests/integration/test_sdk_google_adk_memory.py index 6995618148..47d4c2b676 100644 --- a/tests/integration/test_sdk_google_adk_memory.py +++ b/tests/integration/test_sdk_google_adk_memory.py @@ -151,3 +151,38 @@ async def carols_vector() -> list[str]: carol = await ids("carol") dave = await eventually(lambda: ids("dave"), description="dave's memory") assert len(carol) == len(dave) == 1 and carol != dave + + +async def test_each_turn_saved_in_one_session_keeps_its_passage(agent) -> None: + """The documented callback saves each turn on its own under one session; a search + for words only the first turn said still finds that turn's verbatim passage.""" + service = LoomMemoryService(agent, app_name="travel", honour_abstain=False, defer=False) + llm = _EchoLlm() + sessions = InMemorySessionService() + runner = Runner( + app_name="travel", + agent=LlmAgent(name="assistant", model=llm, after_agent_callback=_save_turn), + session_service=sessions, + memory_service=service, + ) + session = await sessions.create_session(app_name="travel", user_id="alice") + for text in ( + "My cat Zanzibar loves sardines from the harbour market.", + "Tomorrow I am repainting the garage door bright teal.", + ): + message = types.Content(role="user", parts=[types.Part(text=text)]) + async for _ in runner.run_async( + user_id="alice", session_id=session.id, new_message=message + ): + pass + + async def passage(query: str, words: str) -> bool: + found = await service.search_memory(app_name="travel", user_id="alice", query=query) + return any( + m.custom_metadata["source"] == "chunk" and words in (m.content.parts[0].text or "") + for m in found.memories + if m.content and m.content.parts + ) + + await eventually(lambda: passage("Zanzibar sardines harbour", "Zanzibar"), description="turn 1") + assert await passage("garage door teal", "garage door") From 7c26884ad9bd2f9cc0ddc5902ef0007ae3a1e8fd Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 05:59:56 +0000 Subject: [PATCH 14/21] The ADK service sends a long session in batches of 400 and digests every key one way Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/integrations/frameworks.md | 2 +- sdk/python/loom/integrations/google_adk.py | 22 ++++++++++++++++------ sdk/python/tests/test_google_adk.py | 13 +++++++++++++ 3 files changed, 30 insertions(+), 7 deletions(-) diff --git a/docs/features/integrations/frameworks.md b/docs/features/integrations/frameworks.md index 0cebeddb70..b2d9bb710a 100644 --- a/docs/features/integrations/frameworks.md +++ b/docs/features/integrations/frameworks.md @@ -392,7 +392,7 @@ namespace, from every session. | ADK | Loom | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages`; Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | +| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages` (400 messages a call, the op's cap); Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | | `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom files a turn's verbatim chunks by session. A turn saved before a later rewind keeps its memories: the app deletes its facts by the ids a search returns, and its verbatim passages stay until [erasure](../memory/retention-and-erasure.md) removes them | | `add_memory` | one `memory.set` per entry under `/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 (one without a zone is read as local time, as ADK writes its own) | | `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py index f13bcce00a..7223646bf4 100644 --- a/sdk/python/loom/integrations/google_adk.py +++ b/sdk/python/loom/integrations/google_adk.py @@ -64,6 +64,10 @@ async def save_turn(ctx): from loom.agent import Agent +# The server's cap on the messages of one memory.set_from_messages call. +_MAX_MESSAGES = 400 + + class LoomMemoryService(BaseMemoryService): """ADK ``BaseMemoryService`` over a Loom ``Agent``, for one ADK app. @@ -133,7 +137,7 @@ async def add_memory( if not text: continue # The user is in the key: Loom files a long value's passages by key alone. - digest = hashlib.sha256(f"{user_id}\0{text}".encode()).hexdigest()[:20] + digest = _digest(user_id, text) await self._agent.memory.set( f"{self._key_prefix}/{digest}", text, @@ -212,11 +216,13 @@ async def _extract(self, user_id: str, session_id: str, events: Sequence[Event]) "timestamp": datetime.fromtimestamp(event.timestamp, UTC).isoformat(), } ) - if messages: + session = _loom_session(user_id, session_id) + # memory.set_from_messages takes at most _MAX_MESSAGES messages a call. + for start in range(0, len(messages), _MAX_MESSAGES): await self._agent.memory.set_from_messages( - messages, + messages[start : start + _MAX_MESSAGES], user_id=user_id, - session_id=_loom_session(user_id, session_id), + session_id=session, defer=self._defer, ) @@ -224,8 +230,12 @@ async def _extract(self, user_id: str, session_id: str, events: Sequence[Event]) def _loom_session(user_id: str, session_id: str) -> str: """The Loom session of an ADK user's session: ADK makes a session id unique per user only, and Loom files a turn's verbatim chunks by session alone.""" - pair = json.dumps([user_id, session_id]) - return f"adk-{hashlib.sha256(pair.encode()).hexdigest()[:20]}" + return f"adk-{_digest(user_id, session_id)}" + + +def _digest(*parts: str) -> str: + """The first 20 hex of the sha256 of `parts`, encoded so no two tuples meet.""" + return hashlib.sha256(json.dumps(parts).encode()).hexdigest()[:20] def _iso_time(text: str | None) -> datetime | None: diff --git a/sdk/python/tests/test_google_adk.py b/sdk/python/tests/test_google_adk.py index 5b002ed926..b780f8dc1c 100644 --- a/sdk/python/tests/test_google_adk.py +++ b/sdk/python/tests/test_google_adk.py @@ -472,3 +472,16 @@ def test_a_user_id_that_names_no_loom_user_is_refused(user: str) -> None: with pytest.raises(ValueError, match="names none"): asyncio.run(call) assert fake.calls == [] + + +def test_a_long_session_is_sent_in_batches_the_server_takes() -> None: + fake = _FakeMemory() + events = [Event(author="user", content=_user(f"fact {i}")) for i in range(401)] + asyncio.run( + _service(fake).add_events_to_memory( + app_name="travel", user_id="alice", events=events, session_id="s1" + ) + ) + sizes = [len(c[1][0]) for c in fake.calls if c[0] == "set_from_messages"] + assert sizes == [400, 1] + assert {c[2]["session_id"] for c in fake.calls} == {_loom_session("alice", "s1")} From b4dd422b445faac4681e1806a8e0b02ba79ce4ce Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 06:09:18 +0000 Subject: [PATCH 15/21] The SDK reference names add_memory for the ADK service Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/reference/python-sdk.md | 6 +++--- sdk/python/loom/integrations/google_adk.py | 1 - 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/docs/reference/python-sdk.md b/docs/reference/python-sdk.md index 72dacf7439..229361fcbb 100644 --- a/docs/reference/python-sdk.md +++ b/docs/reference/python-sdk.md @@ -257,9 +257,9 @@ system prompt of an agent with no plugin; `part="reference"` lists every plane. `AgentTools` as AG2 tools; install the `[ag2]` extra. - `loom.integrations.google_adk.LoomMemoryService(agent, app_name=...)` is a Google ADK `BaseMemoryService` for one ADK app: a saved session or turn goes - to `memory.set_from_messages`, `search_memory` is `memory.search` scoped to - the ADK user, and `delete_memory` is `memory.delete`; install the - `[google-adk]` extra. + to `memory.set_from_messages`, `add_memory` is `memory.set`, `search_memory` + is `memory.search` scoped to the ADK user, and `delete_memory` is + `memory.delete`; install the `[google-adk]` extra. - `loom.integrations.pydantic_ai.loom_toolset(agent, user_id=...)` returns `AgentTools` as a Pydantic AI `FunctionToolset`; install the `[pydantic-ai]` extra. diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py index 7223646bf4..021a4e8b30 100644 --- a/sdk/python/loom/integrations/google_adk.py +++ b/sdk/python/loom/integrations/google_adk.py @@ -217,7 +217,6 @@ async def _extract(self, user_id: str, session_id: str, events: Sequence[Event]) } ) session = _loom_session(user_id, session_id) - # memory.set_from_messages takes at most _MAX_MESSAGES messages a call. for start in range(0, len(messages), _MAX_MESSAGES): await self._agent.memory.set_from_messages( messages[start : start + _MAX_MESSAGES], From b26a45e667ef9baea5262a6d4542a31695ed0509 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 06:18:47 +0000 Subject: [PATCH 16/21] An ADK entry id names the memory's key and session, so a delete reaches the user's own row Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/integrations/frameworks.md | 14 +++++----- sdk/python/loom/integrations/google_adk.py | 26 ++++++++++++++++--- sdk/python/tests/test_google_adk.py | 20 ++++++++------ .../integration/test_sdk_google_adk_memory.py | 24 ++++++++++++++++- 4 files changed, 64 insertions(+), 20 deletions(-) diff --git a/docs/features/integrations/frameworks.md b/docs/features/integrations/frameworks.md index b2d9bb710a..8a1374e391 100644 --- a/docs/features/integrations/frameworks.md +++ b/docs/features/integrations/frameworks.md @@ -390,13 +390,13 @@ and a digest of the pair): Loom files a turn's verbatim chunks by session alone, makes a session id unique per user only. A search reads all of the user's memories in the namespace, from every session. -| ADK | Loom | -| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages` (400 messages a call, the op's cap); Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | -| `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom files a turn's verbatim chunks by session. A turn saved before a later rewind keeps its memories: the app deletes its facts by the ids a search returns, and its verbatim passages stay until [erasure](../memory/retention-and-erasure.md) removes them | -| `add_memory` | one `memory.set` per entry under `/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 (one without a zone is read as local time, as ADK writes its own) | -| `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | -| `delete_memory` | `memory.delete` of the entry's `id`, the memory's key. A verbatim passage or a session summary has no `id`: a conversation's passage outlives the facts extracted from it, and [erasure](../memory/retention-and-erasure.md) removes it; a call without an id does nothing, as in ADK's own memory service | +| ADK | Loom | +| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages` (400 messages a call, the op's cap); Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | +| `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom files a turn's verbatim chunks by session. A turn saved before a later rewind keeps its memories: the app deletes its facts by the ids a search returns, and its verbatim passages stay until [erasure](../memory/retention-and-erasure.md) removes them | +| `add_memory` | one `memory.set` per entry under `/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 (one without a zone is read as local time, as ADK writes its own) | +| `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | +| `delete_memory` | `memory.delete` of the memory the entry's `id` names: the JSON pair of its key and its session, since users share extracted keys and a key alone would reach the key's newest row, any user's. A verbatim passage or a session summary has no `id`: a conversation's passage outlives the facts extracted from it, and [erasure](../memory/retention-and-erasure.md) removes it; a call without an id does nothing, as in ADK's own memory service | Events keep their text parts only: the model's thoughts and tool calls and results are not sent, and neither is `custom_metadata` or an entry's `author` and `id`. diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py index 021a4e8b30..e90ae0b558 100644 --- a/sdk/python/loom/integrations/google_adk.py +++ b/sdk/python/loom/integrations/google_adk.py @@ -73,7 +73,7 @@ class LoomMemoryService(BaseMemoryService): Saved sessions and turns go to ``memory.set_from_messages``, ``add_memory`` to ``memory.set`` and ``search_memory`` to ``memory.search`` of the ADK user's - memories; a returned memory's ``id`` is the key ``delete_memory`` deletes. ADK + memories; a returned memory's ``id`` names it for ``delete_memory``. ADK awaits its memory service, so the service takes a ``loom.Agent``. The mapping of each method is in ``docs/features/integrations/frameworks.md`` (Google ADK). """ @@ -173,7 +173,7 @@ async def search_memory( MemoryEntry( # Only a memory has a key memory.delete takes. A conversation's passage # names the fact extracted from it, yet deleting that fact keeps it. - id=hit.memory_key if hit.source == "fact" else None, + id=_entry_id(hit.memory_key, hit.session_id) if hit.source == "fact" else None, content=types.Content( role="user", parts=[types.Part(text=hit.content_excerpt)] ), @@ -189,8 +189,10 @@ async def delete_memory( self, *, app_name: str, user_id: str, memory_id: str | None = None ) -> None: self._check_scope(app_name, user_id) - if memory_id: # an entry with no id has nothing a key deletes, as in ADK's own service - await self._agent.memory.delete(memory_id, user_id=user_id) + if not memory_id: # an entry with no id has nothing a key deletes, as in ADK's own + return + key, session = _parse_entry_id(memory_id) + await self._agent.memory.delete(key, user_id=user_id, session_id=session) def _check_scope(self, app_name: str, user_id: str) -> None: # Loom merges a write into a matching memory of the namespace whichever agent @@ -226,6 +228,22 @@ async def _extract(self, user_id: str, session_id: str, events: Sequence[Event]) ) +def _entry_id(memory_key: str, session_id: str) -> str: + """A memory's entry id: its key and its session. Users share extracted keys, and a + delete by key alone finds the newest row of the key, which can be another user's.""" + return json.dumps([memory_key, session_id or "-"]) + + +def _parse_entry_id(memory_id: str) -> tuple[str, str]: + try: + key, session = json.loads(memory_id) + except (ValueError, TypeError) as e: + raise ValueError(f"{memory_id!r} is not an id this service's search returned") from e + if not (isinstance(key, str) and isinstance(session, str)): + raise ValueError(f"{memory_id!r} is not an id this service's search returned") + return key, session + + def _loom_session(user_id: str, session_id: str) -> str: """The Loom session of an ADK user's session: ADK makes a session id unique per user only, and Loom files a turn's verbatim chunks by session alone.""" diff --git a/sdk/python/tests/test_google_adk.py b/sdk/python/tests/test_google_adk.py index b780f8dc1c..27fd1a4057 100644 --- a/sdk/python/tests/test_google_adk.py +++ b/sdk/python/tests/test_google_adk.py @@ -24,7 +24,7 @@ from google.adk.tools import load_memory, preload_memory from google.genai import types from loom import Agent, SyncAgent -from loom.integrations.google_adk import LoomMemoryService, _loom_session +from loom.integrations.google_adk import LoomMemoryService, _entry_id, _loom_session from loom.memory import MemorySearchHit, MemorySearchResult from pydantic import Field @@ -167,7 +167,7 @@ def test_the_model_reads_load_memory_results() -> None: if p.function_response ] (memory,) = response.response["result"].memories - assert memory.id == "adk/1" + assert memory.id == _entry_id("adk/1", "-") assert memory.content.parts[0].text == "Alice prefers aisle seats" @@ -176,10 +176,10 @@ def test_search_leaves_out_rows_below_the_floor_and_an_abstention() -> None: found = asyncio.run( _service(_FakeMemory(hits)).search_memory(app_name="travel", user_id="u", query="q") ) - assert [m.id for m in found.memories] == ["adk/1"] + assert [m.id for m in found.memories] == [_entry_id("adk/1", "-")] everything = _service(_FakeMemory(hits), honour_abstain=False) found = asyncio.run(everything.search_memory(app_name="travel", user_id="u", query="q")) - assert [m.id for m in found.memories] == ["adk/1", "adk/2"] + assert [m.id for m in found.memories] == [_entry_id(k, "-") for k in ("adk/1", "adk/2")] abstained = _service(_FakeMemory(hits, abstain=True)) assert not asyncio.run( abstained.search_memory(app_name="travel", user_id="u", query="q") @@ -191,7 +191,7 @@ def test_search_cuts_to_top_k_and_skips_an_empty_query() -> None: found = asyncio.run( _service(fake, top_k=2).search_memory(app_name="travel", user_id="u", query="q") ) - assert [m.id for m in found.memories] == ["adk/0", "adk/1"] + assert [m.id for m in found.memories] == [_entry_id(k, "-") for k in ("adk/0", "adk/1")] assert not asyncio.run( _service(fake).search_memory(app_name="travel", user_id="u", query=" ") ).memories @@ -367,9 +367,13 @@ def test_a_timestamp_that_is_not_iso_is_no_valid_at() -> None: def test_delete_memory_deletes_the_key_and_skips_an_entry_without_one() -> None: fake = _FakeMemory() service = _service(fake) - asyncio.run(service.delete_memory(app_name="travel", user_id="alice", memory_id="adk/1")) + memory_id = _entry_id("user_seat", "adk-1") + asyncio.run(service.delete_memory(app_name="travel", user_id="alice", memory_id=memory_id)) asyncio.run(service.delete_memory(app_name="travel", user_id="alice")) - assert fake.calls == [("delete", ("adk/1",), {"user_id": "alice"})] + # The session is sent: by key alone the delete finds the key's newest row, any user's. + assert fake.calls == [("delete", ("user_seat",), {"user_id": "alice", "session_id": "adk-1"})] + with pytest.raises(ValueError, match="not an id"): + asyncio.run(service.delete_memory(app_name="travel", user_id="alice", memory_id="adk/1")) def test_the_loom_session_is_per_user_and_unambiguous() -> None: @@ -405,7 +409,7 @@ def test_an_entry_id_is_the_key_delete_memory_deletes() -> None: found = asyncio.run( _service(_FakeMemory(hits)).search_memory(app_name="travel", user_id="u", query="q") ) - assert [m.id for m in found.memories] == ["adk/1", None, None, None] + assert [m.id for m in found.memories] == [_entry_id("adk/1", "-"), None, None, None] sources = ["fact", "chunk", "chunk", "summary"] assert [m.custom_metadata["source"] for m in found.memories] == sources diff --git a/tests/integration/test_sdk_google_adk_memory.py b/tests/integration/test_sdk_google_adk_memory.py index 47d4c2b676..ce45558ad5 100644 --- a/tests/integration/test_sdk_google_adk_memory.py +++ b/tests/integration/test_sdk_google_adk_memory.py @@ -108,7 +108,8 @@ async def ids(user: str) -> list[str | None]: await eventually(lambda: ids("alice"), description="the memory found") (memory_id,) = await ids("alice") assert memory_id is not None - row = await agent.memory.get(memory_id, user_id="alice") + key, _session = json.loads(memory_id) + row = await agent.memory.get(key, user_id="alice") assert row is not None fields = ("value", "agent", "user_id", "session_id", "memory_type", "source_class", "tags") assert [row[f] for f in fields] == [ @@ -186,3 +187,24 @@ async def passage(query: str, words: str) -> bool: await eventually(lambda: passage("Zanzibar sardines harbour", "Zanzibar"), description="turn 1") assert await passage("garage door teal", "garage door") + + +async def test_a_users_delete_reaches_their_fact_when_another_user_holds_its_key(agent) -> None: + """Extracted keys are concept names two users share; the entry id carries the + session, so Alice's delete reaches her row and leaves Bob's.""" + service = LoomMemoryService(agent, app_name="travel", honour_abstain=False, defer=False) + for user in ("alice", "bob"): + await _turn(service, user, "I fly to Lisbon every month.") + + async def facts(user: str) -> set[str | None]: + found = await service.search_memory(app_name="travel", user_id=user, query="Lisbon") + return {m.id for m in found.memories if m.custom_metadata["source"] == "fact"} + + alices = await eventually(lambda: facts("alice"), description="alice's facts") + bobs = await eventually(lambda: facts("bob"), description="bob's facts") + shared = {json.loads(i)[0] for i in alices} & {json.loads(i)[0] for i in bobs} + assert shared, "the two users' extracted facts share a key" + for memory_id in alices: + await service.delete_memory(app_name="travel", user_id="alice", memory_id=memory_id) + assert not await facts("alice") & alices + assert await facts("bob") == bobs From 5cdd072ae2b6ce6b75da477b9d67f7be9225c7f6 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 06:25:48 +0000 Subject: [PATCH 17/21] The ADK service accepts only the two-string ids it returns; the shared-key test needs the fake extractor Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/integrations/frameworks.md | 14 +++++++------- sdk/python/loom/integrations/google_adk.py | 16 +++++++++------- sdk/python/tests/test_google_adk.py | 7 +++++-- tests/integration/test_sdk_google_adk_memory.py | 4 +++- 4 files changed, 24 insertions(+), 17 deletions(-) diff --git a/docs/features/integrations/frameworks.md b/docs/features/integrations/frameworks.md index 8a1374e391..b7ea2dd992 100644 --- a/docs/features/integrations/frameworks.md +++ b/docs/features/integrations/frameworks.md @@ -390,13 +390,13 @@ and a digest of the pair): Loom files a turn's verbatim chunks by session alone, makes a session id unique per user only. A search reads all of the user's memories in the namespace, from every session. -| ADK | Loom | -| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages` (400 messages a call, the op's cap); Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | -| `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom files a turn's verbatim chunks by session. A turn saved before a later rewind keeps its memories: the app deletes its facts by the ids a search returns, and its verbatim passages stay until [erasure](../memory/retention-and-erasure.md) removes them | -| `add_memory` | one `memory.set` per entry under `/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 (one without a zone is read as local time, as ADK writes its own) | -| `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | -| `delete_memory` | `memory.delete` of the memory the entry's `id` names: the JSON pair of its key and its session, since users share extracted keys and a key alone would reach the key's newest row, any user's. A verbatim passage or a session summary has no `id`: a conversation's passage outlives the facts extracted from it, and [erasure](../memory/retention-and-erasure.md) removes it; a call without an id does nothing, as in ADK's own memory service | +| ADK | Loom | +| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages` (400 messages a call, the op's cap); Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | +| `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom files a turn's verbatim chunks by session. A turn saved before a later rewind keeps its memories: the app deletes its facts by the ids a search returns, and its verbatim passages stay until [erasure](../memory/retention-and-erasure.md) removes them | +| `add_memory` | one `memory.set` per entry under `/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 (one without a zone is read as local time, as ADK writes its own) | +| `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | +| `delete_memory` | `memory.delete` of the memory the entry's `id` names: the JSON pair of its key and its session, since users share extracted keys and a key alone finds the key's newest row, which can be another user's, and then deletes nothing. A verbatim passage or a session summary has no `id`: a conversation's passage outlives the facts extracted from it, and [erasure](../memory/retention-and-erasure.md) removes it; a call without an id does nothing, as in ADK's own memory service | Events keep their text parts only: the model's thoughts and tool calls and results are not sent, and neither is `custom_metadata` or an entry's `author` and `id`. diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py index e90ae0b558..b28394075f 100644 --- a/sdk/python/loom/integrations/google_adk.py +++ b/sdk/python/loom/integrations/google_adk.py @@ -33,8 +33,8 @@ async def save_turn(ctx): ADK scopes memory by app and user. Loom's boundary is the namespace, so a service serves one ADK app, the namespace of its Loom agent, and refuses a -call for another app; the ADK user is the Loom ``user_id``, and extraction -runs under a Loom session derived from the user and the ADK session. Install with +call for another app; the ADK user is the Loom ``user_id``, and extraction runs +under a Loom session derived from the user and the ADK session. Install with ``pip install 'clickhouse-loom[google-adk]'``. """ @@ -236,12 +236,14 @@ def _entry_id(memory_key: str, session_id: str) -> str: def _parse_entry_id(memory_id: str) -> tuple[str, str]: try: - key, session = json.loads(memory_id) - except (ValueError, TypeError) as e: - raise ValueError(f"{memory_id!r} is not an id this service's search returned") from e - if not (isinstance(key, str) and isinstance(session, str)): + parsed = json.loads(memory_id) + except ValueError: + parsed = None + if not ( + isinstance(parsed, list) and len(parsed) == 2 and all(isinstance(p, str) for p in parsed) + ): raise ValueError(f"{memory_id!r} is not an id this service's search returned") - return key, session + return parsed[0], parsed[1] def _loom_session(user_id: str, session_id: str) -> str: diff --git a/sdk/python/tests/test_google_adk.py b/sdk/python/tests/test_google_adk.py index 27fd1a4057..8d6492f464 100644 --- a/sdk/python/tests/test_google_adk.py +++ b/sdk/python/tests/test_google_adk.py @@ -372,8 +372,11 @@ def test_delete_memory_deletes_the_key_and_skips_an_entry_without_one() -> None: asyncio.run(service.delete_memory(app_name="travel", user_id="alice")) # The session is sent: by key alone the delete finds the key's newest row, any user's. assert fake.calls == [("delete", ("user_seat",), {"user_id": "alice", "session_id": "adk-1"})] - with pytest.raises(ValueError, match="not an id"): - asyncio.run(service.delete_memory(app_name="travel", user_id="alice", memory_id="adk/1")) + for not_an_id in ("adk/1", '"ab"', '{"k": "s", "x": "y"}', '["k"]', '["k", 1]'): + with pytest.raises(ValueError, match="not an id"): + asyncio.run( + service.delete_memory(app_name="travel", user_id="alice", memory_id=not_an_id) + ) def test_the_loom_session_is_per_user_and_unambiguous() -> None: diff --git a/tests/integration/test_sdk_google_adk_memory.py b/tests/integration/test_sdk_google_adk_memory.py index ce45558ad5..802a5e7239 100644 --- a/tests/integration/test_sdk_google_adk_memory.py +++ b/tests/integration/test_sdk_google_adk_memory.py @@ -189,7 +189,9 @@ async def passage(query: str, words: str) -> bool: assert await passage("garage door teal", "garage door") -async def test_a_users_delete_reaches_their_fact_when_another_user_holds_its_key(agent) -> None: +async def test_a_users_delete_reaches_their_fact_when_another_user_holds_its_key( + agent, require_fake_llm +) -> None: """Extracted keys are concept names two users share; the entry id carries the session, so Alice's delete reaches her row and leaves Bob's.""" service = LoomMemoryService(agent, app_name="travel", honour_abstain=False, defer=False) From ea226b9367993f85b4e2010e05d2e05e973daf21 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 06:37:25 +0000 Subject: [PATCH 18/21] The ADK example runs a turn; tests delete a key held in two sessions and wait for a shared key Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/integrations/frameworks.md | 10 +++++- sdk/python/loom/integrations/google_adk.py | 12 +++++-- .../integration/test_sdk_google_adk_memory.py | 34 ++++++++++++++++--- 3 files changed, 48 insertions(+), 8 deletions(-) diff --git a/docs/features/integrations/frameworks.md b/docs/features/integrations/frameworks.md index b7ea2dd992..06fe606ed8 100644 --- a/docs/features/integrations/frameworks.md +++ b/docs/features/integrations/frameworks.md @@ -356,6 +356,7 @@ from google.adk.agents import LlmAgent from google.adk.runners import Runner from google.adk.sessions import InMemorySessionService from google.adk.tools import preload_memory +from google.genai import types from loom import Agent from loom.integrations.google_adk import LoomMemoryService @@ -366,6 +367,7 @@ async def save_turn(ctx): async with Agent(org="acme", namespace="support") as loom_agent: + sessions = InMemorySessionService() runner = Runner( app_name="support", agent=LlmAgent( @@ -374,9 +376,15 @@ async with Agent(org="acme", namespace="support") as loom_agent: tools=[preload_memory], after_agent_callback=save_turn, ), - session_service=InMemorySessionService(), + session_service=sessions, memory_service=LoomMemoryService(loom_agent, app_name="support"), ) + session = await sessions.create_session(app_name="support", user_id="alice") + message = types.Content(role="user", parts=[types.Part(text="I prefer aisle seats")]) + async for event in runner.run_async( + user_id="alice", session_id=session.id, new_message=message + ): + ... ``` ADK scopes memory by app and user. Loom's boundary is the namespace: a Loom write that diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py index b28394075f..8c21496433 100644 --- a/sdk/python/loom/integrations/google_adk.py +++ b/sdk/python/loom/integrations/google_adk.py @@ -9,6 +9,7 @@ from google.adk.runners import Runner from google.adk.sessions import InMemorySessionService from google.adk.tools import preload_memory + from google.genai import types from loom import Agent from loom.integrations.google_adk import LoomMemoryService @@ -19,6 +20,7 @@ async def save_turn(ctx): async with Agent(org="acme", namespace="support") as loom_agent: + sessions = InMemorySessionService() runner = Runner( app_name="support", agent=LlmAgent( @@ -27,9 +29,15 @@ async def save_turn(ctx): tools=[preload_memory], after_agent_callback=save_turn, ), - session_service=InMemorySessionService(), + session_service=sessions, memory_service=LoomMemoryService(loom_agent, app_name="support"), ) + session = await sessions.create_session(app_name="support", user_id="alice") + message = types.Content(role="user", parts=[types.Part(text="I prefer aisle seats")]) + async for event in runner.run_async( + user_id="alice", session_id=session.id, new_message=message + ): + ... ADK scopes memory by app and user. Loom's boundary is the namespace, so a service serves one ADK app, the namespace of its Loom agent, and refuses a @@ -189,7 +197,7 @@ async def delete_memory( self, *, app_name: str, user_id: str, memory_id: str | None = None ) -> None: self._check_scope(app_name, user_id) - if not memory_id: # an entry with no id has nothing a key deletes, as in ADK's own + if not memory_id: # no id, nothing to delete: ADK's InMemoryMemoryService also returns return key, session = _parse_entry_id(memory_id) await self._agent.memory.delete(key, user_id=user_id, session_id=session) diff --git a/tests/integration/test_sdk_google_adk_memory.py b/tests/integration/test_sdk_google_adk_memory.py index 802a5e7239..ab43cdfea0 100644 --- a/tests/integration/test_sdk_google_adk_memory.py +++ b/tests/integration/test_sdk_google_adk_memory.py @@ -202,11 +202,35 @@ async def facts(user: str) -> set[str | None]: found = await service.search_memory(app_name="travel", user_id=user, query="Lisbon") return {m.id for m in found.memories if m.custom_metadata["source"] == "fact"} - alices = await eventually(lambda: facts("alice"), description="alice's facts") - bobs = await eventually(lambda: facts("bob"), description="bob's facts") - shared = {json.loads(i)[0] for i in alices} & {json.loads(i)[0] for i in bobs} - assert shared, "the two users' extracted facts share a key" + async def both() -> tuple[set[str | None], set[str | None]] | None: + alices, bobs = await facts("alice"), await facts("bob") + keys = {json.loads(i)[0] for i in alices} & {json.loads(i)[0] for i in bobs} + return (alices, bobs) if keys else None # wait until the two share a key + + alices, bobs = await eventually(both, description="the users' facts sharing a key") for memory_id in alices: await service.delete_memory(app_name="travel", user_id="alice", memory_id=memory_id) assert not await facts("alice") & alices - assert await facts("bob") == bobs + assert bobs <= await facts("bob") + + +async def test_a_delete_reaches_the_key_in_each_session_it_is_served_from(agent) -> None: + """A key the user holds in two sessions is served once per session, each under its + own id, so deleting what a search returns leaves the key unserved.""" + for session, city in (("adk-a", "Lisbon"), ("adk-b", "Porto")): + await agent.memory.set( + "user_home_city", f"Alice lives in {city}", user_id="alice", session_id=session + ) + service = LoomMemoryService(agent, app_name="travel", honour_abstain=False) + + async def facts() -> set[str | None]: + found = await service.search_memory(app_name="travel", user_id="alice", query="Alice lives") + return {m.id for m in found.memories if m.custom_metadata["source"] == "fact"} + + async def two() -> set[str | None] | None: + ids = await facts() + return ids if len(ids) == 2 else None + + for memory_id in await eventually(two, description="both sessions' rows"): + await service.delete_memory(app_name="travel", user_id="alice", memory_id=memory_id) + assert await facts() == set() From 47c990992fd9e6f2ff4adf52d0b8789180457607 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 06:45:22 +0000 Subject: [PATCH 19/21] A unit test pins the session in a fact's entry id and the delete it sends Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- sdk/python/tests/test_google_adk.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/sdk/python/tests/test_google_adk.py b/sdk/python/tests/test_google_adk.py index 8d6492f464..432a588319 100644 --- a/sdk/python/tests/test_google_adk.py +++ b/sdk/python/tests/test_google_adk.py @@ -402,19 +402,24 @@ def test_a_call_for_another_app_is_refused() -> None: assert fake.calls == [] -def test_an_entry_id_is_the_key_delete_memory_deletes() -> None: +def test_only_a_fact_gets_an_entry_id_and_it_carries_the_rows_session() -> None: hits = [ - _hit("adk/1", "a fact"), + _hit("user_seat", "a fact", session_id="adk-1"), + _hit("adk/1", "an entry"), _hit("chunk:adk/1:0", "a passage", source="chunk", parent_memory_key="adk/1"), _hit("chunk:s1:0", "a turn", source="chunk", parent_memory_key="adk/1"), _hit("summary:s1", "a session", source="summary"), ] - found = asyncio.run( - _service(_FakeMemory(hits)).search_memory(app_name="travel", user_id="u", query="q") - ) - assert [m.id for m in found.memories] == [_entry_id("adk/1", "-"), None, None, None] - sources = ["fact", "chunk", "chunk", "summary"] + fake = _FakeMemory(hits) + service = _service(fake) + found = asyncio.run(service.search_memory(app_name="travel", user_id="u", query="q")) + ids = [m.id for m in found.memories] + assert ids == [_entry_id("user_seat", "adk-1"), _entry_id("adk/1", "-"), None, None, None] + sources = ["fact", "fact", "chunk", "chunk", "summary"] assert [m.custom_metadata["source"] for m in found.memories] == sources + # The id a search returned deletes that row: its key under its session. + asyncio.run(service.delete_memory(app_name="travel", user_id="u", memory_id=ids[0])) + assert fake.calls[-1] == ("delete", ("user_seat",), {"user_id": "u", "session_id": "adk-1"}) def test_without_google_adk_the_import_names_the_extra(monkeypatch: pytest.MonkeyPatch) -> None: From b8c097edad3b8a2f5b82290201d17aabb82ec9e4 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 06:53:13 +0000 Subject: [PATCH 20/21] Two ADK comments say what they mean Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- sdk/python/loom/integrations/google_adk.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/sdk/python/loom/integrations/google_adk.py b/sdk/python/loom/integrations/google_adk.py index 8c21496433..2435dfd61f 100644 --- a/sdk/python/loom/integrations/google_adk.py +++ b/sdk/python/loom/integrations/google_adk.py @@ -179,8 +179,8 @@ async def search_memory( return SearchMemoryResponse( memories=[ MemoryEntry( - # Only a memory has a key memory.delete takes. A conversation's passage - # names the fact extracted from it, yet deleting that fact keeps it. + # Only a fact is deleted by its key; a chunk outlives the fact it names + # and a summary has no key, so erasure removes both. id=_entry_id(hit.memory_key, hit.session_id) if hit.source == "fact" else None, content=types.Content( role="user", parts=[types.Part(text=hit.content_excerpt)] @@ -261,7 +261,8 @@ def _loom_session(user_id: str, session_id: str) -> str: def _digest(*parts: str) -> str: - """The first 20 hex of the sha256 of `parts`, encoded so no two tuples meet.""" + """The first 20 hex of the sha256 of `parts` as a JSON list, so two different tuples + never hash the same text.""" return hashlib.sha256(json.dumps(parts).encode()).hexdigest()[:20] From ef3d82bf985dd40f18d1b7410c10999f9122a8a8 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 16 Nov 2026 07:08:48 +0000 Subject: [PATCH 21/21] The ADK docs say a delete does not refuse a fact and an entry without text is skipped; the real-Agent test drives delete Co-Authored-By: Claude Opus 5.5 Signed-off-by: zlareb1 --- docs/features/integrations/frameworks.md | 14 +++++++------- sdk/python/tests/test_google_adk.py | 17 +++++++++++++++-- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/docs/features/integrations/frameworks.md b/docs/features/integrations/frameworks.md index 06fe606ed8..88bf9f8589 100644 --- a/docs/features/integrations/frameworks.md +++ b/docs/features/integrations/frameworks.md @@ -398,13 +398,13 @@ and a digest of the pair): Loom files a turn's verbatim chunks by session alone, makes a session id unique per user only. A search reads all of the user's memories in the namespace, from every session. -| ADK | Loom | -| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages` (400 messages a call, the op's cap); Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | -| `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom files a turn's verbatim chunks by session. A turn saved before a later rewind keeps its memories: the app deletes its facts by the ids a search returns, and its verbatim passages stay until [erasure](../memory/retention-and-erasure.md) removes them | -| `add_memory` | one `memory.set` per entry under `/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 (one without a zone is read as local time, as ADK writes its own) | -| `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | -| `delete_memory` | `memory.delete` of the memory the entry's `id` names: the JSON pair of its key and its session, since users share extracted keys and a key alone finds the key's newest row, which can be another user's, and then deletes nothing. A verbatim passage or a session summary has no `id`: a conversation's passage outlives the facts extracted from it, and [erasure](../memory/retention-and-erasure.md) removes it; a call without an id does nothing, as in ADK's own memory service | +| ADK | Loom | +| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `add_session_to_memory` | the text of the session's events, without the ones a rewind took back, sent to `memory.set_from_messages` (400 messages a call, the op's cap); Loom extracts the facts and resolves duplicates and conflicts. A session added again is extracted again, so a callback that runs every turn, as `after_agent_callback` does, saves that turn's events, as in the example | +| `add_events_to_memory` | the same for the events given, such as the latest turn; a call without a `session_id` raises `ValueError`, since Loom files a turn's verbatim chunks by session. A turn saved before a later rewind keeps its memories: the app deletes its facts by the ids a search returns, and its verbatim passages stay until [erasure](../memory/retention-and-erasure.md) removes them | +| `add_memory` | one `memory.set` per entry with text (an entry without text is skipped) under `/`, its `timestamp` as the memory's `valid_at` when it is ISO 8601 (one without a zone is read as local time, as ADK writes its own) | +| `search_memory` | `memory.search` of the user's memories; with `honour_abstain`, leaves out memories below Loom's floor and returns nothing when Loom abstains; each entry's `custom_metadata` carries `similarity` and `source`, and its `timestamp` is `valid_at` when the row has one | +| `delete_memory` | `memory.delete` of the memory the entry's `id` names: the JSON pair of its key and its session, since users share extracted keys and a key alone finds the key's newest row, which can be another user's, and then deletes nothing. A verbatim passage or a session summary has no `id`: a conversation's passage outlives the facts extracted from it, and [erasure](../memory/retention-and-erasure.md) removes it; a call without an id does nothing, as in ADK's own memory service. A delete removes the fact, it does not refuse it: adding its session again extracts it again (the per-turn callback adds each turn once), and [`blacklist.add`](../memory/conflicts-and-refusal.md#refusal-the-blacklist) refuses it | Events keep their text parts only: the model's thoughts and tool calls and results are not sent, and neither is `custom_metadata` or an entry's `author` and `id`. diff --git a/sdk/python/tests/test_google_adk.py b/sdk/python/tests/test_google_adk.py index 432a588319..95ea2ee8bb 100644 --- a/sdk/python/tests/test_google_adk.py +++ b/sdk/python/tests/test_google_adk.py @@ -448,11 +448,19 @@ async def calls() -> None: app_name="travel", user_id="alice", events=[event], session_id="s1" ) await service.add_memory(app_name="travel", user_id="alice", memories=[entry]) + await service.delete_memory( + app_name="travel", user_id="alice", memory_id=_entry_id("user_seat", "adk-1") + ) asyncio.run(calls()) paths = [p for p, _ in posts] - assert paths == ["/v1/memory.search", "/v1/memory.set_from_messages", "/v1/memory.set"] - search, extract, write = (body for _, body in posts) + assert paths == [ + "/v1/memory.search", + "/v1/memory.set_from_messages", + "/v1/memory.set", + "/v1/memory.delete", + ] + search, extract, write, delete = (body for _, body in posts) assert (search["query"], search["top_k"], search["user_id"]) == ("seat", 3, "alice") assert (search["namespace_scope"], search["bodies"], search["explain"]) == ( "this", @@ -462,6 +470,11 @@ async def calls() -> None: assert (extract["user_id"], extract["session_id"]) == ("alice", _loom_session("alice", "s1")) assert [m["content"] for m in extract["messages"]] == ["I prefer aisle seats"] assert write["memory_key"].startswith("adk/") and write["user_id"] == "alice" + assert (delete["memory_key"], delete["user_id"], delete["session_id"]) == ( + "user_seat", + "alice", + "adk-1", + ) @pytest.mark.parametrize("user", ["", "-"])