diff --git a/cascade/validator/lane_d.py b/cascade/validator/lane_d.py index dfd0afe8..77bbf24e 100644 --- a/cascade/validator/lane_d.py +++ b/cascade/validator/lane_d.py @@ -618,6 +618,30 @@ def _keeps_hold(rec: dict, state: dict) -> bool: return True +def held_gate_digests(state: dict, cfg, boundary: int) -> list[str]: + """Owner 2026-12-01 (timing only): the digests a settlement at + ``boundary`` would re-gate as held (:func:`_held_candidates` and the held + house entry), read from ``state`` WITHOUT changing it. The box uses it + to start their bench sweep ahead of the scoring phase + (:meth:`~cascade.validator.lane_d_bench.SweepSession.prefetch`); the + settlement still decides its candidates itself, so a digest named here + and not gated costs a sweep, never a different record.""" + if _closing(cfg, boundary): + return [] + king = state["king"]["digest"] + + def held(rec) -> bool: + hold = rec.get("gate_hold") if isinstance(rec, dict) else None + return (rec["status"] in OPEN_STATUSES and bool(hold) + and hold["king_d"] == king) + + out = [dg for dg, rec in sorted(state["entries"].items()) if held(rec)] + house_rec = state.get(HOUSE_ENTRY_KEY) if state["king"].get("house") else None + if house_rec is not None and held(house_rec): + out.append(str(state["house"]["digest"])) + return out + + def _ranked(cands: list[dict]) -> list[dict]: """Max-T order: highest LCB first, then the earlier reveal, then digest.""" return sorted(cands, key=lambda c: (-c["lcb"], c["reveal_ts"], c["digest"])) @@ -2382,5 +2406,5 @@ def absent_settlement(*, cfg, boundary: int, state_path, house: dict, reason: st receipt=receipt) -__all__ = ["LaneDSettlement", "absent_settlement", "judge_cohort", "load_pool", - "settle_lane_d", "window_id"] +__all__ = ["LaneDSettlement", "absent_settlement", "held_gate_digests", "judge_cohort", + "load_pool", "settle_lane_d", "window_id"] diff --git a/cascade/validator/lane_d_bench.py b/cascade/validator/lane_d_bench.py index f7f0bd8c..690fa098 100644 --- a/cascade/validator/lane_d_bench.py +++ b/cascade/validator/lane_d_bench.py @@ -24,7 +24,12 @@ :class:`SweepSession` wraps the bench host's sweep: every digest a session has not swept yet goes out in one deduplicated host call, and cached rows are -re-used only within that session. +re-used only within that session. :meth:`SweepSession.prefetch` (owner +2026-12-01, timing only) sweeps digests known at the start of a settlement +(the held gate candidates, KING_D, the house) ahead of the gate; the gate's +:meth:`SweepSession.paired` adopts a prefetched digest only when its suites +and effective context are exactly those the gate asks for, so the records +the gate decides on are the ones a sequential sweep returns. Pure apart from the injected host sweep: no process-local state (no ``hash()``), so every validator computes the same JSON. Wiring into @@ -35,6 +40,7 @@ import copy import math +import threading from collections.abc import Callable, Iterable, Mapping, MutableMapping from typing import Any @@ -503,6 +509,11 @@ def __init__(self, session_id: str, sweep: Sweep, self._sweep = sweep store = {} if cache is None else cache self._rows: dict[str, dict[str, Any]] = store.setdefault(session_id, {}) + # One host sweep at a time per session: the gate's ``paired`` waits for + # a running ``prefetch`` (one sidecar on the bench host). + self._lock = threading.Lock() + # {digest: (context, suites, {suite: entry})}: prefetched, not adopted yet + self._ahead: dict[str, tuple[int, tuple[str, ...], dict[str, Any]]] = {} @staticmethod def _suites(suites: Iterable[str]) -> tuple[str, ...]: @@ -518,6 +529,69 @@ def _suites(suites: Iterable[str]) -> tuple[str, ...]: raise ValueError("at least one suite is required") return tuple(out) + def prefetch(self, digests: Iterable[str], suites: Iterable[str], *, + contexts: Mapping[str, int]) -> tuple[str, ...]: + """Owner 2026-12-01 (timing only): sweep ``digests`` for ``suites`` in + one host call at the contexts given, ahead of :meth:`paired`. Nothing + is decided here: the rows are held aside and :meth:`paired` adopts a + digest's rows only when the suites it asks for are exactly + ``suites`` (same order) and the host's settlement context for the + digest (``sweep.context_of``) equals the context swept here; + otherwise the gate sweeps that digest itself, as without a prefetch. + A reply missing any digest or suite, or naming another suite, keeps + nothing. Raises on any failure (the caller falls back to the + sequential sweep). Returns the digests held aside.""" + wanted = self._suites(suites) + if isinstance(digests, (str, bytes)): + raise TypeError(f"digests must be a sequence of digests; got {digests!r}") + ds: list[str] = [] + for dg in digests: + if not isinstance(dg, str) or not dg: + raise ValueError(f"digest {dg!r} is not a non-empty str") + if dg not in ds: + ds.append(dg) + if not ds: + return () + if not callable(getattr(self._sweep, "context_of", None)): + raise TypeError("prefetch needs a host sweep with context_of (the settlement's " + "contexts the gate sweeps at)") + ctx = {dg: int(contexts[dg]) for dg in ds} + with self._lock: + got = self._sweep(tuple(ds), wanted, contexts=dict(ctx)) + if not isinstance(got, Mapping): + raise TypeError(f"host sweep returned {type(got).__name__}, not a mapping") + kept: dict[str, tuple[int, tuple[str, ...], dict[str, Any]]] = {} + for dg in ds: + per = got.get(dg) + if (not isinstance(per, Mapping) or set(per) != set(wanted) + or not all(isinstance(e, Mapping) for e in per.values())): + raise ValueError(f"prefetch reply for {dg[:16]} does not carry exactly " + f"{list(wanted)}") + kept[dg] = (ctx[dg], wanted, + {s: copy.deepcopy(dict(e)) for s, e in per.items()}) + self._ahead.update(kept) + return tuple(ds) + + def _adopt(self, order: list[str], wanted: tuple[str, ...]) -> None: + """Move each prefetched digest of ``order`` into this session's rows + when it was swept for exactly ``wanted`` at the host's settlement + context; a prefetched digest that does not match is dropped (the + caller sweeps it). Called under ``_lock``.""" + if not self._ahead: + return + context_of = getattr(self._sweep, "context_of", None) + for dg in order: + ahead = self._ahead.pop(dg, None) + if ahead is None or dg in self._rows: + continue + ctx, suites, rows = ahead + try: + now = context_of(dg) if callable(context_of) else None + except Exception: # noqa: BLE001 — no context: the gate sweeps it itself + now = None + if suites == wanted and now is not None and int(now) == ctx: + self._rows[dg] = rows + def _record(self, dg: str) -> dict: return {"session": self.session_id, "digest": dg, "suites": copy.deepcopy(self._rows.get(dg, {}))} @@ -534,21 +608,23 @@ def paired(self, candidate: str, king_d: str, house: str, *, raise ValueError(f"{name} digest must be a non-empty str; got {dg!r}") if dg not in order: order.append(dg) - todo = [dg for dg in order - if not all(s in self._rows.get(dg, {}) for s in wanted)] - if todo: - got = self._sweep(tuple(todo), wanted) - if not isinstance(got, Mapping): - raise TypeError(f"host sweep returned {type(got).__name__}, not a mapping") - for dg in todo: - per = got.get(dg) - if not isinstance(per, Mapping): - continue - slot = self._rows.setdefault(dg, {}) - for s, entry in per.items(): - if isinstance(s, str) and isinstance(entry, Mapping): - slot[s] = copy.deepcopy(dict(entry)) - return self._record(candidate), self._record(king_d), self._record(house) + with self._lock: + self._adopt(order, wanted) + todo = [dg for dg in order + if not all(s in self._rows.get(dg, {}) for s in wanted)] + if todo: + got = self._sweep(tuple(todo), wanted) + if not isinstance(got, Mapping): + raise TypeError(f"host sweep returned {type(got).__name__}, not a mapping") + for dg in todo: + per = got.get(dg) + if not isinstance(per, Mapping): + continue + slot = self._rows.setdefault(dg, {}) + for s, entry in per.items(): + if isinstance(s, str) and isinstance(entry, Mapping): + slot[s] = copy.deepcopy(dict(entry)) + return self._record(candidate), self._record(king_d), self._record(house) __all__ = ["CLASSES", "FAULT_CODES", "HOLD_CODES", "INFRA_CODES", "KNOWN_SUITES", "METRICS", diff --git a/cascade/validator/lane_d_bench_host.py b/cascade/validator/lane_d_bench_host.py index 47f731f9..4fbb31bb 100644 --- a/cascade/validator/lane_d_bench_host.py +++ b/cascade/validator/lane_d_bench_host.py @@ -134,9 +134,12 @@ def _aggregates(reply: dict, digests: list[str]) -> dict: if isinstance(s, str) and isinstance(a, dict)} for dg, per in raw.items() if dg in digests and isinstance(per, dict)} - def __call__(self, digests, suites) -> dict: + def __call__(self, digests, suites, *, contexts: Mapping[str, int] | None = None) -> dict: + """The gate's sweep. ``contexts`` overrides the settlement's map (the + held-candidate prefetch, swept before the settlement sets it; owner + 2026-12-01); the rows are the same call's either way.""" ds = [str(d) for d in digests] - return self._checked(self._sweep(ds, [str(s) for s in suites]), ds) + return self._checked(self._sweep(ds, [str(s) for s in suites], contexts=contexts), ds) def sweep_full(self, digests, suites, *, contexts: Mapping[str, int] | None = None, timeout_s: float | None = None) -> dict: diff --git a/cascade/validator/lane_d_inputs.py b/cascade/validator/lane_d_inputs.py index 4767170d..6ea17cea 100644 --- a/cascade/validator/lane_d_inputs.py +++ b/cascade/validator/lane_d_inputs.py @@ -476,6 +476,51 @@ def bench(self, boundary: int): return SweepSession(f"{BENCH_SESSION_PREFIX}/{int(boundary)}", self._bench_host) + def gate_prefetch(self, boundary: int) -> dict | None: + """Owner 2026-12-01 (timing only): what the box may sweep on the bench + host while the eval host scores, ``{"digests": (held..., KING_D, the + house), "contexts": {digest: effective context}}``: the gate's held + candidates (:func:`~cascade.validator.lane_d.held_gate_digests`) + with the references every gate sweep pairs them with, at the + contexts :meth:`_needed` gives this settlement (the map ``__call__`` + hands the bench host). ``None`` with no bench host, lane D inactive, + the boundary already settled, no held candidate, or any read failing + (the gate then sweeps as before). Reads only; never raises.""" + if self._bench_host is None: + return None + b = int(boundary) + try: + if self._cfg_at is not None: + self.cfg = self._cfg_at(b) # what ``__call__`` sets for ``b`` + if not self.cfg.lane_d.active(b): + return None + house = self._house() + state = self._state(house) + if int(state["boundary"]) >= b: + return None + from .lane_d import held_gate_digests + + held = held_gate_digests(state, self.cfg.lane_d, b) + if not held: + return None + entries = self._entries(self._reader(), b) + armed = self._armed() + need, _ = self._needed(entries, state, house, tuple(armed["armed_contexts"])) + refs = [str(state["king"]["digest"]), str(state["house"]["digest"])] + if any(r not in need for r in refs): + return None + digests: list[str] = [] + for dg in [d for d in held if d in need] + refs: + if dg not in digests: + digests.append(dg) + if not any(d in need for d in held): + return None + return {"digests": tuple(digests), "contexts": {d: int(need[d]) for d in digests}} + except Exception as e: # noqa: BLE001 — timing only: the gate sweeps as before + log.info("lane_d_gate_prefetch settlement %d: no plan (%s: %s)", b, + type(e).__name__, e) + return None + # ── the reads, in order ───────────────────────────────────────────────── def _reader(self) -> Any: diff --git a/cascade/validator/lane_d_wiring.py b/cascade/validator/lane_d_wiring.py index 3fd37673..278ecdf3 100644 --- a/cascade/validator/lane_d_wiring.py +++ b/cascade/validator/lane_d_wiring.py @@ -11,6 +11,12 @@ thread's client); 3. with W-S1 armed for the boundary's era, the era-start block hash and the era's sentinel drawn from it; +3a. owner 2026-12-01 (timing only): when the boundary has held gate + candidates and a bench host, their gate sweep (with KING_D and the house) + starts on a background thread in the boundary's bench session, beside + the eval host's scoring; the gate in 6 adopts those rows only where the + suites and contexts match (``SweepSession.prefetch``), so the signed + report is the sequential one, byte for byte; 4. the last published lane D receipt (``RECEIPT_LATEST_KEY``), which binds the local state (``expect_prior_sha256``, W7c); 5. the settlement inputs (``inputs(boundary)``: pool snapshots, revealed @@ -262,6 +268,9 @@ def __init__(self, cfg: Any, *, state_dir: str | Path, signer: Any, self._courts: dict[int, list[int | None]] = {} self._genesis: dict[int, bool] = {} self._lock = threading.Lock() + # owner 2026-12-01: the held gate candidates' bench sweep started at + # the step's start, [boundary, session, thread, used] (None: none) + self._prefetch: list | None = None # ── the weight fold's read ────────────────────────────────────────────── @@ -366,6 +375,84 @@ def _bench_session(self, boundary: int) -> Any: "candidate is held", boundary, e) return None + def _start_gate_prefetch(self, boundary: int, block_hash: str, + sentinel: str | None) -> Any: + """Owner 2026-12-01 (timing only): at the step's start, sweep the + boundary's held gate candidates (and KING_D and the house) on the + bench host on a background thread while the eval host scores. Returns + the boundary's bench session doing it (the one the settlement then + gates with), or ``None``: no bench, no plan (no held candidate, + :meth:`~cascade.validator.lane_d_inputs.LaneDInputsSource. + gate_prefetch`), the king's full bench or an earlier prefetch still + on the host, or any failure; the gate then sweeps as before. Same + session id, suite draw, sentinel and contexts as the gate, and the + gate adopts a prefetched digest only when they match + (:meth:`~cascade.validator.lane_d_bench.SweepSession.prefetch`), so + the signed report is byte-identical either way.""" + b = int(boundary) + pending = self._prefetch + if pending is not None: + pb, session, thread, used = pending + if pb == b and not used: + return session # a retried tick: the same sweep, never a second + if thread.is_alive(): + log.info("lane_d_gate_prefetch settlement %d: skipped (the settlement %d " + "prefetch is still on the bench host)", b, pb) + return None + self._prefetch = None + plan_of = getattr(self._inputs, "gate_prefetch", None) + if self._bench is None or not callable(plan_of): + return None + kb = self._king_bench + try: + if kb is not None and getattr(kb, "running", None): + log.info("lane_d_gate_prefetch settlement %d: skipped (the king's full bench " + "is on the bench host)", b) + return None + plan = plan_of(b) + if not plan or not plan.get("digests"): + return None + session = self._bench(b) + if session is None or not callable(getattr(session, "prefetch", None)): + return None + from .lane_d_gate import gate_record + + suite = gate_record(self.cfg.lane_d, b, block_hash, sentinel=sentinel)["suite"] + suites = (suite,) if sentinel is None else (suite, str(sentinel)) + digests = tuple(plan["digests"]) + contexts = dict(plan["contexts"]) + except Exception as e: # noqa: BLE001 — timing only: the gate sweeps as before + log.warning("lane_d_gate_prefetch settlement %d: not started (%s: %s)", b, + type(e).__name__, e) + return None + + def run() -> None: + try: + kept = session.prefetch(digests, suites, contexts=contexts) + log.info("lane_d_gate_prefetch settlement %d: swept %d digest(s) ahead of the " + "gate", b, len(kept)) + except Exception as e: # noqa: BLE001 — the gate sweeps them itself + log.warning("lane_d_gate_prefetch_failed settlement %d: %s: %s; the gate sweeps " + "in order", b, type(e).__name__, e) + + thread = threading.Thread(target=run, name="lane-d-gate-prefetch", daemon=True) + try: + thread.start() + except Exception as e: # noqa: BLE001 + log.warning("lane_d_gate_prefetch settlement %d: could not start (%s)", b, e) + return None + log.info("lane_d_gate_prefetch settlement %d: started (%d digest(s) incl. KING_D and " + "the house, suites %s)", b, len(digests), list(suites)) + self._prefetch = [b, session, thread, False] + return session + + def _await_prefetch(self) -> None: + """Wait for a running prefetch to leave the bench host (one sweep on + it at a time); its own SSH timeout bounds the wait.""" + pending = self._prefetch + if pending is not None: + pending[2].join() + def _local_state(self, house: Mapping) -> dict: try: return load_state(self.state_path, dict(house)) @@ -758,6 +845,9 @@ def _produce(self, b: int) -> LaneDSettlement | None: except (TypeError, ValueError) as e: raise LaneDWiringError("settle_refused", f"era {era}: no sentinel draw ({e})") from e + # owner 2026-12-01: the held candidates' gate sweep runs while the + # eval host scores (timing only; see _start_gate_prefetch). + ahead = self._start_gate_prefetch(b, block_hash, sentinel) latest = self._latest_receipt() inp = self._read_inputs(b) picked_with = getattr(inp, "channel_block_hash", None) @@ -797,7 +887,12 @@ def _produce(self, b: int) -> LaneDSettlement | None: self._request_publication(b, s, None) self._publish_status(b, s, inp.house, era=era, era_hash=era_hash) return s - session = self._bench_session(b) + if ahead is not None: + session = ahead + self._prefetch[3] = True # used: a retry never reuses its rows + else: + self._await_prefetch() # a stale prefetch leaves the host first + session = self._bench_session(b) s = self._settle(b, inp, expect=None if latest is None else latest["posterior_state_sha256"], block_hash=block_hash, sentinel=sentinel, bench=session) @@ -807,6 +902,8 @@ def _produce(self, b: int) -> LaneDSettlement | None: self._publish(b, s) self._request_publication(b, s, record) self._publish_status(b, s, inp.house, era=era, era_hash=era_hash) + self._await_prefetch() # never beside the king's full bench + self._prefetch = None self._schedule_king_bench(b, inp) return s diff --git a/tests/accept/w8b/test_w8b_gate_prefetch.py b/tests/accept/w8b/test_w8b_gate_prefetch.py new file mode 100644 index 00000000..0e294a8a --- /dev/null +++ b/tests/accept/w8b/test_w8b_gate_prefetch.py @@ -0,0 +1,335 @@ +"""W8b x owner 2026-12-01: lane D's public-bench gate for ALREADY-HELD +candidates starts on the bench host as soon as the settlement step starts, +beside the scoring phase (the eval host's pool / public forecasts), instead +of after it. Timing only: the signed report, the gate record, the bound bench +records, the receipt and the state are byte-identical to the sequential +path; a prefetch that fails (or does not match the gate's suites / contexts) +leaves the gate sweeping in order, exactly as before; no held candidate or no +bench host means no prefetch; new clears are still gated. + +Real ``settle_lane_d`` runs on W7a's synthetic chain through the W8b rig. X +clears at B2 while the bench host is unreachable (``bench_hold``), so at B3 +it is a held candidate re-gated without a duel. The bench host is a fake +(:class:`CtxHost`: W7a's healthy rows, the settlement's contexts, a +``contexts=`` override for the prefetch); the eval-host scoring is the +inputs call (:class:`PrefetchInputs`), which can block until a bench sweep is +observed. Nothing in PATHS is imported at module import time; a missing +feature on the base fails by assertion. +""" + +from __future__ import annotations + +import threading + +import pytest + +from . import helpers as h + +CTX = 4096 +WAIT_S = 5.0 + + +class CtxHost(h.BenchHost): + """The bench host with the settlement's contexts (``context_of``) and the + ``contexts=`` override the prefetch sends. ``prefetch_fault``: ``raise`` + (the host is lost), ``partial`` (a suite missing from the reply).""" + + def __init__(self, house_digest: str): + super().__init__(house_digest) + self.contexts: dict[str, int] = {} + self.prefetches: list[dict] = [] + self.gate_calls: list[tuple[tuple[str, ...], tuple[str, ...]]] = [] + self.seen = threading.Event() + self.prefetch_fault: str | None = None + self._busy = 0 + self._guard = threading.Lock() + self.overlap = False + + def set_contexts(self, contexts): + self.contexts = {str(d): int(c) for d, c in contexts.items()} + + def context_of(self, digest): + return self.contexts.get(str(digest), CTX) + + def __call__(self, digests, suites, *, contexts=None): + with self._guard: + self._busy += 1 + self.overlap = self.overlap or self._busy > 1 + try: + if contexts is None: + self.gate_calls.append((tuple(digests), tuple(suites))) + else: + self.prefetches.append({"digests": tuple(digests), "suites": tuple(suites), + "contexts": dict(contexts), + "thread": threading.get_ident()}) + self.seen.set() + if contexts is not None and self.prefetch_fault == "raise": + raise ConnectionError("w8b: bench host lost during the prefetch") + out = super().__call__(digests, suites) + if contexts is not None and self.prefetch_fault == "partial": + first = tuple(digests)[0] + out[first].pop(tuple(suites)[0]) + return out + finally: + with self._guard: + self._busy -= 1 + + +class PrefetchInputs(h.Inputs): + """The settlement inputs (the eval-host scoring), plus the source's + ``gate_prefetch`` plan read from the rig's state. ``wait``: the scoring + blocks until a bench sweep is observed (or ``WAIT_S``); ``plan``: offer + the plan at all; ``plan_ctx``: contexts the plan names (else ``CTX``).""" + + def __init__(self, fx, host: CtxHost, cfg, state_path, *, plan: bool = True): + super().__init__(fx) + self.host, self.cfg, self.state_path = host, cfg, state_path + self.plan = plan + self.wait_at: set[int] = set() + self.saw_bench: dict[int, bool] = {} + self.plan_calls: list[int] = [] + self.plan_ctx: dict[str, int] = {} + + def __call__(self, boundary): + if int(boundary) in self.wait_at: + self.saw_bench[int(boundary)] = self.host.seen.wait(WAIT_S) + out = super().__call__(boundary) + # the source hands the bench host each digest's effective context + self.host.set_contexts({d: CTX for d in (self.fx["x"], self.fx["house"]["digest"])}) + return out + + def gate_prefetch(self, boundary): + self.plan_calls.append(int(boundary)) + if not self.plan or not self.state_path.is_file(): + return None + from cascade.validator.lane_d import held_gate_digests + from cascade.validator.lane_d_state import load_state + + state = load_state(self.state_path, dict(self.fx["chain"]["house"])) + if int(state["boundary"]) >= int(boundary): + return None + held = held_gate_digests(state, self.cfg.lane_d, int(boundary)) + if not held: + return None + ds = [] + for d in held + [state["king"]["digest"], state["house"]["digest"]]: + if d not in ds: + ds.append(str(d)) + return {"digests": tuple(ds), "contexts": {d: self.plan_ctx.get(d, CTX) for d in ds}} + + +class PRig(h.Rig): + """The W8b rig over :class:`CtxHost` and :class:`PrefetchInputs`.""" + + def __init__(self, tmp, cfg, fx, *, plan: bool = True, bench: bool = True): + host = CtxHost(fx["house"]["digest"]) + state_dir = tmp / "lane_d" + inputs = PrefetchInputs(fx, host, cfg, state_dir / "lane_d_state.json", plan=plan) + super().__init__(tmp, cfg, fx, host=host, inputs=inputs, bench=bench, + state_dir=state_dir) + + def hold_then_regate(self): + """B1; B2 with the bench host unreachable (X held); B3 (X re-gated).""" + self.step(h.B1) + self.bench.fail = True + self.step(h.B2) + self.bench.fail = False + return self.step(h.B3) + + +def _features(): + from cascade.validator import lane_d + from cascade.validator.lane_d_bench import SweepSession + + assert hasattr(SweepSession, "prefetch"), "SweepSession has no prefetch (owner 2026-12-01)" + assert hasattr(lane_d, "held_gate_digests"), "lane_d has no held_gate_digests" + + +def _x_held_at_b2(rig): + rep = rig.published_report(h.B2) + assert rep["crowned"] is None, "fixture: X must be held at B2 (bench unreachable)" + assert rep.get("gate") is None or all(r["outcome"] == "bench_hold" + for r in rep["gate"]["results"]) + + +def _same_settlements(a, b, boundaries=(h.B1, h.B2, h.B3)): + from cascade.validator.lane_d import bench_rows_dir + + for bd in boundaries: + ra, rb = a.published_report(bd), b.published_report(bd) + assert h.body_sha256(ra) == h.body_sha256(rb), f"report body differs at {bd}" + assert ra.get("gate") == rb.get("gate"), f"gate record differs at {bd}" + assert a.published_receipt(bd) == b.published_receipt(bd), f"receipt differs at {bd}" + assert a.state_path.read_bytes() == b.state_path.read_bytes() + assert h.dir_bytes(bench_rows_dir(a.state_path)) == h.dir_bytes(bench_rows_dir(b.state_path)) + + +def test_the_held_gate_sweep_starts_before_the_scoring_finishes(tmp_path): + cfg = h.chain_cfg(tmp_path / "v", sentinel=False) + rig = PRig(tmp_path / "rig", cfg, h.fixture(tmp_path)) + rig.inputs.wait_at = {h.B3} + rig.step(h.B1) + rig.bench.fail = True + rig.step(h.B2) + _x_held_at_b2(rig) + rig.bench.fail = False + rig.host.seen.clear() + main = threading.get_ident() + rig.step(h.B3) + assert rig.inputs.saw_bench.get(h.B3) is True, \ + "no bench sweep was started while the eval host was still scoring" + assert rig.host.prefetches, "no prefetch call reached the bench host" + pre = rig.host.prefetches[0] + assert rig.fx["x"] in pre["digests"] and rig.fx["house"]["digest"] in pre["digests"] + assert pre["thread"] != main, "the prefetch ran on the step's thread (blocking)" + assert pre["contexts"] == {d: CTX for d in pre["digests"]} + rep = rig.published_report(h.B3) + assert rep["crowned"] == rig.fx["x"], "the held candidate was not crowned at its re-gate" + assert not rig.host.overlap, "two sweeps ran on the bench host at once" + + +@pytest.mark.parametrize("sentinel", [False, True]) +def test_report_bytes_identical_with_and_without_the_prefetch(tmp_path, sentinel): + _features() + cfg = h.chain_cfg(tmp_path / "v", sentinel=sentinel) + fx = h.fixture(tmp_path) + control = PRig(tmp_path / "control", cfg, fx, plan=False) + rig = PRig(tmp_path / "rig", cfg, fx) + control.hold_then_regate() + rig.hold_then_regate() + _x_held_at_b2(rig) + assert control.host.prefetches == [], "the control rig prefetched" + assert len(rig.host.prefetches) == 1, rig.host.prefetches + suites = rig.host.prefetches[0]["suites"] + gate = rig.published_report(h.B3)["gate"] + want = (gate["suite"],) + ((h.era_sentinel(cfg, h.B3),) if sentinel else ()) + assert suites == want, "the prefetch did not sweep the gate's own suite draw" + # the gate adopted the prefetched rows: X was not swept again for them + assert not any(rig.fx["x"] in ds and ss == suites for ds, ss in rig.host.gate_calls), \ + rig.host.gate_calls + assert rig.published_report(h.B3)["crowned"] == rig.fx["x"] + _same_settlements(rig, control) + + +@pytest.mark.parametrize("fault", ["raise", "partial", "context"]) +def test_a_failed_prefetch_falls_back_to_the_sequential_sweep(tmp_path, fault): + _features() + cfg = h.chain_cfg(tmp_path / "v", sentinel=False) + fx = h.fixture(tmp_path) + control = PRig(tmp_path / "control", cfg, fx, plan=False) + rig = PRig(tmp_path / "rig", cfg, fx) + if fault == "context": + rig.inputs.plan_ctx = {fx["x"]: 2048} # not the settlement's context + else: + rig.host.prefetch_fault = fault + control.hold_then_regate() + rig.hold_then_regate() + assert len(rig.host.prefetches) == 1, "no prefetch was attempted" + assert any(rig.fx["x"] in ds for ds, _ in rig.host.gate_calls), \ + "the gate did not sweep the held candidate itself after a failed prefetch" + assert rig.published_report(h.B3)["crowned"] == rig.fx["x"] + _same_settlements(rig, control) + + +def test_no_prefetch_without_a_held_candidate(tmp_path): + _features() + cfg = h.chain_cfg(tmp_path / "v", sentinel=False) + rig = PRig(tmp_path / "rig", cfg, h.fixture(tmp_path)) + rig.step(h.B1) + rig.step(h.B2) # X is a NEW clear: gated, crowned, no prefetch + assert rig.published_report(h.B2)["crowned"] == rig.fx["x"], "the new clear was not gated" + assert any(rig.fx["x"] in ds for ds, _ in rig.host.gate_calls) + rig.step(h.B3) + assert rig.host.prefetches == [], "a prefetch ran with no held candidate" + assert h.B2 in rig.inputs.plan_calls, "the step never asked the source for a prefetch plan" + + +def test_no_prefetch_without_a_bench_host(tmp_path): + _features() + from cascade.validator.lane_d_inputs import LaneDInputsSource + + cfg = h.chain_cfg(tmp_path / "v", sentinel=False) + rig = PRig(tmp_path / "rig", cfg, h.fixture(tmp_path), bench=False) + rig.step(h.B1) + rig.step(h.B2) + rig.step(h.B3) + assert rig.host.prefetches == [] and rig.host.gate_calls == [] + assert rig.inputs.plan_calls == [], "a plan was read with no bench configured" + src = LaneDInputsSource.__new__(LaneDInputsSource) + src._bench_host = None + assert src.gate_prefetch(h.B3) is None + + +def test_held_gate_digests_names_the_settlements_held_candidates_without_mutating(tmp_path): + _features() + import copy + + from cascade.validator.lane_d import _held_candidates, held_gate_digests + from cascade.validator.lane_d_state import load_state + + cfg = h.chain_cfg(tmp_path / "v", sentinel=False) + rig = PRig(tmp_path / "rig", cfg, h.fixture(tmp_path), plan=False) + rig.step(h.B1) + rig.bench.fail = True + rig.step(h.B2) + state = load_state(rig.state_path, dict(rig.fx["chain"]["house"])) + before = copy.deepcopy(state) + got = held_gate_digests(state, cfg.lane_d, h.B3) + assert state == before, "held_gate_digests changed the state" + assert got == [rig.fx["x"]] == _held_candidates(copy.deepcopy(state)) + # a hold taken under another KING_D is not re-gated: not prefetched either + other = copy.deepcopy(state) + other["entries"][rig.fx["x"]]["gate_hold"]["king_d"] = "0" * 64 + assert held_gate_digests(other, cfg.lane_d, h.B3) == [] + + +def test_new_clears_are_swept_beside_the_prefetched_held_rows(): + """Session level: a prefetch of a held H, KING_D and the house; the gate + then sweeps only a NEW clear N (H, KING_D, the house come from the + prefetch), and every record equals a sequential session's.""" + _features() + from cascade.validator.lane_d_bench import SweepSession + + held, new, king, house = "aa" * 32, "bb" * 32, "cc" * 32, "dd" * 32 + suites = ("gift", "boom") + + def run(prefetch: bool): + host = CtxHost(house) + s = SweepSession("w8b-prefetch/1", host) + if prefetch: + s.prefetch([held, king, house], suites, contexts={held: CTX, king: CTX, house: CTX}) + recs = [s.paired(new, king, house, suites=suites), s.paired(held, king, house, + suites=suites)] + return host, recs + + host, recs = run(True) + seq_host, seq = run(False) + assert recs == seq + assert host.gate_calls == [((new,), suites)], host.gate_calls + assert seq_host.gate_calls == [((new, king, house), suites), ((held,), suites)] + + +def test_the_gate_waits_for_a_running_prefetch(): + """One sweep on the bench host at a time: the gate's paired call waits + for the prefetch in flight, then adopts its rows.""" + _features() + from cascade.validator.lane_d_bench import SweepSession + + held, king, house = "aa" * 32, "cc" * 32, "dd" * 32 + host = CtxHost(house) + host.hang = True + s = SweepSession("w8b-prefetch/2", host) + t = threading.Thread(target=s.prefetch, args=([held, king, house], ("gift",)), + kwargs={"contexts": {held: CTX, king: CTX, house: CTX}}) + t.start() + assert host.started.wait(WAIT_S) + out = [] + g = threading.Thread(target=lambda: out.append(s.paired(held, king, house, + suites=("gift",)))) + g.start() + g.join(0.3) + assert g.is_alive(), "the gate swept while the prefetch was on the host" + host.release.set() + t.join(WAIT_S) + g.join(WAIT_S) + assert out and not host.overlap and host.gate_calls == []