Repository navigation
Name writer-lease races and enforce read-only sessions - #168
Conversation
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]>
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]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 869bb7e635
ℹ️ 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".
| if self.read_only: | ||
| fragment += " -c default_transaction_read_only=on" |
There was a problem hiding this comment.
Enforce read-only after psql wrappers
When read_only=True uses the subprocess backend through a wrapper that does not forward its environment, this startup option never reaches PostgreSQL and gate-free methods can still write to a writable primary. The newly added integration setup explicitly acknowledges this for docker exec and substitutes a separate command containing -e PGOPTIONS (test/test-prism-postgres-ledger.sh:67-76), but ordinary PsqlShareLedger consumers—including the existing commands in test/test-prism-public-read-replica.sh:85-86—receive no such substitution. Apply read-only state inside the --single-transaction SQL session, or fail closed when the setting cannot be verified, rather than relying exclusively on the parent process environment.
Useful? React with 👍 / 👎.
| json_build_object( | ||
| 'acquired', false, | ||
| '{WRITER_LEASE_ACQUIRE_RETRY_KEY}', true, |
There was a problem hiding this comment.
Update the concurrency model for the retry arm
The deterministic PostgreSQL model still returns None from FakePostgres._evaluate_acquire when the first-acquire loser's snapshot is empty, and tests/test_prism_concurrency_harness.py:369-405 still asserts the old postgres query returned no JSON failure. Consequently those concurrency tests pass while bypassing this new third arm and its second statement entirely; the new canned-result tests cannot validate that the SQL itself produces the sentinel. Teach the harness to recognize this arm and update the race expectations so the exact interleaving this change fixes exercises the retry.
Useful? React with 👍 / 👎.
* Discriminate the outbox record from the share append in the harness classifier (#156) `OUTBOX_RECORD` was identified by two fragments that `_append_batch_with_replay_outcomes` also emits: it opens the same `INSERT INTO qbit_block_candidate_outbox (` and raises the same `'block candidate payload mismatch'` as `persist_block_candidate_intent`. A captured share submission therefore matched the outbox signature first and was answered by the outbox evaluator, so the harness reported the statement against the wrong state machine — arguing for an outbox defect that did not exist while hiding the deferral that did. Add the conflict action as a third required fragment. The intent writer inserts a candidate with no share attached and leaves a colliding row alone (`ON CONFLICT (block_hash) DO NOTHING`); the share append claims that row (`ON CONFLICT (block_hash) DO UPDATE`). That difference is the SQL-level statement of which caller owns the row, so it is a load-bearing identity rather than an incidental token. At this baseline the fragment occurs in exactly one ledger method. Self-tests pin all three directions: the shipped `append_batch`, captured at the port, now reaches `_DEFERRED_SIGNATURES` and names the share-submission machine; `persist_block_candidate_intent` still classifies as `OUTBOX_RECORD`; and the discriminator is asserted unique to the intent writer, so a second emitter fails here rather than at the next confusing scenario failure. Unknown SQL stays loud. Co-Authored-By: Claude Opus 5 <[email protected]> * Land the on-demand PRISM performance instruments (#160) Two on-demand drivers under tests/perf/, neither collected by test discovery: their filenames do not begin with `test_` and nothing imports them. window_pipeline_gil_scaling measures how much of the payout-window materialization pipeline is actually GIL-held rather than assumed to be. This is recovered work, restored byte-for-byte from the artifact that was already written rather than re-derived: cores-used via process_time/perf_counter, positive and negative controls, a control-floor abort, a wall-clock floor, alternating repetitions, load average, a memory guard, JSON capture and render replay. The one deviation from the recovered bytes is a `# noqa: F821` with its reasoning: `inputs` is bound at the top of the loop body and released by `del inputs` at the end of it, which is enough for Ruff to read the closure as unbound, and measure_cores joins every thread before returning so no invocation outlives the binding. stratum_session_concurrency_load is rebuilt, because the original was lost with its workspace and no reachable object contained it. It drives the shipped StratumSessionService, VardiffService and ShareSubmissionService through a real PrismCoordinator with real threads, real sockets and a real wall clock -- deliberately not the baton harness, which replaces the scheduler, clock and lock that this question is about. Paced, saturating and herd modes; herd reports a per-session re-establishment census including the exact count that never returned, because a storm that settles at high throughput while a third of the pool gets no work back is a failure a throughput-only report would call a success. Metrics: cores-used, shares/s, CPU us/share, ack p50/p95/p99/max, lock acquisitions/contentions with hold attribution by call site, watchdog misses, rejections, and a fixed-work GIL-wait probe that charges its own CPU so it cannot inflate the coordinator's. Hold attribution lives in the driver, not in production: _ObservedRLock is right that a clock read per acquire/release is the fast-path cost it exists to avoid, so the wrapper is paid for only while measuring and --no-lock-attribution quantifies it. No production code changes. Ledger mode is selectable and named in every output -- in-memory to isolate interpreter cost, or a real PsqlShareLedger through the repository's real-server gate, since a shares/s figure means something different with and without a durable write. Difficulty is not permanently pinned: resume and climb both exercise the real retarget path. The health abort refuses to report any settle, load, herd or lock number when the host cannot demonstrate parallelism, and --selftest asserts that the abort report contains none of them. Co-Authored-By: Claude Opus 5 <[email protected]> * Key the harness lease-acquire model to the shipped statement shape (#140) The acquire model hardcoded the pre-#140 result: when a first-acquire race loser could see neither its own upsert nor a committed holder, the evaluator returned SQL NULL unconditionally, and test_first_acquire_race_loser_gets_an_unhelpful_error pinned the generic "postgres query returned no JSON" diagnostic that produces. Once the ledger PR adds an explicit not-acquired/retry arm that outcome is no longer reachable, and a model that kept producing it would let a scenario assert something the server can no longer do. Read the shape off the statement instead. `acquire_result_arms` counts the result arms of the final SELECT COALESCE and `acquire_terminal_arm_keys` names the keys of the last one, both computed from the SQL PsqlShareLedger actually emitted. Two arms is today's shape and still evaluates to NULL; three or more carries a terminal arm and cannot, so the evaluator answers it. Counting arms rather than matching a chosen literal is deliberate: the arm has to exist for the fix to work, whatever its author names its keys. Unknown SQL stays loud in both new directions. A statement without the recognised COALESCE, or with fewer than two arms, raises UnsupportedStatement naming the shape; and the terminal arm's value policy is narrow on purpose -- `acquired` is false, holder and lease columns are null because nothing is visible, a retry flag is true, and any other key raises rather than being guessed at. The tests switch with the statement rather than being rewritten, and are not vacuous. The forward branch is exercised now, against a terminal-arm statement built from the shipped one, so a mistake in it surfaces here rather than as a harness failure blamed on the ledger PR. Both directions are pinned: the baseline is asserted to have exactly two arms and the old diagnostic, and the new branch is asserted to retire it. Mutating the arm counter to a constant, forcing either branch, or letting an unteachable key through each fail this suite. No production files are touched, and this stays green on the current baseline. Co-Authored-By: Claude Opus 5 <[email protected]> * Model the shipped lease-acquire retry arm's literal values (#140) The signed ledger branch renders a terminal arm with four keys: `acquired` false, `lease_snapshot_retry` true, `lease` naming the subject, and `retry_reason` carrying a sentence. The narrow policy landed earlier answered two of them wrongly. It refused `lease` outright, because the key was on neither of its lists. Worse, it answered `retry_reason` with `True`, because the policy keyed on the key's *name* and the name contains "retry" -- so it got `lease_snapshot_retry` right by luck and would have reported a boolean where production emits an explanation. Answer what the statement says instead of what the key is called. `acquire_terminal_arm_fields` pairs the terminal `json_build_object` arguments and returns each value's raw SQL text, and the value reader resolves `true`/`false`/`null` and single-quoted literals from it. The subject and the reason therefore come out of the shipped SQL verbatim and cannot drift from the wording the ledger PR chose. Splitting the arguments respects parenthesised sub-expressions and quoted literals, because the holder arm nests `GREATEST(0, EXTRACT(...))` and a reason sentence must survive as one argument. Unknown keys stay loud. The key set is still an allowlist, so a key this model has never seen is refused even when its value is a perfectly readable literal, and a literal key given a non-literal value is refused rather than guessed at. The new integration self-test reads `share_ledger.py` out of the signed ledger commit read-only, renders its final COALESCE with that commit's own retry constants, splices it onto the statement production emits here, and requires the exact terminal object -- not NULL and not a substitute. It matters that this reads the real arm: the synthetic fixtures the first attempt was written against were chosen to match its policy, which is exactly why both defects survived them. The expected object is written out independently rather than derived from the same parse, so the assertion cannot agree with itself. Mutations checked: name-based values, a fixed guess for string literals, a quote-blind splitter, a paren-blind splitter, a silently accepted unknown key, a three-arm shape still answered as NULL, and the baseline wrongly answered with the terminal object all fail this suite. Dropping the doubled-quote branch does not, and is an equivalent mutant -- toggling the quote state twice over adjacent quotes yields identical output -- rather than an untested path. No production files are touched, and the current baseline stays green. Co-Authored-By: Claude Opus 5 <[email protected]> * Make the retry-arm coverage self-contained (#140) The integration self-test in a2ec459 read `share_ledger.py` out of a foreign commit object and fetched it when absent. That is the wrong trade for a test suite. It makes a result depend on the network and on objects this repository does not own, so it fails on a shallow clone, a pruned object or an offline runner for reasons that say nothing about the tree under test -- and its skip-when-missing fallback was worse still, because coverage that quietly disappears reads as coverage. Remove it, along with the machinery it needed: the subprocess and pathlib imports, `_git`, `_share_ledger_source_at`, `_acquire_coalesce_tail`, and the `LEDGER_RETRY_COMMIT` constant. No test path invokes git or opens a socket now, checked statically and by running the suite with subprocess and socket replaced by tripwires that raise: 34 tests, zero failures, zero skips. What that test was protecting is kept. The terminal arm stays as the captured fixture, spliced onto the statement production emits here, and the exact expected object stays written out independently of it, so the assertion still cannot agree with itself. The value-type assertions move across with it -- a boolean in `retry_reason` is the precise defect the first policy had, and dict equality alone would read as a typo check. The provenance of the fixture bytes (PR #168, commit 869bb7e) is now a comment documenting where to re-capture from, and nothing reaches for it. The literal-valued parser policy and the punctuation/quote regression are untouched; `prism_concurrency_harness.py` does not change in this commit. Coverage did not regress with the removal: name-based values, a fixed guess for string literals, a quote-blind splitter, a paren-blind splitter, a silently accepted unknown key, a three-arm shape answered as NULL, and the baseline answered with the terminal object all still fail this suite. Co-Authored-By: Claude Opus 5 <[email protected]> --------- Co-authored-by: Claude Opus 5 <[email protected]>
Closes #140.
Closes #163.
Problem
PsqlShareLedgerhad two session-correctness gaps:postgres query returned no JSONerror during bootstrap.read_only=Trueinstalled an in-process refusing writer gate but never told PostgreSQL that every transaction on the session must be read-only.Design
This PR keeps the two changes as separate signed commits.
_try_acquire_writer_leaseconsumes only that sentinel, retries with a fresh statement snapshot, and fails with a lease-named diagnostic if the bounded retry cannot converge. The general JSON parser is unchanged.default_transaction_read_only=onto the existing libpqoptions/PGOPTIONScarrier. The coordinator fragment remains last, so it preserves caller options while overriding an attemptedoff. Pool slots, read slots, the native lease-guard connection, psql subprocesses, and autocommit statements inherit the same guarantee. The refusing writer gate remains defense in depth.Verification
python3 -m unittest tests.test_prism_share_ledger— 218 tests passed.read_only=Trueand succeed for the writable control.docker,lab,tests,examples, andscripts.E4,E7,E9,Fpassed on both changed Python files; Docker ShellCheck passed on the changed integration scripts.Sequencing and residual risk
The test-infrastructure PR lands first and updates the deterministic concurrency harness's legacy model of the #140 statement. The ledger's own deterministic tests already prove retry-to-acquisition, retry-to-named-holder-refusal, bounded failure, and that unrelated empty JSON remains loud.
The new real-PostgreSQL read-only assertions explicitly forward
PGOPTIONSthroughdocker exec. Older portions of those integration harnesses still do not exercise every #137 session guard through their main psql command; that pre-existing harness gap is outside these two fixes.Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.