"""Per-thread asyncio event loop reuse (avoids asyncio.run() overhead in recorder threads).""" from __future__ import annotations import asyncio import threading from typing import Any, Coroutine, TypeVar _T = TypeVar("_T") _tls = threading.local() def run_async_coro(coro: Coroutine[Any, Any, _T]) -> _T: loop: asyncio.AbstractEventLoop | None = getattr(_tls, "loop", None) if loop is None or loop.is_closed(): loop = asyncio.new_event_loop() _tls.loop = loop asyncio.set_event_loop(loop) return loop.run_until_complete(coro)