Repository navigation
Move the payout-window fold, digest, and advance() behind the --serve daemon - #166
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
09930f8 to
52e3139
Compare
97b9ef2 to
a211515
Compare
Update — review findings addressedTwo adversarial reviews ran against this stack. The review of this PR found no blocking defect; the review of #165 found two blocking holes in the oracle itself, which mattered here because this PR is proven against it. Three further commits landed:
Eight regression tests, each proven failing at the base commit.
On integer width: the corpus's new wide-integer cases exceed That is modelled honestly as a narrower domain, not a divergence: the daemon answers Verification after all three commits
Rebased onto |
… daemon First slice of the #131 window-pipeline migration, stacked on the #165 parity oracle. The --serve audit builder gains a prepare_window request (protocol 2) with full and advance modes: the daemon owns the payout-window fold, the canonical digest (which is the window cache key), and the incremental advance, byte-identical to the shipped Python pipeline and proven by the existing 14-case parity corpus through a registered rust-daemon adapter. Prepared windows unify with the build window cache, so builds whose share_snapshot_sha256 matches a prepared window hit it with no window upload; prepared state is epoch-tagged and dropped by any request carrying a newer append-invalidation epoch. The coordinator holds the folded window as an opaque, digest-verified byte mirror of the canonical items stream (full stream on full mode; prefix-drop plus appended suffix on advance), from which shares_json parses lazily: the routine build path never materializes dicts or compact payloads, while the rare consumers that need real dicts (the durable candidate intent, the found-block canonical audit build, the one-shot builder fallback) parse the in-memory bytes at their own call sites with no database re-read and no daemon dependency on the landing path. Switched by PRISM_WINDOW_PIPELINE_RUST, default Python, strictly boolean (startup refuses anything else), and inert while PRISM_BUILDER_SERVE is off. needs_full and fallback are ordinary control flow: a daemon that lost its state is re-seeded through a full preparation, and an advance invariant failure takes exactly the IncrementalWindowFallback path (cache cleared, full rescan reasoned incremental_invariant_failed) without retiring the daemon. Any daemon anomaly degrades to the in-process pipeline for that materialization; the Python window pipeline stays fully intact. Co-Authored-By: Claude Fable 5 <[email protected]>
A prepare that cannot get the daemon promptly now degrades instead of retiring it. prepare_payout_window stamped its deadline before an untimed blocking acquire, so a preparation that queued behind a slow build arrived inside the lock with its whole budget already spent: the first write read as a daemon timeout, and the anomaly handler recorded a live termination, SIGKILLed a healthy daemon, counted a fallback, and sent the caller into a cache-clearing full DB walk, full fold and full window upload. The wait is now bounded by the preparation's own budget and the exchange deadline is stamped after the acquire, so a build's runtime is never charged against the daemon's health. Losing the race answers a new "busy" outcome -- ordinary control flow, counted as window_prepare_contended, surfaced as a window_daemon_busy full-rescan reason -- and bypass_build_interval materializations (the accepted-block preview, which takes the prepare lock non-blocking precisely so publication never queues) refuse to queue at all. A declared record count is reconciled with the mirror's own bytes eagerly. The construction-time digest pinned the bytes and said nothing about the count beside them, so a miscount could only surface at whichever consumer first parsed the stream -- possibly a serve request that had already written its prefix, leaving the daemon's stdin holding an unterminated line for the next request to concatenate onto. The count is now walked out of the bytes next to the digest check: fully for a full mirror, and from the dropped prefix plus appended suffix for an advance, so the hot path stays proportional to the surgery. Separator placement at both seams is checked too. Any DaemonWindowMirrorDivergence that can still escape now invalidates the cached window and counts a window_mirror_divergence event, and a request that escapes half-written retires the daemon on any exception rather than only the enumerated anomalies. The daemon's epoch tag no longer evicts prepared windows. The coordinator's own late-append policy is finer -- it clears the incremental cache only when the late row predates the cached anchor, and otherwise retags the window so the next delta build advances it in place -- and the daemon never chooses a window: entries are addressed by content digest, validity is decided by the install fence and the job-bundle epoch checks, and an advance base is the coordinator's own digest-verified mirror. A tag mismatch could catch nothing the coordinator had not already decided; it could only turn every retag into a full rescan under exactly the replay bursts that produce the bumps. The tag now rides along for diagnostics only, echoed back on advance beside the requesting epoch. An unheld digest remains the only needs_full. Co-Authored-By: Claude Opus 5 <[email protected]>
…dth contract Running the strengthened 34-case parity corpus through the rust-daemon adapter left 22 cases not passing, for three causes, none of them in the fold itself. The adapter raised on every non-ok envelope, so the daemon's correct fold_invalid/fallback refusals (12 cases) read as harness errors; it never relayed the daemon's added_rows/expired_rows/touched_pages into the seam's advance_stats (8 advancing cases); and the two wide-integer cases died in serde with "number out of range", which the daemon answered as a malformed request -- the one shape the coordinator treats as an anomaly, so a window holding such a value retired a healthy daemon and respawned it on the next materialization only to kill it again. Rejections now cross the wire as structure, not prose. Both window error enums gain rejection_category(), the parity oracle's own vocabulary (five full-snapshot conditions, six advance conditions; a Rust unit test pins the eleven strings), and the daemon's fold_invalid and fallback envelopes carry it as `rejection` beside the human-readable `error`, which is diagnostic and free to drift. The adapter maps on that field alone -- an unknown or missing category is a harness error, never a guess -- and takes each advance's stats triple from its envelope. PreparedWindowOutcome carries the category too. Protocol 2 is already this branch's bump; its doc now lists these fields. The integer-width contract is narrowed to the Rust widths, deliberately and in writing: share_seq u64, share_difficulty and network_difficulty u128, template_height u64, ntime u32, the millisecond stamps and anchors i64, window_weight u128, with the fold's difficulty accumulators u128 as well. The reasoning sits in the parity docstring and beside the Rust types: a share is (pow_limit_target*1e6)//target, about 2^98 at a mainnet-scale target, so a 16x window totals about 2^102 -- a factor of roughly 6e7 short of 2^128 and unreachable on any chain this code will see; numeric(78,0) is a generic wide column, not a statement that difficulties exceed 2^128; and arbitrary precision would put bignum arithmetic on the path the migration exists to speed up. No bignum crate. The narrower domain is modelled as a domain, not a divergence. The seam gains a third outcome, WindowPipelineUnsupported(reason), and each adapter declares a WindowPipelineIntegerDomain (unbounded for Python, the table above for rust-daemon; an adapter declaring nothing claims everything). The frozen reference keeps Python's bytes for every case; diverging_outputs accepts Unsupported only where the case really lies outside the backend's declared domain, still fails wrong bytes there (a saturating u128 accumulator declaring the Rust domain is held to the frozen digits), and fails Unsupported for a case inside the declared domain. The divergence suite demonstrates each of those with perturbed backends. The daemon declares it cleanly. A line the strict parse refuses is re-parsed once, with exact digits, and a prepare_window request whose integer lies outside its declared width is answered as out_of_range -- naming the field, the literal and the width -- while a corrupt line stays a malformed request. The accumulators are checked rather than saturating: a retained or advanced total that leaves u128 is declined the same way (field total_difficulty) instead of silently changing later expiry. The coordinator treats out_of_range as ordinary control flow: a full preparation so declined falls to the in-process fold, an advance so declined rebuilds through the full path (reason window_value_out_of_range), the daemon keeps its state and is never retired, and the declines are counted as window_prepare_out_of_range. The fake serve builder mirrors the declared widths and rejection categories, and regression tests prove a daemon that receives an out-of-range window survives two materializations with one spawn and no termination, at both the snapshot and the delta. The width cases are split so the original protection survives. wide-integers now carries every integer far above 2^31/2^53/2^64 but inside every declared width (share_seq to u64::MAX, network_difficulty to u128::MAX, ntime to u32::MAX, share_difficulty still 2^127+3 with the 2^64-dependent cutoff), so both backends produce bytes and full parity is enforced there; its ntime 2^63-1 moves to a new ntime-beyond-u32 case beside difficulty-beyond-u128, both frozen with Python's bytes and answered Unsupported by the daemon. Re-running the backends that motivated the case -- u32-wrapping, u64-wrapping and a u64-saturating accumulator -- each still fails the retuned wide-integers (record_count 2 and 3 against the frozen 4 for the two that touch the accumulator) while passing the sub-2^31 corpus, and that check is kept in the divergence suite. With the 35-case corpus, both adapters pass every case with no case reported as an error; the fixture regenerates as a no-op. Co-Authored-By: Claude Fable 5 <[email protected]>
1c6b85d to
e4064e8
Compare
|
Rebased onto The conflict GitHub reported was not content divergence: when #165 merged as a squash, this PR's base was retargeted from the parity-oracle branch to This also carries the PR across four Re-verified on the rebased branch:
One note for the reviewer: the three commits on this branch are unsigned, at the repository owner's instruction; the earlier commits in this line are signed. |
First slice of #131. Stacked on #165 — that PR's parity oracle is the test that proves this one. Review and merge #165 first; this PR's base is its branch, so the diff here is only the migration.
Problem
#131's profiling comment identified the payout-window pipeline — fold, canonical digest, spool serialization — as the concrete first migration target, and the decision comment on that issue measured which parts of it are actually GIL-held:
hashlib.sha256)So the fold is the target: 71 ms per materialization today, 1,057 ms at 400k shares, serialized, paid on every re-anchor inside the process that must ack shares within the group-commit linger.
The digest is not a saving. It moves because the daemon's window cache key is the digest, so Python cannot decide "upload or not" for a window it never folds. Nobody should count it as a win.
advance()is in scope deliberately. A daemon that only implementedfrom_full_snapshotcould not populate the coordinator's incremental window cache, so every 60 s re-anchor would become a full fold where today's common case is a delta fold — that would make the steady state worse to improve the tail.What changes
The
--serveaudit builder gains aprepare_windowrequest (protocol 2) withfullandadvancemodes, called once per window generation from artifact materialization — never per build. The daemon owns the fold, the canonical digest, and the incremental advance.Prepared windows unify with the build window cache, so a build whose
share_snapshot_sha256matches a prepared window hits it with no window upload at all. Prepared state is epoch-tagged and dropped by any request carrying a newer append-invalidation epoch — a tag rather than an invalidate message, because a daemon that missed an invalidate while mid-respawn would be a soundness hole, whereas a tag mismatch is self-correcting.How
shares_jsonsurvivesThis was the hard part, and it is worth stating explicitly because the obvious designs all fail.
shares_jsonhas consumers outside the daemon path, and it cannot be rebuilt from what the daemon holds: the compact wire form carries seven fields and drops four thatto_prism_jsonemits —network_difficulty,template_height,job_id,ntime.The coordinator therefore holds the folded window as an opaque, digest-verified byte mirror of the canonical items stream: the full stream on
full, and prefix-drop plus appended suffix onadvance, so an advance ships bytes proportional to the delta rather than the whole window.shares_jsonparses lazily from those bytes. The routine build path never materializes dicts or compact payloads; the rare consumers that need real dicts — the durable candidate intent, the found-block canonical audit build, the one-shot builder fallback — parse the in-memory bytes at their own call sites, with no database re-read and no daemon dependency on the landing path.Every mirror construction re-hashes its bytes against the digest the daemon declared. A divergence between the two implementations, or a bug in the byte surgery itself, becomes a detected full rescan rather than a silently wrong payout artifact.
Switch and degradation
PRISM_WINDOW_PIPELINE_RUST, default Python, strictly boolean (startup refuses anything else rather than silently reading a typo as false), and inert — not an error — whilePRISM_BUILDER_SERVEis off.needs_fullandfallbackare ordinary control flow, not errors: a daemon that lost its state is re-seeded through a full preparation, and an advance-invariant failure takes exactly the existingIncrementalWindowFallbackpath (cache cleared, full rescan reasonedincremental_invariant_failed) without retiring the daemon. Any genuine daemon anomaly degrades to the in-process pipeline for that materialization. The Python window pipeline stays fully intact — this adds a path, it does not replace one.Rollback is three independent env levers plus the automatic ladder:
PRISM_WINDOW_PIPELINE_RUST=0,PRISM_BUILDER_SERVE=0,PRISM_PAYOUT_ARTIFACT_REUSE=0.Verification
Byte-parity is proven by #165's existing 14-case corpus through a registered
rust-daemonadapter that drives the real daemon binary over its actual JSONL protocol — not a stub or a reimplementation.rust-daemonadapter: 14 OK, including the incrementaladvance()cases. Python adapter: 14 OK.tests.test_prism_window_pipeline_rust(new, covering epoch discard, in-flight anchor exposure, mid-prepare_windowdeath,needs_fullre-preparation,fallbackwithout retirement, protocol mismatch, switch defaults): 19 OK.test_prism_payout_state,test_prism_incremental_payout_window,test_prism_share_ledger,test_prism_coordinator_config_loading,test_prism_coordinator_metrics: 349 OK.cargo test --locked --workspace --all-targets: 230 passed, 0 failed across 13 test binaries.test_prism_job_builderos.splicetests that are Linux-only and fail identically on the base commit — same five, same counts, 106 tests in that module before and after. Linux discovery: 2347 OK.compileallclean;bash -nandshellcheck -xover all tracked shell files clean.The parity oracle was confirmed to fail on a real Rust divergence, not only on synthetic perturbations: flipping the crossing-row retention rule from
>=to>in the new fold turns the suite red with a precise diagnostic, and restoring it returns the suite to green.Known trade-offs, stated rather than buried
prepare_windowtakes the daemon lock blocking, unlike builds, which prefer one-shot over queueing. A window preparation has no cheaper transport to defect to, so it waits; the exchange is bounded bybundle_build_timeout_secondsand falls back to in-process Python on timeout. The consequence is that a found-block preview materialization can queue behind an in-flight build. Reviewers should decide whether the preview path warrants a non-blocking acquire.crates/gains a Postgres, async-runtime, or TLS dependency.Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.