From 0bed294ff088b8fc43867a7708dd49c5ca11303d Mon Sep 17 00:00:00 2001 From: tensorlink-dev Date: Tue, 1 Dec 2026 03:54:56 +0000 Subject: [PATCH 1/2] feat(lane D): full public bench of a newly crowned king, published as status king.bench Owner 2026-12-01: "if someone is crowned [on lane D] we score them". After a settlement is published, a miner KING_D without a stored bench gets ONE display-only sweep on gift/boom/time/fev on the lane D bench host (SweepSession over SSHBenchHost.sweep_full, lane A's sidecar settings), on its own thread with an allowance ending an hour before the next boundary. The bench host's reply now carries per-suite aggregate CRPS/MASE beside the unchanged gate rows. The result is stored in the lane D state dir and published in the unsigned status/lane_d.json as king.bench under lane A's BenchScores keys (gifteval_crps/gifteval_mase, ... the website's keys); prior kings keep theirs. Failures are logged and retried next settlement; the house is never benched. Never gate, crown, pay, signed report or any consensus value; main validator only (needs --lane-d-inputs bench_hosts). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BMT4D7f8wd5dXsASyWUBwe --- cascade/eval/lane_d_bench_sweep.py | 62 +++- cascade/validator/lane_d_bench_host.py | 58 +++- cascade/validator/lane_d_king_bench.py | 323 ++++++++++++++++++ cascade/validator/lane_d_wiring.py | 76 ++++- cascade/validator/main.py | 9 +- tests/accept/w3b6a/PATHS | 5 + .../w3b6a/test_w3b6a_king_full_bench.py | 80 +++++ tests/accept/w8b/PATHS | 9 + tests/accept/w8b/README.md | 17 + tests/accept/w8b/test_w8b_king_full_bench.py | 225 ++++++++++++ 10 files changed, 849 insertions(+), 15 deletions(-) create mode 100644 cascade/validator/lane_d_king_bench.py create mode 100644 tests/accept/w3b6a/test_w3b6a_king_full_bench.py create mode 100644 tests/accept/w8b/test_w8b_king_full_bench.py diff --git a/cascade/eval/lane_d_bench_sweep.py b/cascade/eval/lane_d_bench_sweep.py index afed1d1f9..8e295d090 100644 --- a/cascade/eval/lane_d_bench_sweep.py +++ b/cascade/eval/lane_d_bench_sweep.py @@ -34,6 +34,7 @@ import argparse import json import logging +import math import shutil import subprocess import sys @@ -159,6 +160,57 @@ def _error_rows(suites: Sequence[str]) -> dict: return {s: {"status": "error", "rows": []} for s in suites} +def _positive(v) -> float | None: + if isinstance(v, bool) or not isinstance(v, (int, float)): + return None + f = float(v) + return f if math.isfinite(f) and f > 0 else None + + +def suite_aggregates(report: Mapping | None) -> dict: + """Each suite's aggregate CRPS / MASE of one sidecar report, keyed by gate + key: ``{"gift": {"status", "crps", "mase", "partial"[, "data_revision"] + [, "bench_method"]}, …}``. The suite-level ``metrics`` lane A's six + numbers come from (:func:`cascade.eval.benchmarks.extract_bench_scores`: + same metric aliases, same coverage rule), so a lane D king's public + numbers compare with the lane A king's signed ones. Display only (the + gate pairs item rows, never these). A non-finite or non-positive metric + is ``None``; ``{}`` for a missing report. Never raises.""" + if not isinstance(report, Mapping): + return {} + from .benchmarks import ( + _CRPS_ALIASES, + _MASE_ALIASES, + ITEM_SUITE_KEY, + _pick_metric, + suite_incomplete, + ) + + out: dict[str, dict] = {} + try: + method = report.get("bench_method") + revisions = report.get("data_revisions") or {} + for s in report.get("suites") or []: + key = ITEM_SUITE_KEY.get(s.get("suite")) if isinstance(s, Mapping) else None + if key is None: + continue + m = s.get("metrics") if isinstance(s.get("metrics"), Mapping) else {} + agg = {"status": s.get("status"), + "crps": _positive(_pick_metric(dict(m), _CRPS_ALIASES)), + "mase": _positive(_pick_metric(dict(m), _MASE_ALIASES)), + "partial": bool(suite_incomplete(dict(s)))} + rev = revisions.get(s.get("suite")) if isinstance(revisions, Mapping) else None + if rev: + agg["data_revision"] = str(rev) + if isinstance(method, str) and method: + agg["bench_method"] = method + out[key] = agg + except Exception as e: # noqa: BLE001 — display numbers, never a verdict + log.warning("lane_d_bench: could not parse suite aggregates: %s", e) + return {} + return out + + def serve_sweep(request, *, cache, work_dir, contract=None, expect=None, sidecar: Callable | None = None, fingerprint: Mapping | None = None) -> dict: """Answer one :data:`REQUEST_SCHEMA` request (see the module docstring). @@ -169,6 +221,7 @@ def serve_sweep(request, *, cache, work_dir, contract=None, expect=None, digests, suites, contexts, grants, settings = _checked(request) names = _gate_keys() rows: dict[str, dict] = {} + aggregates: dict[str, dict] = {} dirs: list[tuple[str, Path]] = [] for dg in digests: # W15 lease: no process sharing the cache root evicts the entry between @@ -199,8 +252,15 @@ def serve_sweep(request, *, cache, work_dir, contract=None, expect=None, for (dg, _), rep in zip(dirs, reports, strict=True): got = item_rows_from_report(rep) rows[dg] = _error_rows(suites) if got is None else got + agg = suite_aggregates(rep) + if agg: + aggregates[dg] = {s: agg[s] for s in suites if s in agg} fp = probe_fingerprint() if fingerprint is None else dict(fingerprint) + # ``aggregates`` (the lane D king's public numbers, display only) rides + # beside ``rows``: the gate reads ``rows`` alone, so a box that predates + # it reads this reply unchanged. reply = {"schema": REPLY_SCHEMA, "rows": {dg: rows[dg] for dg in digests}, + "aggregates": {dg: aggregates[dg] for dg in digests if dg in aggregates}, "fingerprint": fp} json.dumps(reply, allow_nan=False) return reply @@ -255,4 +315,4 @@ def main(argv: list[str] | None = None) -> int: __all__ = ["REPLY_SCHEMA", "REQUEST_SCHEMA", "SWEEP_ERROR_CODES", "LaneDBenchSweepError", - "materialise", "probe_fingerprint", "serve_sweep"] + "materialise", "probe_fingerprint", "serve_sweep", "suite_aggregates"] diff --git a/cascade/validator/lane_d_bench_host.py b/cascade/validator/lane_d_bench_host.py index 46c5b5004..6aa2d5370 100644 --- a/cascade/validator/lane_d_bench_host.py +++ b/cascade/validator/lane_d_bench_host.py @@ -76,6 +76,12 @@ def set_contexts(self, contexts: Mapping[str, int]) -> None: """Each digest's effective context for this settlement (W8c source).""" self._contexts = {str(d): int(c) for d, c in contexts.items()} + def context_of(self, digest: str) -> int | None: + """``digest``'s effective context of the last settlement (``None``: + not set).""" + c = self._contexts.get(str(digest)) + return None if c is None else int(c) + def _resolve(self): from ..trainer.remote import load_hosts @@ -86,8 +92,11 @@ def _resolve(self): raise LaneDBenchHostError(f"{self.hosts_path}: no final/any bench host") return hosts[0] - def _request(self, digests: list[str], suites: list[str]) -> dict: - missing = [d for d in digests if d not in self._contexts] + def _request(self, digests: list[str], suites: list[str], + contexts: Mapping[str, int] | None = None) -> dict: + ctx = self._contexts if contexts is None else {str(d): int(c) + for d, c in contexts.items()} + missing = [d for d in digests if d not in ctx] if missing: raise LaneDBenchHostError(f"no effective context for {[d[:16] for d in missing]}") grants = {} @@ -95,7 +104,7 @@ def _request(self, digests: list[str], suites: list[str]) -> dict: g = None if self._grants is None else self._grants(d) grants[d] = None if g is None else dict(g) return {"schema": REQUEST_SCHEMA, "digests": digests, "suites": suites, - "contexts": {d: self._contexts[d] for d in digests}, "grants": grants, + "contexts": {d: ctx[d] for d in digests}, "grants": grants, "settings": {k: self.settings[k] for k in SETTINGS_KEYS}} @staticmethod @@ -114,10 +123,40 @@ def _checked(reply, digests: list[str]) -> dict: raise LaneDBenchHostError(f"reply rows for {dg[:16]} are malformed") return rows + @staticmethod + def _aggregates(reply: dict, digests: list[str]) -> dict: + """The reply's optional per-suite aggregates (display only; ``{}`` + from a bench host that predates them).""" + raw = reply.get("aggregates") + if not isinstance(raw, dict): + return {} + return {dg: {s: dict(a) for s, a in per.items() + if isinstance(s, str) and isinstance(a, dict)} + for dg, per in raw.items() if dg in digests and isinstance(per, dict)} + def __call__(self, digests, suites) -> dict: ds = [str(d) for d in digests] - ss = [str(s) for s in suites] - request = self._request(ds, ss) + return self._checked(self._sweep(ds, [str(s) for s in suites]), ds) + + def sweep_full(self, digests, suites, *, contexts: Mapping[str, int] | None = None, + timeout_s: float | None = None) -> dict: + """One display-only sweep (the lane D king's full public bench): the + ``__call__`` rows, each suite entry carrying the reply's + ``aggregate`` (``{"status", "crps", "mase", "partial", …}``) when the + bench host sent one. ``contexts`` overrides the settlement's map, + ``timeout_s`` caps the allowance. Raises as ``__call__`` does.""" + ds = [str(d) for d in digests] + reply = self._sweep(ds, [str(s) for s in suites], contexts=contexts, + timeout_s=timeout_s) + rows = self._checked(reply, ds) + aggs = self._aggregates(reply, ds) + return {dg: {s: ({**e, "aggregate": aggs[dg][s]} if s in aggs.get(dg, {}) else e) + for s, e in per.items()} for dg, per in rows.items()} + + def _sweep(self, ds: list[str], ss: list[str], *, + contexts: Mapping[str, int] | None = None, + timeout_s: float | None = None) -> dict: + request = self._request(ds, ss, contexts) host = self._resolve() from ..trainer.remote import build_ssh_argv @@ -130,8 +169,11 @@ def __call__(self, digests, suites) -> dict: args += ["--chain-toml", host.chain_toml] cmd = f"cd {shlex.quote(host.workdir)} && {env}" + " ".join(shlex.quote(a) for a in args) payload = json.dumps(request, sort_keys=True).encode("utf-8") + timeout = self.timeout_per_checkpoint_s * len(ds) + if timeout_s is not None: + timeout = min(timeout, float(timeout_s)) proc = self._run(build_ssh_argv(host, cmd), input=payload, capture_output=True, - timeout=self.timeout_per_checkpoint_s * len(ds), check=False) + timeout=timeout, check=False) err = (proc.stderr or b"").decode("utf-8", "replace")[-600:] if proc.returncode != 0: raise LaneDBenchHostError(f"{host.name}: lane D bench sweep exited " @@ -144,7 +186,9 @@ def __call__(self, digests, suites) -> dict: reply = json.loads(lines[-1]) except ValueError as e: raise LaneDBenchHostError(f"{host.name}: reply is not JSON ({e})") from e - return self._checked(reply, ds) + if not isinstance(reply, dict): + raise LaneDBenchHostError(f"not a {REPLY_SCHEMA} reply") + return reply __all__ = ["REPLY_SCHEMA", "REQUEST_SCHEMA", "SETTINGS_KEYS", "LaneDBenchHostError", "SSHBenchHost", diff --git a/cascade/validator/lane_d_king_bench.py b/cascade/validator/lane_d_king_bench.py new file mode 100644 index 000000000..33c3e6d1a --- /dev/null +++ b/cascade/validator/lane_d_king_bench.py @@ -0,0 +1,323 @@ +"""The lane D king's full public bench (owner 2026-12-01: "if someone is +crowned we score them"). Main validator only, DISPLAY ONLY. + +When a settlement leaves a miner KING_D without a stored bench, the +production step (:class:`cascade.validator.lane_d_wiring.LaneDStep`) hands +the king to :meth:`KingBench.schedule` AFTER the settlement is published. +One full sweep of that king on all four public suites +(:data:`FULL_SUITES`: GIFT-Eval, BOOM, TIME, FEV) then runs on a daemon +thread on the lane D bench host, through a +:class:`~cascade.validator.lane_d_bench.SweepSession` over +:meth:`~cascade.validator.lane_d_bench_host.SSHBenchHost.sweep_full` (lane +A's DEC-CA-0063 sidecar settings, so the numbers compare with the lane A +king's signed ones). The result (per-suite aggregate CRPS / MASE, the bench +method, the data revisions, the digest, ``as_of``) is persisted at +``/lane_d_king_bench/.json`` and published in the +unsigned ``status/lane_d.json`` as ``king.bench`` (prior kings keep theirs), +with the six/eight numbers under lane A's ``BenchScores`` key convention +(``gifteval_crps``, ``gifteval_mase``, ``boom_*``, ``time_*``, ``fev_*``): +the keys ``cascade/website`` reads. + +Never part of the gate, the crown, pay, the signed report or any consensus +value; external validators never run it (no bench host is wired there). + +Timing: the sweep never blocks the step (its own thread, one at a time) and +its SSH allowance ends :data:`GUARD_S` before the next settlement boundary +(chain time: the boundary's on-chain timestamp plus the grid's blocks), so +it never overlaps the next settlement's gate sweep on the bench host. With +less than :data:`MIN_RUN_S` left it is not started. A failure (host down, +timeout, a reply without aggregates) is logged and the king is retried at +the next settlement; a sweep that completed without all four suites is kept +(published, ``complete: false``) and retried up to :data:`MAX_ATTEMPTS` +completed sweeps. The house is never benched here. +""" + +from __future__ import annotations + +import json +import logging +import math +import os +import re +import threading +import time +from collections.abc import Callable, Iterable, Mapping +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +log = logging.getLogger("cascade.validator.lane_d") + +SCHEMA = "lane-d-king-bench/1" +STORE_DIR = "lane_d_king_bench" +SESSION_PREFIX = "lane-d-king-bench" +FULL_SUITES = ("gift", "boom", "time", "fev") +# gate key -> lane A's BenchScores prefix (the website's key convention) +FLAT_PREFIX = {"gift": "gifteval", "boom": "boom", "time": "time", "fev": "fev"} +GUARD_S = 3600.0 # the sweep's allowance ends this long before the next boundary +MIN_RUN_S = 900.0 # less time left than this: not started (retried next settlement) +MAX_ATTEMPTS = 4 # completed-but-incomplete sweeps before the partial result stands +_HEX64 = re.compile(r"[0-9a-f]{64}") + + +class KingBenchError(RuntimeError): + """The sweep answered nothing publishable (retried next settlement).""" + + +# ── the store ─────────────────────────────────────────────────────────────── + + +def bench_dir(state_dir) -> Path: + return Path(state_dir) / STORE_DIR + + +def bench_path(state_dir, digest: str) -> Path: + if not isinstance(digest, str) or not _HEX64.fullmatch(digest): + raise ValueError(f"lane D king bench: {digest!r} is not a 64-hex digest") + return bench_dir(state_dir) / f"{digest}.json" + + +def _attempts_path(state_dir, digest: str) -> Path: + return bench_path(state_dir, digest).with_suffix(".attempts.json") + + +def _read(path: Path) -> dict | None: + try: + doc = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + return doc if isinstance(doc, dict) else None + + +def _write(path: Path, doc: Mapping) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(f".{path.name}.tmp-{os.getpid()}-{threading.get_ident()}") + tmp.write_text(json.dumps(doc, sort_keys=True, allow_nan=False) + "\n", encoding="utf-8") + os.replace(tmp, path) + + +def load_bench(state_dir, digest: str) -> dict | None: + """The stored bench of ``digest`` (``None``: none, or unreadable). Never + raises.""" + try: + doc = _read(bench_path(state_dir, digest)) + except ValueError: + return None + if doc is None or doc.get("schema") != SCHEMA or doc.get("digest") != digest: + return None + return doc + + +def load_benches(state_dir, digests: Iterable[str]) -> dict[str, dict]: + out = {} + for dg in digests: + doc = load_bench(state_dir, dg) if isinstance(dg, str) else None + if doc is not None: + out[dg] = doc + return out + + +def attach_benches(doc: dict | None, benches: Mapping[str, Mapping]) -> dict | None: + """``doc`` (a ``status/lane_d.json`` document) with ``king.bench`` for a + miner king and ``bench`` on each prior king that has a stored one. + Mutates and returns ``doc``; ``None`` stays ``None``.""" + if doc is None: + return None + king = doc.get("king") + if isinstance(king, dict) and not king.get("house") and king.get("digest") in benches: + king["bench"] = json.loads(json.dumps(benches[king["digest"]])) + for p in doc.get("prior_kings") or []: + if isinstance(p, dict) and p.get("digest") in benches: + p["bench"] = json.loads(json.dumps(benches[p["digest"]])) + return doc + + +# ── the record ────────────────────────────────────────────────────────────── + + +def _positive(v) -> float | None: + if isinstance(v, bool) or not isinstance(v, (int, float)): + return None + f = float(v) + return f if math.isfinite(f) and f > 0 else None + + +def summarise(suites: Mapping[str, Mapping], *, digest: str, boundary: int, + as_of: str) -> dict: + """The stored / published bench of one sweep record's ``suites`` + (``{suite: {"status", "rows", "aggregate"?, …}}``). Raises + :class:`KingBenchError` when no suite has an aggregate pair (e.g. a bench + host that predates aggregates).""" + per: dict[str, dict] = {} + flat: dict[str, float] = {} + methods: set[str] = set() + revisions: dict[str, str] = {} + for s in FULL_SUITES: + e = suites.get(s) if isinstance(suites, Mapping) else None + e = e if isinstance(e, Mapping) else {} + agg = e.get("aggregate") if isinstance(e.get("aggregate"), Mapping) else {} + status = agg.get("status", e.get("status")) + crps, mase = _positive(agg.get("crps")), _positive(agg.get("mase")) + partial = bool(agg.get("partial") or e.get("partial")) + rows = e.get("rows") + rec = {"status": status if isinstance(status, str) else None, "crps": crps, + "mase": mase, "partial": partial, + "n_items": len(rows) if isinstance(rows, list) else 0} + method = agg.get("bench_method") or e.get("bench_method") + if isinstance(method, str) and method: + methods.add(method) + rec["bench_method"] = method + rev = agg.get("data_revision") or e.get("data_revision") + if isinstance(rev, str) and rev: + revisions[s] = rev + rec["data_revision"] = rev + per[s] = rec + if status == "ok" and not partial and crps is not None and mase is not None: + flat[f"{FLAT_PREFIX[s]}_crps"] = crps + flat[f"{FLAT_PREFIX[s]}_mase"] = mase + if not flat: + raise KingBenchError("the sweep returned no suite aggregate (a bench host that " + f"predates them?): {json.dumps(per, sort_keys=True)[:300]}") + return {"schema": SCHEMA, "digest": digest, "boundary": int(boundary), "as_of": as_of, + "suites": per, "bench_method": methods.pop() if len(methods) == 1 else None, + "data_revisions": revisions, + "complete": len(flat) == 2 * len(FULL_SUITES), **flat} + + +# ── the runner ────────────────────────────────────────────────────────────── + + +def _thread(fn: Callable[[], None]) -> None: + threading.Thread(target=fn, name="lane-d-king-bench", daemon=True).start() + + +def _iso(ts: float) -> str: + return datetime.fromtimestamp(float(ts), UTC).strftime("%Y-%m-%dT%H:%M:%SZ") + + +class KingBench: + """Schedules and runs the lane D king's full bench (module docstring). + ``host`` is the lane D bench host (``sweep_full`` and ``context_of``: + :class:`~cascade.validator.lane_d_bench_host.SSHBenchHost`); ``spawn`` + runs the sweep (default: a daemon thread); ``now`` is wall-clock + seconds.""" + + def __init__(self, host: Any, *, state_dir, suites: Iterable[str] = FULL_SUITES, + guard_s: float = GUARD_S, min_run_s: float = MIN_RUN_S, + max_attempts: int = MAX_ATTEMPTS, + spawn: Callable[[Callable[[], None]], None] | None = None, + now: Callable[[], float] = time.time): + self.host = host + self.state_dir = Path(state_dir) + self.suites = tuple(suites) + self.guard_s = float(guard_s) + self.min_run_s = float(min_run_s) + self.max_attempts = int(max_attempts) + self._spawn = spawn or _thread + self._now = now + self._lock = threading.Lock() + self._running: str | None = None + + @property + def running(self) -> str | None: + """The digest being swept (``None``: idle).""" + with self._lock: + return self._running + + def _attempts(self, digest: str) -> int: + doc = _read(_attempts_path(self.state_dir, digest)) or {} + n = doc.get("attempts", 0) + return int(n) if isinstance(n, int) and not isinstance(n, bool) else 0 + + def due(self, digest: str) -> bool: + """``digest`` still needs a sweep: none stored, or an incomplete one + with completed attempts left.""" + stored = load_bench(self.state_dir, digest) + if stored is not None and stored.get("complete") is True: + return False + return self._attempts(digest) < self.max_attempts + + def schedule(self, *, digest: str, boundary: int, deadline_ts: float, + on_done: Callable[[dict], None] | None = None) -> bool: + """Start one full sweep of ``digest`` (crowned / held at ``boundary``) + when it is due, none is running and at least ``min_run_s`` remain + before ``deadline_ts`` (wall-clock seconds; the allowance ends + there). ``on_done(bench)`` gets the stored record. True when + started. Never raises.""" + try: + if not self.due(digest): + return False + budget = float(deadline_ts) - float(self._now()) + if budget < self.min_run_s: + log.info("lane_d_king_bench_deferred settlement %d king %s: %.0f s left before " + "the pre-settlement guard; retried next settlement", int(boundary), + digest[:16], budget) + return False + context_of = getattr(self.host, "context_of", None) + context = context_of(digest) if callable(context_of) else None + if context is None: + log.warning("lane_d_king_bench_deferred settlement %d king %s: no effective " + "context; retried next settlement", int(boundary), digest[:16]) + return False + with self._lock: + if self._running is not None: + return False + self._running = digest + except Exception as e: # noqa: BLE001 — display only, never the settlement + log.warning("lane_d_king_bench_failed settlement %s: not scheduled (%s)", + boundary, e) + return False + + def run() -> None: + self._run(digest, int(boundary), int(context), budget, on_done) + + try: + self._spawn(run) + except Exception as e: # noqa: BLE001 + with self._lock: + self._running = None + log.warning("lane_d_king_bench_failed settlement %d: could not start (%s)", + int(boundary), e) + return False + log.info("lane_d_king_bench_started settlement %d king %s (allowance %.0f s)", + int(boundary), digest[:16], budget) + return True + + def _run(self, digest: str, boundary: int, context: int, timeout_s: float, + on_done: Callable[[dict], None] | None) -> None: + from .lane_d_bench import SweepSession + + try: + def sweep(digests, suites): + return self.host.sweep_full(digests, suites, contexts={digest: context}, + timeout_s=timeout_s) + + session = SweepSession(f"{SESSION_PREFIX}/{boundary}/{digest}", sweep) + rec, _, _ = session.paired(digest, digest, digest, suites=self.suites) + doc = summarise(rec["suites"], digest=digest, boundary=boundary, + as_of=_iso(self._now())) + _write(bench_path(self.state_dir, digest), doc) + if not doc["complete"]: + _write(_attempts_path(self.state_dir, digest), + {"attempts": self._attempts(digest) + 1, "boundary": boundary}) + log.info("lane_d_king_bench_done settlement %d king %s complete=%s gift " + "crps=%s mase=%s", boundary, digest[:16], doc["complete"], + doc.get("gifteval_crps"), doc.get("gifteval_mase")) + except Exception as e: # noqa: BLE001 — retried next settlement + log.warning("lane_d_king_bench_failed settlement %d king %s: %s: %s; retried next " + "settlement (display only: the crown and pay stand)", boundary, + digest[:16], type(e).__name__, e) + return + finally: + with self._lock: + self._running = None + if on_done is not None: + try: + on_done(doc) + except Exception as e: # noqa: BLE001 + log.warning("lane_d_king_bench: status republish failed (%s)", e) + + +__all__ = ["FLAT_PREFIX", "FULL_SUITES", "GUARD_S", "MAX_ATTEMPTS", "MIN_RUN_S", "SCHEMA", + "STORE_DIR", "KingBench", "KingBenchError", "attach_benches", "bench_path", + "load_bench", "load_benches", "summarise"] diff --git a/cascade/validator/lane_d_wiring.py b/cascade/validator/lane_d_wiring.py index 0b441e770..3fd376730 100644 --- a/cascade/validator/lane_d_wiring.py +++ b/cascade/validator/lane_d_wiring.py @@ -25,7 +25,14 @@ (``lane_d_publish_requests/.json``, with the sentinel record): the king-publish ops job copies the king to the mirrors and re-signs the index; nothing heavy runs here and a failure never withholds pay; -10. ``status/lane_d.json`` (W17, which embeds the W-S3 sentinel board). +10. ``status/lane_d.json`` (W17, which embeds the W-S3 sentinel board, and + the stored full public bench of KING_D and the prior kings); +11. with a ``king_bench`` wired (the main validator), a miner KING_D without + a stored full bench is handed to + :meth:`~cascade.validator.lane_d_king_bench.KingBench.schedule`: one + display-only sweep on all four public suites on its own thread, ending + an hour before the next boundary; never gating, never pay, never in the + signed report, retried at the next settlement after a failure. FAIL CLOSED: any unreadable input in 2-6 raises :class:`LaneDWiringError` before anything is written, published or swept; the W19 worker retries the @@ -70,6 +77,7 @@ bench_rows_dir, settle_lane_d, ) +from .lane_d_king_bench import attach_benches, load_benches from .lane_d_report import canonical_json from .lane_d_sentinel import sweep_and_publish from .lane_d_state import ( @@ -231,8 +239,13 @@ def __init__(self, cfg: Any, *, state_dir: str | Path, signer: Any, chain_factory: Callable[[], Any], store: Any, inputs: Callable[[int], LaneDInputs] | None = None, bench: Callable[[int], Any] | None = None, - cfg_at: Callable[[int], Any] | None = None): + cfg_at: Callable[[int], Any] | None = None, + king_bench: Any = None): self.cfg = cfg + # owner 2026-12-01: the display-only full public bench of a new king + self._king_bench = king_bench + self._status_lock = threading.Lock() + self._last_status: dict | None = None # containment (owner 2026-11-24): the config in force at a boundary # (the adopted overlay's), so an overlay-armed lane D settles; None = # the startup config (direct construction) @@ -507,11 +520,57 @@ def _publish_status(self, boundary: int, s: LaneDSettlement, house: Mapping, *, doc = build_lane_d_status(self.cfg, state=state, report=s.report, block=int(boundary), era_block=era, era_block_hash=era_hash, store=self.store) - publish_lane_d_status(self.store, doc) + if doc is not None: + kings = [doc["king"]["digest"]] + [p["digest"] for p in doc["prior_kings"]] + attach_benches(doc, load_benches(self.state_path.parent, kings)) + with self._status_lock: + publish_lane_d_status(self.store, doc) + self._last_status = doc except Exception as e: # noqa: BLE001 — status never gates pay log.warning("lane D settlement %d: status/lane_d.json not published (%s)", boundary, e) + def _republish_bench(self, bench: Mapping) -> None: + """A finished king bench into the last published status (the king + unchanged since). Display only; never raises.""" + try: + with self._status_lock: + doc = self._last_status + if doc is None or doc["king"].get("house") \ + or doc["king"]["digest"] != bench.get("digest"): + return + doc = json.loads(json.dumps(doc)) + attach_benches(doc, {str(bench["digest"]): dict(bench)}) + publish_lane_d_status(self.store, doc) + self._last_status = doc + except Exception as e: # noqa: BLE001 — status never gates pay + log.warning("lane D: king bench not republished in status/lane_d.json (%s)", e) + + def _schedule_king_bench(self, boundary: int, inp: LaneDInputs) -> None: + """Step 11 (module docstring): after the settlement is published. + Never raises, never waits for the sweep.""" + kb = self._king_bench + if kb is None: + return + try: + king = load_state(self.state_path, dict(inp.house))["king"] + if king.get("house"): + return + ts = getattr(inp, "boundary_ts", None) + if ts is None: + log.info("lane_d_king_bench_deferred settlement %d: no boundary timestamp", + boundary) + return + from ..shared.config import BLOCK_SECONDS, effective_epoch_blocks + + grid = int(effective_epoch_blocks(self.cfg.round, int(boundary))) + deadline = float(ts) + grid * BLOCK_SECONDS - float(kb.guard_s) + kb.schedule(digest=str(king["digest"]), boundary=int(boundary), + deadline_ts=deadline, on_done=self._republish_bench) + except Exception as e: # noqa: BLE001 — display only, never the settlement + log.warning("lane_d_king_bench_failed settlement %d: not scheduled (%s)", + boundary, e) + def _catch_up(self, settled: int, inp: LaneDInputs, latest: dict | None) -> dict: """A settlement saved at ``settled`` but never published (its publish failed and the tick moved on): publish it now, re-scoring nothing. @@ -748,6 +807,7 @@ def _produce(self, b: int) -> LaneDSettlement | None: self._publish(b, s) self._request_publication(b, s, record) self._publish_status(b, s, inp.house, era=era, era_hash=era_hash) + self._schedule_king_bench(b, inp) return s @@ -756,7 +816,7 @@ def build_lane_d_step(cfg: Any, *, state_dir: str | Path, signer: Any, inputs: Callable[[int], LaneDInputs] | None = None, bench: Callable[[int], Any] | None = None, cfg_at: Callable[[int], Any] | None = None, - always: bool = False) -> LaneDStep | None: + always: bool = False, king_bench: Any = None) -> LaneDStep | None: """The lane D step for ``cfg`` (the full ``ChainConfig``), or ``None`` while ``[lane_d] from_block = 0`` (nothing is built, read or called). ``always`` (containment, owner 2026-11-24; the validator passes it with @@ -765,11 +825,15 @@ def build_lane_d_step(cfg: Any, *, state_dir: str | Path, signer: Any, unarmed — until an adopted overlay arms lane D. ``chain_factory()`` builds the step's own read-only chain reader (``block_hash(block) -> str``) on the step's thread, at its first armed - call; ``store`` is the bucket the report, receipt and status go to.""" + call; ``store`` is the bucket the report, receipt and status go to. + ``king_bench`` (main validator only) is the display-only + :class:`~cascade.validator.lane_d_king_bench.KingBench` (``None``: no + king bench).""" if not always and int(getattr(getattr(cfg, "lane_d", None), "from_block", 0) or 0) <= 0: return None return LaneDStep(cfg, state_dir=state_dir, signer=signer, chain_factory=chain_factory, - store=store, inputs=inputs, bench=bench, cfg_at=cfg_at) + store=store, inputs=inputs, bench=bench, cfg_at=cfg_at, + king_bench=king_bench) __all__ = ["RECEIPT_LATEST_KEY", "WIRING_ERROR_CODES", "LaneDInputs", "LaneDStep", diff --git a/cascade/validator/main.py b/cascade/validator/main.py index ccff674ca..2591ca237 100644 --- a/cascade/validator/main.py +++ b/cascade/validator/main.py @@ -606,6 +606,13 @@ def main(argv: list[str] | None = None) -> int: chain_factory=lambda: ChainClient.from_config( runner.cfg, network=args.network, history_network=_history(args)), cfg_at=runner.cfg_at, always=True, **lane_d_services) + # owner 2026-12-01: the display-only full public bench of a new lane D + # king, on the lane D bench host (only where --lane-d-inputs wires one) + lane_d_king_bench = None + if lane_d_services is not None and lane_d_services.get("bench_host") is not None: + from .lane_d_king_bench import KingBench + + lane_d_king_bench = KingBench(lane_d_services["bench_host"], state_dir=lane_d_dir) runner.lane_d_step = build_lane_d_step( runner.cfg, state_dir=lane_d_dir, signer=runner.bench_signer, @@ -613,7 +620,7 @@ def main(argv: list[str] | None = None) -> int: runner.cfg, network=args.network, history_network=_history(args)), store=lane_d_store, inputs=lane_d_inputs, bench=None if lane_d_inputs is None else lane_d_inputs.bench, - cfg_at=runner.cfg_at, always=True) + cfg_at=runner.cfg_at, always=True, king_bench=lane_d_king_bench) if armed_at_start: log.info("lane D armed from block %d: settlements run off the poll thread", int(runner.cfg.lane_d.from_block)) diff --git a/tests/accept/w3b6a/PATHS b/tests/accept/w3b6a/PATHS index 421013ac2..032c118a6 100644 --- a/tests/accept/w3b6a/PATHS +++ b/tests/accept/w3b6a/PATHS @@ -14,3 +14,8 @@ cascade/validator/lane_d_bench_host.py cascade/validator/lane_d_inputs.py # #903: the offloaded sweep's remote command resolves uv on the host. cascade/validator/eval_offload.py +# Owner 2026-12-01 (the lane D king's display-only full bench, W8b): the +# reply also carries each digest's per-suite aggregate CRPS / MASE +# (suite_aggregates: lane A's extract_bench_scores convention) beside the +# unchanged gate rows; SSHBenchHost.sweep_full returns them merged into the +# rows, with a context override and a capped allowance. diff --git a/tests/accept/w3b6a/test_w3b6a_king_full_bench.py b/tests/accept/w3b6a/test_w3b6a_king_full_bench.py new file mode 100644 index 000000000..92c84ff1b --- /dev/null +++ b/tests/accept/w3b6a/test_w3b6a_king_full_bench.py @@ -0,0 +1,80 @@ +"""W3b6a x owner 2026-12-01 (the lane D king's display-only full public +bench): the bench host's reply carries each digest's per-suite AGGREGATE CRPS +/ MASE (the suite-level ``metrics`` lane A's six numbers come from, same +metric aliases and coverage rule as ``extract_bench_scores``) beside the +gate's item ``rows``; the box's ``SSHBenchHost.sweep_full`` returns the rows +with each suite's ``aggregate`` merged in, with a context override and a +capped allowance. The gate's ``__call__`` rows are unchanged. Missing +features on the base fail by assertion. Contract: README.md.""" + +from __future__ import annotations + +from . import helpers as h + +A = "a" * 64 +FULL = ("gift", "boom", "time", "fev") + + +def _report(seed: int) -> dict: + rep = h.report_for(seed, FULL) + for i, s in enumerate(rep["suites"]): + s["metrics"] = ({"CRPS": 0.4 + 0.01 * i, "MASE": 0.8 + 0.01 * i} if i % 2 else + {"crps": 0.4 + 0.01 * i, "mase": 0.8 + 0.01 * i}) + rep["suites"][3]["metrics"] = {"crps": float("nan"), "mase": 0.9} + rep["bench_method"] = "observed_mask/3" + rep["data_revisions"] = {"gift-eval": "rev-g", "boom": "rev-b"} + return rep + + +def test_the_reply_carries_suite_aggregates_beside_unchanged_rows(tmp_path): + from cascade.eval.benchmarks import item_rows_from_report + + m = h.sweep_mod() + assert hasattr(m, "suite_aggregates"), "no suite_aggregates on the bench host" + e = h.Entry(5) + cache = h.cache(tmp_path, e) + sidecar = h.Sidecar({e.digest: _report(5)}) + got = m.serve_sweep(h.request([e.digest], suites=FULL), cache=cache, + work_dir=tmp_path / "work", sidecar=sidecar, + fingerprint=dict(h.FINGERPRINT)) + assert got["rows"][e.digest] == item_rows_from_report(_report(5)), "gate rows unchanged" + agg = got.get("aggregates", {}).get(e.digest) + assert agg is not None, "the reply carries no aggregates" + assert agg["gift"] == {"status": "ok", "crps": 0.4, "mase": 0.8, "partial": False, + "data_revision": "rev-g", "bench_method": "observed_mask/3"} + assert agg["boom"]["crps"] == 0.4 + 0.01 and agg["boom"]["mase"] == 0.8 + 0.01 + assert agg["time"]["crps"] == 0.4 + 0.02 and "data_revision" not in agg["time"] + assert agg["fev"]["crps"] is None and agg["fev"]["mase"] == 0.9, "non-finite is None" + + +def _host(tmp_path, run): + host = h.host_mod().SSHBenchHost(h.hosts_file(tmp_path), cache_dir="/root/c", + budget_bytes=10 ** 9, run=run, + settings={**h.SETTINGS, "timeout_s_per_checkpoint": 7200}) + host.set_contexts({A: 4096}) + return host + + +def test_sweep_full_merges_aggregates_with_a_context_override_and_capped_allowance(tmp_path): + rows = {A: h.rows_entry(1, FULL)} + aggs = {A: {"gift": {"status": "ok", "crps": 0.4, "mase": 0.8, "partial": False}}} + run = h.Run({**h.reply(rows), "aggregates": aggs}) + host = _host(tmp_path, run) + assert callable(getattr(host, "sweep_full", None)), "SSHBenchHost has no sweep_full" + got = host.sweep_full((A,), FULL, contexts={A: 16384}, timeout_s=1234.0) + assert got[A]["gift"] == {**rows[A]["gift"], "aggregate": aggs[A]["gift"]} + assert got[A]["boom"] == rows[A]["boom"], "no aggregate: the entry as replied" + assert run.request()["contexts"] == {A: 16384} + assert run.calls[0]["timeout"] == 1234.0 + assert host.context_of(A) == 4096 and host.context_of("f" * 64) is None + # the gate's call keeps its rows (aggregates ignored) and lane A's allowance + assert host((A,), FULL) == rows + assert run.calls[1]["timeout"] == 7200.0 + + +def test_a_bench_host_without_aggregates_still_answers_the_gate(tmp_path): + rows = {A: h.rows_entry(2, FULL)} + host = _host(tmp_path, h.Run(h.reply(rows))) + assert callable(getattr(host, "sweep_full", None)), "SSHBenchHost has no sweep_full" + assert host((A,), FULL) == rows + assert host.sweep_full((A,), FULL) == rows diff --git a/tests/accept/w8b/PATHS b/tests/accept/w8b/PATHS index 0e3d53e33..f5e60f18d 100644 --- a/tests/accept/w8b/PATHS +++ b/tests/accept/w8b/PATHS @@ -30,3 +30,12 @@ cascade/audit/lane_d_chain.py # rebuilt node following the signed published lane D court, documented in # "Lane D: what satellites verify" / "Lane D: rebuilt from empty state". docs/VALIDATOR.md +# Owner 2026-12-01 ("if someone is crowned we score them"): the lane D king's +# display-only full public bench. After a settlement is published, a miner +# KING_D without a stored bench gets ONE sweep on gift/boom/time/fev on the +# lane D bench host (own thread, allowance ending an hour before the next +# boundary, retried next settlement on failure, never the house); the result +# is stored in the state dir and published as status/lane_d.json king.bench +# (lane A's BenchScores keys, the ones cascade/website reads). Never gate, +# crown, pay, signed report or any consensus value; main validator only. +cascade/validator/lane_d_king_bench.py diff --git a/tests/accept/w8b/README.md b/tests/accept/w8b/README.md index fa4006f55..fcd11e079 100644 --- a/tests/accept/w8b/README.md +++ b/tests/accept/w8b/README.md @@ -317,3 +317,20 @@ started with the shared-ladder rule decided on chain writes the `lad-` segment, locks in with the stake majority, persists `activation_shared_ladder_state.json` and restores it with the chain down; a typed block writes no note. The ladder values are untouched. + +## King full bench (owner 2026-12-01) + +"If someone is crowned [on lane D] we score them": when a settlement leaves a +miner KING_D without a stored full bench, the step (built with +`king_bench=`, main validator only) schedules ONE display-only sweep of the +king on all four public suites (gift, boom, time, fev) on the lane D bench +host, after the settlement is published, on its own thread, with an SSH +allowance that ends an hour before the next boundary (chain time; less than +15 min left: not started). The result is stored at +`/lane_d_king_bench/.json` and published in the unsigned +`status/lane_d.json` as `king.bench` (prior kings keep theirs), with the +numbers under lane A's BenchScores keys (`gifteval_crps`, `gifteval_mase`, +`boom_*`, `time_*`, `fev_*`) plus `bench_method`, `data_revisions`, `digest`, +`as_of`, `complete`, `suites`. A failure is logged and retried at the next +settlement; the signed report and receipt are those of a step without it; +the house is never benched (`test_w8b_king_full_bench.py`). diff --git a/tests/accept/w8b/test_w8b_king_full_bench.py b/tests/accept/w8b/test_w8b_king_full_bench.py new file mode 100644 index 000000000..a45414553 --- /dev/null +++ b/tests/accept/w8b/test_w8b_king_full_bench.py @@ -0,0 +1,225 @@ +"""W8b x owner 2026-12-01 ("if someone is crowned [on lane D] we score +them"): when a settlement crowns a new KING_D, the production step (main +validator only) schedules ONE display-only full sweep of that king on all +four public suites (gift, boom, time, fev) on the lane D bench host, AFTER +the settlement is published, and publishes the result in the unsigned +``status/lane_d.json`` as ``king.bench`` in the shape ``cascade/website`` +parses (flat ``gifteval_crps`` / ``gifteval_mase``, lane A's BenchScores key +convention). Never part of the gate, the crown, pay or the signed report: a +failed sweep leaves the settlement byte-identical and is retried at the next +settlement; the house is never benched. + +Real ``settle_lane_d`` runs on W7a's synthetic chain through the W8b rig; +the full-bench host is a fake (:class:`FullHost`), the sweep runs inline. +Nothing in PATHS is imported at module import time; a missing feature on the +base fails by assertion. +""" + +from __future__ import annotations + +import importlib +import importlib.util +import inspect +import json + +from . import helpers as h + +KING_BENCH = "cascade.validator.lane_d_king_bench" +SIX = ("gifteval_crps", "gifteval_mase", "boom_crps", "boom_mase", "time_crps", "time_mase") +SIDE = {"gift": "gifteval", "boom": "boom", "time": "time", "fev": "fev"} + + +def kb_mod(): + assert importlib.util.find_spec(KING_BENCH) is not None, \ + "no lane D king full-bench module (cascade.validator.lane_d_king_bench)" + return importlib.import_module(KING_BENCH) + + +def _takes_king_bench() -> None: + params = inspect.signature(h.wiring().build_lane_d_step).parameters + assert "king_bench" in params, "build_lane_d_step takes no king_bench" + + +class FullHost: + """The lane D bench host's display-only full sweep (``sweep_full``): + every suite ``ok`` with an ``aggregate`` pair, or a raise (``fail``).""" + + def __init__(self): + self.calls: list[dict] = [] + self.fail = False + + def context_of(self, digest): + return 4096 + + def sweep_full(self, digests, suites, *, contexts=None, timeout_s=None): + self.calls.append({"digests": tuple(digests), "suites": tuple(suites), + "contexts": dict(contexts or {}), "timeout_s": timeout_s}) + if self.fail: + raise ConnectionError("w8b: bench host lost during the king's full sweep") + out = {} + for d in digests: + out[d] = {s: {"status": "ok", + "rows": [{"item": f"{s}/i{i}", "crps": 0.5, "mase": 1.1} + for i in range(3)], + "aggregate": {"status": "ok", "crps": 0.40 + 0.01 * k, + "mase": 0.80 + 0.01 * k, "partial": False, + "bench_method": "observed_mask/3", + "data_revision": f"rev-{s}"}} + for k, s in enumerate(suites)} + return out + + +class Clock: + """Wall clock: one minute after the boundary's on-chain timestamp.""" + + def __init__(self): + self.t = float(h.boundary_ts(h.B1) + 60) + + def at(self, boundary): + self.t = float(h.boundary_ts(boundary) + 60) + + def __call__(self): + return self.t + + +class KBRig(h.Rig): + """The W8b rig with a ``KingBench`` over :class:`FullHost` (inline).""" + + def __init__(self, tmp, cfg, fx, **kw): + self.full = FullHost() + self.clock = Clock() + self.kb = None + self._tmp = tmp + super().__init__(tmp, cfg, fx, **kw) + + def build(self): + _takes_king_bench() + self.kb = kb_mod().KingBench(self.full, state_dir=self.state_dir, + spawn=lambda fn: fn(), now=self.clock) + return h.wiring().build_lane_d_step( + self.cfg, state_dir=self.state_dir, signer=h.signer(), + chain_factory=self.factory, store=self.store, inputs=self.inputs, + bench=self.bench, king_bench=self.kb) + + def run(self, boundary): + self.clock.at(boundary) + return self.step(boundary) + + def status(self) -> dict: + from cascade.validator.lane_d_status import LANE_D_STATUS_KEY + + return json.loads(self.store.objects[LANE_D_STATUS_KEY]) + + +def _gift_pair(o): + """``cascade/website`` giftPair(): flat gifteval_crps / gifteval_mase.""" + if not isinstance(o, dict): + return None + c, m = o.get("gifteval_crps"), o.get("gifteval_mase") + ok = all(isinstance(v, float) and v > 0 for v in (c, m)) + return (c, m) if ok else None + + +def _website_king_bench(king): + for k in ("bench", "public", "public_bench", "bench_scores"): + g = _gift_pair(king.get(k)) + if g: + return g + return None + + +def test_a_crowning_schedules_exactly_one_full_sweep_of_the_new_king(tmp_path): + cfg = h.chain_cfg(tmp_path / "v", sentinel=False) + rig = KBRig(tmp_path / "rig", cfg, h.fixture(tmp_path)) + rig.run(h.B1) + assert rig.full.calls == [], "the house was benched" + rig.run(h.B2) + assert rig.published_report(h.B2)["crowned"] == rig.fx["x"] + assert len(rig.full.calls) == 1, rig.full.calls + call = rig.full.calls[0] + assert call["digests"] == (rig.fx["x"],) + assert set(call["suites"]) == {"gift", "boom", "time", "fev"} + assert call["contexts"] == {rig.fx["x"]: 4096} + # the allowance ends an hour before the next boundary (chain time) + grid_s = 12 * h.SETTLEMENT + assert call["timeout_s"] is not None and 0 < call["timeout_s"] <= grid_s - 3600 - 60 + 1 + rig.run(h.B3) + rig.restart() + rig.run(h.B3 + h.SETTLEMENT) + assert len(rig.full.calls) == 1, "the king was swept again after a stored full bench" + # the gate's bench host never saw the full sweep + assert all(set(s) != {"gift", "boom", "time", "fev"} for _, s in rig.host.calls) + + +def test_the_result_lands_in_status_king_bench_in_the_website_shape(tmp_path): + cfg = h.chain_cfg(tmp_path / "v", sentinel=False) + rig = KBRig(tmp_path / "rig", cfg, h.fixture(tmp_path)) + rig.run(h.B1) + rig.run(h.B2) + king = rig.status()["king"] + assert king["digest"] == rig.fx["x"] and king["house"] is False + bench = king.get("bench") + assert isinstance(bench, dict), f"status king carries no bench: {king}" + assert _website_king_bench(king) == (0.40, 0.80) + for k in SIX + ("fev_crps", "fev_mase"): + assert isinstance(bench.get(k), float) and bench[k] > 0, k + assert bench["digest"] == rig.fx["x"] + assert bench["bench_method"] == "observed_mask/3" + assert bench["data_revisions"] == {s: f"rev-{s}" for s in SIDE} + assert isinstance(bench["as_of"], str) and bench["as_of"].endswith("Z") + assert bench["complete"] is True + stored = json.loads((rig.state_dir / "lane_d_king_bench" / f"{rig.fx['x']}.json") + .read_text()) + assert stored == bench + # the next settlement's status still carries it (read from the store) + rig.run(h.B3) + assert rig.status()["king"]["bench"] == bench + + +def test_a_failed_sweep_leaves_the_settlement_alone_and_is_retried(tmp_path): + cfg = h.chain_cfg(tmp_path / "v", sentinel=False) + fx = h.fixture(tmp_path) + control = h.Rig(tmp_path / "control", cfg, fx) + rig = KBRig(tmp_path / "rig", cfg, fx) + rig.full.fail = True + for b in (h.B1, h.B2): + control.step(b) + s = rig.run(b) + assert s is not None and len(rig.full.calls) == 1 + def body(r, b): # the signed body (sr25519 signatures are randomised) + return h.body_sha256(r.published_report(b)) + + assert body(rig, h.B2) == body(control, h.B2) + assert (rig.published_receipt(h.B2)["posterior_state_sha256"] + == control.published_receipt(h.B2)["posterior_state_sha256"]) + assert "bench" not in rig.status()["king"] + rig.full.fail = False + rig.run(h.B3) + assert len(rig.full.calls) == 2, "the failed king bench was not retried" + assert _website_king_bench(rig.status()["king"]) == (0.40, 0.80) + control.step(h.B3) + assert body(rig, h.B3) == body(control, h.B3) + + +def test_no_bench_call_while_the_king_is_the_house(tmp_path): + cfg = h.chain_cfg(tmp_path / "v", sentinel=False) + fx = h.fixture(tmp_path) + rig = KBRig(tmp_path / "rig", cfg, fx, inputs=h.Inputs(fx, entries=[])) + for b in (h.B1, h.B2, h.B3): + rig.run(b) + assert rig.status()["king"]["house"] is True + assert rig.full.calls == [] + assert "bench" not in rig.status()["king"] + + +def test_no_sweep_inside_the_hour_before_the_next_settlement(tmp_path): + cfg = h.chain_cfg(tmp_path / "v", sentinel=False) + rig = KBRig(tmp_path / "rig", cfg, h.fixture(tmp_path)) + rig.run(h.B1) + rig.clock.at(h.B2) + rig.clock.t += 12 * h.SETTLEMENT - 3600 - 60 # 50 min before the next boundary + rig.step(h.B2) + assert rig.published_report(h.B2)["crowned"] == rig.fx["x"] + assert rig.full.calls == [], "the king bench started inside the pre-settlement hour" + rig.run(h.B3) + assert len(rig.full.calls) == 1 From 937f37a0e1ddfe0713b7a5d72377f3b7df2decb1 Mon Sep 17 00:00:00 2001 From: tensorlink-dev Date: Tue, 1 Dec 2026 04:07:34 +0000 Subject: [PATCH 2/2] lane D bench host: the remote sweep carries an on-host timeout (IR008) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BMT4D7f8wd5dXsASyWUBwe --- cascade/validator/lane_d_bench_host.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/cascade/validator/lane_d_bench_host.py b/cascade/validator/lane_d_bench_host.py index 6aa2d5370..47f731f9f 100644 --- a/cascade/validator/lane_d_bench_host.py +++ b/cascade/validator/lane_d_bench_host.py @@ -167,11 +167,14 @@ def _sweep(self, ds: list[str], ss: list[str], *, "--cache-dir", self.cache_dir, "--budget-bytes", str(self.budget_bytes)] if host.chain_toml: args += ["--chain-toml", host.chain_toml] - cmd = f"cd {shlex.quote(host.workdir)} && {env}" + " ".join(shlex.quote(a) for a in args) - payload = json.dumps(request, sort_keys=True).encode("utf-8") timeout = self.timeout_per_checkpoint_s * len(ds) if timeout_s is not None: timeout = min(timeout, float(timeout_s)) + # IR008: the sweep ends ON the host too (subprocess timeout= kills only + # the local ssh client; the remote sidecar would keep running) + cmd = (f"cd {shlex.quote(host.workdir)} && {env}timeout -k 30 {max(1, int(timeout))} " + + " ".join(shlex.quote(a) for a in args)) + payload = json.dumps(request, sort_keys=True).encode("utf-8") proc = self._run(build_ssh_argv(host, cmd), input=payload, capture_output=True, timeout=timeout, check=False) err = (proc.stderr or b"").decode("utf-8", "replace")[-600:]