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
11 changes: 10 additions & 1 deletion cascade/eval/lane_d_forecasts.py
Original file line number Diff line number Diff line change
Expand Up @@ -676,6 +676,11 @@ def _build_parser() -> argparse.ArgumentParser:
help="this host's B6 score cache (default: none)")
s.add_argument("--chain-toml", type=Path, default=None,
help="this host's chain.toml (the contract a cache miss ingests against)")
fl = sub.add_parser("floor", help="owner 2026-12-01: one settlement's floor pre-check "
"(pins, windows, frozen sets, cohort draw; no forecast) read as JSON "
"from stdin")
fl.add_argument("--pool-root", type=Path, required=True,
help="this host's copy of the pinned pool_d snapshots (<root>/<snapshot>/)")
w = sub.add_parser("warm-public", help="fill the public blob cache with whole source "
"mirrors ahead of a settlement (resumable)")
w.add_argument("--index", action="append", required=True, metavar="SOURCE=INDEX_SHA256",
Expand Down Expand Up @@ -767,7 +772,11 @@ def main(argv: list[str] | None = None) -> int:
print(refusal, file=sys.stderr)
return EXIT_MISSING_MODULES
try:
if args.cmd == "settle":
if args.cmd == "floor":
from .lane_d_settle import serve_floor

reply = serve_floor(sys.stdin.buffer.read(), pool_root=args.pool_root)
elif args.cmd == "settle":
from .lane_d_settle import LocalForecaster, serve_settle

score_cache = None
Expand Down
108 changes: 88 additions & 20 deletions cascade/eval/lane_d_settle.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,14 @@ def forecast(self, digest: str, *, context: int, horizon: int, windows):
grant=self.grants.get(digest), chain_toml=self.chain_toml)


def _check_pins(pins, what: str) -> None:
if not isinstance(pins, list) or not pins or not all(
isinstance(p, dict) and isinstance(p.get("sha256"), str)
and isinstance(p.get("snapshot"), str) and _SNAPSHOT_RE.fullmatch(p["snapshot"])
and ".." not in p["snapshot"] for p in pins):
raise ValueError(f"{what} request pins must be [{{snapshot, sha256}}] with plain names")


def _check_request(req) -> None:
from ..validator.lane_d_inputs import SETTLE_REQUEST_SCHEMA

Expand All @@ -89,12 +97,7 @@ def _check_request(req) -> None:
missing = [k for k in REQUEST_KEYS if k not in req]
if missing:
raise ValueError(f"settle request lacks {missing}")
pins = req["pins"]
if not isinstance(pins, list) or not pins or not all(
isinstance(p, dict) and isinstance(p.get("sha256"), str)
and isinstance(p.get("snapshot"), str) and _SNAPSHOT_RE.fullmatch(p["snapshot"])
and ".." not in p["snapshot"] for p in pins):
raise ValueError("settle request pins must be [{snapshot, sha256}] with plain names")
_check_pins(req["pins"], "settle")
need = req["need"]
if not isinstance(need, dict) or not all(
isinstance(k, str) and type(v) is int for k, v in need.items()):
Expand All @@ -103,20 +106,16 @@ def _check_request(req) -> None:
raise ValueError("settle request grants / pinned must be objects")


def settle_pool_phase(req: Mapping, *, pool_root, forecaster, score_cache=None
) -> tuple[dict, str | None, list[str], int]:
"""``(judged record, channel_block_hash, snapshot digests, windows)`` of
one settle request (module docstring). Raises
:class:`~cascade.validator.lane_d_inputs.LaneDInputsError` (typed, the
box re-raises it) or ``ValueError`` (a malformed request)."""
from ..validator.lane_d import _judge_pools, judge_phase_of, judged_record, load_pool_for
from ..validator.lane_d_inputs import LaneDInputsError, forecast_windows, pinned_windows
def _load_pins(pins: list[dict], pool_root, cfg) -> tuple[list[dict], list[dict]]:
"""``(snapshots in pin order, the settlement's pool order)``: every pin
loaded from ``<pool_root>/<snapshot>/`` once and hashed against its pin
(``pool_unavailable`` / ``pool_digest_mismatch``)."""
from ..validator.lane_d import load_pool_for
from ..validator.lane_d_inputs import LaneDInputsError

phase = judge_phase_of(req["judge"])
cfg = phase["cfg"]
loaded: dict[str, dict] = {}
seq: list[dict] = []
for pin in req["pins"]:
for pin in pins:
name = pin["snapshot"]
if name not in loaded:
d = Path(pool_root) / name
Expand All @@ -134,13 +133,27 @@ def settle_pool_phase(req: Mapping, *, pool_root, forecaster, score_cache=None
seq.append(loaded[name])
# The settlement's order (lane_d._load_pools): the distinct earlier
# snapshots oldest first, the newest last.
names = [p["snapshot"] for p in req["pins"]]
names = [p["snapshot"] for p in pins]
order, seen = [], {names[-1]}
for n in names[:-1]:
if n not in seen:
seen.add(n)
order.append(n)
judge_pools = [loaded[n] for n in order] + [loaded[names[-1]]]
return seq, [loaded[n] for n in order] + [loaded[names[-1]]]


def settle_pool_phase(req: Mapping, *, pool_root, forecaster, score_cache=None
) -> tuple[dict, str | None, list[str], int]:
"""``(judged record, channel_block_hash, snapshot digests, windows)`` of
one settle request (module docstring). Raises
:class:`~cascade.validator.lane_d_inputs.LaneDInputsError` (typed, the
box re-raises it) or ``ValueError`` (a malformed request)."""
from ..validator.lane_d import _judge_pools, judge_phase_of, judged_record
from ..validator.lane_d_inputs import LaneDInputsError, forecast_windows, pinned_windows

phase = judge_phase_of(req["judge"])
cfg = phase["cfg"]
seq, judge_pools = _load_pins(req["pins"], pool_root, cfg)

def block_hash_of() -> str:
if not req["block_hash"]:
Expand Down Expand Up @@ -187,4 +200,59 @@ def serve_settle(raw: bytes, *, pool_root, forecaster, score_cache=None) -> dict
"channel_block_hash": chb, "snapshots": shas, "windows": n}


__all__ = ["LocalForecaster", "serve_settle", "settle_pool_phase"]
def floor_plan_phase(req: Mapping, *, pool_root) -> tuple[dict, list[str]]:
"""``(forecast plan, snapshot digests)`` of one floor request (owner
2026-12-01): the pins loaded as for ``settle``, the windows cut by the
same function (only their ids are kept: the windows the settle request
would forecast) and :func:`~cascade.validator.lane_d.forecast_plan` run
over them. No forecast, no model, no grant."""
from ..validator.lane_d import forecast_plan, lane_d_config_from_record
from ..validator.lane_d_inputs import LaneDInputsError, pinned_windows

plan = req["plan"]
cfg = lane_d_config_from_record(plan["lane_d"])
seq, judge_pools = _load_pins(req["pins"], pool_root, cfg)

def block_hash_of() -> str:
if not req["block_hash"]:
raise LaneDInputsError("chain_unavailable", "the floor request has no block hash")
return str(req["block_hash"])

windows, _ = pinned_windows(seq, cfg, int(req["cap"]), block_hash_of,
bound_lo=req["bound_lo"])
got = forecast_plan(plan, judge_pools, cfg=cfg,
forecast_ids=[w["window_id"] for w in windows])
return got, [p["sha256"] for p in seq]


def serve_floor(raw: bytes, *, pool_root) -> dict:
"""Answer one floor request: the ``lane-d-floor-reply/1`` record (the
plan, or a typed refusal). ``ValueError`` on a malformed request."""
from ..validator.lane_d_inputs import (
FLOOR_REPLY_SCHEMA,
FLOOR_REQUEST_SCHEMA,
LaneDInputsError,
)

try:
req = json.loads(raw)
except (UnicodeDecodeError, json.JSONDecodeError) as e:
raise ValueError(f"malformed floor request ({e})") from e
if not isinstance(req, dict) or req.get("schema") != FLOOR_REQUEST_SCHEMA:
raise ValueError(f"not a {FLOOR_REQUEST_SCHEMA} request")
missing = [k for k in ("pins", "plan", "cap", "bound_lo", "block_hash") if k not in req]
if missing:
raise ValueError(f"floor request lacks {missing}")
_check_pins(req["pins"], "floor")
try:
got, shas = floor_plan_phase(req, pool_root=pool_root)
except LaneDInputsError as e:
log.warning("lane_d_floor_refused %s detail=%s", e.code, e)
return {"schema": FLOOR_REPLY_SCHEMA, "ok": False, "code": e.code, "detail": str(e)}
log.info("lane_d_floor_ok boundary=%s pins=%d duel=%d floored=%d",
req["plan"].get("boundary"), len(shas), len(got["duel"]), len(got["floored"]))
return {"schema": FLOOR_REPLY_SCHEMA, "ok": True, "plan": got, "snapshots": shas}


__all__ = ["LocalForecaster", "floor_plan_phase", "serve_floor", "serve_settle",
"settle_pool_phase"]
Loading
Loading