Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix(context): skip redundant vector cascade when erasure's vector leg covers it (#1379)
BingEdwardb08444c9fb97
diff --git a/semantica/context/erasure.py b/semantica/context/erasure.pyindex 8bcf7105..c34996c6 100644--- a/semantica/context/erasure.py+++ b/semantica/context/erasure.py@@ -151,7 +151,12 @@ class ErasureCoordinator:graph: A :class:`~semantica.context.ContextGraph` (or anything exposing``purge_node``).memory: An :class:`~semantica.context.AgentMemory` (or anything- exposing ``find_by_entity`` and ``batch_delete``).+ exposing ``find_by_entity`` and ``batch_delete``; when+ ``batch_delete`` accepts a ``skip_vector`` keyword the coordinator+ sets it once its vector leg has fully covered the memory-bound+ store, or when the vector leg is disabled outright, and otherwise+ calls ``batch_delete(memory_ids)`` and leaves the implementation's+ own cascade running).vector_store: Vector store holding entity-keyed embeddings. Defaults to``memory.vector_store`` when a memory is supplied, and staysoverridable for deployments that bind a store the memory does not@@ -266,10 +271,18 @@ class ErasureCoordinator:# embedding behind. Deleting those ids here instead puts them behind# the one leg that reports honestly. Collected before anything is# deleted, while the items still exist to be enumerated.- stores["vectors"] = self._erase_vectors(- entity_id, self._all_vector_ids(entity_id, vector_ids)+ all_ids, enumerated = self._all_vector_ids(entity_id, vector_ids)+ stores["vectors"] = self._erase_vectors(entity_id, all_ids)+ # The memory leg may only suppress delete_memory()'s own vector+ # cascade when the vector leg demonstrably covered it: every+ # memory-owned id was enumerated AND the store accepted the delete.+ # Store identity alone proves neither.+ vector_leg_covered = (+ enumerated and stores["vectors"].get("status") == STATUS_ERASED+ )+ stores["memory"] = self._erase_memory(+ entity_id, vector_leg_covered=vector_leg_covered)- stores["memory"] = self._erase_memory(entity_id)stores["graph"] = self._erase_graph(entity_id, reason, erased_at)receipt = ErasureReceipt(@@ -320,7 +333,7 @@ class ErasureCoordinator:def _all_vector_ids(self, entity_id: str, vector_ids: Optional[Sequence[str]]- ) -> List[str]:+ ) -> Tuple[List[str], bool]:"""Caller-supplied vector ids plus the ids owned by memory items.Best-effort by design: if memory cannot be enumerated here, the memory@@ -331,10 +344,15 @@ class ErasureCoordinator:Collects vector IDs from ALL memory items before deletion. Must callfind_by_entity with limit=None to get all items, since find_by_entitydoesn't support offset/cursor and we cannot delete while collecting.++ Returns:+ ``(ids, complete)``, where ``complete`` is False when enumeration+ raised part-way through -- the list may then be missing ids, so+ the caller must not treat the vector leg as covering everything."""ids: List[str] = list(vector_ids) if vector_ids is not None else [entity_id]if self.memory is None:- return ids+ return ids, Trueseen_vector_ids = set(ids)try:@@ -359,7 +377,8 @@ class ErasureCoordinator:entity_id,exc,)- return ids+ return ids, False+ return ids, Truedef _erase_vectors(self, entity_id: str, vector_ids: Optional[Sequence[str]]@@ -457,15 +476,35 @@ class ErasureCoordinator:result["detail"] = "store reported the ids were not deleted"return result- def _erase_memory(self, entity_id: str) -> Dict[str, Any]:+ def _erase_memory(+ self, entity_id: str, *, vector_leg_covered: bool = False+ ) -> Dict[str, Any]:"""Delete every memory item referencing the entity."""if self.memory is None:return {"status": STATUS_NOT_CONFIGURED}- deleted = 0- skip_vector = self._vector_leg_disabled and _accepts_skip_vector(- self.memory.batch_delete+ # When the vector leg succeeded against the store memory itself holds+ # -- the default binding -- it has already deleted (and reported on)+ # every memory-owned embedding, so delete_memory()'s own best-effort+ # cascade would only re-attempt ids that are already gone: a redundant+ # round-trip per item, and spurious warnings on backends that flag+ # missing ids. In every other case -- a separate coordinator store,+ # its deletion rejected, or its enumeration incomplete -- that cascade+ # is still the only cleanup memory's own store gets, so it must keep+ # running. The one exception is an explicit vector_store=False, which+ # means "no vector activity at all" (see the class docstring). A+ # memory-like whose batch_delete predates the keyword keeps its old+ # call and cascade.+ vector_leg_owns_store = (+ vector_leg_covered+ and self.vector_store is not None+ and self.vector_store is getattr(self.memory, "vector_store", None))+ skip_vector = (+ self._vector_leg_disabled or vector_leg_owns_store+ ) and _accepts_skip_vector(self.memory.batch_delete)++ deleted = 0if self._vector_leg_disabled and not skip_vector:# The class docstring only requires find_by_entity/batch_delete; a# duck-typed adapter is not required to support skip_vector. Falling@@ -627,7 +666,16 @@ def _accepts_skip_vector(batch_delete: Any) -> bool:duck-typed contract the class docstring promises (``find_by_entity`` and``batch_delete`` only). Passing it to an adapter that doesn't accept itwould raise ``TypeError`` and fail the whole memory leg, so this is- checked before ever passing the kwarg.+ checked before ever passing the kwarg. Probed by signature rather than+ try/except around the real call: a ``TypeError`` raised from *inside* an+ implementation that does accept the keyword must surface as that leg's+ failure, not trigger a second delete attempt.++ Only a callable whose signature cannot be introspected at all gets the+ conservative plain call; a ``(*args, **kwargs)`` signature (a+ ``MagicMock``, a hand-rolled passthrough wrapper) counts as accepting+ ``skip_vector`` even if the callee then drops the keyword; the only+ consequence is the cascade the flag would have suppressed."""try:signature = inspect.signature(batch_delete)diff --git a/tests/context/test_erasure_coordinator.py b/tests/context/test_erasure_coordinator.pyindex 18a408aa..cf7232ae 100644--- a/tests/context/test_erasure_coordinator.py+++ b/tests/context/test_erasure_coordinator.py@@ -323,6 +323,138 @@ class TestVectorBackendShapes(unittest.TestCase):self.assertEqual(receipt.stores["vectors"]["status"], STATUS_NOT_CONFIGURED)+class TestVectorsAreDeletedOnceNotTwice(unittest.TestCase):+ """The vector leg owns embedding deletion (issue #1375).++ ``delete_memory()`` cascades to the vector store on its own, so without+ ``skip_vector=True`` the memory leg would re-attempt every vector id the+ vector leg already deleted and reported on.+ """++ def test_memory_owned_vector_ids_are_deleted_exactly_once(self):+ store = _MemoryVectorStore()+ memory = AgentMemory(vector_store=store)+ memory.store(+ "note about customer-4471",+ entities=[{"id": "customer-4471", "name": "customer-4471"}],+ skip_graph=True,+ )++ receipt = ErasureCoordinator(memory=memory).erase_entity("customer-4471")++ self.assertEqual(receipt.stores["memory"]["status"], STATUS_ERASED)+ # One delete call: the vector leg's. delete_memory() must not add a+ # second, per-item attempt against ids that are already gone.+ self.assertEqual(len(store.deleted), 1)+ flattened = [vid for call in store.deleted for vid in call]+ self.assertEqual(len(flattened), len(set(flattened)))++ def test_batch_delete_still_cascades_to_vectors_by_default(self):+ """Callers other than the coordinator keep the old behavior."""+ store = _MemoryVectorStore()+ memory = AgentMemory(vector_store=store)+ memory_id = memory.store("a note", skip_graph=True)++ self.assertEqual(memory.batch_delete([memory_id]), 1)++ self.assertEqual(len(store.deleted), 1)++ def test_rejected_vector_deletion_does_not_suppress_the_cascade(self):+ """Store identity is not coverage: a failed vector leg keeps the+ memory-side cascade as the second (and only remaining) attempt."""+ store = _MemoryVectorStore(result=False)+ memory = AgentMemory(vector_store=store)+ memory.store(+ "note about customer-4471",+ entities=[{"id": "customer-4471", "name": "customer-4471"}],+ skip_graph=True,+ )++ receipt = ErasureCoordinator(memory=memory).erase_entity("customer-4471")++ self.assertEqual(receipt.stores["vectors"]["status"], STATUS_FAILED)+ self.assertFalse(receipt.complete)+ self.assertEqual(receipt.stores["memory"]["status"], STATUS_ERASED)+ # Two delete attempts: the vector leg's, then delete_memory()'s+ # cascade -- which must NOT be skipped when the store rejected the+ # first attempt.+ self.assertEqual(len(store.deleted), 2)++ def test_incomplete_enumeration_does_not_suppress_the_cascade(self):+ """When memory-owned ids could not all be enumerated, the vector leg+ did not cover them, so delete_memory()'s cascade must still run."""++ class _MappingUnreadableMemory(AgentMemory):+ def vector_ids_for(self, memory_id):+ raise RuntimeError("mapping backend unavailable")++ store = _MemoryVectorStore()+ memory = _MappingUnreadableMemory(vector_store=store)+ memory_id = memory.store(+ "note about customer-4471",+ entities=[{"id": "customer-4471", "name": "customer-4471"}],+ skip_graph=True,+ )+ owned = list(memory._vector_ids[memory_id])++ receipt = ErasureCoordinator(memory=memory).erase_entity("customer-4471")++ # The vector leg only ever learned the entity-keyed id...+ self.assertEqual(store.deleted[0], ["customer-4471"])+ # ...so the cascade still deleted the ids it missed.+ self.assertEqual(receipt.stores["memory"]["status"], STATUS_ERASED)+ flattened = [vid for call in store.deleted for vid in call]+ for vector_id in owned:+ self.assertIn(vector_id, flattened)++ def test_skipped_cascade_still_drops_vector_id_bookkeeping(self):+ """batch_delete(skip_vector=True) deletes permanently, so the local+ vector-id mapping must not survive it (it would otherwise persist+ through save()/load())."""+ store = _MemoryVectorStore()+ memory = AgentMemory(vector_store=store)+ memory.store(+ "note about customer-4471",+ entities=[{"id": "customer-4471", "name": "customer-4471"}],+ skip_graph=True,+ )++ receipt = ErasureCoordinator(memory=memory).erase_entity("customer-4471")++ self.assertEqual(receipt.stores["memory"]["status"], STATUS_ERASED)+ self.assertEqual(len(store.deleted), 1) # the skip actually happened+ self.assertEqual(memory._vector_ids, {})++ def test_a_batch_delete_without_the_keyword_still_erases_memory(self):+ """Duck-typed memories predating skip_vector keep working: the+ coordinator probes the signature and falls back to the plain call."""+ store = _DeleteVectorsStore()++ class _LegacyMemory:+ def __init__(self):+ self.vector_store = store+ self.items = {"m-1": {"memory_id": "m-1", "entities": [{"id": "e1"}]}}++ def find_by_entity(self, entity_id, limit=None):+ return list(self.items.values())[:limit]++ def vector_ids_for(self, memory_id):+ return [f"vec-{memory_id}"]++ def batch_delete(self, memory_ids): # pre-skip_vector signature+ removed = 0+ for memory_id in memory_ids:+ if self.items.pop(memory_id, None) is not None:+ removed += 1+ return removed++ receipt = ErasureCoordinator(memory=_LegacyMemory()).erase_entity("e1")++ self.assertEqual(receipt.stores["vectors"]["status"], STATUS_ERASED)+ self.assertEqual(receipt.stores["memory"]["status"], STATUS_ERASED)+ self.assertEqual(receipt.stores["memory"]["items"], 1)++class TestPartialFailureIsAResultNotAnException(unittest.TestCase):def test_a_raising_vector_store_does_not_stop_the_remaining_legs(self):graph, memory = _graph(), _memory_with("customer-4471", 4)