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): preserve Store reads and namespace discovery (#6342)
z1gon6ec6116b7beb
diff --git a/docs/en/agent-integrations/07-langchain-langgraph.md b/docs/en/agent-integrations/07-langchain-langgraph.mdindex ac5219bbc..1c47da27a 100644--- a/docs/en/agent-integrations/07-langchain-langgraph.md+++ b/docs/en/agent-integrations/07-langchain-langgraph.md@@ -266,6 +266,11 @@ equivalent to `delete()`. Deleting a key that does not exist is a no-op.the caller. Record and search-projection removal are separate operations: if only onesucceeds, resolve the reported error and retry the operation to finish cleanup.+Record reads return `None` only for a missing record; permission, backend, and invalid-JSON+errors propagate, and `put()` does not overwrite a record after a failed read.+`list_namespaces(prefix=("users", "*"))` matches one namespace label per `*`, including+when `root_uri` uses a peer home alias such as `viking://~/peers/support/memories/langgraph_store`.+### LangGraph middleware```pythondiff --git a/docs/zh/agent-integrations/07-langchain-langgraph.md b/docs/zh/agent-integrations/07-langchain-langgraph.mdindex 189b618c5..1cb7b089f 100644--- a/docs/zh/agent-integrations/07-langchain-langgraph.md+++ b/docs/zh/agent-integrations/07-langchain-langgraph.md@@ -253,6 +253,11 @@ store.put(("users", "ada"), "preferences", None) # 值为 None 表示删除该`put()` 会在修改记录前校验命名空间。其他删除错误会向调用方抛出。记录和搜索索引文件分别删除;如果只完成其中一步,请解决报告的错误后重试,以完成清理。+读取记录时,仅记录不存在才返回 `None`;权限、后端和 JSON 解析错误会向调用方抛出,+`put()` 不会在读取失败后覆盖记录。+`list_namespaces(prefix=("users", "*"))` 中的每个 `*` 匹配一层命名空间,+也适用于 `viking://~/peers/support/memories/langgraph_store` 这样的 peer 主目录别名。+### LangGraph middleware```pythondiff --git a/integrations/frameworks/langchain/src/langchain_openviking/store.py b/integrations/frameworks/langchain/src/langchain_openviking/store.pyindex 98e8be983..e1e4e5a3c 100644--- a/integrations/frameworks/langchain/src/langchain_openviking/store.py+++ b/integrations/frameworks/langchain/src/langchain_openviking/store.py@@ -31,6 +31,7 @@ if TYPE_CHECKING:GetOp,Item,ListNamespacesOp,+ MatchCondition,PutOp,SearchItem,SearchOp,@@ -42,6 +43,7 @@ else:GetOp,Item,ListNamespacesOp,+ MatchCondition,PutOp,SearchItem,SearchOp,@@ -49,7 +51,7 @@ else:except ImportError: # pragma: no cover - exercised by optional import path_LANGGRAPH_IMPORT_ERROR = missing_dependency("langgraph", "langgraph")BaseStore = object- GetOp = PutOp = SearchOp = ListNamespacesOp = object+ GetOp = PutOp = SearchOp = ListNamespacesOp = MatchCondition = objectItem = SearchItem = objectlogger = logging.getLogger(__name__)@@ -127,11 +129,9 @@ class OpenVikingStore(BaseStore):))elif isinstance(op, ListNamespacesOp):- prefix, suffix = self._match_conditions_to_prefix_suffix(op.match_conditions)results.append(- self.list_namespaces(- prefix=prefix,- suffix=suffix,+ self._list_namespaces(+ op.match_conditions,max_depth=op.max_depth,limit=op.limit,offset=op.offset,@@ -147,7 +147,9 @@ class OpenVikingStore(BaseStore):def get(self, namespace: tuple[str, ...], key: str, *, refresh_ttl: Any = None) -> Any:try:record = self._read_record(self._data_uri(namespace, key))- except Exception:+ except Exception as exc:+ if not is_not_found_error(exc):+ raisereturn Nonereturn Item(namespace=tuple(record["namespace"]),@@ -223,15 +225,38 @@ class OpenVikingStore(BaseStore):limit: int = 100,offset: int = 0,) -> list[tuple[str, ...]]:+ conditions = []+ if prefix:+ conditions.append(MatchCondition("prefix", prefix))+ if suffix:+ conditions.append(MatchCondition("suffix", suffix))+ return self._list_namespaces(conditions, max_depth=max_depth, limit=limit, offset=offset)++ def _list_namespaces(+ self,+ match_conditions: Iterable[Any] | None,+ *,+ max_depth: int | None,+ limit: int,+ offset: int,+ ) -> list[tuple[str, ...]]:+ conditions = tuple(match_conditions or ())+ scan_prefix: tuple[str, ...] = ()+ for condition in conditions:+ if condition.match_type == "prefix":+ path = tuple(condition.path)+ literal_prefix = path[: path.index("*")] if "*" in path else path+ if len(literal_prefix) > len(scan_prefix):+ scan_prefix = literal_prefix+namespaces = set()- for uri in self._all_data_uris(prefix or ()):+ # Wildcards match namespace labels, never physical URI path segments.+ for uri in self._all_data_uris(scan_prefix):parsed = self._parse_data_uri(uri)if parsed is None:continuenamespace, _key = parsed- if prefix and not _tuple_matches_prefix(namespace, prefix):- continue- if suffix and not _tuple_matches_suffix(namespace, suffix):+ if not all(_namespace_matches(namespace, condition) for condition in conditions):continueif max_depth is not None and len(namespace) > max_depth:namespace = namespace[:max_depth]@@ -317,7 +342,9 @@ class OpenVikingStore(BaseStore):) -> dict[str, Any]:try:existing = self._read_record(uri)- except Exception:+ except Exception as exc:+ if not is_not_found_error(exc):+ raiserecord = _store_record(namespace, key, value, created_at=now, updated_at=now)self._write_create(uri, json.dumps(record, ensure_ascii=False, indent=2))return record@@ -421,20 +448,6 @@ class OpenVikingStore(BaseStore):score=score,)- def _match_conditions_to_prefix_suffix(- self, conditions: Iterable[Any] | None- ) -> tuple[tuple[str, ...] | None, tuple[str, ...] | None]:- prefix = None- suffix = None- for condition in conditions or []:- match_type = getattr(condition, "match_type", None)- path = tuple(getattr(condition, "path", ()) or ())- if match_type == "prefix":- prefix = path- elif match_type == "suffix":- suffix = path- return prefix, suffix-def _segment(value: str) -> str:return quote(str(value), safe="")@@ -454,14 +467,20 @@ def _parse_canonicalized_record_uri() -> tuple[tuple[str, ...], str] | None:root = classify_uri(root_uri)root_tail = _identity_relative_root_tail(root)- if root_tail is None:- return None-candidate = classify_uri(uri)- if candidate.scope != root.scope or candidate.content_index is None:- return None+ if root.parts[:2] == ("~", "peers") and root.content_index == 3:+ if candidate.scope != "user" or candidate.content_index != 4:+ return None+ # Only the current-user alias changes; keep the peer ID in the match.+ root_tail = root.parts[1:]+ candidate_tail = candidate.parts[2:]+ else:+ if root_tail is None:+ return None+ if candidate.scope != root.scope or candidate.content_index is None:+ return None+ candidate_tail = candidate.parts[candidate.content_index :]- candidate_tail = candidate.parts[candidate.content_index :]if len(candidate_tail) < len(root_tail) + 2:return Noneif candidate_tail[: len(root_tail)] != root_tail:@@ -597,9 +616,16 @@ def _safe_ordered_compare(actual: Any, target: Any, compare) -> bool:return False-def _tuple_matches_prefix(value: tuple[str, ...], prefix: tuple[str, ...]) -> bool:- return len(value) >= len(prefix) and value[: len(prefix)] == prefix---def _tuple_matches_suffix(value: tuple[str, ...], suffix: tuple[str, ...]) -> bool:- return len(value) >= len(suffix) and value[-len(suffix) :] == suffix+def _namespace_matches(value: tuple[str, ...], condition: Any) -> bool:+ path = condition.path+ if len(value) < len(path):+ return False+ if condition.match_type == "prefix":+ selected = value[: len(path)]+ elif condition.match_type == "suffix":+ selected = value[-len(path) :] if path else ()+ else:+ raise ValueError(f"Unsupported match type: {condition.match_type}")+ return all(+ pattern == "*" or actual == pattern for actual, pattern in zip(selected, path, strict=False)+ )diff --git a/integrations/frameworks/langchain/tests/test_store.py b/integrations/frameworks/langchain/tests/test_store.pyindex 47a0cea13..b6049a737 100644--- a/integrations/frameworks/langchain/tests/test_store.py+++ b/integrations/frameworks/langchain/tests/test_store.py@@ -1,10 +1,24 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0+import asyncio+import jsonfrom datetime import datetime, timezonefrom unittest.mock import Mock+import pytest+from langgraph.store.base import (+ GetOp,+ InvalidNamespaceError,+ ListNamespacesOp,+ MatchCondition,+ PutOp,+)+from langgraph.store.memory import InMemoryStore+from openviking_sdk.errors import NotFoundError, PermissionDeniedError, UnavailableError+from langchain_openviking.store import OpenVikingStore+from langchain_openviking.testing import InMemoryOpenVikingClientdef test_write_record_preserves_created_at_when_create_is_an_upsert_alias():@@ -26,3 +40,183 @@ def test_write_record_preserves_created_at_when_create_is_an_upsert_alias():assert record["updated_at"] == "2026-01-02T00:00:00+00:00"store._write_create.assert_not_called()store._write_replace.assert_called_once()+++async def _read_or_update(store, operation, asynchronous):+ namespace, key = ("memory",), "note"+ if operation in {"batch-get", "batch-put"}:+ op = (+ GetOp(namespace, key)+ if operation == "batch-get"+ else PutOp(namespace, key, {"version": 2})+ )+ return (await store.abatch([op]) if asynchronous else store.batch([op]))[0]+ if operation == "put":+ return (+ await store.aput(namespace, key, {"version": 2})+ if asynchronous+ else store.put(namespace, key, {"version": 2})+ )+ if operation in {"search", "semantic"}:+ kwargs = {"query": "version"} if operation == "semantic" else {}+ return (+ await store.asearch(namespace, **kwargs)+ if asynchronous+ else store.search(namespace, **kwargs)+ )+ return await store.aget(namespace, key) if asynchronous else store.get(namespace, key)++[email protected]("asynchronous", [False, True])+ "operation", ["get", "put", "batch-get", "batch-put", "search", "semantic"]+)+ "error",+ [+ UnavailableError("test backend"),+ PermissionDeniedError("test read denied"),+ json.JSONDecodeError("invalid record", "{", 1),+ OSError("test storage read failed"),+ ],+)+def test_store_propagates_record_read_errors_without_writing(+ monkeypatch, operation, error, asynchronous+):+ client = InMemoryOpenVikingClient()+ store = OpenVikingStore(client=client)+ store.put(("memory",), "note", {"version": 1})+ original_records = dict(client.records)+ monkeypatch.setattr(client, "read", Mock(side_effect=error))++ with pytest.raises(type(error)) as caught:+ asyncio.run(_read_or_update(store, operation, asynchronous))++ assert caught.value is error+ assert client.records == original_records+ monkeypatch.undo()+ assert store.get(("memory",), "note").value == {"version": 1}++[email protected]("asynchronous", [False, True])+ "operation", ["get", "put", "batch-get", "batch-put", "search", "semantic"]+)[email protected]("error", [FileNotFoundError("test missing"), NotFoundError("test")])+def test_store_retains_explicit_missing_record_behavior(+ monkeypatch, operation, error, asynchronous+):+ client = InMemoryOpenVikingClient()+ store = OpenVikingStore(client=client)+ if operation not in {"put", "batch-put"}:+ store.put(("memory",), "note", {"version": 1})+ monkeypatch.setattr(client, "read", Mock(side_effect=error))++ result = asyncio.run(_read_or_update(store, operation, asynchronous))+ if operation in {"put", "batch-put"}:+ monkeypatch.undo()+ assert store.get(("memory",), "note").value == {"version": 2}+ elif operation in {"search", "semantic"}:+ assert result == []+ else:+ assert result is None+++NAMESPACES = (+ ("users", "ada", "prefs"),+ ("users", "grace", "prefs"),+ ("users", "ada", "events"),+ ("teams", "ops", "prefs"),+ ("users",),+ ("users", "ada", "prefs", "v2"),+ ("users", "a*b", "prefs"),+ ("用户", "小王", "prefs"),+)+++def stores():+ store = OpenVikingStore(client=InMemoryOpenVikingClient())+ reference = InMemoryStore()+ for number, namespace in enumerate(NAMESPACES):+ value = {"number": number}+ store.put(namespace, "item", value)+ reference.put(namespace, "item", value)+ return store, reference++[email protected]("asynchronous", [False, True])+ "query",+ [+ {},+ {"prefix": ("users",)},+ {"suffix": ("prefs",)},+ {"prefix": ("users", "ada")},+ {"prefix": ("users", "*")},+ {"prefix": ("*", "ada")},+ {"suffix": ("*", "prefs")},+ {"suffix": ("users", "*", "prefs")},+ {"prefix": ("users", "*"), "suffix": ("prefs",)},+ {"prefix": ("users", "*", "prefs"), "max_depth": 2},+ {"prefix": ("users", "*"), "limit": 2, "offset": 1},+ {"prefix": ("users", "a*b")},+ {"prefix": ("users", "a*")},+ {"prefix": ("users", "**")},+ {"prefix": (), "suffix": ()},+ {"prefix": ("用户",)},+ {"prefix": ("用户", "*")},+ ],+)+def test_store_namespace_queries_match_langgraph(stores, query, asynchronous):+ store, reference = stores+ expected = reference.list_namespaces(**query)+ actual = (+ asyncio.run(store.alist_namespaces(**query))+ if asynchronous+ else store.list_namespaces(**query)+ )+ assert actual == expected++[email protected]("asynchronous", [False, True])+ "conditions",+ [+ (MatchCondition("prefix", ("users", "*")), MatchCondition("prefix", ("users", "ada"))),+ (MatchCondition("prefix", ("teams",)), MatchCondition("prefix", ("users",))),+ (MatchCondition("suffix", ("events",)), MatchCondition("suffix", ("prefs",))),+ (MatchCondition("prefix", ("users", "*")), MatchCondition("suffix", ("*", "prefs"))),+ ],+)+def test_store_namespace_batch_applies_all_conditions(stores, conditions, asynchronous):+ store, reference = stores+ op = ListNamespacesOp(match_conditions=conditions)+ expected = reference.batch([op])+ actual = asyncio.run(store.abatch([op])) if asynchronous else store.batch([op])+ assert actual == expected+++def test_store_namespace_batch_rejects_unknown_match_type(stores):+ store, reference = stores+ op = ListNamespacesOp(match_conditions=(MatchCondition("unknown", ("users",)),))+ for implementation in (reference, store):+ with pytest.raises(ValueError, match="Unsupported match type: unknown"):+ implementation.batch([op])++[email protected]("max_depth", [0, -1])+def test_store_keeps_existing_nonpositive_namespace_depth_behavior(stores, max_depth):+ store, _ = stores+ assert store.list_namespaces(max_depth=max_depth) == sorted(+ {namespace[:max_depth] for namespace in NAMESPACES}+ )+++def test_store_keeps_namespace_validation_and_persisted_values(stores):+ store, _ = stores+ with pytest.raises(InvalidNamespaceError, match="Namespace cannot be empty"):+ store.put((), "root", {"number": -1})+ assert store.list_namespaces() == sorted(NAMESPACES)+ for number, namespace in enumerate(NAMESPACES):+ assert store.get(namespace, "item").value == {"number": number}diff --git a/integrations/frameworks/langchain/tests/unit/test_langchain_integration.py b/integrations/frameworks/langchain/tests/unit/test_langchain_integration.pyindex 6bfa6239f..063657047 100644--- a/integrations/frameworks/langchain/tests/unit/test_langchain_integration.py+++ b/integrations/frameworks/langchain/tests/unit/test_langchain_integration.py@@ -1935,15 +1935,35 @@ def test_langgraph_store_batch_rejects_ttl_writes():"viking://~/memories","viking://user/default/memories",),+ (+ "viking://~/peers/support/memories/langgraph_store",+ "viking://~/peers/support/memories",+ "viking://user/default/peers/support/memories",+ ),+ (+ "viking://~/peers/support/resources/langgraph_store",+ "viking://~/peers/support/resources",+ "viking://user/default/peers/support/resources",+ ),+ (+ "viking://user/default/peers/support/memories/langgraph_store",+ "viking://user/default/peers/support/memories",+ "viking://user/default/peers/support/memories",+ ),],ids=["user-memory",+ "peer-memory",+ "peer-resource",+ "explicit-peer-memory",],)[email protected]("asynchronous", [False, True])def test_langgraph_store_accepts_canonical_result_uris_for_home_alias_root(root_uri,alias_prefix,canonical_prefix,+ asynchronous,):class CanonicalizingClient(InMemoryOpenVikingClient):def _canonicalize(self, value):@@ -1973,11 +1993,30 @@ def test_langgraph_store_accepts_canonical_result_uris_for_home_alias_root(store.put(("users", "ada"), "preferences", {"color": "azure"})- semantic = store.search(("users",), query="azure", limit=5)+ async def read_results():+ return (+ await store.aget(("users", "ada"), "preferences"),+ await store.asearch(("users",)),+ await store.alist_namespaces(prefix=("users", "*")),+ await store.asearch(("users",), query="azure", limit=5),+ )- assert semantic[0].namespace == ("users", "ada")- assert semantic[0].key == "preferences"- assert semantic[0].value["color"] == "azure"+ direct, ordinary, namespaces, semantic = (+ asyncio.run(read_results())+ if asynchronous+ else (+ store.get(("users", "ada"), "preferences"),+ store.search(("users",)),+ store.list_namespaces(prefix=("users", "*")),+ store.search(("users",), query="azure", limit=5),+ )+ )+ assert direct.value == {"color": "azure"}+ assert [item.key for item in ordinary] == ["preferences"]+ assert namespaces == [("users", "ada")]+ assert [(item.namespace, item.key, item.value) for item in semantic] == [+ (("users", "ada"), "preferences", {"color": "azure"})+ ]def test_langgraph_store_ignores_unrelated_canonical_result_uris():@@ -1997,6 +2036,19 @@ def test_langgraph_store_ignores_unrelated_canonical_result_uris():is None)+ peer_store = OpenVikingStore(+ client=InMemoryOpenVikingClient(),+ root_uri="viking://~/peers/support/memories/langgraph_store",+ )+ for unrelated_root in (+ "viking://user/default/peers/other/memories/langgraph_store",+ "viking://user/default/memories/langgraph_store",+ "viking://agent/support/memories/langgraph_store",+ "viking://user/default/peers/support/memories/other_store",+ "viking://user/default/peers/support/resources/langgraph_store",+ ):+ assert peer_store._parse_index_uri(f"{unrelated_root}/index/users/ada.md") is None+def test_langgraph_store_waits_for_indexing_by_default():class RecordingClient(InMemoryOpenVikingClient):