Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
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 @@ -73,6 +79,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 @@ -301,6 +301,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
2 changes: 2 additions & 0 deletions tests/data/test_chunk_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ class TestGetPut:
def test_roundtrip(self, root):
cache = ChunkCache("deadbeef", root)
assert cache.get(0, 4) is None
assert not cache.contains(0, 4)
cache.put(0, 4, b"data")
assert cache.get(0, 4) == b"data"
assert cache.contains(0, 4) and not cache.contains(0, 5)

def test_offset_and_size_are_both_part_of_the_key(self, root):
cache = ChunkCache("deadbeef", root)
Expand Down
232 changes: 228 additions & 4 deletions tests/data/test_chunk_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@

import http.server
import inspect
import logging
import os
import socketserver
import threading
from importlib import import_module
import time
from unittest.mock import MagicMock
from unittest.mock import MagicMock, patch

import aiohttp
import h5py
Expand Down Expand Up @@ -448,6 +449,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 +712,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 +761,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 +796,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 +934,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 +954,202 @@ 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_sparse_ranges_are_not_inflated(self):
"""One small chunk per far-apart frame stays one request each, instead of a request
that is mostly gap."""
misses = [(i, i * (1 << 20), 64 << 10) for i in range(8)]
assert len(chunk_reader._merge(misses)) == 8
# Gaps no larger than the chunks still merge.
misses = [(i, i * (128 << 10), 64 << 10) for i in range(8)]
assert len(chunk_reader._merge(misses)) == 1

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"


@pytest.mark.parametrize("value", ["0", "-3", "lots"])
def test_bad_request_cap_falls_back_to_the_default(monkeypatch, value):
"""A cap of zero would hang every request; a non-number would break the import."""
monkeypatch.setenv("ZEA_MAX_CONCURRENT_REQUESTS", value)
with pytest.warns(UserWarning, match="ZEA_MAX_CONCURRENT_REQUESTS"):
assert chunk_reader._max_concurrent_requests(default=64) == 64


def test_retry_log_does_not_refresh_or_leak_the_url(structured_file, fast_backoff):
"""The retry message neither reads ``self.url`` (which may refresh) nor logs a signature."""

class Location:
def __init__(self, url):
self.url, self.calls = url, 0

def current(self):
self.calls += 1
return self.url, {}

def refresh(self, stale_url):
return False

server = _CountingServer(structured_file.parent, latency=0, reject_first=1)
try:
location = Location(server.url + structured_file.name + "?Signature=secret")
fetcher = HTTPFetcher(location)
with patch("zea.log.debug") as debug:
fetcher.fetch([(0, 16)])
assert location.calls == 1 # only the one call in fetch(), none from the retry
message = debug.call_args[0][0]
assert "retrying" in message and "secret" not in message
finally:
server.close()


def test_fsspec_debug_log_redacts_signed_urls(structured_file, caplog):
"""fsspec logs every URL it requests; the signature must not end up in the log."""
server = _CountingServer(structured_file.parent, latency=0)
try:
url = server.url + structured_file.name + "?Policy=abc&Signature=secret"
fetcher = HTTPFetcher(url) # the test server ignores the query string
with caplog.at_level(logging.DEBUG, logger="fsspec.http"):
data = fetcher.fetch([(0, 16)])
assert data[0] == structured_file.read_bytes()[:16] # requested with the full URL
logged = [r.getMessage() for r in caplog.records if r.name == "fsspec.http"]
assert any(structured_file.name in m for m in logged)
assert not any("secret" in m or "Policy" in m for m in logged)
finally:
server.close()


@pytest.mark.parametrize(
"name, status, error",
[("gone.hdf5", None, FileNotFoundError), (None, 403, chunk_reader.RemoteReadError)],
)
def test_errors_redact_signed_urls(structured_file, name, status, error):
"""The error of a failed request names the file, but not the signature of its URL."""
server = _CountingServer(
structured_file.parent, latency=0, reject_first=100 if status else 0, reject_status=status
)
try:
name = name or structured_file.name
fetcher = HTTPFetcher(server.url + name + "?Policy=abc&Signature=secret")
with pytest.raises(error) as info:
fetcher.fetch([(0, 16)])
assert name in str(info.value) and "secret" not in str(info.value)
assert info.value.__suppress_context__
if status == 403:
assert info.value.status == 403
finally:
server.close()


class TestIsTransient:
@pytest.mark.parametrize("status", sorted(chunk_reader.RETRY_STATUS))
def test_transient_statuses(self, status):
Expand Down
Loading
Loading