Skip to content

Make schema applies atomic and repair a poisoned carry-forward summary seed (#124) - #155

Merged
kiwidream merged 4 commits into
2.x.xfrom
fix-carry-forward-seed-poisoning
Aug 19, 2026
Merged

kiwidream merged 4 commits into
2.x.xfrom
fix-carry-forward-seed-poisoning

Conversation

@kiwidream

@kiwidream kiwidream commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

What was broken

_run_sql invoked psql without --single-transaction, so the schema script
applied 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 EXISTS guard then treated the partial
summary 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=0 procedure walked
operators straight into it.

What changed

The schema script now wraps itself in one BEGIN/COMMIT transaction
(crates/qbit-prism/sql/001_share_ledger.sql). This makes the apply atomic
under 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 explicit BEGIN/COMMIT around only
the 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_sql passes --single-transaction as well. Interactions checked:

  • ON_ERROR_ROLLBACK — never set: --no-psqlrc prevents any psqlrc from
    injecting it, and nothing sets it in code; the default (interactive) is a
    no-op for non-interactive runs.
  • \connect — absent from the schema script and from every SQL string sent
    through _run_sql (and it cannot appear in SQL sent via stdin).
  • Explicit BEGIN/COMMIT in the SQL — the schema script now contains
    exactly one top-level BEGIN; and one COMMIT; (verified by the new test);
    no runtime SQL sent through _run_sql contains transaction control, and no
    advisory-lock statement rides this path (the lease guard's session lock is
    psycopg-only, on its own connection). psql tolerates the script's own
    BEGIN under -1 with two harmless warnings; the combination was verified
    empirically 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-only
divergence; 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 schema
through their own plain-autocommit psql path that bypasses _run_sql — the
SQL file's old explicit BEGIN/COMMIT was 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: any
caller, in-repo or operator, now gets an atomic apply. Removing the phase's
local BEGIN/COMMIT while adding the whole-file wrapper keeps those gates
green (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 CI postgres-native-client
job, 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

Check Result
bash -n on the new script pass
shellcheck -x (in Docker) on changed scripts pass
compileall docker lab tests examples scripts equivalent (lab tests) pass
make test-prism-postgres-seed-guard PASS (three local runs)
make test-prism-postgres-ledger (includes A1 migration/revert/process gates) PASS
make test-prism-postgres-scale PASS
make test-prism-postgres-native-ledger PASS
python -m unittest tests.test_prism_share_ledger 201 tests OK
python -m unittest discover -s tests only the 14 pre-existing, unrelated failures already present on the base commit (check_env_production_gate, prepare_qbit_source, prism_job_builder — environment-dependent, reproduced on a pristine 2.x.x worktree)

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.


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

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

…, 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.
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