Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
d646442
Stream hf:// files from the CDN to avoid Hub rate limits (#664)
tristan-deep Oct 26, 2026
62e40e6
Validate ZEA_MAX_CONCURRENT_REQUESTS and keep the retry log off the e…
tristan-deep Oct 26, 2026
bde3508
Redact signed URLs in fsspec's HTTP debug log
tristan-deep Oct 26, 2026
1f4122d
fixed potential burst of requests on ttl expiry
Louisvh Oct 29, 2026
4bb3aee
Merge branch 'main' into feature/hf-cdn-streaming
tristan-deep Nov 2, 2026
d3b0c59
improve fetching of small chunks
tristan-deep Nov 2, 2026
e465a91
Keep large chunks on the merged path and make read_at thread-safe
tristan-deep Nov 2, 2026
d378820
Merge remote-tracking branch 'origin/main' into feature/hf-cdn-streaming
tristan-deep Nov 4, 2026
cd2bcb6
Drop cached CDN URLs on upload and reuse branch URLs only as long as …
tristan-deep Nov 4, 2026
206600e
Ask the Hub at most once per cooldown when a URL refresh gives nothin…
tristan-deep Nov 4, 2026
9e9954e
Keep using the current URL when its early refresh fails
tristan-deep Nov 4, 2026
a138178
Redact signed URLs in the errors of failed range requests
tristan-deep Nov 4, 2026
0a2ba87
Draw no progress bar for reads below MIN_BYTES
tristan-deep Nov 4, 2026
68c62c7
Check the chunk cache with a stat in pending_bytes
tristan-deep Nov 4, 2026
7b3d0ec
Fetch the blocks of a small read concurrently
tristan-deep Nov 4, 2026
3f43635
Merge ranges only while a request downloads no more gap bytes than ch…
tristan-deep Nov 4, 2026
afcc0ef
Keep one block cache per streamed file instead of two
tristan-deep Nov 4, 2026
dca16d0
Ask the stream whether it keeps the blocks it reads
tristan-deep Nov 4, 2026
dcd792d
Share the on-disk cache helpers of the Hub listing and the CDN URLs
tristan-deep Nov 4, 2026
3fcd16b
Merge branch 'main' into feature/hf-cdn-streaming
tristan-deep Nov 4, 2026
08f275f
Merge branch 'main' into feature/hf-cdn-streaming
swpenninga Nov 4, 2026
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
Prev Previous commit
Next Next commit
Share the on-disk cache helpers of the Hub listing and the CDN URLs
The token hashing and the JSON disk cache (TTL check, private atomic write, logged failure)
were written out twice, in preset_utils and hf_remote. They are now _hf_token_id and
zea.internal.utils.load_json_cache / store_json_cache.
  • Loading branch information
tristan-deep committed Nov 4, 2026
commit dcd792d97cbc74707c7fd5ea2098fe6f9c61fce4
32 changes: 9 additions & 23 deletions zea/data/hf_remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
from __future__ import annotations

import hashlib
import json
import re
import threading
import time
Expand All @@ -36,7 +35,7 @@

from zea import log
from zea.internal.cache import ZEA_CACHE_DIR
from zea.internal.utils import atomic_write
from zea.internal.utils import load_json_cache, store_json_cache

#: Seconds to reuse a resolved URL. The Hub's signed URLs currently expire after about an
#: hour. If that changes, a rejected URL is resolved again anyway.
Expand Down Expand Up @@ -77,11 +76,6 @@ def fresh(self) -> bool:
return time.time() - self.resolved_at < URL_TTL


def _token_id(token: str | None) -> str:
"""Hash of the token, so cached URLs are kept per user."""
return hashlib.sha256(token.encode()).hexdigest()[:16] if token else "anonymous"


def _reusable(resolved: Resolved | None, revision: str | None) -> bool:
"""Whether a cached ``resolved`` may be used to open the file at ``revision``.

Expand All @@ -107,21 +101,13 @@ def _disk_path(key: tuple) -> Path:


def _load(key: tuple) -> Resolved | None:
try:
resolved = Resolved(**json.loads(_disk_path(key).read_text()))
except (OSError, ValueError, TypeError):
data = load_json_cache(_disk_path(key), URL_TTL)
if not isinstance(data, dict):
return None
return resolved


def _store(key: tuple, resolved: Resolved) -> None:
try:
_CACHE_DIR.mkdir(parents=True, exist_ok=True)
# atomic_write goes through mkstemp, so the file is private to this user (0600).
with atomic_write(_disk_path(key), suffix=".part") as tmp:
tmp.write_text(json.dumps(asdict(resolved)))
except OSError as exc: # the disk cache is optional
log.debug(f"Could not cache the location of a streamed file: {exc}")
return Resolved(**data)
except TypeError: # written by another version of zea
return None


def resolve(
Expand All @@ -144,13 +130,13 @@ def resolve(
"""
from huggingface_hub import constants, get_hf_file_metadata, get_token, hf_hub_url

