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
26 changes: 24 additions & 2 deletions cascade/validator/lane_d.py
Original file line number Diff line number Diff line change
Expand Up @@ -1188,6 +1188,8 @@ def _cohort_plan(jobs: list, *, king_ts_of, pools: list[dict], forecasts: dict,
own draw would have failed, the report unchanged."""
jobs = list(jobs)
advanced: set[str] = set()
# members whose frozen set reopened after a short draw (once each)
reopened: set[str] = set()
while jobs:
kd, stage, members, recs, is_house = jobs.pop(0)
members = list(members)
Expand Down Expand Up @@ -1265,6 +1267,25 @@ def cands_of(ms, recs, bars=bars, king_ts=king_ts):
members.append(nm)
eligible, refused, seen_c = cands_of(members, recs)
picked, drawn, ok = _drawn(eligible, cfg, block_hash, budget, seen_c)
if not ok and budget >= int(cfg.min_windows) \
and any(m not in reopened for m in members):
# A frozen set whose draw misses the floors (or the fresh share)
# would miss them at every settlement: it reopens now (its
# windows as its union, plus what the loaded pools admit, then
# the freeze test with this settlement's seed) and each member
# is redrawn once, alone, in reveal order. Not on a budget
# shortfall: that is this settlement's spend, not the set.
requeue = []
for m in members:
if m in reopened:
yield ("skip", m, "pending_floor", recs[m])
continue
reopened.add(m)
recs[m]["frozen_set"] = _advance_member(recs[m], pools, int(king_ts), cfg,
cap_seed, reopen=True)
requeue.append((kd, stage, [m], {**recs, m: recs[m]}, is_house))
jobs[:0] = requeue
continue
if not ok:
# The members share one candidate set, so each alone gets this
# same draw: every one waits, in reveal order.
Expand Down Expand Up @@ -1330,7 +1351,8 @@ def _subscore(scores, idx: list[int]) -> dict:
return {"n": len(idx), "geomean": math.sqrt(math.exp(lc) * math.exp(lm))}


def _advance_member(rec: dict, pools: list[dict], king_ts: int, cfg, seed: str) -> dict:
def _advance_member(rec: dict, pools: list[dict], king_ts: int, cfg, seed: str,
reopen: bool = False) -> dict:
"""Advance one entry's ``frozen_set`` against a king revealed at
``king_ts``. The record carries the bound it was built for
(``t_max = max(T_E, T_K)``): a not-yet-judged set built for another bound
Expand All @@ -1341,7 +1363,7 @@ def _advance_member(rec: dict, pools: list[dict], king_ts: int, cfg, seed: str)
if prog is not None and int(prog.get("t_max", -1)) != t_max:
prog = None
prog = advance_frozen_set(prog, pools, t_entry=int(rec["reveal_ts"]), t_king=int(king_ts),
cfg=cfg, seed=seed)
cfg=cfg, seed=seed, reopen=reopen)
prog["t_max"] = t_max
return prog

Expand Down
17 changes: 13 additions & 4 deletions cascade/validator/lane_d_frozen.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def fresh_feasible(window_ids: Iterable[str], embargo: Iterable[str], cfg) -> bo


def advance_frozen_set(progress, pools, *, t_entry: int, t_king: int, cfg, seed: str,
exclude=()) -> dict:
exclude=(), reopen: bool = False) -> dict:
"""One check of an entry's set (see the module docstring).

``progress`` is ``None`` (a new entry) or an earlier return value, possibly
Expand All @@ -142,8 +142,16 @@ def advance_frozen_set(progress, pools, *, t_entry: int, t_king: int, cfg, seed:
A window's class is its verdict in the earliest of ``pools`` admitting it
(the version the draw judges, ``lane_d._admitted_versions``), else the
class recorded when it joined; a window of a record written before the
key existed and absent from ``pools`` counts as fresh (as before)."""
frozen = progress is not None and bool(progress.get("frozen"))
key existed and absent from ``pools`` counts as fresh (as before).

``reopen``: the frozen set's W5j draw missed the floors or the fresh
share this settlement (``lane_d._cohort_plan``): it reopens as if
unfrozen, keeping its windows as its union, and the freeze test runs
again with ``seed``. On a reopen only ids some pool in ``pools`` admits
count toward the freeze floors (a union id no loaded snapshot admits
stays in the union but cannot be drawn, so it cannot carry the set over
the floors again)."""
frozen = progress is not None and bool(progress.get("frozen")) and not reopen
if frozen and float(getattr(cfg, "min_fresh_window_share", 0.0)) <= 0.0:
return copy.deepcopy(progress)
klass: dict[str, bool] = {}
Expand Down Expand Up @@ -173,7 +181,8 @@ def embargo_of(ids) -> list[str]:
sources = {str(k): str(v) for k, v in (progress.get("sources") or {}).items()
if str(k) not in skip}
sources.update({k: v for k, v in admitted.items() if k not in skip and k not in sources})
union = [{"window_id": k, "source": sources[k]} for k in sorted(sources)]
union = [{"window_id": k, "source": sources[k]} for k in sorted(sources)
if not reopen or k in admitted]
capped = cap_source_share(union, max_share=float(cfg.max_source_share), seed=str(seed))
ids = [w["window_id"] for w in capped]
emb = embargo_of(ids)
Expand Down
130 changes: 130 additions & 0 deletions tests/unit/test_lane_d_frozen_reopen.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
"""A frozen lane D set whose W5j draw misses the floors reopens and redraws
in the same settlement; union ids no loaded pool admits never count toward
the freeze floors. Pure python: the §1.3 verdicts and the draw are stubbed."""

from __future__ import annotations

import copy
from types import SimpleNamespace

import pytest

from cascade.validator import lane_d, lane_d_frozen
from cascade.validator.lane_d_frozen import advance_frozen_set


def _cfg(**kw):
base = dict(min_windows=4, min_clusters=1, max_source_share=1.0,
min_fresh_window_share=0.5, max_windows_per_settlement=100)
base.update(kw)
return SimpleNamespace(**base)


def _pool(name, ids, embargo=()):
return {"sha256": name, "windows": [
{"window_id": i, "source": "src", "_emb": i in embargo} for i in ids]}


@pytest.fixture(autouse=True)
def _verdicts(monkeypatch):
def fake(pool, *, t_entry, t_king, cfg):
for w in pool["windows"]:
yield SimpleNamespace(eligible=True, embargo_window=w["_emb"], reason=None)
monkeypatch.setattr(lane_d_frozen, "eligible_windows", fake)


def _frozen(ids, emb=()):
ids = sorted(ids)
out = {"frozen": True, "window_ids": ids, "sources": {i: "src" for i in ids},
"set_sha256": lane_d_frozen.set_sha256(ids), "seed": "old", "t_max": 10}
if emb:
out["embargo_ids"] = sorted(emb)
return out


def test_reopen_flag_grows_frozen_set():
cfg = _cfg()
prog = _frozen(["a", "b", "c", "d"])
pools = [_pool("p1", ["a", "b", "c", "d"]), _pool("p2", ["e", "f"])]
same = advance_frozen_set(prog, pools, t_entry=1, t_king=1, cfg=cfg, seed="s")
assert same == prog
out = advance_frozen_set(prog, pools, t_entry=1, t_king=1, cfg=cfg, seed="s", reopen=True)
assert out["frozen"] and out["seed"] == "s"
assert out["window_ids"] == ["a", "b", "c", "d", "e", "f"]


def test_absent_ids_do_not_count_to_floors_on_reopen():
cfg = _cfg(min_fresh_window_share=0.0)
# frozen on 4 ids, of which only "a" is admitted by a loaded pool
prog = _frozen(["a", "x1", "x2", "x3"])
out = advance_frozen_set(prog, [_pool("p", ["a"])], t_entry=1, t_king=1, cfg=cfg,
seed="s", reopen=True)
assert not out["frozen"]
assert out["window_ids"] == ["a", "x1", "x2", "x3"] # the union is kept
out = advance_frozen_set(out, [_pool("p", ["a", "b", "c", "d"])], t_entry=1, t_king=1,
cfg=cfg, seed="s", reopen=True)
assert out["frozen"] and out["window_ids"] == ["a", "b", "c", "d"]


def _plan(monkeypatch, pools, rec, cfg, drawable, windows_out=None):
"""Run ``_cohort_plan`` for one miner member; the draw passes iff the
member's frozen set holds ``drawable`` (a set of ids) entirely."""
def cohort_set(pools_, members, bars, king_ts, recs, *a, **k):
ids = set.intersection(*(set(recs[m]["frozen_set"]["window_ids"]) for m in members))
return [({"window_id": i, "source": "src"}, {"sha256": "p"}, None)
for i in sorted(ids)], {}
monkeypatch.setattr(lane_d, "_cohort_set", cohort_set)
monkeypatch.setattr(lane_d, "_seen_set", lambda *a, **k: [])
monkeypatch.setattr(lane_d, "_same_record", lambda c, *a, **k: c)
draws = []

def drawn(picked, cfg_, bh, budget, seen=()):
picked = picked[:max(0, int(budget))]
ids = {w["window_id"] for w, _, _ in picked}
draws.append(sorted(ids))
return picked, {"n": len(ids)}, drawable <= ids
monkeypatch.setattr(lane_d, "_drawn", drawn)
monkeypatch.setattr(lane_d, "_window_record", lambda w, *a, **k: {"id": w["window_id"]})
jobs = [("K", "first", ["m"], {"m": rec}, False)]
steps = list(lane_d._cohort_plan(
jobs, king_ts_of=lambda kd: 5, pools=pools, forecasts={"K": {}, "m": {}}, cfg=cfg,
picks={}, block_hash="h", cap_seed="seed2", pub_ready=lambda d: True, pinned={},
windows_out={} if windows_out is None else windows_out))
return steps, draws


def test_short_draw_reopens_and_passes_with_newer_pool(monkeypatch):
cfg = _cfg()
rec = {"reveal_ts": 10, "frozen_set": _frozen(["a", "b", "c", "d"])}
pools = [_pool("p1", ["a", "b", "c", "d"]), _pool("p2", ["e", "f", "g"])]
steps, draws = _plan(monkeypatch, pools, rec, cfg, drawable={"e", "f"})
assert [s[0] for s in steps] == ["cohort"]
assert len(draws) == 2 and draws[1] == ["a", "b", "c", "d", "e", "f", "g"]
fs = rec["frozen_set"]
assert fs["frozen"] and fs["seed"] == "seed2" and fs["t_max"] == 10


def test_short_draw_no_new_windows_stays_pending_deterministic(monkeypatch):
cfg = _cfg()
pools = [_pool("p1", ["a", "b", "c", "d"])]
outs = []
for _ in range(2):
rec = {"reveal_ts": 10, "frozen_set": _frozen(["a", "b", "c", "d"])}
steps, draws = _plan(monkeypatch, pools, rec, cfg, drawable={"zz"})
assert [(s[0], s[2]) for s in steps] == [("skip", "pending_floor")]
assert len(draws) == 2 # one redraw, no loop
outs.append(copy.deepcopy(rec["frozen_set"]))
assert outs[0] == outs[1]
assert outs[0]["frozen"] and outs[0]["seed"] == "seed2"


def test_budget_shortfall_does_not_reopen(monkeypatch):
cfg = _cfg()
prog = _frozen(["a", "b", "c", "d"])
rec = {"reveal_ts": 10, "frozen_set": copy.deepcopy(prog)}
pools = [_pool("p1", ["a", "b", "c", "d"]), _pool("p2", ["e"])]
# earlier cohorts spent 98 of the 100-window settlement budget
spent = {f"o{i:03d}": {} for i in range(98)}
steps, _ = _plan(monkeypatch, pools, rec, cfg, drawable={"d"}, windows_out=spent)
assert [(s[0], s[2]) for s in steps] == [("skip", "pending_floor")]
assert rec["frozen_set"]["window_ids"] == prog["window_ids"]
Loading