"""Job repos on the Hugging Face Hub, with a lease so only one Kaggle session writes a job at a time. Every job has its own repo. Every commit to it is a compare-and-swap on the head the holder last saw (HF `parent_commit`), and every commit also rewrites `lease.json`. So a session whose lease expired and was taken over cannot write again: its next commit fails, and it stops. The local filesystem store implements the same contract for tests. """ from __future__ import annotations import json import os import shutil import threading import time from dataclasses import asdict, dataclass from pathlib import Path from typing import Protocol import httpx LEASE_FILE = "lease.json" HTTP_TIMEOUT = httpx.Timeout(connect=30.0, read=300.0, write=300.0, pool=60.0) def use_http_timeouts() -> None: """huggingface_hub's default client never times out; a half-open connection would hang a session (and its lease) until Kaggle kills it.""" from huggingface_hub import set_client_factory set_client_factory(lambda: httpx.Client(timeout=HTTP_TIMEOUT, follow_redirects=True)) class Conflict(Exception): """The repo head moved since we last read it.""" class TransientError(Exception): """A network or server error worth retrying.""" class LeaseLost(Exception): """Another session holds this job now. Stop without writing.""" Adds = dict[str, "Path | bytes"] class Store(Protocol): name: str def ensure(self) -> None: ... def head(self) -> str | None: ... def read_text(self, path: str, revision: str | None = None) -> str | None: ... def download(self, patterns: list[str], local_dir: Path, revision: str | None = None) -> Path: ... def list_files(self, revision: str | None = None) -> list[str]: ... def commit(self, adds: Adds, deletes: list[str], message: str, parent: str | None) -> str: ... def squash(self) -> None: ... def _matches(path: str, patterns: list[str]) -> bool: from fnmatch import fnmatch return any(fnmatch(path, p) or path.startswith(p.rstrip("*")) and p.endswith("/**") for p in patterns) class LocalStore: """A directory that behaves like a single-branch repo with compare-and-swap commits.""" _locks: dict[str, threading.Lock] = {} def __init__(self, root: str | os.PathLike, name: str): self.name = name self.root = Path(root) / name.replace("/", "__") self._lock = LocalStore._locks.setdefault(str(self.root), threading.Lock()) def ensure(self) -> None: (self.root / "files").mkdir(parents=True, exist_ok=True) if not (self.root / "HEAD").exists(): (self.root / "HEAD").write_text("0") def head(self) -> str | None: p = self.root / "HEAD" return p.read_text() if p.exists() else None def read_text(self, path: str, revision: str | None = None) -> str | None: p = self.root / "files" / path return p.read_text(encoding="utf-8") if p.is_file() else None def list_files(self, revision: str | None = None) -> list[str]: base = self.root / "files" if not base.exists(): return [] return sorted(p.relative_to(base).as_posix() for p in base.rglob("*") if p.is_file()) def download(self, patterns: list[str], local_dir: Path, revision: str | None = None) -> Path: local_dir = Path(local_dir) for rel in self.list_files(): if _matches(rel, patterns): dst = local_dir / rel dst.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(self.root / "files" / rel, dst) return local_dir def commit(self, adds: Adds, deletes: list[str], message: str, parent: str | None) -> str: with self._lock: self.ensure() current = self.head() if parent is not None and parent != current: raise Conflict(f"head is {current}, expected {parent}") base = self.root / "files" for rel in deletes: target = base / rel.rstrip("/") if target.is_dir(): shutil.rmtree(target) elif target.exists(): target.unlink() for rel, src in adds.items(): dst = base / rel dst.parent.mkdir(parents=True, exist_ok=True) tmp = dst.with_name(dst.name + ".tmp") if isinstance(src, bytes): tmp.write_bytes(src) else: shutil.copyfile(src, tmp) os.replace(tmp, dst) new = str(int(current or "0") + 1) (self.root / "HEAD").write_text(new) return new def squash(self) -> None: """History is not kept locally, so there is nothing to squash.""" LFS_MISSING = "LFS pointer pointed to a file that does not exist" class HfStore: """One model or dataset repo on the Hugging Face Hub.""" def __init__(self, repo_id: str, repo_type: str = "model", token: str | None = None, private: bool = False): from huggingface_hub import HfApi self.name = repo_id self.repo_type = repo_type self.private = private self.api = HfApi(token=token) def _call(self, fn, *args, **kwargs): from huggingface_hub.errors import HfHubHTTPError try: return fn(*args, **kwargs) except HfHubHTTPError as e: status = getattr(e.response, "status_code", None) if status in (409, 412): raise Conflict(str(e)[:300]) from e if status is None or status == 429 or status >= 500: raise TransientError(str(e)[:300]) from e if status == 400 and LFS_MISSING in str(e): # The Hub accepted the upload, then rejected the commit because it could not find the # file (opd-8k round 22, jay-synapse, 2026-11-23). Nothing landed, and a retry builds # the operations and uploads again, so treat it like a server error. raise TransientError(str(e)[:300]) from e raise except (OSError, TimeoutError, httpx.TransportError) as e: raise TransientError(f"{type(e).__name__}: {str(e)[:300]}") from e def ensure(self) -> None: self._call(self.api.create_repo, self.name, repo_type=self.repo_type, private=self.private, exist_ok=True) def head(self) -> str | None: from huggingface_hub.errors import RepositoryNotFoundError try: return self._call(self.api.repo_info, self.name, repo_type=self.repo_type).sha except RepositoryNotFoundError: return None def read_text(self, path: str, revision: str | None = None) -> str | None: from huggingface_hub import hf_hub_download from huggingface_hub.errors import EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError try: local = self._call(hf_hub_download, self.name, path, repo_type=self.repo_type, revision=revision, token=self.api.token) except (EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError): return None return Path(local).read_text(encoding="utf-8") def list_files(self, revision: str | None = None) -> list[str]: return self._call(self.api.list_repo_files, self.name, repo_type=self.repo_type, revision=revision) def download(self, patterns: list[str], local_dir: Path, revision: str | None = None) -> Path: from huggingface_hub import snapshot_download path = self._call(snapshot_download, self.name, repo_type=self.repo_type, revision=revision, allow_patterns=patterns, local_dir=str(local_dir), token=self.api.token) return Path(path) def _file_deletes(self, deletes: list[str], adds: Adds, parent: str | None) -> list[str]: """The files to delete: a folder ("dir/") becomes the files under it at `parent`, and paths this commit also adds are left out. With a folder delete and adds inside it in one commit, the Hub lost 30 of the 58 re-added files (ops publish-code before smoke v4, D-024).""" listed = self.list_files(revision=parent) if any(p.endswith("/") for p in deletes) else [] paths = {f for p in deletes for f in ([x for x in listed if x.startswith(p)] if p.endswith("/") else [p])} return sorted(paths - set(adds)) def commit(self, adds: Adds, deletes: list[str], message: str, parent: str | None) -> str: from huggingface_hub import CommitOperationAdd, CommitOperationDelete ops = [CommitOperationDelete(path_in_repo=p) for p in self._file_deletes(deletes, adds, parent)] ops += [CommitOperationAdd(path_in_repo=p, path_or_fileobj=src if isinstance(src, bytes) else str(src)) for p, src in adds.items()] info = self._call(self.api.create_commit, self.name, operations=ops, commit_message=message, parent_commit=parent, repo_type=self.repo_type) return info.oid def squash(self) -> None: """Collapse history to one commit so overwritten checkpoints stop counting against storage.""" self._call(self.api.super_squash_history, self.name, repo_type=self.repo_type, commit_message="squash history (old checkpoints)") def make_store(name: str, hub: str, repo_type: str = "model") -> Store: """hub is "hf" or "local: