diff --git a/cascade/eval/lane_d_forecasts.py b/cascade/eval/lane_d_forecasts.py index ef4810675..abd5e27fe 100644 --- a/cascade/eval/lane_d_forecasts.py +++ b/cascade/eval/lane_d_forecasts.py @@ -33,7 +33,9 @@ dropped at read time. Without ``--public-root`` the drawn series come from the Hippius mirror (``deploy/laned/public_mirror.toml``, ranged GETs behind the Lium-volume blob cache; owner 2026-11-24, #894), else from a local - mirror at R; + mirror at R. The settlement's cut windows are cut by its first digest and + reused by the rest (live 2026-12-01; ``--cut-cache-dir``, + :mod:`cascade.eval.lane_d_public_cut`); * ``forecast --cache-dir D --budget-bytes N`` reads one request (an ``.npz`` of the window histories plus a JSON ``meta`` record, :data:`REQUEST_SCHEMA`) from stdin and prints one :data:`REPLY_SCHEMA` JSON line: the quantiles, or @@ -381,7 +383,8 @@ def public_scores_entry(cache: PrefetchCache, digest: str, draws: Sequence[Mappi block_hash: str | None, max_channels: int, grant: Mapping | None = None, contract=None, expect=None, device: str = "cpu", forecast: Callable | None = None, - mirror=None, keep: Mapping | None = None) -> dict: + mirror=None, keep: Mapping | None = None, + cut_cache=None) -> dict: """One checkpoint's per-window scores on the settlement's public draws (rev6.18 A3, F4): each source's drawn series are read from the Hippius mirror when ``mirror`` is given (:class:`~cascade.eval.lane_d_public_mirror. @@ -402,16 +405,57 @@ def public_scores_entry(cache: PrefetchCache, digest: str, draws: Sequence[Mappi (:func:`~cascade.validator.lane_d_public.keep_public` over the windows that survive the data rules, by ``block_hash``); ``dropped`` stays the data drops, from which the validator re-derives the same set. Without - it (a request of an older validator) every surviving window is scored.""" - from ..validator.lane_d_public import ( - keep_public, - read_public_windows, - score_public_windows, - ) + it (a request of an older validator) every surviving window is scored. + + ``cut_cache`` (live 2026-12-01; :class:`~cascade.eval.lane_d_public_cut. + CutCache`): the settlement's cut windows and drops are read and cut once + and reused by every later digest of the same draws (and by a retry after + a restart); the same windows, so the same scores and drops.""" + from ..validator.lane_d_public import score_public_windows if mirror is None and public_root is None: raise LaneDForecastError("forecast_failed", "no public mirror: neither a Hippius " "mirror nor a local public root") + got = None + if cut_cache is not None: + from .lane_d_public_cut import cut_key + + key = cut_key(draws, block_hash=block_hash, max_channels=max_channels, + context=context, horizon=horizon, contexts=contexts, keep=keep) + got = cut_cache.load(key) + if got is None: + got = _cut_public_windows(draws, public_root=public_root, block_hash=block_hash, + max_channels=max_channels, mirror=mirror, keep=keep) + if cut_cache is not None: + cut_cache.store(key, *got) + windows, dropped = got + # owner 2026-11-27: each public window is forecast at its own h (its + # target's length); one forecast per horizon group, windows in id order + # inside it. Under the fixed rule every window is one group at + # ``horizon``: the pre-band single call. + by_h: dict[int, list[dict]] = {} + for w in windows: + by_h.setdefault(int(np.shape(w["target"])[-1]), []).append(w) + fc: dict = {} + for hz in sorted(by_h): + cut = [{"window_id": w["window_id"], + "history": np.asarray(w["history"])[..., -int(context):]} for w in by_h[hz]] + arr = forecast_entry(cache, digest, cut, context=context, horizon=hz, + contexts=contexts, grant=grant, contract=contract, expect=expect, + device=device, forecast=forecast) + fc.update(_split_rows(arr, cut)) + per = score_public_windows(windows, {digest: fc}).get(digest, {}) + return {"scores": {src: per.get(src, []) for src in sorted(dropped)}, "dropped": dropped} + + +def _cut_public_windows(draws: Sequence[Mapping], *, public_root, block_hash: str | None, + max_channels: int, mirror=None, + keep: Mapping | None = None) -> tuple[list[dict], dict]: + """The settlement's judged public windows (``window_id`` order) and the + data drops per source: every draw's series read and cut, then the size + rule. The same for every digest of the settlement.""" + from ..validator.lane_d_public import keep_public, read_public_windows + windows, dropped = [], {} for d in draws: src = str(d["source"]) @@ -440,23 +484,7 @@ def public_scores_entry(cache: PrefetchCache, digest: str, draws: Sequence[Mappi if keep is not None: windows, _ = keep_public(windows, boundary_block_hash=str(block_hash), series=keep["series"], total=int(keep["total"])) - # owner 2026-11-27: each public window is forecast at its own h (its - # target's length); one forecast per horizon group, windows in id order - # inside it. Under the fixed rule every window is one group at - # ``horizon``: the pre-band single call. - by_h: dict[int, list[dict]] = {} - for w in windows: - by_h.setdefault(int(np.shape(w["target"])[-1]), []).append(w) - fc: dict = {} - for hz in sorted(by_h): - cut = [{"window_id": w["window_id"], - "history": np.asarray(w["history"])[..., -int(context):]} for w in by_h[hz]] - arr = forecast_entry(cache, digest, cut, context=context, horizon=hz, - contexts=contexts, grant=grant, contract=contract, expect=expect, - device=device, forecast=forecast) - fc.update(_split_rows(arr, cut)) - per = score_public_windows(windows, {digest: fc}).get(digest, {}) - return {"scores": {src: per.get(src, []) for src in sorted(dropped)}, "dropped": dropped} + return windows, dropped def public_mirror(*, mirror_config=None, cache_dir=None, budget_bytes: int | None = None, @@ -536,11 +564,13 @@ def _keep_field(meta: Mapping, draws: Sequence[Mapping]) -> dict | None: def serve_public(raw: bytes, *, cache_dir, budget_bytes: int, device: str, public_root=None, - chain_toml=None, mirror=None) -> dict: + chain_toml=None, mirror=None, cut_cache=None) -> dict: """Answer one :data:`PUBLIC_REQUEST_SCHEMA` request (JSON): the :data:`PUBLIC_REPLY_SCHEMA` record. ``ValueError`` on a malformed request. Without ``public_root`` the series come from ``mirror`` (default: the - release's Hippius mirror config, :func:`public_mirror`).""" + release's Hippius mirror config, :func:`public_mirror`). ``cut_cache`` + (:class:`~cascade.eval.lane_d_public_cut.CutCache`): the settlement's cut + windows, cut by the first digest and reused by the rest.""" try: meta = json.loads(raw.decode("utf-8")) except (UnicodeDecodeError, json.JSONDecodeError) as e: @@ -584,7 +614,7 @@ def serve_public(raw: bytes, *, cache_dir, budget_bytes: int, device: str, publi block_hash=meta.get("block_hash"), max_channels=max_channels, grant=grant, contract=contract, device=device, mirror=None if public_root is not None - else mirror, keep=keep) + else mirror, keep=keep, cut_cache=cut_cache) except LaneDForecastError as e: log.warning("lane_d_public_refused %s digest=%s detail=%s", e.code, digest, e.detail) return {"schema": PUBLIC_REPLY_SCHEMA, "ok": False, "code": e.code, "detail": e.detail} @@ -630,6 +660,11 @@ def _build_parser() -> argparse.ArgumentParser: help="this host's chain.toml (the contract a cache miss ingests against)") q.add_argument("--public-workers", type=int, default=None, help="series read at once (default: the mirror config's read_workers)") + q.add_argument("--cut-cache-dir", type=Path, default=None, + help="the settlement's cut public windows, cut once and reused by every " + "digest (default: /cut; none with --public-root)") + q.add_argument("--cut-cache-budget-bytes", type=int, default=None, + help="the cut-window cache byte budget (default 16 GiB; 0 disables it)") s = sub.add_parser("settle", help="W-OFFBOX: one settlement's pool phase (pins, windows, " "forecasts, scores) read as JSON from stdin") s.add_argument("--cache-dir", type=Path, required=True, help="the W15 prefetch cache root") @@ -675,6 +710,23 @@ def _parse_indexes(items: Sequence[str]) -> dict[str, str]: return out +def _cut_cache(args, mirror): + """The ``public`` command's :class:`~cascade.eval.lane_d_public_cut. + CutCache`: ``--cut-cache-dir``, else ``cut/`` beside the mirror's blob + cache; ``None`` (cut per digest, as before) with a budget of 0 or no + directory.""" + from .lane_d_public_cut import CUT_SUBDIR, DEFAULT_BUDGET_BYTES, CutCache + + budget = args.cut_cache_budget_bytes + budget = DEFAULT_BUDGET_BYTES if budget is None else int(budget) + root = args.cut_cache_dir + if root is None and mirror is not None and getattr(mirror, "cache", None) is not None: + root = Path(mirror.cache.root) / CUT_SUBDIR + if root is None or budget <= 0: + return None + return CutCache(root, budget_bytes=budget) + + def main(argv: list[str] | None = None) -> int: # A crash in native code (the 2026-11-28 allocator segfault under the # public read) would otherwise exit 139 with an EMPTY stderr: the box got @@ -742,7 +794,7 @@ def main(argv: list[str] | None = None) -> int: reply = serve_public(sys.stdin.buffer.read(), cache_dir=args.cache_dir, budget_bytes=args.budget_bytes, device=args.device, public_root=args.public_root, chain_toml=args.chain_toml, - mirror=mirror) + mirror=mirror, cut_cache=_cut_cache(args, mirror)) else: reply = serve_forecast(sys.stdin.buffer.read(), cache_dir=args.cache_dir, budget_bytes=args.budget_bytes, device=args.device, diff --git a/cascade/eval/lane_d_public_cut.py b/cascade/eval/lane_d_public_cut.py new file mode 100644 index 000000000..2cee81317 --- /dev/null +++ b/cascade/eval/lane_d_public_cut.py @@ -0,0 +1,288 @@ +"""Lane D public half: the settlement's cut public windows, cut ONCE per +settlement on the eval host (live 2026-12-01). + +Every digest of a settlement is scored on the SAME public windows: the draws +are fixed by the boundary block hash and the data by each draw's +``index_sha256``. Reading and cutting them +(:func:`~cascade.validator.lane_d_public.read_public_windows` over the +Lium-volume blob cache) took ~12 min of 16 busy cores per digest, then a +short GPU burst; 7 digests re-read and re-cut the same windows for ~90 min. + +:class:`CutCache` keeps the cut windows (after the size rule, ``keep``) and +the data drops of one request shape in one file, keyed by +:func:`cut_key` (the draws, the boundary block hash, ``max_channels``, +``context`` / ``horizon`` / ``contexts``, the ``keep`` rule and +:data:`CUT_SCHEMA`, which names the cut code's version). The first digest of a +settlement cuts and writes; every later digest, and a retry of the same +settlement after a validator or host restart, loads the file instead. The +loaded windows are the cut windows bit for bit (the arrays' raw bytes and +dtypes, the records' JSON), so the per-digest scores and ``dropped`` are +unchanged. + +On disk (``/.cut``, written to a temporary name then +``os.replace``d):: + + MAGIC | u64 header length (big-endian) | header JSON | payload + +The header names every window's fields and its arrays' dtype / shape / +offset into the payload, the drops, and the payload's length and sha256. A +file that is short, not this format, not this key or does not hash is +deleted and the windows are cut again. The cache holds at most +``budget_bytes`` (oldest use first out, by mtime; a hit refreshes it) and +never writes when the volume would keep less than ``min_free_bytes`` free. +A failed write never fails the request: the windows are served uncached. +""" + +from __future__ import annotations + +import contextlib +import hashlib +import json +import logging +import os +import shutil +import struct +import threading +import time +from collections.abc import Mapping, Sequence +from pathlib import Path + +import numpy as np + +log = logging.getLogger("cascade.eval.lane_d_public_cut") + +# Bump when read_public_windows / build_window / keep_public change what a +# cut window holds: old files then stop matching any key. +CUT_SCHEMA = "lane-d-public-cut/1" +MAGIC = b"LANEDCUT\x01\n" +SUFFIX = ".cut" +DEFAULT_BUDGET_BYTES = 16 * 2**30 +DEFAULT_MIN_FREE_BYTES = 2 * 2**30 +CUT_SUBDIR = "cut" +_ARRAY_FIELDS = ("history", "target") +_STALE_TMP_SECONDS = 3600.0 +_CHUNK = 64 * 2**20 + + +def _canon(obj) -> bytes: + return json.dumps(obj, sort_keys=True, separators=(",", ":"), + allow_nan=False).encode("utf-8") + + +def _dump(obj) -> bytes: + """JSON in insertion order (a loaded record keeps every dict's key order).""" + return json.dumps(obj, separators=(",", ":"), allow_nan=False).encode("utf-8") + + +def cut_key(draws: Sequence[Mapping], *, block_hash: str | None, max_channels: int, + context: int, horizon: int, contexts: Sequence[int], + keep: Mapping | None) -> str: + """sha256 hex of everything the cut windows depend on (and of the + request shape they were cut for).""" + return hashlib.sha256(_canon({ + "schema": CUT_SCHEMA, "draws": [dict(d) for d in draws], "block_hash": block_hash, + "max_channels": int(max_channels), "context": int(context), + "horizon": int(horizon), "contexts": [int(c) for c in contexts], + "keep": None if keep is None else {"total": int(keep["total"]), + "series": dict(keep["series"])}, + })).hexdigest() + + +class CutCache: + """The eval host's cut public windows, one file per :func:`cut_key`.""" + + def __init__(self, root, *, budget_bytes: int = DEFAULT_BUDGET_BYTES, + min_free_bytes: int = DEFAULT_MIN_FREE_BYTES): + if isinstance(budget_bytes, bool) or not isinstance(budget_bytes, int) \ + or budget_bytes <= 0: + raise ValueError(f"budget_bytes must be a positive int; got {budget_bytes!r}") + self.root = Path(root) + self.budget_bytes = int(budget_bytes) + self.min_free_bytes = int(min_free_bytes) + + def path(self, key: str) -> Path: + return self.root / f"{key}{SUFFIX}" + + # -- read --------------------------------------------------------------- + def load(self, key: str) -> tuple[list[dict], dict] | None: + """``(windows, dropped)`` cut for ``key``, or ``None`` (absent, or a + corrupt / partial file, which is deleted).""" + p = self.path(key) + try: + f = p.open("rb") + except OSError: + return None + try: + with f: + got = self._read(f, key) + except (OSError, ValueError, KeyError, TypeError, AttributeError) as e: + log.warning("lane_d_public_cut_corrupt %s (%s): dropped, cutting again", + key[:16], e) + with contextlib.suppress(OSError): + p.unlink() + return None + with contextlib.suppress(OSError): + os.utime(p) + log.info("lane_d_public_cut_hit %s windows=%d", key[:16], len(got[0])) + return got + + @staticmethod + def _read(f, key: str) -> tuple[list[dict], dict]: + if f.read(len(MAGIC)) != MAGIC: + raise ValueError("not a cut file") + raw = f.read(8) + if len(raw) != 8: + raise ValueError("short header length") + (n,) = struct.unpack(">Q", raw) + if n > 2**31: + raise ValueError("header too large") + head_raw = f.read(n) + if len(head_raw) != n: + raise ValueError("short header") + head = json.loads(head_raw.decode("utf-8")) + if head.get("schema") != CUT_SCHEMA or head.get("key") != key: + raise ValueError("not this key") + size = int(head["payload_bytes"]) + if size != os.fstat(f.fileno()).st_size - f.tell(): + raise ValueError("partial or oversized payload") + payload = bytearray(size) + view, got, h = memoryview(payload), 0, hashlib.sha256() + while got < size: + k = f.readinto(view[got:got + _CHUNK]) + if not k: + raise ValueError(f"short payload ({got} of {size} bytes)") + h.update(view[got:got + k]) + got += k + if f.read(1): + raise ValueError("trailing bytes") + if h.hexdigest() != head["payload_sha256"]: + raise ValueError("payload sha256 mismatch") + windows = [] + for rec in head["windows"]: + fields, arrs = rec["fields"], {} + for name, a in rec["arrays"].items(): + dt = np.dtype(a["dtype"]) + count = int(np.prod(a["shape"], dtype=np.int64)) + off, nb = int(a["offset"]), int(a["nbytes"]) + if nb != count * dt.itemsize or off < 0 or off + nb > size: + raise ValueError(f"{fields.get('window_id')}: {name} out of range") + arrs[name] = np.frombuffer(payload, dtype=dt, count=count, + offset=off).reshape(a["shape"]) + order = rec["order"] + if sorted(order) != sorted([*fields, *arrs]): + raise ValueError(f"{fields.get('window_id')}: field order mismatch") + windows.append({k: arrs[k] if k in arrs else fields[k] for k in order}) + dropped = head["dropped"] + if not isinstance(dropped, dict): + raise ValueError("dropped is not an object") + return windows, dropped + + # -- write -------------------------------------------------------------- + def store(self, key: str, windows: Sequence[Mapping], dropped: Mapping) -> bool: + """Write ``(windows, dropped)`` for ``key``; ``False`` (logged) when + they cannot round-trip exactly, would leave the budget or the volume's + free floor, or the write fails.""" + try: + head, arrays = self._encode(key, windows, dropped) + except (TypeError, ValueError) as e: + log.warning("lane_d_public_cut_skip %s: not cacheable (%s)", key[:16], e) + return False + head_raw = _dump(head) + size = len(MAGIC) + 8 + len(head_raw) + head["payload_bytes"] + if size > self.budget_bytes: + log.warning("lane_d_public_cut_skip %s: %d bytes > budget %d", key[:16], size, + self.budget_bytes) + return False + p = self.path(key) + tmp = p.with_name(f".{p.name}.{os.getpid()}.{threading.get_ident()}.tmp") + try: + self.root.mkdir(parents=True, exist_ok=True) + self._sweep_tmp() + self._evict(size, keep=p) + free = shutil.disk_usage(self.root).free + if free - size < self.min_free_bytes: + log.warning("lane_d_public_cut_skip %s: %d bytes would leave %d free (< %d)", + key[:16], size, free - size, self.min_free_bytes) + return False + with tmp.open("wb") as f: + f.write(MAGIC) + f.write(struct.pack(">Q", len(head_raw))) + f.write(head_raw) + for a in arrays: + f.write(memoryview(a).cast("B")) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, p) + except OSError as e: + log.warning("lane_d_public_cut_write_failed %s (%s): served uncached", key[:16], e) + with contextlib.suppress(OSError): + tmp.unlink() + return False + log.info("lane_d_public_cut_stored %s windows=%d bytes=%d", key[:16], len(windows), + size) + return True + + @staticmethod + def _encode(key: str, windows: Sequence[Mapping], dropped: Mapping): + recs, arrays, off, h = [], [], 0, hashlib.sha256() + for w in windows: + fields = {k: v for k, v in w.items() if k not in _ARRAY_FIELDS} + if json.loads(_dump(fields)) != fields: + raise ValueError(f"{w.get('window_id')}: fields do not round-trip as JSON") + meta = {} + for name in _ARRAY_FIELDS: + if name not in w: + continue + a = w[name] + if not isinstance(a, np.ndarray) or a.dtype.kind not in "fiu" \ + or a.dtype.byteorder not in "=<|": + raise ValueError(f"{w.get('window_id')}: {name} is not a little-endian " + "numeric ndarray") + c = np.ascontiguousarray(a) + meta[name] = {"dtype": c.dtype.str, "shape": list(c.shape), "offset": off, + "nbytes": int(c.nbytes)} + h.update(memoryview(c).cast("B")) + arrays.append(c) + off += int(c.nbytes) + recs.append({"order": list(w), "fields": fields, "arrays": meta}) + drops = {str(k): [dict(d) for d in v] for k, v in dropped.items()} + if json.loads(_dump(drops)) != drops: + raise ValueError("dropped does not round-trip as JSON") + head = {"schema": CUT_SCHEMA, "key": key, "windows": recs, "dropped": drops, + "payload_bytes": off, "payload_sha256": h.hexdigest()} + return head, arrays + + def _entries(self) -> list[tuple[int, int, Path]]: + out = [] + for p in self.root.glob(f"*{SUFFIX}"): + with contextlib.suppress(OSError): + st = p.stat() + out.append((st.st_mtime_ns, st.st_size, p)) + return sorted(out) + + def total_bytes(self) -> int: + return sum(s for _m, s, _p in self._entries()) + + def _evict(self, incoming: int, *, keep: Path) -> None: + entries = self._entries() + total = sum(s for _m, s, p in entries if p != keep) + for _mt, size, p in entries: + if total + incoming <= self.budget_bytes: + break + if p == keep: + continue + with contextlib.suppress(OSError): + p.unlink() + total -= size + log.info("lane_d_public_cut_evict %s bytes=%d", p.name[:16], size) + + def _sweep_tmp(self) -> None: + now = time.time() + for p in self.root.glob(f".*{SUFFIX}.*.tmp"): + with contextlib.suppress(OSError): + if now - p.stat().st_mtime > _STALE_TMP_SECONDS: + p.unlink() + + +__all__ = ["CUT_SCHEMA", "CUT_SUBDIR", "DEFAULT_BUDGET_BYTES", "DEFAULT_MIN_FREE_BYTES", + "CutCache", "cut_key"] diff --git a/tests/accept/w8c/PATHS b/tests/accept/w8c/PATHS index 563d30fab..d65db7d55 100644 --- a/tests/accept/w8c/PATHS +++ b/tests/accept/w8c/PATHS @@ -26,3 +26,6 @@ cascade/validator/lane_d_public.py # eval host's warm-public / --public-workers; docs/OPERATOR.md ONLY the # "Lane D public half: warm the mirror before raising public_weight" section. docs/OPERATOR.md +# live 2026-12-01 (public half cut once per settlement): the eval host's cut +# public window cache, used by lane_d_forecasts public_scores_entry. +cascade/eval/lane_d_public_cut.py diff --git a/tests/accept/w8c/README.md b/tests/accept/w8c/README.md index c72509528..467c74f2f 100644 --- a/tests/accept/w8c/README.md +++ b/tests/accept/w8c/README.md @@ -369,3 +369,20 @@ drops, order); a reader error fails the read. `public_scores_entry` passes the mirror's `workers` (`read_workers`, `public --public-workers`). The draw is untouched. `test_w8c_public_parallel.py`. Runbook: docs/OPERATOR.md "Lane D public half: warm the mirror before raising public_weight". + +## Public half: cut once per settlement (live 2026-12-01) + +Every digest of a settlement is scored on the same public windows, so the +eval host cuts them once: `public_scores_entry(..., cut_cache=)` loads the +judged windows and data drops from a `CutCache` +(`cascade/eval/lane_d_public_cut.py`, one file per `cut_key`: the draws, the +boundary block hash, `max_channels`, `context` / `horizon` / `contexts`, the +`keep` rule and `CUT_SCHEMA`), else reads and cuts them and writes the file +(atomic `os.replace`, sha256-checked payload). A later digest, or a retry +after a restart, reads nothing; its reply (scores, `dropped`) is byte-identical +to an uncached one. A corrupt or partial file is deleted and the windows are +cut again; the cache keeps its byte budget (oldest use first out) and a +volume free-space floor; a write that fails or does not round-trip exactly is +skipped (served uncached). The `public` command puts it at +`/cut` (`--cut-cache-dir`, `--cut-cache-budget-bytes`, 0 +disables). The box's request is unchanged. `test_w8c_public_cut.py`. diff --git a/tests/accept/w8c/test_w8c_public_cut.py b/tests/accept/w8c/test_w8c_public_cut.py new file mode 100644 index 000000000..f83c35bbe --- /dev/null +++ b/tests/accept/w8c/test_w8c_public_cut.py @@ -0,0 +1,282 @@ +"""W8c (live 2026-12-01): the settlement's public windows are cut ONCE on the +eval host. + +Every digest of a settlement is scored on the same public windows (the draws +are fixed by the boundary block hash, the data by each draw's +``index_sha256``). Live, each digest re-read and re-cut the 5,000 drawn +windows (~12.5 min of CPU per digest, ~90 min for 7 digests). With the cut +cache (:mod:`cascade.eval.lane_d_public_cut`) the first digest cuts and +writes them; every later digest of the same draws, and a retry after a +restart, loads them, with the same replies (scores and ``dropped``) byte for +byte. Torch-free: the series reader and the scorer are stand-ins. +""" + +from __future__ import annotations + +import importlib +import importlib.util +import inspect +import json +from types import SimpleNamespace + +import numpy as np + +from . import helpers as h + +BH = "0x" + "c3" * 32 +DIGESTS = ("a" * 64, "b" * 64, "e" * 64) + + +def _cutmod(): + assert importlib.util.find_spec("cascade.eval.lane_d_public_cut") is not None, ( + "live 2026-12-01: no cascade.eval.lane_d_public_cut (the public windows are re-read " + "and re-cut for every digest of a settlement)") + return importlib.import_module("cascade.eval.lane_d_public_cut") + + +def _fc(): + fc = h.forecasts_mod() + assert "cut_cache" in inspect.signature(fc.public_scores_entry).parameters, ( + "live 2026-12-01: public_scores_entry(..., cut_cache=) is missing (every digest " + "re-cuts the settlement's public windows)") + return fc + + +def _source_windows(src: str, n: int, seed: int): + """Real cut windows (``build_window``) of synthetic series: univariate and + multichannel, with NaN gaps, so the cached records carry every field the + live ones do (channels record, 1-D and 2-D arrays).""" + from cascade.validator.lane_d_public import build_window + + rng = np.random.default_rng(seed) + wins, drops = [], [] + for i in range(n): + c = 1 if i % 3 else 3 + s = rng.random((c, 400)) * 10 + 1.0 + if i % 4 == 0: + s[:, 50:60] = np.nan + hz = 8 if i % 2 else 16 + w = {"window_id": f"{src}:s{i}:300:h{hz}", "series_id": f"s{i}", "family": "fam", + "freq": "H", "cut": 300, "h": hz} + win, why = build_window(s, w, block_hash=BH, max_channels=2) + if win is None: + drops.append({"window_id": w["window_id"], "reason": why}) + else: + wins.append(win) + drops.append({"window_id": f"{src}:gone:0:h8", "reason": "public_short_history"}) + return wins, drops + + +class Reads: + """A stand-in for ``read_public_windows`` that counts its reads.""" + + def __init__(self): + self.data = {"gift_eval_pretrain": _source_windows("gift_eval_pretrain", 9, 1), + "rmisc": _source_windows("rmisc", 7, 2)} + self.calls: list[str] = [] + + def __call__(self, draw, *, index_dir, block_hash, max_channels, data_root=None, + reader=None, workers=1): + self.calls.append(draw["source"]) + wins, drops = self.data[draw["source"]] + return [dict(w) for w in wins], [dict(d) for d in drops] + + +def _draws(tag: str = "x"): + return [{"source": s, "index_sha256": tag * 64, "windows": [{"window_id": f"{s}:w"}]} + for s in ("gift_eval_pretrain", "rmisc")] + + +def _forecast(ckpt, histories, *, context, horizon, contexts, device): + # depends on the checkpoint and the histories' values: a changed window + # changes the reply + base = 1.0 + (sum(map(ord, str(ckpt))) % 7) / 10.0 + rows = [] + for x in histories: + a = np.atleast_2d(np.asarray(x, dtype=np.float64)) + k = a.shape[0] if np.ndim(x) == 2 and a.shape[0] > 1 else 1 + for c in range(k): + last = float(np.nanmean(a[c if k > 1 else 0][-8:])) + rows.append(np.sort(np.full((horizon, 9), last * base) + + np.linspace(-1, 1, 9)[None, :], axis=-1)) + return np.stack(rows) + + +class Cache: + def __init__(self, root): + self.root = root + + def get(self, digest): + return self.root / digest[:8] + + +def _run(fc, tmp_path, digest, *, cut_cache=None, draws=None, keep=None, horizon=8): + kw = {"cut_cache": cut_cache} if cut_cache is not None else {} + return fc.public_scores_entry(Cache(tmp_path), digest, draws or _draws(), + public_root=tmp_path, context=128, horizon=horizon, + contexts=(128,), block_hash=BH, max_channels=2, + forecast=_forecast, keep=keep, **kw) + + +def _canon(reply) -> bytes: + return json.dumps(reply, sort_keys=True).encode() + + +def _patch(monkeypatch): + from cascade.validator import lane_d_public + + reads = Reads() + monkeypatch.setattr(lane_d_public, "read_public_windows", reads) + return reads + + +def test_later_digests_of_the_same_draws_do_not_re_read_or_re_cut(tmp_path, monkeypatch): + fc, cut = _fc(), _cutmod() + reads = _patch(monkeypatch) + cc = cut.CutCache(tmp_path / "cut") + for dg in DIGESTS: + _run(fc, tmp_path, dg, cut_cache=cc) + assert reads.calls == ["gift_eval_pretrain", "rmisc"], ( + f"the settlement's draws were read {len(reads.calls)} times for {len(DIGESTS)} " + "digests; want once") + + +def test_a_restarted_validator_reuses_the_first_digests_cut(tmp_path, monkeypatch): + """A new ``public`` process (a validator or host restart, a retry) over + the same cache directory loads the cut and reads nothing.""" + fc, cut = _fc(), _cutmod() + reads = _patch(monkeypatch) + _run(fc, tmp_path, DIGESTS[0], cut_cache=cut.CutCache(tmp_path / "cut")) + reads.calls.clear() + _run(fc, tmp_path, DIGESTS[1], cut_cache=cut.CutCache(tmp_path / "cut")) + assert reads.calls == [], "the retried settlement re-read the public draws" + + +def test_replies_are_byte_identical_with_and_without_the_cache(tmp_path, monkeypatch): + fc, cut = _fc(), _cutmod() + _patch(monkeypatch) + keep = {"total": 8, "series": {"gift_eval_pretrain": 3, "rmisc": 1}} + for kp in (None, keep): + cc = cut.CutCache(tmp_path / f"cut-{kp is None}") + for dg in DIGESTS: + plain = _canon(_run(fc, tmp_path, dg, keep=kp)) + first = _canon(_run(fc, tmp_path, dg, cut_cache=cc, keep=kp)) # miss or hit + again = _canon(_run(fc, tmp_path, dg, cut_cache=cut.CutCache(cc.root), keep=kp)) + assert plain == first == again, f"{dg[:4]} keep={kp}: the cached reply differs" + assert json.loads(plain)["scores"]["rmisc"], "the comparison scored nothing" + + +def test_loaded_windows_are_the_cut_windows_bit_for_bit(tmp_path): + cut = _cutmod() + wins, drops = _source_windows("rmisc", 12, 7) + assert any(np.ndim(w["history"]) == 2 for w in wins) and any(w["channels"] for w in wins) + cc = cut.CutCache(tmp_path) + assert cc.store("k" * 64, wins, {"rmisc": drops}) + got, dropped = cc.load("k" * 64) + assert dropped == {"rmisc": drops} + assert len(got) == len(wins) + for a, b in zip(got, wins, strict=True): + assert list(a) == list(b), "key order" + for k in b: + if isinstance(b[k], np.ndarray): + assert a[k].dtype == b[k].dtype and a[k].shape == b[k].shape + assert a[k].tobytes() == b[k].tobytes(), k + else: + assert a[k] == b[k] and type(a[k]) is type(b[k]), k + + +def test_the_key_changes_with_what_the_cut_depends_on(): + cut = _cutmod() + base = {"draws": _draws(), "block_hash": BH, "max_channels": 2, "context": 128, + "horizon": 8, "contexts": (128,), "keep": None} + k0 = cut.cut_key(**base) + assert cut.cut_key(**base) == k0, "the key is deterministic" + changed = { + "draws": _draws("y"), + "block_hash": "0x" + "d4" * 32, + "max_channels": 3, + "context": 256, + "horizon": 16, + "contexts": (128, 256), + "keep": {"total": 8, "series": {"gift_eval_pretrain": 3, "rmisc": 1}}, + } + for name, v in changed.items(): + assert cut.cut_key(**{**base, name: v}) != k0, f"the key ignores {name}" + moved = [dict(d) for d in _draws()] + moved[0]["windows"] = [{"window_id": "gift_eval_pretrain:other"}] + assert cut.cut_key(**{**base, "draws": moved}) != k0, "the key ignores the drawn windows" + + +def test_a_corrupt_or_partial_cut_file_is_ignored_and_rebuilt(tmp_path, monkeypatch): + fc, cut = _fc(), _cutmod() + reads = _patch(monkeypatch) + cc = cut.CutCache(tmp_path / "cut") + want = _canon(_run(fc, tmp_path, DIGESTS[0], cut_cache=cc)) + [path] = sorted((tmp_path / "cut").glob("*.cut")) + good = path.read_bytes() + bad = {"truncated": good[:len(good) // 2], "empty": b"", "garbage": b"not a cut file", + "flipped": good[:-3] + bytes([good[-3] ^ 0xFF]) + good[-2:], + "trailing": good + b"x"} + for name, raw in bad.items(): + path.write_bytes(raw) + reads.calls.clear() + got = _canon(_run(fc, tmp_path, DIGESTS[1], cut_cache=cut.CutCache(cc.root))) + assert reads.calls == ["gift_eval_pretrain", "rmisc"], f"{name}: the file was trusted" + assert got == _canon(_run(fc, tmp_path, DIGESTS[1])), f"{name}: the reply differs" + assert path.read_bytes() == good, f"{name}: the cut was not rebuilt" + assert want + + +def test_the_cache_keeps_its_budget_oldest_first(tmp_path): + import os + + cut = _cutmod() + wins, drops = _source_windows("rmisc", 6, 3) + probe = cut.CutCache(tmp_path / "probe") + assert probe.store("0" * 64, wins, {"rmisc": drops}) + one = probe.path("0" * 64).stat().st_size + cc = cut.CutCache(tmp_path / "c", budget_bytes=2 * one + one // 2) + for i, k in enumerate(("1" * 64, "2" * 64, "3" * 64)): + assert cc.store(k, wins, {"rmisc": drops}), k + os.utime(cc.path(k), ns=(10**18 + i * 10**9, 10**18 + i * 10**9)) + assert not cc.path("1" * 64).exists(), "the oldest entry was not evicted" + assert cc.path("2" * 64).exists() and cc.path("3" * 64).exists() + assert cc.total_bytes() <= cc.budget_bytes + # a load refreshes an entry: the next store evicts the other one + os.utime(cc.path("2" * 64), ns=(10**18 + 9 * 10**9, 10**18 + 9 * 10**9)) + assert cc.load("2" * 64) is not None + assert cc.store("4" * 64, wins, {"rmisc": drops}) + assert cc.path("2" * 64).exists() and not cc.path("3" * 64).exists() + tiny = cut.CutCache(tmp_path / "t", budget_bytes=one // 2) + assert not tiny.store("5" * 64, wins, {"rmisc": drops}), "an entry over budget was written" + assert not list((tmp_path / "t").glob("*.cut")) + + +def test_uncacheable_windows_are_served_uncached(tmp_path, monkeypatch): + fc, cut = _fc(), _cutmod() + reads = _patch(monkeypatch) + for src in reads.data: + reads.data[src][0][0]["seasonal_period"] = np.int64(24) # not JSON + cc = cut.CutCache(tmp_path / "cut") + a = _canon(_run(fc, tmp_path, DIGESTS[0], cut_cache=cc)) + assert a == _canon(_run(fc, tmp_path, DIGESTS[0])) + assert not list((tmp_path / "cut").glob("*.cut")) + + +def test_the_public_command_caches_beside_the_mirrors_blob_cache(tmp_path): + fc = _fc() + _cutmod() + assert hasattr(fc, "_cut_cache"), "the public command builds no cut cache" + mirror = SimpleNamespace(cache=SimpleNamespace(root=tmp_path / "pub")) + args = fc._build_parser().parse_args( + ["public", "--cache-dir", str(tmp_path), "--budget-bytes", "1"]) + got = fc._cut_cache(args, mirror) + assert got is not None and got.root == tmp_path / "pub" / "cut" + args = fc._build_parser().parse_args( + ["public", "--cache-dir", str(tmp_path), "--budget-bytes", "1", + "--cut-cache-budget-bytes", "0"]) + assert fc._cut_cache(args, mirror) is None, "a budget of 0 disables the cut cache" + args = fc._build_parser().parse_args( + ["public", "--cache-dir", str(tmp_path), "--budget-bytes", "1", + "--public-root", str(tmp_path), "--cut-cache-dir", str(tmp_path / "x")]) + assert fc._cut_cache(args, None).root == tmp_path / "x"