Skip to content

3.x.x: answer a session's submits while its own job rebuild is built and persisted, and measure what still waits for it (#621) - #642

Merged
kiwidream merged 6 commits into
3.x.xfrom
kiwidream/621-ack-behind-rebuild
Oct 1, 2026
Merged

kiwidream merged 6 commits into
3.x.xfrom
kiwidream/621-ack-behind-rebuild

Conversation

@kiwidream

@kiwidream kiwidream commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

Closes #621.

A Stratum session handled one thing at a time. When it needed a new job, serve_connection ran deliver_job after its select! and read no request until the job had been admitted, built and persisted. So a mining.submit arriving during a rebuild was answered only after it. Back in the select!, the refresh and read branches raced, so a submit could wait for a second rebuild too. When rebuilds queue, as in #553's 2,000-wallet case at a 1 s reanchor, every session always has one queued, and a share ACK waited up to PRISM_STRATUM_INITIAL_JOB_TIMEOUT_SECONDS (30 s) behind its own session's rebuild.

Change

deliver_job is split in two:

  • prepare_job admits, builds and persists the job. It works from DeliveryInputs read from the session when the delivery starts (worker, extranonce1, difficulty, miner version mask) and borrows nothing else from the session. The session keeps it as an in-flight future and polls it from the same select!, and also while it handles a request (alongside). So the delivery never stalls behind a slow submit while holding its admission permit.
  • announce_job runs once prepare_job completes and does what the second half of deliver_job did: version mask, mining.set_difficulty, then mining.notify, then retiring and burying the work it replaces.

Answered during a delivery: mining.submit and mining.get_health. Neither changes what the job is built from or how it is announced. A submit is checked against the jobs the session already holds, which are the jobs the miner holds, because the new job has not been announced yet. A frame that is not a JSON object is answered at once, as before.

Held: every other JSON object frame, in order. That is mining.subscribe, mining.authorize, mining.configure, mining.suggest_difficulty, mining.extranonce.subscribe, any other method, or a frame whose method is missing or not a string. Such a request waits for the delivery in flight, and the session reads nothing after it until it is handled. Responses therefore keep request order, and these requests see the session exactly as before.

Ordering guarantees kept:

  • A job is announced only once it is durable. Its difficulty and notify are written together, after any answer already given.
  • A share on work the rebuild will supersede is decided as before, by the coordinator against the durable payout revision and the published tip. The session's stale-grace anchor is still its last announcement, as for a share that arrived just before the rebuild. Nothing is retired or buried before the announcement.
  • No retarget runs while a delivery is in flight, because that job keeps the difficulty it was built at. A due retarget rides the next delivery as it starts, so back-to-back rebuilds cannot starve vardiff. A share accepted while a retarget's delivery is in flight also counts in the vardiff state that a failed delivery restores.
  • retry_job is consumed when a delivery starts. A publication seen while a delivery is in flight is therefore delivered after it, instead of being cleared by it. A failed delivery is still retried after the next event, never in the same pass.
  • The initial-job deadline does not cut a delivery in flight; before this change the timer could not fire during one either.
  • A session that ends abandons a delivery still in flight, and any finished but unannounced one, before its last writes. A budget breach closes it before a finished delivery is announced. Either way the session stops right after the response that ended it, as before.
  • The select! is biased, with reads last. Every other branch (shutdown, the finished delivery, refresh, timer) is ready at most once per event and returns at once, so none of them can starve a pending read. A request backlog in turn cannot hold off a finished delivery, a new publication or the unauthenticated-peer deadline.

Metrics

  • qbit_prism_stratum_request_delivery_wait_seconds (histogram, default ladder, no labels): from a held request's complete frame to the end of its session's own delivery. A submit queued behind a held request is read only afterwards, and share_ack_seconds starts at that read, so this family carries the ACK wait still attributable to job delivery. It is registered at startup; every bucket, _sum and _count reads 0 until the first wait.
  • qbit_prism_job_delivery_cancellations_total (counter): deliveries abandoned unannounced because their session ended (disconnect, protocol error or shutdown). A session now notices that while a delivery is in flight. These are not failures: a delivery is counted once, in exactly one of successes, failures and cancellations. A failed announcement write still counts as a failure, as before. The count is also exposed as the additive /health field stratum.job_delivery_cancellations.
  • The census goes from 75 to 77 families: startup series 289 → 304, populated 898 → 913. The contract, the allocation test and the generated inventory are updated.

