Repository navigation
perf(coordinator): all-time totals and leaderboard from earnings_summary - #1144
brandon-eigenlabs wants to merge 1 commit into
Conversation
|
@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>
142c3bd to
cf68133
Compare
|
Rebased onto |
|
Refresh note (2026-09-29): this PR no longer rebases cleanly onto master, and the conflict is semantic, not textual.
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 |
|
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. |
Summary
window=all— the default for/v1/network/totals— is the most expensive window: three CTEs over a ~140M-rowprovider_earningstable that exceed the 10 s store timeout (planner cost ~29M; 503 in production since 2026-09-10).earnings_summaryalready holds the lifetime totals, maintained in the same transaction as every earnings write, but folds base rewards intototal_micro_usdand so could not reproduce the API's work/reward split. This addstotal_base_reward_micro_usdto the summary, maintains it at every writer, backfills the history once at boot fromprovider_floor_draws, and answers all-timeNetworkTotals/Leaderboardfrom 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/— cleancd coordinator && go test ./store/ -count=1— pass (memory backend of the parity test runs locally; Postgres-backed tests skip withoutDATABASE_URL)cd coordinator && go test $(go list ./... | grep -v /internal/api) -count=1— the pre-push set, passmake 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 OKDATABASE_URL) runs the three Postgres-backed tests below — no local Postgres on this boxTests (
coordinator/store/postgres_earnings_all_time_test.go):TestAllTimeTotalsAndLeaderboardAgreeAcrossBackends— seeds inference work, a floor draw, abase_rewardearning 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-timeNetworkTotalsrow and leaderboard rows (all three metrics) on memory and Postgres viastoreBackends. 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 readsearnings_summaryand neverprovider_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 fromprovider_floor_drawsis 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:
testPostgresStorenow truncatesearnings_summaryand both pending tables together withprovider_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
Protocol / interface changes
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 newearnings_summary_base_reward_pendingqueue table, and twoschema_migrationsmarkers (prepare_…,backfill_earnings_summary_base_reward_v1).Documentation impact
docs/architecture/storage.md: the boot-time migration list gainsmigrateEarningsSummaryBaseReward; 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_drawsat read timeVerified on the production read replica (2026-09-19):
SUM(amount)overprovider_floor_drawsequals themodel='base_reward'share ofprovider_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 trackprovider_earningswithin the ingestion delta between measurements, and there are no rows with an emptyaccount_idorprovider_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)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, cachedBefore / 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 endflowchart 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 endBackfill protocol and its limits
Same shape as
migrateEarningsSummary: one planning transaction pins aREPEATABLE READsnapshot, writes per-key deltas toearnings_summary_base_reward_pendingand 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 instorage.md. If exactness matters, deploy outside a base-reward settlement window or run the plan statement'sSELECToffline against the column afterwards.Deployment
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.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);EXPLAINoncurl .../v1/network/totals?window=allpath is not directly observable — instead confirm the endpoint returns 200 within milliseconds andcache.refresh_failed{key:network_totals:all}stops incrementing.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 newleaderboardAllTimeshould return([]LeaderboardRow, error)instead ofnilon 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.GetProviderEarningsSummary/ProviderEarningsSummary.queryMudecoupling and alerting oncache.refresh_failed.Limitations
v0.3.6/v0.4.0with zero open items.🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.