Skip to content

Distinguish an idempotent confirm replay from a fresh block confirmation - #146

Merged
kiwidream merged 1 commit into
2.x.xfrom
distinguish-idempotent-confirm-replay
Aug 19, 2026
Merged

kiwidream merged 1 commit into
2.x.xfrom
distinguish-idempotent-confirm-replay

Conversation

@kiwidream

@kiwidream kiwidream commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Closes the follow-up deferred from #59: qbit_confirm_pool_block could not tell a fresh block confirmation from an idempotent replay.

Scope note, added after review: on the current 2.x.x base the at-tip churn itself (generation bump, cache wipe, refresh abort) is already neutralized by the generation-based publication gate landed with #59/#133 — the PR's own replay scenario, run under the old 1-for-both contract on origin/2.x.x, passes every no-churn assertion. What remains live on this base is the contract defect: the function's return value still cannot distinguish the two outcomes, so callers reason from a collapsed signal — the coordinator's confirmed_count != 1 arm treats a covered replay as a confirmation failure, and any future consumer would inherit the same ambiguity. This PR is therefore durable contract hardening: it makes the distinction explicit and load-bearing rather than incidental, and pins it across both backends.

The defect

The function collapsed two different outcomes into a return of 1:

  • the fresh flip — the UPDATE ... SET chain_state='confirmed' matched a prepared row, so confirmed_count = 1, and the same statement allocated an audit publication ordinal via nextval;
  • the idempotent arm — the UPDATE matched nothing, but a confirmed non-reversed row already exists at that (hash, height), so the function returned a literal 1 without allocating an ordinal.

A caller could not distinguish them, and a genuinely new confirmation must publish for payout correctness. So every replay of a candidate whose block is still the best tip bumped the payout generation, wiped the job-bundle cache, and aborted in-flight refreshes until a successor block arrived — the window right after finding a block, not a rare corner.

#59 rejected in-memory discriminators (published tip, source-cause heuristics) because reorg corners can make a genuinely new confirmation look already-covered, and skipping one strands stale payout state. That reasoning still holds for in-memory signals. The audit publication ordinal draws exactly this line durably: only the flip allocates one, and the function already knew internally which arm it took — it just discarded the fact.

Return contract

before after
fresh flip out of prepared, allocates the publication ordinal 1 1
idempotent replay of an already-confirmed row, allocates none 1 2
no row, or a live row this confirmation does not match 0 0
terminally disposed (reorg quarantine, rejection, reversal) -1 -1

2 returns the ordinal the original flip assigned and burns no sequence.

Consumers threaded

  • crates/qbit-prism/sql/001_share_ledger.sql — qbit_confirm_pool_block, the idempotent arm now returns 2.
  • lab/prism/share_ledger.py — the memory ledger's parity implementation, which now splits on whether the row was already confirmed.
  • lab/prism/share_ledger.py — the psql wrapper, which read the ordinal only on 1 and now reads it on 1 and 2; a covered replay still needs the ordinal to address its audit publication. Non-confirming dispositions (0, -1) have no row to read and stay a single statement, so the two-statement heartbeat behaviour from PRISM: escalated landing budget can outrun the 120s watchdog and restart-loop found-block settlement #125 is unchanged for them.
  • lab/prism/block_finalization.py — the coordinator confirm branch. 2 binds the publication identity and completes the candidate exactly like a fresh flip, instead of falling into the confirmation-failure arm.
  • lab/prism/audit_artifacts.py — see the publication-ordering section below.
  • tests/prism_vardiff_test_support.py — the shared ledger fake now models the split, so existing replay coverage exercises it.
  • tests/prism_postgres_a1_gate.py and test/test-prism-postgres-ledger.sh — the disposition matrix.

The pre-ordinal function in 001_share_ledger_revert_audit_publication_sequence.sql is deliberately untouched: a revert restores the old contract, and a rolled-forward coordinator reading 1 from it behaves exactly as it does today.

What an at-tip replay does now

It completes as a covered replay: no payout source reserved, no generation bump, no job-bundle cache wipe, no tip-refresh churn, and the candidate stays accepted rather than being abandoned with a shutdown request.

