Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(langchain): preserve injected clients during deepcopy (#3603)
Hao Zhee9701baa659a
diff --git a/openviking/integrations/langchain/client.py b/openviking/integrations/langchain/client.pyindex ddc3a673f..167c741d6 100644--- a/openviking/integrations/langchain/client.py+++ b/openviking/integrations/langchain/client.py@@ -75,6 +75,26 @@ class OpenVikingConnection:auto_initialize: bool = Trueasync_client: Any = None+ def __deepcopy__(self, memo: dict[int, Any]) -> OpenVikingConnection:+ """Copy configuration while preserving caller-owned client identities."""++ copied = type(self)(+ client=self.client,+ async_client=self.async_client,+ url=self.url,+ api_key=self.api_key,+ account=self.account,+ user=self.user,+ user_id=self.user_id,+ actor_peer_id=self.actor_peer_id,+ path=self.path,+ timeout=self.timeout,+ extra_headers=copy.deepcopy(self.extra_headers, memo),+ auto_initialize=self.auto_initialize,+ )+ memo[id(self)] = copied+ return copied+@dataclass(slots=True)class OpenVikingCommitPolicy:diff --git a/openviking/integrations/langchain/retrievers.py b/openviking/integrations/langchain/retrievers.pyindex 0615c0f0a..8e53ae2d7 100644--- a/openviking/integrations/langchain/retrievers.py+++ b/openviking/integrations/langchain/retrievers.py@@ -68,6 +68,29 @@ class OpenVikingRetriever(BaseRetriever):_owns_client_cache: bool = PrivateAttr(default=False)_closed: bool = PrivateAttr(default=False)+ def __deepcopy__(+ self,+ memo: dict[int, Any] | None = None,+ ) -> OpenVikingRetriever:+ """Copy configuration without cloning clients or cached runtime state."""++ memo = {} if memo is None else memo+ for client in (self.client, self.async_client):+ if client is not None:+ memo[id(client)] = client++ sync_client_cache = getattr(self, "_client_cache", None)+ if getattr(self, "_owns_client_cache", False) and sync_client_cache is not None:+ memo[id(sync_client_cache)] = None++ copied = super().__deepcopy__(memo)+ private_attributes = getattr(type(copied), "__private_attributes__", {})+ private_state = copied.__pydantic_private__+ if private_state is not None and "_client_cache" in private_attributes:+ private_state["_client_cache"] = None+ private_state["_owns_client_cache"] = False+ return copied+def _get_client(self) -> Any:self._raise_if_closed()if self._client_cache is None:diff --git a/tests/unit/test_langchain_async_integration.py b/tests/unit/test_langchain_async_integration.pyindex 2ae49d7a4..7a79faac7 100644--- a/tests/unit/test_langchain_async_integration.py+++ b/tests/unit/test_langchain_async_integration.py@@ -63,6 +63,94 @@ class AsyncInMemoryOpenVikingClient:return call+def test_connection_handle_and_retriever_deepcopy_preserve_injected_clients():+ class NonCopyableClient:+ def __deepcopy__(self, _memo: dict[int, Any]) -> None:+ raise AssertionError("live clients must not be deep-copied")++ client = NonCopyableClient()+ async_client = NonCopyableClient()+ connection = OpenVikingConnection(+ client=client,+ async_client=async_client,+ url="http://localhost:1933",+ extra_headers={"X-Tenant": "tenant-a"},+ )++ copied_connection = copy.deepcopy(connection)++ assert copied_connection is not connection+ assert copied_connection.client is client+ assert copied_connection.async_client is async_client+ assert copied_connection.extra_headers == connection.extra_headers+ assert copied_connection.extra_headers is not connection.extra_headers++ async_handle = OpenVikingAsyncClientHandle(connection)+ async_handle._client = async_client+ copied_async_handle = copy.deepcopy(async_handle)++ assert copied_async_handle is not async_handle+ assert copied_async_handle._connection.async_client is async_client+ assert copied_async_handle._client is None++ retriever = OpenVikingRetriever(+ client=client,+ async_client=async_client,+ extra_headers={"X-Tenant": "tenant-a"},+ target_uri=["viking://resources"],+ filter={"category": ["guide"]},+ tags=["stable"],+ )+ copied_retriever = copy.deepcopy(retriever)++ assert copied_retriever is not retriever+ assert copied_retriever.client is client+ assert copied_retriever.async_client is async_client+ assert copied_retriever.extra_headers == retriever.extra_headers+ assert copied_retriever.extra_headers is not retriever.extra_headers+ assert copied_retriever.target_uri == retriever.target_uri+ assert copied_retriever.target_uri is not retriever.target_uri+ assert copied_retriever.filter == retriever.filter+ assert copied_retriever.filter is not retriever.filter+ assert copied_retriever.tags == retriever.tags+ assert copied_retriever.tags is not retriever.tags+++def test_retriever_deepcopy_discards_owned_sync_client(monkeypatch):+ instances: list[Any] = []++ class NonCopyableSyncHTTPClient:+ def __init__(self, **_kwargs: Any):+ self.closed = False+ instances.append(self)++ def __deepcopy__(self, _memo: dict[int, Any]) -> None:+ raise AssertionError("owned live clients must not be deep-copied")++ def initialize(self) -> None:+ return None++ def close(self) -> None:+ self.closed = True++ def find(self, **_kwargs: Any) -> dict[str, Any]:+ return {"memories": [], "resources": [], "skills": []}++ import openviking.client as client_module++ monkeypatch.setattr(client_module, "SyncHTTPClient", NonCopyableSyncHTTPClient)+ retriever = OpenVikingRetriever(url="http://localhost:1933")++ assert retriever.invoke("original") == []+ copied = copy.deepcopy(retriever)+ assert copied.invoke("copied") == []++ assert len(instances) == 2+ asyncio.run(copied.aclose())+ asyncio.run(retriever.aclose())+ assert all(client.closed for client in instances)++@pytest.mark.asyncioasync def test_ensure_async_client_defaults_to_native_http_client(monkeypatch):created: dict[str, Any] = {}