Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(langchain): align Store deletion, validation and removal errors (#6324)
z1gond8f485496451
diff --git a/docs/en/agent-integrations/07-langchain-langgraph.md b/docs/en/agent-integrations/07-langchain-langgraph.mdindex d4bd083e1..ac5219bbc 100644--- a/docs/en/agent-integrations/07-langchain-langgraph.md+++ b/docs/en/agent-integrations/07-langchain-langgraph.md@@ -256,8 +256,16 @@ from langchain_openviking import OpenVikingStorestore = OpenVikingStore(url="http://localhost:1933", api_key="...")store.put(("users", "ada"), "preferences", {"color": "azure"})items = store.search(("users",), query="azure", limit=3)+store.put(("users", "ada"), "preferences", None) # a None value deletes the item```+Following LangGraph's `BaseStore` contract, passing `None` as the value deletes the item and is+equivalent to `delete()`. Deleting a key that does not exist is a no-op.++`put()` validates the namespace before changing records. Other removal errors propagate to+the caller. Record and search-projection removal are separate operations: if only one+succeeds, resolve the reported error and retry the operation to finish cleanup.+### LangGraph middleware```pythondiff --git a/docs/zh/agent-integrations/07-langchain-langgraph.md b/docs/zh/agent-integrations/07-langchain-langgraph.mdindex fca4d46bf..189b618c5 100644--- a/docs/zh/agent-integrations/07-langchain-langgraph.md+++ b/docs/zh/agent-integrations/07-langchain-langgraph.md@@ -244,8 +244,15 @@ from langchain_openviking import OpenVikingStorestore = OpenVikingStore(url="http://localhost:1933", api_key="...")store.put(("users", "ada"), "preferences", {"color": "azure"})items = store.search(("users",), query="azure", limit=3)+store.put(("users", "ada"), "preferences", None) # 值为 None 表示删除该条目```+按 LangGraph `BaseStore` 约定,传入 `None` 作为值表示删除该条目,等价于 `delete()`。+删除不存在的键不会产生任何影响。++`put()` 会在修改记录前校验命名空间。其他删除错误会向调用方抛出。+记录和搜索索引文件分别删除;如果只完成其中一步,请解决报告的错误后重试,以完成清理。+### LangGraph middleware```pythondiff --git a/integrations/frameworks/langchain/src/langchain_openviking/store.py b/integrations/frameworks/langchain/src/langchain_openviking/store.pyindex 4c06444db..98e8be983 100644--- a/integrations/frameworks/langchain/src/langchain_openviking/store.py+++ b/integrations/frameworks/langchain/src/langchain_openviking/store.py@@ -18,6 +18,7 @@ from langchain_openviking.client import (OptionalDependencyError,call_openviking,ensure_client,+ is_not_found_error,item_value,iter_result_items,missing_dependency,@@ -60,6 +61,7 @@ class OpenVikingStore(BaseStore):Values are stored as JSON records under ``<root_uri>/data``. A separatemarkdown projection under ``<root_uri>/index`` gives OpenViking semanticretrieval a compact document to index for query-based ``search`` calls.+ Removal ignores missing targets and propagates other backend errors.Args:root_uri: Base URI for the store. Defaults to the ``viking://~`` home alias,@@ -159,17 +161,23 @@ class OpenVikingStore(BaseStore):self,namespace: tuple[str, ...],key: str,- value: Mapping[str, Any],+ value: Mapping[str, Any] | None,index: bool | list[str] | None = None,*,ttl: Any = None,) -> None:+ from langgraph.store.base import _validate_namespace+if ttl is not None:raise NotImplementedError("TTL is not supported by OpenVikingStore. ""OpenViking stores LangGraph values as durable content records.")namespace = tuple(namespace)+ _validate_namespace(namespace)+ if value is None:+ self.delete(namespace, key)+ returnnow = datetime.now(timezone.utc)data_uri = self._data_uri(namespace, key)record = self._write_record(data_uri, namespace, key, dict(value), now)@@ -353,9 +361,10 @@ class OpenVikingStore(BaseStore):def _remove(self, uri: str) -> None:try:call_openviking(self._client(), "rm", uri=uri, recursive=False)- except Exception:- logger.debug("OpenVikingStore remove ignored missing/unavailable URI", exc_info=True)- pass+ except Exception as exc:+ if not is_not_found_error(exc):+ raise+ logger.debug("OpenVikingStore remove ignored missing URI", exc_info=True)def _data_uri(self, namespace: tuple[str, ...], key: str) -> str:return f"{self._data_prefix_uri(namespace)}/{_segment(key)}.json"diff --git a/integrations/frameworks/langchain/tests/unit/test_langchain_integration.py b/integrations/frameworks/langchain/tests/unit/test_langchain_integration.pyindex 48fc0cbe6..e6e6d537e 100644--- a/integrations/frameworks/langchain/tests/unit/test_langchain_integration.py+++ b/integrations/frameworks/langchain/tests/unit/test_langchain_integration.py@@ -1,5 +1,6 @@from __future__ import annotations+import asyncioimport jsonfrom copy import deepcopyfrom types import MappingProxyType@@ -23,8 +24,13 @@ from langchain_core.messages import (convert_to_openai_messages,)from langchain_core.runnables import RunnableLambda-from langgraph.store.base import PutOp-from openviking_sdk.errors import InvalidArgumentError+from langgraph.store.base import InvalidNamespaceError, PutOp+from openviking_sdk.errors import (+ InvalidArgumentError,+ NotFoundError,+ PermissionDeniedError,+ UnavailableError,+)import langchain_openviking.client as client_helpersfrom langchain_openviking import (@@ -1609,7 +1615,11 @@ def test_chat_message_history_clear_raises_when_delete_fails():assert len(client.sessions["clear-session"]) == 1-def test_langgraph_store_round_trip_and_semantic_search():+ "invalid_namespace",+ [(), ("users", "", "ada"), ("users", 1), ("users", "ada.profile"), ("langgraph", "ada")],+)+def test_langgraph_store_round_trip_and_semantic_search(invalid_namespace):client = InMemoryOpenVikingClient()store = OpenVikingStore(client=client)@@ -1640,6 +1650,113 @@ def test_langgraph_store_round_trip_and_semantic_search():assert store.list_namespaces(prefix=("users",)) == [("users", "ada")]+ records = dict(client.records)+ for value in ({"color": "invalid"}, None):+ with pytest.raises(InvalidNamespaceError):+ store.put(invalid_namespace, "preferences", value)+ assert client.records == records+ with pytest.raises(InvalidNamespaceError):+ asyncio.run(store.aput(invalid_namespace, "preferences", value))+ assert client.records == records++ # A None value is a deletion in LangGraph's BaseStore contract.+ store.put(("users", "ada"), "profile", None)+ assert store.get(("users", "ada"), "profile") is None+ assert "profile" not in {found.key for found in store.search(("users",), limit=5)}++ # Deleting a missing key is idempotent and must not create a record.+ store.put(("users", "ada"), "absent", None)+ assert store.get(("users", "ada"), "absent") is None++ store.put(("users", "ada"), "preferences", None)+ store.put(("users", "ada"), "bad-rank", None)+ assert store.search(("users",), limit=5) == []+ assert store.list_namespaces(prefix=("users",)) == []++[email protected]("method", ["put", "aput", "batch", "abatch", "delete", "adelete"])[email protected]("existing", [False, True])+def test_langgraph_store_none_deletes_through_public_store_methods(+ method: str, existing: bool+) -> None:+ store = OpenVikingStore(client=InMemoryOpenVikingClient())+ namespace = ("users", "ada", "memories")+ other_namespace = ("users", "grace", "memories")+ store.put(other_namespace, "keep", {"text": "independent memory"})+ if existing:+ store.put(namespace, "item", {"text": "memory to remove"})++ if method == "put":+ store.put(namespace, "item", None)+ elif method == "aput":+ asyncio.run(store.aput(namespace, "item", None))+ elif method == "batch":+ store.batch([PutOp(namespace, "item", None)])+ elif method == "abatch":+ asyncio.run(store.abatch([PutOp(namespace, "item", None)]))+ elif method == "delete":+ store.delete(namespace, "item")+ else:+ asyncio.run(store.adelete(namespace, "item"))++ assert store.get(namespace, "item") is None+ assert store.search(namespace) == []+ assert store.search(namespace, query="memory to remove") == []+ assert store.list_namespaces() == [other_namespace]+ assert store.get(other_namespace, "keep").value == {"text": "independent memory"}++[email protected]("index", [False, ["text"]])[email protected]("existing", [False, True])+def test_langgraph_store_put_none_deletes_with_index_overrides(+ index: bool | list[str], existing: bool+) -> None:+ store = OpenVikingStore(client=InMemoryOpenVikingClient())+ namespace = ("users", "ada")+ if existing:+ store.put(namespace, "item", {"text": "memory to remove"})++ store.put(namespace, "item", None, index=index)++ assert store.get(namespace, "item") is None+ assert store.search(namespace) == []+ assert store.search(namespace, query="memory to remove") == []+ assert store.list_namespaces() == []++[email protected]("method", ["put", "aput"])[email protected]("value", [{}, {"number": 0}, {"text": "saved memory"}])+def test_langgraph_store_dictionary_values_remain_stored(method: str, value: dict) -> None:+ store = OpenVikingStore(client=InMemoryOpenVikingClient())+ namespace = ("users", "ada")+ if method == "put":+ store.put(namespace, "item", value)+ else:+ asyncio.run(store.aput(namespace, "item", value))++ assert store.get(namespace, "item").value == value+ assert store.search(namespace)[0].value == value+ assert store.list_namespaces() == [namespace]++[email protected]("method", ["put", "aput"])[email protected]("value", [None, {"text": "replacement"}])+def test_langgraph_store_unsupported_ttl_still_rejects_before_mutation(+ method: str, value: dict | None+) -> None:+ store = OpenVikingStore(client=InMemoryOpenVikingClient())+ namespace = ("users", "ada")+ original = {"text": "original memory"}+ store.put(namespace, "item", original)++ with pytest.raises(NotImplementedError, match="TTL"):+ if method == "put":+ store.put(namespace, "item", value, ttl=60)+ else:+ asyncio.run(store.aput(namespace, "item", value, ttl=60))++ assert store.get(namespace, "item").value == original+@pytest.mark.parametrize("use_batch", [False, True])def test_langgraph_store_accepts_mapping_values(use_batch):@@ -1659,6 +1776,96 @@ def test_langgraph_store_accepts_mapping_values(use_batch):assert original == {"color": "azure", "nested": {"rank": 3}}+ ("method", "collection", "deindex"),+ [+ (method, collection, False)+ for method in ("delete", "adelete", "put", "aput", "batch", "abatch")+ for collection in ("data", "index")+ ]+ + [(method, "index", True) for method in ("put", "aput", "batch", "abatch")],+)+ "error", [PermissionDeniedError(), UnavailableError(), TimeoutError("removal timed out")]+)+async def test_langgraph_store_removal_errors_remain_visible_and_retryable(+ method, collection, deindex, error+):+ class FailingRemoveClient(InMemoryOpenVikingClient):+ fail = True++ def rm(self, uri, recursive=False):+ if self.fail and f"/{collection}/" in uri:+ raise error+ if uri not in self.records:+ raise NotFoundError(uri)+ return super().rm(uri, recursive=recursive)++ client = FailingRemoveClient()+ store = OpenVikingStore(client=client)+ namespace, key, value = ("users",), "ada", {"color": "azure"}+ store.put(namespace, key, value)+ store.put(("other",), key, {"color": "teal"})++ async def mutate():+ replacement = value if deindex else None+ index = False if deindex else None+ if method == "delete":+ store.delete(namespace, key)+ elif method == "adelete":+ await store.adelete(namespace, key)+ elif method == "put":+ store.put(namespace, key, replacement, index=index)+ elif method == "aput":+ await store.aput(namespace, key, replacement, index=index)+ else:+ ops = [+ PutOp(namespace, key, replacement, index=index),+ PutOp(namespace, "later", {"written": True}),+ ]+ if method == "batch":+ store.batch(ops)+ else:+ await store.abatch(ops)++ with pytest.raises(type(error)) as caught:+ await mutate()+ assert str(caught.value) == str(error)+ assert getattr(caught.value, "code", None) == getattr(error, "code", None)+ assert bool(store.get(namespace, key)) is (deindex or collection == "data")+ assert store.get(namespace, "later") is None+ assert store.get(("other",), key).value == {"color": "teal"}++ client.fail = False+ await mutate()+ assert store.search(namespace, query="azure") == []+ item = store.get(namespace, key)+ assert (item.value if item else None) == (value if deindex else None)+ if method in ("batch", "abatch"):+ assert store.get(namespace, "later").value == {"written": True}++[email protected]("missing_error", [FileNotFoundError, NotFoundError])+def test_langgraph_store_removal_keeps_missing_targets_idempotent(missing_error):+ class StrictRemoveClient(InMemoryOpenVikingClient):+ def rm(self, uri, recursive=False):+ if uri not in self.records:+ raise missing_error(uri)+ return super().rm(uri, recursive=recursive)++ store = OpenVikingStore(client=StrictRemoveClient())+ namespace, key, value = ("users",), "ada", {"color": "azure"}+ store.delete(namespace, key)+ store.put(namespace, key, value, index=False)+ assert store.get(namespace, key).value == value+ store.put(namespace, key, value)+ assert len(store.search(namespace, query="azure")) == 1+ store.delete(namespace, key)+ store.delete(namespace, key)+ assert store.get(namespace, key) is None+ assert store.search(namespace, query="azure") == []++def test_langgraph_store_semantic_search_keeps_peer_id_out_of_retrieval():client = InMemoryOpenVikingClient()store = OpenVikingStore(client=client, actor_peer_id="peer-store")