Repository navigation
fix(backend): the two loop blocks the probe measured run in a thread (#4674) - #4682
Conversation
#4671 measured /health over 150 ms in 24 of 1,500 samples on a hosted instance, worst 1.5 s, clustered near the minute mark, with nothing in the logs to say why. /health does no I/O on PostgreSQL, so that latency is the event loop's lag: sync work ran on the loop. An audit lists hundreds of candidates; it cannot say which one ran at :58. services/loop_health.py says which, from inside the process: - The probe: a coroutine sleeps 50 ms and measures how late it woke. A daemon thread watches its last wake-up and, once the loop has been silent past EVENT_LOOP_STALL_THRESHOLD_MS (250), snapshots the loop thread's stack. When the loop returns, one event_loop_blocked warning carries the blocked ms, the worker pid and that stack. A stall still going after 5 s is reported before it ends. Code locations only: never a local or an argument. - tick(name) times one cycle of a background loop and logs loop_tick_slow past LOOP_TICK_WARN_MS (250). Wrapped: capacity maintenance, heartbeat watch, operator-queue sync, monitoring, sync health, and the 5 s loop due-run sweep. - Numbers (lag, 60 s max, 10 min stall count, per-loop tick times) are on GET /api/telemetry/host -> backend, for the worker that answered. Runs in every worker with no lease, by design: a worker can only measure its own loop. Also: the uvicorn worker count is BACKEND_WORKERS in the prod and hosted compose files, default 2 (unchanged), with a note on what scales per worker (the background loops, the PostgreSQL pool). This does not fix the stall. It is the "measure first" step: one stall on an instance running this build is the attribution #4671 asks for. Related to #4674 Related to #4671 Co-Authored-By: Claude Fable 5.2 <[email protected]>
A submodule of operator_queue_service may import nothing the package __init__ has not imported first (test_3785), and __init__ is at its 800-line cap, so the tick timer is imported in _poll_loop rather than at module level. Related to #4674 Co-Authored-By: Claude Fable 5.2 <[email protected]>
…global (#4674) Four capture tests replaced services.loop_health.format_stack with monkeypatch and passed locally, but failed in CI's seeded run: by then the module object the test held was not the one the probe's methods resolve their globals in, so the patch never reached check(). The probe now takes read_stack as a constructor argument (default: the loop thread's stack), and the tests hand in their own. No behaviour change. Related to #4674 Co-Authored-By: Claude Fable 5.2 <[email protected]>
Review finding. #4671 and #4674 both measure /health against 150 ms, but the probe only logged a block past 250 ms, so a sample that failed the acceptance check could leave no line saying why. Default is now 150 ms; EVENT_LOOP_STALL_THRESHOLD_MS still overrides it. Related to #4674 Co-Authored-By: Claude Fable 5.2 <[email protected]>
…it (#4674) Found by running it on a live instance: a 159 ms block against the 150 ms threshold was reported as 'stack not captured'. The watch thread looked every 50 ms and only snapshotted once the loop had been silent for the whole threshold, so a block that ended just past it was over before the next look. The stack is now taken at half the threshold and the watch thread looks at least six times per threshold. Whether a block is reported still depends only on how long it turned out to be; an early capture of a block that ends under the threshold is discarded. Related to #4674 Co-Authored-By: Claude Fable 5.2 <[email protected]>
Found on a live instance: a sync HTTP call on the loop was reported as twelve frames of urllib3, http.client and email.parser, with the Trinity caller cut off. The stack is now 40 frames deep. Related to #4674 Co-Authored-By: Claude Fable 5.2 <[email protected]>
…4674) services/loop_health.py, run on a live instance, named two things blocking a worker's event loop: - run_heartbeat_watch_loop -> process_watch_tick -> list_all_agents_fast: 208 ms with 55 containers. It runs every 5 s in every worker. A /health sample taken the same second read 236 ms. - login -> authenticate_user -> verify_password: 176-200 ms of bcrypt per login, successful or not. The heartbeat tick now runs on the Docker executor (docker_utils.run_blocking); its alerts are still awaited on the loop. The password check runs in a thread; the rate limit, the audit record and the 401 are unchanged. After, on the same instance: 1,800 /health samples over 150 s, none over 150 ms attributed to either. Stacked on #4677 (the probe and the heartbeat tick timer). Related to #4674 Related to #4671 Co-Authored-By: Claude Fable 5.2 <[email protected]>
Test evidenceMeasured on a local dev instance (55 agent containers, 3 running), before and after this change, with the probe from #4677 running in both.
Before, the one slow sample and the probe's heartbeat line fell in the same second. Limits: one instance, one 150 s window each — not the 10-minute sample the issue asks for, and not the hosted instance that reported the minute-mark stall. The heartbeat watch still runs in every worker with no leader lease; it is off the loop, not deduplicated. |
|
✅ Nightly unit-suite clean when this PR is merged into |
|
merge-train (2026-11-21): not on this train. A security finding needs your call on the fix. Validated at CRITICAL: concurrent logins bypass the per-account lockout (
Reproduced with 40 concurrent
So each lockout window allows a burst of guesses limited only by the attacker's concurrency (OWASP A07). The shape of the fix is yours:
Either way, please add a concurrent-login test that fails on this head. Related (WARNING): bcrypt now runs on the default thread pool, up to The heartbeat half (the tick on Rides the next train once fixed. #4677 is landing on this one, so this PR's diff will shrink to its own commit. |
|
Resolve by merging |
Conflicts: heartbeat_service.py (keep the off-loop tick inside dev's loop_health.tick wrapper), tests/registry.json (dev's entries). Co-Authored-By: Claude Fable 5.2 <[email protected]>
…4674) Verifying the password in a thread put an await between the limit check and the failure record, so every concurrent request for one account passed the check before any failure was counted: 40 concurrent attempts verified 40 passwords where dev verified 5. - check -> verify -> record is now one critical section per account (a reference-counted asyncio.Lock, dropped when its last request leaves). Other accounts are not delayed. - at most LOGIN_VERIFY_CONCURRENCY (4) bcrypt verifies run at once per worker, so a login flood over many accounts cannot fill the default thread pool shared with every other asyncio.to_thread caller. Tests drive the real login handler, limit check and record against a fake Redis: 40 concurrent wrong passwords verify exactly 5 (401 x5, 429 x35). Co-Authored-By: Claude Fable 5.2 <[email protected]>
Lockout finding fixed (
|
…#4674) The heartbeat watch tick now runs off the event loop, so heartbeat_service.py goes from 1 counted call to 0 (total 1919 -> 1918). Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
merge-train (2026-11-24): not on this train. The per-IP login limit no longer holds under concurrency, and the fix needs your design. Validated at The per-account fix from the last round holds: check → verify → record run inside What is open ( async with _account_verify_lock(account):
check_login_rate_limit(client_ip, account=account)The lock is keyed by account only. Requests from one IP for different accounts all pass the IP check before any of them records a failure, and the 4-slot semaphore sits after the check. Reproduced with this PR's own test rig (real
So "the rate limit is unchanged" in the body is true for the account bucket and not for the IP bucket. No test covers the IP bucket under concurrency; every lockout test uses one IP per request. A per-IP lock would bring back the shared-NAT serialisation #591 removed. The other shapes are re-checking after the slot is acquired, or charging the attempt before the verify. Also: Rides the next train once fixed. |
…ccounts at once (#4674) The per-account lock covers one account. Requests from one address for different accounts each hold their own lock, so all of them passed the IP check before any failure was recorded: 200 concurrent wrong-password logins from one address verified 200 passwords where dev verified 30. A verify is now counted against its address from the moment it is admitted until its outcome is recorded. The admission check reads recorded failures plus verifies in flight, with no await between the read and the increment. A verify that succeeds gives its place back and never counts as a failure. No per-address lock: a shared NAT is not queued (#591). Also corrects the heartbeat watch comment: the tick runs in every worker. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Per-IP limit fixed (
|
…chanical, per the merge-train note on the PR Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
merge-train note: pushed one commit to this branch, Validated at |
Summary
The first two event-loop blocks attributed by the probe in #4677, fixed. Stacked on #4677 — until it merges, this diff also shows its commits; review the last commit.
Run on a local instance (55 agent containers, 3 running), the probe logged:
/healthrequest sent the same second as the 208 ms block took 236 ms.Fix
docker_utils.run_blocking); its alerts are still awaited on the loop.authenticate_userruns in a thread, at most 4 at once per worker. The audit record and the 401 are unchanged.Measured on the same instance
/healthevery 80 ms for 150 s:This is one instance and one 150 s window each, not the 10-minute sample the issue asks for, and not the hosted instance that reported the minute-mark stall.
Not in this PR
The other four loops in #4674's table, the hot handlers, a leader lease for the heartbeat watch (it still runs in every worker, now off the loop), Redis socket timeouts.
Test plan
tests/unit/test_4674_measured_loop_blocks.py(4): the blocking function runs on a different thread than the loop, and a 5 ms ticker keeps running while it does; a failing tick still cannot kill the loop; a wrong password is still refused and auditedRelated to #4674
Related to #4671
🤖 Generated with Claude Code