Repository navigation
Serve the PRISM public read tier from a Postgres hot standby - #157
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
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.
86d7c11 to
a344f54
Compare
|
Force-pushed: rebased onto This PR was opened at Dropped, because #152 landed its own version: this branch's Kept and reworked: the replica itself. The scaffolding applied cleanly, but 25 files / 2921 insertions → 18 files / 1871. Three things changed on the way in, from the earlier review of this branch:
Findings F1 and F8 from that review turned out not to apply — #152 The previous CI failure on this branch was a rustup toolchain download transient |
* 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]>
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
413f51ewith its own copy of theextraction, before #152 merged. It has been rebased onto
2.x.xand reduced tothe replica delta only — everything #152 already landed is gone from the diff.
See the comment below for what was dropped.
Deployment shape
prism-postgresnow runs with a mountedhba_fileso it can accept physicalreplication.
config/prism-postgres/pg_hba.confreproduces the stock imagerules — 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_USERmeans editing them. Postgres 16'swal_level/sender/slot defaults already allow one standby, so no other serversettings change.
prism-postgres-replicais a streaming standby whose data directory is clonedby
pg_basebackuprather than initdb. The entrypoint takes the base backup(creating, or reusing, the
prism_public_replicaslot) on a bounded retry loopso a cold
docker compose upworks, then hands off to the stock imageentrypoint. Its healthcheck gates on the TCP listener, a real query, and
pg_is_in_recovery(), so an out-of-band promotion reports unhealthy instead ofquietly becoming a second writable cluster.
prism-public-apinow waits on the standby rather than the primary and readsthrough it.
PRISM_PUBLIC_DATABASE_URLis a separate operator knob fromPRISM_DATABASE_URLon purpose: the latter names the primary, and thecoordinator needs it to — reusing it would let one
.envline silently pointthe public tier back at the primary.
The staleness contract
PsqlShareLedger.read_replica_status()is a bounded read-slot probe returningrecovery 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 primaryhas 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 theqbit_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-configurationisassembled from environment and keeps serving through a replica outage.
Staged cutover
PRISM_PUBLIC_REPLICA_MODEdefaults tooffin code andrequirein 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_CODESentry mapping to the already-documentedupstream_unavailablewire code. This was a real bug found by the containergate: an undocumented code is silently rewritten to
internal_error, so therefusal shipped a 503 whose body said "internal error".
Hardening carried over from review
cluster, so a production bind mount aimed by mistake at a primary's data
directory stops the script instead of being destroyed.
pg_controldatais thediscriminator because
PG_VERSIONis also present in the debris of aninterrupted backup, which the script must still be free to clear. A marker
file cannot serve here —
pg_basebackuprefuses a target directory that isnot empty, dot files included.
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.
RUN_TOKENassignment removed (shellcheck SC2034).Verification
os.splicefailures in
test_prism_job_builder, confirmed byte-identical on a cleanworktree at the base commit. They pass on Linux CI.
shellcheckandcompileall: clean.docker compose configvalidates.
make test-prism-public-read-replica): primary plusstreaming standby, replicated data served through a moved endpoint, the
staleness bound refusing, the writable-primary refusal, and
mining-configurationstill 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 setdefault_transaction_read_only=on. With this PR the standby enforces it inpractice, but the class-level guard is still worth having.
handle_publicnever consults the readiness probe on the non-replica path; itis bounded only by per-endpoint cache-age budgets.
Production provisioning beyond the compose scaffolding — dedicated replication
role, scoped
pg_hbaentry, separate storage, slot monitoring, and the WALretention risk of an abandoned slot — is documented as a manual checklist in
docs/prism-postgres-replica.md. Nothing in this repository performs thosesteps, and this standby is not a failover target.