Skip to content

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

fix(queuefs): close worker-loop async clients before closing the loop (#5675)

t0saki81805e9008b1
diff --git a/openviking/storage/queuefs/queue_manager.py b/openviking/storage/queuefs/queue_manager.py
index e045527b1..b2ac17cdf 100644
--- a/openviking/storage/queuefs/queue_manager.py
+++ b/openviking/storage/queuefs/queue_manager.py
@@ -13,6 +13,7 @@ import traceback
from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence, Set, Union
from openviking.service.task_work_index import TaskWorkIndex
+from openviking.utils.async_client_cache import LoopScopedAsyncClientCache
from openviking_cli.utils.logger import get_logger
from .embedding_queue import EmbeddingQueue
@@ -324,6 +325,14 @@ class QueueManager:
loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
loop.run_until_complete(loop.shutdown_asyncgens())
loop.run_until_complete(loop.shutdown_default_executor())
+ try:
+ loop.run_until_complete(LoopScopedAsyncClientCache.close_current_loop_clients())
+ except Exception:
+ logger.warning(
+ "[QueueManager] Failed to close async clients for %s",
+ queue.name,
+ exc_info=True,
+ )
loop.close()
if queue.name == self.EMBEDDING:
# No more deliveries can start and active handlers have exited,
diff --git a/openviking/utils/async_client_cache.py b/openviking/utils/async_client_cache.py
index 713d35159..c4ca007b8 100644
--- a/openviking/utils/async_client_cache.py
+++ b/openviking/utils/async_client_cache.py
@@ -28,6 +28,11 @@ def _aclose_client(client: AsyncCloseable) -> Any:
return client.aclose()
+def _close_async_client(client: Any) -> Any:
+ close = getattr(client, "aclose", None) or getattr(client, "close", None)
+ return close() if close is not None else None
+
+
class LoopScopedAsyncClientCache:
"""Cache async clients per running event loop.
@@ -36,12 +41,17 @@ class LoopScopedAsyncClientCache:
across worker threads with separate event loops can then fail at runtime.
"""
+ _instances: weakref.WeakSet[LoopScopedAsyncClientCache] = weakref.WeakSet()
+ _instances_lock = threading.Lock()
+
def __init__(self) -> None:
self._clients_by_loop: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, Any] = (
weakref.WeakKeyDictionary()
)
self._fallback_client: Any = None
self._lock = threading.Lock()
+ with self._instances_lock:
+ self._instances.add(self)
def __copy__(self) -> LoopScopedAsyncClientCache:
"""Return an empty cache instead of sharing live async clients."""
@@ -88,6 +98,24 @@ class LoopScopedAsyncClientCache:
self._fallback_client = None
return clients
+ @classmethod
+ async def close_current_loop_clients(cls) -> None:
+ """Close the clients every cache holds for the running loop, on that loop.
+
+ Call this before closing a private event loop: clients bound to a closed
+ loop can no longer close their transports.
+ """
+ loop = asyncio.get_running_loop()
+ with cls._instances_lock:
+ caches = list(cls._instances)
+ clients = []
+ for cache in caches:
+ with cache._lock:
+ client = cache._clients_by_loop.pop(loop, None)
+ if client is not None:
+ clients.append(client)
+ await cls._close_clients(clients, _close_async_client)
+
@staticmethod
async def _close_clients(clients: list[Any], close_client: Callable[[Any], Any]) -> None:
seen: set[int] = set()
diff --git a/tests/storage/test_queue_manager.py b/tests/storage/test_queue_manager.py
index 662569a10..b0aa487af 100644
--- a/tests/storage/test_queue_manager.py
+++ b/tests/storage/test_queue_manager.py
@@ -19,6 +19,7 @@ from openviking.storage.queuefs.named_queue import DequeueHandlerBase, NamedQueu
from openviking.storage.queuefs.process_result import ProcessResult
from openviking.storage.queuefs.queue_manager import QueueManager
from openviking.storage.queuefs.queue_middleware import QueueMiddleware
+from openviking.utils.async_client_cache import LoopScopedAsyncClientCache
def test_queuefs_package_imports_in_a_clean_process(tmp_path) -> None:
@@ -50,6 +51,32 @@ def test_queue_concurrency_uses_separate_configured_values() -> None:
assert manager._max_concurrent_for_queue(manager.SESSION_COMMIT) == 5
+def test_queue_worker_closes_loop_scoped_clients_before_closing_its_loop() -> None:
+ cache = LoopScopedAsyncClientCache()
+ stop_event = threading.Event()
+ loop_closed_at_close = []
+
+ class Client:
+ async def aclose(self):
+ loop_closed_at_close.append(asyncio.get_running_loop().is_closed())
+
+ class Queue:
+ name = "Test"
+
+ async def size(self):
+ cache.get(Client)
+ stop_event.set()
+ return 0
+
+ def has_dequeue_handler(self):
+ return False
+
+ QueueManager(agfs=object())._queue_worker_loop(Queue(), stop_event)
+
+ assert loop_closed_at_close == [False]
+ assert not cache.has_clients()
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("concurrency", [1, 2])
async def test_skill_shutdown_releases_lock_after_embedding_worker_exits(
diff --git a/tests/unit/test_async_client_cache.py b/tests/unit/test_async_client_cache.py
index 605b41cd5..53ce5607b 100644
--- a/tests/unit/test_async_client_cache.py
+++ b/tests/unit/test_async_client_cache.py
@@ -59,3 +59,70 @@ def test_loop_scoped_async_client_cache_copies_without_live_clients():
assert cache.has_clients()
assert not shallow.has_clients()
assert not deep.has_clients()
+
+
+class _LoopBoundClient:
+ def __init__(self):
+ self.loop = asyncio.get_running_loop()
+ self.closed_on = []
+
+ async def aclose(self):
+ running = asyncio.get_running_loop()
+ if running is not self.loop:
+ raise RuntimeError("Event loop is closed")
+ self.closed_on.append(running)
+
+
+def test_close_current_loop_clients_closes_only_clients_owned_by_that_loop():
+ cache = LoopScopedAsyncClientCache()
+ loop_a = asyncio.new_event_loop()
+ loop_b = asyncio.new_event_loop()
+
+ async def get_client():
+ return cache.get(_LoopBoundClient)
+
+ try:
+ client_a = loop_a.run_until_complete(get_client())
+ client_b = loop_b.run_until_complete(get_client())
+
+ loop_b.run_until_complete(LoopScopedAsyncClientCache.close_current_loop_clients())
+
+ assert client_b.closed_on == [loop_b]
+ assert client_a.closed_on == []
+ assert cache.has_clients()
+
+ loop_a.run_until_complete(LoopScopedAsyncClientCache.close_current_loop_clients())
+
+ assert client_a.closed_on == [loop_a]
+ assert not cache.has_clients()
+ finally:
+ loop_a.close()
+ loop_b.close()
+
+
+def test_worker_loop_clients_do_not_fail_when_caches_close_on_another_loop():
+ caches = [LoopScopedAsyncClientCache() for _ in range(3)]
+ clients = []
+
+ async def use_and_close():
+ clients.extend(cache.get(_LoopBoundClient) for cache in caches)
+ await LoopScopedAsyncClientCache.close_current_loop_clients()
+
+ worker_loop = asyncio.new_event_loop()
+ worker_loop.run_until_complete(use_and_close())
+ worker_loop.close()
+
+ errors = []
+
+ async def service_close():
+ asyncio.get_running_loop().set_exception_handler(lambda _loop, ctx: errors.append(ctx))
+ for cache in caches:
+ cache.close_all_with_aclose()
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+
+ asyncio.run(service_close())
+
+ assert [client.closed_on for client in clients] == [[worker_loop]] * 3
+ assert not any(cache.has_clients() for cache in caches)
+ assert errors == []