Skip to content

test(backend): ratchet on blocking calls inside async def (#4674) - #4680

Merged
vybe merged 8 commits into
devfrom
refactor/4674-sync-on-loop-ratchet
Nov 23, 2026
Merged

vybe merged 8 commits into
devfrom
refactor/4674-sync-on-loop-ratchet

Conversation

@dolho

@dolho dolho commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Summary

The guard AC of #4674: a CI check that counts async def functions calling the sync db layer or Docker helpers directly, against a baseline that may only shrink.

Merge order: this one last. The baseline pins per-file counts on today's dev. #4676, #4677 and #4679 add or move a few calls in async functions, so whichever lands second needs python scripts/ci/check_sync_on_loop.py --write re-run. I will rebase and regenerate this branch once those are in.

What it does

scripts/ci/check_sync_on_loop.py parses src/backend (never imports it) and counts, per file, calls written directly inside an async def to:

  • the sync db layer — db.x(), core_db.x(), _db.x(), deps.db.x()
  • Docker helpers — get_agent_container, list_all_agents_fast, agent_container_states
  • time.sleep, subprocess.run, requests.*
  • one of the same module's plain defs that makes such a call (how the heartbeat loop reaches its Docker listing)

Not counted: plain def handlers (threadpool), nested defs and lambdas, and the arguments of asyncio.to_thread / run_in_executor / run_in_threadpool.

Against scripts/ci/sync_on_loop_baseline.json:

  • a file may not exceed its entry;
  • a file with no entry starts at zero;
  • an entry above reality fails too, so a fix has to lower the baseline.

Today's numbers

1,911 call sites in 831 async functions across 194 files: 1,363 direct db, 386 through a module's own sync function, 161 Docker, 1 requests. The issue's "about 390 handlers" counted route handlers only; this also counts services and loops.

These are candidates, not confirmed stalls: an indexed read counts the same as a fleet-wide Docker listing. The probe in #4677 says which ones actually block a worker.

Limits

  • Sync Redis clients are not detected (no reliable name to match).
  • Calls into another module's sync function are not followed.
  • The enterprise submodule and Alembic revisions are out of scope.
  • Like the raw-color ratchet, the baseline file will conflict between PRs that touch async code; the fix is to regenerate.

Test plan

  • tests/unit/test_4674_sync_on_loop_ratchet.py (28): what counts, what does not, the compare rules, the two known offenders (heartbeat_service.run_heartbeat_watch_loop, dependencies.py), and the ratchet on the live tree
  • CI

Related to #4674

🤖 Generated with Claude Code

dolho and others added 2 commits November 20, 2026 12:51
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]>
…move (#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]>
@dolho

dolho commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Test evidence

This PR changes no runtime code, so there is nothing to measure on an instance; the evidence is what the scanner finds and whether it is right.

  • On dev at the time of writing: 1,911 call sites in 831 async functions across 194 files.
  • The two blocks later measured on a live instance are both in its output. The probe in feat(backend): event-loop probe names what blocked a worker (#4674) #4677 attributed a 208 ms block to heartbeat_service.run_heartbeat_watch_loop (via process_watch_tick → list_all_agents_fast) and ~190 ms per login to bcrypt under routers/auth.py::login. The scanner lists the first as via:docker; the second it does not catch — authenticate_user lives in another module, and calls across modules are not followed (stated under Limits).
  • Review fix pushed: one test pinned those offenders by name and would have failed on the fix (fix(backend): the two loop blocks the probe measured run in a thread (#4674) #4682). It now asserts only that both families are found.

Merge order still applies: #4676, #4677, #4679 and #4682 all change per-file counts, so this branch needs python scripts/ci/check_sync_on_loop.py --write re-run on top of whatever has merged. It should go last.

dolho and others added 2 commits November 20, 2026 13:29
…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]>
@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: bbeceb3770c1ec98e2f21580da8125c2a64c986d).

trinity-ability and others added 2 commits November 21, 2026 13:02
…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

vybe commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

merge-train (2026-11-21): merging last, after #4676, #4679 and #4677. Validated at ba290f8ca: READY. Adding a call, adding a new file and removing a call each turn the ratchet red with a clear message, and the scanner walks src/backend with rglob.

Pushed to this branch, mechanical:

Non-blocking, for a follow-up:

  1. --write absorbs growth without saying so. main() calls write_baseline(current) with no comparison, so a regeneration can hide new blocking calls, and only the JSON diff shows them. This train only caught them by running the check before --write. Refusing a per-file increase without --allow-growth, or at least printing the GREW lines, would close that.
  2. Aliased db imports are not counted: from database import db as platform_db, db_ops, and the portal's sync portal_db. Counting them finds about 10 more call sites today, and re-aliasing db hides a call from the guard.
  3. The docstring says BLOCKING is "shared with /code-health", but nothing references it there.

vybe added a commit that referenced this pull request Nov 22, 2026
…4281) — mechanical, per the merge-train note on the PR

The two db.get_schedule calls in the new async take_over_schedule route move to
asyncio.to_thread, so #4674's sync-on-loop ratchet (#4680) holds on schedules.py
(40 -> 38, the baseline) once both PRs are on dev.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
dolho and others added 2 commits November 23, 2026 10:28
)

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

