Skip to content

perf(coordinator): all-time totals and leaderboard from earnings_summary - #1144

Closed
brandon-eigenlabs wants to merge 1 commit into
Layr-Labs:masterfrom
brandon-eigenlabs:perf/all-window-from-earnings-summary
Closed

brandon-eigenlabs wants to merge 1 commit into
Layr-Labs:masterfrom
brandon-eigenlabs:perf/all-window-from-earnings-summary

Conversation

@brandon-eigenlabs

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

Copy link
Copy Markdown
Contributor

Summary

window=all — the default for /v1/network/totals — is the most expensive window: three CTEs over a ~140M-row provider_earnings table that exceed the 10 s store timeout (planner cost ~29M; 503 in production since 2026-09-10). earnings_summary already holds the lifetime totals, maintained in the same transaction as every earnings write, but folds base rewards into total_micro_usd and so could not reproduce the API's work/reward split. This adds total_base_reward_micro_usd to the summary, maintains it at every writer, backfills the history once at boot from provider_floor_draws, and answers all-time NetworkTotals/Leaderboard from the summary (planner cost ~3K). Windowed queries are unchanged.

Linked issue

Closes #1143

Test plan

Local, on this branch:

  • cd coordinator && gofmt -l ./store — clean; go build ./... — ok; go vet ./store/ — clean
  • cd coordinator && go test ./store/ -count=1 — pass (memory backend of the parity test runs locally; Postgres-backed tests skip without DATABASE_URL)
  • cd coordinator && go test $(go list ./... | grep -v /internal/api) -count=1 — the pre-push set, pass
  • make docs-stamp FILES=docs/architecture/storage.md, make docs-impact-check BASE=origin/master — "11 changed file(s), canonical documentation coverage OK"
  • make docs-check — 309 files OK
  • CI Postgres job (DATABASE_URL) runs the three Postgres-backed tests below — no local Postgres on this box

Tests (coordinator/store/postgres_earnings_all_time_test.go):

  • TestAllTimeTotalsAndLeaderboardAgreeAcrossBackends — seeds inference work, a floor draw, a base_reward earning through the generic path, ledger rewards for a provider and for a consumer-only account, and an earning with no account; asserts the exact all-time NetworkTotals row and leaderboard rows (all three metrics) on memory and Postgres via storeBackends. On Postgres the numbers come from the summary, so this proves every writer maintains the new column.
  • TestPostgresAllTimeMatchesWindowScan — with the statement tracer, asserts the all-time path reads earnings_summary and never provider_earnings, and that it equals the scan path (since = Unix epoch) row-for-row for totals and all three leaderboard metrics.
  • TestEarningsSummaryBaseRewardBackfill — isolated database: history from provider_floor_draws is added to existing rows, a missing summary row is created with the reward as its total, zero-amount draws are ignored, a rerun is a no-op, and a leftover queue after a simulated crash is drained exactly once with the completion marker restored.

Harness change: testPostgresStore now truncates earnings_summary and both pending tables together with provider_earnings. Before this the test database's summary silently drifted from its source between tests; now that the all-time paths read the summary, it must reset with its source.

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

No HTTP, WebSocket, config or CLI change; response shapes and semantics are unchanged (the tests pin equality with the scan). Schema/migration effect (no version bump): ALTER TABLE earnings_summary ADD COLUMN IF NOT EXISTS total_base_reward_micro_usd BIGINT NOT NULL DEFAULT 0 (instant in PG ≥ 11), a new earnings_summary_base_reward_pending queue table, and two schema_migrations markers (prepare_…, backfill_earnings_summary_base_reward_v1).

Documentation impact

  • Canonical documentation updated
  • No documentation needed — reason:

docs/architecture/storage.md: the boot-time migration list gains migrateEarningsSummaryBaseReward; a new paragraph documents the column, its writers, the backfill protocol and the blue-green limitation; the Bookkeeping table family and the code map list the new table and files; stamp refreshed. CHANGELOG.md: Unreleased — all-time earnings from the summary table.

Notes for reviewers

Why a column, not provider_floor_draws at read time

