Repository navigation
Make PRISM payout-artifact builds incremental and debounced (1.x.x) - #112
Conversation
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7bdaed65e8
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d31396a2f4
ℹ️ 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".
The idle-sweep cache-miss fixture's SimpleNamespace build key predates the payout_append_invalidation_epoch field, so _cache_job_bundle_if_current raised AttributeError on the bounded worker and no retarget was delivered. Mirror the real build key by stamping the coordinator's live epoch. Co-Authored-By: Claude Fable 5 <[email protected]>
A late-visible replay append committing while a cold-start or forced full rescan walks the ledger found no cached window or armed artifact anchor, so no invalidation epoch was recorded and the in-flight walk -- whose database snapshot could predate the commit -- installed a window that delta reads can never re-discover the row from. Publish the walk's anchor under _job_cache_lock before each ledger window read (the materialization path and the synchronous bundle-build read) and include it in the append-side predates() checks, re-reading the cached window pointer under the same lock so a completing walk always exposes its anchor. Normal submissions stay floor-protected above any in-flight anchor, so cold-start share traffic cannot starve the first arming. Co-Authored-By: Claude Fable 5 <[email protected]>
A balance drift detected during an ordinary background build alarmed and blocked byte reuse of the refuted digest, but the published payout-state artifact kept its pre-mutation balances for the rest of the generation: the armed-artifact fence cleared every fresh-balance artifact against the stale published digest and the synchronous fallback kept serving the published bytes, so the advertised backstop could never actually repair. Publish the oracle's fresh balances as a repaired artifact for the same generation under a guarded swap that only replaces the exact refuted snapshot. New work re-keys to the corrected digest, the mismatch build's artifact can arm and serve, and work keyed to the refuted digest is superseded by the existing balance fences exactly as on a generation change. Co-Authored-By: Claude Fable 5 <[email protected]>
_deliver_initial_bundle checked the bundle's append invalidation epoch once before waiting on the per-client Vardiff lock, and neither its payout-gate cancellation nor the stamp itself re-read the live epoch. A late-visible append bumping the epoch during that wait let a pre-append ready bundle become the miner's active job. Mirror direct delivery on both boundaries: cancel the payout-gate wait when the bundle's generation or epoch goes stale, and make the live epoch re-read and the stamp one commit boundary under _job_cache_lock after the Vardiff lock is held. Co-Authored-By: Claude Fable 5 <[email protected]>
_deliver_initial_bundle's staleness check compared only the payout generation and append invalidation epoch. A periodic self-check repair replaces the published balance snapshot in place -- neither fence moves -- so a ready bundle probed before the repair could pass the payout gate and the post-Vardiff commit boundary and become the miner's active job carrying the refuted balances. Mirror every other serving decision (cache usability, idle issuance, cache publication): treat a missing build key or a build-key digest that no longer matches the published artifact as stale, at the gate hint and at both commit-boundary re-reads. Co-Authored-By: Claude Fable 5 <[email protected]>
The cold ready-bundle build cleared its in-flight scan anchor as soon as snapshot_at_job_issue returned, but nothing else exposes that window's anchor until the seeded artifact passes the install fence: manifest construction, cache publication, and the flight handoff all run in between. A replay-shaped append committing in that gap advanced no epoch, so the publication and install fences accepted a snapshot that omitted the row and both stamps sat below the seeded anchor -- delta reads could never rediscover the share until the periodic full rescan. Replace the single in-flight anchor slot with a token registry so exposures can overlap and outlive one lock scope. The oracle walk retires its entry as before (its incremental pointer is visible first); the synchronous build's entry now rides the seeded artifact and is retired by the install fence, by the bundle publication fence when no seed is created, or by the executor wrapper when the build dies. Entries older than the audit ceiling prune lazily: the install fence rejects anchors past that same ceiling as born-expired, so an exposure leaked by an abandoned bundle cannot outlive the last install that could have used it. Co-Authored-By: Claude Fable 5 <[email protected]>
The periodic self-check's repair publication swaps the refuted balance snapshot in place: the payout generation and append-invalidation epoch both survive, and those are the only fences current-job and submission admission apply. Jobs already stamped for miners therefore kept mining the refuted balances -- an accepted block would commit the stale allocation -- and no refresh wave was scheduled to replace them; wave reselection compared only the payout generation, so even a later wave left them untouched. Stamp each job with the published balance digest its payouts were keyed to, reselect active jobs whose stamped digest no longer matches the published artifact, and schedule the same refresh wave a payout publication schedules whenever the repair swap wins. Newly issued work already re-keys through the existing digest fences. Co-Authored-By: Claude Fable 5 <[email protected]>
d09b8cc to
7129d8d
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7129d8d52e
ℹ️ 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".
A refresh wave selected by the balance-digest fence stamped its replacement with clean_jobs from client_tip_changed_for_snapshot, which compared only the tip and payout generation -- both unchanged by an in-place self-check repair. The refuted job ID therefore stayed in active_job_ids, and a late block submission on it could still commit the refuted allocation after corrected work was delivered. The clean-jobs predicate now treats a published balance digest mismatch as requiring clean-job retirement, with the same None guards as the reselection predicate. Co-Authored-By: Claude Fable 5 <[email protected]>
A late-visible append advanced the append invalidation epoch and disarmed payout artifacts, but active jobs stamped against the pre-append window were never superseded: the reselection and clean-jobs predicates compared only the tip, generation, and balance digest -- all unchanged by the append -- and the invalidation hook never scheduled a refresh wave. Miners could keep working (and solve a block from) a window that omitted the late share, possibly a replayed winning share, until some unrelated tip event. Both predicates now treat append-epoch skew as requiring refresh and clean-job retirement (collection jobs exempt, as at every other epoch fence), and the invalidation hook schedules the same refresh wave a repair publication schedules, before the prepare-lock wait so a long oracle build cannot delay it. Co-Authored-By: Claude Fable 5 <[email protected]>
_maybe_send_job_locked admitted a freshly built context by comparing only the payout generation and append invalidation epoch, and its non-prepared commit path re-read only the epoch. A periodic self-check repair swaps the published balance snapshot in place -- neither fence moves -- so a routine or Vardiff direct delivery whose build finished just before the swap could still send a job keyed to the refuted balances, and a block solved from it would commit the stale allocation. Capture the context's stamped digest, treat a mismatch with the published artifact as stale at the gate hint, and re-read it under _job_cache_lock at the commit boundary, as initial delivery already does. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1989f1b603
ℹ️ 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".
The periodic self-check ran the share-window oracle and the carry-balance backstop inside one try block. Once the oracle had materialized the full window -- possibly refuting the delta window with matched == False -- a failure in the independent current_prior_balances() read still discarded that result: the except restored the pre-oracle delta window and stamped the attempt, so the coordinator kept serving the refuted window for a full rescan interval (3600s by default), during which a settlement could omit or misweight shares. Split the failure domains: adopt the full window as soon as it materializes, then run the balance backstop in its own try. A failed backstop keeps the oracle's window, records periodic_self_check_balance_check_failed as the rescan reason, and leaves the reused balances unverified until the next self-check. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ce7b606737
ℹ️ 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".
A late-visible replay append advances the append-invalidation epoch and schedules the tip-refresh wave, but that wave retires the pre-append job asynchronously. Until it lands, submission admission still accepts the job by active membership, and the landing checked the tip, height, and prior-balance content -- all of which survive an append invalidation -- so a miner solving a block during the multi-second rescan/refresh window could land a coinbase whose payout window omitted the replayed share. Landing now fails closed: before submitblock, a candidate whose context epoch differs from the live epoch is abandoned under the new append_epoch_stale class, mirroring the balance_stale fence (the credited share survives; only the block candidate is abandoned, and the chain probes still protect an already-accepted block). Collection candidates settle solver-pays-all and are exempt, as at every other epoch fence. Candidates reconstructed from durable intent carry a negative sentinel stamp: epochs are process-local, so cross-restart drift stays governed by the content-based prior-balance fence instead of a meaningless epoch comparison. Regression tests: test_block_submit_rejects_job_after_late_append_epoch_invalidation, test_replayed_block_candidate_is_exempt_from_append_epoch_fence. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c1aa516562
ℹ️ 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".
A candidate reconstructed from durable intent carries the negative epoch sentinel, which stands the landing append-epoch fence down -- epochs are process-local, so the stamp is meaningless after a restart. But the hazard that fence guards against survives the restart: a share append that became durably visible after the recorded window walk leaves the tip, height, and carry balances untouched, so the prior-balance backstop cannot see it, and a replayed candidate could land a coinbase omitting the appended share (the same held for a same-process outbox reconstruction once the in-memory queue drained). Landing now revalidates reconstructed candidates instead of trusting the sentinel: the reward-window contract keeps the share window replayable at the artifact's declared anchor, so the fence replays the durable audit window at the intent's recorded anchor and fails closed under append_epoch_stale when the replay surfaces a share the recorded window omitted. Only omissions abandon the candidate -- share rows are append-only, and drift from settled payout state stays governed by the reorg and prior-balance fences. A failed replay read defers the candidate for retry rather than abandoning it terminally, and the fence engages only on durable-payout-state backends, matching the prior-balance fence's gating. Regression tests: test_replayed_block_candidate_rejects_window_omitting_durable_append, test_replayed_block_candidate_lands_when_durable_window_replays_intact. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1d812924fe
ℹ️ 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".
…alizer Two interlocked holes in the landing append fence. The epoch fence read the live epoch once and released _job_cache_lock, so an append-side invalidation could advance the epoch between that read and submitblock and the candidate still landed a coinbase omitting the newly visible share. And the reconstructed-candidate revalidation ran the audit share-window replay -- the slow oracle walk, which takes the ledger writer lock -- while holding _payout_balance_mutation_lock, stalling share persistence and every other landing for the walk's duration during outbox replay. The revalidation now runs in the submit path before the balance serializer is taken. That is safe because the window is append-only content: a pass can only be invalidated by a later append, and the revalidation captures a baseline epoch under _job_cache_lock before the read, rebasing the reconstructed candidate onto the live epoch sequence so both candidate kinds share one epoch fence from there. The fence itself becomes authoritative at the submitblock boundary: a new landing fence lock is held across the final epoch comparison and the submitblock RPC, and the append-side bump acquires the same lock, so an invalidation now lands either before the comparison (candidate abandoned under append_epoch_stale) or after the RPC returns (the refresh wave retires the job) -- never in between. Ordinary share commits never touch the lock: an unfenced peek keeps the fast path lock-free and only a row predating a live anchor re-checks and bumps under it. The landing also exposes its own declared anchor for its duration, so a replay-shaped append still bumps the epoch when no armed artifact or in-flight walk would otherwise predate it (an outbox replay at startup). Regression tests: test_block_submit_aborts_when_append_invalidation_races_the_landing, test_replayed_candidate_aborts_when_append_races_after_revalidation. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5f0a6f1e97
ℹ️ 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".
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 5f0a6f1. Configure here.
…h bump The landing fence serialized only the append-side epoch bump against the landing's epoch-check-and-submitblock boundary; the durable append itself committed before the bump ever acquired the fence. For a replay-shaped late append that left a gap: the group-commit writer's append_batch() returns with the row durable, a landing acquires the fence, verifies the still-unbumped epoch, and enters submitblock -- landing a coinbase whose payout window omits a share that was already durable before the block entered qbitd. The refresh wave the bump later schedules cannot unsubmit it. The durable append and its epoch advance now share the landing fence boundary. The batch writer peeks unfenced before committing; a batch holding a row that predates a live anchor takes the fence BEFORE the ledger commit and holds it through the bump, so a landing either observes the advanced epoch (candidate abandoned as append_epoch_stale) or holds the fence first, in which case the row is not yet durable when the block enters qbitd and the post-release bump retires the job via the ordinary refresh wave. Ordinary share commits never touch the lock: the pre-commit peek fires only for replay-shaped rows. The post-bump window retirement (refresh scheduling and the prepare-lock cache disarm) stays outside the fence so a long oracle build cannot block landings through it. The invalidation helper is split so both shapes share one implementation: a locked predicate, a fence-aware epoch bump, and an out-of-fence window retirement; the existing post-commit helper keeps its behavior for callers that do not commit under the fence. Reported by codex review on PR #112 (thread on the two-phase bump). Regression tests: test_replay_shaped_batch_commits_under_the_landing_fence, test_landing_blocked_by_fenced_append_aborts_on_bumped_epoch. Co-Authored-By: Claude Fable 5 <[email protected]>
…ence The landing holds the append landing fence across submitblock so no epoch bump can slip between its final epoch read and the block entering qbitd. But a predating append that had already committed its row durably before reaching the fence turned that hold against the check: the bump queued behind the RPC, the authoritative comparison could not observe the invalidation, and the underpaying coinbase entered qbitd with the late-visible share already durable -- a state the later refresh wave cannot unsubmit. The batch writer already commits predating rows under the fence; this extends the same boundary to the two remaining durable-append paths, so holding the fence across the RPC now provably excludes the commit itself, not just the bump: - _append_share_entry (synchronous/no-writer path) wraps one commit attempt plus its epoch bump in the fence; the retry backoff sleeps outside it so a ledger outage never blocks a landing. - replay_recovered_shares commits each recovered row under the fence with its bump. Recovered rows reconstruct pre-crash timestamps, so they are exactly the replay-shaped appends the fence exists for; the per-row window retirement still runs after the fence releases. With every durable-append path fenced, a predating row is either durable with its epoch advanced before the landing's authoritative check (abort as append_epoch_stale), or not yet durable until the RPC returns (the post-release bump retires the job through the refresh wave). Reported by cursor bugbot on PR #112 ("Fence defers underpay abort"). Regression tests: test_predating_append_stays_undurable_while_landing_holds_submit_fence, test_replay_recovered_shares_commit_under_the_landing_fence, test_sync_append_commits_predating_row_under_the_landing_fence. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6ba8c77c9a
ℹ️ 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".
The unfenced classification in _landing_fence_for_predating_append is a one-time predicate: an append checked while no artifact, incremental window, or scan anchor is exposed (most directly the documented PRISM_PAYOUT_ARTIFACT_REUSE=0 rollback mode) commits outside the landing fence. A landing could then expose its declared anchor and acquire the submit fence before that commit finished: the row became durable during submitblock while its post-commit epoch bump queued behind the very fence the landing held across the RPC, arriving too late to reject a coinbase that omits the now-durable predating share. Serialize that transition instead of re-deciding it: an unfenced batch now registers itself -- atomically with the classification, under _job_cache_lock -- in a registry keyed by the batch's most predating row stamp (min over rows of max(job_issued_at_ms, accepted_at_ms)), and deregisters only after its commit and post-commit bump attempt ran. A landing drains matching entries right after exposing its declared anchor, before any window revalidation or epoch fence runs: - Each drained append finished its bump attempt against the now-exposed anchor, so a predating row advanced the epoch the landing's fences check and the candidate abandons as append_epoch_stale. - Any append classified after the exposure sees the anchor, so a predating row takes the fence itself and serializes with the landing. - The landing holds no fence while draining, so the bump can always proceed; the wait is bounded by one ledger commit, and appends whose rows cannot predate the anchor never block it. Reported by chatgpt-codex-connector on PR #112 ("Recheck anchors before committing an unfenced append"). Regression test: test_landing_drains_unfenced_inflight_append_before_epoch_fences. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bf00027703
ℹ️ 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".
A ready build that seeds no payout artifact (most directly the documented PRISM_PAYOUT_ARTIFACT_REUSE=0 rollback mode, or a build with nothing to seed) retired its walk exposure at the bundle publication fence, leaving no live anchor for the window its jobs keep serving. A replay-shaped append that started AND finished in the gap between that publication and a landing's own anchor exposure then saw no artifact, no cached window, and no in-flight walk: it classified as unfenced, committed, found nothing to bump against, and its registry entry was popped on completion. The later landing drained an empty registry, its nonnegative context epoch skipped durable-window revalidation, and submitblock accepted a coinbase omitting the already-durable share. Close the gap on the append side rather than by retaining registry entries: the publication fence now hands the bundle's declared anchor to a monotonic published-window watermark under the same _job_cache_lock hold that retires the walk exposure, and _pending_share_predates_live_anchor_locked checks that watermark with the other live anchors. A replay-shaped append committing after publication therefore always predates a live anchor: it takes the landing fence, commits with its epoch bump, and the landing's epoch fences reject the pre-append window (append_epoch_stale) no matter how long ago the append completed -- the registry keeps its commit-scoped lifetime. Ordinary share commits stay off the fence because every job anchor is clamped below the pending-commit floor, so no stamp they carry can predate the watermark. Reported by chatgpt-codex-connector on PR #112 ("Preserve completed unfenced appends until active jobs retire"). Regression test: test_completed_append_predating_seedless_published_window_fences. Co-Authored-By: Claude Fable 5 <[email protected]>
Accepted-block previews build with bypass_build_interval=True, refresh the incremental window's refreshed_monotonic on every block, and never run the periodic full oracle themselves. When blocks arrive faster than the minimum build interval, every routine build then returned from the debounce branch before reaching the self-check condition -- so the configured PRISM_PAYOUT_ARTIFACT_FULL_RESCAN_SECONDS window comparison and the reused-balance oracle could be postponed for as long as the cadence held, leaving incremental or reused-balance drift undetected. Evaluate the self-check deadline before the debounce and let an overdue check disarm the debounce for routine builds: the next routine build folds the delta and runs the full-window (and balance) oracle instead of debouncing, restoring the configured cadence without adding oracle work to the urgent preview path, which stays debounce-free and oracle-free exactly as before. Failed attempts still advance full_rescan_attempt_monotonic, so a saturated database keeps its self-check spacing rather than retrying the oracle on every routine build. Reported by chatgpt-codex-connector on PR #112 ("Keep overdue self-checks eligible after bypass builds"). Regression test: test_routine_build_runs_overdue_self_check_despite_preview_refresh. Co-Authored-By: Claude Fable 5 <[email protected]>
…iation Issue #224: a reconcile pass that matured payouts, marked a pool block inactive, or reactivated one answered with force_full_window_rescan, so the accepted-preview landing paid an O(window) oracle read under the writer lock for a window that had not changed. Reconciliation mutates pool-block, payout and carry state but never qbit_share_ledger (the invariant recorded in accepted_preview_telemetry), so at a fixed anchor the accepted-share window stays exact and only the prior balances need a live read. Core fix (Option A): - Add a distinct force_prior_balances_read intent through _prepared_payout_state_candidate and _build_payout_ledger_artifact. It disables published-balance reuse and reads the carry aggregate live while the window goes through the normal debounce/delta path. It is never a full rescan and never records one. - The reconciler's confirmed-mutation path now requests that reread (ReorgReconcilerService._candidate_intent); the intent keyword is only forwarded when set so pre-existing preparation and build seams keep their exact signatures. - force_full_window_rescan keeps its whole meaning everywhere else: cold and cache invalidation, late-visible append, anchor/weight regression, daemon and incremental fallbacks, the periodic oracle, accepted-preview withdrawal, and the error-after-possible-commit path, which still republishes against a forced full rescan (and therefore fresh balances). Attribution (fixed telemetry contract only): - ReorgPorts gains an optional accepted_preview_telemetry owner; the coordinator wires ensure_accepted_preview_telemetry(self). Ports without one get a private owner. - reconcile records qbit_prism_reorg_reconcile_pass_seconds{caller} on every exit and the step family (admission_wait, watch_query, chain_probe, mutations, candidate_prepare, publish) around the calls themselves. - Callers are stamped per thread by the entry points -- landing (the flight-bypassing ensure_tip), post_confirm (forced publication), job_build (ensure_current), tip_refresh (the prefetch lane) and other -- so the reconcile_with_admission / reconcile_serialized / ensure_tip seams keep their kwargs. Optional _caller keywords are accepted by the coordinator entry points for explicit attribution. - payout_state records qbit_prism_payout_window_full_rescan_seconds {reason,path} only where the whole-window oracle actually runs: the full materialization (daemon vs in_process by which pipeline folded) and the periodic self-check. Tests: tests/test_prism_issue_224_core.py covers the intent split, the fail-closed paths, pass/step/caller observations on success and failure exits, rescan reason/path recording, seam compatibility, and the end-to-end coordinator path (maturation reuses the window, rereads and publishes fresh balances, records no reconcile_invalidation rescan). The two reconciler assertions that pinned the #112 forced rescan on the confirmed-mutation path now assert the reread intent. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01MgytztiBedDJPHGxnWnAqg
…cadence (#230) * Freeze the accepted-preview latency attribution contract Issue #224, Wave 0. Union mainnet's accepted-preview publication tail crosses the 4 s warning and 5 s child wait budget without anything on /metrics naming the landing stretch that owns a sample. Three lanes will instrument the core landing path, landing attribution and ledger attribution in parallel; this commit is the shared surface they record into, behavior-neutral and mergeable on its own. lab/prism/accepted_preview_telemetry.py freezes the closed vocabularies (landing sub-phases; reconcile callers and steps, spelled to join the existing lookup family; payout-window full-rescan reasons mirrored from payout_state's literals plus an ``other`` fold, and the daemon versus in-process pipeline path; the ledger read operation names), a thread-safe sum/count/max owner with context-manager timers, a bounded per-publication diagnostic record and ring where a hash or height may appear, ``fold_ledger_read_stats`` for the existing operation label, and ``ensure_accepted_preview_telemetry`` so every lane and the renderer share one owner per coordinator without touching prism_coordinator.py. The module docstring records the verified invariant: reconciliation mutates pool-block and payout balance state but never qbit_share_ledger, which the later reread-instead-of-rescan optimization relies on and this wave does not implement. The renderer appends four summary families -- landing phase, reconcile pass, reconcile step, payout-window full rescan -- from an empty owner, so every cell renders at zero from process start, and folds out-of- contract ledger read operations into ``other``. Every pre-existing line of the metrics document is unchanged: the base render is an exact prefix of the new one. The frozen reference, parity seed and needles cover the new families and the fold; a direct test module pins the vocabularies, parses payout_state for reason drift, and checks the recorder, ring, owner sharing and rendered labels. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01GFRhW6iq62pKU8pGZSJskw * Reread prior balances instead of rescanning the window after reconciliation Issue #224: a reconcile pass that matured payouts, marked a pool block inactive, or reactivated one answered with force_full_window_rescan, so the accepted-preview landing paid an O(window) oracle read under the writer lock for a window that had not changed. Reconciliation mutates pool-block, payout and carry state but never qbit_share_ledger (the invariant recorded in accepted_preview_telemetry), so at a fixed anchor the accepted-share window stays exact and only the prior balances need a live read. Core fix (Option A): - Add a distinct force_prior_balances_read intent through _prepared_payout_state_candidate and _build_payout_ledger_artifact. It disables published-balance reuse and reads the carry aggregate live while the window goes through the normal debounce/delta path. It is never a full rescan and never records one. - The reconciler's confirmed-mutation path now requests that reread (ReorgReconcilerService._candidate_intent); the intent keyword is only forwarded when set so pre-existing preparation and build seams keep their exact signatures. - force_full_window_rescan keeps its whole meaning everywhere else: cold and cache invalidation, late-visible append, anchor/weight regression, daemon and incremental fallbacks, the periodic oracle, accepted-preview withdrawal, and the error-after-possible-commit path, which still republishes against a forced full rescan (and therefore fresh balances). Attribution (fixed telemetry contract only): - ReorgPorts gains an optional accepted_preview_telemetry owner; the coordinator wires ensure_accepted_preview_telemetry(self). Ports without one get a private owner. - reconcile records qbit_prism_reorg_reconcile_pass_seconds{caller} on every exit and the step family (admission_wait, watch_query, chain_probe, mutations, candidate_prepare, publish) around the calls themselves. - Callers are stamped per thread by the entry points -- landing (the flight-bypassing ensure_tip), post_confirm (forced publication), job_build (ensure_current), tip_refresh (the prefetch lane) and other -- so the reconcile_with_admission / reconcile_serialized / ensure_tip seams keep their kwargs. Optional _caller keywords are accepted by the coordinator entry points for explicit attribution. - payout_state records qbit_prism_payout_window_full_rescan_seconds {reason,path} only where the whole-window oracle actually runs: the full materialization (daemon vs in_process by which pipeline folded) and the periodic self-check. Tests: tests/test_prism_issue_224_core.py covers the intent split, the fail-closed paths, pass/step/caller observations on success and failure exits, rescan reason/path recording, seam compatibility, and the end-to-end coordinator path (maturation reuses the window, rereads and publishes fresh balances, records no reconcile_invalidation rescan). The two reconciler assertions that pinned the #112 forced rescan on the confirmed-mutation path now assert the reread intent. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01MgytztiBedDJPHGxnWnAqg * Attribute accepted-landing latency to its owning phase (#224) The publication histogram proves an acceptance-to-preview tail exists, but nothing on /metrics said which stretch of the landing owned a sample above the 4 s warning or the 5 s child wait budget. This instruments the existing definitive-acceptance-to-publication path against the Wave 0 contract, changing no payout, finalization, candidate, lock, retry, timeout or publication behaviour. The seven fixed phases are recorded where they actually run: lane_wait from the acceptance stamp to the lane starting the landing task, balance_lock_wait around the serializer acquisition (the plain `with` becomes an ExitStack so only the acquisition is timed and the release point is unchanged), reconcile around both inline ensure_reorg_reconciled_for_tip stretches, prior_balances_check around the bracketed reread and the live current_prior_balances comparison, chain_probe around pool-block-state, tip-height-rpc and _block_candidate_chain_probe, preview_prepare around both preview materializations, and preview_publish from entering the publish call to the instant the preview becomes visible. Per-hash state lives beside B1's acceptance stamps, under the same leaf lock and bounded by the same cap with the same oldest-first eviction, and is discarded on terminal abandonment and collapse withdrawal. It accumulates only while a hash's interval is open, so a stretch that ran before definitive acceptance and a retry's stretch after the interval closed reach the process-wide family without ever being claimed by a landing's diagnostic. The first publication -- published or degraded -- is the single point that closes the interval, so it pops the record, builds one AcceptedPreviewPublicationDiagnostic with reconcile caller=landing, and emits one bounded JSON lifecycle line in the payout-artifact style, both outside the leaf lock. Rescan and ledger totals stay at the contract's neutral values: no per-landing causal evidence for either is available here without a process-wide delta read that would claim another lane's work as this block's. Hash and height appear in that diagnostic and log only; every metric label is a fixed phase name. Checks: tests.test_prism_block_finalization, tests.test_prism_block_candidates, tests.test_prism_accepted_preview_telemetry, tests.test_prism_metrics, tests.test_prism_issue_224_landing, the full `unittest discover -s tests` suite (3107 tests, 2 pre-existing skips), compileall, and diff --check. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01EgdzHvd8NL26qjYnmJncAn * Attribute the payout-window and prior-balances reads (#224) The accepted-preview latency alert fired while the coordinator stayed healthy, and nothing on /metrics said which stretch of the landing owned the sample. Four ledger reads sit in that stretch, and each can be slow for either of two unrelated reasons: coordinator-local admission behind an accounting write, or PostgreSQL execution. One duration covering both cannot tell an operator which -- the same ambiguity that misdiagnosed #211 on the enumeration path before it was split. Route those four through the attributed read helper the enumeration already uses, under the operation names Wave 0 froze: snapshot_at_job_issue -> payout_window_snapshot snapshot_between_job_issues -> payout_window_delta current_prior_balances -> current_prior_balances prior_balances_after_pool_block -> prior_balances_after_pool_block The helper was hard-wired to the read semaphore, so it is generalized over the gate the caller already takes. That is the invariant most at risk here: the prior-balances reread stays on the *writer lock*, where it must observe the fenced state a payout mutation leaves behind, and the other three stay on the bounded read slot. gate_name is the string _operation_gate would have been given, so an expired admission still names the primitive it was waiting for. No SQL text, result parsing, thread, connection, retry, lock nesting or label value changes. The legacy qbit_prism_prior_balances_* aggregate is left exactly as it was -- one duration over admission and execution, recorded only on success. It duplicates part of the new per-operation sample on purpose: an operator comparing that existing series across this upgrade must not find its meaning quietly redefined. Operation names stay bare string literals at each call site because tests.test_prism_accepted_preview_telemetry harvests them from this file's source to fail on a name outside the closed vocabulary; imported constants would leave that check with nothing to read. tests/test_prism_issue_224_ledger.py drives the new module against real Lock/BoundedSemaphore primitives behind a recording wrapper and a scripted clock, so recorded seconds are exact and a released gate is a fact about a primitive rather than a counter. It pins the fixed operation per read, the gate each read keeps (proved from both sides, including a refusing writer gate the read-slot reads never touch), gate wait separated from execution, admission expiry as a gate timeout with no execution sample, statement expiry as an execution timeout, release-and-preserve on failure exits, a differential against the pre-change admission body for byte-identical SQL and results, and the fold that keeps an out-of-contract name from growing a series. The two existing tests that call the helper directly gained the now explicit gate arguments; their scenarios are unchanged. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01GQRKR6tm627cizwNTZ81h2 * Prove the #224 reread over a dense reconcile cadence and in PostgreSQL Wave 1 answers a confirmed payout mutation with a live prior-balances reread over the still-exact accepted-share window instead of the O(window) oracle rescan. Its tests pin one mutation at a time; the alert hour was a dense accepted-tip cadence. tests/test_prism_issue_224_cadence.py drives consecutive trusted passes through the real coordinator adapters over one frozen-anchor window while the carry aggregate moves through a maturation, an inactive marking and a reactivation, interleaved with quiet passes and with the post-confirm and landing entry points. Per pass it records the preparation intent, the ledger artifact, the published balances and the ledger reads, and pins them against each other and against the fixed-cardinality telemetry: mutating passes forward force_prior_balances_read=True with force_full_window_rescan=False, reuse the very armed window object and publish the live balances after exactly one attributed current_prior_balances read; quiet passes prepare, read and publish nothing; the rendered families carry only closed-vocabulary labels. A lost maturation response mid-cadence still fails closed to the reconcile_invalidation full rescan. The Wave 1 fixture gains an optional ledger parameter so the cadence module reuses its setup. test/test-prism-postgres-ledger.sh captures the exact identity of qbit_share_ledger (every row in sequence order with ctid and xmin, plus the sequence allocator) before block 66's reconciliation-owned mutations and requires it back after each inactive quarantine, maturation sweep and reactivation, while the owed balance proves each transition landed. Its PASS summary names the invariant. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01SSg1LisJpnfCju56WjZrpM * Add the #224 operator validation contract for the accepted-preview boundaries Issue #224, Wave 3 closeout. The integrated Wave 0/1/2 stack was reviewed end to end from origin/2.x.x: confirmed reconciliation mutations request force_prior_balances_read=True with force_full_window_rescan=False and reuse the armed window object; the lost-response path still forces the reconcile_invalidation full rescan; withdrawal, late-visible append, anchor/weight regression, daemon loss and the periodic self-check keep their reasons; landing attribution opens only at definitive acceptance, is popped by the first published/degraded publication under the same lock that tombstones the stamp, and a retry or republication after that reaches the process-wide family only; every rendered label is drawn from a closed vocabulary; the attributed ledger helper keeps each read on the gate it already took with identical SQL, retry and release ordering; the flight, fencing and replay paths are wrapped, not changed; and the dense cadence and PostgreSQL identity proofs assert the successful and ambiguous paths against distinct balance values and tuple identity. No production or test defect was demonstrated, so no code changes. docs/prism-overload-alerts.md gains the operator contract the rollout needs to judge the 4 s warning and 5 s child-wait boundaries from the shipped metrics: the verified signal inventory (histogram le="4"/le="5" labels, the four attribution families, the ledger operation split, the artifact event counter, the legacy carry aggregate and the backlog gauges), the two bounded structured log lines that carry block identity, bucket-derived rolling-hour breach counts with a subquery form for whole soaks and the reason percentiles cannot prove a count, phase / caller / step / rescan-reason / admission-versus-execution breakdowns, the log-correlation recipe, the pre-deploy baseline and post-deploy testnet cadence and Union mainnet soak checklist, the #224 pass/fail criteria, and a fail-closed rollback/escalation decision that never raises the alert, extends the child wait, weakens exactness or disables the conservative rescan. It distinguishes the deliberate reconcile_invalidation fallback from a successful balance-only reread and notes open #207's separate window_daemon_state_lost scope. docs/prism-ledger-ops.md now lists the four #224 read operations and the writer-lock gate of current_prior_balances beside the existing read-slot enumeration paragraph, and points at the new section. Checks: the two focused unit groups (135 and 595 tests), compileall, bash -n on the PostgreSQL gate, git diff --check, and the real Docker PostgreSQL ledger gate (all five gates PASS, including share-ledger-identity=inactive+reactivate+mature). Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_014FMYTWWK1au9ptcu2sB4fq * Keep the #224 landing attribution honest under replay and writer stalls Codex review of #230 found two ways the attribution reports something the landing did not do. The publish span allocated an in-flight record for every publication, including the startup replays and chain-proven candidates that publish without an in-process acceptance stamp. The observer returns before it can pop anything for those, and the span's exit only cleared its token, so each one stayed in the bounded map as a publication permanently in flight -- and a large enough replay evicted live landings from the cap before their diagnostics were ever emitted. The record is now allocated only for an open interval, and an interval that closed under the publication because its stamp aged out of the shared cap drops it. The phase family still takes its sample either way. lane_wait closed after _mark_block_candidate_attempted, so the landing's own PostgreSQL write was charged to queue time, and a marker that timed out kept charging its retry backoff there too: the one stretch that exonerates the landing grew precisely when the writer was degraded. Both queued paths now close the lane before the marker write, leaving that write in the unattributed remainder the operator guide already describes. * Close the landing lane on both sides of the node offer The previous commit moved lane_wait's close above the attempt marker, but in doing so moved it above _node_submission_for_candidate_or_retained as well -- and that call is where a fresh candidate gets its definitive acceptance stamp, inside _submit_block_candidate_to_node. The close then found no open interval and returned, so every first-pass queued landing published a diagnostic with no lane_wait sample at all. A zero sample and a missing sample are indistinguishable in the per-landing diagnostic, so the loss would only have shown up as the family count trailing the accepted block count. Both queued paths now close the lane on either side of the offer. _close_accepted_landing_lane_wait is already once-per-open-interval, so the second close is a no-op when the first recorded: a candidate carrying a retained acceptance keeps the earlier, tighter sample that excludes this landing's own work, and a fresh candidate reports the zero queue time it genuinely had. Both closes stay above the attempt marker, so that write is still outside lane_wait. The ordering guard now also requires a close after each path's last node offer, which is what fails against the previous commit. --------- Co-authored-by: Claude Fable 5.1 <[email protected]>

Problem. The PRISM coordinator's payout-artifact pipeline has been running at a 100% duty cycle on mainnet for weeks, and it is the root cause of a chain of stratum-visible failures.
Measured in production, 2026-08-11, stable for 34 hours straight: the payout artifact is rebuilt every ~15–30 s, and every build takes 11–36 s (mean ~11.5 s).
payout_artifact_installedlogsduring_publication: trueessentially always — publication never idles. Each build re-walks the entire ~70–93k-share reward window through the recursiveWITH RECURSIVE pages AS (...)CTE overqbit_share_ledger(47.8M rows / 116 GB), and Postgres 16 sits at ~150% CPU withwait_eventIO/DataFileRead. Two prior Postgres sizing passes (2026-07-16, 2026-07-19;shared_buffers=8GB,work_mem=256MB,effective_cache_size=36GB) did not help — the workload itself is the problem, not its memory envelope.The knock-on damage all traces to that saturation:
reconcile prefetch join exceeded 20s; retrying refresh pass while it completes~20×/hour, continuously.tip refresh wave outcome=trust_blocked,outcome=payout_blocked,tip/template refresh superseded; retrying: payout state invalidation is pending publication.mining.subscribeprobes (12 s budget) fail 50–115/hour, chronically breaching the 30/h Grafana warning since at least Aug 7.block_submitterwedged for 300 s, the watchdog restarted the process, and the pool paged.The core observation: between two consecutive builds the ~80k-share window advances by a few hundred shares, yet every build re-aggregates all ~80k. Build cost should be O(delta), not O(window).
Fixing that exposed three further defects on the resulting reuse line — a share that can never enter the incremental window, a lost-response mutation that stops self-healing, and a reused balance snapshot with no independent check. All four are addressed here because the last three are only reachable once the first is in place.
Fix.
Incremental window maintenance (
lab/prism/share_ledger.py).IncrementalShareWindowis an immutable cache of the exact whole-share window superset, paged in ascendingshare_seq. A new ledger delta API —snapshot_between_job_issues(previous_anchor_ms, anchor_ms), implemented for both the in-memory and Postgres ledgers — returns exactlyeligible(new_anchor) - eligible(previous_anchor)as two disjoint indexed timestamp ranges joined withUNION ALL, never the recursive pages CTE; heap reads are limited to delta rows and existing partial indexes cover range discovery.advance()extends only the newest page and expires weight off the oldest, retaining the exact whole crossing share the SQL oracle retains, so retained interior pages are never revisited.IncrementalShareJsonSequencekeeps the wire view byte-identical while streaming the canonical SHA-256 from already-encoded page fragments, so retained shares are never re-serialized either. Every non-append condition — anchor regression, duplicate or lowershare_seq, non-positive difficulty, a share ineligible at the new anchor, a delta row that was already eligible at the previous anchor — raisesIncrementalWindowFallbackand the build falls back to the full oracle. Page sums were only ever a cutoff accelerator; no payout amount, fee math, or artifact wire byte changes.Debounced cadence. New
PRISM_PAYOUT_ARTIFACT_MIN_BUILD_INTERVAL_SECONDS(default: the configured re-anchor interval, 60 s) sets a floor between real refreshes. A routine generation inside the interval retags the cached window with zero share queries and logswindow_build_mode: "debounced". Found-block settlement and accepted-block previews bypass the interval unconditionally — a settlement artifact is never delayed by the debounce — and found-block publication no longer queues behind an in-flight 11–36 s oracle: it reuses the last exact armed window and patches prospective balances (found_block_cached). The 300 sPRISM_PAYOUT_ARTIFACT_MAX_ANCHOR_AGE_SECONDSaudit ceiling stays fail-closed and now aborts before paying the window walk;validate_payout_artifact_age_boundsrejects a configuration where the ceiling is not at least 2× the effective refresh floor.Periodic full-oracle self-check. Every
PRISM_PAYOUT_ARTIFACT_FULL_RESCAN_SECONDS(default 3600) an otherwise-incremental build also runs the full rescan, compares the exact retained records, installs the oracle's bytes either way, and reportsself_check_match/self_check_mismatch. A failed oracle attempt is spaced by the same interval so a saturated or unavailable database cannot turn a safety check into one full CTE retry per minute; the already-validated delta remains in service and the build reportsself_check_failedwithout claiming parity.Prior-balance reuse. Prior carry balances are generation-owned immutable state that a share-window refresh cannot change, so a routine refresh at the same published generation copies the published artifact's exact bytes instead of re-aggregating the 1.3M-row carry tables on every generation. The source is logged as
prior_balances_source: "published" | "ledger".Late-visible appends invalidate the cache (money-path fix). The delta design assumes delta completeness, and the pending-share commit floor normally guarantees it by clamping anchors below every registered pending share. The hole: the durable-outbox replay path reconstructs
PendingSharefrom persisted JSON with its originalaccepted_at_msand never registers it in the floor, and replay is not restart-only —block_submit_loopcallsreplay_pending_block_candidates()every iteration. For acredit_share_on_acceptcandidate the share row is inserted only after the block confirms, by which time the warm cache's anchor has advanced past both of the row's timestamps. BothUNIONbranches of the delta query require a timestamp> prev_anchor, so that row is invisible to the delta path forever, and the urgent fold scheduled right after the append cannot help. The winning share — the heaviest in the window — would be absent from every published payout window for up to a full hour, and a child-block settlement inside that window would underpay that miner finally and on-chain. (Pre-incremental behavior bounded the same exposure to a single ~15–30 s build.) Fix: at the append boundary, when an appended share'sjob_issued_at_msandaccepted_at_msare both<=the cached anchor, the cached window is dropped under_payout_state_prepare_lockwithfull_rescan_reason: "late_visible_append", so the urgent rebuild takes the full oracle and includes the row. Registering the replayed candidate's oldaccepted_at_msin the commit floor was rejected: an old floor clamps every subsequent anchor pathologically old and trips both the pathologically-old-floor build abort and the 300 s max-anchor-age abort.IncrementalShareWindow.advance's append-only invariants are untouched — the fix lives at the append/coordination layer, not in window algebra.Lost mutation responses re-arm the ledger read.
payout_changedwas derived exclusively from observed mutation results (row counts / returned state) inreconcile_prism_pool_blocks_once. The balance-affecting RPCs (mark_pool_block_inactive,reactivate_pool_block,mark_mature_pool_payouts) are single round trips: if a statement commits server-side but the client sees a reset or timeout, the exception handler skipped the forced rescan (it is gated onif payout_changed:), and the next pass saw an already-consistent DB, so the flag was never set. Before balance reuse this self-healed within one build; after it, both sides of the digest fence trace to the same reused bytes and the fence becomes a tautology, so pre-mutation balances — and the signedprior_balancesdigests in ledger-window attestations — persist until an unrelated payout event or a restart. Now apayout_mutation_attemptedflag is set before each mutation RPC, and any exception escaping the pass after an attempt is treated aspayout_changed=True, publishing the error candidate withforce_full_window_rescan=True. Read-only prefetch/refresh failures are deliberately excluded from this: they are the ~20×/hreconcile prefetch join exceeded 20sevents, and forcing an oracle pass on each would reintroduce exactly the saturation this branch removes. Settlement money movement was never affected — previews read the DB fresh.Balance self-check backstop and alarm. The hourly self-check now also re-reads
current_prior_balances()and compares its canonical digest against the balances the reuse path would serve. On mismatch it serves the freshly read balances (no duplicate carry query — the check already paid for it), pins the failed digest out of the reuse path, drops the armed artifact so the fresh read cannot be discarded as a window-only no-op, and emitspayout_artifact_balance_check_mismatchat detection time — before serialization or stats work that could fail and hide the alarm. Cost envelope: at most one carry-aggregate read perPRISM_PAYOUT_ARTIFACT_FULL_RESCAN_SECONDS, no new steady-state queries.Observability.
payout_artifact_builtgainswindow_build_mode,window_build_seconds,delta_rows,expired_rows,touched_pages,build_interval_bypassed,prior_balances_source, andfull_rescan_reason. New counter events:debounced,full_rescan,self_check_match,self_check_mismatch,self_check_failed,balance_check_mismatch,found_block_cached.balance_check_mismatchandself_check_mismatchare the two operators should alert on.Configuration.
PRISM_PAYOUT_ARTIFACT_MIN_BUILD_INTERVAL_SECONDS(default = re-anchor interval) andPRISM_PAYOUT_ARTIFACT_FULL_RESCAN_SECONDS(default 3600) are new; both are plumbed through.env.exampleandcompose.yamlalongside the existingPRISM_PAYOUT_ARTIFACT_*vars, which now also appear explicitly rather than relying on in-code defaults. The pre-existingPRISM_PAYOUT_ARTIFACT_REUSE=0master kill-switch remains the rollback lever: off disables the whole reuse line — no probe acceptance, no background reward-window walks, no arming — restoring pre-reuse delivery economics by env flip instead of a revert.Tests.
tests/test_prism_incremental_payout_window.py(new): 10,000 seeded randomized sequences mixing appends, anchor advances, large crossing weights, credit policies, reorg/reconcile corrections, and carry-forward boundaries assert the incremental artifact is bit-identical to the full-rescan oracle at every step; crossing-row retention and ascending order; non-append deltas rejected without mutating the window; and a 90,000-share window with a 500-share delta touching only the append and expired-edge pages — the other ~89,500 shares' pages are never revisited.tests/test_prism_coordinator_job_cache.py: debounce → delta → forced full rescan; 15 s generation bumps producing exactly one real refresh per minute; found-block candidates bypassing the interval, reusing the armed window when the prepare lock is busy, and staying visible on build failure; periodic self-check match, divergence replacement, and failure spacing; generation-owned balance reuse; drifted balances caught by the self-check backstop; and the late-visible-append pair — a replay-shaped append below the cached anchor forces the next build to the full oracle with the new reason, while a normal append above the anchor leaves the incremental cache intact.tests/test_prism_coordinator_vardiff.py: a fake ledger whosemark_pool_block_inactivemutates rows and raises — the next publication re-reads balances with a forced rescan; and a read-phase failure before any mutation attempt provably forces neither.tests/test_prism_share_ledger.py: the delta returns each newly eligible share exactly once, and the Postgres delta SQL uses disjoint timestamp ranges and never containsWITH RECURSIVE pages.ShareWindowSpoolTests/ServeBuilderTestsfrom Linux-onlyos.splice. Verified identical (2 failures + 3 errors, same tests) on the base commit6c00d6ein a clean worktree — pre-existing, not introduced here.Docs.
docs/prism-payout-artifact-measurement.mdis a read-only production runbook for a human operator:pg_stat_statementstop-N bytotal_exec_time(with the pages oracle, delta query, and carry aggregate always retained even when they fall out of the top-N),EXPLAIN (ANALYZE, BUFFERS)for the pages CTE at the current window size, and the three log-derived metrics — build duration p50/p95,during_publicationduty cycle, and sidecar failure rate — captured before and after rollout so the actual win can be stated from evidence rather than estimated.Expected production effect. Steady state should move from ~100% publication duty cycle to <20%: routine generations retag with zero share queries, real refreshes run once per minute against a few hundred delta rows instead of ~80k, and the full pages CTE runs roughly hourly plus on genuine invalidations.
reconcile prefetch join exceeded 20sshould disappear; the sidecarmining.subscribeprobe failure rate should drop from 50–115/h to ~0 background and clearPrismStratumCheckFailureRateHigh; tip-refresh waves should stop reportingtrust_blocked/payout_blockedfrom payout-state contention. Confirm against the runbook's before/after capture rather than assuming.Note
Low Risk
Config documentation and compose env wiring only; no application logic changes. Defaults match existing in-code values, so behavior should stay the same unless operators override them.
Overview
Exposes the payout-artifact reuse settings for rollout and ops tuning, and adds a production measurement runbook to validate the incremental build path.
.env.exampleandcompose.yamlnow surfacePRISM_PAYOUT_ARTIFACT_REUSE, re-arm/re-anchor intervals, min build interval, full rescan cadence, and max anchor age (compose defaults the min-build interval to the re-anchor value).Adds
docs/prism-payout-artifact-measurement.md: a read-only operator runbook for before/afterpg_stat_statements, oracleEXPLAIN ANALYZE, artifact-event duty-cycle metrics, and sidecar/reconcile failure rates.Reviewed by Cursor Bugbot for commit c94f982. Bugbot is set up for automated code reviews on this repo. Configure here.