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
perf(vectordb): reuse pooled HTTP session per client (#4696)
dingbenfbeb1345e682
diff --git a/openviking/storage/vectordb/collection/vikingdb_clients.py b/openviking/storage/vectordb/collection/vikingdb_clients.pyindex 1c4b75f18..5cfcd4dff 100644--- a/openviking/storage/vectordb/collection/vikingdb_clients.py+++ b/openviking/storage/vectordb/collection/vikingdb_clients.py@@ -4,6 +4,7 @@ import jsonfrom typing import Any, Dict, Optionalimport requests+from requests.adapters import HTTPAdapterimport openvikingfrom openviking.storage.errors import ConnectionError@@ -15,6 +16,10 @@ DEFAULT_TIMEOUT = 30# VikingDB API VersionVIKING_DB_VERSION = "2025-06-09"+# Connection pool sizing for the per-client keep-alive session.+_POOL_CONNECTIONS = 16+_POOL_MAXSIZE = 32+# SDK Action to VikingDB API path and method mappingVIKINGDB_APIS = {# Collection APIs@@ -58,6 +63,13 @@ class VikingDBClient:if not self.host:raise ValueError("Host is required for VikingDBClient")+ # One long-lived session per client so repeated data-plane calls reuse+ # keep-alive connections instead of re-handshaking on every request.+ self._session = requests.Session()+ adapter = HTTPAdapter(pool_connections=_POOL_CONNECTIONS, pool_maxsize=_POOL_MAXSIZE)+ self._session.mount("https://", adapter)+ self._session.mount("http://", adapter)+def do_req(self,method: str,@@ -89,7 +101,7 @@ class VikingDBClient:headers.update(self.headers)try:- response = requests.request(+ response = self._session.request(method=method,url=url,headers=headers,diff --git a/openviking/storage/vectordb/collection/volcengine_clients.py b/openviking/storage/vectordb/collection/volcengine_clients.pyindex e68382a69..4e4d6943e 100644--- a/openviking/storage/vectordb/collection/volcengine_clients.py+++ b/openviking/storage/vectordb/collection/volcengine_clients.py@@ -3,6 +3,7 @@import jsonimport requests # type: ignore+from requests.adapters import HTTPAdapterfrom volcengine.auth.SignerV4 import SignerV4from volcengine.base.Request import Requestfrom volcengine.Credentials import Credentials@@ -15,6 +16,23 @@ DEFAULT_TIMEOUT = 30# VikingDB API VersionVIKING_DB_VERSION = "2025-06-09"+# Connection pool sizing for the per-client keep-alive session.+_POOL_CONNECTIONS = 16+_POOL_MAXSIZE = 32+++def _build_pooled_session() -> requests.Session:+ """Create a session that reuses TCP/TLS connections across requests.++ Each client owns one long-lived session so repeated search/find calls hit a+ warm keep-alive connection instead of paying a fresh TCP + TLS handshake.+ """+ session = requests.Session()+ adapter = HTTPAdapter(pool_connections=_POOL_CONNECTIONS, pool_maxsize=_POOL_MAXSIZE)+ session.mount("https://", adapter)+ session.mount("http://", adapter)+ return session+class ClientForConsoleApi:_global_host = {@@ -34,6 +52,8 @@ class ClientForConsoleApi:if not all([self.ak, self.sk, self.host, self.region]):raise ValueError("AK, SK, Host, and Region are required for ClientForConsoleApi")+ self._session = _build_pooled_session()+def prepare_request(self, method, params=None, data=None):if Request is None:raise ImportError(@@ -71,7 +91,7 @@ class ClientForConsoleApi:def do_req(self, req_method, req_params=None, req_body=None):req = self.prepare_request(method=req_method, params=req_params, data=req_body)- return requests.request(+ return self._session.request(method=req.method,url=f"https://{self.host}{req.path}",headers=req.headers,@@ -99,6 +119,8 @@ class ClientForDataApi:if not all([self.ak, self.sk, self.host, self.region]):raise ValueError("AK, SK, Host, and Region are required for ClientForDataApi")+ self._session = _build_pooled_session()+def prepare_request(self, method, path, params=None, data=None):if Request is None:raise ImportError(@@ -138,7 +160,7 @@ class ClientForDataApi:req = self.prepare_request(method=req_method, path=req_path, params=req_params, data=req_body)- return requests.request(+ return self._session.request(method=req.method,url=f"https://{self.host}{req.path}",headers=req.headers,@@ -158,6 +180,8 @@ class ClientForDataApiWithApiKey:if not self.api_key or not self.host:raise ValueError("api_key and host are required for ClientForDataApiWithApiKey")+ self._session = _build_pooled_session()+def prepare_request(self, method, path, params=None, data=None):if Request is None:raise ImportError(@@ -189,7 +213,7 @@ class ClientForDataApiWithApiKey:req = self.prepare_request(method=req_method, path=req_path, params=req_params, data=req_body)- return requests.request(+ return self._session.request(method=req.method,url=f"https://{self.host}{req.path}",headers=req.headers,diff --git a/openviking/storage/vectordb/project/vikingdb_project.py b/openviking/storage/vectordb/project/vikingdb_project.pyindex b295b06c1..04a227296 100644--- a/openviking/storage/vectordb/project/vikingdb_project.py+++ b/openviking/storage/vectordb/project/vikingdb_project.py@@ -44,6 +44,10 @@ class VikingDBProject:self.CollectionClass = load_collection_class(self.collection_class_path)self.collection_args = collection_args or {}+ # One long-lived client shared by all metadata calls so its pooled+ # keep-alive session is reused instead of rebuilt per request.+ self._client = VikingDBClient(self.host, self.headers)+logger.info(f"Initialized VikingDB project: {project_name} with host {host} and collection class {collection_class_path}")@@ -54,18 +58,16 @@ class VikingDBProject:def has_collection(self, collection_name: str) -> bool:"""Check if collection exists by calling API"""- client = VikingDBClient(self.host, self.headers)path, method = VIKINGDB_APIS["GetVikingdbCollection"]data = {"ProjectName": self.project_name, "CollectionName": collection_name}- response = client.do_req(method, path=path, req_body=data)+ response = self._client.do_req(method, path=path, req_body=data)return response.status_code == 200def get_collection(self, collection_name: str) -> Optional[Collection]:"""Get collection by name by calling API"""- client = VikingDBClient(self.host, self.headers)path, method = VIKINGDB_APIS["GetVikingdbCollection"]data = {"ProjectName": self.project_name, "CollectionName": collection_name}- response = client.do_req(method, path=path, req_body=data)+ response = self._client.do_req(method, path=path, req_body=data)if response.status_code != 200:return None@@ -91,10 +93,9 @@ class VikingDBProject:def _get_collections(self) -> List[str]:"""List all collection names from server"""- client = VikingDBClient(self.host, self.headers)path, method = VIKINGDB_APIS["ListVikingdbCollection"]data = {"ProjectName": self.project_name}- response = client.do_req(method, path=path, req_body=data)+ response = self._client.do_req(method, path=path, req_body=data)if response.status_code != 200:logger.error(f"List collections failed: {response.text}")return []diff --git a/tests/storage/test_collection_schemas.py b/tests/storage/test_collection_schemas.pyindex b0047a9f2..8f9e0a4ce 100644--- a/tests/storage/test_collection_schemas.py+++ b/tests/storage/test_collection_schemas.py@@ -904,10 +904,11 @@ def test_private_vikingdb_client_wraps_connection_error(monkeypatch):del kwargsraise requests.ConnectionError("connection refused")- monkeypatch.setattr(requests, "request", _raise_connection_error)+ client = VikingDBClient("https://vikingdb.example.com")+ monkeypatch.setattr(client._session, "request", _raise_connection_error)with pytest.raises(ConnectionError, match="connection refused") as exc_info:- VikingDBClient("https://vikingdb.example.com").do_req(+ client.do_req("POST","/api/vikingdb/data/upsert",req_body={},diff --git a/tests/storage/test_volcengine_clients.py b/tests/storage/test_volcengine_clients.pyindex 20d98a0f1..1b33dd0b6 100644--- a/tests/storage/test_volcengine_clients.py+++ b/tests/storage/test_volcengine_clients.py@@ -1,3 +1,4 @@+import requestsfrom volcengine.base.Request import Requestfrom openviking.storage.vectordb.collection.volcengine_clients import (@@ -52,13 +53,10 @@ def test_console_client_do_req_uses_signed_query_params(monkeypatch):}return request- monkeypatch.setattr(- "openviking.storage.vectordb.collection.volcengine_clients.requests.request",- fake_request,- )monkeypatch.setattr(ClientForConsoleApi, "prepare_request", fake_prepare_request)client = ClientForConsoleApi("test-ak", "test-sk", "cn-beijing")+ monkeypatch.setattr(client._session, "request", fake_request)client.do_req("POST",req_params={"Action": "ListVikingdbCollection", "Version": "2025-06-09"},@@ -90,13 +88,10 @@ def test_data_client_do_req_uses_signed_query_params(monkeypatch):}return request- monkeypatch.setattr(- "openviking.storage.vectordb.collection.volcengine_clients.requests.request",- fake_request,- )monkeypatch.setattr(ClientForDataApi, "prepare_request", fake_prepare_request)client = ClientForDataApi("test-ak", "test-sk", "cn-beijing")+ monkeypatch.setattr(client._session, "request", fake_request)client.do_req("POST","/api/vikingdb/data/search/vector",@@ -108,6 +103,49 @@ def test_data_client_do_req_uses_signed_query_params(monkeypatch):assert captured["params"]["X-Signature"] == "signed"+def test_clients_keep_pooled_session_reused_across_calls(monkeypatch):+ """Each client owns one keep-alive session that serves every request."""+ from requests.adapters import HTTPAdapter++ for client in (+ ClientForConsoleApi("test-ak", "test-sk", "cn-beijing"),+ ClientForDataApi("test-ak", "test-sk", "cn-beijing"),+ ClientForDataApiWithApiKey(+ api_key="vk-test-token",+ host="api-vikingdb.vikingdb.cn-beijing.volces.com",+ ),+ ):+ adapter = client._session.get_adapter("https://example.com")+ assert isinstance(adapter, HTTPAdapter)+ # HTTP and HTTPS share the same pooled adapter instance.+ assert client._session.get_adapter("http://example.com") is adapter++ seen_sessions = []++ def fake_prepare_request(self, *args, **kwargs):+ request = Request()+ request.method = "POST"+ request.path = "/api/vikingdb/data/search/vector"+ request.body = "{}"+ request.headers = {}+ request.query = {}+ return request++ def fake_request(self, **kwargs):+ seen_sessions.append(self)+ return object()++ monkeypatch.setattr(ClientForDataApi, "prepare_request", fake_prepare_request)+ monkeypatch.setattr(requests.Session, "request", fake_request)++ client = ClientForDataApi("test-ak", "test-sk", "cn-beijing")+ client.do_req("POST", "/api/vikingdb/data/search/vector")+ client.do_req("POST", "/api/vikingdb/data/search/vector")++ assert len(seen_sessions) == 2+ assert seen_sessions[0] is seen_sessions[1] is client._session++def test_data_api_key_client_prepare_request_sets_bearer_auth():client = ClientForDataApiWithApiKey(api_key="vk-test-token",