Skip to content

fix(backend): the two loop blocks the probe measured run in a thread (#4674) - #4682

Merged
vybe merged 15 commits into
devfrom
fix/4674-measured-loop-blocks
Nov 24, 2026
Merged

vybe merged 15 commits into
devfrom
fix/4674-measured-loop-blocks

Conversation

@dolho

@dolho dolho commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

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:

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
  • Heartbeat watch. Every 5 s, in every worker, the tick lists every agent container and reads Redis synchronously. A /health request sent the same second as the 208 ms block took 236 ms.
  • Login. bcrypt is ~200 ms of CPU by design; verified on the loop it stalled the worker for every login, successful or not.

Fix

  • The heartbeat tick runs on the Docker executor (docker_utils.run_blocking); its alerts are still awaited on the loop.
  • authenticate_user runs in a thread, at most 4 at once per worker. The audit record and the 401 are unchanged.
  • Both login limits hold under concurrency, which they did before only because bcrypt held the event loop:

Measured on the same instance

/health every 80 ms for 150 s:

samples p99 max over 150 ms probe lines
Before 1,779 67 ms 236 ms 1 heartbeat 208 ms; ~190 ms on each login
After (19 logins sent during the sample) 1,796 8.4 ms 106 ms 0 none

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 audited
  • Heartbeat and login test files locally: same results with and without the change
  • CI

Related to #4674
Related to #4671

🤖 Generated with Claude Code

dolho and others added 7 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]>
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]>
@dolho

dolho commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Test evidence

Measured on a local dev instance (55 agent containers, 3 running), before and after this change, with the probe from #4677 running in both.

/health every 80 ms for 150 s:

samples p50 p99 max over 150 ms probe lines in the window
Before 1,779 3.1 ms 67 ms 236 ms 1 heartbeat watch 208 ms; ~190 ms on each login
After, with 19 password logins sent during the sample 1,796 3.2 ms 8.4 ms 106 ms 0 none

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.

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

✅ Nightly unit-suite clean when this PR is merged into dev, all 3 seeds (head_sha: e5d37caec1e443800c9ec5aa36d1d33017692443).

@vybe

vybe commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

merge-train (2026-11-21): not on this train. A security finding needs your call on the fix. Validated at b4405e02c (this commit only, on top of #4677).

CRITICAL: concurrent logins bypass the per-account lockout (src/backend/routers/auth.py:406, user = await asyncio.to_thread(authenticate_user, ...)).

  • The limit is checked around :392 (check_login_rate_limit), and the failure is recorded after the await (record_login_attempt). They are separate Redis reads and writes, with nothing atomic between them.
  • Before this PR, check → bcrypt → record had no await between them, so a worker ran them one request at a time and 5 failures per 15 min held.
  • Now every concurrent request passes the check before any failure is recorded.

Reproduced with 40 concurrent auth.login() calls on one account (in-memory Redis, 200 ms fake bcrypt):

  • dev: 5 passwords verified, then 401 ×5 and 429 ×35.
  • This PR: 40 passwords verified, 401 ×40, counter at 40.

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:

  • charge the attempt atomically before verifying: INCR, compare the returned count, clear it on success;
  • or take a per-account lock around check → verify → record.

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 min(32, CPUs+4) at once per worker. A login flood spread over many IPs can occupy those threads and the CPU, and starve other to_thread users. A small semaphore would cap it. Is unbounded parallel bcrypt acceptable?

The heartbeat half (the tick on _docker_executor) looks fine, and the to_thread / run_blocking mutations are each caught. The test_subprocess_pgroup failure on the nightly run is a flake unrelated to this PR: 8/8 alone, and clean across 4 seeds on both this head and dev.

Rides the next train once fixed. #4677 is landing on this one, so this PR's diff will shrink to its own commit.

@vybe vybe added the status-needs-fix PR has an unaddressed review/validation finding; cleared by the author's next push (#2815) label Nov 21, 2026
@github-actions

Copy link
Copy Markdown

⚠️ Live-instance suite skipped — merge conflict against dev.

Resolve by merging dev locally and pushing the result; the next nightly re-tests.

dolho and others added 2 commits November 23, 2026 10:24
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]>
@github-actions github-actions Bot removed the status-needs-fix PR has an unaddressed review/validation finding; cleared by the author's next push (#2815) label Nov 23, 2026
@dolho

dolho commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Lockout finding fixed (e29fc30d8)

Shape chosen: a per-account lock around check → verify → record, not a counter charged before the verify.

  • Why the lock: it restores exactly what dev does (attempts on one account are counted one at a time) and changes nothing for a correct login. Charging before the verify would refuse the sixth of six simultaneous correct logins on one account.
  • Scope: per worker process, the same scope the lockout had before this PR. It is not a cross-worker guarantee, and neither was dev's.
  • Lock table: reference-counted and dropped when the last request for an account leaves, so it does not grow with attacker-chosen usernames.
  • Parallel bcrypt (the WARNING): capped at 4 verifies at once per worker (LOGIN_VERIFY_CONCURRENCY), so a flood over many accounts cannot fill the default thread pool.

