Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 89 additions & 31 deletions cascade/lane_d/mirrors.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,18 @@
:data:`~cascade.lane_d.storage.STREAM_CHUNK_BYTES`, never held in memory:

* **hub**: the public Hippius Hub repo ``{[storage] hub_namespace}/laned-king-
c{context}-{hotkey8}`` (:func:`cascade.lane_d.publish.hub_repo`; one repo per
king), through ``hippius_hub.HippiusApi``; the token is the existing
``HIPPIUS_HUB_TOKEN`` / ``HIPPIUS_TOKEN`` (or the username/password pair),
resolved by :mod:`cascade.shared.hippius`. A file is ``<file>`` in the repo.
c{context}-{hotkey8}`` (``hotkey8`` lowercased: the Hub refuses an
uppercase repo name; :func:`cascade.lane_d.publish.hub_repo`; one repo per
king), through ``huggingface_hub.HfApi`` pointed at the Hippius Hub
(``HIPPIUS_HF_ENDPOINT``, default :data:`HIPPIUS_HF_ENDPOINT_DEFAULT`). Live
2026-12-01 the Hippius registry API refused model pushes ("Push models with
huggingface_hub: set HF_ENDPOINT=https://hub.hippius.com and use a hip_
key"). Writes (create, upload, takedown delete) carry the ``hip_`` key
``HIPPIUS_HF_TOKEN``; reads (the read-back re-hash, listing, sizes) are
ANONYMOUS (``token=False``), as the miners' ``pull-king`` is: a king repo is
public. Endpoint and token are per ``HfApi`` instance, NEVER the global
``HF_ENDPOINT`` / ``HF_TOKEN``: the validator and trainer use the real
Hugging Face in the same process. A file is ``<file>`` in the repo.
* **hf**: the HF dataset :data:`cascade.lane_d.publish.HF_MIRROR_REPO` through
``huggingface_hub.HfApi`` with ``HF_TOKEN`` / ``HUGGINGFACE_API_KEY``; the
file path in the dataset is the full key.
Expand Down Expand Up @@ -51,6 +59,16 @@
R2_ACCESS_KEY_ENV = "BACKUP_S3_ACCESS_KEY"
R2_SECRET_KEY_ENV = "BACKUP_S3_SECRET_KEY"
HF_TOKEN_ENVS = ("HF_TOKEN", "HUGGINGFACE_API_KEY")
# The Hippius Hub's huggingface_hub API (2026-12-01): the hip_ key
# (``hip_<S3 access key id>:<secret>``) and an optional endpoint override.
HIPPIUS_HF_TOKEN_ENV = "HIPPIUS_HF_TOKEN"
HIPPIUS_HF_ENDPOINT_ENV = "HIPPIUS_HF_ENDPOINT"
HIPPIUS_HF_ENDPOINT_DEFAULT = "https://hub.hippius.com"
# HTTP answers a READ treats as "not there": a Hub (Hippius or Hugging Face)
# answers an anonymous read of a repo that does not exist with 401, and the
# Hippius Hub has answered 403. Reads only: an upload or a takedown delete
# that answers 401/403 is an error, never "already gone".
_READ_ABSENT_HTTP = frozenset((401, 403))
# Parts of one R2 upload in flight at once: with STREAM_CHUNK_BYTES parts this
# is the most of a checkpoint an upload holds in memory.
TRANSFER_THREADS = 2
Expand Down Expand Up @@ -78,17 +96,33 @@ def _missing(exc: BaseException) -> bool:
return status == 404


def _read_missing(exc: BaseException) -> bool:
""":func:`_missing`, or a 401/403 answer: what a READ treats as absent."""
status = getattr(getattr(exc, "response", None), "status_code", None)
return _missing(exc) or status in _READ_ABSENT_HTTP


def hippius_hf_endpoint(environ: Mapping[str, str] | None = None) -> str:
"""The Hippius Hub's huggingface_hub endpoint: ``HIPPIUS_HF_ENDPOINT`` or
:data:`HIPPIUS_HF_ENDPOINT_DEFAULT`. Never ``HF_ENDPOINT`` (real HF)."""
env = os.environ if environ is None else environ
return str(env.get(HIPPIUS_HF_ENDPOINT_ENV) or HIPPIUS_HF_ENDPOINT_DEFAULT).rstrip("/")


class RepoMirror:
"""A mirror over one HF-shaped repo (``hippius_hub.HippiusApi`` or
``huggingface_hub.HfApi``). ``path_of(key)`` maps a mirror key to the
file path in the repo (``None``: the key is outside this mirror). A
download lands in a fresh directory under ``tmp_dir`` (default: the system
temp directory) that is removed before the call returns."""
"""A mirror over one HF-shaped repo (``huggingface_hub.HfApi``, on the
Hippius Hub or Hugging Face). ``path_of(key)`` maps a mirror key to the
file path in the repo (``None``: the key is outside this mirror). Writes
go through ``api``; reads through ``read_api`` (default ``api``), the
Hub's anonymous client. A download lands in a fresh directory under
``tmp_dir`` (default: the system temp directory) that is removed before
the call returns."""

def __init__(self, api, *, repo_id: str, repo_type: str,
path_of: Callable[[str], str | None], key_of: Callable[[str], str | None],
tmp_dir: str | os.PathLike | None = None):
tmp_dir: str | os.PathLike | None = None, read_api=None):
self.api = api
self.read_api = api if read_api is None else read_api
self.repo_id = str(repo_id)
self.repo_type = str(repo_type)
self.tmp_dir = tmp_dir
Expand Down Expand Up @@ -122,10 +156,13 @@ def put_file(self, key: str, path: str | os.PathLike) -> None:
def _download(self, key: str, tmp: str) -> Path:
path = self._path(key)
try:
return Path(self.api.hf_hub_download(repo_id=self.repo_id, filename=path,
repo_type=self.repo_type, local_dir=tmp))
return Path(self.read_api.hf_hub_download(repo_id=self.repo_id, filename=path,
repo_type=self.repo_type, local_dir=tmp))
except Exception as e:
if _missing(e):
# A missing repo answers a read 401/403 (2026-12-01). Missing is
# safe here: the post-upload read-back must return the bytes, or
# the publish fails with the index unchanged.
if _read_missing(e):
raise KeyError(key) from None
raise

Expand All @@ -148,9 +185,9 @@ def get_to(self, key: str, fileobj) -> None:

def _files(self) -> list[str]:
try:
return list(self.api.list_repo_files(self.repo_id, repo_type=self.repo_type))
return list(self.read_api.list_repo_files(self.repo_id, repo_type=self.repo_type))
except Exception as e:
if _missing(e):
if _read_missing(e):
return []
raise

Expand All @@ -161,9 +198,10 @@ def list(self, prefix: str) -> list[str]:
def size(self, key: str) -> int:
path = self._path(key)
try:
infos = list(self.api.get_paths_info(self.repo_id, [path], repo_type=self.repo_type))
infos = list(self.read_api.get_paths_info(self.repo_id, [path],
repo_type=self.repo_type))
except Exception as e:
if _missing(e):
if _read_missing(e):
raise KeyError(key) from None
raise
for info in infos:
Expand All @@ -183,17 +221,18 @@ def delete(self, key: str) -> None:


def hub_mirror(api, *, namespace: str, context: int, hotkey: str, digest: str,
tmp_dir: str | os.PathLike | None = None) -> RepoMirror:
tmp_dir: str | os.PathLike | None = None, read_api=None) -> RepoMirror:
"""The Hub mirror of ONE king: its repo holds ``<file>`` for the key
``lane-d-kings/<digest>/<file>``; any other key is outside it."""
``lane-d-kings/<digest>/<file>``; any other key is outside it. ``api``
writes, ``read_api`` (default ``api``) reads."""
prefix = mirror_prefix(digest)

def path_of(key: str) -> str | None:
return key[len(prefix):] if key.startswith(prefix) and len(key) > len(prefix) else None

return RepoMirror(api, repo_id=hub_repo(namespace, context, hotkey),
repo_type=HUB_REPO_TYPE, path_of=path_of, key_of=lambda p: prefix + p,
tmp_dir=tmp_dir)
tmp_dir=tmp_dir, read_api=read_api)


def hf_mirror(api, *, repo_id: str = HF_MIRROR_REPO,
Expand Down Expand Up @@ -313,12 +352,24 @@ def get():


def _hub_api(environ: Mapping[str, str]):
from hippius_hub import HippiusApi
"""The Hub WRITER: ``HfApi`` on the Hippius Hub endpoint with the ``hip_``
key ``HIPPIUS_HF_TOKEN``, both per instance (no global env is read or set
beyond ``environ``)."""
from huggingface_hub import HfApi

from ..shared.hippius import _resolve_hub_token
token = str(environ.get(HIPPIUS_HF_TOKEN_ENV) or "").strip()
if not token:
raise MirrorError(f"publishing a lane D king to the Hippius Hub needs "
f"{HIPPIUS_HF_TOKEN_ENV} (a hip_ key) in the job environment")
return HfApi(endpoint=hippius_hf_endpoint(environ), token=token)


def _hub_read_api(environ: Mapping[str, str]):
"""The Hub READER: ``HfApi`` on the same endpoint, anonymous
(``token=False``: no env token or cached login is sent)."""
from huggingface_hub import HfApi

del environ # the shared resolver reads os.environ itself
return HippiusApi(token=_resolve_hub_token("Publishing a lane D king"))
return HfApi(endpoint=hippius_hf_endpoint(environ), token=False)


def _hf_api(environ: Mapping[str, str]):
Expand Down Expand Up @@ -359,13 +410,14 @@ def _r2_client(storage, environ: Mapping[str, str]):

def open_live_mirrors(cfg, *, context: int, hotkey: str, digest: str,
environ: Mapping[str, str] | None = None,
hub_api=None, hf_api=None, r2_client=None,
hub_api=None, hf_api=None, r2_client=None, hub_read_api=None,
tmp_dir: str | os.PathLike | None = None, names=None) -> dict:
"""The mirror clients of ``names`` (the king mirrors,
:func:`cascade.lane_d.publish.king_mirror_names`: the Hub only by
default) for one king from the loaded ``ChainConfig`` (``[storage]``); no
other mirror's client is built. The ``*_api`` / ``r2_client`` arguments
replace the live backends (tests). ``tmp_dir`` is where the Hub and HF
replace the live backends (tests); a ``hub_api`` given without
``hub_read_api`` also reads. ``tmp_dir`` is where the Hub and HF
mirrors download a file for a read-back (default: the system temp
directory)."""
from .publish import king_mirror_names
Expand All @@ -375,11 +427,16 @@ def open_live_mirrors(cfg, *, context: int, hotkey: str, digest: str,
out: dict = {}
for name in king_mirror_names(names):
if name == "hub":
hub = hub_api if hub_api is not None else _LazyApi(lambda: _hub_api(env))
if hub_api is not None:
hub, reader = hub_api, hub_read_api
else:
hub = _LazyApi(lambda: _hub_api(env))
reader = (hub_read_api if hub_read_api is not None
else _LazyApi(lambda: _hub_read_api(env)))
out[name] = hub_mirror(hub, namespace=str(getattr(storage, "hub_namespace",
"cascade")),
context=context, hotkey=hotkey, digest=digest,
tmp_dir=tmp_dir)
tmp_dir=tmp_dir, read_api=reader)
elif name == "r2":
r2 = ((lambda: r2_client) if r2_client is not None
else _lazy(lambda: _r2_client(storage, env)))
Expand Down Expand Up @@ -418,6 +475,7 @@ def open_index_store(cfg) -> PublicStore:
return PublicStore(open_manifest_store(cfg.storage))


__all__ = ["HF_REPO_TYPE", "HUB_REPO_TYPE", "MirrorError", "PublicStore", "RepoMirror",
"S3Mirror", "hf_mirror", "hub_mirror", "open_index_store", "open_live_mirrors",
"open_live_vault", "r2_bucket"]
__all__ = ["HF_REPO_TYPE", "HIPPIUS_HF_ENDPOINT_DEFAULT", "HIPPIUS_HF_ENDPOINT_ENV",
"HIPPIUS_HF_TOKEN_ENV", "HUB_REPO_TYPE", "MirrorError", "PublicStore", "RepoMirror",
"S3Mirror", "hf_mirror", "hippius_hf_endpoint", "hub_mirror", "open_index_store",
"open_live_mirrors", "open_live_vault", "r2_bucket"]
20 changes: 18 additions & 2 deletions cascade/lane_d/publish.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,25 @@ def __init__(self, code: str, detail: str = ""):
self.detail = detail


# An OCI distribution repository name: lowercase path components only. The
# Hippius registry (Harbor) answers 401 "un-recognized request" for ANY call on
# a name with an uppercase letter (live 2026-12-01: the first king publish
# failed on ``cascade/laned-king-c4096-5HpKLEju/manifests/main``), so a king's
# repo carries the lowercased hotkey prefix.
OCI_REPO_RE = re.compile(r"^[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*"
r"(?:/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)+$")


def hub_repo(ns: str, context: int, hotkey: str) -> str:
"""§11.1: the public Hub repository of a king."""
return f"{ns}/laned-king-c{int(context)}-{str(hotkey)[:8]}"
"""§11.1: the public Hub repository of a king,
``{ns}/laned-king-c{context}-{hotkey8}`` with ``hotkey8`` the LOWERCASED
first 8 characters of the ss58 hotkey (an OCI repository name is lowercase).
``ValueError`` when the result is still not a valid OCI repository name."""
repo = f"{ns}/laned-king-c{int(context)}-{str(hotkey)[:8].lower()}"
if not OCI_REPO_RE.match(repo):
raise ValueError(f"{repo!r} is not a valid OCI repository name (lowercase "
f"[a-z0-9] components separated by '.', '_', '__' or '-')")
return repo


def king_mirror_names(names=None) -> tuple[str, ...]:
Expand Down
48 changes: 32 additions & 16 deletions cascade/miner/lane_d_pull_king.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"""``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).
one) from the Hippius Hub 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}``
``{[storage] hub_namespace}/laned-king-c{context}-{hotkey8}`` (``hotkey8`` lowercased)
(: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,
Expand All @@ -16,8 +16,11 @@
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
3. pulls the king's ``manifest.json`` from its Hub repo ANONYMOUSLY through
``huggingface_hub.HfApi(endpoint=https://hub.hippius.com, token=False)``
(the Hippius Hub serves models over the huggingface_hub API since
2026-12-01; the endpoint is per instance, ``HF_ENDPOINT`` / ``HF_TOKEN``
are never read or set, and no ambient credential is sent) 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;
Expand Down Expand Up @@ -82,7 +85,7 @@ def _intake():
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.")
"Hub, 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).")
Expand Down Expand Up @@ -217,16 +220,28 @@ def pick_king(index: dict, digest: str | None = None) -> dict:
# ── the Hub pull ────────────────────────────────────────────────────────────


HIPPIUS_HUB_ENDPOINT = "https://hub.hippius.com"
HIPPIUS_HUB_ENDPOINT_ENV = "HIPPIUS_HF_ENDPOINT"


def hub_endpoint() -> str:
"""The Hippius Hub endpoint: ``HIPPIUS_HF_ENDPOINT`` (an override for a
mirror or testnet) or :data:`HIPPIUS_HUB_ENDPOINT`. Never ``HF_ENDPOINT``."""
return str(os.environ.get(HIPPIUS_HUB_ENDPOINT_ENV) or HIPPIUS_HUB_ENDPOINT).rstrip("/")


def anonymous_hub_api():
"""``hippius_hub.HippiusApi`` with the anonymous sentinel ``token=False``:
no env token, cached login or docker credential is consulted."""
"""``huggingface_hub.HfApi`` on the Hippius Hub endpoint with the anonymous
sentinel ``token=False``: no env token or cached login is consulted, and
the endpoint is this instance's only (the global ``HF_ENDPOINT`` is not
touched)."""
try:
from hippius_hub import HippiusApi
from huggingface_hub import HfApi
except ImportError as e:
raise PullError("hippius_hub_missing",
f"pulling from the Hippius registry needs hippius-hub: pip install -e "
raise PullError("huggingface_hub_missing",
f"pulling from the Hippius Hub needs huggingface_hub: pip install -e "
f"'.[hippius]' ({e})", USAGE) from None
return HippiusApi(token=False)
return HfApi(endpoint=hub_endpoint(), token=False)


def _sha256_file(path: Path) -> tuple[str, int]:
Expand Down Expand Up @@ -260,18 +275,18 @@ def _download(api, repo: str, name: str, work: Path) -> Path:
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
f"{name} is not in the Hippius Hub repo {repo}") from None
if _denied(e):
raise PullError("hub_auth_required",
f"the Hippius registry refused an anonymous pull of {repo}/{name} "
f"the Hippius Hub 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}")
raise PullError("king_files_missing", f"the Hub returned no file for {repo}/{name}")
return got


Expand All @@ -298,7 +313,7 @@ def pull_king(king: dict, dest: Path, *, namespace: str, king_mirrors=None, api=
shutil.rmtree(stage, ignore_errors=True)
stage.mkdir()
try:
log(f"pulling lane D king {digest[:12]} from the Hippius registry repo {repo} "
log(f"pulling lane D king {digest[:12]} from the Hippius Hub repo {repo} "
"(anonymous)")
mpath = _download(api, repo, intake.MANIFEST_OBJECT, stage)
if mpath.stat().st_size > MAX_MANIFEST_BYTES:
Expand Down Expand Up @@ -346,6 +361,7 @@ def pull_king(king: dict, dest: Path, *, namespace: str, king_mirrors=None, api=
"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",
__all__ = ["HIPPIUS_HUB_ENDPOINT", "PullError", "add_lane_d_pull_king", "anonymous_hub_api",
"cmd_lane_d_pull_king", "hub_endpoint",
"default_index_url", "fetch_index_bytes", "load_index", "next_command",
"pick_king", "pull_king"]
5 changes: 3 additions & 2 deletions deploy/laned/systemd/cascade-laned-king-publish.service
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@
# Credentials (env names only, from the service environment, never this
# file): HIPPIUS_S3_ACCESS_KEY / HIPPIUS_S3_SECRET_KEY (vault read, index
# put; the vault read uses CASCADE_LANE_D_VAULT_ACCESS_KEY /
# CASCADE_LANE_D_VAULT_SECRET_KEY when both are set), HIPPIUS_HUB_TOKEN,
# HF_TOKEN, BACKUP_S3_ACCESS_KEY /
# CASCADE_LANE_D_VAULT_SECRET_KEY when both are set), HIPPIUS_HF_TOKEN (the
# Hippius Hub hip_ key; HIPPIUS_HF_ENDPOINT optional), HF_TOKEN (HF mirror
# only), BACKUP_S3_ACCESS_KEY /
# BACKUP_S3_SECRET_KEY (R2). Ships in --dry-run; going live is a drop-in
# without --dry-run. Log tag lane_d_ops_king_publish_* / lane_d_ops_king_published.

Expand Down
Loading
Loading