diff --git a/cascade/shared/config/lane_b.py b/cascade/shared/config/lane_b.py index cfa3ea08f..60928dbff 100644 --- a/cascade/shared/config/lane_b.py +++ b/cascade/shared/config/lane_b.py @@ -60,6 +60,11 @@ # a suite slot clears. "tau_anchor_public": 0.0, "tau_anchor_domain": 0.0, + # owner 2026-12-01 (TRAINER-ONLY, release-only): lane B funded legs' OWN + # worker image, decoupled from lane A's seed-epoch pins. Both or neither; + # "" = the epoch image (today's behaviour, byte for byte). + "pod_image": "", + "worker_code_fingerprint": "", } # Lane B EMA, no cooldown (plan rev6.20, owner 2026-11-24: "let's just do EMA, @@ -223,6 +228,29 @@ def _skus(v: object) -> tuple[str, ...]: return tuple(v) +def _pod_pins(lb: dict) -> dict[str, str]: + """``[lane_b] pod_image`` / ``worker_code_fingerprint`` (owner 2026-12-01, + trainer-only): a digest-pinned ``:@sha256:<64 hex>`` ref and its + 64-hex worker code fingerprint (``scripts/worker_code_fingerprint.py``), + both or neither. No validator reads them (lane B entries record the image a + leg ran; they never enforce it).""" + image = lb.get("pod_image", LANE_B_TRACK_DEFAULTS["pod_image"]) + fp = lb.get("worker_code_fingerprint", LANE_B_TRACK_DEFAULTS["worker_code_fingerprint"]) + for key, v in (("pod_image", image), ("worker_code_fingerprint", fp)): + if not isinstance(v, str): + raise ValueError(f"[lane_b] {key} must be a string; got {v!r}") + image, fp = image.strip(), fp.strip().lower() + if bool(image) != bool(fp): + raise ValueError("[lane_b] pod_image and worker_code_fingerprint are set together " + "(both or neither)") + if image and not re.fullmatch(r"[^\s@]+:[^\s@/]+@sha256:[0-9a-f]{64}", image): + raise ValueError(f"[lane_b] pod_image must be pinned by digest " + f"(':@sha256:<64 hex>'); got {image!r}") + if fp and not re.fullmatch(r"[0-9a-f]{64}", fp): + raise ValueError(f"[lane_b] worker_code_fingerprint must be 64 hex; got {fp!r}") + return {"pod_image": image, "worker_code_fingerprint": fp} + + def parse_lane_b_track(lb: dict, *, round_funded_pod_skus: tuple[str, ...] | None = None, generator_max_repo_mb: int | None = None) -> dict[str, object]: @@ -277,6 +305,7 @@ def parse_lane_b_track(lb: dict, *, "tau_anchor_domain": _float("tau_anchor_domain", lb.get("tau_anchor_domain", d["tau_anchor_domain"])), "contamination_hashset_key": _hashset_key(lb.get("contamination_hashset_key", "")), + **_pod_pins(lb), } from ..rules_menu import parse_lane_menu diff --git a/cascade/shared/config/v2.py b/cascade/shared/config/v2.py index f630f143e..790a8dde0 100644 --- a/cascade/shared/config/v2.py +++ b/cascade/shared/config/v2.py @@ -823,6 +823,14 @@ def leg_caps_at(self, block: int | None) -> tuple[float, int]: # clears): the anchor-king guard tolerances tau_anchor_public: float = 0.0 tau_anchor_domain: float = 0.0 + # owner 2026-12-01 (TRAINER-ONLY, release-only; no validator reads them): + # lane B funded legs' own worker image, a ":@sha256:<64 hex>" + # ref with its worker code fingerprint, both or neither. Set, every lane + # B funded leg rents, code-checks and declares this image (its leg + # contract's runtime pin) while lane A / king / lane C / MarketCast legs + # keep their pins (cascade.trainer.leg_pins); "" = the epoch image. + pod_image: str = "" + worker_code_fingerprint: str = "" def active(self, block: int | None) -> bool: return (self.from_block > 0 and block is not None and int(block) >= self.from_block diff --git a/cascade/shared/netconfig_bounds.py b/cascade/shared/netconfig_bounds.py index cd9ef8d7a..930ec184a 100644 --- a/cascade/shared/netconfig_bounds.py +++ b/cascade/shared/netconfig_bounds.py @@ -261,6 +261,9 @@ def _hours(hi: float) -> Bound: ("lane_d", "max_horizon"): "the per-window horizon rule is release-only", ("lane_d", "band_slots"): "the per-window horizon rule is release-only", ("lane_d", "min_cell_windows"): "the per-window horizon rule is release-only", + # owner 2026-12-01: lane B's own worker image is a trainer-local pin + ("lane_b", "pod_image"): "a worker image pin is release-only", + ("lane_b", "worker_code_fingerprint"): "a worker image pin is release-only", } # Eval DATA keys (owner 2026-11-24: what data a lane is judged on is diff --git a/cascade/trainer/lane_b_driver.py b/cascade/trainer/lane_b_driver.py index 4523f13be..9c585a4de 100644 --- a/cascade/trainer/lane_b_driver.py +++ b/cascade/trainer/lane_b_driver.py @@ -2448,6 +2448,15 @@ def done(leg, ptr, *a, failure=None, **kw): # noqa: F811 — the re-attach v outer(leg, ptr, *a, failure=failure, **kw) def _run(): + # owner 2026-12-01: this thread's leg is a lane B funded leg — with + # [lane_b] pod_image set it rents / code-checks / declares that + # image (leg_pins.leg_round, the dispatch hook); unset = no-op + from .leg_pins import lane_b_leg_scope + + with lane_b_leg_scope(self.r): + return _run_leg() + + def _run_leg(): if reattach is None: return _body() if not self.leg_pod_ledgered(leg): @@ -2508,6 +2517,11 @@ def _body(): contract = lane_b_leg_contract(contract) contract = apply_spec_levers(self.r.cfg.lane_b, contract, spec, int(block)) + # owner 2026-12-01: [lane_b] pod_image set ⇒ the leg declares + # (and its pod runs) lane B's own image; unset ⇒ same object + from .leg_pins import lane_b_leg_contract_image + + contract = lane_b_leg_contract_image(self.r.cfg, contract) # 2026-11-30: a leg contract the pinned model cannot build fails # on the pod every time; refuse it here, before generation and # any rent (operator side: never charged, never burned) diff --git a/cascade/trainer/leg_pins.py b/cascade/trainer/leg_pins.py index cfc3a0a83..e11f3c635 100644 --- a/cascade/trainer/leg_pins.py +++ b/cascade/trainer/leg_pins.py @@ -21,6 +21,13 @@ A MarketCast leg (:func:`mkt_leg_scope`) with ``[marketcast] pod_image`` set rents and code-checks on that image instead — lane A never sees it. + +A lane B funded leg (:func:`lane_b_leg_scope`) with ``[lane_b] pod_image`` set +(owner 2026-12-01) rents, code-checks and DECLARES that image: its leg contract +carries the image as its runtime pin (:func:`lane_b_leg_contract_image`) and +the pod gets a deployed chain.toml whose every image pin is it +(:func:`render_lane_b_toml`), so the worker's FINAL image check and the receipt +digest agree. Lane A's seed-epoch image, contract and W-IMG pins never move. """ from __future__ import annotations @@ -83,6 +90,11 @@ def leg_round(runner): is ever rented on an unqualified image (and never on the old one for a post-switch leg).""" cfg = runner.cfg + if lane_b_own_image_leg(runner): + # owner 2026-12-01: a lane B leg on its own release ([lane_b] + # pod_image) — checked by its own pin (digest ref + code fingerprint), + # never refused for differing from the [v2] *_after release + return _lane_b_round(cfg) mc = getattr(cfg, "marketcast", None) if getattr(_local(runner), "mkt_leg", False) and getattr(mc, "pod_image", ""): # a MarketCast leg on its own release ([marketcast] pod_image): the SKU @@ -109,6 +121,8 @@ def leg_round_view(runner): pins, without the qualification refusal (no log, never raises for it — the rent itself still goes through :func:`leg_round`).""" cfg = runner.cfg + if lane_b_own_image_leg(runner): + return _lane_b_round(cfg) mc = getattr(cfg, "marketcast", None) if getattr(_local(runner), "mkt_leg", False) and getattr(mc, "pod_image", ""): return _mkt_round(cfg, mc) @@ -214,6 +228,72 @@ def mkt_leg_scope(runner): loc.mkt_leg = saved +# ── lane B's own worker image (owner 2026-12-01) ──────────────────────────── + + +def lane_b_image(cfg) -> str: + """The bare ``sha256:<64 hex>`` of ``[lane_b] pod_image``, or "" (unset: + lane B legs run the epoch image, exactly as before).""" + lb = getattr(cfg, "lane_b", None) + ref = str(getattr(lb, "pod_image", "") or "") + fp = str(getattr(lb, "worker_code_fingerprint", "") or "") + return image_digest(ref) if ref and fp else "" + + +def lane_b_own_image_leg(runner) -> bool: + """Whether the leg on this thread is a lane B funded leg + (:func:`lane_b_leg_scope`) AND ``[lane_b] pod_image`` is set.""" + return bool(getattr(_local(runner), "lane_b_leg", False) and lane_b_image(runner.cfg)) + + +def contract_runs_lane_b_image(cfg, contract) -> bool: + """Whether ``contract`` (a leg's contract) declares ``[lane_b] pod_image`` + — only a lane B leg's contract does (:func:`lane_b_leg_contract_image`).""" + img = lane_b_image(cfg) + return bool(img and contract is not None + and image_digest(str(getattr(contract, "train_image_digest", "") or "")) == img) + + +def lane_b_leg_contract_image(cfg, contract): + """A lane B leg's contract with ``[lane_b] pod_image`` as its runtime pin + (``train_image_digest``, a DEC-CA-0067 runtime-only field: the numerics + digest is unchanged), or ``contract`` itself (same object) when unset. + The pod's worker refuses FINAL unless the contract's image IS the image it + runs (``contract.assert_train_image``), so the leg must declare it; no + validator checks a lane B leg's contract or image (expert entries record + ``train_image_digest`` and never enforce it).""" + img = lane_b_image(cfg) + if not img: + return contract + from dataclasses import replace + + return replace(contract, train_image_digest=img) + + +def _lane_b_round(cfg): + from dataclasses import replace + + lb = cfg.lane_b + # the [round] SKU-wall gate is unchanged: it still names the image the + # walls were measured on (an unmeasured image rents under the cap) + return replace(cfg.round, funded_pod_image=str(lb.pod_image), + worker_code_fingerprint=str(lb.worker_code_fingerprint).lower()) + + +@contextlib.contextmanager +def lane_b_leg_scope(runner): + """Mark the leg on this thread as a lane B funded leg for + :func:`leg_round` and the dispatch hook (its ``[lane_b] pod_image`` pins, + when set).""" + loc = runner.__dict__.setdefault("_leg_local_obj", threading.local()) + saved = getattr(loc, "lane_b_leg", False) + loc.lane_b_leg = True + try: + yield + finally: + loc.lane_b_leg = saved + + @contextlib.contextmanager def leg_contract_scope(runner, contract): """Name the leg's contract for :func:`leg_round` on this thread (paths that @@ -335,6 +415,67 @@ def render_after_toml(text: str, cfg) -> str: return out +LANE_B_TOML_NAME = "chain.deployed.laneb.toml" + + +def render_lane_b_toml(text: str, cfg) -> str: + """The deployed chain.toml a lane B own-image leg's worker loads: every + image pin it resolves IS ``[lane_b] pod_image`` — ``[v2.training] + train_image_digest``, ``[round] funded_pod_image`` / + ``worker_code_fingerprint`` (+ ``ops_continuation_image_digest`` when + continuation is armed: the worker refuses a continuation root on any + other image) and, while a ``[v2] *_after`` release is configured, the + three ``*_after`` pins — so ``training.at_block(b).train_image_digest`` is + the lane B image at every block (the contract the trainer expects, + :func:`lane_b_leg_contract_image`). Nothing else changes. Verified by + re-parsing.""" + lb = cfg.lane_b + img = lane_b_image(cfg) + if not img: + raise ValueError("[lane_b] pod_image is not set") + raw = tomllib.loads(text) + fp = str(lb.worker_code_fingerprint).lower() + want: dict[tuple, object] = {("v2", "training", "train_image_digest"): img} + out = _set_keys(text, "v2.training", {"train_image_digest": img}) + round_vals = {"funded_pod_image": str(lb.pod_image), "worker_code_fingerprint": fp} + if str(raw.get("round", {}).get("ops_continuation_image_digest", "") or ""): + round_vals["ops_continuation_image_digest"] = img + out = _set_keys(out, "round", round_vals) + want.update({("round", k): v for k, v in round_vals.items()}) + if str(raw.get("v2", {}).get("train_image_digest_after", "") or "").strip(): + v2_vals = {"train_image_digest_after": img, + "funded_pod_image_after": str(lb.pod_image), + "worker_code_fingerprint_after": fp} + out = _set_keys(out, "v2", v2_vals) + want.update({("v2", k): v for k, v in v2_vals.items()}) + parsed = tomllib.loads(out) + for path, value in want.items(): + node = parsed + for part in path: + node = node.get(part, {}) if isinstance(node, dict) else {} + if node != value: + raise ValueError(f"rendered lane B chain.toml: {'.'.join(path)} = {node!r}, " + f"expected {value!r}") + return out + + +def _push_lane_b_toml(runner, host): + from dataclasses import replace as dc_replace + + from ..shared.atomic import write_text_atomic + + src = getattr(runner, "deployed_chain_toml", None) + if not src: + raise LegImageMismatch("lane B own-image leg needs the trainer's deployed_chain_toml " + "(--chain-toml) to render its lane B config") + text = render_lane_b_toml(Path(src).read_text(encoding="utf-8"), runner.cfg) + local = Path(getattr(runner, "work_root", ".")) / "_deployed" / LANE_B_TOML_NAME + local.parent.mkdir(parents=True, exist_ok=True) + write_text_atomic(local, text) + pushed = runner._push_deployed_chain_toml(host, src=local, dest_name=LANE_B_TOML_NAME) + return dc_replace(pushed, chain_toml=f"{host.workdir}/{LANE_B_TOML_NAME}") + + def _push_after_toml(runner, host): from dataclasses import replace as dc_replace @@ -484,11 +625,15 @@ def __init__(self, runner, fingerprint_fn, image_fn=None, clock=None): def filters(self, block) -> bool: cfg = self.runner.cfg + if lane_b_own_image_leg(self.runner): + return True # owner 2026-12-01: lane B's own image, any era return bool(image_after_armed(cfg) and block is not None and image_decoupled_era(cfg, int(block))) def _want(self, block) -> tuple[str, str]: cfg = self.runner.cfg + if lane_b_own_image_leg(self.runner): + return str(cfg.lane_b.worker_code_fingerprint).lower(), lane_b_image(cfg) fp = str(round_pins_at(cfg, int(block)).worker_code_fingerprint or "").lower() img = image_digest(str(cfg.training.at_block(int(block)).train_image_digest or "")) return fp, img @@ -504,8 +649,9 @@ def _observe(self, host, *, fresh: bool) -> tuple[str, str]: def require_qualified(self, block) -> None: """Raise :class:`ImageAfterUnqualified` for a post-switch leg whose - after release is not qualified (before any lane is taken).""" - if self.filters(block): + after release is not qualified (before any lane is taken). A lane B + own-image leg is checked by its own pin only.""" + if self.filters(block) and not lane_b_own_image_leg(self.runner): require_after_qualified(self.runner.cfg, f"dispatch (contract block {int(block)})") def match_state(self, host, block): @@ -555,6 +701,8 @@ def __call__(self, host, block): f"{getattr(host, 'name', host)} reports runtime image " f"{got[1][:19] or ''} but this leg's era (start {block}) pins " f"{want_img[:19]} — its worker would refuse FINAL; not dispatched here") + if lane_b_own_image_leg(self.runner): + return _push_lane_b_toml(self.runner, host) return _push_after_toml(self.runner, host) diff --git a/cascade/trainer/runner_funded_legs.py b/cascade/trainer/runner_funded_legs.py index 2eff48712..fc2eb9706 100644 --- a/cascade/trainer/runner_funded_legs.py +++ b/cascade/trainer/runner_funded_legs.py @@ -354,12 +354,17 @@ def _run_funded_leg_scoped(self, disp, gen, seeds, block, contract, suffix, *, ImageRetryCapped, after_image_refusal, contract_runs_after, + contract_runs_lane_b_image, image_retry_exhausted, leg_key, ) key = leg_key(gen.hotkey, role, getattr(seeds, "base_seed", "")) - if contract_runs_after(self.cfg, contract) and image_retry_exhausted(self, key): + # owner 2026-12-01: a lane B own-image leg gets the same never-the- + # wrong-image protections (never the after-release qualification) + pinned_release = (contract_runs_after(self.cfg, contract) + or contract_runs_lane_b_image(self.cfg, contract)) + if pinned_release and image_retry_exhausted(self, key): # owner rule: never the wrong image — and a miner is never billed # over and over for OUR image skew: the leg WAITS (unburned, # no_capacity, requeued), it is not dropped @@ -637,9 +642,11 @@ def release_pod() -> None: rc = getattr(e, "returncode", None) text = str(e) from .leg_pins import contract_runs_after as _runs_after + from .leg_pins import contract_runs_lane_b_image as _runs_lane_b from .leg_pins import worker_refused_image - if worker_refused_image(e) and _runs_after(self.cfg, contract): + if worker_refused_image(e) and (_runs_after(self.cfg, contract) + or _runs_lane_b(self.cfg, contract)): # A post-switch leg's worker refused FINAL (exit 2 + its own # stdout sentinel, before any corpus streaming or training). # Released (finally below), unburned, billing unchanged, diff --git a/cascade/trainer/runner_funded_pods.py b/cascade/trainer/runner_funded_pods.py index 7dddd459c..08c9232c5 100644 --- a/cascade/trainer/runner_funded_pods.py +++ b/cascade/trainer/runner_funded_pods.py @@ -1909,12 +1909,15 @@ def on_allocated(machine_id, pod_id, *, allocated=allocated, from .leg_pins import ( WRONG_IMAGE_BAD_SECONDS, contract_runs_after, + contract_runs_lane_b_image, leg_contract, ) if (why and not blocked and result.machine_id and why.startswith(STALE_CODE_PREFIX) - and contract_runs_after(self.cfg, leg_contract(self))): + and (contract_runs_after(self.cfg, leg_contract(self)) + or contract_runs_lane_b_image(self.cfg, + leg_contract(self)))): # owner rule 2026-11-02 (never the wrong image), post- # switch legs only: the pod's code was MEASURED as # another release — the executor and its learned diff --git a/cascade/trainer/runner_rolling.py b/cascade/trainer/runner_rolling.py index 05f03a0f8..f0099d4a3 100644 --- a/cascade/trainer/runner_rolling.py +++ b/cascade/trainer/runner_rolling.py @@ -206,12 +206,14 @@ def _dispatcher(self): ) def _leg_pins_hook(self) -> dict: - """DEC-CA-0067: the per-leg image hook, only while a repin is armed.""" + """DEC-CA-0067: the per-leg image hook, only while a repin is armed + (or, owner 2026-12-01, ``[lane_b] pod_image`` is set: lane B's own + image needs its own code check + rendered config at dispatch).""" from ..shared.era import image_after_armed + from .leg_pins import dispatch_host_hook, lane_b_image - if not image_after_armed(self.cfg): + if not image_after_armed(self.cfg) and not lane_b_image(self.cfg): return {} - from .leg_pins import dispatch_host_hook return {"host_hook": dispatch_host_hook(self)} diff --git a/chain.testnet.toml b/chain.testnet.toml index 6cfcf482f..149243488 100644 --- a/chain.testnet.toml +++ b/chain.testnet.toml @@ -822,6 +822,11 @@ max_leg_seconds = 4500 # TESTNET-FAST (2026-11-24): 54000 (1 h x 1.2 guard_factor = 1.25 tau_anchor_public = 0.0 tau_anchor_domain = 0.0 +# Owner 2026-12-01 (trainer-only, release-only): lane B funded legs' own +# worker image + its code fingerprint, both or neither; absent = the epoch +# image. See chain.toml [lane_b] pod_image for the full rule. +# pod_image = "" +# worker_code_fingerprint = "" [lane_c] diff --git a/chain.toml b/chain.toml index 1dec18028..c88380533 100644 --- a/chain.toml +++ b/chain.toml @@ -1494,6 +1494,23 @@ guard_factor = 1.25 # worse than the anchor king (the era's promotion member) at these tolerances. tau_anchor_public = 0.0 tau_anchor_domain = 0.0 +# Owner 2026-12-01 (TRAINER-ONLY, release-only — never an overlay; no +# validator reads them): lane B funded legs' OWN worker image, decoupled from +# lane A's seed-epoch pins. Both or neither; absent/"" = lane B runs the +# epoch image (today's behaviour, byte for byte). +# pod_image = ":@sha256:<64 hex>" +# worker_code_fingerprint = "<64 hex>" # scripts/worker_code_fingerprint.py +# Set, ONLY lane B funded legs (never lane A / king / lane C / MarketCast / +# bench) rent this image, pass the pod code-fingerprint check on this +# fingerprint, declare it as their leg contract's runtime pin +# (train_image_digest; the numerics digest is unchanged) and get a pushed +# chain.deployed.laneb.toml whose image pins (incl. [v2] *_after and an armed +# ops_continuation_image_digest) all name it. Checked by its own pin, never by +# the [v2] *_after qualification. Lane B's WB19 step-rate table stays keyed +# on the epoch image. Flip only with no lane B leg in flight (a re-attached +# leg re-derives its contract with the current pins). +# pod_image = "" +# worker_code_fingerprint = "" [lane_c] diff --git a/docs/MINER.md b/docs/MINER.md index 395ba82f9..420825ff4 100644 --- a/docs/MINER.md +++ b/docs/MINER.md @@ -1479,6 +1479,11 @@ before upload or commitment; do not construct the chain payload by hand. [Lane A funding](#choosing-your-gpu-dec-ca-0060). The configured B budget is `[lane_b] leg_hours`; it is not an extra budget for each declared target. +Operator image keys (trainer-only, not overlay-settable): +- `[lane_b] pod_image = ""`: the worker image funded lane B legs rent. +- `[lane_b] worker_code_fingerprint = ""`: the code fingerprint those pods must have. +Both set or both empty; empty keeps lane B on the seed epoch's image. + A hotkey holds one chain commitment. Committing B replaces its A/C commitment and can supersede queued work. Each revealed B commitment funds one leg; re-funding a spent commitment returns `spent`. To make a new attempt, commit diff --git a/tests/accept/w_img/PATHS b/tests/accept/w_img/PATHS index 41eb9ec83..5e26e9d4b 100644 --- a/tests/accept/w_img/PATHS +++ b/tests/accept/w_img/PATHS @@ -86,3 +86,18 @@ deploy/qualify/worker_image_job.toml tests/unit/test_image_qualification.py tests/unit/test_marketcast_pod_image.py tests/unit/test_worker_config_push.py +# Owner 2026-12-01 ("a code change so it uses a different image"): lane B +# funded legs' OWN worker image, decoupled from the seed-epoch pins — +# [lane_b] pod_image + worker_code_fingerprint (trainer-only, release-only: +# never an overlay), the lane B leg scope / pins / declared contract image / +# rendered pod config (leg_pins), the dispatch-hook install, the +# never-the-wrong-image protections, the shipped-config docs and the tests. +cascade/shared/config/lane_b.py +cascade/shared/netconfig_bounds.py +cascade/trainer/runner_funded_legs.py +cascade/trainer/runner_rolling.py +chain.toml +chain.testnet.toml +tests/unit/test_lane_b_pod_image.py +docs/MINER.md +tests/unit/test_stage_pods_gate_on_their_own_pins.py diff --git a/tests/unit/test_lane_b_pod_image.py b/tests/unit/test_lane_b_pod_image.py new file mode 100644 index 000000000..ed00c8a8a --- /dev/null +++ b/tests/unit/test_lane_b_pod_image.py @@ -0,0 +1,259 @@ +"""Owner 2026-12-01: lane B funded legs run their OWN worker image +(``[lane_b] pod_image`` + ``worker_code_fingerprint``, trainer-only), decoupled +from lane A's seed-epoch pins. Unset = the epoch image, byte-identical. + +Torch-free: config loading, the leg pins, the dispatch hook and the lane B +driver with ``_run_funded_leg`` stubbed.""" +from __future__ import annotations + +import dataclasses +import re +import threading +import tomllib +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from cascade.shared.config import load_chain_config +from cascade.shared.manifest import contract_digest, numerics_contract_digest +from cascade.trainer.leg_pins import dispatch_host_hook, leg_round, mkt_leg_scope + +REPO = Path(__file__).resolve().parents[2] +LB = "sha256:ab45ef5f3e509f27a83898729f50e0f9b6720b021e37a8d171f8d007769fa3be" +LB_REF = "ghcr.io/tensorlink-ai/cascade-worker:worker-v2.1.0-rc5ctx-a555d1a5@" + LB +LB_FP = "acaa23f67f615e1063607d832c01dcf1b1721a38ebc0834c1de2eaeca481e919" +GEN = "alice/metro-gen@sha256:" + "a" * 64 + + +def _toml(tmp_path, keys: dict, src: Path | None = None, name="chain.toml") -> Path: + text = (src or REPO / "chain.toml").read_text() + lines = "".join(f"{k} = {v!r}\n".replace("'", '"') for k, v in keys.items()) + text, n = re.subn(r"(?m)^\[lane_b\]\n", "[lane_b]\n" + lines, text, count=1) + assert n == 1 + p = tmp_path / name + p.write_text(text) + return p + + +def _lane_b(tmp_path, **keys): + return load_chain_config(_toml(tmp_path, keys)).lane_b + + +# ── the knobs: loader parse, round trip, validation ───────────────────────── + + +def test_loader_parses_and_round_trips_the_pins(tmp_path): + lb = _lane_b(tmp_path, pod_image=LB_REF, worker_code_fingerprint=LB_FP.upper()) + assert getattr(lb, "pod_image", None) == LB_REF + assert getattr(lb, "worker_code_fingerprint", None) == LB_FP # lower-cased + + +def test_shipped_files_and_absent_keys_are_empty(tmp_path): + for path in ("chain.toml", "chain.testnet.toml"): + lb = load_chain_config(REPO / path).lane_b + assert (getattr(lb, "pod_image", None), + getattr(lb, "worker_code_fingerprint", None)) == ("", "") + lb = _lane_b(tmp_path, pod_image="", worker_code_fingerprint="") + assert (getattr(lb, "pod_image", None), getattr(lb, "worker_code_fingerprint", None)) == ( + "", "") + + +@pytest.mark.parametrize("keys, why", [ + ({"pod_image": LB_REF}, "both or neither"), + ({"worker_code_fingerprint": LB_FP}, "both or neither"), + ({"pod_image": "ghcr.io/x/y:tag", "worker_code_fingerprint": LB_FP}, "digest"), + ({"pod_image": LB, "worker_code_fingerprint": LB_FP}, "digest"), # no repo:tag + ({"pod_image": LB_REF[:-1], "worker_code_fingerprint": LB_FP}, "digest"), + ({"pod_image": LB_REF, "worker_code_fingerprint": "abc"}, "64 hex"), + ({"pod_image": LB_REF, "worker_code_fingerprint": "g" * 64}, "64 hex"), +]) +def test_loader_refuses_half_or_malformed_pins(tmp_path, keys, why): + with pytest.raises(ValueError, match=why): + _lane_b(tmp_path, **keys) + + +def test_an_overlay_can_never_set_the_pins(): + from cascade.shared.netconfig_bounds import key_refusals + + for key in ("pod_image", "worker_code_fingerprint"): + assert key_refusals({"lane_b": {key: "x"}}), key + + +# ── the lane B driver: launch spec, contract, hook, record ────────────────── + + +def _dispatch(cfg, tmp_path, monkeypatch, lane_b): + """One lane B funded leg through ``RunnerLaneBOps._dispatch_funded`` with + ``_run_funded_leg`` stubbed: returns what the leg saw on its thread.""" + from cascade.trainer.expert_lane import LaneBSubmission, OpenLeg + from cascade.trainer.lane_b_driver import RunnerLaneBOps + from cascade.trainer.loop import TrainerRunner + from cascade.trainer.remote import RemoteHost + + deployed = tmp_path / "deployed.toml" + deployed.write_text((REPO / "chain.toml").read_text()) + r = TrainerRunner(cfg=cfg, base_trainer=object(), work_root=tmp_path, trainer_spec="m:C", + deployed_chain_toml=deployed) + era = SimpleNamespace(base_seed=12345, start_block=7200, index=3) + r.cfg = dataclasses.replace(cfg, lane_b=lane_b, + round=dataclasses.replace(cfg.round, funded_mode="required")) + r.__dict__["_rolling_sched"] = SimpleNamespace(state=SimpleNamespace(current=era)) + monkeypatch.setattr(TrainerRunner, "_dispatcher", lambda self: object()) + pushed = [] + + def push(host, *, src=None, dest_name="chain.deployed.toml"): + pushed.append((dest_name, Path(src).read_text() if src else "")) + return dataclasses.replace(host, chain_toml=f"{host.workdir}/{dest_name}") + + r._push_deployed_chain_toml = push + seen = {} + + def run(self, disp, gen, seeds, block, contract, suffix, **kw): + rnd = leg_round(self) + seen["round_is_cfg"] = rnd is self.cfg.round + seen["pins"] = (rnd.funded_pod_image, rnd.worker_code_fingerprint) + seen["contract"] = contract + host = RemoteHost(name="pod", host="10.0.0.1", workdir="/w", + chain_toml="/w/chain.deployed.toml") + hook = dispatch_host_hook(self, fingerprint_fn=lambda h, fresh=False: LB_FP, + image_fn=lambda h, fresh=False: LB) + seen["host"] = hook(host, 7200) + seen["hook_installed"] = "host_hook" in self._leg_pins_hook() + return SimpleNamespace(trained_pointer="ptr", corpus_digest="cd", train_block=block, + gpu_name="L40S") + + monkeypatch.setattr(TrainerRunner, "_run_funded_leg", run) + import cascade.funding.lane_b_gpus as lbg + + monkeypatch.setattr(lbg, "lane_b_gpus_from_env", + lambda cfg, **kw: lbg.lane_b_gpus(cfg, None)) + ops = RunnerLaneBOps(r, client=None, window_source=None) + leg = OpenLeg(sub=LaneBSubmission("alice", 7, GEN, "energy", 5), + selection={0: [1, 2]}, base_king_ref="kingref", base_era=3, + funding={"entry_ref": "x", "gpu": "H100", "gpu_allow_fallback": True}) + ev, out = threading.Event(), {} + + def done(leg, ptr, *a, failure=None, **kw): + out.update(ptr=ptr, failure=failure, kw=kw) + ev.set() + + ops.dispatch_leg(leg, 3, 7300, done) + assert ev.wait(10) + assert out["failure"] is None and out["ptr"] == "ptr", out + base = r.cfg.throne_contracts_at(7200)[0] + return r, seen, out, pushed, base + + +def test_lane_b_leg_rents_checks_and_declares_its_own_image(cfg, tmp_path, monkeypatch): + lb = _lane_b(tmp_path, pod_image=LB_REF, worker_code_fingerprint=LB_FP) + r, seen, out, pushed, base = _dispatch(cfg, tmp_path, monkeypatch, lb) + # the rent + pod code check read these pins (leg_round) + assert seen["pins"] == (LB_REF, LB_FP) + # the leg declares its image (the pod's FINAL check needs it); numerics + # (everything validators could compare) unchanged + c = seen["contract"] + assert c.train_image_digest == LB + assert numerics_contract_digest(c) == numerics_contract_digest( + dataclasses.replace(c, train_image_digest=base.train_image_digest)) + # the dispatch hook is installed, code-checks on the lane B pins and + # pushes the lane B config whose image pins all name it + assert seen["hook_installed"] + assert seen["host"].chain_toml.endswith("chain.deployed.laneb.toml") + raw = tomllib.loads(pushed[-1][1]) + assert raw["v2"]["training"]["train_image_digest"] == LB + assert (raw["round"]["funded_pod_image"], raw["round"]["worker_code_fingerprint"]) == ( + LB_REF, LB_FP) + # the expert entry records the image the leg ran + assert out["kw"]["train_image_digest"] == LB + # lane A / king (no lane B scope) and lane C / MarketCast keep the round pins + assert leg_round(r) is r.cfg.round + from cascade.trainer.leg_pins import leg_round_view + + with mkt_leg_scope(r): # the planning view (no qualification read) + assert leg_round_view(r).funded_pod_image != LB_REF + assert r.cfg.throne_contracts_at(7200)[0].train_image_digest == base.train_image_digest + assert base.train_image_digest != LB + + +def test_empty_keys_are_todays_lane_b_leg(cfg, tmp_path, monkeypatch): + lb = _lane_b(tmp_path) + r, seen, out, pushed, base = _dispatch(cfg, tmp_path, monkeypatch, lb) + assert seen["round_is_cfg"] # same object + assert seen["contract"].train_image_digest == base.train_image_digest + assert not seen["hook_installed"] and seen["host"].chain_toml == "/w/chain.deployed.toml" + assert pushed == [] + + +def test_hook_refuses_a_lane_b_pod_on_another_release(cfg, tmp_path): + from cascade.trainer.leg_pins import LegImageMismatch, lane_b_leg_scope + from cascade.trainer.remote import RemoteHost + + lb = _lane_b(tmp_path, pod_image=LB_REF, worker_code_fingerprint=LB_FP) + runner = SimpleNamespace(cfg=dataclasses.replace(cfg, lane_b=lb)) + host = RemoteHost(name="pod", host="10.0.0.1", workdir="/w") + epoch_fp = "a0f85c287745c02cbb326393037a8a436c04f110c49d41553829e0ea925edcbc" + hook = dispatch_host_hook(runner, fingerprint_fn=lambda h, fresh=False: epoch_fp, + image_fn=lambda h, fresh=False: LB) + assert hook(host, 7200) is host # not a lane B leg: untouched + with lane_b_leg_scope(runner), pytest.raises(LegImageMismatch, match="worker code"): + hook(host, 7200) + hook = dispatch_host_hook(runner, fingerprint_fn=lambda h, fresh=False: LB_FP, + image_fn=lambda h, fresh=False: "sha256:" + "0" * 64) + with lane_b_leg_scope(runner), pytest.raises(LegImageMismatch, match="runtime image"): + hook(host, 7200) + + +def test_lane_b_image_is_never_refused_by_the_after_qualification(cfg, tmp_path, monkeypatch): + from cascade.trainer.leg_pins import lane_b_leg_scope + + monkeypatch.setattr("cascade.trainer.leg_pins.after_image_refusal", + lambda cfg: "not qualified") + monkeypatch.setattr("cascade.trainer.leg_pins.contract_runs_after", lambda cfg, c: True) + lb = _lane_b(tmp_path, pod_image=LB_REF, worker_code_fingerprint=LB_FP) + runner = SimpleNamespace(cfg=dataclasses.replace(cfg, lane_b=lb)) + with lane_b_leg_scope(runner): + rnd = leg_round(runner) + assert (rnd.funded_pod_image, rnd.worker_code_fingerprint) == (LB_REF, LB_FP) + + +# ── the worker resolves the contract the trainer expects ──────────────────── + + +def test_rendered_config_makes_the_worker_derive_the_trainers_contract(tmp_path): + """With a ``[v2] *_after`` release armed (as deployed), the pod's config + resolves the lane B image at every block, and its contract digest is the + trainer's lane B leg contract digest.""" + from cascade.trainer.leg_pins import lane_b_leg_contract_image, render_lane_b_toml + from tests.unit.test_image_after_repin import AFTER, WALL16, _with + + src = _with(tmp_path, **AFTER, funded_sku_wall_measured_image_after=WALL16) + deployed = _toml(tmp_path, {"pod_image": LB_REF, "worker_code_fingerprint": LB_FP}, + src=src, name="deployed.toml") + tcfg = load_chain_config(deployed) + text = deployed.read_text() + out = render_lane_b_toml(text, tcfg) + assert out.count("\n") == text.count("\n") # in place, nothing else + raw = tomllib.loads(out) + assert raw["v2"]["train_image_digest_after"] == LB + assert raw["v2"]["funded_pod_image_after"] == LB_REF + assert raw["v2"]["worker_code_fingerprint_after"] == LB_FP + assert raw["v2"]["training"]["base_lr"] == tomllib.loads(text)["v2"]["training"]["base_lr"] + p = tmp_path / "pod.toml" + p.write_text(out) + wcfg = load_chain_config(p) + v2b = int(tcfg.training.v2_from_block or 0) + for blk in (v2b, v2b + 36_000, v2b + 3_600_000): + want = lane_b_leg_contract_image(tcfg, tcfg.training.at_block(blk)) + got = wcfg.training.at_block(blk) + assert got.train_image_digest == LB + assert contract_digest(got) == contract_digest(want) + assert numerics_contract_digest(got) == numerics_contract_digest( + tcfg.training.at_block(blk)) + + +def test_unset_contract_is_the_same_object(cfg): + from cascade.trainer.leg_pins import lane_b_leg_contract_image + + c = cfg.training.at_block(0) + assert lane_b_leg_contract_image(cfg, c) is c diff --git a/tests/unit/test_stage_pods_gate_on_their_own_pins.py b/tests/unit/test_stage_pods_gate_on_their_own_pins.py index 65cf0f077..a944c636e 100644 --- a/tests/unit/test_stage_pods_gate_on_their_own_pins.py +++ b/tests/unit/test_stage_pods_gate_on_their_own_pins.py @@ -22,6 +22,11 @@ # config dataclass with its own pod image -> (chain.toml section, provisioner stage) STAGE_OF = {"MarketCastConfig": ("marketcast", "mkt")} +# config dataclass with its own pod image whose pods the TRAINER rents (no +# provisioner stage boots them) -> the trainer-side gate that checks the pod +# against that section's own pin (2026-12-01: [lane_b] pod_image, funded lane +# B legs; leg_pins.lane_b_image + the lane B code-fingerprint check) +TRAINER_RENTED = {"LaneBConfig": ("cascade.trainer.leg_pins", "lane_b_image")} FLEET_DIGEST = "sha256:" + "1" * 64 STAGE_DIGEST = "sha256:" + "2" * 64 @@ -42,7 +47,7 @@ def own_pod_image_sections() -> set[str]: def test_every_own_image_section_has_a_gate_stage(): found = own_pod_image_sections() assert "MarketCastConfig" in found, found - missing = found - set(STAGE_OF) + missing = found - set(STAGE_OF) - set(TRAINER_RENTED) assert not missing, (f"config sections pin their own pod image but no provisioner stage gates " f"on it (add it to stage_gate_pins and STAGE_OF): {sorted(missing)}") @@ -59,3 +64,11 @@ def test_each_stage_gates_on_its_own_image_not_the_fleets(): worker_code_fingerprint="e" * 64)) pins = stage_gate_pins(cfg) assert pins.get(stage) == (STAGE_DIGEST, "e" * 64), (cls, pins) + + +def test_trainer_rented_sections_have_their_own_gate(): + import importlib + + for cls, (module, fn) in TRAINER_RENTED.items(): + mod = importlib.import_module(module) + assert callable(getattr(mod, fn, None)), (cls, module, fn)