Repository navigation
Add a differential parity oracle for the payout-window pipeline - #165
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
The window pipeline (accepted-share records in; folded window, canonical digest, and audit-builder spool fragments out) is slated to gain a second implementation that must be proven byte-identical to the shipped Python one before it can take traffic. This adds the proof apparatus ahead of that implementation, composing the two existing precedents: the seeded-corpus discipline of the incremental payout-window golden tests (whose record factory it reuses) and the frozen byte-exact reference discipline of the metrics render-parity fixture. tests/window_pipeline_parity.py carries the corpus, the adapter seam, and the frozen-reference plumbing. The corpus is derived from the fold's own invariants: the retained crossing row paired with an exact-fit sibling, independent job/accepted eligibility exclusions with an on-anchor boundary row, unsorted input, credit_policy present and absent (null-vs-absent in the compact fragments), identity deduplication, non-ASCII/escaping including a non-BMP surrogate pair, page boundaries at 511/512/513 of the default page size, a multi-page interior cutoff, an empty and a single-record window, incremental advances that must land on full-rebuild bytes, and a seeded bulk case with a 700-record advance. Each case pins three byte outputs: the ordered per-record canonical encodings, the framed canonical document bytes plus their SHA-256 digest exactly as the digest streams page fragments, and the spool payload tail written by the real acquire_spooled_tail path. Small cases pin literal bytes for diagnosability; large ones pin length plus SHA-256. The frozen reference regenerates reproducibly with `python3 -m tests.window_pipeline_parity regenerate`, a no-op on an unchanged tree and enforced as such by test. The runner drives any registered backend over the same corpus through a plain adapter seam (inputs in, three byte outputs out), defaulting to the shipped Python pipeline; a future backend registers an adapter and is selected via QBIT_WINDOW_PIPELINE_PARITY_ADAPTER. No production switch is added anywhere. Divergence-detection tests drive deliberately perturbed backends (field reordering, missing page separator in the digest framing, explicit-null credit_policy, a dropped crossing row, spool whitespace) and prove the harness fails exactly where it should and passes where the perturbation is invisible, which is the evidence that single-page or crossing-free corpora alone would prove nothing. Co-Authored-By: Claude Fable 5 <[email protected]>
09930f8 to
52e3139
Compare
… 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]>
An adversarial review of the window-pipeline parity oracle found that its
corpus and seam let wrong second implementations through: every integer the
corpus fed the pipeline sat below 2^31, so nine perturbed backends carrying
integers in u32/i32/u64/i64/u128 (wrapping or saturating) and an f64
round-trip all passed 14/14; and no input triggered any of the fold's eleven
rejections while run() could only return outputs, so a fold with every check
removed -- or one that silently performs the coordinator's full-rescan
recovery and returns its bytes -- also passed 14/14. Both holes were already
blessing a registered backend. This closes them and the four should-fix
items, as a new commit on top of the oracle.
Corpus. wide-integers carries every integer field above 2^32 at a realistic
epoch-millisecond anchor, share_difficulty across 2^53+1, 2^63, 2^64+1 and
2^127+3, network_difficulty up to 10^77, template_height and ntime to 2^62
and 2^63-1 plus a legal zero pair, share_seq to 2^63-1, and a window_weight
of 2^127+2^64+2^63+4 arranged so the three newest rows fall short of the
weight only because of bits above 2^64 -- a 64-bit accumulator stops one row
early, so the retained count diverges, not just the digits. The decision the
review left open is made explicitly and documented in the module docstring:
the corpus also carries values at and above 2^128 (difficulty-beyond-u128:
share_difficulty 2^128+1 as the retained crossing row, network_difficulty at
2^128-1, 2^128 and numeric(78,0)'s maximum, window_weight above 2^128).
The ledger schema is the only written width contract and the mandated
wide-integers values already hold a backend to it rather than to any
existing narrower type, so the oracle refuses a 128-bit difficulty
accumulator -- saturating or not -- instead of blessing it silently;
narrowing that contract belongs in the schema plus a visible edit to those
cases. A structural assertion pins share_difficulty.bit_length() > 64 (and
> 128 in the second case) so neither can be quietly shrunk.
Seam. run() now returns WindowPipelineOutputs | WindowPipelineRejection,
where the rejection carries one of eleven implementation-neutral categories
(five for from_full_snapshot, six for advance), never an exception class or
message; the Python adapter classifies the shipped fold's exceptions by
exact message and re-raises anything it does not know. The fixture freezes
{"rejected": "<category>"} for such cases, and diverging_outputs compares
rejected-vs-rejected by category and reports rejected-vs-outputs in either
direction. One case per condition is added (both eligibility exclusions
separately; the repeat case re-delivers a share still inside the window;
the three DB-unreachable full-snapshot shapes are pinned anyway because the
in-memory ledger and the daemon protocol are not the database). The
docstring states that the oracle pins the pipeline's rejection, not the
coordinator's recovery from it.
Advance path. advance-exact-fit-expiry separates >= from > in the advance
loops; advance-delta-exceeds-window makes expiry run into the freshly
appended pages (the shape a drop-prefix/append-suffix protocol must get
right); advance-partial-expiry-in-appended-page lands partial expiry inside
a fresh page; and one-record cases cover an advance from an empty window, an
empty delta at a later anchor, and an equal anchor (the check is <). The
per-advance IncrementalWindowAdvanceStats triple is brought into the seam
as advance_stats and frozen per step, with touched_pages' definition spelled
out on the seam type: a page appended into and then expired wholesale still
counts, a freshly allocated page never does.
Escapes and regeneration. non-ascii-strings gains a record carrying DEL,
solidus, CR/BS/FF, U+001F, U+2028/U+2029, space and uppercase in share_id
and the identity fields, with the corresponding needles (and the absence of
a raw DEL or an escaped solidus) asserted structurally. The corpus owns its
record factory instead of importing the sibling golden test's, and
literal-pinned cases freeze the input document itself, so an input-only
change shows in the fixture diff as such instead of as a wall of moved
hashes. The reference schema is bumped to v2 for the new entry shape and
checked on load.
Every closed hole is demonstrated, not merely green: throwaway perturbed
backends modelling each divergence (the nine integer widths plus a
difficulty-only saturating u128, a fold that never refuses, a misfiled
category, strict advance expiry, expiry confined to pre-existing pages, an
equal-anchor rejection, a trailing separator on an empty delta, a last-page
unwrap on an empty window, a raw DEL, an escaped solidus, zeroed and
survivor-derived advance stats) pass 0/14 against the previous corpus and
fail against this one; the in-repo divergence-detection suite keeps a
representative of each class and asserts it fails exactly where it should
and passes where the perturbation is invisible.
Co-Authored-By: Claude Fable 5 <[email protected]>
… 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]>
Update — two blocking holes found and closedAn adversarial review of this PR found two blocking holes, each demonstrated by a perturbed backend that kept all 14 cases green. Both are closed by B1 — the corpus never left 32-bit integers. Every value it fed the pipeline was B2 — every rejection path was unpinned, and the seam could not express one. None of the eleven rejection conditions was triggered by any input, and Also closed: the exact-fit expiry and delta-exceeds-window advance cases (the second is the shape the stacked #166's byte-surgery protocol has to get right), empty/equal-anchor advances, the escape alphabet ( A third outcome, Verification
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]>
… daemon (#166) * Move the payout-window fold, digest, and advance() behind the --serve 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]> * Fix three degraded-mode defects in the window-pipeline daemon slice 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]> * Wire the Rust adapter to the rejection seam and settle the integer-width 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]> --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Alex <[email protected]>
Toward #131.
Problem
#131's method clause is explicit about what makes the Rust migration safe: "run the Python and
Rust implementations against the same inputs and assert byte-identical outputs … ship behind a
per-component switch defaulting to Python, flip it after the parity corpus is convincing, and
keep the switch for a release."
The window pipeline — accepted-share records in; folded window, canonical digest, and
audit-builder spool fragments out — is the concrete first target that #131's profiling comment
converged on. It is deterministic and byte-comparable, so the method applies cleanly. But the
corpus that method depends on does not exist, and building it after a second implementation
exists is the wrong order: the corpus would then be written by someone who already knows what
the new implementation does, which is exactly the bias a differential oracle is supposed to
exclude.
This PR lands the proof apparatus ahead of the implementation. It is useful regardless of which
way the migration's open design questions are settled, and it does not depend on any of them
being settled.
What it pins
Three byte outputs per corpus case, all inside the migration's scope:
AcceptedShareRecord.to_prism_json()sequence, onecanonical encoding per record.
IncrementalShareJsonSequence.canonical_json_sha256()(
lab/prism/share_ledger.py:333-345) and the framed bytes that produced it. This one iseasy to get subtly wrong: the digest is not a hash of a monolithic re-encode, it streams
pre-encoded per-page fragments joined with
,inside[/]. An implementation with correctrecords and wrong framing produces a different digest, so both are pinned.
_ShareWindowSerialization.acquire_spooled_tail(lab/prism/bundle_compiler.py:250-293),byte-for-byte including the
,"compact_share_identities":/,"compact_shares":/}framing, because that framing is the wire contract.
Shape
It composes the two precedents #131 names rather than inventing a third:
tests/test_prism_incremental_payout_window.py(whoseaccepted_sharerecord factory it reuses, with a deliberately distinct master seed so the twocorpora cannot silently alias);
tests/test_prism_metrics.py.The corpus is derived from the fold's own invariants, not from its bulk behaviour: the retained
crossing row paired with an exact-fit sibling,
job_issued_at_msandaccepted_at_mseligibility exclusions taken independently plus an on-anchor boundary row, unsorted input,
credit_policypresent and absent (null-vs-absent in the compact fragments), identitydeduplication, non-ASCII and escaping including a non-BMP surrogate pair, page boundaries at
511/512/513 of the 512-record default, a multi-page interior cutoff, empty and single-record
windows, incremental
advance()runs that must land on full-rebuild bytes, and a seeded bulkcase with a 700-record advance. Fourteen cases.
Small cases pin literal bytes so a divergence shows what diverged; large ones pin length plus
SHA-256, which is still byte-exact. The frozen reference regenerates reproducibly with
python3 -m tests.window_pipeline_parity regenerate, and a test asserts that regeneration is ano-op on an unchanged tree.
The runner drives any registered backend over the same corpus through a plain adapter seam —
inputs in, three byte outputs out — defaulting to the shipped Python pipeline. A future backend
registers an adapter and is selected with
QBIT_WINDOW_PIPELINE_PARITY_ADAPTER. No productionfeature switch is added anywhere: the per-component switch #131 describes belongs to the
migration slice, not to the oracle.
The part that makes it evidence
A parity harness nobody has seen fail is not evidence.
WindowPipelineDivergenceDetectionTestsdrives deliberately perturbed backends — field reordering, a missing page separator in the digest
framing, explicit-null instead of absent
credit_policy, a dropped crossing row, spoolwhitespace — and asserts the harness catches each one exactly where it should and nowhere
else. Two of those tests are the load-bearing ones: they prove a single-page corpus could not
have caught the framing bug, and a crossing-free corpus could not have caught the cutoff bug.
That is the evidence that the corpus's edge cases are necessary rather than decorative.
Verification
tests.test_window_pipeline_parity— 14 tests, OK.tests.test_prism_incremental_payout_window,tests.test_prism_payout_state,tests.test_prism_share_ledger— 294 tests, OK, unchanged.test_prism_job_builderos.splicefailures that this platform always shows and Linux CI doesnot; the same tree at the base commit shows the identical five. Full discovery on a Linux host
before the change: 2314 tests, OK; after: 2328 tests, OK.
python -m compileall -q docker lab tests examples scriptsclean;bash -nandshellcheck -xover all tracked shell files clean.Independently confirmed that the harness fails on a real change to the shipped pipeline, not
only on the synthetic perturbations: dropping the closing
b"]"fromIncrementalShareJsonSequence.canonical_json_sha256turns the suite red with 30 failures and 1error; restoring it returns the suite to green.
Scope
Tests and one fixture only. No file under
lab/orcrates/is touched, no dependency is added,and no behaviour changes. It does not migrate anything, does not choose a read fork, and takes no
position on #131's open design questions.
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.