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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: never pick a macOS AppleDouble sidecar as a GGUF (#8919)
sts-change8d6e969378b9
diff --git a/studio/backend/core/data_recipe/jobs/worker.py b/studio/backend/core/data_recipe/jobs/worker.pyindex 402caebe094..79943b3b708 100644--- a/studio/backend/core/data_recipe/jobs/worker.py+++ b/studio/backend/core/data_recipe/jobs/worker.py@@ -22,6 +22,7 @@ from utils.paths import ensure_dir, recipe_datasets_root# Fresh spawned interpreter: re-apply main.py's OS-trust-store injection.from utils.native_tls import activate_native_tls+from utils.paths.path_utils import drop_appledouble_metadataactivate_native_tls()@@ -192,7 +193,9 @@ def run_job_process(*, event_queue, recipe: dict[str, Any], run: dict[str, Any])def _merge_batches_to_single_parquet(base_dataset_path: Path) -> None:parquet_dir = base_dataset_path / "parquet-files"- parquet_files = sorted(parquet_dir.glob("*.parquet"))+ # Counted, so a companion makes a single-batch job take the merge path and rewrite a+ # dataset that needed none.+ parquet_files = drop_appledouble_metadata(sorted(parquet_dir.glob("*.parquet")))if len(parquet_files) <= 1:returndiff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.pyindex 806f92732a5..dce992b0a4d 100644--- a/studio/backend/core/export/export.py+++ b/studio/backend/core/export/export.py@@ -37,6 +37,7 @@ from utils.paths import (resolve_output_dir,)from core.inference import get_inference_backend+from utils.paths.path_utils import drop_appledouble_metadata# GPU/PyTorch-only imports, skipped on MLX and --no-torch installs so the module stays importable.torch = None@@ -1221,10 +1222,11 @@ class ExportBackend:shutil.rmtree(model_tmp_root, ignore_errors = True)# iterdir, not glob.glob: glob hides dot-leading names, so an empty- # model stem's ".Q4_K_M.gguf" got reported as "(none)".+ # model stem's ".Q4_K_M.gguf" got reported as "(none)". This list is the+ # success gate, so a leftover companion would report a run that wrote nothing.final_ggufs = sorted(str(p)- for p in Path(abs_save_dir).iterdir()+ for p in drop_appledouble_metadata(list(Path(abs_save_dir).iterdir()))if p.is_file() and p.name.lower().endswith(".gguf"))logger.info(@@ -1373,7 +1375,7 @@ class ExportBackend:# iterdir, not glob.glob: glob hides dot-leading names.final_ggufs = sorted(str(p)- for p in Path(save_directory).iterdir()+ for p in drop_appledouble_metadata(list(Path(save_directory).iterdir()))if p.is_file() and p.name.lower().endswith(".gguf"))logger.info(diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex b8ca7509da6..54bb69aa2a4 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -163,6 +163,10 @@ from .diffusion_transformer_quant import (quantize_transformer,select_transformer_quant_scheme,)+from utils.paths.path_utils import (+ any_not_appledouble_metadata,+ is_appledouble_metadata,+)logger = get_logger(__name__)@@ -341,12 +345,14 @@ def resolve_local_single_file(model_path: str) -> Optional[str]:# A PEFT adapter folder is not a base checkpoint; skip it so validation 400s before eviction.if (root / "adapter_config.json").is_file():return None+checkpoints = [p.namefor p in root.iterdir()if p.is_file()and p.suffix.lower() == ".safetensors"and p.stem.lower() != "adapter_model"+ and not is_appledouble_metadata(p)]except OSError:return None@@ -1035,7 +1041,9 @@ def _local_base_transformer_present(base_repo: Optional[str]) -> bool:return Falsetry:transformer = Path(base).expanduser() / "transformer"- return transformer.is_dir() and any(transformer.glob("*.safetensors"))+ return transformer.is_dir() and any_not_appledouble_metadata(+ transformer.glob("*.safetensors")+ )except OSError: # an id with invalid path characters is simply not a directoryreturn Falsediff --git a/studio/backend/core/inference/diffusion_controlnet.py b/studio/backend/core/inference/diffusion_controlnet.pyindex e20e976d947..433b868c04b 100644--- a/studio/backend/core/inference/diffusion_controlnet.py+++ b/studio/backend/core/inference/diffusion_controlnet.py@@ -22,6 +22,7 @@ from pathlib import Pathfrom typing import Any, Optionalfrom utils.paths.storage_roots import studio_root+from utils.paths.path_utils import is_appledouble_metadata# Control map types. "passthrough": the supplied image IS the control map. "canny": derive an edge map here.CONTROL_TYPES = ("passthrough", "canny")@@ -104,8 +105,12 @@ def _has_controlnet_weights(p: Path) -> bool:)if any((p / n).exists() for n in names):return True+try:- return any(child.suffix == ".safetensors" for child in p.iterdir())+ return any(+ child.suffix == ".safetensors" and not is_appledouble_metadata(child)+ for child in p.iterdir()+ )except OSError:return Falsediff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex e0ea90a01df..8b329429f21 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -22,6 +22,7 @@ import tempfilefrom dataclasses import dataclass, fieldfrom pathlib import Path, PurePosixPathfrom typing import NamedTuple, Optional, Sequence+from utils.paths.path_utils import is_appledouble_metadata# Runtime->route contract: the /images/generate route matches these messages EXACTLY for a 409 (vs a 500), so both engines raise them verbatim.@@ -719,7 +720,12 @@ def _root_holds_upstream(root: Path, repo_id: str, wanted: Sequence[str]) -> booif wanted:if all((rev / name).exists() for name in wanted):return True- elif any(p.suffix.lower() in _WEIGHT_SUFFIXES and p.is_file() for p in rev.rglob("*")):+ elif any(+ p.suffix.lower() in _WEIGHT_SUFFIXES+ and p.is_file()+ and not is_appledouble_metadata(p)+ for p in rev.rglob("*")+ ):return Truereturn Falseexcept Exception: # noqa: BLE001 -- an unreadable/absent cache just means "not cached"diff --git a/studio/backend/core/inference/diffusion_lora.py b/studio/backend/core/inference/diffusion_lora.pyindex 0a46c4a0384..7fe3db50db6 100644--- a/studio/backend/core/inference/diffusion_lora.py+++ b/studio/backend/core/inference/diffusion_lora.py@@ -27,6 +27,7 @@ from utils.hf_xet_fallback import hf_hub_download_with_xet_fallbackfrom utils.paths.storage_roots import studio_rootfrom .diffusion_families import DIFFUSION_CANCELLED_MSG+from utils.paths.path_utils import is_appledouble_metadata# Accepted LoRA formats. safetensors + gguf only (.pt is pickled -> excluded for safety)._NATIVE_EXTS = (".safetensors", ".gguf")@@ -121,7 +122,12 @@ def _scan_local() -> list[LoraCatalogEntry]:children = sorted(root.iterdir())except OSError:return []- files = [p for p in children if p.is_file() and p.suffix.lower() in _ALL_EXTS]++ files = [+ p+ for p in children+ if p.is_file() and p.suffix.lower() in _ALL_EXTS and not is_appledouble_metadata(p)+ ]# Two files sharing a stem but differing in extension collide on id (== stem), so a colliding stem keeps the full filename.stem_counts: dict[str, int] = {}for p in files:@@ -268,7 +274,9 @@ def _pick_repo_weight_file(repo_id: str, hf_token: Optional[str]) -> str:"""Pick the single LoRA weight file in an HF repo (prefer safetensors)."""from huggingface_hub import HfApi- files = HfApi(token = hf_token).list_repo_files(repo_id)+ from hub.utils.gguf import drop_shadowed_appledouble_names++ files = drop_shadowed_appledouble_names(list(HfApi(token = hf_token).list_repo_files(repo_id)))safes = [f for f in files if f.lower().endswith(".safetensors") and "/" not in f]if len(safes) == 1:return safes[0]diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex fee040787b3..2cc8fb0f211 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -123,6 +123,7 @@ from state.tool_approvals import (new_approval_id,wait_tool_decision,)+from utils.paths.path_utils import is_appledouble_metadatalogger = get_logger(__name__)@@ -1347,7 +1348,7 @@ def _gguf_snapshot_files(snapshot: Path) -> list[str]:return [p.relative_to(snapshot).as_posix()for p in snapshot.rglob("*")- if p.is_file() and p.name.lower().endswith(".gguf")+ if p.is_file() and p.name.lower().endswith(".gguf") and not is_appledouble_metadata(p)]@@ -1684,7 +1685,29 @@ def _companion_snapshot_sibling(return str(candidate) if _drafter_split_is_complete(candidate) else None+def _pick_dspark(candidates: list[str]) -> Optional[str]:+ """The DSpark drafter a listing offers, or None. Module level for the same reason+ ``_pick_mmproj`` is: both are handed a live repo listing as well as a snapshot."""+ from hub.utils.gguf import drop_shadowed_appledouble_names+ from utils.models.model_config import dspark_preference_key++ # Every GGUF under dspark/ qualifies, so a sidecar ranks equal to its sibling and sorts first.+ files = sorted(+ (+ name+ for name in drop_shadowed_appledouble_names(list(candidates))+ if _is_dspark_drafter_path(name)+ ),+ key = dspark_preference_key,+ )+ return files[0] if files else None++def _pick_mmproj(candidates: list[str]) -> Optional[str]:+ from hub.utils.gguf import drop_shadowed_appledouble_names++ # "._mmproj-F16.gguf" satisfies the F16 preference and sorts ahead of the real adapter.+ candidates = drop_shadowed_appledouble_names(list(candidates))mmproj_files = sorted(f for f in candidates if f.lower().endswith(".gguf") and "mmproj" in Path(f).name.lower())@@ -1893,10 +1916,13 @@ def _gguf_files_for_variant(files: Iterable[str], variant: str) -> list[str]:Prefer exact quant-label matches over loose substring matches so a requestfor ``stories260K`` does not resolve to ``stories260K-be.gguf``."""+ from hub.utils.gguf import drop_shadowed_appledouble_names+variant_key = variant.strip().lower()+ # A repo listing has no bytes to read; a local one arrives already filtered on its headers.main_files = [f- for f in files+ for f in drop_shadowed_appledouble_names(list(files))if f.lower().endswith(".gguf")and not _is_companion_gguf_path(f)# The endian predicate reads a quant TOKEN -- it decides whether the quant came from the@@ -8927,9 +8953,11 @@ class LlamaCppBackend:from huggingface_hub import get_paths_info, list_repo_filesfiles = list_repo_files(hf_repo, token = hf_token)+ from hub.utils.gguf import drop_shadowed_appledouble_names+gguf_files = [f- for f in files+ for f in drop_shadowed_appledouble_names(list(files))if f.lower().endswith(".gguf")and not _is_companion_gguf_path(f)and not _is_big_endian_gguf_path(f)@@ -10658,14 +10686,6 @@ class LlamaCppBackend:if caps_probe is None:caps_probe = self.probe_server_capabilities- def _pick_dspark(candidates: list[str]) -> Optional[str]:- from utils.models.model_config import dspark_preference_key- files = sorted(- (name for name in candidates if _is_dspark_drafter_path(name)),- key = dspark_preference_key,- )- return files[0] if files else None-cached = _companion_snapshot_sibling(near_path, _pick_dspark) if near_path else Noneif not cached and _hf_env_offline():cached = self._cached_repo_dspark_drafter(@@ -11977,6 +11997,30 @@ class LlamaCppBackend:"settings and reload.")+ # llama.cpp prints the four bytes it found with %c, so a binary header arrives as+ # unprintable characters; the generic fallback then blamed the user's memory (#8566).+ if "invalid magic characters" in lowered:+ # Not necessarily the main model: the projector and drafter report this too.+ base = os.path.basename(gguf_path) if gguf_path else ""+ named = f", loading {base}" if base else ""+ # A "._" model path proves the volume keeps xattrs in companions, whichever file+ # llama-server actually opened, and dot_clean is the remedy for the volume.+ remedy = (+ 'This volume has no native extended attributes, so macOS keeps them in "._" '+ 'companions: run "dot_clean -m" on the folder to remove them, or keep models '+ "on an APFS disk."+ if base.startswith("._")+ else "Re-download the model, or pick a different file."+ )+ return LlamaCppBackend._with_startup_diagnostics(+ f"llama-server opened a file that is not a GGUF{named}: it does not start with "+ "the GGUF magic. It may be that file or a companion loaded with it, such as a "+ f"vision projector or a drafter, which llama-server does not always name. {remedy}",+ output,+ log_path,+ secrets,+ )+# Detect Ollama source up front so the arch branch can keep the# Ollama hint instead of the generic "unsupported arch" message.gguf = gguf_path or ""diff --git a/studio/backend/core/inference/openai_auto_download.py b/studio/backend/core/inference/openai_auto_download.pyindex a3c1a0d74de..53b1ceb3ac0 100644--- a/studio/backend/core/inference/openai_auto_download.py+++ b/studio/backend/core/inference/openai_auto_download.py@@ -273,9 +273,12 @@ def _gguf_variants(siblings, repo_id: str = "") -> dict[str, int]:_is_mtp_drafter,)+ from hub.utils.gguf import drop_shadowed_appledouble_siblings++ # Plans and advertised variants are derived separately, so both are filtered here.siblings = [sibling- for sibling in (siblings or [])+ for sibling in drop_shadowed_appledouble_siblings(list(siblings or []))if _is_selectable_repo_gguf(repo_id, getattr(sibling, "rfilename", "") or "")]plans = build_gguf_variant_plans(siblings)diff --git a/studio/backend/core/rag/embed_llama_server.py b/studio/backend/core/rag/embed_llama_server.pyindex d1762f22d0f..d049b0a8ba7 100644--- a/studio/backend/core/rag/embed_llama_server.py+++ b/studio/backend/core/rag/embed_llama_server.py@@ -34,6 +34,7 @@ from utils.subprocess_compat import windows_hidden_subprocess_kwargsfrom utils.process_lifetime import adopt_pid, child_popen_kwargs, forget_pidfrom . import config+from utils.paths.path_utils import is_appledouble_metadatalogger = logging.getLogger(__name__)@@ -195,13 +196,16 @@ class LlamaServerBackend:"""A custom model may be a local .gguf file or a directory holding one;resolve it without the hub. None when the value is not a local path."""p = Path(model).expanduser()+if p.is_file() and p.suffix.lower() == ".gguf":- return str(p)+ return None if is_appledouble_metadata(p) else str(p)if p.is_dir():files = [ffor f in p.iterdir()- if f.suffix.lower() == ".gguf" and "mmproj" not in f.name.lower()+ if f.suffix.lower() == ".gguf"+ and "mmproj" not in f.name.lower()+ and not is_appledouble_metadata(f)]if not files:raise RuntimeError(f"no .gguf file found in local model dir {model!r}")@@ -292,7 +296,12 @@ class LlamaServerBackend:try:# Not a "*.gguf" glob: that is case-sensitive, and quant-per-directory layouts# put the file a level down, both of which the hub listing handles.- files = [p for p in snapshot.rglob("*") if p.is_file()]++ # A complete family of sidecars is servable by every test below -- whole, quant+ # matched, opens as a file -- so the retry that drops a torn real set lands on it.+ files = [+ p for p in snapshot.rglob("*") if p.is_file() and not is_appledouble_metadata(p)+ ]except OSError:return None# llama-server opens sibling shards implicitly, so a split set is servable only whendiff --git a/studio/backend/core/rag/folder_sync.py b/studio/backend/core/rag/folder_sync.pyindex 4941ba6fdf9..920c65fc9a9 100644--- a/studio/backend/core/rag/folder_sync.py+++ b/studio/backend/core/rag/folder_sync.py@@ -23,6 +23,7 @@ from storage import rag_dbfrom utils.paths import ensure_dir, rag_uploads_rootfrom . import config, ingestion, job_leases, store+from utils.paths.path_utils import is_appledouble_metadatalogger = logging.getLogger(__name__)@@ -978,6 +979,10 @@ def _scan(continueif os.path.splitext(entry.name)[1].lower() not in config.UPLOAD_EXTS:continue+ # Finder metadata carries the document's extension, and a text parser reads it+ # with errors="replace", so it would be embedded and cited as a real chunk.+ if is_appledouble_metadata(Path(full)):+ continuest = entry.stat(follow_symlinks = False)from_path = Falseif st.st_ino in (None, 0):diff --git a/studio/backend/core/training/diffusion_h3_clips.py b/studio/backend/core/training/diffusion_h3_clips.pyindex 806f57da1ae..d067a027dbb 100644--- a/studio/backend/core/training/diffusion_h3_clips.py+++ b/studio/backend/core/training/diffusion_h3_clips.py@@ -22,6 +22,7 @@ import mathimport osfrom pathlib import Pathfrom typing import Any, Callable, Optional+from utils.paths.path_utils import drop_appledouble_metadata# ── the model's grid ─────────────────────────────────────────────────────────#@@ -198,7 +199,9 @@ def discover_clip_caption_pairs(if not root.is_dir():raise FileNotFoundError(f"data_dir is not a directory: {data_dir}")- clips = sorted(p for p in root.iterdir() if p.is_file() and p.suffix.lower() in _VIDEO_EXTS)+ clips = drop_appledouble_metadata(+ sorted(p for p in root.iterdir() if p.is_file() and p.suffix.lower() in _VIDEO_EXTS)+ )meta_caption: dict[str, str] = {}for meta_name in ("metadata.jsonl", "captions.jsonl"):diff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.pyindex f9d3310c329..b8a4b31bbaf 100644--- a/studio/backend/core/training/diffusion_train_common.py+++ b/studio/backend/core/training/diffusion_train_common.py@@ -37,6 +37,7 @@ from core.inference.diffusion_families import (trainable_family_names,)from core.inference.video_families import detect_video_family, supported_video_family_names+from utils.paths.path_utils import drop_appledouble_metadata# The trainers run in a spawned child that imports diffusers itself, so the inference-side install does not carry over. Both import this module first.install_xformers_windows_rocm_stub()@@ -1404,7 +1405,11 @@ def discover_image_caption_pairs(if not root.is_dir():raise FileNotFoundError(f"data_dir is not a directory: {data_dir}")- images = sorted(p for p in root.iterdir() if p.is_file() and p.suffix.lower() in _IMAGE_EXTS)+ # The caption lookup resolves to the caption's own companion, which exists, so the pair+ # reads as a real one.+ images = drop_appledouble_metadata(+ sorted(p for p in root.iterdir() if p.is_file() and p.suffix.lower() in _IMAGE_EXTS)+ )# 1. metadata.jsonl / captions.jsonl (either name accepted).meta_caption: dict[str, str] = {}diff --git a/studio/backend/core/training/diffusion_training_service.py b/studio/backend/core/training/diffusion_training_service.pyindex 86a75d4673d..d734672a05f 100644--- a/studio/backend/core/training/diffusion_training_service.py+++ b/studio/backend/core/training/diffusion_training_service.py@@ -27,6 +27,7 @@ import timeimport uuidfrom pathlib import Pathfrom typing import Any, Callable, Optional+from utils.paths.path_utils import drop_appledouble_metadata# Spawn (not fork): a fresh interpreter so parent CUDA/torch state never leaks into the trainer._CTX = mp.get_context("spawn")@@ -209,7 +210,10 @@ def list_diffusion_runs(limit: int = 20) -> list[dict]:"""Summaries of persisted diffusion runs, newest first. The heavy per-run payload(metric logs, config) stays in the file; fetch it via ``get_diffusion_run``."""try:- files = sorted(_runs_dir().glob("*.json"), key = lambda p: p.stat().st_mtime, reverse = True)+ # Sliced by limit below, so a companion per run would halve the history window.+ files = drop_appledouble_metadata(+ sorted(_runs_dir().glob("*.json"), key = lambda p: p.stat().st_mtime, reverse = True)+ )except Exception: # noqa: BLE001 -- unreadable dir -> no historyreturn []out: list[dict] = []diff --git a/studio/backend/core/training/s3_dataset.py b/studio/backend/core/training/s3_dataset.pyindex 3d05d19c75b..e25b1479419 100644--- a/studio/backend/core/training/s3_dataset.py+++ b/studio/backend/core/training/s3_dataset.py@@ -22,6 +22,7 @@ import shutilimport tempfilefrom importlib.util import find_specfrom typing import Callable, Optional+from utils.paths.path_utils import drop_shadowed_appledouble_nameslogger = logging.getLogger(__name__)@@ -102,7 +103,10 @@ def _list_dataset_keys(client, bucket: str, prefix: Optional[str]) -> list[str]:continueif key.lower().endswith(SUPPORTED_EXTENSIONS):keys.append(key)- return keys+ # A sync from a Mac uploads Finder metadata too, under the shard's own extension, and+ # _validate_single_extension_family cannot see it. Nothing to read here, so a key is+ # dropped only when the object it would describe is in the same listing.+ return drop_shadowed_appledouble_names(keys)def _extension_family(key: str) -> str:diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex 73b2af3eea9..b6131c2e38d 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -76,6 +76,7 @@ from utils.datasets.completion_masking import apply_completion_maskingfrom utils.datasets.iterable import is_streaming_dataset as detect_streaming_datasetfrom utils.datasets.raw_text import prepare_raw_text_dataset, resolve_column_namesfrom utils.paths import (+ dataset_files_in_dir,ensure_dir,resolve_dataset_path,resolve_output_dir,@@ -2522,22 +2523,7 @@ class UnslothTrainer:file_path_obj = Path(file_path)if file_path_obj.is_dir():- parquet_dir = (- file_path_obj / "parquet-files"- if (file_path_obj / "parquet-files").exists()- else file_path_obj- )- parquet_files = sorted(parquet_dir.glob("*.parquet"))- if parquet_files:- all_files.extend(str(p) for p in parquet_files)- continue- candidates: list[Path] = []- for ext in (".json", ".jsonl", ".csv", ".parquet"):- candidates.extend(sorted(file_path_obj.glob(f"*{ext}")))- if candidates:- all_files.extend(str(c) for c in candidates)- continue- raise ValueError(f"No supported data files in directory: {file_path_obj}")+ all_files.extend(str(p) for p in dataset_files_in_dir(file_path_obj))else:all_files.append(str(file_path_obj))return all_filesdiff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex a3f1f4a1601..c7aa274b207 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -2443,7 +2443,7 @@ def _normalize_mlx_studio_scheduler(value):def _resolve_mlx_local_dataset_files(file_paths: list) -> list[str]:"""Resolve CLI paths and Unsloth local dataset uploads without importing the GPU trainer."""- from utils.paths import resolve_dataset_path+ from utils.paths import dataset_files_in_dir, resolve_dataset_pathall_files: list[str] = []for dataset_file in file_paths or []:@@ -2457,24 +2457,8 @@ def _resolve_mlx_local_dataset_files(file_paths: list) -> list[str]:file_path_obj = Path(file_path)if file_path_obj.is_dir():- parquet_dir = (- file_path_obj / "parquet-files"- if (file_path_obj / "parquet-files").exists()- else file_path_obj- )- parquet_files = sorted(parquet_dir.glob("*.parquet"))- if parquet_files:- all_files.extend(str(p) for p in parquet_files)- continue-- candidates: list[Path] = []- for ext in (".json", ".jsonl", ".csv", ".parquet"):- candidates.extend(sorted(file_path_obj.glob(f"*{ext}")))- if candidates:- all_files.extend(str(c) for c in candidates)- continue-- raise ValueError(f"No supported data files in directory: {file_path_obj}")+ all_files.extend(str(p) for p in dataset_files_in_dir(file_path_obj))+ continueall_files.append(str(file_path_obj))@@ -5174,6 +5158,8 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->local_datasets = config.get("local_datasets") or []def _load_local_embedding_dataset(dataset_paths: list[str]):+ from utils.paths import dataset_files_in_dir+all_files: list[str] = []for dataset_file in dataset_paths:file_path = (@@ -5186,22 +5172,7 @@ def _run_embedding_training(event_queue: Any, stop_queue: Any, config: dict) ->)if os.path.isdir(file_path):file_path_obj = Path(file_path)- parquet_dir = (- file_path_obj / "parquet-files"- if (file_path_obj / "parquet-files").exists()- else file_path_obj- )- parquet_files = sorted(parquet_dir.glob("*.parquet"))- if parquet_files:- all_files.extend(str(p) for p in parquet_files)- continue- candidates: list[Path] = []- for ext in (".json", ".jsonl", ".csv", ".parquet"):- candidates.extend(sorted(file_path_obj.glob(f"*{ext}")))- if candidates:- all_files.extend(str(c) for c in candidates)- continue- raise ValueError(f"No supported data files in directory: {file_path_obj}")+ all_files.extend(str(p) for p in dataset_files_in_dir(file_path_obj))else:all_files.append(file_path)diff --git a/studio/backend/hub/services/datasets/formatting.py b/studio/backend/hub/services/datasets/formatting.pyindex c60b5b502b1..8f52f9b4306 100644--- a/studio/backend/hub/services/datasets/formatting.py+++ b/studio/backend/hub/services/datasets/formatting.py@@ -44,6 +44,7 @@ from hub.utils.paths import (resolve_dataset_path,)from utils.datasets.audio_decode import ensure_audio_decoding+from utils.paths.path_utils import drop_shadowed_appledouble_nameslogger = get_logger(__name__)@@ -226,7 +227,12 @@ def _select_tier1_repo_file(train_split: str,allow_unlabeled_fallback: bool = False,) -> Optional[str]:- data_files = sorted(f for f in files if any(f.lower().endswith(ext) for ext in DATA_EXTS))+ # "._train.parquet" sorts first and would be handed to the single-file preview load.+ data_files = sorted(+ f+ for f in drop_shadowed_appledouble_names(list(files))+ if any(f.lower().endswith(ext) for ext in DATA_EXTS)+ )if not data_files:return Nonetabular_files = [f for f in data_files if any(f.lower().endswith(ext) for ext in _TABULAR_EXTS)]diff --git a/studio/backend/hub/services/datasets/local.py b/studio/backend/hub/services/datasets/local.pyindex 988ad5d6b68..4360128a122 100644--- a/studio/backend/hub/services/datasets/local.py+++ b/studio/backend/hub/services/datasets/local.py@@ -20,6 +20,11 @@ from hub.schemas.datasets import ()from hub.utils.paths import dataset_uploads_root, ensure_dir, recipe_datasets_rootfrom utils.upload_limits import get_upload_limit_mb, upload_limit_bytes, upload_limit_label+from utils.paths.path_utils import (+ any_not_appledouble_metadata,+ drop_appledouble_metadata,+ is_appledouble_metadata,+)# Tabular formats are preferred over archives for Tier 1 preview: archives (e.g. images.zip)# load as ImageFolder with synthetic columns that don't match the real schema.@@ -133,7 +138,9 @@ def _build_recipe_dataset_items() -> list[LocalDatasetItem]:if not entry.is_dir() or not entry.name.startswith("recipe_"):continueparquet_dir = entry / "parquet-files"- if not parquet_dir.exists() or not any(parquet_dir.glob("*.parquet")):+ if not parquet_dir.exists() or not any_not_appledouble_metadata(+ parquet_dir.glob("*.parquet")+ ):continuerows = None@@ -167,6 +174,8 @@ def _build_uploaded_dataset_items() -> list[LocalDatasetItem]:for path in DATASET_UPLOAD_DIR.iterdir():if not path.is_file() or path.suffix.lower() not in LOCAL_UPLOAD_EXTS:continue+ if is_appledouble_metadata(path):+ continuetry:if path.stat().st_size == 0:continue@@ -233,7 +242,7 @@ def _load_local_preview_slice(*, dataset_path: Path, train_split: str, preview_sif (dataset_path / "parquet-files").exists()else dataset_path)- parquet_files = sorted(parquet_dir.glob("*.parquet"))+ parquet_files = drop_appledouble_metadata(sorted(parquet_dir.glob("*.parquet")))if parquet_files:dataset = load_dataset("parquet",@@ -246,7 +255,7 @@ def _load_local_preview_slice(*, dataset_path: Path, train_split: str, preview_scandidate_files: list[Path] = []for ext in LOCAL_FILE_EXTS:- candidate_files.extend(sorted(dataset_path.glob(f"*{ext}")))+ candidate_files.extend(drop_appledouble_metadata(sorted(dataset_path.glob(f"*{ext}"))))if not candidate_files:raise HTTPException(status_code = 400,diff --git a/studio/backend/hub/services/datasets/local_options.py b/studio/backend/hub/services/datasets/local_options.pyindex 21746f3ee99..222a02d1557 100644--- a/studio/backend/hub/services/datasets/local_options.py+++ b/studio/backend/hub/services/datasets/local_options.py@@ -27,6 +27,7 @@ from utils.hf_dataset_options import (HF_DATASET_SPLIT_NAME_PATTERN,has_unsafe_hf_dataset_option_characters,)+from utils.paths.path_utils import is_appledouble_metadata_MAX_METADATA_BYTES = 2 * 1024 * 1024@@ -196,6 +197,7 @@ def _processed_options(path: Path) -> set[tuple[str, str]]:name.lower().endswith(".arrow")and not (base / name).is_symlink()and (base / name).is_file()+ and not is_appledouble_metadata(base / name)for name in filenames):continuediff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.pyindex 119ff55e3a9..cde5f4817d5 100644--- a/studio/backend/hub/services/models/cache_inventory.py+++ b/studio/backend/hub/services/models/cache_inventory.py@@ -45,6 +45,7 @@ from hub.services.models.common import (# scan loop swallows per-repo exceptions and would drop every repo. Lives under# ``utils`` (not ``utils.models``) to avoid the eager model-config/checkpoint# imports in ``utils/models/__init__.py``.+from utils.paths.path_utils import is_appledouble_metadatafrom utils.hidden_models import is_curated_stt_repo_id, is_hidden_modellogger = get_logger(__name__)@@ -131,7 +132,7 @@ def _repo_gguf_size_bytes(repo_info) -> int:unique_blobs: dict[str, int] = {}for revision in repo_info.revisions:rev_id = getattr(revision, "commit_hash", None) or str(id(revision))- for f in revision.files:+ for f in cached_repo_files(revision):# Snapshot-relative: only the directory marks an MTP/ drafter as a companion.name = _cached_repo_file_name(f)if _is_main_gguf_filename(name):@@ -164,7 +165,7 @@ def _blob_mtime(file_obj) -> float:def _repo_gguf_last_modified(repo_info) -> float:latest = 0.0for revision in repo_info.revisions:- for f in revision.files:+ for f in cached_repo_files(revision):if _is_main_gguf_filename(_cached_repo_file_name(f)):latest = max(latest, _blob_mtime(f))return latest@@ -177,7 +178,7 @@ def _repo_has_mmproj(repo_info) -> bool:return any(_is_gguf_filename(f.file_name) and _is_mmproj_filename(f.file_name)for revision in repo_info.revisions- for f in revision.files+ for f in cached_repo_files(revision))@@ -195,6 +196,21 @@ def _cached_repo_file_name(file_obj) -> str:return str(getattr(file_obj, "file_name", "")).replace("\\", "/")+def cached_repo_files(revision) -> list:+ """``revision.files`` without the Finder metadata companions.++ Every classification below reads these by name, and a "._" companion carries the described+ file's own name, so it answers each one the way the real file does.+ """+ # The "._" name is on the snapshot entry, the bytes are in the content-addressed blob whose+ # own name carries no prefix -- but the entry is a symlink to it, so one open reads both.+ return [+ f+ for f in getattr(revision, "files", ()) or ()+ if not is_appledouble_metadata(Path(getattr(f, "file_path", "")))+ ]++def _is_real_cache_blob(blob: Optional[Path], repo_dir: Optional[Path]) -> bool:"""True only for a real cache blob at ``<repo_dir>/blobs/<etag>``.@@ -242,7 +258,7 @@ def _repo_gguf_blob_map(repo_info, *, include_companions: bool = False) -> dict[blob_map: dict[str, set[str]] = {}repo_path = getattr(repo_info, "repo_path", None)for revision in repo_info.revisions:- for f in revision.files:+ for f in cached_repo_files(revision):name = _cached_repo_file_name(f)if include_companions:if not _is_gguf_filename(name):@@ -721,7 +737,9 @@ def _repo_gguf_payload_snapshots(repo_info) -> tuple[Optional[Path], frozenset[ssnapshotfor revision in repo_info.revisionsif (snapshot := getattr(revision, "snapshot_path", None)) is not None- and any(_is_main_gguf_filename(_cached_repo_file_name(f)) for f in revision.files)+ and any(+ _is_main_gguf_filename(_cached_repo_file_name(f)) for f in cached_repo_files(revision)+ )]complete = [snapshot@@ -753,7 +771,7 @@ def _repo_non_gguf_model_payload(repo_info) -> _CachedNonGgufPayload:for revision in repo_info.revisions:rev_id = getattr(revision, "commit_hash", None) or str(id(revision))flags = dict.fromkeys(_PAYLOAD_FLAGS, False)- for f in revision.files:+ for f in cached_repo_files(revision):file_name = str(f.file_name)lower = file_name.lower()name = lower.replace("\\", "/").rsplit("/", 1)[-1]diff --git a/studio/backend/hub/services/models/common.py b/studio/backend/hub/services/models/common.pyindex 68c6ac9d0c9..4c96cfd2ea5 100644--- a/studio/backend/hub/services/models/common.py+++ b/studio/backend/hub/services/models/common.py@@ -24,6 +24,7 @@ from hub.utils.gguf import (is_mtp_drafter_path as _is_mtp_drafter_path,)from hub.utils.paths import is_valid_repo_id as _is_valid_repo_id+from utils.paths.path_utils import drop_appledouble_metadata, is_appledouble_metadataModelType = Literal["text", "vision", "audio", "embeddings"]LocalModelSource = Literal["models_dir", "hf_cache", "lmstudio", "ollama", "custom"]@@ -68,6 +69,8 @@ def _is_model_directory(d: Path) -> bool:"""True when *d* has a config plus real weights; excludes mmproj GGUFs and non-weight ``.bin`` files (``tokenizer.bin``) to avoid false positives."""def _is_weight_file(f: Path) -> bool:+ if is_appledouble_metadata(f):+ return Falsesuffix = f.suffix.lower()if suffix == ".safetensors":return True@@ -564,6 +567,8 @@ def _iter_gguf_paths(root: Path):if path.is_dir() and not path.is_symlink():stack.append(path)elif path.is_file() and _is_gguf_filename(path.name):+ if is_appledouble_metadata(path):+ continueyield pathexcept OSError:continue@@ -592,7 +597,7 @@ def _iter_hf_cache_model_files(path: Path) -> list[Path]:_is_main_gguf_filename(entry.name)or _is_transformers_safetensors_weight_file(entry)or _is_checkpoint_weight_file(entry)- for entry in files+ for entry in drop_appledouble_metadata(files)):return filestry:@@ -624,7 +629,7 @@ def _main_gguf_files(path: Path, *, include_symlinks: bool = False) -> list[Pathreturn [entryfor entry in _iter_immediate_files(path, include_symlinks = include_symlinks)- if _is_main_gguf_filename(entry.name)+ if _is_main_gguf_filename(entry.name) and not is_appledouble_metadata(entry)]@@ -761,6 +766,7 @@ def _classify_local_path(if source == "hf_cache"else _iter_immediate_files(scan_path))+ files = [f for f in files if not is_appledouble_metadata(f)]if not files:return []diff --git a/studio/backend/hub/services/models/companion_cleanup.py b/studio/backend/hub/services/models/companion_cleanup.pyindex 1939358324b..3c251c236e6 100644--- a/studio/backend/hub/services/models/companion_cleanup.py+++ b/studio/backend/hub/services/models/companion_cleanup.py@@ -29,6 +29,7 @@ from hub.services.models import cache_inventoryfrom hub.services.models.common import _is_main_gguf_filenamefrom hub.utils.paths import is_valid_gguf_variant as _is_valid_gguf_variantfrom hub.utils.paths import is_valid_repo_id as _is_valid_repo_id+from utils.paths.path_utils import is_appledouble_metadatalogger = get_logger(__name__)@@ -114,6 +115,10 @@ def _remaining_main_gguf_variants(repo_info, *, excluding: Optional[str] = None)passif not _is_main_gguf_filename(name):continue+ # The delete this previews ignores proven metadata, so counting it here reports a+ # checkpoint as surviving that the deletion itself does not see.+ if path and is_appledouble_metadata(Path(path)):+ continuekey = gguf_variant_key(name).lower()if key and key not in skip:found.add(key)diff --git a/studio/backend/hub/services/models/deletion.py b/studio/backend/hub/services/models/deletion.pyindex dd3af996b20..2d992875c40 100644--- a/studio/backend/hub/services/models/deletion.py+++ b/studio/backend/hub/services/models/deletion.py@@ -22,6 +22,7 @@ from hub.utils.gguf import (gguf_variant_key,is_qualified_gguf_variant_key,quant_token_with_bpw,+ remove_appledouble_sidecar,is_reclaimable_drafter_path as _is_reclaimable_drafter_path,)from hub.utils.hf_cache_state import (@@ -43,6 +44,7 @@ from hub.services.models.common import (_is_main_gguf_filename,_is_mmproj_filename,)+from utils.paths.path_utils import is_appledouble_metadatalogger = get_logger(__name__)@@ -84,6 +86,20 @@ def _path_exists_or_symlink(path: Path) -> bool:return False+def _unlink_snapshot_entry(snap: Path) -> int:+ """Unlink one snapshot entry, plus any AppleDouble sidecar beside it.++ Returns the entries removed, which never counts the sidecar: it is metadata about a file the+ caller asked to remove, not a second file.+ """+ removed = 0+ if _path_exists_or_symlink(snap):+ snap.unlink()+ removed += 1+ remove_appledouble_sidecar(snap)+ return removed++def _repo_file_matches(target_repo, predicate) -> list[tuple[Path, Optional[Path], str]]:"""Files whose snapshot-relative path satisfies *predicate*.@@ -109,6 +125,11 @@ def _repo_file_matches(target_repo, predicate) -> list[tuple[Path, Optional[Pathcontinueif not file_path:continue+ # Every predicate here keys on the name, which a sidecar answers exactly as its+ # neighbour does, so it would be counted as a deleted model in its own right.+ # Proven metadata only: anything else carrying this key is a file to delete.+ if is_appledouble_metadata(Path(file_path)):+ continueblob_path = getattr(f, "blob_path", None)matches.append((@@ -265,9 +286,7 @@ def _delete_gguf_variant_from_repos(for snap, _blob, name in matched:try:- if _path_exists_or_symlink(snap):- snap.unlink()- removed_snapshots += 1+ removed_snapshots += _unlink_snapshot_entry(snap)except OSError as e:failures.append(f"{name}: {e}")@@ -283,9 +302,7 @@ def _delete_gguf_variant_from_repos()for snap, _blob, name in companion_matches:try:- if _path_exists_or_symlink(snap):- snap.unlink()- removed_snapshots += 1+ removed_snapshots += _unlink_snapshot_entry(snap)except OSError as e:failures.append(f"{name}: {e}")@@ -502,9 +519,7 @@ def reclaim_replaced_gguf_variant(for snap, _blob, name in stale_matches:try:- if _path_exists_or_symlink(snap):- snap.unlink()- removed_snapshots += 1+ removed_snapshots += _unlink_snapshot_entry(snap)except OSError as e:failures.append(f"{name}: {e}")diff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.pyindex aeb64e6974a..96682434c18 100644--- a/studio/backend/hub/services/models/gguf_variants.py+++ b/studio/backend/hub/services/models/gguf_variants.py@@ -59,6 +59,7 @@ from hub.utils.gguf_plan import (is_main_gguf_variant_path,plan_from_expected_files,)+from utils.paths.path_utils import is_appledouble_metadatalogger = get_logger(__name__)@@ -723,6 +724,7 @@ def _direct_gguf_loads(path: Path) -> bool:_is_mmproj_filename(path.name)or _is_mtp_drafter_path(context)or is_big_endian_gguf_path(context, _extract_quant_label(context))+ or is_appledouble_metadata(path))diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.pyindex a929830b409..12f147f5ba7 100644--- a/studio/backend/hub/services/models/local_inventory.py+++ b/studio/backend/hub/services/models/local_inventory.py@@ -37,6 +37,7 @@ from hub.utils.paths import (from hub.services.models import common as model_commonfrom hub.services.models.ollama import scan_ollama_dirfrom utils.hidden_models import is_hidden_model+from utils.paths.path_utils import is_appledouble_metadatafrom utils.paths.scan_folder_health import (annotate_scan_folders,note_scan_folder_scanned,@@ -92,6 +93,8 @@ _gguf_variant_state_summary = model_common._gguf_variant_state_summarydef _is_immediate_model_weight_file(path: Path) -> bool:+ if is_appledouble_metadata(path):+ return Falsesuffix = path.suffix.lower()if suffix == ".safetensors":return True@@ -225,7 +228,12 @@ def _scan_models_dir(breaktry:is_dir = child.is_dir()- is_gguf_file = not is_dir and child.suffix.lower() == ".gguf" and child.is_file()+ is_gguf_file = (+ not is_dir+ and child.suffix.lower() == ".gguf"+ and child.is_file()+ and not is_appledouble_metadata(child)+ )if not is_dir and not is_gguf_file:continuehas_model_files = is_gguf_file or _has_immediate_model_signal(child)@@ -488,7 +496,11 @@ def _scan_lmstudio_dir(lm_dir: Path, *, entry_limit: int | None = None) -> List[breaktry:if not child.is_dir():- if child.suffix.lower() == ".gguf" and child.is_file():+ if (+ child.suffix.lower() == ".gguf"+ and child.is_file()+ and not is_appledouble_metadata(child)+ ):try:updated_at = child.stat().st_mtimeexcept OSError:@@ -542,7 +554,11 @@ def _scan_lmstudio_dir(lm_dir: Path, *, entry_limit: int | None = None) -> List[updated_at = updated_at,))- elif model_dir.suffix.lower() == ".gguf" and model_dir.is_file():+ elif (+ model_dir.suffix.lower() == ".gguf"+ and model_dir.is_file()+ and not is_appledouble_metadata(model_dir)+ ):try:updated_at = model_dir.stat().st_mtimeexcept OSError:diff --git a/studio/backend/hub/services/snapshot_progress.py b/studio/backend/hub/services/snapshot_progress.pyindex 8112852d487..449ed185c29 100644--- a/studio/backend/hub/services/snapshot_progress.py+++ b/studio/backend/hub/services/snapshot_progress.py@@ -31,6 +31,7 @@ from hub.utils.hf_cache_state import (snapshot_selection_key,)from hub.utils.paths import is_valid_repo_id as _is_valid_repo_id+from utils.paths.path_utils import is_appledouble_metadatalogger = get_logger(__name__)@@ -211,6 +212,9 @@ def _variant_main_shard_present(entries, complete = _walk_files(snapshot_dir)for path in entries:relative = path.relative_to(snapshot_dir).as_posix()+ # A sidecar left by a deleted quant answers the quant matcher, so the job is re-adopted.+ if is_appledouble_metadata(path):+ continueif variant_file_matcher(relative, companions = False):return Truereturn None if not complete else False@@ -266,6 +270,8 @@ def _materialized_bytes(snapshot_dir: Path, variant_file_matcher: "VariantFileMaentries = list(snapshot_dir.rglob("*")) # unordered: the result is a sumexcept OSError:return 0+ # Same false "still active" as the companion clause below, reached by a stranded sidecar.+ entries = [path for path in entries if not is_appledouble_metadata(path)]def _accepts(relative: str, *, companions: bool) -> bool:# A matcher that understands the distinction gets asked for it; an older one isdiff --git a/studio/backend/hub/tests/conftest.py b/studio/backend/hub/tests/conftest.pyindex 9b79c738b85..a19f4c74051 100644--- a/studio/backend/hub/tests/conftest.py+++ b/studio/backend/hub/tests/conftest.py@@ -74,7 +74,23 @@ class _DummyLogger:return lambda *args, **kwargs: None-sys.modules.setdefault(+def _stub_unless_installed(name: str, stub) -> None:+ """Stub *name* only when it is genuinely not installed.++ ``setdefault`` alone stubs whenever the module is merely not imported yet, and these stubs+ carry a few symbols each. Since they are never removed, one such stub decides the rest of+ the process: anything importing ``routes`` afterwards dies on a name the stub omits, which+ is most of ``studio/backend/tests``.+ """+ if name in sys.modules:+ return+ try:+ __import__(name)+ except ImportError:+ sys.modules[name] = stub+++_stub_unless_installed("pydantic",types.SimpleNamespace(BaseModel = _BaseModel,@@ -82,7 +98,7 @@ sys.modules.setdefault(model_validator = _model_validator,),)-sys.modules.setdefault(+_stub_unless_installed("fastapi",types.SimpleNamespace(APIRouter = _APIRouter,diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.pyindex 2f2666a0b1b..0366fb31bec 100644--- a/studio/backend/hub/tests/test_model_services.py+++ b/studio/backend/hub/tests/test_model_services.py@@ -5701,6 +5701,27 @@ def test_a_shared_companion_alone_is_not_evidence_the_quant_is_here(tmp_path):assert snapshot_progress._materialized_bytes(snap, lambda path: path.startswith("mmproj")) == 64+def test_finder_metadata_left_by_a_deleted_quant_is_not_that_quant(tmp_path):+ """macOS keeps a file's metadata in a "._" companion carrying the same name, so it matches+ the quant matcher exactly as its file does. Deleting the quant on a filesystem without+ native xattrs strands that companion, which both walks then read as the quant still being+ here -- hydration re-adopts the stale job and blocks a fresh download. A real GGUF a user+ named that way is still the quant."""+ snap = tmp_path / "snapshots" / "rev0"+ snap.mkdir(parents = True)+ (snap / "._model-Q4_K_M.gguf").write_bytes(b"\x00\x05\x16\x07" + b"m" * 60)++ def matcher(path, *, companions = True):+ return path.endswith("Q4_K_M.gguf")++ assert snapshot_progress._materialized_bytes(snap, matcher) == 0+ assert snapshot_progress._variant_main_shard_present(snap, matcher) is False++ (snap / "._named-Q4_K_M.gguf").write_bytes(b"GGUF" + b"q" * 28)+ assert snapshot_progress._materialized_bytes(snap, matcher) == 32+ assert snapshot_progress._variant_main_shard_present(snap, matcher) is True++def test_a_root_that_will_not_resolve_is_a_scan_error(monkeypatch, tmp_path):"""A root that stats but will not resolve -- an intermittent network mount, a Windowsreparse point -- was dropped silently, so the scan answered "measured, no cache" and@@ -6097,6 +6118,25 @@ def test_local_embedding_model_is_not_chat_capable(tmp_path):assert rows["all-MiniLM-L6-v2"].capabilities.can_train is True+def test_a_snapshot_whose_only_weight_is_finder_metadata_is_not_a_safetensors_row(tmp_path):+ """Every non-GGUF classification here reads the file list by suffix, and a "._" companion+ carries the suffix of the file it describes -- so a directory left holding only those was+ given a ready safetensors row. A real weight named that way still gets one."""++ def _formats(name, weight = None):+ d = tmp_path / name+ d.mkdir()+ (d / "config.json").write_text("{}")+ if weight is not None:+ (d / "._model.safetensors").write_bytes(weight)+ return [r.model_format for r in model_common._classify_local_path(d, "models_dir")]++ # A config with no weight beside it is already "unknown"; metadata must not read as more.+ assert _formats("config-only") == ["unknown"]+ assert _formats("metadata-only", b"\x00\x05\x16\x07\x00\x02\x00\x00") == ["unknown"]+ assert _formats("named", b"weights") == ["safetensors"]++def test_cached_encoder_repo_is_not_chat_capable(tmp_path):"""Cached rows build capabilities from file format too, so a cached BERTlooked like a chat model to auto-load."""diff --git a/studio/backend/hub/utils/companion_assets.py b/studio/backend/hub/utils/companion_assets.pyindex 6ab669a0f0a..a674c7531d0 100644--- a/studio/backend/hub/utils/companion_assets.py+++ b/studio/backend/hub/utils/companion_assets.py@@ -174,9 +174,10 @@ def _snapshot_relative_names(repo) -> Iterable[str]:relative name, so a GGUF filed under ``FLUX.2-klein/model-Q4_K_M.gguf`` is a dependent that abasename-only scan cannot see. The inventory and cleanup scanners already reconstruct it thisway; this is the same reconstruction, so all three agree on what a cached file is called."""+ from hub.services.models.cache_inventory import cached_repo_filesfor revision in getattr(repo, "revisions", ()) or ():snapshot = getattr(revision, "snapshot_path", None)- for file in getattr(revision, "files", ()) or ():+ for file in cached_repo_files(revision):name = str(getattr(file, "file_name", "") or "")path = getattr(file, "file_path", None)if path and snapshot:diff --git a/studio/backend/hub/utils/dataset_cache.py b/studio/backend/hub/utils/dataset_cache.pyindex 8d47b396add..80d2374c7c1 100644--- a/studio/backend/hub/utils/dataset_cache.py+++ b/studio/backend/hub/utils/dataset_cache.py@@ -22,6 +22,7 @@ from hub.utils.hf_cache_state import (same_existing_path,validated_repo_cache_path,)+from utils.paths.path_utils import drop_appledouble_metadata, is_appledouble_metadataTRAINING_DATA_EXTS = (".parquet", ".json", ".jsonl", ".csv")@@ -190,7 +191,7 @@ def processed_dataset_cache_has_artifacts(path: Path) -> bool:continuefor filename in filenames:entry = base / filename- if entry.suffix.lower() != ".arrow":+ if entry.suffix.lower() != ".arrow" or is_appledouble_metadata(entry):continuetry:if entry.is_symlink() or not entry.is_file():@@ -569,9 +570,9 @@ def cached_dataset_candidates(preferred_extensions: tuple[str, ...] = TRAINING_DATA_EXTS,) -> list[Path]:try:- files = [- p for p in snapshot.rglob("*") if p.is_file() and p.name.lower().endswith(extensions)- ]+ files = drop_appledouble_metadata(+ [p for p in snapshot.rglob("*") if p.is_file() and p.name.lower().endswith(extensions)]+ )except OSError:return []if not files:diff --git a/studio/backend/hub/utils/download_manifest.py b/studio/backend/hub/utils/download_manifest.pyindex 18e1eefc64b..e70c076c5fb 100644--- a/studio/backend/hub/utils/download_manifest.py+++ b/studio/backend/hub/utils/download_manifest.py@@ -56,6 +56,7 @@ from hub.utils.state_dir import (variant_filename_prefix,variant_key_fragments,)+from utils.paths.path_utils import drop_appledouble_metadatalogger = get_logger(__name__)@@ -870,7 +871,9 @@ def expected_files_from_snapshot_dir(snapshot_dir: Path) -> list[ExpectedFile]:"""out: list[ExpectedFile] = []try:- entries = sorted(snapshot_dir.rglob("*"))+ # Baking a companion into the completion contract makes the download read as partial+ # forever once macOS cleans it up.+ entries = drop_appledouble_metadata(sorted(snapshot_dir.rglob("*")))except OSError:return outfor path in entries:diff --git a/studio/backend/hub/utils/gguf.py b/studio/backend/hub/utils/gguf.pyindex a66c39e0938..6d2b5b0e039 100644--- a/studio/backend/hub/utils/gguf.py+++ b/studio/backend/hub/utils/gguf.py@@ -9,9 +9,14 @@ import osimport refrom dataclasses import dataclassfrom pathlib import Path-from typing import Optional+from typing import Optional, Sequencefrom loggers import get_logger+from utils.paths.path_utils import (+ drop_shadowed_appledouble_names as _drop_shadowed_appledouble_names,+ has_appledouble_magic,+ is_appledouble_metadata,+)from utils.models.gguf_metadata import mmproj_accepts_imagelogger = get_logger(__name__)@@ -142,6 +147,48 @@ def is_reclaimable_drafter_path(path: str) -> bool:)+def _appledouble_subject_key(name: str) -> object:+ """What a listing entry has to share with a ``._`` name for it to be that name's subject.++ Only a GGUF has shards to belong to, and a split quant's companions need not all be+ shadowed; every other suffix is its own subject.+ """+ return ("gguf", gguf_variant_family(name)) if is_gguf_filename(name) else ("name", name)+++def drop_shadowed_appledouble_names(files: list[str]) -> list[str]:+ """Shadow pairing keyed by GGUF shard family."""+ return _drop_shadowed_appledouble_names(files, subject_key = _appledouble_subject_key)+++def drop_shadowed_appledouble_siblings(siblings: Sequence) -> list:+ """Shadow pairing for callers holding sizes and hashes beside the name."""+ names = [getattr(s, "rfilename", None) for s in siblings]+ kept = set(drop_shadowed_appledouble_names([n for n in names if isinstance(n, str)]))+ return [s for s, n in zip(siblings, names) if not isinstance(n, str) or n in kept]+++def remove_appledouble_sidecar(path: Path) -> int:+ """Remove the sidecar beside *path* if it really is one; return the bytes freed.++ Now that discovery rejects sidecars, nothing else would ever name one, and metadata would+ outlive the weights it describes. Identified positively because this unlinks a file nobody+ asked for: a user's own ``._model.gguf`` is a real model, and deciding by name would delete+ weights. Best effort -- a sidecar that resists removal is a few KB, never a failed delete.+ """+ try:+ sidecar = Path(path).with_name(f"._{Path(path).name}")+ if not has_appledouble_magic(sidecar):+ return 0+ if sidecar.is_symlink() or sidecar.exists():+ freed = sidecar.stat().st_size+ sidecar.unlink()+ return freed+ except (OSError, ValueError):+ pass+ return 0++def is_gguf_filename(filename: str) -> bool:return filename.lower().endswith(".gguf")@@ -212,7 +259,10 @@ def iter_gguf_files(directory: Path, recursive: bool = False):for dirpath, dirnames, filenames in os.walk(directory, onerror = lambda _e: None):for name in filenames:if is_gguf_filename(name):- yield Path(dirpath) / name+ path = Path(dirpath) / name+ if is_appledouble_metadata(path):+ continue+ yield pathseen += len(dirnames) + len(filenames)if seen > _MAX_LOCAL_SCAN_ENTRIES:return@@ -224,6 +274,8 @@ def iter_gguf_files(directory: Path, recursive: bool = False):for file in entries:try:if file.is_file() and is_gguf_filename(file.name):+ if is_appledouble_metadata(file):+ continueyield fileexcept OSError:continue@@ -232,7 +284,8 @@ def iter_gguf_files(directory: Path, recursive: bool = False):def pick_best_gguf(filenames: list[str]) -> Optional[str]:gguf_files = [name- for name in filenames+ # The preference loop returns the first matching name, and "._" sorts ahead of it.+ for name in drop_shadowed_appledouble_names(list(filenames))if is_gguf_filename(name)and not is_mmproj_filename(name)and not is_mtp_drafter_path(name)@@ -853,7 +906,8 @@ def list_gguf_variants(has_vision = Falsemain_files: list[tuple[str, int]] = []- for sibling in info.siblings:+ # Sidecars in the listing would otherwise be advertised as the variant, at their own size.+ for sibling in drop_shadowed_appledouble_siblings(list(info.siblings)):filename = getattr(sibling, "rfilename", None)if not isinstance(filename, str) or not is_gguf_filename(filename):continuediff --git a/studio/backend/hub/utils/gguf_plan.py b/studio/backend/hub/utils/gguf_plan.pyindex ce563ea86b2..01287f66cc9 100644--- a/studio/backend/hub/utils/gguf_plan.py+++ b/studio/backend/hub/utils/gguf_plan.py@@ -13,6 +13,7 @@ from hub.utils.gguf import (gguf_variant_family,gguf_variant_key,is_big_endian_gguf_path,+ drop_shadowed_appledouble_siblings,is_gguf_filename,is_mmproj_filename,is_mtp_drafter_path,@@ -215,6 +216,10 @@ def dflash_plan_files(def build_gguf_variant_plans(siblings: Sequence) -> dict[str, GgufVariantPlan]:+ # Family grouping keeps the family holding the lexicographically first name, which is the+ # "._" one, so the plan fetched the sidecar and marked the variant complete -- leaving local+ # discovery, which judges by header, no main GGUF to load.+ siblings = drop_shadowed_appledouble_siblings(list(siblings))main: dict[str, list] = {}all_mmproj = mmproj_siblings(siblings)all_mmproj_filenames = frozenset(diff --git a/studio/backend/hub/utils/inventory_scan.py b/studio/backend/hub/utils/inventory_scan.pyindex 8fa12ee0f55..08d896d205a 100644--- a/studio/backend/hub/utils/inventory_scan.py+++ b/studio/backend/hub/utils/inventory_scan.py@@ -45,6 +45,7 @@ from hub.utils.hf_cache_state import (latest_snapshot_dir,repo_cache_dir_has_incomplete_blobs,)+from utils.paths.path_utils import drop_appledouble_metadata, is_appledouble_metadata# Inventory is invalidated explicitly on every app-driven cache mutation, so# this TTL only bounds staleness from out-of-band edits while skipping re-walks@@ -284,7 +285,7 @@ def _recover_repo_hidden_by_dangling_refs(repo_dir: Path) -> Optional[_Recoveredif not snapshot.is_dir():# Upstream treats a file here as corruption; defer to it.return None- entries = sorted(snapshot.rglob("*"))+ entries = drop_appledouble_metadata(sorted(snapshot.rglob("*")))except OSError:return Nonefiles: set[_RecoveredFileInfo] = set()@@ -779,6 +780,11 @@ def _completed_gguf_variants(snapshot_dir: Optional[Path]) -> set[str]:rel = path.relative_to(snapshot_dir).as_posix()if not is_gguf_filename(rel) or is_mmproj_filename(rel) or is_mtp_drafter_path(rel):continue+ # Metadata vouching for a quant marks a torn snapshot ready: a set whose sidecars are+ # all present but whose weights are not answers the shard count exactly as the real+ # files would, in its own family and under their quant.+ if is_appledouble_metadata(path):+ continuequant = gguf_variant_key(rel)# Mirror the lister: a big-endian build is never offered, so it cannot vouch for the# quant. Judged with the loader's label, since the two extractors disagree on@@ -975,7 +981,7 @@ def _snapshot_payload(snapshot_dir: Path) -> Optional[_SnapshotPayload]:unreachable_root: set[str] = set()unreadable: set[str] = set()try:- paths = list(snapshot_dir.rglob("*"))+ paths = drop_appledouble_metadata(list(snapshot_dir.rglob("*")))except OSError:return Nonefor path in paths:diff --git a/studio/backend/hub/utils/snapshot_filters.py b/studio/backend/hub/utils/snapshot_filters.pyindex 20674db4f01..67f5b47bdcb 100644--- a/studio/backend/hub/utils/snapshot_filters.py+++ b/studio/backend/hub/utils/snapshot_filters.py@@ -5,6 +5,7 @@ from __future__ import annotationsfrom fnmatch import fnmatchcasefrom typing import Iterable+from utils.paths.path_utils import drop_shadowed_appledouble_namesSNAPSHOT_IGNORE_PATTERNS: tuple[str, ...] = (@@ -43,7 +44,9 @@ def _size(sibling) -> int:def repo_ships_transformers_weights(filenames: Iterable[str]) -> bool:- for name in filenames:+ # A "._consolidated.safetensors" does not start with "consolidated", so it would answer yes+ # here and then have every consolidated* file stripped from the download.+ for name in drop_shadowed_appledouble_names(list(filenames)):base = name.rsplit("/", 1)[-1].lower()if base.startswith("consolidated"):continuediff --git a/studio/backend/picker/service.py b/studio/backend/picker/service.pyindex 123d332f655..1dc9c3b870e 100644--- a/studio/backend/picker/service.py+++ b/studio/backend/picker/service.py@@ -14,7 +14,10 @@ from hub.services.models.folder_browser import (_build_browse_allowlist,_is_path_inside_allowlist,)-from hub.utils.gguf import extract_quant_label, iter_snapshots_preferring_whole+from hub.utils.gguf import (+ extract_quant_label,+ iter_snapshots_preferring_whole,+)from utils.models.gguf_metadata import read_gguf_chat_templatefrom utils.models.model_config import (_extract_quant_label,@@ -30,6 +33,7 @@ from utils.paths.path_utils import ()from .schemas import MAX_CHAT_TEMPLATE_BYTES, ValidateChatTemplateResponse+from utils.paths.path_utils import is_appledouble_metadatalogger = logging.getLogger(__name__)@@ -232,6 +236,8 @@ def _iter_ggufs(dir_path: Path) -> list[Path]:if not name.lower().endswith(".gguf") or _is_mmproj(name):continuepath = Path(current) / name+ if is_appledouble_metadata(path):+ continuetry:rel = path.relative_to(dir_path).as_posix()except ValueError:diff --git a/studio/backend/routes/data_recipe/seed.py b/studio/backend/routes/data_recipe/seed.pyindex e38c9a59f9e..9c32b38945f 100644--- a/studio/backend/routes/data_recipe/seed.py+++ b/studio/backend/routes/data_recipe/seed.py@@ -37,6 +37,7 @@ from models.data_recipe import (SeedInspectUploadRequest,UnstructuredFileUploadResponse,)+from utils.paths.path_utils import is_appledouble_metadatalogger = get_logger(__name__)router = APIRouter()@@ -438,6 +439,10 @@ def _get_block_total_size(block_dir: Path) -> int:continueif f.name.endswith(".extracted.txt") or f.name.endswith(".meta.json"):continue+ # remove_unstructured_file keys on the name up to the first dot, which is empty for a+ # "._" name, so a counted companion could never be removed and the quota never freed.+ if is_appledouble_metadata(f):+ continuetotal += f.stat().st_sizereturn totaldiff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 8de4327795f..6370619c574 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -5895,7 +5895,11 @@ def _remote_gguf_companion_bytes(mtp_bytes = 0dspark_candidates: list[tuple[str, int]] = []dflash_sizes: dict[str, int] = {}- for sibling in info.siblings or []:+ from hub.utils.gguf import drop_shadowed_appledouble_siblings++ # The same listing the downloader resolves against: a sidecar outranking the real drafter+ # here budgets its own few KB for a load that then fetches the whole thing.+ for sibling in drop_shadowed_appledouble_siblings(list(info.siblings or [])):name = sibling.rfilename or ""base = Path(name).name.lower()if not base.endswith(".gguf"):@@ -6018,9 +6022,13 @@ def _remote_drafter_repo_bytes(spec: str, *, hf_token: Optional[str]) -> int:from huggingface_hub import model_infofrom utils.models.drafters import dflash_budget_bytes, split_listing_is_complete+ from hub.utils.gguf import drop_shadowed_appledouble_siblings+info = model_info(repo, token = hf_token, files_metadata = True)sizes: dict[str, int] = {}- for sibling in info.siblings or []:+ # A sidecar's few KB stands in for the drafter the launch then fetches, and this figure+ # is what admits or refuses a load beside a training run.+ for sibling in drop_shadowed_appledouble_siblings(list(info.siblings or [])):name = sibling.rfilename or ""if not Path(name).name.lower().endswith(".gguf"):continue@@ -6095,7 +6103,10 @@ def _cached_repo_gguf_bytes(repo: str, hint: str = "") -> int:),None,) or max(revisions, key = lambda r: getattr(r, "last_modified", 0) or 0, default = None)- for f in getattr(chosen, "files", ()) or ():+ from hub.services.models.cache_inventory import cached_repo_files++ # Quant subdirectories share a basename, so the largest file carrying one is charged.+ for f in cached_repo_files(chosen):name = str(f.file_name)if name.lower().endswith(".gguf"):sizes[name] = max(sizes.get(name, 0), int(f.size_on_disk or 0))@@ -16519,6 +16530,7 @@ from core.inference.tools import (_MAX_SNAPSHOT_FILES,_servable_segment,)+from utils.paths.path_utils import is_appledouble_metadatadef _contained_sandbox_path(session_id: str, filename: str) -> tuple[str, str]:@@ -16582,6 +16594,8 @@ def _sandbox_listing_names(sandbox_dir: str) -> "list[str]":continueexcept OSError:continue+ if is_appledouble_metadata(Path(path)):+ continuenames.append(os.path.relpath(path, sandbox_dir).replace(os.sep, "/"))if len(names) >= _MAX_SNAPSHOT_FILES:return namesdiff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 28bf3745b9f..6ecfbf81c66 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -217,6 +217,7 @@ from models.responses import (VisionCheckResponse,EmbeddingCheckResponse,)+from utils.paths.path_utils import is_appledouble_metadatarouter = APIRouter()logger = get_logger(__name__)@@ -253,6 +254,8 @@ def _is_model_directory(d: Path) -> bool:"""def _is_weight_file(f: Path) -> bool:+ if is_appledouble_metadata(f):+ return Falsesuffix = f.suffix.lower()if suffix == ".safetensors":return True@@ -292,7 +295,9 @@ def _has_non_gguf_weights(path: Path) -> bool:``.bin``), ignoring companion ``.bin`` files such as ``tokenizer.bin`` so aGGUF-only folder is not misread as a plain checkpoint."""try:- if any(path.glob("*.safetensors")):+ # Only the safetensors arm needs the check: a weight ".bin" is recognised by its name+ # prefix, which a "._" already fails.+ if any(not is_appledouble_metadata(f) for f in path.glob("*.safetensors")):return Truereturn any(_is_weight_bin(f.name) for f in path.glob("*.bin"))except OSError:@@ -362,7 +367,8 @@ def _scan_models_dir(models_dir: Path, *, limit: int | None = None) -> List[Locatry:if not child.is_dir():continue- gguf_names = [p.name for p in child.glob("*.gguf")]++ gguf_names = [p.name for p in child.glob("*.gguf") if not is_appledouble_metadata(p)]has_gguf = bool(gguf_names)# mmproj alone is a vision adapter, not servable weights: decides presence, never format.has_main_gguf = any(_is_main_gguf_filename(n) for n in gguf_names)@@ -400,7 +406,11 @@ def _scan_models_dir(models_dir: Path, *, limit: int | None = None) -> List[Locaif limit is not None and len(found) >= limit:break# A standalone mmproj is a vision adapter, not servable weights.- if gguf_file.is_file() and _is_main_gguf_filename(gguf_file.name):+ if (+ gguf_file.is_file()+ and _is_main_gguf_filename(gguf_file.name)+ and not is_appledouble_metadata(gguf_file)+ ):try:updated_at = gguf_file.stat().st_mtimeexcept OSError:@@ -521,11 +531,14 @@ def _dir_model_format(path: Path, recursive: bool = False) -> Optional[str]:blocking the event loop on a large cache."""try:- found = path.glob("*.gguf")- if not any(_is_main_gguf_filename(p.name) for p in found):++ def _servable(p: Path) -> bool:+ return _is_main_gguf_filename(p.name) and not is_appledouble_metadata(p)++ if not any(_servable(p) for p in path.glob("*.gguf")):if not recursive:return None- if not any(_is_main_gguf_filename(p.name) for p in path.glob("*/*.gguf")):+ if not any(_servable(p) for p in path.glob("*/*.gguf")):return Nonereturn None if _has_non_gguf_weights(path) else "gguf"except OSError:@@ -562,7 +575,11 @@ def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:for child in lm_dir.iterdir():try:if not child.is_dir():- if _is_main_gguf_filename(child.name) and child.is_file():+ if (+ _is_main_gguf_filename(child.name)+ and child.is_file()+ and not is_appledouble_metadata(child)+ ):try:updated_at = child.stat().st_mtimeexcept OSError:@@ -602,9 +619,12 @@ def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:try:if model_dir.is_dir():has_model = (- any(model_dir.glob("*.gguf"))+ any(not is_appledouble_metadata(p) for p in model_dir.glob("*.gguf"))or (model_dir / "config.json").exists()- or any(model_dir.glob("*.safetensors"))+ or any(+ not is_appledouble_metadata(p)+ for p in model_dir.glob("*.safetensors")+ ))if not has_model:continue@@ -624,7 +644,11 @@ def _scan_lmstudio_dir(lm_dir: Path) -> List[LocalModelInfo]:updated_at = updated_at,),)- elif _is_main_gguf_filename(model_dir.name) and model_dir.is_file():+ elif (+ _is_main_gguf_filename(model_dir.name)+ and model_dir.is_file()+ and not is_appledouble_metadata(model_dir)+ ):try:updated_at = model_dir.stat().st_mtimeexcept OSError:@@ -1322,6 +1346,8 @@ def _dir_has_downloaded_model(directory: Path, max_entries: int = 4000) -> bool:queue.append(entry)else:low = entry.name.lower()+ if is_appledouble_metadata(entry):+ continueif low.endswith((".gguf", ".safetensors")):return True# PyTorch checkpoints; gate by name so tokenizer.bin and friends don't count as weights.@@ -1434,7 +1460,9 @@ def _has_direct_model_signal(directory: Path) -> bool:name = child.nameif child.is_file():low = name.lower()- if low.endswith((".gguf", ".safetensors")):+ if low.endswith((".gguf", ".safetensors")) and not is_appledouble_metadata(+ child+ ):return Trueif low in ("config.json", "adapter_config.json"):return True@@ -2548,10 +2576,8 @@ async def discard_remote_code_download(return {"deleted": False, "reason": "not_cached"}# Hard guard: a repo with weights is a real model the user has -- leave it.- for rev in target_repo.revisions:- for f in rev.files:- if f.file_name.lower().endswith(_WEIGHTS):- return {"deleted": False, "reason": "has_weights"}+ if any(f.file_name.lower().endswith(_WEIGHTS) for f in _cached_files(target_repo)):+ return {"deleted": False, "reason": "has_weights"}revision_hashes = [rev.commit_hash for rev in target_repo.revisions]if not revision_hashes:@@ -2882,9 +2908,16 @@ def _variant_names_same_checkpoint(a: Optional[str], b: Optional[str]) -> bool:def _delete_gguf_variant_files(root: Path, variant: str) -> tuple[int, int]:deleted_count = 0deleted_bytes = 0+ from hub.utils.gguf import remove_appledouble_sidecar+for path in root.rglob("*"):if not path.is_file() or not _is_main_gguf_filename(path.name):continue+ # Counted as a model if left in, so the reported count would follow the walk order; it+ # still goes below, as metadata of the file it belongs to. Proven metadata only: anything+ # else carrying this variant's key is a file the user asked to delete.+ if is_appledouble_metadata(path):+ continue# Keyed on the path, not the basename: a repo holding several checkpoints at# one quant would otherwise delete every one of them for a single row.from utils.models.model_config import _gguf_variant_key@@ -2900,6 +2933,9 @@ def _delete_gguf_variant_files(root: Path, variant: str) -> tuple[int, int]:except OSError:passpath.unlink()+ # Skipped by the walk above, so this is its only chance to be reclaimed. Its bytes count+ # toward what was freed even though it is not counted as a model.+ deleted_bytes += remove_appledouble_sidecar(path)deleted_count += 1return deleted_count, deleted_bytes@@ -3770,6 +3806,15 @@ def _snapshot_has_gguf_projector(snapshot: str) -> bool:return impl(Path(snapshot))+def _cached_files(repo_info) -> list:+ return [f for rev in getattr(repo_info, "revisions", ()) or () for f in cached_repo_files(rev)]+++def cached_repo_files(revision) -> list:+ from hub.services.models.cache_inventory import cached_repo_files as impl+ return impl(revision)++def _cached_repo_file_name(file_obj) -> str:"""Snapshot-relative name for a cached file: huggingface_hub records the bare ``file_name``,which cannot tell an ``MTP/`` drafter from a quant."""@@ -3858,7 +3903,9 @@ def _repo_has_mmproj(repo_info) -> bool:"""True if the repo ships a GGUF vision adapter (mmproj), so it cantake image inputs. Cheap: scans already-listed file names only."""return any(- _is_mmproj_filename(f.file_name) for revision in repo_info.revisions for f in revision.files+ _is_mmproj_filename(f.file_name)+ for revision in repo_info.revisions+ for f in cached_repo_files(revision))@@ -3898,6 +3945,8 @@ def _iter_gguf_paths(root: Path, deadline: Optional[float] = None):if deadline is not None and time.monotonic() >= deadline:returnif path.is_file() and _is_gguf_filename(path.name):+ if is_appledouble_metadata(path):+ continueyield path@@ -3916,7 +3965,7 @@ def _repo_gguf_size_bytes(repo_info) -> int:unique_blobs: dict[str, int] = {}for revision in repo_info.revisions:rev_id = getattr(revision, "commit_hash", None) or str(id(revision))- for f in revision.files:+ for f in cached_repo_files(revision):# Snapshot-relative: only the directory tells an MTP/ drafter from a primary quant.name = _cached_repo_file_name(f)if _is_main_gguf_filename(name):@@ -3962,7 +4011,7 @@ def _repo_gguf_last_modified(repo_info) -> float:"""latest = 0.0for revision in repo_info.revisions:- for f in revision.files:+ for f in cached_repo_files(revision):if _is_main_gguf_filename(_cached_repo_file_name(f)):latest = max(latest, _blob_mtime(f))return latest@@ -4466,7 +4515,9 @@ def _repo_gguf_load_id(repo_info, active_root: Optional[Path]) -> Optional[str]:Path(snapshot)for revision in repo_info.revisionsif (snapshot := getattr(revision, "snapshot_path", None)) is not None- and any(_is_main_gguf_filename(_cached_repo_file_name(f)) for f in revision.files)+ and any(+ _is_main_gguf_filename(_cached_repo_file_name(f)) for f in cached_repo_files(revision)+ )]candidates.sort(key = snapshot_selection_key, reverse = True)# Newest first, skipping any holding no whole quant, else a torn download beats a loadable one.@@ -4722,8 +4773,7 @@ async def list_cached_models(continueweight_files = [f- for rev in repo_info.revisions- for f in rev.files+ for f in _cached_files(repo_info)if f.file_name.endswith(_WEIGHT_EXTENSIONS)]if not weight_files:@@ -4806,6 +4856,7 @@ def _resolve_cached_model_path(repo_id: str, variant: Optional[str]) -> Path:"""Absolute path of a cached repo (newest snapshot dir) or, with *variant*,that quant's main GGUF file (first split of a sharded quant). Paths comefrom the HF cache scan only, so callers can't probe arbitrary paths."""+cache_scans = _all_hf_cache_scans()matching_repos = []@@ -4839,6 +4890,9 @@ def _resolve_cached_model_path(repo_id: str, variant: Optional[str]) -> Path:rank = _main_variant_rank(rel, want)if rank is None:continue+ # Listed as a file of the revision, and keyed like the weights beside it.+ if is_appledouble_metadata(p):+ continueif p.exists() or p.is_symlink():ranked[rank].append((rel, p))# Exact keys alone when any exist, else the legacy label spelling.diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.pyindex 2fa2b74f72c..669febd7056 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -120,6 +120,7 @@ from pydantic import (Field as PydanticField,ValidationError,)+from utils.paths.path_utils import drop_appledouble_metadata, is_appledouble_metadataclass TrainingStopRequest(PydanticBaseModel):@@ -270,6 +271,14 @@ def _validate_local_dataset_paths(paths: list[str], label: str = "Local dataset"if not dataset_file.exists():missing.append(f"{dataset_path} (resolved: {dataset_file})")continue+ if is_appledouble_metadata(dataset_file):+ raise HTTPException(+ status_code = 400,+ detail = (+ f"{label} '{dataset_path}' is macOS Finder metadata, not data. "+ "Pick the file it sits beside."+ ),+ )logger.info(f"Found {label.lower()} file: {dataset_file}")validated.append(str(dataset_file))@@ -3114,7 +3123,7 @@ def _diffusion_dataset_summary(folder: Path) -> DiffusionDatasetSummary:# kind can read each), but captions are one folder total: the resolution rule is the same.meta_captions = _load_metadata_captions(folder)images = clips = captions = 0- for f in folder.iterdir():+ for f in drop_appledouble_metadata(list(folder.iterdir())):if not f.is_file():continueext = f.suffix.lower()@@ -3680,6 +3689,8 @@ def _safe_dataset_image_path(folder: Path, filename: str) -> Path:path.resolve().relative_to(folder.resolve())except ValueError:raise HTTPException(status_code = 400, detail = "Invalid image filename.")+ if is_appledouble_metadata(path):+ raise HTTPException(status_code = 400, detail = "Not an image file.")return path@@ -3792,7 +3803,7 @@ async def list_diffusion_dataset_images(def scan() -> DiffusionDatasetImagesResponse:meta = _load_metadata_captions(folder)records: list[DiffusionDatasetImageRecord] = []- for p in sorted(folder.iterdir()):+ for p in drop_appledouble_metadata(sorted(folder.iterdir())):if p.is_file() and p.suffix.lower() in _DIFFUSION_DATASET_MEDIA_EXTS:records.append(_image_record(folder, p, meta))return DiffusionDatasetImagesResponse(name = folder.name, path = str(folder), images = records)@@ -4160,7 +4171,9 @@ def _materialize_imagefolder_jsonl(entry: dict, dest: Path, cap: int) -> int:)# Map basename -> caption from every jsonl carrying file_name + caption column.captions: dict[str, str] = {}- for jf in sorted(snap.rglob("*.jsonl")):+ # read_text on a companion raises, and the caller turns any exception into a 502 that+ # fails the whole import.+ for jf in drop_appledouble_metadata(sorted(snap.rglob("*.jsonl"))):for line in jf.read_text(encoding = "utf-8").splitlines():line = line.strip()if not line:@@ -4176,10 +4189,12 @@ def _materialize_imagefolder_jsonl(entry: dict, dest: Path, cap: int) -> int:# First writer wins over sorted manifests, for deterministic results.captions.setdefault(Path(str(fn)).name, str(value))# Copy images (those with a caption first, so a cap keeps captioned pairs).- images = sorted(- p- for p in snap.rglob("*")- if p.is_file() and p.suffix.lower() in _DIFFUSION_DATASET_IMAGE_EXTS+ images = drop_appledouble_metadata(+ sorted(+ p+ for p in snap.rglob("*")+ if p.is_file() and p.suffix.lower() in _DIFFUSION_DATASET_IMAGE_EXTS+ ))images.sort(key = lambda p: (p.name not in captions, p.name))written = 0diff --git a/studio/backend/tests/test_appledouble_guards.py b/studio/backend/tests/test_appledouble_guards.pynew file mode 100644index 00000000000..f4bc56bd8e3--- /dev/null+++ b/studio/backend/tests/test_appledouble_guards.py@@ -0,0 +1,212 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""macOS Finder metadata companions, against the predicates and the shared walks.++A ``._<name>`` companion carries the described file's extension, so it answers every name-shaped+question the way the real file does, and ``Path.glob`` matches it. Consumers are covered through+what they share -- the predicates, the cache walk, the dataset walk -- rather than one case each.+Every fixture also holds a real file a user named ``._something``, which must survive: nothing+may be refused for its name alone.+"""++from __future__ import annotations++import os+import sys+from dataclasses import dataclass+from pathlib import Path+from types import SimpleNamespace++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from utils.paths.path_utils import ( # noqa: E402+ drop_appledouble_metadata,+ drop_shadowed_appledouble_names,+ is_appledouble_metadata,+)++_AD = b"\x00\x05\x16\x07\x00\x02\x00\x00"+++def test_only_the_magic_bytes_settle_it(tmp_path):+ (tmp_path / "model.safetensors").write_bytes(b"real")+ (tmp_path / "._model.safetensors").write_bytes(_AD)+ (tmp_path / "._mine.safetensors").write_bytes(b"real")++ assert is_appledouble_metadata(tmp_path / "._model.safetensors") is True+ assert is_appledouble_metadata(tmp_path / "._mine.safetensors") is False+ assert [p.name for p in drop_appledouble_metadata(sorted(tmp_path.iterdir()))] == [+ "._mine.safetensors",+ "model.safetensors",+ ]+++def test_a_read_that_fails_settles_nothing(tmp_path):+ """An unreadable ``._`` file is not proven to be metadata, so it is kept."""+ locked = tmp_path / "._locked.safetensors"+ locked.write_bytes(_AD)+ locked.chmod(0o000)+ if os.access(locked, os.R_OK):+ locked.chmod(0o600)+ pytest.skip("this user can read a mode-000 file, so the failed read cannot be staged")+ try:+ metadata = tmp_path / "._readable.safetensors"+ metadata.write_bytes(_AD)+ assert is_appledouble_metadata(locked) is False+ assert drop_appledouble_metadata([locked, metadata]) == [locked]+ finally:+ locked.chmod(0o600)+++def test_a_listing_with_no_bytes_pairs_by_subject():+ """Remote listings carry no bytes, so a ``._x`` goes only when its subject is listed beside+ it, in the same directory -- a sole candidate survives whatever it is called."""+ assert drop_shadowed_appledouble_names(["._solo.py"]) == ["._solo.py"]+ assert drop_shadowed_appledouble_names(["._a.py", "a.py"]) == ["a.py"]+ assert drop_shadowed_appledouble_names(["sub/._a.py", "a.py"]) == ["sub/._a.py", "a.py"]+ assert drop_shadowed_appledouble_names(["sub/._a.py", "sub/a.py"]) == ["sub/a.py"]+++def test_a_split_quant_pairs_by_shard_family():+ """A split quant's shards need not all be shadowed, so the subject is the family."""+ from hub.utils.gguf import drop_shadowed_appledouble_names as by_family++ assert by_family(["._m-00001-of-00002.gguf", "m-00002-of-00002.gguf"]) == [+ "m-00002-of-00002.gguf"+ ]+ assert by_family(["._mine.gguf"]) == ["._mine.gguf"]+++@dataclass(frozen = True)+class _CachedFile:+ file_name: str+ file_path: Path+ size_on_disk: int = 0+++def _cache_repo(tmp_path, entries):+ """A repo scan shaped like a real cache: the snapshot entry is a symlink, and the bytes it+ names live in a content-addressed blob whose own name carries no prefix."""+ blobs = tmp_path / "blobs"+ snapshot = tmp_path / "snapshots" / "rev0"+ blobs.mkdir()+ snapshot.mkdir(parents = True)+ files = []+ for i, (name, payload, size) in enumerate(entries):+ blob = blobs / f"blob{i}"+ blob.write_bytes(payload)+ entry = snapshot / name+ entry.parent.mkdir(parents = True, exist_ok = True)+ entry.symlink_to(blob)+ files.append(_CachedFile(Path(name).name, entry, size))+ revision = SimpleNamespace(files = frozenset(files), snapshot_path = snapshot, refs = {"main"})+ return SimpleNamespace(revisions = [revision])+++def test_cached_repo_files_follows_the_snapshot_entry_to_its_blob(tmp_path):+ """The ``._`` name is on the snapshot entry and the bytes are in the blob, but the entry+ links to it, so one open observes both. Every cache and model-route scan reads this list."""+ from hub.services.models.cache_inventory import cached_repo_files++ repo = _cache_repo(+ tmp_path,+ (+ ("transformer/model.safetensors", b"real", 0),+ ("transformer/._model.safetensors", _AD, 0),+ ("._mine.safetensors", b"real", 0),+ ("model-Q4_K_M.gguf", b"GGUF", 0),+ ("._model-Q4_K_M.gguf", _AD, 0),+ ("._mine.gguf", b"GGUF", 0),+ ),+ )+ assert sorted(f.file_name for f in cached_repo_files(repo.revisions[0])) == [+ "._mine.gguf",+ "._mine.safetensors",+ "model-Q4_K_M.gguf",+ "model.safetensors",+ ]+++def test_a_drafter_budget_prices_the_largest_file_of_a_shared_basename(tmp_path, monkeypatch):+ """Quant subdirectories share a basename, so the budget maxes over every cached file that+ carries it: keeping one entry per name would charge whichever quant a frozenset yielded."""+ import huggingface_hub++ from routes.inference import _cached_repo_gguf_bytes+ from utils.models import drafters++ # Largest in the middle, so keeping the first or the last entry for a name both miss it.+ repo = _cache_repo(+ tmp_path,+ (+ ("Q4_K_M/model.gguf", b"GGUF", 4),+ ("F16/model.gguf", b"GGUF", 9),+ ("Q8_0/model.gguf", b"GGUF", 1),+ ("._model.gguf", _AD, 2),+ ),+ )+ repo.repo_id = "org/d"+ monkeypatch.setattr(+ huggingface_hub, "scan_cache_dir", lambda **kw: SimpleNamespace(repos = [repo])+ )+ seen: dict = {}+ monkeypatch.setattr(+ drafters, "dflash_budget_bytes", lambda sizes, *a, **k: seen.update(sizes) or 0+ )++ _cached_repo_gguf_bytes("org/d")+ assert seen == {"model.gguf": 9}+++def test_a_dataset_directory_prefers_its_parquet_export(tmp_path):+ """The GPU, MLX and embedding trainers share this walk: the export outranks the directory's+ own files, a genuine prefixed file inside it survives, and holding neither is an error."""+ from utils.paths import dataset_files_in_dir++ (tmp_path / "train.jsonl").write_bytes(b'{"text": "hi"}\n')+ export = tmp_path / "parquet-files"+ export.mkdir()+ (export / "part.parquet").write_bytes(b"PAR1")+ (export / "._part.parquet").write_bytes(_AD)+ (export / "._mine.parquet").write_bytes(b"PAR1")+ assert [p.name for p in dataset_files_in_dir(tmp_path)] == ["._mine.parquet", "part.parquet"]++ empty = tmp_path / "empty"+ empty.mkdir()+ with pytest.raises(ValueError):+ dataset_files_in_dir(empty)+++def test_a_folder_holding_only_metadata_is_not_a_model(tmp_path):+ """The browse and downloaded-model probes walk the filesystem themselves. A folder whose+ only weight is the user's own prefixed file is a model; one holding only metadata is not."""+ from routes.models import _dir_has_downloaded_model, _has_direct_model_signal++ mine = tmp_path / "mine"+ mine.mkdir()+ (mine / "._mine.safetensors").write_bytes(b"real")+ assert _has_direct_model_signal(mine) is True+ assert _dir_has_downloaded_model(mine) is True++ metadata = tmp_path / "metadata"+ metadata.mkdir()+ (metadata / "._model.safetensors").write_bytes(_AD)+ assert _has_direct_model_signal(metadata) is False+ assert _dir_has_downloaded_model(metadata) is False+++def test_consolidated_weights_are_not_hidden_by_their_companion():+ """The companion does not start with "consolidated", so it answered the weight test and+ every consolidated* file was then stripped from the download."""+ from hub.utils.snapshot_filters import repo_ships_transformers_weights++ assert (+ repo_ships_transformers_weights(["._consolidated.safetensors", "consolidated.safetensors"])+ is False+ )+ assert repo_ships_transformers_weights(["model.safetensors"]) is Truediff --git a/studio/backend/tests/test_llama_cpp_start_failure_classification.py b/studio/backend/tests/test_llama_cpp_start_failure_classification.pyindex 4a83af57c9f..878cc6379c1 100644--- a/studio/backend/tests/test_llama_cpp_start_failure_classification.py+++ b/studio/backend/tests/test_llama_cpp_start_failure_classification.py@@ -753,6 +753,51 @@ class TestMacOSLoaderFailures:assert "llama-server failed to start." in msg+class TestANonGgufFile:+ # What llama.cpp prints when the bytes are not a GGUF. It formats the four it found with %c,+ # so an AppleDouble sidecar's 0x00051607 arrives as unprintable characters (#8566).+ _OUT = (+ "build: 9415 (06d26dfd) with Apple clang version 17.0.0 for arm64-apple-darwin24.6.0\n"+ "gguf_init_from_reader: invalid magic characters: '\ufffd\ufffd\ufffd\ufffd', "+ "expected 'GGUF'\n"+ "llama_server: exiting due to model loading error"+ )++ def test_it_is_reported_as_not_a_gguf(self, tmp_path):+ log = tmp_path / "llama-1-port-8080.log"+ msg = _classify(self._OUT, "/models/._muse-UD-Q2_K_XL.gguf", "local/muse", 1, None, log)++ assert "not a GGUF" in msg+ # The two things the generic fallback used to blame, neither of which is the cause.+ assert "enough memory" not in msg.lower()+ assert not msg.startswith("llama-server failed to start.")+ # The echoed bytes are unreadable, so the path is the only usable identifier.+ assert "._muse-UD-Q2_K_XL.gguf" in msg+ assert "companion" in msg+ # The remedy for the volume, not the generic re-download (#8566).+ assert "dot_clean -m" in msg+ assert "llama-server output:" in msg+ assert f"Full log: {log}" in msg++ def test_it_does_not_call_an_ordinary_main_model_the_bad_file(self):+ # The message must not settle which file was invalid, nor promise the output does.+ assert "is not a GGUF" in _classify(self._OUT, None, "local/muse", 1)+ msg = _classify(self._OUT, "/models/model-Q4_K_M.gguf", "local/m", 1)+ assert "model-Q4_K_M.gguf" in msg and "companion" in msg+ assert "names it" not in msg+ # An ordinary path is no evidence about the volume, so it keeps the generic remedy.+ assert "dot_clean" not in msg and "Re-download the model" in msg++ def test_a_dyld_failure_still_outranks_it(self):+ # Ordering only matters when both appear; the loader diagnosis is the more specific one.+ out = (+ "dyld[1]: Library not loaded: @rpath/libggml.dylib\n"+ "gguf_init_from_reader: invalid magic characters: '????', expected 'GGUF'"+ )+ msg = _classify(out, "/models/x.gguf", "local/x", 1)+ assert "not a GGUF" not in msg++class TestStartupDiagnostics:_UNKNOWN_OUT = ("build: 9415 (06d26dfd) with Apple clang version 17.0.0 for arm64-apple-darwin24.6.0\n"diff --git a/studio/backend/tests/test_recommended_folders_has_model.py b/studio/backend/tests/test_recommended_folders_has_model.pyindex c034824ba05..73ff0ccc40a 100644--- a/studio/backend/tests/test_recommended_folders_has_model.py+++ b/studio/backend/tests/test_recommended_folders_has_model.py@@ -24,6 +24,8 @@ import jsonimport osfrom pathlib import Path+from utils.paths.path_utils import is_appledouble_metadata+_backend_root = Path(__file__).resolve().parent.parent_models_src = _backend_root / "routes" / "models.py"@@ -45,7 +47,12 @@ def _load_has_downloaded_model():got = {n.name for n in body if isinstance(n, ast.FunctionDef)}assert got == wanted, f"helpers missing from source: {wanted - got}"module = ast.Module(body = body, type_ignores = [])- ns: dict = {"Path": Path, "os": os, "json": json}+ ns: dict = {+ "Path": Path,+ "os": os,+ "json": json,+ "is_appledouble_metadata": is_appledouble_metadata,+ }exec(compile(module, f"<extracted {_models_src}>", "exec"), ns)return ns["_dir_has_downloaded_model"]diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex 26b28573c76..dcfef11d118 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -1579,9 +1579,10 @@ def _is_gguf_filename(filename: str) -> bool:def _iter_gguf_files(directory: Path, recursive: bool = False):if not directory.is_dir():return+iterator = directory.rglob("*") if recursive else directory.iterdir()for f in iterator:- if f.is_file() and _is_gguf_filename(f.name):+ if f.is_file() and _is_gguf_filename(f.name) and not is_appledouble_metadata(f):yield f@@ -1834,6 +1835,7 @@ from utils.models.drafters import ( # noqa: E402from utils.models.drafters import ( # noqa: E402dspark_preference_key as _drafters_dspark_preference_key,)+from utils.paths.path_utils import is_appledouble_metadatadef dspark_preference_key(name: str) -> Tuple[int, str]:@@ -2191,10 +2193,14 @@ def detect_gguf_model(path: str, model_root: Optional[str] = None) -> Optional[s# copies are caught -- the basename alone (...-MTP.gguf) misses the mtp- prefix.rel = f"{p.parent.name}/{p.name}"quant = _extract_quant_label(rel)+if (_is_mmproj(p.name)or _is_local_mtp_drafter(p, root, rel)or _is_big_endian_gguf_path(rel, quant)+ # Pointed at directly, a sidecar bypasses the scan that would have skipped it.+ # Identified positively so an unreadable file still reaches the lock window below.+ or is_appledouble_metadata(p)):return None# Extension is authoritative: is_file()/exists() can fail in the Windows lock window.@@ -2296,6 +2302,10 @@ _GGUF_QUANT_PREFERENCE = [def _pick_best_gguf(filenames: list[str]) -> Optional[str]:"""Pick the best GGUF file: quant levels in _GGUF_QUANT_PREFERENCE order, else first .gguf."""+ from hub.utils.gguf import drop_shadowed_appledouble_names++ # See hub.utils.gguf.pick_best_gguf: the first matching name wins.+ filenames = drop_shadowed_appledouble_names(list(filenames))gguf_files = [f for f in filenames if f.lower().endswith(".gguf")]if not gguf_files:return None@@ -2698,7 +2708,10 @@ def list_gguf_variants(# (name, quant, size); grouped per shard FAMILY below, not summed across copies.main_files: list[tuple[str, str, int]] = []- for sibling in info.siblings:+ from hub.utils.gguf import drop_shadowed_appledouble_siblings++ # Sidecars in the listing would otherwise be advertised as the variant, at their own size.+ for sibling in drop_shadowed_appledouble_siblings(list(info.siblings)):fname = sibling.rfilenameif not fname.lower().endswith(".gguf"):continue@@ -3116,9 +3129,12 @@ def is_embedding_model(model_name: str, hf_token: Optional[str] = None) -> bool:def _has_model_weight_files(model_dir: Path) -> bool:"""Return True when a directory contains loadable model weights."""+for item in model_dir.iterdir():if not item.is_file():continue+ if is_appledouble_metadata(item):+ continuesuffix = item.suffix.lower()if suffix == ".safetensors":@@ -3211,6 +3227,7 @@ def scan_exported_models(List of (display_name, model_path, export_type, base_model), whereexport_type is "lora" | "merged" | "gguf"."""+results = []exports_path = resolve_export_dir(exports_dir)@@ -3247,8 +3264,9 @@ def scan_exported_models(adapter_config = checkpoint_dir / "adapter_config.json"config_file = checkpoint_dir / "config.json"- has_weights = any(checkpoint_dir.glob("*.safetensors")) or any(- checkpoint_dir.glob("*.bin")+ has_weights = any(+ not is_appledouble_metadata(f)+ for f in (*checkpoint_dir.glob("*.safetensors"), *checkpoint_dir.glob("*.bin")))has_gguf = any(_iter_gguf_files(checkpoint_dir))diff --git a/studio/backend/utils/paths/__init__.py b/studio/backend/utils/paths/__init__.pyindex 5ed7ae102c0..0876ccf0d7a 100644--- a/studio/backend/utils/paths/__init__.py+++ b/studio/backend/utils/paths/__init__.py@@ -16,6 +16,7 @@ from .path_utils import (from .storage_roots import (studio_root,assets_root,+ dataset_files_in_dir,datasets_root,dataset_uploads_root,recipe_datasets_root,@@ -65,6 +66,7 @@ __all__ = ["reveal_in_file_manager","studio_root","assets_root",+ "dataset_files_in_dir","datasets_root","dataset_uploads_root","recipe_datasets_root",diff --git a/studio/backend/utils/paths/path_utils.py b/studio/backend/utils/paths/path_utils.pyindex 12c177b5982..7c31127c835 100644--- a/studio/backend/utils/paths/path_utils.py+++ b/studio/backend/utils/paths/path_utils.py@@ -8,12 +8,79 @@ Path utilities for model and dataset handlingimport osimport sysfrom pathlib import Path-from typing import Optional+from typing import Callable, Iterable, Optional, TypeVarimport structlogfrom loggers import get_loggerlogger = get_logger(__name__)++# ── macOS Finder metadata companions ───────────────────────────+# A volume without native xattrs (exFAT, FAT, most SMB and NFS) makes macOS keep a file's xattrs+# in a "._" companion carrying the same extension, so it answers every name-shaped question the+# way the real file does and sorts ahead of it. Nothing may be refused for the prefix alone: a+# user's own "._model.gguf" is a real model, and only the magic bytes settle it.++_MAGIC = b"\x00\x05\x16\x07"++PathLike = TypeVar("PathLike", str, Path)+++def is_appledouble_name(path: str) -> bool:+ """A name test only: it decides which files are worth opening, never what one is."""+ return str(path).replace("\\", "/").rsplit("/", 1)[-1].startswith("._")+++def has_appledouble_magic(path: Path) -> bool:+ """The four bytes ``file(1)`` reads to report "AppleDouble encoded Macintosh file"."""+ try:+ # Directory scans reach here with whatever the volume holds, and opening a FIFO blocks+ # until someone writes to it. Only a regular file can carry the magic anyway.+ if not path.is_file():+ return False+ with open(path, "rb") as handle:+ return handle.read(len(_MAGIC)) == _MAGIC+ except OSError:+ return False+++def is_appledouble_metadata(path: Path) -> bool:+ """True only for a ``._`` file whose bytes ARE AppleDouble."""+ path = Path(path)+ return is_appledouble_name(path.name) and has_appledouble_magic(path)+++def drop_appledouble_metadata(paths: Iterable[PathLike]) -> list[PathLike]:+ """*paths* without the entries that are Finder metadata, preserving order and type."""+ return [p for p in paths if not is_appledouble_metadata(Path(p))]+++def any_not_appledouble_metadata(paths: Iterable[PathLike]) -> bool:+ """Whether *paths* holds anything that is not Finder metadata, stopping at the first.++ Callers hand this a live ``glob``, which materializing would walk in full.+ """+ return any(not is_appledouble_metadata(Path(p)) for p in paths)+++def _shadowed_name(path: str) -> str:+ head, _, name = str(path).replace("\\", "/").rpartition("/")+ return f"{head}/{name[2:]}" if head else name[2:]+++def drop_shadowed_appledouble_names(+ files: list[str], *, subject_key: Callable[[str], object] | None = None+) -> list[str]:+ """*files* without the ``._`` entries whose subject is present in the same listing.++ For remote listings, which carry no bytes to read, so a sole candidate survives whatever it+ is called. *subject_key* widens what counts as the subject, for files that come in sets.+ """+ key = subject_key or (lambda name: name)+ present = {key(f.replace("\\", "/")) for f in files}+ return [f for f in files if not (is_appledouble_name(f) and key(_shadowed_name(f)) in present)]++# Per-process cache to avoid repeated cache-dir scans for the same identifier._CACHE_CASE_RESOLUTION_MEMO: dict[str, str] = {}@@ -114,7 +181,7 @@ def is_model_cached(model_name: str) -> bool:# Check for model filesfor suffix in [".safetensors", ".bin", ".json"]:- if list(cache_path.rglob(f"*{suffix}")):+ if any_not_appledouble_metadata(cache_path.rglob(f"*{suffix}")):return Truereturn Falsediff --git a/studio/backend/utils/paths/storage_roots.py b/studio/backend/utils/paths/storage_roots.pyindex d317f217a69..6b551fa6210 100644--- a/studio/backend/utils/paths/storage_roots.py+++ b/studio/backend/utils/paths/storage_roots.py@@ -11,6 +11,8 @@ import sysfrom pathlib import Path, PurePosixPath, PureWindowsPathimport tempfile+from utils.paths.path_utils import drop_appledouble_metadata+def _infer_studio_home_from_venv() -> Path | None:"""Return parent of sys.prefix as STUDIO_HOME when running from an@@ -532,6 +534,23 @@ def resolve_tensorboard_dir(path_value: str | None = None) -> Path:)+def dataset_files_in_dir(directory: Path) -> list[Path]:+ """Loadable dataset files for *directory*, preferring a ``parquet-files/`` export over the+ directory's own files. Raises ``ValueError`` when it holds no supported format."""+ parquet_dir = directory / "parquet-files"+ if not parquet_dir.exists():+ parquet_dir = directory+ parquet = drop_appledouble_metadata(sorted(parquet_dir.glob("*.parquet")))+ if parquet:+ return parquet+ files: list[Path] = []+ for ext in (".json", ".jsonl", ".csv", ".parquet"):+ files.extend(drop_appledouble_metadata(sorted(directory.glob(f"*{ext}"))))+ if not files:+ raise ValueError(f"No supported data files in directory: {directory}")+ return files++def resolve_dataset_path(path_value: str) -> Path:raw = str(path_value or "").strip()if "\x00" in raw:diff --git a/studio/backend/utils/security/remote_code_scan.py b/studio/backend/utils/security/remote_code_scan.pyindex b624919b419..9a071a502cd 100644--- a/studio/backend/utils/security/remote_code_scan.py+++ b/studio/backend/utils/security/remote_code_scan.py@@ -34,6 +34,7 @@ from typing import Optionalfrom loggers import get_loggerfrom utils.hf_cache_settings import active_hf_hub_cache+from utils.paths.path_utils import is_appledouble_metadatalogger = get_logger(__name__)@@ -495,6 +496,8 @@ def repo_remote_code_files(if not name.endswith(".py"):continuep = directory_path / name+ if is_appledouble_metadata(p):+ continueif not p.is_file():raise RemoteCodeUnscannable(f"{model_name}: Python source {p.relative_to(root)} is unreadable"diff --git a/studio/backend/utils/utils.py b/studio/backend/utils/utils.pyindex 4518d6a1977..560a2e08076 100644--- a/studio/backend/utils/utils.py+++ b/studio/backend/utils/utils.py@@ -13,6 +13,7 @@ from pathlib import Pathfrom typing import Optionalimport shutilimport tempfile+from utils.paths.path_utils import is_appledouble_metadatalogger = get_logger(__name__)@@ -579,8 +580,11 @@ def hf_cache_snapshot_is_loadable(model_name: str) -> bool:has_config = (snapshot / "config.json").is_file() or (snapshot / "modules.json").is_file()if not has_config:return False+for path in snapshot.rglob("*"):- if path.suffix.lower() in _LOADABLE_WEIGHT_SUFFIXES and path.is_file():+ if path.suffix.lower() not in _LOADABLE_WEIGHT_SUFFIXES or not path.is_file():+ continue+ if not is_appledouble_metadata(path):return Trueexcept OSError:return False