Skip to content

perf(dashboard): Cache model usage sums with a seq watermark - #2688

Merged
BYK merged 1 commit into
mainfrom
fix/detail-usage-cold-load
Nov 4, 2026
Merged

BYK merged 1 commit into
mainfrom
fix/detail-usage-cold-load

Conversation

@sentry-junior

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

Copy link
Copy Markdown
Contributor

Cold loads of long Conversation details take 6–10s. Almost all of that time is the model usage query.

In trace 0be91b7baf694887aa6b28a1b1e29189 (release 0.277.0), local:web:0ab4fc2bd5a2e23f2c25efcf loaded twice:

detail request total usage query (cab9c71d57e8180d) next slowest DB span
1 9,641ms 8,299ms annotations, 247ms
2 6,356ms 4,173ms subtree cost, 237ms

The query reads every assistant_message payload in the Conversation tree. Each payload holds the full reply, and Postgres must load and decompress all of it to read the usage fields.

This PR caches the per-model sums in the state adapter (Redis), with a watermark: the last seq of each Conversation in the subtree. A read gets the last seqs in one indexed query and sums only the events after the cached seqs. Then it adds them to the cached sums and writes the entry back. There is no migration and no write-path change.

  • First read of an old Conversation pays the full cost once. Later reads add only new events.
  • Correctness: rows at or below a seen seq never change whether they count. Events are append-only, and the per-Conversation event lock serializes appends up to commit. notInheritedByForkChild reads only lower seqs, and a fork commits its copied events and its fork note in one transaction.
  • Purge: a purged Conversation can get new events under the same id, with seq starting again at 0. The entry stores the creation time of each Conversation's first event, so a mismatch rebuilds from zero.
  • Concurrent reads: last write wins. Each entry is correct at its own seqs.

On a local run with 3,000 large assistant rows, the first read touched ~30k buffers (~80ms warm). A read after 5 new events touched 29 buffers (~6ms) through junior_conversation_events_type_idx, with the seq range in the index condition.

The dashboard-reporting scenarios now read, append, and read again. They cover a cost sum, a fork child with inherited history, a child agent added after the first read, and new events after a purge.

via @BYK.

--

View Session in Sentry

@vercel

vercel Bot commented Nov 4, 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 4, 2026 9:16pm UTC

Request Review

@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

6 screenshot changes — 6 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
Code · Desktop
Code · Desktop
Changed
Conversation Share Details · Desktop
Conversation Share Details · Desktop
Changed
Conversation Subagents · Desktop
Conversation Subagents · Desktop
Changed
Settings Mcp · Desktop
Settings Mcp · Desktop
Changed

…atermark

The detail model usage query decompressed every assistant payload in the
Conversation tree. On long Conversations this took 4-8s on a cold load.
Cache the per-model sums in the state adapter with the last seq of each
Conversation in the subtree. A read sums only events after that seq and
adds them. A purged Conversation that gets new events rebuilds from zero.

Co-Authored-By: BYK <[email protected]>
@sentry-junior
sentry-junior Bot force-pushed the fix/detail-usage-cold-load branch from e4cb672 to f0476a9 Compare November 4, 2026 21:15
@sentry-junior sentry-junior Bot changed the title perf(dashboard): Read model usage from a small assistant_call column perf(dashboard): Cache model usage sums with a seq watermark Nov 4, 2026
@BYK
BYK merged commit 3c62a10 into main Nov 4, 2026
46 checks passed
@BYK
BYK deleted the fix/detail-usage-cold-load branch November 4, 2026 21:42
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]>

This branch was successfully deployed

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

Labels

risk: high PR risk score: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant