Repository navigation
feat(backend): event-loop probe names what blocked a worker (#4674) - #4677
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]>
Test evidenceRun on a local dev instance (55 agent containers, 3 running; default settings, threshold 150 ms). The probe logged real blocks, each with the worker pid and the frame: The first one lines up with an outside measurement:
Isolated rig (fresh PostgreSQL, seeded): 16 probed responses identical to Three defects of the probe itself, found by running it and fixed here:
Known limit: a few blocks are still reported without a stack (the watch thread cannot run while a C extension holds the GIL). Not done here: this has not run on the hosted instance that reported the minute-mark stall, so that stall is still unattributed. |
…cal, per the merge-train note on the PR Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
merge-train (2026-11-21): on this train. Validated at Pushed / changed, mechanical only:
Non-blocking, for you to decide:
#4682 is not on this train; see the note there. |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…4679/#4677 (#4680) Accepted growth, ruled at merge-train Gate 2 (2026-11-21): - routers/setup.py 6 -> 9 (ent#1329 setup terms, #4683/#4694/#4698) - client_portal/work/service.py 8 -> 10, agent_service/autonomy.py 12 -> 14 (#4679's batch prefetch reads: fewer queries, more call sites) Co-Authored-By: Claude Opus 5.5 <[email protected]>
) * test(backend): ratchet on blocking calls inside async def (#4674) A sync db, Docker, HTTP or sleep call written directly inside an `async def` runs on the event loop and blocks the whole worker. scripts/ci/check_sync_on_loop.py counts them per file by parsing (never importing) and compares with scripts/ci/sync_on_loop_baseline.json: - a file's count may not exceed its entry; - a file with no entry starts at zero; - an entry above reality fails too, so a paydown lowers the baseline. Today: 1,911 call sites in 831 async functions across 194 files (db 1,363; through a module's own sync function 386; Docker 161). Counted: db / core_db / _db / *.db method calls, get_agent_container, list_all_agents_fast, agent_container_states, time.sleep, subprocess.run, requests.*, and calls to the same module's plain defs that make one. Not counted: plain def handlers, nested defs, and the arguments of to_thread / run_in_executor / run_in_threadpool. The ratchet runs in the unit suite (test_4674_sync_on_loop_ratchet.py). The helper list is one constant, for trinity-dev#82 to share. Related to #4674 Co-Authored-By: Claude Fable 5.2 <[email protected]> * test(backend): the ratchet does not pin the offenders it exists to remove (#4674) Review finding. One test asserted that heartbeat_service's watch loop and dependencies.py are in the scan. Those are exactly what #4674 goes on to fix, so the test would have failed on the fix. It now asserts only that the live scan sees both families. The backend is parsed once per module instead of once per test. Related to #4674 Co-Authored-By: Claude Fable 5.2 <[email protected]> * test(backend): regenerate the sync-on-loop baseline on current dev (#4674) dev moved under the branch and changed two files' counts, which is the ratchet doing its job on its own PR. Related to #4674 Co-Authored-By: Claude Fable 5.2 <[email protected]> * merge-train: regenerate the sync-on-loop baseline on dev after #4676/#4679/#4677 (#4680) Accepted growth, ruled at merge-train Gate 2 (2026-11-21): - routers/setup.py 6 -> 9 (ent#1329 setup terms, #4683/#4694/#4698) - client_portal/work/service.py 8 -> 10, agent_service/autonomy.py 12 -> 14 (#4679's batch prefetch reads: fewer queries, more call sites) Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(backend): --write refuses to absorb growth into the baseline (#4674) Regenerating the baseline wrote whatever the scan found, so a regeneration could wave new blocking calls through and only the JSON diff showed it. --write now prints each file whose count grew and writes nothing unless --allow-growth is passed; a paydown is written as before. Also: main() reads and writes the baseline path it names (the helpers' default argument was bound at import), and the docstring no longer claims a /code-health consumer that does not exist. Co-Authored-By: Claude Fable 5.2 <[email protected]> --------- Co-authored-by: Claude Fable 5.2 <[email protected]> Co-authored-by: trinity-ability <[email protected]>
…4674) (#4682) * feat(backend): event-loop probe names what blocked a worker (#4674) #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]> * fix(backend): import loop_health inside the poller loop (#4674) 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]> * test(backend): inject the probe's stack reader instead of patching a 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]> * fix(backend): the probe's stall threshold is the 150 ms bar (#4674) 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]> * fix(backend): the probe takes the stack before the threshold, not at 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]> * fix(backend): the probe's stack reaches Trinity's own frame (#4674) 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]> * fix(backend): the two loop blocks the probe measured run in a thread (#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]> * fix(auth): concurrent logins cannot outrun the per-account lockout (#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]> * test(backend): lower the sync-on-loop baseline for the heartbeat tick (#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]> * fix(auth): the per-IP login limit holds when one address tries many accounts 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]> --------- Co-authored-by: Claude Fable 5.2 <[email protected]> Co-authored-by: trinity-ability <[email protected]>
Summary
The "measure first" step of #4674, and the instrument that attributes the minute-mark stall in #4671.
#4671 measured
/healthover 150 ms in 24 of 1,500 samples, worst 1.5 s, with nothing in the logs to say why./healthdoes no I/O on PostgreSQL, so that latency is event-loop lag: synchronous work ran on the loop. The audit lists about 390 candidates; it cannot say which one ran at :58. This PR makes the backend say it.What it adds
services/loop_health.pyThe probe. A coroutine sleeps 50 ms and measures how late it woke. A daemon thread watches its last wake-up; once the loop has been silent for half of
EVENT_LOOP_STALL_THRESHOLD_MS(default 150, the bar bug(workspace): a turn end or page load costs 1–3 s on the server — asks makes ~130 lookups per call, the page fetches duplicates, and the backend stalls near the minute mark #4671 measures against) it snapshots the loop thread's stack, and reports the stall once it passes the threshold. When the loop returns, one warning is logged:A stall still going after 5 s is reported before it ends (
event_loop_stuck). Code locations only — never a local or an argument.Tick timing.
tick(name)wraps one cycle of a background loop and logsloop_tick_slowwith the pid pastLOOP_TICK_WARN_MS(default 250). Wrapped: capacity maintenance, heartbeat watch, operator-queue sync, monitoring, sync health (the five in refactor(backend): sync DB, Redis and Docker calls on the event loop — background loops and about 390 async handlers block the worker #4674's table) and the 5 s loop due-run sweep. Wall time includes awaits, so a slow tick names the cycle; the probe says whether the loop was actually blocked.The metric.
GET /api/telemetry/hostgainsbackend: {event_loop: {pid, lag_ms, max_lag_ms_60s, stalls_10m, worst_stall_ms_10m, …}, loops: {name: {ticks, slow_ticks, last_ms, max_ms}}}for the worker that answered.Runs in every worker with no leader lease, by design: a worker can only measure its own loop.
EVENT_LOOP_PROBE_ENABLED=falseturns it off.Worker count.
--workers ${BACKEND_WORKERS:-2}indocker-compose.prod.ymlanddocker-compose.hosted.yml; default unchanged. The comment says what scales per worker (the background loops, the PostgreSQL pool).Release note: new env keys
All optional, defaults shown; set in all three compose files and documented in
.env.example:EVENT_LOOP_PROBE_ENABLEDtrueEVENT_LOOP_STALL_THRESHOLD_MS150event loop blockedwith the stackLOOP_TICK_WARN_MS250loop_tick_slowBACKEND_WORKERS2Section added by the merge train (2026-11-21) so
/releasecollects the keys.What this does not do
It does not fix the stall or move any sync work off the loop. Next steps, once one stall has been logged on an instance running this build:
event_loop_blockedline on bug(workspace): a turn end or page load costs 1–3 s on the server — asks makes ~130 lookups per call, the page fetches duplicates, and the backend stalls near the minute mark #4671 (that is the attribution AC, including whether the stall-monitor cycle is the cause — it is now timed insidecapacity_maintenance);Overhead: one 50 ms timer per worker and one thread waking every
min(50 ms, threshold/6)(25 ms at the default); the stack is read only once per stall.Test plan
tests/unit/test_4674_loop_health.py(37): a blocking call on a real loop is reported once and named; an awaiting loop is never reported; a captured stack belongs to its own stall (a capture read after the loop woke is dropped); no values in the stack; tick timing; the six loops are wrapped with the sleep outside; compose wiringtests/unit/test_1028_lifespan_phases.pystill passes (no new phase)Related to #4674
Related to #4671
🤖 Generated with Claude Code