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
Next Next commit
Stream hf:// files from the CDN to avoid Hub rate limits (#664)
Streaming sent every chunk read through the Hub's /resolve/ URL, and every
such request counts toward the Hugging Face rate limit. Shuffled,
multi-worker training hit HTTP 429 within minutes.

- Resolve each file once with huggingface_hub.get_hf_file_metadata and send
  range reads straight to the signed CDN URL, which is not rate limited.
  URLs are cached in memory and on disk, refreshed on expiry or rejection,
  pinned to the first commit, and never sent the Hub token
  (zea/data/hf_remote.py).
- Merge nearby chunk reads into one request (a frame is now one request,
  not ~8).
- Share repo listings between processes through a disk cache with the
  existing ZEA_HF_CACHE_TTL.
- Fix two multi-thread slowdowns: small remote reads no longer go through
  h5py block by block, and file metadata blocks are shared between handles
  and prefetched before h5py opens the file.
- Add ZEA_MAX_CONCURRENT_REQUESTS (default 64, was a hard-coded 16) and
  ZEA_FIND_H5_SHAPES_WORKERS (default 32, was one process per core).
- Turn the chunk cache warning into an info note, and stop recommending
  lazy=False for training.
- Keep the on-disk location and listing caches of a test session in a temp
  dir, since CI runners share one ZEA_CACHE_DIR.
  • Loading branch information
