Skip to content

Extract the PRISM public read tier into its own process - #152

Merged
kiwidream merged 3 commits into
2.x.xfrom
extract-public-read-tier
Aug 19, 2026
Merged

kiwidream merged 3 commits into
2.x.xfrom
extract-public-read-tier

Conversation

@kiwidream

@kiwidream kiwidream commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

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_json kept Serve content-addressed artifacts as their exact canonical bytes #154's public_api.RawJsonBody branch while this PR removed the public_api import, so every audit response raised NameError. 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_json re-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. The RawJsonBody branch 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, default 0.0.0.0:3342), composed as the prism-public-api service:

  • It builds the same PsqlShareLedger from PRISM_DATABASE_URL and dispatches through public_api.dispatch under the same PublicResponseCache / 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 and PublicApiError cases.
  • The coordinator keeps /healthz, /metrics, /audit/*, /owed*, and the status routes; an unknown /public/v1/... request to the coordinator now gets the standard 404. audit_http.py no longer imports public_api at all, and its shutdown-race lifecycle machinery is untouched.
  • The 24 PRISM_PUBLIC_* knobs (including PRISM_PUBLIC_ARTIFACT_CACHE_*) moved to prism-public-api; PRISM_PUBLIC_REWARD_WINDOW_CACHE_SECONDS stays on both since both construct a ledger. The service gets no writer-lease, signing-seed, or block-submission configuration, and sets PRISM_ALLOW_MEMORY_LEDGER=0.
  • prism-public-api depends only on prism-postgres (not the coordinator), mounts the audit artifact volume read-only, and has its own /healthz and /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 by PRISM_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 via current_owed_balances(), which returns every recipient under the writer lock and filters in Python. dashboard_miner_owed_balance_bits filters 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-artifacts fell through to audit_bundle() under the writer lock for direct-coinbase blocks. dashboard_direct_coinbase_settlement returns the identical payload shape through the read slot, reusing the existing _read_external_body sha256 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), and AuditArtifactStore(read_only=True) skips the publication lock that cannot open on the :ro mount. 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 /metrics precedent in observability.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 existing Age header); when observed age exceeds the budget the service returns 503 with Cache-Control: no-store and a prism.dashboard.error.v1 body naming both numbers — a silently stale dashboard is worse than an honest one. Budgets with defaults:

Route Budget (s)
/public/v1/pool-summary, /hashrate-series, /miners/{id}/workers 90
/public/v1/blocks, /leaderboard, /miners/{id}/earnings, /miners/{id}/payouts, /blocks/{hash}/settlement-artifacts, /fanouts/pending, /fanouts/{txid} 15
/public/v1/mining-configuration 900
/public/v1/miners/{recipient_id} 105
/public/v1/artifacts/{sha256} unbounded (immutable)

Note for operators: raising a PRISM_PUBLIC_*_CACHE_TTL_SECONDS above its route's derived budget will make that route refuse; raise both together. prism-public-api also fails closed at startup without PRISM_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):

  • Targeted suites — public read service, endpoint registry, compose profiles, mining compose profiles, mainnet compose contract: 134 OK; public dashboard API, dashboard contract, audit HTTP, audit API, audit artifacts: 207 OK (1 expected failure, Serve content-addressed artifacts as their exact canonical bytes #154's documented audit-bundle gap); background services, coordinator metrics, coordinator shutdown, share ledger: 327 OK.
  • Full unittest discover in a Linux container, compared against a ddff673 baseline 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 -n and shellcheck -x over all 23 tracked shell scripts — clean.
  • docker compose config --quiet for the permissionless, real-miner-smoke, auxpow, and prism profiles plus the production overlay — all valid.
  • Review blockers re-checked on a host that has make: make -n up-prism-pool starts prism-public-api in both the build and --no-build branches, and the rendered compose environment for that service carries PRISM_STRATUM_PORT and PRISM_STRATUM_HIGHDIFF_PORT.

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

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@kiwidream
kiwidream changed the base branch from 2.x.x to map-public-operator-endpoint-split August 19, 2026 17:15
@kiwidream
kiwidream force-pushed the extract-public-read-tier branch from 82d12fe to 8193220 Compare August 19, 2026 17:23
@kiwidream
kiwidream changed the base branch from map-public-operator-endpoint-split to 2.x.x August 19, 2026 19:50
Alex and others added 3 commits August 19, 2026 15:54
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.
@kiwidream
kiwidream force-pushed the extract-public-read-tier branch from 8193220 to 7cb247c Compare August 19, 2026 20:08
@kiwidream

Copy link
Copy Markdown
Member Author

Review fixes applied, and the branch is rebased onto 2.x.x now that #147 has merged.

The four review findings

# Finding Resolution
1 make up-prism-pool and the mainnet runbook never start the new service prism-public-api added to every bring-up path. Verified with a real make -n up-prism-pool: it appears in both the build and --no-build branches.
2 Stratum port env never reaches the new process, so /public/v1/mining-configuration drops the High-diff endpoint PRISM_STRATUM_PORT and PRISM_STRATUM_HIGHDIFF_PORT passed into the compose service; covered by a compose-profile pass-through test and a contract-equality case. Confirmed against the rendered docker compose config.
3 Nonexistent budget knob in the docs Corrected to the TTL knobs that exist; the PRISM_PUBLIC_ARTIFACT_CACHE_* TTLs are called out as exempt because the artifact route never refuses for staleness.
4 Closes #145 over-claims while the replica is deferred Body now says Refs #145; the one in-repo text that equated the move with the whole issue (the test_prism_public_read_service module docstring) was corrected. The other docs already stated the replica is deferred.

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 audit_http was left calling public_api.RawJsonBody without the import (NameError on every audit response), and the extracted service re-serialized artifact bodies, silently undoing #154's byte-exactness guarantee for the route this PR moves. Both are fixed in 7cb247c, and #154's byte-exactness tests now drive the extracted handler, so the guarantee is pinned where the route actually lives: four of the five fail with that fix reverted.

Verification: 668 tests green across the touched suites; full discovery in a Linux container shows 2226 vs 2155 tests against a ddff673 baseline — 71 net-new, all passing, with an identical failing set on both sides, so no regressions. Compose profiles, compileall, and shellcheck all clean. Details in the PR body.

@kiwidream
kiwidream merged commit e2117a9 into 2.x.x Aug 19, 2026
11 checks passed
@kiwidream
kiwidream deleted the extract-public-read-tier branch August 19, 2026 20:16
kiwidream added a commit that referenced this pull request Aug 19, 2026
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.
kiwidream added a commit that referenced this pull request Aug 19, 2026
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.
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