diff --git a/AGENTS.md b/AGENTS.md index 9f385db36..e6bf9fcf4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -129,7 +129,9 @@ agent's role is to prepare and check the entry locally. Read crown bar (3% at a king's tenure 0, falling to 1%; `--tenure`). It prints per-window and aggregate CRPS/MASE, the LCB and whether it would clear. `--king` is the lane D king, or before the first crown the house (the lane - A king). The tool defaults to live-only (`--public-weight 0`); the live + A king). `cascade lane-d pull-king --out DIR` downloads the current king + from the Hippius registry (read-only, no credential, every file checked + against the signed index); before the first crown it reports `no_king`. The tool defaults to live-only (`--public-weight 0`); the live deployment scores at 0.5, so pass `--public-weight 0.5 --public-pool-dir DIR` to match it. It runs torch on the human's GPU/CPU (`--device cuda`); the result is directional. diff --git a/cascade/miner/lane_d.py b/cascade/miner/lane_d.py index 7718eb479..589539877 100644 --- a/cascade/miner/lane_d.py +++ b/cascade/miner/lane_d.py @@ -31,6 +31,11 @@ every file checked against a pinned sha256) and judge a checkpoint on it by the settlement rule; needs no king checkpoint, submits nothing (``cascade.miner.lane_d_example``, loaded at call time). +* ``pull-king [--digest D] [--out DIR]`` — download the current lane D king + (or a prior one) from the Hippius registry, anonymously, after verifying + the signed ``champions/lane_d/index.json`` against ``[manifest] + validator_hotkey`` and every file against the signed digest; read-only + (``cascade.miner.lane_d_pull_king``, loaded at call time). No flag takes a credential or a URL to a grant (§1.2). The hotkey signs; the coldkey is never opened. The lane D intake and ingest helpers are loaded at @@ -127,7 +132,8 @@ def _chain_args(p: argparse.ArgumentParser) -> None: LANE_D_EPILOG = """\ examples (one dedicated hotkey; BF16 weights; MIT is the only licence): cascade lane-d example-round --out ./example-round --candidate ./trained-ckpt --context 4096 --device cuda - cascade lane-d test ./trained-ckpt --king ./king --context 16384 --pool-dir ./pool_d --device cuda + cascade lane-d pull-king --out ./king + cascade lane-d test ./trained-ckpt --king ./king --king-context 16384 --context 16384 --pool-dir ./pool_d --device cuda cascade lane-d export ./trained-ckpt --out ./entry cascade lane-d verify ./entry cascade lane-d submit https://submissions.cascadesub.net ./entry --context 16384 --wallet-name W --wallet-hotkey H @@ -199,6 +205,9 @@ def add_lane_d(sub: argparse._SubParsersAction) -> None: # `lane-d example-round`: the public example round (download, verify, score), # loaded at call time for the same reason. importlib.import_module("cascade.miner.lane_d_example").add_lane_d_example(lsub) + # `lane-d pull-king`: the current (or a prior) king from the Hippius + # registry, checked against the signed index; loaded at call time too. + importlib.import_module("cascade.miner.lane_d_pull_king").add_lane_d_pull_king(lsub) def _run(args: argparse.Namespace, body) -> int: diff --git a/cascade/miner/lane_d_preview.py b/cascade/miner/lane_d_preview.py index 599629d4e..854818ddf 100644 --- a/cascade/miner/lane_d_preview.py +++ b/cascade/miner/lane_d_preview.py @@ -71,9 +71,10 @@ def add_lane_d_test(lsub) -> None: "exported entry or the trained checkpoint).") t.add_argument("--king", type=Path, required=True, help="The bar's checkpoint directory: the current KING_D, or before the " - "first lane D crown the house (the lane A king, BF16). Kings are public " - "after a crown (HF mirror tensorlink-dev/cascade-lane-d-kings); the " - "house is not published, and no command downloads either.") + "first lane D crown the house (the lane A king, BF16). A crowned king " + "is on the Hippius registry: `cascade lane-d pull-king --out DIR` " + "downloads and verifies it (then pass --king DIR --king-context N). " + "The house is not published.") t.add_argument("--context", type=int, required=True, help="Your declared context (one of [lane_d] contexts).") t.add_argument("--king-context", type=int, default=None, diff --git a/cascade/miner/lane_d_pull_king.py b/cascade/miner/lane_d_pull_king.py new file mode 100644 index 000000000..ce99ee61c --- /dev/null +++ b/cascade/miner/lane_d_pull_king.py @@ -0,0 +1,351 @@ +"""``cascade lane-d pull-king``: download the current lane D king (or a prior +one) from the Hippius registry and check every byte (owner 2026-12-01). + +A crowned lane D king is published to the Hippius Hub only (``[lane_d_ops] +king_mirrors``, default ``["hub"]``): one public model repo per king, +``{[storage] hub_namespace}/laned-king-c{context}-{hotkey8}`` +(:func:`cascade.lane_d.publish.hub_repo`), holding the entry's four files +and its ``manifest.json``. The signed index ``champions/lane_d/index.json`` on +the public manifest store lists every king (context, digest, crown block, +LCB, gate, sentinel, licence). + +The command: + +1. GETs the index (no credential) and verifies its sr25519 signature against + the pinned main-validator hotkey ``[manifest] validator_hotkey``, the + signer of the lane D reports and the index (``LANED_SIGNER_SS58``); an + index that does not verify is refused and nothing is downloaded; +2. picks the newest crowned king (the current KING_D) or ``--digest``; +3. pulls the king's ``manifest.json`` from its Hub repo ANONYMOUSLY + (``hippius_hub`` with ``token=False``: no ambient credential is read) and + requires it to hash to the signed digest (the canonical-manifest sha256, + :func:`cascade.lane_d.intake.manifest_digest`) and to list exactly the four + lane D files; +4. pulls each file and requires its sha256 and size to equal the manifest's; +5. writes ``--out`` only when everything verified: ``config.json``, + ``weights.safetensors``, ``forecast_wrapper.py``, ``model.py``, + ``manifest.json`` and the king's repo cards ``PROVENANCE.json`` / + ``MODEL_CARD.md`` (rendered from the signed index entry by the same + functions that write ``champions/lane_d//``). On any refusal the + partial download is removed and ``--out`` is left as it was. + +Read-only: nothing is signed, committed or uploaded, no GPU is used and +torch is never imported. The lane D modules are loaded at call time (W9 +invariant 12: ``cascade.miner.lane_d`` loads this module by name). +""" + +from __future__ import annotations + +import hashlib +import importlib +import json +import os +import shutil +import urllib.error +import urllib.request +from pathlib import Path + +from .output import NETWORK, OK, REJECTED, USAGE, reporter + +MAX_INDEX_BYTES = 16 * 1024 * 1024 +MAX_MANIFEST_BYTES = 1024 * 1024 +TIMEOUT_S = 60 +HUB_REPO_TYPE = "model" +_CHUNK = 1 << 20 +# HTTP answers that mean "no index object is readable there": the public +# bucket answers 403 (not 404) for a key that does not exist yet. +_ABSENT_HTTP = (403, 404) +NO_KING_HINT = ("Until the first lane D crown the bar is the house (the lane A king, BF16), " + "which is not published: score against it with `cascade lane-d example-round` " + "(it stores the house's score on every window).") + + +class PullError(Exception): + """A typed refusal: ``code``, a human message and the CLI exit code.""" + + def __init__(self, code: str, message: str, exit_code: int = REJECTED): + super().__init__(f"{code}: {message}") + self.code, self.message, self.exit_code = code, message, exit_code + + +def _publish(): + return importlib.import_module("cascade.lane_d.publish") + + +def _intake(): + return importlib.import_module("cascade.lane_d.intake") + + +# ── the command ───────────────────────────────────────────────────────────── + + +def add_lane_d_pull_king(lsub) -> None: + p = lsub.add_parser( + "pull-king", help="Download the current lane D king (or --digest) from the Hippius " + "registry, checked against the signed index; read-only.") + p.add_argument("--digest", default=None, + help="A crowned king's digest (64 hex) from the signed index; default the " + "current king (the newest crown).") + p.add_argument("--out", type=Path, default=None, + help="Folder to write the king into (default ./lane-d-king-); it " + "must be absent or empty.") + p.add_argument("--index-url", default=None, + help="Where the signed champions/lane_d/index.json is read (default: the " + "public manifest store of [storage] in chain.toml). It is verified " + "against [manifest] validator_hotkey wherever it comes from.") + p.add_argument("--chain-toml", type=Path, default=None, help="Override chain.toml path.") + p.set_defaults(func=cmd_lane_d_pull_king, command="lane-d pull-king") + + +def default_index_url(storage) -> str: + endpoint = str(getattr(storage, "s3_endpoint", "") or "https://s3.hippius.com") + bucket = str(getattr(storage, "manifest_bucket", "") or "cascade-manifests") + return f"{endpoint.rstrip('/')}/{bucket}/{_publish().INDEX_KEY}" + + +def cmd_lane_d_pull_king(args) -> int: + from ..shared.config import load_chain_config + from ..shared.config.lane_d_ops import lane_d_ops_config + + out = reporter(args) + try: + cfg = load_chain_config(args.chain_toml) + signer = str(getattr(cfg.manifest, "validator_hotkey", "") or "").strip() + if not signer: + raise PullError("signer_unpinned", + "[manifest] validator_hotkey is empty in this chain.toml: the " + "index signer is not pinned, so no index can be trusted", USAGE) + url = str(args.index_url or default_index_url(cfg.storage)) + index = load_index(url, signer) + king = pick_king(index, args.digest) + dest = Path(args.out) if args.out is not None else Path( + f"lane-d-king-{king['digest'][:12]}") + res = pull_king(king, dest, + namespace=str(getattr(cfg.storage, "hub_namespace", "") or "cascade"), + king_mirrors=lane_d_ops_config(cfg).king_mirrors, log=out.info) + except PullError as e: + return out.fail(e.code, e.message, e.exit_code) + except (ValueError, OSError) as e: + return out.fail("lane_d_pull_king_failed", str(e), REJECTED) + nxt = next_command(res["dir"], int(king["context"])) + out.info(f"lane D king {king['digest']} (c{king['context']}, crowned at block " + f"{king['crown_block']}) is in {res['dir']}; every file matched the signed index") + out.info(f"next: {nxt}") + out.result(**res, index_url=url, signer=signer, next=nxt) + return OK + + +def next_command(directory: str, king_context: int) -> str: + return (f"cascade lane-d test YOUR_CKPT --king {directory} --king-context {king_context} " + "--context YOUR_CONTEXT --series YOUR_SERIES.npz") + + +# ── the signed index ──────────────────────────────────────────────────────── + + +def fetch_index_bytes(url: str) -> bytes | None: + """The index bytes at ``url`` (http(s) or file), ``None`` when no index + object is there (HTTP 403/404, a missing file). No credential is sent.""" + if not isinstance(url, str) or url.split(":", 1)[0].lower() not in ("http", "https", "file"): + raise PullError("bad_index_url", f"--index-url must be http(s) or file: {url!r}", USAGE) + req = urllib.request.Request(url, method="GET", headers={"Accept-Encoding": "identity"}) + try: + with urllib.request.urlopen(req, timeout=TIMEOUT_S) as r: + data = r.read(MAX_INDEX_BYTES + 1) + except urllib.error.HTTPError as e: + e.close() + if e.code in _ABSENT_HTTP: + return None + raise PullError("index_unreachable", f"HTTP {e.code} reading {url}", NETWORK) from None + except urllib.error.URLError as e: + if isinstance(e.reason, FileNotFoundError) or "No such file" in str(e.reason): + return None + raise PullError("index_unreachable", f"{url}: {e.reason}", NETWORK) from None + except OSError as e: + raise PullError("index_unreachable", f"{type(e).__name__} reading {url}", + NETWORK) from None + if len(data) > MAX_INDEX_BYTES: + raise PullError("index_invalid", f"{url} is larger than {MAX_INDEX_BYTES} bytes") + return data + + +def load_index(url: str, signer_ss58: str, *, fetch=fetch_index_bytes) -> dict: + """The verified index at ``url``. No index at all is ``no_king``; an index + that is not ``signer_ss58``'s signature is ``index_signature_invalid``.""" + raw = fetch(url) + if raw is None: + raise PullError("no_king", f"no signed lane D index is published at {url}: no lane D " + f"king has been crowned yet. {NO_KING_HINT}") + try: + index = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, ValueError): + raise PullError("index_invalid", f"{url} is not JSON") from None + try: + ok = _publish().verify_index(index, signer_ss58) + except Exception as e: # noqa: BLE001 — SignatureVerifierUnavailable: no verdict + raise PullError("verifier_unavailable", + f"the index signature cannot be checked ({type(e).__name__}: {e}); " + "install the [chain] extra", USAGE) from None + if not ok: + raise PullError("index_signature_invalid", + f"{url} is not a lane D index signed by the pinned validator hotkey " + f"{signer_ss58} ([manifest] validator_hotkey); nothing downloaded") + return index + + +def pick_king(index: dict, digest: str | None = None) -> dict: + """The index entry of ``digest``, else the current king (newest crown).""" + kings = sorted(index.get("kings") or (), key=lambda k: (k["crown_block"], k["digest"])) + if not kings: + raise PullError("no_king", f"the signed lane D index lists no king yet. {NO_KING_HINT}") + if digest is None: + king = kings[-1] + else: + king = next((k for k in kings if k["digest"] == str(digest).strip().lower()), None) + if king is None: + listed = ", ".join(f"{k['digest']} (block {k['crown_block']})" for k in kings) + raise PullError("unknown_king", + f"{digest!r} is not a crowned lane D king; the index lists {listed}") + if isinstance(king.get("takedown"), dict): + td = king["takedown"] + raise PullError("king_taken_down", + f"king {king['digest']} was unpublished at block {td.get('block')} after " + f"a {td.get('reason')} claim; its weights are no longer on the Hub") + return king + + +# ── the Hub pull ──────────────────────────────────────────────────────────── + + +def anonymous_hub_api(): + """``hippius_hub.HippiusApi`` with the anonymous sentinel ``token=False``: + no env token, cached login or docker credential is consulted.""" + try: + from hippius_hub import HippiusApi + except ImportError as e: + raise PullError("hippius_hub_missing", + f"pulling from the Hippius registry needs hippius-hub: pip install -e " + f"'.[hippius]' ({e})", USAGE) from None + return HippiusApi(token=False) + + +def _sha256_file(path: Path) -> tuple[str, int]: + h, n = hashlib.sha256(), 0 + with open(path, "rb") as f: + for block in iter(lambda: f.read(_CHUNK), b""): + h.update(block) + n += len(block) + return h.hexdigest(), n + + +def _denied(exc: BaseException) -> bool: + status = getattr(getattr(exc, "response", None), "status_code", None) + text = f"{type(exc).__name__} {exc}".lower() + return status in (401, 403) or any( + s in text for s in ("401", "403", "unauthorized", "forbidden", "authentication")) + + +def _download(api, repo: str, name: str, work: Path) -> Path: + """One file of ``repo`` into a fresh folder under ``work``; its path.""" + from cascade.lane_d.mirrors import _missing + + dl = work / f".dl-{name}" + shutil.rmtree(dl, ignore_errors=True) + dl.mkdir(parents=True) + try: + got = Path(api.hf_hub_download(repo_id=repo, filename=name, repo_type=HUB_REPO_TYPE, + local_dir=str(dl))) + except PullError: + raise + except Exception as e: # noqa: BLE001 — the Hub client's own error types + if _missing(e): + raise PullError("king_files_missing", + f"{name} is not in the Hippius registry repo {repo}") from None + if _denied(e): + raise PullError("hub_auth_required", + f"the Hippius registry refused an anonymous pull of {repo}/{name} " + f"({type(e).__name__}: {e}). Lane D king repos are published public " + "and pull-king takes no credential: report this to the subnet " + "operator", NETWORK) from None + raise PullError("hub_unreachable", + f"pulling {repo}/{name} failed ({type(e).__name__}: {e})", + NETWORK) from None + if not got.is_file(): + raise PullError("king_files_missing", f"the registry returned no file for {repo}/{name}") + return got + + +def _check_out(dest: Path) -> None: + if dest.exists() and (not dest.is_dir() or any(dest.iterdir())): + raise PullError("out_not_empty", + f"{dest} exists and is not an empty folder; pass a new --out", USAGE) + + +def pull_king(king: dict, dest: Path, *, namespace: str, king_mirrors=None, api=None, + log=lambda _line: None) -> dict: + """Pull one verified index entry's files from its Hub repo into ``dest``. + Everything lands in a sibling staging folder first and is moved into + ``dest`` only once every hash matched; a refusal removes it.""" + pub, intake = _publish(), _intake() + dest = Path(dest) + _check_out(dest) + digest, context, hotkey = str(king["digest"]), int(king["context"]), str(king["hotkey"]) + repo = pub.hub_repo(namespace, context, hotkey) + if api is None: + api = anonymous_hub_api() + dest.parent.mkdir(parents=True, exist_ok=True) + stage = dest.parent / f".{dest.name}.pull-king-{os.getpid()}" + shutil.rmtree(stage, ignore_errors=True) + stage.mkdir() + try: + log(f"pulling lane D king {digest[:12]} from the Hippius registry repo {repo} " + "(anonymous)") + mpath = _download(api, repo, intake.MANIFEST_OBJECT, stage) + if mpath.stat().st_size > MAX_MANIFEST_BYTES: + raise PullError("hash_mismatch", f"{repo}/{intake.MANIFEST_OBJECT} is oversize") + raw = mpath.read_bytes() + try: + manifest = json.loads(raw.decode("utf-8")) + ok = intake.manifest_digest(manifest) == digest + files = dict(manifest["files"]) + except (UnicodeDecodeError, ValueError, KeyError, TypeError): + ok, files = False, {} + if not ok: + raise PullError("hash_mismatch", + f"{repo}/{intake.MANIFEST_OBJECT} does not hash to the signed digest " + f"{digest}; nothing kept") + if set(files) != set(intake.ALLOWED_FILES): + raise PullError("hash_mismatch", + f"the king's manifest lists {sorted(files)}, not the lane D files " + f"{list(intake.ALLOWED_FILES)}; nothing kept") + (stage / intake.MANIFEST_OBJECT).write_bytes(raw) + shutil.rmtree(stage / f".dl-{intake.MANIFEST_OBJECT}", ignore_errors=True) + for name in sorted(files): + meta = files[name] + log(f" {name} ({int(meta['size'])} bytes)") + got = _download(api, repo, name, stage) + sha, size = _sha256_file(got) + if sha != str(meta["sha256"]) or size != int(meta["size"]): + raise PullError("hash_mismatch", + f"{repo}/{name} does not match the signed manifest (sha256 " + f"{sha[:16]}…, {size} bytes; want {str(meta['sha256'])[:16]}…, " + f"{int(meta['size'])} bytes); nothing kept") + os.replace(got, stage / name) + shutil.rmtree(stage / f".dl-{name}", ignore_errors=True) + names = pub.king_mirror_names(king_mirrors) + (stage / pub.PROVENANCE_FILE).write_bytes(pub.index_bytes(pub.provenance(king, names))) + (stage / pub.MODEL_CARD_FILE).write_text(pub.model_card(king, names), encoding="utf-8") + _check_out(dest) + if dest.exists(): + dest.rmdir() + os.replace(stage, dest) + finally: + shutil.rmtree(stage, ignore_errors=True) + written = sorted(p.name for p in dest.iterdir()) + return {"dir": str(dest), "digest": digest, "context": context, "hotkey": hotkey, + "crown_block": int(king["crown_block"]), "hub_repo": repo, "files": written} + + +__all__ = ["PullError", "add_lane_d_pull_king", "anonymous_hub_api", "cmd_lane_d_pull_king", + "default_index_url", "fetch_index_bytes", "load_index", "next_command", + "pick_king", "pull_king"] diff --git a/docs/LANE_D.md b/docs/LANE_D.md index 02c1736b6..15a4c1c85 100644 --- a/docs/LANE_D.md +++ b/docs/LANE_D.md @@ -202,7 +202,12 @@ Ephemeris or anything else, on your own account, as long as the teacher's licence permits it. Kings are published to the Hippius Hub only (owner 2026-12-01; the mirrors -are `[lane_d_ops] king_mirrors`). A licence or rights claim triggers a +are `[lane_d_ops] king_mirrors`), one public repo per king, +`cascade/laned-king-c-`. `cascade lane-d pull-king [--digest D] +--out DIR` downloads the current king (or a prior one) anonymously, after it +has checked the signed index against `[manifest] validator_hotkey` and every +file against the signed digest. Pass `DIR` to `cascade lane-d test --king DIR +--king-context N`. A licence or rights claim triggers a takedown: the Hub copy is removed, while the vault, the digest and the verdict record stay, and the re-signed lane D index marks the king `takedown`. diff --git a/docs/MINER_LANE_D.md b/docs/MINER_LANE_D.md index 6823ebf5a..a017170da 100644 --- a/docs/MINER_LANE_D.md +++ b/docs/MINER_LANE_D.md @@ -65,7 +65,7 @@ tenure. Without the house weights, use the [example round](#example-round) below: it needs no `--king`. ```bash -cascade lane-d test ./my-trained-ckpt --king ./king --context 16384 \ +cascade lane-d test ./my-trained-ckpt --king ./king --king-context 16384 --context 16384 \ --pool-dir ./pool_d --device cuda # a pool_d/1 snapshot cascade lane-d test ./my-trained-ckpt --king ./king --context 4096 \ --series ./my-series.npz --windows-per-series 20 # your own series @@ -74,15 +74,35 @@ cascade lane-d test ./my-trained-ckpt --king ./king --context 4096 \ The result is directional. Your local windows are not the private live pool, and the bench gate, caps and queue run only live. -**Where `--king` and `--pool-dir` come from.** No `cascade` command downloads either -yet. Before the first lane D crown the bar is the house, a BF16 cast of the -frozen lane A king (uid 164) that the operator builds and does not publish. -After a crown, each king's checkpoint is published (Hippius Hub repo -`cascade/laned-king-c-`, indexed in the signed -`champions/lane_d/index.json`). Spent `pool_d` snapshots are public (see -[Past evaluations](#past-evaluations)): every window of a snapshot no entry -can still be judged on, with the house's forecasts and scores. Preview on -those (`windows.npz`) or on your own data with `--series S.npz`. +**Where `--king` and `--pool-dir` come from.** After a lane D crown, download +the king from the Hippius registry (no account or credential needed): + +```bash +cascade lane-d pull-king --out ./king # the current king +cascade lane-d pull-king --digest D --out ./king-old # a prior king +``` + +It reads the signed index `champions/lane_d/index.json` from the public +manifest store (, +`--index-url` to override) and checks its signature against the main +validator hotkey pinned in `chain.toml` (`[manifest] validator_hotkey`). It +then pulls the king's Hippius Hub repo `cascade/laned-king-c-` +anonymously and checks `manifest.json` against the signed digest and every +file against its sha256. Nothing is written unless every check passes. +`--out` then holds `config.json`, `weights.safetensors`, `model.py`, +`forecast_wrapper.py`, `manifest.json`, `PROVENANCE.json` and `MODEL_CARD.md`, +and the command prints the `cascade lane-d test ... --king DIR --king-context N` +line to run next. Use the king's own context as `--king-context`. It is +read-only and needs no GPU or torch. + +Before the first lane D crown, `pull-king` reports `no_king`. The bar is then +the house, a BF16 cast of the frozen lane A king (uid 164), which the +operator builds and does not publish. Use the [example round](#example-round) +instead: it stores the house's score on every window. Spent `pool_d` +snapshots are public (see [Past evaluations](#past-evaluations)): every window +of a snapshot no entry can still be judged on, with the house's forecasts and +scores. Preview on those (`windows.npz`) or on your own data with +`--series S.npz`. ### Example round diff --git a/llms.txt b/llms.txt index 4c1ffea98..069679a67 100644 --- a/llms.txt +++ b/llms.txt @@ -68,7 +68,7 @@ Percentages are shares of total emissions. A lane's pool is its budget; miners r - [Lane B: expert targets](docs/MINER_LANE_B.md): declared domain and horizon targets, selected expert rows, the slot judge and merge acceptance. - [Lane C: MarketCast](docs/MINER_LANE_C_MARKETCAST.md): the `mkt:market` target, the pinned Timestral base, confirmation and full-pay duration. - [Lane D: open weights](docs/MINER_LANE_D.md): BF16 cascade_pyramid checkpoints, the crown bar, the court and skip reasons. -- [Lane D guide](docs/LANE_D.md): checkpoint format, `cascade lane-d` test/export/verify/submit/ready/status, forward-only judging, caps and FAQ. +- [Lane D guide](docs/LANE_D.md): checkpoint format, `cascade lane-d` test/pull-king/export/verify/submit/ready/status, forward-only judging, caps and FAQ. - [MarketCast reference](docs/MARKETCAST.md): the MarketCast observation pool and scorer behind lane C. ## Submit diff --git a/tests/accept/w10/PATHS b/tests/accept/w10/PATHS index 6268d068a..b4cffd45d 100644 --- a/tests/accept/w10/PATHS +++ b/tests/accept/w10/PATHS @@ -10,6 +10,10 @@ cascade/miner/lane_d_preview.py # `lane-d example` (owner 2026-11-29): download the public example round # (pinned manifest) and score a checkpoint on it against the stored king scores. cascade/miner/lane_d_example.py +# `lane-d pull-king` (owner 2026-12-01): the current (or a prior) lane D king +# from the Hippius registry, verified against the signed index; loaded at call +# time by cascade/miner/lane_d.py. +cascade/miner/lane_d_pull_king.py # build_parser registers add_lane_d; the module docstring lists the group. cascade/miner/cli.py # `cascade rules a|b|c|d` (owner 2026-11-24 miner CLI refresh): prints each @@ -18,4 +22,6 @@ cascade/miner/rules.py # The miner kit's lane D pages describe these commands (plan §10.2): the guide # and the agent guide change with the CLI in the same PR. docs/MINER_LANE_D.md +docs/LANE_D.md AGENTS.md +llms.txt diff --git a/tests/accept/w10/README.md b/tests/accept/w10/README.md index 6f5703f7b..6129bc6a9 100644 --- a/tests/accept/w10/README.md +++ b/tests/accept/w10/README.md @@ -220,6 +220,27 @@ The only fake is the model forward (`forecast_quantiles`); its torch path is the scorer's own and CI covers it. The module is loaded with `importlib` from `cascade/miner/lane_d.py` (W9 invariant 12). +## `pull-king [--digest D] [--out DIR] [--index-url URL]` (owner 2026-12-01) + +Downloads a crowned lane D king from the Hippius registry +(`test_w10_pull_king.py`). The signed `champions/lane_d/index.json` (default: +the public manifest store of `[storage]`) must verify under `[manifest] +validator_hotkey` (`cascade.lane_d.publish.verify_index`) before anything is +pulled; the king is the newest crown, or `--digest`. Its Hub repo is +`cascade.lane_d.publish.hub_repo(hub_namespace, context, hotkey)`, pulled with +`hippius_hub.HippiusApi(token=False)` (anonymous, no ambient credential). The +tests pin, with a fake index and a fake Hub: + +- a good index: the four files, `manifest.json`, `PROVENANCE.json` and + `MODEL_CARD.md` are written, byte-identical to the published ones, and the + next `cascade lane-d test --king DIR --king-context N` line is printed; +- a bad signature is `index_signature_invalid` and the Hub is never called; +- a file whose sha256 differs from the signed manifest is `hash_mismatch` + and no file (partial or staged) is left behind; +- `--digest` picks a prior king's repo and files; +- no index (HTTP 403/404) or an index with no king is `no_king`, naming the + house and `example-round`. + ## Secrets (every flow) stdout, stderr and every log record never contain any of these: diff --git a/tests/accept/w10/test_w10_cli.py b/tests/accept/w10/test_w10_cli.py index 2f273e50f..25f7c5cff 100644 --- a/tests/accept/w10/test_w10_cli.py +++ b/tests/accept/w10/test_w10_cli.py @@ -33,7 +33,7 @@ def _flags(parser) -> set[str]: def test_the_lane_d_group_has_exactly_the_five_commands(): kids = _children(_lane_d_parser()) assert set(kids) >= set(SUBCOMMANDS), sorted(kids) - extra = set(kids) - set(SUBCOMMANDS) - {"test", "example-round"} + extra = set(kids) - set(SUBCOMMANDS) - {"test", "example-round", "pull-king"} assert not extra, f"unexpected lane-d commands: {sorted(extra)}" diff --git a/tests/accept/w10/test_w10_pull_king.py b/tests/accept/w10/test_w10_pull_king.py new file mode 100644 index 000000000..3a2ceac48 --- /dev/null +++ b/tests/accept/w10/test_w10_pull_king.py @@ -0,0 +1,302 @@ +"""W10: `cascade lane-d pull-king` (owner 2026-12-01: "miners must be able to +pull the current lane D king's model from the Hippius registry with the +miner CLI"). + +The command verifies the signed ``champions/lane_d/index.json`` against the +pinned ``[manifest] validator_hotkey``, picks the newest crown (or +``--digest``), pulls the king's files from its Hub repo +(``cascade.lane_d.publish.hub_repo``) anonymously and checks every byte +against the signed digest before ``--out`` is written. Contract: README.md +"pull-king". + +The fakes: the index is a ``file://`` URL; the Hippius registry is +:class:`FakeHub` (``hf_hub_download`` over an in-memory repo map, every call +recorded), monkeypatched in for the anonymous ``HippiusApi``; the pinned +signer is a ``//w10-…`` test key written into a copy of chain.toml. No +network, no torch. Every test asserts the command exists first, so on a base +without it each fails by assertion.""" + +from __future__ import annotations + +import argparse +import importlib +import importlib.util +import json +from pathlib import Path + +import pytest + +from .helpers import CHAIN_TOML + +MOD = "cascade.miner.lane_d_pull_king" +FILES = ("config.json", "forecast_wrapper.py", "model.py", "weights.safetensors") +NAMESPACE = "cascade" +KING_CTX, PRIOR_CTX = 16384, 4096 + + +def _mod(): + assert importlib.util.find_spec(MOD) is not None, f"no {MOD}: `lane-d pull-king` is missing" + return importlib.import_module(MOD) + + +def _keypair(name: str): + try: + from bittensor.sp_core import Keypair + except ImportError: + from bittensor import Keypair + return Keypair.create_from_uri(f"//w10-{name}") + + +class EntryNotFoundError(Exception): + """The not-found error name the Hub client raises (huggingface_hub's).""" + + +class FakeHub: + """The Hippius registry: ``{repo: {file: bytes}}``; every download is + recorded as ``(repo, file)``.""" + + def __init__(self): + self.repos: dict[str, dict[str, bytes]] = {} + self.calls: list[tuple[str, str]] = [] + + def hf_hub_download(self, *, repo_id, filename, repo_type, local_dir, **_): + assert repo_type == "model" + self.calls.append((repo_id, filename)) + files = self.repos.get(repo_id) + if files is None or filename not in files: + raise EntryNotFoundError(f"{repo_id}/{filename}") + p = Path(local_dir) / filename + p.write_bytes(files[filename]) + return str(p) + + +def _checkpoint(root: Path, seed: int) -> dict[str, bytes]: + root.mkdir(parents=True) + files = { + "config.json": json.dumps({"seed": seed, "arch": "cascade_pyramid"}).encode(), + "forecast_wrapper.py": b"# wrapper\n", + "model.py": b"# model\n", + "weights.safetensors": bytes(range(256)) * (8 + seed), + } + for name, data in files.items(): + (root / name).write_bytes(data) + return files + + +def _king(tmp: Path, hub: FakeHub, *, name: str, seed: int, context: int, crown: int): + """One crowned king: its files on the fake Hub and its index entry.""" + from cascade.lane_d.intake import checkpoint_manifest, manifest_digest + from cascade.lane_d.publish import canonical_json, hub_repo + + ckpt = tmp / f"ckpt-{name}" + files = _checkpoint(ckpt, seed) + manifest = checkpoint_manifest(ckpt) + digest = manifest_digest(manifest) + hotkey = _keypair(f"miner-{name}").ss58_address + hub.repos[hub_repo(NAMESPACE, context, hotkey)] = {**files, + "manifest.json": canonical_json(manifest)} + entry = {"hotkey": hotkey, "context": context, "digest": digest, "crown_block": crown, + "lcb": 0.0123, "gate": {"outcome": "pass", "suite": "gift_eval"}, + "sentinel": {"suite": "none", "status": "not_armed"}, "license": "MIT"} + return entry, files + + +@pytest.fixture +def world(tmp_path, monkeypatch): + signer = _keypair("index-signer") + text = CHAIN_TOML.read_text(encoding="utf-8") + # The main validator's key: [manifest] validator_hotkey and the keys the + # loader requires to name the same validator, all swapped for the test key. + main = "5FcCsoB2R5M55RdrNrvPQv7xmLJRFzs7R7C73UUSxgUCyfsw" + assert f'validator_hotkey = "{main}"' in text, "chain.toml's [manifest] validator_hotkey moved" + toml = tmp_path / "chain.toml" + toml.write_text(text.replace(main, signer.ss58_address), encoding="utf-8") + hub = FakeHub() + if importlib.util.find_spec(MOD) is not None: # absent: each test fails on _mod() + monkeypatch.setattr(importlib.import_module(MOD), "anonymous_hub_api", lambda: hub) + prior, prior_files = _king(tmp_path, hub, name="prior", seed=1, context=PRIOR_CTX, + crown=9_000_000) + king, king_files = _king(tmp_path, hub, name="king", seed=2, context=KING_CTX, + crown=9_000_900) + return argparse.Namespace(tmp=tmp_path, toml=toml, signer=signer, hub=hub, prior=prior, + prior_files=prior_files, king=king, king_files=king_files) + + +def _write_index(w, kings, *, signer=None) -> str: + from cascade.lane_d.publish import build_index, index_bytes + + path = w.tmp / "index.json" + path.write_bytes(index_bytes(build_index(kings, signer or w.signer))) + return path.as_uri() + + +def _run(capsys, w, *argv): + _mod() + from cascade.miner.cli import build_parser, main + + root = build_parser() + (sub,) = [a for a in root._actions if isinstance(a, argparse._SubParsersAction)] + (lsub,) = [a for a in sub.choices["lane-d"]._actions + if isinstance(a, argparse._SubParsersAction)] + assert "pull-king" in lsub.choices, sorted(lsub.choices) + rc = main(["lane-d", "pull-king", *map(str, argv), "--chain-toml", str(w.toml), "--json"]) + captured = capsys.readouterr() + doc = json.loads(captured.out.strip().splitlines()[-1]) + return rc, doc, captured.out + captured.err + + +def _tree(root: Path) -> dict[str, bytes]: + return {p.name: p.read_bytes() for p in root.iterdir()} if root.exists() else {} + + +def test_good_index_writes_and_verifies_the_current_king(capsys, world): + from cascade.lane_d.publish import hub_repo, index_bytes, model_card, provenance + + w = world + url = _write_index(w, [w.prior, w.king]) + out = w.tmp / "king" + rc, doc, text = _run(capsys, w, "--index-url", url, "--out", out) + assert rc == 0, doc + got = _tree(out) + for name, data in w.king_files.items(): + assert got.get(name) == data, name + assert set(got) == {*FILES, "manifest.json", "PROVENANCE.json", "MODEL_CARD.md"}, sorted(got) + assert got["PROVENANCE.json"] == index_bytes(provenance(w.king)) + assert got["MODEL_CARD.md"].decode() == model_card(w.king) + repo = hub_repo(NAMESPACE, KING_CTX, w.king["hotkey"]) + assert {r for r, _ in w.hub.calls} == {repo} + assert doc["data"]["digest"] == w.king["digest"] + assert f"--king {out} --king-context {KING_CTX}" in text + assert "cascade lane-d test" in doc["data"]["next"] + assert not [p for p in w.tmp.iterdir() if ".pull-king-" in p.name] + + +def test_bad_signature_is_refused_before_any_hub_call(capsys, world): + w = world + url = _write_index(w, [w.prior, w.king], signer=_keypair("not-the-validator")) + out = w.tmp / "king" + rc, doc, _ = _run(capsys, w, "--index-url", url, "--out", out) + assert rc != 0 and doc["error"]["code"] == "index_signature_invalid", doc + assert w.hub.calls == [] + assert not out.exists() + + +def test_tampered_index_is_refused(capsys, world): + w = world + url = _write_index(w, [w.prior, w.king]) + path = Path(url[len("file://"):]) + doc = json.loads(path.read_text()) + doc["kings"][-1]["lcb"] = 0.5 + path.write_text(json.dumps(doc)) + rc, res, _ = _run(capsys, w, "--index-url", url, "--out", w.tmp / "king") + assert rc != 0 and res["error"]["code"] == "index_signature_invalid", res + assert w.hub.calls == [] + + +def test_hash_mismatch_is_refused_and_partial_files_removed(capsys, world): + from cascade.lane_d.publish import hub_repo + + w = world + url = _write_index(w, [w.prior, w.king]) + repo = hub_repo(NAMESPACE, KING_CTX, w.king["hotkey"]) + good = w.hub.repos[repo]["weights.safetensors"] + w.hub.repos[repo]["weights.safetensors"] = good[:-1] + bytes([good[-1] ^ 1]) + out = w.tmp / "king" + rc, doc, _ = _run(capsys, w, "--index-url", url, "--out", out) + assert rc != 0 and doc["error"]["code"] == "hash_mismatch", doc + assert ("weights.safetensors" in {f for _, f in w.hub.calls}) + assert not out.exists() or not any(out.iterdir()) + assert not [p for p in w.tmp.iterdir() if ".pull-king-" in p.name], sorted( + p.name for p in w.tmp.iterdir()) + + +def test_a_manifest_that_does_not_hash_to_the_digest_is_refused(capsys, world): + from cascade.lane_d.publish import hub_repo + + w = world + url = _write_index(w, [w.prior, w.king]) + repo = hub_repo(NAMESPACE, KING_CTX, w.king["hotkey"]) + # a consistent rewrite: model.py and its manifest sha both changed + manifest = json.loads(w.hub.repos[repo]["manifest.json"]) + w.hub.repos[repo]["model.py"] = b"# other code\n" + import hashlib + + manifest["files"]["model.py"] = {"sha256": hashlib.sha256(b"# other code\n").hexdigest(), + "size": len(b"# other code\n")} + w.hub.repos[repo]["manifest.json"] = json.dumps(manifest).encode() + out = w.tmp / "king" + rc, doc, _ = _run(capsys, w, "--index-url", url, "--out", out) + assert rc != 0 and doc["error"]["code"] == "hash_mismatch", doc + assert {f for _, f in w.hub.calls} == {"manifest.json"} + assert not out.exists() + + +def test_digest_picks_a_prior_king(capsys, world): + from cascade.lane_d.publish import hub_repo + + w = world + url = _write_index(w, [w.prior, w.king]) + out = w.tmp / "prior" + rc, doc, text = _run(capsys, w, "--index-url", url, "--out", out, + "--digest", w.prior["digest"]) + assert rc == 0, doc + got = _tree(out) + for name, data in w.prior_files.items(): + assert got.get(name) == data, name + assert {r for r, _ in w.hub.calls} == {hub_repo(NAMESPACE, PRIOR_CTX, w.prior["hotkey"])} + assert f"--king-context {PRIOR_CTX}" in text + rc, doc, _ = _run(capsys, w, "--index-url", url, "--out", w.tmp / "x", "--digest", "ab" * 32) + assert rc != 0 and doc["error"]["code"] == "unknown_king", doc + + +def test_no_king_yet_is_a_clear_message(capsys, world): + w = world + url = _write_index(w, []) + rc, doc, _ = _run(capsys, w, "--index-url", url, "--out", w.tmp / "king") + assert rc != 0 and doc["error"]["code"] == "no_king", doc + msg = doc["error"]["message"] + assert "house" in msg and "example-round" in msg, msg + missing = (w.tmp / "absent-index.json").as_uri() + rc, doc, _ = _run(capsys, w, "--index-url", missing, "--out", w.tmp / "king") + assert rc != 0 and doc["error"]["code"] == "no_king", doc + assert w.hub.calls == [] + + +def test_the_default_index_url_is_the_public_manifest_store(): + mod = _mod() + from cascade.shared.config import load_chain_config + + url = mod.default_index_url(load_chain_config(CHAIN_TOML).storage) + assert url == "https://s3.hippius.com/cascade-manifests/champions/lane_d/index.json" + + +def test_the_hub_is_pulled_anonymously(monkeypatch): + mod = _mod() + seen = {} + + class Api: + def __init__(self, token=None, **_): + seen["token"] = token + + import types + + monkeypatch.setitem(__import__("sys").modules, "hippius_hub", + types.SimpleNamespace(HippiusApi=Api)) + mod.anonymous_hub_api() + assert seen["token"] is False + + +def test_the_module_is_loaded_by_name_only_and_never_imports_torch(): + import ast + + _mod() + src = Path(importlib.util.find_spec(MOD).origin).read_text(encoding="utf-8") + names = set() + for node in ast.walk(ast.parse(src)): + if isinstance(node, ast.Import): + names |= {a.name for a in node.names} + elif isinstance(node, ast.ImportFrom) and node.module: + names.add(node.module) + assert not any(n == "torch" or n.startswith("torch.") for n in names), names + lane_d = Path(importlib.util.find_spec("cascade.miner.lane_d").origin).read_text() + assert "import_module(\"cascade.miner.lane_d_pull_king\")" in lane_d diff --git a/tests/accept/w10/test_w10_rules.py b/tests/accept/w10/test_w10_rules.py index 693db0976..b80fa5f54 100644 --- a/tests/accept/w10/test_w10_rules.py +++ b/tests/accept/w10/test_w10_rules.py @@ -166,7 +166,8 @@ def test_lane_d_help_has_runnable_examples_and_points_at_rules(): for line in examples: args = _parse(shlex.split(line)[1:]) seen.add(args.lane_d_cmd) - assert seen == {"example-round", "export", "verify", "submit", "ready", "status", "test"}, seen + assert seen == {"example-round", "export", "verify", "submit", "ready", "status", "test", + "pull-king"}, seen assert any("--licence MIT" in line for line in examples)