Skip to content

fix(workspace): asks list runs a fixed number of queries (#4671) - #4676

Merged
vybe merged 3 commits into
devfrom
fix/4671-asks-query-count
Nov 21, 2026
Merged

vybe merged 3 commits into
devfrom
fix/4671-asks-query-count

Conversation

@dolho

@dolho dolho commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Summary

Part 1 of #4671 (the asks lookups), and the shared memo + query-count helper #4672 asks for.

GET /api/enterprise/client-portal/asks ran a number of queries that grew with the rows and agents it listed. Reproduced on a seeded SQLite, 65 rows over 13 agents (the report had 63 rows):

Queries Best of 15
Before 276 (users 156, system_settings 65, agent_ownership 39, operator_queue 29, agent_sharing 26, skill_gate_requests 13) 319 ms
After 12 (users 5, operator_queue 4, agent_ownership 3, agent_sharing 2, skill_gate_requests 1, system_settings 1) 19 ms

The count is now the same at any size.

Where the lookups came from (AC: source identified)

Query log of one list_asks_page call, by source:

Source Cost
_on_roster → agent_on_roster → roster_agent_names 2 roster queries per agent
_platform_username → get_user_by_email (the viewer's own row) 1 per row
is_aged → aging_hours → get_setting_value 1 per row — not named in the issue, 65 of the 276
card_view: get_gate_request, then _openable_run ×2 → get_user_by_username + can_user_access_agent 5–9 per gate row
_linked_request_id → get_operator_queue_item 1 per replaced / replacing row
_answered_by → get_user_by_email 1 per shared row someone else answered

The fix

  • 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.
  • Batch readers in db/ (get_users_by_emails, get_agent_owners, agents_shared_with_user, get_gate_requests, get_operator_queue_items_by_ids) — one query each, and each answers 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; membership is not re-implemented in the caller.
  • list_asks_page runs in one scope and prefetches once per kind. The prefetch is best-effort: if it fails, the per-row reads run as before.
  • tests/query_counter.py — count_queries() counts the statements a block runs on the active engine, with a per-table tally for the failure message. Reusable for refactor(backend): per-row lookups in list endpoints — uncached user, owner and access helpers make query counts grow with rows and agents #4672's endpoints.

Visibility is unchanged

Pinned in test_4671_asks_query_count.py:

  • every listed row equals the same row projected alone, outside any scope;
  • _on_roster is still asked per agent; a revoked share hides only that agent's asks;
  • a run link still needs access to that run's own agent;
  • an unreadable roster or queue is still AsksUnavailable (503), never an empty list.

test_4671_request_memo.py pins the memo contract (nothing cached outside a scope, nothing outlives one, no cross-principal answer, failures not remembered) and that each batch reader returns exactly what its per-item twin returns.

Not in this PR

Test plan

  • tests/unit/test_4671_asks_query_count.py (8) and tests/unit/test_4671_request_memo.py (21) pass locally
  • CI unit suite

Related to #4671
Related to #4672

🤖 Generated with Claude Code

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

dolho commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Test evidence

Isolated rig — a fresh PostgreSQL built by dev's own migrations, seeded to the reported volume (65 asks over 13 agents, with gate approvals, replaced asks and shared asks answered by a co-addressee). dev and this branch ran side by side against the same database; each endpoint was called 7 times after a warm-up.

Endpoint dev (best) This PR (best)
GET …/client-portal/asks?include_ended=true (share holder, 65 rows) 104 ms 22 ms
GET …/client-portal/asks (pending only) 65 ms 16 ms
GET …/client-portal/asks?include_ended=true (owner) 44 ms 14 ms

Responses are identical. 16 probed responses (asks, roster, operator queue, loops, autonomy-status, work, as share holder / owner / admin) were compared body-for-body between dev and this branch, ignoring clock fields: 16 identical, 0 different.

Local SQLite (the unit harness, same seed shape): 276 queries → 12 for one list_asks_page call; the count is equal at two sizes.

Live instance: the branch also ran on a local dev instance with real agents (as part of a combined build of this PR set); the asks, roster and operator-queue endpoints returned 200 with the same shapes.

Not verified: the "under 100 ms for ~60 rows" criterion on the hosted instance that reported the problem. The rig is local Postgres on a developer machine.

Review fix pushed after the first CI run: two structural guards (test_3785, test_ent715) — see the second commit.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
vybe pushed a commit that referenced this pull request Nov 21, 2026
….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. Validated at 4ab4c2e3d: READY, no critical findings. The tests count real SQL against a real DB, and removing the scope, the _prefetch call or the roster memo turns them red.

Pushed to this branch, mechanical only: 21ef3041a merges dev and rebuilds tests/registry.json from the merge stages (dev's entries plus this PR's two). No code changed.

Non-blocking, for a follow-up: deleting db.get_agent_owners(run_agents) or db.agents_shared_with_user(run_agents, username) from _prefetch (client_portal/asks/service.py) leaves all 29 tests green, because every gate row in test_4671_asks_query_count.py uses source_agent=self.agents[0]. Giving each gate row its own source agent would pin both lines.

The body says "Related to" #4671/#4672 on purpose (part 1 of each), so the train leaves the issues open.

@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 2c49e56 into dev Nov 21, 2026
27 checks passed
vybe pushed a commit that referenced this pull request Nov 21, 2026
vybe pushed a commit that referenced this pull request Nov 21, 2026
… (#4679)

* fix(workspace): asks list runs a fixed number of queries (#4671)

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

* fix(workspace): keep two structural guards green (#4671)

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

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

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

---------

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