tristan-deep committed Oct 26, 2026
commit d646442e1afdba844387c2f088c41c80e8dad718
13 changes: 13 additions & 0 deletions docs/source/environment.rst
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ Here are the environment variables that ``zea`` uses at runtime. Arguably the mo
(reading HDF5 file shapes, and validating files against the zea format).
- ``1``
- ``0``, ``1``
* - ``ZEA_FIND_H5_SHAPES_WORKERS``
- Number of worker processes for those parallel sweeps. The sweeps mostly wait on file
opens (over the network for ``hf://`` files), so more processes than this rarely help,
and each one has to import ``zea``. Never more than the number of cores or files.
- ``32``
- Any positive integer.
* - ``ZEA_TEST_DEVICE``
- Can be used to only run the tests with a particular device.
- ``auto:1``
Expand All @@ -69,6 +75,13 @@ Here are the environment variables that ``zea`` uses at runtime. Arguably the mo
- Byte budget for that cache; least-recently-used chunks are evicted once it is exceeded.
- ``10737418240`` (10 GiB)
- Any positive integer (bytes).
* - ``ZEA_MAX_CONCURRENT_REQUESTS``
- Maximum number of HTTP range requests in flight at once per process while streaming
(``hf://``), shared by all open files and dataloaders. Streamed reads go to the Hugging
Face CDN, which is not rate limited, so this only bounds connections and memory. Raise
it when many dataloader threads stream at once; lower it on a slow or shared connection.
- ``64``
- Any positive integer.
* - ``BLOSC_NTHREADS``
- Threads Blosc uses within a single HDF5 chunk, which is most of the write throughput
(~4x). Turn it **down** when writes are already parallel (several dataloader workers each
Expand Down
17 changes: 17 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,23 @@ def pytest_terminal_summary(terminalreporter, exitstatus, config):
terminalreporter.write_line(f"{count} requiring {', '.join(required_backends)}")


@pytest.fixture(scope="session", autouse=True)
def _isolated_hf_caches(tmp_path_factory):
"""Keep the on-disk HF location and listing caches of this session in a temp dir.

Tests mock repos (some under real names), and CI runners share one ZEA_CACHE_DIR
between concurrent jobs, so those caches must never be written to or wiped there.
"""
from zea.data import hf_remote
from zea.internal import preset_utils

root = tmp_path_factory.mktemp("hf_caches")
with pytest.MonkeyPatch.context() as mp:
mp.setattr(hf_remote, "_CACHE_DIR", root / "locations")
mp.setattr(preset_utils, "_LISTING_DIR", root / "listings")
yield


@pytest.fixture(scope="session", autouse=True)
def run_once_after_all_tests():
"""Fixture to stop workers after all tests have run."""
Expand Down
147 changes: 144 additions & 3 deletions tests/data/test_chunk_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,22 @@ def test_small_read_below_threshold(self, structured_file):
np.testing.assert_array_equal(got, file[RAW][selection])


class TestSmallRemoteReads:
def test_small_remote_read_takes_the_fast_path(self, structured_file):
"""A small read over HTTP is still one merged request, not h5py's block-by-block reads."""
server = _CountingServer(structured_file.parent, latency=0)
try:
fetcher = HTTPFetcher(server.url + structured_file.name)
with File(structured_file) as file:
selection = (0, 0, slice(0, 4))
got = read(file[RAW], selection, fetcher)
assert got.nbytes < MIN_BYTES
np.testing.assert_array_equal(got, file[RAW][selection])
assert server.count == 1
finally:
server.close()


class TestHumanBytes:
@pytest.mark.parametrize(
("n", "expected"),
Expand Down Expand Up @@ -695,6 +711,11 @@ def send_head(self):
self.end_headers()
return None
path = self.translate_path(self.path)
if not os.path.isfile(path): # an expired or unknown URL
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
return None
with open(path, "rb") as handle:
body = handle.read()
rng = self.headers.get("Range")
Expand Down Expand Up @@ -739,6 +760,12 @@ def close(self):
pass


@pytest.fixture
def no_merge(monkeypatch):
"""Send one request per chunk, for tests about concurrency rather than merging."""
monkeypatch.setattr(chunk_reader, "MERGE_GAP", -1)


class TestRemote:
def test_http_fetcher_matches_local_bytes(self, structured_file):
server = _CountingServer(structured_file.parent, latency=0)
Expand Down Expand Up @@ -768,7 +795,7 @@ def test_reads_over_http_match_h5py(self, structured_file):
finally:
server.close()

def test_chunks_are_fetched_concurrently(self, structured_file):
def test_chunks_are_fetched_concurrently(self, structured_file, no_merge):
"""The point of the remote path: N chunks cost ~1 round trip, not N.

Asserted on *peak concurrency* — the maximum number of requests the server held open
Expand Down Expand Up @@ -906,8 +933,8 @@ def test_a_missing_file_is_not_retried(self, structured_file, fast_backoff):
finally:
server.close()

def test_requests_in_flight_are_capped(self, structured_file, monkeypatch):
"""The cap is what keeps a read from tripping the rate limit in the first place."""
def test_requests_in_flight_are_capped(self, structured_file, monkeypatch, no_merge):
"""No more requests are in flight than the cap allows."""
cap = 2
monkeypatch.setattr(chunk_reader, "MAX_CONCURRENT_REQUESTS", cap)
# The semaphore is made once per event loop and cached, so drop whatever earlier
Expand All @@ -926,6 +953,120 @@ def test_requests_in_flight_are_capped(self, structured_file, monkeypatch):
server.close()


class TestMerge:
def test_adjacent_chunks_cost_one_request(self, structured_file):
"""A read of neighbouring chunks goes out as one request, and still matches h5py."""
server = _CountingServer(structured_file.parent, latency=0)
try:
fetcher = HTTPFetcher(server.url + structured_file.name)
with File(structured_file) as file:
got = read(file[RAW], slice(0, 4), fetcher)
np.testing.assert_array_equal(got, file[RAW][0:4])
assert server.count == 1
finally:
server.close()

def test_merged_bytes_are_cached_per_chunk(self, structured_file, tmp_path):
"""The cache stores each chunk on its own, so a later partial read is a hit."""
from zea.data.chunk_cache import ChunkCache

server = _CountingServer(structured_file.parent, latency=0)
try:
cache = ChunkCache("merge-test", root=tmp_path)
fetcher = HTTPFetcher(server.url + structured_file.name, cache=cache)
with File(structured_file) as file:
read(file[RAW], slice(0, 4), fetcher)
before = server.count
np.testing.assert_array_equal(read(file[RAW], 2, fetcher), file[RAW][2])
assert server.count == before
finally:
server.close()

def test_groups_by_gap_and_size(self, monkeypatch):
monkeypatch.setattr(chunk_reader, "MERGE_GAP", 10)
monkeypatch.setattr(chunk_reader, "MERGE_MAX", 100)
misses = [(0, 0, 40), (1, 45, 40), (2, 200, 10), (3, 85, 30)]
spans = chunk_reader._merge(misses)
# 0 and 1 merge (gap 5); 3 would make the request 115 bytes, over the max; 2 is far.
assert [(start, end) for start, end, _ in spans] == [(0, 85), (85, 115), (200, 210)]
assert [[m[0] for m in members] for *_, members in spans] == [[0, 1], [3], [2]]

def test_unsorted_and_overlapping_ranges(self):
spans = chunk_reader._merge([(0, 50, 10), (1, 0, 60), (2, 55, 10)])
assert [(start, end) for start, end, _ in spans] == [(0, 65)]


class _Location:
"""A SignedURL stand-in: a URL that is rejected until it is refreshed."""

def __init__(self, stale, fresh):
self.url, self.fresh, self.refreshes = stale, fresh, 0

def current(self):
return self.url, {}

def refresh(self, stale_url):
if self.url == stale_url:
self.refreshes += 1
self.url = self.fresh
return True


class TestRefusedLocation:
def test_rejected_url_is_refreshed_once(self, structured_file):
server = _CountingServer(structured_file.parent, latency=0)
try:
location = _Location(server.url + "expired.hdf5", server.url + structured_file.name)
fetcher = HTTPFetcher(location)
with File(structured_file) as file:
got = read(file[RAW], slice(0, 4), fetcher)
np.testing.assert_array_equal(got, file[RAW][0:4])
assert location.refreshes == 1
finally:
server.close()

def test_plain_url_is_not_refreshed(self, structured_file, fast_backoff):
server = _CountingServer(
structured_file.parent, latency=0, reject_first=1, reject_status=403
)
try:
fetcher = HTTPFetcher(server.url + structured_file.name)
with pytest.raises(aiohttp.ClientResponseError):
fetcher.fetch([(0, 16)])
assert server.count == 1
finally:
server.close()

@pytest.mark.parametrize("status", [401, 403, 410])
def test_refused_statuses(self, status):
exc = aiohttp.ClientResponseError(MagicMock(), (), status=status)
assert chunk_reader._is_refused(exc)

def test_missing_file_is_refused(self):
assert chunk_reader._is_refused(FileNotFoundError("x"))

def test_server_errors_are_not_refusals(self):
exc = aiohttp.ClientResponseError(MagicMock(), (), status=503)
assert not chunk_reader._is_refused(exc)


def test_request_cap_is_read_from_the_environment():
"""ZEA_MAX_CONCURRENT_REQUESTS sets the cap (read once, at import)."""
import subprocess
import sys

env = {**os.environ, "ZEA_MAX_CONCURRENT_REQUESTS": "7", "KERAS_BACKEND": "numpy"}
code = "from zea.data import chunk_reader as c; print(c.MAX_CONCURRENT_REQUESTS)"
out = subprocess.run(
[sys.executable, "-c", code],
env=env,
capture_output=True,
text=True,
check=True,
)
assert out.stdout.strip().splitlines()[-1] == "7"


class TestIsTransient:
@pytest.mark.parametrize("status", sorted(chunk_reader.RETRY_STATUS))
def test_transient_statuses(self, status):
Expand Down
74 changes: 64 additions & 10 deletions tests/data/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,8 +479,8 @@ def open_at_revision(file_path, *args, revision=None, **kwargs):
np.testing.assert_array_equal(sample, expected)


def test_dataloader_warns_when_stream_exceeds_chunk_cache():
"""Streaming more than the chunk cache holds re-fetches every epoch, so it warns."""
def test_dataloader_notes_when_stream_exceeds_chunk_cache():
"""Streaming more than the chunk cache holds re-downloads every epoch, so it says so."""
from zea.data import dataloader as dataloader_module
from zea.data.dataloader import H5DataSource

Expand All @@ -489,31 +489,52 @@ def test_dataloader_warns_when_stream_exceeds_chunk_cache():
with (
patch("zea.data.datasets._hf_list_h5_files", return_value=[("file1.hdf5", oversized)]),
patch("zea.data.datasets.Dataset.load_file_shapes", return_value=_FAKE_SHAPES),
patch.object(dataloader_module, "_warned_about_streaming", False),
patch.object(dataloader_module, "_noted_streaming", False),
patch.object(dataloader_module.chunk_cache, "ENABLED", True),
patch("zea.data.dataloader.log") as mock_log,
):
H5DataSource("hf://org/myrepo", key="data/image", lazy=True)
# Only the first loader warns: the message is about the data, not the loader.
# Only the first loader notes it: the message is about the data, not the loader.
H5DataSource("hf://org/myrepo", key="data/image", lazy=True)

assert mock_log.warning.call_count == 1
assert "chunk cache" in mock_log.warning.call_args[0][0]
mock_log.warning.assert_not_called()
assert mock_log.info.call_count == 1
assert "chunk cache" in mock_log.info.call_args[0][0]


def test_dataloader_does_not_warn_when_stream_fits_chunk_cache():
"""A dataset the cache can hold streams without complaint."""
def test_dataloader_does_not_note_when_stream_fits_chunk_cache():
"""A dataset the cache can hold streams without comment."""
from zea.data import dataloader as dataloader_module
from zea.data.dataloader import H5DataSource

with (
patch("zea.data.datasets._hf_list_h5_files", return_value=[("file1.hdf5", 1024)]),
patch("zea.data.datasets.Dataset.load_file_shapes", return_value=_FAKE_SHAPES),
patch.object(dataloader_module, "_warned_about_streaming", False),
patch.object(dataloader_module, "_noted_streaming", False),
patch("zea.data.dataloader.log") as mock_log,
):
H5DataSource("hf://org/myrepo", key="data/image", lazy=True)

mock_log.warning.assert_not_called()
mock_log.info.assert_not_called()


def test_dataloader_does_not_note_when_chunk_cache_is_off():
"""Without a chunk cache there is nothing to exceed."""
from zea.data import dataloader as dataloader_module
from zea.data.dataloader import H5DataSource

oversized = dataloader_module.chunk_cache.MAX_BYTES + 1

with (
patch("zea.data.datasets._hf_list_h5_files", return_value=[("file1.hdf5", oversized)]),
patch("zea.data.datasets.Dataset.load_file_shapes", return_value=_FAKE_SHAPES),
patch.object(dataloader_module, "_noted_streaming", False),
patch.object(dataloader_module.chunk_cache, "ENABLED", False),
patch("zea.data.dataloader.log") as mock_log,
):
H5DataSource("hf://org/myrepo", key="data/image", lazy=True)

mock_log.info.assert_not_called()


def test_dataset_hf_large_warns_about_gb_size(tmp_path):
Expand Down Expand Up @@ -643,3 +664,36 @@ def test_folder_validate_raises(self, dummy_dataset_path):

with pytest.raises(ValueError, match="broken.hdf5"):
Folder(folder, validate=True)


class TestSweepWorkers:
"""The parallel per-file sweeps use a bounded, configurable number of processes."""

def test_default_is_bounded(self, monkeypatch):
from zea.data import datasets

monkeypatch.delenv("ZEA_FIND_H5_SHAPES_WORKERS", raising=False)
monkeypatch.setattr(datasets.os, "cpu_count", lambda: 256)
assert datasets._sweep_workers(10_000) == datasets._DEFAULT_SWEEP_WORKERS

def test_environment_variable(self, monkeypatch):
from zea.data import datasets

monkeypatch.setenv("ZEA_FIND_H5_SHAPES_WORKERS", "5")
monkeypatch.setattr(datasets.os, "cpu_count", lambda: 256)
assert datasets._sweep_workers(10_000) == 5

def test_never_more_than_cores_or_files(self, monkeypatch):
from zea.data import datasets

monkeypatch.setenv("ZEA_FIND_H5_SHAPES_WORKERS", "64")
monkeypatch.setattr(datasets.os, "cpu_count", lambda: 8)
assert datasets._sweep_workers(10_000) == 8
assert datasets._sweep_workers(3) == 3

def test_bad_value_falls_back(self, monkeypatch):
from zea.data import datasets

monkeypatch.setenv("ZEA_FIND_H5_SHAPES_WORKERS", "lots")
monkeypatch.setattr(datasets.os, "cpu_count", lambda: 256)
assert datasets._sweep_workers(10_000) == datasets._DEFAULT_SWEEP_WORKERS
Loading
Loading