Enterprise agent platform for building, deploying, and operating AI teammates.
fix(memory): never re-create a note an update raced a delete for (#3816)
Zhenghao Yinc5c94700dc5f
diff --git a/src/xagent/core/memory/in_memory.py b/src/xagent/core/memory/in_memory.pyindex 9b0561713..9a6612792 100644--- a/src/xagent/core/memory/in_memory.py+++ b/src/xagent/core/memory/in_memory.py@@ -1,5 +1,6 @@from __future__ import annotations+import threadingimport uuidfrom typing import Any, List, Optional@@ -13,11 +14,16 @@ class InMemoryMemoryStore(MemoryStore):def __init__(self) -> None:self._store: dict[str, MemoryNote] = {}+ # Serializes the check-then-write of ``update`` against ``delete``, so+ # an update never re-creates a note deleted while it ran (the same+ # contract as ``LanceDBMemoryStore.update``).+ self._lock = threading.Lock()def add(self, note: MemoryNote) -> MemoryResponse:note_id = note.id or str(uuid.uuid4())note.id = note_id- self._store[note_id] = note+ with self._lock:+ self._store[note_id] = notereturn MemoryResponse(success=True, memory_id=note_id)def get(self, note_id: str) -> MemoryResponse:@@ -30,21 +36,23 @@ class InMemoryMemoryStore(MemoryStore):)def update(self, note: MemoryNote) -> MemoryResponse:- if note.id is None or note.id not in self._store:- return MemoryResponse(- success=False, error="Note not found or ID missing", memory_id=note.id- )- self._store[note.id] = note+ """Replace a stored note, only while it still exists (never re-creates it)."""+ with self._lock:+ if note.id is None or note.id not in self._store:+ return MemoryResponse(+ success=False,+ error="Note not found or ID missing",+ memory_id=note.id,+ )+ self._store[note.id] = notereturn MemoryResponse(success=True, memory_id=note.id)def delete(self, note_id: str) -> MemoryResponse:- if note_id in self._store:- del self._store[note_id]+ with self._lock:+ deleted = self._store.pop(note_id, None) is not None+ if deleted:return MemoryResponse(success=True, memory_id=note_id)- else:- return MemoryResponse(- success=False, error="Note not found", memory_id=note_id- )+ return MemoryResponse(success=False, error="Note not found", memory_id=note_id)def search(self,@@ -64,7 +72,8 @@ class InMemoryMemoryStore(MemoryStore):return results[:k]def clear(self) -> None:- self._store.clear()+ with self._lock:+ self._store.clear()def list_all(self, filters: Optional[dict[str, Any]] = None) -> List[MemoryNote]:if filters:diff --git a/src/xagent/core/memory/lancedb.py b/src/xagent/core/memory/lancedb.pyindex 3aa7f314b..74623e19b 100644--- a/src/xagent/core/memory/lancedb.py+++ b/src/xagent/core/memory/lancedb.py@@ -595,12 +595,87 @@ class LanceDBMemoryStore(MemoryStore):allow_vector_rebuild=False,)+ def _storage_record(self, table: Any, data: dict[str, Any]) -> dict[str, Any]:+ """The row ``add`` and ``update`` write for ``data`` into ``table``.++ The vector goes in only where this store's vectors may enter the table+ (``_table_accepts_vectors``).+ """+ record = {+ "id": data["id"],+ "text": data["text"],+ "metadata": data["metadata"],+ USER_ID_COLUMN: data[USER_ID_COLUMN],+ SCOPE_DIMS_COLUMN: data[SCOPE_DIMS_COLUMN],+ }+ if data["vector"] and self._table_accepts_vectors(table):+ record["vector"] = data["vector"]+ elif data["vector"]:+ logger.warning(+ "Memory table %r no longer holds this store's vector "+ "space; storing memory %r without a vector",+ self._collection_name,+ data["id"],+ )+ return record++ def _replacement_record(self, table: Any, data: dict[str, Any]) -> dict[str, Any]:+ """The row ``update`` writes over a stored one: every column, ``vector``+ included where the table has one.++ A matched merge keeps a column the source leaves out, so a replacement+ without an embedding (the provider failed, or the table holds another+ vector space) must clear the stored vector explicitly; otherwise the new+ text would be ranked by its former content's embedding.+ """+ record = self._fit_record(table, self._storage_record(table, data))+ if "vector" in table.schema.names:+ record.setdefault("vector", None)+ return record++ @staticmethod+ def _fit_record(table: Any, record: dict[str, Any]) -> dict[str, Any]:+ """``record`` adapted to the (possibly migrated) table schema."""+ if "vector" in record and "vector" not in set(table.schema.names):+ return {k: v for k, v in record.items() if k != "vector"}+ return record+def _insert_record(self, table: Any, record: dict[str, Any]) -> None:"""Insert a record, adapting it to the (possibly migrated) table schema."""- schema_names = set(table.schema.names)- if "vector" in record and "vector" not in schema_names:- record = {k: v for k, v in record.items() if k != "vector"}- table.add([record])+ table.add([self._fit_record(table, record)])++ def _update_existing(self, table: Any, record: dict[str, Any]) -> bool:+ """Overwrite the row whose id is ``record``'s; False when there is none.++ Matched rows are updated and unmatched ones are *not* inserted, so this+ can never re-create a deleted id. Rebases once onto the latest version+ when a concurrent ``compact()`` pruned the handle's version, as+ ``_delete_where`` does.+ """++ def merge(target: Any) -> bool:+ result = (+ target.merge_insert("id").when_matched_update_all().execute([record])+ )+ return int(result.num_updated_rows) > 0++ try:+ return merge(table)+ except RuntimeError as error:+ if not _is_pruned_version_error(error):+ raise+ logger.warning(+ "Memory update raced a compaction of %r; retrying on the latest "+ "version",+ self._collection_name,+ )+ latest = self._vector_store.get_raw_connection().open_table(+ self._collection_name+ )+ try:+ return merge(latest)+ finally:+ _safe_close_table(latest)def _memory_note_to_dict(self, note: MemoryNote) -> dict[str, Any]:"""Convert MemoryNote to dictionary for storage."""@@ -684,26 +759,7 @@ class LanceDBMemoryStore(MemoryStore):table = Nonetry:table = conn.open_table(self._collection_name)-- # Prepare record for insertion- record = {- "id": data["id"],- "text": data["text"],- "metadata": data["metadata"],- USER_ID_COLUMN: data[USER_ID_COLUMN],- SCOPE_DIMS_COLUMN: data[SCOPE_DIMS_COLUMN],- }-- # Add vector if available- if data["vector"] and self._table_accepts_vectors(table):- record["vector"] = data["vector"]- elif data["vector"]:- logger.warning(- "Memory table %r no longer holds this store's vector "- "space; storing memory %r without a vector",- self._collection_name,- data["id"],- )+ record = self._storage_record(table, data)# Try to add the record. On a schema mismatch, migrate the# existing table in place (preserving all rows) instead of@@ -788,22 +844,61 @@ class LanceDBMemoryStore(MemoryStore):_safe_close_table(table)def update(self, note: MemoryNote) -> MemoryResponse:- """Update an existing memory note."""+ """Replace a stored note, only while a row with its id still exists.++ One conditional ``merge_insert`` on ``id`` that updates the matching row+ and never inserts: a note deleted concurrently -- a forget that commits+ between a caller's ``get`` and this write -- stays deleted, and the+ update reports it as not found. LanceDB commits the merge as one table+ version and, when another commit lands first, retries it against the+ newer version, so there is no window in which the id is absent and then+ re-added (a delete followed by an add had one).+ """+ if not note.id:+ return MemoryResponse(+ success=False, error="Memory not found", memory_id=note.id+ )try:- # Check if memory exists- get_response = self.get(note.id)- if not get_response.success:+ data = self._memory_note_to_dict(note)+ conn = self._vector_store.get_raw_connection()+ table = None+ try:+ table = conn.open_table(self._collection_name)+ record = self._replacement_record(table, data)+ try:+ updated = self._update_existing(table, record)+ except Exception as update_error:+ # The same schema-mismatch recovery as ``add``; the update+ # stays conditional on the migrated table.+ logger.warning(+ f"update() failed on possible schema mismatch: {update_error}; "+ "attempting safe in-place migration"+ )+ _safe_close_table(table)+ table = None+ try:+ self._migrate_schema_mismatch(conn, record)+ except Exception as migrate_error:+ logger.error(+ "Safe schema migration failed; table left intact: %s",+ migrate_error,+ )+ return MemoryResponse(+ success=False,+ error=f"Failed to update memory: {migrate_error}",+ memory_id=note.id,+ )+ table = conn.open_table(self._collection_name)+ updated = self._update_existing(+ table, self._replacement_record(table, data)+ )+ finally:+ _safe_close_table(table)+ if not updated:return MemoryResponse(- success=False,- error="Memory not found",- memory_id=note.id,+ success=False, error="Memory not found", memory_id=note.id)-- # Delete old record- self.delete(note.id)-- # Add updated record- return self.add(note)+ return MemoryResponse(success=True, memory_id=note.id)except Exception as e:logger.error(f"Failed to update memory note {note.id}: {e}")diff --git a/tests/core/memory/test_update_never_resurrects.py b/tests/core/memory/test_update_never_resurrects.pynew file mode 100644index 000000000..ed6f1a995--- /dev/null+++ b/tests/core/memory/test_update_never_resurrects.py@@ -0,0 +1,211 @@+"""``update`` replaces a stored note only while it still exists.++``update_memory`` reads a note and then writes it back, and a delete (a user's or+an administrator's forget) can commit at any point of that, including while the+store's own ``update`` is in flight. ``update`` must then leave the note deleted:+it may never re-create the id. The interleaving tests below delete from inside the+concrete update -- while LanceDB computes the replacement embedding, before its+write; between the in-process store's membership check and its assignment -- so a+check-then-delete-then-add update, or an unserialized check-then-set one, fails+them.+"""++from __future__ import annotations++import asyncio+import threading+from collections.abc import Callable++import pytest++from xagent.core.agent.context.memory_tool import UpdateMemoryTool+from xagent.core.memory.base import MemoryStore+from xagent.core.memory.core import MemoryNote+from xagent.core.memory.in_memory import InMemoryMemoryStore+from xagent.core.memory.lancedb import LanceDBMemoryStore, _safe_close_table+from xagent.core.model.embedding import BaseEmbedding+from xagent.web.user_isolated_memory import UserContext, UserIsolatedMemoryStore+++class _Embedding(BaseEmbedding):+ """A constant vector; ``during_next_encode`` runs once, inside the next encode,+ and ``fail`` makes encodes raise (after that hook)."""++ def __init__(self) -> None:+ self.during_next_encode: Callable[[], None] | None = None+ self.fail = False++ def encode(self, text, dimension=None, instruct=None):+ hook, self.during_next_encode = self.during_next_encode, None+ if hook is not None:+ hook()+ if self.fail:+ raise RuntimeError("embedding unavailable")+ return [0.1] * 8 if isinstance(text, str) else [[0.1] * 8 for _ in text]++ def get_dimension(self):+ return 8++ @property+ def abilities(self):+ return ["embed"]+++def _lancedb(tmp_path, embedding: _Embedding) -> LanceDBMemoryStore:+ return LanceDBMemoryStore(+ db_dir=str(tmp_path), collection_name="memories", embedding_model=embedding+ )+++def _column_names(store: LanceDBMemoryStore) -> set[str]:+ table = store._vector_store.get_raw_connection().open_table("memories")+ try:+ return set(table.schema.names)+ finally:+ _safe_close_table(table)++[email protected](params=["lancedb", "lancedb_text_only", "in_memory"])+def store(request, tmp_path) -> MemoryStore:+ if request.param == "in_memory":+ return InMemoryMemoryStore()+ if request.param == "lancedb_text_only":+ # No embedding adapter at all: the supported text-only schema, which has+ # no ``vector`` column (a failing adapter would still get one).+ text_only = LanceDBMemoryStore(+ db_dir=str(tmp_path), collection_name="memories", embedding_model=None+ )+ assert "vector" not in _column_names(text_only)+ return text_only+ return _lancedb(tmp_path, _Embedding())+++def _ids(store: MemoryStore) -> list[str]:+ return sorted(str(note.id) for note in store.list_all())+++def test_an_update_replaces_a_note_that_exists(store):+ kept = store.add(MemoryNote(content="kept")).memory_id+ memory_id = store.add(+ MemoryNote(content="prefers tea", metadata={"v": 1})+ ).memory_id++ response = store.update(+ MemoryNote(id=memory_id, content="prefers coffee", metadata={"v": 2})+ )++ assert response.success and response.memory_id == memory_id+ stored = store.get(memory_id).content+ assert (stored.content, stored.metadata["v"]) == ("prefers coffee", 2)+ assert _ids(store) == sorted([kept, memory_id])+++def test_an_update_after_a_delete_reports_not_found(store):+ """The plain contract: an update of an id that is gone writes nothing."""+ memory_id = store.add(MemoryNote(content="prefers tea")).memory_id+ read = store.get(memory_id).content+ assert store.delete(memory_id).success++ read.content = "prefers coffee"+ response = store.update(read)++ assert not response.success+ assert _ids(store) == []+++ "failing_embedding", [False, True], ids=["embedded", "unembedded"]+)+def test_a_delete_during_a_lancedb_update_is_not_undone(tmp_path, failing_embedding):+ """The forget commits while the update computes the replacement's embedding --+ after any existence check an update could make, before its write."""+ embedding = _Embedding()+ store = _lancedb(tmp_path, embedding)+ memory_id = store.add(MemoryNote(content="prefers tea")).memory_id+ read = store.get(memory_id).content+ embedding.fail = failing_embedding+ embedding.during_next_encode = lambda: store.delete(memory_id)++ read.content = "prefers coffee"+ response = store.update(read)++ assert embedding.during_next_encode is None # the delete ran inside the update+ assert not response.success+ assert _ids(store) == []+ assert not store.get(memory_id).success+++def test_a_delete_during_an_in_memory_update_is_not_undone():+ """The forget arrives between the update's membership check and its write:+ serialized behind the update, it removes the replacement too."""+ store = InMemoryMemoryStore()+ memory_id = store.add(MemoryNote(content="prefers tea")).memory_id+ forget = threading.Thread(target=store.delete, args=(memory_id,))++ class _Notes(dict):+ def __contains__(self, key):+ found = super().__contains__(key)+ if key == memory_id and forget.ident is None:+ forget.start()+ # Long enough for an unserialized delete to land before the write.+ forget.join(timeout=0.5)+ return found++ store._store = _Notes(store._store)++ store.update(MemoryNote(id=memory_id, content="prefers coffee"))+ forget.join(timeout=5)++ assert forget.ident is not None and not forget.is_alive()+ assert _ids(store) == []+++def test_update_memory_racing_a_forget_reports_not_found(tmp_path):+ """The tool's own read-then-write, with the forget landing inside the store's+ update."""+ embedding = _Embedding()+ store = _lancedb(tmp_path, embedding)+ memory_id = store.add(MemoryNote(content="prefers tea")).memory_id+ embedding.during_next_encode = lambda: store.delete(memory_id)+ tool = UpdateMemoryTool(memory_store=store)++ result = asyncio.run(tool.execute(memory_id=memory_id, content="prefers coffee"))++ assert result["success"] is False+ assert _ids(store) == []+++def test_the_user_isolated_wrapper_never_recreates_a_deleted_note(tmp_path):+ embedding = _Embedding()+ base = _lancedb(tmp_path, embedding)+ isolated = UserIsolatedMemoryStore(base)+ with UserContext(7):+ memory_id = isolated.add(MemoryNote(content="prefers tea")).memory_id+ read = isolated.get(memory_id).content+ embedding.during_next_encode = lambda: base.delete(memory_id)++ read.content = "prefers coffee"+ response = isolated.update(read)++ assert not response.success+ assert _ids(base) == []+++def test_an_update_without_a_replacement_embedding_clears_the_old_vector(tmp_path):+ """A matched merge keeps a column the update leaves out; the new text must not+ be ranked by its former content's vector."""+ embedding = _Embedding()+ store = _lancedb(tmp_path, embedding)+ memory_id = store.add(MemoryNote(content="prefers tea")).memory_id+ embedding.fail = True++ response = store.update(MemoryNote(id=memory_id, content="prefers coffee"))++ assert response.success+ table = store._vector_store.get_raw_connection().open_table("memories")+ try:+ rows = table.to_arrow().to_pylist()+ finally:+ _safe_close_table(table)+ (row,) = rows+ assert (row["text"], row["vector"]) == ("prefers coffee", None)