Skip to content

perf(api): Read detail state in one query and access once per request - #2820

Merged
BYK merged 2 commits into
mainfrom
perf/detail-tail
Nov 7, 2026
Merged

BYK merged 2 commits into
mainfrom
perf/detail-tail

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Cuts the detail p95 tail. In prod (0.282.0–0.283.0) detail is p50 72 / p95 329 ms, and 89% of the requests above p95 are full-report reads. In 120 tail samples, 52% opened 6 or more new Neon WebSockets (115–190 ms each). The ETag phase starts about 9 queries at once, then the report starts about 10 more. Trace b3329c364809a352 shows 6 DB rounds that run one after another.

Change

  1. Mailbox shares the access reader. readConversationPendingMessages / requireConversationPendingMessages take the detail request's ConversationAccessReader, so the route reads access (7e0742f4) and participants (c8a0e6ef) once per request, not twice. The mailbox store read and the access read now run in parallel.
  2. ETag state in one query. readDetailStateRow reads the subtree version, the Slack attachments version, fork ids and fork source, parent, read position, viewer marks and auto-archive choice in one statement. It reuses the owning modules' query builders (conversationReadPositionQuery, slackAttachmentsVersionQuery). Access stays in the shared reader, and forks and the agent tree reuse the row, so they don't read again. The ETag basis and value are unchanged.

Helper changes: readConversationForks and readConversationAgentTree take the stored row. readConversationAutoArchive, readConversationViewerMarks and readSlackAttachmentsVersion are replaced, and they had no other callers.

Measured

Local Postgres 17. The seeded detail has 20 visible messages, a child agent, and a viewer participant on the root. Pool max was raised to 10 to match Neon. "Rounds" means DB rounds that run one after another, and "peak" means queries in flight at once. Each row has two runs. Each run is the median wall time of 100 requests after one warm-up request.

Read Queries Rounds Peak in flight Wall p50
Full report, before 31 7–8 11 34.3 / 40.0 ms
Full report, after 21 6 11 31.9 / 33.6 ms
Unchanged poll (ETag + mailbox, 304), before 14 5 7–8 11.4 / 12.7 ms
Unchanged poll, after 4 3 2 8.5 / 8.4 ms

Local wall time is mostly JS, because each query costs about 1 ms here. In prod, each round costs a Neon RTT, and each query in flight at once can open a new WebSocket. So the query, round and peak counts are the better guide to prod. The full-report peak stays at 11 because the report phase doesn't change. This PR only shrinks the ETag phase before it.

Checks

  • pnpm typecheck and pnpm lint pass.
  • All tests in tests/integration/api (including conversations/) and tests/component pass against local Postgres. The exception is tests/component/memory-plugin-storage.test.ts, which needs pgvector. The local image lacks it, and that file fails the same way on main.
  • New test in conversations/archive.test.ts: a child agent's detail shows the root's archivedAt. That covers reading viewer marks through the root join. It passes before and after this change.

via @BYK.

--

View Session in Sentry

The detail ETag phase started about nine queries at once on every poll,
and each could open a new pool connection. Read the state rows (subtree
version, Slack attachments version, fork links, parent, read position,
viewer marks, auto-archive choice) in one query beside the access read.

The mailbox read now uses the detail request's access reader, so access
and participants are read once per request.

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

vercel Bot commented Nov 6, 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 7, 2026 12:59am UTC

Request Review

@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

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

Review screenshots in Frameshift

Automation Run Details · Desktop
Automation Run Details · Desktop
Changed
Automation Run Details Light · Desktop
Automation Run Details Light · Desktop
Changed
Conversation Attachment · Desktop
Conversation Attachment · Desktop
Changed
Conversation Attachment · Mobile
Conversation Attachment · Mobile
Changed
Conversation Attachment Modal · Desktop
Conversation Attachment Modal · Desktop
Changed
Conversation Attachment Zoom · Desktop
Conversation Attachment Zoom · Desktop
Changed
Show 8 more changed screenshots
Conversation Captured Memories Popover · Desktop
Conversation Captured Memories Popover · Desktop
Changed
Conversation Captured Memories Popover · Mobile
Conversation Captured Memories Popover · Mobile
Changed
Conversation Details Watched Linked Work · Desktop
Conversation Details Watched Linked Work · Desktop
Changed
Conversation Details Watched Linked Work · Mobile
Conversation Details Watched Linked Work · Mobile
Changed
Conversation Event Log Virtual · Desktop
Conversation Event Log Virtual · Desktop
Changed
Conversation Long Transcript Touch · Mobile
Conversation Long Transcript Touch · Mobile
Changed
Conversation Stop Active · Mobile
Conversation Stop Active · Mobile
Changed
Settings Mcp · Desktop
Settings Mcp · Desktop
Changed

@BYK
BYK enabled auto-merge (squash) November 7, 2026 00:53
# Conflicts:
#	packages/junior/src/api/conversations/agent-tree.ts
@blacksmith-sh

blacksmith-sh Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Found 2 test failures on Blacksmith runners:

