diff --git a/docs/source/environment.rst b/docs/source/environment.rst index c5a56808d..4eecf3aa5 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`` @@ -73,6 +79,13 @@ Here are the environment variables that ``zea`` uses at runtime. Arguably the mo - Byte budget for that cache; least-recently-used chunks are evicted once it is exceeded. - ``10737418240`` (10 GiB) - Any positive integer (bytes). + * - ``ZEA_MAX_CONCURRENT_REQUESTS`` + - Maximum number of HTTP range requests in flight at once per process while streaming + (``hf://``), shared by all open files and dataloaders. Streamed reads go to the Hugging + Face CDN, which is not rate limited, so this only bounds connections and memory. Raise + it when many dataloader threads stream at once; lower it on a slow or shared connection. + - ``64`` + - Any positive integer. * - ``BLOSC_NTHREADS`` - Threads Blosc uses within a single HDF5 chunk, which is most of the write throughput (~4x). Turn it **down** when writes are already parallel (several dataloader workers each diff --git a/tests/conftest.py b/tests/conftest.py index 556f89932..5ce37f05c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -301,6 +301,23 @@ def pytest_terminal_summary(terminalreporter, exitstatus, config): terminalreporter.write_line(f"{count} requiring {', '.join(required_backends)}") +@pytest.fixture(scope="session", autouse=True) +def _isolated_hf_caches(tmp_path_factory): + """Keep the on-disk HF location and listing caches of this session in a temp dir. + + Tests mock repos (some under real names), and CI runners share one ZEA_CACHE_DIR + between concurrent jobs, so those caches must never be written to or wiped there. + """ + from zea.data import hf_remote + from zea.internal import preset_utils + + root = tmp_path_factory.mktemp("hf_caches") + with pytest.MonkeyPatch.context() as mp: + mp.setattr(hf_remote, "_CACHE_DIR", root / "locations") + mp.setattr(preset_utils, "_LISTING_DIR", root / "listings") + yield + + @pytest.fixture(scope="session", autouse=True) def run_once_after_all_tests(): """Fixture to stop workers after all tests have run.""" 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/tests/data/test_chunk_reader.py b/tests/data/test_chunk_reader.py index a521a0c7b..efd490d01 100644 --- a/tests/data/test_chunk_reader.py +++ b/tests/data/test_chunk_reader.py @@ -13,12 +13,13 @@ import http.server import inspect +import logging import os import socketserver import threading from importlib import import_module import time -from unittest.mock import MagicMock +from unittest.mock import MagicMock, patch import aiohttp import h5py @@ -448,6 +449,22 @@ def test_small_read_below_threshold(self, structured_file): np.testing.assert_array_equal(got, file[RAW][selection]) +class TestSmallRemoteReads: + def test_small_remote_read_takes_the_fast_path(self, structured_file): + """A small read over HTTP is still one merged request, not h5py's block-by-block reads.""" + server = _CountingServer(structured_file.parent, latency=0) + try: + fetcher = HTTPFetcher(server.url + structured_file.name) + with File(structured_file) as file: + selection = (0, 0, slice(0, 4)) + got = read(file[RAW], selection, fetcher) + assert got.nbytes < MIN_BYTES + np.testing.assert_array_equal(got, file[RAW][selection]) + assert server.count == 1 + finally: + server.close() + + class TestHumanBytes: @pytest.mark.parametrize( ("n", "expected"), @@ -695,6 +712,11 @@ def send_head(self): self.end_headers() return None path = self.translate_path(self.path) + if not os.path.isfile(path): # an expired or unknown URL + self.send_response(404) + self.send_header("Content-Length", "0") + self.end_headers() + return None with open(path, "rb") as handle: body = handle.read() rng = self.headers.get("Range") @@ -739,6 +761,12 @@ def close(self): pass +@pytest.fixture +def no_merge(monkeypatch): + """Send one request per chunk, for tests about concurrency rather than merging.""" + monkeypatch.setattr(chunk_reader, "MERGE_GAP", -1) + + class TestRemote: def test_http_fetcher_matches_local_bytes(self, structured_file): server = _CountingServer(structured_file.parent, latency=0) @@ -768,7 +796,7 @@ def test_reads_over_http_match_h5py(self, structured_file): finally: server.close() - def test_chunks_are_fetched_concurrently(self, structured_file): + def test_chunks_are_fetched_concurrently(self, structured_file, no_merge): """The point of the remote path: N chunks cost ~1 round trip, not N. Asserted on *peak concurrency* — the maximum number of requests the server held open @@ -906,8 +934,8 @@ def test_a_missing_file_is_not_retried(self, structured_file, fast_backoff): finally: server.close() - def test_requests_in_flight_are_capped(self, structured_file, monkeypatch): - """The cap is what keeps a read from tripping the rate limit in the first place.""" + def test_requests_in_flight_are_capped(self, structured_file, monkeypatch, no_merge): + """No more requests are in flight than the cap allows.""" cap = 2 monkeypatch.setattr(chunk_reader, "MAX_CONCURRENT_REQUESTS", cap) # The semaphore is made once per event loop and cached, so drop whatever earlier @@ -926,6 +954,202 @@ def test_requests_in_flight_are_capped(self, structured_file, monkeypatch): server.close() +class TestMerge: + def test_adjacent_chunks_cost_one_request(self, structured_file): + """A read of neighbouring chunks goes out as one request, and still matches h5py.""" + server = _CountingServer(structured_file.parent, latency=0) + try: + fetcher = HTTPFetcher(server.url + structured_file.name) + with File(structured_file) as file: + got = read(file[RAW], slice(0, 4), fetcher) + np.testing.assert_array_equal(got, file[RAW][0:4]) + assert server.count == 1 + finally: + server.close() + + def test_merged_bytes_are_cached_per_chunk(self, structured_file, tmp_path): + """The cache stores each chunk on its own, so a later partial read is a hit.""" + from zea.data.chunk_cache import ChunkCache + + server = _CountingServer(structured_file.parent, latency=0) + try: + cache = ChunkCache("merge-test", root=tmp_path) + fetcher = HTTPFetcher(server.url + structured_file.name, cache=cache) + with File(structured_file) as file: + read(file[RAW], slice(0, 4), fetcher) + before = server.count + np.testing.assert_array_equal(read(file[RAW], 2, fetcher), file[RAW][2]) + assert server.count == before + finally: + server.close() + + def test_groups_by_gap_and_size(self, monkeypatch): + monkeypatch.setattr(chunk_reader, "MERGE_GAP", 10) + monkeypatch.setattr(chunk_reader, "MERGE_MAX", 100) + misses = [(0, 0, 40), (1, 45, 40), (2, 200, 10), (3, 85, 30)] + spans = chunk_reader._merge(misses) + # 0 and 1 merge (gap 5); 3 would make the request 115 bytes, over the max; 2 is far. + assert [(start, end) for start, end, _ in spans] == [(0, 85), (85, 115), (200, 210)] + assert [[m[0] for m in members] for *_, members in spans] == [[0, 1], [3], [2]] + + def test_sparse_ranges_are_not_inflated(self): + """One small chunk per far-apart frame stays one request each, instead of a request + that is mostly gap.""" + misses = [(i, i * (1 << 20), 64 << 10) for i in range(8)] + assert len(chunk_reader._merge(misses)) == 8 + # Gaps no larger than the chunks still merge. + misses = [(i, i * (128 << 10), 64 << 10) for i in range(8)] + assert len(chunk_reader._merge(misses)) == 1 + + def test_unsorted_and_overlapping_ranges(self): + spans = chunk_reader._merge([(0, 50, 10), (1, 0, 60), (2, 55, 10)]) + assert [(start, end) for start, end, _ in spans] == [(0, 65)] + + +class _Location: + """A SignedURL stand-in: a URL that is rejected until it is refreshed.""" + + def __init__(self, stale, fresh): + self.url, self.fresh, self.refreshes = stale, fresh, 0 + + def current(self): + return self.url, {} + + def refresh(self, stale_url): + if self.url == stale_url: + self.refreshes += 1 + self.url = self.fresh + return True + + +class TestRefusedLocation: + def test_rejected_url_is_refreshed_once(self, structured_file): + server = _CountingServer(structured_file.parent, latency=0) + try: + location = _Location(server.url + "expired.hdf5", server.url + structured_file.name) + fetcher = HTTPFetcher(location) + with File(structured_file) as file: + got = read(file[RAW], slice(0, 4), fetcher) + np.testing.assert_array_equal(got, file[RAW][0:4]) + assert location.refreshes == 1 + finally: + server.close() + + def test_plain_url_is_not_refreshed(self, structured_file, fast_backoff): + server = _CountingServer( + structured_file.parent, latency=0, reject_first=1, reject_status=403 + ) + try: + fetcher = HTTPFetcher(server.url + structured_file.name) + with pytest.raises(aiohttp.ClientResponseError): + fetcher.fetch([(0, 16)]) + assert server.count == 1 + finally: + server.close() + + @pytest.mark.parametrize("status", [401, 403, 410]) + def test_refused_statuses(self, status): + exc = aiohttp.ClientResponseError(MagicMock(), (), status=status) + assert chunk_reader._is_refused(exc) + + def test_missing_file_is_refused(self): + assert chunk_reader._is_refused(FileNotFoundError("x")) + + def test_server_errors_are_not_refusals(self): + exc = aiohttp.ClientResponseError(MagicMock(), (), status=503) + assert not chunk_reader._is_refused(exc) + + +def test_request_cap_is_read_from_the_environment(): + """ZEA_MAX_CONCURRENT_REQUESTS sets the cap (read once, at import).""" + import subprocess + import sys + + env = {**os.environ, "ZEA_MAX_CONCURRENT_REQUESTS": "7", "KERAS_BACKEND": "numpy"} + code = "from zea.data import chunk_reader as c; print(c.MAX_CONCURRENT_REQUESTS)" + out = subprocess.run( + [sys.executable, "-c", code], + env=env, + capture_output=True, + text=True, + check=True, + ) + assert out.stdout.strip().splitlines()[-1] == "7" + + +@pytest.mark.parametrize("value", ["0", "-3", "lots"]) +def test_bad_request_cap_falls_back_to_the_default(monkeypatch, value): + """A cap of zero would hang every request; a non-number would break the import.""" + monkeypatch.setenv("ZEA_MAX_CONCURRENT_REQUESTS", value) + with pytest.warns(UserWarning, match="ZEA_MAX_CONCURRENT_REQUESTS"): + assert chunk_reader._max_concurrent_requests(default=64) == 64 + + +def test_retry_log_does_not_refresh_or_leak_the_url(structured_file, fast_backoff): + """The retry message neither reads ``self.url`` (which may refresh) nor logs a signature.""" + + class Location: + def __init__(self, url): + self.url, self.calls = url, 0 + + def current(self): + self.calls += 1 + return self.url, {} + + def refresh(self, stale_url): + return False + + server = _CountingServer(structured_file.parent, latency=0, reject_first=1) + try: + location = Location(server.url + structured_file.name + "?Signature=secret") + fetcher = HTTPFetcher(location) + with patch("zea.log.debug") as debug: + fetcher.fetch([(0, 16)]) + assert location.calls == 1 # only the one call in fetch(), none from the retry + message = debug.call_args[0][0] + assert "retrying" in message and "secret" not in message + finally: + server.close() + + +def test_fsspec_debug_log_redacts_signed_urls(structured_file, caplog): + """fsspec logs every URL it requests; the signature must not end up in the log.""" + server = _CountingServer(structured_file.parent, latency=0) + try: + url = server.url + structured_file.name + "?Policy=abc&Signature=secret" + fetcher = HTTPFetcher(url) # the test server ignores the query string + with caplog.at_level(logging.DEBUG, logger="fsspec.http"): + data = fetcher.fetch([(0, 16)]) + assert data[0] == structured_file.read_bytes()[:16] # requested with the full URL + logged = [r.getMessage() for r in caplog.records if r.name == "fsspec.http"] + assert any(structured_file.name in m for m in logged) + assert not any("secret" in m or "Policy" in m for m in logged) + finally: + server.close() + + +@pytest.mark.parametrize( + "name, status, error", + [("gone.hdf5", None, FileNotFoundError), (None, 403, chunk_reader.RemoteReadError)], +) +def test_errors_redact_signed_urls(structured_file, name, status, error): + """The error of a failed request names the file, but not the signature of its URL.""" + server = _CountingServer( + structured_file.parent, latency=0, reject_first=100 if status else 0, reject_status=status + ) + try: + name = name or structured_file.name + fetcher = HTTPFetcher(server.url + name + "?Policy=abc&Signature=secret") + with pytest.raises(error) as info: + fetcher.fetch([(0, 16)]) + assert name in str(info.value) and "secret" not in str(info.value) + assert info.value.__suppress_context__ + if status == 403: + assert info.value.status == 403 + finally: + server.close() + + class TestIsTransient: @pytest.mark.parametrize("status", sorted(chunk_reader.RETRY_STATUS)) def test_transient_statuses(self, status): 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..656446257 --- /dev/null +++ b/tests/data/test_hf_remote.py @@ -0,0 +1,386 @@ +"""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_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) + 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_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_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" + 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() + + +@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 + + +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] + + +@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=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): + """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 (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] == (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() + + +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() + + +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/tests/test_preset_utils.py b/tests/test_preset_utils.py index cf2722006..22cba63a5 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, "_block", lambda self, start: bytes(self.blocksize)) + + +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..09cb719a7 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, "_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}"] + 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..b70b75a40 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: @@ -131,10 +138,17 @@ 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. 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() def _block_bytes(self, index: int) -> bytes: offset = index * self._block @@ -142,21 +156,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 @@ -166,9 +182,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) @@ -208,6 +230,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..c107af901 100644 --- a/zea/data/chunk_reader.py +++ b/zea/data/chunk_reader.py @@ -29,21 +29,27 @@ import asyncio import functools +import logging import os import random +import re import threading +import warnings import zlib from concurrent.futures import ThreadPoolExecutor 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,11 +66,14 @@ 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 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 -# *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 @@ -82,9 +91,46 @@ 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. +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, +#: 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 +#: requests. +MERGE_MAX = 32 << 20 # 32 MiB _limiters: "dict[Any, asyncio.Semaphore]" = {} _limiters_lock = threading.Lock() @@ -124,13 +170,121 @@ 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 _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 + + +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() + + +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.""" + + 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`, 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] + 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 + + 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) @@ -189,6 +343,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. @@ -260,44 +420,72 @@ 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 - ) + #: 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() + + @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 + 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) 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) @@ -322,26 +510,83 @@ 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 fetch_small( + self, ranges: Sequence[tuple[int, int]], on_bytes: Ticker = None + ) -> list[bytes]: + """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. 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. + """ + blocks = self.blocks + if blocks is None: + return self.fetch(ranges, on_bytes) + out: list[bytes | None] = [None] * len(ranges) + 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] = 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. + + 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) 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)) ) @@ -359,14 +604,20 @@ 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 + if getattr(stream, "keeps_blocks", False): + fetcher.blocks = stream return fetcher if getattr(file, "_stream_fileobj", None) is not None: @@ -708,8 +959,10 @@ 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: + 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( @@ -770,6 +1023,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: @@ -782,7 +1037,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/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/file.py b/zea/data/file.py index c4bd67514..4ba70a7e7 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 @@ -1134,6 +1135,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 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: if stream_fileobj is not None: diff --git a/zea/data/hf_remote.py b/zea/data/hf_remote.py new file mode 100644 index 000000000..175c0c76f --- /dev/null +++ b/zea/data/hf_remote.py @@ -0,0 +1,419 @@ +""" +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. 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. +""" + +from __future__ import annotations + +import hashlib +import re +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 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. +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}) + +_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 _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 + + +def _disk_path(key: tuple) -> Path: + return _CACHE_DIR / f"{hashlib.sha256(repr(key).encode()).hexdigest()}.json" + + +def _load(key: tuple) -> Resolved | None: + data = load_json_cache(_disk_path(key), URL_TTL) + if not isinstance(data, dict): + return None + try: + return Resolved(**data) + except TypeError: # written by another version of zea + return None + + +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, _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, _hf_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 not _reusable(cached, revision): + cached = _load(key) + if cached is not None and _reusable(cached, revision): + 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_json_cache(_disk_path(key), asdict(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 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. + + 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 + #: ``(stale_url, time)`` of the last refresh, see :data:`REFRESH_COOLDOWN`. + self._last_refresh: tuple[str, float] | None = None + + @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. + + 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: + 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) + + def refresh(self, stale_url: str) -> bool: + """Resolve again after ``stale_url`` was rejected or expired. Returns whether there is + a new URL. + + Checks the shared cache first to prevent multiple handles of the same file sending + 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( + 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 FileChangedError( + 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. + + 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, keep_blocks: bool = True): + 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) + #: 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 + self._closed = False + + 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) + _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. Thread-safe.""" + end = min(self.size, offset + size) + if end <= offset: + return b"" + if not self.keeps_blocks: + return self._fetcher.read_range(offset, end - offset) + out = bytearray() + pos = offset + while pos < end: + start = pos - pos % self.blocksize + block = self._block(start) + out += block[pos - start : end - start] + pos = start + len(block) + return bytes(out) + + def read(self, length: int = -1) -> bytes: + if length is None or length < 0: + length = self.size - self._pos + 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) + 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. + + ``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, + keep_blocks=cache_type != "none", + ) diff --git a/zea/internal/preset_utils.py b/zea/internal/preset_utils.py index aca7b4bcb..9e1b58f1b 100644 --- a/zea/internal/preset_utils.py +++ b/zea/internal/preset_utils.py @@ -9,11 +9,13 @@ See https://huggingface.co/zeahub/ """ +import hashlib 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 +27,7 @@ from zea import log from zea.internal.cache import ZEA_CACHE_DIR +from zea.internal.utils import load_json_cache, store_json_cache HF_SCHEME = "hf" HF_PREFIX = "hf://" @@ -175,9 +178,15 @@ 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) def _cache_key(*parts, **kwargs): @@ -190,8 +199,45 @@ 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 _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 + + 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": + entries = load_json_cache(path, _HF_CACHE_TTL) + if not isinstance(entries, dict): + return None + try: + 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]": + """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 +246,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_json_cache(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 +386,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: @@ -397,7 +452,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 @@ -412,13 +466,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 +498,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 @@ -462,38 +513,33 @@ 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. - **kwargs: Forwarded to :meth:`HfFileSystem.open`. + 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 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, + ) 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.