The Memory Layer for AI Agents - Drop-in memory infrastructure for AI agents and apps. Context that persists. Built for production.
Python agentic-memoryagentic-memory-systemagentsaiai-agentschatgptgenaillmlong-term-memorymemorymemory-managementpythonragstate-management
fix(client): reject empty entity IDs and filters in add and delete_all (#7581)
Kartikd26ba5e4518c
diff --git a/docs/core-concepts/memory-operations/delete.mdx b/docs/core-concepts/memory-operations/delete.mdxindex eb8f4c8c9..ddd86a8e3 100644--- a/docs/core-concepts/memory-operations/delete.mdx+++ b/docs/core-concepts/memory-operations/delete.mdx@@ -137,6 +137,10 @@ You can also filter by other parameters such as:**Breaking change:** `delete_all` previously wiped all project memories when called with no filters. It now **raises an error** if no filters are provided. Use `"*"` wildcards for intentional bulk deletion (see below).</Warning>+<Warning>+ Pass entity IDs as top-level arguments (`user_id="alice"` or `userId: "alice"`). `delete_all` does not accept `filters`. An empty or whitespace-only ID such as `user_id=""` matches every memory in the project, so the SDKs raise an error before sending the request. `delete_users` and `deleteUsers` apply the same check.+</Warning>+### Wildcard deletesSetting a filter to `"*"` deletes **all memories** for that entity type across the entire project. This is an intentionally explicit opt-in to bulk deletion.diff --git a/docs/platform/features/async-client.mdx b/docs/platform/features/async-client.mdxindex 6effd9995..964fb1ce5 100644--- a/docs/platform/features/async-client.mdx+++ b/docs/platform/features/async-client.mdx@@ -124,7 +124,7 @@ await client.deleteAll({ userId: "alice" });</CodeGroup><Note>- At least one filter (`user_id`, `agent_id`, `app_id`, or `run_id`) is required: calling `delete_all` with no filters raises an error to prevent accidental data loss. You can pass `"*"` as a value to delete all memories for a given entity type (e.g., `user_id="*"` removes memories for every user). A full project wipe requires all four filters set to `"*"`. When multiple entity filters are combined on a single `delete_all` call, only one is currently guaranteed to be honored; scope each call to a single entity id to be safe.+ At least one filter (`user_id`, `agent_id`, `app_id`, or `run_id`) is required: calling `delete_all` with no filters raises an error to prevent accidental data loss. You can pass `"*"` as a value to delete all memories for a given entity type (e.g., `user_id="*"` removes memories for every user). A full project wipe requires all four filters set to `"*"`. When multiple entity filters are combined on a single `delete_all` call, only one is currently guaranteed to be honored; scope each call to a single entity id to be safe. Entity IDs are top-level arguments, not `filters`, and an empty or whitespace-only ID raises an error instead of matching every memory.</Note>### Historydiff --git a/docs/platform/features/custom-instructions.mdx b/docs/platform/features/custom-instructions.mdxindex 8b5b1f35e..9acd741f2 100644--- a/docs/platform/features/custom-instructions.mdx+++ b/docs/platform/features/custom-instructions.mdx@@ -153,7 +153,7 @@ Both fields are also accepted per request, overriding the project setting for th```python Pythonclient.add(messages,- filters={"agent_id": "support-agent"},+ agent_id="support-agent",agent_custom_instructions="Only remember which tools errored and why.",)```diff --git a/mem0-ts/src/client/mem0.ts b/mem0-ts/src/client/mem0.tsindex 0f8725164..c386be323 100644--- a/mem0-ts/src/client/mem0.ts+++ b/mem0-ts/src/client/mem0.ts@@ -74,6 +74,34 @@ function rejectTopLevelEntityParams(}}+function rejectFilters(+ options: Record<string, any> | undefined,+ methodName: string,+): void {+ if (options?.filters != null) {+ throw new Error(+ `filters is not supported in ${methodName}(). ` ++ `Pass entity IDs at the top level, e.g. userId: "...".`,+ );+ }+}++/** Throws on an empty entity ID, which the API treats as matching every memory. */+function rejectBlankEntityIds(options: Record<string, any> | undefined): void {+ for (const [key, value] of Object.entries(options ?? {})) {+ if (+ ENTITY_PARAMS.includes(key) &&+ typeof value === "string" &&+ value.trim() === ""+ ) {+ throw new Error(+ `${key} cannot be empty or whitespace-only: an empty ID would match every memory in the project. ` ++ `To delete everything on purpose, call deleteAll() with "*" explicitly.`,+ );+ }+ }+}+function encodePathSegment(value: unknown): string {return encodeURIComponent(String(value));}@@ -396,6 +424,7 @@ export default class MemoryClient {if (!messages || (Array.isArray(messages) && messages.length === 0)) {throw new Error("Cannot process an empty messages payload.");}+ rejectFilters(options, "add");const payload = this._preparePayload(messages, options);const payloadKeys = Object.keys(payload);@@ -540,6 +569,8 @@ export default class MemoryClient {async deleteAll(options: DeleteAllMemoryOptions = {},): Promise<{ message: string }> {+ rejectFilters(options, "deleteAll");+ rejectBlankEntityIds(options);const payloadKeys = Object.keys(options || {});this._captureEvent("delete_all", [payloadKeys]);const snakeOptions = camelToSnakeKeys(this._prepareParams(options));@@ -611,6 +642,7 @@ export default class MemoryClient {runId?: string;} = {},): Promise<{ message: string }> {+ rejectBlankEntityIds(params);let to_delete: Array<{ type: string; name: string }> = [];const { userId, agentId, appId, runId } = params;diff --git a/mem0-ts/src/client/tests/memoryClient.entityGuards.test.ts b/mem0-ts/src/client/tests/memoryClient.entityGuards.test.tsnew file mode 100644index 000000000..463284852--- /dev/null+++ b/mem0-ts/src/client/tests/memoryClient.entityGuards.test.ts@@ -0,0 +1,234 @@+/** MemoryClient unit tests for entity ID handling in add, deleteAll, and deleteUsers. */+import { MemoryClient } from "../mem0";+import { createMockAllUsers, createMockUser, TEST_API_KEY } from "./helpers";+import {+ setupMockFetch,+ findFetchCall,+ getFetchBody,+ installConsoleSuppression,+} from "./setup";++installConsoleSuppression();++const BLANK_IDS = ["", " ", "\t\n"];+const ENTITY_KEYS = [+ "userId",+ "agentId",+ "appId",+ "runId",+ "user_id",+ "agent_id",+ "app_id",+ "run_id",+];++function mockDeleteAll() {+ const extra = new Map<string, { status: number; body: unknown }>();+ extra.set("/v1/memories/", { status: 200, body: { message: "Deleted" } });+ return setupMockFetch(extra);+}++describe("MemoryClient - deleteAll() blank entity IDs", () => {+ test.each(+ ENTITY_KEYS.flatMap((key) => BLANK_IDS.map((blank) => [key, blank])),+ )("rejects %s=%j without sending a request", async (key, blank) => {+ const mock = mockDeleteAll();+ const client = new MemoryClient({ apiKey: TEST_API_KEY });++ await expect(client.deleteAll({ [key]: blank } as never)).rejects.toThrow(+ key,+ );++ expect(findFetchCall(mock, "/v1/memories/", "DELETE")).toBeUndefined();+ });++ test("rejects a blank ID next to a valid ID", async () => {+ const mock = mockDeleteAll();+ const client = new MemoryClient({ apiKey: TEST_API_KEY });++ await expect(+ client.deleteAll({ userId: "u1", agentId: "" }),+ ).rejects.toThrow("agentId");++ expect(findFetchCall(mock, "/v1/memories/", "DELETE")).toBeUndefined();+ });++ test("error explains the risk and the wildcard", async () => {+ mockDeleteAll();+ const client = new MemoryClient({ apiKey: TEST_API_KEY });++ await expect(client.deleteAll({ userId: "" })).rejects.toThrow(+ /every memory in the project.*"\*"/,+ );+ });+});++describe("MemoryClient - deleteAll() valid inputs", () => {+ test("sends the entity ID as a query param", async () => {+ const mock = mockDeleteAll();+ const client = new MemoryClient({ apiKey: TEST_API_KEY });++ await client.deleteAll({ userId: "u1" });++ const call = findFetchCall(mock, "/v1/memories/?", "DELETE");+ expect(call![0]).toContain("user_id=u1");+ });++ test("still allows the explicit wildcard", async () => {+ const mock = mockDeleteAll();+ const client = new MemoryClient({ apiKey: TEST_API_KEY });++ await client.deleteAll({ userId: "*" });++ const call = findFetchCall(mock, "/v1/memories/?", "DELETE");+ expect(call![0]).toContain("user_id=*");+ });++ test("ignores undefined entity IDs", async () => {+ const mock = mockDeleteAll();+ const client = new MemoryClient({ apiKey: TEST_API_KEY });++ await client.deleteAll({ userId: "u1", agentId: undefined });++ const call = findFetchCall(mock, "/v1/memories/?", "DELETE");+ expect(call![0]).not.toContain("agent_id");+ });+});++describe("MemoryClient - deleteAll() rejects filters", () => {+ test("throws and sends no request", async () => {+ const mock = mockDeleteAll();+ const client = new MemoryClient({ apiKey: TEST_API_KEY });++ await expect(+ client.deleteAll({ filters: { user_id: "u1" } } as never),+ ).rejects.toThrow(/filters.*userId/);++ expect(findFetchCall(mock, "/v1/memories/", "DELETE")).toBeUndefined();+ });+});++describe("MemoryClient - deleteUsers() blank entity IDs", () => {+ test.each(+ ["userId", "agentId", "appId", "runId"].flatMap((key) =>+ BLANK_IDS.map((blank) => [key, blank]),+ ),+ )("rejects %s=%j before any request", async (key, blank) => {+ const extra = new Map<string, { status: number; body: unknown }>();+ extra.set("/v1/entities/", {+ status: 200,+ body: createMockAllUsers([createMockUser()]),+ });+ const mock = setupMockFetch(extra);+ const client = new MemoryClient({ apiKey: TEST_API_KEY });++ await expect(client.deleteUsers({ [key]: blank })).rejects.toThrow(key);++ expect(findFetchCall(mock, "/v1/entities/")).toBeUndefined();+ expect(findFetchCall(mock, "/v2/entities/", "DELETE")).toBeUndefined();+ });+});++describe("MemoryClient - deleteUsers() valid inputs", () => {+ test("deletes the named entity", async () => {+ const extra = new Map<string, { status: number; body: unknown }>();+ extra.set("/v2/entities/user/u1/", {+ status: 200,+ body: { message: "ok" },+ });+ const mock = setupMockFetch(extra);+ const client = new MemoryClient({ apiKey: TEST_API_KEY });++ await client.deleteUsers({ userId: "u1" });++ expect(+ findFetchCall(mock, "/v2/entities/user/u1/", "DELETE"),+ ).toBeDefined();+ });++ test("with no IDs still deletes every listed entity", async () => {+ const extra = new Map<string, { status: number; body: unknown }>();+ extra.set("/v1/entities/", {+ status: 200,+ body: createMockAllUsers([+ createMockUser({ name: "u1", type: "user" }),+ createMockUser({ name: "a1", type: "agent" }),+ ]),+ });+ extra.set("/v2/entities/user/u1/", {+ status: 200,+ body: { message: "ok" },+ });+ extra.set("/v2/entities/agent/a1/", {+ status: 200,+ body: { message: "ok" },+ });+ const mock = setupMockFetch(extra);+ const client = new MemoryClient({ apiKey: TEST_API_KEY });++ await client.deleteUsers();++ expect(+ findFetchCall(mock, "/v2/entities/user/u1/", "DELETE"),+ ).toBeDefined();+ expect(+ findFetchCall(mock, "/v2/entities/agent/a1/", "DELETE"),+ ).toBeDefined();+ });+});++describe("MemoryClient - add() entity IDs", () => {+ function mockAdd() {+ const extra = new Map<string, { status: number; body: unknown }>();+ extra.set("/v3/memories/add/", { status: 200, body: [] });+ return setupMockFetch(extra);+ }++ test("rejects filters and sends no request", async () => {+ const mock = mockAdd();+ const client = new MemoryClient({ apiKey: TEST_API_KEY });++ await expect(+ client.add([{ role: "user", content: "hi" }], {+ filters: { user_id: "u1" },+ }),+ ).rejects.toThrow(/filters.*userId/);++ expect(findFetchCall(mock, "/v3/memories/add/", "POST")).toBeUndefined();+ });++ test("treats filters: undefined as not provided", async () => {+ const mock = mockAdd();+ const client = new MemoryClient({ apiKey: TEST_API_KEY });++ await client.add([{ role: "user", content: "hi" }], {+ userId: "u1",+ filters: undefined,+ });++ const call = findFetchCall(mock, "/v3/memories/add/", "POST");+ expect(getFetchBody(call!).user_id).toBe("u1");+ });++ test("sends top-level entity IDs in the body", async () => {+ const mock = mockAdd();+ const client = new MemoryClient({ apiKey: TEST_API_KEY });++ await client.add([{ role: "user", content: "hi" }], {+ userId: "u1",+ agentId: "a1",+ appId: "p1",+ runId: "r1",+ });++ const body = getFetchBody(+ findFetchCall(mock, "/v3/memories/add/", "POST")!,+ );+ expect(body).toMatchObject({+ user_id: "u1",+ agent_id: "a1",+ app_id: "p1",+ run_id: "r1",+ });+ });+});diff --git a/mem0/client/main.py b/mem0/client/main.pyindex d65d4f0b1..18896466a 100644--- a/mem0/client/main.py+++ b/mem0/client/main.py@@ -91,6 +91,24 @@ def _encode_path_segment(value: Any) -> str:return quote(str(value), safe="")+def _reject_filters(method: str, params: Dict[str, Any]) -> None:+ """Raise when filters is passed to an endpoint that reads entity IDs at the top level."""+ if params.get("filters") is not None:+ raise ValueError(+ f"filters is not supported in {method}(). Pass entity IDs at the top level, e.g. user_id='...'."+ )+++def _reject_blank_entity_ids(params: Dict[str, Any]) -> None:+ """Raise on an empty or whitespace-only entity ID, which the API treats as matching every memory."""+ for name, value in params.items():+ if name in ENTITY_PARAMS and isinstance(value, str) and not value.strip():+ raise ValueError(+ f"{name} cannot be empty or whitespace-only: an empty ID would match every memory in the project. "+ f"To delete everything on purpose, call delete_all() with '*' explicitly."+ )++def _maybe_alias_anon_to_email(user_email):"""Fire $identify per prior anon ID so PostHog merges them into email.@@ -309,7 +327,7 @@ class MemoryClient:a user message.options: Typed options for the add operation (AddMemoryOptions).**kwargs: Additional parameters such as user_id, agent_id, app_id,- metadata, filters.+ run_id, metadata. Entity IDs go at the top level, not in filters.Returns:A dictionary containing the API response in v1.1 format.@@ -321,8 +339,10 @@ class MemoryClient:MemoryQuotaExceededError: If memory quota is exceeded.NetworkError: If network connectivity issues occur.MemoryNotFoundError: If the memory doesn't exist (for updates/deletes).+ ValueError: If filters is passed."""kwargs = {**(options.model_dump(exclude_unset=True) if options else {}), **kwargs}+ _reject_filters("add", kwargs)# Handle different message input formats (align with OSS behavior)if isinstance(messages, str):messages = [{"role": "user", "content": messages}]@@ -533,12 +553,12 @@ class MemoryClient:@api_error_handlerdef delete_all(self, options: Optional[DeleteAllMemoryOptions] = None, **kwargs) -> Dict[str, str]:- """Delete all memories, with optional filtering.+ """Delete all memories for the given entity IDs.Args:options: Typed options for the delete_all operation (DeleteAllMemoryOptions).- **kwargs: Optional parameters for filtering (user_id, agent_id,- app_id).+ **kwargs: Entity IDs to delete memories for (user_id, agent_id, app_id, run_id).+ Pass '*' to target every entity of that type.Returns:A dictionary containing the API response.@@ -550,8 +570,11 @@ class MemoryClient:MemoryQuotaExceededError: If memory quota is exceeded.NetworkError: If network connectivity issues occur.MemoryNotFoundError: If the memory doesn't exist (for updates/deletes).+ ValueError: If filters is passed or an entity ID is empty or whitespace-only."""kwargs = {**(options.model_dump(exclude_unset=True) if options else {}), **kwargs}+ _reject_filters("delete_all", kwargs)+ _reject_blank_entity_ids(kwargs)params = self._prepare_params(kwargs)response = self.client.delete("/v1/memories/", params=params)response.raise_for_status()@@ -615,12 +638,13 @@ class MemoryClient:Dict with success messageRaises:- ValueError: If specified entity not found+ ValueError: If specified entity not found or an entity ID is empty or whitespace-onlyValidationError: If the input data is invalid.AuthenticationError: If authentication fails.MemoryNotFoundError: If the entity doesn't exist.NetworkError: If network connectivity issues occur."""+ _reject_blank_entity_ids({"user_id": user_id, "agent_id": agent_id, "app_id": app_id, "run_id": run_id})if user_id:to_delete = [{"type": "user", "name": user_id}]@@ -1404,7 +1428,7 @@ class AsyncMemoryClient:a user message.options: Typed options for the add operation (AddMemoryOptions).**kwargs: Additional parameters such as user_id, agent_id, app_id,- metadata, filters.+ run_id, metadata. Entity IDs go at the top level, not in filters.Returns:A dictionary containing the API response in v1.1 format.@@ -1416,8 +1440,10 @@ class AsyncMemoryClient:MemoryQuotaExceededError: If memory quota is exceeded.NetworkError: If network connectivity issues occur.MemoryNotFoundError: If the memory doesn't exist (for updates/deletes).+ ValueError: If filters is passed."""kwargs = {**(options.model_dump(exclude_unset=True) if options else {}), **kwargs}+ _reject_filters("add", kwargs)# Handle different message input formats (align with OSS behavior)if isinstance(messages, str):messages = [{"role": "user", "content": messages}]@@ -1614,11 +1640,12 @@ class AsyncMemoryClient:@api_error_handlerasync def delete_all(self, options: Optional[DeleteAllMemoryOptions] = None, **kwargs) -> Dict[str, str]:- """Delete all memories, with optional filtering.+ """Delete all memories for the given entity IDs.Args:options: Typed options for the delete_all operation (DeleteAllMemoryOptions).- **kwargs: Optional parameters for filtering (user_id, agent_id, app_id).+ **kwargs: Entity IDs to delete memories for (user_id, agent_id, app_id, run_id).+ Pass '*' to target every entity of that type.Returns:A dictionary containing the API response.@@ -1630,8 +1657,11 @@ class AsyncMemoryClient:MemoryQuotaExceededError: If memory quota is exceeded.NetworkError: If network connectivity issues occur.MemoryNotFoundError: If the memory doesn't exist (for updates/deletes).+ ValueError: If filters is passed or an entity ID is empty or whitespace-only."""kwargs = {**(options.model_dump(exclude_unset=True) if options else {}), **kwargs}+ _reject_filters("delete_all", kwargs)+ _reject_blank_entity_ids(kwargs)params = self._prepare_params(kwargs)response = await self.async_client.delete("/v1/memories/", params=params)response.raise_for_status()@@ -1694,12 +1724,13 @@ class AsyncMemoryClient:Dict with success messageRaises:- ValueError: If specified entity not found+ ValueError: If specified entity not found or an entity ID is empty or whitespace-onlyValidationError: If the input data is invalid.AuthenticationError: If authentication fails.MemoryNotFoundError: If the entity doesn't exist.NetworkError: If network connectivity issues occur."""+ _reject_blank_entity_ids({"user_id": user_id, "agent_id": agent_id, "app_id": app_id, "run_id": run_id})if user_id:to_delete = [{"type": "user", "name": user_id}]diff --git a/mem0/client/types.py b/mem0/client/types.pyindex 5663dcf5d..5d88b821f 100644--- a/mem0/client/types.py+++ b/mem0/client/types.py@@ -1,11 +1,4 @@-"""Pydantic option models for MemoryClient methods.--These models provide IDE autocompletion, runtime validation, and type safety.-Methods accept both typed options and **kwargs for backward compatibility.--Identity fields (user_id, agent_id, app_id, run_id) must be passed inside-the ``filters`` dict — the v3 API does not accept them at the top level.-"""+"""Pydantic option models for MemoryClient methods."""from typing import Any, Dict, List, Optional, Union@@ -13,15 +6,12 @@ from pydantic import BaseModel, Fieldclass AddMemoryOptions(BaseModel):- """Options for the add() method.-- Identity fields (user_id, agent_id, app_id, run_id) must be passed inside- the ``filters`` dict — the v3 API does not accept them at the top level.- """+ """Options for the add() method, with entity IDs passed at the top level."""- filters: Optional[Dict[str, Any]] = Field(- default=None, description="Filters containing entity IDs (e.g. {'user_id': '...'})"- )+ user_id: Optional[str] = Field(default=None, description="User the memory belongs to")+ agent_id: Optional[str] = Field(default=None, description="Agent the memory belongs to")+ app_id: Optional[str] = Field(default=None, description="App the memory belongs to")+ run_id: Optional[str] = Field(default=None, description="Run the memory belongs to")metadata: Optional[Dict[str, Any]] = Field(default=None, description="Additional metadata for the memory")infer: Optional[bool] = Field(default=None, description="Whether to infer memories from the input")custom_categories: Optional[List[Dict[str, Any]]] = Field(@@ -86,15 +76,12 @@ class GetAllMemoryOptions(BaseModel):class DeleteAllMemoryOptions(BaseModel):- """Options for the delete_all() method.+ """Options for the delete_all() method, with entity IDs passed at the top level."""- Identity fields (user_id, agent_id, app_id, run_id) must be passed inside- the ``filters`` dict — the API does not accept them at the top level.- """-- filters: Optional[Dict[str, Any]] = Field(- default=None, description="Filters containing entity IDs (e.g. {'user_id': '...'})"- )+ user_id: Optional[str] = Field(default=None, description="Delete memories belonging to this user")+ agent_id: Optional[str] = Field(default=None, description="Delete memories belonging to this agent")+ app_id: Optional[str] = Field(default=None, description="Delete memories belonging to this app")+ run_id: Optional[str] = Field(default=None, description="Delete memories belonging to this run")class UpdateMemoryOptions(BaseModel):@@ -103,7 +90,9 @@ class UpdateMemoryOptions(BaseModel):text: Optional[str] = Field(default=None, description="New text content for the memory")metadata: Optional[Dict[str, Any]] = Field(default=None, description="Updated metadata")timestamp: Optional[Union[int, float, str]] = Field(default=None, description="Updated timestamp")- expiration_date: Optional[str] = Field(default=None, description="Expiration date in YYYY-MM-DD format, or None to clear")+ expiration_date: Optional[str] = Field(+ default=None, description="Expiration date in YYYY-MM-DD format, or None to clear"+ )class ProjectUpdateOptions(BaseModel):diff --git a/mem0/proxy/main.py b/mem0/proxy/main.pyindex 167bc3f58..5806fca74 100644--- a/mem0/proxy/main.py+++ b/mem0/proxy/main.py@@ -99,7 +99,7 @@ class Completions:prepared_messages = self._prepare_messages(messages)if prepared_messages[-1]["role"] == "user":- self._async_add_to_memory(messages, user_id, agent_id, run_id, metadata, filters)+ self._async_add_to_memory(messages, user_id, agent_id, run_id, metadata)relevant_memories = self._fetch_relevant_memories(messages, user_id, agent_id, run_id, filters, top_k)logger.debug(f"Retrieved {len(relevant_memories)} relevant memories")prepared_messages[-1]["content"] = self._format_query_with_memories(messages, relevant_memories)@@ -146,7 +146,7 @@ class Completions:return [{"role": "system", "content": MEMORY_ANSWER_PROMPT}] + messagesreturn messages- def _async_add_to_memory(self, messages, user_id, agent_id, run_id, metadata, filters):+ def _async_add_to_memory(self, messages, user_id, agent_id, run_id, metadata):def add_task():logger.debug("Adding to memory asynchronously")self.mem0_client.add(@@ -155,7 +155,6 @@ class Completions:agent_id=agent_id,run_id=run_id,metadata=metadata,- filters=filters,)threading.Thread(target=add_task, daemon=True).start()diff --git a/tests/test_client.py b/tests/test_client.pyindex 07fc2052b..138b8a97d 100644--- a/tests/test_client.py+++ b/tests/test_client.py@@ -602,7 +602,7 @@ class TestAddAgentCustomInstructions:mock_memory_client.add("hello",- filters={"agent_id": "a1"},+ agent_id="a1",agent_custom_instructions="remember tool failures",)@@ -617,7 +617,7 @@ class TestAddAgentCustomInstructions:mock_memory_client.add("hello",AddMemoryOptions(- filters={"agent_id": "a1"},+ agent_id="a1",agent_custom_instructions="remember tool failures",),)@@ -629,7 +629,7 @@ class TestAddAgentCustomInstructions:"""Callers that don't use the feature send an unchanged payload."""self._mock_add(mock_memory_client)- mock_memory_client.add("hello", filters={"user_id": "u1"})+ mock_memory_client.add("hello", user_id="u1")_, kwargs = mock_memory_client.client.post.call_argsassert "agent_custom_instructions" not in kwargs["json"]diff --git a/tests/test_client_entity_guards.py b/tests/test_client_entity_guards.pynew file mode 100644index 000000000..28bef2a75--- /dev/null+++ b/tests/test_client_entity_guards.py@@ -0,0 +1,198 @@+"""Tests for entity ID handling in MemoryClient add, delete_all, and delete_users."""++import asyncio+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from mem0.client.main import AsyncMemoryClient, MemoryClient+from mem0.client.types import AddMemoryOptions, DeleteAllMemoryOptions++ENTITY_FIELDS = ["user_id", "agent_id", "app_id", "run_id"]+BLANK_IDS = ["", " ", "\t\n"]+++def _ok_response(body=None):+ response = MagicMock()+ response.json.return_value = body if body is not None else {"message": "ok"}+ response.raise_for_status.return_value = None+ return response+++def sync_client():+ client = MemoryClient.__new__(MemoryClient)+ client.client = MagicMock()+ client.client.post.return_value = _ok_response()+ client.client.delete.return_value = _ok_response()+ with patch("mem0.client.main.capture_client_event"):+ yield client+++def async_client():+ client = AsyncMemoryClient.__new__(AsyncMemoryClient)+ client.async_client = MagicMock()+ client.async_client.post = AsyncMock(return_value=_ok_response())+ client.async_client.delete = AsyncMock(return_value=_ok_response())+ with patch("mem0.client.main.capture_client_event"):+ yield client+++class TestDeleteAllBlankEntityIds:+ @pytest.mark.parametrize("field", ENTITY_FIELDS)+ @pytest.mark.parametrize("blank", BLANK_IDS)+ def test_sync_raises_without_http_call(self, sync_client, field, blank):+ with pytest.raises(ValueError, match=field):+ sync_client.delete_all(**{field: blank})++ sync_client.client.delete.assert_not_called()++ @pytest.mark.parametrize("field", ENTITY_FIELDS)+ @pytest.mark.parametrize("blank", BLANK_IDS)+ def test_async_raises_without_http_call(self, async_client, field, blank):+ with pytest.raises(ValueError, match=field):+ asyncio.run(async_client.delete_all(**{field: blank}))++ async_client.async_client.delete.assert_not_called()++ def test_blank_id_next_to_valid_id_still_raises(self, sync_client):+ with pytest.raises(ValueError, match="agent_id"):+ sync_client.delete_all(user_id="u1", agent_id="")++ sync_client.client.delete.assert_not_called()++ def test_blank_id_in_typed_options_raises(self, sync_client):+ with pytest.raises(ValueError, match="user_id"):+ sync_client.delete_all(DeleteAllMemoryOptions(user_id=" "))++ sync_client.client.delete.assert_not_called()++ def test_error_explains_the_risk_and_the_wildcard(self, sync_client):+ with pytest.raises(ValueError) as exc_info:+ sync_client.delete_all(user_id="")++ message = str(exc_info.value)+ assert "every memory in the project" in message+ assert "'*'" in message+++class TestDeleteAllValidInputs:+ def test_sync_sends_entity_id_as_query_param(self, sync_client):+ sync_client.delete_all(user_id="u1")++ sync_client.client.delete.assert_called_once_with("/v1/memories/", params={"user_id": "u1"})++ def test_async_sends_entity_id_as_query_param(self, async_client):+ asyncio.run(async_client.delete_all(user_id="u1"))++ async_client.async_client.delete.assert_called_once_with("/v1/memories/", params={"user_id": "u1"})++ def test_typed_options_send_entity_id_as_query_param(self, sync_client):+ sync_client.delete_all(DeleteAllMemoryOptions(user_id="u1"))++ sync_client.client.delete.assert_called_once_with("/v1/memories/", params={"user_id": "u1"})++ def test_wildcard_is_still_allowed(self, sync_client):+ sync_client.delete_all(user_id="*")++ sync_client.client.delete.assert_called_once_with("/v1/memories/", params={"user_id": "*"})+++class TestDeleteAllRejectsFilters:+ def test_sync_raises_without_http_call(self, sync_client):+ with pytest.raises(ValueError, match="filters"):+ sync_client.delete_all(filters={"user_id": "u1"})++ sync_client.client.delete.assert_not_called()++ def test_async_raises_without_http_call(self, async_client):+ with pytest.raises(ValueError, match="filters"):+ asyncio.run(async_client.delete_all(filters={"user_id": "u1"}))++ async_client.async_client.delete.assert_not_called()+++class TestDeleteUsersBlankEntityIds:+ @pytest.mark.parametrize("field", ENTITY_FIELDS)+ @pytest.mark.parametrize("blank", BLANK_IDS)+ def test_sync_raises_before_any_request(self, sync_client, field, blank):+ with patch.object(sync_client, "users") as users:+ with pytest.raises(ValueError, match=field):+ sync_client.delete_users(**{field: blank})++ users.assert_not_called()+ sync_client.client.delete.assert_not_called()++ @pytest.mark.parametrize("field", ENTITY_FIELDS)+ @pytest.mark.parametrize("blank", BLANK_IDS)+ def test_async_raises_before_any_request(self, async_client, field, blank):+ with patch.object(async_client, "users", new=AsyncMock()) as users:+ with pytest.raises(ValueError, match=field):+ asyncio.run(async_client.delete_users(**{field: blank}))++ users.assert_not_called()+ async_client.async_client.delete.assert_not_called()+++class TestDeleteUsersValidInputs:+ def test_sync_deletes_the_named_entity(self, sync_client):+ sync_client.delete_users(user_id="u1")++ sync_client.client.delete.assert_called_once_with("/v2/entities/user/u1/", params={})++ def test_async_deletes_the_named_entity(self, async_client):+ asyncio.run(async_client.delete_users(user_id="u1"))++ async_client.async_client.delete.assert_called_once_with("/v2/entities/user/u1/", params={})++ def test_no_ids_still_deletes_every_listed_entity(self, sync_client):+ listing = {"results": [{"type": "user", "name": "u1"}, {"type": "agent", "name": "a1"}]}++ with patch.object(sync_client, "users", return_value=listing):+ sync_client.delete_users()++ deleted_paths = [call.args[0] for call in sync_client.client.delete.call_args_list]+ assert deleted_paths == ["/v2/entities/user/u1/", "/v2/entities/agent/a1/"]+++class TestAddEntityIds:+ def test_sync_rejects_filters_without_http_call(self, sync_client):+ with pytest.raises(ValueError, match="user_id"):+ sync_client.add("hello", filters={"user_id": "u1"})++ sync_client.client.post.assert_not_called()++ def test_async_rejects_filters_without_http_call(self, async_client):+ with pytest.raises(ValueError, match="user_id"):+ asyncio.run(async_client.add("hello", filters={"user_id": "u1"}))++ async_client.async_client.post.assert_not_called()++ def test_filters_none_is_treated_as_not_provided(self, sync_client):+ sync_client.add("hello", user_id="u1", filters=None)++ payload = sync_client.client.post.call_args.kwargs["json"]+ assert payload["user_id"] == "u1"+ assert "filters" not in payload++ def test_sync_typed_options_put_entity_ids_in_payload(self, sync_client):+ sync_client.add("hello", AddMemoryOptions(user_id="u1", agent_id="a1", app_id="p1", run_id="r1"))++ payload = sync_client.client.post.call_args.kwargs["json"]+ assert payload["user_id"] == "u1"+ assert payload["agent_id"] == "a1"+ assert payload["app_id"] == "p1"+ assert payload["run_id"] == "r1"++ def test_async_typed_options_put_entity_ids_in_payload(self, async_client):+ asyncio.run(async_client.add("hello", AddMemoryOptions(user_id="u1")))++ payload = async_client.async_client.post.call_args.kwargs["json"]+ assert payload["user_id"] == "u1"++ def test_kwargs_put_entity_ids_in_payload(self, sync_client):+ sync_client.add("hello", user_id="u1")++ payload = sync_client.client.post.call_args.kwargs["json"]+ assert payload["user_id"] == "u1"diff --git a/tests/test_proxy.py b/tests/test_proxy.pyindex 8e48a4c6d..26209695e 100644--- a/tests/test_proxy.py+++ b/tests/test_proxy.py@@ -86,6 +86,25 @@ def test_completions_create(mock_memory_client, mock_litellm):assert response == {"choices": [{"message": {"content": "I'm doing well, thank you!"}}]}+def test_completions_create_keeps_filters_out_of_add(mock_memory_client, mock_litellm):+ completions = Completions(mock_memory_client)+ mock_memory_client.search.return_value = []+ mock_litellm.supports_function_calling.return_value = True++ with patch("mem0.proxy.main.threading.Thread") as mock_thread:+ mock_thread.side_effect = lambda target, daemon: Mock(start=target)+ completions.create(+ model="gpt-4.1-nano-2025-04-14",+ messages=[{"role": "user", "content": "Hello"}],+ user_id="test_user",+ filters={"categories": {"in": ["travel"]}},+ )++ assert "filters" not in mock_memory_client.add.call_args.kwargs+ assert mock_memory_client.add.call_args.kwargs["user_id"] == "test_user"+ assert mock_memory_client.search.call_args.kwargs["filters"] == {"categories": {"in": ["travel"]}}++def test_completions_create_with_system_message(mock_memory_client, mock_litellm):completions = Completions(mock_memory_client)