Skip to content

Commit 6ec6116

Browse files
ehz0ahktz03
andauthored
fix(langchain): preserve Store reads and namespace discovery (#6342)
* fix(langchain): preserve LangGraph Store read errors (cherry picked from commit 471ade9) Signed-off-by: Hao Zhe <[email protected]> * fix(langchain): resolve peer home-alias store results (cherry picked from commit 91b5ada) Signed-off-by: Hao Zhe <[email protected]> * fix(langchain): honor namespace match conditions (cherry picked from commit bd26425) Signed-off-by: Hao Zhe <[email protected]> * test(langgraph): verify Store read and discovery contracts together Move namespace coverage into the existing package suite. Exercise read failures through sync, async, batch and search entrypoints, combine peer-alias discovery with wildcard listing, and retain the current empty-namespace validation. Document the corrected behavior in both integration guides. Signed-off-by: Hao Zhe <[email protected]> --------- Signed-off-by: Hao Zhe <[email protected]> Co-authored-by: ktz03 <[email protected]>
1 parent c0e35a5 commit 6ec6116

5 files changed

Lines changed: 323 additions & 41 deletions

File tree

‎docs/en/agent-integrations/07-langchain-langgraph.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,11 @@ equivalent to `delete()`. Deleting a key that does not exist is a no-op.
266266
the caller. Record and search-projection removal are separate operations: if only one
267267
succeeds, resolve the reported error and retry the operation to finish cleanup.
268268

269+
Record reads return `None` only for a missing record; permission, backend, and invalid-JSON
270+
errors propagate, and `put()` does not overwrite a record after a failed read.
271+
`list_namespaces(prefix=("users", "*"))` matches one namespace label per `*`, including
272+
when `root_uri` uses a peer home alias such as `viking://~/peers/support/memories/langgraph_store`.
273+
269274
### LangGraph middleware
270275

271276
```python

‎docs/zh/agent-integrations/07-langchain-langgraph.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,11 @@ store.put(("users", "ada"), "preferences", None) # 值为 None 表示删除该
253253
`put()` 会在修改记录前校验命名空间。其他删除错误会向调用方抛出。
254254
记录和搜索索引文件分别删除;如果只完成其中一步,请解决报告的错误后重试,以完成清理。
255255

256+
读取记录时,仅记录不存在才返回 `None`;权限、后端和 JSON 解析错误会向调用方抛出,
257+
`put()` 不会在读取失败后覆盖记录。
258+
`list_namespaces(prefix=("users", "*"))` 中的每个 `*` 匹配一层命名空间,
259+
也适用于 `viking://~/peers/support/memories/langgraph_store` 这样的 peer 主目录别名。
260+
256261
### LangGraph middleware
257262

258263
```python

‎integrations/frameworks/langchain/src/langchain_openviking/store.py‎

Lines changed: 63 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
GetOp,
3232
Item,
3333
ListNamespacesOp,
34+
MatchCondition,
3435
PutOp,
3536
SearchItem,
3637
SearchOp,
@@ -42,14 +43,15 @@
4243
GetOp,
4344
Item,
4445
ListNamespacesOp,
46+
MatchCondition,
4547
PutOp,
4648
SearchItem,
4749
SearchOp,
4850
)
4951
except ImportError: # pragma: no cover - exercised by optional import path
5052
_LANGGRAPH_IMPORT_ERROR = missing_dependency("langgraph", "langgraph")
5153
BaseStore = object
52-
GetOp = PutOp = SearchOp = ListNamespacesOp = object
54+
GetOp = PutOp = SearchOp = ListNamespacesOp = MatchCondition = object
5355
Item = SearchItem = object
5456

5557
logger = logging.getLogger(__name__)
@@ -127,11 +129,9 @@ def batch(self, ops: Iterable[Any]) -> list[Any]:
127129
)
128130
)
129131
elif isinstance(op, ListNamespacesOp):
130-
prefix, suffix = self._match_conditions_to_prefix_suffix(op.match_conditions)
131132
results.append(
132-
self.list_namespaces(
133-
prefix=prefix,
134-
suffix=suffix,
133+
self._list_namespaces(
134+
op.match_conditions,
135135
max_depth=op.max_depth,
136136
limit=op.limit,
137137
offset=op.offset,
@@ -147,7 +147,9 @@ async def abatch(self, ops: Iterable[Any]) -> list[Any]:
147147
def get(self, namespace: tuple[str, ...], key: str, *, refresh_ttl: Any = None) -> Any:
148148
try:
149149
record = self._read_record(self._data_uri(namespace, key))
150-
except Exception:
150+
except Exception as exc:
151+
if not is_not_found_error(exc):
152+
raise
151153
return None
152154
return Item(
153155
namespace=tuple(record["namespace"]),
@@ -223,15 +225,38 @@ def list_namespaces(
223225
limit: int = 100,
224226
offset: int = 0,
225227
) -> list[tuple[str, ...]]:
228+
conditions = []
229+
if prefix:
230+
conditions.append(MatchCondition("prefix", prefix))
231+
if suffix:
232+
conditions.append(MatchCondition("suffix", suffix))
233+
return self._list_namespaces(conditions, max_depth=max_depth, limit=limit, offset=offset)
234+
235+
def _list_namespaces(
236+
self,
237+
match_conditions: Iterable[Any] | None,
238+
*,
239+
max_depth: int | None,
240+
limit: int,
241+
offset: int,
242+
) -> list[tuple[str, ...]]:
243+
conditions = tuple(match_conditions or ())
244+
scan_prefix: tuple[str, ...] = ()
245+
for condition in conditions:
246+
if condition.match_type == "prefix":
247+
path = tuple(condition.path)
248+
literal_prefix = path[: path.index("*")] if "*" in path else path
249+
if len(literal_prefix) > len(scan_prefix):
250+
scan_prefix = literal_prefix
251+
226252
namespaces = set()
227-
for uri in self._all_data_uris(prefix or ()):
253+
# Wildcards match namespace labels, never physical URI path segments.
254+
for uri in self._all_data_uris(scan_prefix):
228255
parsed = self._parse_data_uri(uri)
229256
if parsed is None:
230257
continue
231258
namespace, _key = parsed
232-
if prefix and not _tuple_matches_prefix(namespace, prefix):
233-
continue
234-
if suffix and not _tuple_matches_suffix(namespace, suffix):
259+
if not all(_namespace_matches(namespace, condition) for condition in conditions):
235260
continue
236261
if max_depth is not None and len(namespace) > max_depth:
237262
namespace = namespace[:max_depth]
@@ -317,7 +342,9 @@ def _write_record(
317342
) -> dict[str, Any]:
318343
try:
319344
existing = self._read_record(uri)
320-
except Exception:
345+
except Exception as exc:
346+
if not is_not_found_error(exc):
347+
raise
321348
record = _store_record(namespace, key, value, created_at=now, updated_at=now)
322349
self._write_create(uri, json.dumps(record, ensure_ascii=False, indent=2))
323350
return record
@@ -421,20 +448,6 @@ def _item_to_search_item(self, item: Any, score: float | None) -> Any:
421448
score=score,
422449
)
423450

424-
def _match_conditions_to_prefix_suffix(
425-
self, conditions: Iterable[Any] | None
426-
) -> tuple[tuple[str, ...] | None, tuple[str, ...] | None]:
427-
prefix = None
428-
suffix = None
429-
for condition in conditions or []:
430-
match_type = getattr(condition, "match_type", None)
431-
path = tuple(getattr(condition, "path", ()) or ())
432-
if match_type == "prefix":
433-
prefix = path
434-
elif match_type == "suffix":
435-
suffix = path
436-
return prefix, suffix
437-
438451

439452
def _segment(value: str) -> str:
440453
return quote(str(value), safe="")
@@ -454,14 +467,20 @@ def _parse_canonicalized_record_uri(
454467
) -> tuple[tuple[str, ...], str] | None:
455468
root = classify_uri(root_uri)
456469
root_tail = _identity_relative_root_tail(root)
457-
if root_tail is None:
458-
return None
459-
460470
candidate = classify_uri(uri)
461-
if candidate.scope != root.scope or candidate.content_index is None:
462-
return None
471+
if root.parts[:2] == ("~", "peers") and root.content_index == 3:
472+
if candidate.scope != "user" or candidate.content_index != 4:
473+
return None
474+
# Only the current-user alias changes; keep the peer ID in the match.
475+
root_tail = root.parts[1:]
476+
candidate_tail = candidate.parts[2:]
477+
else:
478+
if root_tail is None:
479+
return None
480+
if candidate.scope != root.scope or candidate.content_index is None:
481+
return None
482+
candidate_tail = candidate.parts[candidate.content_index :]
463483

464-
candidate_tail = candidate.parts[candidate.content_index :]
465484
if len(candidate_tail) < len(root_tail) + 2:
466485
return None
467486
if candidate_tail[: len(root_tail)] != root_tail:
@@ -597,9 +616,16 @@ def _safe_ordered_compare(actual: Any, target: Any, compare) -> bool:
597616
return False
598617

599618

600-
def _tuple_matches_prefix(value: tuple[str, ...], prefix: tuple[str, ...]) -> bool:
601-
return len(value) >= len(prefix) and value[: len(prefix)] == prefix
602-
603-
604-
def _tuple_matches_suffix(value: tuple[str, ...], suffix: tuple[str, ...]) -> bool:
605-
return len(value) >= len(suffix) and value[-len(suffix) :] == suffix
619+
def _namespace_matches(value: tuple[str, ...], condition: Any) -> bool:
620+
path = condition.path
621+
if len(value) < len(path):
622+
return False
623+
if condition.match_type == "prefix":
624+
selected = value[: len(path)]
625+
elif condition.match_type == "suffix":
626+
selected = value[-len(path) :] if path else ()
627+
else:
628+
raise ValueError(f"Unsupported match type: {condition.match_type}")
629+
return all(
630+
pattern == "*" or actual == pattern for actual, pattern in zip(selected, path, strict=False)
631+
)

0 commit comments

Comments
 (0)