The fence and pending-source checks that decide publication are unchanged and unweakened. A source left unpublished by a prior attempt, or a leaked delivery fence whose source already published (the #59 healing case), still publishes here exactly as before — the disposition never forces a publication past those checks, and never suppresses one they demand.

Publication-ordering interaction (commit 03e733e, issue #133)

Checked before changing the return contract, and it needed a fix:

  • The confirmation dict rides in the published evidence ("confirmation": landed.confirmation), and publish_success compares the whole normalized payload on an exact replay. A restart replay reporting 2 where the flip had published 1 would have been rejected as exact audit publication replay payload conflict. The disposition now joins accepted_share_count / distinct_miner_count / persistence.share_count as an observational annotation reused from the durable publication. The publication ordinal it rides with is block identity and is still compared unchanged, so a replay returning a different ordinal still conflicts — covered by a new case in test_exact_replay_is_stable_but_changed_evidence_conflicts.
  • The publication floor is unaffected. audit_publication_sequence_floor() reads durable rows, and the idempotent arm burns no sequence and rewrites no ordinal, so a replay cannot move the floor. Confirmed directly against PostgreSQL 16: the A1 gate now asserts allocator immobility alongside the new disposition on every replay round, and the ledger suite asserts the sequence's last_value/is_called are byte-identical before and after an exact replay.
  • The superseded-envelope restore path from 03e733e is untouched: it keys on identity.sequence versus the durable floor, neither of which a replay changes. The C1–C3 process gates (C1-confirmation-order, C2-A-wins-confirmation-publication, C3-B-wins-late-A) pass unchanged.

Verification

Regression test — sensitivity, stated precisely. test_at_tip_idempotent_confirm_replay_skips_publication in tests/test_prism_block_candidates.py pins the new contract end to end: it lands a block, then replays the durable candidate while that block is still the best tip, with the ledger reporting the idempotent disposition. It asserts the payout generation, published source, _payout_state_source, job-bundle cache, tip-refresh retry count, pending-refresh counter and discarded-candidate counter are all untouched, delivery is unfenced, no shutdown was requested, and the audit publication replays against the ordinal the flip allocated.

It fails before this change and passes after — confirmed explicitly. The sensitivity is to the contract change, exercised through the new disposition: on the unmodified tree the replay reports disposition 2, the coordinator's confirmed_count != 1 arm fires, and it fails with ledger did not confirm accepted block …: shutdown requested, published preview withdrawn, candidate abandoned. (Under the old contract the same replay returns 1 and the already-neutralized generation gate keeps the churn assertions green — that is the baseline the scope note above describes.) test_exact_replay_is_stable_but_changed_evidence_conflicts likewise fails before the audit_artifacts.py change with RuntimeError not raised inverted — the old case asserted that confirmed_count: 2 on replay must conflict, which is precisely the assumption this contract retires.

Postgres suites ran for real — test/test-prism-postgres-ledger.sh against a provisioned PostgreSQL 16 container (postgres:16-alpine, sha256:7e7dbab8…), all four gates green:

prism postgres ledger PASS shares=14 lease=replay startup-retry persist-fence sql-window maturity=reorg carry-replay integrity multipage-window=9000
prism postgres A1 gate PASS exact-transition-parity empty-fresh empty-legacy ordinary-decoy-binding temporary-decoy-binding durable-floor-gaps
prism postgres A1 migration gate PASS M0-M11 bigint-bounds invalid-definitions migration-advisory-waiter
prism postgres A1 revert gate PASS round-trip legacy-confirm loud-failure noop-idempotent
prism postgres A1 process gate PASS C1-confirmation-order C2-A-wins-confirmation-publication C3-B-wins-late-A

The A1 gate's test_exact_transition_parity compares full Postgres and memory-ledger responses on every transition, so it is what holds the two backends to the same disposition matrix. It now asserts 1 / 2 / 0 / -1 explicitly across fresh confirm, three exact-replay rounds, confirm-after-reactivation, inactive, reversed and wrong-height, plus a fresh confirmation after the replays. The ledger suite adds no-sequence-burn and confirm-after-reactivation coverage.

Unit suites — 2123 tests, all green except the five pre-existing tests/test_prism_job_builder os.splice failures, which are macOS-only; they fail identically on the unmodified tree and pass under Linux/Python 3.12.

Lint — shellcheck -x over all tracked shell scripts (in Docker) and python -m compileall docker lab tests examples scripts both clean; bash -n clean; cargo test --locked --workspace --all-targets green.

Refs #61. Overlaps #133 / commit 03e733e as described above.

🤖 Generated with Claude Code


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

qbit_confirm_pool_block collapsed two different outcomes into a return of 1:
the fresh flip, where the UPDATE matched a 'prepared' row and allocated an
audit publication ordinal through nextval, and the idempotent arm, where the
UPDATE matched nothing but a confirmed non-reversed row already exists at that
(hash, height) and no ordinal is allocated. A caller could not tell them apart,
and a genuinely new confirmation must publish for payout correctness, so every
replay of a candidate whose block is still the best tip republished identical
payout state -- bumping the payout generation, wiping the job-bundle cache and
aborting in-flight refreshes until a successor block arrived.

The audit publication ordinal already draws this line durably: only the flip
allocates one. Report that fact instead of discarding it.

Return contract, was 1 / 0 / -1, now 1 / 2 / 0 / -1:

  1   fresh flip out of 'prepared'; allocates the publication ordinal
  2   idempotent replay of an already-confirmed row; allocates none, and
      returns the ordinal its original flip assigned (new)
  0   no row, or a live row this confirmation does not match
 -1   terminally disposed (reorg quarantine, rejection, reversal)

Threaded through every consumer:

  * the SQL function itself
  * the memory ledger's parity implementation, which now splits on whether
    the row was already 'confirmed'
  * the psql wrapper, which reads the ordinal on 1 and 2 (a covered replay
    still needs it to address its audit publication) and stays a single
    statement for the non-confirming dispositions
  * the coordinator confirm branch, where 2 completes the candidate exactly
    like a fresh flip instead of falling into the confirmation-failure arm
  * the shared test ledger fake, so unit coverage models the split
  * the A1 gate disposition matrix and the Postgres ledger suite

An at-tip replay now completes as a covered replay: it reserves no payout
source, bumps no generation, wipes no job-bundle cache and schedules no
refresh churn. The fence and pending-source checks that decide publication are
unchanged and unweakened -- a source left unpublished by a prior attempt, or a
leaked delivery fence, still publishes exactly as before.

Publication-ordering interaction with the audit ordinal work: the confirmation
dict rides in the published evidence, which publish_success compares in full on
an exact replay. A restart replay reporting 2 where the flip published 1 would
have been rejected as a payload conflict, so the disposition now joins the
share counters as an observational annotation reused from the durable
publication. The ordinal it rides with is block identity and is still compared
unchanged, so a replay returning a different ordinal still conflicts. The
ordinal is unaffected either way: the idempotent arm burns no sequence, so the
durable publication floor cannot move on a replay.

Refs #61

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@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.

@kiwidream

Copy link
Copy Markdown
Member Author

Post-review narrative update: a Fable review verified the code but could not reproduce the historical at-tip churn on the current 2.x.x base — #59's generation-based publication gate already neutralizes it under the old 1-for-both contract. The PR body now presents this as durable contract hardening (making the fresh-flip/idempotent-replay distinction explicit and load-bearing, pinned across both backends) rather than a live-bug fix, and states the regression test's sensitivity precisely: it fails before the change via the new disposition (confirmed_count != 1 arm), not via the historical churn. No code changes — the diff was approved as-is apart from this framing.

@kiwidream
kiwidream merged commit 15540e3 into 2.x.x Aug 19, 2026
11 checks passed
@kiwidream
kiwidream deleted the distinguish-idempotent-confirm-replay branch August 19, 2026 19:01
kiwidream added a commit that referenced this pull request Aug 19, 2026
The harness PR (#148) was squash-merged, so 2.x.x carries
tests/prism_landing_harness.py under a commit unrelated to this branch's
history. The merge base therefore predates the file on both sides and git
reports an add/add conflict for it.

Resolved in favour of this branch: 2.x.x's copy is byte-identical to this
branch's pre-change version of the file, and this branch's copy is that
same file plus the additive accepted_at_ms kwarg the straddling-row tests
need. Nothing from 2.x.x is dropped.

Everything else auto-merged; the regions are disjoint. Verified both sides
survived: this branch's anchor-set comment and the per-anchor fences in
block_finalization.py, and 2.x.x's idempotent-confirm-replay handling from
#146.
kiwidream added a commit that referenced this pull request Sep 11, 2026