Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: managed dataset media decodes stay on readable files, and Arrow data files are validated (#14430)

Daniel Hanc446f6562311
diff --git a/studio/backend/core/data_recipe/jobs/worker.py b/studio/backend/core/data_recipe/jobs/worker.py
index 4d9283d94bc..07da898e83a 100644
--- a/studio/backend/core/data_recipe/jobs/worker.py
+++ b/studio/backend/core/data_recipe/jobs/worker.py
@@ -91,7 +91,10 @@ def run_job_process(*, event_queue, recipe: dict[str, Any], run: dict[str, Any])
"""Subprocess entrypoint. Sends events to `event_queue`."""
import os
+ from utils.security.dataset_media import install as guard_dataset_media
+
install_public_egress_guard()
+ guard_dataset_media()
os.environ["PYTHONWARNINGS"] = "ignore"
import warnings
diff --git a/studio/backend/core/training/token_preview_worker.py b/studio/backend/core/training/token_preview_worker.py
index 0fdb28af508..4cccf33b81e 100644
--- a/studio/backend/core/training/token_preview_worker.py
+++ b/studio/backend/core/training/token_preview_worker.py
@@ -314,8 +314,10 @@ def run_token_preview_process(*, cmd_queue: Any, resp_queue: Any, config: dict)
sys.path.insert(0, backend_path)
from utils.security.hub_data_files import install as guard_hub_data_files
+ from utils.security.dataset_media import install as guard_dataset_media
guard_hub_data_files()
+ guard_dataset_media()
tokenizer = None
load_error = None
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.py
index f34e00cc2e3..f5997565794 100644
--- a/studio/backend/core/training/worker.py
+++ b/studio/backend/core/training/worker.py
@@ -4086,8 +4086,11 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
os.environ["PYTHONWARNINGS"] = "ignore" # before imports
from utils.security.hub_data_files import install as guard_hub_data_files
+ from utils.security.dataset_media import allow_dataset_repos, install as guard_dataset_media
guard_hub_data_files()
+ guard_dataset_media()
+ allow_dataset_repos(config.get("hf_dataset"))
if not config.get("allow_ambient", True):
from hub.utils.hf_tokens import apply_token_to_child_env, hf_token_arg, is_anonymous
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 20b3d71c451..8643afcd6c9 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -273,6 +273,11 @@ from utils.security.hub_data_files import install as _guard_hub_data_files
_guard_hub_data_files()
del _guard_hub_data_files
+from utils.security.dataset_media import install as _guard_dataset_media
+
+_guard_dataset_media()
+del _guard_dataset_media
+
# The studio bundles unsloth_zoo; declare unsloth present (as `import unsloth` does) so its
# lazy submodule imports and the DiffusionGemma runner don't trip the install guard.
os.environ.setdefault("UNSLOTH_IS_PRESENT", "1")
diff --git a/studio/backend/tests/test_arrow_validation.py b/studio/backend/tests/test_arrow_validation.py
new file mode 100644
index 00000000000..ff24668182c
--- /dev/null
+++ b/studio/backend/tests/test_arrow_validation.py
@@ -0,0 +1,95 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""An `.arrow` data file is validated before its rows are read: lengths and offsets that do not fit the file's
+buffers are a ValueError, never a read past them."""
+
+from __future__ import annotations
+
+import io
+import struct
+
+import pytest
+
+from hub.services.datasets.local import _stream_file_preview_slice
+
+VALUES = b"ABCDEFGH"
+ROWS = 15
+WINDOW = 8192
+
+
[email protected](autouse = True)
+def guarded():
+ try:
+ from utils.security import dataset_media
+ except ImportError: # a tree without the guard
+ return
+ dataset_media.install()
+ dataset_media.install()
+
+
+def _stream_bytes() -> bytes:
+ import pyarrow
+
+ offsets = [0] + [len(VALUES)] * ROWS
+ column = pyarrow.LargeListArray.from_arrays(
+ pyarrow.array(offsets, pyarrow.int64()),
+ pyarrow.array(list(VALUES), pyarrow.uint8()),
+ )
+ batch = pyarrow.record_batch([column], names = ["v"])
+ sink = io.BytesIO()
+ with pyarrow.ipc.new_stream(sink, batch.schema) as writer:
+ writer.write_batch(batch)
+ return sink.getvalue()
+
+
+def _malformed(raw: bytes) -> bytes:
+ """The same stream claiming WINDOW values over its 8-byte buffer, with offsets around it."""
+ crafted = bytearray(raw)
+ nodes = crafted.index(struct.pack("<4q", ROWS, 0, len(VALUES), 0))
+ crafted[nodes + 16 : nodes + 24] = struct.pack("<q", WINDOW)
+ offsets = [0] + [len(VALUES)] * ROWS
+ start = crafted.index(struct.pack("<16q", *offsets), nodes)
+ crafted[start : start + 128] = struct.pack("<16q", -WINDOW, 0, *[WINDOW] * (ROWS - 1))
+ return bytes(crafted)
+
+
+def test_malformed_arrow_stream_is_refused(tmp_path):
+ path = tmp_path / "train.arrow"
+ path.write_bytes(_malformed(_stream_bytes()))
+ with pytest.raises(ValueError):
+ _stream_file_preview_slice(path, 10)
+
+
+def test_malformed_arrow_file_is_refused_by_a_full_load(tmp_path):
+ from datasets import load_dataset
+
+ path = tmp_path / "train.arrow"
+ path.write_bytes(_malformed(_stream_bytes()))
+ with pytest.raises(Exception) as exc:
+ load_dataset("arrow", data_files = str(path), split = "train", cache_dir = str(tmp_path / "c"))
+ chain = [exc.value, exc.value.__cause__, exc.value.__context__]
+ assert any(isinstance(error, ValueError) for error in chain)
+
+
+def test_intact_arrow_stream_previews(tmp_path):
+ path = tmp_path / "validation.arrow"
+ path.write_bytes(_stream_bytes())
+ dataset, _ = _stream_file_preview_slice(path, 10)
+ assert bytes(dataset[0]["v"]) == VALUES
+
+
+def test_datasets_cache_files_skip_the_builder(tmp_path, monkeypatch):
+ from datasets import load_dataset
+ from datasets.packaged_modules.arrow.arrow import Arrow
+
+ path = tmp_path / "validation.arrow"
+ path.write_bytes(_stream_bytes())
+ kwargs = {"data_files": str(path), "split": "train", "cache_dir": str(tmp_path / "c")}
+ assert bytes(load_dataset("arrow", **kwargs)[0]["v"]) == VALUES
+
+ def no_cast(self, pa_table):
+ raise AssertionError("a cached dataset was re-read through the arrow builder")
+
+ monkeypatch.setattr(Arrow, "_cast_table", no_cast)
+ assert bytes(load_dataset("arrow", **kwargs)[0]["v"]) == VALUES
diff --git a/studio/backend/tests/test_dataset_media_decode_guard.py b/studio/backend/tests/test_dataset_media_decode_guard.py
new file mode 100644
index 00000000000..0ef806c6774
--- /dev/null
+++ b/studio/backend/tests/test_dataset_media_decode_guard.py
@@ -0,0 +1,245 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A managed account's dataset media cells and image strings open only files it may read, and never reach
+the Hub with the server's own token; the owner decodes as before."""
+
+from __future__ import annotations
+
+import io
+
+import pytest
+from fastapi import HTTPException
+
+from auth import policy
+from hub.schemas.datasets import CheckFormatRequest
+from hub.services.datasets import formatting
+from utils import hf_cache_settings
+from utils.account_context import AccountContext, run_as
+from utils.paths import storage_roots
+
+ALICE = AccountContext("a" * 32, "alice")
+
+
+def _png(color) -> bytes:
+ from PIL import Image
+
+ buf = io.BytesIO()
+ Image.new("RGB", (4, 4), color).save(buf, format = "PNG")
+ return buf.getvalue()
+
+
[email protected](autouse = True)
+def guarded(monkeypatch, tmp_path):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))
+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)
+ monkeypatch.setattr(formatting, "ensure_audio_decoding", lambda: True)
+ cache = tmp_path / "hub-cache"
+ cache.mkdir()
+ monkeypatch.setattr(hf_cache_settings, "active_hf_hub_cache", lambda: str(cache))
+ monkeypatch.setattr(hf_cache_settings, "known_hf_hub_caches", lambda: [cache])
+ try:
+ from utils.security import dataset_media
+ except ImportError: # a tree without the guard: the tests below show what it lets through
+ return
+ dataset_media.install()
+ dataset_media.install()
+
+
+def outside_png(tmp_path):
+ path = tmp_path / "owner-private" / "secret.png"
+ path.parent.mkdir()
+ path.write_bytes(_png((255, 0, 0)))
+ return path
+
+
+def _upload(rows, account = ALICE) -> str:
+ import datasets
+ def write():
+ root = storage_roots.dataset_uploads_root()
+ root.mkdir(parents = True, exist_ok = True)
+ target = root / "pictures.parquet"
+ features = datasets.Features({"image": datasets.Image(), "text": datasets.Value("string")})
+ datasets.Dataset.from_list(rows, features = features).to_parquet(str(target))
+ return str(target)
+
+ return run_as(account, write)
+
+
+def _check(name, account = ALICE):
+ return run_as(
+ account, formatting.check_format_response, CheckFormatRequest(dataset_name = name), None
+ )
+
+
+def test_managed_image_cell_naming_a_host_file_is_refused(outside_png):
+ name = _upload([{"image": {"bytes": None, "path": str(outside_png)}, "text": "a cat"}])
+ with pytest.raises(HTTPException) as exc:
+ _check(name)
+ assert 400 <= exc.value.status_code < 500
+
+
+def test_managed_image_cell_with_embedded_bytes_still_previews():
+ name = _upload([{"image": {"bytes": _png((0, 255, 0)), "path": None}, "text": "a cat"}])
+ response = _check(name)
+ assert response.preview_samples
+ assert response.preview_samples[0]["image"]["type"] == "image"
+
+
+def test_managed_image_cell_inside_own_workspace_still_previews():
+ def own_png():
+ path = storage_roots.dataset_uploads_root() / "own.png"
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_bytes(_png((0, 0, 255)))
+ return str(path)
+
+ name = _upload([{"image": {"bytes": None, "path": run_as(ALICE, own_png)}, "text": "x"}])
+ assert _check(name).preview_samples[0]["image"]["type"] == "image"
+
+
+def test_owner_image_cell_naming_a_host_file_is_unchanged(outside_png):
+ from utils.account_context import OWNER
+
+ name = _upload([{"image": {"bytes": None, "path": str(outside_png)}, "text": "a cat"}], OWNER)
+ response = _check(name, OWNER)
+ assert response.preview_samples[0]["image"]["type"] == "image"
+
+
+def hub_fetches(monkeypatch):
+ from datasets.features import image as image_module
+
+ seen = []
+
+ def fake_xopen(
+ path,
+ mode = "r",
+ *args,
+ download_config = None,
+ **kwargs,
+ ):
+ seen.append((path, download_config.token if download_config else None))
+ return io.BytesIO(_png((1, 2, 3)))
+
+ monkeypatch.setattr(image_module, "xopen", fake_xopen)
+ return seen
+
+
+def _decode(
+ value,
+ tokens,
+ account = ALICE,
+):
+ from datasets import Image
+ return run_as(account, Image().decode_example, value, token_per_repo_id = tokens)
+
+
+ "path",
+ [
+ "hf://datasets/other/private@main/secret.png",
+ "{endpoint}/datasets/other/private/resolve/main/secret.png",
+ ],
+)
+def test_managed_hub_cell_of_another_repo_never_uses_the_server_token(hub_fetches, path):
+ from datasets import config
+
+ path = path.format(endpoint = config.HF_ENDPOINT)
+ _decode({"bytes": None, "path": path}, {"alice/own": "alice-token"})
+ assert hub_fetches == [(path, False)]
+
+
+def test_managed_hub_cell_of_its_own_repo_keeps_its_token(hub_fetches):
+ path = "hf://datasets/alice/own@main/a.png"
+ _decode({"bytes": None, "path": path}, {"alice/own": "alice-token"})
+ assert hub_fetches == [(path, "alice-token")]
+
+
+ "path",
+ [
+ "http://127.0.0.1:9/secret.png",
+ "hf://datasets/other/private/secret.png",
+ "s3://bucket/x.png",
+ ],
+)
+def test_managed_cell_naming_another_url_is_never_fetched(hub_fetches, path):
+ with pytest.raises(PermissionError):
+ _decode({"bytes": None, "path": path}, {})
+ assert hub_fetches == []
+
+
+def test_owner_hub_cell_is_unchanged(hub_fetches):
+ from utils.account_context import OWNER
+
+ path = "hf://datasets/other/private@main/secret.png"
+ _decode({"bytes": None, "path": path}, {}, OWNER)
+ assert hub_fetches == [(path, None)]
+
+
+def test_managed_vlm_string_image_paths_stay_in_the_account(outside_png):
+ from utils.account_context import OWNER
+ from utils.datasets.format_conversion import convert_llava_to_vlm_format
+
+ def rows(path):
+ return [
+ {
+ "messages": [
+ {
+ "role": "user",
+ "content": [{"type": "image", "index": 0}, {"type": "text", "text": "hi"}],
+ },
+ {"role": "assistant", "content": [{"type": "text", "text": "a red square"}]},
+ ],
+ "images": [path],
+ }
+ ]
+
+ with pytest.raises(Exception) as exc:
+ run_as(ALICE, convert_llava_to_vlm_format, rows(str(outside_png)))
+ assert isinstance(exc.value, (PermissionError, HTTPException))
+ assert run_as(OWNER, convert_llava_to_vlm_format, rows(str(outside_png)))
+
+ def own_png():
+ path = storage_roots.dataset_uploads_root() / "own.png"
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_bytes(_png((0, 0, 255)))
+ return str(path)
+
+ assert run_as(ALICE, convert_llava_to_vlm_format, rows(run_as(ALICE, own_png)))
+
+
+def test_install_is_idempotent():
+ from datasets import Image
+
+ from utils.security import dataset_media
+
+ decode = Image.decode_example
+ dataset_media.install()
+ assert Image.decode_example is decode
+ assert dataset_media.guard_decoder(decode) is decode
+
+
+def test_managed_snapshot_files_of_its_training_dataset_still_decode(tmp_path, monkeypatch):
+ from hub.services.models import account_access
+ from utils.security import dataset_media
+
+ monkeypatch.setattr(dataset_media, "_dataset_repos", set())
+ monkeypatch.setattr(account_access, "model_grants", lambda: set())
+ monkeypatch.setattr(account_access, "repo_is_public", lambda *args, **kwargs: False)
+ image = tmp_path / "hub-cache" / "datasets--alice--private" / "snapshots" / "rev" / "a.png"
+ image.parent.mkdir(parents = True)
+ image.write_bytes(_png((9, 9, 9)))
+ cell = {"bytes": None, "path": str(image)}
+
+ with pytest.raises(PermissionError):
+ _decode(cell, {})
+ dataset_media.allow_dataset_repos("alice/private")
+ assert _decode(cell, {}).size == (4, 4)
+ dataset_media.allow_dataset_repos("someone/else")
+ other = tmp_path / "hub-cache" / "datasets--bob--private" / "snapshots" / "rev" / "b.png"
+ other.parent.mkdir(parents = True)
+ other.write_bytes(_png((9, 9, 9)))
+ with pytest.raises(PermissionError):
+ _decode({"bytes": None, "path": str(other)}, {})
diff --git a/studio/backend/utils/datasets/audio_decode.py b/studio/backend/utils/datasets/audio_decode.py
index 8e929b2e7f2..458c427490b 100644
--- a/studio/backend/utils/datasets/audio_decode.py
+++ b/studio/backend/utils/datasets/audio_decode.py
@@ -235,7 +235,10 @@ def ensure_audio_decoding() -> bool:
if _installed:
return True
_ORIGINAL_ENCODE = Audio.encode_example
- Audio.decode_example = _decode_with_soundfile
+ # Behind the same account check as the decoder it replaces.
+ from utils.security.dataset_media import guard_decoder
+
+ Audio.decode_example = guard_decoder(_decode_with_soundfile)
Audio.encode_example = _encode_with_soundfile
_installed = True
logger.info("torchcodec is unusable; decoding dataset audio with soundfile and PyAV")
diff --git a/studio/backend/utils/datasets/format_conversion.py b/studio/backend/utils/datasets/format_conversion.py
index ec13b113644..86df81b743a 100644
--- a/studio/backend/utils/datasets/format_conversion.py
+++ b/studio/backend/utils/datasets/format_conversion.py
@@ -21,6 +21,16 @@ def _quiet_bar_kwargs() -> dict:
return {}
+def _own_image_path(path, account):
+ """A local image a managed account names must be one it may read (a no-op for the owner). ``account`` is
+ captured when the conversion starts: URL datasets convert in a thread pool, which does not carry it."""
+ from utils.account_context import run_as
+ from utils.security.dataset_media import require_readable_media
+
+ run_as(account, require_readable_media, path)
+ return path
+
+
def _normalize_role_alias(role) -> str:
"""Stripped and lowercased, as `standardize_data_formats` and the preview do it."""
if role is None:
@@ -395,8 +405,11 @@ def convert_to_vlm_format(
Returns a LIST of dicts with a 'messages' field, not a HuggingFace Dataset, to preserve PIL Images. For URL-based datasets, runs a 200-sample parallel probe first to estimate speed and failure rate via progress_callback, an optional callable(status_message=str).
"""
from PIL import Image
+ from utils.account_context import current_account
from .vlm_processing import generate_smart_vlm_instruction
+ account = current_account()
+
def _notify(msg):
"""Send a status update to the training overlay if callback set."""
if progress_callback:
@@ -448,7 +461,7 @@ def convert_to_vlm_format(
)
image_data = Image.open(local_path).convert("RGB")
else:
- image_data = Image.open(image_data).convert("RGB")
+ image_data = Image.open(_own_image_path(image_data, account)).convert("RGB")
elif image_data is None:
raise ValueError("Row has no image")
@@ -738,7 +751,9 @@ def convert_sharegpt_with_images_to_vlm_format(
"""Convert ShareGPT/ChatML datasets carrying a separate image column and ``<image>`` placeholders in the conversation text, e.g. {"image": "sam/images/sa_545504.jpg", "conversations": [{"from": "human", "value": "<image> What is this photo about?"}, ...]}. Returns a list of dicts in standard VLM messages format, PIL Images inline."""
from PIL import Image
from tqdm import tqdm
+ from utils.account_context import current_account
+ account = current_account()
_IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff")
_ROLE_MAP = {
"human": "user",
@@ -815,13 +830,13 @@ def convert_sharegpt_with_images_to_vlm_format(
)
return Image.open(local_path).convert("RGB")
else:
- return Image.open(image_data).convert("RGB")
+ return Image.open(_own_image_path(image_data, account)).convert("RGB")
if isinstance(image_data, dict) and ("bytes" in image_data or "path" in image_data):
if image_data.get("bytes"):
from io import BytesIO
return Image.open(BytesIO(image_data["bytes"])).convert("RGB")
if image_data.get("path"):
- return Image.open(image_data["path"]).convert("RGB")
+ return Image.open(_own_image_path(image_data["path"], account)).convert("RGB")
raise ValueError(f"Cannot resolve image: {type(image_data)}")
def _convert_single_sample(sample):
@@ -891,6 +906,9 @@ def convert_sharegpt_with_images_to_vlm_format(
def convert_llava_to_vlm_format(dataset):
"""Convert Llava format to standard VLM format: Llava carries messages whose content blocks name an image by {'type': 'image', 'index': 0} plus a parallel images list, while the standard form inlines the PIL object as {'type': 'image', 'image': PIL_Image}."""
from PIL import Image
+ from utils.account_context import current_account
+
+ account = current_account()
is_iterable = is_streaming_dataset(dataset)
if is_iterable:
@@ -949,7 +967,7 @@ def convert_llava_to_vlm_format(dataset):
pil_image = images[img_idx]
if isinstance(pil_image, str):
- pil_image = Image.open(pil_image).convert("RGB")
+ pil_image = Image.open(_own_image_path(pil_image, account)).convert("RGB")
elif not isinstance(pil_image, Image.Image):
raise ValueError(
f"Unsupported Llava image value at index {img_idx}: "
diff --git a/studio/backend/utils/security/dataset_media.py b/studio/backend/utils/security/dataset_media.py
new file mode 100644
index 00000000000..6aa2e283a82
--- /dev/null
+++ b/studio/backend/utils/security/dataset_media.py
@@ -0,0 +1,231 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Keep a managed account's dataset media to files it may read, and validate Arrow data files.
+
+A ``datasets`` Image / Audio / Video / Pdf / Nifti cell holding a ``path`` and no ``bytes`` is opened by the
+feature's decoder in whichever process reads the row: a local path is read from disk, and a Hub URL is fetched
+with ``token_per_repo_id[repo]``, which falls back to the process's own Hub credentials for any repo the dataset
+was not loaded from. Any dataset can carry such cells, so for a managed account a local path must be one the
+account may read (its own roots, a Hub snapshot it can see or its training dataset's, an archive ``datasets``
+extracted), a Hub URL is fetched with the token the caller supplied for its repo or anonymously, and any other
+URL is refused. The owner is unchanged.
+
+pyarrow's IPC reader trusts the lengths and offsets an ``.arrow`` file declares, so the ``arrow`` builder validates
+each table in full before ``datasets`` converts its rows: a malformed file raises ``ArrowInvalid`` (a ValueError)
+instead of reading past its buffers. ``datasets``' own cache files are memory-mapped by its reader, not this builder.
+
+``install()`` patches ``datasets`` once it is imported, without importing it at startup; it is idempotent.
+"""
+
+import functools
+import importlib.abc
+import importlib.util
+import os
+import re
+import sys
+
+_DECODERS = {
+ "datasets.features.image": "Image",
+ "datasets.features.audio": "Audio",
+ "datasets.features.video": "Video",
+ "datasets.features.pdf": "Pdf",
+ "datasets.features.nifti": "Nifti",
+}
+_ARROW = "datasets.packaged_modules.arrow.arrow"
+_MARK = "_unsloth_dataset_media_guard"
+_SNAPSHOT_REPO = re.compile(r"[\\/]datasets--([^\\/]+?)--([^\\/]+)[\\/]")
+# Hub dataset repos the process was started to train on (a worker serves one account's job).
+_dataset_repos: set[str] = set()
+
+
+class MediaPathRefused(PermissionError, ValueError):
+ """A ValueError too, so check-format answers 400 like any other unreadable dataset."""
+
+
+def _is_owner() -> bool:
+ try:
+ from utils.account_context import is_owner_context
+ except ImportError: # outside Studio's backend there are no managed accounts
+ return True
+ return is_owner_context()
+
+
+def allow_dataset_repos(*repo_ids) -> None:
+ """Snapshot files of these Hub datasets may be decoded: the job loaded them with the account's own token."""
+ _dataset_repos.update(
+ str(repo).strip() for repo in repo_ids if isinstance(repo, str) and repo.strip()
+ )
+
+
+def _refuse(path) -> None:
+ raise MediaPathRefused(f"Dataset media path is not readable by this account: {path}")
+
+
+def _training_snapshot(path: str) -> bool:
+ if not _dataset_repos:
+ return False
+ from utils.hf_cache_settings import known_hf_hub_caches
+
+ real = os.path.realpath(path)
+ lexical, resolved = _SNAPSHOT_REPO.search(path), _SNAPSHOT_REPO.search(real)
+ if not (lexical and resolved) or lexical.groups() != resolved.groups():
+ return False
+ caches = [os.path.realpath(root) for root in known_hf_hub_caches()]
+ return "/".join(resolved.groups()) in _dataset_repos and any(
+ real.startswith(root.rstrip(os.sep) + os.sep) for root in caches
+ )
+
+
+def _extracted_archive(path: str) -> bool:
+ from datasets import config
+ root = os.path.realpath(str(config.EXTRACTED_DATASETS_PATH))
+ return os.path.realpath(path).startswith(root.rstrip(os.sep) + os.sep)
+
+
+def _require_readable(path: str) -> None:
+ from fastapi import HTTPException
+
+ from core.training.account_jobs import visible_cached_path
+
+ path = os.path.abspath(os.path.expanduser(path))
+ try:
+ visible_cached_path(path, "dataset")
+ except HTTPException:
+ if not (_training_snapshot(path) or _extracted_archive(path)):
+ _refuse(path)
+
+
+def require_readable_media(path) -> None:
+ """Refuse a local media path the managed account may not read; a no-op for the owner."""
+ if not _is_owner():
+ _require_readable(str(path))
+
+
+def _permitted_tokens(value, token_per_repo_id):
+ """The token mapping the decoder may use for ``value``; raises for a path the account may not read."""
+ if isinstance(value, str):
+ path, raw = value, None
+ elif isinstance(value, dict):
+ path, raw = value.get("path"), value.get("bytes")
+ else:
+ return token_per_repo_id
+ if raw is not None or not isinstance(path, str) or not path:
+ return token_per_repo_id
+ from datasets import config
+ from datasets.utils.file_utils import is_local_path
+ from datasets.utils.py_utils import string_to_dict
+
+ # A chained URL ("zip://inner::<outer>") reads the outer location.
+ source = path.split("::")[-1]
+ if is_local_path(source):
+ _require_readable(source)
+ return token_per_repo_id
+ # The decoders' own lookup: whatever key they will read is the one given a token here.
+ pattern = (
+ config.HUB_DATASETS_URL
+ if source.startswith(config.HF_ENDPOINT)
+ else config.HUB_DATASETS_HFFS_URL
+ )
+ try:
+ fields = string_to_dict(source, pattern)
+ except ValueError:
+ fields = None
+ if fields is None:
+ # Not a Hub file the decoder can key a token on: it would dial it with the server's credentials.
+ _refuse(path)
+ tokens = dict(token_per_repo_id or {})
+ if not isinstance(tokens.get(fields["repo_id"]), str):
+ # None and True both mean the server's own token; only a token the caller supplied is sent.
+ tokens[fields["repo_id"]] = False
+ return tokens
+
+
+def _decode_guard(decode_example):
+ @functools.wraps(decode_example)
+ def guarded(self, value, *args, **kwargs):
+ if _is_owner():
+ return decode_example(self, value, *args, **kwargs)
+ tokens = kwargs.pop("token_per_repo_id", args[0] if args else None)
+ return decode_example(
+ self, value, *args[1:], token_per_repo_id = _permitted_tokens(value, tokens), **kwargs
+ )
+
+ return guarded
+
+
+def _validated_cast(cast_table):
+ @functools.wraps(cast_table)
+ def guarded(self, pa_table, *args, **kwargs):
+ pa_table.validate(full = True)
+ return cast_table(self, pa_table, *args, **kwargs)
+
+ return guarded
+
+
+def guard_decoder(decode_example):
+ """``decode_example`` behind the account check; for a decoder installed after ``install()``."""
+ if getattr(decode_example, _MARK, False):
+ return decode_example
+ guarded = _decode_guard(decode_example)
+ setattr(guarded, _MARK, True)
+ return guarded
+
+
+def _patch_attribute(owner, attribute, wrapper) -> None:
+ original = getattr(owner, attribute, None)
+ if original is not None and not getattr(original, _MARK, False):
+ guarded = wrapper(original)
+ setattr(guarded, _MARK, True)
+ setattr(owner, attribute, guarded)
+
+
+def _patch(module) -> None:
+ if module.__name__ == _ARROW:
+ owner = getattr(module, "Arrow", None)
+ if owner is not None:
+ _patch_attribute(owner, "_cast_table", _validated_cast)
+ return
+ owner = getattr(module, _DECODERS[module.__name__], None)
+ if owner is not None:
+ _patch_attribute(owner, "decode_example", _decode_guard)
+
+
+class _Loader(importlib.abc.Loader):
+ def __init__(self, loader):
+ self._loader = loader
+
+ def create_module(self, spec):
+ return self._loader.create_module(spec)
+
+ def exec_module(self, module):
+ self._loader.exec_module(module)
+ _patch(module)
+
+
+class _Finder(importlib.abc.MetaPathFinder):
+ def find_spec(
+ self,
+ name,
+ path,
+ target = None,
+ ):
+ if name not in _DECODERS and name != _ARROW:
+ return None
+ sys.meta_path.remove(self)
+ try:
+ spec = importlib.util.find_spec(name)
+ finally:
+ sys.meta_path.insert(0, self)
+ if spec is None or spec.loader is None:
+ return spec
+ spec.loader = _Loader(spec.loader)
+ return spec
+
+
+def install() -> None:
+ for name in (*_DECODERS, _ARROW):
+ if name in sys.modules:
+ _patch(sys.modules[name])
+ if not any(isinstance(finder, _Finder) for finder in sys.meta_path):
+ sys.meta_path.insert(0, _Finder())