Skip to content

feat(backend): event-loop probe names what blocked a worker (#4674) - #4677

Merged
vybe merged 8 commits into
devfrom
fix/4674-loop-stall-probe
Nov 21, 2026
Merged

vybe merged 8 commits into
devfrom
fix/4674-loop-stall-probe

Conversation

@dolho

@dolho dolho commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The "measure first" step of #4674, and the instrument that attributes the minute-mark stall in #4671.

#4671 measured /health over 150 ms in 24 of 1,500 samples, worst 1.5 s, with nothing in the logs to say why. /health does 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.py

Runs in every worker with no leader lease, by design: a worker can only measure its own loop. EVENT_LOOP_PROBE_ENABLED=false turns it off.

Worker count. --workers ${BACKEND_WORKERS:-2} in docker-compose.prod.yml and docker-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:

Key Default What it does
EVENT_LOOP_PROBE_ENABLED true turns the event-loop stall probe on or off
EVENT_LOOP_STALL_THRESHOLD_MS 150 loop silence (ms) that logs event loop blocked with the stack
LOOP_TICK_WARN_MS 250 background-loop cycle time (ms) that logs loop_tick_slow
BACKEND_WORKERS 2 uvicorn worker count (prod and hosted compose only)

Section added by the merge train (2026-11-21) so /release collects 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:

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 wiring
  • tests/unit/test_1028_lifespan_phases.py still passes (no new phase)
  • 72 related unit files (heartbeat, operator-queue poller, monitoring, sync health, telemetry) pass locally
  • CI

Related to #4674
Related to #4671

🤖 Generated with Claude Code

dolho and others added 3 commits November 20, 2026 11:54
#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]>
dolho and others added 3 commits November 20, 2026 13:05
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]>
@dolho

dolho commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Test evidence

Run 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:

event loop blocked 208 ms pid=82 at services/docker_service.py:239 in list_all_agents_fast
   <- heartbeat_service.py:297 _list_agent_names <- :344 process_watch_tick <- :405 run_heartbeat_watch_loop
event loop blocked 190 ms pid=42 at dependencies.py:278 in verify_password
   <- dependencies.py:303 authenticate_user <- routers/auth.py:403 login <- :501 login_api

The first one lines up with an outside measurement: /health sampled every 80 ms for 150 s had exactly one sample over 150 ms (236 ms), in the same second as that line. Both are fixed in #4682; with that applied the same sample had none, and the probe logged nothing.

GET /api/telemetry/host → backend on that instance:

event_loop: {pid: 8, lag_ms: 19.8, max_lag_ms_60s: 158.9, stalls_10m: 1, worst_stall_ms_10m: 158.9, stall_threshold_ms: 150}
loops: capacity_maintenance max 17.6 ms · heartbeat_watch max 62.6 ms · loop_due_sweep max 1.8 ms · sync_health max 3.9 ms · operator_queue_sync max 3084.7 ms

operator_queue_sync ticks took 2.5–5 s of wall time. The probe did not flag them as blocking the loop, so that is awaited time, not a stall — but it is as long as the loop's own 5 s interval.

Isolated rig (fresh PostgreSQL, seeded): 16 probed responses identical to dev; the probe caught a 144 ms block at boot in cleanup_service._guard_allows → retention_guard.note_allowed → platform_alerts.clear.

Three defects of the probe itself, found by running it and fixed here:

  • a 159 ms block against the 150 ms threshold was reported as "stack not captured" — the stack is now taken at half the threshold;
  • a sync HTTP call was reported as 12 frames of urllib3 / http.client with Trinity's caller cut off — the stack is now 40 frames deep;
  • the default threshold was 250 ms while the issues measure /health against 150 ms — now 150.

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]>
@vybe

vybe commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

merge-train (2026-11-21): on this train. Validated at d55d9e7e1: no critical findings. The stack snapshot logs only file:line in function (a f_locals mutation is caught by a test), shutdown joins the daemon thread, and the probe adds little load. /cso --diff found nothing beyond the note below.

Pushed / changed, mechanical only:

  • 37e156004 merges dev and rebuilds tests/registry.json. No code changed.
  • The PR body: a Release note: new env keys table (EVENT_LOOP_PROBE_ENABLED, EVENT_LOOP_STALL_THRESHOLD_MS, LOOP_TICK_WARN_MS, BACKEND_WORKERS) so /release collects them, and three corrections: the watch thread wakes every min(50 ms, threshold/6), the stack is taken at half the threshold (since 4049e97), and the test file has 37 tests, not 40.

Non-blocking, for you to decide:

  1. The start wiring is pinned by source text only (test_4674_loop_health.py:406-409 reads main.py): pass # loop_health.start() and if False: loop_health.start() both stay green, and no test calls the telemetry endpoint that returns loop_health.snapshot().
  2. GET /api/telemetry/host is get_current_user-gated, so any signed-in user now also sees worker pids and loop timings. That endpoint already shows host CPU, memory and disk, so this adds little, but it is a widening.

#4682 is not on this train; see the note there.

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merge-train: batch validated on train/20261121-1212 (#4705)

@vybe
vybe merged commit 71a348c into dev Nov 21, 2026
25 checks passed
vybe pushed a commit that referenced this pull request Nov 21, 2026
…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]>
vybe pushed a commit that referenced this pull request Nov 23, 2026
)

* 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]>
vybe pushed a commit that referenced this pull request Nov 24, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants