Skip to content

feat(leaderboard): serve model leaderboards from a Postgres rollup - #13017

Merged
chrarnoldus merged 10 commits into
mainfrom
leaderboard-postgres-rollup
Nov 27, 2026
Merged

chrarnoldus merged 10 commits into
mainfrom
leaderboard-postgres-rollup

Conversation

@chrarnoldus

@chrarnoldus chrarnoldus commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Moves two public leaderboard routes from Snowflake to Postgres:

  • /api/public/leaderboard-model-usage
  • /api/public/leaderboard-model-provider-usage

/api/public/leaderboard-provider-race stays on Snowflake. It depends on model_provider_company and is_open_weights, which come from the dbt model dimension and don't exist in Postgres yet.

Rollup table

leaderboard_usage_daily is a global per-day rollup with no user or organization columns.

  • Grain: UTC day × provider, requested_model, model, inference_provider, mode, is_user_byok. is_user_byok is non-null: a missing metadata row or a NULL flag is stored as false.
  • Sums: input, output and cache-hit tokens, cost, request count, error count.
  • Filters are applied when reading. The stored dimensions are unfiltered, including provider, so leaderboard filters can change without rebuilding the table. Filtering after aggregation can differ slightly from per-request filtering. That's acceptable for marketing figures.

Building the rollup

  • A new cron, /api/cron/leaderboard-usage-rollup, runs hourly at :20. Each run builds the days in the 7-day leaderboard window that have no rows yet, newest first. It builds at most 2 days per run, within a 500 s budget. The budget is checked before every 15-minute slice, so a run stops partway through a day rather than being killed. Unfinished days are reported as remaining and picked up by the next run.
  • Each day is built once and written whole in one transaction, so the routes never see a partly built day. Usage-ingest queue retries can write a row 20+ minutes after its created_at, so a day is built 1 hour after it ends, and only once the replica has replayed past that point (pg_last_xact_replay_timestamp()). Until then the day is left out of the leaderboards rather than shown short. Rows written more than an hour after the day ends are not counted. To recount, delete the affected days' rows (or truncate the table) and the next runs rebuild them, 2 days per run.
  • A day is aggregated from readDb in 15-minute slices. Each slice joins microdollar_usage to microdollar_usage_metadata and mode, with both sides bounded by created_at (production writes both rows with the same created_at in one statement). Each slice runs with statement_timeout = 60s and work_mem = 128MB. On a production replica, a warm one-hour query (~660k rows) took 3.3 s and spilled its hash join to disk at the default 32MB work_mem; the same hour cold exceeded 120 s. Slices keep each query small and well under the replica's 90 s max_standby_streaming_delay.
  • The day's rows are then replaced on the primary in one transaction. An advisory lock per day prevents duplicate rows from overlapping runs.

Logging

The cron logs structured JSON to the console only, with no Sentry events or alerts:

  • leaderboard_usage_rollup_day: one line per built day, with rows, durationMs, slices and slowestSliceMs.
  • leaderboard_usage_rollup_day_deadline: a day abandoned at the deadline, with how many slices it finished.
  • leaderboard_usage_rollup_day_failed: the day, the stage (read or write), the slice start, slices completed, and the Postgres error code (57014 statement timeout, 40001 replica replay conflict). The error is then rethrown.
  • leaderboard_usage_rollup: the run summary, with built, remaining, unsettled, emptyDays, stoppedBy (cap or deadline), yesterdayBuilt, replicaLagMs and durationMs. It's logged as a warning when a built day had no rows, or when yesterday is still missing at 03:00 UTC or later.

Routes

  • public-snowflake-report.ts became public-report.ts. createPublicReport takes a load function, and Redis caching is now optional through cacheKey. createPublicSnowflakeReport stays as a thin wrapper for provider-race, which keeps its Redis cache.
  • The two Postgres routes drop Redis. The rollup read takes milliseconds and the data changes once a day, so the Vercel edge cache and the in-process last-known-good cache are enough. Their Redis keys are removed.
  • The edge cache (s-maxage and stale-while-revalidate) and the in-process cache now expire after 5 minutes instead of 1 hour, for all public reports. The Redis cache that provider race still uses keeps its 1-hour TTL.
  • The two routes run the same SQL as before against leaderboard_usage_daily, using the UTC date for the window.
  • An empty window now returns 502 instead of []. Empty means the rollup hasn't been built yet. The 502 keeps the in-process last-known-good value instead of caching an empty leaderboard.

Rollout

The first backfill takes about 4 hourly runs; triggering /api/cron/leaderboard-usage-rollup by hand speeds it up. Until the first run, both routes return 502 for anything not already cached. While the backfill runs they report a partial week, but never a partial day. There is no Snowflake fallback.

Verification

  • NODE_ENV=test npx jest src/app/api/public src/app/api/cron src/lib/leaderboard in apps/web: 48 suites, 310 tests passed. The new rollup tests and route tests run against real Postgres.
  • packages/db jest: 11 suites passed.
  • pnpm --filter web typecheck, pnpm --filter web lint and pnpm drizzle check pass.
  • Not checked against production: whether the numbers match the current Snowflake leaderboards, and how long a cold 15-minute slice takes.

Models used: Claude Opus 5.5 (main session), Claude Haiku 5.5 (exploration subagent).

@chrarnoldus chrarnoldus self-assigned this Nov 27, 2026
@chrarnoldus
chrarnoldus force-pushed the leaderboard-postgres-rollup branch from 31a4cbe to a69e05a Compare November 27, 2026 10:53
@chrarnoldus
chrarnoldus force-pushed the leaderboard-postgres-rollup branch from 5220a89 to 59c8a2e Compare November 27, 2026 14:16
@chrarnoldus
chrarnoldus added this pull request to the merge queue Nov 27, 2026
Merged via the queue into main with commit 999d0a7 Nov 27, 2026
83 checks passed
@chrarnoldus
chrarnoldus deleted the leaderboard-postgres-rollup branch November 27, 2026 14:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants