Repository navigation
perf(api): Read access, root, and viewer once per detail request - #2758
Merged
Merged
Conversation
Filter annotations on the joined Conversation row so the query uses the primary key and root index instead of scanning both tables. Resolve a known viewer with one read instead of an insert attempt and two reads. Share access and root id reads across the parts of one detail request.
Contributor
|
9 screenshot changes — 9 changed · 0 added · 0 removed Review screenshots in Frameshift |
BYK
approved these changes
Nov 5, 2026
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
BYK
added a commit
that referenced
this pull request
Nov 5, 2026
…2761) 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: | Span group | Query | Prod p50 | Prod p95 | |---|---|---|---| | `c885030f` | subtree cost (`readConversationAuxiliaryCostsFromSql`) | 287 ms | 927 ms (max 3.8 s) | | `d9361166` | last user message (`readLastUserMessageAtByConversation`) | 204 ms | 485 ms | | `008e3d9a` | latest message preview (`readConversationActivityPreviews`) | 136 ms | 500 ms | 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, from `junior_conversations`. Two new partial indexes back it: - `junior_conversation_events_message_role_idx` on `(conversation_id, (payload->>'role'), created_at, seq) WHERE type = 'message'` - `junior_conversation_events_user_message_time_idx` on `(conversation_id, created_at, seq) WHERE type = 'user_message'` and the instruction check (authority `instruction`, platform `slack`, `local` or `web`). `isUserInstruction` in 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. An `exists` or 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 #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. - Correct for the same reasons as the model usage cache: events are append-only, appends commit in seq order, and a fork commits its copied events and fork note in one transaction. - A purge is detected when `originMs` (first event time) differs or the seq goes down. The entry is then rebuilt. - Nothing changes on the write path, and there are no triggers. - The watermark read and the seq range join move from `sql-model-usage.ts` to `chat/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. | Query | Before | After | |---|---|---| | Latest message preview | 10,809 buffers, 22–23 ms | 449 buffers, **1.0 ms** | | Last user message | 21,083 buffers, 34 ms | 599 buffers, **1.4 ms** | | Subtree cost, every read | 113k buffers (54k read from disk), 268–290 ms | — | | Subtree cost, first read (cache miss) | — | watermarks 1,820 buffers / 7.7 ms + one full sum 70.7k buffers / 127–173 ms | | Subtree cost, no new events | — | watermarks only: 1,820 buffers, **6.6 ms** (15 ms wall with Redis) | | Subtree cost, 5 new events per Conversation | — | watermarks 7 ms + delta sum 3,711 buffers / 5.9 ms (27 ms wall) | 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 from `auto_explain` on the real node-postgres call, with bind parameters. | user_message read, per Conversation | Before | After | |---|---|---| | 20k-Conversation seed | Index Scan Backward with a Filter, 1,500 rows removed, 55 buffers, 0.58 ms | Index Only Scan Backward, no filter, 4 buffers, 0.02 ms | | Only the 5 large Conversations in the table | Bitmap Heap Scan + top-N sort of all 4,500 rows, 538 buffers, 4.0 ms | Index Only Scan Backward, 3 buffers, 0.01 ms | 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 `0080` follows the `0079` pattern: a `DO` block skips an index that already exists, then checks that both are valid and ready. Both `CREATE INDEX` statements have the `-- junior:concurrent-index` marker, so `junior upgrade` builds them with `CREATE INDEX CONCURRENTLY` before the migration runs. **Merge order:** #2761 must merge after #2772. Without #2772, `0080` builds its indexes inside the migration transaction and blocks writes to `junior_conversation_events` during the build. ## Checks - `tsc`, `pnpm lint` (oxlint, dependency-cruiser), prettier, `pnpm migration-metadata:check`, `pnpm file-length:check`, `pnpm test-architecture:check`. - With `DATABASE_URL` set to local Postgres: 26 files / 116 tests pass, including `tests/integration/api/conversations/**`, `dashboard-reporting`, `memory-plugin-storage`, `conversation-brief-task` and `tests/unit/api/conversations/**`. - `list-usage.test.ts` now 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 the `originMs` path. Removing the origin check makes the test fail. <!-- junior-request-attribution:start --> via @BYK. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3A57f19e3bf526c322da5782cc885008fc --> -- [View Session in Sentry](https://sentry.sentry.io/explore/conversations/agent%3A57f19e3bf526c322da5782cc885008fc/?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]>
22 tasks done
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.
Three server-side read cuts for the dashboard, from prod traces on 0.280.0.
Annotations query
listConversationAnnotationsByIdfiltered with anORacross two tables (junior_conversation_annotations.conversation_idorjunior_conversations.root_conversation_id). Postgres cannot use an index for that and scans both tables. Both ids now filter on the joinedjunior_conversationsrow, so the plan uses the primary key and the root index. Results are the same, because the join is onconversation_id.In prod this is span group
5216ed24: p50 77 / p95 197 ms per detail 200, and the most expensive DB span on detail reads.EXPLAIN ANALYZEon local Postgres with seeded data:Viewer resolution
Every authenticated request ran
junior_usersinsert-on-conflict-do-nothing, then a select, then an identities read.resolveViewerUserFromSqlnow reads the user with its identities in one join first, and only falls back to the insert path for a new email. Because the insert wasON CONFLICT DO NOTHING, a known user's row never changed on this path, so behavior is the same.findUserByEmailFromSqluses the same join.Access and root reads per detail request
Span groups
7e0742f4,d5f80e46andc8a0e6efeach ran about twice per detail read: access, forks, and the agent tree each read access for the same Conversation, and viewer marks and auto-archive each resolved the root id.createConversationAccessReaderreturns a reader that holds aMapof promises for one request. Each id is read at most once. It is created insidereadConversationDetailStateand passed to forks and the agent tree. No globals.Checks
pnpm typecheck,pnpm linttests/component/viewer-display-name.test.tsextended: a known viewer resolves without a write and keeps its identities; a new viewer is still created.No UI change.
via @BYK.
--
View Session in Sentry