From d646442e1afdba844387c2f088c41c80e8dad718 Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Mon, 26 Oct 2026 08:41:25 +0000 Subject: [PATCH 01/17] 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. --- docs/source/environment.rst | 13 ++ tests/conftest.py | 17 ++ tests/data/test_chunk_reader.py | 147 ++++++++++++- tests/data/test_dataset.py | 74 ++++++- tests/data/test_hf_remote.py | 197 +++++++++++++++++ tests/test_preset_utils.py | 73 +++++-- tests/tools/test_hf.py | 52 ++--- zea/data/chunk_cache.py | 4 + zea/data/chunk_reader.py | 177 ++++++++++++--- zea/data/dataloader.py | 52 ++--- zea/data/datasets.py | 26 ++- zea/data/hf_remote.py | 366 ++++++++++++++++++++++++++++++++ zea/internal/preset_utils.py | 120 +++++++---- 13 files changed, 1163 insertions(+), 155 deletions(-) create mode 100644 tests/data/test_hf_remote.py create mode 100644 zea/data/hf_remote.py diff --git a/docs/source/environment.rst b/docs/source/environment.rst index 7e356ac13..d9e3abc77 100644 --- a/docs/source/environment.rst +++ b/docs/source/environment.rst @@ -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`` @@ -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 diff --git a/tests/conftest.py b/tests/conftest.py index 7fbc9f6ec..207b93e84 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -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.""" diff --git a/tests/data/test_chunk_reader.py b/tests/data/test_chunk_reader.py index a521a0c7b..1d1f5f7a3 100644 --- a/tests/data/test_chunk_reader.py +++ b/tests/data/test_chunk_reader.py @@ -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"), @@ -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") @@ -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) @@ -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 @@ -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 @@ -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): diff --git a/tests/data/test_dataset.py b/tests/data/test_dataset.py index 62a799e2d..05d24ba9d 100644 --- a/tests/data/test_dataset.py +++ b/tests/data/test_dataset.py @@ -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 @@ -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): @@ -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 diff --git a/tests/data/test_hf_remote.py b/tests/data/test_hf_remote.py new file mode 100644 index 000000000..17e8dd2c2 --- /dev/null +++ b/tests/data/test_hf_remote.py @@ -0,0 +1,197 @@ +"""Tests for zea.data.hf_remote: resolving streamed hf:// files to their CDN URL once.""" + +import json +from types import SimpleNamespace + +import numpy as np +import pytest + +from zea.data import chunk_reader, hf_remote +from zea.data.file import File + +from .test_chunk_reader import RAW, _CountingServer, _structured, _write + +HF_PATH = "hf://org/repo/data/x.hdf5" + + +@pytest.fixture(autouse=True) +def _isolated_cache(tmp_path, monkeypatch): + monkeypatch.setattr(hf_remote, "_CACHE_DIR", tmp_path / "locations") + hf_remote.clear() + yield + hf_remote.clear() + + +@pytest.fixture +def hub(monkeypatch): + """Fake ``get_hf_file_metadata``: records each HEAD and answers with ``hub.location``.""" + state = SimpleNamespace( + heads=[], location="https://cdn.example/signed?1", etag="sha-1", size=1234 + ) + + def fake_metadata(url, **kwargs): + state.heads.append(url) + return SimpleNamespace( + location=state.location, etag=state.etag, commit_hash="c0ffee", size=state.size + ) + + monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", fake_metadata) + return state + + +class TestResolve: + def test_resolves_once(self, hub): + first = hf_remote.resolve(HF_PATH) + second = hf_remote.resolve(HF_PATH) + assert first == second + assert len(hub.heads) == 1 + assert first.size == 1234 and first.etag == "sha-1" and first.commit == "c0ffee" + + def test_shared_between_processes_through_disk(self, hub): + """A second process (simulated by clearing memory) reuses the URL on disk.""" + hf_remote.resolve(HF_PATH) + hf_remote._memory.clear() + hf_remote.resolve(HF_PATH) + assert len(hub.heads) == 1 + + def test_disk_cache_is_private(self, hub): + hf_remote.resolve(HF_PATH) + (path,) = hf_remote._CACHE_DIR.iterdir() + assert path.stat().st_mode & 0o077 == 0 + assert json.loads(path.read_text())["url"] == hub.location + + def test_expired_url_is_resolved_again(self, hub, monkeypatch): + hf_remote.resolve(HF_PATH) + monkeypatch.setattr(hf_remote, "URL_TTL", 0) + hf_remote.resolve(HF_PATH) + assert len(hub.heads) == 2 + + def test_refresh_skips_the_cache(self, hub): + hf_remote.resolve(HF_PATH) + hf_remote.resolve(HF_PATH, refresh=True) + assert len(hub.heads) == 2 + + def test_keyed_on_revision(self, hub): + hf_remote.resolve(HF_PATH) + hf_remote.resolve(HF_PATH, revision="v1") + assert len(hub.heads) == 2 + assert "/resolve/v1/" in hub.heads[1] + + def test_no_token_sent_to_the_cdn(self, hub): + assert not hf_remote.resolve(HF_PATH).send_auth + + def test_token_kept_for_the_hub_itself(self, hub): + from huggingface_hub import constants + + hub.location = f"{constants.ENDPOINT}/datasets/org/repo/resolve/main/data/x.hdf5" + assert hf_remote.resolve(HF_PATH).send_auth + + def test_requires_a_file(self, hub): + with pytest.raises(ValueError, match="single file"): + hf_remote.resolve("hf://org/repo") + + +class TestSignedURL: + def test_refresh_is_pinned_to_the_first_commit(self, hub): + location = hf_remote.SignedURL(HF_PATH) + hub.location = "https://cdn.example/signed?2" + assert location.refresh("https://cdn.example/signed?1") + assert "/resolve/c0ffee/" in hub.heads[-1] + assert location.current()[0] == "https://cdn.example/signed?2" + + def test_refresh_happens_once_for_concurrent_failures(self, hub): + location = hf_remote.SignedURL(HF_PATH) + hub.location = "https://cdn.example/signed?2" + assert location.refresh("https://cdn.example/signed?1") + assert location.refresh("https://cdn.example/signed?1") # already replaced + assert len(hub.heads) == 2 + + def test_content_change_while_open_raises(self, hub): + location = hf_remote.SignedURL(HF_PATH) + hub.etag = "sha-2" + with pytest.raises(OSError, match="changed on the Hub"): + location.refresh(location.current()[0]) + + def test_stale_url_is_refreshed_before_use(self, hub, monkeypatch): + location = hf_remote.SignedURL(HF_PATH) + monkeypatch.setattr(hf_remote, "URL_TTL", 0) + hub.location = "https://cdn.example/signed?2" + assert location.current() == ("https://cdn.example/signed?2", {}) + + +class TestStreamedFile: + """End to end: ``zea.File("hf://...")`` against a local server standing in for the CDN.""" + + @pytest.fixture(autouse=True) + def _fast_path(self, monkeypatch): + """The test file is small; send its reads through the chunk reader anyway.""" + monkeypatch.setattr(chunk_reader, "MIN_BYTES", 0) + + @pytest.fixture + def cdn(self, tmp_path, hub): + path = _write(tmp_path / "x.hdf5", _structured()) + server = _CountingServer(tmp_path, latency=0) + hub.location = server.url + path.name + hub.size = path.stat().st_size + yield SimpleNamespace(server=server, path=path, hub=hub) + server.close() + + def test_reads_match_the_local_file(self, cdn): + with File(HF_PATH, cache=False, progress=False) as remote, File(cdn.path) as local: + np.testing.assert_array_equal(remote[RAW][0:3], local[RAW][0:3]) + got = chunk_reader.read(remote[RAW], slice(0, 4), remote._chunk_fetcher) + np.testing.assert_array_equal(got, local[RAW][0:4]) + + def test_one_hub_request_for_open_and_reads(self, cdn): + with File(HF_PATH, cache=False, progress=False) as remote: + for i in range(4): + chunk_reader.read(remote[RAW], i, remote._chunk_fetcher) + assert len(cdn.hub.heads) == 1 # every read after that went to the CDN + assert cdn.server.count > 1 + + def test_expired_url_mid_read_is_refreshed(self, cdn): + with File(HF_PATH, cache=False, progress=False) as remote, File(cdn.path) as local: + fetcher = remote._chunk_fetcher + # The CDN stops accepting the URL; the hub hands out a new, working one. + fetcher.location._resolved = hf_remote.Resolved( + **{**fetcher.location._resolved.__dict__, "url": cdn.server.url + "gone.hdf5"} + ) + got = chunk_reader.read(remote[RAW], slice(0, 2), fetcher) + np.testing.assert_array_equal(got, local[RAW][0:2]) + assert len(cdn.hub.heads) == 2 + + def test_handles_share_metadata_blocks(self, cdn): + """A second handle of the same file (another dataloader thread) fetches nothing.""" + with File(HF_PATH, cache=False, progress=False) as first: + first[RAW].shape + before = cdn.server.count + with File(HF_PATH, cache=False, progress=False) as second: + second[RAW].shape + assert cdn.server.count == before + + def test_shared_blocks_are_bounded(self): + blocks = hf_remote._SharedBlocks(max_bytes=10) + for i in range(4): + blocks.put(("etag", i), b"xxxx") + assert blocks.get(("etag", 0)) is None # evicted, oldest first + assert blocks.get(("etag", 3)) == b"xxxx" + + def test_resolved_location_is_shared_with_the_chunk_reader(self, cdn): + with File(HF_PATH, cache=False, progress=False) as remote: + assert remote._chunk_fetcher.location is remote._stream_fileobj.location + + +def test_merged_requests_are_counted_once(tmp_path, hub): + """The network byte counter sees the bytes actually fetched, not one count per chunk.""" + from zea.data import chunk_cache + + path = _write(tmp_path / "x.hdf5", _structured()) + server = _CountingServer(tmp_path, latency=0) + try: + fetcher = chunk_reader.HTTPFetcher(server.url + path.name) + before = chunk_cache.network_bytes() + fetcher.fetch([(0, 100), (100, 100)]) + assert chunk_cache.network_bytes() - before == 200 + assert server.count == 1 + finally: + server.close() diff --git a/tests/test_preset_utils.py b/tests/test_preset_utils.py index cf2722006..4dce0395c 100644 --- a/tests/test_preset_utils.py +++ b/tests/test_preset_utils.py @@ -9,6 +9,8 @@ import threading import time from pathlib import Path +from types import SimpleNamespace +from unittest.mock import MagicMock import httpx import keras @@ -518,22 +520,37 @@ def test_stream_url_rejects_bad_repo_type(): ipu._hf_stream_url(f"hf://{REPO_ID}/a.hdf5", repo_type="banana") -def test_stream_open_retries_after_login(monkeypatch): +def _fake_metadata(url="https://cdn.example/x", etag="sha", commit="c0ffee", size=10): + return SimpleNamespace(location=url, etag=etag, commit_hash=commit, size=size) + + +@pytest.fixture +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)) + + +def test_stream_open_retries_after_login(monkeypatch, no_byte_reads): """A stream open that 404s anonymously is retried once after logging in.""" + from zea.data import hf_remote + + hf_remote.clear() logins = [] monkeypatch.setattr(ipu, "_hf_login", lambda: logins.append(1)) attempts = [] - class FakeFS: - def open(self, path, mode, **kwargs): - attempts.append(path) - if len(attempts) == 1: - raise _repo_not_found() - return "FILEOBJ" + def fake_metadata(url, **kwargs): + attempts.append(url) + if len(attempts) == 1: + raise _repo_not_found() + return _fake_metadata() - monkeypatch.setattr("huggingface_hub.HfFileSystem", FakeFS) + monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", fake_metadata) - assert ipu._hf_stream_open(f"hf://{REPO_ID}/val/a.hdf5") == "FILEOBJ" + fileobj = ipu._hf_stream_open(f"hf://{REPO_ID}/val/a.hdf5") + assert fileobj.size == 10 assert len(attempts) == 2 assert len(logins) == 1 @@ -1381,20 +1398,38 @@ def test_cache_ttl_falls_back_on_an_unparseable_value(monkeypatch): assert ipu._hf_cache_ttl() == 0 -def test_streaming_does_not_go_through_the_caches(monkeypatch): - """Streamed reads must reach the hub every time; they are not downloads.""" - opens = [] - - class FakeFS: - def open(self, path, mode, **kwargs): - opens.append(path) - return "FILEOBJ" +def test_stream_opens_share_one_resolution(monkeypatch, no_byte_reads): + """Opening a streamed file twice asks the Hub once, and never downloads it.""" + from zea.data import hf_remote - monkeypatch.setattr("huggingface_hub.HfFileSystem", FakeFS) + hf_remote.clear() + heads = [] + monkeypatch.setattr( + "huggingface_hub.get_hf_file_metadata", + lambda url, **kwargs: heads.append(url) or _fake_metadata(), + ) + monkeypatch.setattr(ipu, "hf_hub_download", MagicMock(side_effect=AssertionError)) for _ in range(2): ipu._hf_stream_open(f"hf://{REPO_ID}/val/a.hdf5") - assert len(opens) == 2 + assert len(heads) == 1 + hf_remote.clear() + + +def test_listing_is_shared_through_disk(fake_tree): + """A second process (simulated by clearing the in-memory cache) reuses the listing.""" + first = ipu._hf_list_h5_files(f"hf://{REPO_ID}") + ipu._LISTING_CACHE.clear() + assert ipu._hf_list_h5_files(f"hf://{REPO_ID}") == first + assert len(fake_tree) == 1 + + +def test_listing_is_not_shared_when_caching_is_off(fake_tree, monkeypatch): + monkeypatch.setattr(ipu, "_HF_CACHE_TTL", 0) + monkeypatch.setattr(ipu, "_LISTING_CACHE", ipu._TTLCache(0)) + ipu._hf_list_h5_files(f"hf://{REPO_ID}") + ipu._hf_list_h5_files(f"hf://{REPO_ID}") + assert len(fake_tree) == 2 def test_dtype_size_falls_back_for_unsizeable_dtypes(): diff --git a/tests/tools/test_hf.py b/tests/tools/test_hf.py index b4f9e0601..424765a16 100644 --- a/tests/tools/test_hf.py +++ b/tests/tools/test_hf.py @@ -216,48 +216,48 @@ def fake_download(repo_id, filename, cache_dir, repo_type="dataset", **kwargs): @pytest.mark.parametrize( - "hf_path, kwargs, expected_fs_path", + "kwargs, expected_url_path", [ - (FILE_STR, {}, f"datasets/{REPO_ID}/{FILE_SUBPATH}"), - (FILE_STR, {"repo_type": "model"}, f"{REPO_ID}/{FILE_SUBPATH}"), - (FILE_STR, {"repo_type": "space"}, f"spaces/{REPO_ID}/{FILE_SUBPATH}"), - ( - FILE_STR, - {"revision": "v0.1.0"}, - f"datasets/{REPO_ID}@v0.1.0/{FILE_SUBPATH}", - ), + ({}, f"datasets/{REPO_ID}/resolve/main/{FILE_SUBPATH}"), + ({"repo_type": "model"}, f"{REPO_ID}/resolve/main/{FILE_SUBPATH}"), + ({"repo_type": "space"}, f"spaces/{REPO_ID}/resolve/main/{FILE_SUBPATH}"), + ({"revision": "v0.1.0"}, f"datasets/{REPO_ID}/resolve/v0.1.0/{FILE_SUBPATH}"), ], ) -def test_hf_stream_open_path_construction(hf_path, kwargs, expected_fs_path, monkeypatch): - """The fsspec path (prefix + repo + revision + subpath) is built correctly.""" - opened = {} +def test_hf_stream_open_path_construction(kwargs, expected_url_path, monkeypatch): + """The file is resolved at the right repo, repo type and revision.""" + from types import SimpleNamespace - class FakeFS: - def open(self, path, mode, block_size=None, **kw): - opened["path"] = path - opened["mode"] = mode - opened["block_size"] = block_size - return "FAKE_FILEOBJ" + from huggingface_hub import constants - monkeypatch.setattr("huggingface_hub.HfFileSystem", FakeFS) + from zea.data import hf_remote - result = _hf_stream_open(hf_path, block_size=1234, **kwargs) - assert result == "FAKE_FILEOBJ" - assert opened["path"] == expected_fs_path - assert opened["mode"] == "rb" - assert opened["block_size"] == 1234 + hf_remote.clear() + heads = [] + + def fake_metadata(url, **kw): + heads.append(url) + 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)) + + result = _hf_stream_open(FILE_STR, block_size=1234, **kwargs) + assert heads == [f"{constants.ENDPOINT}/{expected_url_path}"] + assert result.blocksize == 1234 + hf_remote.clear() def test_hf_stream_open_requires_file(monkeypatch): """Streaming a repo root / directory (no subpath) raises a clear error.""" - monkeypatch.setattr("huggingface_hub.HfFileSystem", object) + monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", object) with pytest.raises(ValueError, match="single file"): _hf_stream_open(FOLDER_STR) def test_hf_stream_open_rejects_bad_repo_type(monkeypatch): """An unknown repo_type is rejected before any network access.""" - monkeypatch.setattr("huggingface_hub.HfFileSystem", object) + monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", object) with pytest.raises(ValueError, match="repo_type"): _hf_stream_open(FILE_STR, repo_type="banana") diff --git a/zea/data/chunk_cache.py b/zea/data/chunk_cache.py index 846ca916f..8e456eaf0 100644 --- a/zea/data/chunk_cache.py +++ b/zea/data/chunk_cache.py @@ -135,6 +135,8 @@ def __init__(self, fileobj, cache: "ChunkCache", block_size: int | None = None): self.size = fileobj.size #: Passed through: this is where the chunk fetcher reads the file's content hash from. self.details = getattr(fileobj, "details", {}) + #: Passed through: the chunk fetcher reuses the file's CDN URL. + self.location = getattr(fileobj, "location", None) def _block_bytes(self, index: int) -> bytes: offset = index * self._block @@ -208,6 +210,8 @@ def cache_for(details: dict, root: str | os.PathLike | None = None) -> ChunkCach content_id = None if isinstance(lfs, dict): content_id = lfs.get("sha256") + # The Hub etag equals the LFS sha256, so both give the same cache key. + content_id = content_id or details.get("etag") content_id = content_id or details.get("blob_id") # non-LFS files if not content_id: return None diff --git a/zea/data/chunk_reader.py b/zea/data/chunk_reader.py index ab8db9b73..408f2ca33 100644 --- a/zea/data/chunk_reader.py +++ b/zea/data/chunk_reader.py @@ -37,13 +37,16 @@ from contextlib import contextmanager from itertools import repeat from pathlib import Path -from typing import Any, Callable, Sequence, cast +from typing import TYPE_CHECKING, Any, Callable, Protocol, Sequence, cast import h5py import numpy as np from zea.data.chunk_cache import _count_network_bytes +if TYPE_CHECKING: + from zea.data.hf_remote import SignedURL + #: Called with the byte size of each chunk as it arrives. Runs on worker threads. Ticker = Callable[[int], None] | None @@ -60,7 +63,9 @@ DECODABLE = (BLOSC, LZ4, ZSTD, GZIP, SHUFFLE) -# Reads below this are served by h5py: the thread hand-off costs more than it saves. +# Local reads below this are served by h5py: the thread hand-off costs more than it saves. +# Remote reads always take the fast path. Through h5py they would be fetched block by block, +# serially and under h5py's global lock, which stalls every dataloader thread. MIN_BYTES = 1 << 20 # 1 MiB # Ceiling on compressed bytes held in memory at once. Bounded by bytes and not by chunk @@ -82,9 +87,21 @@ BASE_BACKOFF = 1.0 MAX_BACKOFF = 8.0 -#: Range requests in flight at once, across every fetcher sharing fsspec's event loop. Kept low -#: enough to stay under Hugging Face's per-IP rate limit from a shared machine. -MAX_CONCURRENT_REQUESTS = 16 +#: Range requests in flight at once, across every fetcher sharing fsspec's event loop, i.e. +#: per process (``ZEA_MAX_CONCURRENT_REQUESTS``). Streamed reads go to the CDN, which is not +#: rate limited, so this only bounds connections and memory (at most this many merged +#: requests of up to :data:`MERGE_MAX` each). Measured with five streaming dataloaders in one +#: process: 16 gave ~37 MB/s, 32 to 128 gave ~45-50 MB/s. +MAX_CONCURRENT_REQUESTS = int(os.environ.get("ZEA_MAX_CONCURRENT_REQUESTS", 64)) + +#: Merge ranges into one request when the gap between them is at most this many bytes. +#: The chunks of a frame are stored almost back to back, so a frame (or a block of +#: consecutive frames) becomes one request instead of one per chunk. +MERGE_GAP = 1 << 20 # 1 MiB + +#: Maximum size of a merged request, so large reads are still split over a few parallel +#: requests. +MERGE_MAX = 32 << 20 # 32 MiB _limiters: "dict[Any, asyncio.Semaphore]" = {} _limiters_lock = threading.Lock() @@ -124,13 +141,64 @@ def _is_transient(exc: BaseException) -> bool: return isinstance(exc, _transient_errors()) +def _is_refused(exc: BaseException) -> bool: + """Whether the server rejected the URL itself, e.g. because a signed URL expired. + + fsspec raises ``FileNotFoundError`` for a 404 and keeps the status on other errors. + """ + from zea.data.hf_remote import REFUSED_STATUS + + if isinstance(exc, (FileNotFoundError, PermissionError)): + return True + return getattr(exc, "status", None) in REFUSED_STATUS + + +class _Location(Protocol): + """Where a :class:`HTTPFetcher` sends its requests: :class:`_FixedURL` or ``SignedURL``.""" + + def current(self) -> tuple[str, dict[str, str]]: ... + + def refresh(self, stale_url: str) -> bool: ... + + +class _FixedURL: + """A plain URL that is never refreshed.""" + + def __init__(self, url: str, headers: dict[str, str]): + self._url = url + self._headers = headers + + def current(self) -> tuple[str, dict[str, str]]: + return self._url, self._headers + + def refresh(self, stale_url: str) -> bool: + return False + + +def _merge(misses: Sequence[tuple[int, int, int]]) -> list[tuple[int, int, list]]: + """Group ``(index, offset, size)`` ranges into ``(start, end, members)`` requests. + + A range joins the previous request if the gap is at most :data:`MERGE_GAP` and the + request stays within :data:`MERGE_MAX`. Overlapping ranges are allowed. + """ + spans: list[tuple[int, int, list]] = [] + for miss in sorted(misses, key=lambda m: m[1]): + _, offset, size = miss + if spans: + start, end, members = spans[-1] + if offset - end <= MERGE_GAP and max(end, offset + size) - start <= MERGE_MAX: + spans[-1] = (start, max(end, offset + size), members + [miss]) + continue + spans.append((offset, offset + size, [miss])) + return spans + + def _limiter(loop) -> asyncio.Semaphore: """The semaphore bounding the requests in flight on ``loop``. - Global rather than per read: one read already fans out to a request per chunk, and every - dataloader thread issues one at the same moment, so it is the threads together that overrun - Hugging Face. fsspec keeps a single event loop for all its async filesystems, so in practice - every fetcher shares this one semaphore. + Global rather than per read, because it is all dataloader threads together that open + connections and hold bytes in memory. fsspec keeps a single event loop for all its async + filesystems, so in practice every fetcher shares this one semaphore. """ with _limiters_lock: semaphore = _limiters.get(loop) @@ -260,35 +328,54 @@ class HTTPFetcher(Fetcher): 1.06 s against 0.06 s here) — and it is what makes per-chunk progress possible at all, since ``cat_ranges`` only returns once every range is done. - Neither fsspec nor aiohttp retries anything, so the retry Hugging Face needs — it rate-limits - per IP, and a dataloader reading a streamed dataset reaches that limit quickly — lives here, - along with the concurrency cap that keeps a read from tripping the limit to begin with; see - :func:`_is_transient` and :data:`MAX_CONCURRENT_REQUESTS`. + Neither fsspec nor aiohttp retries anything, so retries for 429s, 5xx and dropped + connections live here (:func:`_is_transient`), along with the cap on requests in flight + (:data:`MAX_CONCURRENT_REQUESTS`). + + ``url`` is a plain URL or a :class:`~zea.data.hf_remote.SignedURL` (the CDN URL of an + ``hf://`` file). A ``SignedURL`` that gets rejected is resolved again and the request retried. + + Nearby ranges in one :meth:`fetch` call are merged into one request (see :data:`MERGE_GAP` + and :data:`MERGE_MAX`) and split again afterwards. """ - def __init__(self, url: str, token: str | None = None, cache=None): + def __init__(self, url: "str | SignedURL", token: str | None = None, cache=None): import fsspec - self.url = url + if isinstance(url, str): + headers = {"Authorization": f"Bearer {token}"} if token else {} + self.location: _Location = _FixedURL(url, headers) + else: + self.location = url self.cache = cache # zea.data.chunk_cache.ChunkCache, or None - headers = {"Authorization": f"Bearer {token}"} if token else None - self._fs = fsspec.filesystem( - "http", client_kwargs={"headers": headers} if headers else None - ) + self._fs = fsspec.filesystem("http") + + @property + def url(self) -> str: + return self.location.current()[0] - async def _cat_range(self, offset: int, size: int) -> bytes: + async def _cat_range(self, offset: int, size: int, url: str, headers: dict) -> bytes: """One range request: bounded by the shared limiter, retried through rate limits. What counts as worth retrying is :func:`_is_transient`. The limiter is released before sleeping — holding a slot through the backoff would starve the requests that - are not being throttled. + are not being throttled. If the URL is rejected (:func:`_is_refused`), it is resolved + again once, in a thread so the event loop is not blocked. """ attempt = 0 + refreshed = False while True: try: async with _limiter(asyncio.get_running_loop()): - return await self._fs._cat_file(self.url, start=offset, end=offset + size) + return await self._fs._cat_file( + url, start=offset, end=offset + size, headers=headers + ) except Exception as exc: + if not refreshed and _is_refused(exc): + refreshed = True + if await asyncio.to_thread(self.location.refresh, url): + url, headers = await asyncio.to_thread(self.location.current) + continue if not _is_transient(exc) or attempt >= MAX_RETRIES: raise from zea import log # local, like the fallback warning below: zea imports us @@ -322,21 +409,37 @@ def fetch(self, ranges: Sequence[tuple[int, int]], on_bytes: Ticker = None) -> l if not misses: return cast(list[bytes], out) - async def one(index: int, offset: int, size: int) -> None: - data = await self._cat_range(offset, size) + # Get the URL here, not in the event loop: refreshing it may make a blocking request. + url, headers = self.location.current() + + async def one(start: int, end: int, members: list[tuple[int, int, int]]) -> None: + data = await self._cat_range(start, end - start, url, headers) _count_network_bytes(len(data)) - out[index] = data - if self.cache is not None: - self.cache.put(offset, size, data) - if on_bytes is not None: - on_bytes(size) + for index, offset, size in members: + piece = data[offset - start : offset - start + size] + out[index] = piece + if self.cache is not None: + self.cache.put(offset, size, piece) + if on_bytes is not None: + on_bytes(size) async def gather() -> None: - await asyncio.gather(*(one(*miss) for miss in misses)) + await asyncio.gather(*(one(*span) for span in _merge(misses))) sync(self._fs.loop, gather) 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. + + Used by :class:`~zea.data.hf_remote.RemoteFile`; :class:`~zea.data.chunk_cache.CachedFile` + does its own caching and counting. + """ + from fsspec.asyn import sync + + url, headers = self.location.current() + return sync(self._fs.loop, self._cat_range, offset, size, url, headers) + def pending_bytes(self, ranges: Sequence[tuple[int, int]]) -> int: if self.cache is None: return super().pending_bytes(ranges) @@ -359,13 +462,17 @@ def fetcher_for(file: h5py.File) -> Fetcher | None: source = getattr(file, "_source_name", None) if source is not None and str(source).startswith(HF_PREFIX): - token = get_token() - url = _hf_stream_url(str(source), **getattr(file, "_hf_kwargs", {})) + stream = getattr(file, "_stream_fileobj", None) + # Reuse the CDN URL the file was opened with (see zea.data.hf_remote). Fall back to + # the resolve URL if the file object has none. + location = getattr(stream, "location", None) or _hf_stream_url( + str(source), **getattr(file, "_hf_kwargs", {}) + ) # The streamed file object already carries HF's metadata (fetched on open), so the # content hash that keys the cache costs no extra request. - details = getattr(getattr(file, "_stream_fileobj", None), "details", None) or {} + details = getattr(stream, "details", None) or {} cache = cache_for(details) if getattr(file, "_cache_chunks", True) else None - fetcher = HTTPFetcher(url, token, cache) + fetcher = HTTPFetcher(location, get_token(), cache) fetcher.source = str(source) # the hf:// path, not the resolved streaming url return fetcher @@ -708,7 +815,7 @@ def read( dtype = dset.dtype itemsize = dtype.itemsize n_selected = int(np.prod([len(indices) for indices, _ in axes])) - if n_selected * itemsize < MIN_BYTES: + if fetcher.per_chunk and n_selected * itemsize < MIN_BYTES: return dset[selection] chunks = dset.chunks diff --git a/zea/data/dataloader.py b/zea/data/dataloader.py index ff3b0e748..ca7985524 100644 --- a/zea/data/dataloader.py +++ b/zea/data/dataloader.py @@ -64,30 +64,34 @@ #: What a loader does with files it cannot serve: refuse to build, or drop them. _FILE_POLICIES = ("error", "skip") -#: Whether this process already warned about streaming more than the chunk cache holds. +#: Whether this process already noted that the streamed data exceeds the chunk cache. #: That is a property of the data, so repeating it for every loader only adds noise. -_warned_about_streaming = False +_noted_streaming = False -def _warn_if_stream_exceeds_chunk_cache(remote_bytes: int) -> None: - """Warn when streamed files cannot all fit in the on-disk chunk cache. +def _note_if_stream_exceeds_chunk_cache(remote_bytes: int) -> None: + """Note when the streamed files are larger than the on-disk chunk cache. - Only the chunks a read touches are ever fetched, so a loader that reads a slice of - each file (``axis_selections``, ``limit_n_frames``) stays well under this bound -- but - when the part being read does exceed the cache, an LRU that never gets to serve a hit - turns every epoch into a fresh download. Downloading the files once is cheaper then. + Then each epoch downloads again whatever it reads. That is fine (streamed reads go to the + CDN and are not rate limited, see :mod:`zea.data.hf_remote`), but for many epochs over a + dataset that fits on disk, downloading it once with ``lazy=False`` is cheaper. Compares + whole file sizes, so a loader that reads only part of each file (``axis_selections``, + ``limit_n_frames``) may well fit anyway. """ - global _warned_about_streaming - if _warned_about_streaming or not remote_bytes or remote_bytes <= chunk_cache.MAX_BYTES: + global _noted_streaming + if ( + _noted_streaming + or not chunk_cache.ENABLED + or not remote_bytes + or remote_bytes <= chunk_cache.MAX_BYTES + ): return - _warned_about_streaming = True - log.warning( + _noted_streaming = True + log.info( f"Streaming {remote_bytes / 1e9:.1f} GB of hf:// files, more than the " - f"{chunk_cache.MAX_BYTES / 1e9:.1f} GB chunk cache " - "(zea.data.chunk_cache, ZEA_CHUNK_CACHE_SIZE). Reading all of it repeatedly will " - "evict chunks before they are re-read, so every epoch re-fetches them. Pass " - "lazy=False to download the files once instead. Reading only part of each file " - "(axis_selections, limit_n_frames) may still fit." + f"{chunk_cache.MAX_BYTES / 1e9:.1f} GB chunk cache (ZEA_CHUNK_CACHE_SIZE), so each " + "epoch downloads the data it reads again. For many epochs over a dataset that fits " + "on disk, lazy=False downloads it once instead." ) @@ -604,7 +608,7 @@ def __init__( _suggest_lazy=False, **kwargs, ) - _warn_if_stream_exceeds_chunk_cache(_dataset.remote_bytes) + _note_if_stream_exceeds_chunk_cache(_dataset.remote_bytes) self.file_paths = _dataset.file_paths # Requested metadata paths are checked in the same sweep that reads the shapes, # so a file that cannot answer surfaces here rather than mid-epoch. @@ -1079,13 +1083,13 @@ class Dataloader: revision: HuggingFace revision (branch, tag, or commit hash) for ``hf://`` paths. Defaults to ``None`` (uses the default branch, typically ``"main"``). lazy: Stream ``hf://`` files over HTTP instead of downloading them up front. - Default is ``True``: a read fetches only the chunks it touches, so reading a - slice of a few large files costs a fraction of them, and the bytes land in the + Default is ``True``: a read fetches only the chunks it touches, so you can train + on datasets too large to download. Streamed reads go to the Hugging Face CDN, + which is not rate limited (see :mod:`zea.data.hf_remote`), and land in the on-disk chunk cache (:mod:`zea.data.chunk_cache`) for the next read. Pass - ``False`` to download every file in full before the pipeline is built, which - is the better trade for training: shuffled access over a dataset larger than - that cache re-fetches it every epoch, and a bulk download is both faster per - byte and resumable. Ignored for local paths. + ``False`` to download every file in full before the pipeline is built. That pays + off for many epochs over a dataset that fits on disk, since streaming downloads + again whatever no longer fits in the cache. Ignored for local paths. shard_index: Shard index to select when ``num_shards > 1``. Must satisfy ``0 <= shard_index < num_shards``. num_shards: Total number of shards for distributed loading. diff --git a/zea/data/datasets.py b/zea/data/datasets.py index 42b399d66..3800329ce 100644 --- a/zea/data/datasets.py +++ b/zea/data/datasets.py @@ -66,6 +66,10 @@ FILE_HANDLE_CACHE_CAPACITY = 128 # Below this many files the sweeps stay serial; sized for network opens _PARALLEL_MIN_FILES = 32 +# Default cap on worker processes for those sweeps (ZEA_FIND_H5_SHAPES_WORKERS). Each worker +# imports zea, and a sweep spends most of its time waiting on file opens, so one process per +# core (256 on a large node) costs startup time and buys nothing. +_DEFAULT_SWEEP_WORKERS = 32 # How many invalid files a validation error spells out before summarising the rest. _MAX_LISTED_INVALID_FILES = 10 # Seconds a per-file sweep may take before it draws a progress bar. @@ -259,12 +263,30 @@ def _shape_and_metadata_gaps(file_path, key, metadata_paths, revision=None): return shape, missing, signature +def _sweep_workers(n_files: int) -> int: + """Worker processes for a parallel sweep over ``n_files`` files. + + ``ZEA_FIND_H5_SHAPES_WORKERS`` if set, else :data:`_DEFAULT_SWEEP_WORKERS`, and never more + than the number of cores or files. + """ + value = os.environ.get("ZEA_FIND_H5_SHAPES_WORKERS") + try: + workers = int(value) if value else _DEFAULT_SWEEP_WORKERS + except ValueError: + log.warning( + f"Ignoring ZEA_FIND_H5_SHAPES_WORKERS={value!r}: expected a number of processes." + ) + workers = _DEFAULT_SWEEP_WORKERS + return max(1, min(workers, os.cpu_count() or 1, n_files)) + + def _map_over_files(func, file_paths, desc, verbose=True): """Apply *func* to every file path, in parallel when that is worth its startup cost. ``func`` must be importable at module level -- it runs in a :mod:`multiprocessing` worker. Set ``ZEA_FIND_H5_SHAPES_PARALLEL=0`` to force the - main process (e.g. when calling from a worker yourself). + main process (e.g. when calling from a worker yourself), and + ``ZEA_FIND_H5_SHAPES_WORKERS`` to change the number of workers (see :func:`_sweep_workers`). """ parallel = len(file_paths) >= _PARALLEL_MIN_FILES and os.environ.get( "ZEA_FIND_H5_SHAPES_PARALLEL", "1" @@ -273,7 +295,7 @@ def _map_over_files(func, file_paths, desc, verbose=True): if parallel: # make sure to call this from within a function or use if __name__ == "__main__" # to avoid freezing the main process - with multiprocessing.Pool() as pool: + with multiprocessing.Pool(_sweep_workers(len(file_paths))) as pool: return list( tqdm.tqdm( pool.imap(func, file_paths), diff --git a/zea/data/hf_remote.py b/zea/data/hf_remote.py new file mode 100644 index 000000000..8f2faa595 --- /dev/null +++ b/zea/data/hf_remote.py @@ -0,0 +1,366 @@ +""" +zea.data.hf_remote +================== + +Resolve streamed ``hf://`` files to their CDN URL once, instead of on every read. + +Each request to a Hub ``/resolve/`` URL counts toward the Hub rate limit (see +https://huggingface.co/docs/hub/rate-limits). The Hub answers it with a redirect to a signed +CDN URL, and requests to that CDN URL are not rate limited. Before this module, every chunk +read went through ``/resolve/`` (about 8 requests per raw-data frame), so multi-worker +training quickly hit HTTP 429. + +We now do what :func:`huggingface_hub.hf_hub_download` does: one HEAD request per file via +:func:`huggingface_hub.get_hf_file_metadata`, then range requests directly to the returned +``location``, without the ``Authorization`` header (the token is for the Hub, not the CDN). + +- The signed URL is treated as opaque. It is reused for :data:`URL_TTL` seconds and + resolved again when it expires or the CDN rejects it. +- Re-resolving uses the commit of the first resolve, so the file cannot change while open. +- Resolved URLs are cached in memory and on disk, so all threads and processes on a machine + (e.g. one process per GPU) share them. The disk cache files are only readable by the user. +""" + +from __future__ import annotations + +import hashlib +import json +import threading +import time +from dataclasses import asdict, dataclass +from pathlib import Path +from urllib.parse import urlsplit + +from zea import log +from zea.internal.cache import ZEA_CACHE_DIR +from zea.internal.utils import atomic_write + +#: 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. +URL_TTL = 30 * 60 + +#: HTTP statuses the CDN returns for an expired or invalid URL. +REFUSED_STATUS = frozenset({401, 403, 404, 410}) + +_CACHE_DIR = Path(ZEA_CACHE_DIR) / "hf_locations" + +#: Byte budget of the in-memory blocks shared by all open handles of the same file (see +#: :class:`_SharedBlocks`). +SHARED_BLOCK_BYTES = 256 << 20 # 256 MiB + +_memory: dict[tuple, "Resolved"] = {} +_memory_lock = threading.Lock() +_key_locks: dict[tuple, threading.Lock] = {} + + +@dataclass(frozen=True) +class Resolved: + """The CDN URL and metadata of one ``hf://`` file, as returned by the Hub.""" + + url: str + size: int + etag: str | None + commit: str | None + #: Send the Hub token with requests to ``url``. Only true if ``url`` is on the Hub itself. + send_auth: bool + resolved_at: float + + @property + 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 _origin(url: str) -> tuple[str, str]: + parts = urlsplit(url) + return parts.scheme, parts.netloc + + +def _disk_path(key: tuple) -> Path: + return _CACHE_DIR / f"{hashlib.sha256(repr(key).encode()).hexdigest()}.json" + + +def _load(key: tuple) -> Resolved | None: + try: + resolved = Resolved(**json.loads(_disk_path(key).read_text())) + except (OSError, ValueError, TypeError): + return None + return resolved if resolved.fresh else None + + +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}") + + +def resolve( + hf_path: str, + revision: str | None = None, + repo_type: str = "dataset", + refresh: bool = False, +) -> Resolved: + """Return the CDN URL of an ``hf://`` file, from cache when possible. + + Args: + hf_path (str): An ``hf://org/repo/path/to/file`` path to a single file. + revision (str, optional): Branch, tag or commit hash. Defaults to the default branch. + repo_type (str, optional): One of ``"dataset"``, ``"model"`` or ``"space"``. + refresh (bool, optional): Skip the cache and ask the Hub again, e.g. after the CDN + rejected the cached URL. + + Returns: + Resolved: The CDN URL, size, etag and commit of the file. + """ + 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 + + 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)) + + with _memory_lock: + lock = _key_locks.setdefault(key, threading.Lock()) + # One lock per file, so dataloader threads opening the same file send only one request. + with lock: + if not refresh: + with _memory_lock: + cached = _memory.get(key) + if cached is None or not cached.fresh: + cached = _load(key) + if cached is not None: + with _memory_lock: + _memory[key] = cached + return cached + + url = hf_hub_url(repo_id, subpath, repo_type=repo_type, revision=revision) + meta = _hf_call(get_hf_file_metadata, url, retry_on_errors=True) + if meta.size is None: + raise OSError(f"The Hub did not report a size for '{hf_path}'; cannot stream it.") + resolved = Resolved( + url=meta.location, + size=int(meta.size), + etag=meta.etag, + commit=meta.commit_hash, + send_auth=_origin(meta.location) == _origin(constants.ENDPOINT), + resolved_at=time.time(), + ) + with _memory_lock: + _memory[key] = resolved + _store(key, resolved) + return resolved + + +def clear() -> None: + """Clear all cached URLs (in memory and on disk) and shared file blocks.""" + import shutil + + with _memory_lock: + _memory.clear() + _shared_blocks.clear() + shutil.rmtree(_CACHE_DIR, ignore_errors=True) + + +class SignedURL: + """The current CDN URL of one open file. Refreshed when it expires or is rejected. + + Shared by the h5py file object (:class:`RemoteFile`) and the chunk reader + (:class:`~zea.data.chunk_reader.HTTPFetcher`) of the same file. + """ + + def __init__(self, hf_path: str, revision: str | None = None, repo_type: str = "dataset"): + self.hf_path = hf_path + self.repo_type = repo_type + self._lock = threading.Lock() + self._resolved = resolve(hf_path, revision=revision, repo_type=repo_type) + # Pin later refreshes to this commit, so the file cannot change while open. + self._revision = self._resolved.commit or revision + + @property + def size(self) -> int: + return self._resolved.size + + @property + def etag(self) -> str | None: + return self._resolved.etag + + def _headers(self, resolved: Resolved) -> dict[str, str]: + if not resolved.send_auth: + return {} + from huggingface_hub.utils import build_hf_headers + + return build_hf_headers() + + def current(self) -> tuple[str, dict[str, str]]: + """Return ``(url, headers)``, refreshing the URL first if it is older than + :data:`URL_TTL`. May make a request, so do not call it from an event loop. + """ + resolved = self._resolved + if not resolved.fresh: + self.refresh(resolved.url) + resolved = self._resolved + return resolved.url, self._headers(resolved) + + def refresh(self, stale_url: str) -> bool: + """Resolve again after ``stale_url`` was rejected. Returns whether there is a new URL. + + If several requests fail at once, only the first one asks the Hub. + """ + with self._lock: + if self._resolved.url != stale_url: + return True + resolved = resolve( + self.hf_path, revision=self._revision, repo_type=self.repo_type, refresh=True + ) + if self._resolved.etag and resolved.etag and resolved.etag != self._resolved.etag: + raise OSError( + f"'{self.hf_path}' changed on the Hub while it was open " + f"(etag {self._resolved.etag} -> {resolved.etag}). Reopen the file." + ) + changed = resolved.url != stale_url + self._resolved = resolved + return changed + + +class _SharedBlocks: + """LRU of file blocks, shared by every open handle of the same file in this process. + + h5py holds its global lock while it reads file metadata, so a metadata read that waits on + the network stalls every thread. Dataloader threads each open their own handle of the + same file, so without sharing, every thread re-fetches the same metadata under that lock. + Keyed by etag, so a block is never served for different content. + """ + + def __init__(self, max_bytes: int): + from collections import OrderedDict + + self.max_bytes = max_bytes + self._blocks: "OrderedDict[tuple, bytes]" = OrderedDict() + self._bytes = 0 + self._lock = threading.Lock() + + def get(self, key: tuple) -> bytes | None: + with self._lock: + data = self._blocks.get(key) + if data is not None: + self._blocks.move_to_end(key) + return data + + def put(self, key: tuple, data: bytes) -> None: + with self._lock: + if key in self._blocks: + return + self._blocks[key] = data + self._bytes += len(data) + while self._bytes > self.max_bytes and self._blocks: + _, evicted = self._blocks.popitem(last=False) + self._bytes -= len(evicted) + + def clear(self) -> None: + with self._lock: + self._blocks.clear() + self._bytes = 0 + + +_shared_blocks = _SharedBlocks(SHARED_BLOCK_BYTES) + + +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. + """ + + def __init__(self, location: SignedURL, block_size: int, cache_type: str = "blockcache"): + import fsspec.caching + + from zea.data.chunk_reader import HTTPFetcher + + self.location = location + self.size = location.size + self.blocksize = block_size + #: 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._pos = 0 + self._closed = False + # zea files keep their HDF5 metadata at the start. Fetch that block now, before h5py + # opens the file and takes its global lock, so threads opening different files fetch + # in parallel instead of one after another. + if self.size: + self._fetch(0, min(block_size, self.size)) + + 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: + return hit + data = self._fetcher.read_range(start, end - start) + if key[0] is not None: + _shared_blocks.put(key, data) + return data + + 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) + self._pos += len(data) + return data + + def seek(self, offset: int, whence: int = 0) -> int: + base = {0: 0, 1: self._pos, 2: self.size}[whence] + self._pos = max(0, base + offset) + return self._pos + + def tell(self) -> int: + return self._pos + + def readable(self) -> bool: + return True + + def seekable(self) -> bool: + return True + + def writable(self) -> bool: + return False + + def close(self) -> None: + self._closed = True + + @property + def closed(self) -> bool: + return self._closed + + +def open_remote( + hf_path: str, + revision: str | None = None, + repo_type: str = "dataset", + 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 + + 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, + ) diff --git a/zea/internal/preset_utils.py b/zea/internal/preset_utils.py index aca7b4bcb..3b287464f 100644 --- a/zea/internal/preset_utils.py +++ b/zea/internal/preset_utils.py @@ -9,11 +9,14 @@ See https://huggingface.co/zeahub/ """ +import hashlib +import json import os import threading import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path +from typing import NamedTuple from urllib.parse import quote from huggingface_hub import RepoFile, hf_hub_download, list_repo_tree, login @@ -25,6 +28,7 @@ from zea import log from zea.internal.cache import ZEA_CACHE_DIR +from zea.internal.utils import atomic_write HF_SCHEME = "hf" HF_PREFIX = "hf://" @@ -176,8 +180,11 @@ def clear(self): def _hf_clear_caches() -> None: """Drop the memoized repository listings and resolved download paths.""" + import shutil + _LISTING_CACHE.clear() _DOWNLOAD_CACHE.clear() + shutil.rmtree(_LISTING_DIR, ignore_errors=True) def _cache_key(*parts, **kwargs): @@ -190,8 +197,49 @@ def _cache_key(*parts, **kwargs): return key -def _hf_repo_files(repo_id, repo_type="dataset", **kwargs) -> dict: - """Map every file in a repo to its :class:`~huggingface_hub.RepoFile` (memoized). +# Repo listings are also cached on disk, so processes on one machine (e.g. one per GPU) +# share them. Listing a large repo takes one API request per page (~20 for Open-H-RF). +# Entries expire after _HF_CACHE_TTL, the same as the in-memory cache. +_LISTING_DIR = ZEA_CACHE_DIR / "huggingface" / "listings" + + +class _RepoEntry(NamedTuple): + """What zea needs from a :class:`~huggingface_hub.RepoFile`.""" + + size: int + #: LFS sha256, or the git blob id for non-LFS files. See :func:`_hf_content_id`. + content_id: str | None + + +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" + 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): + 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}") + + +def _hf_repo_files(repo_id, repo_type="dataset", **kwargs) -> "dict[str, _RepoEntry]": + """Map every file in a repo to its size and content id (cached in memory and on disk). ``list_repo_tree`` already carries the sizes and content ids that ``list_repo_files`` throws away, so one listing serves the callers that only want names @@ -200,12 +248,24 @@ def _hf_repo_files(repo_id, repo_type="dataset", **kwargs) -> dict: The returned mapping is shared between callers and must not be mutated. """ + key = _cache_key(repo_id, repo_type, **kwargs) + shared = key is not None and _HF_CACHE_TTL > 0 def _list(): + path = _listing_path(key) if shared else None + if path is not None and (listing := _load_listing(path)) is not None: + return listing entries = _hf_call(list_repo_tree, repo_id, recursive=True, repo_type=repo_type, **kwargs) - return {entry.path: entry for entry in entries if isinstance(entry, RepoFile)} + listing = { + entry.path: _RepoEntry(entry.size, getattr(entry.lfs, "sha256", None) or entry.blob_id) + for entry in entries + if isinstance(entry, RepoFile) + } + if path is not None: + _store_listing(path, listing) + return listing - return _LISTING_CACHE.get_or_call(_cache_key(repo_id, repo_type, **kwargs), _list) + return _LISTING_CACHE.get_or_call(key, _list) def _hf_list_files(repo_id, repo_type="dataset", **kwargs) -> list: @@ -328,10 +388,7 @@ def _hf_content_id(hf_path: str, **kwargs) -> str | None: """ repo_id, subpath = _hf_parse_path(hf_path) entry = _hf_repo_files(repo_id, repo_type="dataset", **kwargs).get(subpath) - if entry is None: - return None - lfs = getattr(entry, "lfs", None) - return getattr(lfs, "sha256", None) or entry.blob_id + return None if entry is None else entry.content_id def _hf_resolve_path(hf_path: str, cache_dir=None, repo_type="dataset", **kwargs) -> Path: @@ -412,13 +469,11 @@ def _hf_stream_url( repo_type: str = "dataset", **kwargs, ) -> str: - """The HTTPS URL the bytes of an ``hf://`` file live at. + """The ``resolve`` URL of an ``hf://`` file. - :func:`_hf_stream_open` streams through :class:`~huggingface_hub.HfFileSystem`, which - is a *sync* filesystem: its ``cat_ranges`` fetches ranges one after another. Concurrent - chunk reads (:mod:`zea.data.chunk_reader`) therefore address this URL directly through - fsspec's async HTTP filesystem instead — measured at one round trip for 16 ranges, - against sixteen through ``HfFileSystem``. + Streamed reads normally use the CDN URL this redirects to (see :mod:`zea.data.hf_remote`), + because each request to the resolve URL counts toward the Hub rate limit. This URL is + only the fallback. Args: hf_path (str): An ``hf://org/repo/path/to/file`` path to a single file. @@ -446,14 +501,13 @@ def _hf_stream_open( repo_type: str = "dataset", block_size: int | None = None, cache_type: str | None = None, - **kwargs, ): """Open a single Hugging Face file lazily for HTTP range-request streaming. - Unlike :func:`_hf_resolve_path`, this does **not** download the whole file. - It returns an open fsspec file object backed by - :class:`~huggingface_hub.HfFileSystem`; only the byte ranges actually read - (e.g. via ``h5py`` slicing) are fetched over HTTP. + Unlike :func:`_hf_resolve_path`, this does **not** download the whole file. It looks up + the file's CDN URL once and returns a file object over it + (:func:`zea.data.hf_remote.open_remote`). Only the byte ranges that are read get fetched, + and those requests do not count toward the Hub rate limit. Args: hf_path (str): A ``hf://org/repo/path/to/file`` path pointing at a @@ -469,31 +523,25 @@ def _hf_stream_open( 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. - **kwargs: Forwarded to :meth:`HfFileSystem.open`. Returns: An open, seekable binary file object. The caller is responsible for closing it. """ - from huggingface_hub import HfFileSystem + from zea.data.hf_remote import open_remote - repo_id, subpath = _hf_parse_path(hf_path) + _, subpath = _hf_parse_path(hf_path) if not subpath: raise ValueError( f"Streaming requires an 'hf://' path to a single file, got '{hf_path}'. " "Point at a specific '.hdf5'/'.h5' file, or pass stream=False to download." ) - - prefix = _hf_repo_type_prefix(repo_type) - ref = f"@{revision}" if revision else "" - fs_path = f"{prefix}{repo_id}{ref}/{subpath}" - - if block_size is None: - block_size = _HF_STREAM_BLOCK_SIZE - if cache_type is None: - cache_type = _HF_STREAM_CACHE_TYPE - - open_kwargs = {"cache_type": cache_type, "block_size": block_size, **kwargs} - # We never pass a token, so `HfFileSystem` resolves one per request: the retry - # picks up a login even though fsspec may hand back the same cached instance. - return _hf_call(lambda: HfFileSystem().open(fs_path, "rb", **open_kwargs)) + _hf_repo_type_prefix(repo_type) # validates + + return open_remote( + hf_path, + revision=revision, + repo_type=repo_type, + block_size=block_size, + cache_type=cache_type, + ) From 62e40e62bb7faf631e36b2f310d9879b3b6f510d Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Mon, 26 Oct 2026 09:05:47 +0000 Subject: [PATCH 02/17] Validate ZEA_MAX_CONCURRENT_REQUESTS and keep the retry log off the event loop - Fall back to the default (with a warning) for a non-numeric or non-positive ZEA_MAX_CONCURRENT_REQUESTS. A non-number broke the import, and 0 made a semaphore no request could acquire. - Log retries with the URL _cat_range already holds instead of self.url, which could refresh a signed URL (a blocking Hub request) on the event loop. Name the file by its hf:// source, since a signed URL is a credential. --- tests/data/test_chunk_reader.py | 37 ++++++++++++++++++++++++++++++++- zea/data/chunk_reader.py | 32 ++++++++++++++++++++++++++-- 2 files changed, 66 insertions(+), 3 deletions(-) diff --git a/tests/data/test_chunk_reader.py b/tests/data/test_chunk_reader.py index 1d1f5f7a3..168b0bea3 100644 --- a/tests/data/test_chunk_reader.py +++ b/tests/data/test_chunk_reader.py @@ -18,7 +18,7 @@ import threading from importlib import import_module import time -from unittest.mock import MagicMock +from unittest.mock import MagicMock, patch import aiohttp import h5py @@ -1067,6 +1067,41 @@ def test_request_cap_is_read_from_the_environment(): 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() + + class TestIsTransient: @pytest.mark.parametrize("status", sorted(chunk_reader.RETRY_STATUS)) def test_transient_statuses(self, status): diff --git a/zea/data/chunk_reader.py b/zea/data/chunk_reader.py index 408f2ca33..96be06336 100644 --- a/zea/data/chunk_reader.py +++ b/zea/data/chunk_reader.py @@ -32,6 +32,7 @@ import os import random import threading +import warnings import zlib from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager @@ -87,12 +88,36 @@ BASE_BACKOFF = 1.0 MAX_BACKOFF = 8.0 + #: Range requests in flight at once, across every fetcher sharing fsspec's event loop, i.e. #: per process (``ZEA_MAX_CONCURRENT_REQUESTS``). Streamed reads go to the CDN, which is not #: rate limited, so this only bounds connections and memory (at most this many merged #: requests of up to :data:`MERGE_MAX` each). Measured with five streaming dataloaders in one #: process: 16 gave ~37 MB/s, 32 to 128 gave ~45-50 MB/s. -MAX_CONCURRENT_REQUESTS = int(os.environ.get("ZEA_MAX_CONCURRENT_REQUESTS", 64)) +def _max_concurrent_requests(default: int = 64) -> int: + """``ZEA_MAX_CONCURRENT_REQUESTS``, or ``default`` if unset or not a positive integer. + + Zero must not get through: it would make a semaphore no request can ever acquire. Warns + with :mod:`warnings`, as ``zea.log`` cannot be imported yet when this module loads. + """ + value = os.environ.get("ZEA_MAX_CONCURRENT_REQUESTS") + if value is None: + return default + try: + parsed = int(value) + except ValueError: + parsed = 0 + if parsed < 1: + warnings.warn( + f"Ignoring ZEA_MAX_CONCURRENT_REQUESTS={value!r}: expected a positive integer. " + f"Using {default}.", + stacklevel=2, + ) + return default + return parsed + + +MAX_CONCURRENT_REQUESTS = _max_concurrent_requests() #: Merge ranges into one request when the gap between them is at most this many bytes. #: The chunks of a frame are stored almost back to back, so a frame (or a block of @@ -383,8 +408,11 @@ async def _cat_range(self, offset: int, size: int, url: str, headers: dict) -> b status = getattr(exc, "status", None) reason = f"HTTP {status}" if status is not None else type(exc).__name__ delay = _retry_delay(attempt, getattr(exc, "headers", None)) + # The local url, not self.url: that may refresh it, which would block the + # event loop. Named by its hf:// source, since a signed URL is a credential. + name = self.source or url.split("?", 1)[0] log.debug( - f"{reason} for {size} bytes at {offset} of {self.url}; " + f"{reason} for {size} bytes at {offset} of {name}; " f"retrying in {delay:.1f}s ({attempt + 1}/{MAX_RETRIES})" ) await asyncio.sleep(delay) From bde3508a320ea1da0fb0f7b8bf917ea0124b0cd2 Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Mon, 26 Oct 2026 09:21:26 +0000 Subject: [PATCH 03/17] Redact signed URLs in fsspec's HTTP debug log fsspec logs every URL it requests on the fsspec.http logger, so enabling debug logging printed the full signed CDN URL, signature included. Add a logging filter to that logger that strips query strings from logged URLs. Requests still use the complete URL. --- tests/data/test_chunk_reader.py | 17 +++++++++++++++++ zea/data/chunk_reader.py | 27 +++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/tests/data/test_chunk_reader.py b/tests/data/test_chunk_reader.py index 168b0bea3..c8ea0f8fa 100644 --- a/tests/data/test_chunk_reader.py +++ b/tests/data/test_chunk_reader.py @@ -13,6 +13,7 @@ import http.server import inspect +import logging import os import socketserver import threading @@ -1102,6 +1103,22 @@ def refresh(self, stale_url): 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() + + class TestIsTransient: @pytest.mark.parametrize("status", sorted(chunk_reader.RETRY_STATUS)) def test_transient_statuses(self, status): diff --git a/zea/data/chunk_reader.py b/zea/data/chunk_reader.py index 96be06336..458dbb737 100644 --- a/zea/data/chunk_reader.py +++ b/zea/data/chunk_reader.py @@ -29,8 +29,10 @@ import asyncio import functools +import logging import os import random +import re import threading import warnings import zlib @@ -186,6 +188,30 @@ def current(self) -> tuple[str, dict[str, str]]: ... def refresh(self, stale_url: str) -> bool: ... +class _RedactQueryStrings(logging.Filter): + """Strip query strings from URLs in log records: they carry the signature of a CDN URL.""" + + _url = re.compile(r"(https?://[^\s?]+)\?\S*") + + def filter(self, record: logging.LogRecord) -> bool: + message = record.getMessage() + redacted = self._url.sub(r"\1?", message) + if redacted != message: + record.msg, record.args = redacted, () + return True + + +_redaction_lock = threading.Lock() + + +def _redact_fsspec_http_logs() -> None: + """Keep signed URLs out of fsspec's HTTP debug log, which logs every requested URL.""" + logger = logging.getLogger("fsspec.http") + with _redaction_lock: + if not any(isinstance(f, _RedactQueryStrings) for f in logger.filters): + logger.addFilter(_RedactQueryStrings()) + + class _FixedURL: """A plain URL that is never refreshed.""" @@ -374,6 +400,7 @@ def __init__(self, url: "str | SignedURL", token: str | None = None, cache=None) self.location = url self.cache = cache # zea.data.chunk_cache.ChunkCache, or None self._fs = fsspec.filesystem("http") + _redact_fsspec_http_logs() @property def url(self) -> str: From 1f4122db004201bfd0576106a7ab6b6b84c3c658 Mon Sep 17 00:00:00 2001 From: Louis van Harten Date: Thu, 29 Oct 2026 13:58:34 +0100 Subject: [PATCH 04/17] fixed potential burst of requests on ttl expiry --- zea/data/hf_remote.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/zea/data/hf_remote.py b/zea/data/hf_remote.py index 8f2faa595..653880df5 100644 --- a/zea/data/hf_remote.py +++ b/zea/data/hf_remote.py @@ -213,16 +213,20 @@ def current(self) -> tuple[str, dict[str, str]]: return resolved.url, self._headers(resolved) def refresh(self, stale_url: str) -> bool: - """Resolve again after ``stale_url`` was rejected. Returns whether there is a new URL. + """Resolve again after ``stale_url`` was rejected or expired. Returns whether there is + a new URL. - If several requests fail at once, only the first one asks the Hub. + Checks the shared cache first to prevent multiple handles of the same file sending + multiple requests. """ with self._lock: if self._resolved.url != stale_url: return True - resolved = resolve( - self.hf_path, revision=self._revision, repo_type=self.repo_type, refresh=True - ) + resolved = resolve(self.hf_path, revision=self._revision, repo_type=self.repo_type) + if resolved == self._resolved: + resolved = resolve( + self.hf_path, revision=self._revision, repo_type=self.repo_type, refresh=True + ) if self._resolved.etag and resolved.etag and resolved.etag != self._resolved.etag: raise OSError( f"'{self.hf_path}' changed on the Hub while it was open " From d3b0c590d085ac49d54fd2ee894d9ded64cdc3bb Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Mon, 2 Nov 2026 15:44:33 +0000 Subject: [PATCH 05/17] improve fetching of small chunks --- tests/data/test_hf_remote.py | 38 ++++++++++++++++++++++++++++++++++++ zea/data/chunk_cache.py | 32 +++++++++++++++++++----------- zea/data/chunk_reader.py | 38 ++++++++++++++++++++++++++++++++---- zea/data/file.py | 6 ++++++ zea/data/hf_remote.py | 19 +++++++++--------- 5 files changed, 109 insertions(+), 24 deletions(-) diff --git a/tests/data/test_hf_remote.py b/tests/data/test_hf_remote.py index 17e8dd2c2..e5c1bdd2f 100644 --- a/tests/data/test_hf_remote.py +++ b/tests/data/test_hf_remote.py @@ -195,3 +195,41 @@ def test_merged_requests_are_counted_once(tmp_path, hub): assert server.count == 1 finally: server.close() + + +@pytest.fixture +def small_cdn(tmp_path, hub, monkeypatch): + """A streamed file whose frames are each below MIN_BYTES, with a private chunk cache.""" + from zea.data import chunk_cache + + monkeypatch.setattr(chunk_cache, "ZEA_CACHE_DIR", tmp_path / "zea-cache") + path = _write(tmp_path / "x.hdf5", _structured()) + server = _CountingServer(tmp_path, latency=0) + hub.location = server.url + path.name + hub.size = path.stat().st_size + yield SimpleNamespace(server=server, path=path) + server.close() + + +def test_small_reads_share_blocks(small_cdn): + """Frame reads below MIN_BYTES are served from the file's blocks, not one request each.""" + with File(HF_PATH, progress=False) as remote, File(small_cdn.path) as local: + assert remote[RAW][0].nbytes < chunk_reader.MIN_BYTES + before = small_cdn.server.count + for i in range(remote[RAW].shape[0]): + got = chunk_reader.read(remote[RAW], i, remote._chunk_fetcher) + np.testing.assert_array_equal(got, local[RAW][i]) + # The whole test file fits in the block fetched on open. + assert small_cdn.server.count == before + + +def test_open_uses_cached_first_block(small_cdn): + """Opening a file whose first block is in the chunk cache sends no request for it, + e.g. in a second dataloader worker process (simulated by clearing the memory caches).""" + with File(HF_PATH, progress=False) as remote: + remote[RAW].shape + hf_remote._shared_blocks.clear() + before = small_cdn.server.count + with File(HF_PATH, progress=False) as remote: + remote[RAW].shape + assert small_cdn.server.count == before diff --git a/zea/data/chunk_cache.py b/zea/data/chunk_cache.py index 8e456eaf0..1f1d0196c 100644 --- a/zea/data/chunk_cache.py +++ b/zea/data/chunk_cache.py @@ -137,6 +137,8 @@ def __init__(self, fileobj, cache: "ChunkCache", block_size: int | None = None): self.details = getattr(fileobj, "details", {}) #: Passed through: the chunk fetcher reuses the file's CDN URL. self.location = getattr(fileobj, "location", None) + # Guards seek + read on a wrapped file object that has no positional read_at. + self._lock = threading.Lock() def _block_bytes(self, index: int) -> bytes: offset = index * self._block @@ -144,21 +146,23 @@ def _block_bytes(self, index: int) -> bytes: hit = self._cache.get(offset, size) if hit is not None: return hit - self._file.seek(offset) - data = self._file.read(size) + if hasattr(self._file, "read_at"): + data = self._file.read_at(offset, size) + else: + with self._lock: + self._file.seek(offset) + data = self._file.read(size) _count_network_bytes(len(data)) self._cache.put(offset, size, data) return data - def read(self, length: int = -1) -> bytes: - if length < 0: - length = self.size - self._pos - length = max(0, min(length, self.size - self._pos)) - if not length: - return b"" - + def read_at(self, offset: int, size: int) -> bytes: + """Read ``size`` bytes at ``offset`` through the cached blocks, without moving the file + position. Safe to call from several threads. + """ + length = max(0, min(size, self.size - offset)) out = bytearray() - pos = self._pos + pos = offset while len(out) < length: index = pos // self._block within = pos - index * self._block @@ -168,9 +172,15 @@ def read(self, length: int = -1) -> bytes: break # short block: end of file out += take pos += len(take) - self._pos = pos return bytes(out) + def read(self, length: int = -1) -> bytes: + if length < 0: + length = self.size - self._pos + data = self.read_at(self._pos, length) + self._pos += len(data) + return data + def seek(self, offset: int, whence: int = 0) -> int: base = {0: 0, 1: self._pos, 2: self.size}[whence] self._pos = max(0, base + offset) diff --git a/zea/data/chunk_reader.py b/zea/data/chunk_reader.py index 458dbb737..f33cad7ac 100644 --- a/zea/data/chunk_reader.py +++ b/zea/data/chunk_reader.py @@ -67,8 +67,8 @@ # Local reads below this are served by h5py: the thread hand-off costs more than it saves. -# Remote reads always take the fast path. Through h5py they would be fetched block by block, -# serially and under h5py's global lock, which stalls every dataloader thread. +# Remote reads below this go through the file's block cache (see Fetcher.fetch_small), not +# through h5py, which would fetch serially and under its global lock. MIN_BYTES = 1 << 20 # 1 MiB # Ceiling on compressed bytes held in memory at once. Bounded by bytes and not by chunk @@ -308,6 +308,12 @@ def fetch(self, ranges: Sequence[tuple[int, int]], on_bytes: Ticker = None) -> l """ raise NotImplementedError + def fetch_small( + self, ranges: Sequence[tuple[int, int]], on_bytes: Ticker = None + ) -> list[bytes]: + """:meth:`fetch` for a read below :data:`MIN_BYTES`. See :meth:`HTTPFetcher.fetch_small`.""" + return self.fetch(ranges, on_bytes) + def pending_bytes(self, ranges: Sequence[tuple[int, int]]) -> int: """Bytes of ``ranges`` that :meth:`fetch` would actually have to stream or download. @@ -399,6 +405,8 @@ def __init__(self, url: "str | SignedURL", token: str | None = None, cache=None) else: self.location = url self.cache = cache # zea.data.chunk_cache.ChunkCache, or None + #: The file object h5py reads through, if it has a block cache (see fetch_small). + self.blocks = None self._fs = fsspec.filesystem("http") _redact_fsspec_http_logs() @@ -484,6 +492,24 @@ async def gather() -> None: sync(self._fs.loop, gather) return cast(list[bytes], out) + 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. + + 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. + """ + 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 + def read_range(self, offset: int, size: int) -> bytes: """Fetch one range without the chunk cache, merging or byte counting. @@ -529,6 +555,8 @@ def fetcher_for(file: h5py.File) -> Fetcher | None: cache = cache_for(details) if getattr(file, "_cache_chunks", True) else None fetcher = HTTPFetcher(location, get_token(), cache) fetcher.source = str(source) # the hf:// path, not the resolved streaming url + if hasattr(stream, "read_at"): + fetcher.blocks = stream return fetcher if getattr(file, "_stream_fileobj", None) is not None: @@ -870,8 +898,10 @@ def read( dtype = dset.dtype itemsize = dtype.itemsize n_selected = int(np.prod([len(indices) for indices, _ in axes])) - if fetcher.per_chunk and n_selected * itemsize < MIN_BYTES: + small = n_selected * itemsize < MIN_BYTES + if fetcher.per_chunk and small: return dset[selection] + fetch = fetcher.fetch_small if small else fetcher.fetch chunks = dset.chunks out = np.empty( @@ -944,7 +974,7 @@ def fetch_and_place(task, on_bytes): # Bounded by *bytes*, since chunk sizes vary hugely across files. for batch in _batched(tasks, MAX_BYTES_IN_FLIGHT): ranges = [(int(t[0].byte_offset), int(t[0].size)) for t in batch] - raws = fetcher.fetch(ranges, on_bytes) + raws = fetch(ranges, on_bytes) list(pool.map(place, batch, raws)) return out diff --git a/zea/data/file.py b/zea/data/file.py index c4bd67514..a97f73535 100644 --- a/zea/data/file.py +++ b/zea/data/file.py @@ -1134,6 +1134,12 @@ def __init__(self, name, mode="r", *args, **kwargs): # Initialize the h5py.File try: + # zea files keep their HDF5 metadata at the start. Fetch that block now, before + # 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"): + stream_fileobj.read_at(0, 1) super().__init__(name, mode, *args, **kwargs) except Exception: if stream_fileobj is not None: diff --git a/zea/data/hf_remote.py b/zea/data/hf_remote.py index 653880df5..befbfbecd 100644 --- a/zea/data/hf_remote.py +++ b/zea/data/hf_remote.py @@ -302,11 +302,6 @@ def __init__(self, location: SignedURL, block_size: int, cache_type: str = "bloc self._cache = fsspec.caching.caches[cache_type](block_size, self._fetch, self.size) self._pos = 0 self._closed = False - # zea files keep their HDF5 metadata at the start. Fetch that block now, before h5py - # opens the file and takes its global lock, so threads opening different files fetch - # in parallel instead of one after another. - if self.size: - self._fetch(0, min(block_size, self.size)) def _fetch(self, start: int, end: int) -> bytes: key = (self.location.etag, start, end) @@ -317,13 +312,19 @@ def _fetch(self, start: int, end: int) -> bytes: _shared_blocks.put(key, data) 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. + """ + end = min(self.size, offset + size) + if end <= offset: + return b"" + return self._cache._fetch(offset, end) + 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 From e465a911713ea53e6a6064a6c2660babae74e35d Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Mon, 2 Nov 2026 16:32:00 +0000 Subject: [PATCH 06/17] Keep large chunks on the merged path and make read_at thread-safe Follow-up to d3b0c590. 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". --- tests/data/test_hf_remote.py | 42 ++++++++++++++++++++++++++++++++++++ zea/data/chunk_cache.py | 1 + zea/data/chunk_reader.py | 23 +++++++++++++------- zea/data/file.py | 6 +++++- zea/data/hf_remote.py | 22 +++++++++++++------ 5 files changed, 79 insertions(+), 15 deletions(-) diff --git a/tests/data/test_hf_remote.py b/tests/data/test_hf_remote.py index e5c1bdd2f..363b36284 100644 --- a/tests/data/test_hf_remote.py +++ b/tests/data/test_hf_remote.py @@ -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)] diff --git a/zea/data/chunk_cache.py b/zea/data/chunk_cache.py index 1f1d0196c..0c30a4e5f 100644 --- a/zea/data/chunk_cache.py +++ b/zea/data/chunk_cache.py @@ -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. diff --git a/zea/data/chunk_reader.py b/zea/data/chunk_reader.py index f33cad7ac..d79771e17 100644 --- a/zea/data/chunk_reader.py +++ b/zea/data/chunk_reader.py @@ -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. diff --git a/zea/data/file.py b/zea/data/file.py index a97f73535..a10fea2f0 100644 --- a/zea/data/file.py +++ b/zea/data/file.py @@ -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 @@ -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 @@ -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: @@ -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: diff --git a/zea/data/hf_remote.py b/zea/data/hf_remote.py index befbfbecd..23f5f7515 100644 --- a/zea/data/hf_remote.py +++ b/zea/data/hf_remote.py @@ -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 From cd2bcb608f2f23c783b395b4e381c9e9f4355916 Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Wed, 4 Nov 2026 12:32:38 +0000 Subject: [PATCH 07/17] Drop cached CDN URLs on upload and reuse branch URLs only as long as the listing _hf_clear_caches() now clears zea.data.hf_remote too, so a file uploaded from this machine is not read through the old signed URL for up to 30 minutes. Opening a file by branch or tag reuses a cached URL no longer than ZEA_HF_CACHE_TTL, so the bytes read and the content id from the listing stay in step. Commit-pinned URLs keep the full URL_TTL. --- tests/data/test_hf_remote.py | 23 +++++++++++++++++++++++ zea/data/hf_remote.py | 26 ++++++++++++++++++++++---- zea/internal/preset_utils.py | 5 ++++- 3 files changed, 49 insertions(+), 5 deletions(-) diff --git a/tests/data/test_hf_remote.py b/tests/data/test_hf_remote.py index 363b36284..1d3e3d561 100644 --- a/tests/data/test_hf_remote.py +++ b/tests/data/test_hf_remote.py @@ -66,6 +66,29 @@ def test_expired_url_is_resolved_again(self, hub, monkeypatch): hf_remote.resolve(HF_PATH) assert len(hub.heads) == 2 + def test_branch_reuse_is_capped_by_the_listing_ttl(self, hub, monkeypatch): + """A branch can move after an upload, so its URL is reused no longer than the listing. + A commit cannot move, so its URL is reused until it expires.""" + from zea.internal import preset_utils + + commit = "c0ffee" * 6 + "c0ff" + monkeypatch.setattr(preset_utils, "_HF_CACHE_TTL", 0) + hf_remote.resolve(HF_PATH) + hf_remote.resolve(HF_PATH) + assert len(hub.heads) == 2 + hf_remote.resolve(HF_PATH, revision=commit) + hf_remote.resolve(HF_PATH, revision=commit) + assert len(hub.heads) == 3 + + def test_clearing_the_hub_caches_drops_urls(self, hub): + """An upload clears the hub caches, so the next open sees the new file.""" + from zea.internal.preset_utils import _hf_clear_caches + + hf_remote.resolve(HF_PATH) + _hf_clear_caches() + hf_remote.resolve(HF_PATH) + assert len(hub.heads) == 2 + def test_refresh_skips_the_cache(self, hub): hf_remote.resolve(HF_PATH) hf_remote.resolve(HF_PATH, refresh=True) diff --git a/zea/data/hf_remote.py b/zea/data/hf_remote.py index 23f5f7515..6b2519896 100644 --- a/zea/data/hf_remote.py +++ b/zea/data/hf_remote.py @@ -15,7 +15,9 @@ ``location``, without the ``Authorization`` header (the token is for the Hub, not the CDN). - The signed URL is treated as opaque. It is reused for :data:`URL_TTL` seconds and - resolved again when it expires or the CDN rejects it. + resolved again when it expires or the CDN rejects it. A branch or tag can point at new + content after an upload, so opening a file by one reuses a cached URL only as long as the + repo listing is cached (``ZEA_HF_CACHE_TTL``). - Re-resolving uses the commit of the first resolve, so the file cannot change while open. - Resolved URLs are cached in memory and on disk, so all threads and processes on a machine (e.g. one process per GPU) share them. The disk cache files are only readable by the user. @@ -25,6 +27,7 @@ import hashlib import json +import re import threading import time from dataclasses import asdict, dataclass @@ -75,6 +78,21 @@ def _token_id(token: str | None) -> str: 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``. + + A commit cannot change, so its URL is reused until it expires. A branch or tag is reused + no longer than the repo listing, so the content id and the bytes read stay in step. + """ + if resolved is None or not resolved.fresh: + return False + if revision is not None and re.fullmatch(r"[0-9a-f]{40}", revision): + return True + from zea.internal.preset_utils import _HF_CACHE_TTL + + return time.time() - resolved.resolved_at < _HF_CACHE_TTL + + def _origin(url: str) -> tuple[str, str]: parts = urlsplit(url) return parts.scheme, parts.netloc @@ -89,7 +107,7 @@ def _load(key: tuple) -> Resolved | None: resolved = Resolved(**json.loads(_disk_path(key).read_text())) except (OSError, ValueError, TypeError): return None - return resolved if resolved.fresh else None + return resolved def _store(key: tuple, resolved: Resolved) -> None: @@ -137,9 +155,9 @@ def resolve( if not refresh: with _memory_lock: cached = _memory.get(key) - if cached is None or not cached.fresh: + if not _reusable(cached, revision): cached = _load(key) - if cached is not None: + if cached is not None and _reusable(cached, revision): with _memory_lock: _memory[key] = cached return cached diff --git a/zea/internal/preset_utils.py b/zea/internal/preset_utils.py index 3b287464f..fb95b91a5 100644 --- a/zea/internal/preset_utils.py +++ b/zea/internal/preset_utils.py @@ -179,9 +179,12 @@ def clear(self): def _hf_clear_caches() -> None: - """Drop the memoized repository listings and resolved download paths.""" + """Drop the memoized repository listings, resolved download paths and CDN URLs.""" import shutil + from zea.data import hf_remote + + hf_remote.clear() _LISTING_CACHE.clear() _DOWNLOAD_CACHE.clear() shutil.rmtree(_LISTING_DIR, ignore_errors=True) From 206600e00aab76d600e4a141e64ed5086da00863 Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Wed, 4 Nov 2026 12:33:46 +0000 Subject: [PATCH 08/17] Ask the Hub at most once per cooldown when a URL refresh gives nothing new When many merged requests are rejected at once with a URL the Hub hands out again (a Hub URL, or a commit-pinned one), each of them used to send its own HEAD, one after another. A refresh that failed or kept the URL now holds off the next one for the same URL for REFRESH_COOLDOWN seconds. --- tests/data/test_hf_remote.py | 21 +++++++++++++++++++++ zea/data/hf_remote.py | 15 ++++++++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/tests/data/test_hf_remote.py b/tests/data/test_hf_remote.py index 1d3e3d561..680b9de4e 100644 --- a/tests/data/test_hf_remote.py +++ b/tests/data/test_hf_remote.py @@ -129,6 +129,27 @@ def test_refresh_happens_once_for_concurrent_failures(self, hub): assert location.refresh("https://cdn.example/signed?1") # already replaced assert len(hub.heads) == 2 + def test_unchanged_url_is_not_refreshed_again_right_away(self, hub): + """Many requests rejected at once with a URL the Hub hands out again (e.g. a Hub URL) + send one request to the Hub, not one each.""" + location = hf_remote.SignedURL(HF_PATH) + for _ in range(5): + assert not location.refresh("https://cdn.example/signed?1") + assert len(hub.heads) == 2 + + def test_failed_refresh_is_not_retried_right_away(self, hub, monkeypatch): + location = hf_remote.SignedURL(HF_PATH) + + def rate_limited(url, **kwargs): + hub.heads.append(url) + raise OSError("429") + + monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", rate_limited) + with pytest.raises(OSError, match="429"): + location.refresh("https://cdn.example/signed?1") + assert not location.refresh("https://cdn.example/signed?1") + assert len(hub.heads) == 2 + def test_content_change_while_open_raises(self, hub): location = hf_remote.SignedURL(HF_PATH) hub.etag = "sha-2" diff --git a/zea/data/hf_remote.py b/zea/data/hf_remote.py index 6b2519896..9fac96170 100644 --- a/zea/data/hf_remote.py +++ b/zea/data/hf_remote.py @@ -42,6 +42,10 @@ #: hour. If that changes, a rejected URL is resolved again anyway. URL_TTL = 30 * 60 +#: Seconds after a refresh that did not give a new URL (it failed, or the URL is the same, +#: e.g. a Hub URL) during which a request rejected with that URL does not ask the Hub again. +REFRESH_COOLDOWN = 30.0 + #: HTTP statuses the CDN returns for an expired or invalid URL. REFUSED_STATUS = frozenset({401, 403, 404, 410}) @@ -204,6 +208,8 @@ def __init__(self, hf_path: str, revision: str | None = None, repo_type: str = " self._resolved = resolve(hf_path, revision=revision, repo_type=repo_type) # Pin later refreshes to this commit, so the file cannot change while open. self._revision = self._resolved.commit or revision + #: ``(stale_url, time)`` of the last refresh, see :data:`REFRESH_COOLDOWN`. + self._last_refresh: tuple[str, float] | None = None @property def size(self) -> int: @@ -235,11 +241,18 @@ def refresh(self, stale_url: str) -> bool: a new URL. Checks the shared cache first to prevent multiple handles of the same file sending - multiple requests. + multiple requests, and asks the Hub at most once per :data:`REFRESH_COOLDOWN` for the + same ``stale_url``, so many rejected requests at once send one request. """ with self._lock: if self._resolved.url != stale_url: return True + last = self._last_refresh + if last is not None and last[0] == stale_url: + if time.time() - last[1] < REFRESH_COOLDOWN: + return False + # Recorded before asking, so a failed request also holds off the next one. + self._last_refresh = (stale_url, time.time()) resolved = resolve(self.hf_path, revision=self._revision, repo_type=self.repo_type) if resolved == self._resolved: resolved = resolve( From 9e9954efbd29eb75d69cd6c78e3574383fe61e52 Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Wed, 4 Nov 2026 12:34:26 +0000 Subject: [PATCH 09/17] Keep using the current URL when its early refresh fails SignedURL refreshes after URL_TTL (30 min) while signed URLs last about an hour, so a Hub error at that point (429, 5xx, network) no longer fails the read: the current URL is used and the CDN decides whether it still works. A changed file still raises, now as FileChangedError. --- tests/data/test_hf_remote.py | 11 +++++++++++ zea/data/hf_remote.py | 17 +++++++++++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/tests/data/test_hf_remote.py b/tests/data/test_hf_remote.py index 680b9de4e..a8dadeafb 100644 --- a/tests/data/test_hf_remote.py +++ b/tests/data/test_hf_remote.py @@ -150,6 +150,17 @@ def rate_limited(url, **kwargs): assert not location.refresh("https://cdn.example/signed?1") assert len(hub.heads) == 2 + def test_failed_early_refresh_keeps_the_current_url(self, hub, monkeypatch): + """Signed URLs outlive URL_TTL, so a Hub outage at that point must not fail reads.""" + location = hf_remote.SignedURL(HF_PATH) + monkeypatch.setattr(hf_remote, "URL_TTL", 0) + + def unavailable(url, **kwargs): + raise RuntimeError("503") + + monkeypatch.setattr("huggingface_hub.get_hf_file_metadata", unavailable) + assert location.current() == ("https://cdn.example/signed?1", {}) + def test_content_change_while_open_raises(self, hub): location = hf_remote.SignedURL(HF_PATH) hub.etag = "sha-2" diff --git a/zea/data/hf_remote.py b/zea/data/hf_remote.py index 9fac96170..02dd108cb 100644 --- a/zea/data/hf_remote.py +++ b/zea/data/hf_remote.py @@ -194,6 +194,10 @@ def clear() -> None: shutil.rmtree(_CACHE_DIR, ignore_errors=True) +class FileChangedError(OSError): + """The content of a file changed on the Hub while it was open.""" + + class SignedURL: """The current CDN URL of one open file. Refreshed when it expires or is rejected. @@ -229,10 +233,19 @@ def _headers(self, resolved: Resolved) -> dict[str, str]: def current(self) -> tuple[str, dict[str, str]]: """Return ``(url, headers)``, refreshing the URL first if it is older than :data:`URL_TTL`. May make a request, so do not call it from an event loop. + + The refresh is early (signed URLs last longer than :data:`URL_TTL`), so if it fails + the current URL is used. If that has expired too, the CDN rejects it and + :meth:`refresh` is called again. """ resolved = self._resolved if not resolved.fresh: - self.refresh(resolved.url) + try: + self.refresh(resolved.url) + except FileChangedError: + raise + except Exception as exc: # noqa: BLE001 — any failure to reach the Hub + log.debug(f"Could not refresh the URL of '{self.hf_path}', reusing it: {exc}") resolved = self._resolved return resolved.url, self._headers(resolved) @@ -259,7 +272,7 @@ def refresh(self, stale_url: str) -> bool: self.hf_path, revision=self._revision, repo_type=self.repo_type, refresh=True ) if self._resolved.etag and resolved.etag and resolved.etag != self._resolved.etag: - raise OSError( + raise FileChangedError( f"'{self.hf_path}' changed on the Hub while it was open " f"(etag {self._resolved.etag} -> {resolved.etag}). Reopen the file." ) From a1381780471cfb41d2d974b1ad69c9baaa0225c6 Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Wed, 4 Nov 2026 12:36:10 +0000 Subject: [PATCH 10/17] Redact signed URLs in the errors of failed range requests fsspec and aiohttp put the requested URL in FileNotFoundError and ClientResponseError, so a request that kept failing showed a working signed CDN URL in tracebacks and logs. Such errors are re-raised with the query string redacted (FileNotFoundError and PermissionError keep their type, others become RemoteReadError with the status). The redaction pattern now also stops at quotes. --- tests/data/test_chunk_reader.py | 22 ++++++++++++++++++++++ zea/data/chunk_reader.py | 31 +++++++++++++++++++++++++++++-- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/tests/data/test_chunk_reader.py b/tests/data/test_chunk_reader.py index c8ea0f8fa..8e8536d42 100644 --- a/tests/data/test_chunk_reader.py +++ b/tests/data/test_chunk_reader.py @@ -1119,6 +1119,28 @@ def test_fsspec_debug_log_redacts_signed_urls(structured_file, caplog): 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): diff --git a/zea/data/chunk_reader.py b/zea/data/chunk_reader.py index d79771e17..4e3a221aa 100644 --- a/zea/data/chunk_reader.py +++ b/zea/data/chunk_reader.py @@ -191,7 +191,7 @@ def refresh(self, stale_url: str) -> bool: ... class _RedactQueryStrings(logging.Filter): """Strip query strings from URLs in log records: they carry the signature of a CDN URL.""" - _url = re.compile(r"(https?://[^\s?]+)\?\S*") + _url = re.compile(r"(https?://[^\s?'\"]+)\?[^\s'\"]*") def filter(self, record: logging.LogRecord) -> bool: message = record.getMessage() @@ -201,6 +201,30 @@ def filter(self, record: logging.LogRecord) -> bool: return True +class RemoteReadError(OSError): + """A failed range request whose message had a signed URL in it (now redacted).""" + + def __init__(self, message: str, status: int | None = None): + super().__init__(message) + self.status = status + + +def _redacted(exc: Exception) -> Exception | None: + """``exc`` with the query strings of its URLs redacted, or ``None`` if it has none. + + fsspec and aiohttp put the requested URL in their errors, and a signed URL is a credential. + """ + message = str(exc) + redacted = _RedactQueryStrings._url.sub(r"\1?", message) + if redacted == message: + return None + if isinstance(exc, FileNotFoundError): + return FileNotFoundError(redacted) + if isinstance(exc, PermissionError): + return PermissionError(redacted) + return RemoteReadError(redacted, getattr(exc, "status", None)) + + _redaction_lock = threading.Lock() @@ -437,7 +461,10 @@ async def _cat_range(self, offset: int, size: int, url: str, headers: dict) -> b url, headers = await asyncio.to_thread(self.location.current) continue if not _is_transient(exc) or attempt >= MAX_RETRIES: - raise + redacted = _redacted(exc) + if redacted is None: + raise + raise redacted from None from zea import log # local, like the fallback warning below: zea imports us status = getattr(exc, "status", None) From 0a2ba874e6614e9c82e1daaf1784870965f2f2c8 Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Wed, 4 Nov 2026 12:37:27 +0000 Subject: [PATCH 11/17] Draw no progress bar for reads below MIN_BYTES Small reads now take the fast path, and their chunks are cached as whole blocks, so pending_bytes never found them and every small read drew a 'streaming' bar, even one served from the cache. A read below MIN_BYTES is one request at most; it gets no bar, as when h5py served it. A progress callback still gets every tick. --- tests/data/test_hf_remote.py | 13 +++++++++++++ zea/data/chunk_reader.py | 2 ++ 2 files changed, 15 insertions(+) diff --git a/tests/data/test_hf_remote.py b/tests/data/test_hf_remote.py index a8dadeafb..2c527fcce 100644 --- a/tests/data/test_hf_remote.py +++ b/tests/data/test_hf_remote.py @@ -330,3 +330,16 @@ def test_no_prefetch_when_nothing_keeps_the_block(small_cdn, monkeypatch): with File(HF_PATH, progress=False, cache=False) as remote: remote[RAW].shape assert calls == [(0, 1)] + + +def test_small_reads_draw_no_progress_bar(small_cdn, monkeypatch): + """A read below MIN_BYTES is one request at most, so it gets no bar (h5py, which served + these reads before, drew none either).""" + from unittest.mock import MagicMock + + tqdm_mock = MagicMock() + monkeypatch.setattr("tqdm.auto.tqdm", tqdm_mock) + with File(HF_PATH, progress=False) as remote: + for _ in range(2): + chunk_reader.read(remote[RAW], 0, remote._chunk_fetcher, progress=True) + tqdm_mock.assert_not_called() diff --git a/zea/data/chunk_reader.py b/zea/data/chunk_reader.py index 4e3a221aa..0f2df1f95 100644 --- a/zea/data/chunk_reader.py +++ b/zea/data/chunk_reader.py @@ -996,6 +996,8 @@ def fetch_and_place(task, on_bytes): # total before a single byte moves — it measures the bytes actually transferred, not a # guess. Ticks arrive from worker threads; tqdm.update is thread-safe. total = sum(int(task[0].size) for task in tasks) + if small and not callable(progress): + progress = False # one quick request at most: a bar would only flash by all_ranges = [(int(task[0].byte_offset), int(task[0].size)) for task in tasks] with _ticker(progress, total, all_ranges, fetcher) as on_bytes: with ThreadPoolExecutor(max_workers=MAX_WORKERS) as pool: From 68c62c768ac9e2b98c4e32bc86a4b3d2913426eb Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Wed, 4 Nov 2026 12:38:44 +0000 Subject: [PATCH 12/17] Check the chunk cache with a stat in pending_bytes pending_bytes only decides whether to draw a progress bar, but it read every cached chunk from disk (and touched its atime) before fetch read it again. ChunkCache.contains checks the file size instead. --- tests/data/test_chunk_cache.py | 2 ++ zea/data/chunk_cache.py | 7 +++++++ zea/data/chunk_reader.py | 2 +- 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/tests/data/test_chunk_cache.py b/tests/data/test_chunk_cache.py index 3df6a4fb1..72417e316 100644 --- a/tests/data/test_chunk_cache.py +++ b/tests/data/test_chunk_cache.py @@ -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) diff --git a/zea/data/chunk_cache.py b/zea/data/chunk_cache.py index 0c30a4e5f..fba57fd97 100644 --- a/zea/data/chunk_cache.py +++ b/zea/data/chunk_cache.py @@ -90,6 +90,13 @@ def get(self, offset: int, size: int) -> bytes | None: pass return data + def contains(self, offset: int, size: int) -> bool: + """Whether this chunk is cached, without reading it.""" + try: + return self._path(offset, size).stat().st_size == size + except OSError: + return False + def put(self, offset: int, size: int, data: bytes) -> None: """Store this chunk. Failure to cache is never an error — it just costs a re-fetch.""" try: diff --git a/zea/data/chunk_reader.py b/zea/data/chunk_reader.py index 0f2df1f95..81224780c 100644 --- a/zea/data/chunk_reader.py +++ b/zea/data/chunk_reader.py @@ -559,7 +559,7 @@ def pending_bytes(self, ranges: Sequence[tuple[int, int]]) -> int: if self.cache is None: return super().pending_bytes(ranges) return sum( - size for offset, size in ranges if self.cache.get(int(offset), int(size)) is None + size for offset, size in ranges if not self.cache.contains(int(offset), int(size)) ) From 7b3d0ec7abcc18070a278d1fb9cc6fe497831600 Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Wed, 4 Nov 2026 12:41:53 +0000 Subject: [PATCH 13/17] Fetch the blocks of a small read concurrently fetch_small read each sub-block chunk with a blocking read_at, so a small read touching chunks in N blocks cost N round trips one after another. The blocks it is missing are now fetched together first, and the chunks are then served from them. --- tests/data/test_hf_remote.py | 21 +++++++++++++++++++++ zea/data/chunk_reader.py | 22 +++++++++++++++++++--- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/tests/data/test_hf_remote.py b/tests/data/test_hf_remote.py index 2c527fcce..e674a81bc 100644 --- a/tests/data/test_hf_remote.py +++ b/tests/data/test_hf_remote.py @@ -343,3 +343,24 @@ def test_small_reads_draw_no_progress_bar(small_cdn, monkeypatch): for _ in range(2): chunk_reader.read(remote[RAW], 0, remote._chunk_fetcher, progress=True) tqdm_mock.assert_not_called() + + +def test_small_reads_fetch_their_blocks_concurrently(tmp_path, hub): + """A small read whose chunks lie in several blocks fetches those blocks together.""" + path = _write(tmp_path / "x.hdf5", _structured()) + server = _CountingServer(tmp_path, latency=0.05) + hub.location, hub.size = server.url + path.name, path.stat().st_size + try: + block = 64 << 10 + with File(HF_PATH, progress=False, cache=False, block_size=block) as remote: + dset = remote[RAW] + chunks = [dset.id.get_chunk_info(i) for i in (3, 4)] + assert all(chunk.size < block for chunk in chunks) + assert len({chunk.byte_offset // block for chunk in chunks}) == 2 + server.peak, before = 0, server.count + got = chunk_reader.read(dset, slice(3, 5), remote._chunk_fetcher) + with File(path) as local: + np.testing.assert_array_equal(got, local[RAW][3:5]) + assert server.count - before == 2 and server.peak == 2 + finally: + server.close() diff --git a/zea/data/chunk_reader.py b/zea/data/chunk_reader.py index 81224780c..ce6439eae 100644 --- a/zea/data/chunk_reader.py +++ b/zea/data/chunk_reader.py @@ -531,15 +531,31 @@ def fetch_small( 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: + blocks = self.blocks + if blocks is None: return self.fetch(ranges, on_bytes) out: list[bytes | None] = [None] * len(ranges) - large = [i for i, (_, size) in enumerate(ranges) if size >= self.blocks.blocksize] + block_size = blocks.blocksize + large = [i for i, (_, size) in enumerate(ranges) if size >= block_size] for i, data in zip(large, self.fetch([ranges[i] for i in large], on_bytes)): out[i] = data + + # Fetch the blocks of the small chunks together, so a read spread over many blocks + # costs one round trip instead of one per block. read_at keeps them for the reads below. + starts = { + start + for i, (offset, size) in enumerate(ranges) + if out[i] is None + for start in range(offset - offset % block_size, offset + size, block_size) + } + if len(starts) > 1: + workers = min(len(starts), MAX_CONCURRENT_REQUESTS) + with ThreadPoolExecutor(max_workers=workers) as pool: + list(pool.map(lambda start: blocks.read_at(start, 1), sorted(starts))) + for i, (offset, size) in enumerate(ranges): if out[i] is None: - out[i] = self.blocks.read_at(int(offset), int(size)) + out[i] = blocks.read_at(int(offset), int(size)) if on_bytes is not None: on_bytes(int(size)) return cast(list[bytes], out) From 3f436354e14d17e538e991af6238d59d19baaf59 Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Wed, 4 Nov 2026 12:43:02 +0000 Subject: [PATCH 14/17] Merge ranges only while a request downloads no more gap bytes than chunk bytes With MERGE_GAP = 1 MiB, a sparse read (one small chunk per frame, frames ~1 MiB apart) merged into 32 MiB requests that were mostly gap, and the bytes in flight were not bounded by MAX_BYTES_IN_FLIGHT, which only counts chunks. A range now joins a request only if the request's gap bytes stay at most its chunk bytes, so the chunks of a frame still go out as one request and the bytes in flight stay within twice the budget. --- tests/data/test_chunk_reader.py | 9 +++++++++ zea/data/chunk_reader.py | 25 ++++++++++++++++++------- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/tests/data/test_chunk_reader.py b/tests/data/test_chunk_reader.py index 8e8536d42..efd490d01 100644 --- a/tests/data/test_chunk_reader.py +++ b/tests/data/test_chunk_reader.py @@ -992,6 +992,15 @@ def test_groups_by_gap_and_size(self, monkeypatch): 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)] diff --git a/zea/data/chunk_reader.py b/zea/data/chunk_reader.py index ce6439eae..177c7440a 100644 --- a/zea/data/chunk_reader.py +++ b/zea/data/chunk_reader.py @@ -72,7 +72,8 @@ MIN_BYTES = 1 << 20 # 1 MiB # Ceiling on compressed bytes held in memory at once. Bounded by bytes and not by chunk -# *count*, because chunk sizes vary hugely across files (12 MB to 166 MB). +# *count*, because chunk sizes vary hugely across files (12 MB to 166 MB). Merged requests +# (see _merge) download at most as many gap bytes as chunk bytes, so at most twice this. MAX_BYTES_IN_FLIGHT = 512 << 20 # 512 MiB # Decode threads. Blosc and zlib release the GIL, so these scale with cores; but the work @@ -121,9 +122,10 @@ def _max_concurrent_requests(default: int = 64) -> int: MAX_CONCURRENT_REQUESTS = _max_concurrent_requests() -#: Merge ranges into one request when the gap between them is at most this many bytes. -#: The chunks of a frame are stored almost back to back, so a frame (or a block of -#: consecutive frames) becomes one request instead of one per chunk. +#: Merge ranges into one request when the gap between them is at most this many bytes, +#: and the request then downloads no more gap bytes than requested ones. The chunks of a +#: frame are stored almost back to back, so a frame (or a block of consecutive frames) +#: becomes one request instead of one per chunk, while a sparse read is not inflated. MERGE_GAP = 1 << 20 # 1 MiB #: Maximum size of a merged request, so large reads are still split over a few parallel @@ -253,18 +255,27 @@ def refresh(self, stale_url: str) -> bool: def _merge(misses: Sequence[tuple[int, int, int]]) -> list[tuple[int, int, list]]: """Group ``(index, offset, size)`` ranges into ``(start, end, members)`` requests. - A range joins the previous request if the gap is at most :data:`MERGE_GAP` and the - request stays within :data:`MERGE_MAX`. Overlapping ranges are allowed. + A range joins the previous request if the gap is at most :data:`MERGE_GAP`, the request + stays within :data:`MERGE_MAX`, and it downloads no more gap bytes than range bytes. + Overlapping ranges are allowed. """ spans: list[tuple[int, int, list]] = [] + wanted = gaps = 0 # range and gap bytes of the last request for miss in sorted(misses, key=lambda m: m[1]): _, offset, size = miss if spans: start, end, members = spans[-1] - if offset - end <= MERGE_GAP and max(end, offset + size) - start <= MERGE_MAX: + gap = max(0, offset - end) + if ( + offset - end <= MERGE_GAP + and max(end, offset + size) - start <= MERGE_MAX + and gaps + gap <= wanted + size + ): spans[-1] = (start, max(end, offset + size), members + [miss]) + wanted, gaps = wanted + size, gaps + gap continue spans.append((offset, offset + size, [miss])) + wanted, gaps = size, 0 return spans From afcc0ef9ce2e92fcec35542cf4246ea44219d8dd Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Wed, 4 Nov 2026 12:54:00 +0000 Subject: [PATCH 15/17] 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. --- tests/data/test_hf_remote.py | 35 ++++++++++++++-------- tests/test_preset_utils.py | 2 +- tests/tools/test_hf.py | 2 +- zea/data/file.py | 7 +++-- zea/data/hf_remote.py | 57 ++++++++++++++++++++---------------- zea/internal/preset_utils.py | 10 +++---- 6 files changed, 66 insertions(+), 47 deletions(-) diff --git a/tests/data/test_hf_remote.py b/tests/data/test_hf_remote.py index e674a81bc..17e795ec0 100644 --- a/tests/data/test_hf_remote.py +++ b/tests/data/test_hf_remote.py @@ -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): @@ -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): diff --git a/tests/test_preset_utils.py b/tests/test_preset_utils.py index 4dce0395c..22cba63a5 100644 --- a/tests/test_preset_utils.py +++ b/tests/test_preset_utils.py @@ -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): diff --git a/tests/tools/test_hf.py b/tests/tools/test_hf.py index 424765a16..09cb719a7 100644 --- a/tests/tools/test_hf.py +++ b/tests/tools/test_hf.py @@ -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}"] diff --git a/zea/data/file.py b/zea/data/file.py index a10fea2f0..5d5e0cfd1 100644 --- a/zea/data/file.py +++ b/zea/data/file.py @@ -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 diff --git a/zea/data/hf_remote.py b/zea/data/hf_remote.py index 02dd108cb..41a37a3d0 100644 --- a/zea/data/hf_remote.py +++ b/zea/data/hf_remote.py @@ -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 @@ -343,31 +342,33 @@ 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) @@ -375,10 +376,7 @@ def read_at(self, offset: int, size: int) -> bytes: 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 @@ -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", ) diff --git a/zea/internal/preset_utils.py b/zea/internal/preset_utils.py index fb95b91a5..8e5a2c40b 100644 --- a/zea/internal/preset_utils.py +++ b/zea/internal/preset_utils.py @@ -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 @@ -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 From dca16d08ac365d03b10cd85dfadfefa784e76d4b Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Wed, 4 Nov 2026 12:55:41 +0000 Subject: [PATCH 16/17] Ask the stream whether it keeps the blocks it reads File prefetched the first block whenever cache_type was not "none", and fetcher_for served small reads from any stream with read_at, whether or not it kept the blocks. RemoteFile and CachedFile now say so themselves (keeps_blocks), and both checks use that: no wasted prefetch, and with cache_type="none" small reads go through fetch, as merged concurrent requests, instead of one request per chunk. --- tests/data/test_hf_remote.py | 9 +++++++++ zea/data/chunk_cache.py | 2 ++ zea/data/chunk_reader.py | 4 ++-- zea/data/file.py | 6 +----- zea/data/hf_remote.py | 5 +++-- 5 files changed, 17 insertions(+), 9 deletions(-) diff --git a/tests/data/test_hf_remote.py b/tests/data/test_hf_remote.py index 17e795ec0..656446257 100644 --- a/tests/data/test_hf_remote.py +++ b/tests/data/test_hf_remote.py @@ -375,3 +375,12 @@ def test_small_reads_fetch_their_blocks_concurrently(tmp_path, hub): assert server.count - before == 2 and server.peak == 2 finally: server.close() + + +def test_small_reads_use_blocks_only_if_the_stream_keeps_them(small_cdn): + """With cache_type="none", serving small reads from blocks would fetch every chunk on + its own, so they go through the merged requests of fetch instead.""" + with File(HF_PATH, progress=False, cache=False, cache_type="none") as remote: + assert remote._chunk_fetcher.blocks is None + with File(HF_PATH, progress=False, cache=False) as remote: + assert remote._chunk_fetcher.blocks is remote._stream_fileobj diff --git a/zea/data/chunk_cache.py b/zea/data/chunk_cache.py index fba57fd97..b70b75a40 100644 --- a/zea/data/chunk_cache.py +++ b/zea/data/chunk_cache.py @@ -145,6 +145,8 @@ def __init__(self, fileobj, cache: "ChunkCache", block_size: int | None = None): self.details = getattr(fileobj, "details", {}) #: Passed through: the chunk fetcher reuses the file's CDN URL. self.location = getattr(fileobj, "location", None) + #: Reads keep the blocks they fetch (in the cache). + self.keeps_blocks = True # Guards seek + read on a wrapped file object that has no positional read_at. self._lock = threading.Lock() diff --git a/zea/data/chunk_reader.py b/zea/data/chunk_reader.py index 177c7440a..c107af901 100644 --- a/zea/data/chunk_reader.py +++ b/zea/data/chunk_reader.py @@ -440,7 +440,7 @@ def __init__(self, url: "str | SignedURL", token: str | None = None, cache=None) else: self.location = url self.cache = cache # zea.data.chunk_cache.ChunkCache, or None - #: The file object h5py reads through, if it has a block cache (see fetch_small). + #: The file object h5py reads through, if it keeps its blocks (see fetch_small). self.blocks = None self._fs = fsspec.filesystem("http") _redact_fsspec_http_logs() @@ -616,7 +616,7 @@ def fetcher_for(file: h5py.File) -> Fetcher | None: cache = cache_for(details) if getattr(file, "_cache_chunks", True) else None fetcher = HTTPFetcher(location, get_token(), cache) fetcher.source = str(source) # the hf:// path, not the resolved streaming url - if hasattr(stream, "read_at"): + if getattr(stream, "keeps_blocks", False): fetcher.blocks = stream return fetcher diff --git a/zea/data/file.py b/zea/data/file.py index 5d5e0cfd1..4ba70a7e7 100644 --- a/zea/data/file.py +++ b/zea/data/file.py @@ -1084,8 +1084,6 @@ 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 @@ -1110,7 +1108,6 @@ 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 @@ -1121,7 +1118,6 @@ 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: @@ -1143,7 +1139,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 keeps_blocks and hasattr(stream_fileobj, "read_at"): + if stream_fileobj is not None and getattr(stream_fileobj, "keeps_blocks", False): stream_fileobj.read_at(0, 1) super().__init__(name, mode, *args, **kwargs) except Exception: diff --git a/zea/data/hf_remote.py b/zea/data/hf_remote.py index 41a37a3d0..eddaec2d8 100644 --- a/zea/data/hf_remote.py +++ b/zea/data/hf_remote.py @@ -342,7 +342,8 @@ def __init__(self, location: SignedURL, block_size: int, keep_blocks: bool = Tru #: 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._keep_blocks = keep_blocks + #: Whether reads keep the blocks they fetch, so reading one ahead pays off. + self.keeps_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 @@ -362,7 +363,7 @@ def read_at(self, offset: int, size: int) -> bytes: end = min(self.size, offset + size) if end <= offset: return b"" - if not self._keep_blocks: + if not self.keeps_blocks: return self._fetcher.read_range(offset, end - offset) out = bytearray() pos = offset From dcd792d97cbc74707c7fd5ea2098fe6f9c61fce4 Mon Sep 17 00:00:00 2001 From: Tristan Stevens Date: Wed, 4 Nov 2026 12:57:45 +0000 Subject: [PATCH 17/17] 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. --- zea/data/hf_remote.py | 32 +++++++++----------------------- zea/internal/preset_utils.py | 31 +++++++++++++------------------ zea/internal/utils.py | 30 ++++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 41 deletions(-) diff --git a/zea/data/hf_remote.py b/zea/data/hf_remote.py index eddaec2d8..175c0c76f 100644 --- a/zea/data/hf_remote.py +++ b/zea/data/hf_remote.py @@ -26,7 +26,6 @@ from __future__ import annotations import hashlib -import json import re import threading import time @@ -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. @@ -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``. @@ -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( @@ -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()) @@ -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 diff --git a/zea/internal/preset_utils.py b/zea/internal/preset_utils.py index 8e5a2c40b..9e1b58f1b 100644 --- a/zea/internal/preset_utils.py +++ b/zea/internal/preset_utils.py @@ -10,7 +10,6 @@ """ import hashlib -import json import os import threading import time @@ -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://" @@ -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]": @@ -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) diff --git a/zea/internal/utils.py b/zea/internal/utils.py index 5e6743d7e..c122105ba 100644 --- a/zea/internal/utils.py +++ b/zea/internal/utils.py @@ -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.