Skip to content

perf(agents): Batch the Conversation loop check when listing child agents - #3271

Merged
BYK merged 2 commits into
mainfrom
perf/child-agents-loop-batch
Nov 12, 2026
Merged

BYK merged 2 commits into
mainfrom
perf/child-agents-loop-batch

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

listChildAgents sets onConversationLoop for each pending, running or paused child. It did that one child at a time:

  • getConversationWorkState read the child's work state;
  • listActiveMailboxTurns called getTurnRecord for each open Turn.

getTurnRecord materializes the Turn: it loads the Turn history from junior_conversation_events and the current history version (a max(...) query), and reads the Conversation and its execution metrics. The loop check uses none of that. It needs only a few fields of the stored Turn cursor.

Change

  • One work-state read for all active children. getConversationWorkStates reads them with getStateValues, which is one mGet on Redis. It parses each record the same way readConversation does, through the new shared conversationFromValue.
  • One cursor read for all open Turns. listActiveMailboxTurnSources reads the Turn summaries of each child, then reads the stored cursors of the open ones with getStoredTurnFields, also one getStateValues read. It returns the Source of each active mailbox Turn and loads no Turn history.
  • Legacy cursors. A cursor with no Source and a surface other than api still loads its Turn with getTurnRecord, because its Actors come from Turn history. This is the legacy branch that the existing TODO already marks for removal.
  • One predicate. listActiveMailboxTurns and the batched read share isOpenTurnSummary and isActiveMailboxTurn, so both apply the same mailbox Turn rule.
  • Same answer. runsOnConversationLoop now takes the pending input and the mailbox Turn Sources as arguments, and its rules are unchanged. A child with no work state still has no pending input. A paused Turn still counts as open.

The batched read doesn't check that a Turn's history still exists, but getTurnRecord does. In listChildAgents this can't change the answer: only a purge deletes Turn history, and a purge deletes the agent invocations of the whole tree in the same transaction, so a purged child is never listed. A comment at the call site says this.

Tests
tests/integration/child-conversation-loop.test.ts, "shows a child as running while its Watch Event waits in the mailbox", now has 2 active children with different loop states:

  • a Task whose Watch Event waits in its mailbox shows running;
  • a sibling Thread with a person's message in its mailbox shows idle, because that input doesn't answer the parent.

The test checks the status of each child by Conversation id. If every active child is forced onto the loop, it fails on the Thread.

Checks

  • tests/integration/api, child-conversation-loop, agent-invocation-* and thread-input*: 89 files, 320 tests, all pass.
  • pnpm typecheck and pnpm lint pass.

via @BYK.

--

View Session [Sentry]

…ents

listChildAgents read the work state and the open mailbox Turns of each
active child one by one. Each open Turn materialized its Turn history,
which the check does not use.

Read the work states and the stored Turn cursors of all active children
in one state read each. Only a legacy cursor with no Source still loads
its Turn, because its Actors come from history. listActiveMailboxTurns
and the batched read share one mailbox Turn predicate.

Co-Authored-By: BYK <[email protected]>
@vercel

vercel Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
junior-docs Ready Ready Preview Nov 12, 2026 4:24pm UTC

Request Review

@github-actions github-actions Bot added the risk: medium PR risk score: medium label Nov 12, 2026
Cap the Turn summary, legacy Turn record and routeChildInput fan-out
with p-limit, and use for-of in getConversationWorkStates.
@BYK
BYK enabled auto-merge (squash) November 12, 2026 16:30
@github-actions

Copy link
Copy Markdown
Contributor

16 screenshot changes — 16 changed · 0 added · 0 removed

Review screenshots in Frameshift

Automation Run Details · Desktop
Automation Run Details · Desktop
Changed
Automation Skill Editor · Desktop
Automation Skill Editor · Desktop
Changed
Automations Runs Filters · Desktop
Automations Runs Filters · Desktop
Changed
Conversation Details Watched Linked Work · Desktop
Conversation Details Watched Linked Work · Desktop
Changed
Conversation Event Log Virtual · Desktop
Conversation Event Log Virtual · Desktop
Changed
Conversation Event Log Virtual · Mobile
Conversation Event Log Virtual · Mobile
Changed
Show 10 more changed screenshots
Conversation Fork Dialog · Desktop
Conversation Fork Dialog · Desktop
Changed
Conversation Fork Dialog · Mobile
Conversation Fork Dialog · Mobile
Changed
Conversation Long Transcript Touch · Mobile
Conversation Long Transcript Touch · Mobile
Changed
Conversation Question Picks And Text · Desktop
Conversation Question Picks And Text · Desktop
Changed
Conversations Pinned · Desktop
Conversations Pinned · Desktop
Changed
Conversations Pinned Light · Desktop
Conversations Pinned Light · Desktop
Changed
Memories · Mobile
Memories · Mobile
Changed
Push Notifications Tip · Desktop
Push Notifications Tip · Desktop
Changed
Push Notifications Tip On · Desktop
Push Notifications Tip On · Desktop
Changed
Settings Mcp · Desktop
Settings Mcp · Desktop
Changed

@BYK
BYK merged commit 2891c5f into main Nov 12, 2026
64 of 66 checks passed
@BYK
BYK deleted the perf/child-agents-loop-batch branch November 12, 2026 16:37
sentry-junior Bot added a commit that referenced this pull request Nov 16, 2026
Reviewers asked for `for...of` over `forEach` in #2921
("for .. of would be better here") and #3271 ("always
prefer for-of over forEach"). Nothing failed, so agents kept copying the
`forEach` sites that were already in the repo.

This turns on `unicorn/no-array-for-each` and converts the 31 existing
calls, including `Headers` and `FormData` iteration. A callback
`return` is now `continue`.

Co-Authored-By: David Cramer <[email protected]>
sentry-junior Bot added a commit that referenced this pull request Nov 16, 2026
Reviewers asked for bounded concurrency on `Promise.all(items.map(fn))`
in #2921 ("May wanna pLimit this?"), #2989
("No pLimit?"), and twice in #3271. The list size sets how
many Slack, GitHub, Postgres, or Redis calls run at once.

`pnpm unbounded-concurrency:check` counts `Promise.all` and
`Promise.allSettled` over `items.map(...)` or `Array.from(...)` per
file in production source. It fails when a file gains one, and names
`pLimit(LIMIT).map(items, fn)` as the fix. The 70 sites that exist today
are in scripts/unbounded-concurrency-baseline.json, which can only shrink.

The six p-limit call sites now use `limit.map`, so the nearest example
is the supported one. The type assertion ratchet and this one share
scripts/source-ratchet.mjs.

Co-Authored-By: David Cramer <[email protected]>
BYK added a commit that referenced this pull request Nov 17, 2026
Turns the perf patterns from #3184,
#2820, #2991, #3271,
#2921 and #3449 into checks that fail
CI, and fixes the code that breaks them. `policies/performance.md` lists
each rule and the check behind it. The DB and request budgets come in a
follow-up PR.

| Rule | Where | Fixed | Left |
| --- | --- | --- | --- |
| `unicorn/no-array-for-each` | root + dashboard | 43 | 0 |
| `query-invalidation/no-broad-query-invalidation` (new, dashboard JS
plugin) | dashboard `src` | 20 calls | 5 disable comments with reasons |
| `junior/bounded-fan-out` (new) | `packages/*/src` | 24 (19 behind
`pLimit`, 5 batched reads) | 13 disable comments naming the cap |
| `no-await-in-loop` | `packages/*/src` | 3 moved to bounded
`Promise.all`, 2 dashboard disables | 467 sites in 137 files, baselined
|

**`query-invalidation/no-broad-query-invalidation`** fails on
`invalidateQueries`, `refetchQueries`, `resetQueries` or `removeQueries`
when the key is missing, a literal of 2 or fewer parts, or a bare prefix
const, unless the call passes `exact: true`. The fixes:
- `invalidateConversationFeeds` replaces each `["dashboard",
"conversations"]` refresh.
- Rename writes the response title into the feeds and does not refetch.
- `reviewItemQueryKey` and `invalidateReviewItemCollections` let Review
item actions write item details from the response and refresh only
count, list and waiting conversations.

**`junior/bounded-fan-out`** flags
`Promise.all`/`allSettled(<list>.map(async …))` unless the callback
calls a `p-limit` limiter. A literal array is not flagged. Fixes use
limits of 5 for provider APIs and 8 for internal storage. Batched fixes
are `readSubscriptions` (one `mGet`) in `chat/events/store.ts` and
`getStateValues` in cache warming. `junior-github` gets a `p-limit`
dependency.

**`no-await-in-loop` uses a baseline** because 467 sites is too many to
triage safely in one PR. Many are intentionally sequential: cursor
pages, ordered writes, rate limits, stop-on-first-failure.
`tools/oxlint/await-in-loop.json` turns the rule off only for the listed
files, and `scripts/await-in-loop-baseline.json` holds their per-file
counts. `pnpm await-in-loop:check` (part of `pnpm lint`) fails when:
- a count goes up,
- a count goes down and the entry is not lowered or removed,
- the two file lists drift.

New files get the rule with no exemption.

**Automations exclusion:** Otto is rewriting this code in
#3570, so it is left alone. In the dashboard,
`pages/automations/**`, `inbox/pages/automations/**` and
`review-desk/inboxQueries.ts` have `no-broad-query-invalidation` and
`no-await-in-loop` turned off. The server-side Automations files sit in
the `no-await-in-loop` baseline like any other file. None of them had
fan-out sites. Remove the dashboard override when that rewrite lands.

<!-- junior-request-attribution:start -->
via @BYK.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:agent%3A7e1432c2f4a2110ee7bb48718f8b6fad -->

--

