Skip to content

Serve the public hashrate series from incremental rollups - #219

Merged
kiwidream merged 6 commits into
2.x.xfrom
hashrate-rollup-buckets
Sep 1, 2026
Merged

kiwidream merged 6 commits into
2.x.xfrom
hashrate-rollup-buckets

Conversation

@kiwidream

@kiwidream kiwidream commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Problem

/public/v1/hashrate-series re-aggregates raw qbit_share_ledger rows on every cache miss, so cost is linear in shares in range. With ~47 days of history the 1m/6m/all ranges exceed the fronting proxy's ~15s timeout and the dashboard's long-range charts 504 (measured live 2026-08-31: 1w answers in 0.9s; 1m, 6m, and all time out). Hashrate is growing fast, so the raw scan only gets worse.

Design

Maintain incremental per-bucket rollups — pool-wide and per-miner, at the 5m/1h/1d grains, keyed by the exact bucketing expression the serving query uses — advanced past a single durable watermark (qbit_hashrate_rollup_progress.last_share_seq):

  • Exactness. qbit_share_ledger rows are immutable and share_seq is append-only, so watermark batching folds every share into its (grain, bucket) rows exactly once regardless of accepted_at ordering; no re-aggregation window is needed. Rejected rows advance the watermark without counting.
  • Maintenance is one statement, one transaction: a guarded watermark upsert gates both rollup upserts, so a lost race writes nothing and the caller fails loudly instead of double-counting. It runs as a coordinator background service (hashrate-rollup-maintenance) — only the lease-holding writer mutates ledger-derived state; the read tier never runs it. A cold database backfills itself through the same statement live shares take (bounded batches, looping until caught up) — there is no separate migration to operate.
  • Serving merges exact-grain rollup buckets with a live tail of shares above the watermark in one statement (one snapshot, so a concurrent advance cannot double-count), re-aggregating only the bucket straddling the range lower bound, which raw scans emit partially. Cost is O(buckets in range) for every range including all.
  • The bar is byte-identical responses. Mid-backfill, an absent progress row, and a database without the rollup tables all degrade to exactly the raw scan, so pre-migration databases and half-deployed states stay correct with no operator action.

Knobs: PRISM_HASHRATE_ROLLUP_ENABLED (default on), PRISM_HASHRATE_ROLLUP_INTERVAL_SECONDS (default 15), PRISM_HASHRATE_ROLLUP_BATCH_SHARES (default 50000). No public contract change.

Verification

  • Full unit suite green on Linux (2973 tests) and macOS (modulo the five known macOS-only test_prism_job_builder splice tests).
  • make test-prism-postgres-ledger green end-to-end on Linux and macOS, including the new hashrate-rollup-parity (subjects × ranges × grains across every serving state, partial boundary bucket included) and hashrate-rollup-guard (watermark race under a real row lock) scenarios.
  • A 250k-share scale check confirms self-backfill and bucket-bound serving cost.

Deploy notes

  • The writer applies the idempotent DDL at startup; the read tier detects the tables without a restart and falls back to the raw scan until then.
  • During the initial backfill (~minutes for weeks of history at default batch size), long-range queries stay correct via the fallback/tail merge. If live share-append latency matters during backfill, lower PRISM_HASHRATE_ROLLUP_BATCH_SHARES.
  • Merges cleanly with Harden public hashrate-series reads: statement deadline, bucket vocabulary, in-process stale-while-revalidate #218. The block-markers PR touches adjacent regions of share_ledger.py and the Postgres gate; whichever lands second gets a small rebase.

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

kiwidream and others added 3 commits August 31, 2026 16:31
The dashboard hashrate-series endpoint re-aggregated raw share-ledger
rows on every cache miss, so long ranges (1m/6m/all) cost O(shares in
range) and timed out behind the proxy limit as pool history grew.
Maintain per-bucket rollups instead -- pool-wide and per-miner, at the
5m/1h/1d grains, keyed by the exact bucketing expression the serving
query uses so rollup and raw bucketing can never disagree -- advanced
incrementally past a single durable watermark. Share rows are immutable
and share_seq is append-only, so watermark batching folds every share
into its bucket exactly once with no re-aggregation window; rejected
rows advance the watermark without counting. The watermark advance is a
guarded upsert and both rollup upserts are gated on it winning, so a
lost race writes nothing at all and the caller fails loudly instead of
double-counting -- two live maintenance passes would mean the
single-writer invariant is already broken.

Serving merges exact-grain rollup buckets with a live tail of shares
above the watermark inside one statement (one snapshot, so a concurrent
advance cannot double-count), and re-aggregates only the bucket
straddling the range lower bound, which raw scans emit partially. The
bar is byte-identical responses in every state: mid-backfill, an absent
progress row, and a database without the rollup tables all degrade to
exactly the raw scan, which also keeps pre-migration databases and
half-deployed states working with no operator action.

Postgres gate scenarios pin the parity matrix (subjects x ranges x
grains across every serving state, the partial boundary bucket
included), accumulation across adjacent passes, the watermark guard
under a real row-lock race, and both fallbacks.