Tests

There are 12 new deterministic tests. A gate holds the build, a submit or a write, and no test sleeps. Each test fails against a mutant that undoes the guarantee it names:

test mutant it catches
a_submit_is_answered_while_the_sessions_own_rebuild_is_held (also answers a health probe) 3.x.x itself (no reply in 5 s); health probes held
a_rebuild_keeps_moving_while_a_submit_is_handled delivery not polled while a request is handled
a_publication_seen_during_a_held_rebuild_is_delivered_after_it announcement clears retry_job
a_retarget_earned_during_a_held_rebuild_rides_the_next_delivery no retarget at delivery start
observability::a_difficulty_request_waits_for_the_delivery_in_flight_and_its_wait_is_observed no request held
stratum::stale_grace_tests::a_failed_retarget_delivery_keeps_the_shares_answered_while_it_was_in_flight (lib) shares not credited to the restorable vardiff state
a_rebuild_keeps_moving_while_an_invalid_frame_answer_is_held invalid-frame answer written outside alongside
a_delivery_abandoned_by_its_session_is_a_cancellation_not_a_failure cancellation counted as a failure
a_failed_announcement_write_is_still_a_failed_delivery failed announcement write counted as a cancellation
a_budget_breach_closes_the_session_before_a_finished_delivery_is_announced announcement before the budget check (Codex's review)
an_oversized_frame_abandons_the_delivery_before_its_rejection_is_written delivery kept, unpolled, through a closing session's last write (Codex's review)
stratum_rebuild_lane::a_rebuild_releases_its_lane_permit_while_a_submit_delays_its_announcement lane permit carried in PreparedJob until the announcement

Run on this branch, rebased onto the current 3.x.x, against a private PostgreSQL 16 through test/prism-native-tests.sh cargo-args --locked, one test binary at a time:

suite passed failed ignored
--test stratum_protocol 49 0 1 (pre-existing)
--test stratum_rebuild_lane 7 0 0
--test stratum_admission_postgres 17 0 1 (pre-existing)
--test observability 17 0 0
--test stratum_admission 5 0 0
--test vardiff_convergence 7 0 0
--test stratum_properties 8 0 0
--test stratum_codec 7 0 0
--test metrics_allocation 4 0 0
--test landing_metrics 41 0 0
--test session_cleanup_metrics 5 0 0
--test b574_ack_cap 22 0 0
--test readiness_rpc 11 0 0
--lib -- stratum:: metrics:: vardiff:: coordinator::first_job_lane_tests 83 0 0

Earlier, on the first commit, the wider set also passed. That set was authorization_rpc, b478_capture_overpay, b478_payout_integrity, b478_stale_revision_block, b602_order_lock_hold, compact_runtime_e2e, refresh_liveness, refresh_window_split and stratum_admission_postgres (381 passed across 21 binaries), plus --lib coordinator:: (377 passed together with stratum::, metrics:: and vardiff::). cargo fmt --all -- --check, cargo clippy --locked -p qbit-prism-server --all-targets -- -D warnings, python3 scripts/generate_prism_metrics.py --check, python3 scripts/check_e2e_scenarios.py and python3 scripts/check_prism_pool_acquires.py are clean, and so is scripts/run_python_test_shard.py --shard-index 2 --shard-count 4 (348 tests OK, 15 skipped).

An adversarial verification of the first commit returned APPROVE, with three low findings, all fixed in the second commit:

  • An abandoned delivery was counted as a failure; it now counts as a cancellation.
  • The invalid-frame answer was written outside alongside.
  • The help and metadata did not list the held requests exactly.

Not run here and why

The build host has no qbitd and no docker, so these were not run:

  • live_regtest, including the transcript replay;
  • the qbitd-dependent Stratum suites (checkout_probe_delivery, fanout_revision_bump, equal_work_scheduler, equal_work_tip, lost_race_pin, candidate_window_qualification, compact_runtime_scale);
  • 3.x.x: Chain-event scenarios under session load (L4) (#487 S15) #553's 2,000-wallet case;
  • the load and rental-churn presets.

Merge notes

@djh58: your #625 (#604, the first-job lane) merged into 3.x.x while this PR was in review. This branch is rebased onto it, and the composition follows the three conditions the review set:

#625's lane code moved from deliver_job into prepare_job unchanged. Its stratum_rebuild_lane tests (now 7) and the gated coordinator::first_job_lane_tests::a_first_job_is_not_queued_behind_a_rebuild_storm pass. Its scripts/prism_pool_acquires.json keys now name prepare_job, and the test-only deliver_job wrapper takes the refresh receiver its stale_grace_tests call sites pass. #625's note that a session "answers submits only between deliveries: #621" no longer holds.

🤖 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-01T17:23:09.783744Z ae4f9fa Manual request
ℹ️ 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.

@blacksmith-sh

This comment has been minimized.

@kiwidream

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 431241e3a5

ℹ️ 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".

Comment thread crates/qbit-prism-server/src/stratum.rs Resolved
kiwidream added a commit that referenced this pull request Oct 1, 2026
…hat finished during its answer (#621)

Codex's review of #642: when a request that breaches a per-session budget
(a malformed frame, an unknown-job submit, an authorize) was answered while
the session's delivery was in flight, `alongside` could finish that
delivery meanwhile. The loop then announced the job before its budget
check closed the session. Before #621 a breach closed the session right
after its answer and never announced anything. A peer that stopped reading
after its rejection could also hold its connection for up to the write
timeout while those writes waited.

The budget check now runs first in the post-select pass, before a finished
delivery is announced. It runs again after a held request is handled, since
that request can breach a budget too. A delivery dropped this way counts
as a cancellation: its session ended before the announcement.

`a_budget_breach_closes_the_session_before_a_finished_delivery_is_announced`
holds the breaching frame's answer while the delivery finishes. Without the
fix it reads the job's set_difficulty after the breach.

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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 51b2319226

ℹ️ 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".

kiwidream and others added 5 commits October 1, 2026 13:04
…and persisted, and measure what still waits for it (#621)

A Stratum session ran `deliver_job` after its `select!` and read no request
until it returned, so a `mining.submit` arriving during a rebuild was
answered only after the job was admitted, built and persisted: up to
`PRISM_STRATUM_INITIAL_JOB_TIMEOUT_SECONDS` when rebuilds queue, as in
branches raced, so a submit could also wait for a second rebuild.

The delivery is split in two. `prepare_job` admits, builds and persists the
job from `DeliveryInputs` read from the session when it starts (worker,
extranonce1, difficulty, miner version mask) and borrows nothing else from
it; the session loop keeps it as an in-flight future and polls it from the
same `select!`. `announce_job` runs when it completes and does what the
second half of `deliver_job` did: version mask, difficulty, then notify,
then retiring and burying the work it replaces. So:

- A submit (or health probe) arriving meanwhile is answered at once,
  against the jobs the session already holds, which are the ones the miner
  holds: the new job is not announced yet. The delivery keeps being polled
  while that request is handled, so it never stalls behind a slow submit
  holding its admission permit; one that finishes meanwhile is announced
  after the answer. A share on work the rebuild will supersede is decided
  as before, by the coordinator against the durable payout revision and
  published tip; the session's grace anchor is the last announcement, as
  for a share that arrived just before the rebuild.
- A job is announced only after it is durable, and its difficulty and
  notify are written together, after any answer already given.
- A request that changes what the job is built from (subscribe, authorize,
  configure, suggest_difficulty, or a method the server does not know)
  waits for the delivery, and the session reads nothing after it until it
  is handled, so responses keep request order and those requests see the
  session exactly as before.
- A retarget does not run under a delivery in flight (that job keeps the
  difficulty it was built at); a due retarget rides the next delivery as it
  starts, so back-to-back rebuilds cannot starve vardiff. A share accepted
  while a retarget's delivery is in flight also counts in the vardiff state
  a failed delivery restores.
- `retry_job` is consumed when a delivery starts, so a publication seen
  while one is in flight is delivered after it instead of being cleared by
  it; a failed delivery is still retried after the next event, not at once.
- The initial-job deadline does not cut a delivery in flight, as the timer
  could not fire during one before.
- The `select!` is biased with reads last: every other branch is ready at
  most once per tick, publication or delivery and returns promptly, so none
  starves a pending request, and a request backlog cannot hold off a
  finished delivery, a publication or the unauthenticated-peer deadline.

What still makes a request wait for the session's own delivery is measured
by the new histogram `qbit_prism_stratum_request_delivery_wait_seconds`:
one observation per held request, from its complete frame to the end of
the delivery. A submit queued behind it is read only afterwards, and
`share_ack_seconds` starts at that read, so this family carries that wait.
It is registered at startup, documented in the generated inventory and
counted in the observability contract and census (+1 family, +14 series).

The in-crate `deliver_job` remains as a test-only wrapper over the two
halves. #625's rebuild lane composes: its lane wait moves into
`prepare_job`'s build, its `prior` hint into `DeliveryInputs`, and the lane
permit still drops once the job is persisted, before any write.

Tests (no sleeps; a gate holds the build): a submit sent during a held
rebuild is answered before the release (fails on 3.x.x: no reply in 5 s);
a health probe is answered too; the rebuild is persisted while a submit is
held in the backend and announced after its answer; a publication seen
during the hold is delivered after it; a retarget earned during the hold
rides the next delivery; a suggest_difficulty during the hold waits, holds
the submit sent after it, and is observed once in the new histogram; a
failed retarget delivery keeps the share answered while it was in flight.
Each fails against a mutant that drops the guarantee it names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…a delivery moving while an invalid frame is answered, and list the held requests exactly (#621)

The adversarial review of the previous commit found three things.

A delivery its session abandons is no failure. Since the previous commit
a session notices EOF, a protocol error or shutdown while its delivery is
in flight and drops the delivery. Dropping it counted in
`job_delivery_failures_total`, so in #621's own regime every churned miner
added a "failed delivery" beside the build, persistence and deadline
failures that counter is for. Before the previous commit the loop could
not end mid-delivery: the build finished and its announcement was written
to whatever was left of the socket. A delivery now settles in exactly one
of three counters: a success, a failure (an admission, build or
persistence error or deadline, or a failed announcement write, as
before), or the new `job_delivery_cancellations_total`. That counter
covers a delivery still being admitted, built or persisted, or built but
not yet announced, when its session ends. It is registered at startup at 0
and also exposed as `stratum.job_delivery_cancellations` in /health, an
additive field. The metadata of the failure counter now names the
boundary.

The answer to a frame that is not a JSON object was written outside
`alongside`, so a peer that stopped reading could hold the in-flight
delivery, and an admission permit taken inside its build, without
progress for up to the 20 s write timeout. It is now written alongside the
delivery, like every other answer. The oversized-frame answer is left as
is, because the session ends right after it.

The held-request lists in the new histogram's help, its metadata and the
`answered_during_delivery` doc comment named only subscribe, authorize,
configure, suggest_difficulty and unknown methods. The code also holds
`mining.extranonce.subscribe` and object frames whose method is missing or
not a string. Every JSON object frame other than `mining.submit` and
`mining.get_health` is held. The metadata said "Zero series from start";
it now says the buckets, `_sum` and `_count` are registered at startup and
read 0 until the first wait.

Composing with #625. The review approved the rebase on four conditions;
the fourth was the alongside write above, now done. The other three, for
whoever rebases:
- Keep the rebuild-lane permit a local of `prepare_job`, dropped when
  persistence returns. Do not move it into `PreparedJob`, or it stays held
  while a concurrent submit finishes (`backend.submit` can take seconds,
  #602) before the announcement.
- Capture `prior`, the current-work hint, in `DeliveryInputs` as an owned
  (parent, payout revision) pair. Do not clone the `Job`, which carries
  the ~2,000-output coinbase.
- Give `prepare_job` its own clone of the refresh receiver for the lane
  wait's re-check. Do not share the session loop's receiver.

Tests:
- `a_delivery_abandoned_by_its_session_is_a_cancellation_not_a_failure`:
  one session disconnects and another is shut down, each mid-rebuild. On
  the previous commit this read 2 failures.
- `a_rebuild_keeps_moving_while_an_invalid_frame_answer_is_held`: a gated
  writer holds the invalid-frame answer, and the rebuild is still persisted
  meanwhile. On the previous commit it stalled until the write was
  released.
- `a_failed_announcement_write_is_still_a_failed_delivery`: the boundary
  of the first test.
Each fails against a mutant that undoes its fix and passes with it. None
sleeps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ensus (#621)

The delivery split moved the shared initial-job admission,
`config.initial_job_limit.acquire()`, from `deliver_job` into
`prepare_job`. `scripts/check_prism_pool_acquires.py` keys its census by
function, so CI's Python shard 2 saw an unclassified acquire and a stale
classification. The entry keeps its "non-database" class (a Tokio
semaphore, not a database checkout) under its new name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hat finished during its answer (#621)

Codex's review of #642: when a request that breaches a per-session budget
(a malformed frame, an unknown-job submit, an authorize) was answered while
the session's delivery was in flight, `alongside` could finish that
delivery meanwhile. The loop then announced the job before its budget
check closed the session. Before #621 a breach closed the session right
after its answer and never announced anything. A peer that stopped reading
after its rejection could also hold its connection for up to the write
timeout while those writes waited.

The budget check now runs first in the post-select pass, before a finished
delivery is announced. It runs again after a held request is handled, since
that request can breach a budget too. A delivery dropped this way counts
as a cancellation: its session ended before the announcement.

`a_budget_breach_closes_the_session_before_a_finished_delivery_is_announced`
holds the breaching frame's answer while the delivery finishes. Without the
fix it reads the job's set_difficulty after the breach.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hile a submit delays its announcement (#621)

#625's rebuild lane is now on 3.x.x, and this branch composes with it on
the three conditions its review set:
- the lane permit stays a local of `prepare_job`, dropped once
  persistence returns, never carried in `PreparedJob`;
- `prior` is captured in `DeliveryInputs` as an owned (parent, payout
  revision) pair;
- `prepare_job` gets its own clone of the refresh receiver for the lane
  wait's re-check.

The first condition matters only since #621: a session may now hold a
persisted job unannounced while it finishes a submit (`alongside`), and
`backend.submit` can take seconds (#602).
`a_rebuild_releases_its_lane_permit_while_a_submit_delays_its_announcement`
holds a submit in the backend while the rebuild persists, and requires the
lane permit back before that submit is answered. It fails against a mutant
that carries the permit in `PreparedJob` until the announcement. The lane
test backend gains a submit gate for it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@kiwidream
kiwidream force-pushed the kiwidream/621-ack-behind-rebuild branch from 51b2319 to a21a0ec Compare October 1, 2026 17:11
@kiwidream

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a21a0ec34c

ℹ️ 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".

Comment thread crates/qbit-prism-server/src/stratum.rs Resolved
…rites (#621)

Codex's review of #642: a frame over the size limit closes the session,
but its rejection was written while the session's delivery was still in
flight and no longer polled. A peer that stopped reading could hold that
write for up to the 20 s write timeout. Meanwhile the paused delivery kept
the initial-job admission permit, or #604's rebuild-lane permit, that it
took inside its build. Polling the delivery during that write would only
build a job no one announces, so the session now abandons it instead.

On leaving its loop for any reason, the session drops a delivery still in
flight, and any finished but unannounced one, before its last writes: the
oversized-frame rejection, which moves after the loop, and the writer's
shutdown. Either counts as a cancellation.

`an_oversized_frame_abandons_the_delivery_before_its_rejection_is_written`
holds the rejection's write and requires the admission permit back and the
cancellation counted meanwhile. Without the fix the permit stays held (127
of 128).

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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: ae4f9fa3ba

ℹ️ 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".

@kiwidream
kiwidream merged commit 8dbdb57 into 3.x.x Oct 1, 2026
34 checks passed
kiwidream added a commit that referenced this pull request Oct 1, 2026
…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 added a commit that referenced this pull request Oct 1, 2026
…offer, and stop issuing that work after an async promotion (#619) (#645)

* 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)

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]>

* 3.x.x: classify #619's two pool checkouts, and pin the refusal at enqueue 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]>

* 3.x.x: list #619's two gated lib tests in the expected gate list (#619)

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]>

---------

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 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]>
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