Verified on the production read replica (2026-09-19): SUM(amount) over provider_floor_draws equals the model='base_reward' share of provider_earnings (13.82B micro-USD; the 1.35M extra draw rows are zero-amount and never produced an earnings row), so it is a correct source — but it is 7.3M rows / 3.2 GB and a plain aggregate took ~50 s cold. Fine for a one-time backfill, not for a request path. The summary's account and provider partitions agree exactly (40.66B micro-USD, 138.5M jobs, 476B tokens) and track provider_earnings within the ingestion delta between measurements, and there are no rows with an empty account_id or provider_key.

Before / after — observable behavior

sequenceDiagram
    participant R as totals refresher / leaderboard miss
    participant S as NetworkTotals / Leaderboard (since = zero)
    participant PE as provider_earnings (140M rows)
    Note over R,PE: BEFORE
    R->>S: all-time aggregate (10 s ctx)
    S->>PE: 3 CTEs: full index scan / seq scans (cost ~29M)
    PE--xS: context deadline exceeded
    S-->>R: error → 503 / cache latch (totals), or empty board (leaderboard, pre-#1140)
Loading
sequenceDiagram
    participant R as totals refresher / leaderboard miss
    participant S as NetworkTotals / Leaderboard (since = zero)
    participant ES as earnings_summary (~54K rows)
    participant L as ledger_entries (idx_ledger_reward)
    Note over R,ES: AFTER
    R->>S: all-time aggregate
    S->>ES: SUM / rank over summary rows (cost ~3K)
    S->>L: reward join, index scan
    ES-->>S: totals with work = total − base_reward
    S-->>R: 200, cached
Loading

Before / after — code flow

flowchart TD
    subgraph BEFORE
        W1["writers: RecordProviderEarning / creditProviderAccount / SettleProviderFloorDraw"] --> ES1["earnings_summary\n(total_count, total_micro_usd, tokens)"]
        NT1[NetworkTotals since] --> Q1["3-CTE scan of provider_earnings\n(all windows incl. all-time)"]
        LB1[Leaderboard since] --> Q1
    end
Loading
flowchart TD
    subgraph AFTER
        W2["writers (same 3, 5 statements)"] --> ES2["earnings_summary\n+ total_base_reward_micro_usd"]
        M2["migrate(): migrateEarningsSummaryBaseReward\nplan (REPEATABLE READ) → pending → per-key apply → marker"] -. once .-> ES2
        NT2[NetworkTotals since] -->|"since.IsZero()"| A2[networkTotalsAllTime → earnings_summary + ledger]
        NT2 -->|windowed| Q2[3-CTE scan, unchanged]
        LB2[Leaderboard since] -->|"since.IsZero()"| B2[leaderboardAllTime → earnings_summary + ledger]
        LB2 -->|windowed| Q2
    end
Loading

Backfill protocol and its limits

Same shape as migrateEarningsSummary: one planning transaction pins a REPEATABLE READ snapshot, writes per-key deltas to earnings_summary_base_reward_pending and commits them with the plan marker atomically; each key is then added (… = … + delta) and dequeued in its own short transaction, so a crash resumes without double-adding; the completion marker is written when the queue is empty. Nothing is applied before the plan marker commits, so a failed plan is simply replanned — this is why it does not need the attempted-plan marker the original backfill uses. Per-key application never holds two summary rows at once, so it cannot form a lock cycle with a live writer's account+provider upsert.

Known undercount: base rewards that a previous coordinator settles after the plan snapshot, during the blue-green overlap, are added to total_micro_usd (old writers still maintain that) but not to the new column. Totals stay exact; the work/reward split understates reward by that amount (one or a few epochs' worth for the providers settled in that window). Documented in storage.md. If exactness matters, deploy outside a base-reward settlement window or run the plan statement's SELECT offline against the column afterwards.

Deployment

  • First boot after deploy is slower once: the plan aggregates provider_floor_draws (3.2 GB, tens of seconds) and then applies ~54K single-key statements (accounts + providers; a minute or two). No table locks that block writers. Later boots hit the completion marker.
  • Verify after deploy: SELECT SUM(total_micro_usd), SUM(total_base_reward_micro_usd) FROM earnings_summary WHERE key_type='account'; should show base ≈ 13.8B micro-USD (2026-09-19 value; it grows); EXPLAIN on curl .../v1/network/totals?window=all path is not directly observable — instead confirm the endpoint returns 200 within milliseconds and cache.refresh_failed{key:network_totals:all} stops incrementing.
  • Rollback: the column and queue table are additive; an older binary ignores them.

Overlap with #1140 and #1142

Both edit the tail of PostgresStore.Leaderboard (error propagation; analytics transaction). This PR inserts an early return above that tail and leaves the windowed body untouched, so the merge is clean; after #1140 lands the new leaderboardAllTime should return ([]LeaderboardRow, error) instead of nil on error — a mechanical follow-up I will make on whichever branch is still open.

Deliberately out of scope

  • window=30d (76% of the table) still scans; it needs a time-bucketed rollup.
  • The provider partition's new column is maintained and backfilled for consistency but not yet exposed on GetProviderEarningsSummary / ProviderEarningsSummary.
  • Refresher queryMu decoupling and alerting on cache.refresh_failed.

Limitations

  • The Postgres-backed tests only run in CI.
  • Production numbers above come from the read replica; the fast path itself cannot be exercised there before deploy (the column does not exist yet).
  • No milestone set: open milestones are v0.3.6 / v0.4.0 with zero open items.

🤖 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.

@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.

The all-time window is the default for /v1/network/totals and the most
expensive: three scans of a ~140M-row provider_earnings table that exceed
the 10 s store timeout. earnings_summary already holds per-account and
per-provider lifetime totals, maintained in the same transaction as every
earnings write, but it folds base rewards into total_micro_usd and so could
not reproduce the API's work/reward split.

Add total_base_reward_micro_usd to earnings_summary. Every summary writer
(RecordProviderEarning, creditProviderAccount, SettleProviderFloorDraw)
maintains it, and a one-shot boot migration fills the history from
provider_floor_draws — the settlement record behind every base_reward
earning and an order of magnitude smaller than provider_earnings — using
the summary backfill's shape: a REPEATABLE READ plan commits per-key deltas
with its marker, each is added and dequeued in a short transaction, and the
completion marker keeps later boots from rescanning. NetworkTotals and
Leaderboard then answer a zero since from the summary joined to the
already-indexed reward ledger; windowed queries are unchanged.

The test harness now truncates the summary tables with provider_earnings,
since the summary is derived from it and the all-time paths now read it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@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.

@brandon-eigenlabs

Copy link
Copy Markdown
Contributor Author

Refresh note (2026-09-29): this PR no longer rebases cleanly onto master, and the conflict is semantic, not textual.

networkTotalsAllTime reads the provider-keyed earnings_summary partition (key_type = 'provider'). #1208 removed the three upserts that maintained those rows (they were written but never read at the time), and deleted earningsSummaryBackfillPendingDDL, which this PR references. Resolving the conflict by restoring the upserts would leave the provider partition missing every earning written while a post-#1208 coordinator was running, so all-time totals would silently undercount.

Options before this can move: (a) restore the provider upserts plus a new one-shot migration that rebuilds provider rows, or (b) rework the all-time path to avoid provider rows, e.g. a single network-wide summary row maintained on every earning write. Parked until that's decided.

🤖 Generated with Claude Code

@jonathan308

Copy link
Copy Markdown
Collaborator

Closing this PR as retired from d-inference: the all-time earnings aggregation and associated store migration now belong in https://github.com/Layr-Labs/darkbloom-platform under merged #1408 and #1410. No exact successor was verified. This is repository cleanup, not a claim that the optimization was merged, its migration applied or any behavior deployed.

This branch had an error being deployed

1 failed deployment
benchmarks — cf681338 Deployed Sep 21, 2026 by brandon-eigenlabs via E2E Benchmarks #1502
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:coordinator Coordinator (Go) enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf: serve all-time /v1/network/totals and /v1/leaderboard from earnings_summary instead of scanning provider_earnings

2 participants