Co-Authored-By: Claude Fable 5 <[email protected]>
The rollups only stay cheap to serve while something keeps folding new
shares past the watermark. Register a coordinator background loop for
it -- the coordinator already holds the single writer role, and the
public read tier constructs its ledger without a writer lease and must
never run maintenance. Each pass folds one bounded batch and keeps
looping while the ledger reports more history behind the watermark,
which is also how a cold database with weeks of history backfills
itself through the very statement live shares take: there is no
separate migration to operate. Once caught up the loop sleeps the
configured interval; a failed pass logs and retries on the next
interval, and the transactional watermark makes retries exact.

The service registers only for ledgers exposing the rollup advance (the
Postgres backend). Unlike an enable flag, that capability cannot flip
after construction -- a memory-backed ledger never grows the method at
runtime -- so registering an unstartable service would only mislead the
registry snapshot. The enable flag and cadence stay live serve-time
attributes (PRISM_HASHRATE_ROLLUP_ENABLED, _INTERVAL_SECONDS,
_BATCH_SHARES) so tests and embedders can retune a constructed
coordinator, and lightweight coordinators built without the full
constructor read the absent flag as disabled.

Co-Authored-By: Claude Fable 5 <[email protected]>
The three PRISM_HASHRATE_ROLLUP_* variables join the operational knob
table with a short section on how the rollups, the backfill loop, and
the raw-scan fallback fit together, and the public dashboard contract
notes that hashrate-series is now served from incremental rollups -- a
serving-side change only, with the response schemas and values
unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 31, 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-09-01T13:37:18.899909Z fb3e6cf 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.

@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: 1ddc31326a

ℹ️ 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 lab/prism/share_ledger.py Outdated
Comment on lines +7568 to +7570
advance AS (
INSERT INTO qbit_hashrate_rollup_progress (singleton, last_share_seq)
VALUES (true, (SELECT next_share_seq FROM batch_stats))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Gate rollup mutations on the active writer lease

When the lease expires or is taken over before the old coordinator's heartbeat terminates it, this statement can still advance the watermark and update both rollup tables because it never checks or renews qbit_ledger_writer_lease. _run_fenced_json provides only a process-local operation lock; unlike the existing ledger mutations, the SQL has no exact (writer_id, writer_epoch, writer_session_token) lease CTE. Include that lease update in the statement and gate advance and both rollup upserts on its success so a fenced-out coordinator cannot continue mutating ledger-derived state.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Addressed in 6590388: the maintenance statement now renews and verifies the exact (writer_id, writer_epoch, writer_session_token) lease tuple in a lease CTE, mirroring mark_block_candidate_attempted, and the watermark upsert applies only when that renewal matched — so a fenced-out coordinator writes nothing and raises writer lease is not active. Worth noting the watermark CAS already prevented double-counting between racing passes; the lease gate closes the fencing-discipline gap rather than a counting race. New gate scenario hashrate-rollup-lease-fence stages a real takeover: the usurped pass leaves the watermark and both rollup tables untouched, and the restored lease folds the held-back share.

Comment on lines +2580 to +2581
accepted_share_count bigint NOT NULL CHECK (accepted_share_count >= 0),
accepted_share_difficulty numeric(78, 0) NOT NULL CHECK (accepted_share_difficulty >= 0),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Allow rollup difficulty totals to exceed one share's precision

When multiple individually valid 78-digit share_difficulty values land in one bucket, their sum can require 79 digits, but these aggregate columns retain the source row's numeric(78, 0) limit. For example, two accepted shares of 6e77 are valid ledger rows but make the maintenance insert fail with numeric overflow on every retry, preventing the watermark from progressing. The aggregate columns should use unconstrained numeric or enough additional precision for bucket totals, as the raw sum(numeric) does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Addressed in 6590388: both aggregate columns are unconstrained numeric now (matching the raw scan's sum(numeric)), with an idempotent, catalog-only ALTER for databases that already applied the constrained definition. New gate scenario hashrate-rollup-overflow folds three 6e77 shares into one bucket, covering both the oversized insert fold and the oversized ON CONFLICT accumulate — the exact statement a constrained column would fail on every retry.

…otals

Review follow-ups on the incremental hashrate rollups.

The maintenance statement ran under the process-local writer lock alone.
Every other mutation of ledger-derived state renews and verifies the exact
(writer_id, writer_epoch, writer_session_token) lease tuple inside its own
statement, and the rollup advance now does the same: the watermark upsert
applies only when that renewal matched, the rollup upserts were already
gated on the advance winning, and a fenced-out coordinator therefore writes
nothing and raises instead of continuing to mutate rollups after a
takeover. The watermark CAS already made concurrent passes safe against
double-counting; the lease gate closes the fencing-discipline gap, not a
counting race.

