From 7824caf9728896b3525a94e7935118a7fd153ea8 Mon Sep 17 00:00:00 2001 From: Adrien Date: Wed, 14 Oct 2026 18:20:11 +0200 Subject: [PATCH 1/6] feat(hffs): read file ranges and streams from Xet storage --- src/huggingface_hub/hf_file_system.py | 45 +++++++++++++++++++++++++-- tests/test_hf_file_system.py | 33 +++++++++++++++++--- 2 files changed, 71 insertions(+), 7 deletions(-) diff --git a/src/huggingface_hub/hf_file_system.py b/src/huggingface_hub/hf_file_system.py index dec400e0cc..19bc11ab5f 100644 --- a/src/huggingface_hub/hf_file_system.py +++ b/src/huggingface_hub/hf_file_system.py @@ -33,7 +33,13 @@ from .hf_api import SPECIAL_REFS_REVISION_REGEX, HfApi, LastCommitInfo, RepoFile, RepoFolder from .utils import HFValidationError, XetFileData, hf_raise_for_status, http_backoff, http_stream_backoff, parse_hf_uri from .utils._runtime import is_xet_available -from .utils._xet import XetTokenType, xet_connection_info_refresh_url +from .utils._xet import ( + XetTokenType, + get_xet_session, + refresh_xet_connection_info, + xet_connection_info_refresh_url, + xet_headers_without_auth, +) from .utils.insecure_hashlib import md5 @@ -1109,6 +1115,24 @@ def _get_xet_file_data( ) return XetFileData(file_hash=xet_hash, refresh_route=refresh_route) + def _open_xet_stream( + self, xet_file_data: XetFileData, size: int, start: int, end: int | None = None + ) -> Iterator[bytes]: + """Stream the bytes `[start, end)` of a file from Xet storage.""" + from hf_xet import XetFileInfo + + headers = self._api._build_hf_headers() + connection_info = refresh_xet_connection_info(file_data=xet_file_data, headers=headers) + group = get_xet_session().new_download_stream_group( + endpoint=connection_info.endpoint, + token=connection_info.access_token, + token_expiry_unix_secs=connection_info.expiration_unix_epoch, + token_refresh_url=xet_file_data.refresh_route, + token_refresh_headers=headers, + custom_headers=xet_headers_without_auth(headers), + ) + return group.download_stream(XetFileInfo(xet_file_data.file_hash, size), start=start, end=end) + def get_file(self, rpath, lpath=None, callback=_DEFAULT_CALLBACK, outfile=None, **kwargs) -> None: """ Copy single remote file to local. @@ -1241,6 +1265,8 @@ def __del__(self): return super().__del__() def _fetch_range(self, start: int, end: int) -> bytes: + if (xet_file_data := self.fs._get_xet_file_data(self.resolved_path, self.details)) is not None: + return b"".join(self.fs._open_xet_stream(xet_file_data, self.size, start=start, end=end)) headers = { "range": f"bytes={start}-{end - 1}", **self.fs._api._build_hf_headers(), @@ -1343,13 +1369,13 @@ def read(self, length: int = -1): If reading the stream fails, we retry with a new connection. """ - if self.response is None: + if self._stream_iterator is None: self._open_connection() retried_once = False while True: try: - if self.response is None or self._stream_iterator is None: + if self._stream_iterator is None: return b"" # Already read the entire file out = self._read_from_stream(self._stream_iterator, length) self.loc += len(out) @@ -1410,12 +1436,25 @@ def __del__(self): def __reduce__(self): return reopen, (self.fs, self.path, self.mode, self.blocksize, self.cache.name) + def _get_xet_file_data(self) -> XetFileData | None: + if not is_xet_available(): + return None + if self.size is None: + self.details = self.fs.info(self.path) + self.size = self.details["size"] + return self.fs._get_xet_file_data(self.resolved_path, self.details) + def _open_connection(self): """Open a connection to the remote file.""" # reset streaming state self._stream_buffer.clear() self._stream_iterator = None + if (xet_file_data := self._get_xet_file_data()) is not None: + if self.loc < self.size: + self._stream_iterator = self.fs._open_xet_stream(xet_file_data, self.size, start=self.loc) + return + url = self.url() headers = self.fs._api._build_hf_headers() if self.loc > 0: diff --git a/tests/test_hf_file_system.py b/tests/test_hf_file_system.py index abd849f45f..a8cee69222 100644 --- a/tests/test_hf_file_system.py +++ b/tests/test_hf_file_system.py @@ -118,17 +118,17 @@ def test_stream_file_retry(self): assert isinstance(f, HfFileSystemStreamFile) assert f.read(6) == b"dummy " # Simulate that streaming fails mid-way - f.response = None + f._stream_iterator = None assert f.read(6) == b"binary" - assert f.response is not None # a new connection has been created + assert f._stream_iterator is not None # a new stream has been opened def test_stream_file_reuse_response(self): with self.hffs.open(self.hf_path + "/data/binary_data.bin", block_size=0) as f: assert isinstance(f, HfFileSystemStreamFile) assert f.read(6) == b"dummy " - first_response = f.response + first_stream = f._stream_iterator assert f.read(6) == b"binary" - assert f.response == first_response + assert f._stream_iterator is first_stream def _make_stream_file_with_fake_response(self, chunks: Iterable[bytes]): """Helper: create iterator from specified chunks to simulate a stream response.""" @@ -636,6 +636,31 @@ def test_get_file_with_xet(self): assert Path(temp_dir, "pr.bin").read_bytes() == b"dummy binary data on pr" assert xet_mock.call_count == 2 + @pytest.mark.xet + def test_read_range_with_xet(self): + with ( + patch.object(self.hffs, "_open_xet_stream", wraps=self.hffs._open_xet_stream) as xet_mock, + patch.object(hf_file_system, "http_backoff") as http_mock, + ): + with self.hffs.open(self.hf_path + "/data/binary_data.bin", "rb", block_size=4) as f: + f.seek(6) + assert f.read(6) == b"binary" + assert xet_mock.called + http_mock.assert_not_called() + + @pytest.mark.xet + def test_stream_with_xet(self): + with ( + patch.object(self.hffs, "_open_xet_stream", wraps=self.hffs._open_xet_stream) as xet_mock, + patch.object(hf_file_system, "http_stream_backoff") as http_mock, + ): + with self.hffs.open(self.hf_path + "/data/binary_data.bin", "rb", block_size=0) as f: + assert f.read(6) == b"dummy " + assert f.read() == b"binary data" + assert f.read() == b"" + assert xet_mock.call_count == 1 + http_mock.assert_not_called() + def test_list_data_directory_with_revision(self): files = self.hffs.ls(self.hf_path + "@refs%2Fpr%2F1" + "/data") From 27861bf699b18dd404dd83d96dad604ca339e232 Mon Sep 17 00:00:00 2001 From: Adrien Date: Wed, 14 Oct 2026 18:32:27 +0200 Subject: [PATCH 2/6] refactor(hffs): reuse one Xet stream group per open file --- src/huggingface_hub/file_download.py | 16 ++------- src/huggingface_hub/hf_file_system.py | 50 ++++++++++++--------------- src/huggingface_hub/utils/_xet.py | 16 +++++++++ tests/test_hf_file_system.py | 4 +-- 4 files changed, 44 insertions(+), 42 deletions(-) diff --git a/src/huggingface_hub/file_download.py b/src/huggingface_hub/file_download.py index 2e332ac078..e2c58be0b8 100644 --- a/src/huggingface_hub/file_download.py +++ b/src/huggingface_hub/file_download.py @@ -565,14 +565,12 @@ def xet_get( if len(displayed_filename) > 40: displayed_filename = f"{displayed_filename[:40]}(…)" - from .utils._xet import abort_xet_session, get_xet_session, refresh_xet_connection_info, xet_headers_without_auth + from .utils._xet import abort_xet_session, get_xet_session, xet_download_group_kwargs from .utils._xet_progress_reporting import XetDownloadProgressReporter - xet_headers = xet_headers_without_auth(headers) - # Fetched once per repo revision and cached; otherwise each download group would request its own # token, i.e. one Hub API call per file (rate-limited on large snapshot downloads, see #4722). - connection_info = refresh_xet_connection_info(file_data=xet_file_data, headers=headers) + group_kwargs = xet_download_group_kwargs(xet_file_data, headers) session = get_xet_session() @@ -586,15 +584,7 @@ def xet_get( external_reconstruction_bar=_tqdm_bar, ) as progress: try: - with session.new_file_download_group( - endpoint=connection_info.endpoint, - token=connection_info.access_token, - token_expiry_unix_secs=connection_info.expiration_unix_epoch, - token_refresh_url=xet_file_data.refresh_route, - token_refresh_headers=headers, - custom_headers=xet_headers, - progress_callback=progress.update_progress, - ) as group: + with session.new_file_download_group(**group_kwargs, progress_callback=progress.update_progress) as group: group.start_download_file( XetFileInfo(xet_file_data.file_hash, expected_size), str(incomplete_path.absolute()) ) diff --git a/src/huggingface_hub/hf_file_system.py b/src/huggingface_hub/hf_file_system.py index 19bc11ab5f..6484ba35a4 100644 --- a/src/huggingface_hub/hf_file_system.py +++ b/src/huggingface_hub/hf_file_system.py @@ -3,11 +3,12 @@ import tempfile import threading from collections import deque -from collections.abc import Iterable, Iterator +from collections.abc import Callable, Iterable, Iterator from contextlib import ExitStack from copy import deepcopy from dataclasses import dataclass, field from datetime import datetime +from functools import cached_property, partial from pathlib import Path, PurePosixPath from typing import Any, NoReturn, Union from urllib.parse import quote, unquote @@ -33,13 +34,7 @@ from .hf_api import SPECIAL_REFS_REVISION_REGEX, HfApi, LastCommitInfo, RepoFile, RepoFolder from .utils import HFValidationError, XetFileData, hf_raise_for_status, http_backoff, http_stream_backoff, parse_hf_uri from .utils._runtime import is_xet_available -from .utils._xet import ( - XetTokenType, - get_xet_session, - refresh_xet_connection_info, - xet_connection_info_refresh_url, - xet_headers_without_auth, -) +from .utils._xet import XetTokenType, get_xet_session, xet_connection_info_refresh_url, xet_download_group_kwargs from .utils.insecure_hashlib import md5 @@ -1115,23 +1110,18 @@ def _get_xet_file_data( ) return XetFileData(file_hash=xet_hash, refresh_route=refresh_route) - def _open_xet_stream( - self, xet_file_data: XetFileData, size: int, start: int, end: int | None = None - ) -> Iterator[bytes]: - """Stream the bytes `[start, end)` of a file from Xet storage.""" + def _xet_stream_opener( + self, resolved_path: HfFileSystemResolvedRepositoryPath | HfFileSystemResolvedBucketPath, info: dict[str, Any] + ) -> Callable[..., Iterator[bytes]] | None: + """Return `open(start=..., end=...)`, which streams bytes of the file from Xet storage, or None if the file is not in Xet.""" + if (xet_file_data := self._get_xet_file_data(resolved_path, info)) is None: + return None from hf_xet import XetFileInfo - headers = self._api._build_hf_headers() - connection_info = refresh_xet_connection_info(file_data=xet_file_data, headers=headers) group = get_xet_session().new_download_stream_group( - endpoint=connection_info.endpoint, - token=connection_info.access_token, - token_expiry_unix_secs=connection_info.expiration_unix_epoch, - token_refresh_url=xet_file_data.refresh_route, - token_refresh_headers=headers, - custom_headers=xet_headers_without_auth(headers), + **xet_download_group_kwargs(xet_file_data, self._api._build_hf_headers()) ) - return group.download_stream(XetFileInfo(xet_file_data.file_hash, size), start=start, end=end) + return partial(group.download_stream, XetFileInfo(xet_file_data.file_hash, info["size"])) def get_file(self, rpath, lpath=None, callback=_DEFAULT_CALLBACK, outfile=None, **kwargs) -> None: """ @@ -1265,8 +1255,8 @@ def __del__(self): return super().__del__() def _fetch_range(self, start: int, end: int) -> bytes: - if (xet_file_data := self.fs._get_xet_file_data(self.resolved_path, self.details)) is not None: - return b"".join(self.fs._open_xet_stream(xet_file_data, self.size, start=start, end=end)) + if self._open_xet_stream is not None: + return b"".join(self._open_xet_stream(start=start, end=end)) headers = { "range": f"bytes={start}-{end - 1}", **self.fs._api._build_hf_headers(), @@ -1276,6 +1266,10 @@ def _fetch_range(self, start: int, end: int) -> bytes: hf_raise_for_status(r) return r.content + @cached_property + def _open_xet_stream(self) -> Callable[..., Iterator[bytes]] | None: + return self.fs._xet_stream_opener(self.resolved_path, self.details) + def _initiate_upload(self) -> None: self.temp_file = tempfile.NamedTemporaryFile(prefix="hffs-", delete=False) @@ -1436,13 +1430,15 @@ def __del__(self): def __reduce__(self): return reopen, (self.fs, self.path, self.mode, self.blocksize, self.cache.name) - def _get_xet_file_data(self) -> XetFileData | None: + @cached_property + def _open_xet_stream(self) -> Callable[..., Iterator[bytes]] | None: + # Checked first to skip the `info()` call when hf_xet is not installed if not is_xet_available(): return None if self.size is None: self.details = self.fs.info(self.path) self.size = self.details["size"] - return self.fs._get_xet_file_data(self.resolved_path, self.details) + return self.fs._xet_stream_opener(self.resolved_path, self.details) def _open_connection(self): """Open a connection to the remote file.""" @@ -1450,9 +1446,9 @@ def _open_connection(self): self._stream_buffer.clear() self._stream_iterator = None - if (xet_file_data := self._get_xet_file_data()) is not None: + if self._open_xet_stream is not None: if self.loc < self.size: - self._stream_iterator = self.fs._open_xet_stream(xet_file_data, self.size, start=self.loc) + self._stream_iterator = self._open_xet_stream(start=self.loc) return url = self.url() diff --git a/src/huggingface_hub/utils/_xet.py b/src/huggingface_hub/utils/_xet.py index 9847b9c933..f19ed61964 100644 --- a/src/huggingface_hub/utils/_xet.py +++ b/src/huggingface_hub/utils/_xet.py @@ -322,6 +322,22 @@ def xet_headers_without_auth(headers: dict[str, str]) -> dict[str, str]: return {key: value for key, value in headers.items() if key.lower() != "authorization"} +def xet_download_group_kwargs(file_data: XetFileData, headers: dict[str, str]) -> dict[str, Any]: + """Return the connection arguments of an hf_xet download group for a file. + + The connection info is cached per repo revision, so building a group does not request a new token. + """ + connection_info = refresh_xet_connection_info(file_data=file_data, headers=headers) + return { + "endpoint": connection_info.endpoint, + "token": connection_info.access_token, + "token_expiry_unix_secs": connection_info.expiration_unix_epoch, + "token_refresh_url": file_data.refresh_route, + "token_refresh_headers": headers, + "custom_headers": xet_headers_without_auth(headers), + } + + def abort_xet_session(): """Abort the global xet session after a KeyboardInterrupt. diff --git a/tests/test_hf_file_system.py b/tests/test_hf_file_system.py index a8cee69222..19c907d6c7 100644 --- a/tests/test_hf_file_system.py +++ b/tests/test_hf_file_system.py @@ -639,7 +639,7 @@ def test_get_file_with_xet(self): @pytest.mark.xet def test_read_range_with_xet(self): with ( - patch.object(self.hffs, "_open_xet_stream", wraps=self.hffs._open_xet_stream) as xet_mock, + patch.object(self.hffs, "_xet_stream_opener", wraps=self.hffs._xet_stream_opener) as xet_mock, patch.object(hf_file_system, "http_backoff") as http_mock, ): with self.hffs.open(self.hf_path + "/data/binary_data.bin", "rb", block_size=4) as f: @@ -651,7 +651,7 @@ def test_read_range_with_xet(self): @pytest.mark.xet def test_stream_with_xet(self): with ( - patch.object(self.hffs, "_open_xet_stream", wraps=self.hffs._open_xet_stream) as xet_mock, + patch.object(self.hffs, "_xet_stream_opener", wraps=self.hffs._xet_stream_opener) as xet_mock, patch.object(hf_file_system, "http_stream_backoff") as http_mock, ): with self.hffs.open(self.hf_path + "/data/binary_data.bin", "rb", block_size=0) as f: From 3af5e7b967e19c9782d0d867817e245a16dc0bc3 Mon Sep 17 00:00:00 2001 From: Adrien Date: Wed, 14 Oct 2026 18:43:59 +0200 Subject: [PATCH 3/6] fix(hffs): open the Xet stream group from the current session on each read --- src/huggingface_hub/hf_file_system.py | 42 +++++++++++++++------------ tests/test_hf_file_system.py | 4 +-- 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/src/huggingface_hub/hf_file_system.py b/src/huggingface_hub/hf_file_system.py index 6484ba35a4..2d4c708f26 100644 --- a/src/huggingface_hub/hf_file_system.py +++ b/src/huggingface_hub/hf_file_system.py @@ -3,12 +3,12 @@ import tempfile import threading from collections import deque -from collections.abc import Callable, Iterable, Iterator +from collections.abc import Iterable, Iterator from contextlib import ExitStack from copy import deepcopy from dataclasses import dataclass, field from datetime import datetime -from functools import cached_property, partial +from functools import cached_property from pathlib import Path, PurePosixPath from typing import Any, NoReturn, Union from urllib.parse import quote, unquote @@ -34,7 +34,13 @@ from .hf_api import SPECIAL_REFS_REVISION_REGEX, HfApi, LastCommitInfo, RepoFile, RepoFolder from .utils import HFValidationError, XetFileData, hf_raise_for_status, http_backoff, http_stream_backoff, parse_hf_uri from .utils._runtime import is_xet_available -from .utils._xet import XetTokenType, get_xet_session, xet_connection_info_refresh_url, xet_download_group_kwargs +from .utils._xet import ( + XetTokenType, + abort_xet_session, + get_xet_session, + xet_connection_info_refresh_url, + xet_download_group_kwargs, +) from .utils.insecure_hashlib import md5 @@ -1110,18 +1116,18 @@ def _get_xet_file_data( ) return XetFileData(file_hash=xet_hash, refresh_route=refresh_route) - def _xet_stream_opener( - self, resolved_path: HfFileSystemResolvedRepositoryPath | HfFileSystemResolvedBucketPath, info: dict[str, Any] - ) -> Callable[..., Iterator[bytes]] | None: - """Return `open(start=..., end=...)`, which streams bytes of the file from Xet storage, or None if the file is not in Xet.""" - if (xet_file_data := self._get_xet_file_data(resolved_path, info)) is None: - return None + def _read_xet(self, xet_file_data: XetFileData, size: int, start: int, end: int | None = None) -> Iterator[bytes]: + """Stream the bytes `[start, end)` of a file from Xet storage.""" from hf_xet import XetFileInfo group = get_xet_session().new_download_stream_group( **xet_download_group_kwargs(xet_file_data, self._api._build_hf_headers()) ) - return partial(group.download_stream, XetFileInfo(xet_file_data.file_hash, info["size"])) + try: + yield from group.download_stream(XetFileInfo(xet_file_data.file_hash, size), start=start, end=end) + except KeyboardInterrupt: + abort_xet_session() + raise def get_file(self, rpath, lpath=None, callback=_DEFAULT_CALLBACK, outfile=None, **kwargs) -> None: """ @@ -1255,8 +1261,8 @@ def __del__(self): return super().__del__() def _fetch_range(self, start: int, end: int) -> bytes: - if self._open_xet_stream is not None: - return b"".join(self._open_xet_stream(start=start, end=end)) + if self._xet_file_data is not None: + return b"".join(self.fs._read_xet(self._xet_file_data, self.size, start=start, end=end)) headers = { "range": f"bytes={start}-{end - 1}", **self.fs._api._build_hf_headers(), @@ -1267,8 +1273,8 @@ def _fetch_range(self, start: int, end: int) -> bytes: return r.content @cached_property - def _open_xet_stream(self) -> Callable[..., Iterator[bytes]] | None: - return self.fs._xet_stream_opener(self.resolved_path, self.details) + def _xet_file_data(self) -> XetFileData | None: + return self.fs._get_xet_file_data(self.resolved_path, self.details) def _initiate_upload(self) -> None: self.temp_file = tempfile.NamedTemporaryFile(prefix="hffs-", delete=False) @@ -1431,14 +1437,14 @@ def __reduce__(self): return reopen, (self.fs, self.path, self.mode, self.blocksize, self.cache.name) @cached_property - def _open_xet_stream(self) -> Callable[..., Iterator[bytes]] | None: + def _xet_file_data(self) -> XetFileData | None: # Checked first to skip the `info()` call when hf_xet is not installed if not is_xet_available(): return None if self.size is None: self.details = self.fs.info(self.path) self.size = self.details["size"] - return self.fs._xet_stream_opener(self.resolved_path, self.details) + return self.fs._get_xet_file_data(self.resolved_path, self.details) def _open_connection(self): """Open a connection to the remote file.""" @@ -1446,9 +1452,9 @@ def _open_connection(self): self._stream_buffer.clear() self._stream_iterator = None - if self._open_xet_stream is not None: + if self._xet_file_data is not None: if self.loc < self.size: - self._stream_iterator = self._open_xet_stream(start=self.loc) + self._stream_iterator = self.fs._read_xet(self._xet_file_data, self.size, start=self.loc) return url = self.url() diff --git a/tests/test_hf_file_system.py b/tests/test_hf_file_system.py index 19c907d6c7..00363a400e 100644 --- a/tests/test_hf_file_system.py +++ b/tests/test_hf_file_system.py @@ -639,7 +639,7 @@ def test_get_file_with_xet(self): @pytest.mark.xet def test_read_range_with_xet(self): with ( - patch.object(self.hffs, "_xet_stream_opener", wraps=self.hffs._xet_stream_opener) as xet_mock, + patch.object(self.hffs, "_read_xet", wraps=self.hffs._read_xet) as xet_mock, patch.object(hf_file_system, "http_backoff") as http_mock, ): with self.hffs.open(self.hf_path + "/data/binary_data.bin", "rb", block_size=4) as f: @@ -651,7 +651,7 @@ def test_read_range_with_xet(self): @pytest.mark.xet def test_stream_with_xet(self): with ( - patch.object(self.hffs, "_xet_stream_opener", wraps=self.hffs._xet_stream_opener) as xet_mock, + patch.object(self.hffs, "_read_xet", wraps=self.hffs._read_xet) as xet_mock, patch.object(hf_file_system, "http_stream_backoff") as http_mock, ): with self.hffs.open(self.hf_path + "/data/binary_data.bin", "rb", block_size=0) as f: From 94a021dee01e77a82fc79c15308a23285005850d Mon Sep 17 00:00:00 2001 From: Adrien Date: Wed, 14 Oct 2026 19:01:09 +0200 Subject: [PATCH 4/6] perf(hffs): share one Xet stream group per repo revision --- src/huggingface_hub/hf_file_system.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/huggingface_hub/hf_file_system.py b/src/huggingface_hub/hf_file_system.py index 2d4c708f26..684e1cf6e2 100644 --- a/src/huggingface_hub/hf_file_system.py +++ b/src/huggingface_hub/hf_file_system.py @@ -239,6 +239,8 @@ def __init__( self._repo_and_revision_exists_cache: dict[tuple[str, str, str | None], tuple[bool, Exception | None]] = {} # Same for buckets self._bucket_exists_cache: dict[str, tuple[bool, Exception | None]] = {} + # Xet session and download stream group per token refresh route (i.e. per repo revision) + self._xet_stream_groups: dict[str, tuple[Any, Any]] = {} # Note: special case for buckets: revision is always None # Maps parent directory path to path infos self.dircache: dict[str, list[dict[str, Any]]] = {} @@ -1120,11 +1122,17 @@ def _read_xet(self, xet_file_data: XetFileData, size: int, start: int, end: int """Stream the bytes `[start, end)` of a file from Xet storage.""" from hf_xet import XetFileInfo - group = get_xet_session().new_download_stream_group( - **xet_download_group_kwargs(xet_file_data, self._api._build_hf_headers()) - ) + # Files of a revision share one group, so they share its connection pool. The group is rebuilt when the + # session changes (after `abort_xet_session` or in a forked process). + session = get_xet_session() + cached = self._xet_stream_groups.get(xet_file_data.refresh_route) + if cached is None or cached[0] is not session: + group = session.new_download_stream_group( + **xet_download_group_kwargs(xet_file_data, self._api._build_hf_headers()) + ) + cached = self._xet_stream_groups[xet_file_data.refresh_route] = (session, group) try: - yield from group.download_stream(XetFileInfo(xet_file_data.file_hash, size), start=start, end=end) + yield from cached[1].download_stream(XetFileInfo(xet_file_data.file_hash, size), start=start, end=end) except KeyboardInterrupt: abort_xet_session() raise From 6715c4af1594c23d7f8b4459b032f6dc3acd976a Mon Sep 17 00:00:00 2001 From: Adrien Date: Wed, 14 Oct 2026 19:08:20 +0200 Subject: [PATCH 5/6] fix(hffs): key the shared Xet stream groups by process and token --- src/huggingface_hub/hf_file_system.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/huggingface_hub/hf_file_system.py b/src/huggingface_hub/hf_file_system.py index 684e1cf6e2..0b6580de08 100644 --- a/src/huggingface_hub/hf_file_system.py +++ b/src/huggingface_hub/hf_file_system.py @@ -36,6 +36,7 @@ from .utils._runtime import is_xet_available from .utils._xet import ( XetTokenType, + _cache_key, abort_xet_session, get_xet_session, xet_connection_info_refresh_url, @@ -239,7 +240,7 @@ def __init__( self._repo_and_revision_exists_cache: dict[tuple[str, str, str | None], tuple[bool, Exception | None]] = {} # Same for buckets self._bucket_exists_cache: dict[str, tuple[bool, Exception | None]] = {} - # Xet session and download stream group per token refresh route (i.e. per repo revision) + # Xet session and download stream group per process, repo revision and token self._xet_stream_groups: dict[str, tuple[Any, Any]] = {} # Note: special case for buckets: revision is always None # Maps parent directory path to path infos @@ -1122,15 +1123,16 @@ def _read_xet(self, xet_file_data: XetFileData, size: int, start: int, end: int """Stream the bytes `[start, end)` of a file from Xet storage.""" from hf_xet import XetFileInfo - # Files of a revision share one group, so they share its connection pool. The group is rebuilt when the - # session changes (after `abort_xet_session` or in a forked process). + # Files of a revision share one group, so they share its connection pool. The key holds the PID so that a + # forked process never drops the groups of its parent (a group is not fork-safe), and the token so that a + # new token gets a group with up-to-date refresh headers. The group is rebuilt after `abort_xet_session`. + headers = self._api._build_hf_headers() + key = f"{os.getpid()}|{_cache_key(xet_file_data.refresh_route, headers)}" session = get_xet_session() - cached = self._xet_stream_groups.get(xet_file_data.refresh_route) + cached = self._xet_stream_groups.get(key) if cached is None or cached[0] is not session: - group = session.new_download_stream_group( - **xet_download_group_kwargs(xet_file_data, self._api._build_hf_headers()) - ) - cached = self._xet_stream_groups[xet_file_data.refresh_route] = (session, group) + group = session.new_download_stream_group(**xet_download_group_kwargs(xet_file_data, headers)) + cached = self._xet_stream_groups[key] = (session, group) try: yield from cached[1].download_stream(XetFileInfo(xet_file_data.file_hash, size), start=start, end=end) except KeyboardInterrupt: From ec66ab2fd9e0a4c707c4bdded50c55b46b8018c8 Mon Sep 17 00:00:00 2001 From: Adrien Date: Wed, 14 Oct 2026 19:16:53 +0200 Subject: [PATCH 6/6] fix(hffs): replace the shared Xet stream group when the token changes --- src/huggingface_hub/hf_file_system.py | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/huggingface_hub/hf_file_system.py b/src/huggingface_hub/hf_file_system.py index 0b6580de08..b44e5b034e 100644 --- a/src/huggingface_hub/hf_file_system.py +++ b/src/huggingface_hub/hf_file_system.py @@ -36,7 +36,6 @@ from .utils._runtime import is_xet_available from .utils._xet import ( XetTokenType, - _cache_key, abort_xet_session, get_xet_session, xet_connection_info_refresh_url, @@ -240,8 +239,8 @@ def __init__( self._repo_and_revision_exists_cache: dict[tuple[str, str, str | None], tuple[bool, Exception | None]] = {} # Same for buckets self._bucket_exists_cache: dict[str, tuple[bool, Exception | None]] = {} - # Xet session and download stream group per process, repo revision and token - self._xet_stream_groups: dict[str, tuple[Any, Any]] = {} + # (Xet session, token, download stream group) per process and repo revision + self._xet_stream_groups: dict[tuple[int, str], tuple[Any, str, Any]] = {} # Note: special case for buckets: revision is always None # Maps parent directory path to path infos self.dircache: dict[str, list[dict[str, Any]]] = {} @@ -1123,18 +1122,20 @@ def _read_xet(self, xet_file_data: XetFileData, size: int, start: int, end: int """Stream the bytes `[start, end)` of a file from Xet storage.""" from hf_xet import XetFileInfo - # Files of a revision share one group, so they share its connection pool. The key holds the PID so that a - # forked process never drops the groups of its parent (a group is not fork-safe), and the token so that a - # new token gets a group with up-to-date refresh headers. The group is rebuilt after `abort_xet_session`. + # Files of a revision share one group, so they share its connection pool. The group is replaced when the + # session changes (after `abort_xet_session`) or the token changes (its refresh headers hold the token). + # The key holds the PID so that a forked process never drops the groups of its parent: a group is not + # fork-safe. headers = self._api._build_hf_headers() - key = f"{os.getpid()}|{_cache_key(xet_file_data.refresh_route, headers)}" + token = headers.get("authorization", "") session = get_xet_session() + key = (os.getpid(), xet_file_data.refresh_route) cached = self._xet_stream_groups.get(key) - if cached is None or cached[0] is not session: + if cached is None or cached[0] is not session or cached[1] != token: group = session.new_download_stream_group(**xet_download_group_kwargs(xet_file_data, headers)) - cached = self._xet_stream_groups[key] = (session, group) + cached = self._xet_stream_groups[key] = (session, token, group) try: - yield from cached[1].download_stream(XetFileInfo(xet_file_data.file_hash, size), start=start, end=end) + yield from cached[2].download_stream(XetFileInfo(xet_file_data.file_hash, size), start=start, end=end) except KeyboardInterrupt: abort_xet_session() raise