fix(api): resolve event loop starvation in health/metrics endpoints
Fixes #
The production fix is good; the shipped regression test doesn't run (and wouldn't catch the regression)
The endpoint change is sound — interval=None plus asyncio.to_thread(...) correctly moves the ~1s psutil stall off the event loop. But tests/unit/test_health_concurrency.py has three problems:
- It uses
@pytest.mark.asynciobut never doesimport pytest→NameErrorat collection, so CI errors out and the test never runs. run_test()ends insys.exit(0)/sys.exit(1)instead of returning, somax_gap, duration = await run_test()raisesSystemExit.- Even repaired, it's non-discriminating: it invokes the metric function via
await asyncio.to_thread(get_system_metrics), i.e. it offloads to a worker thread itself — so the pre-fix blockinginterval=1would block only that worker thread, not the event loop, and the measured ticker gaps stay small. The test passes against the unfixed code, so it can't guard the regression it's meant to protect.
Suggested direction: add import pytest; have run_test() return (max_gap, duration); and exercise the metric path on the event loop — either call the async metrics endpoint that wraps to_thread directly, or call the sync get_system_metrics() on the loop (no to_thread) — so the old blocking version actually stalls the concurrent ticker and the assertion fails. Happy to provide a concrete rewrite if useful.
Correction to my comment above. I checked current main: both the production change (psutil.cpu_percent(interval=None) + asyncio.to_thread(...)) and archive/v1/tests/unit/test_health_concurrency.py are already present there. The diff shown on this PR is against a stale merge-base, so it only appears to add them. This PR is therefore effectively a no-op and can be closed.
Points (1) and (2) in my earlier comment described this PR's older copy of the test — the version already on main fixes both (it has import pytest and run_test() returns). Apologies for the noise there.
One real issue does remain, but it's on main, not specific to this PR: test_health_concurrency.py still calls get_system_metrics via await asyncio.to_thread(...) (line 35). Because it offloads to a worker thread, a regressed blocking interval=1 would stall only that thread, not the event loop — so the tick gaps stay small and the test passes regardless. I'll open a small PR against main to call get_system_metrics() on the loop instead, so it actually guards the regression.