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
feat(integrations): unify LangChain and LangGraph session recording (#3530)
Hao Zheea6e2dbb419a
diff --git a/docs/en/agent-integrations/07-langchain-langgraph.md b/docs/en/agent-integrations/07-langchain-langgraph.mdindex 3169cb55b..2db109f41 100644--- a/docs/en/agent-integrations/07-langchain-langgraph.md+++ b/docs/en/agent-integrations/07-langchain-langgraph.md@@ -59,6 +59,7 @@ chain.invoke(| Store durable cross-thread state | `OpenVikingStore` || Inject context into LangGraph as middleware | `OpenVikingContextMiddleware` || Back LangChain chat history with OpenViking | `OpenVikingChatMessageHistory` |+| Record caller-selected LangChain messages from a custom lifecycle | `OpenVikingSessionRecorder` |## Quick examples@@ -117,6 +118,40 @@ middleware = OpenVikingContextMiddleware()```+### Session recorder++Use the recorder when your application already owns the conversation lifecycle+and only needs reusable OpenViking persistence:++```python+from openviking.integrations.langchain import (+ OpenVikingPartialWriteError,+ OpenVikingSessionRecorder,+)++recorder = OpenVikingSessionRecorder(url="http://localhost:1933", api_key="...")+try:+ recorder.record("support-thread-1", messages, peer_id="assistant-a")+except OpenVikingPartialWriteError as exc:+ recorder.record(+ "support-thread-1",+ messages[exc.input_messages_consumed :],+ peer_id="assistant-a",+ )+recorder.flush("support-thread-1")+recorder.close()+```++`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,+`OpenVikingPartialWriteError` reports the confirmed input prefix so callers can+retry only the unwritten suffix; an empty suffix safely retries a pending+commit. When supplying `context_parts`, resend them only if+`exc.context_attached` is false. `flush()` forces a commit only when the session+has pending content. After `close()`, the recorder cannot be reused; injected+clients remain owned by the caller.+## Try the examplesThe repository includes runnable examples that work without model credentials using an in-memory test client:diff --git a/docs/zh/agent-integrations/07-langchain-langgraph.md b/docs/zh/agent-integrations/07-langchain-langgraph.mdindex a5b8b5e02..d9bbb342f 100644--- a/docs/zh/agent-integrations/07-langchain-langgraph.md+++ b/docs/zh/agent-integrations/07-langchain-langgraph.md@@ -59,6 +59,7 @@ chain.invoke(| 存储跨线程的持久化状态 | `OpenVikingStore` || 在 LangGraph 中以 middleware 注入上下文 | `OpenVikingContextMiddleware` || 用 OpenViking 存储 LangChain 聊天记录 | `OpenVikingChatMessageHistory` |+| 在自定义生命周期中记录调用方选定的 LangChain 消息 | `OpenVikingSessionRecorder` |## 快速示例@@ -117,6 +118,36 @@ middleware = OpenVikingContextMiddleware()```+### Session recorder++当应用已经自行管理会话生命周期,只需要复用 OpenViking 持久化能力时,可使用 recorder:++```python+from openviking.integrations.langchain import (+ OpenVikingPartialWriteError,+ OpenVikingSessionRecorder,+)++recorder = OpenVikingSessionRecorder(url="http://localhost:1933", api_key="...")+try:+ recorder.record("support-thread-1", messages, peer_id="assistant-a")+except OpenVikingPartialWriteError as exc:+ recorder.record(+ "support-thread-1",+ messages[exc.input_messages_consumed :],+ peer_id="assistant-a",+ )+recorder.flush("support-thread-1")+recorder.close()+```++`record()` 只写入调用方传入的消息;它会过滤框架控制消息、按服务端限制分批写入,并应用已配置的+commit 策略。如果后续批次或写入后的 commit 失败,`OpenVikingPartialWriteError` 会报告已经+确认写入的输入前缀,调用方可仅重试尚未写入的后缀;空后缀会安全地重试待完成的 commit。+传入 `context_parts` 时,仅在 `exc.context_attached` 为 false 时重传。`flush()` 仅在 session+存在待提交内容时强制 commit。`close()` 后 recorder 不可复用;由调用方注入的 client+仍归调用方管理。+## 运行示例仓库内提供了可直接运行的最小示例,使用内存测试客户端,无需模型凭证:diff --git a/openviking/integrations/langchain/__init__.py b/openviking/integrations/langchain/__init__.pyindex d33e6ce67..21cb4707e 100644--- a/openviking/integrations/langchain/__init__.py+++ b/openviking/integrations/langchain/__init__.py@@ -15,8 +15,11 @@ __all__ = ["OpenVikingChatMessageHistory","OpenVikingCommitPolicy","OpenVikingContextMiddleware",+ "OpenVikingPartialWriteError",+ "OpenVikingRecordResult","OpenVikingRetriever","OpenVikingSessionContextAssembler",+ "OpenVikingSessionRecorder","OpenVikingStore","create_openviking_tools","with_openviking_context",@@ -44,6 +47,18 @@ def __getattr__(name: str) -> Any:from openviking.integrations.langchain.context import OpenVikingSessionContextAssemblerreturn OpenVikingSessionContextAssembler+ if name == "OpenVikingSessionRecorder":+ from openviking.integrations.langchain.recording import OpenVikingSessionRecorder++ return OpenVikingSessionRecorder+ if name == "OpenVikingPartialWriteError":+ from openviking.integrations.langchain.recording import OpenVikingPartialWriteError++ return OpenVikingPartialWriteError+ if name == "OpenVikingRecordResult":+ from openviking.integrations.langchain.recording import OpenVikingRecordResult++ return OpenVikingRecordResultif name == "OpenVikingCommitPolicy":from openviking.integrations.langchain.client import OpenVikingCommitPolicydiff --git a/openviking/integrations/langchain/context.py b/openviking/integrations/langchain/context.pyindex a1d34b212..fc71e085c 100644--- a/openviking/integrations/langchain/context.py+++ b/openviking/integrations/langchain/context.py@@ -5,6 +5,7 @@from __future__ import annotationsimport logging+from collections.abc import Callablefrom dataclasses import dataclass, fieldfrom typing import Any, Sequence@@ -29,9 +30,9 @@ from openviking.integrations.langchain.history import (OpenVikingChatMessageHistory,context_parts_from_documents,)+from openviking.integrations.langchain.messages import OPENVIKING_CONTEXT_MARKERfrom openviking.integrations.langchain.retrievers import OpenVikingRetriever-OPENVIKING_CONTEXT_MARKER = "<openviking_context>"logger = logging.getLogger(__name__)@@ -268,6 +269,18 @@ def with_openviking_context(active_peer_ids: dict[str, str | None] = {}def make_history(active_session_id: str) -> OpenVikingChatMessageHistory:+ def pending_key(current_session_id: str) -> tuple[str, str]:+ return _pending_context_key(+ current_session_id,+ active_peer_ids.get(current_session_id, peer_id),+ )++ def provide_context_parts(current_session_id: str) -> list[dict[str, Any]]:+ return list(pending_context_parts.get(pending_key(current_session_id), []))++ def acknowledge_context_parts(current_session_id: str) -> None:+ pending_context_parts.pop(pending_key(current_session_id), None)+return OpenVikingChatMessageHistory(session_id=active_session_id,peer_id=peer_id,@@ -288,22 +301,22 @@ def with_openviking_context(auto_initialize=auto_initialize,token_budget=token_budget,commit_policy=commit_policy,- context_parts_provider=lambda current_session_id: pending_context_parts.pop(- _pending_context_key(- current_session_id,- active_peer_ids.get(current_session_id, peer_id),- ),- [],- ),+ context_parts_provider=provide_context_parts,+ context_parts_acknowledger=acknowledge_context_parts,)if session_id is None:- def session_history_factory(resolved_session_id: str) -> OpenVikingChatMessageHistory:+ def dynamic_session_history_factory(+ resolved_session_id: str,+ ) -> OpenVikingChatMessageHistory:return make_history(_validate_session_id(resolved_session_id, key=session_id_config_key))+ session_history_factory: Callable[..., OpenVikingChatMessageHistory] = (+ dynamic_session_history_factory+ )history_factory_config = [ConfigurableFieldSpec(id=session_id_config_key,@@ -316,9 +329,10 @@ def with_openviking_context(]else:- def session_history_factory() -> OpenVikingChatMessageHistory:+ def fixed_session_history_factory() -> OpenVikingChatMessageHistory:return make_history(session_id)+ session_history_factory = fixed_session_history_factoryhistory_factory_config = Nonedef inject(input_value: Any, config: dict[str, Any] | None = None) -> Any:diff --git a/openviking/integrations/langchain/history.py b/openviking/integrations/langchain/history.pyindex 9af0893c7..f16ddf2b7 100644--- a/openviking/integrations/langchain/history.py+++ b/openviking/integrations/langchain/history.py@@ -10,13 +10,7 @@ from typing import Any, Callabletry:from langchain_core.chat_history import BaseChatMessageHistory- from langchain_core.messages import (- AIMessage,- BaseMessage,- HumanMessage,- SystemMessage,- ToolMessage,- )+ from langchain_core.messages import BaseMessageexcept ImportError as exc: # pragma: no cover - exercised by optional import pathfrom openviking.integrations.langchain.client import missing_dependency@@ -24,11 +18,20 @@ except ImportError as exc: # pragma: no cover - exercised by optional import pafrom openviking.integrations.langchain.client import (OpenVikingCommitPolicy,- OpenVikingConnection,- apply_commit_policy,call_openviking,- ensure_client,- extract_message_text,+)+from openviking.integrations.langchain.messages import (+ langchain_message_to_openviking as langchain_message_to_openviking,+)+from openviking.integrations.langchain.messages import (+ openviking_message_to_langchain as openviking_message_to_langchain,+)+from openviking.integrations.langchain.messages import (+ restore_openviking_messages,+)+from openviking.integrations.langchain.recording import (+ OpenVikingPartialWriteError,+ OpenVikingSessionRecorder,)logger = logging.getLogger(__name__)@@ -56,6 +59,7 @@ class OpenVikingChatMessageHistory(BaseChatMessageHistory):persist_system_messages: bool = False,commit_policy: OpenVikingCommitPolicy | None = None,context_parts_provider: Callable[[str], list[dict[str, Any]]] | None = None,+ context_parts_acknowledger: Callable[[str], None] | None = None,peer_id: str | None = None,peer_id_provider: Callable[[str], str | None] | None = None,):@@ -66,9 +70,10 @@ class OpenVikingChatMessageHistory(BaseChatMessageHistory):# Retained for constructor compatibility. System messages are runtime# policy, not conversation memory, so they are never persisted.self.persist_system_messages = False- self.commit_policy = commit_policyself.context_parts_provider = context_parts_provider- self._connection = OpenVikingConnection(+ self.context_parts_acknowledger = context_parts_acknowledger+ self._pending_context_parts: list[dict[str, Any]] = []+ self._recorder = OpenVikingSessionRecorder(client=client,url=url,api_key=api_key,@@ -80,8 +85,18 @@ class OpenVikingChatMessageHistory(BaseChatMessageHistory):timeout=timeout,extra_headers=extra_headers,auto_initialize=auto_initialize,+ commit_policy=commit_policy,)- self._client_cache: Any = None++ @property+ def commit_policy(self) -> OpenVikingCommitPolicy | None:+ """Return the recorder commit policy used by this history."""++ return self._recorder.commit_policy++ @commit_policy.setter+ def commit_policy(self, value: OpenVikingCommitPolicy | None) -> None:+ self._recorder.commit_policy = value@propertydef messages(self) -> list[BaseMessage]:@@ -98,47 +113,39 @@ class OpenVikingChatMessageHistory(BaseChatMessageHistory):self._ensure_session(client)return []- return _restore_openviking_messages(context.get("messages") or [])+ return restore_openviking_messages(context.get("messages") or [])def add_messages(self, messages: Sequence[BaseMessage]) -> None:- client = self._get_client()- pending_context_parts = (- list(self.context_parts_provider(self.session_id))- if self.context_parts_provider- else []- )- batch = []- effective_peer_id = self._effective_peer_id()- for message in messages:- for payload in langchain_message_to_openviking(- message,- persist_system_messages=self.persist_system_messages,- ):- if pending_context_parts and payload["role"] == "assistant":- payload["parts"].extend(pending_context_parts)- pending_context_parts = []- if effective_peer_id is not None:- payload["peer_id"] = effective_peer_id- batch.append(payload)-- if batch:- call_openviking(- client,- "batch_add_messages",- session_id=self.session_id,- messages=batch,+ if not self._pending_context_parts and self.context_parts_provider:+ self._pending_context_parts = list(self.context_parts_provider(self.session_id))+ try:+ result = self._recorder.record(+ self.session_id,+ messages,+ peer_id=self._effective_peer_id(),+ context_parts=self._pending_context_parts,)- apply_commit_policy(client, self.session_id, self.commit_policy)+ except OpenVikingPartialWriteError as exc:+ if exc.context_attached:+ self._acknowledge_context_parts()+ raise+ if result.context_attached:+ self._acknowledge_context_parts()def clear(self) -> None:client = self._get_client()call_openviking(client, "delete_session", session_id=self.session_id)self._ensure_session(client)+ self._acknowledge_context_parts()++ def close(self) -> None:+ """Release resources owned by this history adapter."""++ self._acknowledge_context_parts()+ self._recorder.close()def _get_client(self) -> Any:- if self._client_cache is None:- self._client_cache = ensure_client(self._connection)- return self._client_cache+ return self._recorder.clientdef _ensure_session(self, client: Any) -> None:try:@@ -157,126 +164,19 @@ class OpenVikingChatMessageHistory(BaseChatMessageHistory):text = str(value).strip()return text or None--def langchain_message_to_openviking(- message: BaseMessage,- *,- persist_system_messages: bool = False,-) -> list[dict[str, Any]]:- """Convert a LangChain message into one or more OpenViking add_message payloads."""-- if isinstance(message, HumanMessage):- parts = _text_parts(message.content)- return [{"role": "user", "parts": parts or [{"type": "text", "text": ""}]}]-- if isinstance(message, AIMessage):- parts = _text_parts(message.content)- for tool_call in message.tool_calls or []:- parts.append(- {- "type": "tool",- "tool_id": str(tool_call.get("id") or ""),- "tool_name": str(tool_call.get("name") or ""),- "tool_input": _tool_args(tool_call.get("args")),- "tool_status": "pending",- }- )- return [{"role": "assistant", "parts": parts or [{"type": "text", "text": ""}]}]-- if isinstance(message, ToolMessage):- return [- {- "role": "assistant",- "parts": [- {- "type": "tool",- "tool_id": str(message.tool_call_id or ""),- "tool_name": str(message.name or ""),- "tool_output": extract_message_text(message.content),- "tool_status": _tool_status(message),- }- ],- }- ]-- if isinstance(message, SystemMessage):- return []-- text = extract_message_text(getattr(message, "content", ""))- if not text:- return []- role = "user" if getattr(message, "type", "") == "human" else "assistant"- return [{"role": role, "parts": [{"type": "text", "text": text}]}]---def openviking_message_to_langchain(message: dict[str, Any]) -> list[BaseMessage]:- """Convert one OpenViking session message into LangChain messages."""-- role = str(message.get("role") or "")- parts = list(message.get("parts") or [])- text = _parts_text(parts)- if role == "user":- return [HumanMessage(content=text)]-- tool_calls = []- tool_messages = []- for part in parts:- if part.get("type") != "tool":- continue- tool_id = str(part.get("tool_id") or "")- tool_name = str(part.get("tool_name") or "")- status = str(part.get("tool_status") or "")- has_output = part.get("tool_output") is not None- is_completed_result = has_output or status in {"completed", "error"}- if is_completed_result:- tool_messages.append(- ToolMessage(- content=str(part.get("tool_output") or ""),- tool_call_id=tool_id or "openviking-tool",- name=tool_name or None,- status="error" if status == "error" else "success",- )- )- else:- tool_calls.append(- {- "id": tool_id,- "name": tool_name,- "args": _tool_args(part.get("tool_input")),- }+ def _acknowledge_context_parts(self) -> None:+ had_pending_context = bool(self._pending_context_parts)+ self._pending_context_parts = []+ if not had_pending_context or self.context_parts_acknowledger is None:+ return+ try:+ self.context_parts_acknowledger(self.session_id)+ except Exception:+ logger.warning(+ "OpenViking context-parts acknowledgement failed",+ exc_info=True,)- messages: list[BaseMessage] = []- if text or tool_calls or not tool_messages:- messages.append(- AIMessage(content=text, tool_calls=tool_calls or [])- if tool_calls- else AIMessage(content=text)- )- messages.extend(tool_messages)- return messages---def _restore_openviking_messages(messages: Sequence[dict[str, Any]]) -> list[BaseMessage]:- restored: list[BaseMessage] = []- active_tool_call_ids: set[str] = set()- for message in messages:- for langchain_message in openviking_message_to_langchain(message):- if isinstance(langchain_message, AIMessage):- restored.append(langchain_message)- for tool_call in langchain_message.tool_calls or []:- tool_call_id = str(tool_call.get("id") or "")- if tool_call_id:- active_tool_call_ids.add(tool_call_id)- elif isinstance(langchain_message, ToolMessage):- tool_call_id = str(langchain_message.tool_call_id or "")- if tool_call_id and tool_call_id in active_tool_call_ids:- restored.append(langchain_message)- active_tool_call_ids.discard(tool_call_id)- else:- restored.append(langchain_message)- return restored-def context_parts_from_documents(documents: Sequence[Any]) -> list[dict[str, Any]]:"""Build OpenViking ContextPart dictionaries from LangChain Documents."""@@ -297,32 +197,3 @@ def context_parts_from_documents(documents: Sequence[Any]) -> list[dict[str, Any})return parts---def _text_parts(content: Any) -> list[dict[str, str]]:- text = extract_message_text(content)- return [{"type": "text", "text": text}] if text else []---def _parts_text(parts: Sequence[dict[str, Any]]) -> str:- chunks: list[str] = []- for part in parts:- part_type = part.get("type")- if part_type == "text" and part.get("text"):- chunks.append(str(part["text"]))- elif part_type == "context" and part.get("abstract"):- uri = part.get("uri") or "context"- chunks.append(f"[context:{uri}] {part['abstract']}")- return "\n".join(chunks)---def _tool_args(value: Any) -> dict[str, Any]:- if value is None:- return {}- if isinstance(value, dict):- return value- return {"value": value}---def _tool_status(message: ToolMessage) -> str:- return "error" if getattr(message, "status", "") == "error" else "completed"diff --git a/openviking/integrations/langchain/messages.py b/openviking/integrations/langchain/messages.pynew file mode 100644index 000000000..4cd348eeb--- /dev/null+++ b/openviking/integrations/langchain/messages.py@@ -0,0 +1,206 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""LangChain message conversion and recording filters."""++from __future__ import annotations++from collections.abc import Sequence+from copy import deepcopy+from typing import Any++try:+ from langchain_core.messages import (+ AIMessage,+ BaseMessage,+ HumanMessage,+ SystemMessage,+ ToolMessage,+ )+except ImportError as exc: # pragma: no cover - exercised by optional import path+ from openviking.integrations.langchain.client import missing_dependency++ raise missing_dependency("langchain", "langchain-core") from exc++from openviking.integrations.langchain.client import extract_message_text++OPENVIKING_CONTEXT_MARKER = "<openviking_context>"+LANGCHAIN_SUMMARIZATION_SOURCE = "summarization"+++def is_recordable_langchain_message(message: BaseMessage) -> bool:+ """Return whether a framework message belongs in OpenViking session history."""++ if isinstance(message, SystemMessage):+ return False+ additional_kwargs = getattr(message, "additional_kwargs", {}) or {}+ if additional_kwargs.get("lc_source") == LANGCHAIN_SUMMARIZATION_SOURCE:+ return False+ if isinstance(message, AIMessage):+ return bool(+ extract_message_text(message.content)+ or message.tool_calls+ or additional_kwargs.get("tool_calls")+ )+ return bool(langchain_message_to_openviking(message))+++def is_context_carrier_langchain_message(message: BaseMessage) -> bool:+ """Return whether an otherwise-empty assistant can carry recalled context."""++ if not isinstance(message, AIMessage):+ return False+ additional_kwargs = getattr(message, "additional_kwargs", {}) or {}+ return additional_kwargs.get("lc_source") != LANGCHAIN_SUMMARIZATION_SOURCE+++def langchain_message_to_openviking(+ message: BaseMessage,+ *,+ persist_system_messages: bool = False,+) -> list[dict[str, Any]]:+ """Convert a LangChain message into one or more OpenViking message payloads."""++ del persist_system_messages # Retained for compatibility; system policy is never persisted.++ if isinstance(message, HumanMessage):+ human_parts = _text_parts(message.content)+ return [{"role": "user", "parts": human_parts or [{"type": "text", "text": ""}]}]++ if isinstance(message, AIMessage):+ parts: list[dict[str, Any]] = _text_parts(message.content)+ for tool_call in message.tool_calls or []:+ parts.append(+ {+ "type": "tool",+ "tool_id": str(tool_call.get("id") or ""),+ "tool_name": str(tool_call.get("name") or ""),+ "tool_input": _tool_args(tool_call.get("args")),+ "tool_status": "pending",+ }+ )+ return [{"role": "assistant", "parts": parts or [{"type": "text", "text": ""}]}]++ if isinstance(message, ToolMessage):+ return [+ {+ "role": "assistant",+ "parts": [+ {+ "type": "tool",+ "tool_id": str(message.tool_call_id or ""),+ "tool_name": str(message.name or ""),+ "tool_output": extract_message_text(message.content),+ "tool_status": _tool_status(message),+ }+ ],+ }+ ]++ if isinstance(message, SystemMessage):+ return []++ text = extract_message_text(getattr(message, "content", ""))+ if not text:+ return []+ role = "user" if getattr(message, "type", "") == "human" else "assistant"+ return [{"role": role, "parts": [{"type": "text", "text": text}]}]+++def openviking_message_to_langchain(message: dict[str, Any]) -> list[BaseMessage]:+ """Convert one OpenViking session message into LangChain messages."""++ role = str(message.get("role") or "")+ parts = list(message.get("parts") or [])+ text = _parts_text(parts)+ if role == "user":+ return [HumanMessage(content=text)]++ tool_calls = []+ tool_messages = []+ for part in parts:+ if part.get("type") != "tool":+ continue+ tool_id = str(part.get("tool_id") or "")+ tool_name = str(part.get("tool_name") or "")+ status = str(part.get("tool_status") or "")+ has_output = part.get("tool_output") is not None+ is_completed_result = has_output or status in {"completed", "error"}+ if is_completed_result:+ tool_messages.append(+ ToolMessage(+ content=str(part.get("tool_output") or ""),+ tool_call_id=tool_id or "openviking-tool",+ name=tool_name or None,+ status="error" if status == "error" else "success",+ )+ )+ else:+ tool_calls.append(+ {+ "id": tool_id,+ "name": tool_name,+ "args": _tool_args(part.get("tool_input")),+ }+ )++ messages: list[BaseMessage] = []+ if text or tool_calls or not tool_messages:+ messages.append(+ AIMessage(content=text, tool_calls=tool_calls or [])+ if tool_calls+ else AIMessage(content=text)+ )+ messages.extend(tool_messages)+ return messages+++def restore_openviking_messages(messages: Sequence[dict[str, Any]]) -> list[BaseMessage]:+ """Restore a valid LangChain message sequence from OpenViking session messages."""++ restored: list[BaseMessage] = []+ active_tool_call_ids: set[str] = set()+ for message in messages:+ for langchain_message in openviking_message_to_langchain(message):+ if isinstance(langchain_message, AIMessage):+ restored.append(langchain_message)+ for tool_call in langchain_message.tool_calls or []:+ tool_call_id = str(tool_call.get("id") or "")+ if tool_call_id:+ active_tool_call_ids.add(tool_call_id)+ elif isinstance(langchain_message, ToolMessage):+ tool_call_id = str(langchain_message.tool_call_id or "")+ if tool_call_id and tool_call_id in active_tool_call_ids:+ restored.append(langchain_message)+ active_tool_call_ids.discard(tool_call_id)+ else:+ restored.append(langchain_message)+ return restored+++def _text_parts(content: Any) -> list[dict[str, Any]]:+ text = extract_message_text(content)+ return [{"type": "text", "text": text}] if text else []+++def _parts_text(parts: Sequence[dict[str, Any]]) -> str:+ chunks: list[str] = []+ for part in parts:+ part_type = part.get("type")+ if part_type == "text" and part.get("text"):+ chunks.append(str(part["text"]))+ elif part_type == "context" and part.get("abstract"):+ uri = part.get("uri") or "context"+ chunks.append(f"[context:{uri}] {part['abstract']}")+ return "\n".join(chunks)+++def _tool_args(value: Any) -> dict[str, Any]:+ if value is None:+ return {}+ if isinstance(value, dict):+ return deepcopy(value)+ return {"value": deepcopy(value)}+++def _tool_status(message: ToolMessage) -> str:+ return "error" if getattr(message, "status", "") == "error" else "completed"diff --git a/openviking/integrations/langchain/middleware.py b/openviking/integrations/langchain/middleware.pyindex d73bd0255..101e8c698 100644--- a/openviking/integrations/langchain/middleware.py+++ b/openviking/integrations/langchain/middleware.py@@ -5,7 +5,6 @@from __future__ import annotationsimport json-import loggingfrom typing import Any, Callabletry:@@ -25,23 +24,16 @@ except ImportError as exc: # pragma: no cover - exercised by optional import pafrom openviking.integrations.langchain.client import (OpenVikingCommitPolicy,- OpenVikingConnection,- apply_commit_policy,- call_openviking,- ensure_client,extract_message_text,get_latest_user_text,)-from openviking.integrations.langchain.context import (- OPENVIKING_CONTEXT_MARKER,- OpenVikingSessionContextAssembler,+from openviking.integrations.langchain.context import OpenVikingSessionContextAssembler+from openviking.integrations.langchain.recording import (+ OpenVikingPartialWriteError,+ OpenVikingSessionRecorder,)-from openviking.integrations.langchain.history import langchain_message_to_openvikingfrom openviking.integrations.langchain.retrievers import OpenVikingRetriever-logger = logging.getLogger(__name__)--_BATCH_ADD_MESSAGES_LIMIT = 100_SESSION_ID_ERROR = ("OpenVikingContextMiddleware requires a LangGraph session id. Pass "'config={"configurable": {"thread_id": "..."}}, set state["session_id"], '@@ -83,8 +75,7 @@ class OpenVikingContextMiddleware(AgentMiddleware):include_active_messages: bool = False,):super().__init__()- self._client = client- self._connection = OpenVikingConnection(+ self.recorder = OpenVikingSessionRecorder(client=client,url=url,api_key=api_key,@@ -93,6 +84,7 @@ class OpenVikingContextMiddleware(AgentMiddleware):user_id=user_id,actor_peer_id=actor_peer_id,path=path,+ commit_policy=None,)self.retriever = retriever or OpenVikingRetriever(client=client,@@ -187,6 +179,8 @@ class OpenVikingContextMiddleware(AgentMiddleware):current_signatures = tuple(_message_signature(message) for message in messages)if current_signatures == previous_signatures:+ self.recorder.commit_policy = self.commit_policy+ self.recorder.record(session_id, ())self._pending_context_parts.pop(capture_key, None)return Nonestart = 0@@ -197,43 +191,26 @@ class OpenVikingContextMiddleware(AgentMiddleware):):start = len(previous_signatures)- client = ensure_client(self._connection)- batch: list[dict[str, Any]] = []- chunks: list[tuple[list[dict[str, Any]], int, bool]] = []- batch_has_context = Falsepending_context_parts = list(self._pending_context_parts.get(capture_key, []))- for message_index, message in enumerate(messages[start:], start=start):- if OPENVIKING_CONTEXT_MARKER in _message_content(message):- continue- payloads = langchain_message_to_openviking(message)- if batch and len(batch) + len(payloads) > _BATCH_ADD_MESSAGES_LIMIT:- chunks.append((batch, message_index, batch_has_context))- batch = []- batch_has_context = False- for payload in payloads:- if pending_context_parts and payload["role"] == "assistant":- payload["parts"].extend(pending_context_parts)- pending_context_parts = []- batch_has_context = True- if peer_id is not None:- payload["peer_id"] = peer_id- batch.append(payload)- if batch:- chunks.append((batch, len(messages), batch_has_context))- for chunk, signature_end, has_context in chunks:- call_openviking(- client,- "batch_add_messages",- session_id=session_id,- messages=chunk,+ self.recorder.commit_policy = self.commit_policy+ try:+ result = self.recorder.record(+ session_id,+ messages[start:],+ peer_id=peer_id,+ context_parts=pending_context_parts,)- self._captured_signatures[capture_key] = current_signatures[:signature_end]- if has_context:+ except OpenVikingPartialWriteError as exc:+ if exc.input_messages_consumed:+ consumed_end = start + exc.input_messages_consumed+ self._captured_signatures[capture_key] = current_signatures[:consumed_end]+ if exc.context_attached:self._pending_context_parts.pop(capture_key, None)- self._pending_context_parts.pop(capture_key, None)+ raise+self._captured_signatures[capture_key] = current_signatures- if batch:- apply_commit_policy(client, session_id, self.commit_policy)+ if result.context_attached:+ self._pending_context_parts.pop(capture_key, None)return Nonedef _resolve_session_id(self, state: dict[str, Any], runtime: Any) -> str:@@ -273,13 +250,6 @@ class OpenVikingContextMiddleware(AgentMiddleware):return resolvedreturn None- def _ensure_session(self, client: Any, session_id: str) -> None:- try:- call_openviking(client, "create_session", session_id=session_id)- except Exception:- logger.debug("OpenViking LangGraph middleware session ensure failed", exc_info=True)- pass-def _nested_get(value: Any, *keys: str) -> Any:current = valuediff --git a/openviking/integrations/langchain/recording.py b/openviking/integrations/langchain/recording.pynew file mode 100644index 000000000..bb98090d7--- /dev/null+++ b/openviking/integrations/langchain/recording.py@@ -0,0 +1,364 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Reusable OpenViking session recording for LangChain messages."""++from __future__ import annotations++from collections.abc import Iterable, Sequence+from copy import deepcopy+from dataclasses import dataclass+from typing import Any, Literal++try:+ from langchain_core.messages import BaseMessage+except ImportError as exc: # pragma: no cover - exercised by optional import path+ from openviking.integrations.langchain.client import missing_dependency++ raise missing_dependency("langchain", "langchain-core") from exc++from openviking.integrations.langchain.client import (+ OpenVikingCommitPolicy,+ OpenVikingConnection,+ apply_commit_policy,+ call_openviking,+ ensure_client,+ item_value,+)+from openviking.integrations.langchain.messages import (+ is_context_carrier_langchain_message,+ is_recordable_langchain_message,+ langchain_message_to_openviking,+)++MAX_RECORDING_BATCH_SIZE = 100+++@dataclass(frozen=True, slots=True)+class OpenVikingRecordResult:+ """Confirmed progress from a recorder call."""++ messages_written: int = 0+ input_messages_consumed: int = 0+ context_attached: bool = False+++class OpenVikingPartialWriteError(RuntimeError):+ """Report confirmed progress when recording cannot finish."""++ def __init__(+ self,+ *,+ session_id: str,+ result: OpenVikingRecordResult,+ cause: Exception,+ stage: Literal["batch", "commit"] = "batch",+ ):+ if stage == "batch":+ detail = "before a later batch failed"+ else:+ detail = "before the commit policy failed"+ super().__init__(+ f"OpenViking recorded {result.messages_written} messages for session "+ f"{session_id!r} {detail}: {cause}"+ )+ self.session_id = session_id+ self.result = result+ self.stage = stage++ @property+ def messages_written(self) -> int:+ """Return the number of payloads confirmed written before failure."""++ return self.result.messages_written++ @property+ def input_messages_consumed(self) -> int:+ """Return the caller-message prefix that is safe to skip on retry."""++ return self.result.input_messages_consumed++ @property+ def context_attached(self) -> bool:+ """Return whether recalled context was confirmed persisted."""++ return self.result.context_attached++ @property+ def commit_pending(self) -> bool:+ """Return whether only the post-write commit remains incomplete."""++ return self.stage == "commit"+++@dataclass(slots=True)+class _PreparedMessage:+ input_end: int+ payloads: list[dict[str, Any]]+ context_attached: bool = False+++@dataclass(slots=True)+class _PreparedBatch:+ input_end: int+ payloads: list[dict[str, Any]]+ context_attached: bool = False+++class OpenVikingSessionRecorder:+ """Persist caller-selected LangChain messages to OpenViking sessions.++ The recorder intentionally does not decide which messages form a turn or+ deduplicate transcript snapshots. Callers own that policy and pass only the+ messages they want persisted.+ """++ def __init__(+ self,+ *,+ client: Any = None,+ url: str | None = None,+ api_key: str | None = None,+ account: str | None = None,+ user: str | None = None,+ user_id: str | None = None,+ actor_peer_id: str | None = None,+ path: str | None = None,+ timeout: float = 60.0,+ extra_headers: dict[str, str] | None = None,+ auto_initialize: bool = True,+ commit_policy: OpenVikingCommitPolicy | None = None,+ batch_size: int = MAX_RECORDING_BATCH_SIZE,+ ):+ if batch_size <= 0 or batch_size > MAX_RECORDING_BATCH_SIZE:+ raise ValueError(f"batch_size must be between 1 and {MAX_RECORDING_BATCH_SIZE}")+ self._connection = OpenVikingConnection(+ client=client,+ url=url,+ api_key=api_key,+ account=account,+ user=user,+ user_id=user_id,+ actor_peer_id=actor_peer_id,+ path=path,+ timeout=timeout,+ extra_headers=extra_headers,+ auto_initialize=auto_initialize,+ )+ self._owns_client = client is None+ self._client_cache: Any = None+ self._pending_commit_sessions: set[str] = set()+ self._closed = False+ self.commit_policy = commit_policy+ self.batch_size = batch_size++ @property+ def client(self) -> Any:+ """Return the lazily initialized OpenViking client used by this recorder."""++ self._raise_if_closed()+ if self._client_cache is None:+ self._client_cache = ensure_client(self._connection)+ return self._client_cache++ def record(+ self,+ session_id: str,+ messages: Iterable[BaseMessage],+ peer_id: str | None = None,+ context_parts: Sequence[dict[str, Any]] = (),+ ) -> OpenVikingRecordResult:+ """Persist a caller-selected batch and apply the configured commit policy."""++ self._raise_if_closed()+ self._retry_pending_commit(session_id)+ input_messages = list(messages)+ prepared_messages = _prepare_messages(+ input_messages,+ peer_id=peer_id,+ context_parts=context_parts,+ )+ if not prepared_messages:+ return OpenVikingRecordResult(input_messages_consumed=len(input_messages))++ batches = _prepare_batches(prepared_messages, batch_size=self.batch_size)+ client = self.client+ messages_written = 0+ input_messages_consumed = 0+ context_attached = False+ for batch in batches:+ try:+ call_openviking(+ client,+ "batch_add_messages",+ session_id=session_id,+ messages=batch.payloads,+ )+ except Exception as exc:+ if messages_written == 0:+ raise+ result = OpenVikingRecordResult(+ messages_written=messages_written,+ input_messages_consumed=input_messages_consumed,+ context_attached=context_attached,+ )+ raise OpenVikingPartialWriteError(+ session_id=session_id,+ result=result,+ cause=exc,+ ) from exc+ messages_written += len(batch.payloads)+ input_messages_consumed = batch.input_end+ context_attached = context_attached or batch.context_attached+ result = OpenVikingRecordResult(+ messages_written=messages_written,+ input_messages_consumed=len(input_messages),+ context_attached=context_attached,+ )+ try:+ apply_commit_policy(client, session_id, self.commit_policy)+ except Exception as exc:+ self._pending_commit_sessions.add(session_id)+ raise OpenVikingPartialWriteError(+ session_id=session_id,+ result=result,+ cause=exc,+ stage="commit",+ ) from exc+ return result++ def flush(self, session_id: str) -> dict[str, Any] | None:+ """Commit a session only when it contains pending, uncommitted content."""++ result = self._flush_pending_content(session_id)+ self._pending_commit_sessions.discard(session_id)+ return result++ def _flush_pending_content(self, session_id: str) -> dict[str, Any] | None:+ client = self.client+ try:+ session = call_openviking(+ client,+ "get_session",+ session_id=session_id,+ auto_create=False,+ )+ except Exception as exc:+ error_code = str(getattr(exc, "code", "")).upper()+ if isinstance(exc, FileNotFoundError) or error_code == "NOT_FOUND":+ return None+ raise+ if int(item_value(session, "pending_tokens", 0) or 0) <= 0:+ return None+ return call_openviking(client, "commit_session", session_id=session_id)++ def _retry_pending_commit(self, session_id: str) -> None:+ if session_id not in self._pending_commit_sessions:+ return+ self._flush_pending_content(session_id)+ self._pending_commit_sessions.discard(session_id)++ def close(self) -> None:+ """Release an internally created client.++ Injected clients remain owned by their caller and are never closed here.+ """++ if self._closed:+ return+ self._closed = True+ self._pending_commit_sessions.clear()+ client = self._client_cache+ self._client_cache = None+ if client is None or not self._owns_client:+ return+ close = getattr(client, "close", None)+ if callable(close):+ close()++ def _raise_if_closed(self) -> None:+ if self._closed:+ raise RuntimeError("OpenVikingSessionRecorder is closed")+++def _prepare_messages(+ messages: Sequence[BaseMessage],+ *,+ peer_id: str | None,+ context_parts: Sequence[dict[str, Any]],+) -> list[_PreparedMessage]:+ normalized_peer_id = _normalize_peer_id(peer_id)+ pending_context = deepcopy(list(context_parts))+ prepared_messages: list[_PreparedMessage] = []++ for index, message in enumerate(messages):+ context_carrier = is_context_carrier_langchain_message(message)+ recordable = is_recordable_langchain_message(message)+ if not recordable and not (pending_context and context_carrier):+ continue+ payloads = langchain_message_to_openviking(message)+ message_context_attached = False+ for payload in payloads:+ if pending_context and context_carrier and payload["role"] == "assistant":+ payload["parts"].extend(pending_context)+ pending_context = []+ message_context_attached = True+ if normalized_peer_id is not None:+ payload["peer_id"] = normalized_peer_id+ if payloads:+ prepared_messages.append(+ _PreparedMessage(+ input_end=index + 1,+ payloads=payloads,+ context_attached=message_context_attached,+ )+ )+ return prepared_messages+++def _prepare_batches(+ messages: Sequence[_PreparedMessage],+ *,+ batch_size: int,+) -> list[_PreparedBatch]:+ batches: list[_PreparedBatch] = []+ payloads: list[dict[str, Any]] = []+ input_end = 0+ context_attached = False++ for message in messages:+ payload_count = len(message.payloads)+ if payload_count > batch_size:+ raise ValueError(+ "one LangChain message produced more OpenViking payloads "+ f"({payload_count}) than batch_size ({batch_size})"+ )+ if payloads and len(payloads) + payload_count > batch_size:+ batches.append(+ _PreparedBatch(+ input_end=input_end,+ payloads=payloads,+ context_attached=context_attached,+ )+ )+ payloads = []+ context_attached = False+ payloads.extend(message.payloads)+ input_end = message.input_end+ context_attached = context_attached or message.context_attached++ if payloads:+ batches.append(+ _PreparedBatch(+ input_end=input_end,+ payloads=payloads,+ context_attached=context_attached,+ )+ )+ return batches+++def _normalize_peer_id(peer_id: str | None) -> str | None:+ if peer_id is None:+ return None+ text = str(peer_id).strip()+ return text or Nonediff --git a/tests/integration/langchain_langgraph/test_recording.py b/tests/integration/langchain_langgraph/test_recording.pynew file mode 100644index 000000000..65f22a74a--- /dev/null+++ b/tests/integration/langchain_langgraph/test_recording.py@@ -0,0 +1,137 @@+from __future__ import annotations++from typing import Any++import pytest++pytest.importorskip("langchain_core")++from langchain.agents import create_agent+from langchain_core.language_models.fake_chat_models import FakeListChatModel+from langchain_core.messages import AIMessage, BaseMessage, HumanMessage+from langchain_core.runnables import RunnableLambda+from langchain_core.runnables.history import RunnableWithMessageHistory++from openviking.integrations.langchain import (+ InMemoryOpenVikingClient,+ OpenVikingChatMessageHistory,+ OpenVikingContextMiddleware,+ with_openviking_context,+)+++class BatchTrackingClient(InMemoryOpenVikingClient):+ def __init__(self):+ super().__init__()+ self.batch_sizes: list[int] = []++ def batch_add_messages(+ self,+ session_id: str,+ messages: list[dict[str, Any]],+ **kwargs: Any,+ ) -> dict[str, Any]:+ self.batch_sizes.append(len(messages))+ return super().batch_add_messages(session_id, messages, **kwargs)+++def test_real_runnable_with_message_history_records_each_turn_as_one_batch():+ client = BatchTrackingClient()++ def answer(messages: list[BaseMessage]) -> AIMessage:+ remembered_azure = any(+ "azure" in str(message.content).lower()+ for message in messages+ if isinstance(message, HumanMessage)+ )+ return AIMessage(content="I remember azure." if remembered_azure else "No preference yet.")++ app = RunnableWithMessageHistory(+ RunnableLambda(answer),+ lambda session_id: OpenVikingChatMessageHistory(+ session_id=session_id,+ client=client,+ ),+ )+ config = {"configurable": {"session_id": "real-history-recorder"}}++ app.invoke(+ [HumanMessage(content="Remember that the deployment color is azure.")],+ config=config,+ )+ response = app.invoke(+ [HumanMessage(content="Which deployment color do you remember?")],+ config=config,+ )++ assert response.content == "I remember azure."+ assert client.batch_sizes == [2, 2]+ assert len(client.sessions["real-history-recorder"]) == 4+++def test_real_runnable_with_message_history_preserves_context_marker_text():+ client = BatchTrackingClient()+ app = RunnableWithMessageHistory(+ RunnableLambda(lambda _messages: AIMessage(content="Literal marker preserved.")),+ lambda session_id: OpenVikingChatMessageHistory(+ session_id=session_id,+ client=client,+ ),+ )++ app.invoke(+ [HumanMessage(content="How do I write <openviking_context> literally?")],+ config={"configurable": {"session_id": "real-history-marker"}},+ )++ stored = client.sessions["real-history-marker"]+ assert [message["role"] for message in stored] == ["user", "assistant"]+ assert stored[0]["parts"][0]["text"] == ("How do I write <openviking_context> literally?")+++def test_real_openviking_context_wrapper_attributes_context_to_empty_assistant():+ client = BatchTrackingClient()+ client.records["viking://resources/runbooks/empty.md"] = "The deployment color is azure."++ def answer(messages: list[BaseMessage]) -> AIMessage:+ assert "The deployment color is azure." in str(messages[0].content)+ return AIMessage(content="")++ app = with_openviking_context(+ RunnableLambda(answer),+ client=client,+ session_id="real-empty-assistant",+ target_uri="viking://resources",+ )++ app.invoke([HumanMessage(content="What is the deployment color?")])++ stored = client.sessions["real-empty-assistant"]+ assert [message["role"] for message in stored] == ["user", "assistant"]+ assert not any(part["type"] == "context" for part in stored[0]["parts"])+ assert any(part["type"] == "context" for part in stored[1]["parts"])+++def test_real_create_agent_records_through_middleware_recorder():+ client = BatchTrackingClient()+ middleware = OpenVikingContextMiddleware(+ client=client,+ session_id_resolver=lambda _state, _runtime: "real-agent-recorder",+ )+ agent = create_agent(+ model=FakeListChatModel(responses=["Stored by a real LangChain agent."]),+ tools=[],+ middleware=[middleware],+ )++ result = agent.invoke(+ {"messages": [HumanMessage(content="Remember this agent turn.")]},+ config={"configurable": {"thread_id": "real-agent-recorder"}},+ )++ assert result["messages"][-1].content == "Stored by a real LangChain agent."+ assert client.batch_sizes == [2]+ assert [message["parts"][0]["text"] for message in client.sessions["real-agent-recorder"]] == [+ "Remember this agent turn.",+ "Stored by a real LangChain agent.",+ ]diff --git a/tests/unit/test_langchain_recording.py b/tests/unit/test_langchain_recording.pynew file mode 100644index 000000000..9d66aa1a8--- /dev/null+++ b/tests/unit/test_langchain_recording.py@@ -0,0 +1,805 @@+from __future__ import annotations++from typing import Any++import pytest++pytest.importorskip("langchain_core")++from langchain_core.messages import (+ AIMessage,+ BaseMessage,+ HumanMessage,+ SystemMessage,+ ToolMessage,+)++import openviking.integrations.langchain.recording as recording_module+from openviking.integrations.langchain import (+ InMemoryOpenVikingClient,+ OpenVikingChatMessageHistory,+ OpenVikingCommitPolicy,+ OpenVikingContextMiddleware,+ OpenVikingPartialWriteError,+ OpenVikingRecordResult,+ OpenVikingSessionRecorder,+)+from openviking.integrations.langchain.messages import OPENVIKING_CONTEXT_MARKER+++class TrackingOpenVikingClient(InMemoryOpenVikingClient):+ def __init__(self):+ super().__init__()+ self.batch_sizes: list[int] = []+ self.commit_calls: list[str] = []+ self.closed = False++ def batch_add_messages(+ self,+ session_id: str,+ messages: list[dict[str, Any]],+ **kwargs: Any,+ ) -> dict[str, Any]:+ self.batch_sizes.append(len(messages))+ return super().batch_add_messages(session_id, messages, **kwargs)++ def commit_session(self, session_id: str, **kwargs: Any) -> dict[str, Any]:+ self.commit_calls.append(session_id)+ return super().commit_session(session_id, **kwargs)++ def close(self) -> None:+ self.closed = True+ super().close()+++def test_recorder_filters_framework_control_messages_and_preserves_tool_parts():+ client = TrackingOpenVikingClient()+ recorder = OpenVikingSessionRecorder(client=client)+ context_parts = [+ {+ "type": "context",+ "uri": "viking://user/memories/preference.md",+ "context_type": "memory",+ "abstract": "The user prefers azure.",+ }+ ]++ result = recorder.record(+ "recorder-filtering",+ [+ SystemMessage(content="Runtime policy must not be persisted."),+ HumanMessage(+ content="Here is a summary of the conversation to date.",+ additional_kwargs={"lc_source": "summarization"},+ ),+ HumanMessage(content="Find the deployment notes."),+ AIMessage(+ content="Searching.",+ tool_calls=[+ {+ "id": "call-1",+ "name": "viking_find",+ "args": {"query": "deployment"},+ }+ ],+ ),+ ToolMessage(+ content="Azure deployment notes found.",+ tool_call_id="call-1",+ name="viking_find",+ ),+ ],+ peer_id=" peer-recorder ",+ context_parts=context_parts,+ )++ assert result.messages_written == 3+ assert result.context_attached is True+ assert isinstance(result, OpenVikingRecordResult)+ assert client.batch_sizes == [3]+ stored = client.sessions["recorder-filtering"]+ assert [message["role"] for message in stored] == ["user", "assistant", "assistant"]+ assert [message.get("peer_id") for message in stored] == ["peer-recorder"] * 3+ assert [part["type"] for part in stored[1]["parts"]] == ["text", "tool", "context"]+ assert stored[2]["parts"][0]["tool_output"] == "Azure deployment notes found."+ assert context_parts == [+ {+ "type": "context",+ "uri": "viking://user/memories/preference.md",+ "context_type": "memory",+ "abstract": "The user prefers azure.",+ }+ ]+++def test_recorder_preserves_user_text_containing_context_marker():+ client = TrackingOpenVikingClient()+ recorder = OpenVikingSessionRecorder(client=client)++ result = recorder.record(+ "recorder-user-marker",+ [+ HumanMessage(content=f"How do I escape {OPENVIKING_CONTEXT_MARKER} in my prompt?"),+ AIMessage(content="Use it as literal text."),+ ],+ )++ assert result.messages_written == 2+ assert [message["parts"][0]["text"] for message in client.sessions["recorder-user-marker"]] == [+ "How do I escape <openviking_context> in my prompt?",+ "Use it as literal text.",+ ]+++def test_recorder_uses_empty_assistant_as_context_carrier():+ client = TrackingOpenVikingClient()+ recorder = OpenVikingSessionRecorder(client=client)+ context_parts = [+ {+ "type": "context",+ "uri": "viking://user/memories/context-carrier.md",+ "context_type": "memory",+ }+ ]++ result = recorder.record(+ "recorder-empty-assistant",+ [+ HumanMessage(content="Use recalled context."),+ AIMessage(content=""),+ ],+ context_parts=context_parts,+ )++ assert result.messages_written == 2+ assert result.input_messages_consumed == 2+ assert result.context_attached is True+ stored = client.sessions["recorder-empty-assistant"]+ assert [message["role"] for message in stored] == ["user", "assistant"]+ assert [part["type"] for part in stored[1]["parts"]] == ["text", "context"]+ assert not any(part["type"] == "context" for part in stored[0]["parts"])+++def test_recorder_leaves_context_unattached_without_assistant_payload():+ client = TrackingOpenVikingClient()+ recorder = OpenVikingSessionRecorder(client=client)++ result = recorder.record(+ "recorder-user-only-context",+ [HumanMessage(content="No assistant response yet.")],+ context_parts=[+ {+ "type": "context",+ "uri": "viking://user/memories/pending.md",+ "context_type": "memory",+ }+ ],+ )++ assert result.messages_written == 1+ assert result.context_attached is False+ assert client.sessions["recorder-user-only-context"][0]["role"] == "user"+ assert not any(+ part["type"] == "context"+ for part in client.sessions["recorder-user-only-context"][0]["parts"]+ )+++def test_recorder_does_not_attribute_context_to_tool_result_payload():+ client = TrackingOpenVikingClient()+ recorder = OpenVikingSessionRecorder(client=client)+ context_parts = [+ {+ "type": "context",+ "uri": "viking://user/memories/assistant-only.md",+ "context_type": "memory",+ }+ ]++ result = recorder.record(+ "recorder-tool-result-context",+ [+ ToolMessage(+ content="Tool output.",+ tool_call_id="call-1",+ name="lookup",+ ),+ AIMessage(content="Used the tool output."),+ ],+ context_parts=context_parts,+ )++ assert result.context_attached is True+ stored = client.sessions["recorder-tool-result-context"]+ assert not any(part["type"] == "context" for part in stored[0]["parts"])+ assert any(part["type"] == "context" for part in stored[1]["parts"])+++def test_recorder_chunks_writes_at_server_batch_limit():+ client = TrackingOpenVikingClient()+ recorder = OpenVikingSessionRecorder(client=client)++ result = recorder.record(+ "recorder-batches",+ [HumanMessage(content=f"Message {index}") for index in range(101)],+ )++ assert result.messages_written == 101+ assert result.input_messages_consumed == 101+ assert client.batch_sizes == [100, 1]+ assert len(client.sessions["recorder-batches"]) == 101+++def test_recorder_batches_by_payload_count_without_splitting_source_messages(+ monkeypatch: pytest.MonkeyPatch,+):+ class FailSecondBatchClient(TrackingOpenVikingClient):+ def batch_add_messages(+ self,+ session_id: str,+ messages: list[dict[str, Any]],+ **kwargs: Any,+ ) -> dict[str, Any]:+ if len(self.batch_sizes) == 1:+ self.batch_sizes.append(len(messages))+ raise RuntimeError("second payload batch failed")+ return super().batch_add_messages(session_id, messages, **kwargs)++ def split_message(message: BaseMessage) -> list[dict[str, Any]]:+ text = str(message.content)+ return [+ {"role": "user", "parts": [{"type": "text", "text": f"{text}:1"}]},+ {"role": "user", "parts": [{"type": "text", "text": f"{text}:2"}]},+ ]++ monkeypatch.setattr(recording_module, "langchain_message_to_openviking", split_message)+ client = FailSecondBatchClient()+ recorder = OpenVikingSessionRecorder(client=client, batch_size=3)+ messages = [HumanMessage(content="first"), HumanMessage(content="second")]++ with pytest.raises(+ OpenVikingPartialWriteError,+ match="second payload batch failed",+ ) as exc_info:+ recorder.record("recorder-payload-batches", messages)++ assert client.batch_sizes == [2, 2]+ assert exc_info.value.messages_written == 2+ assert exc_info.value.input_messages_consumed == 1++ recorder.record(+ "recorder-payload-batches",+ messages[exc_info.value.input_messages_consumed :],+ )++ assert client.batch_sizes == [2, 2, 2]+ assert [+ message["parts"][0]["text"] for message in client.sessions["recorder-payload-batches"]+ ] == ["first:1", "first:2", "second:1", "second:2"]+++def test_recorder_rejects_source_message_larger_than_configured_batch(+ monkeypatch: pytest.MonkeyPatch,+):+ monkeypatch.setattr(+ recording_module,+ "langchain_message_to_openviking",+ lambda _message: [+ {"role": "user", "parts": [{"type": "text", "text": str(index)}]} for index in range(3)+ ],+ )+ client = TrackingOpenVikingClient()+ recorder = OpenVikingSessionRecorder(client=client, batch_size=2)++ with pytest.raises(ValueError, match="one LangChain message produced"):+ recorder.record(+ "recorder-oversized-source-message",+ [HumanMessage(content="Expands to three payloads.")],+ )++ assert client.batch_sizes == []+++def test_recorder_ignores_filtered_only_batch_without_initializing_client():+ client = TrackingOpenVikingClient()+ recorder = OpenVikingSessionRecorder(client=client)++ result = recorder.record(+ "recorder-filtered-only",+ [+ SystemMessage(content="Runtime policy."),+ AIMessage(content=""),+ ],+ )++ assert result.messages_written == 0+ assert result.context_attached is False+ assert client.batch_sizes == []+ assert client._initialized is False+++def test_recorder_applies_commit_policy_once_after_all_batches():+ client = TrackingOpenVikingClient()+ recorder = OpenVikingSessionRecorder(+ client=client,+ commit_policy=OpenVikingCommitPolicy(mode="always"),+ )++ recorder.record(+ "recorder-commit",+ [HumanMessage(content=f"Message {index}") for index in range(101)],+ )++ 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+++def test_recorder_reports_partial_progress_and_retries_only_unwritten_suffix():+ class FailSecondBatchClient(TrackingOpenVikingClient):+ def batch_add_messages(+ self,+ session_id: str,+ messages: list[dict[str, Any]],+ **kwargs: Any,+ ) -> dict[str, Any]:+ if len(self.batch_sizes) == 1:+ self.batch_sizes.append(len(messages))+ raise RuntimeError("second batch failed")+ return super().batch_add_messages(session_id, messages, **kwargs)++ client = FailSecondBatchClient()+ recorder = OpenVikingSessionRecorder(+ client=client,+ commit_policy=OpenVikingCommitPolicy(mode="always"),+ )++ messages = [HumanMessage(content=f"Message {index}") for index in range(101)]+ with pytest.raises(OpenVikingPartialWriteError, match="second batch failed") as exc_info:+ recorder.record(+ "recorder-failed-batch",+ messages,+ )++ assert client.batch_sizes == [100, 1]+ assert client.commit_calls == []+ assert len(client.sessions["recorder-failed-batch"]) == 100+ assert exc_info.value.messages_written == 100+ assert exc_info.value.input_messages_consumed == 100+ assert exc_info.value.context_attached is False++ recorder.record(+ "recorder-failed-batch",+ messages[exc_info.value.input_messages_consumed :],+ )++ assert client.batch_sizes == [100, 1, 1]+ assert client.commit_calls == ["recorder-failed-batch"]+ assert client.sessions["recorder-failed-batch"] == []+ archived = client.archives["recorder-failed-batch"][0]["messages"]+ assert len(archived) == 101+ assert [message["parts"][0]["text"] for message in archived] == [+ f"Message {index}" for index in range(101)+ ]+++def test_recorder_reports_commit_failure_and_retries_without_duplicate_writes():+ class FailFirstCommitClient(TrackingOpenVikingClient):+ def commit_session(self, session_id: str, **kwargs: Any) -> dict[str, Any]:+ self.commit_calls.append(session_id)+ if len(self.commit_calls) == 1:+ raise RuntimeError("commit failed")+ return InMemoryOpenVikingClient.commit_session(self, session_id, **kwargs)++ client = FailFirstCommitClient()+ recorder = OpenVikingSessionRecorder(+ client=client,+ commit_policy=OpenVikingCommitPolicy(mode="always"),+ )+ 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)++ assert exc_info.value.stage == "commit"+ assert exc_info.value.commit_pending is True+ assert exc_info.value.messages_written == 2+ assert exc_info.value.input_messages_consumed == 2+ 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 :],+ )++ 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+++def test_recorder_preserves_first_batch_exception_type():+ class FailFirstBatchClient(TrackingOpenVikingClient):+ def batch_add_messages(+ self,+ session_id: str,+ messages: list[dict[str, Any]],+ **kwargs: Any,+ ) -> dict[str, Any]:+ raise FileNotFoundError("first batch failed")++ recorder = OpenVikingSessionRecorder(client=FailFirstBatchClient())++ with pytest.raises(FileNotFoundError, match="first batch failed"):+ recorder.record(+ "recorder-first-batch-failure",+ [HumanMessage(content="Not written.")],+ )+++def test_recorder_flush_commits_only_pending_content():+ client = TrackingOpenVikingClient()+ recorder = OpenVikingSessionRecorder(client=client)++ assert recorder.flush("missing-session") is None+ recorder.record("recorder-flush", [HumanMessage(content="Pending content.")])++ result = recorder.flush("recorder-flush")++ assert result is not None+ assert result["archived"] is True+ assert recorder.flush("recorder-flush") is None+ assert client.commit_calls == ["recorder-flush"]+++def test_recorder_flush_treats_missing_session_as_no_pending_content():+ class MissingSessionClient(TrackingOpenVikingClient):+ def get_session(self, session_id: str, auto_create: bool = False) -> dict[str, Any]:+ raise FileNotFoundError(session_id)++ recorder = OpenVikingSessionRecorder(client=MissingSessionClient())++ assert recorder.flush("missing-session") is None+++def test_recorder_flush_accepts_openviking_not_found_code():+ class NotFoundError(RuntimeError):+ code = "NOT_FOUND"++ class MissingSessionClient(TrackingOpenVikingClient):+ def get_session(self, session_id: str, auto_create: bool = False) -> dict[str, Any]:+ raise NotFoundError(session_id)++ recorder = OpenVikingSessionRecorder(client=MissingSessionClient())++ assert recorder.flush("missing-session") is None+++def test_recorder_flush_propagates_unexpected_lookup_failure():+ class FailingLookupClient(TrackingOpenVikingClient):+ def get_session(self, session_id: str, auto_create: bool = False) -> dict[str, Any]:+ raise RuntimeError(f"lookup failed for {session_id}")++ recorder = OpenVikingSessionRecorder(client=FailingLookupClient())++ with pytest.raises(RuntimeError, match="lookup failed"):+ recorder.flush("broken-session")+++def test_recorder_close_does_not_close_injected_client():+ client = TrackingOpenVikingClient()+ recorder = OpenVikingSessionRecorder(client=client)+ assert recorder.client is client++ recorder.close()+ recorder.close()++ assert client.closed is False+ with pytest.raises(RuntimeError, match="closed"):+ recorder.record("closed-injected-recorder", [HumanMessage(content="Rejected.")])+ with pytest.raises(RuntimeError, match="closed"):+ recorder.flush("closed-injected-recorder")+ with pytest.raises(RuntimeError, match="closed"):+ _ = recorder.client+++def test_recorder_close_closes_owned_client(monkeypatch: pytest.MonkeyPatch):+ client = TrackingOpenVikingClient()+ monkeypatch.setattr(recording_module, "ensure_client", lambda _connection: client)+ recorder = OpenVikingSessionRecorder(url="http://openviking.test")+ assert recorder.client is client++ recorder.close()+ recorder.close()++ assert client.closed is True+ with pytest.raises(RuntimeError, match="closed"):+ recorder.record("closed-owned-recorder", [HumanMessage(content="Rejected.")])++[email protected]("batch_size", [0, 101])+def test_recorder_rejects_unsupported_batch_sizes(batch_size: int):+ with pytest.raises(ValueError, match="batch_size"):+ OpenVikingSessionRecorder(+ client=TrackingOpenVikingClient(),+ batch_size=batch_size,+ )+++def test_chat_message_history_delegates_writes_to_recorder_batching():+ client = TrackingOpenVikingClient()+ history = OpenVikingChatMessageHistory(+ session_id="history-recorder",+ client=client,+ )++ history.add_messages(+ [+ HumanMessage(content="Remember azure."),+ AIMessage(content="Stored."),+ HumanMessage(content="What did I ask you to remember?"),+ ]+ )++ assert client.batch_sizes == [3]+ assert [message["role"] for message in client.sessions["history-recorder"]] == [+ "user",+ "assistant",+ "user",+ ]+++def test_chat_message_history_keeps_context_pending_until_assistant_message():+ client = TrackingOpenVikingClient()+ acknowledged_sessions: list[str] = []+ history = OpenVikingChatMessageHistory(+ session_id="history-pending-context",+ client=client,+ context_parts_provider=lambda _session_id: [+ {+ "type": "context",+ "uri": "viking://user/memories/history-pending.md",+ "context_type": "memory",+ }+ ],+ context_parts_acknowledger=acknowledged_sessions.append,+ )++ history.add_messages([HumanMessage(content="Wait for the assistant.")])++ assert acknowledged_sessions == []+ assert not any(+ part["type"] == "context" for part in client.sessions["history-pending-context"][0]["parts"]+ )++ history.add_messages([AIMessage(content="")])++ assert acknowledged_sessions == ["history-pending-context"]+ stored = client.sessions["history-pending-context"]+ assert [message["role"] for message in stored] == ["user", "assistant"]+ assert any(part["type"] == "context" for part in stored[1]["parts"])+++def test_chat_message_history_close_is_terminal():+ client = TrackingOpenVikingClient()+ history = OpenVikingChatMessageHistory(+ session_id="history-close",+ client=client,+ )++ history.close()++ assert client.closed is False+ with pytest.raises(RuntimeError, match="closed"):+ history.add_messages([HumanMessage(content="Rejected.")])+ with pytest.raises(RuntimeError, match="closed"):+ _ = history.messages++[email protected]("lifecycle_method", ["clear", "close"])+def test_chat_message_history_lifecycle_discards_pending_context(+ lifecycle_method: str,+):+ client = TrackingOpenVikingClient()+ acknowledged_sessions: list[str] = []+ history = OpenVikingChatMessageHistory(+ session_id=f"history-{lifecycle_method}-pending-context",+ client=client,+ context_parts_provider=lambda _session_id: [+ {+ "type": "context",+ "uri": "viking://user/memories/discarded.md",+ "context_type": "memory",+ }+ ],+ context_parts_acknowledger=acknowledged_sessions.append,+ )+ history.add_messages([HumanMessage(content="No assistant response yet.")])++ getattr(history, lifecycle_method)()++ assert acknowledged_sessions == [history.session_id]+++def test_chat_message_history_uses_updated_commit_policy():+ client = TrackingOpenVikingClient()+ history = OpenVikingChatMessageHistory(+ session_id="history-dynamic-policy",+ client=client,+ )+ history.add_messages([HumanMessage(content="Pending before policy update.")])+ history.commit_policy = OpenVikingCommitPolicy(mode="always")++ history.add_messages([AIMessage(content="Commit after policy update.")])++ assert history.commit_policy == OpenVikingCommitPolicy(mode="always")+ assert client.sessions["history-dynamic-policy"] == []+ assert len(client.archives["history-dynamic-policy"][0]["messages"]) == 2+++def test_middleware_resumes_after_last_successful_recorder_batch():+ class FailSecondBatchClient(TrackingOpenVikingClient):+ def batch_add_messages(+ self,+ session_id: str,+ messages: list[dict[str, Any]],+ **kwargs: Any,+ ) -> dict[str, Any]:+ if len(self.batch_sizes) == 1:+ self.batch_sizes.append(len(messages))+ raise RuntimeError("second batch failed")+ return super().batch_add_messages(session_id, messages, **kwargs)++ client = FailSecondBatchClient()+ middleware = OpenVikingContextMiddleware(+ client=client,+ session_id_resolver=lambda _state, _runtime: "middleware-recorder-retry",+ )+ capture_key = ("middleware-recorder-retry", "")+ middleware._pending_context_parts[capture_key] = [+ {+ "type": "context",+ "uri": "viking://user/memories/retry.md",+ "context_type": "memory",+ "abstract": "Retry context.",+ }+ ]+ messages = [+ HumanMessage(content="First message."),+ AIMessage(content="Context holder."),+ *[HumanMessage(content=f"Message {index}") for index in range(98)],+ AIMessage(content="Retry only this message."),+ ]+ state = {"messages": messages}++ with pytest.raises(RuntimeError, match="second batch failed"):+ middleware.after_agent(state, runtime=None)+ middleware.after_agent(state, runtime=None)+ middleware.after_agent(state, runtime=None)++ assert client.batch_sizes == [100, 1, 1]+ stored = client.sessions["middleware-recorder-retry"]+ assert len(stored) == 101+ assert sum(part["type"] == "context" for message in stored for part in message["parts"]) == 1+++def test_middleware_retains_pending_context_when_first_recorder_batch_fails():+ class FailFirstBatchClient(TrackingOpenVikingClient):+ def __init__(self):+ super().__init__()+ self.attempts = 0++ def batch_add_messages(+ self,+ session_id: str,+ messages: list[dict[str, Any]],+ **kwargs: Any,+ ) -> dict[str, Any]:+ self.attempts += 1+ if self.attempts == 1:+ raise RuntimeError("first batch failed")+ return super().batch_add_messages(session_id, messages, **kwargs)++ client = FailFirstBatchClient()+ middleware = OpenVikingContextMiddleware(+ client=client,+ session_id_resolver=lambda _state, _runtime: "middleware-first-batch-retry",+ )+ capture_key = ("middleware-first-batch-retry", "")+ middleware._pending_context_parts[capture_key] = [+ {+ "type": "context",+ "uri": "viking://user/memories/retry.md",+ "context_type": "memory",+ "abstract": "Retained retry context.",+ }+ ]+ state = {+ "messages": [+ HumanMessage(content="Remember the retained context."),+ AIMessage(content="Context holder."),+ ]+ }++ with pytest.raises(RuntimeError, match="first batch failed"):+ middleware.after_agent(state, runtime=None)+ middleware.after_agent(state, runtime=None)++ assert client.attempts == 2+ stored = client.sessions["middleware-first-batch-retry"]+ assert len(stored) == 2+ assert sum(part["type"] == "context" for message in stored for part in message["parts"]) == 1+++def test_middleware_keeps_context_pending_until_empty_assistant_arrives():+ client = TrackingOpenVikingClient()+ middleware = OpenVikingContextMiddleware(+ client=client,+ session_id_resolver=lambda _state, _runtime: "middleware-pending-assistant",+ )+ capture_key = ("middleware-pending-assistant", "")+ middleware._pending_context_parts[capture_key] = [+ {+ "type": "context",+ "uri": "viking://user/memories/pending-assistant.md",+ "context_type": "memory",+ }+ ]+ user_message = HumanMessage(content="The assistant has not responded yet.")++ middleware.after_agent({"messages": [user_message]}, runtime=None)++ assert capture_key in middleware._pending_context_parts+ assert not any(+ part["type"] == "context"+ for part in client.sessions["middleware-pending-assistant"][0]["parts"]+ )++ middleware.after_agent(+ {"messages": [user_message, AIMessage(content="")]},+ runtime=None,+ )++ assert capture_key not in middleware._pending_context_parts+ stored = client.sessions["middleware-pending-assistant"]+ assert [message["role"] for message in stored] == ["user", "assistant"]+ assert any(part["type"] == "context" for part in stored[1]["parts"])+++def test_middleware_retries_failed_commit_without_duplicate_writes():+ class FailFirstCommitClient(TrackingOpenVikingClient):+ def commit_session(self, session_id: str, **kwargs: Any) -> dict[str, Any]:+ self.commit_calls.append(session_id)+ if len(self.commit_calls) == 1:+ raise RuntimeError("commit failed")+ return InMemoryOpenVikingClient.commit_session(self, session_id, **kwargs)++ client = FailFirstCommitClient()+ middleware = OpenVikingContextMiddleware(+ client=client,+ session_id_resolver=lambda _state, _runtime: "middleware-commit-retry",+ commit_on_after_agent=True,+ )+ state = {+ "messages": [+ HumanMessage(content="Remember this middleware turn."),+ AIMessage(content="Remembered."),+ ]+ }++ with pytest.raises(OpenVikingPartialWriteError, match="commit failed"):+ middleware.after_agent(state, runtime=None)+ middleware.after_agent(state, runtime=None)++ assert client.batch_sizes == [2]+ assert client.commit_calls == [+ "middleware-commit-retry",+ "middleware-commit-retry",+ ]+ assert client.sessions["middleware-commit-retry"] == []+ assert len(client.archives["middleware-commit-retry"][0]["messages"]) == 2