Skip to content

refactor(backend): list reads stop growing with rows and agents (#4672) - #4679

Merged
vybe merged 6 commits into
devfrom
refactor/4672-list-query-counts
Nov 21, 2026
Merged

vybe merged 6 commits into
devfrom
refactor/4672-list-query-counts

Conversation

@dolho

@dolho dolho commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Summary

Ranks 1–9 of #4672. Stacked on #4676 (the memo and the query counter): until that merges, this diff also shows its two commits. Review the last commit here.

Each list is fixed the same way: the access predicate is unchanged and still decides; it is asked inside one request_memo.scope() after one batch read per kind. No caller re-implements membership.

Rank Endpoint What repeated Now
1 client-portal/my-agents may_manage_canvases per agent: the caller's user row + an owner row 3 reads for any roster (canvas_managers)
2 GET /api/operator-queue per gate row: its record, each approver's name, access to two agents one read per kind (skill_gate_service.prefetch_cards, shared with asks)
3 GET /api/ops/fleet/status one agent call after another, unbounded; an owner read per agent concurrent, 3 s bound per agent, 10 at a time; one owners read
4 GET /api/agents/{name}/loops one runs query per loop (up to 200) 2 queries
5 GET /api/agents/autonomy-status 2–5 access queries per agent owners and shares read once
6 GET /api/agents/context-stats TTL 15 s = the poll interval, so it never hit; only admins wrote it TTL 20 s; a non-admin keeps their own entry. Cached rows are still filtered to current access
7 client-portal/work, /work/activity a timeout read per agent; an execution read per live turn one read each
8 GET /api/agents/{name}/schedules the caller's tier per schedule one memo scope
9 GET /api/evaluations owner check per distinct agent owners read once

New db batch readers (get_execution_timeouts, get_executions_by_ids, list_loop_runs_for_loops) each return exactly what the per-item read returns.

Left as they are, with the reason

  • Rank 7, _chat_is_callers: one session read per requested agent, but a chat id is only sent for a 1:1 (a room passes none), so N is 1.
  • Rank 5, agent-key callers: agent_may_reach still reads one permission edge per agent for an agent principal. The polls are a person's; a person's path is flat.
  • Rank 10 (access requests), 11 (public links, public sessions), 12 (ops/auth-report): opened on demand, not polled; 11 is capped at 20 and 12 is admin-only low traffic. Not touched here.
  • Rank 13 (/api/systems): not read end to end yet — neither confirmed nor dismissed.
  • The handlers are still async def with sync DB calls; that is refactor(backend): sync DB, Redis and Docker calls on the event loop — background loops and about 390 async handlers block the worker #4674.

Test plan

  • tests/unit/test_4672_list_query_counts.py (24): each read at two sizes with equal query counts, and each answer equal to the unbatched per-item answer (revoked share, share-holder-only rows, fail-closed paths)
  • tests/unit/test_4672_fleet_reads.py (13): one slow agent cannot hold fleet status; the context-stats cache never widens access, never crosses callers, non-admins never write the fleet entry
  • Gate, loop and autonomy test files locally (682 pass; 1 failure is a missing package in my local env)
  • CI full unit suite — I did not run it locally

Related to #4672

🤖 Generated with Claude Code

dolho and others added 3 commits November 20, 2026 11:47
One GET /api/enterprise/client-portal/asks took 0.45 s for 63 rows on a
hosted instance. Reproduced on a seeded SQLite (65 rows over 13 agents):
276 queries, 319 ms. The per-row and per-agent sources:

- the roster re-check ran both roster queries once per agent
  (_on_roster -> agent_on_roster -> roster_agent_names);
- _platform_username read the viewer's own users row once per row;
- is_aged read the aging-hours setting once per row (not named in the
  issue: 65 of the 276 queries);
- a gate approval read its record, the viewer's user row and their
  access to two agents per row (card_view, _openable_run);
- a replaced / replacing ask read the row it links to, per row;
- a shared ask someone else answered read that person's users row.

After: 12 queries, 19 ms, and the count is the same at any size.

The fix is the shared one #4672 asks for, used here first:

- utils/request_memo.py: inside a scope() a @memoized leaf read runs
  once per distinct arguments; outside one it is the plain function.
  Failures are never remembered, the key carries every argument, and
  the memo is dropped when the scope exits.
- db batch readers (get_users_by_emails, get_agent_owners,
  agents_shared_with_user, get_gate_requests,
  get_operator_queue_items_by_ids) answer the per-item read for the
  rest of the scope, so can_user_access_agent, card_view and _project
  are unchanged and still decide everything.
- list_asks_page runs in one scope and prefetches once per kind.

Visibility is unchanged and pinned: _on_roster is still asked per agent
and fails closed per agent, a revoked share hides only that agent's
asks, and an unreadable roster or queue is still AsksUnavailable (503),
never an empty list.

tests/query_counter.py is the reusable helper (#4672's guard AC): it
counts the statements a block runs on the active engine.

Related to #4671
Related to #4672

Co-Authored-By: Claude Fable 5.2 <[email protected]>
CI's regression diff named two guards the first commit tripped:

- test_3785: a submodule of operator_queue_service may import nothing
  the package __init__ has not imported first, and __init__ is at its
  800-line cap. So the aging-hours memo moves one layer down, onto
  db.get_setting_value — the read `aging_hours` makes — and rows.py is
  back to its original imports. Same single query per request.
- test_ent715: every DatabaseManager accessor over operator-queue rows
  must be classified. get_operator_queue_items_by_ids is a row accessor
  (the batch form of get_operator_queue_item) and its one reader,
  asks `_prefetch`, is `internal`: the rows are returned to nobody
  there; what leaves is still only what `_linked_request_id` decides.

Related to #4671

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The class #4671 found in `asks`, in the other hot lists. Each is fixed
the same way: the predicate is unchanged and still decides; it is asked
inside one request_memo.scope() after one batch read per kind.

- Rank 1, Workspace roster: `may_manage_canvases` per agent re-read the
  caller's user row and one owner row each (`canvas_managers`).
- Rank 2, operator queue: a gate approval card read its record, each
  approver's name and the viewer's access to two agents, per row.
  `skill_gate_service.prefetch_cards` is shared with the asks list.
- Rank 3, /api/ops/fleet/status: agents are read concurrently, each
  under a 3 s bound, 10 at a time; owners are one read.
- Rank 4, loops list: one runs query for the page, not one per loop.
- Rank 5, autonomy-status: owners and the caller's shares read once.
- Rank 6, context-stats: the cache TTL (20 s) outlives the 15 s poll,
  and a non-admin keeps their own entry instead of fanning out on
  every poll. Cached rows are still filtered to current access.
- Rank 7, Work feed: one timeout read for the agents, one execution
  read for the live turns on shared agents.
- Rank 8, schedules list and rank 9, evaluations: one memo scope.

New db batch readers: get_execution_timeouts, get_executions_by_ids,
list_loop_runs_for_loops. Each returns what its per-item twin returns.

Stacked on #4676 (the memo and the query counter).

Related to #4672

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

dolho commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Test evidence

Isolated rig — fresh PostgreSQL built by dev's migrations, seeded with 14 agents, 65 queue rows (13 gate approvals), 40 loops with 3 runs each and 39 executions. dev and this branch side by side, 7 calls each after a warm-up, best time:

Endpoint dev This PR
GET /api/operator-queue?limit=200 (share holder) 47 ms 17 ms
GET /api/operator-queue?limit=200 (admin) 30 ms 12 ms
GET /api/agents/autonomy-status (share holder) 19 ms 4 ms
GET …/client-portal/my-agents 26 ms 13 ms
GET /api/agents/{name}/loops?limit=200 (40 loops) 17 ms 9 ms
GET …/client-portal/work (13 agents) 16 ms 10 ms
GET …/client-portal/asks?include_ended=true (from #4676) 104 ms 24 ms

Responses are identical: 16 probed responses compared body-for-body with dev (clock fields ignored): 16 identical, 0 different.

Live instance (local dev instance, 55 agent containers, 3 running):

  • GET /api/ops/fleet/status → 200 in 70 ms, context present for the agents that answered, absent for the one that did not;
  • GET /api/agents/context-stats → 200, all agents listed with the right active/offline state;
  • the roster returned can_manage_canvases: true for the owner's agents.

Not verified live: fleet status with a deliberately wedged agent (unit-tested with a 5 s sleeper against a 0.15 s bound), and the per-caller context-stats cache with a real non-admin account (unit-tested).

A bug of mine caught before the first push: a new helper shadowed the existing skill_gate_service._approvers; renamed to _card_approvers.

trinity-ability and others added 2 commits November 21, 2026 11:43
…cal, per the merge-train note on the PR

Co-Authored-By: Claude Opus 5.5 <[email protected]>
….json) into #4679 — mechanical

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, after #4676. Validated at 849f99551 (last commit only): READY, no critical findings. Access predicates still decide every row, the context-stats cache key includes agent_name / connector_agent / mcp_scope, and no scope wraps a write.

Pushed to this branch, mechanical only: b9b050a9a merges #4676's updated head, which carries dev and the rebuilt tests/registry.json. 186 tests pass on the merged tree. No code changed.

Non-blocking, for a follow-up:

  1. prefetch_cards (services/skill_gate_service.py) can lose its owners, shares or approvers batch line with every test green; the gate-card tests use a fixed source agent and approver pair.
  2. Nothing pins the context-stats TTL: setting it back to 15 stays green.
  3. test_4672_fleet_reads.py:199 asserts elapsed < 0.12s on wall-clock time and failed once under load during validation; asserting peak > 1 alone would not flake.
  4. /api/ops/fleet/health (named in refactor(backend): per-row lookups in list endpoints — uncached user, owner and access helpers make query counts grow with rows and agents #4672 rank 3 next to /fleet/status) is untouched and not in the "left as they are" list, so refactor(backend): per-row lookups in list endpoints — uncached user, owner and access helpers make query counts grow with rows and agents #4672 stays open for it and for rank 13.

@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 0b40b09 into dev Nov 21, 2026
26 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]>
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