diff --git a/cascade/eval/lane_d_public_export.py b/cascade/eval/lane_d_public_export.py new file mode 100644 index 000000000..281c3b821 --- /dev/null +++ b/cascade/eval/lane_d_public_export.py @@ -0,0 +1,322 @@ +"""Lane D public half: export one settlement's judged PUBLIC windows from the +eval host's cut-window cache (owner 2026-12-01: "store each lane D +settlement's public half eval set publicly"). + +The public half (GIFT-Eval pretrain, RMISC) is public data, so it needs no +retirement wait: the box (:mod:`cascade.pool.settlement_evals`) asks for it as +soon as the settlement's signed report is published. The box sends this host +the report's public block, reduced to what the file needs: the judged window +ids in the report's order (the distinct ``public.rows`` window ids), each +window's draw record (``cut``, ``h``, ``band``, ``length``, ``ordinal``, +``family``, ``freq``), every drawn id, and the per-window CRPS / MASE of +every judged digest (KING_D, the house, each judged member) from the signed +rows. This host finds the settlement's cut file in its +:class:`~cascade.eval.lane_d_public_cut.CutCache` (``/.cut``, +written by the settlement's first digest, #1052) by its windows: the file +whose window ids hold every judged id and only drawn ids. Its key binds the +draws and the boundary block hash, so no other settlement's file can match; +the payload is re-hashed before use. Nothing is re-read or re-cut: the +exported arrays are the cut windows bit for bit (dtype as cut, float64). + +``public_windows.npz`` (one row per judged window, report order; a ``(C, L)`` +window is ``C`` channels flattened channel-major): + +* ``history`` / ``history_offsets``: the history as cut (the finite suffix, + at most ``PUBLIC_MAX_HISTORY`` points; each model forecast from its last + ``context`` points, MASE scales by the whole cut history); +* ``target`` / ``target_offsets``: the ``h`` target points (missing points + NaN, masked by the scorers); +* columns ``window_id``, ``series_id``, ``source``, ``family``, ``freq``, + ``band``, ``channels`` (the ``max_channels`` pick as JSON, ``""`` for a + univariate window), ``h``, ``cut``, ``length``, ``ordinal``, + ``n_channels``, ``history_len``, ``seasonal_period``; +* scores: ``models`` (digests), ``roles`` (``king_d`` / ``house`` / + ``king_d+house`` / ``member``), ``contexts`` (-1 when the report does not + record it), ``crps`` / ``mase`` ``(n_windows, n_models)`` float64 (the + signed rows' values). The eval host keeps no public quantiles (the + forecasts are scored in memory), so the file has none. + +CLI (the box runs it over SSH; the request JSON on stdin, the reply JSON the +last stdout line):: + + python -m cascade.eval.lane_d_public_export build --out-dir D [--cut-cache-dir C] + +Without ``--cut-cache-dir`` the cut dir is ``/cut`` of the +release's ``deploy/laned/public_mirror.toml`` (the ``public`` command's +default). Torch-free, numpy only; the cut file is read without refreshing its +LRU time. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import shutil +import struct +import sys +import zipfile +from collections.abc import Mapping +from pathlib import Path + +import numpy as np + +REQUEST_SCHEMA = "lane-d-public-evals-request/1" +REPLY_SCHEMA = "lane-d-public-evals-reply/1" +NPZ_NAME = "public_windows.npz" +ROLES = ("king_d", "house", "king_d+house", "member") +_STR_COLS = ("window_id", "series_id", "source", "family", "freq", "band", "channels") +_INT_COLS = ("h", "cut", "length", "ordinal", "n_channels", "history_len", "seasonal_period") + + +class ExportError(RuntimeError): + """A request that cannot be exported (typed ``code``).""" + + def __init__(self, code: str, detail: str = ""): + super().__init__(f"{code}: {detail}" if detail else code) + self.code, self.detail = code, detail + + +def _file_sha(p: Path) -> str: + h = hashlib.sha256() + with open(p, "rb") as f: + for b in iter(lambda: f.read(1 << 20), b""): + h.update(b) + return h.hexdigest() + + +def _check_request(req: Mapping) -> dict: + if not isinstance(req, Mapping) or req.get("schema") != REQUEST_SCHEMA: + raise ExportError("bad_request", f"not a {REQUEST_SCHEMA} request") + ws, models = req.get("windows"), req.get("models") + if not isinstance(ws, list) or not ws or not isinstance(models, list) or not models: + raise ExportError("bad_request", "no windows or no models") + ids = [str(w["window_id"]) for w in ws] + if len(set(ids)) != len(ids): + raise ExportError("bad_request", "duplicate window ids") + drawn = {str(x) for x in req.get("drawn_ids") or []} + if not set(ids) <= drawn: + raise ExportError("bad_request", "a judged window is not a drawn one") + for m in models: + if m.get("role") not in ROLES or not isinstance(m.get("digest"), str): + raise ExportError("bad_request", f"bad model {m!r}") + for k in ("crps", "mase"): + a = req.get(k) + if not isinstance(a, list) or len(a) != len(ids) \ + or any(not isinstance(r, list) or len(r) != len(models) for r in a): + raise ExportError("bad_request", f"{k} is not (n_windows, n_models)") + return {"ids": ids, "drawn": drawn} + + +def read_header(p: Path) -> dict: + """A cut file's header JSON only (never the payload).""" + from .lane_d_public_cut import MAGIC + + with open(p, "rb") as f: + 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 = f.read(n) + if len(head) != n: + raise ValueError("short header") + return json.loads(head.decode("utf-8")) + + +def find_cut(cut_dir: Path | str, judged: list[str], drawn: set[str]) -> tuple[Path, str] | None: + """``(path, key)`` of the cut file holding every judged id and only drawn + ids (newest first), or ``None``.""" + from .lane_d_public_cut import CUT_SCHEMA, SUFFIX + + want = set(judged) + cands = [] + for p in Path(cut_dir).glob(f"*{SUFFIX}"): + try: + cands.append((p.stat().st_mtime_ns, p)) + except OSError: + continue + for _mt, p in sorted(cands, reverse=True): + try: + head = read_header(p) + except (OSError, ValueError, UnicodeDecodeError): + continue + if head.get("schema") != CUT_SCHEMA: + continue + ids = {str(r["fields"].get("window_id")) for r in head.get("windows") or []} + if want <= ids <= drawn: + return p, str(head["key"]) + return None + + +def _load_cut(p: Path, key: str) -> list[dict]: + """The cut windows of ``p`` (payload re-hashed), without touching its + mtime (the cache's LRU clock).""" + from .lane_d_public_cut import CutCache + + try: + with open(p, "rb") as f: + windows, _dropped = CutCache._read(f, key) + except (OSError, ValueError, KeyError, TypeError, AttributeError) as e: + raise ExportError("cut_corrupt", f"{p.name}: {e}") from e + return windows + + +class _Raw: + def __init__(self, path: Path, dtype): + self.path, self.dtype, self.n = Path(path), np.dtype(dtype), 0 + self._f = open(self.path, "wb") # noqa: SIM115 — closed by close(), in a finally + + def write(self, a) -> int: + c = np.ascontiguousarray(a, dtype=self.dtype).reshape(-1) + self._f.write(c.tobytes()) + self.n += c.size + return c.size + + def close(self) -> None: + self._f.close() + + +def _stream_npy(zf: zipfile.ZipFile, name: str, raw: _Raw) -> None: + with zf.open(name + ".npy", "w", force_zip64=True) as f: + np.lib.format.write_array_header_1_0( + f, {"descr": np.lib.format.dtype_to_descr(raw.dtype), "fortran_order": False, + "shape": (int(raw.n),)}) + with open(raw.path, "rb") as src: + shutil.copyfileobj(src, f, 1 << 20) + + +def _write_npy(zf: zipfile.ZipFile, name: str, arr) -> None: + with zf.open(name + ".npy", "w", force_zip64=True) as f: + np.lib.format.write_array(f, np.asarray(arr), allow_pickle=False) + + +def _num(x) -> float: + try: + v = float(x) + except (TypeError, ValueError): + return math.nan + return v + + +def build(req: Mapping, *, cut_dir: Path | str, out_dir: Path | str) -> dict: + """Write ``/public_windows.npz`` for the request; the reply. + ``ok: False`` with ``code: "cut_unavailable"`` (and no file) when this + host holds no cut file of the settlement (evicted, or cut before #1052).""" + chk = _check_request(req) + out = Path(out_dir) + if out.exists(): + shutil.rmtree(out) + out.mkdir(parents=True) + try: + hit = find_cut(cut_dir, chk["ids"], chk["drawn"]) + if hit is None: + return {"schema": REPLY_SCHEMA, "ok": False, "code": "cut_unavailable", + "detail": f"no cut file under {cut_dir} holds the {len(chk['ids'])} " + "judged windows"} + path, key = hit + by_id = {str(w["window_id"]): w for w in _load_cut(path, key)} + return _write(req, by_id, out, key=key) + except BaseException: + shutil.rmtree(out, ignore_errors=True) + raise + + +def _write(req: Mapping, by_id: Mapping[str, dict], out: Path, *, key: str) -> dict: + raws = {"history": _Raw(out / "history.raw", np.float64), + "target": _Raw(out / "target.raw", np.float64)} + offs = {k: [0] for k in raws} + cols: dict[str, list] = {k: [] for k in (*_STR_COLS, *_INT_COLS)} + try: + for w in req["windows"]: + wid = str(w["window_id"]) + c = by_id[wid] + if str(c.get("source")) != wid.split(":", 1)[0] \ + or str(c.get("family")) != str(w.get("family", c.get("family"))) \ + or str(c.get("freq")) != str(w.get("freq", c.get("freq"))): + raise ExportError("cut_mismatch", f"{wid}: the cut window names another " + "source, family or freq than the report") + hist, tgt = np.asarray(c["history"]), np.asarray(c["target"]) + if int(tgt.shape[-1]) != int(w["h"]): + raise ExportError("cut_mismatch", f"{wid}: target of {tgt.shape[-1]} points, " + f"not h={w['h']}") + for k, a in (("history", hist), ("target", tgt)): + offs[k].append(offs[k][-1] + raws[k].write(a)) + ch = c.get("channels") + vals = {"window_id": wid, "series_id": str(c.get("series_id") or ""), + "source": str(c["source"]), "family": str(c["family"]), + "freq": str(c["freq"]), "band": str(w.get("band") or ""), + "channels": "" if ch is None else json.dumps(ch, sort_keys=True), + "h": int(w["h"]), "cut": int(w.get("cut", -1)), + "length": int(w.get("length", -1)), "ordinal": int(w.get("ordinal", -1)), + "n_channels": 1 if tgt.ndim == 1 else int(tgt.shape[0]), + "history_len": int(hist.shape[-1]), + "seasonal_period": int(c.get("seasonal_period") or 1)} + for k, v in vals.items(): + cols[k].append(v) + finally: + for r in raws.values(): + r.close() + models = req["models"] + crps = np.asarray([[_num(x) for x in r] for r in req["crps"]], dtype=np.float64) + mase = np.asarray([[_num(x) for x in r] for r in req["mase"]], dtype=np.float64) + npz = out / NPZ_NAME + with zipfile.ZipFile(npz, "w", compression=zipfile.ZIP_DEFLATED, allowZip64=True) as zf: + for k, r in raws.items(): + _stream_npy(zf, k, r) + _write_npy(zf, "history_offsets", np.asarray(offs["history"], dtype=np.int64)) + _write_npy(zf, "target_offsets", np.asarray(offs["target"], dtype=np.int64)) + for k in _STR_COLS: + _write_npy(zf, k, np.asarray(cols[k], dtype=str)) + for k in _INT_COLS: + _write_npy(zf, k, np.asarray(cols[k], dtype=np.int64)) + _write_npy(zf, "models", np.asarray([str(m["digest"]) for m in models], dtype=str)) + _write_npy(zf, "roles", np.asarray([str(m["role"]) for m in models], dtype=str)) + _write_npy(zf, "contexts", np.asarray([int(m.get("context", -1)) for m in models], + dtype=np.int64)) + _write_npy(zf, "crps", crps) + _write_npy(zf, "mase", mase) + for r in raws.values(): + r.path.unlink(missing_ok=True) + return {"schema": REPLY_SCHEMA, "ok": True, "npz": str(npz), "sha256": _file_sha(npz), + "bytes": npz.stat().st_size, "windows": len(cols["window_id"]), + "models": len(models), "cut_key": key, "dtype": "float64"} + + +def default_cut_dir() -> Path: + from .lane_d_public_cut import CUT_SUBDIR + from .lane_d_public_mirror import load_mirror_config + + return Path(load_mirror_config()["cache_dir"]) / CUT_SUBDIR + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(prog="python -m cascade.eval.lane_d_public_export") + sub = ap.add_subparsers(dest="cmd", required=True) + b = sub.add_parser("build", help="build public_windows.npz from the request on stdin") + b.add_argument("--out-dir", type=Path, required=True) + b.add_argument("--cut-cache-dir", type=Path, default=None, + help="the cut-window cache (default: /cut)") + a = ap.parse_args(argv) + try: + cut_dir = a.cut_cache_dir or default_cut_dir() + reply = build(json.loads(sys.stdin.buffer.read()), cut_dir=cut_dir, out_dir=a.out_dir) + except ExportError as e: + reply = {"schema": REPLY_SCHEMA, "ok": False, "code": e.code, "detail": e.detail} + except (ValueError, KeyError, TypeError, OSError) as e: + reply = {"schema": REPLY_SCHEMA, "ok": False, "code": "bad_request", + "detail": f"{type(e).__name__}: {e}"} + print(json.dumps(reply, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) + + +__all__ = ["ExportError", "NPZ_NAME", "REPLY_SCHEMA", "REQUEST_SCHEMA", "ROLES", "build", + "find_cut", "read_header"] diff --git a/cascade/pool/settlement_evals.py b/cascade/pool/settlement_evals.py index 7d93b7d47..2116bac9d 100644 --- a/cascade/pool/settlement_evals.py +++ b/cascade/pool/settlement_evals.py @@ -11,6 +11,15 @@ judged (its signed report's ``windows``), each with its history and target as the settlement cut them, built on the lane D eval host (:mod:`cascade.eval.settlement_eval_build`; the box never loads a pool); +* **lane D public half** (``lane-d/evals//{public_windows.npz, + public_manifest.json}``, listed in the same index; owner 2026-12-01): the + PUBLIC windows the settlement judged (GIFT-Eval pretrain, RMISC), as cut, + with every judged model's per-window CRPS / MASE from the signed rows. + Public data, so no retirement wait: published once the settlement's + signed report is in the bucket. Built on the eval host from its + cut-window cache (:mod:`cascade.eval.lane_d_public_export`), streamed to + the stage like ``windows.npz``; the box reads only its id / score-shape + members. Unsigned extra: the signed report is untouched; * **MarketCast / lane C** (``marketcast/evals//{windows.json, README.md, manifest.json}`` + ``marketcast/evals/index.json``): the windows the MarketCast judge drew for each entry of the round (wid, kind, span, the @@ -91,6 +100,16 @@ LANED_INDEX_SCHEMA = "lane-d-evals-index/1" MKT_INDEX_SCHEMA = "marketcast-evals-index/1" LANED_FILES = ("windows.npz", "README.md", "manifest.json") # manifest last +# owner 2026-12-01: the settlement's PUBLIC half, published at report time +PUBLIC_NPZ = "public_windows.npz" +PUBLIC_MANIFEST = "public_manifest.json" +LANED_PUBLIC_FILES = (PUBLIC_NPZ, PUBLIC_MANIFEST) # manifest last +LANED_PUBLIC_SCHEMA = "lane-d-settlement-public-evals/1" +PUBLIC_UNAVAILABLE_FILE = "public_unavailable.txt" +DEFAULT_PUBLIC_PER_RUN = 2 +# a public half is ~1 GB (5000 windows, up to 131072 history points): the box +# stages it only with this much disk left over +PUBLIC_STAGE_HEADROOM_BYTES = 20 * 2**30 MKT_FILES = ("windows.json", "README.md", "manifest.json") DEFAULT_LANED_SLACK_HOURS = 6.0 DEFAULT_MKT_SLACK_HOURS = 72.0 @@ -215,6 +234,9 @@ def __init__(self, inputs_path, *, timeout_s: float = 3600.0, run: Callable | No self.pool_root = str(raw.get("eval_pool_root") or "") if not self.pool_root: raise ValueError(f"{inputs_path}: eval_pool_root unset (W-OFFBOX host copy)") + # the public half's cut-window cache (#1052) sits under the host's + # public blob cache, as the validator's ``public`` requests put it + self.public_cache_dir = str(raw.get("eval_public_cache_dir") or "") self.timeout_s = float(timeout_s) self._run = run or subprocess.run @@ -237,13 +259,30 @@ def _argv(self, host, cmd: str) -> list[str]: def out_dir(boundary: int) -> str: return f"{HOST_STAGE}/{int(boundary)}" + @staticmethod + def public_out_dir(boundary: int) -> str: + return f"{HOST_STAGE}/public-{int(boundary)}" + def build(self, request: Mapping) -> dict: + return self._ask(["cascade.eval.settlement_eval_build", "build", + "--pool-root", self.pool_root, + "--out-dir", self.out_dir(request["boundary"])], request) + + def build_public(self, request: Mapping) -> dict: + """The settlement's ``public_windows.npz`` from the host's cut cache + (:mod:`cascade.eval.lane_d_public_export`).""" + extra = (["--cut-cache-dir", f"{self.public_cache_dir.rstrip('/')}/cut"] + if self.public_cache_dir else []) + return self._ask(["cascade.eval.lane_d_public_export", "build", + "--out-dir", self.public_out_dir(request["boundary"]), *extra], + request) + + def _ask(self, module_args: list[str], request: Mapping) -> dict: host = self._host() bound = max(1, int(self.timeout_s) - 30) cmd = " ".join(shlex.quote(a) for a in [ "timeout", "-k", "30", str(bound), "nice", "-n", "19", "ionice", "-c", "3", - host.remote_python, "-m", "cascade.eval.settlement_eval_build", "build", - "--pool-root", self.pool_root, "--out-dir", self.out_dir(request["boundary"])]) + host.remote_python, "-m", *module_args]) proc = self._run(self._argv(host, cmd), input=json.dumps(request).encode(), capture_output=True, timeout=self.timeout_s, check=False) lines = [ln for ln in (proc.stdout or b"").decode("utf-8", "replace").splitlines() @@ -255,8 +294,20 @@ def build(self, request: Mapping) -> dict: def fetch(self, boundary: int, dest: Path) -> None: """Stream the host's ``windows.npz`` to ``dest`` (disk, never memory).""" + self._cat(f"{self.out_dir(boundary)}/windows.npz", dest) + + def fetch_public(self, boundary: int, dest: Path) -> None: + """Stream the host's ``public_windows.npz`` to ``dest`` (disk, never + memory).""" + self._cat(f"{self.public_out_dir(boundary)}/{PUBLIC_NPZ}", dest) + + def cleanup_public(self, boundary: int) -> None: + host = self._host() + self._run(self._argv(host, f"rm -rf -- {shlex.quote(self.public_out_dir(boundary))}"), + capture_output=True, timeout=600, check=False) + + def _cat(self, src: str, dest: Path) -> None: host = self._host() - src = f"{self.out_dir(boundary)}/windows.npz" with open(dest, "wb") as f: proc = self._run(self._argv(host, f"cat {shlex.quote(src)}"), stdout=f, stderr=subprocess.PIPE, timeout=self.timeout_s, check=False) @@ -360,6 +411,22 @@ def laned_readme(man: Mapping) -> str: `feed`, `freq`, `band`, `h`, `origin_ts`, `n_channels`, `history_len`, `seasonal_period`, `embargo_window`. Every published settlement is listed in `../index.json`. + +## The public half + +`public_windows.npz` (published at the settlement, no wait; see +`public_manifest.json`) holds the public windows (GIFT-Eval pretrain, RMISC) +this settlement judged, as cut, and every judged model's CRPS / MASE on each: + +```python +z = np.load("public_windows.npz") +i = 0 +c = int(z["n_channels"][i]) +history = z["history"][z["history_offsets"][i]:z["history_offsets"][i + 1]].reshape(c, -1) +target = z["target"][z["target_offsets"][i]:z["target_offsets"][i + 1]].reshape(c, -1) +king = [str(r).startswith("king_d") for r in z["roles"]].index(True) # KING_D's column +print(z["window_id"][i], z["band"][i], z["crps"][i, king], z["mase"][i, king]) +``` """ @@ -394,13 +461,14 @@ def _ctype(name: str) -> str: "npz": "application/octet-stream"}[name.rsplit(".", 1)[-1]] -def published_ids(client, bucket: str, prefix: str) -> list[str]: - """Ids ``//manifest.json`` exists for.""" +def published_ids(client, bucket: str, prefix: str, name: str = "manifest.json") -> list[str]: + """Ids ``//`` exists for (``manifest.json``: the + retired sets).""" out = set() for o in _list_keys(client, bucket, prefix + "/"): rest = o["Key"][len(prefix) + 1:] head, _, tail = rest.partition("/") - if head and tail == "manifest.json": + if head and tail == name: out.add(head) return sorted(out) @@ -417,11 +485,14 @@ def upload_dir(client, bucket: str, prefix: str, stage: Path, names) -> list[str def refresh_index(client, bucket: str, prefix: str, *, schema: str, base_url: str, now: int, - entry: Callable[[str, dict], dict], waiting: list, dry_run: bool) -> tuple: - """Rebuild ``/index.json`` from the published manifests; PUT it - only when its list (or the waiting list) changed.""" + entry: Callable[[str, dict], dict], waiting: list, dry_run: bool, + ids: Iterable[str] | None = None) -> tuple: + """Rebuild ``/index.json`` from the published manifests (of + ``ids``, default every id with a ``manifest.json``); PUT it only when its + list (or the waiting list) changed.""" + ids = published_ids(client, bucket, prefix) if ids is None else list(ids) items = [entry(i, _get_json(client, bucket, f"{prefix}/{i}/manifest.json") or {}) - for i in published_ids(client, bucket, prefix)] + for i in ids] doc = {"schema": schema, "generated_ts": int(now), "count": len(items), "items": items, "waiting": waiting} old = _get_json(client, bucket, f"{prefix}/{INDEX_NAME}") or {} @@ -434,27 +505,282 @@ def refresh_index(client, bucket: str, prefix: str, *, schema: str, base_url: st return doc, True -def _laned_entry(base_url: str): +def _laned_entry(base_url: str, public: Mapping[str, dict] | None = None): + """One index item. Every pre-2026-12-01 field is present on every item; + on a settlement whose retired set is not out yet (only its public half + is) they are ``null``. The public half's fields are optional extras, + present iff its ``public_manifest.json`` is published.""" + public = public or {} + def entry(i: str, man: dict) -> dict: f = (man.get("files") or {}).get("windows.npz") or {} p = f"{LANED_PREFIX}/{i}" - return {"boundary": int(i), "windows": man.get("windows"), - "windows_sha256": f.get("sha256"), "windows_bytes": f.get("bytes"), - "cut_ts": (man.get("retired_rule") or {}).get("cut_ts"), - "built_ts": man.get("built_ts"), "report_url": man.get("report_url"), - "manifest_url": f"{base_url}/{p}/manifest.json", - "windows_url": f"{base_url}/{p}/windows.npz", - "readme_url": f"{base_url}/{p}/README.md"} + out = {"boundary": int(i), "windows": man.get("windows"), + "windows_sha256": f.get("sha256"), "windows_bytes": f.get("bytes"), + "cut_ts": (man.get("retired_rule") or {}).get("cut_ts"), + "built_ts": man.get("built_ts"), "report_url": man.get("report_url"), + "manifest_url": f"{base_url}/{p}/manifest.json" if man else None, + "windows_url": f"{base_url}/{p}/windows.npz" if man else None, + "readme_url": f"{base_url}/{p}/README.md" if man else None} + pm = public.get(i) + if pm: + pf = (pm.get("files") or {}).get(PUBLIC_NPZ) or {} + out.update({"public_windows": pm.get("windows"), + "public_windows_sha256": pf.get("sha256"), + "public_windows_bytes": pf.get("bytes"), + "public_windows_url": f"{base_url}/{p}/{PUBLIC_NPZ}", + "public_manifest_url": f"{base_url}/{p}/{PUBLIC_MANIFEST}"}) + if out["report_url"] is None: + out["report_url"] = pm.get("report_url") + return out return entry +def laned_index(client, bucket: str, *, base_url: str, now: int, waiting: list, + dry_run: bool) -> tuple: + """``lane-d/evals/index.json``: one item per settlement with a retired + set or a public half (or both), boundary order.""" + retired = set(published_ids(client, bucket, LANED_PREFIX)) + pub_ids = set(published_ids(client, bucket, LANED_PREFIX, PUBLIC_MANIFEST)) + public = {i: _get_json(client, bucket, f"{LANED_PREFIX}/{i}/{PUBLIC_MANIFEST}") or {} + for i in pub_ids} + ids = sorted(retired | pub_ids, key=lambda x: (not x.isdigit(), int(x) if x.isdigit() + else 0, x)) + return refresh_index(client, bucket, LANED_PREFIX, schema=LANED_INDEX_SCHEMA, + base_url=base_url, now=now, entry=_laned_entry(base_url, public), + waiting=waiting, dry_run=dry_run, ids=ids) + + +# ── lane D: the public half (no retirement wait) ──────────────────────────── + + +def public_request(report: Mapping) -> dict | None: + """The eval host's export request of one report's judged PUBLIC windows, + or ``None`` (no public block, or nobody was scored on it). The judged + ids are the distinct ``public.rows`` window ids in the rows' order (the + settlement's kept public windows, ``window_id`` order); the scores are + the signed rows' values.""" + from ..eval.lane_d_public_export import REQUEST_SCHEMA + + pub = report.get("public") + rows = (pub or {}).get("rows") or [] + if not rows: + return None + rec: dict[str, dict] = {} + for s in pub.get("sources") or []: + for w in s.get("windows") or []: + rec[str(w["window_id"])] = {**w, "source": str(s["source"])} + ids: list[str] = [] + seen: set[str] = set() + score: dict[tuple[str, str], tuple] = {} + for r in rows: + wid = str(r["window_id"]) + if wid not in seen: + seen.add(wid) + ids.append(wid) + score[(wid, str(r["digest"]))] = (r.get("crps"), r.get("mase")) + missing = [i for i in ids if i not in rec] + if missing: + raise ValueError(f"public rows name undrawn windows ({missing[:2]})") + king = str(((report.get("king_before") or {}).get("digest")) or "") + house = str(((report.get("house") or {}).get("digest")) or "") + ctx = {str(e.get("digest")): int(e["context"]) for e in report.get("entries") or [] + if isinstance(e, Mapping) and type(e.get("context")) is int} + models = [] + for dg in sorted({str(r["digest"]) for r in rows}): + role = ("king_d+house" if dg == king == house else "king_d" if dg == king + else "house" if dg == house else "member") + models.append({"digest": dg, "role": role, "context": ctx.get(dg, -1)}) + keep = ("window_id", "source", "family", "freq", "cut", "h", "band", "length", "ordinal") + nan = float("nan") + return {"schema": REQUEST_SCHEMA, "boundary": int(report["boundary"]), + "windows": [{k: rec[i][k] for k in keep if k in rec[i]} for i in ids], + "drawn_ids": sorted(rec), + "models": models, + "crps": [[score.get((i, m["digest"]), (nan, nan))[0] for m in models] for i in ids], + "mase": [[score.get((i, m["digest"]), (nan, nan))[1] for m in models] for i in ids]} + + +def _npy_header(z: zipfile.ZipFile, name: str) -> tuple: + import numpy as np + + with z.open(name + ".npy") as f: + major, _ = np.lib.format.read_magic(f) + shape, _fortran, dtype = (np.lib.format.read_array_header_1_0(f) if major == 1 + else np.lib.format.read_array_header_2_0(f)) + return tuple(shape), np.dtype(dtype) + + +def verify_public_npz(npz: Path, request: Mapping) -> None: + """Re-check the fetched file on the box without loading its arrays: + the ``window_id`` column is the report's judged ids in order, ``models`` + its digests, and ``crps`` / ``mase`` are ``(n_windows, n_models)``. Only + those small members are read; ``history`` / ``target`` never are.""" + import numpy as np + + ids = [str(w["window_id"]) for w in request["windows"]] + digests = [str(m["digest"]) for m in request["models"]] + with zipfile.ZipFile(npz) as z: + for name in ("crps", "mase"): + shape, _ = _npy_header(z, name) + if shape != (len(ids), len(digests)): + raise RuntimeError(f"{npz}: {name} is {shape}, not ({len(ids)}, {len(digests)})") + for name, want in (("window_id", ids), ("models", digests)): + with z.open(name + ".npy") as f: + got = [str(x) for x in np.lib.format.read_array(f, allow_pickle=False)] + if got != want: + raise RuntimeError(f"{npz}: {name} is not the report's public draw") + + +def _report_published(client, bucket: str, boundary: int) -> bool: + from ..validator.lane_d_wiring import report_key + + key = report_key(int(boundary)) + return any(o["Key"] == key for o in _list_keys(client, bucket, key)) + + +def laned_public_manifest(report: Mapping, report_path: Path, request: Mapping, + reply: Mapping, *, now: int, base_url: str, npz: Path) -> dict: + from ..validator.lane_d_wiring import report_key + + b = int(report["boundary"]) + rk = report_key(b) + srcs = (report.get("public") or {}).get("sources") or [] + seeds = [str(s.get("seed") or "") for s in srcs] + return { + "schema": LANED_PUBLIC_SCHEMA, "boundary": b, "boundary_ts": report.get("boundary_ts"), + "kind": "the public windows this settlement judged (its signed report's public " + "rows), each as the settlement cut it, with every judged model's " + "per-window CRPS and MASE", + "report_key": rk, "report_url": f"{base_url}/{rk}", + "report_sha256": _sha_file(report_path), + "public_rows_sha256": (report.get("public") or {}).get("rows_sha256"), + "boundary_block_hash": seeds[0].partition(":")[0] if seeds else None, + "draw_seeds": {str(s["source"]): s.get("seed") for s in srcs}, + "data": {str(s["source"]): {"repo": s.get("repo"), "revision": s.get("revision"), + "index_sha256": s.get("index_sha256"), + "files_sha256": s.get("files_sha256")} for s in srcs}, + "keep": (report.get("extensions") or {}).get("public_keep"), + "windows": reply.get("windows"), + "models": list(request["models"]), + "quantiles": None, + "quantiles_note": "the eval host scores the public forecasts in memory and keeps no " + "quantiles", + "cut_key": reply.get("cut_key"), "dtype": reply.get("dtype"), "built_ts": int(now), + "files": {PUBLIC_NPZ: {"sha256": _sha_file(npz), "bytes": npz.stat().st_size}}, + } + + +def _unavailable(stage: Path) -> set[int]: + p = Path(stage) / PUBLIC_UNAVAILABLE_FILE + try: + return {int(x) for x in p.read_text(encoding="utf-8").split() if x.isdigit()} + except OSError: + return set() + + +def publish_laned_public(*, client, bucket: str, base_url: str, reports_dir: Path, host, + stage: Path, now: int, max_per_run: int = DEFAULT_PUBLIC_PER_RUN, + dry_run: bool = False, log: Callable[[str], None] = print) -> dict: + """One public-half pass: every settlement whose signed report is + published and has public rows, newest first, gets + ``lane-d/evals//public_windows.npz`` + ``public_manifest.json`` + (built on the eval host from its cut cache, streamed to ``stage``, + re-checked, uploaded public-read, manifest last). No retirement wait: + the windows are public data, re-derivable from the report's draw.""" + done = {int(x) for x in published_ids(client, bucket, LANED_PREFIX, PUBLIC_MANIFEST) + if x.isdigit()} + gone = _unavailable(stage) + out = {"built": [], "unavailable": [], "empty": [], "unpublished": [], "failed": []} + tried = 0 + for b, rp in sorted(laned_reports(reports_dir), reverse=True): + if b in done or b in gone: + continue + if tried >= max(0, int(max_per_run)): + break + rep = json.loads(rp.read_text(encoding="utf-8")) + try: + req = public_request(rep) + except (KeyError, TypeError, ValueError) as e: + log(f"evals laned public: {b} malformed public block ({type(e).__name__}: {e})") + out["failed"].append(b) + continue + if req is None: + out["empty"].append(b) + continue + if not _report_published(client, bucket, b): + out["unpublished"].append(b) + continue + tried += 1 + d = Path(stage) / f"laned-public-{b}" + shutil.rmtree(d, ignore_errors=True) + d.mkdir(parents=True) + try: + reply = host.build_public(req) + if not reply.get("ok"): + log(f"evals laned public: {b} not built ({reply.get('code')}: " + f"{reply.get('detail')})") + if reply.get("code") == "cut_unavailable": + out["unavailable"].append(b) + if not dry_run: + with open(Path(stage) / PUBLIC_UNAVAILABLE_FILE, "a", + encoding="utf-8") as f: + f.write(f"{b}\n") + else: + out["failed"].append(b) + continue + need = int(reply.get("bytes") or 0) + PUBLIC_STAGE_HEADROOM_BYTES + free = shutil.disk_usage(d).free + if free < need: + log(f"evals laned public: {b} waits (stage {free} B free < {need} B: the " + f"file plus {PUBLIC_STAGE_HEADROOM_BYTES} B headroom)") + out["failed"].append(b) + continue + npz = d / PUBLIC_NPZ + host.fetch_public(b, npz) + if _sha_file(npz) != reply.get("sha256"): + raise RuntimeError(f"{b}: fetched {PUBLIC_NPZ} does not hash to the reply") + verify_public_npz(npz, req) + man = laned_public_manifest(rep, rp, req, reply, now=now, base_url=base_url, + npz=npz) + (d / PUBLIC_MANIFEST).write_text(json.dumps(man, indent=1, sort_keys=True) + "\n", + encoding="utf-8") + log(f"evals laned public: {'would upload' if dry_run else 'upload'} " + f"{LANED_PREFIX}/{b}/{PUBLIC_NPZ} windows={man['windows']} " + f"models={len(man['models'])} ({npz.stat().st_size} B)") + if not dry_run: + upload_dir(client, bucket, f"{LANED_PREFIX}/{b}", d, LANED_PUBLIC_FILES) + out["built"].append(b) + except Exception as e: # noqa: BLE001 + log(f"evals laned public: {b} FAILED {type(e).__name__}: {e}") + out["failed"].append(b) + finally: + shutil.rmtree(d, ignore_errors=True) + cleanup = getattr(host, "cleanup_public", None) + if callable(cleanup): + cleanup(b) + log("evals laned public: " + json.dumps(out, sort_keys=True)) + return out + + def publish_laned(*, client, bucket: str, base_url: str, reports_dir: Path, state: Mapping, state_mtime: int, embargo_hours: float, host, stage: Path, now: int, slack_hours: float = DEFAULT_LANED_SLACK_HOURS, history_cap: int | None = None, max_per_run: int = 2, dry_run: bool = False, - log: Callable[[str], None] = print) -> dict: - """One lane D pass: plan, build each candidate on the host, verify, - upload (unless ``dry_run``), refresh the index.""" + log: Callable[[str], None] = print, + public_per_run: int = DEFAULT_PUBLIC_PER_RUN) -> dict: + """One lane D pass: the public halves (no wait), then plan, build each + retired candidate on the host, verify, upload (unless ``dry_run``), + refresh the index.""" + public = None + if public_per_run > 0 and callable(getattr(host, "build_public", None)): + try: + public = publish_laned_public(client=client, bucket=bucket, base_url=base_url, + reports_dir=reports_dir, host=host, stage=stage, + now=now, max_per_run=public_per_run, + dry_run=dry_run, log=log) + except Exception as e: # noqa: BLE001 + log(f"evals laned public: FAILED {type(e).__name__}: {e}") published = [int(x) for x in published_ids(client, bucket, LANED_PREFIX) if x.isdigit()] plan = laned_plan(reports_dir, state, now=now, state_mtime=state_mtime, embargo_hours=embargo_hours, slack_hours=slack_hours, published=published) @@ -496,13 +822,12 @@ def publish_laned(*, client, bucket: str, base_url: str, reports_dir: Path, stat finally: shutil.rmtree(d, ignore_errors=True) host.cleanup(b) - doc, wrote = refresh_index(client, bucket, LANED_PREFIX, schema=LANED_INDEX_SCHEMA, - base_url=base_url, now=now, entry=_laned_entry(base_url), - waiting=sorted(waiting, key=lambda x: x["boundary"]), - dry_run=dry_run) + doc, wrote = laned_index(client, bucket, base_url=base_url, now=now, + waiting=sorted(waiting, key=lambda x: x["boundary"]), + dry_run=dry_run) log(f"evals laned: index {LANED_PREFIX}/{INDEX_NAME} items={doc.get('count')} " + ("unchanged" if not wrote else ("would write" if dry_run else "written"))) - return {"plan": plan, "built": done} + return {"plan": plan, "built": done, "public": public} # ── MarketCast / lane C ───────────────────────────────────────────────────── @@ -793,7 +1118,8 @@ def cmd_run(a) -> int: state=state, state_mtime=int(os.stat(sp).st_mtime), embargo_hours=effective_embargo_hours(cfg.lane_d.embargo_hours), host=host, stage=stage, now=now, slack_hours=a.laned_slack_hours, - history_cap=a.history_cap, dry_run=a.dry_run) + history_cap=a.history_cap, dry_run=a.dry_run, + public_per_run=a.laned_public_per_run) except Exception as e: # noqa: BLE001 print(f"evals laned: FAILED {type(e).__name__}: {e}", file=sys.stderr) rc = 2 @@ -831,6 +1157,8 @@ def main(argv: list[str] | None = None) -> int: p.add_argument("--laned-state", type=Path, default=None, help="lane_d_state.json") p.add_argument("--laned-inputs", type=Path, default=None, help="the --lane-d-inputs file") p.add_argument("--laned-slack-hours", type=float, default=DEFAULT_LANED_SLACK_HOURS) + p.add_argument("--laned-public-per-run", type=int, default=DEFAULT_PUBLIC_PER_RUN, + help="settlement public halves exported per run (0: none); no wait") p.add_argument("--history-cap", type=int, default=None, help="most history points published per window (default: 131072, the " "longest scorer context, so the set carries what the judge used)") @@ -852,7 +1180,9 @@ def main(argv: list[str] | None = None) -> int: __all__ = [ "EmbargoViolation", "EvalHost", "LANED_PREFIX", "MKT_PREFIX", "PUBLIC_PREFIXES", - "acl_backfill", "build_request", "laned_cut", "laned_plan", "mkt_cut", "mkt_round_retired", - "mkt_windows", "publish_laned", "publish_mkt", "report_precheck", "verify_npz", + "acl_backfill", "build_request", "laned_cut", "laned_index", "laned_plan", "mkt_cut", + "mkt_round_retired", "mkt_windows", "public_request", "publish_laned", + "publish_laned_public", "publish_mkt", "report_precheck", "verify_npz", + "verify_public_npz", "window_retired", ] diff --git a/docs/MINER_LANE_D.md b/docs/MINER_LANE_D.md index e716f2c0d..73b9fc3b8 100644 --- a/docs/MINER_LANE_D.md +++ b/docs/MINER_LANE_D.md @@ -385,8 +385,9 @@ no keys needed): | One boundary's report | `lane-d/reports/lane_d_report_.json` | Signed by the validator (`signer`, `signature`) | | Spent pools index | [`lane-d/spent/index.json`](https://s3.hippius.com/cascade-manifests/lane-d/spent/index.json) | Every published spent `pool_d` snapshot (`pools[]`: `as_of_ts`, `windows`, `windows_sha256`, `manifest_url`, `windows_url`, `readme_url`). Updated hourly; append-only | | One spent pool | `lane-d/spent/pool-preview-/` | `windows.npz` (history as the judge used it, up to 131072 points; target, both clocks, the house's 9 quantiles, CRPS and MASE per window), `manifest.json` (sha256s, counts, the spent rule's `cut_ts`), `README.md` (load snippet). Every window of the snapshot, not a settlement's draw; consecutive pools overlap, dedupe by `window_id` | -| Settlement eval sets index | [`lane-d/evals/index.json`](https://s3.hippius.com/cascade-manifests/lane-d/evals/index.json) | Every published settlement eval set (`items[]`: `boundary`, `windows`, `windows_sha256`, `cut_ts`, `report_url`, `manifest_url`, `windows_url`, `readme_url`) and the settlements still `waiting` to retire. Updated hourly | +| Settlement eval sets index | [`lane-d/evals/index.json`](https://s3.hippius.com/cascade-manifests/lane-d/evals/index.json) | Every published settlement eval set (`items[]`: `boundary`, `windows`, `windows_sha256`, `cut_ts`, `report_url`, `manifest_url`, `windows_url`, `readme_url`, plus the optional `public_windows`, `public_windows_sha256`, `public_windows_url`) and the settlements still `waiting` to retire. Updated hourly | | One settlement's eval set | `lane-d/evals//` | `windows.npz`: exactly the windows that settlement judged, each with its history (the points the judge used: up to 131072, or up to 16384 for a window from a snapshot built before 2026-11-29) and target as the settlement cut them (any band `h`), both clocks, `band`, `embargo_window`; `manifest.json` (sha256s, the report it came from, the retirement `cut_ts`), `README.md` (load snippet). Per-window scores per model are the report's `rows` | +| One settlement's public half | `lane-d/evals//public_windows.npz` | Published at the settlement (public data, no wait) for every settlement with public rows. Exactly the public windows (GIFT-Eval pretrain, RMISC) it judged, in the report's order, as cut: history (finite suffix, up to 131072 points; each model forecast from its last `context` points, MASE scales by the whole history), target, `window_id`, `source`, `family`, `freq`, `band`, `h`, `cut`, the `max_channels` pick (`channels`); per-window `crps` / `mase` for every judged model (`models`, `roles`: `king_d`, `house`, `member`). No quantiles. `public_manifest.json`: sha256s, boundary block hash, draw seeds, data revisions, `report_sha256`. The index item gains `public_windows`, `public_windows_sha256`, `public_windows_url` (an item whose retired set is not out yet has `windows_url: null`) | | Live lane D board | `status/lane_d.json` | King, prior kings, queue, latest board and verdicts | A boundary is a block number that is a multiple of 900 (`epoch_blocks`, diff --git a/tests/accept/w_evalpub/PATHS b/tests/accept/w_evalpub/PATHS index afecd9b99..593d1918e 100644 --- a/tests/accept/w_evalpub/PATHS +++ b/tests/accept/w_evalpub/PATHS @@ -20,3 +20,6 @@ docs/MINER_LANE_D.md docs/MINER_LANE_C_MARKETCAST.md docs/OPERATOR.md cascade/website/index.html +# Owner 2026-12-01: the settlement's public half, exported on the eval host +# from its cut-window cache (published at report time). +cascade/eval/lane_d_public_export.py diff --git a/tests/accept/w_evalpub/README.md b/tests/accept/w_evalpub/README.md index 53ce9eb9a..c72431b9c 100644 --- a/tests/accept/w_evalpub/README.md +++ b/tests/accept/w_evalpub/README.md @@ -69,6 +69,15 @@ lane D per the lanes B/C/D defaults rule. (`cascade.eval.settlement_eval_build`, niced, its pinned copies re-hashed against the report's `snapshot_sha256`), streamed to the box's stage and re-verified there; the box loads no pool. +- `lane-d/evals//{public_windows.npz, public_manifest.json}` (owner + 2026-12-01): the settlement's judged PUBLIC windows, published once its + signed report is in the bucket (public data: no wait). Built on the eval host + from the settlement's cut-window cache (`cascade.eval.lane_d_public_export` + over `lane_d_public_cut.CutCache`, file found by its window ids, payload + re-hashed), streamed to the stage, checked on the box from the `window_id` / + `models` / score-shape members only, listed in the index item + (`public_windows*`). A settlement whose cut file is gone is recorded in + `public_unavailable.txt` and not retried. - `marketcast/evals//{windows.json, README.md, manifest.json}` + `marketcast/evals/index.json`; bars = the public post-embargo bars. - `public-read` on `lane_b/round-*`, `lane_c/round-*` (also at write, trainer) diff --git a/tests/accept/w_evalpub/test_w_evalpub_public.py b/tests/accept/w_evalpub/test_w_evalpub_public.py new file mode 100644 index 000000000..00899ee3a --- /dev/null +++ b/tests/accept/w_evalpub/test_w_evalpub_public.py @@ -0,0 +1,385 @@ +"""W-EVALPUB public half (owner 2026-12-01): each lane D settlement's judged +PUBLIC windows, published at report time as +``lane-d/evals//public_windows.npz`` + ``public_manifest.json``. + +Torch-free: an in-memory S3, an in-process eval host over a real +:class:`~cascade.eval.lane_d_public_cut.CutCache` (the settlement's cut file +plus a decoy of another settlement). Every test reaches the new code through +:func:`pub` / :func:`export`, which ASSERT it exists, so on main each fails +by assertion. +""" + +from __future__ import annotations + +import hashlib +import io +import json +import shutil +import sys +import zipfile +from types import SimpleNamespace + +import numpy as np +import pytest + +from tests.accept.w_evalpub.helpers import FakeS3, evals, mod + +BASE = "https://s3.example/b" +B = 9623700 +BH = "0x" + "2b" * 32 +KING = "b0" * 32 # KING_D and the house (the house reigns) +MEMBER = "7b" * 32 +NOW = 1_796_100_000 + + +def pub(): + m = evals() + for name in ("publish_laned_public", "public_request", "verify_public_npz", "laned_index", + "PUBLIC_NPZ", "PUBLIC_MANIFEST"): + assert hasattr(m, name), f"settlement_evals.{name} is missing" + return m + + +def export(): + return mod("cascade.eval.lane_d_public_export") + + +def _series(seed: int, shape) -> np.ndarray: + return np.random.default_rng(seed).normal(10.0, 1.0, shape) + + +def drawn(src: str, n: int, *, h: int = 8, bh: str = BH) -> list[dict]: + tag = bh[2:6] + return [{"window_id": f"{src}:{tag}_S{i}#{i}:{200 + i}:h{h}", "ordinal": i, + "family": f"fam{i % 2}", "freq": "H", "cut": 200 + i, "h": h, + "length": 400 + i, "band": "short"} for i in range(n)] + + +def cut_window(w: dict, src: str, i: int) -> dict: + multi = i == 1 + hist = _series(i + 10, (2, 150 + i) if multi else (150 + i,)) + tgt = _series(i + 50, (2, w["h"]) if multi else (w["h"],)) + sid = w["window_id"].split(":")[1] + return {"window_id": w["window_id"], "series_id": sid, "source": src, + "family": w["family"], "freq": w["freq"], "seasonal_period": 24, + "history": hist, "target": tgt, + "channels": ({"series_id": sid, "n_channels_raw": 3, "empty_channels": [], + "n_channels": 2, "channels": [0, 2], "channels_sha256": "ee" * 32} + if multi else None)} + + +def setting(tmp_path, *, with_cut: bool = True, bh: str = BH, boundary: int = B): + """A report with a public block (two sources, one drawn window dropped), + its rows for KING_D/house and a member, and the eval host's cut cache.""" + from cascade.eval.lane_d_public_cut import CutCache + + srcs, cut, dropped = [], [], {} + for src, n in (("gift_eval_pretrain", 4), ("rmisc", 3)): + ws = drawn(src, n, bh=bh) + srcs.append({"source": src, "repo": f"repo/{src}", "revision": "c0ffee" + src[:2], + "index_sha256": hashlib.sha256(src.encode()).hexdigest(), + "files_sha256": "11" * 32, "seed": f"{bh}:lane_d_public:{src}", + "n_windows": 5000, "horizon": 64, "min_history": 128, + "multi_window": src == "rmisc", "capacity": {}, "quota": {}, + "windows": ws, + "dropped": [{"window_id": ws[-1]["window_id"], + "reason": "public_short_history"}]}) + dropped[src] = srcs[-1]["dropped"] + cut += [cut_window(w, src, i) for i, w in enumerate(ws[:-1])] + cut.sort(key=lambda w: w["window_id"]) + rows = [] + for k, w in enumerate(cut): + for dg in sorted((KING, MEMBER)): + rows.append({"window_id": w["window_id"], "digest": dg, + "crps": 0.1 + k / 100 + (dg == MEMBER) / 7, + "mase": 1.0 + k / 10 + (dg == MEMBER) / 3}) + rep = {"schema": "lane-d-report/1", "boundary": boundary, "boundary_ts": NOW - 3600, + "king_before": {"digest": KING, "house": True}, + "house": {"digest": KING, "house": True}, + "entries": [{"digest": MEMBER, "context": 4096, "status": "lost"}], + "extensions": {"public_keep": {"schema": "lane-d-public-keep/1", "total": 5000}}, + "windows": [], "rows": [], + "public": {"schema": "lane-d-public/1", "sources": srcs, "rows": rows, + "rows_sha256": "cd" * 32}} + reports = tmp_path / "lane_d_state_reports" + reports.mkdir(exist_ok=True) + rp = reports / f"lane_d_report_{boundary}.json" + rp.write_text(json.dumps(rep)) + cut_dir = tmp_path / "public_cache" / "cut" + if with_cut: + CutCache(cut_dir).store("a" * 64 if bh == BH else "c" * 64, cut, dropped) + return SimpleNamespace(report=rep, path=rp, reports=reports, cut=cut, cut_dir=cut_dir) + + +def decoy(tmp_path): + """A newer cut file of ANOTHER settlement (other draw) in the same cache.""" + from cascade.eval.lane_d_public_cut import CutCache + + other = [cut_window(w, "rmisc", i) for i, w in enumerate(drawn("rmisc", 3, + bh="0x" + "9f" * 32))] + CutCache(tmp_path / "public_cache" / "cut").store("d" * 64, other, {"rmisc": []}) + + +class Host: + """The eval host in-process (EvalHost's public interface).""" + + def __init__(self, cut_dir, work): + self.cut_dir, self.work = cut_dir, work + self.requests: list[bytes] = [] + self.built = [] + + def build_public(self, request): + raw = json.dumps(request).encode() + self.requests.append(raw) + return export().build(json.loads(raw), cut_dir=self.cut_dir, + out_dir=self.work / f"public-{request['boundary']}") + + def fetch_public(self, b, dest): + shutil.copyfile(self.work / f"public-{b}" / "public_windows.npz", dest) + + def cleanup_public(self, b): + shutil.rmtree(self.work / f"public-{b}", ignore_errors=True) + + +def put_report(s3, b=B): + s3.objects[f"lane-d/reports/lane_d_report_{b}.json"] = {"body": b"{}"} + + +def run_public(m, s3, st, host, tmp_path, **kw): + return m.publish_laned_public(client=s3, bucket="b", base_url=BASE, + reports_dir=st.reports, host=host, + stage=tmp_path / "stage", now=NOW, log=lambda s: None, **kw) + + +def judged_ids(rep) -> list[str]: + out = [] + for r in rep["public"]["rows"]: + if r["window_id"] not in out: + out.append(r["window_id"]) + return out + + +def test_public_npz_is_the_reports_public_draw_exactly(tmp_path): + m = pub() + st = setting(tmp_path) + decoy(tmp_path) + s3, host = FakeS3(), Host(st.cut_dir, tmp_path / "host") + put_report(s3) + got = run_public(m, s3, st, host, tmp_path) + assert got["built"] == [B] + pre = f"{m.LANED_PREFIX}/{B}/" + assert [k for k in s3.puts if k.startswith(pre)] == [pre + "public_windows.npz", + pre + "public_manifest.json"] + assert all(s3.objects[k]["ACL"] == "public-read" for k in s3.puts) + z = np.load(io.BytesIO(s3.objects[pre + "public_windows.npz"]["body"])) + ids = judged_ids(st.report) + assert [str(x) for x in z["window_id"]] == ids # the report's order, exactly + by = {w["window_id"]: w for w in st.cut} + for i, wid in enumerate(ids): + c = int(z["n_channels"][i]) + hist = z["history"][z["history_offsets"][i]:z["history_offsets"][i + 1]].reshape(c, -1) + tgt = z["target"][z["target_offsets"][i]:z["target_offsets"][i + 1]].reshape(c, -1) + assert hist.dtype == np.float64 + assert np.array_equal(hist, np.atleast_2d(by[wid]["history"])) # bit for bit + assert np.array_equal(tgt, np.atleast_2d(by[wid]["target"])) + assert str(z["source"][i]) == wid.split(":", 1)[0] + assert int(z["h"][i]) == 8 and str(z["band"][i]) == "short" + ch = str(z["channels"][i]) + assert (json.loads(ch)["channels"] == [0, 2]) if by[wid]["channels"] else ch == "" + assert [str(x) for x in z["models"]] == sorted((KING, MEMBER)) + roles = dict(zip([str(x) for x in z["models"]], [str(x) for x in z["roles"]], strict=True)) + assert roles == {KING: "king_d+house", MEMBER: "member"} + rows = {(r["window_id"], r["digest"]): r for r in st.report["public"]["rows"]} + for i, wid in enumerate(ids): + for j, dg in enumerate(str(x) for x in z["models"]): + assert z["crps"][i, j] == rows[(wid, dg)]["crps"] + assert z["mase"][i, j] == rows[(wid, dg)]["mase"] + man = json.loads(s3.objects[pre + "public_manifest.json"]["body"]) + assert man["report_sha256"] == hashlib.sha256(st.path.read_bytes()).hexdigest() + assert man["boundary"] == B and man["boundary_block_hash"] == BH + assert man["draw_seeds"]["rmisc"] == f"{BH}:lane_d_public:rmisc" + assert man["data"]["gift_eval_pretrain"]["revision"] == "c0ffeegi" + assert man["files"]["public_windows.npz"]["sha256"] == hashlib.sha256( + s3.objects[pre + "public_windows.npz"]["body"]).hexdigest() + assert man["cut_key"] == "a" * 64 and man["windows"] == len(ids) + assert not (tmp_path / "host" / f"public-{B}").exists() # host stage cleaned + + +def test_published_at_report_time_not_retirement(tmp_path): + """The live half still waits (its window is not retired); the public half + goes out as soon as the signed report is in the bucket, not before.""" + m = pub() + st = setting(tmp_path) + rep = dict(st.report) + rep["windows"] = [{"window_id": f"tsforge__a~a.c0:{NOW}:h64", "origin": NOW, + "min_target_ts": NOW, "min_first_seen_ts": NOW + 1800, + "snapshot_sha256": "ff" * 32, "h": 64}] + st.path.write_text(json.dumps(rep)) + s3, host = FakeS3(), Host(st.cut_dir, tmp_path / "host") + + class NoRetired: + def build(self, req): + raise AssertionError("the retired build must wait") + + def __getattr__(self, name): + return getattr(host, name) + + def run(): + return m.publish_laned(client=s3, bucket="b", base_url=BASE, reports_dir=st.reports, + state={"entries": {}}, state_mtime=NOW, embargo_hours=48.0, + host=NoRetired(), stage=tmp_path / "stage", now=NOW, + log=lambda s: None) + + first = run() # the report is not published yet + assert first["public"]["unpublished"] == [B] and not host.requests + put_report(s3) + second = run() + assert second["public"]["built"] == [B] + assert [w["boundary"] for w in second["plan"]["waiting"]] == [B] # live half waits + assert f"{m.LANED_PREFIX}/{B}/manifest.json" not in s3.objects + assert f"{m.LANED_PREFIX}/{B}/public_windows.npz" in s3.objects + n = len(s3.puts) + third = run() + assert third["public"]["built"] == [] and len(host.requests) == 1 # never rebuilt + assert len(s3.puts) == n + + +OLD_ITEM_KEYS = ("boundary", "windows", "windows_sha256", "windows_bytes", "cut_ts", "built_ts", + "report_url", "manifest_url", "windows_url", "readme_url") + + +def old_reader(doc: dict) -> list[tuple]: + """The pre-2026-12-01 index reader: the schema, then every old key.""" + assert doc["schema"] == "lane-d-evals-index/1" + assert isinstance(doc["count"], int) and isinstance(doc["waiting"], list) + return [tuple(it[k] for k in OLD_ITEM_KEYS) for it in doc["items"]] + + +def test_index_gains_public_fields_and_old_readers_still_parse(tmp_path): + m = pub() + st = setting(tmp_path) + s3, host = FakeS3(), Host(st.cut_dir, tmp_path / "host") + put_report(s3) + # an older settlement whose retired set is out (and has no public half) + s3.objects[f"{m.LANED_PREFIX}/9603900/manifest.json"] = {"body": json.dumps( + {"windows": 3, "files": {"windows.npz": {"sha256": "ab" * 32, "bytes": 10}}, + "retired_rule": {"cut_ts": 5}, "built_ts": 6, "report_url": "r"}).encode()} + run_public(m, s3, st, host, tmp_path) + doc, wrote = m.laned_index(s3, "b", base_url=BASE, now=NOW, waiting=[], dry_run=False) + assert wrote + doc = json.loads(s3.objects[f"{m.LANED_PREFIX}/index.json"]["body"]) + rows = old_reader(json.loads(json.dumps(doc))) + assert [r[0] for r in rows] == [9603900, B] and doc["count"] == 2 + old, new = doc["items"] + assert old["windows_url"].endswith("/9603900/windows.npz") + assert "public_windows" not in old # optional: absent when none + assert new["windows_url"] is None and new["manifest_url"] is None # not retired yet + pre = f"{BASE}/{m.LANED_PREFIX}/{B}/" + assert new["public_windows"] == len(judged_ids(st.report)) + assert new["public_windows_url"] == pre + "public_windows.npz" + assert new["public_windows_sha256"] == hashlib.sha256( + s3.objects[f"{m.LANED_PREFIX}/{B}/public_windows.npz"]["body"]).hexdigest() + assert new["report_url"].endswith(f"lane_d_report_{B}.json") + # a public-only id never counts as a retired set (the retired pass rebuilds it) + assert m.published_ids(s3, "b", m.LANED_PREFIX) == ["9603900"] + + +def test_nothing_large_loaded_on_the_box(tmp_path, monkeypatch): + """The box sends ids + scores (no arrays), fetches to disk and reads only + the id / model / score-shape members; history and target never; no + torch / pyarrow; and a file out of the report's order is refused.""" + m = pub() + st = setting(tmp_path) + s3 = FakeS3() + put_report(s3) + opened: list[str] = [] + real_open = zipfile.ZipFile.open + + def spy(self, name, *a, **kw): + opened.append(str(getattr(name, "filename", name))) + return real_open(self, name, *a, **kw) + + class BoxHost(Host): + def build_public(self, request): + monkeypatch.setattr(zipfile.ZipFile, "open", real_open) # host side: free + try: + return super().build_public(request) + finally: + monkeypatch.setattr(zipfile.ZipFile, "open", spy) + + bh = BoxHost(st.cut_dir, tmp_path / "host") + monkeypatch.setattr(zipfile.ZipFile, "open", spy) + got = run_public(m, s3, st, bh, tmp_path) + monkeypatch.setattr(zipfile.ZipFile, "open", real_open) + assert got["built"] == [B] + assert opened and not {"history.npy", "target.npy"} & set(opened) + assert set(opened) <= {"window_id.npy", "models.npy", "crps.npy", "mase.npy"} + req = json.loads(bh.requests[0]) + assert "history" not in json.dumps(req) and len(bh.requests[0]) < 20_000 + assert "torch" not in sys.modules and "pyarrow" not in sys.modules + # a reordered file is refused on the box + bad = tmp_path / "bad.npz" + ids = [w["window_id"] for w in req["windows"]] + with zipfile.ZipFile(bad, "w") as zf: + for name, arr in (("window_id", np.asarray(ids[::-1])), + ("models", np.asarray([x["digest"] for x in req["models"]])), + ("crps", np.zeros((len(ids), 2))), ("mase", np.zeros((len(ids), 2)))): + with zf.open(name + ".npy", "w") as f: + np.lib.format.write_array(f, arr) + with pytest.raises(RuntimeError, match="public draw"): + m.verify_public_npz(bad, req) + + +def test_missing_cut_file_is_recorded_once_and_nothing_published(tmp_path): + m = pub() + st = setting(tmp_path, with_cut=False) + decoy(tmp_path) # another settlement's file never matches + s3, host = FakeS3(), Host(st.cut_dir, tmp_path / "host") + put_report(s3) + got = run_public(m, s3, st, host, tmp_path) + assert got["unavailable"] == [B] and got["built"] == [] + assert not [k for k in s3.objects if "/evals/" in k] + again = run_public(m, s3, st, host, tmp_path) + assert again["unavailable"] == [] and len(host.requests) == 1 + + +def test_report_without_public_rows_is_skipped(tmp_path): + m = pub() + st = setting(tmp_path) + rep = dict(st.report) + rep["public"] = {**rep["public"], "rows": []} + st.path.write_text(json.dumps(rep)) + s3, host = FakeS3(), Host(st.cut_dir, tmp_path / "host") + put_report(s3) + got = run_public(m, s3, st, host, tmp_path) + assert got["empty"] == [B] and not host.requests + + +def test_eval_host_exports_niced_from_the_inputs_cut_dir(tmp_path): + m = pub() + hosts = tmp_path / "hosts.toml" + hosts.write_text('[[host]]\nname = "laned-eval"\nhost = "1.2.3.4"\nport = 22\nuser = "root"\n' + 'remote_python = "/r/.venv/bin/python"\nworkdir = "/r"\n') + inputs = tmp_path / "in.toml" + inputs.write_text(f'eval_hosts = "{hosts}"\neval_host_name = "laned-eval"\n' + 'eval_pool_root = "/root/lane_d_pool_d/pool_d"\n' + 'eval_public_cache_dir = "/workspace/lane_d_public_cache"\n') + calls = [] + + def run(argv, **kw): + calls.append((argv, kw)) + if "stdout" in kw: + kw["stdout"].write(b"NPZ") + return SimpleNamespace(returncode=0, stdout=None, stderr=b"") + return SimpleNamespace(returncode=0, stdout=b'{"ok": true}\n', stderr=b"") + + h = m.EvalHost(inputs, run=run) + assert h.build_public({"boundary": 7}) == {"ok": True} + cmd = calls[0][0][-1] + for part in ("timeout", "nice -n 19", "ionice -c 3", "cascade.eval.lane_d_public_export", + "--cut-cache-dir /workspace/lane_d_public_cache/cut", + f"{m.HOST_STAGE}/public-7"): + assert part in cmd + h.fetch_public(7, tmp_path / "got.npz") + assert (tmp_path / "got.npz").read_bytes() == b"NPZ" + assert f"{m.HOST_STAGE}/public-7/public_windows.npz" in calls[1][0][-1]