Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(langchain): isolate session commits and report reset failures (#6479)

z1gon2260f6899e88
diff --git a/docs/en/agent-integrations/07-langchain-langgraph.md b/docs/en/agent-integrations/07-langchain-langgraph.md
index 6e9b6ce97..aa726c183 100644
--- a/docs/en/agent-integrations/07-langchain-langgraph.md
+++ b/docs/en/agent-integrations/07-langchain-langgraph.md
@@ -312,6 +312,13 @@ recorder.flush("support-thread-1")
recorder.close()
```
+Pass `commit_policy=` to `record()` or `arecord()` to override the recorder's
+policy for that call without changing its default. `None` uses the default;
+`OpenVikingCommitPolicy(mode="never")` suppresses a new post-write commit, but
+still retries any previously failed commit. `history.clear()` and `aclear()`
+raise if deletion or recreation fails; a failed recreation leaves the old
+session deleted and does not acknowledge pending context references.
+
`record()` writes only the messages supplied by the caller. It filters framework
control messages, writes in server-safe batches, and applies the configured
commit policy. If a later batch or the post-write commit fails,
diff --git a/docs/zh/agent-integrations/07-langchain-langgraph.md b/docs/zh/agent-integrations/07-langchain-langgraph.md
index a2611530b..6281d8a37 100644
--- a/docs/zh/agent-integrations/07-langchain-langgraph.md
+++ b/docs/zh/agent-integrations/07-langchain-langgraph.md
@@ -298,6 +298,11 @@ recorder.flush("support-thread-1")
recorder.close()
```
+向 `record()` 或 `arecord()` 传入 `commit_policy=` 可仅覆盖本次调用的策略,
+不改变 recorder 的默认值。`None` 使用默认策略;`OpenVikingCommitPolicy(mode="never")`
+禁止本次写入后的新 commit,但仍会重试之前失败的 commit。`history.clear()` 和 `aclear()`
+会在删除或重建失败时抛出异常;重建失败时旧 session 已被删除,待确认的上下文引用不会被确认。
+
`record()` 只写入调用方传入的消息;它会过滤框架控制消息、按服务端限制分批写入,并应用已配置的
commit 策略。如果后续批次或写入后的 commit 失败,`OpenVikingPartialWriteError` 会报告已经
确认写入的输入前缀,调用方可仅重试尚未写入的后缀;空后缀会安全地重试待完成的 commit。
diff --git a/integrations/frameworks/langchain/src/langchain_openviking/history.py b/integrations/frameworks/langchain/src/langchain_openviking/history.py
index 54e8eb7d0..0ef508bef 100644
--- a/integrations/frameworks/langchain/src/langchain_openviking/history.py
+++ b/integrations/frameworks/langchain/src/langchain_openviking/history.py
@@ -185,7 +185,7 @@ class OpenVikingChatMessageHistory(BaseChatMessageHistory):
def clear(self) -> None:
client = self._get_client()
call_openviking(client, "delete_session", session_id=self.session_id)
- self._ensure_session(client)
+ call_openviking(client, "create_session", session_id=self.session_id)
self._acknowledge_context_parts()
async def aclear(self) -> None:
@@ -193,7 +193,7 @@ class OpenVikingChatMessageHistory(BaseChatMessageHistory):
client = await self._get_async_client()
await acall_openviking(client, "delete_session", session_id=self.session_id)
- await self._aensure_session(client)
+ await acall_openviking(client, "create_session", session_id=self.session_id)
self._acknowledge_context_parts()
def close(self) -> None:
diff --git a/integrations/frameworks/langchain/src/langchain_openviking/middleware.py b/integrations/frameworks/langchain/src/langchain_openviking/middleware.py
index 4ff9e0761..d61c4c7de 100644
--- a/integrations/frameworks/langchain/src/langchain_openviking/middleware.py
+++ b/integrations/frameworks/langchain/src/langchain_openviking/middleware.py
@@ -312,10 +312,10 @@ class OpenVikingContextMiddleware(AgentMiddleware[OpenVikingCaptureState]):
plan = self._capture_plan(state, runtime)
if plan is None:
return None
- self.recorder.commit_policy = self.commit_policy if commit else None
+ policy = self.commit_policy if commit else None
if plan.unchanged:
with self._actor_peer_scope(plan.actor_peer_id):
- self.recorder.record(plan.session_id, ())
+ self.recorder.record(plan.session_id, (), commit_policy=policy)
self._pending_context_parts.pop(plan.key, None)
return None
try:
@@ -325,6 +325,7 @@ class OpenVikingContextMiddleware(AgentMiddleware[OpenVikingCaptureState]):
plan.messages[plan.start :],
peer_id=plan.peer_id,
context_parts=plan.context_parts,
+ commit_policy=policy,
)
except OpenVikingPartialWriteError as exc:
self._handle_partial_capture(plan, exc)
@@ -347,10 +348,10 @@ class OpenVikingContextMiddleware(AgentMiddleware[OpenVikingCaptureState]):
plan = self._capture_plan(state, runtime)
if plan is None:
return None
- self.recorder.commit_policy = self.commit_policy if commit else None
+ policy = self.commit_policy if commit else None
if plan.unchanged:
with self._actor_peer_scope(plan.actor_peer_id):
- await self.recorder.arecord(plan.session_id, ())
+ await self.recorder.arecord(plan.session_id, (), commit_policy=policy)
self._pending_context_parts.pop(plan.key, None)
return None
try:
@@ -360,6 +361,7 @@ class OpenVikingContextMiddleware(AgentMiddleware[OpenVikingCaptureState]):
plan.messages[plan.start :],
peer_id=plan.peer_id,
context_parts=plan.context_parts,
+ commit_policy=policy,
)
except OpenVikingPartialWriteError as exc:
self._handle_partial_capture(plan, exc)
diff --git a/integrations/frameworks/langchain/src/langchain_openviking/recording.py b/integrations/frameworks/langchain/src/langchain_openviking/recording.py
index b146cb069..4701a1606 100644
--- a/integrations/frameworks/langchain/src/langchain_openviking/recording.py
+++ b/integrations/frameworks/langchain/src/langchain_openviking/recording.py
@@ -284,10 +284,16 @@ class OpenVikingSessionRecorder:
messages: Iterable[BaseMessage],
peer_id: str | None = None,
context_parts: Sequence[dict[str, Any]] = (),
+ *,
+ commit_policy: OpenVikingCommitPolicy | None = None,
) -> OpenVikingRecordResult:
- """Persist a caller-selected batch and apply the configured commit policy."""
+ """Persist messages with a per-call policy, or the recorder default if None.
+
+ Use a ``never`` policy to suppress this call's post-write commit.
+ """
self._raise_if_closed()
+ policy = self.commit_policy if commit_policy is None else commit_policy
self._retry_pending_commit(session_id)
input_messages = list(messages)
prepared_messages = _prepare_messages(
@@ -343,7 +349,7 @@ class OpenVikingSessionRecorder:
apply_commit_policy(
client,
session_id,
- self.commit_policy,
+ policy,
persisted_pending_tokens=persisted_pending_tokens,
)
except Exception as exc:
@@ -362,10 +368,13 @@ class OpenVikingSessionRecorder:
messages: Iterable[BaseMessage],
peer_id: str | None = None,
context_parts: Sequence[dict[str, Any]] = (),
+ *,
+ commit_policy: OpenVikingCommitPolicy | None = None,
) -> OpenVikingRecordResult:
- """Asynchronously persist messages and apply the configured commit policy."""
+ """Async ``record`` with the same per-call and default policy behavior."""
self._raise_if_closed()
+ policy = self.commit_policy if commit_policy is None else commit_policy
await self._aretry_pending_commit(session_id)
input_messages = list(messages)
prepared_messages = _prepare_messages(
@@ -435,7 +444,7 @@ class OpenVikingSessionRecorder:
await aapply_commit_policy(
client,
session_id,
- self.commit_policy,
+ policy,
persisted_pending_tokens=persisted_pending_tokens,
)
except asyncio.CancelledError as exc:
diff --git a/integrations/frameworks/langchain/tests/unit/test_langchain_host_history.py b/integrations/frameworks/langchain/tests/unit/test_langchain_host_history.py
index 4a49c4bd8..b44b7b8d8 100644
--- a/integrations/frameworks/langchain/tests/unit/test_langchain_host_history.py
+++ b/integrations/frameworks/langchain/tests/unit/test_langchain_host_history.py
@@ -1,5 +1,7 @@
"""Native host history and capture remain independent of OV archive summaries."""
+import asyncio
+import threading
from copy import deepcopy
from types import SimpleNamespace
@@ -290,3 +292,53 @@ async def test_recall_preserves_existing_system_message(
else:
assert observed.content.startswith(f"{content}\n\n<openviking_context>")
assert "Deployment uses azure." in observed.content
+
+
[email protected]("capture_mode", ["sync", "async-sync-client", "async-native-client"])
[email protected]("first_commits", [False, True])
+async def test_concurrent_capture_hooks_keep_their_commit_policies(capture_mode, first_commits):
+ entered = threading.Event()
+ release = threading.Event()
+
+ class PausedClient(NoContextClient):
+ def batch_add_messages(self, session_id, messages, **kwargs):
+ if session_id == "first":
+ entered.set()
+ assert release.wait(5), "other session did not finish its capture"
+ return super().batch_add_messages(session_id, messages, **kwargs)
+
+ class AsyncPausedClient(NoContextClient):
+ async def batch_add_messages(self, session_id, messages, **kwargs):
+ if session_id == "first":
+ entered.set()
+ assert await asyncio.to_thread(release.wait, 5), "other session did not finish"
+ return super().batch_add_messages(session_id, messages, **kwargs)
+
+ client = AsyncPausedClient() if capture_mode == "async-native-client" else PausedClient()
+ client_kwargs = {"async_client" if capture_mode == "async-native-client" else "client": client}
+ middleware = OpenVikingContextMiddleware(**client_kwargs, commit_on_after_agent=True)
+
+ async def capture(session_id, commit):
+ name = "after_agent" if commit else "before_model"
+ state = {"session_id": session_id, "messages": [HumanMessage(content=session_id)]}
+ if capture_mode != "sync":
+ await getattr(middleware, "a" + name)(state, None)
+ else:
+ await asyncio.to_thread(getattr(middleware, name), state, None)
+
+ first = asyncio.create_task(capture("first", first_commits))
+ try:
+ assert await asyncio.to_thread(entered.wait, 5)
+ await capture("second", not first_commits)
+ finally:
+ release.set()
+ await first
+ await middleware.aclose()
+
+ committed, pending = ("first", "second") if first_commits else ("second", "first")
+ assert len(client.archives[committed]) == 1
+ assert client.archives[committed][0]["messages"][0]["parts"][0]["text"] == committed
+ assert not client.sessions[committed]
+ assert not client.archives[pending]
+ assert client.sessions[pending][0]["parts"][0]["text"] == pending
diff --git a/integrations/frameworks/langchain/tests/unit/test_langchain_recording.py b/integrations/frameworks/langchain/tests/unit/test_langchain_recording.py
index e999c9eeb..0fdb61798 100644
--- a/integrations/frameworks/langchain/tests/unit/test_langchain_recording.py
+++ b/integrations/frameworks/langchain/tests/unit/test_langchain_recording.py
@@ -15,6 +15,7 @@ from langchain_core.messages import (
SystemMessage,
ToolMessage,
)
+from openviking_sdk.errors import UnavailableError
import langchain_openviking.recording as recording_module
from langchain_openviking import (
@@ -321,22 +322,48 @@ def test_recorder_ignores_filtered_only_batch_without_initializing_client():
assert client._initialized is False
-def test_recorder_applies_commit_policy_once_after_all_batches():
[email protected]("asynchronous", [False, True])
+ "override", [None, "always", "never", "threshold-met", "threshold-not-met"]
+)
+async def test_recorder_applies_commit_policy_once_after_all_batches(asynchronous, override):
client = TrackingOpenVikingClient()
- recorder = OpenVikingSessionRecorder(
- client=client,
- commit_policy=OpenVikingCommitPolicy(mode="always"),
- )
+ default = OpenVikingCommitPolicy(mode="always" if override in (None, "never") else "never")
+ recorder = OpenVikingSessionRecorder(client=client, commit_policy=default)
+ policy = None
+ if override in ("always", "never"):
+ policy = OpenVikingCommitPolicy(mode=override)
+ elif override is not None:
+ policy = OpenVikingCommitPolicy(
+ mode="pending_tokens",
+ pending_token_threshold=1 if override == "threshold-met" else 100_000,
+ )
- recorder.record(
+ async def record(session_id, messages, **kwargs):
+ if asynchronous:
+ return await recorder.arecord(session_id, messages, **kwargs)
+ return recorder.record(session_id, messages, **kwargs)
+
+ await record(
"recorder-commit",
[HumanMessage(content=f"Message {index}") for index in range(101)],
+ **({"commit_policy": policy} if override is not None else {}),
)
+ commits = override not in ("never", "threshold-not-met")
assert client.batch_sizes == [100, 1]
- assert client.commit_calls == ["recorder-commit"]
- assert client.sessions["recorder-commit"] == []
- assert len(client.archives["recorder-commit"][0]["messages"]) == 101
+ assert client.commit_calls == (["recorder-commit"] if commits else [])
+ if commits:
+ assert client.sessions["recorder-commit"] == []
+ assert len(client.archives["recorder-commit"][0]["messages"]) == 101
+ else:
+ assert len(client.sessions["recorder-commit"]) == 101
+ assert not client.archives["recorder-commit"]
+
+ await record("recorder-default", [HumanMessage(content="Use the default again.")])
+ assert bool(client.archives["recorder-default"]) == (default.mode == "always")
+ await recorder.aclose()
def test_recorder_reports_partial_progress_and_retries_only_unwritten_suffix():
@@ -387,7 +414,12 @@ def test_recorder_reports_partial_progress_and_retries_only_unwritten_suffix():
]
-def test_recorder_reports_commit_failure_and_retries_without_duplicate_writes():
[email protected]("asynchronous", [False, True])
[email protected]("override", [False, True])
+async def test_recorder_reports_commit_failure_and_retries_without_duplicate_writes(
+ asynchronous, override
+):
class FailFirstCommitClient(TrackingOpenVikingClient):
def commit_session(self, session_id: str, **kwargs: Any) -> dict[str, Any]:
self.commit_calls.append(session_id)
@@ -398,15 +430,22 @@ def test_recorder_reports_commit_failure_and_retries_without_duplicate_writes():
client = FailFirstCommitClient()
recorder = OpenVikingSessionRecorder(
client=client,
- commit_policy=OpenVikingCommitPolicy(mode="always"),
+ commit_policy=OpenVikingCommitPolicy(mode="never" if override else "always"),
)
+
+ async def record(messages, policy):
+ kwargs = {"commit_policy": OpenVikingCommitPolicy(mode=policy)} if override else {}
+ if asynchronous:
+ return await recorder.arecord("recorder-failed-commit", messages, **kwargs)
+ return recorder.record("recorder-failed-commit", messages, **kwargs)
+
messages = [
HumanMessage(content="Remember this turn."),
AIMessage(content="Remembered."),
]
with pytest.raises(OpenVikingPartialWriteError, match="commit failed") as exc_info:
- recorder.record("recorder-failed-commit", messages)
+ await record(messages, "always")
assert exc_info.value.stage == "commit"
assert exc_info.value.commit_pending is True
@@ -415,16 +454,15 @@ def test_recorder_reports_commit_failure_and_retries_without_duplicate_writes():
assert client.batch_sizes == [2]
assert len(client.sessions["recorder-failed-commit"]) == 2
- recorder.record(
- "recorder-failed-commit",
- messages[exc_info.value.input_messages_consumed :],
- )
+ await record(messages[exc_info.value.input_messages_consumed :], "never")
assert client.batch_sizes == [2]
assert client.commit_calls == ["recorder-failed-commit", "recorder-failed-commit"]
assert client.sessions["recorder-failed-commit"] == []
assert len(client.archives["recorder-failed-commit"][0]["messages"]) == 2
+ await recorder.aclose()
+
def test_recorder_preserves_first_batch_exception_type():
class FailFirstBatchClient(TrackingOpenVikingClient):
@@ -851,3 +889,78 @@ def test_responses_text_used_for_recall_and_tool_output():
recorder = OpenVikingSessionRecorder(client=client)
recorder.record("tools", [tool])
assert client.sessions["tools"][0]["parts"][0]["tool_output"] == "tool result"
+
+
[email protected]("async_mode", [False, True])
[email protected]("failure", [None, "create-unavailable", "create-denied", "delete"])
+async def test_history_clear_reports_reset_failures_before_acknowledging_context(
+ async_mode, failure
+):
+ error = (
+ UnavailableError("recreation unavailable")
+ if failure == "create-unavailable"
+ else PermissionError("reset denied")
+ )
+ calls = []
+ acknowledged = []
+ resetting = False
+
+ class ResetClient(InMemoryOpenVikingClient):
+ def delete_session(self, session_id):
+ calls.append("delete")
+ if failure == "delete":
+ raise error
+ return super().delete_session(session_id)
+
+ def create_session(self, session_id=None):
+ calls.append("create")
+ if resetting and failure and failure.startswith("create"):
+ raise error
+ return super().create_session(session_id)
+
+ class AsyncResetClient(ResetClient):
+ async def delete_session(self, session_id):
+ return super().delete_session(session_id)
+
+ async def create_session(self, session_id=None):
+ return super().create_session(session_id)
+
+ client = AsyncResetClient() if async_mode else ResetClient()
+ history = OpenVikingChatMessageHistory(
+ "reset-session",
+ **({"async_client": client} if async_mode else {"client": client}),
+ context_parts_provider=lambda _: [{"type": "context", "uri": "viking://resources/a"}],
+ context_parts_acknowledger=acknowledged.append,
+ )
+ InMemoryOpenVikingClient.create_session(client, "reset-session")
+ if async_mode:
+ await history.aadd_messages([HumanMessage("old turn")])
+ else:
+ history.add_messages([HumanMessage("old turn")])
+
+ resetting = True
+
+ async def clear():
+ if async_mode:
+ await history.aclear()
+ else:
+ history.clear()
+
+ if failure:
+ with pytest.raises(type(error)) as caught:
+ await clear()
+ assert caught.value is error
+ assert acknowledged == []
+ assert ("reset-session" in client.sessions) == (failure == "delete")
+ else:
+ await clear()
+ assert client.sessions["reset-session"] == []
+ assert acknowledged == ["reset-session"]
+ if async_mode:
+ await history.aadd_messages([HumanMessage("new turn")])
+ else:
+ history.add_messages([HumanMessage("new turn")])
+ assert len(client.sessions["reset-session"]) == 1
+ assert calls == (["delete"] if failure == "delete" else ["delete", "create"])
+ await history.aclose()