Repository navigation
Extract the PRISM public read tier into its own process - #152
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
82d12fe to
8193220
Compare
The coordinator served its public dashboard API on the same in-process
listener as its operator endpoints, under the same GIL that acknowledges
shares and lands blocks, against the same primary Postgres the
lease-holding writer commits through. Read traffic scales with public
interest rather than hashrate, so it was the one workload whose volume the
pool does not control -- and it sat on the money path.
Exactly the 13 /public/v1 routes classified Disposition.EXTRACT move.
/healthz, /metrics, /audit/*, /owed* and the miner/payout status aliases
stay on the coordinator, per docs/prism-public-operator-endpoint-split.md.
Sever the two writer-lock reads on public routes first; without this the
move would relocate GIL contention and keep lock contention:
- PsqlShareLedger.dashboard_miner_owed_balance_bits filters one recipient
in SQL through _run_read_json, replacing owed_balance_for_recipient's
scan of every recipient's balance under the writer lock. That made
/public/v1/miners/{recipient_id}, the most-polled route on the surface,
a fenced read.
- PsqlShareLedger.dashboard_direct_coinbase_settlement takes the
direct-coinbase settlement branch off audit_bundle(), resolving the body
through the existing _resolve_audit_bundle_row sha256 verification.
public_api prefers both through the same duck-typed pattern as every other
read model, keeping the old paths as in-memory-ledger fallbacks. Both were
verified against real Postgres to return exactly what they replace,
including multi-program recipients, negative balances, and quoted
recipient ids.
The new service is read-only in three independent ways: PsqlShareLedger
gains read_only=True, which skips writer-lease acquisition and swaps the
writer lock for a gate that refuses to be acquired at all; the audit
artifact store gains read_only=True so it holds no publication lock and
works against the :ro volume mount; and the container receives no writer,
signing, or block-submission configuration. It refuses to start without
PRISM_PUBLIC_STRATUM_URL (the fallback would advertise 127.0.0.1:3340 to
miners) or on the in-memory ledger (whose missing dashboard_* read models
would send public_api's fallbacks back onto writer-lock reads).
Staleness becomes a contract, following observability.py's cached /metrics
precedent: Endpoint gains max_staleness_seconds, derived as
max(3 * (cache_ttl + underlying_cache), 15) rather than hand-picked, and
every response publishes X-Prism-Staleness-Budget-Seconds beside Age and
returns 503 rather than serve past it. /public/v1/artifacts/{sha256} is
exempt via an explicit immutable_content flag.
AuditHttpFacade's lifecycle machinery is untouched; audit_http no longer
imports public_api at all, and an unknown /public/v1 request reaches its
ordinary unknown-endpoint 404.
Co-Authored-By: Claude Opus 5 <[email protected]>
REQUEST_CHANGES findings from the Fable review of the public read tier extraction, applied on top of the extraction rebased onto the hardened endpoint-registry base: - Blocker 1: make up-prism-pool and every mainnet runbook bring-up path (config/pull/up service lists and the lane table) started only the coordinator, so a pool brought up through the documented seam had no public API at all. prism-public-api is now part of each of them. - Blocker 2: PRISM_STRATUM_PORT and PRISM_STRATUM_HIGHDIFF_PORT never reached the prism-public-api container, so the rendered /public/v1/mining-configuration silently dropped the High-diff endpoint the coordinator was actually listening on. Both now pass through the compose environment; the compose-profile suite pins the pass-through and a contract-equality case pins the High-diff endpoint in the served body against public_api.dispatch with the env set. - Should-fix 3: the dashboard README told operators to raise a route's staleness budget alongside its cache TTL, but no budget knob exists -- the budgets are constants in lab/prism/endpoint_registry.py. The paragraph now names the cache TTL knobs that do exist and says the registry constant is what changes with them. - Should-fix 4: the extraction moved the process, not the read-replica back-end, so the read-service test docstring no longer equates the move with all of issue #145; the replica remains a follow-up and the service still reads the primary Postgres. Co-Authored-By: Claude Fable 5 <[email protected]>
… tier Rebasing the read-tier extraction onto 2.x.x put it on top of #154, which landed while this PR was in review. Git merged the two textually, but the result was semantically broken in both directions: - audit_http kept #154's `public_api.RawJsonBody` branch in write_json while the extraction removed the public-API import, so every audit response raised NameError. GET /public/v1/artifacts/{sha256} moved out of this listener, so no route reaching it can carry pre-serialized bytes: the branch is dead here and is removed, restoring the module's import isolation. - public_read_service.write_json re-serialized every payload with sorted keys and a trailing newline. The artifacts route moved into this process, so #154's fix silently regressed: sha256(response body) would no longer match the advertised artifact hash. The RawJsonBody branch moves here with the route it serves. The two byte-exactness tests #154 added now exercise the extracted handler rather than the coordinator's audit handler, which is what pins the regression: they fail without the branch above.
8193220 to
7cb247c
Compare
|
Review fixes applied, and the branch is rebased onto The four review findings
One thing the rebase surfaced that the review could not have #154 landed while this PR was in review, and Git merged the two cleanly but incorrectly in both directions. See the new section in the PR body — the short version is that Verification: 668 tests green across the touched suites; full discovery in a Linux container shows 2226 vs 2155 tests against a |
PR #152 extracted the public dashboard and audit read routes into their own process but left them reading the coordinator's primary, deferring the replica. That deferral is the remaining half of issue #145: the extraction takes public read volume off the coordinator's GIL, and this takes it off the database the lease-holding writer commits through. Deployment shape. prism-postgres now runs with a mounted hba_file so it can accept physical replication; config/prism-postgres/pg_hba.conf reproduces the stock image rules -- including the local trust rule the image's initdb bootstrap and the existing healthcheck depend on -- and adds two replication rules. Compose cannot interpolate that file, so those rules name the default superuser literally. Postgres 16's wal_level/sender/slot defaults already allow one standby, so no other server settings change. prism-postgres-replica is a streaming standby whose data directory is cloned by pg_basebackup rather than initdb: the entrypoint takes the base backup (creating, or reusing, the prism_public_replica slot) on a bounded retry loop so a cold `docker compose up` works, then hands off to the stock image entrypoint. It refuses to clear a directory holding a complete cluster, so a production bind mount aimed by mistake at a primary's data directory stops the script instead of being destroyed; pg_controldata is the discriminator because PG_VERSION is also present in the debris of an interrupted backup, which the script must still be free to clear. Its healthcheck gates on the TCP listener, a real query, and pg_is_in_recovery(), so an out-of-band promotion reports unhealthy rather than quietly becoming a second writable cluster. The contract. PsqlShareLedger grows read_replica_status(), a bounded read-slot probe returning recovery state, walreceiver heartbeat age, replay lag and apply backlog. The service polls it on the readiness thread it already runs -- one round trip answers both questions -- and refuses replica-backed routes that fail it: warm-up, a backing server not in recovery, and a replication stream silent past PRISM_PUBLIC_REPLICA_MAX_LAG_SECONDS. The enforced number is the heartbeat age, not replay lag. Heartbeats flow every wal_receiver_status_interval whether or not the primary has anything to send, whereas replay lag grows with wall clock on an idle primary -- bounding that would 503 a healthy standby every time the pool went quiet. Replay lag and apply backlog are published instead, on X-Prism-Replica-Lag-Seconds, /healthz and the qbit_prism_public_replica_* gauges. Freshness ages locally, which is what makes the gate fail closed: the bound is checked against the heartbeat age the last successful probe reported plus how long ago that probe ran, so a probe that starts failing ages its own last good answer out of the bound rather than pinning it there. The check runs before the response cache for the same reason -- an outage does not expire cache entries, so a check after the cache would keep answering 200 for as long as traffic kept one warm. Which routes are gated comes from endpoint_registry rather than a hand-kept list: those reading a read slot, excluding content-addressed ones, whose bodies either hash to the requested digest or do not. mining-configuration is assembled from environment and keeps serving through a replica outage. PRISM_PUBLIC_REPLICA_MODE defaults to off in code and require in compose, so merging this does not 503 a deployment that has not provisioned a standby while anyone bringing the stack up from this repository gets the enforced contract without opting in. An unrecognised value refuses startup rather than guessing, because the two modes disagree about whether this process may read the primary. Refusals use a new PUBLIC_ERROR_CODES entry mapping to the already-documented upstream_unavailable wire code; an undocumented code would have been silently rewritten to internal_error. Verified: the full unit suite (2300 tests; only the five pre-existing os.splice failures remain, identical on the base commit), the compose profile and mainnet contract suites, dockerized shellcheck and compileall, and a live container gate -- primary plus streaming standby, replicated data served through a moved endpoint, the staleness bound refusing, the writable-primary refusal, and mining-configuration still serving underneath both.
PR #152 extracted the public dashboard and audit read routes into their own process but left them reading the coordinator's primary, deferring the replica. That deferral is the remaining half of issue #145: the extraction takes public read volume off the coordinator's GIL, and this takes it off the database the lease-holding writer commits through. Deployment shape. prism-postgres now runs with a mounted hba_file so it can accept physical replication; config/prism-postgres/pg_hba.conf reproduces the stock image rules -- including the local trust rule the image's initdb bootstrap and the existing healthcheck depend on -- and adds two replication rules. Compose cannot interpolate that file, so those rules name the default superuser literally. Postgres 16's wal_level/sender/slot defaults already allow one standby, so no other server settings change. prism-postgres-replica is a streaming standby whose data directory is cloned by pg_basebackup rather than initdb: the entrypoint takes the base backup (creating, or reusing, the prism_public_replica slot) on a bounded retry loop so a cold `docker compose up` works, then hands off to the stock image entrypoint. It refuses to clear a directory holding a complete cluster, so a production bind mount aimed by mistake at a primary's data directory stops the script instead of being destroyed; pg_controldata is the discriminator because PG_VERSION is also present in the debris of an interrupted backup, which the script must still be free to clear. Its healthcheck gates on the TCP listener, a real query, and pg_is_in_recovery(), so an out-of-band promotion reports unhealthy rather than quietly becoming a second writable cluster. The contract. PsqlShareLedger grows read_replica_status(), a bounded read-slot probe returning recovery state, walreceiver heartbeat age, replay lag and apply backlog. The service polls it on the readiness thread it already runs -- one round trip answers both questions -- and refuses replica-backed routes that fail it: warm-up, a backing server not in recovery, and a replication stream silent past PRISM_PUBLIC_REPLICA_MAX_LAG_SECONDS. The enforced number is the heartbeat age, not replay lag. Heartbeats flow every wal_receiver_status_interval whether or not the primary has anything to send, whereas replay lag grows with wall clock on an idle primary -- bounding that would 503 a healthy standby every time the pool went quiet. Replay lag and apply backlog are published instead, on X-Prism-Replica-Lag-Seconds, /healthz and the qbit_prism_public_replica_* gauges. Freshness ages locally, which is what makes the gate fail closed: the bound is checked against the heartbeat age the last successful probe reported plus how long ago that probe ran, so a probe that starts failing ages its own last good answer out of the bound rather than pinning it there. The check runs before the response cache for the same reason -- an outage does not expire cache entries, so a check after the cache would keep answering 200 for as long as traffic kept one warm. Which routes are gated comes from endpoint_registry rather than a hand-kept list: those reading a read slot, excluding content-addressed ones, whose bodies either hash to the requested digest or do not. mining-configuration is assembled from environment and keeps serving through a replica outage. PRISM_PUBLIC_REPLICA_MODE defaults to off in code and require in compose, so merging this does not 503 a deployment that has not provisioned a standby while anyone bringing the stack up from this repository gets the enforced contract without opting in. An unrecognised value refuses startup rather than guessing, because the two modes disagree about whether this process may read the primary. Refusals use a new PUBLIC_ERROR_CODES entry mapping to the already-documented upstream_unavailable wire code; an undocumented code would have been silently rewritten to internal_error. Verified: the full unit suite (2300 tests; only the five pre-existing os.splice failures remain, identical on the base commit), the compose profile and mainnet contract suites, dockerized shellcheck and compileall, and a live container gate -- primary plus streaming standby, replicated data served through a moved endpoint, the staleness bound refusing, the writable-primary refusal, and mining-configuration still serving underneath both.
Builds on #147 (the endpoint classification map and registry this extraction executes), now merged — the registry and its tests are what pin the boundary enforced here. Refs #145 — the read-replica back-end is a deliberate follow-up (this PR moves the process; the service still reads the primary Postgres), so the issue stays open until the replica lands.
Rebased onto 2.x.x after #147 and #154 landed
#147 was squash-merged, so this branch no longer stacks on it; it now sits directly on
2.x.x. The rebase also put the extraction on top of #154 (content-addressed artifacts served as their exact canonical bytes), which merged while this PR was in review. Git merged the two textually, but the result was wrong in both directions — a third commit fixes it:audit_http.write_jsonkept Serve content-addressed artifacts as their exact canonical bytes #154'spublic_api.RawJsonBodybranch while this PR removed thepublic_apiimport, so every audit response raisedNameError.GET /public/v1/artifacts/{sha256}left that listener, so no route reaching it can carry pre-serialized bytes: the branch is dead there and is removed, which is also what keeps the module's import isolation true.public_read_service.write_jsonre-serialized every payload with sorted keys and a trailing newline. The artifacts route moved into this process, so Serve content-addressed artifacts as their exact canonical bytes #154's fix silently regressed —sha256(response body)would no longer match the advertised artifact hash. TheRawJsonBodybranch moves here with the route it serves.The two byte-exactness tests #154 added now drive the extracted handler instead of the coordinator's audit handler, which is what pins the regression: four of the five fail with the ported branch disabled and pass with it restored.
What moved
Exactly the 13
/public/v1/*routes now run in their own process,lab/prism/public_read_service.py(python3 -m lab.prism.public_read_service, default0.0.0.0:3342), composed as theprism-public-apiservice:PsqlShareLedgerfromPRISM_DATABASE_URLand dispatches throughpublic_api.dispatchunder the samePublicResponseCache/ cache policy the coordinator's listener used, so bodies and cache headers are unchanged. Contract tests pin response equality (status, body,Cache-Control/CDN-Cache-Control/Vercel-CDN-Cache-Control/Age) for every extracted route against the pre-extraction fixtures, including error andPublicApiErrorcases./healthz,/metrics,/audit/*,/owed*, and the status routes; an unknown/public/v1/...request to the coordinator now gets the standard 404.audit_http.pyno longer importspublic_apiat all, and its shutdown-race lifecycle machinery is untouched.PRISM_PUBLIC_*knobs (includingPRISM_PUBLIC_ARTIFACT_CACHE_*) moved toprism-public-api;PRISM_PUBLIC_REWARD_WINDOW_CACHE_SECONDSstays on both since both construct a ledger. The service gets no writer-lease, signing-seed, or block-submission configuration, and setsPRISM_ALLOW_MEMORY_LEDGER=0.prism-public-apidepends only onprism-postgres(not the coordinator), mounts the audit artifact volume read-only, and has its own/healthzand/metrics. Published audit evidence is served from the artifact files, which are already the durable public record.Severing the writer-lock reads
The classification found two nominally public routes that took the writer lock. Both are served by new read-slot ledger models (
_run_read_json, bounded byPRISM_POSTGRES_READ_CONCURRENCY, never the writer gate), with the old paths kept as fallbacks for the in-memory ledger:/public/v1/miners/{recipient_id}— the most-polled route on the surface — resolved balances viacurrent_owed_balances(), which returns every recipient under the writer lock and filters in Python.dashboard_miner_owed_balance_bitsfilters in SQL and returns the same integer. Verified equal against a live PostgreSQL 16 instance with the PRISM schema, and by a structural test that drives the call with the writer lock already held./public/v1/blocks/{block_hash}/settlement-artifactsfell through toaudit_bundle()under the writer lock for direct-coinbase blocks.dashboard_direct_coinbase_settlementreturns the identical payload shape through the read slot, reusing the existing_read_external_bodysha256 verification and error tolerance.Two additions the issue did not anticipate, both required by the specified behaviour and both confined to paths the read tier uses:
PsqlShareLedger(read_only=True)swaps the writer lock for a refusing gate (the constructor otherwise claims the lease), andAuditArtifactStore(read_only=True)skips the publication lock that cannot open on the:romount. Worth reviewer attention since both files are payout-critical.Staleness contract
Each route states the staleness it tolerates, derived — not hand-picked — in
endpoint_registry.staleness_budget_seconds:max(3 * (route cache TTL + underlying cache TTL), 15s), following the/metricsprecedent inobservability.py. The underlying term accounts for the ledger's reward-window aggregate cache (default 30s) beneath every miner page./public/v1/artifacts/{sha256}is the one exception: content-addressed and immutable, so it has no budget and never refuses for age.Every response carries
X-Prism-Staleness-Budget-Seconds(plus the existingAgeheader); when observed age exceeds the budget the service returns 503 withCache-Control: no-storeand aprism.dashboard.error.v1body naming both numbers — a silently stale dashboard is worse than an honest one. Budgets with defaults:/public/v1/pool-summary,/hashrate-series,/miners/{id}/workers/public/v1/blocks,/leaderboard,/miners/{id}/earnings,/miners/{id}/payouts,/blocks/{hash}/settlement-artifacts,/fanouts/pending,/fanouts/{txid}/public/v1/mining-configuration/public/v1/miners/{recipient_id}/public/v1/artifacts/{sha256}Note for operators: raising a
PRISM_PUBLIC_*_CACHE_TTL_SECONDSabove its route's derived budget will make that route refuse; raise both together.prism-public-apialso fails closed at startup withoutPRISM_PUBLIC_STRATUM_URL(it would otherwise advertise a default Stratum endpoint) and refuses the memory ledger.What remains: the replica
Replica wiring is deliberately a follow-up, not part of this PR. The read tier still queries the primary Postgres; the extraction already removes the GIL and writer-lock contention from the money path, and the remaining step —
wal_level=replica, slot management, and a standby in the Postgres setup — is the piece most likely to stall everything else. The compose setup already has a dedicated WAL volume but no replication configuration; nothing here blocks adding it.Verification
Re-run after the rebase onto
2.x.x(ddff673):unittest discoverin a Linux container, compared against addff673baseline run: 2226 vs 2155 tests — 71 net-new, all passing — with an identical 42-test failing set on both sides, so this branch introduces no regressions. Those 42 are environment failures of the container (root user, ns-timestamp sensitivity), not of the tree; CI is green on the Ubuntu runners.python -m compileall -q docker lab tests examples scripts— clean.bash -nandshellcheck -xover all 23 tracked shell scripts — clean.docker compose config --quietfor thepermissionless,real-miner-smoke,auxpow, andprismprofiles plus the production overlay — all valid.make:make -n up-prism-poolstartsprism-public-apiin both the build and--no-buildbranches, and the rendered compose environment for that service carriesPRISM_STRATUM_PORTandPRISM_STRATUM_HIGHDIFF_PORT.Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.