diff --git a/openviking/storage/queuefs/queue_manager.py b/openviking/storage/queuefs/queue_manager.py index fd327183d09..9abbd92d09e 100644 --- a/openviking/storage/queuefs/queue_manager.py +++ b/openviking/storage/queuefs/queue_manager.py @@ -13,6 +13,7 @@ from typing import Any, Dict, Optional, 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 @@ -244,7 +245,13 @@ def _queue_worker_loop( traceback.print_exc() stop_event.wait(poll_interval) finally: - loop.close() + try: + loop.run_until_complete(LoopScopedAsyncClientCache.close_current_loop_clients()) + except Exception: + logger.exception("[QueueManager] Failed to close worker-loop async clients") + finally: + asyncio.set_event_loop(None) + loop.close() async def _worker_async_concurrent( self, queue: NamedQueue, stop_event: threading.Event, max_concurrent: int diff --git a/openviking/utils/async_client_cache.py b/openviking/utils/async_client_cache.py index 713d3515940..3ef164c7c34 100644 --- a/openviking/utils/async_client_cache.py +++ b/openviking/utils/async_client_cache.py @@ -28,6 +28,14 @@ def _aclose_client(client: AsyncCloseable) -> Any: return client.aclose() +def _close_async_client(client: Any) -> Any: + """Prefer an async close method for a client owned by a running loop.""" + close = getattr(client, "aclose", None) + if close is None: + close = getattr(client, "close", None) + return close() if close is not None else None + + class LoopScopedAsyncClientCache: """Cache async clients per running event loop. @@ -36,12 +44,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 +101,12 @@ def pop_all(self) -> list[Any]: self._fallback_client = None return clients + def pop_for_loop(self, loop: asyncio.AbstractEventLoop) -> list[Any]: + """Remove and return the client owned by ``loop``, if one exists.""" + with self._lock: + client = self._clients_by_loop.pop(loop, None) + return [] if client is None else [client] + @staticmethod async def _close_clients(clients: list[Any], close_client: Callable[[Any], Any]) -> None: seen: set[int] = set() @@ -101,6 +120,19 @@ async def _close_clients(clients: list[Any], close_client: Callable[[Any], Any]) if inspect.isawaitable(result): await result + @classmethod + async def close_current_loop_clients(cls) -> None: + """Close cached clients owned by the current event loop. + + The no-loop fallback client is managed separately by ``close_all`` or + ``close_all_async``; it is not owned by the current loop. + """ + loop = asyncio.get_running_loop() + with cls._instances_lock: + caches = list(cls._instances) + clients = [client for cache in caches for client in cache.pop_for_loop(loop)] + await cls._close_clients(clients, _close_async_client) + def close_all(self, close_client: Callable[[Any], Any]) -> None: """Close and clear all cached clients on a best-effort basis.""" clients = self.pop_all() diff --git a/tests/storage/test_queue_manager.py b/tests/storage/test_queue_manager.py index ec12526a880..199911b7d32 100644 --- a/tests/storage/test_queue_manager.py +++ b/tests/storage/test_queue_manager.py @@ -2,11 +2,14 @@ # SPDX-License-Identifier: AGPL-3.0 """Focused tests for QueueManager concurrency selection.""" +import asyncio import os import subprocess import sys +import threading from openviking.storage.queuefs.queue_manager import QueueManager +from openviking.utils.async_client_cache import LoopScopedAsyncClientCache def test_queuefs_package_imports_in_a_clean_process(tmp_path) -> None: @@ -34,3 +37,30 @@ def test_queue_concurrency_uses_separate_configured_values() -> None: assert manager._max_concurrent_for_queue(manager.EXTERNAL_PARSE) == 9 assert manager._max_concurrent_for_queue(manager.ADD_RESOURCE) == 7 assert manager._max_concurrent_for_queue(manager.SESSION_COMMIT) == 5 + + +def test_queue_worker_closes_loop_scoped_clients_before_its_loop() -> None: + events = [] + cache = LoopScopedAsyncClientCache() + + class Client: + async def aclose(self): + events.append(("clients", asyncio.get_running_loop().is_closed())) + + class Queue: + name = QueueManager.EMBEDDING + + async def size(self): + cache.get(Client) + stop_event.set() + return 0 + + def has_dequeue_handler(self): + return False + + manager = QueueManager(agfs=object()) + stop_event = threading.Event() + + manager._queue_worker_loop(Queue(), stop_event) + + assert events == [("clients", False)] diff --git a/tests/unit/test_async_client_cache.py b/tests/unit/test_async_client_cache.py index 605b41cd54a..9ee3c2a320a 100644 --- a/tests/unit/test_async_client_cache.py +++ b/tests/unit/test_async_client_cache.py @@ -59,3 +59,34 @@ 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() + + +def test_close_current_loop_clients_closes_only_clients_owned_by_that_loop(): + cache = LoopScopedAsyncClientCache() + closed = [] + + class Client: + async def aclose(self): + closed.append(threading.get_ident()) + + async def get_client(): + return cache.get(Client) + + async def get_and_close_current_loop(): + cache.get(Client) + await LoopScopedAsyncClientCache.close_current_loop_clients() + + retained_loop = asyncio.new_event_loop() + closing_loop = asyncio.new_event_loop() + try: + retained_loop.run_until_complete(get_client()) + closing_loop.run_until_complete(get_and_close_current_loop()) + + assert closed == [threading.get_ident()] + assert cache.has_clients() + + retained_loop.run_until_complete(LoopScopedAsyncClientCache.close_current_loop_clients()) + assert not cache.has_clients() + finally: + retained_loop.close() + closing_loop.close()