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
28 changes: 26 additions & 2 deletions cascade/validator/lane_d.py
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,30 @@ def _keeps_hold(rec: dict, state: dict) -> bool:
return True


def held_gate_digests(state: dict, cfg, boundary: int) -> list[str]:
"""Owner 2026-12-01 (timing only): the digests a settlement at
``boundary`` would re-gate as held (:func:`_held_candidates` and the held
house entry), read from ``state`` WITHOUT changing it. The box uses it
to start their bench sweep ahead of the scoring phase
(:meth:`~cascade.validator.lane_d_bench.SweepSession.prefetch`); the
settlement still decides its candidates itself, so a digest named here
and not gated costs a sweep, never a different record."""
if _closing(cfg, boundary):
return []
king = state["king"]["digest"]

def held(rec) -> bool:
hold = rec.get("gate_hold") if isinstance(rec, dict) else None
return (rec["status"] in OPEN_STATUSES and bool(hold)
and hold["king_d"] == king)

out = [dg for dg, rec in sorted(state["entries"].items()) if held(rec)]
house_rec = state.get(HOUSE_ENTRY_KEY) if state["king"].get("house") else None
if house_rec is not None and held(house_rec):
out.append(str(state["house"]["digest"]))
return out


def _ranked(cands: list[dict]) -> list[dict]:
"""Max-T order: highest LCB first, then the earlier reveal, then digest."""
return sorted(cands, key=lambda c: (-c["lcb"], c["reveal_ts"], c["digest"]))
Expand Down Expand Up @@ -2382,5 +2406,5 @@ def absent_settlement(*, cfg, boundary: int, state_path, house: dict, reason: st
receipt=receipt)


__all__ = ["LaneDSettlement", "absent_settlement", "judge_cohort", "load_pool",
"settle_lane_d", "window_id"]
__all__ = ["LaneDSettlement", "absent_settlement", "held_gate_digests", "judge_cohort",
"load_pool", "settle_lane_d", "window_id"]
108 changes: 92 additions & 16 deletions cascade/validator/lane_d_bench.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,12 @@

:class:`SweepSession` wraps the bench host's sweep: every digest a session
has not swept yet goes out in one deduplicated host call, and cached rows are
re-used only within that session.
re-used only within that session. :meth:`SweepSession.prefetch` (owner
2026-12-01, timing only) sweeps digests known at the start of a settlement
(the held gate candidates, KING_D, the house) ahead of the gate; the gate's
:meth:`SweepSession.paired` adopts a prefetched digest only when its suites
and effective context are exactly those the gate asks for, so the records
the gate decides on are the ones a sequential sweep returns.

Pure apart from the injected host sweep: no process-local state (no
``hash()``), so every validator computes the same JSON. Wiring into
Expand All @@ -35,6 +40,7 @@

import copy
import math
import threading
from collections.abc import Callable, Iterable, Mapping, MutableMapping
from typing import Any

Expand Down Expand Up @@ -503,6 +509,11 @@ def __init__(self, session_id: str, sweep: Sweep,
self._sweep = sweep
store = {} if cache is None else cache
self._rows: dict[str, dict[str, Any]] = store.setdefault(session_id, {})
# One host sweep at a time per session: the gate's ``paired`` waits for
# a running ``prefetch`` (one sidecar on the bench host).
self._lock = threading.Lock()
# {digest: (context, suites, {suite: entry})}: prefetched, not adopted yet
self._ahead: dict[str, tuple[int, tuple[str, ...], dict[str, Any]]] = {}

@staticmethod
def _suites(suites: Iterable[str]) -> tuple[str, ...]:
Expand All @@ -518,6 +529,69 @@ def _suites(suites: Iterable[str]) -> tuple[str, ...]:
raise ValueError("at least one suite is required")
return tuple(out)

def prefetch(self, digests: Iterable[str], suites: Iterable[str], *,
contexts: Mapping[str, int]) -> tuple[str, ...]:
"""Owner 2026-12-01 (timing only): sweep ``digests`` for ``suites`` in
one host call at the contexts given, ahead of :meth:`paired`. Nothing
is decided here: the rows are held aside and :meth:`paired` adopts a
digest's rows only when the suites it asks for are exactly
``suites`` (same order) and the host's settlement context for the
digest (``sweep.context_of``) equals the context swept here;
otherwise the gate sweeps that digest itself, as without a prefetch.
A reply missing any digest or suite, or naming another suite, keeps
nothing. Raises on any failure (the caller falls back to the
sequential sweep). Returns the digests held aside."""
wanted = self._suites(suites)
if isinstance(digests, (str, bytes)):
raise TypeError(f"digests must be a sequence of digests; got {digests!r}")
ds: list[str] = []
for dg in digests:
if not isinstance(dg, str) or not dg:
raise ValueError(f"digest {dg!r} is not a non-empty str")
if dg not in ds:
ds.append(dg)
if not ds:
return ()
if not callable(getattr(self._sweep, "context_of", None)):
raise TypeError("prefetch needs a host sweep with context_of (the settlement's "
"contexts the gate sweeps at)")
ctx = {dg: int(contexts[dg]) for dg in ds}
with self._lock:
got = self._sweep(tuple(ds), wanted, contexts=dict(ctx))
if not isinstance(got, Mapping):
raise TypeError(f"host sweep returned {type(got).__name__}, not a mapping")
kept: dict[str, tuple[int, tuple[str, ...], dict[str, Any]]] = {}
for dg in ds:
per = got.get(dg)
if (not isinstance(per, Mapping) or set(per) != set(wanted)
or not all(isinstance(e, Mapping) for e in per.values())):
raise ValueError(f"prefetch reply for {dg[:16]} does not carry exactly "
f"{list(wanted)}")
kept[dg] = (ctx[dg], wanted,
{s: copy.deepcopy(dict(e)) for s, e in per.items()})
self._ahead.update(kept)
return tuple(ds)

def _adopt(self, order: list[str], wanted: tuple[str, ...]) -> None:
"""Move each prefetched digest of ``order`` into this session's rows
when it was swept for exactly ``wanted`` at the host's settlement
context; a prefetched digest that does not match is dropped (the
caller sweeps it). Called under ``_lock``."""
if not self._ahead:
return
context_of = getattr(self._sweep, "context_of", None)
for dg in order:
ahead = self._ahead.pop(dg, None)
if ahead is None or dg in self._rows:
continue
ctx, suites, rows = ahead
try:
now = context_of(dg) if callable(context_of) else None
except Exception: # noqa: BLE001 — no context: the gate sweeps it itself
now = None
if suites == wanted and now is not None and int(now) == ctx:
self._rows[dg] = rows

def _record(self, dg: str) -> dict:
return {"session": self.session_id, "digest": dg,
"suites": copy.deepcopy(self._rows.get(dg, {}))}
Expand All @@ -534,21 +608,23 @@ def paired(self, candidate: str, king_d: str, house: str, *,
raise ValueError(f"{name} digest must be a non-empty str; got {dg!r}")
if dg not in order:
order.append(dg)
todo = [dg for dg in order
if not all(s in self._rows.get(dg, {}) for s in wanted)]
if todo:
got = self._sweep(tuple(todo), wanted)
if not isinstance(got, Mapping):
raise TypeError(f"host sweep returned {type(got).__name__}, not a mapping")
for dg in todo:
per = got.get(dg)
if not isinstance(per, Mapping):
continue
slot = self._rows.setdefault(dg, {})
for s, entry in per.items():
if isinstance(s, str) and isinstance(entry, Mapping):
slot[s] = copy.deepcopy(dict(entry))
return self._record(candidate), self._record(king_d), self._record(house)
with self._lock:
self._adopt(order, wanted)
todo = [dg for dg in order
if not all(s in self._rows.get(dg, {}) for s in wanted)]
if todo:
got = self._sweep(tuple(todo), wanted)
if not isinstance(got, Mapping):
raise TypeError(f"host sweep returned {type(got).__name__}, not a mapping")
for dg in todo:
per = got.get(dg)
if not isinstance(per, Mapping):
continue
slot = self._rows.setdefault(dg, {})
for s, entry in per.items():
if isinstance(s, str) and isinstance(entry, Mapping):
slot[s] = copy.deepcopy(dict(entry))
return self._record(candidate), self._record(king_d), self._record(house)


__all__ = ["CLASSES", "FAULT_CODES", "HOLD_CODES", "INFRA_CODES", "KNOWN_SUITES", "METRICS",
Expand Down
7 changes: 5 additions & 2 deletions cascade/validator/lane_d_bench_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,12 @@ def _aggregates(reply: dict, digests: list[str]) -> dict:
if isinstance(s, str) and isinstance(a, dict)}
for dg, per in raw.items() if dg in digests and isinstance(per, dict)}

def __call__(self, digests, suites) -> dict:
def __call__(self, digests, suites, *, contexts: Mapping[str, int] | None = None) -> dict:
"""The gate's sweep. ``contexts`` overrides the settlement's map (the
held-candidate prefetch, swept before the settlement sets it; owner
2026-12-01); the rows are the same call's either way."""
ds = [str(d) for d in digests]
return self._checked(self._sweep(ds, [str(s) for s in suites]), ds)
return self._checked(self._sweep(ds, [str(s) for s in suites], contexts=contexts), ds)

def sweep_full(self, digests, suites, *, contexts: Mapping[str, int] | None = None,
timeout_s: float | None = None) -> dict:
Expand Down
45 changes: 45 additions & 0 deletions cascade/validator/lane_d_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,51 @@ def bench(self, boundary: int):

return SweepSession(f"{BENCH_SESSION_PREFIX}/{int(boundary)}", self._bench_host)

def gate_prefetch(self, boundary: int) -> dict | None:
"""Owner 2026-12-01 (timing only): what the box may sweep on the bench
host while the eval host scores, ``{"digests": (held..., KING_D, the
house), "contexts": {digest: effective context}}``: the gate's held
candidates (:func:`~cascade.validator.lane_d.held_gate_digests`)
with the references every gate sweep pairs them with, at the
contexts :meth:`_needed` gives this settlement (the map ``__call__``
hands the bench host). ``None`` with no bench host, lane D inactive,
the boundary already settled, no held candidate, or any read failing
(the gate then sweeps as before). Reads only; never raises."""
if self._bench_host is None:
return None
b = int(boundary)
try:
if self._cfg_at is not None:
self.cfg = self._cfg_at(b) # what ``__call__`` sets for ``b``
if not self.cfg.lane_d.active(b):
return None
house = self._house()
state = self._state(house)
if int(state["boundary"]) >= b:
return None
from .lane_d import held_gate_digests

held = held_gate_digests(state, self.cfg.lane_d, b)
if not held:
return None
entries = self._entries(self._reader(), b)
armed = self._armed()
need, _ = self._needed(entries, state, house, tuple(armed["armed_contexts"]))
refs = [str(state["king"]["digest"]), str(state["house"]["digest"])]
if any(r not in need for r in refs):
return None
digests: list[str] = []
for dg in [d for d in held if d in need] + refs:
if dg not in digests:
digests.append(dg)
if not any(d in need for d in held):
return None
return {"digests": tuple(digests), "contexts": {d: int(need[d]) for d in digests}}
except Exception as e: # noqa: BLE001 — timing only: the gate sweeps as before
log.info("lane_d_gate_prefetch settlement %d: no plan (%s: %s)", b,
type(e).__name__, e)
return None

# ── the reads, in order ─────────────────────────────────────────────────

def _reader(self) -> Any:
Expand Down
Loading
Loading