Skip to content

3.x.x: refuse a block on work from a lost replication gap before its offer, and stop issuing that work after an async promotion (#619) - #645

Merged
kiwidream merged 3 commits into
3.x.xfrom
kiwidream/619-gap-block-investigation
Oct 1, 2026
Merged

kiwidream merged 3 commits into
3.x.xfrom
kiwidream/619-gap-block-investigation

Conversation

@kiwidream

@kiwidream kiwidream commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

Closes #619.

Problem

Under D3 (one primary, one asynchronous standby), a promotion can lose the end of the share history a frontend's work was read from. The promoted sequence then hands the lost share_seq values to other shares, because PostgreSQL WAL-logs sequences 32 values ahead. Every check that admits work, issues a job or enqueues a candidate compared versions a promotion does not change: payout revision, balances, template and tip. The only share-history probes asked whether a share_seq existed. Two modes followed:

  • Mode 1 (the issue's report): a session still holds a job issued in the replication gap. Its block proof is accepted, enqueued and offered, and the node takes it. The landing then fails for good with window range incomplete: expected 15 shares, read 0, and the candidate stays in reconciliation. The coinbase pays the lost window. With CTV settlement on, its covenant outputs commit to a fanout no one can rebuild without that window, and there is no pool spend key.
  • Mode 2 (Anatolie's second comment): the refresh keeps the gap work published after the promotion, because template, revision and balances are unchanged and the 60 s reanchor has not elapsed. The issued-job repair then writes the stale prepared record back onto the promoted primary, because the reissued endpoint share_seqs exist. A new session's block on it fails the same way: 15 rows present, 0 read.

Both modes reproduce deterministically without qbitd, using a real PostgreSQL 16 primary and async standby, one native Coordinator and the fake node. The run uses 20 replicated shares and 80 in the gap, the promoted sequence resumes at share_seq 34 every run, and the gap window is 86..=100 (15 shares). The investigation and the options weighed are in docs/prism-async-promotion-gap-blocks.md.

Decision

Option (d), decided by the operator on 2026-10-01: revalidate the window where it is used. Refuse a block proof stale-job before its offer when the current primary does not hold the window's last row as the window's own, and stop issuing work prepared on another writer timeline.

Option (b), landing the block anyway with a recorded divergence, is rejected. The window is gone, so such a landing could not be audited or settled without inventing numbers. In CTV mode it would still strand the covenant outputs. #478 differs, because there the as-issued window was in the ledger. No migration and no setting are added.

Change

  • Durability test. ledger::probe_window_holding uses one statement and two primary-key lookups. A window is held when its last row exists and matches the window's own predicate (accepted, accepted and issued by the anchor). A missing first row with the last row held is PrefixPruned (retention); anything else is NotHeld. The argument rests on two facts: every native append runs under ORDER_LOCK, so share_seq order is commit order, and a physical standby replays a WAL prefix.
  • Mode 1: candidate enqueue. persist_prepared_candidate runs the test inside the transaction that would write the candidate, under ORDER_LOCK.
  • Mode 2: work authority.
    • Prepared work carries the PostgreSQL writer timeline (3.x.x: bound refresh snapshot payload reads #466's pg_walfile_name expression). It is read in the transaction that scans the window's rows, in the refresh probe's revision statement, and in the clock/revision read issuance already makes.
    • The refresh rebuilds across a timeline change, even on an unchanged template inside the reanchor interval, and never reuses a cached window across one. The rebuild is counted under the new qbit_prism_refresh_seconds{trigger="writer_timeline"}.
    • Issuance (work_authority_in_epoch) admits work from another timeline, or reconstructed from a stored record, only while its window passes the test. A refusal is typed (WorkRefusal), so job preparation deferred and job persistence deferred name window_not_held … (#619), not payout snapshot stale.
    • save_compact_prepared and the issued-job repair require the test before writing a prepared record. They keep the existing prepared share endpoint missing message prefix.
  • Landing text. A landing whose window read fails probes the window. When it is NotHeld, last_error says window not held by this primary … instead of pruning or corruption.
  • Metrics. Two bounded label values are added: one stale-job cause and one refresh trigger. The census grows by exactly those series: +1 at startup and +43 when populated. The contract, cardinality pins, metric metadata and generated inventory are updated.

Docs

  • prism-ha-reference-architecture.md: the accepted asynchronous loss now includes blocks found after a promotion on work whose window lay in the gap; they are refused stale-job. The NTP clock precondition is stated, and promotion step 6 collects the new WARN and the already-offered case.
  • prism-ledger-ops.md, "Work from a lost replication gap (3.x.x: after an async promotion, a block on a job issued in the replication gap is offered and lands on chain but can never be landed in the pool (window range incomplete) #619)":
    • what each check does, with its metrics and logs;
    • the clock precondition;
    • the accounting-loss runbook for a candidate already in reconciliation. In CTV mode it says to keep the fenced old primary unchanged until the window's rows are copied out of an isolated copy. No tool rebuilds a fanout from exported rows today.
  • prism-rejections.md gains the window_not_held cause, and the design note is marked decided (d) with what was implemented.

Tests

All runs used a disposable PostgreSQL 16 started by the native harness, on a shared host, one test binary at a time: PRISM_TEST_PG_BIN_DIR=<PostgreSQL 16 bindir> test/prism-native-tests.sh cargo-args --locked -p qbit-prism-server <target>.

  • --test b619_gap_work_after_promotion. The test file is new and gated; each test builds its own primary and async standby pair, about 14 s for all six. It covers:

    • mode 1, refused stale-job before enqueue, counted once, share not credited;
    • mode 2, issuance refused until the writer_timeline rebuild, both deferral WARNs naming window_not_held, then the new session's window reads whole and its block lands;
    • a fenced switchover with full replay keeps pre-switch work and lands its block;
    • a job persisted before the cut is resumed after an async promotion and lands;
    • a refusal finishing after a 2 s ack deadline, with ORDER_LOCK held from a second connection, counted exactly once;
    • a candidate accepted on the old primary is refused when published on the promoted one.

    With the fix, all pass in every run. Against the product code without the fix, mode 1's block is offered and stuck (window range incomplete … read 0) and mode 2's gap work is issued, 5 of 5 runs. Each review-round fix was also checked by reverting only that fix: its own test fails, and passes again with it.

  • --test candidate_window_switch:

  • Lib:

    • coordinator::window_switch_tests pins the landing's window not held text.
    • ledger::window::payout_state checks, through the execution proxy, that the timeline is read in the transaction that reads the window's rows.
    • coordinator::miner_submit::acquire_tests injects a probe I/O failure: the outcome stays unknown, never stale-job, with nothing enqueued and nothing counted.
  • Results on the branch rebased onto 3f1fba6:

  • Checks: cargo fmt --all -- --check and cargo clippy --locked --workspace --all-targets -- -D warnings are clean. generate_prism_metrics.py --check, check_gate_env_reads.py, check_e2e_scenarios.py (new running scenario r619-gap-work-after-async-promotion) and check_deleted_test_map.py pass.

  • Adversarial verification of the fix commits came back APPROVE, with no Critical, High or Medium finding. Its Low and Info items are addressed in the follow-up commits:

    • the timeline tag is read in the scan transaction;
    • deferral WARNs name window_not_held;
    • late refusals are counted;
    • the clock precondition is documented;
    • two runbook statements are corrected;
    • the out-of-order, probe-error and clock-skew tests are added.

Not run here, and why

The build host has no qbitd and no Docker, so live_regtest did not run. That includes #620's async-promotion test and its opt-in issue_619 reproducer, as well as real CTV landings and load. The reproductions above use the fake node instead of qbitd, with real PostgreSQL promotions.

Merge notes

Review rounds

Follow-ups (not in this PR)

  • Identity guard (option (d)(2)). Carry the last row's share_id in the runtime work and compare it in the enqueue. It would narrow the clock precondition for work held in memory, but work reconstructed from stored records would still need a migration to carry it. Take it if NTP across the database hosts cannot be assured.
  • qbit_share_ledger.writer_epoch is always written as 0. It looks like a writer term but carries none.

🤖 Generated with Claude Code

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-01T20:11:37.878307Z 37e4f67 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

…offer, and stop issuing that work after an async promotion (#619)

Rebased onto 3.x.x 3f1fba6 (#642, #644) as one commit. It squashes the
series that was PR #645's head 60efddd:

- 263e4cd reproduce blocks on gap-issued work after an async promotion
  without qbitd, and weigh the options
- 37b1af7 require the mode 2 reproduction's new session to be issued
  readable work, not just any refusal
- 2fa8c80 refuse a block on work from a lost replication gap before its
  offer, and stop issuing that work after an async promotion
- 850547e document the refusal: the accepted D3 loss, the runbook for an
  already-offered block, and the decided design
- 7d229ac assert each test's outcome before its metric checks
- e7468f4 record the before/after runs in the design note
- c0a8018 tag work with the scan's timeline, name window_not_held in
  deferrals, count late refusals once, and pin the probe-error,
  out-of-order and clock cases
- 60efddd state the clock precondition and correct the runbook

Before a candidate is enqueued, the enqueue transaction checks that the
writer still holds the candidate's PPLNS window: the window's last share
row must exist and must be the window's own row. If it does not, the
block is refused as stale-job (window_not_held) and is never offered.
Prepared work is tagged with the writer timeline (#466's expression,
read in the scan transaction), so a promotion retires it, and issuance
authority refuses a window the promoted writer no longer holds. The
repair path and save_compact_prepared now require the endpoint to be
the window's own row, not just any row with that share_seq. Every
b619 reproduction now passes and is gated.

The only conflict was the cardinality pins: they become 77 families,
305 startup series and 956 populated series. These are 3.x.x's new
families and series plus this series' own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@kiwidream
kiwidream force-pushed the kiwidream/619-gap-block-investigation branch from 60efddd to 384eb2a Compare October 1, 2026 18:11
@blacksmith-sh

This comment has been minimized.

…ueue of a window that reaches past its anchor (#619)

CI on 384eb2a failed two checks for this PR's own reasons.

- The pool-acquire guard needs every checkout classified. Two new
  sites are classified "ledger" (delegated), like the existing
  Ledger::acquire sites: the landing's window probe in
  coordinator.rs::rebuild_claim_parts, and WorkLedger::window_held.
- audit_body_normalization's durable-range test built a window that
  ends with a share accepted after the anchor. It expected the landing's
  proof to refuse that window. The enqueue's #619 check now refuses it
  first, because the last row is not held at the anchor. The case now
  asserts that refusal: it is typed WindowNotHeld for the block and its
  last share_seq, nothing is pending, and no block or audit row is
  written. The other three cases still reach the landing's proof. Share
  history is immutable, so a candidate enqueued before this check
  existed cannot be built to reach the proof's final count.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@kiwidream

Copy link
Copy Markdown
Member Author

Closing and reopening once to re-run CI: on 5c261ad, 'Rust PRISM PostgreSQL and multi-instance contracts (shard 2)' was cancelled at the 30-minute job cap during live_regtest's weighted-recipients PPLNS fanout test on a slow runner (#647). The same product code passed that shard on 384eb2a.

The gate proof on 5c261ad found two gated tests that ran but are not
in test/prism-gated-tests.txt. Both are lib tests from the #619 review
round:

- coordinator::miner_submit::acquire_tests::
  a_failed_window_probe_is_unknown_never_stale_and_enqueues_nothing
- ledger::window::payout_state::tests::
  a_snapshot_reads_its_writer_timeline_in_the_transaction_that_reads_its_rows

The list now holds 804 tests, the same number the proof saw run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@kiwidream
kiwidream merged commit 90327e8 into 3.x.x Oct 1, 2026
34 checks passed
kiwidream added a commit that referenced this pull request Oct 1, 2026
…onger refuses current work as 'tip polling stale' (#622)

Readiness (last_poll), which job preparation, share and block admission
and /healthz require within PRISM_HEALTH_TIP_POLL_MAX_AGE_SECONDS, was
renewed only when a refresh completed. Every refresh starts with a
refresh-grade node poll, but at a fast reanchor each poll is a full rebuild
with no overall deadline, so a rebuild that outlasted the health timeout
after its poll, or a run of rebuilds failing after polling, refused the
current, valid work as 'tip polling stale' and reported unready while the
node answered on the published tip.

A refresh-grade poll now renews readiness, stamped when it was sent and
never backwards, only when: no newer observation found another tip and it
found the published tip; no readiness revocation raced it; the published
template is within PRISM_TEMPLATE_MAX_AGE_SECONDS; readiness was not already
revoked; no refresh has since found the cluster on a heavier chain; and,
under CTV settlement, a relay floor read no older than the poll is recorded
and the published fee meets it (a refresh renews after its own fee_policy,
or without CTV right after its agreeing reconciliation; the block wait
re-reads getmempoolinfo, and a failed read renews nothing). The block wait
polls on an unchanged notification once readiness is one interval old, at
most once per interval: a third of the health timeout, at most 5 s, which
is also its long-poll wait. Revision, fee and lease checks are unchanged;
work_refresh_stalled_seconds still pages on a stalled rebuild.

New metrics: qbit_prism_tip_poll_age_seconds (-1 while unavailable) and
qbit_prism_job_preparation_deferrals_total{reason} (tip_polling_stale,
tip_polling_unavailable, new_tip_pending, work_retired, fee_floor, other);
the tip refusals are typed with unchanged log text. Docs, the generated
inventory, the HA readiness section, the server README and the
PrismWorkRefreshStalledCritical rationale follow.

This fixes the mechanism behind the refusal; that it was #622's trigger on
qbitd is unproven until a #553 2,000-wallet release re-run reads the
deferral reasons beside tip_poll_age and work_refresh_stalled.

Under CTV settlement a refresh's fee policy must also meet the floor kept,
publication checks the work's fee against the current floor, floor reads are
ordered by when their own getmempoolinfo was sent, and a block-wait floor
read that leaves the kept floor above the published fee revokes readiness,
so admissions and submissions in flight fence. A retired authority keeps
#645's refusal context (payout snapshot stale, or window_not_held after a
writer timeline change) and counts as work_retired.

Squashed onto 3.x.x 90327e8 from the reviewed series a98ca18, 86c827c,
c5b43f4, 04ec7f2 (Codex approved 04ec7f2), itself squashed from
4a43b83, 9a13168, 8ed5f6c, 43882f5, 81c4b07, f1fd312, 0537759
(originally 1ba4776e, 9cccdb24, d671cbe9, 5d56b114, 3abba7cb on 4f4b218).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Oct 1, 2026
…bel database refusals truthfully, and page a PostgreSQL outage on its own rule (#581)

#586's nightly variants showed two gaps. Every outbox deadline was the
database clock, so a clock step moved it by the step. Forward, a second
frontend took a live claim whose block was still being offered. Backward,
the reconciliation row that takeover left waited two hours, and a dead
holder's claim would have waited lease + step. Separately, a PostgreSQL
outage held only PrismBlockCandidateMetricsUnavailable: the share-refusal
rules were gated on a snapshot whose freshness flaps while the publisher
waits on the database, and their counters were frozen in it. Database stalls
were refused backend-rpc-unavailable, blaming a healthy node.

Leases (option B, operator-chosen): migration 021 adds claim_renewals and
claim_lease_seconds, a partial index over claimed rows, and the
candidate_claim_observed_lease capability (offline, as 018). A frontend
times each claim version (token, renewals) on its own monotonic clock from
the reply that first shows it, and takes the row over only after the whole
lease, by compare and set on that version, whatever the row's schedule
unless it is parked. Holders fence on their token; their heartbeat deadline
is never extended from the database clock. A row last written later than
the clock proves a backward step and is due at once. candidates recover
waits out an observed lease (--unsafe-database-clock-expiry keeps the old
rule) and its release keeps a schedule within the row's own backoff.
candidates abandon times a claim the same way and abandons by compare and
set on the version it watched, so a forward step no longer lets it take a
pending row from a live holder (Codex on #646); the same flag keeps the
old rule. The pool-acquire inventory classifies the revocation helper.

Attribution and alerting: backend-database-unavailable for session
allocation, the payout reads, job persistence and resume when a SQLx error
is in the chain, and stale readiness when the latest refresh failed on the
database. rejections_total and accepted_shares_total render at scrape time,
the two share-refusal rules drop the snapshot gate, and
PrismDatabaseUnavailable (database collector unavailable for 2 m, paging)
is added, with the qbit-tools patch regenerated. #586's nightly tests now
assert the new behaviour.

Three adversarial verifications: leases and labels requested changes (a
renewal after a backward step stranding a dead holder's row; stale readiness
during an outage still blamed the node), both fixed with regression tests;
the re-verification approved. Rebased onto 3.x.x 90327e8 as one commit
(PR #646's series eb5f65e, 1604a75, 5ce263d), past #642 and #645: the
cardinality pins are 77 families, 306 startup and 957 populated series;
the stratum normalization pin stays 15.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Oct 1, 2026
…onger refuses current work as 'tip polling stale' (#622) (#643)

Readiness (last_poll), which job preparation, share and block admission
and /healthz require within PRISM_HEALTH_TIP_POLL_MAX_AGE_SECONDS, was
renewed only when a refresh completed. Every refresh starts with a
refresh-grade node poll, but at a fast reanchor each poll is a full rebuild
with no overall deadline, so a rebuild that outlasted the health timeout
after its poll, or a run of rebuilds failing after polling, refused the
current, valid work as 'tip polling stale' and reported unready while the
node answered on the published tip.

A refresh-grade poll now renews readiness, stamped when it was sent and
never backwards, only when: no newer observation found another tip and it
found the published tip; no readiness revocation raced it; the published
template is within PRISM_TEMPLATE_MAX_AGE_SECONDS; readiness was not already
revoked; no refresh has since found the cluster on a heavier chain; and,
under CTV settlement, a relay floor read no older than the poll is recorded
and the published fee meets it (a refresh renews after its own fee_policy,
or without CTV right after its agreeing reconciliation; the block wait
re-reads getmempoolinfo, and a failed read renews nothing). The block wait
polls on an unchanged notification once readiness is one interval old, at
most once per interval: a third of the health timeout, at most 5 s, which
is also its long-poll wait. Revision, fee and lease checks are unchanged;
work_refresh_stalled_seconds still pages on a stalled rebuild.

New metrics: qbit_prism_tip_poll_age_seconds (-1 while unavailable) and
qbit_prism_job_preparation_deferrals_total{reason} (tip_polling_stale,
tip_polling_unavailable, new_tip_pending, work_retired, fee_floor, other);
the tip refusals are typed with unchanged log text. Docs, the generated
inventory, the HA readiness section, the server README and the
PrismWorkRefreshStalledCritical rationale follow.

This fixes the mechanism behind the refusal; that it was #622's trigger on
qbitd is unproven until a #553 2,000-wallet release re-run reads the
deferral reasons beside tip_poll_age and work_refresh_stalled.

Under CTV settlement a refresh's fee policy must also meet the floor kept,
publication checks the work's fee against the current floor, floor reads are
ordered by when their own getmempoolinfo was sent, and a block-wait floor
read that leaves the kept floor above the published fee revokes readiness,
so admissions and submissions in flight fence. A retired authority keeps
#645's refusal context (payout snapshot stale, or window_not_held after a
writer timeline change) and counts as work_retired.

Squashed onto 3.x.x 90327e8 from the reviewed series a98ca18, 86c827c,
c5b43f4, 04ec7f2 (Codex approved 04ec7f2), itself squashed from
4a43b83, 9a13168, 8ed5f6c, 43882f5, 81c4b07, f1fd312, 0537759
(originally 1ba4776e, 9cccdb24, d671cbe9, 5d56b114, 3abba7cb on 4f4b218).

Co-authored-by: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Oct 2, 2026
…bel database refusals truthfully, and page a PostgreSQL outage on its own rule (#581)

#586's nightly variants showed two gaps. Every outbox deadline was the
database clock, so a clock step moved it by the step. Forward, a second
frontend took a live claim whose block was still being offered. Backward,
the reconciliation row that takeover left waited two hours, and a dead
holder's claim would have waited lease + step. Separately, a PostgreSQL
outage held only PrismBlockCandidateMetricsUnavailable: the share-refusal
rules were gated on a snapshot whose freshness flaps while the publisher
waits on the database, and their counters were frozen in it. Database stalls
were refused backend-rpc-unavailable, blaming a healthy node.

Leases (option B, operator-chosen): migration 021 adds claim_renewals and
claim_lease_seconds, a partial index over claimed rows, and the
candidate_claim_observed_lease capability (offline, as 018). A frontend
times each claim version (token, renewals) on its own monotonic clock from
the reply that first shows it, and takes the row over only after the whole
lease, by compare and set on that version, whatever the row's schedule
unless it is parked. Holders fence on their token; their heartbeat deadline
is never extended from the database clock. A row last written later than
the clock proves a backward step and is due at once. candidates recover
waits out an observed lease (--unsafe-database-clock-expiry keeps the old
rule) and its release keeps a schedule within the row's own backoff.
candidates abandon times a claim the same way and abandons by compare and
set on the version it watched, so a forward step no longer lets it take a
pending row from a live holder (Codex on #646); the same flag keeps the
old rule. The pool-acquire inventory classifies the revocation helper.

Attribution and alerting: backend-database-unavailable for session
allocation, the payout reads, job persistence and resume when a SQLx error
is in the chain, and stale readiness when the latest refresh failed on the
database. rejections_total and accepted_shares_total render at scrape time,
the two share-refusal rules drop the snapshot gate, and
PrismDatabaseUnavailable (database collector unavailable for 2 m, paging)
is added, with the qbit-tools patch regenerated. #586's nightly tests now
assert the new behaviour.

Three adversarial verifications: leases and labels requested changes (a
renewal after a backward step stranding a dead holder's row; stale readiness
during an outage still blamed the node), both fixed with regression tests;
the re-verification approved. Rebased onto 3.x.x eedf331 as one commit
(PR #646's series eb5f65e, 1604a75, 5ce263d), past #642, #645 and
#643: the cardinality pins are 79 families, 313 startup and 964 populated
series; the stratum normalization pin stays 15. ReadinessState keeps
#643's poll fields and refresh_failed_on_database, whose comment now says
that a guarded tip poll (#622) decides whether readiness ages during a
database outage and this flag decides the label once it does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Oct 2, 2026
…bel database refusals truthfully, and page a PostgreSQL outage on its own rule (#581) (#646)

* 3.x.x: time candidate claim leases on the taker's monotonic clock, label database refusals truthfully, and page a PostgreSQL outage on its own rule (#581)

#586's nightly variants showed two gaps. Every outbox deadline was the
database clock, so a clock step moved it by the step. Forward, a second
frontend took a live claim whose block was still being offered. Backward,
the reconciliation row that takeover left waited two hours, and a dead
holder's claim would have waited lease + step. Separately, a PostgreSQL
outage held only PrismBlockCandidateMetricsUnavailable: the share-refusal
rules were gated on a snapshot whose freshness flaps while the publisher
waits on the database, and their counters were frozen in it. Database stalls
were refused backend-rpc-unavailable, blaming a healthy node.

Leases (option B, operator-chosen): migration 021 adds claim_renewals and
claim_lease_seconds, a partial index over claimed rows, and the
candidate_claim_observed_lease capability (offline, as 018). A frontend
times each claim version (token, renewals) on its own monotonic clock from
the reply that first shows it, and takes the row over only after the whole
lease, by compare and set on that version, whatever the row's schedule
unless it is parked. Holders fence on their token; their heartbeat deadline
is never extended from the database clock. A row last written later than
the clock proves a backward step and is due at once. candidates recover
waits out an observed lease (--unsafe-database-clock-expiry keeps the old
rule) and its release keeps a schedule within the row's own backoff.
candidates abandon times a claim the same way and abandons by compare and
set on the version it watched, so a forward step no longer lets it take a
pending row from a live holder (Codex on #646); the same flag keeps the
old rule. The pool-acquire inventory classifies the revocation helper.

Attribution and alerting: backend-database-unavailable for session
allocation, the payout reads, job persistence and resume when a SQLx error
is in the chain, and stale readiness when the latest refresh failed on the
database. rejections_total and accepted_shares_total render at scrape time,
the two share-refusal rules drop the snapshot gate, and
PrismDatabaseUnavailable (database collector unavailable for 2 m, paging)
is added, with the qbit-tools patch regenerated. #586's nightly tests now
assert the new behaviour.

Three adversarial verifications: leases and labels requested changes (a
renewal after a backward step stranding a dead holder's row; stale readiness
during an outage still blamed the node), both fixed with regression tests;
the re-verification approved. Rebased onto 3.x.x eedf331 as one commit
(PR #646's series eb5f65e, 1604a75, 5ce263d), past #642, #645 and
#643: the cardinality pins are 79 families, 313 startup and 964 populated
series; the stratum normalization pin stays 15. ReadinessState keeps
#643's poll fields and refresh_failed_on_database, whose comment now says
that a guarded tip poll (#622) decides whether readiness ages during a
database outage and this flag decides the label once it does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* 3.x.x: record a refresh's database failure before it releases the refresh lock, so an older refresh cannot overwrite a newer one's (#581)

Codex on #646: refresh_once wrote refresh_failed_on_database after
refresh_once_inner had returned and dropped refresh_lock. Two overlapping
refreshes run serialized under that lock, but the older one could record
its outcome after the newer one had: a success overwriting the database
failure that followed it. If readiness then aged out, the refusal would
blame the node although the latest refresh failed on PostgreSQL.

The work under the lock moves to refresh_locked, and refresh_once_inner
records the outcome before the lock guard drops, so outcomes land in the
order the refreshes ran. The lock order (refresh lock, then readiness) is
the one the refresh already takes.

Test: a refresh paused in its revision read fails on the database while
the test holds readiness, so it cannot record yet. The refresh lock must
still be held, and the newer, successful refresh's outcome is the one
left. On the old code the lock was already free (the headline assertion
fails). The stale-readiness test's comment now names #643's guarded tip
poll.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* 3.x.x: label an issued persistence that outlived its deadline as the database's, whichever of the deadline and the statement failed first (#581)

CI shard 0 on 0b21539 failed compact_runtime_e2e's
issued_expiry_during_sql_wait test: a persistence queued on a database
lock past its 1 s deadline was refused backend-database-unavailable when
the statement its shortened statement_timeout cancelled failed first, and
backend-rpc-unavailable when the deadline fired first (a plain string
error). The label depended on which future completed first.

Persistence waits on the ledger alone (its clock and revision reads, the
batch transaction and its row locks, the compact repair it writes), so an
expiry is the database not answering in time. save_issued_record, the one
place that knows the persistence's own deadline, now marks a failure that
outlived it with a typed IssuedPersistenceExpired, and persist_issued_job
labels that backend-database-unavailable before the SQLx-chain rule. A
failure inside the deadline keeps that rule (a statement error is the
database's; an authority refusal stays backend-rpc-unavailable). The full
error chain is logged.

Tests: a unit test forces both orderings on the fake ledger (a statement
failing inside the deadline; the deadline elapsing while the save still
waits, its statement failing afterwards), both
backend-database-unavailable; without the classification the second is
labelled the node's, as in CI. The e2e test now runs both orderings on
PostgreSQL (the waiting statement cancelled inside the deadline; the lock
held past it) and expects the database label for each. A sweep of other
backend-rpc-unavailable assertions found none on a database-wait path.
prism-rejections.md names the case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
RobertClarke added a commit that referenced this pull request Oct 6, 2026
…, now that #645 refuses it (#474)

#645 fixed #619 on 3.x.x: a block on work from a lost replication gap
is refused as stale-job before its offer. The opt-in reproducer
issue_619_gap_issued_block_after_async_promotion_is_refused_or_pays_only_promoted_rows
passes on the rebased branch, and it asserts everything the gated drill
does plus that refusal. So the gated drill now submits the block it
solved on the gap-issued job, and the ignored copy and the GapBlock
switch are gone.

The comments that described #619 as open now describe #645's behaviour,
and the scenario note and #645's design note name the gated drill
instead of the removed reproducer.

Locally against PostgreSQL 16 and the pinned qbit 1.0.0, the drill
passed 15 of 15 runs; each time the gap-issued block was refused as
stale-job and no session was replaced for a stale window.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
RobertClarke added a commit that referenced this pull request Oct 6, 2026
…he surviving share before any block moves the tip (#474)

Codex: when the gap-issued block was refused, nothing checked that its
share was not credited. It was not added to the answers the drill holds
to the promoted ledger, so a regression that credited the block as an
ordinary share while refusing its payout authority would have passed.
It is now one of those answers: landed, it must be credited once;
refused, not at all. #645's own gated test asserts the same without
qbitd.

/code-review high: the surviving acknowledged share was replayed after
the final block had moved the tip, and was required to read
`duplicate-share`. The server settles a stale parent, with its 3 s
grace, before it looks for a duplicate. So once the replays of the lost
shares outlasted the grace, the same replay would have read
`stale-job` on a correct server. It is now replayed right after the kept
work, while its parent is still the tip.

The review's other findings are test robustness and cleanup, and are
deferred to #697.

Locally against PostgreSQL 16 and the pinned qbit 1.0.0, the drill
passed 8 of 8 runs with both changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
RobertClarke pushed a commit that referenced this pull request Oct 6, 2026
…CKed, rejected and unknown share, keep sessions and work, and land a block on the promoted ledger (#474) (#620)

Refs #474 (slice B). Test-only. A gated live_regtest drill,
pg_failover_tests::async_live_miners, runs an asynchronous PostgreSQL
promotion under four scripted Stratum miners on two native frontends
and a real qbitd. It reuses live_pg_failover.rs's D3 pair, relays and
promotion procedure.

Every submission is recorded with the answer its miner got. A deferred
trigger holds a share's COMMIT across the writer fence. The drill then
reconciles exactly:
- every acknowledged share is on the old primary;
- every acknowledged share the promoted ledger lacks lies in the
  replication gap and is named;
- no refusal was committed, and nothing sent after the fence was
  acknowledged.

After the promotion, the same sessions submit on their current jobs
and on work they kept from before the cut and from inside the gap. A
surviving share replayed while its parent is the tip is a duplicate.
The block solved on a job issued in the gap must be refused as stale
with its share uncredited, or land paying only promoted rows. Since
#645 fixed #619, which this drill found, it is refused before its
offer, so the drill submits it; the opt-in reproducer is folded in. A
real block then lands. Its audit must equal an independent read of the
promoted window, which holds sequence numbers lost shares had. Every
later answer must match the promoted ledger's credits.

ShareClient gains solve and submit_solved, so a miner can keep solved
work and submit it later.

Taken over per #626 and rebased onto 3.x.x. Codex asked that the
refused gap block be held to zero credit, and it is. /code-review high
found the duplicate replay depended on the 3 s stale grace once the
final block moved the tip, so it now runs earlier. Its other findings
are in #697. The drill passed 27 local runs against PostgreSQL 16 and
the pinned qbit 1.0.0. Two runs under heavy host load failed in its
setup; those races are in #697 too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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