Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
322 changes: 322 additions & 0 deletions cascade/eval/lane_d_public_export.py
Original file line number Diff line number Diff line change
@@ -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 dir>/<key>.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 ``<mirror cache_dir>/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 ``<out_dir>/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: <mirror cache_dir>/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"]
Loading
Loading