Skip to content
Merged
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
110 changes: 81 additions & 29 deletions cascade/eval/lane_d_forecasts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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"])
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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}
Expand Down Expand Up @@ -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: <public cache dir>/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")
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading