Skip to content

3.x.x: give first jobs their own admission, so a session opening during a same-tip rebuild storm no longer waits for the whole fan-out (#604) - #625

Merged
djh58 merged 5 commits into
3.x.xfrom
djh58/prism-b604-first-job2
Oct 1, 2026
Merged

djh58 merged 5 commits into
3.x.xfrom
djh58/prism-b604-first-job2

Conversation

@djh58

@djh58 djh58 commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

Closes #604.

Problem

Every publication makes every connected session rebuild its job. Those rebuilds and a new session's first job shared one first come, first served admission (PRISM_STRATUM_MAX_PENDING_INITIAL_JOBS, 128), and job persistence, which runs after that permit is released, is a second queue: the issued-job batcher admits 128 saves in order. A session opening during a fan-out therefore waited for the whole fan-out, and opening sessions one at a time grew with the square of the session count at a fast reanchor (#604).

Change

  • A session that holds current work (its newest live job, for its current worker, is on the published parent and payout revision, from the new MiningBackend::published_work_hint) now rebuilds through a rebuild lane (StratumConfig::rebuild_job_limit): it takes a lane permit before the shared admission and keeps it until its job is persisted, then releases it before writing to the miner. A session without current work (a new or reconnecting session, a re-authorized worker, work a new tip or payout revision superseded) takes only the shared admission, as before. A rebuild already waiting in the lane re-checks on every publication and leaves for the shared admission once its work is superseded; its lane acquire stays pinned, so a same-tip publication keeps its place. A backend without the hint admits everything through the shared admission. Rebuilds therefore occupy at most the lane between admission and a durable job, the other initial-job permits stay free for sessions with no work, and a first job waits for the lane's rebuilds instead of every session's.
  • The lane is a quarter of the initial-job permits, at least one (32 at the default 128), with no setting of its own; .env.example says so next to PRISM_STRATUM_MAX_PENDING_INITIAL_JOBS. Both listeners share it, as they share the initial-job admission.
  • A lane wait sits inside the existing delivery deadline, so a rebuild that cannot get a lane permit in time fails and is retried like any timed-out delivery.
  • New gauge qbit_prism_stratum_rebuild_lane_waiters: rebuilds waiting for a lane permit, so a saturated fan-out is visible. It is registered at startup (0) and documented in the generated inventory.

What is built, revalidated, persisted, credited or offered is unchanged, as is every payout, authority and #478 block-only rule. Only the order in which sessions are admitted changes. #598's same-tip survival is orthogonal: a rebuild admitted later reads the publication current at its build start.

Lane size and the issued-job batcher

The batcher commits up to 64 saves per transaction, so a lane held through persistence also bounds how many rebuilds share a batch: while commits are slow, rebuilds complete at about the lane per commit. A larger lane recovers that, but a first job waits for about the lane's rebuilds. Measured on the gated storm below (debug build, 1,024 sessions rebuilding back to back, noisy shared host):

lane rebuilds/s storm deliveries ahead of each first job / its wait
32 (this PR) 2,360 ~30 / ~14 ms
128 2,672 ~130 / ~48 ms
192 2,691 ~185 / ~67 ms
none (3.x.x order) 2,548 ~1,025 / ~390 ms

Across runs the 32 lane measured 7 to 22 % below an unbounded one on this storm. When the frontend is CPU-bound instead (the debug live fixture below), throughput does not depend on the lane and a first job waits in proportion to it: a 128 lane opened about 330 sessions per frontend in 11 minutes where 32 opened all 1,500.

Tests

  • Gated coordinator::first_job_lane_tests::a_first_job_is_not_queued_behind_a_rebuild_storm: a real coordinator on PostgreSQL and a fake node, 1,024 sessions served through serve_connection over in-memory pipes and kept rebuilding back to back (every rebuild a real build, revalidation and persisted job), then 8 sessions opened one at a time. It counts the storm deliveries between each one's authorize and its first job (a count, not a wall-clock bound) and requires fewer than three lanes (96). This branch: 14-47 ahead, 8-27 ms. A mutant with no lane (3.x.x's admission order): 1,023-1,034 ahead, ~415-440 ms each (fails). A mutant that releases the lane before persistence: 113-208 ahead (fails). About 4.5-5 s per run.

  • tests/stratum_rebuild_lane.rs (mock backend, no database, the hint published in uppercase): a first job is delivered while the lane is full, a rebuild waits in it (gauge 1), a lane wait that outlasts the deadline fails, clears the gauge and is retried once the lane frees; a rebuild holds its lane permit through persistence and only there, not the shared permit, and a first job's persistence takes neither; a rebuild waiting in the lane stays through a same-tip publication and leaves on a tip change or revision landing; a resumed job is not current work. The "no lane", "first jobs take the lane too", "lane released before persistence", "any held job counts as current work", "never leave the lane", "resumed jobs count as current" and "case-sensitive hash comparison" mutants each fail it.

  • Unchanged and passing: stratum_protocol, stratum_admission, observability (census counts +1 family / +1 series), landing_metrics, work_refresh_metric, metrics_allocation, session_cleanup_metrics, api_config, config_cli, lib metrics::, stratum::, config; clippy clean; generate_prism_metrics.py --check, check_prism_settings.py, check_gate_env_reads.py.

  • Per-PR CI cost: about 5 s in the gated PostgreSQL job, plus about 2 s (6 tests) and one more integration-test binary to link for stratum_rebuild_lane.

  • Rental-churn preset (measured on the first commit; the review fixes change only a lane wait that a superseding publication interrupts; rental-churn-bursts-and-storms, release builds, base = 3.x.x at the merge base, interleaved A/B, one run at a time, 3 per arm): first-job p99 does not regress. Noisy: the host is shared with other build and test work, so each run was pinned to 8 otherwise idle cores (mean 1-minute load 1.2-3.7).

    run rental arrivals p50 / p99 / max (ms) storm reconnects p99 (ms) gate p99, all new sessions churn tip to last notify p99
    base 1 7.0 / 16.5 / 65 9.4 15 ms 945 ms
    fix 1 6.7 / 13.1 / 72 8.8 12 ms 841 ms
    base 2 6.6 / 14.4 / 92 8.8 12 ms 822 ms
    fix 2 6.7 / 13.4 / 83 8.4 11 ms 835 ms
    base 3 6.7 / 13.3 / 71 9.0 11 ms 791 ms
    fix 3 6.6 / 12.6 / 542 9.0 12 ms 779 ms

    Every gate passes in all six. The one 542 ms maximum is a first job whose persistence was deferred and retried because a payout revision landed meanwhile (job persistence deferred, logged once in that run). The same retry appears on the base (an earlier base run: two deferrals, 1,009 ms maximum), and first jobs never take the lane.

Risks

  • Slow issued-job COMMITs. The issued-job batcher commits up to 64 saves per transaction, and a rebuild now holds its lane permit until its save commits, so at most 32 same-tip rebuilds share a batch. When COMMITs slow down (seconds under database stress), same-tip rebuilds complete at about 32 per commit rather than a full batch, and a fan-out takes longer to reach every session. Miners keep hashing their current work meanwhile (though, as before this change, a session answers submits only between deliveries: 3.x.x: a session's share acks wait behind its own queued job rebuild (the request loop reads nothing while deliver_job runs) #621), and first jobs, tip changes and payout revision landings bypass the lane, including rebuilds already waiting in it. qbit_prism_stratum_rebuild_lane_waiters shows when it happens.
  • The hint is only a hint. published_work_hint reads the published parent and payout revision without a lock across the build. If it is stale, a rebuild takes the wrong admission (lane or not) until the next publication; what is built and persisted is unchanged.

#553's 2,000-wallet case

#553 (#618) landed #521 scenario 7 at 2,000 wallets as a by-hand expected failure naming this issue (in no lane; #622 blocks it in release). With this change, in debug at the fixture's 1 s reanchor, it opens all ~3,000 worker sessions (it used to die while opening, at ~27 min) and then fails for a separate reason, filed as #621: each debug frontend delivers about 85-100 jobs/s (every job carries the ~2,000-output coinbase) against one per session per second, so every session always has a rebuild queued, and a session answers a submit only after its queued rebuild completes, which exceeds the fixture's 30 s. This PR repoints the case: wallets_2000_share_to_spend_waits_on_submit_acks_until_621_is_fixed passes on #621's got no reply to a submit, fails on any other error (a worker that never gets work is #604 again), and says so once it passes. The scenario catalogue entry and the CI-lanes doc now name #621 and #622. One by-hand run on this branch (debug, 8 cores) got further: it opened every session and landed three rounds, then ran past the fixture's mock-clock horizon (qbitd's mock time is set about 24 minutes ahead; the template aged past 120 s at 1,624 s) before #621 showed. The case's doc comment says so; it runs by hand only, so it gates nothing.

🤖 Generated with Claude Code

@djh58
djh58 requested a review from kiwidream September 30, 2026 22:27
@djh58

djh58 commented Sep 30, 2026

Copy link
Copy Markdown
Member Author

@cursor review

@blacksmith-sh

This comment has been minimized.

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 763c9e2. Configure here.

async fn published_work_hint(&self) -> Option<(String, i64)> {
let prepared = self.prepared.read().await.clone()?;
let parent = prepared.template["previousblockhash"].as_str()?.to_owned();
Some((parent, prepared.snapshot.payout_revision))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hint hash case skips rebuild lane

Medium Severity

published_work_hint returns previousblockhash from the template unchanged, while issued jobs store that field in lowercase. The holds_current_work check then uses a case-sensitive compare, so any uppercase or mixed-case template hash makes every rebuild look like it has no current work. Those rebuilds skip the lane and again share initial_job_limit with first jobs, which reintroduces the #604 fan-out wait this change is meant to remove.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 763c9e2. Configure here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 4a33063. Jobs carry the template parent hash lowercased (Job::from_manifest), so holds_current_work now compares the hint with eq_ignore_ascii_case. The mock backend in tests/stratum_rebuild_lane.rs now publishes its hint in uppercase with hex-letter parents, so every lane test exercises the comparison: a case-sensitive == fails four of them.

djh58 and others added 2 commits October 1, 2026 10:06
…ng a same-tip rebuild storm no longer waits for the whole fan-out (#604)

Every publication makes every connected session rebuild its job, and those
rebuilds shared the one first come, first served initial-job admission
(PRISM_STRATUM_MAX_PENDING_INITIAL_JOBS, 128) with sessions that had no work
yet. Persistence, after that permit is released, is a second queue: the
issued-job batcher admits 128 saves in order. A session opening during a
fan-out therefore waited for the whole fan-out, and opening sessions one at
a time grew with the square of the session count at a fast reanchor.

A session that holds current work (its newest job, for its current worker,
is on the published parent and payout revision) now rebuilds through a
rebuild lane: a quarter of the initial-job permits, at least one, with no
setting of its own. It takes the lane before the shared admission and keeps
it until its job is persisted, so such rebuilds occupy at most the lane
between admission and a durable job, and a session without current work (a
first job, a re-authorized worker, a tip change, a payout revision landing)
takes only the shared admission, as before, and waits for the lane's
rebuilds rather than every session's. The published parent and revision
come from a new MiningBackend::published_work_hint, an admission hint only.
What is built, persisted, credited or offered is unchanged. A new gauge,
qbit_prism_stratum_rebuild_lane_waiters, counts rebuilds waiting for the
lane.

The lane also bounds how many rebuilds share one issued-job batch, so while
commits are slow, same-tip rebuilds complete at about the lane per commit; a
larger lane would make first jobs wait longer.

Tests: a gated coordinator test keeps 1,024 sessions rebuilding back to
back against PostgreSQL and opens 8 sessions one at a time; each first job
has about 15-40 storm deliveries ahead of it, where the previous admission
put about 1,025 ahead, and a lane released before persistence about
125-210.
Mock-backend tests pin that first jobs, re-authorized workers and sessions
whose work a tip change or revision landing superseded bypass a full lane,
that a lane wait times out and is retried like any delivery, and that a
rebuild keeps its lane permit through persistence and only there.

#553's by-hand 2,000-wallet case expected this starvation. It now opens
every session and fails later, on submits that wait behind their session's
queued rebuild (#621), so its expectation, name and catalogue entry now
point at #621.

Closes #604

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…supersedes its work, and address the review of #625 (#604)

A session's current-work check ran once, before its wait for the rebuild
lane, so sessions still queued there when a new tip or payout revision
landed received that new work only through the lane. The wait now also
watches the session's publications: on each one it checks again and, once
the work is superseded, takes only the shared admission, as a session
without current work does. The lane acquire stays pinned, so a same-tip
publication keeps the rebuild's place in the lane.

Also from review:
- Jobs carry the template's parent hash lowercased; the published-work
  hint is compared without regard to case.
- A job resumed after a reconnect is retired work, not current work.
- A backend without a published-work hint admits every delivery through
  the shared admission, as before #604, instead of treating all held work
  as current.
- The help text describes the lane's sessions as those whose work is still
  on the published parent and payout revision; the lane size is a const
  fn with a note on when to revisit it, and the gated test's bound is three
  lanes (96).
- The pool-acquire gate classifies the lane's two semaphore acquires as
  non-database, like the initial-job admission.

Tests: mock tests pin that a rebuild waiting in the lane stays there through
a same-tip publication and leaves it on a tip change or revision landing,
that a resumed job does not take the lane, and (through an uppercase hint)
the case-insensitive comparison; each fails against its mutant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… a full pass, so a fast first job on a slow runner does not void the test (#604)

On CI the eight first jobs opened before the 1,024-session storm had
delivered 1,024 rebuilds (1,001), and the test's check that the storm
really rebuilt every session failed. The storm now keeps running, for at
most 60 s, until it has, so the check depends on the storm, not on how fast
the host is. The first-job counts it asserts are unchanged.

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

djh58 commented Oct 1, 2026

Copy link
Copy Markdown
Member Author

Handover

@kiwidream now owns this PR. Head is 3601aa7, the gated-test storm fix on top of the review fixes. CI is still running on the head commit. A review ledger will be posted here once CI is green. Any findings from that review will be listed in the ledger as open items with a proposed fix. No new commits will be pushed by the current owner. Left to do: green CI, the ledger, then owner review and merge. This closes #604.

djh58 and others added 2 commits October 1, 2026 12:06
…families

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ts on #621, not #604

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@djh58

djh58 commented Oct 1, 2026

Copy link
Copy Markdown
Member Author

Review ledger at 3f95868a

CI green at 3f95868a (22 pass, 11 skipped). No open findings: 9 fixed, 5 rejected, 2 CI failures not from this change.

Commits: e0a2d42c (the change), 4a330634 (review fixes), 3601aa77 (gated-test guard), and two merges of 3.x.x (2c3516b4, 3f95868a).

Stakes: high (Stratum session admission and job issuance), so Bugbot was summoned.

Lane Result
/code-review medium One finding (F1).
Adversarial review (Claude) F1 again, found independently, plus two minor findings (F3, F4).
Maintainability review (Claude) Eight structural candidates (T1-T8).
Bugbot One finding (F2).
Cross-provider adversarial lane Not run: this change's review is limited to Claude models.
ID Claim Disposition
F1 Whether a session holds current work was decided once, before its lane wait, so sessions queued in the lane when a new tip or payout revision landed got that work only through the lane. Fixed in 4a330634. The lane wait also watches the session's publications. On each one it checks again and leaves for the shared admission once the work is superseded. The acquire stays pinned, so a same-tip publication keeps the rebuild's place. Pinned by a_rebuild_leaves_the_lane_when_a_publication_supersedes_its_work; a "never leave" mutant fails it.
F2 The hint's parent hash is compared case-sensitively with jobs that store it lowercased. Fixed in 4a330634 (reply on the thread).
F3 A job resumed after a reconnect into an empty job list counts as current work and takes the lane. Fixed in 4a330634: only live (unretired) jobs count. Pinned by a_resumed_job_is_not_current_work; the mutant fails it.
F4 The repointed by-hand 2,000-wallet case lost its progress guard, so a wedged lane would pass as "#621 reproduced". Rejected. The case runs by hand only and gates nothing. A lane-permit leak is what the guard would catch, and the mock tests already pin it: every test checks that permits return, and a lane wait that times out clears the gauge and is retried. A worker that never gets work, the #604 failure itself, still fails the case.
T1 Move the lane into a stratum/rebuild_lane.rs module behind a JobAdmission type. Rejected. That is code movement. The lane is about 30 lines in deliver_job, next to the admission it orders, and its size has one source (rebuild_lane_permits, now a const fn) used by both Default and from_env.
T2 The hint's default (None) treats every held job as current. Fixed in 4a330634: without a hint every delivery takes the shared admission, as before #604.
T3 Add a Job::work_key() shared by three parent-and-revision comparisons. Rejected. It would touch retained-jobs code this PR doesn't otherwise change, for a two-field comparison.
T4 The help text says the lane is for sessions that "already hold work". Fixed in 4a330634: .env.example, the gauge help and the generated inventory now say "work still on the published parent and payout revision".
T5 The mock tests duplicate stratum_protocol.rs's backend and could be mounted there. Rejected. Other work is changing the shared Stratum suites concurrently, so this PR keeps its tests in its own files.
T6 The gated bound (128) is loose and not tied to the lane. Fixed in 4a330634: three lanes (96). This branch measures 14-47; a lane released before persistence measures 113-208 and fails.
T7 No note on when to revisit the quarter. Fixed in 4a330634.
T8 Nits: repeated rationale, string dispatch in a test, allow(unreachable_code). Rejected as style only.
CI1 Python unit tests: the pool-acquire gate saw the lane's two semaphore acquires as unclassified checkouts. Fixed in 4a330634: both are classified non-database, like the initial-job admission.
CI2 Shipped images: TimeoutError: timed out. Not this change. The lane died about 38 s in, in its node setup (a qbitd wallet RPC with a 30 s timeout), before any PRISM server started. It failed the same way on 3.x.x at 1bcc8f69.
CI3 The gated first-job test's guard ("the storm delivered 1,001 rebuilds … proves nothing") failed on a slower runner: the first jobs finished before the storm made a full pass. Fixed in 3601aa77: the storm keeps running (at most 60 s) until it has delivered one rebuild per session. The asserted first-job counts are unchanged.
CI4 faults_under_load_drain_an_offer_in_flight_and_outlast_a_settlement_lock_holder failed on 3601aa77. Not this change: #635's fault phase, merged into this branch in 3f95868a.

@djh58
djh58 merged commit f1a1c5f into 3.x.x Oct 1, 2026
33 checks passed
kiwidream added a commit that referenced this pull request Oct 1, 2026
…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]>
kiwidream added a commit that referenced this pull request Oct 1, 2026
…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]>
kiwidream added a commit that referenced this pull request Oct 1, 2026
…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 added a commit that referenced this pull request Oct 1, 2026
…and persisted, and measure what still waits for it (#621) (#642)

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

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

* 3.x.x: count a delivery its session abandons as a cancellation, keep 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]>

* 3.x.x: classify prepare_job's initial-job admission in the checkout census (#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]>

* 3.x.x: close a budget-breached session before announcing a delivery that 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]>

* 3.x.x: test that a rebuild's lane permit is released at persistence while 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]>

* 3.x.x: abandon a delivery in flight before a closing session's last writes (#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]>

---------

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