RuView icon indicating copy to clipboard operation
RuView copied to clipboard

fix(api): resolve event loop starvation in health/metrics endpoints

Open sushantguri opened this issue 4 months ago • 2 comments

Fixes # — replaces blocking psutil.cpu_percent(interval=1) with non-blocking interval=None wrapped in asyncio.to_thread(). Metrics latency: ~1,000ms → 0.8ms. Regression test added

sushantguri avatar Jul 15 '26 13:07 sushantguri

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:

  1. It uses @pytest.mark.asyncio but never does import pytest → NameError at collection, so CI errors out and the test never runs.
  2. run_test() ends in sys.exit(0) / sys.exit(1) instead of returning, so max_gap, duration = await run_test() raises SystemExit.
  3. 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 blocking interval=1 would 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.

PrinceAudre avatar Jul 25 '26 12:07 PrinceAudre

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.

PrinceAudre avatar Jul 25 '26 12:07 PrinceAudre