Repository navigation
perf(api): Read list previews and costs without scanning every event - #2761
Merged
Merged
Conversation
The Conversation list reads three per-Conversation aggregates that scan every event of each listed Conversation: the latest message preview, the last user message time, and the subtree cost. - Preview and last user message read the newest match through two new partial indexes, with one lateral LIMIT 1 per role or type. - Subtree costs are cached per Conversation in the state adapter with a seq watermark, like the model usage cache. A read sums only events after the cached seq. The watermark read moves to a shared helper. Co-Authored-By: BYK <[email protected]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Contributor
|
10 screenshot changes — 10 changed · 0 added · 0 removed Review screenshots in Frameshift |
With the provenance check only in the scan filter, Postgres misestimated how many user_message events match. It then read and sorted every user_message of a Conversation instead of stopping at the newest match. The partial index now has the same predicate as the query, so the read is an index-only backward scan that stops at the first entry.
Mark both CREATE INDEX statements with -- junior:concurrent-index, so junior upgrade builds them with CREATE INDEX CONCURRENTLY before the transactional migrate (#2772).
BYK
pushed a commit
that referenced
this pull request
Nov 5, 2026
Drizzle applies every pending migration in one transaction. A plain `CREATE INDEX` inside it takes a `ShareLock` on the table, so writes to `junior_conversation_events` wait until the whole batch commits. Until now an operator had to prebuild these indexes on prod by hand. Nobody has that access, so `junior upgrade` now does it. ## What changed - **Marker:** a migration puts `-- junior:concurrent-index` on the line before a one-line `CREATE INDEX "name" ON "table" …;`. If the next line doesn't have that shape, upgrade throws, so a bad marker fails on every fresh migrate, including tests and preview deploys. - **Prebuild** (`src/db/concurrent-indexes.ts`): `migrateSchema` and `migratePluginSchemas` call it while they hold the migration lock, right before `executor.migrate`. It runs one statement at a time in autocommit, and only for migrations newer than the latest applied one. For each marked index it does this: 1. If the table doesn't exist yet, it skips the index. The table comes from the same pending batch, so it's new and empty, and the transactional migration builds the index. 2. It gets the expected `pg_get_indexdef` by running the migration's own statement on an `ON COMMIT DROP` temporary copy of the table (`LIKE`), inside one transaction. 3. If an index with that name is invalid or not ready (left by an interrupted build), it runs `DROP INDEX CONCURRENTLY`. 4. If no index exists, it runs `CREATE INDEX CONCURRENTLY`. 5. It throws if the index isn't valid and ready, or if its definition differs from the expected one. The current DO-block guard misses this case. - The existing DO-block guards stay as the safety net inside the transaction. After the prebuild they find the index and do nothing. - **0062, 0078 and 0079** get the marker, and their header comments no longer ask for a manual prebuild. Drizzle doesn't re-check the hashes of applied migrations (`PgDialect.migrate` compares only `created_at`), so editing their comments is safe. Plugin hash adoption only covers plugin migrations, and none of them change here. - Plugin migrations use the same prebuild. No plugin migration uses the marker yet. ## Verification - **New integration test** `tests/integration/concurrent-index-migrations.test.ts`, on real Postgres 17. It uses a temporary plugin migration folder, so later core migrations don't affect it. - While an open write transaction makes the build wait, `CREATE INDEX CONCURRENTLY` shows as waiting on a lock, and a second `INSERT` into the table still completes. - A valid index with the same name but other columns makes upgrade fail. A real interrupted build (a failed `CREATE UNIQUE INDEX CONCURRENTLY`) leaves an invalid index, and upgrade replaces it with the right definition. - With the prebuild call removed, both tests fail: the first times out on the blocked insert, and the second migrates over the wrong index without an error. - **Core path, by hand:** I migrated, then dropped `junior_conversation_events_author_idx` and its journal row. `migrateSchema` rebuilt it concurrently and applied 0079 again. - **PgBouncer in transaction mode** (`edoburu/pgbouncer` 1.26 in front of PG17, the same pooling mode as Neon's `-pooler` endpoint): I ran the core rewind there with an invalid leftover and an open write transaction. The temporary-table check, the `DROP`/`CREATE INDEX CONCURRENTLY` and the migrate all worked, and the concurrent insert finished in about 20 ms. - **#2761's 0080 with the marker added:** both indexes build concurrently, the expected definitions match, including the `payload ->> 'role'` expression, and a second run does nothing. - Postgres (`DATABASE_URL`): `concurrent-index-migrations`, `conversation-sql`, `workspace-snapshot-migration`, `memory-plugin-storage`, `conversation-storage-sql` and `scheduled-automations-sql` pass (54 tests). The PGlite default run of `conversation-sql`, `memory-plugin-storage` and `upgrade-cli` also passes. - `pnpm --filter @sentry/junior typecheck` and root `pnpm lint` pass. `pnpm lint` includes `migration-metadata:check`, `test-architecture:check` and `file-length:check`. ## Limits - No `lock_timeout`. `CREATE INDEX CONCURRENTLY` waits for transactions that are already running, so a long transaction makes the build wait, up to the Vercel build limit. A killed build leaves an invalid index, and the next upgrade replaces it. - A marked index may only use columns that exist before its release. If it uses a column added in the same pending batch, the prebuild fails. A preview deploy shows this. - Pre-existing and not changed here: over a transaction-mode pooler, `withMigrationLock`'s session advisory lock can stay held on the server connection after the client ends. A later upgrade then waits until that connection closes. I saw this with local PgBouncer. If the build uses Neon's `-pooler` URL, a direct (non-pooler) URL for `junior upgrade` would avoid it. <!-- junior-request-attribution:start --> via @BYK. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3A02670ec341fd57309b6381d43bf5a6b8 --> -- [View Session in Sentry](https://sentry.sentry.io/explore/conversations/agent%3A02670ec341fd57309b6381d43bf5a6b8/?project=4510944073809921) <!-- junior-session-footer:end --> Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
BYK
approved these changes
Nov 5, 2026
BYK
enabled auto-merge (squash)
November 5, 2026 21:05
22 tasks done
BYK
added a commit
that referenced
this pull request
Nov 10, 2026
Fixes #3032 **Stacked on #3046** (stack [#3058](https://github.com/getsentry/junior/stack/3058): #3037 → #3046 → #3047 → #3035 → #3036). #3046 owns who is in Needs you; this PR owns the order. Review the diff against `fix/dashboard-needs-you`. The conversation list moved under the reader's pointer. Every event moved a row, and the waiting section put the newest activity first, so a queue you were working through kept changing order. This PR fixes the order and cuts the row markers to three channels. ## Order - **Needs you: the oldest wait goes first.** `/api/review-items/waiting-conversations` now returns `waitingSince` next to #3046's `items`. It is the `createdAt` of the conversation's oldest open item for the viewer. New activity no longer moves the queue. - **Date sections: sorted by the last Message.** Feed rows get `lastMessageAt`, which is the newer of the last true user Message and the last Junior reply that the transcript shows. Like the unread reply, it skips tool calls, status changes, Events, and quiet replies, so they don't move a row. It also skips progress acks (`meta.progress`). That exclusion starts working when #3044, a separate PR, lands on main; until then nothing writes the flag. The row age and the home card time show this time too. A row with no Message yet uses `lastSeenAt`. - `pinnedAndWaitingFirst` sorts the same way before paging, so pages split where the sections do. ## Hold while you work in the list - **One list component.** The sidebar and the home card list both render through `ConversationSectionList`. It builds the sections, holds the order, shows the pill, and owns pin reorder. Each list keeps only its own row look. A dashboard lint rule (`no-restricted-imports` in `.oxlintrc.json`) allows `buildConversationSections` and `heldListOrder` only in that component, so a new list can't skip the hold. - While the pointer is over the list, or focus is in it, rows keep their section and position. The hold covers the whole list area, including its padding and scrollbar, from the first paint. Their data still updates: bold, dot, spinner, and the review chip. - An **"N updated"** pill offers the new order. N is the number of rows that the new order would add or move, using the longest increasing run, so moving one row counts as 1. Clicking the pill applies the new order. So does moving the pointer out once focus has left the list. - **Row actions apply at once.** Pin, unpin, reorder, archive, and mark read/unread release the hold, so you see their result. Opening a row does not release it, so the row you just read stays where it was. - The hold starts only after the feed and waiting reads finish. A pointer resting on the list during a page load does not hold back the first rows. - Rows that sort after every held row, such as the next page of the home list, show at the end. Loading more doesn't wait on the pill. - Touch has no hover, so only a mouse or pen holds the order. On a phone only focus holds it. The pill fades in only under `motion-safe`. `AnimatedList` is unchanged and still animates rows in and out. | Held, dark | Held, light | |---|---| |  |  | In these shots, *Checkout latency triage* has started waiting. It gets its dot, bold title, and chip in place, and the pill offers to move it into Needs you. The home card list in a 700px window with a mouse, held and then applied: | Home held, dark | Home held, light | Home applied, light | |---|---|---| |  |  |  | ## Three marker channels - **Position:** the section, such as Needs you. - **Read state:** a dot plus a bold title. This is one channel, so unread and waiting rows keep both. The separate violet "waiting" dot and orange "unread" dot are now one accent dot. The section and the review chip already show that a row is waiting. - **Motion:** the running spinner. - **Secondary text:** the private lock, and "Failed" or "Stopped", sit beside the age, not in the marker slot. The idle glyph is gone. This applies to the sidebar, the home and mobile list cards, and the Code page's recent conversations rows. Thread rows under a parent keep their own child status icon, which is unchanged. ### Mark as unread does not change Every read/unread control works as on `main`: - The dot slot in the sidebar is still the read toggle. It shows on unread rows, shows a preview on hover or focus, and has the "Mark as read/unread" tooltip. - The row context menu still has Mark as unread/read. - The mobile conversation menu still has Mark as unread. This PR adds no shortcuts. The only change is that these actions release the hold, so the row moves right away. | Needs you, before / after (dark) | Sidebar, before / after (light) | |---|---| |  |  | | Read toggle on hover, before / after | Row menu, before / after | |---|---| |  |  | Before is #3046 (`470f3a73f`). In the read toggle and row menu shots, Needs you now lists the longest wait first, so *Plan the billing migration* moves above *Roll out payments-v42*. | Mobile list, before / after | Mobile Needs you, before / after | Mobile conversation menu | |---|---|---| |  |  |  | On mobile, "Failed" is now text beside the time, not a rose dot on the tile. A running card shows one spinner, in place of the time, not a second one on the tile. The waiting card's dot is the same accent dot as unread, not the glowing violet one. ## Pins stay manual Pins don't change, and nothing pins on its own. For diagnosis, a pin change tags its request span with `app.conversation.pin.action` (`pin`, `unpin`, or `reorder`) and `app.conversation.pin.count`, which is the viewer's pin count after the change. The names and a query recipe are in `TELEMETRY.md`. The browser still sends only spans and ratings. ## Notes for reviewers - **Ordering on top of #3046:** in `conversationSections.ts`, `buildConversationSections` and `pinnedAndWaitingFirst` now take `waiting` (the waiting map with `waitingSince`) in place of #3046's `waitingIds` set. Membership is unchanged: a row is in Needs you only when it is in that map. - **Feed query cost:** the feed reads `lastMessageAt` from a new `junior_conversations.last_message_at` column, so it adds no per-row event reads. Recent perf work on main took two routes: #3006 caches usage sums in Redis with a seq watermark, and #2761 reads previews through bounded index walks. I chose a column over a Redis cache because this time changes only when a Message is appended, and the append already writes the Conversation row in its transaction. So there is nothing to invalidate or watermark. - **Write:** `refreshLastMessageAt` (`sql/last-message.ts`) runs in the append transaction, only when the append adds a `message` or `user_message` event. It does the three index walks once per append, not once per root on every feed read. - **Migration `0099_conversation_last_message_at`:** adds the nullable column, with no backfill. An update of every root would lock the rows that appends write (the `migration-locks` check rejects it). A row with no stored time reads it from its events in `coalesce`, which skips that read for every row that has one. Old idle rows drop out of the feed page over time. - **API change:** `waitingSince` is a required field on the strict waiting-conversations schema. The dashboard is the only consumer. The e2e mocks and `mock-reporting/review-items.ts` send it. ## Frameshift changes Report for `8e5f8c40a`: 67 changed and 3 added. I measured every pair and looked at each one that changed outside the sidebar rows. | Count | Cause | Verdict | |---|---|---| | 45 | The private lock on *Direct Message* moves from the leading slot to beside the age. This is the only change. | Expected | | 8 | The same lock move, plus noise elsewhere: transcript scroll position (4), a different demo video frame (3), or a "Conversation details" tooltip (1). | Expected, plus noise | | 5 | Mobile home cards: one accent dot for unread and waiting, and "Failed" as text. The cards also showed a bug: an empty status slot added a flex gap, so every title cut off 12px early. Fixed in `a63504507`. | Expected, bug fixed | | 2 | The Code page recent rows lose the idle dot. | Expected | | 7 | Noise only: transcript scroll (4 mobile), a chart tooltip on a different day on Memories, the random MCP port, and the nav rail height in one full-page capture. | Noise | | 3 added | `conversations-list-held` (dark and light) and `conversation-menu-mark-unread` (mobile). | New in this PR | I checked the noise locally against `main` where it was cheap. `conversation-unsent-answers` (desktop and mobile) is the same on the branch and on `main`, except for the lock, in two runs each. `automation-page` differs between two runs of the branch, and one of them matches `main`. ## Testing - **Unit:** the `conversationSections` wait and last-Message order, and the new `heldListOrder` tests (held order, pending count, new and removed rows). - **Integration (Postgres):** - `unread.test.ts`: a quiet reply or a progress ack doesn't move `lastMessageAt`, and a shown reply does. The append stores the time on the row, and a row with no stored time still reads it from its events. - `review-items/actions.test.ts`: `waitingSince` is the oldest item's time. - `list.test.ts` and `pin.test.ts` pass. - **E2E:** - New: "holds the order under the pointer and offers the new one". It checks the hold, the pill, applying on click, and applying on leave plus blur. - New: "holds the home list order under the pointer", in a 700px window with a mouse. - New: "holds the order for a pointer on the list edge through the first load". It fails on `51a864b37`, before the hold covered the whole list area. - `conversations.spec` "scrolls long conversation and transcript panes independently" now finds the sidebar scroll area by its slot, because the list has a wrapper. - The mobile mark-unread test now saves a menu screenshot. - The `conversations-attention` spec passed 3 times in a row with 3 workers. - **Full dashboard e2e:** 144 of 146 passed with 4 workers. `conversations-attention` "puts waiting conversations in Needs you first" timed out under load and passes on its own. The scroll test failed on the old locator and passes with the fix. - **Checks:** `pnpm typecheck`, `pnpm lint` (with `migration-locks`, `file-length`, and `test-architecture`), and the dashboard unit suite (432 tests) pass. Full integration: 926 passed. `any-resource-event-automations` times out here with or without this change, and `attachment-s3-storage` needs a local S3 server. <!-- junior-request-attribution:start --> via @BYK. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3A8bfa5732f44bc4f91116d3ee1be8f6d7 --> -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3A8bfa5732f44bc4f91116d3ee1be8f6d7) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A8bfa5732f44bc4f91116d3ee1be8f6d7/?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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The Conversation list was at p50 495 / p95 1,158 ms in prod (0.280.0). Each list request ran three per-Conversation aggregates, and each one read every event of every listed Conversation:
c885030freadConversationAuxiliaryCostsFromSql)d9361166readLastUserMessageAtByConversation)008e3d9areadConversationActivityPreviews)The annotations query is already fixed in #2758.
Changes
Preview and last user message: index plus rewrite. Each read is now a
LEFT JOIN LATERAL (… ORDER BY created_at DESC, seq DESC LIMIT 1)per role or type, fromjunior_conversations. Two new partial indexes back it:junior_conversation_events_message_role_idxon(conversation_id, (payload->>'role'), created_at, seq) WHERE type = 'message'junior_conversation_events_user_message_time_idxon(conversation_id, created_at, seq) WHERE type = 'user_message'and the instruction check (authorityinstruction, platformslack,localorweb).isUserInstructionin the schema builds that check for both the index and the query, so they stay the same.The role is in the index because, with only one index for both types, the planner misestimated the jsonb role filter and fell back to a bitmap scan plus a sort. The instruction check is in the user message index predicate. With it only in the scan filter, the planner misestimated how many rows match: on a Conversation with 6,000 user_message events it chose a bitmap scan and a sort of all of them. Now that read is an index-only backward scan that stops at the first entry.
The user-authored check on Messages is a scalar subquery on
junior_identities, so the walk stays a newest-first index scan. Anexistsor a join turned it into a hash semi join. An index predicate cannot hold this check, because it reads another table. So the Message read still walks past the newest Messages from the system or a service Identity until it finds one from a user.Subtree cost: incremental cache. No index can make a sum over all events cheap, so costs follow the model usage cache from perf(dashboard): Cache model usage sums with a seq watermark #2688. Each Conversation has a state adapter entry
conversation-auxiliary-costs:<id>={ seq, originMs, operations }. A read gets the subtree watermarks (two pkey lookups per Conversation), sums only the events after each cached seq, writes back changed entries, and merges members into each scope. Entries are per Conversation, not per subtree, so the list, the detail, and child agent rows share them.originMs(first event time) differs or the seq goes down. The entry is then rebuilt.The watermark read and the seq range join move from
sql-model-usage.tstochat/conversations/sql/event-watermarks.ts, so both caches use one copy.EXPLAIN (ANALYZE, BUFFERS)
Local Postgres 17 with 20k Conversations (12k roots, 8k child agents) and 3.2M events (1.8 GB). The list page has 50 roots: 25 with 2,000 events each and 25 with 120. The SQL is what drizzle generates. Old and new return identical results for all 50.
Wall time with a cold Postgres cache (after restart and
drop_caches): preview 362 → 47 ms, last user message 171 → 8 ms, cost 1,098 → 691 ms on the first read, then 14 ms.Index sizes on the seed: 31 MB (message role) and 9.9 MB (user message time).
Last user message with mixed provenance
A second seed checks the instruction predicate. It gives the 320k user_message events a mix of authorities and platforms (about 40% fail the check), and adds 5 Conversations with 6,000 user_message events each: the newest 1,500 fail the check in four ways, and pairs of events share
created_at. Each also has 900 user-role Messages: the newest 300 are from the system or a service Identity. The plans come fromauto_explainon the real node-postgres call, with bind parameters.For the whole query on the 50-id page (5 large Conversations and 45 others): main 43–44 ms / 12,803 buffers, this PR 20.5–20.9 ms / 7,827 buffers. The Message read is most of what is left (7,568 buffers), because of the 300 newest non-user Messages in each large Conversation. Main and this PR return the same result for all 50 ids on both seeds. That includes a tie between a passing and a failing user_message at the same
created_at, a Conversation where only Messages without an author are left, and one where a user Message is newer than every instruction.Migration
0080follows the0079pattern: aDOblock skips an index that already exists, then checks that both are valid and ready. BothCREATE INDEXstatements have the-- junior:concurrent-indexmarker, sojunior upgradebuilds them withCREATE INDEX CONCURRENTLYbefore the migration runs.Merge order: #2761 must merge after #2772. Without #2772,
0080builds its indexes inside the migration transaction and blocks writes tojunior_conversation_eventsduring the build.Checks
tsc,pnpm lint(oxlint, dependency-cruiser), prettier,pnpm migration-metadata:check,pnpm file-length:check,pnpm test-architecture:check.DATABASE_URLset to local Postgres: 26 files / 116 tests pass, includingtests/integration/api/conversations/**,dashboard-reporting,memory-plugin-storage,conversation-brief-taskandtests/unit/api/conversations/**.list-usage.test.tsnow reads the list a second time, after a child agent is added and new cost events are appended. That checks the delta and the per-Conversation entries. It then purges the root and writes seq 0 and 1 again, which checks theoriginMspath. Removing the origin check makes the test fail.via @BYK.
--
View Session in Sentry