[View
Session](https://junior-prod.sentry.dev/conversations/agent%3A7e1432c2f4a2110ee7bb48718f8b6fad)
[[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A7e1432c2f4a2110ee7bb48718f8b6fad/?project=4510944073809921)

<!-- junior-session-footer:end -->

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: BYK <[email protected]>
BYK added a commit that referenced this pull request Nov 18, 2026
…3680)

`junior/bounded-fan-out` only flagged `Promise.all(list.map(async …))`.
It missed most fan-out forms, so per-item reads and writes went in
unbounded. This extends the rule, fixes the sites it finds, and adds two
dashboard checks.

## Rule

`junior/bounded-fan-out` now also flags:

- `flatMap` and `Array.from(list, fn)`;
- a sync arrow that returns a call (or an array of calls), such as
`list.map((x) => read(x))`;
- a function reference, such as `list.map(read)`;
- `const ps = list.map(…)` and then `Promise.all(ps)`.

A callback that calls a `p-limit` limiter is bounded. This also applies
to a local function that the callback names.

**Type-level caps instead of disables.** Oxlint JS plugins get no type
information, so the rule reads only types that the code writes. A list
is fixed when it is:

- an array literal with no spread;
- `[…] as const`, or `[…] satisfies` a tuple type;
- a binding or parameter with a written tuple or `readonly` tuple type;
- `list.slice(0, MAX)` with a number literal or module-level number
`const`;
- `{ length: N }`.

A plain array literal held in a binding is not fixed: `push` can grow
it.

The rule is off for `packages/junior-evals/src/fixture/**` and
`packages/junior-testing/src/**`, because those sites are only test
fixtures and harness code. No new disable comments.

## Batched fixes

- `listAdminUsersFromSql`: one `inArray` identity read for all admins.
- Cache-warming snapshot: images are written with `setStateValues` (one
Redis `MULTI`).
- `recordGitHubPullRequestLinkedIssues`: one `INSERT … SELECT` over
`unnest(…)` in place of one insert per issue. If the PR row is gone, it
still inserts nothing.
- Review item assignee check: `conversationParticipantUserIds` takes a
list of Conversations and does one `inArray` read.
- `listActiveMailboxTurns`: one `getStoredTurnFields` read (from
#3271) drops Turns that cannot be mailbox Turns. Only
the others load Turn history, through `mapBounded`. A legacy cursor with
no Source and a non-`api` surface still loads its history, because its
Event Actors come from there.
- Slack review item card sync: linked and carded Conversation ids are
deduplicated and resolved in one `mapBounded` pass.

## Bounded fixes

- `mapBounded`:
  - six sites in `slack/runtime.ts`;
  - `slack/turn.ts`, `app/factory.ts`, `task-execution/slack-work.ts`;
  - the state adapter fallbacks;
- web push, `send-files`, web steering, child input routing, pending
messages;
  - `search-conversations`, assignee resolution, service accounts.
- Guardian's hand-written `mapConcurrent` is replaced by `mapBounded(…,
MAX_CONCURRENT_REVIEWS)`.
- `allSettled` with a `p-limit` limiter:
  - review item messages and BullMQ worker close;
- GitHub annotation updates (`ANNOTATION_UPDATE_CONCURRENCY` is now
shared with the preview webhook);
- the dashboard Inbox sweep (8 at once). Dashboard object reads also go
through a limiter (4 at once).
- Written caps:
  - `webActorUserIds` returns `[string, string]`;
- the review item collections and legacy dedupe prefixes are `as const`;
- feedback reaction removal uses
`pLimit(FEEDBACK_REACTION_CONTENTS.size)`;
  - the identity cache clear is an explicit two-item `Promise.all`.

## Dashboard checks

- **Poll allowlist:** a new ast-grep rule,
`no-dashboard-poll-outside-allowlist`, flags `refetchInterval` in the
dashboard. Its `ignores` list the 3 current polls, each with a reason:
  - `client/conversations/queries.ts`
  - `client/versions.ts`
  - `client/pages/system/CacheWarmingRefill.tsx`
- **Nav request budgets:** a new lint script,
`scripts/check-nav-request-budgets.mjs`, reads the routes of both
`primaryNav.ts` files. A dashboard e2e spec must load each route inside
`expectRequestBudget`. `scripts/nav-request-budget-exceptions.mjs`
exempts `/automations`, `/code` and `/system`, each with a reason. A
stale exception, or one with no reason, fails.

`policies/performance.md` describes the fixed-list exemptions and both
checks.

<!-- junior-request-attribution:start -->
via @BYK.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:agent%3Acdada5c589dc375265165b968649b09b -->

--

[View
Session](https://junior-prod.sentry.dev/conversations/agent%3Acdada5c589dc375265165b968649b09b)
[[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3Acdada5c589dc375265165b968649b09b/?project=4510944073809921)

<!-- junior-session-footer:end -->

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: BYK <[email protected]>

This branch was successfully deployed

1 active deployment
Preview – junior-docs — cb7db986 Deployed Nov 12, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: medium PR risk score: medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant