Skip to content

Serve the PRISM public read tier from a Postgres hot standby - #157

Merged
kiwidream merged 1 commit into
2.x.xfrom
extract-prism-public-read-tier
Aug 19, 2026
Merged

kiwidream merged 1 commit into
2.x.xfrom
extract-prism-public-read-tier

Conversation

@kiwidream

@kiwidream kiwidream commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Closes #145.

PR #152 extracted the public dashboard and audit read routes into their own
process, but left them reading the coordinator's primary — the replica was
deliberately deferred. This is that deferred half, and it is what lets #145
close: the extraction took public read volume off the coordinator's GIL, this
takes it off the database the lease-holding writer commits through.

This PR was originally opened against 413f51e with its own copy of the
extraction, before #152 merged. It has been rebased onto 2.x.x and reduced to
the replica delta only — everything #152 already landed is gone from the diff.
See the comment below for what was dropped.

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;
overriding PRISM_POSTGRES_USER means editing them. 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. Its healthcheck gates on the TCP listener, a real query, and
pg_is_in_recovery(), so an out-of-band promotion reports unhealthy instead of
quietly becoming a second writable cluster.

prism-public-api now waits on the standby rather than the primary and reads
through it. PRISM_PUBLIC_DATABASE_URL is a separate operator knob from
PRISM_DATABASE_URL on purpose: the latter names the primary, and the
coordinator needs it to — reusing it would let one .env line silently point
the public tier back at the primary.

The staleness contract

PsqlShareLedger.read_replica_status() is 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 (10s by default) 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 perfectly healthy standby every time the
pool went quiet, which is exactly when the dashboard is least likely to be
wrong. 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, not a hand-kept list:
those reading a read slot, excluding content-addressed ones, whose bodies either
hash to the requested digest or do not. /public/v1/mining-configuration is
assembled from environment and keeps serving through a replica outage.

Staged cutover

PRISM_PUBLIC_REPLICA_MODE defaults to off in code and require in compose.
Merging this must not 503 a deployment that has not provisioned a standby yet,
while anyone bringing the stack up from this repository gets the enforced
contract without opting in. An unrecognised value refuses startup rather than
picking a default, 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. This was a real bug found by the container
gate: an undocumented code is silently rewritten to internal_error, so the
refusal shipped a 503 whose body said "internal error".

Hardening carried over from review

  • The replica entrypoint 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. A marker
    file cannot serve here — pg_basebackup refuses a target directory that is
    not empty, dot files included.
  • The gate's replica-row poll treats a failed query as "not yet" inside its
    deadline; both the schema and the row reach the standby by streaming, so the
    count query fails with "relation does not exist" until the DDL replays.
  • Dead RUN_TOKEN assignment removed (shellcheck SC2034).

Verification

  • Full unit suite: 2300 tests, only the five pre-existing os.splice
    failures in test_prism_job_builder, confirmed byte-identical on a clean
    worktree at the base commit. They pass on Linux CI.
  • Compose profile, mainnet contract, and mining profile suites: green.
  • Dockerized shellcheck and compileall: clean. docker compose config
    validates.
  • Live container gate (make test-prism-public-read-replica): 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.

Follow-ups, not in this PR

Two findings from the earlier review apply to code #152 already merged rather
than to this diff:

  • PsqlShareLedger(read_only=True) does not set
    default_transaction_read_only=on. With this PR the standby enforces it in
    practice, but the class-level guard is still worth having.
  • handle_public never consults the readiness probe on the non-replica path; it
    is bounded only by per-endpoint cache-age budgets.

Production provisioning beyond the compose scaffolding — dedicated replication
role, scoped pg_hba entry, separate storage, slot monitoring, and the WAL
retention risk of an abandoned slot — is documented as a manual checklist in
docs/prism-postgres-replica.md. Nothing in this repository performs those
steps, and this standby is not a failover target.

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

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
kiwidream force-pushed the extract-prism-public-read-tier branch from 86d7c11 to a344f54 Compare August 19, 2026 20:47
@kiwidream kiwidream changed the title Extract the public dashboard and audit read tier out of the coordinator process (#145) Serve the PRISM public read tier from a Postgres hot standby (#145) Aug 19, 2026
@kiwidream

Copy link
Copy Markdown
Member Author

Force-pushed: rebased onto 2.x.x and reduced to the replica delta.

This PR was opened at 413f51e, before #152 merged. Both implemented #145, so
the branch went CONFLICTING/DIRTY and most of its diff became a duplicate of
work already on 2.x.x. Rather than close it, the branch has been rebased onto
e2117a9 and cut down to the part #152 deliberately deferred — the Postgres
read replica.

Dropped, because #152 landed its own version: this branch's
lab/prism/public_read_service.py, its audit_http.py route split, the
coordinator_config.py/prism_coordinator.py changes, its share_ledger
read_only construction mode, and docs/prism-public-read-service.md. #152's
read_only is the stronger of the two — it gives the object a
_RefusingWriterGate rather than only skipping lease acquisition — and its
route split is driven by endpoint_registry from #147 rather than two config
switches.

Kept and reworked: the replica itself. The scaffolding applied cleanly, but
the freshness contract had to be rewritten rather than copied: #152's service
has a full per-endpoint staleness contract and readiness probe, and no replica
awareness at all
— it reads the primary. So the contract is now built on its
ReadinessProbe/endpoint_registry structure instead of this branch's deleted
PublicReadServiceConfig, and the container gate was rewritten against its
build_service() entry point.

25 files / 2921 insertions → 18 files / 1871.

Three things changed on the way in, from the earlier review of this branch:

  • The freshness gate now ages locally and runs before the response cache, so
    a failing probe cannot pin a fresh verdict and a warm cache entry cannot mask
    a refusal. The previous version held its last good snapshot indefinitely.
  • Gating is derived from endpoint_registry rather than a hardcoded exempt
    path set, which also exempts content-addressed artifacts — consistent with the
    unbounded staleness budget Extract the PRISM public read tier into its own process #152 already publishes for them.
  • The entrypoint's rm -rf now refuses a directory holding a complete
    cluster
    , discriminating on pg_controldata rather than a marker file:
    pg_basebackup rejects a non-empty target directory, dot files included, so a
    marker written before the backup would wedge the bootstrap.

Findings F1 and F8 from that review turned out not to apply — #152
classified every /audit/* route as retain/operator, so they stayed on the
coordinator and the extracted service never serves /audit/latest. F3, F4 and
F11 were fixed in #152. F5's staged-cutover switch does not exist there at all.

The previous CI failure on this branch was a rustup toolchain download transient
(exit 123 on the install script), not code.

@kiwidream kiwidream changed the title Serve the PRISM public read tier from a Postgres hot standby (#145) Serve the PRISM public read tier from a Postgres hot standby Aug 19, 2026
@kiwidream
kiwidream merged commit 2aa63cd into 2.x.x Aug 19, 2026
11 checks passed
@kiwidream
kiwidream deleted the extract-prism-public-read-tier branch August 19, 2026 20:57
kiwidream added a commit that referenced this pull request Aug 20, 2026
* Make the first writer-lease acquisition race diagnostic (#140)

Two coordinators racing the first-ever acquisition against an empty
qbit_ledger_writer_lease left the loser dying in PsqlShareLedger.__init__
with "postgres query returned no JSON" -- an error naming neither the
lease nor the coordinator that holds it, at pool bootstrap, which is
exactly where a misleading error costs the most.

Both arms of the acquisition statement's COALESCE can be empty at once.
Under READ COMMITTED the loser's INSERT ... ON CONFLICT DO UPDATE waits
on the singleton unique index, then re-reads only the conflicting tuple
through EvalPlanQual: the winner's identity differs and its lease is
unexpired, so the upsert affects zero rows. The holder arm is a plain
SELECT, which still reads the statement snapshot taken before the winner
committed, so it finds no row either. COALESCE(NULL, NULL) is NULL, and
parse_single_json_value turns that into the driver-level error.

Make the statement total instead. A third COALESCE arm is a constant
json_build_object naming the qbit ledger writer lease and marking the
result not acquired and retryable, so the expression cannot evaluate to
SQL NULL however the first two arms resolve. The retry is a signal local
to this one statement -- the row is committed, and only a fresh statement
snapshot can see it -- so _try_acquire_writer_lease consumes the sentinel
itself and re-runs, converging to the ordinary acquired or held-by arm.
_ensure_writer_lease never sees it, which matters because the sentinel
carries no holder to wait on or adopt.

The retry is bounded at three fresh snapshots. Two suffice under READ
COMMITTED; the third covers a re-raced row and bounds a caller whose
transaction pinned one snapshot for its whole life, which no retry can
advance. Exhausting the bound raises an error that still names the lease,
so no raw parser error can escape the constructor for this race.

parse_single_json_value is unchanged: only the lease statement became
total, and any other statement returning SQL NULL still fails loudly
rather than being reinterpreted as a retry.

tests/test_prism_share_ledger.py drives the loser's side through canned
statement results: the sentinel converging to the named holder refusal,
the sentinel converging to an ordinary acquisition, the sentinel being
rejected by both the wait and adopt predicates it must never reach, an
unconverging retry failing while still naming the lease, and an unrelated
NULL-returning statement still raising the generic parser error through
the native client. Ordinary acquisition, renewal, live-holder refusal and
expiry takeover keep their existing coverage.

Refs #140.

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

* Enforce read-only PostgreSQL sessions for read_only ledgers (#163)

PsqlShareLedger(read_only=True) refused the writer gate but never told
PostgreSQL the session was read-only. The gate covers every path that
takes it, which is most of them, but any statement issued outside it --
the lease upsert, release_writer_lease_fresh_connection's one-shot psql
UPDATE -- reached SQL exactly as it would on a read-write ledger.

Nothing bad happened, for a reason outside this class: since #157 the
public tier reads a hot standby, and a standby refuses writes itself. So
the guarantee was supplied by the deployment topology rather than by the
object that advertises it, and it lapses in two supported cases --
PRISM_PUBLIC_REPLICA_MODE=off, the code default, which aims the same
read-only ledger at the primary, and any future caller constructing
read_only=True against a read-write database.

Fail closed at connection time instead. PostgresSessionGuards, the libpq
options carrier #137 established for the orphan-reaping GUCs, gains a
read_only flag that appends default_transaction_read_only=on. That is one
carrier, not a second GUC transport, and it is why the coverage is total:
all three connection paths already share this object, so pool slots, read
slots, the dedicated lease-guard session and the psql subprocess all
inherit the setting, and a connect-time GUC covers autocommit statements
that no per-transaction spelling would reach. Operator-supplied options
still survive, and the coordinator fragment still goes last, so a DSN that
sets default_transaction_read_only=off cannot turn the session writable
again. The refusing writer gate is unchanged and remains defense in depth.

The essential test target is a writable primary: a standby would refuse
these writes whoever asked, so it can never show that read_only=True is
what refused them. Both PostgreSQL integration scripts now build a
read-only ledger against the primary they have spent the whole run writing
to, and assert that a real write method taking no writer gate is refused
by the server -- release_writer_lease_fresh_connection on the psql path,
and the writer-lease upsert over the pooled psycopg session on the native
path, so both kinds of connection one instance can create are covered.
Each is contrasted against a writable ledger of the same identity running
the same statement, and each read-only ledger is shown still serving reads.

Both scripts reach PostgreSQL through "docker exec", which does not forward
the caller's environment, so PGOPTIONS -- the only session-GUC transport on
the psql path -- was being dropped before it reached the server. The
read-only assertions run through a command that asks docker to pass the
variable through; an external psql inherits the environment already.

Unit coverage pins the conninfo and PGOPTIONS composition for the pooled
client, the lease-guard session and the subprocess backend, the precedence
of the coordinator fragment over an operator's DSN options, that a writable
ledger's session is untouched, and that the writer gate still refuses.

Refs #163.

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

---------

Co-authored-by: Claude Opus 5 <[email protected]>
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