The aggregate difficulty columns mirrored the source column's
numeric(78, 0). Individually valid 78-digit share difficulties can sum past
that in one bucket, and a constrained aggregate would make the upsert
overflow on every retry and wedge the watermark permanently. Bucket totals
are unconstrained numeric now -- matching the raw scan's sum(numeric) --
with an idempotent catalog-only widen for databases that applied the
earlier definition.

Gate scenarios pin both: a 79-digit bucket total folds and accumulates
exactly, and a usurped lease leaves the watermark and both rollup tables
untouched while the pass fails loudly, then folds the held-back share once
the lease is restored.

Co-Authored-By: Claude Fable 5 <[email protected]>

@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: 6590388642

ℹ️ 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 lab/prism/share_ledger.py Outdated
FROM {rollup_table} rollup, bounds
WHERE (SELECT rollups_ready FROM watermark)
AND rollup.grain_seconds = {int(bucket_seconds)}
AND rollup.bucket_epoch <= floor(extract(epoch FROM bounds.ended_at) / {int(bucket_seconds)})::bigint * {int(bucket_seconds)}{rollup_lower_bound}{rollup_subject_filter}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Re-aggregate the current bucket before applying the upper bound

When the coordinator clock is ahead of the PostgreSQL clock, a share can be stored with accepted_at > bounds.ended_at because accepted_at_ms is assigned by the coordinator, yet this predicate includes the entire rolled-up current bucket. The historical raw query—and the tail branch below—exclude such shares with ledger.accepted_at <= bounds.ended_at, so a caught-up rollup response can expose future-dated shares and cease being byte-identical to the raw result. Exclude the current rollup bucket and re-aggregate its rolled portion from the ledger through bounds.ended_at, similarly to the partial lower-bound bucket.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Addressed in 2bc5b01: the rolled branch now stops strictly below the bucket containing bounds.ended_at, and one boundary re-aggregation covers both partial ends (range lower bound and the current bucket) from the already-rolled-up sequence range with the raw scan's accepted_at <= ended_at predicate applied — bounded by one bucket span each. The gate's parity scenario now folds a future-dated share into the rollups and holds every serving state to excluding it exactly as the raw scan does.

Second-round review follow-up on the incremental hashrate rollups.

Maintenance folds by sequence, so a coordinator clock running ahead of the
database clock can put a share into the current bucket's rollup row that
the raw scan's accepted_at <= ended_at would exclude until the clocks catch
up -- and the rolled branch served that row whole, breaking byte parity for
exactly the window of the skew. The bucket containing the statement's upper
bound is now treated like the partial lower-bound bucket: the rolled branch
stops strictly below it and a single boundary re-aggregation covers both
partial ends from the already-rolled-up sequence range, bounded by one
bucket span of shares each, with the raw scan's upper-bound predicate
applied. The gate's parity scenario now seeds a future-dated share and
holds every serving state to excluding it exactly as the raw scan does.

Co-Authored-By: Claude Fable 5 <[email protected]>

@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: 2bc5b011b8

ℹ️ 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 lab/prism/prism_coordinator.py Outdated
Comment on lines +6919 to +6921
result = self.ledger.advance_hashrate_rollups(
batch_limit=self.hashrate_rollup_batch_shares,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Track rollup passes as writer operations

When shutdown is requested after the loop's stop check but before this call begins, the pass is not registered with CoordinatorShutdownController, so shutdown() can observe zero active writers and release the lease concurrently. Since release merely expires the existing tuple and advance_hashrate_rollups() renews an exact matching tuple without requiring it to remain unexpired, the delayed pass can renew the released lease and mutate rollups after shutdown reported success, potentially delaying or overlapping a successor coordinator. Run each pass inside _writer_operation("hashrate_rollup_maintenance") so shutdown closes its admission and includes it in writer quiescence.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Addressed in fb3e6cf: each ledger advance now runs inside _writer_operation("hashrate_rollup_maintenance"), so shutdown quiescence counts an in-flight pass and a closed admission refuses new ones; the loop treats ShutdownInProgress as the orderly stop. Unit tests pin both sides — a pass holds and releases the admission, and a closed admission exits without touching the ledger.

Third-round review follow-up on the incremental hashrate rollups.

The maintenance loop only consulted the stop event, so a pass beginning
after the stop check could race an orderly shutdown: quiescence observed
zero active writers, released the lease -- which expires the tuple but
keeps its identity -- and the delayed pass then renewed that exact identity
and mutated rollups after shutdown reported the writer quiesced,
potentially delaying a successor's takeover. Each ledger advance now runs
inside _writer_operation("hashrate_rollup_maintenance"), like every other
mutation of ledger-derived state: shutdown counts an in-flight pass and
refuses a new one, and the loop treats the refusal as the orderly stop
rather than a failure.

Unit tests pin both sides: a pass executes with the admission held and
releases it, and a closed admission exits the loop without touching the
ledger or logging an error.

Co-Authored-By: Claude Fable 5 <[email protected]>
@kiwidream
kiwidream merged commit dc8f6c8 into 2.x.x Sep 1, 2026
11 checks passed
@kiwidream
kiwidream deleted the hashrate-rollup-buckets branch September 1, 2026 17:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant