Skip to content

Fix empty leaderboards caused by timed-out earnings queries - #1320

Merged
Gajesh2007 merged 2 commits into
masterfrom
codex/leaderboard-recovery
Oct 2, 2026
Merged

Gajesh2007 merged 2 commits into
masterfrom
codex/leaderboard-recovery

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

Summary

The live 24-hour leaderboard took 10.24 seconds and returned 200 {"entries":[]} on October 1, while new inference earnings were still arriving. Read-only database inspection found a 47 GB provider_earnings heap (196.6 million estimated rows), no time-leading index, and a parallel sequential scan for the windowed work aggregate. The store's ten-second query deadline is swallowed and the empty result is cached for five minutes.

Add a concurrent BRIN index on created_at, explicitly enable range autosummarization, and pin the table's analyze threshold to 0.5%. Propagate query, scan, and iteration errors through both store implementations; the public handler returns 503 with Retry-After instead of publishing an empty or partial ranking. Caller limits and equivalent window aliases share one top-200 fill per metric/canonical window; concurrent misses coalesce, and a failed fill retains only a ten-second retry deadline. Successful response fields and ranking/account pseudonymization remain unchanged.

This combines the relevant error handling from #1140 and index design from #1142 on current master; both existing PRs currently have merge conflicts. It retains the current query memory policy. It does not include the broader analytics work in #1197 or the all-time summary change in #1144.

Linked issue

Closes #1139
Closes #1141

Before

flowchart LR
  M["migrate"] --> I["Account/provider indexes only"]
  U["Leaderboard page"] --> H["handleLeaderboard: cache miss"]
  H --> S["PostgresStore.Leaderboard"]
  S --> Q[("24h filter: full heap scan")]
  I -.-> Q
  Q --> T["10s query timeout"]
  T --> E["Store returns nil"]
  E --> C["Cache empty ranking for 5 min"]
  C --> R["200: empty leaderboard"]
  classDef code fill:#dbeafe,stroke:#1d4ed8,color:#172554;
  classDef data fill:#e0e7ff,stroke:#4338ca,color:#312e81;
  classDef failure fill:#fee2e2,stroke:#b91c1c,color:#7f1d1d;
  class M,I,H,S code;
  class Q data;
  class T,E,C,R failure;
Loading

After

flowchart LR
  M["migrate"] --> I["ensureProviderEarningsWindowIndex"]
  I --> B[("Concurrent BRIN + autosummarize")]
  I --> A["Analyze threshold: 0.5%"]
  U["Leaderboard page"] --> H["handleLeaderboard: cache miss"]
  H --> D["cachedLeaderboard: shared top-200 fill"]
  D --> S["PostgresStore.Leaderboard"]
  B -.-> S
  A -.-> S
  S --> OK["Successful complete ranking"]
  OK --> C["Cache for 5 min"]
  C --> R["200: provider rankings"]
  S --> ERR["Query / scan / iteration error"]
  ERR --> F["503 + Retry-After: 10s failure cooldown"]
  classDef code fill:#dbeafe,stroke:#1d4ed8,color:#172554;
  classDef data fill:#e0e7ff,stroke:#4338ca,color:#312e81;
  classDef success fill:#dcfce7,stroke:#15803d,color:#14532d;
  classDef failure fill:#fee2e2,stroke:#b91c1c,color:#7f1d1d;
  class M,I,A,H,D,S code;
  class B data;
  class OK,C,R success;
  class ERR,F failure;
Loading

Blue nodes are code paths, purple nodes are database structures, green nodes are successful outcomes, and red nodes are failures. BRIN makes historical-page pruning available; the actual production plan and latency still require verification after index creation.

Test plan

All PostgreSQL tests below used a throwaway local PostgreSQL 16 instance, with no production credentials or production test traffic.

  • make coordinator-test — complete runner guards and coordinator suite, including 1,787 discovered API tests across eight isolated shards.
  • DATABASE_URL=<local-test-db> go test ./store -count=1 — complete store suite with PostgreSQL, passed.
  • DATABASE_URL=<local-test-db> go test -race ./api -run Leaderboard -count=1 — real HTTP and database error/recovery checks, passed.
  • DATABASE_URL=<local-test-db> go test -p 1 ./store ./api -run 'Leaderboard|ProviderEarningsWindowIndex' -count=1 — final focused checks, passed.
  • go vet ./store ./api, go build ./cmd/coordinator, staged Go formatting and diff whitespace checks. Follow-up changes also pass go vet ./coordinator/api and make coordinator-build from the root.
  • make docs-impact-check BASE=origin/master and make docs-check — passed; 330 docs checked.
  • Independent reviewer inspected the complete PR at 9ddf8b261 and found no actionable in-scope issues. Its focused PostgreSQL/index tests, three repeated leaderboard race runs, shared-fill cancellation probe, and invalid-index startup probe passed.

