diff --git a/cascade/validator/lane_d.py b/cascade/validator/lane_d.py index 4f584dd15..b28e417ee 100644 --- a/cascade/validator/lane_d.py +++ b/cascade/validator/lane_d.py @@ -161,6 +161,7 @@ from __future__ import annotations +import copy import hashlib import json import math @@ -650,6 +651,44 @@ def held(rec) -> bool: return out +def judged_digests(*, cfg, boundary: int, boundary_ts, state: dict, house: dict, + entries: list[dict], uid_of: dict, armed: dict | None) -> dict | None: + """Owner 2026-12-01 ("it doesn't need live and public benchmark again"): + which digests a settlement at ``boundary`` duels, decided BEFORE any + forecast is asked, so the eval host forecasts those and nothing else. + + Runs the settlement's own selection (:func:`_choose`: registration, the + held gate candidates, the queue, the armed context and the judging + start) on a deep copy of ``state`` after the settlement's own + :func:`~cascade.validator.lane_d_state.migrate_confirm_pending` and + :func:`~cascade.validator.lane_d_state.refresh_house`; ``state`` is + never changed. No forecast exists yet, so no member is a + ``checkpoint_fault`` here: the duelled set is a superset of what the + settlement duels (a member it closes on its forecasts was forecast, as + before), never a subset. + + Returns ``{"duel": [digest...], "king_d": digest}``: the duelled miner + members plus the house challenger when its cohort runs, and the KING_D + the cohorts are judged against (a duel needs its forecasts too). + ``duel`` empty: nobody is duelled (only held candidates re-gate, from + the bench), so no live forecast is read. ``None`` when lane D does not + settle at ``boundary`` or it is already settled (the caller then asks + as before).""" + if not cfg.active(boundary) or int(state["boundary"]) >= int(boundary): + return None + st = copy.deepcopy(state) + migrate_confirm_pending(st) + refresh_house(st, check_house(dict(house))) + armed_fields = None if armed is None else check_armed(armed, cfg) + sel = _choose(st, cfg, int(boundary), boundary_ts, copy.deepcopy(list(entries)), + dict(uid_of), armed_fields, lambda _dg: False) + duel = list(sel["chosen"]) + # the house challenger's cohort runs under exactly _judge_pools' condition + if sel["house_open"] and not sel["house_held"] and not st["king"].get("house"): + duel.append(sel["hd"]) + return {"duel": sorted(set(duel)), "king_d": str(st["king"]["digest"])} + + 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"])) @@ -1464,43 +1503,17 @@ def bad(why: str): "armed_evidence": json.loads(json.dumps(ev, allow_nan=False))} -def _judge_pools(*, cfg, boundary: int, boundary_ts, boundary_block_hash, max_channels, - armed_fields, state: dict, entries: list[dict], uid_of: dict, forecasts, - pools: list[dict], pub, crown_bar: float) -> dict: - """The pool phase of :func:`settle_lane_d` (W-OFFBOX, 2026-11-28): every - step that reads a ``pool_d`` window (the channel pick, the forecast - checks, the frozen sets, the cohort draws, the per-window scores), from - the registration through the last cohort's verdicts. Mutates ``state`` - and returns the judged record (plain JSON types only, :func:`remote_judge` - carries it): ``state``, ``skipped``, ``held``, ``house_held``, ``seed``, - ``rows``, ``windows_out``, ``cohorts``, ``verdicts``, ``draws``, - ``candidates``, ``pub_scored`` and ``pool_rec``. - - The validator box runs it in-process only on budget-sized pools - (:data:`~cascade.validator.lane_d_inputs.BOX_POOL_BUDGET_BYTES`); the lane D - eval host runs it for the live settlement - (:func:`cascade.eval.lane_d_settle.serve_settle`), where the pools and - the forecasts already are. The code is the pre-W-OFFBOX body, unchanged.""" - pub_arr: dict[str, object] = {} - - def pub_of(dg: str): - if pub is None: - return True - if dg not in pub_arr: - pub_arr[dg] = _public_arrays(pub, dg) - return pub_arr[dg] - - # rev6.18 A4 (F2): multichannel windows reduced to their scored channels - # (a no-op on a univariate pool). - picks = _pick_channels(pools, boundary_block_hash, max_channels) - pool = pools[-1] - pool_ids = _pool_window_ids(pools) - # owner 2026-11-27: each pool window's own horizon (the fixed one off bands) - pool_h = {w["window_id"]: window_horizon(w, cfg) for p in pools for w in p["windows"] - if w["window_id"]} - seed = f"lane-d/1:{boundary}:{pool['sha256']}" - # T18e: the max_source_share drop is seeded by the settlement alone. - cap_seed = f"lane-d/1:cap:{boundary}" +def _choose(state: dict, cfg, boundary: int, boundary_ts, entries: list[dict], uid_of: dict, + armed_fields, faulty) -> dict: + """The selection step of :func:`_judge_pools`: registration, the held gate + candidates, the queue, the forecast checks (``faulty(digest)``: the + member's forecasts are malformed on a pool window or its public half is + not finite), the armed context and the judging start. Mutates ``state`` + and returns ``skipped``, ``held``, ``house_held``, ``chosen`` (the miner + members duelled), ``house_open``, ``house_rec`` and ``hd``. + :func:`judged_digests` runs it on a copy of the state, before any + forecast exists, to know which digests the settlement duels (owner + 2026-12-01).""" # Every entry considered and not judged is a typed skip, including the # entries voided this settlement (invariant 11). skipped = _register(state, entries, cfg, uid_of) @@ -1549,9 +1562,7 @@ def skip(dg: str, reason: str, rec: dict | None = None) -> None: # A member whose forecasts are malformed on any pool window is the miner's fault # (the house's own: its entry closes, fail closed). for dg in list(chosen): - fc = forecasts.get(dg) - if (fc is not None and any(_fc_ok(fc, wid, pool_h[wid], picks) is False - for wid in sorted(pool_ids))) or pub_of(dg) is False: + if faulty(dg): state["entries"][dg]["status"] = "closed" skip(dg, "checkpoint_fault") chosen.remove(dg) @@ -1581,13 +1592,70 @@ def skip(dg: str, reason: str, rec: dict | None = None) -> None: if why is not None: skip(hd, why, house_rec) house_open = False - if house_open and not house_held: - fc = forecasts.get(hd) - if (fc is not None and any(_fc_ok(fc, wid, pool_h[wid], picks) is False - for wid in sorted(pool_ids))) or pub_of(hd) is False: - house_rec["status"] = "closed" - skip(hd, "checkpoint_fault", house_rec) - house_open = False + if house_open and not house_held and faulty(hd): + house_rec["status"] = "closed" + skip(hd, "checkpoint_fault", house_rec) + house_open = False + return {"skipped": skipped, "held": held, "house_held": house_held, "chosen": chosen, + "house_open": house_open, "house_rec": house_rec, "hd": hd} + + +def _judge_pools(*, cfg, boundary: int, boundary_ts, boundary_block_hash, max_channels, + armed_fields, state: dict, entries: list[dict], uid_of: dict, forecasts, + pools: list[dict], pub, crown_bar: float) -> dict: + """The pool phase of :func:`settle_lane_d` (W-OFFBOX, 2026-11-28): every + step that reads a ``pool_d`` window (the channel pick, the forecast + checks, the frozen sets, the cohort draws, the per-window scores), from + the registration through the last cohort's verdicts. Mutates ``state`` + and returns the judged record (plain JSON types only, :func:`remote_judge` + carries it): ``state``, ``skipped``, ``held``, ``house_held``, ``seed``, + ``rows``, ``windows_out``, ``cohorts``, ``verdicts``, ``draws``, + ``candidates``, ``pub_scored`` and ``pool_rec``. + + The validator box runs it in-process only on budget-sized pools + (:data:`~cascade.validator.lane_d_inputs.BOX_POOL_BUDGET_BYTES`); the lane D + eval host runs it for the live settlement + (:func:`cascade.eval.lane_d_settle.serve_settle`), where the pools and + the forecasts already are. The code is the pre-W-OFFBOX body, unchanged.""" + pub_arr: dict[str, object] = {} + + def pub_of(dg: str): + if pub is None: + return True + if dg not in pub_arr: + pub_arr[dg] = _public_arrays(pub, dg) + return pub_arr[dg] + + # rev6.18 A4 (F2): multichannel windows reduced to their scored channels + # (a no-op on a univariate pool). + picks = _pick_channels(pools, boundary_block_hash, max_channels) + pool = pools[-1] + pool_ids = _pool_window_ids(pools) + # owner 2026-11-27: each pool window's own horizon (the fixed one off bands) + pool_h = {w["window_id"]: window_horizon(w, cfg) for p in pools for w in p["windows"] + if w["window_id"]} + seed = f"lane-d/1:{boundary}:{pool['sha256']}" + # T18e: the max_source_share drop is seeded by the settlement alone. + cap_seed = f"lane-d/1:cap:{boundary}" + + def faulty(dg: str) -> bool: + fc = forecasts.get(dg) + return bool((fc is not None and any(_fc_ok(fc, wid, pool_h[wid], picks) is False + for wid in sorted(pool_ids))) + or pub_of(dg) is False) + + sel = _choose(state, cfg, boundary, boundary_ts, entries, uid_of, armed_fields, faulty) + skipped, held, house_held = sel["skipped"], sel["held"], sel["house_held"] + chosen, house_open, house_rec, hd = (sel["chosen"], sel["house_open"], sel["house_rec"], + sel["hd"]) + + def skip(dg: str, reason: str, rec: dict | None = None) -> None: + (state["entries"][dg] if rec is None else rec)["reason"] = reason + if rec is not None and rec is house_rec: + # The house entry is not a listed entry: its reason is kept in + # state, never a typed ``skipped`` record (which names entries). + return + skipped.append({"digest": dg, "reason": reason}) # rev6.11 (b): every member is judged at its first (and only) verdict # against the current KING_D: one miner cohort, then the house challenger diff --git a/cascade/validator/lane_d_inputs.py b/cascade/validator/lane_d_inputs.py index 3e2019656..358e4d91e 100644 --- a/cascade/validator/lane_d_inputs.py +++ b/cascade/validator/lane_d_inputs.py @@ -768,6 +768,44 @@ def put(dg: str, c: int | None, *, replace: bool = False) -> None: "(no declared context)") return ctx, frozenset(bars) + def _judged(self, b: int, need: dict[str, int], entries: list[dict], state: dict, + house: dict, boundary_ts: int, uid_of: dict, armed: dict + ) -> tuple[dict[str, int], dict[str, int]]: + """Owner 2026-12-01 ("it doesn't need live and public benchmark + again"): ``(live, public)``, the part of :meth:`_needed`'s ``need`` + the eval host forecasts this settlement. ``live`` is the digests the + settlement duels (:func:`~cascade.validator.lane_d.judged_digests`: + the queue's members after the held, armed-context and judging-start + exclusions, the house challenger when its cohort runs) plus KING_D; + empty when nobody is duelled (only held candidates re-gate, from the + bench). ``public`` is ``live`` plus KING_D always: the signed report's + public record carries the eval host's read-time drops, which one + digest's public reply gives. A held, lost, closed, before-delay or + below-armed entry is never forecast. Any failure of the prediction + asks for the whole ``need``, as before (never a missing forecast).""" + from .lane_d import judged_digests + + try: + got = judged_digests(cfg=self.cfg.lane_d, boundary=b, boundary_ts=boundary_ts, + state=state, house=house, entries=entries, + uid_of=uid_of, armed=armed) + except Exception as e: # noqa: BLE001 — ask for everything, as before + log.warning("lane_d_forecast_plan settlement %d: no plan, forecasting every " + "needed digest (%s: %s)", b, type(e).__name__, e) + got = None + if got is None: + return dict(need), dict(need) + kd = got["king_d"] + want = set(got["duel"]) | ({kd} if got["duel"] else set()) + live = {dg: int(need[dg]) for dg in sorted(want) if dg in need} + public = dict(live) + if kd in need: + public[kd] = int(need[kd]) + log.info("lane_d_forecast_plan settlement %d: %d of %d needed digest(s) forecast " + "live, %d on the public half (duelled %d)", b, len(live), len(need), + len(public), len(got["duel"])) + return live, dict(sorted(public.items())) + def _windows(self, pools: list[tuple[Path, dict]], boundary: int | None = None, bound_lo: float | None = None) -> list[dict]: """Every pinned window (:func:`pinned_windows`); the boundary's block @@ -973,7 +1011,11 @@ def _offloaded(self, reader: Any, b: int, entries: list[dict], boundary_ts: int, if not callable(getattr(self._eval_host, "settle", None)): raise LaneDInputsError("forecasts_unavailable", "settle_on_host: the eval host cannot settle") - public_indexes, public_scores = self._public(reader, b, need, bars, ctxs) + live, pub_need = self._judged(b, need, entries, state, house, boundary_ts, uid_of, + armed) + public_indexes, public_scores = self._public(reader, b, pub_need, bars, ctxs) + # the bench host sweeps at every needed context (the gate's held + # candidates are not forecast, but they are swept) set_contexts = getattr(self._bench_host, "set_contexts", None) if callable(set_contexts): set_contexts(dict(need)) @@ -990,11 +1032,11 @@ def _offloaded(self, reader: Any, b: int, entries: list[dict], boundary_ts: int, cap = int(getattr(getattr(self.cfg, "generator", None), "max_channels", 1) or 1) judge = HostJudge(self._eval_host, boundary=b, pins=[ {"snapshot": Path(p["dir"]).name, "sha256": str(p["sha256"])} for p in pins], - need=need, bars=bars, cap=cap, bound_lo=bound_lo, block_hash=block_hash, + need=live, bars=bars, cap=cap, bound_lo=bound_lo, block_hash=block_hash, pinned={"king_d": str(state["king"]["digest"]), "house": str(house["digest"])}, armed=[int(c) for c in ctxs], score_ns=host_ns) dirs = [Path(p["dir"]) for p in pins] - return LaneDInputs(pool_dir=dirs[-1], entries=entries, forecasts=RemoteForecasts(need), + return LaneDInputs(pool_dir=dirs[-1], entries=entries, forecasts=RemoteForecasts(live), uid_of=uid_of, house=house, prior_pool_dirs=tuple(dirs[:-1]), armed=armed, boundary_ts=boundary_ts, channel_block_hash=None, host=host, eval_identity=self._eval_identity, @@ -1043,8 +1085,10 @@ def __call__(self, boundary: int) -> LaneDInputs: windows = self._windows(pools, b, bound_lo=(self._bound_lo(entries, state) if bands_on(self.cfg.lane_d) else None)) need, bars = self._needed(entries, state, house, ctxs) - forecasts, host = self._forecasts(need, bars, windows, state, house, ctxs, b) - public_indexes, public_scores = self._public(reader, b, need, bars, ctxs) + live, pub_need = self._judged(b, need, entries, state, house, boundary_ts, uid_of, + armed) + forecasts, host = self._forecasts(live, bars, windows, state, house, ctxs, b) + public_indexes, public_scores = self._public(reader, b, pub_need, bars, ctxs) # W3b6a: the bench host sweeps each digest at the context it is # forecast at (the same map, once per settlement). set_contexts = getattr(self._bench_host, "set_contexts", None) diff --git a/tests/accept/w8c/test_w8c_armed.py b/tests/accept/w8c/test_w8c_armed.py index 32dcd521d..9251df976 100644 --- a/tests/accept/w8c/test_w8c_armed.py +++ b/tests/accept/w8c/test_w8c_armed.py @@ -39,6 +39,26 @@ def _ctx(rig) -> dict: return {c["digest"]: c["context"] for c in rig.eval_host.calls} +class _ContextBench(h.w8b.BenchHost): + """W8b's bench pod recording the settlement's context map + (``set_contexts``: every needed digest at its effective context, the + gate's sweep contexts). Owner 2026-12-01: a digest nobody duels is in the + map but not forecast.""" + + contexts: dict | None = None + + def set_contexts(self, contexts): + self.contexts = dict(contexts) + + +def _mapped(rig) -> _ContextBench: + """Give ``rig`` a :class:`_ContextBench`; returns it (read its + ``contexts`` after a settlement).""" + rig.bench_host = _ContextBench(rig.fx["house"]["digest"]) + rig.source = rig.build() + return rig.bench_host + + # ── the record ────────────────────────────────────────────────────────────── @@ -150,12 +170,15 @@ def test_no_armed_variant_at_or_below_the_declared_context_is_not_forecast(tmp_p fx = h.w8b.fixture(tmp_path) rig = h.Rig(tmp_path, fx=fx, entries=[dict(fx["entry"], context=4096)]) rig.readiness.data = h.readiness_doc(armed=(8192, 16384)) + bench = _mapped(rig) got = rig.source(h.B1) assert got.armed["armed_contexts"] == [8192, 16384] ctx = _ctx(rig) assert fx["x"] not in ctx, \ f"declared 4096, armed (8192, 16384): the entry is not forecast (got {ctx.get(fx['x'])})" - assert ctx[fx["house"]["digest"]] == 8192, "the house keeps its rule: the lowest armed" + assert fx["x"] not in bench.contexts + assert bench.contexts[fx["house"]["digest"]] == 8192, \ + "the house keeps its rule: the lowest armed" assert [e["context"] for e in got.entries] == [4096], \ "the entry is still listed with its declared context (settle_lane_d skips it)" assert fx["x"] not in got.forecasts @@ -183,19 +206,21 @@ def test_open_entries_and_king_d_follow_the_armed_set(tmp_path): its declared context; the settlement skips it ``context_below_armed``). At B3 with 4096 armed again X runs at 4096.""" rig = h.Rig(tmp_path) + bench = _mapped(rig) rig.step()(h.B1) assert int(json.loads(rig.state_path.read_text(encoding="utf-8")) ["entries"][rig.fx["x"]]["context"]) == 4096 rig.readiness.data = h.readiness_doc(armed=(8192,)) rig.eval_host.calls.clear() rig.source(h.B2) - ctx = _ctx(rig) + ctx = bench.contexts assert ctx[rig.fx["house"]["digest"]] == 8192 assert rig.fx["x"] not in ctx, f"X (declared 4096) runs at {ctx.get(rig.fx['x'])}" + assert rig.fx["x"] not in _ctx(rig), "X (declared 4096) is not forecast" rig.readiness.data = h.readiness_doc(armed=(4096, 8192)) rig.eval_host.calls.clear() rig.source(h.B3) - assert _ctx(rig)[rig.fx["x"]] == 4096 + assert bench.contexts[rig.fx["x"]] == 4096 def test_eval_host_is_told_the_armed_set_before_any_forecast(tmp_path): diff --git a/tests/accept/w8c/test_w8c_source.py b/tests/accept/w8c/test_w8c_source.py index 9dd0d0d68..ae2aa96ef 100644 --- a/tests/accept/w8c/test_w8c_source.py +++ b/tests/accept/w8c/test_w8c_source.py @@ -100,8 +100,19 @@ def test_eval_host_forecasts_every_needed_digest_on_every_pinned_window(tmp_path def test_house_comes_from_the_signed_pointer_only(tmp_path): """A new signed pointer after B1 is the house at B2; the state's house - (KING_D since genesis) is still forecast next to it.""" + (KING_D since genesis) is still needed next to it. Owner 2026-12-01: the + needed digests are the settlement's context map (the bench host's + ``set_contexts``); only the duelled ones are forecast.""" rig = h.Rig(tmp_path) + + class ContextBench(h.w8b.BenchHost): + contexts: dict = {} + + def set_contexts(self, contexts): + self.contexts = dict(contexts) + + rig.bench_host = ContextBench(rig.fx["house"]["digest"]) + rig.source = rig.build() rig.step()(h.B1) new_house = {"digest": h.w7a.text_digest("w8c new house"), "reveal_ts": int(rig.fx["house"]["reveal_ts"]) + 100} @@ -110,10 +121,10 @@ def test_house_comes_from_the_signed_pointer_only(tmp_path): rig.eval_host.calls.clear() got = rig.source(h.B2) assert dict(got.house) == new_house - assert new_house["digest"] in rig.eval_host.digests(), "the new house is forecast" - assert rig.fx["house"]["digest"] in rig.eval_host.digests(), \ - "KING_D (the state's house) is still forecast" - assert rig.fx["x"] in rig.eval_host.digests(), "X (open, confirm_pending) is forecast" + needed = rig.bench_host.contexts + assert new_house["digest"] in needed, "the new house is needed" + assert rig.fx["house"]["digest"] in needed, "KING_D (the state's house) is still needed" + assert rig.fx["x"] in needed, "X (open, confirm_pending) is needed" def test_prior_pinned_snapshots_are_prior_pool_dirs(tmp_path): diff --git a/tests/accept/w_offbox/README.md b/tests/accept/w_offbox/README.md index 7f38bffa9..f5096fd1d 100644 --- a/tests/accept/w_offbox/README.md +++ b/tests/accept/w_offbox/README.md @@ -18,7 +18,8 @@ box (validator, trainer, intake) OOM-killed the validator at 04:39 and 05:41, 1. loads each pin from its own copy `//` and re-hashes it against the pin; 2. cuts the windows with the box's own function (`pinned_windows`); - 3. forecasts every needed digest with the box's own function + 3. forecasts every digest the settlement duels (owner 2026-12-01, see + below) with the box's own function (`forecast_windows`) on its prefetch cache, with the same history cut, grant and contract as a `forecast` request; 4. runs the pool phase of `settle_lane_d` (`lane_d._judge_pools`, the @@ -85,3 +86,19 @@ digest's presigned GET grant. The host refuses a pin it does not hold (`pool_digest_mismatch`). `HOST_MODULES["settle"]` is `forecast`'s. No chain, storage, pod, torch or real key is used in these tests. + +## Only the duelled digests are forecast (owner 2026-12-01) + +Settlement 9624600 spent 30+ min on the eval host forecasting seven +checkpoints, public then live, most of them never judged. The inputs source +now runs the settlement's own selection first (`lane_d.judged_digests`: the +same `_choose` step `_judge_pools` runs, on a copy of the state) and asks the +eval host for the queue's duelled members plus KING_D (and the house +challenger when its cohort runs). A held gate candidate, a lost or closed +entry, an entry before its judging start or below the armed contexts is not +forecast; with nobody duelled no live forecast is asked and the gate still +runs. The public half keeps KING_D (its reply carries the read-time drops the +signed public record names). The bench host's context map stays the whole +need. `test_w_offbox_judged_only` checks the asks and that the report, state +and published bytes equal asking every needed digest, in-process and +offloaded, on a fixture with a held, a lost and a before-delay entry. diff --git a/tests/accept/w_offbox/test_w_offbox_judged_only.py b/tests/accept/w_offbox/test_w_offbox_judged_only.py new file mode 100644 index 000000000..2af31a604 --- /dev/null +++ b/tests/accept/w_offbox/test_w_offbox_judged_only.py @@ -0,0 +1,222 @@ +"""Owner 2026-12-01 ("it doesn't need live and public benchmark again"): the +lane D eval host forecasts only the digests the settlement duels. + +Live 2026-12-01, settlement 9624600 spent 30+ min on the eval host forecasting +seven checkpoints (public, then live) although most were never judged: a held +gate candidate (re-gated from the bench, no duel), entries already ``lost``, +entries before their judging start (``before_eval_delay``). The inputs source +now runs the settlement's own selection first +(:func:`cascade.validator.lane_d.judged_digests`, on a copy of the state) and +asks the eval host for the duelled members plus KING_D (the house challenger +when its cohort runs); with nobody duelled it asks no live forecast and the +gate still runs. The public half keeps KING_D (its reply carries the read-time +drops the signed report records). + +Consensus: the signed report, the posterior state and the published objects +are byte-identical to asking every needed digest (the pre-change behaviour, +reproduced here by handing the settlement the whole need), on a fixture with +a held candidate, a lost entry and an entry before its judging start, both +in-process and offloaded (W-OFFBOX). + +The chain (W7a's synthetic chain with two entry digests, numpy only): +- B1: X (clears) and L (loses) are duelled against the house (KING_D); Y is + listed but before its judging start. The bench is down: X is ``hold``. +- B2: X is re-gated from its hold (bench up: crowned), L is lost, Y still + before its judging start: nobody is duelled. +- B3: Y is past its judging start and duelled against KING_D X; L lost. +""" + +from __future__ import annotations + +import json +from dataclasses import replace + +from tests.accept.w7a import helpers as w7a + +from . import helpers as h + +w8c = h.w8c +B1, B2, B3 = h.B1, h.B2, h.B3 +L_UID, Y_UID = 5, 8 +Y_REVEAL_BLOCK = w7a.REVEAL_BLOCK + 1 + + +def _require_plan() -> None: + from cascade.validator import lane_d + + m = h.inputs_mod() + assert hasattr(lane_d, "judged_digests"), \ + "owner 2026-12-01: lane_d.judged_digests (the duelled digests, before forecasts)" + assert hasattr(m.LaneDInputsSource, "_judged"), \ + "owner 2026-12-01: LaneDInputsSource._judged (the forecast plan)" + + +def _fixture(tmp) -> dict: + chain = w7a.build_chain(tmp / "chain", n_entries=2) + x = w7a.entry(chain["digests"][0], "challenger", coldkey=w7a.coldkey()) + loser = w7a.entry(chain["loser"], "loser", coldkey=w7a.coldkey("coldkey-loser")) + late = w7a.entry(chain["digests"][1], "late", coldkey=w7a.coldkey("coldkey-late")) + late["reveal_block"] = Y_REVEAL_BLOCK + return {"chain": chain, "entry": x, "x": x["digest"], "house": chain["house"], + "loser": loser, "late": late, "uid_of": {x["hotkey"]: w8c.CHALLENGER_UID}} + + +# Y's T: before its judging start (T + 6 h) at B1 and B2, past it at B3. +Y_T = w8c.fixture_boundary_ts(B3) - 6 * 3600 - 60 + + +class FlakyBench(h.w8b.BenchHost): + """W8b's healthy bench pod, down (a pod error) while ``down``.""" + + down = False + + def __call__(self, digests, suites): + if self.down: + self.calls.append((tuple(digests), tuple(suites))) + raise ConnectionError("w-offbox judged-only: bench pod down") + return super().__call__(digests, suites) + + +def _rig(tmp, fx, *, offload: bool = False, public=None): + rig = w8c.Rig(tmp, fx=fx, entries=[fx["entry"], fx["loser"], fx["late"]]) + rig.reader.timestamps[Y_REVEAL_BLOCK] = Y_T + rig.reader.hotkeys[L_UID] = fx["loser"]["hotkey"] + rig.reader.hotkeys[Y_UID] = fx["late"]["hotkey"] + rig.bench_host = FlakyBench(fx["house"]["digest"]) + rig.reader.block_hash = lambda b: h.w8b.block_hash(int(b)) + kw = {} + if public is not None: + rig.cfg = replace(rig.cfg, lane_d=w7a.lane_d_cfg(public_weight=0.5, + window_ratio_floor=0.5)) + rig.eval_host = public(rig.fx) + kw["public_indexes"] = rig.eval_host.indexes + rig.source = rig.build(**kw) + host = None + if offload: + host = h.OffloadHost(rig.eval_host, h.copy_pins(fx, tmp / "host_pool")) + rig.source = rig.build(eval_host=host, settle_on_host=True, **kw) + return rig, host + + +def _ask_everything(rig) -> None: + """The pre-change behaviour: every needed digest is forecast.""" + rig.source._judged = lambda b, need, *a, **k: (dict(need), dict(need)) + + +def _run(rig, boundaries, store=None): + """Settle ``boundaries`` in order; the eval host's live forecast digests + per boundary (in-process: ``forecast`` calls).""" + step = h.step(rig, store) + per = {} + for b in boundaries: + rig.bench_host.down = (b == B1) + before = len(rig.eval_host.calls) + s = step(b) + assert s is not None, f"boundary {b} did not settle" + per[b] = sorted({c["digest"] for c in rig.eval_host.calls[before:]}) + return per + + +def _report(rig, b) -> dict: + return json.loads(h.report_bytes(rig, b)) + + +def _check_story(rig, fx) -> None: + x, lo, y, house = fx["x"], fx["loser"]["digest"], fx["late"]["digest"], fx["house"]["digest"] + r1, r2, r3 = (_report(rig, b) for b in (B1, B2, B3)) + assert sorted(r1["judged"]) == sorted([x, lo]), r1["judged"] + assert {"digest": y, "reason": "before_eval_delay"} in r1["skipped"] + assert r1["king_after"]["digest"] == house and r1["crowned"] is None + assert r2["judged"] == [] and r2["crowned"] == x, "B2: X crowned from its hold, no duel" + assert [c["digest"] for c in r2["gate"]["results"]] == [x], "the gate re-ran X's hold" + assert {"digest": y, "reason": "before_eval_delay"} in r2["skipped"] + assert y in r3["judged"] or {"digest": y, "reason": "pending_floor"} in r3["skipped"], \ + "B3: Y past its judging start is duelled" + + +def test_only_duelled_digests_are_forecast_in_process(tmp_path): + """No live forecast of a held candidate, a lost entry or an entry before + its judging start; an only-held settlement asks no forecast at all and + still runs the gate.""" + _require_plan() + fx = _fixture(tmp_path / "fx") + rig, _ = _rig(tmp_path / "v", fx) + per = _run(rig, (B1, B2, B3)) + _check_story(rig, fx) + x, lo, y, house = fx["x"], fx["loser"]["digest"], fx["late"]["digest"], fx["house"]["digest"] + assert per[B1] == sorted([x, lo, house]), \ + f"B1 forecast {per[B1]}: Y (before its judging start) must not be forecast" + assert per[B2] == [], f"B2 (only a held candidate) forecast {per[B2]}; expected none" + assert per[B3] == sorted([y, x]), \ + f"B3 forecast {per[B3]}: the lost entry and the house must not be forecast" + + +def test_offloaded_settle_request_needs_only_duelled_digests(tmp_path): + """W-OFFBOX: the eval host's settle request names only the duelled + digests and KING_D; empty when only a held candidate re-gates.""" + _require_plan() + fx = _fixture(tmp_path / "fx") + rig, host = _rig(tmp_path / "v", fx, offload=True) + _run(rig, (B1, B2, B3)) + _check_story(rig, fx) + x, lo, y, house = fx["x"], fx["loser"]["digest"], fx["late"]["digest"], fx["house"]["digest"] + need = {r["judge"]["boundary"]: sorted(r["need"]) for r in host.requests} + assert need[B1] == sorted([x, lo, house]), need[B1] + assert need[B2] == [], f"B2 settle request needs {need[B2]}; expected nothing" + assert need[B3] == sorted([y, x]), need[B3] + assert not rig.eval_host.calls or all( + c["digest"] in need[B1] + need[B3] for c in rig.eval_host.calls) + + +def _identical(tmp_path, *, offload: bool, public=None): + _require_plan() + fx = _fixture(tmp_path / "fx") + new, _ = _rig(tmp_path / "new", fx, offload=offload, public=public) + ref, _ = _rig(tmp_path / "ref", fx, offload=offload, public=public) + _ask_everything(ref) + s_new, s_ref = h.w8b.Store(), h.w8b.Store() + step_new, step_ref = h.step(new, s_new), h.step(ref, s_ref) + for b in (B1, B2, B3): + for rig in (new, ref): + rig.bench_host.down = (b == B1) + step_ref(b) + step_new(b) + assert h.report_bytes(new, b) == h.report_bytes(ref, b), \ + f"boundary {b}: the report is not byte-identical to forecasting every digest" + assert new.state_path.read_bytes() == ref.state_path.read_bytes(), \ + f"boundary {b}: the posterior state differs" + assert s_new.objects == s_ref.objects, "the published objects differ" + _check_story(new, fx) + return new, ref + + +def test_report_bytes_identical_in_process(tmp_path): + new, ref = _identical(tmp_path, offload=False) + assert len(new.eval_host.calls) < len(ref.eval_host.calls), \ + "the comparison must cover skipped forecasts (the reference asks more)" + + +def test_report_bytes_identical_offloaded(tmp_path): + _identical(tmp_path, offload=True) + + +def test_public_half_asks_only_duelled_digests_and_king_d(tmp_path): + """The public half: the duelled digests plus KING_D (whose reply carries + the read-time drops the signed public record names); with nobody + duelled, KING_D alone. Report bytes identical to asking every digest.""" + from tests.accept.w7a import pub + from tests.accept.w8c.test_w8c_public import PublicHost + + def public(fx, root=tmp_path / "public"): + if not root.exists(): + public.indexes = pub.index_only(root) + return PublicHost(fx, public.indexes) + + new, ref = _identical(tmp_path, offload=False, public=public) + fx = new.fx + x, lo, y, house = fx["x"], fx["loser"]["digest"], fx["late"]["digest"], fx["house"]["digest"] + asked = [c["digest"] for c in new.eval_host.public_calls] + assert sorted(asked) == sorted([x, lo, house, house, y, x]), \ + f"public half asked {asked}: B1 X, L, house; B2 KING_D alone; B3 Y, X" + assert len(ref.eval_host.public_calls) > len(asked) + assert "public" in _report(new, B2), "the only-held settlement keeps its public record"