Skip to content

Harden public hashrate-series reads: statement deadline, bucket vocabulary, in-process stale-while-revalidate - #218

Merged
kiwidream merged 3 commits into
2.x.xfrom
harden-public-hashrate-reads
Sep 1, 2026
Merged

kiwidream merged 3 commits into
2.x.xfrom
harden-public-hashrate-reads

Conversation

@kiwidream

@kiwidream kiwidream commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Problem

On prismpool.io, /public/v1/hashrate-series with range=1m|6m|all dies at the fronting proxy's ~15s timeout (504) while range=1w answers in under a second. Beyond the slow query itself (fixed separately by the rollups PR), the read path had three structural weaknesses:

  • A request the proxy already abandoned kept its Postgres scan running to completion, pinning one of the four bounded read slots (PRISM_POSTGRES_READ_CONCURRENCY) and competing with the share writer's I/O.
  • range=all&bucket=5m was a legal unauthenticated request whose response outgrows PRISM_PUBLIC_CACHE_MAX_RESPONSE_BYTES, so every such request bypassed the cache and re-scanned the full ledger.
  • An expired in-process cache entry was dropped outright, so the next visitor blocked for the entire recompute even though the policy already advertised stale-while-revalidate to CDNs.

Changes

  • Statement deadline on public origin computations. Database-backed routes run dispatch under the ledger's statement_timeout scope (PRISM_PUBLIC_READ_STATEMENT_TIMEOUT_SECONDS, default 20s, 0 disables), duck-typed like the coordinator's block-submitter scope. A ledger-reported deadline becomes a 503 read_timeout, no-store and never cached.
  • Static bucket-per-range vocabulary. Each range admits a fixed bucket set (1w: 5m/1h/1d; 1m: 1h/1d; 6m and all: 1d), rejected with a 400 naming the allowed buckets. bucket=auto always resolves inside the sets; the deployed frontend only sends auto, so no real client breaks.
  • In-process stale-while-revalidate. An expired entry inside the SWR window is served immediately with its honest Age while at most one background refresh per key recomputes through the ordinary gates. The window is clamped to the route's staleness budget minus its TTL so a stale serve can never trip the unconditional budget refusal, and it is withdrawn entirely while the database is unreachable so the outage contract is unchanged.

No response body schema changes; only new 400/503 error paths and cache/header behavior. Docs and OpenAPI updated.

Verification

  • Full unit suite green on Linux (2986 tests) and macOS (modulo the five known macOS-only test_prism_job_builder splice tests).
  • make test-prism-postgres-ledger green on Linux.
  • New tests: clamp 400s, timeout 503 with no cache poisoning, statement-scope wiring (applied only to database-reading paths, not when disabled), SWR cache behavior (stale serve, single refresh, refresh failure keeps stale, beyond-window blocking miss), STALE metrics.

Notes for review

  • On 2.x.x the read service is the only public dispatch site; the coordinator's listener refuses /public/v1, so there is no second call site to wrap.
  • Merges cleanly with the rollups PR. The block-markers PR carries its own copy of the per-range bucket table (written before this one existed); whichever lands second gets a small dedupe 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.

@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:30:37.415810Z a18bea7 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: 62994d6290

ℹ️ 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 on lines +900 to +902
else lambda: bounded_public_dispatch(
coordinator, path, query, reads_database=reads_database
)

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 Apply the deadline to artifact database lookups

For a cold /public/v1/artifacts/{sha256} request, artifact() calls the ledger's dashboard_public_artifact_document, and the endpoint registry classifies that operation as READ_SLOT; however, path_reads_database() returns false for immutable endpoints, so the value passed here causes bounded_public_dispatch() to skip the new statement-timeout scope. Requests using distinct or uncached hashes can therefore continue occupying Postgres read slots without the advertised deadline. Keep the immutable exemption for staleness/replica decisions, but classify database access separately when deciding whether to arm the timeout.

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 b8b2945: a new path_occupies_read_slot() (registry READ_SLOT access, immutable or not) now decides the deadline, so a cold artifact lookup is bounded, while path_reads_database() keeps its immutable exemption for the replica/outage gates. Wiring test updated to assert the split explicitly.

Comment thread lab/prism/public_api.py
Comment on lines +256 to +260
for stale_key in [
stored_key
for stored_key, stored in self._entries.items()
if stored_key != key and stored.expires_at <= now
]:

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 Preserve stale entries during capacity reaping

When the cache exceeds PRISM_PUBLIC_CACHE_MAX_ENTRIES, this loop removes every entry whose TTL has expired, even when that entry remains eligible for the newly added stale-while-revalidate window. Consequently, once a full cache receives another key, otherwise servable stale entries are discarded and their next visitors block on origin recomputation instead of receiving the promised stale response. The entry needs to retain its stale-window bound so reaping removes only entries past both TTL and SWR.

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 b8b2945: entries record their own stale_until (TTL + the SWR window they were stored under) and capacity reaping now removes only entries past that bound, so a full cache sheds dead weight without discarding promised stale-servable answers. Added a test where a dead entry is reaped while an expired-but-within-window entry survives and still serves STALE.

def test_a_ledger_deadline_becomes_a_503_read_timeout_and_is_never_cached(self) -> None:
ledger = TimingOutPublicLedger()
base = self.serve(ledger)
with patch.dict(os.environ, {}, clear=True):

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 Preserve proxy bypass settings in localhost tests

In environments that define an HTTP proxy, clearing all of os.environ also removes NO_PROXY while urllib.request may retain a previously initialized proxy opener. The localhost request is then sent through the proxy rather than to the test server; running the added cache/bucket tests before this class reproduced 403 responses in all three statement-timeout tests. Patch only PRISM_PUBLIC_READ_STATEMENT_TIMEOUT_SECONDS (deleting that single key when testing the default), or explicitly use a no-proxy opener.

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 b8b2945: the three statement-timeout tests no longer clear the environment — they patch only PRISM_PUBLIC_READ_STATEMENT_TIMEOUT_SECONDS (popping just that key for the default-value test), so NO_PROXY and friends survive on proxy-configured machines.

Three independent hardenings on the public read tier, each standing
alone ahead of the aggregate-rollup work.

Statement deadline on public origin computations. A request the
fronting proxy abandoned at its ~15s timeout kept its Postgres scan
running to completion, holding one of the four bounded read slots
against every other public read and competing with the share writer's
I/O. Database-backed routes now run dispatch under the ledger's
statement_timeout scope (PRISM_PUBLIC_READ_STATEMENT_TIMEOUT_SECONDS,
default 20s, 0 disables), duck-typed exactly like the coordinator's
block-submitter scope so scope-less ledgers keep working. A
ledger-reported deadline becomes a 503 with the new read_timeout error
code, no-store and never cached, so one expensive miss cannot poison
the response cache with a refusal. On 2.x.x the read service is the
only public dispatch site; the coordinator's listener refuses
/public/v1 outright, so no second call site exists to wrap.

Static bucket-per-range vocabulary on the hashrate series.
range=all&bucket=5m was a legal unauthenticated full-table scan whose
response outgrows the cache size cap, so every such request re-scanned
the ledger with no cache in front of it. Each range now admits a fixed
bucket set (1w: 5m/1h/1d; 1m: 1h/1d; 6m and all: 1d), rejected with a
400 naming the allowed buckets. bucket=auto always resolves inside the
allowed sets, and the deployed frontend only ever sends auto, so no
real client breaks. The vocabulary and its check are importable for
the block-marker series to reuse.

In-process stale-while-revalidate. The cache policy already carried
stale_while_revalidate_seconds but only advertised it to CDNs; an
expired in-process entry was dropped and the next requester blocked
for the full recompute. An expired entry inside the window is now
served immediately with its honest Age while at most one background
refresh per key recomputes through the ordinary status/size gates;
concurrent stale hits share that refresh, and a failed refresh keeps
the stale entry servable and frees the slot for a retry. The
in-process window is clamped to the route's staleness budget minus its
TTL, so a stale serve can never trip the unconditional budget refusal
that the blocking path used to satisfy by recomputing, and it is
withdrawn entirely while the database is unreachable so the outage
contract is unchanged. The read service counts the new STALE state in
its cache metrics.

No response body schema changes: only the new 400/503 error paths and
cache/header behavior. The dashboard README and OpenAPI document the
vocabulary, the deadline knob, and the in-process revalidation window.

Co-Authored-By: Claude Fable 5 <[email protected]>
@kiwidream
kiwidream force-pushed the harden-public-hashrate-reads branch from 62994d6 to 1fb8704 Compare September 1, 2026 13:04

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

ℹ️ 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/public_read_service.py Outdated
Comment on lines +666 to +667
with statement_timeout(float(timeout_seconds)):
return public_api.dispatch(coordinator, path, query)

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 Enforce one deadline across the entire public dispatch

When a route performs several ledger operations, this scope does not provide the documented per-request deadline: PsqlShareLedger.statement_timeout() gives every admission and SQL statement a fresh budget. For example, /public/v1/miners/{recipient_id} performs multiple sequential ledger reads, so after the proxy abandons the request those reads can each consume nearly 20 seconds and the dispatch can continue far beyond the configured limit. Use an operation-wide deadline (while retaining server-side statement cancellation) so the remaining budget decreases across the complete dispatch.

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 a18bea7: the dispatch now runs under the ledger's operation_timeout — one budget counting down across every ledger read in the request, with each statement still cancelled server-side on the remaining budget. A wiring test pins that a multi-read route (miner detail) enters the scope exactly once.

…cache entries

Review follow-ups on the public read hardening.

The statement deadline armed on path_reads_database(), whose
immutable-content exemption answers a staleness question, not a cost one: a
cold /public/v1/artifacts/{sha256} occupies a bounded Postgres read slot
exactly like any other cold read, for as long as the lookup takes. A
separate path_occupies_read_slot() predicate -- registry READ_SLOT access,
immutable or not -- now decides the deadline, while the replica and outage
gates keep their exemption.

Capacity reaping removed every entry past its TTL, including ones still
inside the stale-while-revalidate window the lookup path had just promised
to serve. Entries record their own stale_until at store time and reaping
removes only entries past it, so a full cache sheds dead weight without
turning a promised STALE answer into a blocking recompute.

The statement-timeout tests cleared the whole process environment, which
also dropped NO_PROXY: on a proxy-configured machine the localhost request
then went through the proxy and failed. They now patch only the deadline
knob itself.

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: b8b2945306

ℹ️ 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/public_api.py Outdated
args=(key, ttl_seconds, stale_while_revalidate_seconds, compute, refresh),
name="prism-public-cache-refresh",
daemon=True,
).start()

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 Clear the refresh slot when thread startup fails

If the process cannot create another thread during a burst of stale keys, Thread.start() raises after this key has already been inserted into _inflight. Because no refresh thread then executes the cleanup, subsequent stale hits never retry the refresh and, once the stale window expires, requests wait indefinitely on an event that cannot be set. Catch the startup failure and remove or complete the registered inflight entry before propagating or falling back.

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 a18bea7: a Thread.start() failure now frees the registered inflight slot and sets its event, so coalesced waiters wake and the next stale hit retries the refresh; the stale answer is still served. Covered by a test that patches Thread.start to raise and then verifies the slot is free and a later refresh succeeds.

…d failure

Second-round review follow-ups on the public read hardening.

The deadline armed the ledger's statement_timeout scope, which hands every
admission and SQL statement a fresh budget: a route that performs several
sequential ledger reads (the miner detail page does) could run many
multiples of the configured limit after the proxy hung up. The scope is
operation_timeout now -- one budget counting down across the entire
dispatch, with every statement still cancelled server-side on whatever
remains -- and a wiring test pins that a multi-read dispatch enters the
scope exactly once.

The stale-serve path registered its background-refresh slot before
Thread.start(), so a thread-creation failure under resource pressure
stranded the slot: later stale hits never retried the refresh and, past the
window, blocking requests waited on an event nobody could set. Startup
failure now frees the slot and wakes any coalesced waiter; the stale answer
is still served and the next stale hit retries.

Co-Authored-By: Claude Fable 5 <[email protected]>
@kiwidream
kiwidream merged commit 090daa7 into 2.x.x Sep 1, 2026
11 checks passed
@kiwidream
kiwidream deleted the harden-public-hashrate-reads 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