diff --git a/cascade/validator/lane_d.py b/cascade/validator/lane_d.py index 77bbf24ef..0f67331af 100644 --- a/cascade/validator/lane_d.py +++ b/cascade/validator/lane_d.py @@ -78,7 +78,15 @@ a re-gate is then a typed ``bench_hold`` skip). FAIL CLOSED: with no ``bench`` or no ``boundary_block_hash`` (the legacy call) every candidate is ``bench_hold``: never crowned, lost or charged. The report carries the - ``gate`` record whenever the gate ran; a crowned report always has one; + ``gate`` record whenever the gate ran; a crowned report always has one. + Held first (owner 2026-12-01): a held candidate was scored on an earlier + settlement's set, so its LCB is never ranked against this settlement's + clears. The held candidates are swept and decided first (the earliest + hold, then the best LCB); when one passes it is crowned and every new + 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; 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`` @@ -647,6 +655,20 @@ def _ranked(cands: list[dict]) -> list[dict]: return sorted(cands, key=lambda c: (-c["lcb"], c["reveal_ts"], c["digest"])) +def _held_ranked(cands: list[dict]) -> list[dict]: + """Held candidates in crown order (owner 2026-12-01): the earliest hold + first (holds from one settlement share its eval set), then max-T.""" + return sorted(cands, key=lambda c: (int(c["held_from"]["boundary"]), -c["lcb"], + c["reveal_ts"], c["digest"])) + + +def _held_crowns(cands: list[dict], outcomes: dict[str, str]) -> bool: + """Owner 2026-12-01 (lane D order = reveal order): does a held candidate + pass the gate? Then it is decided before, and crowned instead of, every + clear first made at this settlement (scored on a different eval set).""" + return any(c.get("held") and outcomes.get(c["digest"]) == "pass" for c in cands) + + def _gate_result(res: dict, digest: str) -> dict: """A :func:`paired_gate` result projected onto one ``gate.results[]`` item (no free text, §14.3 item 4).""" @@ -698,7 +720,10 @@ def _run_gate(cands: list[dict], state: dict, cfg, boundary: int, sweep with KING_D and the house in ``bench``'s session (the drawn suite, plus the sentinel suite when one is given) decided by :func:`paired_gate`. A host sweep that raises is that candidate's - ``bench_hold`` (infrastructure, never the miner's fault).""" + ``bench_hold`` (infrastructure, never the miner's fault). Held first + (owner 2026-12-01): the held candidates are swept first; when one passes + the new clears are not swept (``bench_hold``: undecided, re-queued by + :func:`settle_lane_d`). Results stay in max-T order.""" if not cands: return None, {} if bench is None or block_hash is None: @@ -708,10 +733,17 @@ def _run_gate(cands: list[dict], state: dict, cfg, boundary: int, suites = [suite] if sentinel is None else [suite, str(sentinel)] king_d, house_d = str(state["king"]["digest"]), str(state["house"]["digest"]) seed = f"lane-d/1:gate:{int(boundary)}:{record['block_hash']}" - results, outcomes = [], {} - for c in _ranked(cands): + by_dg, outcomes = {}, {} + held = _held_ranked([c for c in cands if c.get("held")]) + fresh = _ranked([c for c in cands if not c.get("held")]) + for c in [*held, *fresh]: dg = c["digest"] bound = None + if not c.get("held") and _held_crowns(held, outcomes): + # A held candidate crowns: this new clear is not decided here. + outcomes[dg] = "bench_hold" + by_dg[dg] = _gate_result({"outcome": "bench_hold", "session": bench.session_id}, dg) + continue try: cand_rec, king_rec, house_rec = bench.paired(dg, king_d, house_d, suites=suites) except Exception: # any host failure is infrastructure: hold, never crown @@ -737,8 +769,8 @@ def _run_gate(cands: list[dict], state: dict, cfg, boundary: int, if "held_from" in c: # RV7 B2: a held candidate (no verdict here) names its hold. result["held_from"] = dict(c["held_from"]) - results.append(result) - return {**record, "results": results}, outcomes + by_dg[dg] = result + return {**record, "results": [by_dg[c["digest"]] for c in _ranked(cands)]}, outcomes def _adopted_gate(cands: list[dict], persisted: dict, where) -> tuple[dict | None, dict[str, str]]: @@ -2122,10 +2154,19 @@ def skip(dg: str, reason: str, rec: dict | None = None) -> None: # Recovery: the outcomes the persisted, verified report recorded. gate, gate_outcomes = _adopted_gate(candidates, persisted, rp) by_verdict = {v["digest"]: v for v in verdicts} + held_crowns = _held_crowns(candidates, gate_outcomes) passing = [] for c in candidates: dg, outcome = c["digest"], gate_outcomes[c["digest"]] rec = house_rec if c["house"] else state["entries"][dg] + if held_crowns and not c.get("held") and outcome in ("pass", "bench_hold"): + # Owner 2026-12-01: a held candidate crowns, so this settlement's + # clear (another eval set) is re-queued unjudged and uncharged, + # like a hold whose KING_D changed: judged afresh against the new + # king (its windows stay used; its verdict stays ``cleared``). + rec.pop("gate_hold", None) + rec.update(status="pending", reason="pending_floor", confirm=None, frozen_set=None) + continue if outcome == "pass": rec.pop("gate_hold", None) passing.append(c) @@ -2165,7 +2206,7 @@ def skip(dg: str, reason: str, rec: dict | None = None) -> None: new_king = None if passing: - best = _ranked(passing)[0] + best = (_held_ranked(passing) if held_crowns else _ranked(passing))[0] old = state["king"] if not old.get("house"): state["prior_kings"] = [_king_record(old)] + state["prior_kings"] diff --git a/docs/MINER_LANE_D.md b/docs/MINER_LANE_D.md index 6532ea41e..ccb05c5d9 100644 --- a/docs/MINER_LANE_D.md +++ b/docs/MINER_LANE_D.md @@ -231,6 +231,12 @@ blocks, about 24 h) of `submit`, or the entry expires (`ready_expired`). outage or a sweep past its time limit (`[eval] bench_hold_max_hours`, 9 h) 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. ## How you are paid diff --git a/tests/accept/w5g/PATHS b/tests/accept/w5g/PATHS index 61ba793ed..93d62e22c 100644 --- a/tests/accept/w5g/PATHS +++ b/tests/accept/w5g/PATHS @@ -8,3 +8,5 @@ cascade/validator/lane_d_state.py # report enums and the schema file, only if a reason or record must change. cascade/validator/lane_d_report.py cascade/validator/schemas/lane_d_report_1.json +# owner 2026-12-01 held first: the crown order paragraph (miner doc). +docs/MINER_LANE_D.md diff --git a/tests/accept/w5g/test_w5g_held_first.py b/tests/accept/w5g/test_w5g_held_first.py new file mode 100644 index 000000000..e65820fb7 --- /dev/null +++ b/tests/accept/w5g/test_w5g_held_first.py @@ -0,0 +1,264 @@ +"""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. +""" + +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, + bench_session, + bench_table, + block_hash, + boundary, + entry, + entry_of, + fixture_key, + forecasts, + read_state, + report_digest, + rows_of, + settle, + uids, + verdict_of, +) + +REPO = Path(__file__).resolve().parents[3] +# The lane D checker the deployed validator releases carry (the band release, +# test_w_hz_settle's DEPLOYED_CHECKER) and the pre-band one (09f19baa, the +# same file as a4600dfe / 00f3139c). Satellites never update. +CHECKERS = {"deployed": ("75310262", "b944dc276f337638d4ed3403586060e44213a0cf"), + "pre-band": ("09f19baa", "327df328aad9a8474da18c3a4b0b494faaf13e88")} +# test_no_held_candidate_keeps_max_t_order's report body digest on main +# 49ea024c, before this rule: with no held candidate the bytes are unchanged. +NO_HELD_REPORT_SHA256 = "06ace23dfc4ac7dc8d8c353a1f9471d387187189a8dd371cbf0181e97d4a0ab2" + + +def _need_held_first() -> None: + """The held-first helpers exist (so every test fails on the code before + this rule by assertion, not an import error).""" + import cascade.validator.lane_d as lane_d + + for name in ("_held_crowns", "_held_ranked"): + assert callable(getattr(lane_d, name, None)), f"lane_d.{name} missing (held first not built)" + + +def _flow(tmp_path: Path) -> tuple[Flow, dict]: + """X held at boundary 2 (a lower-quality clear); Y readied after it.""" + f = Flow(tmp_path, mode2="host_down", x_quality="good") + assert read_state(f.path)["entries"][f.x["digest"]]["status"] == "hold", "fixture: X not held" + y = entry("y", reveal_ts=T_X + 60, after=2) + f.models[y["digest"]] = ("sharp", "y") + f.uid_of = uids(f.x, y) + return f, y + + +class _PartDown(BenchHost): + """The bench pod answers, except for the digests in ``down`` (raises).""" + + def __init__(self, table: dict, down: set[str]): + super().__init__(table) + self.down = set(down) + + def __call__(self, digests, suites) -> dict: + if self.down & set(digests): + self.calls.append((tuple(digests), tuple(suites))) + raise ConnectionError("fixture: bench host unreachable for this digest") + return super().__call__(digests, suites) + + +def _settle(f: Flow, n: int, snap: int, entries, spec: dict, down=()): + pool_dir, recs = f.pool(snap) + host = _PartDown(bench_table(spec), set(down)) + out = settle(f.cfg, boundary(n), pool_dir, entries, f.h0, forecasts(recs, f.models), + f.uid_of, f.path, hash_=block_hash(f"b{n}"), + bench=bench_session(host, f"sess-b{n}")) + f.reports[n], f.hosts[n], f.n = out.report, host, n + 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).""" + _need_held_first() + from cascade.validator.lane_d import _ranked + + f = Flow(tmp_path, mode2="regress") + assert read_state(f.path)["king"]["digest"] == f.h0["digest"], "fixture: X must lose" + y = entry("y", reveal_ts=T_X + 60, after=2) + z = entry("z", reveal_ts=T_X + 120, after=2) + f.models.update({y["digest"]: ("sharp", "y"), z["digest"]: ("good", "z")}) + f.uid_of = uids(f.x, y, z) + yd, zd, h = y["digest"], z["digest"], f.h0["digest"] + report, host = _settle(f, 3, 3, [f.x, y, z], + {yd: 0.85, zd: 0.85, h: 1.0}) + cleared = [v for v in report["verdicts"] if v["cleared"]] + assert {v["digest"] for v in cleared} <= {yd, zd} and cleared, report["verdicts"] + order = [c["digest"] for c in _ranked([{"digest": v["digest"], "lcb": v["lcb"], + "reveal_ts": entry_of(report, v["digest"])["reveal_ts"]} + for v in cleared])] + assert [r["digest"] for r in report["gate"]["results"]] == order + assert all(r["outcome"] == "pass" for r in report["gate"]["results"]) + assert report["crowned"] == order[0] + 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)