Skip to content

Avoid reconcile singleflight under the accepted-block payout lock - #96

Merged
RobertClarke merged 2 commits into
1.x.xfrom
fix-reconcile-lock-cycle
Jul 26, 2026
Merged

RobertClarke merged 2 commits into
1.x.xfrom
fix-reconcile-lock-cycle

Conversation

@Anatolie

@Anatolie Anatolie commented Jul 26, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Add an internal same-tip coalescing opt-out to ensure_reorg_reconciled_for_tip.
  • Use that opt-out for both reconciliation calls made by the accepted-block path while it owns the payout-balance mutation lock.
  • Keep the bypass on the existing serialized reconciliation entry point so ledger-writer admission and shutdown accounting remain intact.
  • Add deterministic concurrency coverage for the lock cycle and retain coverage for ordinary same-tip coalescing plus forced and reserved bypasses.

Root cause

PR #95 introduced bounded same-tip reconciliation singleflight. An unflagged caller joins an existing flight and waits up to 30 seconds for its event.

The accepted-block path calls ensure_reorg_reconciled_for_tip while holding the re-entrant payout-balance mutation lock. If another thread has already registered the same-tip flight and is blocked acquiring that lock, the accepted-block thread can join the flight while still owning the lock. The leader then waits for the lock while the lock owner waits for the leader event. The follower timeout eventually breaks the cycle, but the delay happens before submitblock and can lose an otherwise valid block.

Fix

ensure_reorg_reconciled_for_tip now accepts the private _coalesce_same_tip keyword, defaulting to true. Ordinary tip refresh and job build callers therefore retain existing singleflight behavior.

Both lock-owning calls in _land_and_confirm_block_candidate pass _coalesce_same_tip=false. That path invokes _reconcile_prism_pool_blocks_serialized directly, re-entering the lock without consulting the same-tip flight registry.

The serialized method remains decorated with ledger_writer_operation for payout_reconciliation. Reconciliation logic, payout publication, memo invalidation, supersession handling, and retry behavior are otherwise unchanged. Existing tipless, forced-publication, and reserved-source bypass behavior is untouched.

Regression test

The new concurrency test:

  1. Has one thread register a same-tip flight.
  2. Confirms that thread fails a nonblocking acquisition of the payout-balance mutation lock and then blocks on it.
  3. Replaces the flight event with a sentinel that raises if wait is called.
  4. Requests reconciliation from the lock-owning thread with coalescing disabled and verifies the serialized pass completes re-entrantly without touching the flight wait.
  5. Releases the lock, verifies the original leader completes, and checks that the flight registry drains.

This synchronization is event-driven and does not infer correctness from elapsed wall-clock time.

Validation

  • python3 -m unittest tests.test_prism_coordinator_vardiff — 302 passed
  • python3 -m unittest tests.test_prism_coordinator_job_cache — 111 passed
  • python3 -m unittest discover -s tests -p test_*.py — 1,292 passed
  • git diff --check — passed

Security and operational impact

No schema, dependency, configuration, authentication, authorization, secrets-handling, or external API behavior changes.

Operationally, accepted-block reconciliation no longer incurs the bounded flight timeout while holding the payout serializer, removing an approximately 30-second pre-submitblock delay and its valid-block-loss risk. In the exact contention case, the accepted-block bypass and the already-registered leader may each perform a serialized pass, but they cannot form the lock cycle and ordinary callers continue to coalesce.


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


Note

Medium Risk
Changes concurrency around payout reconciliation and the accepted-block submit path; logic is narrow but contention timing and duplicate serialized passes in edge cases need careful review.

Overview
Fixes a deadlock between same-tip reconciliation singleflight and the accepted-block path holding _payout_balance_mutation_lock: a lock owner could join an in-flight reconcile whose leader was blocked on that lock, causing up to ~30s delay before submitblock.

ensure_reorg_reconciled_for_tip gains _coalesce_same_tip (default true). When false, reconciliation goes through reconcile_prism_pool_blocks_once with _wait_for_same_tip_flight=False, so it runs a serialized pass without waiting on an existing same-tip flight while still registering as leader when none exists.

reconcile_prism_pool_blocks_once adds _wait_for_same_tip_flight; followers with it disabled skip the flight wait and call _reconcile_prism_pool_blocks_serialized directly (re-entrant on the RLock).

Both _land_and_confirm_block_candidate reconciliation calls pass _coalesce_same_tip=False. Ordinary tip refresh/job callers keep existing coalescing. Tests cover lock-cycle bypass, lock-owner as visible flight leader, and stub lambdas updated for the new keyword.

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

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

ℹ️ 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
RobertClarke merged commit d1be1d3 into 1.x.x Jul 26, 2026
9 checks passed
RobertClarke added a commit that referenced this pull request Jul 29, 2026
… whale ramp (#100)

* Re-arm PRISM payout-ledger-artifact reuse between payout events

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

* Feed the audit builder's share window from a per-generation spool file

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

* Add a persistent --serve mode to the PRISM audit builder

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

* Fence artifact seeding to the frozen anchor and gate the fallback identity

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

* Share one build deadline across transports and steady same-window installs

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

* Key same-window artifact dedup on difficulty and unblock metrics scrapes

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

* Loan the cached serve window to builds and make the re-arm debounce atomic

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

* Retry the anchor-count bracket and true up serve accounting

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

* Promote daemon cache hits in the coordinator's uploaded-window mirror

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

* Sample serve input deserialization at the parse boundary

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

* Order artifact installs by snapshot count instead of completion time

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

* Back off the artifact re-arm while continuous writes abort rebuilds

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

* Poison the spool on mid-stream splice failures across both transports

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

* Detach the daemon from a build control once its request completes

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

* Keep the live-difficulty artifact when equal counts tie across a retarget

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

* Release the re-arm backoff on every payout-state publication

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

* Treat same-window installs as successes and count daemon respawns

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

* Count idle daemon deaths as crashes before respawning

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

* Overlap tip-refresh reorg reconcile with the template fetch and honor 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]>

* Add qbit_prism_block_submit_seconds around the outbox submitblock call

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

* Record daemon starts at spawn rather than after the handshake

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

* Record live-daemon retirements as terminations before falling back

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

* Build and verify the accepted-block audit bundle off the payout-balance 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]>

* Time the tip-refresh fanout wave and precompose the shared notify serialization

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

* Bind artifact counts only while the pending-commit floor is drained

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

* Let same-username reconnects resume against a dead connection's same-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]>

* Add qbit_prism_share_ack_seconds as the share-ingest saturation instrument

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

* Address round-1 review: submit-first audit windows and retained-extranonce 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]>

* Address round-2 review: retained version masks and symmetric ack observation

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

* Address round-3 review: epoch-validated joins, one-slot prefetch, same-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]>

* Address round-4 review: epoch-gate memo hits at the refresh join

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

* Address round-5 review: bind memo arming to its detection epoch

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

---------

Co-authored-by: RobertClarke <[email protected]>
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.

2 participants