Repository navigation
Make schema applies atomic and repair a poisoned carry-forward summary seed (#124) - #155
Merged
Merged
Conversation
…y seed The psql schema-apply path ran every statement of crates/qbit-prism/sql/001_share_ledger.sql in its own autocommit transaction, so the carry-forward summary sync triggers could commit before the one-time seeding block ran. An interruption in that gap, or a live writer confirming or reversing a block in it, left the summary holding only post-trigger deltas; the seed's NOT EXISTS guard then treated that partial summary as seeded and skipped permanently, on that apply and every later one, silently under-reporting every miner's balance by their full pre-upgrade carry (#124). - The schema script now wraps itself in one BEGIN/COMMIT transaction, so the apply is atomic under every client: the coordinator's psql backend, the native psycopg client, and a manual operator apply with plain autocommit psql. The old explicit BEGIN/COMMIT around only the audit-publication migration phase remains folded into that wrapper; the transaction-scoped advisory lock is now held for the whole apply. - _run_sql additionally passes --single-transaction, so every psql invocation (query batches included) is one transaction. psql tolerates the script's own wrapper with a warning; the combination was checked against ON_ERROR_ROLLBACK (never set: --no-psqlrc), \connect (absent), and explicit transaction control in runtime SQL (absent). - The seed guard compares the summary's active row-count total against the active carry history (one statement, so concurrent commits cannot manufacture a mismatch) and also checks summary drift, rebuilding from history on disagreement. A deployment already poisoned by the old guard is repaired by the next apply instead of locked in. - The psycopg ImportError fallback to the psql backend is no longer silent; it prints a warning line. - docs/prism-ledger-ops.md now documents the single-transaction apply requirement with the writer stopped.
A Docker-gated Postgres test (test/test-prism-postgres-seed-guard.sh, wired as make test-prism-postgres-seed-guard and run in the CI postgres-native-client job, which installs psycopg) reproduces #124's mechanism end to end: - The schema is applied non-atomically the way the pre-fix ops doc instructed (the script's own BEGIN wrapper is stripped and the head -- tables, functions, and the carry-forward summary sync triggers, but not the seed -- is applied with per-statement autocommit psql). - Pre-upgrade carry history is inserted with the summary triggers suppressed, then a live writer confirms a prepared block in the trigger/seed gap, leaving the summary holding only that post-trigger delta. - The old emptiness-based seed guard (embedded verbatim) locks the poison in: miner-a's pre-upgrade carry is silently absent. - A re-apply through the psql backend, and a re-poisoned re-apply through the native psycopg backend, both repair the summary to match the carry history with zero drift. - A second scenario injects a failure inside the apply's transaction on both backends and asserts nothing committed, proving the atomicity half of the fix. The container readiness gate follows the #134 pattern: the real TCP listener plus a confirming query, never the racy socket-only probe. Test harness built by a delegated remote worker; the split-marker, wrapper-stripping, and in-transaction failure injection were adapted to the landed self-wrapping schema script and reviewed here.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
…, drift-only guard test - The setval comment no longer claims rollback undoes the allocator mutation on a pre-existing sequence (it does not); it now states the real residue semantics -- a failed re-apply leaves ordinal gaps only -- and warns future edits not to move validation after the setval. - The ops doc's writer-stopped rationale now describes the actual behavior under the atomic apply (concurrent mutations block on the apply's table locks and fire the recreated triggers afterwards, inviting lock waits and deadlocks) instead of the stale dropped-mutations mechanism, and documents the two harmless psql warnings the single-transaction + self-wrapper combination emits. - The regression test gains the guard's drift-only branch: a summary with matching row-count totals but corrupted balances is repaired by the next apply.
…ed-poisoning # Conflicts: # Makefile
This was referenced Aug 20, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What was broken
_run_sqlinvoked psql without--single-transaction, so the schema scriptapplied statement-by-statement in autocommit. The carry-forward summary sync
triggers could therefore commit before the one-time seeding block later in
the file ran; if the apply was interrupted in that gap, or a still-running
writer confirmed or reversed a block in it, the summary received only those
post-trigger deltas. The seed's
NOT EXISTSguard then treated the partialsummary as already seeded and skipped — on that apply and every later one —
silently under-reporting every miner's balance by their full pre-upgrade
carry (#124). The ops doc's
PRISM_POSTGRES_INIT_SCHEMA=0procedure walkedoperators straight into it.
What changed
The schema script now wraps itself in one
BEGIN/COMMITtransaction(
crates/qbit-prism/sql/001_share_ledger.sql). This makes the apply atomicunder every client, not just the ones that pass the right flags: the
coordinator's psql backend, the native psycopg client (whose single script
execution is one simple-query-protocol message), and a manual operator apply
with plain autocommit
psql -f. The old explicitBEGIN/COMMITaround onlythe audit-publication migration phase is folded into that wrapper; the
transaction-scoped advisory lock is now held for the whole apply, still
serializing concurrent appliers. This mirrors the shape the revert script
already had.
_run_sqlpasses--single-transactionas well. Interactions checked:ON_ERROR_ROLLBACK— never set:--no-psqlrcprevents any psqlrc frominjecting it, and nothing sets it in code; the default (
interactive) is ano-op for non-interactive runs.
\connect— absent from the schema script and from every SQL string sentthrough
_run_sql(and it cannot appear in SQL sent via stdin).BEGIN/COMMITin the SQL — the schema script now containsexactly one top-level
BEGIN;and oneCOMMIT;(verified by the new test);no runtime SQL sent through
_run_sqlcontains transaction control, and noadvisory-lock statement rides this path (the lease guard's session lock is
psycopg-only, on its own connection). psql tolerates the script's own
BEGINunder-1with two harmless warnings; the combination was verifiedempirically against Postgres 16, including that a mid-file failure rolls
everything back.
The seed guard is a repair, not a lock-in. It now compares the summary's
active row-count total against the active carry history (both counts from one
statement, so a concurrent commit cannot manufacture a false mismatch between
them) and also checks
qbit_carry_forward_current_drift()for balance-onlydivergence; on disagreement it rebuilds the summary from history via the same
recomputation the truncate triggers perform. A deployment already poisoned
by the old guard is repaired by the next apply — that is the acceptance
criterion and the regression test proves it.
The psycopg ImportError fallback is no longer silent — it prints a
warning line naming the fallback.
docs/prism-ledger-ops.md documents the single-transaction apply with the
writer stopped, fixes both example commands (forward and revert) to pass
--single-transaction, and explains why.The A1 gate discovery
The A1 migration gates (
tests/prism_postgres_a1_gate.py) apply the schemathrough their own plain-autocommit psql path that bypasses
_run_sql— theSQL file's old explicit
BEGIN/COMMITwas load-bearing for their"rejecting initializer leaves nothing behind" assertions. That is exactly why
the atomicity lives in the script itself rather than only in
_run_sql: anycaller, in-repo or operator, now gets an atomic apply. Removing the phase's
local
BEGIN/COMMITwhile adding the whole-file wrapper keeps those gatesgreen (whole-file rollback is strictly stronger than phase-only rollback).
Regression test
test/test-prism-postgres-seed-guard.sh(make test-prism-postgres-seed-guard, wired into the CIpostgres-native-clientjob, which installs psycopg) reproduces the poisoning on a real Postgres
container: it applies the schema non-atomically the way the old ops doc
instructed (stripping the script's own wrapper and applying everything up to
the seed with per-statement autocommit), inserts pre-upgrade carry history
with the summary triggers suppressed, confirms a prepared block in the
trigger/seed gap, and asserts the partial summary. The old guard (embedded
verbatim) locks the poison in; a re-apply through the psql backend, and a
re-poisoned re-apply through the native psycopg backend, both repair the
summary to match the carry history with zero drift. A second scenario
injects a failure inside the apply's transaction on both backends and
asserts nothing committed. The container readiness gate follows the #134
pattern (real TCP listener plus a confirming query, never the socket-only
probe).
Verification
bash -non the new scriptshellcheck -x(in Docker) on changed scriptscompileall docker lab tests examples scriptsequivalent (lab tests)make test-prism-postgres-seed-guardmake test-prism-postgres-ledger(includes A1 migration/revert/process gates)make test-prism-postgres-scalemake test-prism-postgres-native-ledgerpython -m unittest tests.test_prism_share_ledgerpython -m unittest discover -s tests2.x.xworktree)Residual risk
Applying the schema with a live writer remains unsupported (documented): the
trigger drop/create pairs drop concurrent mutations mid-apply, and a
concurrent commit between the seed guard's checks and its rebuild could
trigger a spurious (correct-by-construction) rebuild. The seed guard closes
the permanent damage path; the operator procedure closes the rest.
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.