dolho commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Follow-ups 1 and 3 done (b9a1ceef3)

  • --write no longer absorbs growth. It prints each file whose count grew and writes nothing unless --allow-growth is passed. A paydown is written as before. Five tests cover it.
  • The docstring no longer claims a /code-health consumer.
  • dev is merged in; the baseline still holds at 1919 candidates in 194 files.

Not done: counting aliased db imports (follow-up 2). It changes the counts, so it is better as its own change.

Merge order: after #4682. That PR takes heartbeat_service.py from 1 to 0, so this baseline needs one regeneration once it lands.

vybe added a commit that referenced this pull request Nov 23, 2026
… take it over, and a restricted run is named, marked and alerted (#4281) (#4648)

* fix(schedules): a schedule says what tier its runs get, the owner can take it over, and a restricted run is named, marked and alerted (#4281)

A schedule created by someone who is neither an admin nor the agent's
owner runs every time as a shared person: no shell, no owner-added MCP
servers. Nothing said so, and the run still ended `success`.

- Every schedule read (list, get, create, PUT, enable, disable and
  GET /api/ops/schedules) carries runs_as, runs_as_reason,
  created_by_you, created_by and can_take_over, from one rule,
  turn_tier_service.schedule_run_tier, which turn_actor also reads.
- The turn-tier answer names the cause, schedule, creator and remedy,
  and the hook and the Gemini/Codex refusals say the run is a scheduled
  task, not a chat.
- Each restricted schedule run records turn_integrity.restricted_turn;
  one schedule_runs_restricted operator-queue row per agent and creator.
- POST /api/agents/{name}/schedules/{id}/take-over lets the owner or an
  admin adopt the schedule in place, human-only.
- A shared-person schedule is refused at create and enable on Gemini and
  Codex agents (409 schedule_cannot_run_for_creator_on_runtime).
- The Schedules tab shows the run tier and the take-over review; the
  Tasks list and execution page mark a restricted run.

No schema change.

* test(schedules): the run-tier change holds on today's dev (#4281)

- The frozen turn_actor matrix pins the project_steward trigger, which
  dev added to OWNER_CONFIGURED_TRIGGERS (trinity-enterprise#1236).
- The operator-queue package's __init__.py stays at 800 lines with the
  schedule-restricted- prefix in its three tuples.
- The take-over race tests patch the module the live db method resolves
  its globals in, so they still fire after a test that evicts
  sys.modules entries (test_1595 ran first: 2 failed, now 72 passed).

* test(schedules): a continuation of a restricted schedule run names the schedule and is stamped (#4281)

A continuation turn (caller_wake, operator_response, operator_ending,
skill_gate) is rated as the turn it continues (trinity-enterprise#1225).
When that turn is a share holder's schedule run, the turn-tier answer
must carry the same cause, schedule, creator and remedy, and the
continuation's run must record restricted_turn. Red: the answer's cause
is null and the run carries no stamp.

* fix(schedules): a continuation of a restricted schedule run follows the run it continues (#4281)

trinity-enterprise#1225 rates a continuation turn (caller_wake,
operator_response, operator_ending, skill_gate) as the turn it
continues, but the turn-tier answer's schedule fields and the run's
restricted_turn stamp read the continuation row itself. Such a turn got
the old "shared with" refusal text and no stamp.

turn_tier_service.rated_turn returns the row the chain leads to, the
same chain _rate follows; run_schedule and turn_schedule_detail read
it, and run_restriction names that row's schedule. A link that cannot be
followed names no schedule, as before.

* docs(skills): the skill gate's log is container-local, not collected by Vector (#4281)

The _log docstring said /logs/guardrails.jsonl reaches Vector. Vector's
only source is docker_logs (container stdout and stderr), and /logs is not
mounted out of the agent container, so nothing collects the file.

* docs(schedules): the run-tier row in the feature-flows index; the #4281 docs and comments describe behaviour only (#4281)

- feature-flows.md gets a row for the schedule run tier, take-over and
  the restricted-run marker and alert.
- Requirement status for §2.12.1 moves to implemented.
- Docs, comments, test docstrings and registry descriptions drop
  cross-references that only made sense while the change was in
  progress, and the scheduling flow drops a "not yet wired" note the
  take-over write already covers. No behaviour change.

* fix(schedules): a schedule row's action icons wrap below its text when both don't fit (#4281)

The row's text column can't be narrower than its widest unbreakable piece,
and the "Runs without shell" badge never wraps. In DejaVu Sans, the CI
runner's sans-serif, the badge is 131px. At 390px in light mode, Linux
Chromium's 15px scrollbar leaves 109px beside the action icons, so the
column held its 131px and pushed Delete 5px past the card. Dark mode's
8px scrollbar left just enough room, and macOS (SF, overlay scrollbars)
passed, which is why only the light run failed.

The row now wraps: the icons stay beside the text while both fit and
move onto their own line, right-aligned, when they don't. The decision
follows the content's width, not a breakpoint, so it holds at any
width and for any font. A name with no break opportunity breaks
anywhere instead of holding the column open.

The narrow-row spec now also covers 320px and a long unbroken name, and
checks that each row's name stays inside the row. Before this change it
fails on macOS as well as Linux.

* fix(schedules): a refused toggle, delete or run says the server's reason, not 'try again' (#4281)

A named refusal ({code, message}) is the server declining on purpose, such
as the 409 for a schedule whose runs this agent's runtime cannot give, so
retrying cannot succeed. The row's error bar now leads with the refusal's
own message. Failures with no named refusal (network, 5xx) keep the
'Nothing was changed - try again' headline.

* merge-train: take-over route reads the schedule off the event loop (#4281) — mechanical, per the merge-train note on the PR

The two db.get_schedule calls in the new async take_over_schedule route move to
asyncio.to_thread, so #4674's sync-on-loop ratchet (#4680) holds on schedules.py
(40 -> 38, the baseline) once both PRs are on dev.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Eugene Vyborov <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>

@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/20261122-1848 (#4722); delta b9a1cee (--write refuses growth) re-checked against dev: ratchet holds, 33 passed

@vybe
vybe merged commit d481847 into dev Nov 23, 2026
23 checks passed
dolho added a commit that referenced this pull request Nov 23, 2026
The sync-on-loop ratchet (#4680, now on dev) counted six blocking calls
this PR added inside async def: the delegating-turn and reply-thread reads
in _post_wake_reply and _claimed_wake, the chat-message write in
post_platform_turn_reply and the execution/session link in
persist_chat_session. Each now hops to a thread; the ratchet holds at its
baseline with no entry raised.

test_4536_wake_window steps the wake window one loop tick at a time, so its
fixture runs that read inline: the choreography it pins is the window's.

Also repoints agentDetailTalkDoor.spec.js at utils/chatSessionMerge.js,
where the row mapping it pins now lives.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
vybe pushed a commit that referenced this pull request Nov 24, 2026
…ies into it (#4537) (#4606)

* fix(wake): a wake turn knows the conversation that delegated and replies into it (#4537)

A person asks an agent in chat to "ask X and tell me what it said". The
agent delegates asynchronously and replies that it will report back. The
wake turn then ran cut off from that conversation at both ends: its frame
carried only the callee's ending, so the agent had lost the request and
its own plan, and its reply stayed on the execution row, so the person
never saw it.

The wake frame now quotes the delegating turn, read off the link the
callee row already records (continues_execution_id): what the agent was
asked and what it replied then. A wake that delegates again links the
next callee to the wake itself, so the request is read from the head of
that chain and the plan from the turn that delegated last. Every row on
the way must be the delegator's own; the text is sanitized and capped.

When the head of the chain is a person's turn in an agent chat thread,
the wake's reply is written into that thread as the agent's next message.
It is written at the wake row's own terminal, which every terminal writer
reaches, once per wake, on SUCCESS only, and announced with the existing
thin chat_response_ready trigger. The open ChatPanel refetches its
session in place on that trigger.

The Chat tab sends /task, which never named its thread on the row, so
persist_chat_session now does, after its own messages are saved.

Workspace, Slack and Telegram conversations are unchanged: a delegated
run already reports into those through its inherited channel context.

Fixes #4537

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

* fix(wake): scrub staged secrets when posting a wake reply to chat (#4537)

The new chat writer copied the persisted row's response without calling the
runtime secret-scrub seam, which the ent#279 parity guard requires of every
message-table writer.

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

* fix(chat): a wake reply reaches the open Chat tab mid-turn and after a failed turn (#4537)

Review of the frontend half found the reply still lost on two paths, and
nothing executing any of it:

- A reply that landed while a turn was in flight was skipped, and a turn's
  end never refetches messages. The re-read now waits for the turn and runs
  when it ends.
- 'Only when it grew' compared lengths. After a failed or cancelled turn the
  panel holds a message the server never saved, the counts are equal, and
  the reply was not shown. utils/chatSessionMerge decides by identity: a
  stored row by its id, a row the panel pushed itself by role and text.
  Rows only the screen has stay where they were.
- A mounted spec drives the whole path: the chat_response_ready frame on
  /ws, the store, the panel's watcher, the session re-read and the merge.

Docs: the user docs for wake-on-ending and report-back describe the reply
landing in the Chat tab.

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

* fix(wake): the wake's new database calls run off the event loop (#4537)

The sync-on-loop ratchet (#4680, now on dev) counted six blocking calls
this PR added inside async def: the delegating-turn and reply-thread reads
in _post_wake_reply and _claimed_wake, the chat-message write in
post_platform_turn_reply and the execution/session link in
persist_chat_session. Each now hops to a thread; the ratchet holds at its
baseline with no entry raised.

test_4536_wake_window steps the wake window one loop tick at a time, so its
fixture runs that read inline: the choreography it pins is the window's.

Also repoints agentDetailTalkDoor.spec.js at utils/chatSessionMerge.js,
where the row mapping it pins now lives.

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

---------

Co-authored-by: Claude Fable 5.2 <[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