Test, as asked: 40 concurrent auth.login() calls on one account against the real limit check and record (fake Redis). On the previous head it verifies 40 passwords; now it verifies 5, with 401 ×5 and 429 ×35. Also covered: account normalisation, other accounts not delayed, the cap of 4, and a correct password clearing the counter.

dev is merged in (cc9033ea3); the diff is now this PR's own four files.

Merge order: this one before #4680. It takes heartbeat_service.py from 1 counted call to 0, and #4680's baseline has to be lowered to match after this lands.

dolho and others added 2 commits November 23, 2026 11:49
…#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]>
@dolho
dolho requested a review from vybe November 23, 2026 20:19
@vybe

vybe commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

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 a73820f35.

The per-account fix from the last round holds: check → verify → record run inside _account_verify_lock, and removing the lock or the semaphore turns tests red.

What is open (src/backend/routers/auth.py, login(), about line 450):

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 login, real check and record, fake Redis), 200 concurrent wrong-password logins from one IP on 200 usernames:

verified 429
dev 30 170
this head 200 0

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: frontend-e2e was skipped on this head (no ui label), and the comment in process_watch_tick still says the 3-miss threshold assumes a single backend process.

Rides the next train once fixed.

@vybe vybe added the status-needs-fix PR has an unaddressed review/validation finding; cleared by the author's next push (#2815) label Nov 24, 2026
dolho and others added 2 commits November 24, 2026 10:09
…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]>
@dolho dolho added the ui PR touches the frontend UI — triggers Playwright e2e tests label Nov 24, 2026
@github-actions github-actions Bot removed the status-needs-fix PR has an unaddressed review/validation finding; cleared by the author's next push (#2815) label Nov 24, 2026
@dolho

dolho commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Per-IP limit fixed (ba715e41c)

Confirmed with your repro in this PR's own rig: 200 concurrent wrong-password logins from one address on 200 usernames verified 200 on the previous head.

Shape chosen: count the verify against its address before it runs, in process. No per-address lock, so a shared NAT is not queued (#591).

  • _admit_ip_verify reads the recorded failures for the address plus the verifies still in flight from it, and refuses with 429 when the sum reaches the limit. There is no await between the read and the increment, so two requests cannot both take the last place.
  • A verify gives its place back after its outcome is recorded, with no await in between. A correct password never becomes a counted failure.
  • Result on the same repro: 30 verified, 401 ×30, 429 ×170, the counter at 30. Same as dev.

Why not the other two shapes: re-checking after the slot is acquired still overshoots by up to the semaphore width, and charging Redis before the verify would count correct logins as failures until they land.

One cost: correct logins in flight also hold a place, so the 31st simultaneous login from one address is refused even if all would succeed. This route is the password login, which only the admin account uses.

New tests (5): the repro above, recorded failures plus in-flight ones, other addresses not held back, correct logins giving their place back, and a verify that raises giving its place back. Without the admission call, three of them fail.

Also done:

  • The process_watch_tick comment now says the tick runs in every worker and what that does to the 3-miss threshold.
  • ui label added so frontend-e2e runs on this head.
  • The body no longer says the rate limit is unchanged; it describes both buckets.

dev is merged in.

…chanical, per the merge-train note on the PR

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@vybe

vybe commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

merge-train note: pushed one commit to this branch, e5d37caec — a merge of dev plus a regenerated scripts/ci/sync_on_loop_baseline.json (python3 scripts/ci/check_sync_on_loop.py --write). The only conflict was that baseline: dev went 1919 → 1921 (#4745), this PR 1919 → 1918; the regenerated total is 1920, i.e. dev minus the heartbeat_service.py entry this PR removes. Nothing else was touched.

Validated at ba715e41c (lane C: /validate-pr, /review, /cso --diff), no criticals. Two low notes for a follow-up, not blocking: a login cancelled mid-verify is never counted and escapes the cap of 4 (routers/auth.py ~341-343, ~511-522; no test); and _ip_verifies_pending is per process, so the per-IP burst bound across 2 workers grows from about 31 to about 60 — the comment "the same scope the lockout had before #4674" is not right for the IP bucket.

vybe pushed a commit that referenced this pull request Nov 24, 2026

@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: validated at e5d37ca; batch gated on Tier 1 (and on train/20261124-1655 for the lane C members)

@vybe
vybe merged commit c1d52af into dev Nov 24, 2026
24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ui PR touches the frontend UI — triggers Playwright e2e tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants