Skip to content

fix(coordinator): 503 from /v1/leaderboard when the ranking query fails - #1140

Closed
brandon-eigenlabs wants to merge 1 commit into
Layr-Labs:masterfrom
brandon-eigenlabs:fix/leaderboard-store-error
Closed

brandon-eigenlabs wants to merge 1 commit into
Layr-Labs:masterfrom
brandon-eigenlabs:fix/leaderboard-store-error

Conversation

@brandon-eigenlabs

@brandon-eigenlabs brandon-eigenlabs commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

store.Leaderboard swallowed every query error and returned nil, so a timed-out ranking over provider_earnings was served as 200 {"entries":[]} and cached for five minutes as if no provider had earned anything — while /v1/network/totals hitting the same 10 s timeout on the same table answered 503. This makes Leaderboard return ([]LeaderboardRow, error) on both backends and has handleLeaderboard answer 503 service_unavailable without caching, matching handleNetworkTotals and handleNetworkSeries. A genuinely empty window is still a successful, cacheable 200.

Linked issue

Closes #1139

Test plan

Local, on this branch (coordinator/):

  • gofmt -l ./store ./api — clean
  • go build ./... (root module) — ok
  • go vet ./store/ ./api/ — clean
  • go test ./store/ -run 'Leaderboard|NetworkTotals|IsRewardLedgerType' -count=1 — pass
  • go test ./api/ -run 'Leaderboard|Totals|StatsRefresh|CacheRefresh' -count=1 — pass (includes the two new regression tests below)
  • go test $(go list ./... | grep -v /internal/api) -count=1 — the pre-push set, pass
  • make docs-check — 309 files OK
  • make docs-impact-check BASE=origin/master — see Documentation impact
  • CI Postgres job runs TestLeaderboardReturnsErrorWhenUnavailable (needs DATABASE_URL; skipped locally, no Postgres on this box)

New tests:

  • coordinator/api/leaderboard_test.go
    • TestLeaderboardStoreErrorIs503NotEmptyBoard — failing store → 503 service_unavailable, nothing cached under leaderboard:earnings:24h:50; after recovery → 200 with the seeded row and the body is cached. Fails without the fix (previously 200 with entries: [], cached).
    • TestLeaderboardEmptyWindowIs200 — pins the contract that no earnings is a successful, cached empty board.
  • coordinator/store/analytics_workmem_test.go
    • TestLeaderboardReturnsErrorWhenUnavailable — Postgres closed-pool test mirroring TestNetworkTotalsReturnsErrorWhenUnavailable.
  • coordinator/store/leaderboard_rewards_test.go — existing memory-store suite moved to the two-value signature via a mustLeaderboard helper; semantics unchanged.

Components touched

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

Protocol / interface changes

  • No protocol/interface changes

  • Yes — described above and matching side updated

  • HTTP: GET /v1/leaderboard gains a 503 service_unavailable response (standard error envelope) on a store error after a cache miss. Success shape unchanged. console-ui/src/app/api/leaderboard/route.ts already forwards non-2xx upstream statuses and useLeaderboard already surfaces !res.ok as an error state, so the UI now shows its existing error state instead of an empty board — no UI change required.

  • Go interface: store.UsageStore.Leaderboard → ([]LeaderboardRow, error). Both implementations (MemoryStore, PostgresStore) and the only caller updated. No WebSocket, config, CLI, schema or migration change; no version bump.

Documentation impact

  • Canonical documentation updated

  • No documentation needed — reason:

  • docs/reference/api-contracts.md: /v1/leaderboard row now states the 503 semantics (and drops the stale "1 min (recent window)" claim — the handler has always cached 5 min unconditionally); 503-envelope paragraph lists the leaderboard handler; freshness stamp refreshed.

  • CHANGELOG.md: new Unreleased — leaderboard availability entry.

  • make docs-impact-check additionally reports the storage schema rule for coordinator/store/postgres.go → docs/architecture/storage.md. That mapping does not apply here: the change to postgres.go is the Leaderboard method's return type and error handling, not a table, index or migration, and storage.md documents no per-method contract for it (its only mention is the generic UsageStore row). Per the contributor skill I have not padded storage.md to satisfy the gate — maintainer: please apply docs-not-needed (the label does not exist in the repo yet and needs creating).

Notes for reviewers

Before / after — observable behavior

sequenceDiagram
    participant C as Client
    participant H as handleLeaderboard
    participant S as store.Leaderboard
    participant DB as provider_earnings
    Note over C,DB: BEFORE
    C->>H: GET /v1/leaderboard (cache miss)
    H->>S: Leaderboard(metric, since, limit)
    S->>DB: 3-CTE aggregate (10 s ctx)
    DB-->>S: context deadline exceeded
    S-->>H: nil  (error swallowed)
    H->>H: readCache.Set(key, {"entries":[]}, 5 min)
    H-->>C: 200 {"entries":[]}
    Note over C: indistinguishable from "nobody earned anything" for 5 min
Loading
sequenceDiagram
    participant C as Client
    participant H as handleLeaderboard
    participant S as store.Leaderboard
    participant DB as provider_earnings
    Note over C,DB: AFTER
    C->>H: GET /v1/leaderboard (cache miss)
    H->>S: Leaderboard(metric, since, limit)
    S->>DB: 3-CTE aggregate (10 s ctx)
    DB-->>S: context deadline exceeded
    S-->>H: nil, error
    H->>H: log warn + ddIncr cache.refresh_failed{key}
    H-->>C: 503 {"error":{"code":"service_unavailable",...}}
    Note over H: nothing cached — next request retries
Loading

Before / after — code flow

flowchart TD
    subgraph BEFORE
        A1[pool.Query] -->|err| B1[return nil]
        A1 -->|ok| C1[rows.Scan]
        C1 -->|err| D1[continue  — row dropped]
        C1 -->|ok| E1[append]
        B1 --> F1["handler: len(rows)==0"]
        E1 --> F1
        F1 --> G1[json.Marshal → readCache.Set 5m → 200]
    end
Loading
flowchart TD
    subgraph AFTER
        A2[pool.Query] -->|err| B2["return nil, err"]
        A2 -->|ok| C2[rows.Scan]
        C2 -->|err| B2
        C2 -->|ok| E2[append]
        E2 --> R2[rows.Err]
        R2 -->|err| B2
        R2 -->|ok| S2["return out, nil"]
        B2 --> H2["handler: 503 service_unavailable, no Set"]
        S2 --> G2[json.Marshal → readCache.Set 5m → 200]
    end
Loading

Metric choice

The failure path reuses cache.refresh_failed tagged key:leaderboard:<metric>:<window>:<limit> rather than adding a new metric, so it lands next to the existing network_totals:* failures from cache_refresher.go and any alert built on that name covers both.

Scan-error semantics

Previously a rows.Scan failure silently dropped that row and published the rest as a complete board. It now fails the request; a partially-read ranking is as misleading as an empty one.

Deliberately out of scope

This PR only makes the failure honest. The aggregate's cost is a separate problem: in production provider_earnings is ~140M rows / 33 GB with no created_at-leading index, so 24h/7d windows plan as parallel seq scans and all as a full index scan, and the 10 s timeout is exceeded for cache misses. Candidate follow-ups (serve window=all from the already-maintained earnings_summary table, a created_at index built CONCURRENTLY, a time-bucketed rollup for 30d) each change semantics or schema and deserve their own issue/PR.

Limitations

  • The Postgres-backed test is only exercised in CI (DATABASE_URL); it was not run locally. CI's Coordinator Tests ran it against the Postgres service and passed on the rebased head (c8ec7529d): DATABASE_URL was set, and coordinator/store took 54 s there versus under 1 s locally, where these tests skip.
  • No milestone set: the only open milestones are v0.3.6 / v0.4.0 with zero open items and the coordinator is at 0.9.x — please assign if a release is targeted.
  • Pushed from a fork because upstream branch creation is ruleset-restricted.

🤖 Generated with Claude Code


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

@brandon-eigenlabs brandon-eigenlabs added bug Something isn't working area:coordinator Coordinator (Go) labels Sep 19, 2026
@vercel

vercel Bot commented Sep 19, 2026

Copy link
Copy Markdown

@brandon-eigenlabs is attempting to deploy a commit to the EigenLabs Team on Vercel.

A member of the Team first needs to authorize it.

@brandon-eigenlabs

Copy link
Copy Markdown
Contributor Author

Rebased onto master at 76a8f03d9 after the v0.9.7 release. Only CHANGELOG.md (the entry now sits under the new ## Unreleased list) and a docs freshness stamp conflicted; the Go changes merged cleanly and store/api tests, docs-check and docs-impact-check were re-run on the rebased branch. No functional change.

store.Leaderboard swallowed every query error and returned nil, so a
timed-out ranking over provider_earnings reached the handler as an empty
slice, was served as 200 {"entries":[]} and cached for five minutes as if
no provider had earned anything. /v1/network/totals hitting the same 10 s
timeout on the same table already answers 503, so the two public endpoints
disagreed about the same outage.

Make Leaderboard return ([]LeaderboardRow, error) on both store backends,
fail on scan/iteration errors instead of silently dropping rows, and have
handleLeaderboard answer 503 service_unavailable without caching, matching
handleNetworkTotals and handleNetworkSeries. A genuinely empty window is
still a successful, cacheable 200.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@jonathan308

Copy link
Copy Markdown
Collaborator

Closing this PR as retired from d-inference: it changes the coordinator leaderboard API and store failure contract. Those now belong in https://github.com/Layr-Labs/darkbloom-platform; see merged #1408 and #1410. No exact successor was verified. Retirement here does not assert that the error-handling fix was merged, deployed or the defect resolved.

This branch was successfully deployed

No deployments
benchmarks — c8ec7529 Deployed Sep 29, 2026 by brandon-eigenlabs via E2E Benchmarks #1858
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:coordinator Coordinator (Go) bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] /v1/leaderboard serves a timed-out ranking query as 200 {"entries":[]} and caches it for 5 min

2 participants