from zea.internal.preset_utils import _hf_call, _hf_parse_path
from zea.internal.preset_utils import _hf_call, _hf_parse_path, _hf_token_id

repo_id, subpath = _hf_parse_path(hf_path)
if not subpath:
raise ValueError(f"Expected an 'hf://' path to a single file, got '{hf_path}'.")
token = get_token()
key = (constants.ENDPOINT, repo_type, repo_id, revision, subpath, _token_id(token))
key = (constants.ENDPOINT, repo_type, repo_id, revision, subpath, _hf_token_id(token))

with _memory_lock:
lock = _key_locks.setdefault(key, threading.Lock())
Expand Down Expand Up @@ -180,7 +166,7 @@ def resolve(
)
with _memory_lock:
_memory[key] = resolved
_store(key, resolved)
store_json_cache(_disk_path(key), asdict(resolved))
return resolved


Expand Down
31 changes: 13 additions & 18 deletions zea/internal/preset_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
"""

import hashlib
import json
import os
import threading
import time
Expand All @@ -28,7 +27,7 @@

from zea import log
from zea.internal.cache import ZEA_CACHE_DIR
from zea.internal.utils import atomic_write
from zea.internal.utils import load_json_cache, store_json_cache

HF_SCHEME = "hf"
HF_PREFIX = "hf://"
Expand Down Expand Up @@ -214,31 +213,27 @@ class _RepoEntry(NamedTuple):
content_id: str | None


def _hf_token_id(token: str | None) -> str:
"""Hash of a Hub token, so on-disk caches of Hub answers are kept per user."""
return hashlib.sha256(token.encode()).hexdigest()[:16] if token else "anonymous"


def _listing_path(key) -> Path:
from huggingface_hub import constants, get_token

token = get_token()
who = hashlib.sha256(token.encode()).hexdigest()[:16] if token else "anonymous"
who = _hf_token_id(get_token())
digest = hashlib.sha256(repr((constants.ENDPOINT, who, key)).encode()).hexdigest()
return _LISTING_DIR / f"{digest}.json"


def _load_listing(path: Path) -> "dict[str, _RepoEntry] | None":
try:
if time.time() - path.stat().st_mtime >= _HF_CACHE_TTL:
return None
return {name: _RepoEntry(*entry) for name, entry in json.loads(path.read_text()).items()}
except (OSError, ValueError, TypeError):
entries = load_json_cache(path, _HF_CACHE_TTL)
if not isinstance(entries, dict):
return None


def _store_listing(path: Path, listing: "dict[str, _RepoEntry]") -> None:
try:
path.parent.mkdir(parents=True, exist_ok=True)
with atomic_write(path, suffix=".part") as tmp:
tmp.write_text(json.dumps(listing))
except OSError as exc: # the disk cache is optional
log.debug(f"Could not cache the listing of a Hugging Face repo: {exc}")
return {name: _RepoEntry(*entry) for name, entry in entries.items()}
except TypeError: # written by another version of zea
return None


def _hf_repo_files(repo_id, repo_type="dataset", **kwargs) -> "dict[str, _RepoEntry]":
Expand All @@ -265,7 +260,7 @@ def _list():
if isinstance(entry, RepoFile)
}
if path is not None:
_store_listing(path, listing)
store_json_cache(path, listing)
return listing

return _LISTING_CACHE.get_or_call(key, _list)
Expand Down
30 changes: 30 additions & 0 deletions zea/internal/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,36 @@ def atomic_write(path, suffix=None):
raise


def load_json_cache(path, max_age: float):
"""The JSON stored at `path` by :func:`store_json_cache`, or ``None`` if it is missing,
unreadable or older than `max_age` seconds."""
import json
import time

path = Path(path)
try:
if time.time() - path.stat().st_mtime >= max_age:
return None
return json.loads(path.read_text())
except (OSError, ValueError):
return None


def store_json_cache(path, data) -> None:
"""Store `data` as JSON at `path`, readable only by this user, for
:func:`load_json_cache`. A failure is logged, not raised: the cache is optional."""
import json

path = Path(path)
try:
path.parent.mkdir(parents=True, exist_ok=True)
# atomic_write goes through mkstemp, so the file is private to this user (0600).
with atomic_write(path, suffix=".part") as tmp:
tmp.write_text(json.dumps(data))
except OSError as exc:
log.debug(f"Could not write the cache file {path}: {exc}")


def calculate_file_hash(file_path, omit_line_str=None):
"""Calculates the hash of a file.

Expand Down
Loading