Skip to content

Commit d8f4854

Browse files
ehz0ahktz03varun-projectsRerankerGuo
authored
fix(langchain): align Store deletion, validation and removal errors (#6324)
* fix(langchain): honor sync Store put deletion semantics (cherry picked from commit 9cc5841) Signed-off-by: Hao Zhe <[email protected]> * fix(langgraph): delete item when store put receives None LangGraph's BaseStore contract treats a None value passed to put() as a deletion. OpenVikingStore.batch() already dispatched PutOp with a None value to delete(), and the inherited aput() reaches the same path through abatch(), but the sync put() override wrote None straight through the ordinary JSON record path. Before this change, put(namespace, key, None) stored a record whose value was null: get() returned an Item with value None, search() still listed the record, and list_namespaces() kept exposing the namespace. Calling it on a key that did not exist created a new null-valued record instead of doing nothing. The sync put() now delegates the None case to the existing delete(), after the unsupported-TTL guard so that put(..., None, ttl=...) still raises NotImplementedError and stays consistent with aput(). get() now returns None, search() omits the item, the namespace disappears once its last record is removed, and deleting a missing key is a no-op. The value annotation was widened to dict[str, Any] | None to match BaseStore. (cherry picked from commit 8578bd0) Signed-off-by: Hao Zhe <[email protected]> * fix(langchain): make OpenVikingStore.put(None) delete the item (fixes #5821) LangGraph's BaseStore.put() defines value=None as a deletion signal. The OpenViking adapter's batch / async paths already routed None through self.delete(...), but the sync put() override wrote the None through the ordinary JSON storage path, persisting a record whose value is JSON null. After the fix, put(namespace, key, None) delegates to delete(namespace, key) and returns, matching the public BaseStore contract: - get() returns None for the deleted key. - search() no longer returns the deleted item. - list_namespaces() no longer keeps the deleted item's namespace. - Deleting a missing key is a no-op (no null-valued record is created). The value type annotation is widened to "Mapping[str, Any] | None" to match the call sites batch already uses (op.value is forwarded as-is). (cherry picked from commit 564f8f1) Signed-off-by: Hao Zhe <[email protected]> * fix(langchain): propagate store removal failures (cherry picked from commit d9a8c82) Signed-off-by: Hao Zhe <[email protected]> * fix(langchain): validate namespaces before sync Store writes (cherry picked from commit 13a9e2c) Signed-off-by: Hao Zhe <[email protected]> * test(langchain): cover Store write and deletion contracts together Keep contributed deletion coverage in the adapter suite and remove overlapping assertions. Exercise sync, async and batch removal failures, partial cleanup and retry, invalid put(None) namespaces, independent items and unsupported TTL. Document partial removal behavior. Signed-off-by: Hao Zhe <[email protected]> --------- Signed-off-by: Hao Zhe <[email protected]> Co-authored-by: ktz03 <[email protected]> Co-authored-by: varun-projects <[email protected]> Co-authored-by: RerankerGuo <[email protected]>
1 parent aa47c87 commit d8f4854

4 files changed

Lines changed: 238 additions & 7 deletions

File tree

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,8 +256,16 @@ from langchain_openviking import OpenVikingStore
256256
store = OpenVikingStore(url="http://localhost:1933", api_key="...")
257257
store.put(("users", "ada"), "preferences", {"color": "azure"})
258258
items = store.search(("users",), query="azure", limit=3)
259+
store.put(("users", "ada"), "preferences", None) # a None value deletes the item
259260
```
260261

262+
Following LangGraph's `BaseStore` contract, passing `None` as the value deletes the item and is
263+
equivalent to `delete()`. Deleting a key that does not exist is a no-op.
264+
265+
`put()` validates the namespace before changing records. Other removal errors propagate to
266+
the caller. Record and search-projection removal are separate operations: if only one
267+
succeeds, resolve the reported error and retry the operation to finish cleanup.
268+
261269
### LangGraph middleware
262270

263271
```python

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,8 +244,15 @@ from langchain_openviking import OpenVikingStore
244244
store = OpenVikingStore(url="http://localhost:1933", api_key="...")
245245
store.put(("users", "ada"), "preferences", {"color": "azure"})
246246
items = store.search(("users",), query="azure", limit=3)
247+
store.put(("users", "ada"), "preferences", None) # 值为 None 表示删除该条目
247248
```
248249

250+
按 LangGraph `BaseStore` 约定,传入 `None` 作为值表示删除该条目,等价于 `delete()`。
251+
删除不存在的键不会产生任何影响。
252+
253+
`put()` 会在修改记录前校验命名空间。其他删除错误会向调用方抛出。
254+
记录和搜索索引文件分别删除;如果只完成其中一步,请解决报告的错误后重试,以完成清理。
255+
249256
### LangGraph middleware
250257

251258
```python

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

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
OptionalDependencyError,
1919
call_openviking,
2020
ensure_client,
21+
is_not_found_error,
2122
item_value,
2223
iter_result_items,
2324
missing_dependency,
@@ -60,6 +61,7 @@ class OpenVikingStore(BaseStore):
6061
Values are stored as JSON records under ``<root_uri>/data``. A separate
6162
markdown projection under ``<root_uri>/index`` gives OpenViking semantic
6263
retrieval a compact document to index for query-based ``search`` calls.
64+
Removal ignores missing targets and propagates other backend errors.
6365
6466
Args:
6567
root_uri: Base URI for the store. Defaults to the ``viking://~`` home alias,
@@ -159,17 +161,23 @@ def put(
159161
self,
160162
namespace: tuple[str, ...],
161163
key: str,
162-
value: Mapping[str, Any],
164+
value: Mapping[str, Any] | None,
163165
index: bool | list[str] | None = None,
164166
*,
165167
ttl: Any = None,
166168
) -> None:
169+
from langgraph.store.base import _validate_namespace
170+
167171
if ttl is not None:
168172
raise NotImplementedError(
169173
"TTL is not supported by OpenVikingStore. "
170174
"OpenViking stores LangGraph values as durable content records."
171175
)
172176
namespace = tuple(namespace)
177+
_validate_namespace(namespace)
178+
if value is None:
179+
self.delete(namespace, key)
180+
return
173181
now = datetime.now(timezone.utc)
174182
data_uri = self._data_uri(namespace, key)
175183
record = self._write_record(data_uri, namespace, key, dict(value), now)
@@ -353,9 +361,10 @@ def _write_replace(self, uri: str, content: str) -> None:
353361
def _remove(self, uri: str) -> None:
354362
try:
355363
call_openviking(self._client(), "rm", uri=uri, recursive=False)
356-
except Exception:
357-
logger.debug("OpenVikingStore remove ignored missing/unavailable URI", exc_info=True)
358-
pass
364+
except Exception as exc:
365+
if not is_not_found_error(exc):
366+
raise
367+
logger.debug("OpenVikingStore remove ignored missing URI", exc_info=True)
359368

360369
def _data_uri(self, namespace: tuple[str, ...], key: str) -> str:
361370
return f"{self._data_prefix_uri(namespace)}/{_segment(key)}.json"

‎integrations/frameworks/langchain/tests/unit/test_langchain_integration.py‎

Lines changed: 210 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import asyncio
34
import json
45
from copy import deepcopy
56
from types import MappingProxyType
@@ -23,8 +24,13 @@
2324
convert_to_openai_messages,
2425
)
2526
from langchain_core.runnables import RunnableLambda
26-
from langgraph.store.base import PutOp
27-
from openviking_sdk.errors import InvalidArgumentError
27+
from langgraph.store.base import InvalidNamespaceError, PutOp
28+
from openviking_sdk.errors import (
29+
InvalidArgumentError,
30+
NotFoundError,
31+
PermissionDeniedError,
32+
UnavailableError,
33+
)
2834

2935
import langchain_openviking.client as client_helpers
3036
from langchain_openviking import (
@@ -1609,7 +1615,11 @@ def delete_session(self, session_id: str) -> None:
16091615
assert len(client.sessions["clear-session"]) == 1
16101616

16111617

1612-
def test_langgraph_store_round_trip_and_semantic_search():
1618+
@pytest.mark.parametrize(
1619+
"invalid_namespace",
1620+
[(), ("users", "", "ada"), ("users", 1), ("users", "ada.profile"), ("langgraph", "ada")],
1621+
)
1622+
def test_langgraph_store_round_trip_and_semantic_search(invalid_namespace):
16131623
client = InMemoryOpenVikingClient()
16141624
store = OpenVikingStore(client=client)
16151625

@@ -1640,6 +1650,113 @@ def test_langgraph_store_round_trip_and_semantic_search():
16401650

16411651
assert store.list_namespaces(prefix=("users",)) == [("users", "ada")]
16421652

1653+
records = dict(client.records)
1654+
for value in ({"color": "invalid"}, None):
1655+
with pytest.raises(InvalidNamespaceError):
1656+
store.put(invalid_namespace, "preferences", value)
1657+
assert client.records == records
1658+
with pytest.raises(InvalidNamespaceError):
1659+
asyncio.run(store.aput(invalid_namespace, "preferences", value))
1660+
assert client.records == records
1661+
1662+
# A None value is a deletion in LangGraph's BaseStore contract.
1663+
store.put(("users", "ada"), "profile", None)
1664+
assert store.get(("users", "ada"), "profile") is None
1665+
assert "profile" not in {found.key for found in store.search(("users",), limit=5)}
1666+
1667+
# Deleting a missing key is idempotent and must not create a record.
1668+
store.put(("users", "ada"), "absent", None)
1669+
assert store.get(("users", "ada"), "absent") is None
1670+
1671+
store.put(("users", "ada"), "preferences", None)
1672+
store.put(("users", "ada"), "bad-rank", None)
1673+
assert store.search(("users",), limit=5) == []
1674+
assert store.list_namespaces(prefix=("users",)) == []
1675+
1676+
1677+
@pytest.mark.parametrize("method", ["put", "aput", "batch", "abatch", "delete", "adelete"])
1678+
@pytest.mark.parametrize("existing", [False, True])
1679+
def test_langgraph_store_none_deletes_through_public_store_methods(
1680+
method: str, existing: bool
1681+
) -> None:
1682+
store = OpenVikingStore(client=InMemoryOpenVikingClient())
1683+
namespace = ("users", "ada", "memories")
1684+
other_namespace = ("users", "grace", "memories")
1685+
store.put(other_namespace, "keep", {"text": "independent memory"})
1686+
if existing:
1687+
store.put(namespace, "item", {"text": "memory to remove"})
1688+
1689+
if method == "put":
1690+
store.put(namespace, "item", None)
1691+
elif method == "aput":
1692+
asyncio.run(store.aput(namespace, "item", None))
1693+
elif method == "batch":
1694+
store.batch([PutOp(namespace, "item", None)])
1695+
elif method == "abatch":
1696+
asyncio.run(store.abatch([PutOp(namespace, "item", None)]))
1697+
elif method == "delete":
1698+
store.delete(namespace, "item")
1699+
else:
1700+
asyncio.run(store.adelete(namespace, "item"))
1701+
1702+
assert store.get(namespace, "item") is None
1703+
assert store.search(namespace) == []
1704+
assert store.search(namespace, query="memory to remove") == []
1705+
assert store.list_namespaces() == [other_namespace]
1706+
assert store.get(other_namespace, "keep").value == {"text": "independent memory"}
1707+
1708+
1709+
@pytest.mark.parametrize("index", [False, ["text"]])
1710+
@pytest.mark.parametrize("existing", [False, True])
1711+
def test_langgraph_store_put_none_deletes_with_index_overrides(
1712+
index: bool | list[str], existing: bool
1713+
) -> None:
1714+
store = OpenVikingStore(client=InMemoryOpenVikingClient())
1715+
namespace = ("users", "ada")
1716+
if existing:
1717+
store.put(namespace, "item", {"text": "memory to remove"})
1718+
1719+
store.put(namespace, "item", None, index=index)
1720+
1721+
assert store.get(namespace, "item") is None
1722+
assert store.search(namespace) == []
1723+
assert store.search(namespace, query="memory to remove") == []
1724+
assert store.list_namespaces() == []
1725+
1726+
1727+
@pytest.mark.parametrize("method", ["put", "aput"])
1728+
@pytest.mark.parametrize("value", [{}, {"number": 0}, {"text": "saved memory"}])
1729+
def test_langgraph_store_dictionary_values_remain_stored(method: str, value: dict) -> None:
1730+
store = OpenVikingStore(client=InMemoryOpenVikingClient())
1731+
namespace = ("users", "ada")
1732+
if method == "put":
1733+
store.put(namespace, "item", value)
1734+
else:
1735+
asyncio.run(store.aput(namespace, "item", value))
1736+
1737+
assert store.get(namespace, "item").value == value
1738+
assert store.search(namespace)[0].value == value
1739+
assert store.list_namespaces() == [namespace]
1740+
1741+
1742+
@pytest.mark.parametrize("method", ["put", "aput"])
1743+
@pytest.mark.parametrize("value", [None, {"text": "replacement"}])
1744+
def test_langgraph_store_unsupported_ttl_still_rejects_before_mutation(
1745+
method: str, value: dict | None
1746+
) -> None:
1747+
store = OpenVikingStore(client=InMemoryOpenVikingClient())
1748+
namespace = ("users", "ada")
1749+
original = {"text": "original memory"}
1750+
store.put(namespace, "item", original)
1751+
1752+
with pytest.raises(NotImplementedError, match="TTL"):
1753+
if method == "put":
1754+
store.put(namespace, "item", value, ttl=60)
1755+
else:
1756+
asyncio.run(store.aput(namespace, "item", value, ttl=60))
1757+
1758+
assert store.get(namespace, "item").value == original
1759+
16431760

16441761
@pytest.mark.parametrize("use_batch", [False, True])
16451762
def test_langgraph_store_accepts_mapping_values(use_batch):
@@ -1659,6 +1776,96 @@ def test_langgraph_store_accepts_mapping_values(use_batch):
16591776
assert original == {"color": "azure", "nested": {"rank": 3}}
16601777

16611778

1779+
@pytest.mark.parametrize(
1780+
("method", "collection", "deindex"),
1781+
[
1782+
(method, collection, False)
1783+
for method in ("delete", "adelete", "put", "aput", "batch", "abatch")
1784+
for collection in ("data", "index")
1785+
]
1786+
+ [(method, "index", True) for method in ("put", "aput", "batch", "abatch")],
1787+
)
1788+
@pytest.mark.parametrize(
1789+
"error", [PermissionDeniedError(), UnavailableError(), TimeoutError("removal timed out")]
1790+
)
1791+
async def test_langgraph_store_removal_errors_remain_visible_and_retryable(
1792+
method, collection, deindex, error
1793+
):
1794+
class FailingRemoveClient(InMemoryOpenVikingClient):
1795+
fail = True
1796+
1797+
def rm(self, uri, recursive=False):
1798+
if self.fail and f"/{collection}/" in uri:
1799+
raise error
1800+
if uri not in self.records:
1801+
raise NotFoundError(uri)
1802+
return super().rm(uri, recursive=recursive)
1803+
1804+
client = FailingRemoveClient()
1805+
store = OpenVikingStore(client=client)
1806+
namespace, key, value = ("users",), "ada", {"color": "azure"}
1807+
store.put(namespace, key, value)
1808+
store.put(("other",), key, {"color": "teal"})
1809+
1810+
async def mutate():
1811+
replacement = value if deindex else None
1812+
index = False if deindex else None
1813+
if method == "delete":
1814+
store.delete(namespace, key)
1815+
elif method == "adelete":
1816+
await store.adelete(namespace, key)
1817+
elif method == "put":
1818+
store.put(namespace, key, replacement, index=index)
1819+
elif method == "aput":
1820+
await store.aput(namespace, key, replacement, index=index)
1821+
else:
1822+
ops = [
1823+
PutOp(namespace, key, replacement, index=index),
1824+
PutOp(namespace, "later", {"written": True}),
1825+
]
1826+
if method == "batch":
1827+
store.batch(ops)
1828+
else:
1829+
await store.abatch(ops)
1830+
1831+
with pytest.raises(type(error)) as caught:
1832+
await mutate()
1833+
assert str(caught.value) == str(error)
1834+
assert getattr(caught.value, "code", None) == getattr(error, "code", None)
1835+
assert bool(store.get(namespace, key)) is (deindex or collection == "data")
1836+
assert store.get(namespace, "later") is None
1837+
assert store.get(("other",), key).value == {"color": "teal"}
1838+
1839+
client.fail = False
1840+
await mutate()
1841+
assert store.search(namespace, query="azure") == []
1842+
item = store.get(namespace, key)
1843+
assert (item.value if item else None) == (value if deindex else None)
1844+
if method in ("batch", "abatch"):
1845+
assert store.get(namespace, "later").value == {"written": True}
1846+
1847+
1848+
@pytest.mark.parametrize("missing_error", [FileNotFoundError, NotFoundError])
1849+
def test_langgraph_store_removal_keeps_missing_targets_idempotent(missing_error):
1850+
class StrictRemoveClient(InMemoryOpenVikingClient):
1851+
def rm(self, uri, recursive=False):
1852+
if uri not in self.records:
1853+
raise missing_error(uri)
1854+
return super().rm(uri, recursive=recursive)
1855+
1856+
store = OpenVikingStore(client=StrictRemoveClient())
1857+
namespace, key, value = ("users",), "ada", {"color": "azure"}
1858+
store.delete(namespace, key)
1859+
store.put(namespace, key, value, index=False)
1860+
assert store.get(namespace, key).value == value
1861+
store.put(namespace, key, value)
1862+
assert len(store.search(namespace, query="azure")) == 1
1863+
store.delete(namespace, key)
1864+
store.delete(namespace, key)
1865+
assert store.get(namespace, key) is None
1866+
assert store.search(namespace, query="azure") == []
1867+
1868+
16621869
def test_langgraph_store_semantic_search_keeps_peer_id_out_of_retrieval():
16631870
client = InMemoryOpenVikingClient()
16641871
store = OpenVikingStore(client=client, actor_peer_id="peer-store")

0 commit comments

Comments
 (0)