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
Keep one block cache per streamed file instead of two
RemoteFile kept an fsspec block cache per handle for h5py's reads (up to 32 MiB each, times
up to 128 open handles per worker) next to the shared LRU that read_at used. read() now goes
through read_at as well, so all reads share the same blocks and the fsspec cache layer is
gone. cache_type keeps its meaning: "none" reads exactly the requested bytes, and any
other fsspec cache type keeps whole blocks. Unknown cache types now raise on open.
  • Loading branch information
tristan-deep committed Nov 4, 2026
commit afcc0ef9ce2e92fcec35542cf4246ea44219d8dd
35 changes: 23 additions & 12 deletions tests/data/test_hf_remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,19 +301,29 @@ def test_small_reads_of_large_chunks_stay_one_request(small_cdn):
assert small_cdn.server.count - before == dset.id.get_num_chunks() // dset.shape[0]


def test_read_at_bypasses_the_fsspec_cache(small_cdn):
"""Positional reads go through the locked shared blocks, never the per-handle fsspec
cache: some cache types keep state per read (e.g. "readahead"), which concurrent
reads would corrupt."""
@pytest.mark.parametrize("cache_type", ["blockcache", "none"])
def test_reads_match_the_file(small_cdn, cache_type):
expected = small_cdn.path.read_bytes()
stream = hf_remote.open_remote(HF_PATH, block_size=4096, cache_type="readahead")

def unsafe(*args):
raise AssertionError("read_at went through the fsspec cache")

stream._cache._fetch = unsafe
stream = hf_remote.open_remote(HF_PATH, block_size=4096, cache_type=cache_type)
for offset, size in [(0, 1), (100, 5000), (4095, 2), (len(expected) - 10, 50)]:
assert stream.read_at(offset, size) == expected[offset : offset + size]
stream.seek(4000)
assert stream.read(200) == expected[4000:4200] and stream.tell() == 4200


def test_read_shares_the_blocks_of_read_at(small_cdn):
"""h5py's reads and the chunk reader's positional reads use the same blocks."""
stream = hf_remote.open_remote(HF_PATH, block_size=4096)
stream.read_at(0, 10)
before = small_cdn.server.count
stream.seek(100)
stream.read(1000)
assert small_cdn.server.count == before


def test_unknown_cache_type_raises(small_cdn):
with pytest.raises(ValueError, match="cache_type"):
hf_remote.open_remote(HF_PATH, cache_type="nope")


def test_no_prefetch_when_nothing_keeps_the_block(small_cdn, monkeypatch):
Expand All @@ -326,10 +336,11 @@ def test_no_prefetch_when_nothing_keeps_the_block(small_cdn, monkeypatch):
)
with File(HF_PATH, progress=False, cache=False, cache_type="none") as remote:
remote[RAW].shape
assert calls == []
assert (0, 1) not in calls # h5py's own reads go through read_at too
calls.clear()
with File(HF_PATH, progress=False, cache=False) as remote:
remote[RAW].shape
assert calls == [(0, 1)]
assert calls[0] == (0, 1)


def test_small_reads_draw_no_progress_bar(small_cdn, monkeypatch):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_preset_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,7 @@ def no_byte_reads(monkeypatch):
"""Answer the streamed file's reads (e.g. its metadata prefetch) without a network."""
from zea.data import hf_remote

monkeypatch.setattr(hf_remote.RemoteFile, "_fetch", lambda self, start, end: bytes(end - start))
monkeypatch.setattr(hf_remote.RemoteFile, "_block", lambda self, start: bytes(self.blocksize))


def test_stream_open_retries_after_login(monkeypatch, no_byte_reads):
Expand Down
2 changes: 1 addition & 1 deletion tests/tools/test_hf.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ def fake_metadata(url, **kw):
return SimpleNamespace(location="https://cdn.example/x", etag="e", commit_hash="c", size=10)

monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", fake_metadata)
monkeypatch.setattr(hf_remote.RemoteFile, "_fetch", lambda self, start, end: bytes(end - start))
monkeypatch.setattr(hf_remote.RemoteFile, "_block", lambda self, start: bytes(self.blocksize))

result = _hf_stream_open(FILE_STR, block_size=1234, **kwargs)
assert heads == [f"{constants.ENDPOINT}/{expected_url_path}"]
Expand Down
7 changes: 4 additions & 3 deletions zea/data/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -1029,9 +1029,10 @@ def __init__(self, name, mode="r", *args, **kwargs):
coalesces more chunk reads into a single HTTP request — faster for
whole-frame reads, at the cost of more over-fetch for sparse reads.
Only used when ``name`` starts with ``hf://`` and ``stream=True``.
cache_type (str, optional): fsspec cache strategy for streaming reads
(default ``"blockcache"``). Only used when ``name`` starts with
``hf://`` and ``stream=True``.
cache_type (str, optional): ``"none"`` to read exactly the requested bytes when
streaming, instead of whole blocks that are kept for later reads (any other
fsspec cache type, default ``"blockcache"``). Only used when ``name`` starts
with ``hf://`` and ``stream=True``.
progress (bool or callable, optional): Report progress while streaming chunks.
Also settable after opening (``file.progress = True``). Defaults to ``True``
for streamed files, ``False`` otherwise. Reads that fall back to h5py
Expand Down
57 changes: 32 additions & 25 deletions zea/data/hf_remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,14 +327,13 @@ def clear(self) -> None:
class RemoteFile:
"""Read-only file object over a :class:`SignedURL`, passed to h5py.

Uses an fsspec block cache so h5py's many small metadata reads become a few requests, and
shares fetched blocks with other handles of the same file (:class:`_SharedBlocks`).
Requests go through :class:`~zea.data.chunk_reader.HTTPFetcher` for retries and URL refresh.
Reads whole blocks, so h5py's many small metadata reads become a few requests, and keeps
them in :class:`_SharedBlocks`, shared with other handles of the same file. With
``keep_blocks=False`` it reads exactly the requested bytes instead. Requests go through
:class:`~zea.data.chunk_reader.HTTPFetcher` for retries and URL refresh.
"""

def __init__(self, location: SignedURL, block_size: int, cache_type: str = "blockcache"):
import fsspec.caching

def __init__(self, location: SignedURL, block_size: int, keep_blocks: bool = True):
from zea.data.chunk_reader import HTTPFetcher

self.location = location
Expand All @@ -343,42 +342,41 @@ def __init__(self, location: SignedURL, block_size: int, cache_type: str = "bloc
#: fsspec-style file info. The chunk cache uses the etag as its key.
self.details = {"name": location.hf_path, "size": self.size, "etag": location.etag}
self._fetcher = HTTPFetcher(location)
self._cache = fsspec.caching.caches[cache_type](block_size, self._fetch, self.size)
self._keep_blocks = keep_blocks
# Without an etag, blocks of other handles may be other content: keep them per handle.
self._blocks_key = location.etag or object()
self._pos = 0
self._closed = False

def _fetch(self, start: int, end: int) -> bytes:
key = (self.location.etag, start, end)
if key[0] is not None and (hit := _shared_blocks.get(key)) is not None:
def _block(self, start: int) -> bytes:
end = min(start + self.blocksize, self.size)
key = (self._blocks_key, start, end)
if (hit := _shared_blocks.get(key)) is not None:
return hit
data = self._fetcher.read_range(start, end - start)
if key[0] is not None:
_shared_blocks.put(key, data)
_shared_blocks.put(key, data)
return data

def read_at(self, offset: int, size: int) -> bytes:
"""Read ``size`` bytes at ``offset`` without moving the file position.

Safe to call from several threads: reads whole blocks through :class:`_SharedBlocks`,
not through the fsspec cache, which may keep state per read (e.g. ``"readahead"``).
"""
"""Read ``size`` bytes at ``offset`` without moving the file position. Thread-safe."""
end = min(self.size, offset + size)
if end <= offset:
return b""
if not self._keep_blocks:
return self._fetcher.read_range(offset, end - offset)
out = bytearray()
pos = offset
while pos < end:
start = pos - pos % self.blocksize
block = self._fetch(start, min(start + self.blocksize, self.size))
block = self._block(start)
out += block[pos - start : end - start]
pos = start + len(block)
return bytes(out)

def read(self, length: int = -1) -> bytes:
if length is None or length < 0:
length = self.size - self._pos
end = min(self.size, self._pos + length)
if end <= self._pos:
return b""
data = self._cache._fetch(self._pos, end)
data = self.read_at(self._pos, length)
self._pos += len(data)
return data

Expand Down Expand Up @@ -414,12 +412,21 @@ def open_remote(
block_size: int | None = None,
cache_type: str | None = None,
) -> RemoteFile:
"""Open an ``hf://`` file for streaming reads."""
from zea.internal.preset_utils import _HF_STREAM_BLOCK_SIZE, _HF_STREAM_CACHE_TYPE
"""Open an ``hf://`` file for streaming reads.

``cache_type="none"`` reads exactly the requested bytes; any other fsspec cache type
reads and keeps whole blocks (see :class:`RemoteFile`).
"""
import fsspec.caching

from zea.internal.preset_utils import _HF_STREAM_BLOCK_SIZE

known = {name for name in fsspec.caching.caches if name}
if cache_type is not None and cache_type not in known:
raise ValueError(f"Unknown cache_type {cache_type!r}; expected one of {sorted(known)}.")
location = SignedURL(hf_path, revision=revision, repo_type=repo_type)
return RemoteFile(
location,
block_size=block_size or _HF_STREAM_BLOCK_SIZE,
cache_type=cache_type or _HF_STREAM_CACHE_TYPE,
keep_blocks=cache_type != "none",
)
10 changes: 5 additions & 5 deletions zea/internal/preset_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,6 @@ def _hf_resolve_path(hf_path: str, cache_dir=None, repo_type="dataset", **kwargs
# This file object only serves h5py's metadata reads; chunk_reader fetches the array chunks
# itself. The paged layout keeps that metadata to ~0.26 MB in one request, so the block just has
# to cover it. Keep it aligned with chunk_cache.CachedFile's block size. Overridable via File().
_HF_STREAM_CACHE_TYPE = "blockcache"
_HF_STREAM_BLOCK_SIZE = 1024 * 1024 # 1 MiB


Expand Down Expand Up @@ -519,13 +518,14 @@ def _hf_stream_open(
repository default branch.
repo_type (str, optional): One of ``"dataset"``, ``"model"`` or
``"space"``. Defaults to ``"dataset"``.
block_size (int, optional): Block size in bytes for the fsspec cache.
block_size (int, optional): Block size in bytes of streamed reads.
Larger blocks coalesce more chunk reads per HTTP request (faster for
whole-frame reads, more over-fetch for sparse reads). Defaults to
:data:`_HF_STREAM_BLOCK_SIZE`.
cache_type (str, optional): fsspec cache strategy. Defaults to
:data:`_HF_STREAM_CACHE_TYPE` (``"blockcache"``), which caches touched
blocks so the many small chunks of a frame share a few requests.
cache_type (str, optional): ``"none"`` reads exactly the requested bytes. Any other
fsspec cache type (default ``"blockcache"``) reads and keeps whole blocks, shared
by all handles of the file, so the many small chunks of a frame share a few
requests.

Returns:
An open, seekable binary file object. The caller is responsible for
Expand Down