Failures

Test View Logs
[chromium] › packages/junior-dashboard/e2e/
conversations-read-position.spec.ts:95:1 › catches the reader up on several unread Turn
s
View Logs
packages/junior-dashboard/e2e/conversations-read-position.spec.ts/
catches the reader up on several unread Turns
View Logs

Fix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need.

@BYK
BYK merged commit 766a91a into main Nov 7, 2026
61 of 64 checks passed
@BYK
BYK deleted the perf/detail-tail branch November 7, 2026 01:09
BYK added a commit that referenced this pull request Nov 7, 2026
The dashboard sent one interval poll per read: the idle detail (10s),
the feed (10s while a row was active), spend (10s), and the Review count
and waiting list (60s). Most of these answered "nothing changed" and
still ran the full read. This adds one cheap change check and refreshes
only the reads whose token moved.

- `GET /api/versions?conversationId=…` runs one SQL statement and
returns opaque tokens:
- `conversation`: the open Conversation tree (row count +
`detail_version` sum), the same value as the new
`x-junior-conversation-version` header on detail responses.
- `conversations`: the viewer's default feed page (newest 50 active
member roots: ids, pin state, and each tree's `detail_version` sum).
- `reviewItems`: count + newest `updated_at` of open Review items that
need the viewer. It also guards the waiting Conversations.
- `spend`: window start + count + newest `updated_at` of the viewer's
Conversations in the 30-day window. The window start makes it move at
UTC midnight.
- The dashboard polls it every 5s (`client/versions.ts`) and removes the
idle detail, feed, spend, Review count and waiting intervals. The 500ms
window after a send and the 2s poll while a Turn runs are unchanged.
Hidden tabs still do not poll.
- The detail compares its own header token with `conversation`, so it
needs no baseline. Feed, spend and Review tokens compare with the
previous poll.
- Access stays on the real endpoints. The tokens are counts and opaque
versions. The Conversation token shows no more than the detail endpoint
does: it answers any viewer with a redacted report.
- The feed token query orders by a joined pin instead of the feed's
per-row pin lookup. With the lookup, the plan cost passed
`jit_above_cost`, and JIT added about 100ms.

## Measurements

Requests/min for one open tab (Playwright, mock dashboard, 30s windows,
prod-like tokens):

| | Before | After |
| --- | --- | --- |
| Idle Conversation | 21 | 12 |
| Active Turn | 43 | 42 (30 detail + 12 versions) |
| List page | 14 (mock feed has an active row) | 12 |

DB statements per request, local Postgres 17 with `log_statement=all`,
heavy viewer (2,000 roots, 3,000 child agents, 20k other rows).
Production adds one viewer lookup to each.

| Poll | Statements | p50 |
| --- | --- | --- |
| Detail 304 (after #2820) | 4 | 11.4ms |
| Feed | 14 | 56.5ms |
| Spend | 1 | 3.2ms |
| Review count | 1 | 1.5ms |
| Waiting | 1 | 2.0ms |
| **Versions (replaces all of the above while idle)** | **1** |
**17-19ms** (EXPLAIN 16ms, no JIT; the page sort is ~12ms) |

Idle Conversation tab: about 46 statements/min before (136 with an
active feed row) and 24 after. DB time for a heavy viewer goes from
about 91ms/min (430ms/min with an active feed row) to about 216ms/min.
That is the cost of a 5s check, and also of the feed and Review count
now refreshing when idle.

Worst-case delay before an idle Conversation shows a reply from Slack:
before ≤10s + 1 RTT, after ≤5s + 2 RTT (check, then the detail). On the
list page with no active row, the feed did not refresh before. Now it
takes ≤5s + 2 RTT.

## Not covered by a token

- Time-window labels and priority sections move with the clock, not with
data. They refresh on focus or on the next data change, as before.
- Automation names, Redis auxiliary costs, and read marks from another
device do not move a token.
- The feed token covers only the first page, plus waiting rows through
`reviewItems`. Later pages refresh on any change of the first page or on
focus.
- The first poll of a tab is the baseline for feed, spend and Review
items. A change in the ms between the first read and that poll waits for
the next change or focus.

## Checks

- `pnpm typecheck`, root `pnpm lint`.
- `tests/integration/api` (65 files, 184 tests), with the new
`versions.test.ts`: unrelated Conversation, child-agent write, mailbox
input, pin, Review add/close, spend, missing Conversation, detail header
equals the token.
- `pnpm test:e2e:dashboard` (local full run before the rebase onto
current main): new "refreshes idle reads only when their version moves".
Two specs that wake an idle Conversation from a mocked detail now also
route a token for it. `conversations-read-position.spec.ts:95` flaked,
as it does on main.

No visible UI change.

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

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

--

[View Session in
Sentry](https://sentry.sentry.io/explore/conversations/agent%3A1ea20ccbf455ecc4f9e350b69bc5af97/?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 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]>

This branch was successfully deployed

1 active deployment
Preview – junior-docs — 14ebdb41 Deployed Nov 7, 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