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 large chunks on the merged path and make read_at thread-safe
Follow-up to d3b0c59. Only chunks smaller than a block are now read
through the block cache. A small read of a large chunk (e.g. one
transmit of tue-aaa in a 5 MB chunk) went out as one request per
1 MiB block, one after another, which cut throughput from ~3 to
~0.6 frames/s. It is one merged request again.

RemoteFile.read_at now reads aligned blocks through _SharedBlocks
instead of the fsspec cache, so concurrent reads are safe with any
cache_type (the "readahead" cache keeps state per read). The first
block is only prefetched on open when something keeps it: the chunk
cache, or a cache_type other than "none".
  • Loading branch information
tristan-deep committed Nov 2, 2026
commit e465a911713ea53e6a6064a6c2660babae74e35d
42 changes: 42 additions & 0 deletions tests/data/test_hf_remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,3 +233,45 @@ def test_open_uses_cached_first_block(small_cdn):
with File(HF_PATH, progress=False) as remote:
remote[RAW].shape
assert small_cdn.server.count == before


def test_small_reads_of_large_chunks_stay_one_request(small_cdn):
"""A small read whose chunk spans several blocks is one request, not one per block."""
with File(HF_PATH, progress=False, block_size=1024) as remote, File(small_cdn.path) as local:
dset = remote[RAW]
assert dset.id.get_chunk_info(0).size > 4 * 1024
before = small_cdn.server.count
got = chunk_reader.read(dset, 0, remote._chunk_fetcher)
np.testing.assert_array_equal(got, local[RAW][0])
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."""
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
for offset, size in [(0, 1), (100, 5000), (4095, 2), (len(expected) - 10, 50)]:
assert stream.read_at(offset, size) == expected[offset : offset + size]


def test_no_prefetch_when_nothing_keeps_the_block(small_cdn, monkeypatch):
"""With cache_type="none" and no chunk cache, prefetching the first block on open would
be a request nothing reuses."""
calls = []
original = hf_remote.RemoteFile.read_at
monkeypatch.setattr(
hf_remote.RemoteFile, "read_at", lambda self, *a: calls.append(a) or original(self, *a)
)
with File(HF_PATH, progress=False, cache=False, cache_type="none") as remote:
remote[RAW].shape
assert calls == []
with File(HF_PATH, progress=False, cache=False) as remote:
remote[RAW].shape
assert calls == [(0, 1)]
1 change: 1 addition & 0 deletions zea/data/chunk_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ def __init__(self, fileobj, cache: "ChunkCache", block_size: int | None = None):
self._file = fileobj
self._cache = cache
self._block = block_size or getattr(fileobj, "blocksize", None) or _HF_STREAM_BLOCK_SIZE
self.blocksize = self._block
self._pos = 0
self.size = fileobj.size
#: Passed through: this is where the chunk fetcher reads the file's content hash from.
Expand Down
23 changes: 15 additions & 8 deletions zea/data/chunk_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,20 +495,27 @@ async def gather() -> None:
def fetch_small(
self, ranges: Sequence[tuple[int, int]], on_bytes: Ticker = None
) -> list[bytes]:
"""Serve a small read from the blocks of :attr:`blocks`, like h5py would.
"""Serve the chunks of a small read that are smaller than a block from the blocks of
:attr:`blocks`, like h5py would.

Small chunks are often many to a block (e.g. ~70 frames per 1 MiB), so a run of small
reads then costs one request per block instead of one per read, and the blocks land in
the same in-memory and on-disk caches h5py's own reads use.
the same in-memory and on-disk caches h5py's own reads use. Larger chunks (e.g. one
transmit stored in a 7 MB chunk) go through :meth:`fetch`, as one request instead of a
request per block.
"""
if self.blocks is None:
return self.fetch(ranges, on_bytes)
out = []
for offset, size in ranges:
out.append(self.blocks.read_at(int(offset), int(size)))
if on_bytes is not None:
on_bytes(int(size))
return out
out: list[bytes | None] = [None] * len(ranges)
large = [i for i, (_, size) in enumerate(ranges) if size >= self.blocks.blocksize]
for i, data in zip(large, self.fetch([ranges[i] for i in large], on_bytes)):
out[i] = data
for i, (offset, size) in enumerate(ranges):
if out[i] is None:
out[i] = self.blocks.read_at(int(offset), int(size))
if on_bytes is not None:
on_bytes(int(size))
return cast(list[bytes], out)

def read_range(self, offset: int, size: int) -> bytes:
"""Fetch one range without the chunk cache, merging or byte counting.
Expand Down
6 changes: 5 additions & 1 deletion zea/data/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -1083,6 +1083,8 @@ def __init__(self, name, mode="r", *args, **kwargs):

# File object opened for streaming; kept so we can close it in close().
stream_fileobj = None
# Whether the stream keeps the blocks it reads, so prefetching one pays off.
keeps_blocks = False
# Original source path, retained for streamed files whose ``filename`` is
# just a placeholder for the underlying file object (see ``path``).
source_name = None
Expand All @@ -1107,6 +1109,7 @@ def __init__(self, name, mode="r", *args, **kwargs):
hf_kwargs.pop("cache_dir", None)
source_name = str(name)
stream_fileobj = _hf_stream_open(str(name), **hf_kwargs)
keeps_blocks = hf_kwargs.get("cache_type") != "none"

# Serve the HDF5 metadata h5py walks on open from the cache too, not just the
# data chunks: it is the same file, and re-opening otherwise re-fetches it every
Expand All @@ -1117,6 +1120,7 @@ def __init__(self, name, mode="r", *args, **kwargs):
chunk_cache = cache_for(getattr(stream_fileobj, "details", None) or {})
if chunk_cache is not None:
stream_fileobj = CachedFile(stream_fileobj, chunk_cache)
keeps_blocks = True

name = stream_fileobj
elif is_hf:
Expand All @@ -1138,7 +1142,7 @@ def __init__(self, name, mode="r", *args, **kwargs):
# h5py opens the file and takes its global lock, so threads opening different
# files fetch in parallel instead of one after another. Reading one byte fetches
# the whole block, from the chunk cache if it is there.
if hasattr(stream_fileobj, "read_at"):
if keeps_blocks and hasattr(stream_fileobj, "read_at"):
stream_fileobj.read_at(0, 1)
super().__init__(name, mode, *args, **kwargs)
except Exception:
Expand Down
22 changes: 16 additions & 6 deletions zea/data/hf_remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,18 +313,28 @@ def _fetch(self, start: int, end: int) -> bytes:
return data

def read_at(self, offset: int, size: int) -> bytes:
"""Read ``size`` bytes at ``offset`` through the block cache, without moving the file
position. Safe to call from several threads.
"""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"``).
"""
end = min(self.size, offset + size)
if end <= offset:
return b""
return self._cache._fetch(offset, end)
out = bytearray()
pos = offset
while pos < end:
start = pos - pos % self.blocksize
block = self._fetch(start, min(start + self.blocksize, self.size))
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
data = self.read_at(self._pos, length)
end = min(self.size, self._pos + length)
if end <= self._pos:
return b""
data = self._cache._fetch(self._pos, end)
self._pos += len(data)
return data

Expand Down
Loading