Regression evidence: temporarily disabling the handler's new error branch causes TestLeaderboardStoreErrorIs503NotEmptyBoard to fail with status=200 want=503 and entries:[]. Restoring the branch passes. The test renames/restores the real earnings table in its own database, exercises Server.Handler() through httptest.NewServer, verifies only a retry deadline is retained during failure, and observes the seeded ranking after cooldown expiry and recovery.

Thirty concurrent real HTTP callers with different limits and window aliases share one PostgreSQL query. Disabling coalescing reproduces 30 queries; disabling failure backoff reproduces repeated failed queries. Alias and limit changes cannot bypass cooldowns, and canceled callers do not start new queries. The query-counting decorator always runs the real underlying store query.

Other checks cover fresh-database BRIN creation, autosummarization, restart idempotency, a closed PostgreSQL pool, legitimate empty-window caching, and PostgreSQL/memory parity for earnings, work/reward components, tokens, jobs, and window boundaries.

Components touched

  • coordinator (Go)
  • provider (Rust, legacy)
  • provider-swift (Swift CLI)
  • console-ui (Next.js)
  • enclave (Swift)
  • infra / CI / release
  • docs

Protocol / interface changes

  • Yes — UsageStore.Leaderboard now returns ([]LeaderboardRow, error); both backends and all callers are updated. GET /v1/leaderboard returns 503 service_unavailable with a positive Retry-After on a cache-miss query failure or during its ten-second cooldown; successful JSON is unchanged. The existing console proxy forwards this status and the hook displays its error state.
  • The schema change adds idx_provider_earnings_created_at_brin and autovacuum_analyze_scale_factor=0.005 on provider_earnings. There is no provider/protocol version bump.

Documentation impact

  • Canonical documentation updated: storage startup/index behavior, API cache/error/retry contract, consumer analytics retry guidance, and topic-specific changelog entry. All three modified canonical docs are stamped with the current UTC verification date.

Notes for reviewers

PostgresStore.Leaderboard lives in its own file, preserving its successful query semantics. The startup index helper is renamed from restore-specific to generic; existing restore-index behavior is retained. An interrupted invalid concurrent build fails readiness rather than silently passing.

Production remains unchanged. Index creation on the large heap is an I/O-intensive, one-time operation that can delay first startup; an approved operator can prebuild the exact index from postgres_earnings_window_index.go and run ANALYZE provider_earnings before deploying this commit. Verify the complete leaderboard query plan and a fresh ranking, then the default console query after its existing empty five-minute cache expires. Production database work and coordinator deployment require separate explicit approval.

All-time and broad 30-day aggregates still need their own measured optimization; this change does not establish their latency. Local fixtures validate correctness and index operation, not production-sized throughput.


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

@vercel

vercel Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
d-inference Ready Ready Preview Oct 2, 2026 7:38pm UTC
d-inference-console-ui-dev Ready Ready Preview Oct 2, 2026 7:38pm UTC
d-inference-landing Ready Ready Preview Oct 2, 2026 7:38pm UTC
eigen-homepages-darkbloom Ready Ready Preview Oct 2, 2026 7:38pm UTC

Request Review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-02T19:41:17.160087Z 9ddf8b2 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

github-actions Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Threat model review — advisory

Reviewed head 9ddf8b261a68 against base c56b98e8638f.

Review not completed for this head. Previous findings are superseded, not confirmed resolved.
Scan incomplete: one or more configured reviewers did not finish; completed reviewers' findings are shown below

Reviewers: anthropic/claude-opus-5.5: incomplete (review unavailable); openai/gpt-6-astra: incomplete (review unavailable)

Models: anthropic/claude-opus-5.5, openai/gpt-6-astra. Findings require human validation; this review never requests changes or blocks merging.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b09c1e60bd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread docs/reference/api-contracts.md Resolved
Comment thread coordinator/api/leaderboard.go Resolved
Comment thread docs/reference/api-contracts.md Resolved
Comment thread coordinator/api/leaderboard.go Resolved

This branch was successfully deployed

4 active deployments
Preview – d-inference — 9ddf8b26 Deployed Oct 2, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — 9ddf8b26 Deployed Oct 2, 2026 by vercel[bot]
Preview – d-inference-landing — 9ddf8b26 Deployed Oct 2, 2026 by vercel[bot]
Preview – eigen-homepages-darkbloom — 9ddf8b26 Deployed Oct 2, 2026 by vercel[bot]
benchmarks — 9ddf8b26 Deployed Oct 2, 2026 by Gajesh2007 via E2E Benchmarks #2134
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants