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
67 changes: 60 additions & 7 deletions cascade/validator/lane_d.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@
import copy
import hashlib
import json
import logging
import math
import os
from dataclasses import dataclass
Expand Down Expand Up @@ -224,6 +225,8 @@
state_digest,
)

_log = logging.getLogger("cascade.validator.lane_d")

POOL_SCHEMA = "pool_d/1"
CLOCKS_FILE = "clk.npz"
# W-IMG (plan rev6.24 (e)): the eval host code identity a settlement ran on
Expand Down Expand Up @@ -1126,6 +1129,49 @@ def _drawn(picked: list[tuple[dict, dict, object]], cfg, block_hash: str | None,
return ws, d, bool(d["meets_floors"])


def _drawn_in_budget(picked: list[tuple[dict, dict, object]], cfg, block_hash: str | None,
windows_out: dict, seen: list[tuple[dict, dict, object]] | tuple = ()
) -> tuple[list[tuple[dict, dict, object]], dict | None, bool, int, int]:
"""One cohort's draw (:func:`_drawn`) charged against
``max_windows_per_settlement`` only for its NEW windows (owner
2026-12-01, settlement 9630000: three frozen members waited
``pending_floor`` with 888 windows left of 5,000, though their sets
overlapped what earlier cohorts had judged). A window an earlier cohort
of this settlement judged (``windows_out``) costs nothing again: the
settlement's unique judged windows stay within the cap, which is what
every checker counts.

The draw itself is unchanged (same seed, same algorithm); only its size
budget is chosen: the full ``max_windows_per_settlement`` when its new
windows fit what is left, else the largest budget whose draw's new
windows fit, found by bisection between what is left (always fits: a
draw never exceeds its budget) and the full cap. Deterministic in the
candidates, the block hash and ``windows_out``.

Returns ``(judged, draw, meets floors, budget used, new windows the full
draw needs)``."""
cap = int(cfg.max_windows_per_settlement)
left = max(0, cap - len(windows_out))

def new(ws) -> int:
return sum(1 for w, _, _ in ws if w["window_id"] not in windows_out)

full = _drawn(picked, cfg, block_hash, cap, seen)
need = new(full[0])
if need <= left:
return (*full, cap, need)
lo, hi = left, cap
best = _drawn(picked, cfg, block_hash, lo, seen)
while hi - lo > 1:
mid = (lo + hi) // 2
got = _drawn(picked, cfg, block_hash, mid, seen)
if new(got[0]) <= left:
lo, best = mid, got
else:
hi = mid
return (*best, lo, need)


def _band_cand(w: dict, v) -> dict:
"""A band draw candidate (:func:`~cascade.validator.lane_d_draw.draw_band_windows`)."""
return {"window_id": w["window_id"], "series_id": str(w["series_id"]),
Expand Down Expand Up @@ -1177,8 +1223,9 @@ def _cohort_plan(jobs: list, *, king_ts_of, pools: list[dict], forecasts: dict,
from its own cut-off (``max(T_E, T_K)``), whatever any other member or an
earlier duel used; consecutive members whose candidate sets coincide
(record for record) share one cohort and one draw. The draws share
``max_windows_per_settlement``, earliest reveal first; a member whose
draw misses the floors waits ``pending_floor`` alone. Each cohort's
``max_windows_per_settlement``, earliest reveal first, each charged only
for windows no earlier cohort judged (:func:`_drawn_in_budget`); a member
whose draw misses the floors waits ``pending_floor`` alone. Each cohort's
picked windows enter ``pinned`` / ``windows_out`` before it is yielded
(a later cohort skips a window an earlier one judged under another
record: the report holds one per window).
Expand Down Expand Up @@ -1227,11 +1274,12 @@ def _cohort_plan(jobs: list, *, king_ts_of, pools: list[dict], forecasts: dict,
if not members:
continue
# W5j: the judged windows are the cohort's seeded per-bin draw over
# its eligible set, within what is left of the settlement's
# its eligible set; its NEW windows (not judged by an earlier cohort
# of this settlement) come out of what is left of the settlement's
# max_windows_per_settlement (earlier cohorts, i.e. earlier reveals,
# draw first); a draw below the floors (or short of the minimum fresh
# share, or out of budget) leaves the member pending.
budget = int(cfg.max_windows_per_settlement) - len(windows_out)
# draw first; owner 2026-12-01: a re-judged window costs nothing,
# :func:`_drawn_in_budget`); a draw below the floors (or short of the
# minimum fresh share, or out of budget) leaves the member pending.

def cands_of(ms, recs, bars=bars, king_ts=king_ts):
el, why = _cohort_set(pools, ms, bars, king_ts, recs, forecasts, cfg, pinned,
Expand Down Expand Up @@ -1264,7 +1312,12 @@ def cands_of(ms, recs, bars=bars, king_ts=king_ts):
recs = {**recs, nm: nrec}
members.append(nm)
eligible, refused, seen_c = cands_of(members, recs)
picked, drawn, ok = _drawn(eligible, cfg, block_hash, budget, seen_c)
picked, drawn, ok, used, need = _drawn_in_budget(eligible, cfg, block_hash,
windows_out, seen_c)
if not ok and used < int(cfg.max_windows_per_settlement):
left = max(0, int(cfg.max_windows_per_settlement) - len(windows_out))
for m in members:
_log.info("lane_d_budget_skip %s budget_left=%d need=%d", m, left, need)
if not ok:
# The members share one candidate set, so each alone gets this
# same draw: every one waits, in reveal order.
Expand Down
8 changes: 5 additions & 3 deletions docs/MINER_LANE_D.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,9 +266,11 @@ blocks, about 24 h) of `submit`, or the entry expires (`ready_expired`).
time T (and the king's, if the king is newer). A later entry never
shrinks your set, and an earlier entry that cannot meet the floors yet
never blocks yours. Entries are judged in reveal order, earliest first,
sharing the settlement's `max_windows_per_settlement` budget. If the
budget runs short of `min_windows`, the later entries wait
(`pending_floor`) for the next settlement. Only the cut-off decides
sharing the settlement's `max_windows_per_settlement` budget, which
counts each window once: a window an earlier entry was already judged on
this settlement costs a later entry nothing. If the new windows a later
entry's draw needs do not fit what is left, its draw shrinks to fit; below
`min_windows` it waits (`pending_floor`) for the next settlement. Only the cut-off decides
which windows you can be judged on: entries may share windows, and a
window you were judged on in an earlier duel (against any king) stays
eligible.
Expand Down
6 changes: 6 additions & 0 deletions tests/accept/w5c/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ behaviour is change 3, and those tests fail on main.
other member's T or frozen set shrinks it.
- The settlement's `max_windows_per_settlement` budget is shared across the
cohorts, earliest reveal first (a window judged in two cohorts counts once).
A cohort's draw is charged only for windows no earlier cohort of the
settlement judged (owner 2026-12-01, settlement 9630000): the draw keeps its
seed and algorithm; its size is the full cap when its new windows fit what is
left, else the largest size whose new windows fit (bisection). A member
skipped for budget stays `pending_floor` and the validator logs
`lane_d_budget_skip <digest> budget_left=N need=M`.
- A window an earlier cohort of the settlement judged under a different
`windows[]` record (another snapshot, or another fresh / embargo class at
that cohort's bound) is left out (one record per window, fail closed).
Expand Down
229 changes: 229 additions & 0 deletions tests/accept/w5c/test_w5c_budget_reuse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
"""A cohort's draw is charged against ``max_windows_per_settlement`` only for
windows no earlier cohort of the settlement judged (owner 2026-12-01).

Live case (settlement 9630000, 22:27 UTC): three members (5GHAPfhm,
5ELRsGeL, 5GhPUmHV) with frozen sets of 10-11k windows waited
``pending_floor``. The fresh share was not the cause (641 fresh windows of
5ELRsGeL allow a 3,205-window draw at 0.2): the three earlier cohorts had
judged 4,112 unique windows of 5,000, and the old rule charged a whole draw
against the 888 left, under ``min_windows`` 1,000 (``window_budget``), though
the later members' sets overlapped what had been judged.

Now a re-judged window costs nothing: the draw (same seed, same algorithm)
takes the full cap when its NEW windows fit what is left, else the largest
size whose new windows fit. The unique judged total stays within the cap,
which is what every released checker counts.
"""

from __future__ import annotations

import logging
import subprocess

import pytest

from tests.accept.w_hz.helpers import (
BAND_RAW,
BOUNDARY_1,
CHALLENGER_UID,
HASH_A,
HOUR,
LIVE_ONLY,
MINUTE,
REPO,
T0,
band_cfg,
band_series,
entry,
feeds_for,
fixture_key,
forecasts,
house,
old_tree,
run_old_checker,
settle,
write_band_pool,
)

from .helpers import BOUNDARY_1 as W5C_BOUNDARY
from .helpers import (
T_A,
T_B,
T_C,
band_start,
group,
lane_d_cfg,
model_forecasts,
read_state,
skipped_reasons,
uids,
wids,
write_pool,
)
from .helpers import entry as w5c_entry
from .helpers import house as w5c_house
from .helpers import settle as w5c_settle

# The released satellite checkers (satellites never update): the deployed
# validator release validator-release-laned-1201c and the live line.
RELEASED = ("86b3dba1", "890fe6d1")


def _bands():
return (group("bandA", 2, band_start(T_A)), group("bandB", 2, band_start(T_B)),
group("bandC", 6, band_start(T_C)))


def _run(tmp_path, records, members, *, skip=None, **over):
cfg = lane_d_cfg(**over)
h = w5c_house()
pool = write_pool(tmp_path / "pool", records, "w5c-budget")
skip = skip or {}
fc = {h["digest"]: model_forecasts(records, "bad", "house")}
for e in members:
fc[e["digest"]] = model_forecasts(records, "good", e["digest"],
skip=skip.get(e["digest"], ()))
path = tmp_path / "state" / "lane_d_state.json"
s = w5c_settle(cfg, W5C_BOUNDARY, pool, list(members), h, fc, uids(*members), path)
return s, path


def _cohort(report, e) -> dict | None:
got = [c for c in report["cohorts"] if e["digest"] in c["members"]]
assert len(got) <= 1
return got[0] if got else None


def test_later_members_are_judged_on_windows_an_earlier_cohort_judged(tmp_path):
"""max_windows_per_settlement 50: A (earliest) draws its 40 windows; B
(32) and C (24) need no new window, so both are judged (on the base 10
were left, under the 24-window floor, and both waited)."""
a_band, b_band, c_band = _bands()
A, B, C = (w5c_entry("alpha", reveal_ts=T_A), w5c_entry("bravo", reveal_ts=T_B),
w5c_entry("charlie", reveal_ts=T_C))
s, _ = _run(tmp_path, a_band + b_band + c_band, (A, B, C), max_windows_per_settlement=50)
assert [c["members"] for c in s.report["cohorts"]] == \
[[A["digest"]], [B["digest"]], [C["digest"]]], \
"a later member was starved by windows an earlier cohort already judged"
assert sorted(_cohort(s.report, B)["window_ids"]) == wids(b_band + c_band)
assert sorted(_cohort(s.report, C)["window_ids"]) == wids(c_band)
assert len({w["window_id"] for w in s.report["windows"]}) <= 50
assert s.report["skipped"] == []


def _a_without_half_of_band_c():
a_band, b_band, c_band = _bands()
A, C = w5c_entry("alpha", reveal_ts=T_A), w5c_entry("charlie", reveal_ts=T_C)
# A has no forecast on 12 of band C (3 per source): A is judged on 28
# windows; C's 24 hold 12 A did not judge
return a_band + b_band + c_band, A, C, wids(c_band[:12]), c_band


def test_only_new_windows_are_charged(tmp_path):
"""Cap 40: A judges 28, 12 are left; C needs 12 new windows (its other 12
A judged), so C is judged on all 24 (on the base C's whole draw was
charged against the 12 left, under the floor)."""
records, A, C, gone, c_band = _a_without_half_of_band_c()
s, _ = _run(tmp_path, records, (A, C), skip={A["digest"]: gone},
max_windows_per_settlement=40)
assert len(_cohort(s.report, A)["window_ids"]) == 28
cc = _cohort(s.report, C)
assert cc is not None, "the re-judged windows were charged against the budget"
assert sorted(cc["window_ids"]) == wids(c_band)
assert len({w["window_id"] for w in s.report["windows"]}) == 40


def test_below_the_floor_after_reuse_still_waits_and_is_logged(tmp_path, caplog):
"""Cap 30: A judges 28, 2 are left; C needs 12 new windows, and a draw
with at most 2 new ones is under the 24-window floor: C waits
``pending_floor`` (the existing reason) and the validator logs the
budget skip."""
records, A, C, gone, _ = _a_without_half_of_band_c()
with caplog.at_level(logging.INFO, logger="cascade.validator.lane_d"):
s, path = _run(tmp_path, records, (A, C), skip={A["digest"]: gone},
max_windows_per_settlement=30)
assert _cohort(s.report, C) is None
assert skipped_reasons(s.report, C["digest"]) == ["pending_floor"]
assert read_state(path)["entries"][C["digest"]]["reason"] == "pending_floor"
assert len({w["window_id"] for w in s.report["windows"]}) <= 30
msgs = [r.getMessage() for r in caplog.records]
assert f"lane_d_budget_skip {C['digest']} budget_left=2 need=12" in msgs, msgs


def test_the_draw_shrinks_to_fit_the_new_windows_left():
"""The draw size is the largest whose new windows fit what is left:
30 of 30 cap spent on 20 windows the cohort shares plus 10 others, so
the cohort's draw keeps only re-judged windows (20)."""
import cascade.validator.lane_d as lane_d

fn = getattr(lane_d, "_drawn_in_budget", None)
assert fn is not None, "no draw charged for new windows only"
cfg = lane_d_cfg(max_windows_per_settlement=30, min_windows=8, min_clusters=4)
cands = [({"window_id": f"w{i:02d}", "source": f"s{i % 4}"}, {}, None) for i in range(40)]
out = {f"w{i:02d}": {} for i in range(20)} | {f"x{i}": {} for i in range(10)}
ws, _, ok, used, need = fn(cands, cfg, None, out)
assert [w["window_id"] for w, _, _ in ws] == [f"w{i:02d}" for i in range(20)]
assert ok and used == 20 and need == 10


# ── six members: the old rule starved the last three ────────────────────────

SHARE, EMBARGO = 0.2, 48.0
OVER = {"min_fresh_window_share": SHARE, "embargo_hours": EMBARGO,
"max_windows_per_settlement": 150, "min_windows": 56}


def _fleet(tag, start, n):
return [band_series(f"{tag}-s{i % 4}-{i}", f"src{i % 4}", freq="min", step=MINUTE,
region=736, start=start + i * 7, bound=start) for i in range(n)]


def _six_member_report(tmp_path):
"""Six members 4 h apart, each with a small fleet of its own after its T
and a common fleet after the last T. Each member draws ~64 windows,
mostly shared: 147 unique of 382 judged. Under the old rule (cap 150,
floor 56) the fourth member's draw got 55 and the last three waited."""
from cascade.validator.lane_d import load_pool_for

cfg = band_cfg(**OVER)
ts = [T0 + i * 4 * HOUR for i in range(6)]
es = [entry(f"six{i}", reveal_ts=t) for i, t in enumerate(ts)]
h = house()
fl = [s for i, t in enumerate(ts) for s in _fleet(f"own{i}", t + HOUR, 4)]
fl += _fleet("common", ts[-1] + HOUR, 40)
d = write_band_pool(tmp_path / "pool", fl, feeds=feeds_for(fl, EMBARGO), snapshot="six")
p = load_pool_for(d, cfg)
fc = forecasts([p], [e["digest"] for e in es], h["digest"])
out = settle(cfg, BOUNDARY_1, d, es, h, fc,
{e["hotkey"]: CHALLENGER_UID + i for i, e in enumerate(es)},
tmp_path / "state.json", HASH_A)
return out.report, es


def test_six_members_all_judged_within_the_cap(tmp_path):
rep, es = _six_member_report(tmp_path)
assert [c["members"] for c in rep["cohorts"]] == [[e["digest"]] for e in es], \
"the later members were starved by re-judged windows"
assert rep["skipped"] == []
assert len({w["window_id"] for w in rep["windows"]}) <= OVER["max_windows_per_settlement"]
for c in rep["cohorts"]:
n = len(c["window_ids"])
assert n >= OVER["min_windows"]
assert c["fresh_windows"] >= SHARE * n


@pytest.mark.parametrize("release", RELEASED)
def test_the_released_checkers_pay_the_six_member_report(tmp_path, release):
"""Zero burns and zero findings from both released satellite checkers."""
rep, _ = _six_member_report(tmp_path)
assert len(rep["cohorts"]) == 6, "the old rule starved the last three members"
got = subprocess.run(["git", "-C", str(REPO), "cat-file", "-e", f"{release}^{{commit}}"],
capture_output=True, text=True)
assert got.returncode == 0, f"release {release} is not in this clone: {got.stderr}"
tree = old_tree(tmp_path, release)
raw = {**BAND_RAW, **LIVE_ONLY, **OVER}
res = run_old_checker(tree, rep, raw, fixture_key("signer").ss58_address, tmp_path)
assert res["transient"] == "", res
assert res["burn"] is None, res
assert res["findings"] == [], res
assert res["n_cohorts"] == 6 and res["n_rows"] == len(rep["rows"])
18 changes: 3 additions & 15 deletions tests/accept/w5c/test_w5c_own_t.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,21 +170,9 @@ def test_cohorts_follow_reveal_order_not_digest_or_input_order(tmp_path):
assert [r["cohort"] for r in s.report["rows"]] == sorted(r["cohort"] for r in s.report["rows"])


def test_the_window_budget_is_shared_across_cohorts_earliest_reveal_first(tmp_path):
"""max_windows_per_settlement 50: A (earliest) draws its 40 windows; 10
are left, under the 24-window floor, so B and C wait ``pending_floor``
(on the base the joint cohort {A, B, C} was judged on band C)."""
a_band, b_band, c_band = _bands()
A, B, C = _people()
s, path, _ = _run(tmp_path, a_band + b_band + c_band, (A, B, C),
max_windows_per_settlement=50)
assert [c["members"] for c in s.report["cohorts"]] == [[A["digest"]]], \
"the budget was not spent earliest reveal first"
assert len({w["window_id"] for w in s.report["windows"]}) <= 50
state = read_state(path)
for e in (B, C):
assert skipped_reasons(s.report, e["digest"]) == ["pending_floor"]
assert state["entries"][e["digest"]]["used_windows"] == []
# The shared max_windows_per_settlement budget (earliest reveal first, each
# cohort charged only for windows no earlier cohort judged; owner 2026-12-01)
# is pinned in test_w5c_budget_reuse.py.


# ── windows are never spent: the cut-off alone decides (owner 2026-12-01) ──
Expand Down
Loading