Skip to content

Trace-native CI/CD for AI agents — production failures become regression tests that block the PR. Auto-detect, cluster, freeze into hermetic cases, replay in CI for $0.

fix(worker): span-store reads survive more than one async task

Wuthrich Julien3bd363b3caac
diff --git a/backend/tests/test_clickhouse_async_client.py b/backend/tests/test_clickhouse_async_client.py
new file mode 100644
index 0000000..c808479
--- /dev/null
+++ b/backend/tests/test_clickhouse_async_client.py
@@ -0,0 +1,35 @@
+"""The shared async ClickHouse client is bound to the event loop that created it."""
+
+import asyncio
+
+from tracely.infrastructure.clickhouse import client as ch
+
+
+class _Fake:
+ closed = False
+
+ async def close(self):
+ self.closed = True
+
+
+def test_a_new_event_loop_gets_a_new_client(monkeypatch):
+ made: list[_Fake] = []
+
+ async def new(_database):
+ made.append(_Fake())
+ return made[-1]
+
+ monkeypatch.setattr(ch, "_new_async_client", new)
+ monkeypatch.setattr(ch, "_async_client", None)
+ monkeypatch.setattr(ch, "_async_client_loop", None)
+
+ async def twice():
+ return await ch.get_async_client(), await ch.get_async_client()
+
+ # one loop (the API): one client, reused
+ a, b = asyncio.run(twice())
+ assert a is b and len(made) == 1
+
+ # a second `asyncio.run` (the next worker task): a fresh client, the stale one closed
+ c, _ = asyncio.run(twice())
+ assert c is not a and len(made) == 2 and a.closed and not c.closed
diff --git a/backend/tracely/infrastructure/clickhouse/client.py b/backend/tracely/infrastructure/clickhouse/client.py
index 8039f12..c5f185f 100644
--- a/backend/tracely/infrastructure/clickhouse/client.py
+++ b/backend/tracely/infrastructure/clickhouse/client.py
@@ -29,6 +29,7 @@ def get_client(database: str | None = None) -> Client:
_async_client = None
+_async_client_loop = None
_async_client_lock = asyncio.Lock()
@@ -50,22 +51,33 @@ async def get_async_client(database: str | None = None):
behavior) leaked a pool — and its sockets/file descriptors — on every API read. Disposed in the
FastAPI `lifespan` via `close_async_client()`. A non-default `database` (migrations/tests only)
always returns a fresh client the caller is responsible for closing."""
- global _async_client
+ global _async_client, _async_client_loop
if database is not None and database != settings.clickhouse_database:
return await _new_async_client(database)
- if _async_client is None:
+ # The client's HTTP session belongs to the loop that made it. The API has one loop for its
+ # whole life; a worker task calls `asyncio.run` per run, so the client a previous task left
+ # behind is unusable ("belongs to a different event loop") and every read after the first
+ # task failed — monitors and the selfcheck's store probe among them.
+ loop = asyncio.get_running_loop()
+ if _async_client is None or _async_client_loop is not loop:
async with _async_client_lock:
- if _async_client is None: # double-checked: only one coroutine creates it
- _async_client = await _new_async_client(None)
+ if _async_client is None or _async_client_loop is not loop: # double-checked
+ stale = _async_client
+ _async_client, _async_client_loop = await _new_async_client(None), loop
+ if stale is not None:
+ try: # its own loop is gone; closing here is what releases the sockets
+ await stale.close()
+ except Exception: # noqa: BLE001 — nothing more to do with a dead client
+ pass
return _async_client
async def close_async_client() -> None:
"""Dispose the shared async client (called on FastAPI shutdown)."""
- global _async_client
+ global _async_client, _async_client_loop
if _async_client is not None:
await _async_client.close()
- _async_client = None
+ _async_client = _async_client_loop = None
def insert_rows(
diff --git a/backend/tracely/workers/tasks.py b/backend/tracely/workers/tasks.py
index 9b45379..f02838a 100644
--- a/backend/tracely/workers/tasks.py
+++ b/backend/tracely/workers/tasks.py
@@ -256,17 +256,32 @@ def _mark_gate_error(session, gate_run_id: str) -> None:
session.commit()
+def _run_async(coro):
+ """`asyncio.run` for a task, leaving nothing behind that is tied to its event loop. The async
+ Postgres pool keeps connections that belong to the loop that opened them; the next task gets
+ a new loop, and its first query on one of those fails ("Event loop is closed")."""
+ import asyncio
+
+ from tracely.infrastructure.db.engine import async_engine
+
+ async def main():
+ try:
+ return await coro
+ finally:
+ await async_engine.dispose()
+
+ return asyncio.run(main())
+
+
@celery_app.task(name="tracely.evaluate_monitors", bind=True, max_retries=0)
def evaluate_monitors_task(self) -> dict:
"""Fire the monitoring engine for every enabled monitor in every project — driven by Celery
beat (`beat_schedule` in `celery_app.py`). Best-effort: one bad monitor is logged + skipped,
transient errors are NOT retried (the next beat tick will pick up where we left off)."""
- import asyncio
-
from tracely.services.monitoring_service import MonitoringService
try:
- return asyncio.run(MonitoringService().evaluate_all())
+ return _run_async(MonitoringService().evaluate_all())
except Exception as exc: # CH outage / Redis blip — the next tick will retry
log.warning("evaluate_monitors_failed", error=str(exc))
return {"monitors": 0, "fired": 0, "error": str(exc)}
@@ -427,12 +442,10 @@ def selfcheck_task(self) -> dict:
"""Watch our own deployment (beat, every 5 min). Tracely's failure modes are quiet — a dead
worker still 202s every ingest — so this is the thing that turns 'the numbers stopped moving'
into a page. Best-effort by construction: it must never itself be the reason a beat tick dies."""
- import asyncio
-
from tracely.services.selfcheck_service import run
try:
- return asyncio.run(run())
+ return _run_async(run())
except Exception as exc: # noqa: BLE001
log.warning("selfcheck_failed", error=str(exc))
return {"degraded": None, "error": str(exc)}