Skip to content

Scale PRISM tip refresh, block finalization, and share ingest for the whale ramp - #100

Merged
RobertClarke merged 35 commits into
1.x.xfrom
prism-whale-scale
Jul 29, 2026
Merged

RobertClarke merged 35 commits into
1.x.xfrom
prism-whale-scale

Conversation

@RobertClarke

@RobertClarke RobertClarke commented Jul 26, 2026 •

Copy link
Copy Markdown
Member

Whale-ramp scaling for the mainnet PRISM coordinator (~2,800 connections, one ~0.5 EH/s worker across ~2,400 devices, ~13k shares/min), measured on mainnet 2026-07-26. Six changes, in priority order.

Stacked on #99 (prism-cache-persist, converged at b289550): this branch builds on the pay-once-per-generation artifact/spool architecture, so until #99 merges the diff below includes its commits. Once #99 lands on 1.x.x, merging 1.x.x here collapses the diff to this PR's own changes (the six commits after the two merge commits).

1. Reconcile off the refresh critical path

phase="reorg_reconcile" (added by #98) measured 0.56s mean at ~750 connections and 0.94s at 2,000+, serial before every bundle build. Root cause: the poll path called ensure_reorg_reconciled_for_tip directly, which never consults the per-tip trusted memo — by design, per the old comment "the blockpoll loop re-reconciles every poll anyway."

  • The poll now consults the memo (same-tip re-polls within PRISM_REORG_RECONCILE_CACHE_SECONDS skip the serialized pass entirely). The live chain-trust check stays uncached, and publication still re-proves trust in _validate_prepared_tip_refresh before any fanout.
  • On a memo miss the pass runs on a single-worker prefetch lane, overlapping the getblocktemplate fetch; the poll joins it where the serial call used to sit. The phase histogram now records the effective serial cost (probe + residual join wait) — the <0.2s target is directly observable on the existing metric.
  • A tip that moves between the probe and the fetch discards the prefetched pass and reconciles the snapshot tip serially, exactly as before.
  • New counter qbit_prism_reorg_reconcile_lookups_total{path,source} exposes the memo hit rate for both the tip-refresh and per-client job-build lanes (the instrument the item asked for first).
  • ensure_reorg_reconciled_for_tip itself is unchanged (always a real pass; Avoid reconcile singleflight under the accepted-block payout lock #96 lock-owner no-wait semantics untouched).

2. Block finalization off the delivery path

_land_and_confirm_block_candidate held _payout_balance_mutation_lock from pre-submit triage through durable confirmation with the audit-builder subprocess, coinbase fence, and bundle verification inside the hold; the landed-transition fence spans the same window. Job delivery and the refresh reconcile queue behind both — the July 2026 healthz coverage-0 / null-delivery-age stalls.

Every input to the audit bundle is frozen on the candidate (share window, prior balances, extranonces, template fields), so it is now built and verified speculatively before the lock and adopted under it. The lock and the landed fence now cover only the submit RPC, preview publications, and the durable persist/confirm writes; the verified preview publishes sooner, unblocking next-tip child job builds earlier. Speculation is strictly an optimization: any anomaly falls back to the in-lock rebuild with today's exact fence and shutdown semantics (submitblock always precedes any mismatch disposition), the cheap coinbase equality fence still runs under the lock either way, and #96's payout-preview/prior-balance semantics are untouched. A fail-fast reconcile pre-check ahead of the lock was considered and deliberately dropped: it contradicts the pinned "persistence allows delivery but serializes reconciliation" contract.

3. qbit_prism_block_submit_seconds

The outbox created_at→completed_at span (~16–22s) conflates post-submit bookkeeping. PrismBlockCandidate now stamps landed_monotonic (share-accept time live, row-restore time on replay) and the histogram observes landed→submitblock-return for every attempt whose RPC returned, accepted or rejected — the race-loss tail metric (4–6 abandons/5min during the ramp vs 23–40/day baseline) and the proof instrument for #96.

4. Fanout wave duration + pay-once notify serialization

  • qbit_prism_tip_refresh_fanout_wave_seconds: wall-clock first-task-submission → last-successful-delivery per completed prepared wave. The existing first/last_delivery histograms anchor at refresh start and conflate reconcile/build time.
  • mining.notify was json.dumps'd per client per wave with coinb1/coinb2/merkle_branch byte-identical across all ~2,800 clients. The base job now carries the seven shared params serialized once per build; send_job_update splices job id and clean_jobs around the fragment into a preserialized send_batch fast path. Byte equality with full serialization is test-pinned; monkeypatched-send seams and hand-built jobs fall back unchanged.
  • The 16-worker cap and its SystemExit guard are unchanged: with serialization off the per-send cost the wave is socket-bound, and raising the cap should be decided against the new wave metric plus descriptor-pressure analysis, not bundled here.

5. Unknown-job rejects under reconnect churn (0.28% during ramp)

Devices behind a flapping proxy keep mining the dead connection's jobs and submit them on the replacement connection, which could never see them: disconnect purged the connection's contexts and graveyard lookups were connection-scoped.

Disconnect now buries the connection's active jobs and retains its same-tip graveyard entries detached from the dead client object; expiry anchors on the entry's own eviction time (same-tip TTL) or the published tip flip — never on delivery state a dead connection cannot advance (avoiding the pre-existing unbounded branch in _stale_grace_entry_expired_locked). An authorized reconnect of the same username may submit against a detached entry; credit and dedup stay on the retained context's original worker identity, so replays remain duplicate-share and foreign usernames still reject unknown-job. Stale-grace entries keep the historical purge. Bounds: existing per-connection cap + TTL, plus PRISM_STRATUM_DISCONNECTED_JOB_RETENTION (default 16384; 0 restores purge-on-disconnect). New metric label values: capacity scope disconnected, submit outcome accepted_same_tip_cross_connection.

6. Share-ingest saturation instrument (measure-first for the thread ceiling)

qbit_prism_share_ack_seconds{result}: mining.submit line-arrival (stamped before JSON parse) → Stratum response. Accepted shares include the group-commit wait; rejects skip it, so the pair separates commit pressure from thread-scheduling/GIL pressure as connection count grows (2,902 threads / 40.5% CPU at 2,818 connections). The fast-path prototype itself is deliberately out of scope.

Validation

  • python3 -m unittest discover -s tests -p 'test_*.py': 1,308 tests, 0 failures, 3 skips (baseline ~1,300; new tests are event-driven, no wall-clock sleeps).
  • All existing metric names stable; additions only (one new label value set on two existing evicted-job families).
  • Reduce PRISM accepted-block payout gate locking #50 payout-preview guard semantics and prior-balance fencing untouched.
  • Two behavior-pinning tests updated to the new contracts with rationale in-diff: the next-tip preview test's mid-flight hook moved from bundle-build (now pre-lock) to persistence, and the disconnect cleanup tests now pin retention-with-detach (plus a new retention-0 purge test).

🤖 Generated with Claude Code


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


Note

High Risk
Touches reconcile memo/prefetch correctness, payout balance locking around block finalization, and cross-connection share acceptance—core mining and settlement paths at high connection scale.

Overview
Whale-ramp scaling for the PRISM coordinator: tip refresh, block landing, Stratum fanout, reconnect churn, and share-ingest observability.

Tip refresh reuses the per-tip trusted reconcile memo on poll (with uncached chain-trust checks) and overlaps memo misses with getblocktemplate on a single-worker prefetch lane, guarded by tip_detection_epoch so flips invalidate stale proofs. New counters qbit_prism_reorg_reconcile_lookups_total and qbit_prism_tip_refresh_fanout_wave_seconds expose reconcile sources and wave wall time.

Block landing runs audit bundle build/verify with the payout balance serializer temporarily released (landed fence still armed); submitblock stays first. qbit_prism_block_submit_seconds measures candidate landed → RPC return via landed_monotonic on PrismBlockCandidate.

Fanout pre-serializes the seven shared mining.notify params once per job build and splices per-client job id and clean_jobs in send_job_update / send_batch.

Reconnect churn: PRISM_STRATUM_DISCONNECTED_JOB_RETENTION (default 16384) keeps detached same-tip graveyard entries after disconnect; same-username reconnects can submit with original worker identity, version mask, and extranonce1; outcome accepted_same_tip_cross_connection.

Share ingest: qbit_prism_share_ack_seconds{result} from line arrival to Stratum response (accepted includes group-commit wait; rejected observed on error path).

Reviewed by Cursor Bugbot for commit 670785a. Bugbot is set up for automated code reviews on this repo. Configure here.

RobertClarke and others added 29 commits July 26, 2026 10:56
The tip-independent PayoutLedgerArtifact spares tip refreshes the multi-
second reward-window read, but at mainnet share rates it was structurally
dead: the exact-count reuse fence rejects the artifact as soon as one share
lands, nothing re-armed preparation until the next payout event, and the
speculative rebuild aborts whenever a share commits mid-read.

Keeping exact-count semantics unchanged:

- A failed count fence now schedules a debounced rebuild through the
  existing one-slot latest-wins preparation worker. The new
  PRISM_PAYOUT_ARTIFACT_REARM_MIN_SECONDS floor (default 5s) keeps the
  reward-window CTE from running continuously, and landed accepted-block
  previews suppress the re-arm entirely so a speculative rebuild cannot
  resurrect database balances the published prospective state supersedes.

- The synchronous ledger_snapshot path inside build_shared_job_bundle now
  publishes the window it just read as a fresh artifact, fenced by the same
  before/after accepted-count check as the background path and anchored at
  the build's own snapshot anchor. The artifact carries the published
  payout-state balances, so the reuse fence's balance hash holds by
  construction. Publication is deferred to bundle cache publication:
  installing mid-build re-keyed concurrent lookups away from the in-flight
  single flight and forked redundant builds.

- Bundle lookups re-keyed by a freshly armed artifact fall back to the
  no-artifact cache identity (and accept it for subscribed flight results),
  so already-cached work keeps serving instead of rebuilding; installs are
  freshness-ordered and idempotent because every flight waiter re-runs
  cache publication with the same prepared artifact.

Co-Authored-By: Claude Fable 5 <[email protected]>
Every audit-bundle build re-streamed the identical multi-megabyte share
window through chunked Python pipe-writes into the freshly spawned builder,
even though the compact serialized fragments are already cached per (payout
generation, ledger artifact generation).

The invariant payload tail (compact identities, compact shares, and the
closing brace) is now spooled once per generation into an anonymous temp
file in the same temporary filesystem the builder's captured output already
uses. Each build serializes only its small varying prefix; the tail moves
into the child's stdin pipe with kernel splice transfers, checkpointing
cancellation between chunks exactly like the write loop it replaces, so
supersession/terminate handling and the registered-process lifecycle are
unchanged. The builder still reads one JSON document from stdin: its
--input file mode is no help here because that file would have to carry the
whole per-build payload, recreating the copy this change removes.

Spool lifecycle is leased: generation rotation and shutdown retire the
spool, and the descriptor closes when the last in-flight transfer releases
it, never underneath one. Being unlinked from birth, a crashed coordinator
cannot strand a window on disk. Spooling failures are sticky per generation
and fall back automatically to the existing in-memory pipe path, as does a
first-byte splice failure (unsupported filesystem) or an embedder process
fake without a real pipe descriptor.

Co-Authored-By: Claude Fable 5 <[email protected]>
Every audit-bundle build spawned a fresh qbit-prism-build-audit-bundle
process that re-parsed megabytes of identical window JSON before doing any
real work. The builder now offers a long-lived JSONL request/response mode
over stdin/stdout, announced by a protocol-versioned startup handshake.

Rust side: --serve caches the PARSED share window keyed by the
coordinator's share_snapshot_sha256, bounded to the two most recent
generations. A request carries only the small varying inputs plus the
window key; a request may inline the compact window (upload), and a request
for an uncached key gets a needs_window response instead of a build. Every
response reports the same input_deserialization/output_serialization
timings the one-shot mode emits plus cumulative cache hit/miss counters.
One-shot mode is unchanged and remains fully supported; the image's
cargo build --locked --release -p qbit-prism --bins still succeeds with no
new dependencies.

Python side: the artifact-backed summary path tries the daemon first,
spawning it through prism_tool_command with stderr inherited so crash
diagnostics reach the journal. Window uploads reuse the per-generation
spool file through kernel splice; the coordinator mirrors the daemon's
bounded cache to predict uploads and repairs divergence on needs_window.
The daemon process is registered through the _register_job_bundle_process
lifecycle, so payout/tip supersession terminates it at request level
(kill+respawn); cancellation and supersession raise exactly like one-shot
builds. Any daemon anomaly -- spawn failure, handshake or protocol
mismatch, crash, timeout, malformed response -- retires the daemon and
falls back transparently to the one-shot subprocess, which stays the path
for canonical/full-share builds. New qbit_prism_serve_builder_* metrics
count daemon requests, fallbacks, spawns, uploads, and window-cache
outcomes; existing metric and phase names are untouched. A contended
daemon simply routes that build to one-shot instead of queueing, and
PRISM_BUILDER_SERVE=0 disables the daemon entirely.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ntity

Review hardening for the payout-ledger-artifact re-arm (PR #99, Cursor
Bugbot high-severity + two Codex P1 findings, same two defects):

- The no-artifact bundle-cache fallback could shadow a fresher re-armed
  artifact: a speculative rebuild installs a newer window while the
  pre-re-key bundle is still inside its cache TTL, and lookups keyed to the
  new artifact fell back to that older bundle unconditionally. The artifact
  now records its window digest, and every fallback consumer (shared flow,
  subscribed flight results, and the initial probe) serves pre-re-key work
  only when the bundle's own window digest matches the armed artifact --
  which the bundle that published the artifact satisfies by construction.
  The digest also lets the share-window serialization slot reuse the
  artifact's digest instead of recomputing it per generation.

- The synchronous seeding fence proved no share committed during the read,
  but not that the accepted count was scoped to the generation's frozen
  anchor: a share committing between anchor freeze and the build left the
  artifact pairing an inclusive count with an anchor-exclusive window,
  wedging the exact-count reuse fence open around a window missing a
  durable share. Anchor clamping now captures a bracketed accepted count
  (single-writer FIFO commits make the total durable count equal the count
  at the anchor), and the synchronous path publishes only while the live
  fenced count still equals that anchor-scoped value.

Co-Authored-By: Claude Fable 5 <[email protected]>
…talls

Round-2 review hardening (PR #99):

- Codex P1: a hung daemon consumed the whole configured build budget and
  the one-shot fallback then started over with a fresh full deadline,
  letting one build run to nearly twice the limit progress health already
  treats as stuck. build_audit_bundle now computes a single deadline that
  the daemon attempt and the one-shot fallback share; a daemon timeout
  falls back with the budget it already spent, so the fallback's own
  timeout path fires at the original limit and records the worker failure
  exactly once (the daemon paths no longer pre-count it).

- Cursor high: the freshness-ordered artifact install let a speculative
  background rebuild replace a sync-published artifact even when no share
  had committed since -- a byte-identical window under a fresh anchor --
  spinning the artifact generation and re-keying bundle lookups for
  nothing. Installs now also skip when the incoming artifact carries the
  same accepted count and window digest as the installed one. Genuinely
  newer windows still replace, which the exact-count reuse fence and the
  per-generation bundle keys already keep sound.

- Codex P2: --serve reported output_serialization_seconds from a
  summary-to-Value conversion while the real encoding happened during the
  envelope write. The summary is now fully encoded to JSON inside the
  measured window and embedded verbatim via RawValue, so the metric covers
  the same serialization work the one-shot mode times and the envelope
  never re-encodes the summary.

Co-Authored-By: Claude Fable 5 <[email protected]>
Round-3 review hardening (PR #99, two Codex P2 findings):

- The same-window install skip compared only the accepted count and window
  digest, so a retarget that changes network difficulty while the window
  stays identical kept discarding the newly prepared artifact; the retained
  old-difficulty artifact fails the reuse fence on every build and nothing
  re-arms until a share changes the count. The skip now also requires
  matching network difficulty, so a difficulty-only rebuild replaces the
  artifact.

- Serve-builder counters were guarded by _serve_builder_lock, which one
  request holds across a whole daemon round trip; a Prometheus scrape
  overlapping an expensive build stalled on it. The counters now have
  their own short-lived _serve_builder_metrics_lock, taken briefly by
  mutations and by the metrics reader.

Co-Authored-By: Claude Fable 5 <[email protected]>
…tomic

Round-4 review hardening (PR #99, two Codex P2 findings):

- Every --serve cache hit deep-cloned the parsed window (O(window) string
  allocations per build on 100k+ share windows). Both audit build entry
  points only borrow the shares for derivation and move the vector
  unmodified into AuditBundle.shares, so the daemon now loans the cached
  vector to the build and reclaims it from the finished bundle -- zero
  copies in either direction. A failed build drops the loaned window and
  the coordinator's needs_window bounce re-uploads it.

- The fence-failure re-arm checked its debounce, released the executor
  lock, and re-acquired it to enqueue, so a worker dequeue or a racing
  probe in the gap could double-run the reward-window snapshot; the
  durable-confirmation call site could also enqueue on top of its own
  probe's re-arm. The debounce check, timestamp update, and request
  enqueue are now one atomic step under the executor lock, and the
  schedule-if-missing probe no longer re-arms since its caller enqueues
  unconditionally.

Co-Authored-By: Claude Fable 5 <[email protected]>
Round-5 review hardening (PR #99, three Cursor findings):

- A commit racing the anchor-count bracket stored None for the generation
  and disabled synchronous artifact seeding until the next template
  rotation. The capture is two cheap aggregate reads, so the freeze now
  retries the bracket a bounded number of times; a late re-bind stays
  impossible (a failed bracket cannot tell which side of the clamp each
  racing commit landed on), so residual failures still store None.

- A needs_window re-send observed serialization_copy once per send,
  inflating the phase against the one-shot transport. The python-side
  write time is now accumulated across sends and observed once per build,
  keeping the three-observation shape (precompose, transport writes,
  builder-reported timings) identical across transports.

- The daemon derived the per-response window_cache.hit flag from
  compact_share_identities while branching on compact_shares, so an
  identities-only request could disagree with the hit/miss counters. The
  flag now derives from the same predicate that selects the branch, and
  identities-without-shares requests are rejected exactly like one-shot
  mode.

Co-Authored-By: Claude Fable 5 <[email protected]>
Round-6 review hardening (PR #99, Codex P2): the daemon moves a hit window
to most-recent LRU position, but the coordinator's mirror only recorded
uploads, so after a hit-then-upload sequence the two sides evicted
different keys -- costing either a needless re-upload of a still-cached
production-sized window or a needs_window round trip for one already
evicted. Every successful response now promotes the window in the mirror
(the upload counter still counts only actual uploads), and the fake serve
builder promotes on hit exactly like the real daemon so the alignment is
testable end to end.

Co-Authored-By: Claude Fable 5 <[email protected]>
Round-7 review hardening (PR #99, Codex P2): --serve recorded
input_deserialization_seconds after compact-window expansion, while
one-shot mode samples immediately after the JSON parse and before its own
expansion. Production-sized uploads therefore folded an extra O(window)
reconstruction into the serve metric, skewing transport comparisons. The
serve timer now samples exactly at the parse boundary, so both transports
report identical work and window resolution stays outside the metric in
both modes.

Co-Authored-By: Claude Fable 5 <[email protected]>
Round-8 review hardening (PR #99, Codex P2): prepared_monotonic stamps
window-conversion completion, so a snapshot read at an older count but
delayed in to_prism_json() could overwrite an installed artifact holding a
newer window; the count fence then rejected the regressed artifact and the
next refresh repeated the full ledger snapshot this change exists to
avoid. Accepted-share counts are append-only within a payout generation,
so installs now order by count: a strictly lower count never replaces, an
equal count with identical window and difficulty keeps the installed
generation, and everything newer installs regardless of completion-time
interleaving.

Co-Authored-By: Claude Fable 5 <[email protected]>
Round-9 review hardening (PR #99, Codex P1): at sustained mainnet share
rates the exact-count publication fence keeps aborting speculative
rebuilds, so the fence-failure re-arm was retrying the full reward-window
walk at the configured floor without ever arming -- and each attempt holds
the payout preparation lock that inline tip builds also need. Consecutive
aborted rebuilds now double the re-arm interval up to a capped multiplier
(80s at the default 5s floor); any successful install or event-driven
preparation resets the backoff, and the exact-count fence itself stays
untouched per the reuse contract. Under saturation the synchronous seeding
path remains the arming mechanism, and the residual speculative duty cycle
drops to a few percent.

Co-Authored-By: Claude Fable 5 <[email protected]>
Round-10 review hardening (PR #99, Codex P2): a daemon upload dying
mid-splice retired the daemon but left the spool marked healthy, so the
transparent one-shot fallback retried the same transfer and its
partial-stream branch failed the whole build even though the cached
in-memory fragments were valid. Genuine spool-side I/O errors now poison
the spool in both transfer loops before propagating -- distinguished from
BrokenPipeError, which means the receiving pipe died and must not degrade
future builds to in-memory streaming -- so the fallback subprocess and
every later build write the cached fragments instead.

Co-Authored-By: Claude Fable 5 <[email protected]>
Round-11 review hardening (PR #99, Codex P2): after a daemon response the
requesting build's control kept referencing the shared process until the
build-level cleanup ran, so a supersession of that build in the assembly
window could terminate the daemon out from under a second flight already
using it, forcing that flight through one-shot fallback on a partially
consumed deadline. The request path now unregisters the daemon from the
control (identity-checked under the job-cache lock, mirroring
registration) the moment the round trip finishes, on every outcome path;
supersession keeps killing genuinely in-flight requests exactly as before.

Co-Authored-By: Claude Fable 5 <[email protected]>
…rget

Round-12 review hardening (PR #99, Codex P2): a pre-retarget build delayed
after its snapshot could install an equal-count artifact at the old
network difficulty over the one already serving the retargeted template;
the reuse fence then rejected it for every new-difficulty build, forcing
another full ledger snapshot. Equal-count installs whose difficulties
differ now defer to the live template difficulty: the artifact that the
current template can actually reuse is kept, and a delayed stale-
difficulty snapshot is dropped. Count ordering and the same-window skip
are unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>
Round-13 review hardening (PR #99, Codex P2): a payout-state candidate's
artifact installs through the atomic publication pointer swap rather than
_install_payout_ledger_artifact, so a backoff accumulated under sustained
pre-publication traffic survived the publication -- and when an accepted
preview also skipped the post-publication scheduling, a share landing
right after the new generation stayed suppressed for the whole scaled
interval instead of the configured floor. Every successful publication now
resets the backoff.

Co-Authored-By: Claude Fable 5 <[email protected]>
Round-14 review hardening (PR #99, Cursor medium + Codex P2):

- The same-window install skip returned before the backoff release, so a
  debounced rebuild that completed a valid fenced read against an
  already-current artifact left the re-arm interval scaled up to 16x. The
  no-op install now keeps the artifact generation (no lookup re-key) while
  still releasing the backoff like any other successful preparation.

- Daemon spawns only incremented worker starts, so a respawn after a
  crash or a supersession kill either never surfaced as a restart or was
  later misattributed to an unrelated one-shot build that consumed the
  pending flag. The daemon spawn path now claims the pending restart
  exactly like the one-shot spawn block, and the long-lived-worker restart
  metric counts these respawns (its help text no longer claims the value
  is zero by design).

Co-Authored-By: Claude Fable 5 <[email protected]>
Round-15 review hardening (PR #99, Codex P2): a persistent builder that
died between requests was silently retired and respawned, recording only
an ordinary start. The idle-death poll branch now records the crash and
marks the restart pending before retiring the client, so the immediate
respawn is attributed as a crash-and-restart in both the worker counts and
the long-lived-worker restart metric.

Co-Authored-By: Claude Fable 5 <[email protected]>
… the trusted memo

The blockpoll refresh serialized a full reconcile pass before every bundle
build (0.56s mean at ~750 connections, 0.94s at 2,000+), and it never
consulted the per-tip trusted memo that already absorbs per-client build
reconciles. Consult the memo on the poll path (the live chain-trust check
stays uncached and publication still re-proves trust before fanout), and on
a memo miss run the pass on a single-worker prefetch lane so it overlaps
the getblocktemplate fetch; the phase histogram now records the effective
serial cost (probe + residual join wait). A tip that moves between the
cheap probe and the template fetch discards the prefetched pass and
reconciles the snapshot tip serially, exactly as before.

New counter qbit_prism_reorg_reconcile_lookups_total{path,source} exposes
the memo hit rate for both the tip-refresh and per-client job-build lanes.
Existing metric names and the ensure_reorg_reconciled_for_tip contract
(always a real pass; lock-owner no-wait semantics from #96) are unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>
The outbox created_at->completed_at span (~16-22s on mainnet) conflates
post-submit audit and persistence bookkeeping with the race-critical
interval: candidate landed in this process -> submitblock RPC returned.
Stamp PrismBlockCandidate with a landed_monotonic (share-accept time for
live candidates, row-restore time for durable replays) and observe the
interval as a histogram for every attempt whose RPC returned, accepted or
rejected -- a rejected race is exactly the tail this metric exists to
expose, and the direct proof instrument for the #96 lock-cycle fix.

Co-Authored-By: Claude Fable 5 <[email protected]>
Round-16 review hardening (PR #99, Codex P2): the daemon start counter was
incremented only after a successful handshake, so a worker that exited or
announced the wrong protocol during the handshake was missing from the
lifecycle totals while its EOF could still record a crash -- fewer starts
than end states. The start (and any pending restart it satisfies) is now
recorded immediately after Popen, exactly like the one-shot spawn block.

Co-Authored-By: Claude Fable 5 <[email protected]>
Round-17 review hardening (PR #99, Codex P2): retiring a still-running
daemon for a timeout, malformed response, protocol mismatch, or spool
failure killed it without touching the termination counters, so the
replacement worker read as an ordinary start and the restart metrics
undercounted exactly the daemon failures the experiment measures. Every
deliberate-kill site (the fallback handlers and the handshake failure
paths) now records the termination and pending restart when the worker is
still alive, while crash paths keep counting themselves at EOF, so no
outcome is double-counted.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ce serializer

Block finalization held _payout_balance_mutation_lock from the pre-submit
triage through durable confirmation, with the audit-builder subprocess,
the coinbase fence, and bundle verification inside the hold. Job delivery
and the tip-refresh reconcile queue behind that lock (and behind the
landed-transition fence armed for the same window), which is the July
2026 healthz coverage-0 / null-delivery-age stall at block cadence.

Every input to the audit bundle is frozen on the candidate (share window,
prior balances, extranonces, template fields), so build it and verify it
speculatively before acquiring the serializer and adopt the results under
the lock. The serializer and landed fence now cover only the submit RPC,
preview publications, and the durable persist/confirm writes; the
verified preview also publishes sooner, unblocking next-tip child job
builds earlier. Speculation is strictly an optimization: any anomaly
falls back to the in-lock rebuild with today's exact fence and shutdown
semantics (submitblock always precedes any mismatch disposition), and
the cheap coinbase equality fence still runs under the lock either way.
The #96 lock-owner no-wait reconcile discipline is untouched.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ialization

Two whale-scale fanout changes:

qbit_prism_tip_refresh_fanout_wave_seconds records the wall-clock span of
one completed prepared wave (first task submission to last successful
delivery). The existing first/last_delivery histograms anchor at refresh
start and so conflate reconcile and bundle-build time with the wave
itself, which at thousands of connections is the dominant staleness term
bounded by the delivery worker pool.

mining.notify serialization was one json.dumps per client per wave, with
coinb1/coinb2/merkle_branch byte-identical across every client of a
bundle (~2,800 identical serializations per wave at current scale). The
base job now carries the seven shared params serialized once at build
time; send_job_update splices the per-client job id and clean_jobs flag
around the fragment and hands the exact bytes to a new preserialized
send_batch fast path. Byte equality with full serialization is pinned by
test; monkeypatched-send test seams and hand-built jobs (fragment None)
fall back to the existing per-payload path.

The 16-worker cap and PRISM_TIP_REFRESH_MAX_WORKERS guard are unchanged:
with serialization off the per-send cost, wave duration is send/socket
bound, and raising the cap belongs with descriptor-pressure analysis
against the wave metric this change introduces.

Co-Authored-By: Claude Fable 5 <[email protected]>
Round-18 review hardening (PR #99, Codex P1): share stamping/registration
and single-writer enqueue happen on different client threads, so a
later-stamped share can become durable while an earlier-stamped one still
holds the anchor floor. At that moment the global accepted count includes
a share every clamped-anchor window excludes, and both artifact producers
could bind that inclusive count to an exclusive window -- letting reuse
serve a payout window that omits a durable share until the next count
change. This falsifies the earlier assumption that FIFO commits make the
total count anchor-scoped whenever the bracket is clean.

Both producers now bind counts only when the clamp returns the raw now
value, which is precisely the pending-floor-empty case where every durable
share is provably at or below the anchor: the background builder aborts
before paying the window walk, and the per-generation anchor-count capture
retries for a drained floor instead of storing an unbindable count. The
floor drains within group-commit latency, so seeding stays effective at
normal rates and fails closed under churn.

Co-Authored-By: Claude Fable 5 <[email protected]>
…tip jobs

The whale ramp showed 0.28% unknown-job rejects (fleet baseline ~0):
devices behind a flapping proxy keep mining the jobs the dead connection
delivered, and their shares arrive on the replacement connection, which
could never see them -- disconnect purged the connection's job contexts
and graveyard entries, and graveyard lookups were connection-scoped.

Disconnect now buries the connection's active jobs and retains its
same-tip graveyard entries detached from the dead client object
(entry.client=None), so expiry anchors on the entry's own eviction time
(same-tip TTL) or the published tip flip -- never on delivery state a
dead connection cannot advance. An authorized reconnect of the same
username may submit against a detached entry; credit and dedup stay on
the retained context's original worker identity, so replays remain
duplicate-share and a foreign username still rejects unknown-job.
Stale-grace entries keep the historical purge (their expiry anchors on
the original connection's delivered work).

Bounds: the existing per-connection cap and same-tip TTL still apply,
plus a new global cap across dead connections
(PRISM_STRATUM_DISCONNECTED_JOB_RETENTION, default 16384; 0 restores
purge-on-disconnect). New capacity scope "disconnected" and submit
outcome "accepted_same_tip_cross_connection" extend the existing
evicted-job metric families.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ument

2,902 OS threads and share processing serialized through the GIL at
2,818 connections make read-to-ack latency the leading indicator for the
thread-per-connection ceiling, and nothing measured it: the earliest
submit-side timestamp was taken after parse, classification, hashing,
and dedup. Stamp request arrival in the handler loop before JSON parsing
and observe mining.submit read-to-response by outcome. Accepted shares
include the group-commit wait; rejects skip it, so the pair separates
commit pressure from thread-scheduling/GIL pressure as connection count
grows -- the measure-first instrument for any future share-ingest fast
path (batch parsing / fewer threads), which is deliberately out of scope
here.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread lab/prism/prism_coordinator.py Resolved

@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: b19e2ff19b

ℹ️ 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 lab/prism/prism_coordinator.py Resolved
Comment thread lab/prism/prism_coordinator.py Resolved
…nonce candidates

Both bots flagged that cross-connection block candidates recorded the
replacement client's extranonce1 while the mined coinbase embeds the
retained job's original value, which would fail the coinbase audit fence
after submitblock and shut the coordinator down. The candidate now
carries the job's stamped extranonce1 whenever the job has one (identical
to the client's on ordinary submits), pinned by a cross-connection
block-candidate test.

Codex also flagged that the speculative pre-lock audit build delayed
submitblock for freshly solved blocks by the whole build+verify duration
-- trading block-race odds for delivery liveness. Replaced the
speculation machinery with a simpler shape that keeps both properties:
submitblock runs first, exactly as before, and the audit build and
verification then execute inside release windows of the payout-balance
serializer (the landed fence stays armed, so reconciliation stays out
while job delivery proceeds and children consume the compact preview).
The submit-before-build ordering is now pinned by test, the
build-runs-unlocked test still passes against the release window, and
the temp-bundle cleanup semantics on verify failure are preserved by
keeping verification inside the payout-commit try.

Co-Authored-By: Claude Fable 5 <[email protected]>

@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: 0d1964ae3a

ℹ️ 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 lab/prism/prism_coordinator.py Resolved
Comment thread lab/prism/prism_coordinator.py Resolved
Comment thread lab/prism/prism_coordinator.py Resolved
…rvation

Both bots flagged that cross-connection resumes validated version-rolled
submissions against the replacement connection's mask (0 until
mining.configure), rejecting in-flight version-rolling work as malformed
or judging it against the wrong mask. Job contexts now stamp the
delivering connection's negotiated mask, and cross-connection submits
assemble against the retained context's mask; same-connection submits
keep using the client's live mask exactly as before.

Codex also flagged the share-ack asymmetry: rejects were observed before
their error response write while accepts were observed after
send_result, so transport backpressure skewed only one side of the
comparison. The rejected observation now happens in the handler loop
after send_error, and the ack test drives the real handle_client loop
over a socketpair to pin both outcomes at their response boundaries.

Co-Authored-By: Claude Fable 5 <[email protected]>

@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: b88eb582b4

ℹ️ 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 lab/prism/prism_coordinator.py Resolved
Comment thread lab/prism/prism_coordinator.py Resolved
Comment thread lab/prism/prism_coordinator.py Resolved
…e-tip-only detached credit

Cursor flagged that the refresh join trusted its pre-fetch memo probe: a
tip that flips away and back during the template fetch evicts the memo
entry precisely so post-flip pool-block state is re-proven, yet the join
skipped the pass. The join now decides against state at join time: the
memo is re-consulted there, and an overlapped pass is honored only when
the tip-detection epoch (a counter bumped exactly where detections evict
cached proofs) did not advance across the fetch; otherwise the poll
re-proves serially. The prefetch machinery is also gated on a positive
memo TTL, since without the memo there is no way to validate an
overlapped pass across the fetch window.

Codex flagged that a refresh dying before its join (template-RPC outage)
left its prefetch unconsumed, so retries could queue unbounded
serialized passes on the single worker. The prefetch is now a one-slot
resource: same-tip retries reuse the outstanding future, a replaced tip
cancels the queued task (disposal happens outside the slot lock --
cancellation runs done callbacks inline), and the prefetched pass itself
honors the memo so a stale queued task no-ops.

Cursor also flagged that a tip moving between the graveyard lookup and
submit classification let a detached cross-connection entry fall through
to stale-grace credit anchored on the reconnect's own window;
cross-connection classification is now same-tip only (same-connection
legacy entries keep the historical stale-grace path).

Co-Authored-By: Claude Fable 5 <[email protected]>

@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: d952e6fd05

ℹ️ 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 lab/prism/prism_coordinator.py Resolved
Codex flagged that the join's memo branch accepted entries re-armed by a
pass whose execution straddled a flip away and back: the flip-back makes
the latest detected hash match again, so _note_reorg_reconcile_outcome
re-arms the entry even though its proof belongs to the closed epoch. The
memo branch now also requires the tip-detection epoch to be unchanged
across the fetch window; any epoch movement lands in the serial re-prove
branches. Pinned by
test_poll_reproves_when_memo_rearmed_across_detection_epoch.

Co-Authored-By: Claude Fable 5 <[email protected]>

@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 2 potential issues.

Fix All in Cursor

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

Reviewed by Cursor Bugbot for commit e95c352. Configure here.

Comment thread lab/prism/prism_coordinator.py Resolved
Comment thread compose.yaml Resolved

@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: e95c352095

ℹ️ 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 lab/prism/prism_coordinator.py Resolved
RobertClarke and others added 2 commits July 26, 2026 16:17
Codex flagged that the join-side epoch gate could not protect the other
memo consumers (initial-job and vardiff-idle builds reach the memo via
ensure_reorg_reconciled_for_current_tip) nor a later refresh whose
baseline epoch postdates a bad re-arm. The structural fix moves the
guard into arming itself: each reconcile attempt captures the
tip-detection epoch its reads happen in, and
_note_reorg_reconcile_outcome refuses to arm when the epoch moved during
the pass -- a flip away and back can never re-arm an entry with a proof
from the closed epoch, for any consumer. Pinned by
test_pass_spanning_detection_cycle_does_not_arm_memo.

Cursor's overlap-join trust-flip finding is addressed by documentation
plus a regression test rather than a second live check: prepared fanout
re-proves the live chain view in _validate_prepared_tip_refresh and
sequential issuance re-proves it per client in
ensure_reorg_reconciled_for_current_tip (whose trust check is never
cached), so the overlap window is already backstopped on both paths and
an extra join-time check would break the one-trust-validation-per-
refresh economy several tests pin.
test_overlap_join_blocks_when_trust_flips_after_prefetch pins the
backstop. Cursor's compose.yaml indentation finding did not reproduce:
the file parses and the variable sits inside the prism-coordinator
service environment.

Co-Authored-By: Claude Fable 5 <[email protected]>
This branch already carries the #99 content (based on prism-cache-persist
at b289550, the exact head that squash-merged) plus the earlier #98
merge, so the 'ours' tree is the correct union by construction; the
merge only records ancestry and collapses the PR diff to this branch's
own changes.

Co-Authored-By: Claude Fable 5 <[email protected]>
@RobertClarke
RobertClarke merged commit 59a3d9d into 1.x.x Jul 29, 2026
10 checks passed
djh58 added a commit that referenced this pull request Jul 29, 2026
Keep-both resolutions: PrismJobContext gains both the epoch sequence
stamp from this branch and the retained version-rolling mask from
#100, at the dataclass and its construction site; .env.example keeps
both new entries.

Co-Authored-By: Claude Fable 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