Skip to content

Move the payout-window fold, digest, and advance() behind the --serve daemon - #166

Merged
kiwidream merged 3 commits into
2.x.xfrom
move-window-fold-into-serve-daemon
Aug 20, 2026
Merged

kiwidream merged 3 commits into
2.x.xfrom
move-window-fold-into-serve-daemon

Conversation

@kiwidream

@kiwidream kiwidream commented Aug 20, 2026 •

Copy link
Copy Markdown
Member

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:

stage @ 21,868 shares N=1 N=8 verdict
Window fold 1.00 1.02 GIL-held
Canonical-JSON digest 1.00 7.57 already fully parallel
Spool serialization 1.00 1.06 GIL-held
positive control (1 MiB hashlib.sha256) 1.00 7.23

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 implemented from_full_snapshot could 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 --serve audit builder gains a prepare_window request (protocol 2) with full and advance modes, 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_sha256 matches 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_json survives

This was the hard part, and it is worth stating explicitly because the obvious designs all fail. shares_json has 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 that to_prism_json emits — 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 on advance, so an advance ships bytes proportional to the delta rather than the whole window. shares_json parses 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 — while PRISM_BUILDER_SERVE is off.

needs_full and fallback are 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 existing IncrementalWindowFallback path (cache cleared, full rescan reasoned incremental_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-daemon adapter that drives the real daemon binary over its actual JSONL protocol — not a stub or a reimplementation.

  • Parity oracle, rust-daemon adapter: 14 OK, including the incremental advance() cases. Python adapter: 14 OK.
  • tests.test_prism_window_pipeline_rust (new, covering epoch discard, in-flight anchor exposure, mid-prepare_window death, needs_full re-preparation, fallback without 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.
  • Full discovery: 2347 tests (2328 at the base), failing only the five test_prism_job_builder os.splice tests 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.
  • Lint in Docker: compileall clean; bash -n and shellcheck -x over 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_window takes 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 by bundle_build_timeout_seconds and 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.
  • The hourly self-check deliberately stays a Python-side oracle, re-converting the cache to mirror form. That costs a Python fold once an hour and is intentional: a self-check that ran through the same implementation it is checking would not be an independent oracle.
  • The GIL benefit is not measured in this PR. Everything above proves byte-identity and degradation, not that the 71 ms left the coordinator. The instrument to measure it exists (see the 2.x.x: land the real-threads load driver as a repo performance instrument #160 comment) and that measurement should land before the switch is flipped anywhere real.
  • No new crate dependencies; nothing under crates/ gains a Postgres, async-runtime, or TLS dependency.

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

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@kiwidream

Copy link
Copy Markdown
Member Author

Update — review findings addressed

Two 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:

a211515 — three degraded-mode defects (this PR's review).

  • The deadline was computed before an untimed blocking lock acquire, so a prepare queued behind a slow build timed out on its first write and was treated as a daemon anomaly — SIGKILLing a healthy daemon and forcing a full DB walk, fold and upload. Now a lock-wait degrades (busy / window_daemon_busy) instead of retiring.
  • A lazily-raised DaemonWindowMirrorDivergence was routed nowhere: it escaped the build, was caught by no anomaly handler, and left the daemon's stdin holding a half-written request that poisoned the next one. record_count is now verified eagerly against the mirror bytes, escaping divergences route to cache invalidation plus a window_mirror_divergence event, and a half-written request retires the daemon on any exception.
  • The daemon's epoch tag evicted prepared windows the coordinator's own policy would have retagged, so every global bump forced a needs_full full rescan where Python advanced in place — under a replay burst, every 60 s re-anchor. The tag is now diagnostic only.

Eight regression tests, each proven failing at the base commit.

1c6b85d — adapter wiring and the integer-width contract.
The daemon already rejected correctly, but only through human-readable error strings, so the parity adapter read a correct rejection as a harness error. A stable machine-readable category now travels on the wire and maps to the oracle's rejection vocabulary.

On integer width: the corpus's new wide-integer cases exceed u128, which the daemon previously met with a serde parse failure — retiring it, so a single out-of-range value meant a permanent spawn-and-kill loop. The contract is narrowed to the Rust widths rather than widening Rust to arbitrary precision: at a mainnet-scale target a share is ~2^98 and a 16× window ~2^102, roughly 6×10^7 short of 2^128, and bignum arithmetic would land on the exact fold this migration exists to make faster. numeric(78,0) is a generic column width, not a considered contract.

That is modelled honestly as a narrower domain, not a divergence: the daemon answers out_of_range (distinct from malformed, with checked accumulators), the coordinator degrades to the in-process Python fold, and the oracle records the case as Unsupported while still holding the backend to Python's frozen bytes everywhere inside the declared domain.

Verification after all three commits

  • Parity oracle: 29 tests green under both adapters; 35 cases resolve as 21 outputs / 12 rejections / 2 unsupported, no errors.
  • Width protection re-confirmed independently: u32-, u64- and u128-truncating backends are each caught by the real oracle suite, so retuning wide-integers to sit inside the declared widths did not hollow out the case it was added for.
  • Five required Python suites: 334 tests OK. cargo test --locked --workspace --all-targets: 236 passed, 0 failed.
  • Full discovery: 2383 tests, failing only the five test_prism_job_builder os.splice tests that are Linux-only and fail identically on the base commit.
  • Docker lint clean (compileall, bash -n, shellcheck -x).

Rebased onto 2.x.x at 31a4708; #151's own landing-epoch suite passes alongside this work.

@kiwidream
kiwidream changed the base branch from window-pipeline-parity-oracle to 2.x.x August 20, 2026 16:43
kiwidream and others added 3 commits August 20, 2026 12:44
… 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]>
@kiwidream
kiwidream force-pushed the move-window-fold-into-serve-daemon branch from 1c6b85d to e4064e8 Compare August 20, 2026 16:48
@kiwidream

Copy link
Copy Markdown
Member Author

Rebased onto 2.x.x at 75abc17 now that #165 has merged.

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 2.x.x, while the branch still carried the two now-upstream parity commits. Rebasing just the three slice commits onto the merged tip resolves it with no conflict resolution required.

This also carries the PR across four 2.x.x commits that landed in the meantime — #167, #168, #170 and #171, including the writer-lease read-only enforcement and the first-job admission-lock convoy removal. None collided with this work.

Re-verified on the rebased branch:

  • Parity oracle 29 tests green under both the python and rust-daemon adapters, corpus still 35 cases (21 outputs / 12 rejections / 2 unsupported).
  • 387 tests across test_prism_window_pipeline_rust, test_prism_payout_state, test_prism_landing_append_epoch, test_prism_share_ledger, test_prism_incremental_payout_window, test_prism_coordinator_metrics.
  • cargo test --locked --workspace --all-targets: 236 passed, 0 failed.
  • Full discovery 2432 tests, failing only the five test_prism_job_builder os.splice tests that are Linux-only and fail identically on the base commit.
  • Docker lint clean (compileall, bash -n, shellcheck -x).

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant