Repository navigation
Fix empty leaderboards caused by timed-out earnings queries - #1320
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Threat model review — advisoryReviewed head Review not completed for this head. Previous findings are superseded, not confirmed resolved. 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. |
There was a problem hiding this comment.
💡 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".
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 GBprovider_earningsheap (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 withRetry-Afterinstead 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;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;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 passgo vet ./coordinator/apiandmake coordinator-buildfrom the root.make docs-impact-check BASE=origin/masterandmake docs-check— passed; 330 docs checked.9ddf8b261and 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
TestLeaderboardStoreErrorIs503NotEmptyBoardto fail withstatus=200 want=503andentries:[]. Restoring the branch passes. The test renames/restores the real earnings table in its own database, exercisesServer.Handler()throughhttptest.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
Protocol / interface changes
UsageStore.Leaderboardnow returns([]LeaderboardRow, error); both backends and all callers are updated.GET /v1/leaderboardreturns 503service_unavailablewith a positiveRetry-Afteron 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.idx_provider_earnings_created_at_brinandautovacuum_analyze_scale_factor=0.005onprovider_earnings. There is no provider/protocol version bump.Documentation impact
Notes for reviewers
PostgresStore.Leaderboardlives 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.goand runANALYZE provider_earningsbefore 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.
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.