aafimalek2032's picture
code 5b89341e29f5
4f61b8a verified
Raw History Blame Contribute Delete
15.3 kB
"""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:<dir>"."""
if hub == "hf":
return HfStore(name, repo_type=repo_type, token=os.environ.get("HF_TOKEN") or None)
if hub.startswith("local:"):
return LocalStore(hub.split(":", 1)[1], name)
raise ValueError(f"unknown hub {hub!r}: use 'hf' or 'local:<dir>'")
@dataclass(frozen=True)
class Lease:
session: str
user: str
seq: int
heartbeat: float
released: bool = False
def held_by_other(self, session: str, now: float, ttl: float) -> bool:
return not self.released and self.session != session and now - self.heartbeat < ttl
@staticmethod
def parse(text: str | None) -> Lease | None:
if not text:
return None
d = json.loads(text)
return Lease(d["session"], d.get("user", "?"), int(d.get("seq", 0)), float(d["heartbeat"]),
bool(d.get("released", False)))
class JobHandle:
"""The single writer of one job repo for as long as it holds the lease."""
def __init__(self, store: Store, session: str, user: str, ttl: float = 2700.0, retries: int = 6,
clock=time.time, sleep=time.sleep):
self.store = store
self.session = session
self.user = user
self.ttl = ttl
self.retries = retries
self.clock = clock
self.sleep = sleep
self.head: str | None = None
self.seq = 0
self.lost = threading.Event()
self._lock = threading.RLock()
def try_claim(self) -> bool:
self.store.ensure()
head = self.store.head()
lease = Lease.parse(self.store.read_text(LEASE_FILE, revision=head))
if lease and lease.held_by_other(self.session, self.clock(), self.ttl):
return False
with self._lock:
self.head, self.seq, self.lost = head, lease.seq if lease else 0, threading.Event()
try:
self.commit({}, "claim")
except LeaseLost:
return False
return True
def _lease_bytes(self, released: bool) -> bytes:
lease = Lease(self.session, self.user, self.seq, self.clock(), released)
return json.dumps(asdict(lease)).encode()
def _lease_at_head(self) -> tuple[str | None, Lease | None]:
head = self.store.head()
return head, Lease.parse(self.store.read_text(LEASE_FILE, revision=head))
def commit(self, adds: Adds, message: str, deletes: list[str] | None = None, released: bool = False) -> None:
with self._lock:
if self.lost.is_set():
raise LeaseLost(self.store.name)
self.seq += 1
payload = {**adds, LEASE_FILE: self._lease_bytes(released)}
delay, transient, adopted = 5.0, 0, False
while True:
try:
self.head = self.store.commit(payload, list(deletes or []), message, parent=self.head)
return
except Conflict:
# Every writer rewrites lease.json, so a head whose lease is still ours means
# only our own commits landed since self.head: this one (same seq), or an
# earlier one whose response was lost (lower seq), which we adopt once.
head, lease = self._lease_at_head()
ours = lease is not None and lease.session == self.session and lease.seq <= self.seq
if not ours or (adopted and lease.seq < self.seq):
self.lost.set()
raise LeaseLost(self.store.name) from None
self.head = head
if lease.seq == self.seq:
return
adopted = True
except TransientError:
if transient == self.retries:
raise
transient += 1
self.sleep(delay)
delay = min(delay * 2, 120.0)
def heartbeat(self) -> None:
self.commit({}, "heartbeat")
def squash(self) -> None:
with self._lock:
if self.lost.is_set():
raise LeaseLost(self.store.name)
try:
self.store.squash()
except TransientError as e:
print(f"history squash skipped: {e}", flush=True)
self.head = self.store.head()
def read_json(self, path: str, default=None):
text = self.store.read_text(path, revision=self.head)
return json.loads(text) if text else default
class Heartbeat(threading.Thread):
"""Renews the lease every `interval` seconds until stopped or the lease is lost."""
def __init__(self, handle: JobHandle, interval: float = 600.0, log=print):
super().__init__(daemon=True)
self.handle = handle
self.interval = interval
self.log = log
self._stop_event = threading.Event()
def run(self) -> None:
while not self._stop_event.wait(self.interval):
try:
self.handle.heartbeat()
except LeaseLost:
self.log(f"lease lost on {self.handle.store.name}; stopping")
return
except Exception as e: # noqa: BLE001 - a failed heartbeat retries next interval
self.log(f"heartbeat failed: {type(e).__name__}: {str(e)[:200]}")
def stop(self) -> None:
self._stop_event.set()