diff --git a/cascade/eval/lane_d_forecasts.py b/cascade/eval/lane_d_forecasts.py index abd5e27fe..52a0551f7 100644 --- a/cascade/eval/lane_d_forecasts.py +++ b/cascade/eval/lane_d_forecasts.py @@ -676,6 +676,11 @@ def _build_parser() -> argparse.ArgumentParser: help="this host's B6 score cache (default: none)") s.add_argument("--chain-toml", type=Path, default=None, help="this host's chain.toml (the contract a cache miss ingests against)") + fl = sub.add_parser("floor", help="owner 2026-12-01: one settlement's floor pre-check " + "(pins, windows, frozen sets, cohort draw; no forecast) read as JSON " + "from stdin") + fl.add_argument("--pool-root", type=Path, required=True, + help="this host's copy of the pinned pool_d snapshots (//)") w = sub.add_parser("warm-public", help="fill the public blob cache with whole source " "mirrors ahead of a settlement (resumable)") w.add_argument("--index", action="append", required=True, metavar="SOURCE=INDEX_SHA256", @@ -767,7 +772,11 @@ def main(argv: list[str] | None = None) -> int: print(refusal, file=sys.stderr) return EXIT_MISSING_MODULES try: - if args.cmd == "settle": + if args.cmd == "floor": + from .lane_d_settle import serve_floor + + reply = serve_floor(sys.stdin.buffer.read(), pool_root=args.pool_root) + elif args.cmd == "settle": from .lane_d_settle import LocalForecaster, serve_settle score_cache = None diff --git a/cascade/eval/lane_d_settle.py b/cascade/eval/lane_d_settle.py index e9d206937..db520aefd 100644 --- a/cascade/eval/lane_d_settle.py +++ b/cascade/eval/lane_d_settle.py @@ -81,6 +81,14 @@ def forecast(self, digest: str, *, context: int, horizon: int, windows): grant=self.grants.get(digest), chain_toml=self.chain_toml) +def _check_pins(pins, what: str) -> None: + if not isinstance(pins, list) or not pins or not all( + isinstance(p, dict) and isinstance(p.get("sha256"), str) + and isinstance(p.get("snapshot"), str) and _SNAPSHOT_RE.fullmatch(p["snapshot"]) + and ".." not in p["snapshot"] for p in pins): + raise ValueError(f"{what} request pins must be [{{snapshot, sha256}}] with plain names") + + def _check_request(req) -> None: from ..validator.lane_d_inputs import SETTLE_REQUEST_SCHEMA @@ -89,12 +97,7 @@ def _check_request(req) -> None: missing = [k for k in REQUEST_KEYS if k not in req] if missing: raise ValueError(f"settle request lacks {missing}") - pins = req["pins"] - if not isinstance(pins, list) or not pins or not all( - isinstance(p, dict) and isinstance(p.get("sha256"), str) - and isinstance(p.get("snapshot"), str) and _SNAPSHOT_RE.fullmatch(p["snapshot"]) - and ".." not in p["snapshot"] for p in pins): - raise ValueError("settle request pins must be [{snapshot, sha256}] with plain names") + _check_pins(req["pins"], "settle") need = req["need"] if not isinstance(need, dict) or not all( isinstance(k, str) and type(v) is int for k, v in need.items()): @@ -103,20 +106,16 @@ def _check_request(req) -> None: raise ValueError("settle request grants / pinned must be objects") -def settle_pool_phase(req: Mapping, *, pool_root, forecaster, score_cache=None - ) -> tuple[dict, str | None, list[str], int]: - """``(judged record, channel_block_hash, snapshot digests, windows)`` of - one settle request (module docstring). Raises - :class:`~cascade.validator.lane_d_inputs.LaneDInputsError` (typed, the - box re-raises it) or ``ValueError`` (a malformed request).""" - from ..validator.lane_d import _judge_pools, judge_phase_of, judged_record, load_pool_for - from ..validator.lane_d_inputs import LaneDInputsError, forecast_windows, pinned_windows +def _load_pins(pins: list[dict], pool_root, cfg) -> tuple[list[dict], list[dict]]: + """``(snapshots in pin order, the settlement's pool order)``: every pin + loaded from ``//`` once and hashed against its pin + (``pool_unavailable`` / ``pool_digest_mismatch``).""" + from ..validator.lane_d import load_pool_for + from ..validator.lane_d_inputs import LaneDInputsError - phase = judge_phase_of(req["judge"]) - cfg = phase["cfg"] loaded: dict[str, dict] = {} seq: list[dict] = [] - for pin in req["pins"]: + for pin in pins: name = pin["snapshot"] if name not in loaded: d = Path(pool_root) / name @@ -134,13 +133,27 @@ def settle_pool_phase(req: Mapping, *, pool_root, forecaster, score_cache=None seq.append(loaded[name]) # The settlement's order (lane_d._load_pools): the distinct earlier # snapshots oldest first, the newest last. - names = [p["snapshot"] for p in req["pins"]] + names = [p["snapshot"] for p in pins] order, seen = [], {names[-1]} for n in names[:-1]: if n not in seen: seen.add(n) order.append(n) - judge_pools = [loaded[n] for n in order] + [loaded[names[-1]]] + return seq, [loaded[n] for n in order] + [loaded[names[-1]]] + + +def settle_pool_phase(req: Mapping, *, pool_root, forecaster, score_cache=None + ) -> tuple[dict, str | None, list[str], int]: + """``(judged record, channel_block_hash, snapshot digests, windows)`` of + one settle request (module docstring). Raises + :class:`~cascade.validator.lane_d_inputs.LaneDInputsError` (typed, the + box re-raises it) or ``ValueError`` (a malformed request).""" + from ..validator.lane_d import _judge_pools, judge_phase_of, judged_record + from ..validator.lane_d_inputs import LaneDInputsError, forecast_windows, pinned_windows + + phase = judge_phase_of(req["judge"]) + cfg = phase["cfg"] + seq, judge_pools = _load_pins(req["pins"], pool_root, cfg) def block_hash_of() -> str: if not req["block_hash"]: @@ -187,4 +200,59 @@ def serve_settle(raw: bytes, *, pool_root, forecaster, score_cache=None) -> dict "channel_block_hash": chb, "snapshots": shas, "windows": n} -__all__ = ["LocalForecaster", "serve_settle", "settle_pool_phase"] +def floor_plan_phase(req: Mapping, *, pool_root) -> tuple[dict, list[str]]: + """``(forecast plan, snapshot digests)`` of one floor request (owner + 2026-12-01): the pins loaded as for ``settle``, the windows cut by the + same function (only their ids are kept: the windows the settle request + would forecast) and :func:`~cascade.validator.lane_d.forecast_plan` run + over them. No forecast, no model, no grant.""" + from ..validator.lane_d import forecast_plan, lane_d_config_from_record + from ..validator.lane_d_inputs import LaneDInputsError, pinned_windows + + plan = req["plan"] + cfg = lane_d_config_from_record(plan["lane_d"]) + seq, judge_pools = _load_pins(req["pins"], pool_root, cfg) + + def block_hash_of() -> str: + if not req["block_hash"]: + raise LaneDInputsError("chain_unavailable", "the floor request has no block hash") + return str(req["block_hash"]) + + windows, _ = pinned_windows(seq, cfg, int(req["cap"]), block_hash_of, + bound_lo=req["bound_lo"]) + got = forecast_plan(plan, judge_pools, cfg=cfg, + forecast_ids=[w["window_id"] for w in windows]) + return got, [p["sha256"] for p in seq] + + +def serve_floor(raw: bytes, *, pool_root) -> dict: + """Answer one floor request: the ``lane-d-floor-reply/1`` record (the + plan, or a typed refusal). ``ValueError`` on a malformed request.""" + from ..validator.lane_d_inputs import ( + FLOOR_REPLY_SCHEMA, + FLOOR_REQUEST_SCHEMA, + LaneDInputsError, + ) + + try: + req = json.loads(raw) + except (UnicodeDecodeError, json.JSONDecodeError) as e: + raise ValueError(f"malformed floor request ({e})") from e + if not isinstance(req, dict) or req.get("schema") != FLOOR_REQUEST_SCHEMA: + raise ValueError(f"not a {FLOOR_REQUEST_SCHEMA} request") + missing = [k for k in ("pins", "plan", "cap", "bound_lo", "block_hash") if k not in req] + if missing: + raise ValueError(f"floor request lacks {missing}") + _check_pins(req["pins"], "floor") + try: + got, shas = floor_plan_phase(req, pool_root=pool_root) + except LaneDInputsError as e: + log.warning("lane_d_floor_refused %s detail=%s", e.code, e) + return {"schema": FLOOR_REPLY_SCHEMA, "ok": False, "code": e.code, "detail": str(e)} + log.info("lane_d_floor_ok boundary=%s pins=%d duel=%d floored=%d", + req["plan"].get("boundary"), len(shas), len(got["duel"]), len(got["floored"])) + return {"schema": FLOOR_REPLY_SCHEMA, "ok": True, "plan": got, "snapshots": shas} + + +__all__ = ["LocalForecaster", "floor_plan_phase", "serve_floor", "serve_settle", + "settle_pool_phase"] diff --git a/cascade/validator/lane_d.py b/cascade/validator/lane_d.py index 4f584dd15..92cb4348c 100644 --- a/cascade/validator/lane_d.py +++ b/cascade/validator/lane_d.py @@ -86,7 +86,12 @@ clear is not swept (``bench_hold`` in ``gate.results``) and re-queued unjudged and uncharged (``pending``/``pending_floor``, as a hold whose KING_D changed), judged afresh against the new king. Only when no held - candidate passes are the new clears gated and ranked; + candidate passes are the new clears gated and ranked. Held defers duels + (owner 2026-12-01, "we don't need that"): a settlement with a held + candidate duels no new entry at all; the queue's selection is skipped + ``pending_floor`` (unjudged, uncharged, no forecast asked) and duelled at + the next settlement against whoever is king then, so a held-only + settlement is the gate alone (no cohort, row or verdict); 6. writes the signed ``lane-d-report/1`` (W7a: the schema file ``schemas/lane_d_report_1.json``; every entry considered and not judged is a typed skip, court slots that burn name a ``burn_reason``; ``pool.snapshots`` @@ -161,6 +166,7 @@ from __future__ import annotations +import copy import hashlib import json import math @@ -602,6 +608,13 @@ def _king_reveal_ts(state: dict, digest: str) -> int | None: # ── the §1.3b gate (W5e) ──────────────────────────────────────────────────── +# Owner 2026-12-01 ("we don't need that"): the typed skip of a new entry a +# settlement with a held gate candidate does not duel (deferred to the next +# settlement, unjudged and uncharged). An existing reason: the released +# satellite checkers accept it. +HELD_DEFER_REASON = "pending_floor" + + def _held_candidates(state: dict) -> list[str]: """The open entries holding a first clear the gate could not decide (``gate_hold``, a ``bench_hold``). They are re-gated without a new duel. @@ -650,6 +663,196 @@ 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).""" + plan = forecast_plan_request(cfg=cfg, boundary=boundary, boundary_ts=boundary_ts, + state=state, house=house, entries=entries, uid_of=uid_of, + armed=armed) + return None if plan is None else forecast_plan(plan, None, cfg=cfg) + + +FORECAST_PLAN_SCHEMA = "lane-d-forecast-plan/1" + + +def forecast_plan_request(*, cfg, boundary: int, boundary_ts, state: dict, house: dict, + entries: list[dict], uid_of: dict, armed: dict | None, + boundary_block_hash: str | None = None, + max_channels: int | None = None) -> dict | None: + """The JSON input of :func:`forecast_plan` (``None`` when lane D does not + settle at ``boundary`` or it is already settled): the settlement's + selection inputs, with ``state`` a copy 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), plus the floors' inputs the pools do not hold: the boundary + block hash (the cohort draw, the channel pick) and ``max_channels``, + exactly as :func:`settle_lane_d` receives them.""" + 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) + return {"schema": FORECAST_PLAN_SCHEMA, "lane_d": lane_d_config_record(cfg), + "boundary": int(boundary), + "boundary_ts": None if boundary_ts is None else int(boundary_ts), + "boundary_block_hash": boundary_block_hash, + "max_channels": None if max_channels is None else int(max_channels), + "armed_fields": plain_json(armed_fields, "armed_fields"), + "state": plain_json(st, "state"), "entries": plain_json(list(entries), "entries"), + "uid_of": plain_json(dict(uid_of), "uid_of")} + + +def forecast_plan(plan: dict, pools: list[dict] | None = None, *, cfg=None, + forecast_ids=None) -> dict: + """Which digests a settlement duels and which of its members the floors + leave pending, decided BEFORE any forecast is asked (owner 2026-12-01). + + Runs the settlement's own selection (:func:`_choose`: registration, the + held gate candidates, the queue, the armed context and the judging + start) on a copy of ``plan["state"]`` (:func:`forecast_plan_request`). + 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. + + With ``pools`` (the settlement's snapshots in its order, oldest first: + on the lane D eval host, where the window clocks are) it also runs the + floors of the miner cohort, the same functions on the same inputs as + :func:`_judge_pools` (:func:`_below_floors`); none of them reads a + forecast but to ask that it is well formed, so every forecast the eval + host would make (on ``forecast_ids``, the windows + :func:`~cascade.validator.lane_d_inputs.pinned_windows` cuts; ``None``: + every pool window) is taken as well formed. ``floored`` lists the members left ``pending_floor``: + their frozen set is not frozen, or the cohort draw drops them (latest T + first). They need no forecast: :func:`_judge_pools` skips them + ``pending_floor`` at the step that does today, and the report is the + same bytes. + + Returns ``{"duel", "king_d", "floored"}``: the duelled miner members plus + the house challenger when its cohort runs (``floored`` never names the + house), and the KING_D the cohorts are judged against. ``duel`` empty: + nobody is duelled (only held candidates re-gate, from the bench).""" + if not isinstance(plan, dict) or plan.get("schema") != FORECAST_PLAN_SCHEMA: + raise ValueError(f"not a {FORECAST_PLAN_SCHEMA} request") + cfg = lane_d_config_from_record(plan["lane_d"]) if cfg is None else cfg + b = int(plan["boundary"]) + st = copy.deepcopy(plan["state"]) + sel = _choose(st, cfg, b, plan["boundary_ts"], copy.deepcopy(list(plan["entries"])), + dict(plan["uid_of"]), copy.deepcopy(plan["armed_fields"]), + lambda _dg: False) + chosen = list(sel["chosen"]) + duel = list(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"]) + kd = str(st["king"]["digest"]) + floored: list[str] = [] + king_ts = _king_reveal_ts(st, kd) + if pools is not None and chosen and king_ts is not None: + floored = _below_floors(chosen, {m: st["entries"][m] for m in chosen}, pools=pools, + king_ts=int(king_ts), bars=[kd], cfg=cfg, boundary=b, + block_hash=plan["boundary_block_hash"], + max_channels=plan["max_channels"], forecast_ids=forecast_ids) + return {"duel": sorted(set(duel)), "king_d": kd, "floored": floored} + + +class _WellFormed: + """One digest's forecasts as :func:`forecast_plan` takes them: a + well-formed (zero-valued, never allocated) quantile array on every pool + window, in the window's scored shape (:func:`_fc_ok`).""" + + def __init__(self, shapes: dict[str, tuple]): + self._shapes = shapes + + def __contains__(self, wid) -> bool: + return wid in self._shapes + + def __getitem__(self, wid): + return np.broadcast_to(np.float64(0.0), self._shapes[wid]) + + +def _below_floors(members: list[str], recs: dict[str, dict], *, pools: list[dict], + king_ts: int, bars: list[str], cfg, boundary: int, block_hash, + max_channels, forecast_ids=None) -> list[str]: + """The miner cohort's members :func:`_judge_pools` leaves + ``pending_floor`` when every forecast is well formed: its frozen-set + advance (:func:`_advance_member`, seeded by the settlement) and its + cohort draw loop (:func:`_cohort_set`, :func:`_seen_set`, + :func:`_drawn`: the latest-T member dropped until the draw meets the + floors), on copies of ``recs`` and of the pools (the channel pick reduces + the windows in place). Every digest's forecasts are well formed on + ``forecast_ids`` (``None``: on every pool window) and absent elsewhere.""" + ids = None if forecast_ids is None else {str(x) for x in forecast_ids} + pools = [dict(p) for p in pools] + picks = _pick_channels(pools, block_hash, max_channels) + n_q = len(SCORING_LEVELS) + shapes = {} + for p in pools: + for w in p["windows"]: + wid = w["window_id"] + if wid and (ids is None or wid in ids): + h = window_horizon(w, cfg) + shapes[wid] = (forecast_shape(picks[wid], h, n_q) if wid in picks + else (h, n_q)) + fc = _WellFormed(shapes) + forecasts = {dg: fc for dg in [*bars, *members]} + recs = copy.deepcopy(recs) + cap_seed = f"lane-d/1:cap:{boundary}" + out: list[str] = [] + frozen: list[str] = [] + for m in sorted(members, key=lambda m: (recs[m]["reveal_ts"], m)): + recs[m]["frozen_set"] = _advance_member(recs[m], pools, int(king_ts), cfg, cap_seed) + (frozen if recs[m]["frozen_set"]["frozen"] else out).append(m) + if frozen: + budget = int(cfg.max_windows_per_settlement) + + def ok_with(ms: list[str]) -> bool: + eligible, _ = _cohort_set(pools, ms, bars, king_ts, recs, forecasts, cfg, {}, picks) + seen_c = _seen_set(pools, ms, bars, king_ts, recs, forecasts, cfg, {}, picks, + eligible) + return _drawn(eligible, cfg, block_hash, budget, seen_c)[2] + + ok = ok_with(frozen) + while frozen and not ok: + out.append(frozen.pop()) + if frozen: + ok = ok_with(frozen) + return sorted(out) + + +def settle_order(named: list[tuple[object, dict]]) -> list[dict]: + """The settlement's snapshot order (:func:`_load_pools`) of ``(key, + pool)`` pairs in pin order: the distinct earlier snapshots oldest first, + the newest last (a key listed twice, or equal to the newest's, once).""" + newest = named[-1][0] + seen, out = {newest}, [] + for k, p in named[:-1]: + if k not in seen: + seen.add(k) + out.append(p) + return out + [named[-1][1]] + + 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 +1667,20 @@ 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``. With a held + gate candidate ``chosen`` is empty and the house challenger closed for + the settlement: the queue's selection waits ``pending_floor`` (held + defers duels, owner 2026-12-01). + :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) @@ -1545,13 +1725,17 @@ def skip(dg: str, reason: str, rec: dict | None = None) -> None: chosen, queued = select_queue(state, cfg, boundary, entries, frozenset(held)) skipped += queued house_held = house_open and _keeps_hold(house_rec, state) + # Owner 2026-12-01 ("we don't need that"): with a held gate candidate + # this settlement duels NO new entry (held first: none could crown). The + # queue's selection is deferred, unjudged and uncharged, to the next + # settlement (``pending`` / ``pending_floor``, a reason the released + # checkers accept): no forecast check, no frozen set, no cohort. + defer = bool(held) or house_held # 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 not defer and faulty(dg): state["entries"][dg]["status"] = "closed" skip(dg, "checkpoint_fault") chosen.remove(dg) @@ -1581,13 +1765,85 @@ 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) + if defer: + for dg in chosen: + skip(dg, HELD_DEFER_REASON) + chosen = [] + if house_open and not house_held: + skip(hd, HELD_DEFER_REASON, 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, floored=()) -> 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. + + ``floored`` (owner 2026-12-01): the members :func:`forecast_plan` found + below the floors, which were never forecast (live or public). Each is + skipped ``pending_floor`` at the step that skips it with every forecast + asked (its frozen set is not frozen; or, frozen, the cohort draw drops + it, latest T first), so the judged record is the same; it is never + ``king_unscored`` for the forecasts it was not asked.""" + floored = frozenset(str(dg) for dg in floored) + 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 @@ -1618,14 +1874,18 @@ def skip(dg: str, reason: str, rec: dict | None = None) -> None: # it is the house; after the first miner crown the house is no # second bar (W5c change 3 retired). bars = [kd] - if king_ts is None or any(forecasts.get(b) is None or not _pub_ready(pub_of(b)) - for b in bars): + # owner 2026-12-01: with every member below the floors no bar was + # forecast either (nothing is scored); the floors still run + only_floored = king_ts is not None and all(m in floored for m in members) + if king_ts is None or (not only_floored and any( + forecasts.get(b) is None or not _pub_ready(pub_of(b)) for b in bars)): for m in members: skip(m, "king_unscored", recs[m]) continue # A member without a public score set (never asked of the eval host) - # cannot be judged on the combined rule: it waits (fail closed). - for m in [m for m in members if not _pub_ready(pub_of(m))]: + # cannot be judged on the combined rule: it waits (fail closed). A + # floored member was not asked: the floors below skip it. + for m in [m for m in members if m not in floored and not _pub_ready(pub_of(m))]: skip(m, "king_unscored", recs[m]) members.remove(m) if not members: @@ -1639,7 +1899,12 @@ def skip(dg: str, reason: str, rec: dict | None = None) -> None: frozen.append(m) else: skip(m, "pending_floor", rec) - members = frozen + # owner 2026-12-01: a frozen floored member is one the cohort draw + # below drops (latest T first, before the members it judges); it has + # no forecast to draw on, so it is dropped here in that same order. + for m in reversed([m for m in frozen if m in floored]): + skip(m, "pending_floor", recs[m]) + members = [m for m in frozen if m not in floored] if not members: continue # W5j: the judged windows are the cohort's seeded per-bin draw over @@ -1906,7 +2171,10 @@ def judge_request(phase: dict) -> dict: "entries": plain_json(phase["entries"], "entries"), "uid_of": plain_json(phase["uid_of"], "uid_of"), "pub": _pub_record(phase["pub"]), - "crown_bar": float(phase["crown_bar"])} + "crown_bar": float(phase["crown_bar"]), + # owner 2026-12-01: present only when a member was not forecast + **({"floored": sorted(str(dg) for dg in phase["floored"])} + if phase.get("floored") else {})} def judge_phase_of(request: dict) -> dict: @@ -1920,7 +2188,8 @@ def judge_phase_of(request: dict) -> dict: "max_channels": request["max_channels"], "armed_fields": request["armed_fields"], "state": request["state"], "entries": request["entries"], "uid_of": request["uid_of"], "pub": _pub_from_record(request["pub"]), - "crown_bar": float(request["crown_bar"])} + "crown_bar": float(request["crown_bar"]), + "floored": [str(dg) for dg in request.get("floored") or ()]} def judged_record(judged: dict) -> dict: @@ -1958,7 +2227,7 @@ def settle_lane_d(*, cfg, boundary: int, pool_dir, entries: list[dict], house: d public_scores: dict | None = None, host: dict | None = None, eval_identity: dict | None = None, - pool_phase=None) -> LaneDSettlement: + pool_phase=None, floored=()) -> LaneDSettlement: """Settle lane D at ``boundary`` (see the module docstring). ``pool_phase`` (W-OFFBOX, 2026-11-28): ``None`` judges in this process @@ -2040,7 +2309,13 @@ def settle_lane_d(*, cfg, boundary: int, pool_dir, entries: list[dict], house: d ``eval_identity`` (W-IMG, plan rev6.24 (e)): the eval host's code identity the forecasts ran on, recorded under ``extensions`` as :data:`EVAL_IMAGE_EXTENSION` (logged, never consensus). ``None`` (every - settlement before ``[v2] image_epoch_from_block``) records nothing.""" + settlement before ``[v2] image_epoch_from_block``) records nothing. + + ``floored`` (owner 2026-12-01): the members the forecast plan + (:func:`forecast_plan`, before any forecast) found below the floors and + left out of ``forecasts`` and the public half; they are skipped + ``pending_floor`` exactly as with their forecasts (:func:`_judge_pools`), + so the report is the same bytes.""" if not cfg.active(boundary): return LaneDSettlement(report=None, pay=None, receipt=None) if boundary_ts is not None and (isinstance(boundary_ts, bool) or not isinstance(boundary_ts, int) @@ -2107,7 +2382,8 @@ def pub_of(dg: str): phase = {"cfg": cfg, "boundary": boundary, "boundary_ts": boundary_ts, "boundary_block_hash": boundary_block_hash, "max_channels": max_channels, "armed_fields": armed_fields, "state": state, "entries": entries, - "uid_of": uid_of, "pub": pub, "crown_bar": crown_bar} + "uid_of": uid_of, "pub": pub, "crown_bar": crown_bar, + "floored": tuple(sorted(str(dg) for dg in floored or ()))} if pool_phase is None: # The in-process reference path (tests, tools): the pools load here. # The validator runs it only under the box pool budget @@ -2457,5 +2733,5 @@ def absent_settlement(*, cfg, boundary: int, state_path, house: dict, reason: st receipt=receipt) -__all__ = ["LaneDSettlement", "absent_settlement", "held_gate_digests", "judge_cohort", - "load_pool", "settle_lane_d", "window_id"] +__all__ = ["HELD_DEFER_REASON", "LaneDSettlement", "absent_settlement", "held_gate_digests", + "judge_cohort", "load_pool", "settle_lane_d", "window_id"] diff --git a/cascade/validator/lane_d_inputs.py b/cascade/validator/lane_d_inputs.py index 3e2019656..cdc5ce81a 100644 --- a/cascade/validator/lane_d_inputs.py +++ b/cascade/validator/lane_d_inputs.py @@ -130,6 +130,9 @@ BOX_POOL_BUDGET_BYTES = 64 * 1024 * 1024 SETTLE_REQUEST_SCHEMA = "lane-d-settle-request/1" SETTLE_REPLY_SCHEMA = "lane-d-settle-reply/1" +# owner 2026-12-01: the eval host's floor pre-check (no forecast, no model) +FLOOR_REQUEST_SCHEMA = "lane-d-floor-request/1" +FLOOR_REPLY_SCHEMA = "lane-d-floor-reply/1" REVEALED = "revealed" ENTRY_FIELDS = ("hotkey", "digest", "context", "coldkey_at_ready", "ready_block", "reveal_block", "reveal_ts") @@ -347,6 +350,13 @@ def _forecast_group(eval_host: Any, need: dict[str, int], bars: frozenset[str], +def _max_channels_of(cfg: Any) -> int | None: + """``[generator] max_channels`` as the settlement receives it + (:func:`~cascade.validator.lane_d_wiring._max_channels`).""" + v = getattr(getattr(cfg, "generator", None), "max_channels", None) + return None if v is None else int(v) + + def pool_dir_bytes(d: Path) -> int: """The bytes of one snapshot directory's files (``stat`` only; an absent directory is 0, its load then refuses).""" @@ -768,6 +778,105 @@ 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, + floor: Callable[[dict], dict | None] | None = None, + block_hash: str | None = None + ) -> 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). + + ``floor`` (owner 2026-12-01, live settlement 9626400: 1 h 45 of + forecasts for six members all skipped ``pending_floor``) runs the + floors before any forecast: ``floor(plan)`` is + :func:`~cascade.validator.lane_d.forecast_plan` of the + :func:`~cascade.validator.lane_d.forecast_plan_request` over the + settlement's pools (in this process, or the eval host's ``floor`` + request), and the members it finds below the floors are neither + forecast nor asked on the public half; they are ``self._floored``, + which the settlement skips ``pending_floor`` (same report bytes). A + floor failure, or a plan whose duelled set is not this one, floors + nobody (#1047's plan, as before).""" + from .lane_d import forecast_plan_request, judged_digests + + self._floored = () + 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) + floored: set[str] = set() + if floor is not None and got["duel"]: + try: + req = forecast_plan_request( + cfg=self.cfg.lane_d, boundary=b, boundary_ts=boundary_ts, state=state, + house=house, entries=entries, uid_of=uid_of, armed=armed, + boundary_block_hash=block_hash, max_channels=_max_channels_of(self.cfg)) + fl = floor(req) if req is not None else None + if fl is not None: + if sorted(fl.get("duel") or ()) != sorted(got["duel"]) \ + or fl.get("king_d") != got["king_d"]: + raise ValueError("the floor plan duels another set") + floored = {str(dg) for dg in fl.get("floored") or ()} + if not floored <= set(got["duel"]) - {str(house["digest"])}: + raise ValueError("the floor plan floors a digest it does not duel") + except Exception as e: # noqa: BLE001 — floor nobody, as before + log.warning("lane_d_floor_plan settlement %d: no floor pre-check, forecasting " + "every duelled digest (%s: %s)", b, type(e).__name__, e) + floored = set() + kd = got["king_d"] + duel = [dg for dg in got["duel"] if dg not in floored] + want = set(duel) | ({kd} if 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]) + self._floored = tuple(sorted(floored)) + log.info("lane_d_forecast_plan settlement %d: %d of %d needed digest(s) forecast " + "live, %d on the public half (duelled %d, %d below the floors)", b, + len(live), len(need), len(public), len(got["duel"]), len(floored)) + return live, dict(sorted(public.items())) + + def _host_floor(self, pins: list[dict], plan: dict, *, cap: int, bound_lo, + block_hash: str) -> dict | None: + """The eval host's floor pre-check (``floor`` request: the pins, the + plan and the window cut's inputs as the settle request carries them; + no forecast) bound to the pins; ``None`` when the host has no + ``floor`` (an older host: nobody is floored).""" + ask = getattr(self._eval_host, "floor", None) + if not callable(ask): + return None + reply = ask({"schema": FLOOR_REQUEST_SCHEMA, "pins": list(pins), "plan": plan, + "cap": int(cap), "bound_lo": None if bound_lo is None else float(bound_lo), + "block_hash": str(block_hash)}) + if not isinstance(reply, dict) or reply.get("schema") != FLOOR_REPLY_SCHEMA: + raise ValueError(f"not a {FLOOR_REPLY_SCHEMA} reply") + if not reply.get("ok"): + raise ValueError(f"eval host floor refused ({reply.get('code')}: " + f"{reply.get('detail')})") + if reply.get("snapshots") != [p["sha256"] for p in pins]: + raise ValueError("the eval host floored other snapshots than the pins") + got = reply.get("plan") + if not isinstance(got, dict) or not isinstance(got.get("duel"), list) \ + or not isinstance(got.get("floored"), list): + raise ValueError("malformed floor plan") + return got + 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,33 +1082,45 @@ 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) - set_contexts = getattr(self._bench_host, "set_contexts", None) - if callable(set_contexts): - set_contexts(dict(need)) try: block_hash = str(reader.block_hash(b)) except Exception as e: # noqa: BLE001 — the channel pick's input raise LaneDInputsError("chain_unavailable", f"boundary {b} block hash unreadable ({e})") from e + host_pins = [{"snapshot": Path(p["dir"]).name, "sha256": str(p["sha256"])} + for p in pins] + # owner 2026-12-01: the floors run on the eval host (the window clocks + # are there) before anything is forecast + self._floored = () + cap = int(getattr(getattr(self.cfg, "generator", None), "max_channels", 1) or 1) + live, pub_need = self._judged( + b, need, entries, state, house, boundary_ts, uid_of, armed, + floor=lambda plan: self._host_floor(host_pins, plan, cap=cap, bound_lo=bound_lo, + block_hash=block_hash), + block_hash=block_hash) + floored = self._floored + 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)) host_ns = None if host is not None: from .lane_d_score_cache import namespace host_ns = namespace(host["identity"], ident.package_hash) - 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, + judge = HostJudge(self._eval_host, boundary=b, pins=host_pins, + 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, public_indexes=public_indexes, public_scores=public_scores, - pool_phase=judge) + pool_phase=judge, floored=floored) @staticmethod def _fault(ids: list[str], horizon: int, per: list[int] | None = None) -> dict: @@ -1043,8 +1164,15 @@ 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) + plan_hash = self._plan_block_hash(reader, b) + self._floored = () + live, pub_need = self._judged(b, need, entries, state, house, boundary_ts, uid_of, + armed, floor=None if plan_hash is None else ( + lambda plan: self._local_floor(pools, plan, windows)), + block_hash=plan_hash) + floored = self._floored + 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) @@ -1056,7 +1184,29 @@ def __call__(self, boundary: int) -> LaneDInputs: armed=armed, boundary_ts=boundary_ts, channel_block_hash=self.channel_block_hash, host=host, eval_identity=getattr(self, "_eval_identity", None), - public_indexes=public_indexes, public_scores=public_scores) + public_indexes=public_indexes, public_scores=public_scores, + floored=floored) + + def _local_floor(self, pools: list[tuple[Path, dict]], plan: dict, + windows: list[dict]) -> dict: + """The floor pre-check in this process (the reference path: the pools + are already loaded here, under the box budget), over the windows the + eval host is asked to forecast.""" + from .lane_d import forecast_plan, settle_order + + return forecast_plan(plan, settle_order([(Path(d).resolve(), p) for d, p in pools]), + cfg=self.cfg.lane_d, + forecast_ids=[w["window_id"] for w in windows]) + + @staticmethod + def _plan_block_hash(reader: Any, b: int) -> str | None: + """The boundary block hash the settlement is given (the cohort draw's + input); ``None`` when unreadable (the floor pre-check then fails + and floors nobody).""" + try: + return str(reader.block_hash(int(b))) + except Exception: # noqa: BLE001 — no plan input: floor nobody + return None def build_lane_d_inputs(cfg: Any, *, state_dir, intake_state_dir, @@ -1408,6 +1558,22 @@ def settle(self, request: dict) -> dict: limit = self.timeout_s * max(1, len(request.get("need") or {})) return json.loads(self._ssh(host, args, payload, timeout_s=limit)) + def floor(self, request: dict) -> dict: + """Owner 2026-12-01: the settlement's floor pre-check on the host + (``floor`` request, JSON both ways): the host loads the pins from + ``pool_root`` and runs :func:`~cascade.validator.lane_d.forecast_plan` + over them. No forecast, no model, no grant; bounded on the host + (``timeout -k``) and under the eval lock like every non-``hello`` + request, at one ``eval_timeout_seconds``.""" + host = self._host + if host is None: + raise RuntimeError("lane D eval host: floor before a matching hello") + if not self.pool_root: + raise RuntimeError("lane D eval host: floor needs eval_pool_root") + args = ["floor", "--pool-root", self.pool_root] + payload = json.dumps(request, sort_keys=True).encode("utf-8") + return json.loads(self._ssh(host, args, payload)) + def public_scores(self, digest: str, *, context: int, horizon: int, draws, block_hash: str, max_channels: int, keep: dict | None = None) -> dict: """rev6.18 A3 (F4): ``digest``'s per-window scores on the public @@ -1630,7 +1796,8 @@ def load_inputs_services(cfg: Any, path) -> dict: BOX_POOL_BUDGET_BYTES))} -__all__ = ["BOX_POOL_BUDGET_BYTES", "INPUTS_ERROR_CODES", "SETTLE_REPLY_SCHEMA", +__all__ = ["BOX_POOL_BUDGET_BYTES", "FLOOR_REPLY_SCHEMA", "FLOOR_REQUEST_SCHEMA", + "INPUTS_ERROR_CODES", "SETTLE_REPLY_SCHEMA", "SETTLE_REQUEST_SCHEMA", "DocumentFile", "HostJudge", "LaneDInputsConfigError", "LaneDInputsError", "LaneDInputsSource", "PinFilePool", "RemoteForecasts", "SSHEvalHost", "VaultGetGrants", "build_lane_d_inputs", "forecast_windows", diff --git a/cascade/validator/lane_d_wiring.py b/cascade/validator/lane_d_wiring.py index 56d13f8be..82ab2aac4 100644 --- a/cascade/validator/lane_d_wiring.py +++ b/cascade/validator/lane_d_wiring.py @@ -169,6 +169,9 @@ class LaneDInputs: # W-OFFBOX (2026-11-28): the settlement's pool phase on the eval host # (settle_lane_d(pool_phase=)); None = judged in this process. pool_phase: Any = None + # owner 2026-12-01: the members the forecast plan found below the floors, + # never forecast (settle_lane_d(floored=)); () = every member was asked. + floored: tuple = () def _eval_identity_of(cfg: Any, inp: Any, boundary: int) -> dict | None: @@ -482,6 +485,8 @@ def _settle(self, boundary: int, inp: LaneDInputs, *, expect: str | None, **({} if _host_of(inp) is None else {"host": _host_of(inp)}), **({} if getattr(inp, "pool_phase", None) is None else {"pool_phase": inp.pool_phase}), + **({"floored": tuple(fl)} if (fl := getattr(inp, "floored", ())) + else {}), **({"eval_identity": ident} if (ident := _eval_identity_of( self.cfg, inp, int(boundary))) else {})) except Exception as e: # noqa: BLE001 — LaneDStateError, schema, pool or crash diff --git a/docs/MINER_LANE_D.md b/docs/MINER_LANE_D.md index 6823ebf5a..a70bcc127 100644 --- a/docs/MINER_LANE_D.md +++ b/docs/MINER_LANE_D.md @@ -232,11 +232,10 @@ blocks, about 24 h) of `submit`, or the entry expires (`ready_expired`). holds the verdict (`bench_hold`); after `max_bench_holds` (4) holds the entry goes back to the queue unjudged, never charged. - **Crown order: held first.** A held entry was scored on an earlier - settlement's windows, so it is gated before any entry that first clears now. - If a held entry passes, it is crowned. The new clears are not gated or - charged: they go back to `pending` (`pending_floor`) and are duelled at the - next settlement against the new king. Only if no held entry passes are the - new clears gated, and the highest LCB crowns. + settlement's windows, so a settlement with a held entry only re-gates it: + no new entry is duelled there. New entries wait in `pending` + (`pending_floor`), unjudged and never charged, and are duelled at the next + settlement against whoever is king then (the held entry if it passed). ## How you are paid diff --git a/tests/accept/w5g/test_w5g_held_defers.py b/tests/accept/w5g/test_w5g_held_defers.py new file mode 100644 index 000000000..bb06e672a --- /dev/null +++ b/tests/accept/w5g/test_w5g_held_defers.py @@ -0,0 +1,210 @@ +"""Held defers duels (owner 2026-12-01, "we don't need that"). A settlement +with a HELD gate candidate (a ``bench_hold``, re-gated without a duel) duels +NO new entry: held first means none could crown there. Every entry the queue +would have selected is skipped ``pending`` / ``pending_floor`` (an existing +reason), unjudged and uncharged: no forecast check, frozen set, cohort, row +or verdict. The next settlement duels it against whoever is king then (the +held candidate if it passed, else the old KING_D). + +X clears at boundary 2 and is held (bench host down). Y readies after it and +is eligible at boundary 3. With no held candidate nothing changes (the report +bytes on main before held first, ``NO_HELD_REPORT_SHA256``). + +Satellites never update: every report of the new rule is run through the +released validator lines' satellite checker (``git archive`` of +validator-release-laned-live 890fe6d1 and validator-release-laned-1201 +15ae7e96) and must give zero problems and no burn. + +On main (before this rule) Y is duelled at boundary 3, so every test here +fails on an AssertionError. +""" + +from __future__ import annotations + +import io +import json +import subprocess +import sys +import tarfile +from pathlib import Path + +import pytest + +from .helpers import ( + ARM_BLOCK, + ERA, + HORIZON, + MARGIN_H, + entry_of, + fixture_key, + read_state, + rows_of, + skips_of, + verdict_of, +) +from .test_w5g_held_first import _flow, _settle + +REPO = Path(__file__).resolve().parents[3] +# The released validator lines (satellites never update), their satellite +# checker blob (cascade/audit/lane_d.py, the same file on both). +RELEASES = {"laned-live": ("890fe6d1c530eedccd4ee764547041e5c607c1ed", + "3a342edfaff625b53beb45f98ebbcd54773b841d"), + "laned-1201": ("15ae7e961bd4973c00551b526614937a0becd18d", + "3a342edfaff625b53beb45f98ebbcd54773b841d")} + + +def _need_rule() -> None: + """The rule's typed reason exists (so every test fails on the code + before it by assertion, not an import error).""" + import cascade.validator.lane_d as lane_d + + assert getattr(lane_d, "HELD_DEFER_REASON", None) == "pending_floor", \ + "lane_d.HELD_DEFER_REASON missing (held defers duels not built)" + + +def _deferred(f, report: dict, yd: str) -> None: + """Y was not duelled: a typed ``pending_floor`` skip, its record untouched.""" + assert verdict_of(report, yd) is None, "a held settlement duels no new entry" + assert rows_of(report, yd) == set(), "no live row for a deferred entry" + assert report["judged"] == [] and report["cohorts"] == [] and report["rows"] == [], \ + "a held-only settlement is the gate alone (no cohort, row or verdict)" + assert skips_of(report, yd) == ["pending_floor"], report["skipped"] + e = entry_of(report, yd) + assert (e["status"], e["reason"]) == ("pending", "pending_floor"), e + rec = read_state(f.path)["entries"][yd] + assert (rec["status"], rec["reason"]) == ("pending", "pending_floor"), rec + assert rec["used_windows"] == [], "uncharged: no window is spent" + assert rec.get("frozen_set") is None and not rec.get("gate_hold") + assert all(s["digest"] != yd for s in report["pay"]["court"]) + assert all(r["digest"] != yd for r in report["gate"]["results"]), \ + "a deferred entry is never gated" + + +def test_held_settlement_duels_no_new_entry(tmp_path): + _need_rule() + f, y = _flow(tmp_path) + x, h, yd = f.x["digest"], f.h0["digest"], y["digest"] + report, host = _settle(f, 3, 3, [f.x, y], {x: 0.9, yd: 0.85, h: 1.0}) + _deferred(f, report, yd) + assert report["crowned"] == x and read_state(f.path)["king"]["digest"] == x + assert [r["digest"] for r in report["gate"]["results"]] == [x] + assert yd not in host.swept_digests() + + +def test_deferred_entry_is_duelled_next_against_the_new_king(tmp_path): + _need_rule() + f, y = _flow(tmp_path) + x, h, yd = f.x["digest"], f.h0["digest"], y["digest"] + _settle(f, 3, 3, [f.x, y], {x: 0.9, yd: 0.85, h: 1.0}) + nxt, _ = _settle(f, 4, 4, [f.x, y], {yd: 0.85, x: 1.0, h: 1.0}) + v = verdict_of(nxt, yd) + assert v is not None and v["stage"] == "first" and v["king_digest"] == x, v + assert rows_of(nxt, yd), "duelled on the next settlement's windows" + + +@pytest.mark.parametrize("held_mode", ["regress", "fault"]) +def test_held_fails_then_the_deferred_entry_duels_the_old_king(tmp_path, held_mode): + _need_rule() + f, y = _flow(tmp_path) + x, h, yd = f.x["digest"], f.h0["digest"], y["digest"] + spec = {"regress": {x: 1.10}, "fault": {x: "nan"}}[held_mode] + report, _ = _settle(f, 3, 3, [f.x, y], {**spec, yd: 0.85, h: 1.0}) + outcomes = {r["digest"]: r["outcome"] for r in report["gate"]["results"]} + assert outcomes == {x: {"regress": "gate_regression", "fault": "checkpoint_fault"}[ + held_mode]}, outcomes + assert report["crowned"] is None and read_state(f.path)["king"]["digest"] == h + _deferred(f, report, yd) + nxt, host = _settle(f, 4, 4, [f.x, y], {yd: 0.85, h: 1.0}) + v = verdict_of(nxt, yd) + assert v is not None and v["king_digest"] == h, v + assert nxt["crowned"] == yd and yd in host.swept_digests() + + +def test_held_again_defers_again(tmp_path): + _need_rule() + f, y = _flow(tmp_path) + x, h, yd = f.x["digest"], f.h0["digest"], y["digest"] + report, _ = _settle(f, 3, 3, [f.x, y], {x: 0.9, yd: 0.85, h: 1.0}, down={x}) + assert {r["digest"]: r["outcome"] for r in report["gate"]["results"]} == {x: "bench_hold"} + assert read_state(f.path)["entries"][x]["status"] == "hold" + _deferred(f, report, yd) + + +def test_no_held_candidate_is_unchanged(tmp_path): + """No held candidate: the new entries are duelled as before; the report + bytes are main's before held first (test_w5g_held_first's fixture).""" + _need_rule() + from .test_w5g_held_first import test_no_held_candidate_keeps_max_t_order + + test_no_held_candidate_keeps_max_t_order(tmp_path) + + +# ── the released satellite checker (never updated) ────────────────────────── + + +_OLD_CHECK = r""" +import json, sys +sys.path.insert(0, sys.argv[1]) +import cascade +assert cascade.__file__.startswith(sys.argv[1]), cascade.__file__ +from cascade.shared.config.lane_d import parse_lane_d +from cascade.audit.lane_d import lane_d_findings +raw = json.loads(sys.argv[3]) +cfg = parse_lane_d(raw, era_blocks_at=lambda _b: int(sys.argv[5])) +report = json.loads(open(sys.argv[2]).read()) +f = lane_d_findings(report, cfg, signer_hotkey=sys.argv[4]) +print(json.dumps({"burn": f.burn, "alerts": f.alerts, "transient": f.transient, + "findings": f.findings})) +""" + + +def _old_tree(tmp: Path, which: str) -> Path: + rel, blob = RELEASES[which] + dest = tmp / f"old-{which}" + if dest.exists(): + return dest + got = subprocess.run(["git", "-C", str(REPO), "rev-parse", f"{rel}:cascade/audit/lane_d.py"], + capture_output=True, text=True) + assert got.returncode == 0 and got.stdout.strip() == blob, \ + (f"the released checker {which} ({rel}) is not readable here", got.stdout, got.stderr) + raw = subprocess.run(["git", "-C", str(REPO), "archive", "--format=tar", rel, "cascade"], + check=True, capture_output=True).stdout + with tarfile.open(fileobj=io.BytesIO(raw)) as tf: + tf.extractall(dest, filter="data") + return dest + + +def _old_findings(tmp: Path, which: str, report: dict, tag: str) -> dict: + tree = _old_tree(tmp, which) + raw = {"from_block": ARM_BLOCK, "share": 0.25, "takes_from": "lane_a", "remainder": "burn", + "contexts": [4096, 8192, 16384], "horizon": HORIZON, + "forward_margin_hours": MARGIN_H, "max_mirror_lag_hours": 6.0, "min_windows": 24, + "min_clusters": 4, "bootstrap_B": 200, "public_weight": 0.0, + "window_ratio_floor": 1e-9, "horizon_bands": []} + path = tmp / f"report-{which}-{tag}.json" + path.write_text(json.dumps(report)) + out = subprocess.run([sys.executable, "-I", "-c", _OLD_CHECK, str(tree), str(path), + json.dumps(raw), fixture_key("signer").ss58_address, str(ERA)], + capture_output=True, text=True, cwd=str(tmp)) + assert out.returncode == 0, f"the old checker crashed: {out.stderr[-2000:]}" + return json.loads(out.stdout.strip().splitlines()[-1]) + + +@pytest.mark.parametrize("which", sorted(RELEASES)) +@pytest.mark.parametrize("case", ["held_crowns", "held_fails", "held_again"]) +def test_the_released_satellite_checker_accepts_held_defers(tmp_path, which, case): + _need_rule() + f, y = _flow(tmp_path / "flow") + x, h, yd = f.x["digest"], f.h0["digest"], y["digest"] + spec = {x: 1.10 if case == "held_fails" else 0.9, yd: 0.85, h: 1.0} + report, _ = _settle(f, 3, 3, [f.x, y], spec, down={x} if case == "held_again" else ()) + _deferred(f, report, yd) + # the next settlement duels the deferred entry (against X, or the house) + nxt, _ = _settle(f, 4, 4, [f.x, y], {yd: 0.85, x: 1.0, h: 1.0}) + if case != "held_again": + assert verdict_of(nxt, yd) is not None, "the deferred entry is duelled next" + for n in (2, 3, 4): + got = _old_findings(tmp_path, which, f.reports[n], f"{case}-{n}") + assert got["transient"] == "", (n, got) + assert got["burn"] is None, (n, got) + assert got["findings"] == [], (n, got) diff --git a/tests/accept/w5g/test_w5g_held_first.py b/tests/accept/w5g/test_w5g_held_first.py index e65820fb7..c3c1e6aa2 100644 --- a/tests/accept/w5g/test_w5g_held_first.py +++ b/tests/accept/w5g/test_w5g_held_first.py @@ -1,41 +1,21 @@ """Held first (owner 2026-12-01: "they need to be scored first"; lane D order = reveal order). A candidate HELD from an earlier settlement (a ``bench_hold``: status ``hold``, its clear in ``gate_hold``) was scored on -that settlement's eval set; a clear first made at this settlement was scored -on this settlement's set, so their LCBs are never ranked against each other. - -The held candidates are gated first. When one passes it crowns, and every -new clear is neither crowned nor charged: it is not swept (``bench_hold`` in -``gate.results``), its verdict stays ``cleared``, and the entry is re-queued -unjudged (``pending`` / ``pending_floor``, as a hold whose KING_D changed), -duelled afresh at the next settlement against the new king. Only when no held -candidate passes do the new clears go through the gate and ranking as before. - -X clears at boundary 2 and is held (bench host down). At boundary 3 Y enters -and clears on a fresh snapshot with an LCB above X's held one. Every report -is also run through the satellite checker of the deployed releases (they -never update): a new rule must give zero problems there. - -On main the boundary-3 crown is Y (the highest LCB across both eval sets), -so the held-first tests fail on an AssertionError. +that settlement's eval set, so its LCB is never ranked against a new clear. + +Superseded the same day by held defers duels (owner 2026-12-01, "we don't +need that"; ``test_w5g_held_defers``): a settlement with a held candidate +duels no new entry at all, so a held candidate and a new clear never meet in +one gate. This file keeps the fixtures those tests share and the no-held +case: every clear is swept and the highest LCB crowns, report bytes +unchanged. """ from __future__ import annotations -import io -import json -import subprocess -import sys -import tarfile from pathlib import Path -import pytest - from .helpers import ( - ARM_BLOCK, - ERA, - HORIZON, - MARGIN_H, T_X, BenchHost, Flow, @@ -45,14 +25,11 @@ boundary, entry, entry_of, - fixture_key, forecasts, read_state, report_digest, - rows_of, settle, uids, - verdict_of, ) REPO = Path(__file__).resolve().parents[3] @@ -109,68 +86,6 @@ def _settle(f: Flow, n: int, snap: int, entries, spec: dict, down=()): return out.report, host -def _new_clear_outranks_held(f: Flow, y: dict, report: dict) -> None: - held = read_state(f.path)["entries"][f.x["digest"]].get("gate_hold") or {} - xl = next(r["held_from"]["lcb"] for r in report["gate"]["results"] - if r["digest"] == f.x["digest"]) - v = verdict_of(report, y["digest"]) - assert v is not None and v["cleared"] is True, f"fixture: Y did not clear: {v}" - assert v["lcb"] > xl, f"fixture: Y's LCB {v['lcb']} must outrank X's held {xl} ({held})" - - -def test_held_candidate_crowns_before_a_higher_lcb_new_clear(tmp_path): - _need_held_first() - f, y = _flow(tmp_path) - x, h = f.x["digest"], f.h0["digest"] - report, host = _settle(f, 3, 3, [f.x, y], {x: 0.9, y["digest"]: 0.85, h: 1.0}) - _new_clear_outranks_held(f, y, report) - assert report["crowned"] == x, \ - "a held candidate is decided before any new clear: X crowns, not the higher-LCB Y" - assert read_state(f.path)["king"]["digest"] == x - assert rows_of(report, x) == set(), "a held candidate is re-gated, never re-duelled" - assert verdict_of(report, y["digest"])["outcome"] == "cleared" - - -def test_the_new_clear_is_requeued_unjudged_and_uncharged(tmp_path): - _need_held_first() - f, y = _flow(tmp_path) - x, h, yd = f.x["digest"], f.h0["digest"], y["digest"] - report, host = _settle(f, 3, 3, [f.x, y], {x: 0.9, yd: 0.85, h: 1.0}) - rec = read_state(f.path)["entries"][yd] - assert (rec["status"], rec["reason"]) == ("pending", "pending_floor"), rec - assert not rec.get("gate_hold") and rec.get("confirm") is None - assert rec.get("frozen_set") is None - e = entry_of(report, yd) - assert (e["status"], e["reason"]) == ("pending", "pending_floor") - assert yd not in host.swept_digests(), "the new clear is not gated once a held one crowns" - (res,) = [r for r in report["gate"]["results"] if r["digest"] == yd] - assert res["outcome"] == "bench_hold" and "rows" not in res and "held_from" not in res - assert all(s["digest"] != yd for s in report["pay"]["court"]) - assert all(s["digest"] != yd for s in report["skipped"]), "judged, so never a skip" - # Next settlement (fresh snapshot): Y is duelled afresh against the new king. - nxt, _ = _settle(f, 4, 4, [f.x, y], {yd: 0.85, x: 1.0, h: 1.0}) - v = verdict_of(nxt, yd) - assert v is not None and v["stage"] == "first" and v["king_digest"] == x, v - assert rows_of(nxt, yd) and not rows_of(nxt, yd) & rows_of(report, yd) - - -@pytest.mark.parametrize("held_mode", ["regress", "fault", "hold_again"]) -def test_held_fails_then_new_clears_rank_as_today(tmp_path, held_mode): - _need_held_first() - f, y = _flow(tmp_path) - x, h, yd = f.x["digest"], f.h0["digest"], y["digest"] - spec = {"regress": {x: 1.10}, "fault": {x: "nan"}, "hold_again": {x: 0.9}}[held_mode] - report, host = _settle(f, 3, 3, [f.x, y], {**spec, yd: 0.85, h: 1.0}, - down={x} if held_mode == "hold_again" else ()) - outcomes = {r["digest"]: r["outcome"] for r in report["gate"]["results"]} - want_x = {"regress": "gate_regression", "fault": "checkpoint_fault", - "hold_again": "bench_hold"}[held_mode] - assert outcomes == {x: want_x, yd: "pass"}, outcomes - assert report["crowned"] == yd and read_state(f.path)["king"]["digest"] == yd - assert yd in host.swept_digests() - assert verdict_of(report, yd)["outcome"] == "crowned" - - def test_no_held_candidate_keeps_max_t_order(tmp_path): """No held candidate: every clear is swept and the highest LCB crowns (the order before this rule; its report bytes are unchanged).""" @@ -197,68 +112,3 @@ def test_no_held_candidate_keeps_max_t_order(tmp_path): assert host.swept_digests() >= set(order) # The report bytes of this settlement on main 49ea024c (before held first). assert report_digest(report) == NO_HELD_REPORT_SHA256 - - -# ── the released satellite checker (never updated) ────────────────────────── - - -_OLD_CHECK = r""" -import json, sys -sys.path.insert(0, sys.argv[1]) -import cascade -assert cascade.__file__.startswith(sys.argv[1]), cascade.__file__ -from cascade.shared.config.lane_d import parse_lane_d -from cascade.audit.lane_d import lane_d_findings -raw = json.loads(sys.argv[3]) -cfg = parse_lane_d(raw, era_blocks_at=lambda _b: int(sys.argv[5])) -report = json.loads(open(sys.argv[2]).read()) -f = lane_d_findings(report, cfg, signer_hotkey=sys.argv[4]) -print(json.dumps({"burn": f.burn, "alerts": f.alerts, "transient": f.transient, - "findings": f.findings})) -""" - - -def _old_tree(tmp: Path, rel: str, blob: str) -> Path: - got = subprocess.run(["git", "-C", str(REPO), "rev-parse", f"{rel}:cascade/audit/lane_d.py"], - capture_output=True, text=True) - assert got.returncode == 0 and got.stdout.strip() == blob, (rel, got.stdout, got.stderr) - raw = subprocess.run(["git", "-C", str(REPO), "archive", "--format=tar", rel, "cascade"], - check=True, capture_output=True).stdout - dest = tmp / f"old-{rel}" - with tarfile.open(fileobj=io.BytesIO(raw)) as tf: - tf.extractall(dest, filter="data") - return dest - - -def _old_findings(tmp: Path, which: str, report: dict) -> dict: - tree = _old_tree(tmp, *CHECKERS[which]) - raw = {"from_block": ARM_BLOCK, "share": 0.25, "takes_from": "lane_a", "remainder": "burn", - "contexts": [4096, 8192, 16384], "horizon": HORIZON, - "forward_margin_hours": MARGIN_H, "max_mirror_lag_hours": 6.0, "min_windows": 24, - "min_clusters": 4, "bootstrap_B": 200, "public_weight": 0.0, - "window_ratio_floor": 1e-9} - if which == "deployed": - raw["horizon_bands"] = [] - path = tmp / f"report-{which}.json" - path.write_text(json.dumps(report)) - out = subprocess.run([sys.executable, "-I", "-c", _OLD_CHECK, str(tree), str(path), - json.dumps(raw), fixture_key("signer").ss58_address, str(ERA)], - capture_output=True, text=True, cwd=str(tmp)) - assert out.returncode == 0, f"the old checker crashed: {out.stderr[-2000:]}" - return json.loads(out.stdout.strip().splitlines()[-1]) - - -@pytest.mark.parametrize("which", sorted(CHECKERS)) -@pytest.mark.parametrize("case", ["held_crowns", "held_fails_new_crowns"]) -def test_the_released_satellite_checker_accepts_held_first(tmp_path, which, case): - _need_held_first() - f, y = _flow(tmp_path / "flow") - x, h, yd = f.x["digest"], f.h0["digest"], y["digest"] - spec = {x: 0.9 if case == "held_crowns" else 1.10, yd: 0.85, h: 1.0} - report, _ = _settle(f, 3, 3, [f.x, y], spec) - assert report["crowned"] == (x if case == "held_crowns" else yd) - for n in (2, 3): - got = _old_findings(tmp_path, which, f.reports[n]) - assert got["transient"] == "", got - assert got["burn"] is None, (n, got) - assert got["findings"] == [], (n, got) 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..ee4681441 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,54 @@ 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. + +## The floors run before any forecast (owner 2026-12-01) + +Settlement 9626400: the plan above asked 7 of 9 digests live and 7 public +(6 duelled); the eval host spent 1 h 45 forecasting them; then every member +was skipped `pending_floor` (frozen set not frozen, then the cohort draw +dropping the latest-T members). Those floors read no forecast but to ask +that it is well formed: they depend on the pins, the windows' clocks, the +entries' reveal_ts / used_windows and the king. + +`lane_d.forecast_plan` now also runs them, the same functions on the same +inputs (`_advance_member`, `_cohort_set`, `_seen_set`, `_drawn`, every +forecast on the windows the host would cut taken as well formed), before +anything is forecast: on the eval host as a `floor` request when the box +settles there (the pins and the plan as JSON; no forecast, no model, no +grant; `timeout -k` on the host and the eval lock like every non-`hello` +request), in-process otherwise. A floored member is neither forecast live +nor asked on the public half; with nobody above the floors nothing is +forecast live and the public half asks KING_D alone. The settlement gets the +floored list (`settle_lane_d(floored=)`, the judge request's `floored`) and +skips each one `pending_floor` at the step that skips it with its forecasts +(`_judge_pools`). A floor failure, an older host without `floor`, or a plan +that duels another set floors nobody (the plan above, as before). + +`test_w_offbox_floor_first` proves the report and posterior state bytes equal +forecasting every member for: all members below the floors, some below, a +frozen latest-T member dropped by the draw, nobody pending (settle_lane_d +directly), and through the inputs source in-process, offloaded, with a +refusing host and with the public half (the #1047 fixture, whose B3 member +is below the floors). What the pre-check cannot foresee is a malformed +checkpoint (`checkpoint_fault`, found only by forecasting it): a floored +member's own fault surfaces at the settlement that forecasts it (it waits +`pending_floor` until then), and a member the draw dropped only because a +faulting member was in its cohort waits one more settlement. Both defer, +uncharged; neither crowns or pays differently. diff --git a/tests/accept/w_offbox/helpers.py b/tests/accept/w_offbox/helpers.py index 9ff691f7c..ecc809020 100644 --- a/tests/accept/w_offbox/helpers.py +++ b/tests/accept/w_offbox/helpers.py @@ -108,14 +108,20 @@ class OffloadHost: """The lane D eval host as an offloaded box sees it: ``hello()`` (W8c's fake) and ``settle(request)`` (the host's ``serve_settle`` over ``pool_root`` with W8c's table forecaster, JSON both ways). ``forecast`` - is never called on the box.""" + is never called on the box. ``floor(request)`` (owner 2026-12-01) is the + host's ``serve_floor`` over ``pool_root`` (no forecast), JSON both ways; + ``floor=False`` is a host without it.""" - def __init__(self, fake: w8c.EvalHost, pool_root: Path, *, fork: bool = False): + def __init__(self, fake: w8c.EvalHost, pool_root: Path, *, fork: bool = False, + floor: bool = True): self.fake = fake self.pool_root = Path(pool_root) self.fork = fork self.requests: list[dict] = [] + self.floor_requests: list[dict] = [] self.hellos = 0 + if not floor: + self.floor = None def hello(self): self.hellos += 1 @@ -129,6 +135,19 @@ def _serve(self, raw: bytes) -> bytes: reply = settle.serve_settle(raw, pool_root=self.pool_root, forecaster=self.fake) return json.dumps(reply, sort_keys=True).encode("utf-8") + def floor(self, request: dict) -> dict: + raw = json.dumps(request, sort_keys=True).encode("utf-8") + self.floor_requests.append(json.loads(raw)) + forecasts = len(self.fake.calls) + out = in_child(self._serve_floor, raw) if self.fork else self._serve_floor(raw) + assert len(self.fake.calls) == forecasts, "the floor request forecast something" + return json.loads(out.decode("utf-8")) + + def _serve_floor(self, raw: bytes) -> bytes: + settle = importlib.import_module(SETTLE) + reply = settle.serve_floor(raw, pool_root=self.pool_root) + return json.dumps(reply, sort_keys=True).encode("utf-8") + def settle(self, request: dict) -> dict: req = {**request, "grants": {dg: None for dg in request["need"]}} raw = json.dumps(req, sort_keys=True).encode("utf-8") diff --git a/tests/accept/w_offbox/test_w_offbox_floor_first.py b/tests/accept/w_offbox/test_w_offbox_floor_first.py new file mode 100644 index 000000000..be43469fb --- /dev/null +++ b/tests/accept/w_offbox/test_w_offbox_floor_first.py @@ -0,0 +1,356 @@ +"""Owner 2026-12-01: the lane D floors run BEFORE any forecast. + +Live 2026-12-01, settlement 9626400: the forecast plan (#1047) asked "7 of 9 +needed digest(s) forecast live, 7 on the public half (duelled 6)"; the eval +host spent 1 h 45 on public and live forecasts; then ``_judge_pools`` skipped +all six members ``pending_floor`` (their frozen sets were not frozen, then +the cohort draw dropped the latest-T members while it fell short of the +floors). Neither step reads a forecast but to ask that it is well formed: +they depend on the pool pins, the windows' clocks, the entries' reveal_ts / +used_windows and the king. + +The forecast plan (``lane_d.forecast_plan``) now also runs those floors, the +same functions on the same inputs, before anything is forecast: on the eval +host (``floor`` request: the pins, no forecast, no model) when the box +settles there, in-process otherwise. A member it finds below the floors is +neither forecast live nor asked on the public half; with nobody above them +no member is forecast at all (the public half asks KING_D alone, as #1049's +empty-need path). The settlement skips each floored member ``pending_floor`` +at the step that skips it today. + +Consensus: the signed report and the posterior state are byte-identical to +forecasting every member, for: all members below the floors (no frozen set), +some below, a frozen latest-T member dropped by the cohort draw, and nobody +pending; in-process and offloaded, with and without the public half. Numpy +only (W7a's synthetic chain, W8c's rig); every test asserts the floor-first +surface first, so on a build without it each fails on an assertion. +""" + +from __future__ import annotations + +import copy +import inspect +import json +from pathlib import Path + +from tests.accept.w7a import helpers as w7a + +from . import helpers as h +from . import test_w_offbox_judged_only as jo + +B1, B3 = h.B1, h.B3 +S1 = w7a.BOUNDARY_1 +S2 = w7a.BOUNDARY_2 +HOUR = 3600 + + +def _require() -> None: + from cascade.validator import lane_d + + assert hasattr(lane_d, "forecast_plan"), \ + "owner 2026-12-01: lane_d.forecast_plan (the floors before any forecast)" + assert hasattr(lane_d, "forecast_plan_request"), \ + "owner 2026-12-01: lane_d.forecast_plan_request" + assert "floored" in inspect.signature(lane_d.settle_lane_d).parameters, \ + "owner 2026-12-01: settle_lane_d(floored=) (the members never forecast)" + settle = __import__("cascade.eval.lane_d_settle", fromlist=["x"]) + assert hasattr(settle, "serve_floor"), "owner 2026-12-01: the eval host's floor request" + + +# ── settle_lane_d with and without the pre-check (W7a's chain) ────────────── + + +def _chain(tmp: Path, n: int) -> dict: + chain = w7a.build_chain(tmp / "chain", n_entries=n) + ents = [w7a.entry(chain["digests"][i], f"floor-{i}", coldkey=w7a.coldkey(f"ck-floor-{i}")) + for i in range(n)] + return {"chain": chain, "entries": ents, + "uid_of": {e["hotkey"]: 6 + i for i, e in enumerate(ents)}} + + +def _settle(fx: dict, cfg, state_path: Path, boundary: int, *, forecasts: dict, + floored=(), boundary_ts: int | None = None): + from cascade.validator.lane_d import settle_lane_d + + ts = w7a._rev614_ts(settle_lane_d, boundary)["boundary_ts"] if boundary_ts is None \ + else int(boundary_ts) + kw = {"floored": tuple(floored)} if floored else {} + return settle_lane_d(cfg=cfg, boundary=boundary, pool_dir=fx["chain"]["pools"][1], + entries=[dict(e) for e in fx["entries"]], + house=dict(fx["chain"]["house"]), forecasts=forecasts, + uid_of=dict(fx["uid_of"]), state_path=state_path, + signer=h.DetSigner(), boundary_ts=ts, + **w7a.gate_inputs(boundary, fx["chain"]["house"]["digest"]), **kw) + + +def _plan(fx: dict, cfg, state_path: Path, boundary: int) -> dict: + from cascade.validator import lane_d + from cascade.validator.lane_d_state import load_prior_state + + house = dict(fx["chain"]["house"]) + state = load_prior_state(state_path, house, boundary) + req = lane_d.forecast_plan_request( + cfg=cfg, boundary=boundary, + boundary_ts=w7a._rev614_ts(lane_d.settle_lane_d, boundary)["boundary_ts"], + state=state, house=house, entries=fx["entries"], uid_of=fx["uid_of"], armed=None, + boundary_block_hash=w7a.gate_block_hash(boundary), max_channels=None) + pools = [lane_d.load_pool_for(fx["chain"]["pools"][1], cfg)] + # the plan travels as JSON (the eval host's floor request) + return lane_d.forecast_plan(json.loads(json.dumps(req)), pools) + + +def _compare(tmp: Path, fx: dict, cfg, boundary: int, *, prior=None) -> dict: + """Settle ``boundary`` twice from the same prior state: forecasting every + member (today) and forecasting only what the plan keeps, the plan's + floored members handed to the settlement. Both reports and posterior + states must be the same bytes.""" + from cascade.validator.lane_d_state import report_path + + full = fx["chain"]["forecasts"][1] + paths = {} + for name in ("ref", "new"): + sp = tmp / name / "lane_d_state.json" + sp.parent.mkdir(parents=True) + if prior is not None: + sp.write_bytes(prior.read_bytes()) + paths[name] = sp + plan = _plan(fx, cfg, paths["new"], boundary) + kd = plan["king_d"] + kept = [dg for dg in plan["duel"] if dg not in plan["floored"]] + live = sorted(set(kept) | ({kd} if kept else set())) + _settle(fx, cfg, paths["ref"], boundary, forecasts=copy.deepcopy(full)) + _settle(fx, cfg, paths["new"], boundary, forecasts={dg: full[dg] for dg in live}, + floored=plan["floored"]) + ref = report_path(paths["ref"], boundary).read_bytes() + new = report_path(paths["new"], boundary).read_bytes() + assert new == ref, "the report is not byte-identical to forecasting every member" + assert paths["new"].read_bytes() == paths["ref"].read_bytes(), \ + "the posterior state differs" + return {"plan": plan, "live": live, "report": json.loads(ref), + "state": json.loads(paths["ref"].read_bytes())} + + +def _skips(report: dict, reason: str) -> list[str]: + return sorted(s["digest"] for s in report["skipped"] if s["reason"] == reason) + + +def test_all_members_below_the_floors_forecast_nothing(tmp_path): + """No member's frozen set freezes: none is forecast, nor KING_D (nothing + is scored); every member is pending_floor, same report bytes.""" + _require() + fx = _chain(tmp_path, 2) + fx["entries"][1]["reveal_ts"] += HOUR + out = _compare(tmp_path, fx, w7a.lane_d_cfg(min_windows=1000), S1) + members = sorted(e["digest"] for e in fx["entries"]) + assert out["plan"]["duel"] == members, out["plan"] + assert out["plan"]["floored"] == members, "every member is below the floors" + assert out["live"] == [], f"forecast {out['live']}: nothing (not even KING_D)" + assert out["report"]["judged"] == [] and out["report"]["cohorts"] == [] + assert _skips(out["report"], "pending_floor") == members + + +def test_some_members_below_the_floors_are_not_forecast(tmp_path): + """A member revealed after the snapshot's clocks has no eligible window: + it alone is floored; the other is duelled on the same windows.""" + _require() + fx = _chain(tmp_path, 2) + a, b = (e["digest"] for e in fx["entries"]) + fx["entries"][1]["reveal_ts"] += 10 * HOUR + out = _compare(tmp_path, fx, w7a.lane_d_cfg(), S1) + assert out["plan"]["floored"] == [b], out["plan"] + assert out["live"] == sorted([a, out["plan"]["king_d"]]), out["live"] + assert out["report"]["judged"] == [a] + assert _skips(out["report"], "pending_floor") == [b] + assert out["state"]["entries"][b]["frozen_set"]["frozen"] is False + + +def test_latest_member_dropped_by_the_draw_is_not_forecast(tmp_path): + """Both members' frozen sets freeze, but they share too few windows (each + was already judged on other sources): the draw drops the latest-T member. + The plan floors exactly it; the earlier member is judged alone.""" + _require() + fx = _chain(tmp_path, 2) + a, b = (e["digest"] for e in fx["entries"]) + fx["entries"][1]["reveal_ts"] += HOUR + cfg = w7a.lane_d_cfg() + # S1: both registered, before their judging start (nothing is judged) + prior = tmp_path / "prior" / "lane_d_state.json" + prior.parent.mkdir(parents=True) + _settle(fx, cfg, prior, S1, forecasts=fx["chain"]["forecasts"][1], + boundary_ts=w7a.T0 + HOUR) + st = json.loads(prior.read_bytes()) + assert st["entries"][a]["status"] == st["entries"][b]["status"] == "pending" + ids = _window_ids(fx["chain"]["pools"][1]) + st["entries"][a]["used_windows"] = sorted(i for i in ids if i.split("-")[0] in + ("src0", "src1")) + st["entries"][b]["used_windows"] = sorted(i for i in ids if i.split("-")[0] in + ("src4", "src5")) + from cascade.validator.lane_d_state import canonical_state + + prior.write_bytes(canonical_state(st)) # a test fixture's state, never a live one + out = _compare(tmp_path, fx, cfg, S2, prior=prior) + assert out["plan"]["floored"] == [b], out["plan"] + assert out["state"]["entries"][b]["frozen_set"]["frozen"] is True, \ + "the latest-T member is frozen: the draw, not its set, drops it" + assert out["report"]["judged"] == [a] + assert _skips(out["report"], "pending_floor") == [b] + assert out["live"] == sorted([a, out["plan"]["king_d"]]) + + +def _window_ids(pool_dir) -> list[str]: + from tests.accept.w8c import helpers as w8c + + return w8c.window_ids(pool_dir) + + +def test_nobody_pending_floors_nobody(tmp_path): + """Every member clears the floors: the plan floors nobody and the + settlement is today's.""" + _require() + fx = _chain(tmp_path, 1) + out = _compare(tmp_path, fx, w7a.lane_d_cfg(), S1) + (a,) = (e["digest"] for e in fx["entries"]) + assert out["plan"]["floored"] == [] and out["report"]["judged"] == [a] + assert out["live"] == sorted([a, out["plan"]["king_d"]]) + + +# ── the inputs source: what the eval host is asked (W8c's rig) ────────────── +# The #1047 fixture: at B3 its one duelled member Y falls short of the floors. + + +def _identical(tmp_path, *, offload: bool, public=None, host_floor: bool = True): + """The settlement with the floor pre-check and the pre-change reference + (every needed digest forecast), boundary by boundary: same report and + state bytes, same published objects.""" + fx = jo._fixture(tmp_path / "fx") + new, nh = jo._rig(tmp_path / "new", fx, offload=offload, public=public) + ref, _ = jo._rig(tmp_path / "ref", fx, offload=offload, public=public) + if nh is not None and not host_floor: + nh.floor = lambda request: {"schema": h.inputs_mod().FLOOR_REPLY_SCHEMA, "ok": False, + "code": "pool_unavailable", "detail": "test"} + jo._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) + per = {} + for b in (h.B1, h.B2, h.B3): + for rig in (new, ref): + rig.bench_host.down = (b == h.B1) + before = len(new.eval_host.calls) + step_ref(b) + step_new(b) + per[b] = sorted({c["digest"] for c in new.eval_host.calls[before:]}) + 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" + y = fx["late"]["digest"] + assert {"digest": y, "reason": "pending_floor"} in jo._report(new, B3)["skipped"] + return new, nh, ref, per, fx + + +def test_in_process_floored_member_is_never_forecast(tmp_path): + _require() + new, _, ref, per, fx = _identical(tmp_path, offload=False) + assert per[B3] == [], f"B3 forecast {per[B3]}: Y is below the floors, nothing is scored" + assert len(new.eval_host.calls) < len(ref.eval_host.calls) + + +def test_offloaded_floor_runs_on_the_eval_host_without_forecasting(tmp_path): + """W-OFFBOX: one floor request per settlement that duels somebody (B1, + B3; none at the held-only B2), carrying the pins and no grant; the + settle request at B3 needs nothing.""" + _require() + new, host, _, _, fx = _identical(tmp_path, offload=True) + m = h.inputs_mod() + floors = {r["plan"]["boundary"]: r for r in host.floor_requests} + assert sorted(floors) == [B1, B3], f"floor requests at {sorted(floors)}" + settles = {r["judge"]["boundary"]: r for r in host.requests} + for b, r in floors.items(): + assert r["schema"] == m.FLOOR_REQUEST_SCHEMA + assert "grants" not in r and "need" not in r, "a floor request forecasts nothing" + assert r["pins"] == settles[b]["pins"], "the floor ran on the settlement's pins" + need = {b: sorted(r["need"]) for b, r in settles.items()} + assert need[B3] == [], f"B3 settle request needs {need[B3]}: Y is below the floors" + assert floors[B3]["plan"]["state"]["entries"][fx["late"]["digest"]]["status"] == "pending" + judge = settles[B3]["judge"] + assert judge.get("floored") == [fx["late"]["digest"]], judge.get("floored") + + +def test_offloaded_floor_refusal_forecasts_as_before(tmp_path): + """A host that refuses the floor request floors nobody: the duelled + digests are forecast (#1047's plan) and the report is unchanged.""" + _require() + _, host, _, _, fx = _identical(tmp_path, offload=True, host_floor=False) + need = {r["judge"]["boundary"]: sorted(r["need"]) for r in host.requests} + assert need[B3] == sorted([fx["late"]["digest"], fx["x"]]), need[B3] + assert all("floored" not in r["judge"] for r in host.requests) + + +def test_public_half_skips_floored_members(tmp_path): + """The public half asks neither a floored member nor, with nobody above + the floors, anything but KING_D; same report bytes.""" + from tests.accept.w7a import pub + from tests.accept.w8c.test_w8c_public import PublicHost + + _require() + + def public(fx, root=tmp_path / "public"): + if not root.exists(): + public.indexes = pub.index_only(root) + return PublicHost(fx, public.indexes) + + new, _, _, _, fx = _identical(tmp_path, offload=False, public=public) + asked = [c["digest"] for c in new.eval_host.public_calls] + assert fx["late"]["digest"] not in asked, f"public half asked the floored Y: {asked}" + assert asked[-1:] == [fx["x"]], f"B3 public half: KING_D X alone ({asked})" + + +# ── the eval host's floor request over SSH ────────────────────────────────── + + +def test_ssh_floor_is_bounded_under_the_eval_lock_and_forecasts_nothing(tmp_path): + """``floor`` runs ``timeout -k`` ON the host and under the eval cache + lock (``flock``), like forecast / public / settle; it carries the plan + and the pins, no grant; the CLI has the command and it needs no model + module (no torch on the host path).""" + import shlex + from types import SimpleNamespace + + from cascade.eval import lane_d_forecasts as f + + _require() + m = h.inputs_mod() + seen = {} + + def run(argv, *, input, capture_output, timeout, check): + if "hello" in argv[-1].split(): + out = json.dumps(h.w8c.hello()) + else: + seen.update(cmd=argv[-1], payload=json.loads(input), timeout=timeout) + out = json.dumps({"schema": m.FLOOR_REPLY_SCHEMA, "ok": False, + "code": "pool_unavailable"}) + return SimpleNamespace(returncode=0, stdout=out.encode(), stderr=b"") + + hosts = tmp_path / "hosts.toml" + hosts.write_text('[[host]]\nname = "laned-eval"\nhost = "10.0.0.9"\nstage = "final"\n' + 'remote_python = "python"\nworkdir = "."\n', encoding="utf-8") + host = m.SSHEvalHost(hosts, cache_dir="/c", budget_bytes=10, contexts=h.w8c.CONTEXTS, + run=run, timeout_s=600.0, grants=lambda dg: {"never": dg}, + pool_root="/root/lane_d_pool_d") + host.hello() + req = {"schema": m.FLOOR_REQUEST_SCHEMA, "pins": [{"snapshot": "s", "sha256": "0" * 64}], + "plan": {"x": 1}, "cap": 1, "bound_lo": None, "block_hash": "0x" + "1" * 64} + reply = host.floor(req) + assert reply["code"] == "pool_unavailable" + words = shlex.split(seen["cmd"].split("&&")[-1]) + assert words[:4] == ["timeout", "-k", "30", str(600 - 30)], "bounded ON the host" + assert words[4] == "flock", "under the eval lock" + i = words.index("-m") + assert words[i + 1:i + 3] == ["cascade.eval.lane_d_forecasts", "floor"] + assert words[words.index("--pool-root") + 1] == "/root/lane_d_pool_d" + assert seen["payload"] == req, "the plan and the pins only (no grant, no need)" + assert seen["timeout"] == 600.0 + args = f._build_parser().parse_args(["floor", "--pool-root", "/p"]) + assert args.cmd == "floor" and str(args.pool_root) == "/p" + assert not f.HOST_MODULES.get("floor"), "the floor pre-check loads no model module" diff --git a/tests/accept/w_offbox/test_w_offbox_held_defers.py b/tests/accept/w_offbox/test_w_offbox_held_defers.py new file mode 100644 index 000000000..471e86e1b --- /dev/null +++ b/tests/accept/w_offbox/test_w_offbox_held_defers.py @@ -0,0 +1,130 @@ +"""Held defers duels (owner 2026-12-01, "we don't need that"): a settlement +with a held gate candidate duels no new entry, so the eval host does no live +or public scoring of new entries there. Only the gate (bench) runs for the +held candidate. + +The eval host's ``settle`` pool phase is still called once (the signed +report's ``pool`` record, the newest snapshot's name and first-seen roots, +comes from the host's copy of the pins; the box loads no ``pool_d``), but +with an EMPTY need: no forecast, no cohort. The public half asks KING_D +alone (its reply carries the read-time drops the signed public record names). + +The chain is test_w_offbox_judged_only's, with Y past its judging start at +B2 (not at B1): +- B1: X (clears) and L (loses) are duelled; Y before its judging start; the + bench is down, so X is held. +- B2: X is re-gated from its hold (crowned). Y is eligible but deferred + (``pending_floor``): not forecast, not in the settle request. +- B3: Y is selected and forecast against KING_D X. + +On main (before this rule) Y is forecast and duelled at B2, so every test +fails on an AssertionError. +""" + +from __future__ import annotations + +from . import helpers as h +from .test_w_offbox_judged_only import ( + B1, + B2, + B3, + Y_REVEAL_BLOCK, + _fixture, + _report, + _rig, + _run, + w8c, +) + +# Y's T: past its judging start (T + 6 h) at B2, before it at B1. +Y_T_EARLY = w8c.fixture_boundary_ts(B2) - 6 * 3600 - 60 + + +def _need_rule() -> None: + import cascade.validator.lane_d as lane_d + + assert getattr(lane_d, "HELD_DEFER_REASON", None) == "pending_floor", \ + "lane_d.HELD_DEFER_REASON missing (held defers duels not built)" + + +def _early(rig): + rig.reader.timestamps[Y_REVEAL_BLOCK] = Y_T_EARLY + return rig + + +def _check_story(rig, fx) -> None: + x, lo, y = fx["x"], fx["loser"]["digest"], fx["late"]["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 r2["crowned"] == x and [c["digest"] for c in r2["gate"]["results"]] == [x] + assert r2["judged"] == [] and r2["cohorts"] == [] and r2["rows"] == [], \ + "B2 (a held candidate): no new entry is duelled" + assert {"digest": y, "reason": "pending_floor"} in r2["skipped"], r2["skipped"] + (ey,) = [e for e in r2["entries"] if e["digest"] == y] + assert (ey["status"], ey["reason"]) == ("pending", "pending_floor") + # B3: Y is selected and forecast against KING_D X (the forecast / need + # assertions); on this fixture's windows its cohort may fall short of the + # floors (pending_floor), as in test_w_offbox_judged_only. + assert y in r3["judged"] or {"digest": y, "reason": "pending_floor"} in r3["skipped"] + assert {v["king_digest"] for v in r3["verdicts"]} <= {x} + + +def test_held_settlement_forecasts_nothing_in_process(tmp_path): + _need_rule() + fx = _fixture(tmp_path / "fx") + rig, _ = _rig(tmp_path / "v", fx) + per = _run(_early(rig), (B1, B2, B3)) + _check_story(rig, fx) + y = fx["late"]["digest"] + assert per[B2] == [], f"B2 forecast {per[B2]}: a held settlement scores no new entry" + # owner 2026-12-01 (floor before forecasts): on this fixture's windows Y + # falls short of the floors at B3 (pending_floor), so nothing is forecast + assert {"digest": y, "reason": "pending_floor"} in _report(rig, B3)["skipped"] + assert per[B3] == [], per[B3] + + +def test_held_settlement_settle_request_has_no_members(tmp_path): + """The eval host's settle pool phase: one call per settlement; at B2 its + need is empty (no live forecast, no duel) and the host forecasts + nothing.""" + _need_rule() + fx = _fixture(tmp_path / "fx") + rig, host = _rig(tmp_path / "v", fx, offload=True) + _early(rig) + calls = {} + for b in (B1, B2, B3): + n_req, n_fc = len(host.requests), len(rig.eval_host.calls) + _run(rig, (b,)) + calls[b] = (len(host.requests) - n_req, len(rig.eval_host.calls) - n_fc) + _check_story(rig, fx) + need = {r["judge"]["boundary"]: sorted(r["need"]) for r in host.requests} + assert calls[B2] == (1, 0), f"B2 settle/forecast calls {calls[B2]}: expected (1, 0)" + assert need[B2] == [], f"B2 settle request needs {need[B2]}; expected nothing" + # owner 2026-12-01: Y is below the floors at B3 (the host's floor + # pre-check), so the settle request needs nothing + assert need[B3] == [], need[B3] + + +def test_held_settlement_public_half_asks_king_d_alone(tmp_path): + from tests.accept.w7a import pub + from tests.accept.w8c.test_w8c_public import PublicHost + + _need_rule() + root = tmp_path / "public" + indexes = pub.index_only(root) + fx = _fixture(tmp_path / "fx") + rig, _ = _rig(tmp_path / "v", fx, public=lambda f: PublicHost(f, indexes)) + _early(rig) + step = h.step(rig) + asked = {} + for b in (B1, B2, B3): + rig.bench_host.down = (b == B1) + before = len(rig.eval_host.public_calls) + assert step(b) is not None, f"boundary {b} did not settle" + asked[b] = sorted(c["digest"] for c in rig.eval_host.public_calls[before:]) + assert asked[B2] == [fx["house"]["digest"]], \ + f"B2 public half asked {asked[B2]}: KING_D alone (no new entry is scored)" + assert "public" in _report(rig, B2) + # owner 2026-12-01: Y below the floors at B3: KING_D alone again + assert asked[B3] == [fx["x"]], asked[B3] 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..564ee3104 --- /dev/null +++ b/tests/accept/w_offbox/test_w_offbox_judged_only.py @@ -0,0 +1,226 @@ +"""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" + # owner 2026-12-01 (floor before forecasts): Y, the one member duelled at + # B3, falls short of the floors on this fixture's windows (pending_floor), + # so nothing is forecast live (the lost entry and the house never are) + assert {"digest": y, "reason": "pending_floor"} in _report(rig, B3)["skipped"] + assert per[B3] == [], f"B3 forecast {per[B3]}: Y is below the floors" + + +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, house = fx["x"], fx["loser"]["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] == [], f"B3 settle request needs {need[B3]}: Y is below the floors" + 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, house = fx["x"], fx["loser"]["digest"], fx["house"]["digest"] + asked = [c["digest"] for c in new.eval_host.public_calls] + assert sorted(asked) == sorted([x, lo, house, house, x]), \ + f"public half asked {asked}: B1 X, L, house; B2 KING_D alone; B3 KING_D alone " \ + "(Y below the floors, owner 2026-12-01)" + assert len(ref.eval_host.public_calls) > len(asked) + assert "public" in _report(new, B2), "the only-held settlement keeps its public record"