Skip to content

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

fix(studio): harden training setup, lifecycle, and audio loading (#8103)

Eyera0b147fdd2a9e
diff --git a/studio/backend/core/export/worker.py b/studio/backend/core/export/worker.py
index 9ecfa73eee7..e18b7fee849 100644
--- a/studio/backend/core/export/worker.py
+++ b/studio/backend/core/export/worker.py
@@ -272,22 +272,36 @@ def _handle_load(backend, cmd: dict, resp_queue: Any) -> None:
# trust_remote_code False, so check HF's security scan (metadata-only) every
# load. Local checkpoints have no Hub scan and are skipped in the helper; a
# LoRA merges its base weights, so gate that repo too.
- from utils.security import evaluate_file_security, security_load_subdirs
+ from utils.security import evaluate_file_security, load_scan_target, security_load_subdirs
- malware_targets = [checkpoint_path]
+ requested_security_targets = [checkpoint_path]
try:
from utils.models.model_config import get_base_model_from_lora_identifier
# Resolve a LOCAL or REMOTE adapter's base so a remote LoRA base is gated too.
_base = get_base_model_from_lora_identifier(checkpoint_path, cmd.get("hf_token"))
if _base:
- malware_targets.append(_base)
+ requested_security_targets.append(_base)
except Exception as exc:
logger.debug("Could not resolve LoRA base for malware scan: %s", exc)
_hf_token = cmd.get("hf_token")
- for target in dict.fromkeys(malware_targets):
+ security_targets: list[str] = []
+ consent_load_subdirs: dict[str, tuple] = {}
+ for requested_target in dict.fromkeys(requested_security_targets):
+ load_subdirs = security_load_subdirs(requested_target, _hf_token)
+ target, load_subdirs = load_scan_target(requested_target, load_subdirs)
+ if target not in consent_load_subdirs:
+ security_targets.append(target)
+ consent_load_subdirs[target] = ()
+ consent_load_subdirs[target] = tuple(
+ dict.fromkeys((*consent_load_subdirs[target], *load_subdirs))
+ )
+
+ for target in security_targets:
_fs = evaluate_file_security(
- target, hf_token = _hf_token, load_subdirs = security_load_subdirs(target, _hf_token)
+ target,
+ hf_token = _hf_token,
+ load_subdirs = consent_load_subdirs[target],
)
if _fs.blocked:
_send_response(
@@ -308,23 +322,14 @@ def _handle_load(backend, cmd: dict, resp_queue: Any) -> None:
if trust_remote_code:
from utils.security import evaluate_remote_code_consent_for_targets
- consent_targets = [checkpoint_path]
- try:
- from utils.models.model_config import get_base_model_from_lora_identifier
-
- # Resolve a local or remote adapter's base so its base repo is gated too.
- base_model = get_base_model_from_lora_identifier(checkpoint_path, cmd.get("hf_token"))
- if base_model:
- consent_targets.append(base_model)
- except Exception as exc:
- logger.debug("Could not resolve LoRA base for consent scan: %s", exc)
# Scan adapter + base as one combined unit, pinned by a single fingerprint.
_rc = evaluate_remote_code_consent_for_targets(
- consent_targets,
- hf_token = cmd.get("hf_token"),
+ security_targets,
+ hf_token = _hf_token,
trust_remote_code = True,
approved_fingerprint = cmd.get("approved_remote_code_fingerprint"),
subject = cmd.get("subject"),
+ load_subdirs_by_target = consent_load_subdirs,
)
if _rc.blocked:
_send_response(
diff --git a/studio/backend/core/inference/audio_codecs.py b/studio/backend/core/inference/audio_codecs.py
index b59f2bcce03..dacba8cf262 100644
--- a/studio/backend/core/inference/audio_codecs.py
+++ b/studio/backend/core/inference/audio_codecs.py
@@ -8,7 +8,6 @@ Supports: SNAC (Orpheus), CSM (Sesame), BiCodec (Spark), DAC (OuteTTS)
import io
import re
-import subprocess
import wave
import structlog
from loggers import get_logger
@@ -17,9 +16,13 @@ from typing import Optional, Tuple
import numpy as np
import torch
-from utils.native_path_leases import child_env_without_native_path_secret
-from utils.subprocess_compat import (
- windows_hidden_subprocess_kwargs as _windows_hidden_subprocess_kwargs,
+from utils.third_party_source import (
+ deactivate_pinned_package,
+ ensure_dac_speech_weights,
+ ensure_outetts_source,
+ ensure_spark_tts_source,
+ import_outetts_module,
+ import_sparktts_module,
)
logger = get_logger(__name__)
@@ -50,7 +53,9 @@ class AudioCodecManager:
self._snac_model = None
self._bicodec_tokenizer = None
self._bicodec_repo_path = None
+ self._bicodec_code_dir = None
self._dac_audio_codec = None
+ self._outetts_code_dir = None
def load_codec(
self,
@@ -93,33 +98,12 @@ class AudioCodecManager:
) -> None:
if self._bicodec_tokenizer is not None:
return
- import os
- import sys
-
- # Clone SparkAudio/Spark-TTS for the sparktts package (HF model repos
- # don't contain it)
- spark_code_dir = os.path.join(os.path.dirname(model_repo_path or "."), "Spark-TTS")
- sparktts_pkg = os.path.join(spark_code_dir, "sparktts")
- if not os.path.isdir(sparktts_pkg):
- logger.info(f"Cloning SparkAudio/Spark-TTS to {spark_code_dir}...")
- subprocess.run(
- [
- "git",
- "clone",
- "--depth",
- "1",
- "https://github.com/SparkAudio/Spark-TTS",
- spark_code_dir,
- ],
- check = True,
- env = child_env_without_native_path_secret(),
- **_windows_hidden_subprocess_kwargs(),
- )
-
- if spark_code_dir not in sys.path:
- sys.path.insert(0, spark_code_dir)
-
- from sparktts.models.audio_tokenizer import BiCodecTokenizer
+ spark_code_dir = ensure_spark_tts_source(model_repo_path)
+ self._bicodec_code_dir = spark_code_dir
+ BiCodecTokenizer = import_sparktts_module(
+ "sparktts.models.audio_tokenizer",
+ spark_code_dir,
+ ).BiCodecTokenizer
# BiCodecTokenizer needs the MODEL repo path (has BiCodec/ weights)
tokenizer_path = model_repo_path or spark_code_dir
@@ -130,50 +114,22 @@ class AudioCodecManager:
def _load_dac(self, device: str) -> None:
if self._dac_audio_codec is not None:
return
- import os
- import sys
-
- # Clone OuteTTS (the pip package has problematic deps; we remove
- # gguf_model.py, interface.py, __init__.py before importing).
- base_dir = os.path.dirname(os.path.abspath(__file__))
- outetts_code_dir = os.path.join(base_dir, "OuteTTS")
- outetts_pkg = os.path.join(outetts_code_dir, "outetts")
- if not os.path.isdir(outetts_pkg):
- logger.info(f"Cloning edwko/OuteTTS to {outetts_code_dir}...")
- subprocess.run(
- [
- "git",
- "clone",
- "--depth",
- "1",
- "https://github.com/edwko/OuteTTS",
- outetts_code_dir,
- ],
- check = True,
- env = child_env_without_native_path_secret(),
- **_windows_hidden_subprocess_kwargs(),
- )
- # Remove files pulling in heavy / incompatible deps
- remove_paths = [
- os.path.join(outetts_pkg, "models", "gguf_model.py"),
- os.path.join(outetts_pkg, "interface.py"),
- os.path.join(outetts_pkg, "__init__.py"),
- ]
- for fpath in remove_paths:
- if os.path.exists(fpath):
- os.remove(fpath)
- logger.info(f"Removed {fpath}")
-
- if outetts_code_dir not in sys.path:
- sys.path.insert(0, outetts_code_dir)
-
- from outetts.version.v3.audio_processor import AudioProcessor
- from outetts.models.config import ModelConfig as OuteTTSModelConfig
+ outetts_code_dir = ensure_outetts_source()
+ self._outetts_code_dir = outetts_code_dir
+ AudioProcessor = import_outetts_module(
+ "outetts.version.v3.audio_processor",
+ outetts_code_dir,
+ ).AudioProcessor
+ OuteTTSModelConfig = import_outetts_module(
+ "outetts.models.config",
+ outetts_code_dir,
+ ).ModelConfig
+ audio_codec_path = ensure_dac_speech_weights()
dummy_config = OuteTTSModelConfig(
- tokenizer_path = "OuteAI/Llama-OuteTTS-1.0-1B",
+ tokenizer_path = None,
device = device,
- audio_codec_path = None,
+ audio_codec_path = str(audio_codec_path),
)
processor = AudioProcessor(config = dummy_config)
self._dac_audio_codec = processor.audio_codec
@@ -332,7 +288,13 @@ class AudioCodecManager:
del self._bicodec_tokenizer
self._bicodec_tokenizer = None
self._bicodec_repo_path = None
+ if self._bicodec_code_dir is not None:
+ deactivate_pinned_package("sparktts", self._bicodec_code_dir)
+ self._bicodec_code_dir = None
if self._dac_audio_codec is not None:
del self._dac_audio_codec
self._dac_audio_codec = None
+ if self._outetts_code_dir is not None:
+ deactivate_pinned_package("outetts", self._outetts_code_dir)
+ self._outetts_code_dir = None
logger.info("Unloaded all audio codecs")
diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.py
index a045c8e228a..375d26d68fc 100644
--- a/studio/backend/core/inference/worker.py
+++ b/studio/backend/core/inference/worker.py
@@ -270,11 +270,24 @@ def _run_security_gates(
# False, so check HF's security scan every load (for a LoRA, the base deserializes).
from utils.security import evaluate_file_security
+ from utils.security import load_scan_target
+
if compute_subdirs:
from utils.security import security_load_subdirs
- for target in targets:
- _subdirs = security_load_subdirs(target, hf_token) if compute_subdirs else ()
+ scoped_targets: list[str] = []
+ consent_load_subdirs: dict[str, tuple] = {}
+ for requested_target in targets:
+ _subdirs = security_load_subdirs(requested_target, hf_token) if compute_subdirs else ()
+ target, _subdirs = load_scan_target(requested_target, _subdirs)
+ if target not in consent_load_subdirs:
+ scoped_targets.append(target)
+ consent_load_subdirs[target] = ()
+ _subdirs = tuple(dict.fromkeys((*consent_load_subdirs[target], *_subdirs)))
+ consent_load_subdirs[target] = _subdirs
+
+ for target in scoped_targets:
+ _subdirs = consent_load_subdirs[target]
_fs = evaluate_file_security(target, hf_token = hf_token, load_subdirs = _subdirs)
if _fs.blocked:
_send_response(
@@ -294,11 +307,12 @@ def _run_security_gates(
if trust_remote_code:
from utils.security import evaluate_remote_code_consent_for_targets
_rc = evaluate_remote_code_consent_for_targets(
- targets,
+ scoped_targets,
hf_token = hf_token,
trust_remote_code = True,
approved_fingerprint = approved_fingerprint,
subject = subject,
+ load_subdirs_by_target = consent_load_subdirs,
)
if _rc.blocked:
_send_response(
diff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.py
index 978b0e407da..9411db146e0 100644
--- a/studio/backend/core/training/trainer.py
+++ b/studio/backend/core/training/trainer.py
@@ -53,7 +53,6 @@ from unsloth.chat_templates import get_chat_template
import json
import threading
import math
-import subprocess
import structlog
from loggers import get_logger
import time
@@ -62,6 +61,14 @@ from typing import Any, Dict, List, Optional, Callable
import pandas as pd
from datasets import Dataset
from utils.datasets.cache_safe import load_dataset_cache_safe as load_dataset
+from utils.hf_dataset_options import hf_dataset_split_instruction_names
+from utils.third_party_source import (
+ ensure_dac_speech_weights,
+ ensure_outetts_source,
+ ensure_spark_tts_source,
+ import_outetts_module,
+ import_sparktts_module,
+)
from utils.models import is_vision_model, detect_audio_type
from utils.models.model_identity import restore_hf_cache_repo_identity
@@ -78,10 +85,6 @@ from utils.paths import (
)
from trl import SFTTrainer, SFTConfig
-from utils.native_path_leases import child_env_without_native_path_secret
-from utils.subprocess_compat import (
- windows_hidden_subprocess_kwargs as _windows_hidden_subprocess_kwargs,
-)
from .training import (
TrainingProgress,
create_mlx_trainer_adapter,
@@ -133,6 +136,8 @@ class UnslothTrainer:
self._audio_type = None # 'csm', 'whisper', 'snac', 'bicodec', 'dac'
self._cuda_audio_used = False # Set once after audio CUDA preprocessing; never cleared
self._spark_tts_repo_dir = None # Spark-TTS repo path, for BiCodecTokenizer
+ self._spark_tts_code_dir = None
+ self._outetts_code_dir = None
self.model_name = None
self.model_load_error = None
self.dataset_loaded_from_exact_snapshot = False
@@ -439,20 +444,16 @@ class UnslothTrainer:
def _cleanup_audio_artifacts(self):
"""Remove sys.path/sys.modules entries from previous audio preprocessing.
- After audio training, cloned repo dirs (OuteTTS, Spark-TTS) and heavy
+ After audio training, codec source dirs and heavy
modules (snac, whisper, sparktts, outetts) linger; the next
dataset.map(num_proc=N) forks children that inherit this stale state and
deadlock.
"""
- # Remove cloned audio repo paths from sys.path
- base_dir = os.path.dirname(os.path.abspath(__file__))
- audio_paths = [
- os.path.join(base_dir, "inference", "OuteTTS"), # DAC/OuteTTS
- ]
- # Spark-TTS path is relative to the downloaded repo
- if self._spark_tts_repo_dir:
- spark_code_dir = os.path.join(os.path.dirname(self._spark_tts_repo_dir), "Spark-TTS")
- audio_paths.append(spark_code_dir)
+ audio_paths = []
+ if self._spark_tts_code_dir:
+ audio_paths.append(str(self._spark_tts_code_dir))
+ if self._outetts_code_dir:
+ audio_paths.append(str(self._outetts_code_dir))
removed_paths = []
for path in audio_paths:
@@ -465,6 +466,8 @@ class UnslothTrainer:
removed_modules = [key for key in sys.modules if key.startswith(prefixes)]
for key in removed_modules:
del sys.modules[key]
+ self._spark_tts_code_dir = None
+ self._outetts_code_dir = None
if removed_paths or removed_modules:
logger.info(
@@ -1738,31 +1741,17 @@ class UnslothTrainer:
# Spark-TTS BiCodec unvalidated on Intel XPU; keep the pre-PR CPU fallback.
device = "cuda" if torch.cuda.is_available() else "cpu"
- # sparktts lives in the SparkAudio/Spark-TTS GitHub repo, not the HF model repo.
- spark_code_dir = os.path.join(os.path.dirname(self._spark_tts_repo_dir), "Spark-TTS")
- sparktts_pkg = os.path.join(spark_code_dir, "sparktts")
- if not os.path.isdir(sparktts_pkg):
- self._update_progress(status_message = "Cloning Spark-TTS code repo...")
- logger.info(f"Cloning SparkAudio/Spark-TTS to {spark_code_dir}...\n")
- subprocess.run(
- [
- "git",
- "clone",
- "--depth",
- "1",
- "https://github.com/SparkAudio/Spark-TTS",
- spark_code_dir,
- ],
- check = True,
- env = child_env_without_native_path_secret(),
- **_windows_hidden_subprocess_kwargs(),
- )
-
- if spark_code_dir not in sys.path:
- sys.path.insert(0, spark_code_dir)
-
- from sparktts.models.audio_tokenizer import BiCodecTokenizer
- from sparktts.utils.audio import audio_volume_normalize
+ self._update_progress(status_message = "Preparing Spark-TTS codec source...")
+ spark_code_dir = ensure_spark_tts_source(self._spark_tts_repo_dir)
+ self._spark_tts_code_dir = spark_code_dir
+ BiCodecTokenizer = import_sparktts_module(
+ "sparktts.models.audio_tokenizer",
+ spark_code_dir,
+ ).BiCodecTokenizer
+ audio_volume_normalize = import_sparktts_module(
+ "sparktts.utils.audio",
+ spark_code_dir,
+ ).audio_volume_normalize
resolved = self._resolve_audio_columns(dataset, custom_format_mapping)
audio_col = resolved["audio_col"]
@@ -1952,42 +1941,25 @@ class UnslothTrainer:
# OuteTTS DAC/Whisper preprocess unvalidated on Intel XPU; CPU fallback kept.
device = "cuda" if torch.cuda.is_available() else "cpu"
- # Clone OuteTTS repo (same as audio_codecs._load_dac)
- base_dir = os.path.dirname(os.path.abspath(__file__))
- outetts_code_dir = os.path.join(base_dir, "inference", "OuteTTS")
- outetts_pkg = os.path.join(outetts_code_dir, "outetts")
- if not os.path.isdir(outetts_pkg):
- self._update_progress(status_message = "Cloning OuteTTS code repo...")
- logger.info(f"Cloning edwko/OuteTTS to {outetts_code_dir}...\n")
- subprocess.run(
- [
- "git",
- "clone",
- "--depth",
- "1",
- "https://github.com/edwko/OuteTTS",
- outetts_code_dir,
- ],
- check = True,
- env = child_env_without_native_path_secret(),
- **_windows_hidden_subprocess_kwargs(),
- )
- for fpath in [
- os.path.join(outetts_pkg, "models", "gguf_model.py"),
- os.path.join(outetts_pkg, "interface.py"),
- os.path.join(outetts_pkg, "__init__.py"),
- ]:
- if os.path.exists(fpath):
- os.remove(fpath)
- logger.info(f"Removed {fpath}\n")
-
- if outetts_code_dir not in sys.path:
- sys.path.insert(0, outetts_code_dir)
-
- from outetts.version.v3.audio_processor import AudioProcessor
- from outetts.version.v3.prompt_processor import PromptProcessor
- from outetts.models.config import ModelConfig as OuteTTSModelConfig
- from outetts.utils.preprocessing import text_normalizations
+ self._update_progress(status_message = "Preparing OuteTTS codec source...")
+ outetts_code_dir = ensure_outetts_source()
+ self._outetts_code_dir = outetts_code_dir
+ AudioProcessor = import_outetts_module(
+ "outetts.version.v3.audio_processor",
+ outetts_code_dir,
+ ).AudioProcessor
+ PromptProcessor = import_outetts_module(
+ "outetts.version.v3.prompt_processor",
+ outetts_code_dir,
+ ).PromptProcessor
+ OuteTTSModelConfig = import_outetts_module(
+ "outetts.models.config",
+ outetts_code_dir,
+ ).ModelConfig
+ text_normalizations = import_outetts_module(
+ "outetts.utils.preprocessing",
+ outetts_code_dir,
+ ).text_normalizations
resolved = self._resolve_audio_columns(dataset, custom_format_mapping)
audio_col = resolved["audio_col"]
@@ -2011,14 +1983,18 @@ class UnslothTrainer:
self._update_progress(status_message = "Loading OuteTTS AudioProcessor...")
logger.info("Loading OuteTTS AudioProcessor...\n")
- model_tokenizer_path = "OuteAI/Llama-OuteTTS-1.0-1B"
+ audio_codec_path = ensure_dac_speech_weights()
dummy_config = OuteTTSModelConfig(
- tokenizer_path = model_tokenizer_path,
+ tokenizer_path = None,
device = device,
- audio_codec_path = None,
+ audio_codec_path = str(audio_codec_path),
)
audio_processor = AudioProcessor(config = dummy_config)
- prompt_processor = PromptProcessor(model_tokenizer_path)
+ if self.tokenizer is None:
+ raise RuntimeError("OuteTTS tokenizer is not loaded")
+ prompt_processor = PromptProcessor(None)
+ prompt_processor.tokenizer = self.tokenizer
+ prompt_processor.get_audio_token_map()
self._update_progress(status_message = "Preprocessing audio with OuteTTS...")
logger.info(f"DAC preprocessing: audio_col='{audio_col}', text_col='{text_col}'\n")
@@ -2666,7 +2642,9 @@ class UnslothTrainer:
subset = subset,
available_splits = available_splits,
split_loader = split_loader,
- excluded_split = (train_split or "train").partition("[")[0].strip(),
+ excluded_split = hf_dataset_split_instruction_names(
+ train_split or "train"
+ ),
revision = dataset_revision,
strict_split_loading = (
require_exact_resume_resources and dataset_loaded_from_cache
@@ -2875,7 +2853,7 @@ class UnslothTrainer:
*,
available_splits: Optional[list[str]] = None,
split_loader: Optional[Callable[[str], Dataset]] = None,
- excluded_split: Optional[str] = None,
+ excluded_split: Any = None,
revision: Optional[str] = None,
strict_split_loading: bool = False,
) -> Optional[Dataset]:
@@ -2896,8 +2874,11 @@ class UnslothTrainer:
from core.training.eval_dataset import EVAL_SPLIT_CANDIDATES, MIN_EVAL_ROWS
+ excluded_splits = (
+ {excluded_split} if isinstance(excluded_split, str) else set(excluded_split or ())
+ )
for candidate in EVAL_SPLIT_CANDIDATES:
- if candidate in available_splits and candidate != excluded_split:
+ if candidate in available_splits and candidate not in excluded_splits:
if split_loader is not None:
candidate_ds = split_loader(candidate)
else:
@@ -3674,7 +3655,7 @@ class UnslothTrainer:
train_on_responses_enabled
and not self.is_audio_vlm
and not self.is_audio
- and not (is_deepseek_ocr or dataset_final_format == "alpaca")
+ and not is_deepseek_ocr
):
from unsloth.chat_templates import train_on_responses_only
@@ -3694,6 +3675,7 @@ class UnslothTrainer:
train_on_responses_only,
num_proc = config_args["dataset_num_proc"],
notify = _notify,
+ dataset_template = ("alpaca" if dataset_final_format == "alpaca" else None),
)
if not masking_applied:
diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.py
index b8eeb811394..59cb8986ad2 100644
--- a/studio/backend/core/training/training.py
+++ b/studio/backend/core/training/training.py
@@ -63,6 +63,8 @@ _COMPLETE_EXIT_GRACE_S = _env_int("UNSLOTH_STUDIO_TRAINING_COMPLETE_EXIT_GRACE_S
_DB_FINALIZE_RETRIES = 3
_DB_FINALIZE_RETRY_S = 0.5
_MAX_TRACKED_START_REQUESTS = 64
+_MAX_START_CANCEL_TOMBSTONES = 1024
+_START_CANCEL_TOMBSTONE_TTL_S = 300.0
_START_CANCELLED_ERROR_CODE = "training_start_cancelled"
_pyplot = None
@@ -79,6 +81,10 @@ class TrainingStartRequestRecord:
error_code: Optional[str] = None
+class TrainingStartCancellationCapacityError(RuntimeError):
+ pass
+
+
@dataclass(frozen = True)
class TrainingStatusIdentitySnapshot:
current_job_id: str
@@ -1112,6 +1118,8 @@ class TrainingBackend:
self.current_job_id: Optional[str] = None
self.current_start_request_id: Optional[str] = None
self._start_requests: dict[str, TrainingStartRequestRecord] = {}
+ self._start_cancel_tombstones: dict[str, tuple[float, TrainingStartRequestRecord]] = {}
+ self._start_cancel_tombstone_reservations: dict[str, int] = {}
self._pending_start_request_id: Optional[str] = None
self._status_start_request_id: Optional[str] = None
self._output_dir: Optional[str] = None
@@ -1140,9 +1148,18 @@ class TrainingBackend:
self, start_request_id: str, job_id: str
) -> tuple[str, TrainingStartRequestRecord]:
with self._lock:
+ self._prune_start_cancel_tombstones_locked()
existing = self._start_requests.get(start_request_id)
if existing is not None:
return "existing", existing
+ cancelled = self._start_cancel_tombstones.get(start_request_id)
+ if cancelled is not None:
+ record = cancelled[1]
+ self._start_cancel_tombstones[start_request_id] = (
+ time.monotonic() + _START_CANCEL_TOMBSTONE_TTL_S,
+ record,
+ )
+ return "existing", record
if self._pending_start_request_id is not None:
record = TrainingStartRequestRecord(
start_request_id = start_request_id,
@@ -1204,9 +1221,20 @@ class TrainingBackend:
) -> tuple[Literal["cancelled", "superseded"], TrainingStartRequestRecord]:
from .lifecycle import training_lifecycle_guard
+ reserved_cancel_tombstone = False
with self._lock:
+ self._prune_start_cancel_tombstones_locked()
existing = self._start_requests.get(start_request_id)
if existing is None:
+ cancelled_tombstone = self._start_cancel_tombstones.get(start_request_id)
+ if cancelled_tombstone is not None:
+ record = cancelled_tombstone[1]
+ self._start_cancel_tombstones[start_request_id] = (
+ time.monotonic() + _START_CANCEL_TOMBSTONE_TTL_S,
+ record,
+ )
+ return "cancelled", record
+ self._reserve_start_cancel_tombstone_locked(start_request_id)
cancelled = TrainingStartRequestRecord(
start_request_id = start_request_id,
job_id = "",
@@ -1215,8 +1243,7 @@ class TrainingBackend:
error = "Training start was cancelled",
error_code = _START_CANCELLED_ERROR_CODE,
)
- self._start_requests[start_request_id] = cancelled
- self._prune_start_requests_locked()
+ self._commit_start_cancel_tombstone_locked(start_request_id, cancelled)
return "cancelled", cancelled
owns_current = (
@@ -1226,11 +1253,21 @@ class TrainingBackend:
if existing.state == "rejected" and (
not owns_current or existing.error_code == _START_CANCELLED_ERROR_CODE
):
+ if existing.error_code == _START_CANCELLED_ERROR_CODE:
+ self._reserve_start_cancel_tombstone_locked(
+ start_request_id,
+ reclaim_capacity = True,
+ )
+ self._start_requests.pop(start_request_id, None)
+ self._commit_start_cancel_tombstone_locked(start_request_id, existing)
if self._status_start_request_id == start_request_id:
self._status_start_request_id = None
return "cancelled", existing
if existing.state == "pending" and not owns_current:
+ # Not the active run, so it does not get the owner's over-cap slot: start
+ # plus cancel could otherwise be repeated to grow the table without bound.
+ self._reserve_start_cancel_tombstone_locked(start_request_id)
cancelled = replace(
existing,
state = "rejected",
@@ -1238,57 +1275,96 @@ class TrainingBackend:
error = "Training start was cancelled",
error_code = _START_CANCELLED_ERROR_CODE,
)
- self._start_requests[start_request_id] = cancelled
+ self._start_requests.pop(start_request_id, None)
+ self._commit_start_cancel_tombstone_locked(start_request_id, cancelled)
if self._pending_start_request_id == start_request_id:
self._pending_start_request_id = None
if self._status_start_request_id == start_request_id:
self._status_start_request_id = None
return "cancelled", cancelled
- with training_lifecycle_guard():
- with self._lock:
- existing = self._start_requests.get(start_request_id) or existing
- owns_current = (
- self.current_start_request_id == start_request_id
- and self.current_job_id == existing.job_id
- )
- if existing.error_code == _START_CANCELLED_ERROR_CODE:
- if self._status_start_request_id == start_request_id:
- self._status_start_request_id = None
- return "cancelled", existing
- if not owns_current or self._run_finished_locked():
+ reserved_cancel_tombstone = self._reserve_start_cancel_tombstone_locked(
+ start_request_id,
+ reclaim_capacity = owns_current,
+ )
+
+ try:
+ with training_lifecycle_guard():
+ with self._lock:
+ cancelled_tombstone = self._start_cancel_tombstones.get(start_request_id)
+ if cancelled_tombstone is not None:
+ record = cancelled_tombstone[1]
+ self._start_cancel_tombstones[start_request_id] = (
+ time.monotonic() + _START_CANCEL_TOMBSTONE_TTL_S,
+ record,
+ )
+ return "cancelled", record
+ latest = self._start_requests.get(start_request_id)
+ if latest is None:
+ return "superseded", existing
+ existing = latest
+ owns_current = (
+ self.current_start_request_id == start_request_id
+ and self.current_job_id == existing.job_id
+ )
+ if not reserved_cancel_tombstone:
+ reserved_cancel_tombstone = self._reserve_start_cancel_tombstone_locked(
+ start_request_id,
+ reclaim_capacity = owns_current,
+ )
+ if existing.error_code == _START_CANCELLED_ERROR_CODE:
+ if self._status_start_request_id == start_request_id:
+ self._status_start_request_id = None
+ return "cancelled", existing
+ if not owns_current or self._run_finished_locked():
+ return "superseded", existing
+ expected_job_id = existing.job_id
+ if not self._stop_training_with_lifecycle_reserved(
+ save = False,
+ expected_job_id = expected_job_id,
+ ):
return "superseded", existing
- expected_job_id = existing.job_id
- if not self._stop_training_with_lifecycle_reserved(
- save = False,
- expected_job_id = expected_job_id,
- ):
- return "superseded", existing
- if self.reset_training_state(expected_job_id = expected_job_id) != "reset":
- return "superseded", existing
+ if self.reset_training_state(expected_job_id = expected_job_id) != "reset":
+ return "superseded", existing
- with self._lock:
- latest = self._start_requests.get(start_request_id) or existing
- if (
- self.current_start_request_id != start_request_id
- or self.current_job_id != expected_job_id
- ):
- return "superseded", latest
- cancelled = replace(
- latest,
- state = "rejected",
- message = "Training start was cancelled",
- error = "Training start was cancelled",
- error_code = _START_CANCELLED_ERROR_CODE,
- )
- self._start_requests[start_request_id] = cancelled
- self.current_start_request_id = None
- if self._pending_start_request_id == start_request_id:
- self._pending_start_request_id = None
- if self._status_start_request_id == start_request_id:
- self._status_start_request_id = None
- return "cancelled", cancelled
+ with self._lock:
+ cancelled_tombstone = self._start_cancel_tombstones.get(start_request_id)
+ if cancelled_tombstone is not None:
+ record = cancelled_tombstone[1]
+ self._start_cancel_tombstones[start_request_id] = (
+ time.monotonic() + _START_CANCEL_TOMBSTONE_TTL_S,
+ record,
+ )
+ return "cancelled", record
+ latest = self._start_requests.get(start_request_id)
+ if latest is None:
+ return "superseded", existing
+ if (
+ self.current_start_request_id != start_request_id
+ or self.current_job_id != expected_job_id
+ ):
+ return "superseded", latest
+ cancelled = replace(
+ latest,
+ state = "rejected",
+ message = "Training start was cancelled",
+ error = "Training start was cancelled",
+ error_code = _START_CANCELLED_ERROR_CODE,
+ )
+ self._start_requests.pop(start_request_id, None)
+ self._commit_start_cancel_tombstone_locked(start_request_id, cancelled)
+ reserved_cancel_tombstone = False
+ self.current_start_request_id = None
+ if self._pending_start_request_id == start_request_id:
+ self._pending_start_request_id = None
+ if self._status_start_request_id == start_request_id:
+ self._status_start_request_id = None
+ return "cancelled", cancelled
+ finally:
+ if reserved_cancel_tombstone:
+ with self._lock:
+ self._release_start_cancel_tombstone_locked(start_request_id)
def _start_request_allows_spawn_locked(
self, start_request_id: Optional[str], job_id: str
@@ -1300,7 +1376,12 @@ class TrainingBackend:
def get_start_request(self, start_request_id: str) -> Optional[TrainingStartRequestRecord]:
with self._lock:
- return self._start_requests.get(start_request_id)
+ self._prune_start_cancel_tombstones_locked()
+ record = self._start_requests.get(start_request_id)
+ if record is not None:
+ return record
+ cancelled = self._start_cancel_tombstones.get(start_request_id)
+ return cancelled[1] if cancelled is not None else None
def status_start_request(self) -> Optional[TrainingStartRequestRecord]:
with self._lock:
@@ -1347,13 +1428,66 @@ class TrainingBackend:
def acknowledge_start_request(self, start_request_id: str) -> bool:
with self._lock:
+ self._prune_start_cancel_tombstones_locked()
record = self._start_requests.get(start_request_id)
+ if record is None and start_request_id in self._start_cancel_tombstones:
+ return True
if record is None or record.state == "pending":
return False
if self._status_start_request_id == start_request_id:
self._status_start_request_id = None
return True
+ def _prune_start_cancel_tombstones_locked(self) -> None:
+ now = time.monotonic()
+ for request_id, (expires_at, _) in tuple(self._start_cancel_tombstones.items()):
+ if expires_at <= now:
+ del self._start_cancel_tombstones[request_id]
+
+ def _reserve_start_cancel_tombstone_locked(
+ self,
+ start_request_id: str,
+ *,
+ reclaim_capacity: bool = False,
+ ) -> bool:
+ self._prune_start_cancel_tombstones_locked()
+ if start_request_id in self._start_cancel_tombstones:
+ return False
+ reservation_count = self._start_cancel_tombstone_reservations.get(start_request_id, 0)
+ if reservation_count:
+ self._start_cancel_tombstone_reservations[start_request_id] = reservation_count + 1
+ return True
+ if (
+ len(self._start_cancel_tombstones) + len(self._start_cancel_tombstone_reservations)
+ >= _MAX_START_CANCEL_TOMBSTONES
+ ):
+ if not reclaim_capacity:
+ raise TrainingStartCancellationCapacityError(
+ "Too many training start cancellations are pending"
+ )
+ # Everything left is unexpired (pruned above), so evicting one would forget a
+ # live cancellation and let its delayed /start spawn the job we just cancelled.
+ # Overshoot instead: only the owner of the active start reaches this, and there
+ # is at most one of those, so the table stays bounded.
+ self._start_cancel_tombstone_reservations[start_request_id] = 1
+ return True
+
+ def _commit_start_cancel_tombstone_locked(
+ self, start_request_id: str, record: TrainingStartRequestRecord
+ ) -> None:
+ self._start_cancel_tombstone_reservations.pop(start_request_id, None)
+ self._start_cancel_tombstones[start_request_id] = (
+ time.monotonic() + _START_CANCEL_TOMBSTONE_TTL_S,
+ record,
+ )
+
+ def _release_start_cancel_tombstone_locked(self, start_request_id: str) -> None:
+ reservation_count = self._start_cancel_tombstone_reservations.get(start_request_id, 0)
+ if reservation_count <= 1:
+ self._start_cancel_tombstone_reservations.pop(start_request_id, None)
+ else:
+ self._start_cancel_tombstone_reservations[start_request_id] = reservation_count - 1
+
def _prune_start_requests_locked(self) -> None:
overflow = len(self._start_requests) - _MAX_TRACKED_START_REQUESTS
if overflow <= 0:
@@ -1692,7 +1826,8 @@ class TrainingBackend:
def stop_training(
self,
save: bool = True,
- expected_job_id: Optional[str] = None,
+ *,
+ expected_job_id: str,
) -> bool:
"""Send stop signal to the training subprocess."""
from .lifecycle import training_lifecycle_guard
@@ -1702,12 +1837,10 @@ class TrainingBackend:
expected_job_id = expected_job_id,
)
- def _stop_training_with_lifecycle_reserved(
- self, save: bool, expected_job_id: Optional[str]
- ) -> bool:
+ def _stop_training_with_lifecycle_reserved(self, save: bool, expected_job_id: str) -> bool:
with self._run_intent_lock:
with self._lock:
- if expected_job_id is not None and self.current_job_id != expected_job_id:
+ if not expected_job_id or self.current_job_id != expected_job_id:
return False
run_id = self.current_job_id
if not save and run_id:
@@ -1786,6 +1919,13 @@ class TrainingBackend:
expected_job_id is not None and self.current_job_id != expected_job_id
):
return "superseded"
+ # An unscoped reset cannot prove it means THIS run, so it never force-
+ # terminates: _cancel_requested is cleared after current_job_id is set, so a
+ # bodyless reset landing in that window would kill the run that just started.
+ # A stop already asked for means the pre-rework cancel-then-dismiss flow, so
+ # let it clear its UI; otherwise this is a stale reset of a live run (409).
+ if expected_job_id is None and is_active:
+ return "superseded" if self._cancel_requested else "active"
cancel_requested = self._cancel_requested
proc = self._proc
diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.py
index b0057c28316..40453b5c022 100644
--- a/studio/backend/core/training/worker.py
+++ b/studio/backend/core/training/worker.py
@@ -46,6 +46,7 @@ if sys.platform.startswith("linux") and "HSA_ENABLE_DXG_DETECTION" not in os.env
logger = get_logger(__name__)
from utils.child_stdio import utf8_child_env
from utils.hardware import apply_gpu_ids
+from utils.hf_dataset_options import hf_dataset_split_instruction_names
from utils.training_runs import build_default_output_dir_name
from utils.wheel_utils import (
direct_wheel_url,
@@ -525,9 +526,9 @@ def _load_hf_train_and_eval_datasets(
split_kwargs["token"] = token
available_splits = get_dataset_split_names(**split_kwargs)
- excluded_split = train_split.partition("[")[0].strip()
+ excluded_splits = set(hf_dataset_split_instruction_names(train_split))
for candidate in EVAL_SPLIT_CANDIDATES:
- if candidate not in available_splits or candidate == excluded_split:
+ if candidate not in available_splits or candidate in excluded_splits:
continue
try:
if loaded_from_cache:
@@ -701,14 +702,15 @@ def _model_load_security_error(config: dict, load_target: str, hf_token: str | N
from utils.security import (
evaluate_file_security,
evaluate_remote_code_consent_for_targets,
+ load_scan_target,
security_load_subdirs,
)
- targets = [load_target]
+ requested_targets = [load_target]
try:
base_model = get_base_model_from_lora_identifier(load_target, hf_token)
if base_model:
- targets.append(base_model)
+ requested_targets.append(base_model)
except Exception as error:
logger.debug("Could not resolve LoRA base for security scan: %s", error)
@@ -716,12 +718,20 @@ def _model_load_security_error(config: dict, load_target: str, hf_token: str | N
primary_name = config["model_name"]
local_only_load = hf_env_offline()
- for target in dict.fromkeys(targets):
- load_subdirs = security_load_subdirs(target, hf_token)
- if target == load_target and target != primary_name:
+ consent_load_subdirs: dict[str, tuple] = {}
+ targets: list[str] = []
+ for requested_target in dict.fromkeys(requested_targets):
+ load_subdirs = security_load_subdirs(requested_target, hf_token)
+ if requested_target == load_target and requested_target != primary_name:
load_subdirs = tuple(
dict.fromkeys((*load_subdirs, *security_load_subdirs(primary_name, hf_token)))
)
+ target, load_subdirs = load_scan_target(requested_target, load_subdirs)
+ if target not in consent_load_subdirs:
+ targets.append(target)
+ consent_load_subdirs[target] = ()
+ load_subdirs = tuple(dict.fromkeys((*consent_load_subdirs[target], *load_subdirs)))
+ consent_load_subdirs[target] = load_subdirs
decision = evaluate_file_security(
target,
hf_token = hf_token,
@@ -744,6 +754,7 @@ def _model_load_security_error(config: dict, load_target: str, hf_token: str | N
trust_remote_code = True,
approved_fingerprint = config.get("approved_remote_code_fingerprint"),
subject = config.get("subject"),
+ load_subdirs_by_target = consent_load_subdirs,
)
if not decision.blocked:
return None
@@ -760,6 +771,26 @@ def _model_load_security_error(config: dict, load_target: str, hf_token: str | N
_CAUSAL_CONV1D_RELEASE_TAG = "v1.6.1.post4"
_CAUSAL_CONV1D_PACKAGE_VERSION = "1.6.1"
+_CAUSAL_CONV1D_MODEL_SUBSTRINGS = (
+ "qwen3.5",
+ "qwen3_5",
+ "qwen3.6",
+ "qwen3_6",
+ "qwen3-next",
+ "qwen3_next",
+ "nemotron_h",
+ "nemotron-h",
+ "nemotron-3-nano",
+ "falcon_h1",
+ "falcon-h1",
+ "granite-4.0-h",
+ "granitemoehybrid",
+ "lfm2",
+ "mamba",
+ "jamba",
+ "zamba",
+ "bamba",
+)
_MAMBA_SSM_RELEASE_TAG = "v2.3.1"
_MAMBA_SSM_PACKAGE_VERSION = "2.3.1"
_FLASH_ATTN_RUNTIME_MIN_SEQ_LEN = 32768
@@ -904,25 +935,7 @@ if sys.platform == "win32":
def _model_wants_causal_conv1d(model_name: str) -> bool:
name = model_name.lower()
- return any(
- key in name
- for key in (
- "qwen3.5",
- "qwen3_5",
- "qwen3.6",
- "qwen3_6",
- "qwen3-next",
- "qwen3_next",
- "nemotron_h",
- "nemotron-h",
- "nemotron-3-nano",
- "falcon_h1",
- "falcon-h1",
- "granite-4.0-h",
- "granitemoehybrid",
- "lfm2",
- )
- )
+ return any(key in name for key in _CAUSAL_CONV1D_MODEL_SUBSTRINGS)
def _hipcc_gcc_install_dir() -> str | None:
@@ -969,6 +982,10 @@ def _install_package_wheel_first(
except ImportError:
pass
+ if _model_offline_mode_enabled():
+ logger.info("Skipping %s installation while offline", display_name)
+ return False
+
env = probe_torch_wheel_env(timeout = 30)
if wheel_url_builder is not None:
wheel_url = wheel_url_builder(env)
@@ -1154,8 +1171,15 @@ def _install_package_wheel_first(
return True
-def _ensure_causal_conv1d_fast_path(event_queue: Any, model_name: str) -> None:
- if not _model_wants_causal_conv1d(model_name):
+def _ensure_causal_conv1d_fast_path(
+ event_queue: Any,
+ model_name: str,
+ *,
+ required: bool | None = None,
+) -> None:
+ if required is None:
+ required = _model_wants_causal_conv1d(model_name)
+ if not required:
return
if sys.platform == "win32":
logger.info("causal-conv1d: no prebuilt wheel for Windows; skipping")
@@ -1255,6 +1279,10 @@ def _ensure_flash_linear_attention_unconditional(event_queue: Any) -> bool:
logger.info("flash-linear-attention already importable at the pinned version")
return True
+ if _model_offline_mode_enabled():
+ logger.info("Skipping flash-linear-attention installation while offline")
+ return False
+
_send_status(
event_queue,
f"Installing flash-linear-attention=={_FLA_PACKAGE_VERSION} for faster training...",
@@ -1588,6 +1616,16 @@ def _ensure_tilelang_backend_unconditional(event_queue: Any) -> bool:
logger.info("tilelang + apache-tvm-ffi already installed")
return True
+ if _model_offline_mode_enabled():
+ if needs_repair and os.environ.get("FLA_TILELANG") is None:
+ os.environ["FLA_TILELANG"] = "0"
+ logger.warning(
+ "Disabling TileLang while offline because apache-tvm-ffi %s is unsafe",
+ existing_tvm_ffi,
+ )
+ logger.info("Skipping TileLang installation while offline")
+ return False
+
# Step 1: --no-deps keeps --force-reinstall off torch/CUDA via the dep graph.
if needs_repair:
logger.info(
@@ -1672,7 +1710,12 @@ def _rebind_in_already_imported_modules(*, attr_name: str, old_obj: Any, new_obj
return count
-def _install_fast_path_hooks(event_queue: Any, model_name: str) -> None:
+def _install_fast_path_hooks(
+ event_queue: Any,
+ model_name: str,
+ *,
+ install_causal_conv1d: bool | None = None,
+) -> None:
"""Hook transformers' is_*_available gates so the first call drives the install.
Idempotent. UNSLOTH_STUDIO_SKIP_FAST_PATH_HOOKS=1 falls back to the substring gate.
@@ -1774,10 +1817,15 @@ def _install_fast_path_hooks(event_queue: Any, model_name: str) -> None:
)
return bool(ok)
- for gate_name, install_fn, post_fn in (
+ hooks = [
("is_flash_linear_attention_available", _fla_install, _fla_post_available),
- ("is_causal_conv1d_available", _causal_conv1d_install, None),
- ):
+ ]
+ if install_causal_conv1d is None:
+ install_causal_conv1d = _model_wants_causal_conv1d(model_name)
+ if install_causal_conv1d:
+ hooks.append(("is_causal_conv1d_available", _causal_conv1d_install, None))
+
+ for gate_name, install_fn, post_fn in hooks:
original = getattr(_iu, gate_name, None)
if original is None:
logger.info(
@@ -2780,13 +2828,12 @@ def _run_mlx_training(event_queue, stop_queue, config):
# ── 7. Apply train_on_responses_only if requested ──
# Auto-detect markers from the chat template first, manual table as fallback. Mirror the
- # CUDA skips: raw/CPT text has no chat turns and Alpaca-rendered text lacks the markers.
+ # CUDA skips: raw/CPT text has no chat turns.
# Check the resolved format too, since format_type="auto" can land on alpaca or raw.
if (
config.get("train_on_completions", False)
and not raw_text_mode
- and format_type != "alpaca"
- and dataset_final_format not in ("alpaca", "raw_text")
+ and dataset_final_format != "raw_text"
):
_send("status", status_message = "Configuring response-only training...")
# No catch: the helper handles detection failures and double misses, so an exception here
@@ -2797,6 +2844,7 @@ def _run_mlx_training(event_queue, stop_queue, config):
model_name,
train_on_responses_only,
notify = lambda level, message: _send("status", status_message = message),
+ dataset_template = "alpaca" if dataset_final_format == "alpaca" else None,
)
# ── 8. Setup wandb / tensorboard ──
@@ -3272,18 +3320,33 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->
return
# ── 1b. Install fast-path kernel libraries for the chosen model.
- # 1) causal-conv1d ALWAYS runs eagerly via the substring path: some SSM modeling files
+ # 1) causal-conv1d runs eagerly for matching architectures: some SSM modeling files
# lazy_load it without calling is_causal_conv1d_available.
# 2) FLA + tilelang: gated by the runtime hook on is_flash_linear_attention_available.
# 3) mamba-ssm + flash-attn keep their substring / size gates.
# 4) UNSLOTH_STUDIO_SKIP_FAST_PATH_HOOKS=1 falls back to the substring path.
try:
- _ensure_causal_conv1d_fast_path(event_queue, model_name)
+ from utils.ssm_runtime import resolved_model_wants_causal_conv1d
+
+ wants_causal_conv1d = resolved_model_wants_causal_conv1d(
+ model_name,
+ model_load_target,
+ config.get("hf_token") or None,
+ )
+ _ensure_causal_conv1d_fast_path(
+ event_queue,
+ model_name,
+ required = wants_causal_conv1d,
+ )
if os.getenv(_FAST_PATH_HOOKS_SKIP_ENV) == "1":
_ensure_flash_linear_attention(event_queue, model_name)
_ensure_tilelang_backend(event_queue, model_name)
else:
- _install_fast_path_hooks(event_queue, model_name)
+ _install_fast_path_hooks(
+ event_queue,
+ model_name,
+ install_causal_conv1d = wants_causal_conv1d,
+ )
_ensure_mamba_ssm(event_queue, model_name)
_ensure_flash_attn_for_long_context(
event_queue,
diff --git a/studio/backend/hub/services/datasets/local_options.py b/studio/backend/hub/services/datasets/local_options.py
index 6f95e6838b8..7c2d5273a77 100644
--- a/studio/backend/hub/services/datasets/local_options.py
+++ b/studio/backend/hub/services/datasets/local_options.py
@@ -22,6 +22,10 @@ from hub.utils.dataset_cache import (
resolved_dataset_snapshot_file,
)
from hub.utils.paths import is_valid_repo_id
+from utils.hf_dataset_options import (
+ HF_DATASET_SPLIT_NAME_PATTERN,
+ has_unsafe_hf_dataset_option_characters,
+)
_MAX_METADATA_BYTES = 2 * 1024 * 1024
@@ -29,11 +33,8 @@ _MAX_PROCESSED_METADATA_FILES = 256
_MAX_PROCESSED_WALK_DEPTH = 4
_MAX_OPTIONS = 2048
_MAX_OPTION_LENGTH = 128
-# The picker starts these, so they have to be the grammar TrainingStartRequest accepts:
-# anything looser is offered and then 422s, anything tighter hides a usable option.
-# _check_subset and _check_split_name in models/training.py are the authority.
-_CONFIG_RE = re.compile(r"[A-Za-z0-9._\-]+")
-_SPLIT_RE = re.compile(r"[A-Za-z0-9_\-\[\]:%.+ ]+")
+_CONFIG_RE = re.compile(r"[^<>:/\\|?*\x00-\x1f\x7f]+")
+_SPLIT_RE = HF_DATASET_SPLIT_NAME_PATTERN
def _valid_option(
@@ -47,12 +48,10 @@ def _valid_option(
normalized = value.strip()
if not normalized or len(normalized) > _MAX_OPTION_LENGTH:
return None
- if "\x00" in normalized or "/" in normalized or "\\" in normalized:
+ if has_unsafe_hf_dataset_option_characters(normalized):
+ return None
+ if "/" in normalized or "\\" in normalized:
return None
- # _check_split_name rejects ".." anywhere, _check_subset does not, so a config named
- # v1..v2 is startable and hiding it would be the same bug in the other direction.
- # Neither charset admits a separator, so the bare "." and ".." names are the only
- # traversal shapes left to refuse.
if normalized in {".", ".."} or (reject_dotdot and ".." in normalized):
return None
if pattern.fullmatch(normalized) is None:
diff --git a/studio/backend/hub/tests/test_dataset_local_options.py b/studio/backend/hub/tests/test_dataset_local_options.py
index 3a5e1650770..690c988f41a 100644
--- a/studio/backend/hub/tests/test_dataset_local_options.py
+++ b/studio/backend/hub/tests/test_dataset_local_options.py
@@ -56,11 +56,19 @@ def test_processed_cache_options_are_local_deduplicated_and_non_train_capable(
)
assert response.cache_available is True
- # "config with spaces" is dropped: TrainingStartRequest._check_subset rejects the space,
- # so offering it would turn the click into a 422. "v1..v2" stays, because that same
- # validator accepts it -- only split names refuse "..".
assert [item.model_dump() for item in response.splits] == [
{"dataset": "org/data", "config": "default", "split": "train"},
+ {"dataset": "org/data", "config": "config with spaces", "split": "test"},
+ {
+ "dataset": "org/data",
+ "config": "config with spaces",
+ "split": "train.clean",
+ },
+ {
+ "dataset": "org/data",
+ "config": "config with spaces",
+ "split": "validation",
+ },
{"dataset": "org/data", "config": "v1..v2", "split": "test"},
]
diff --git a/studio/backend/mcp_server.py b/studio/backend/mcp_server.py
index 981ae66aba6..2f4e63da7bb 100644
--- a/studio/backend/mcp_server.py
+++ b/studio/backend/mcp_server.py
@@ -144,10 +144,15 @@ def create_studio_mcp() -> FastMCP:
return _dump(await start(request, current_subject = "mcp", via_api_key = False))
@mcp.tool
- async def stop_training(save: bool = True) -> dict[str, Any]:
- """Ask the active training process to stop at its next safe checkpoint."""
+ async def stop_training(expected_job_id: str, save: bool = True) -> dict[str, Any]:
+ """Stop the identified training job at its next safe checkpoint."""
from routes.training import TrainingStopRequest, stop_training as stop
- return _dump(await stop(TrainingStopRequest(save = save), current_subject = "mcp"))
+ return _dump(
+ await stop(
+ TrainingStopRequest(save = save, expected_job_id = expected_job_id),
+ current_subject = "mcp",
+ )
+ )
@mcp.tool
async def list_training_runs(limit: int = 50, offset: int = 0) -> dict[str, Any]:
diff --git a/studio/backend/models/training.py b/studio/backend/models/training.py
index 4e654dd681b..fbdd06e61e9 100644
--- a/studio/backend/models/training.py
+++ b/studio/backend/models/training.py
@@ -11,12 +11,19 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
from typing import Any, Optional, List, Dict, Literal, Union
from hub.schemas.inventory import ModelFormat
+from utils.hf_dataset_options import (
+ MAX_HF_DATASET_OPTION_LENGTH,
+ valid_hf_dataset_config_name,
+ valid_hf_dataset_split_name,
+ valid_hf_dataset_split_instruction,
+)
from utils.training_runs import normalize_project_name
# ASCII integer, optional single sign. Rejects "++512" and Unicode digits that pass str.isdigit().
_INT_RE = re.compile(r"[+-]?[0-9]+")
_HF_DATASET_ID_SEGMENT_RE = re.compile(r"[A-Za-z0-9_](?:[A-Za-z0-9._-]*[A-Za-z0-9_])?")
+TRAINING_REQUEST_ID_PATTERN = r"^[A-Za-z0-9][A-Za-z0-9._:-]*$"
_MAX_BATCH_SIZE = 4096
@@ -106,7 +113,7 @@ class TrainingStartRequest(BaseModel):
None,
min_length = 1,
max_length = 128,
- pattern = r"^[A-Za-z0-9][A-Za-z0-9._:-]*$",
+ pattern = TRAINING_REQUEST_ID_PATTERN,
description = "Opaque client-generated identifier used to reconcile an ambiguous start response",
)
training_type: Literal["LoRA/QLoRA", "Full Finetuning", "Continued Pretraining"] = Field(
@@ -235,10 +242,13 @@ class TrainingStartRequest(BaseModel):
def _check_subset(cls, v: Optional[str]) -> Optional[str]:
if v is None:
return v
- if len(v) > 128:
- raise ValueError("subset is too long (max 128 chars)")
- if not re.fullmatch(r"[A-Za-z0-9._\-]*", v):
- raise ValueError("subset may only contain letters, digits, '_', '-', '.'")
+ v = v.strip()
+ if not v:
+ return None
+ if len(v) > MAX_HF_DATASET_OPTION_LENGTH:
+ raise ValueError(f"subset is too long (max {MAX_HF_DATASET_OPTION_LENGTH} chars)")
+ if not valid_hf_dataset_config_name(v):
+ raise ValueError("subset contains invalid characters")
return v
@field_validator(
@@ -265,14 +275,14 @@ class TrainingStartRequest(BaseModel):
@field_validator("train_split", "eval_split")
@classmethod
def _check_split_name(cls, v: Optional[str]) -> Optional[str]:
- # Split names feed HF slice syntax, so allow that charset but cap length and block traversal / NUL.
if v is None:
return v
- if len(v) > 128:
- raise ValueError("split name is too long (max 128 chars)")
- if "\x00" in v or ".." in v or "/" in v or "\\" in v:
- raise ValueError("split name contains invalid characters")
- if not re.fullmatch(r"[A-Za-z0-9_\-\[\]:%.+ ]*", v):
+ v = v.strip()
+ if not v:
+ return None
+ if len(v) > MAX_HF_DATASET_OPTION_LENGTH:
+ raise ValueError(f"split name is too long (max {MAX_HF_DATASET_OPTION_LENGTH} chars)")
+ if not valid_hf_dataset_split_instruction(v):
raise ValueError("split name contains invalid characters")
return v
@@ -579,11 +589,10 @@ class TrainingStartRequest(BaseModel):
("train_split", self.train_split),
("eval_split", self.eval_split),
):
- if split_val is not None and "[" in split_val:
+ if split_val is not None and not valid_hf_dataset_split_name(split_val):
raise ValueError(
- f"dataset_streaming does not support HF slice syntax in {field_name} "
- f"(got {split_val!r}); streaming load_dataset raises 'Bad split' on "
- "bracket expressions. Use a plain split name (e.g. 'train', 'validation')."
+ f"dataset_streaming requires a plain split name in {field_name} "
+ f"(got {split_val!r}); use a name such as 'train' or 'validation'."
)
return self
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 5c22e362ac9..48ce4206bcc 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -7504,9 +7504,8 @@ def _requires_trust_remote_code_for_model(
) -> bool:
"""Whether loading this model would execute custom repo code, so the consent
dialog must run first. True if the Unsloth YAML default enables
- ``trust_remote_code`` OR the raw config declares an ``auto_map`` (Hub/local,
- config.json or tokenizer_config.json). Reads raw JSON only; never imports
- model code."""
+ ``trust_remote_code`` OR a raw config at any model load root declares an
+ ``auto_map``. Reads raw JSON only; never imports model code."""
from utils.inference import load_inference_config
try:
@@ -7516,7 +7515,18 @@ def _requires_trust_remote_code_for_model(
pass
try:
from utils.security.consent import _config_has_auto_map
- return _config_has_auto_map(model_identifier, hf_token) is True
+ from utils.security import load_scan_target, security_load_subdirs
+
+ load_subdirs = security_load_subdirs(model_identifier, hf_token)
+ target, load_subdirs = load_scan_target(model_identifier, load_subdirs)
+ return (
+ _config_has_auto_map(
+ target,
+ hf_token,
+ load_subdirs = load_subdirs,
+ )
+ is True
+ )
except Exception:
return False
@@ -7559,11 +7569,20 @@ def _requires_security_review_for_model(
the consent dialog must open as a hard block before loading. Metadata-only;
never downloads the flagged files. Fails open (False) on any error."""
try:
- from utils.security import evaluate_file_security, security_load_subdirs
+ from utils.security import (
+ evaluate_file_security,
+ load_scan_target,
+ security_load_subdirs,
+ )
+
+ # Normalize the `<name>/LLM` alias here as well as inside evaluate_file_security,
+ # so the subdirs passed alongside the target are resolved against the same repo.
+ load_subdirs = security_load_subdirs(model_identifier, hf_token)
+ target, load_subdirs = load_scan_target(model_identifier, load_subdirs)
return evaluate_file_security(
- model_identifier,
+ target,
hf_token,
- load_subdirs = security_load_subdirs(model_identifier, hf_token),
+ load_subdirs = load_subdirs,
).blocked
except Exception:
return False
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 699adabce12..702c71b70ba 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -2277,7 +2277,11 @@ async def scan_model_remote_code(
never lands in a URL, browser history, or access log.
"""
try:
- from utils.security import preflight_remote_code_consent_for_targets
+ from utils.security import (
+ load_scan_target,
+ preflight_remote_code_consent_for_targets,
+ security_load_subdirs,
+ )
local_model = is_local_path(model_name)
if not local_model:
@@ -2321,21 +2325,38 @@ async def scan_model_remote_code(
# Scan the adapter AND the base together (a LoRA runs both repos' code), pinned by one
# combined fingerprint. Snapshot the primary's cache state BEFORE resolving the base: that
# resolve downloads adapter_config.json, which would hide the adapter from cleanup on decline.
+ primary_cache_target, _ = load_scan_target(scan_target, ())
try:
- _primary_preexisting = is_local_path(model_name) or _repo_in_any_hf_cache(model_name)
+ _primary_preexisting = is_local_path(primary_cache_target) or _repo_in_any_hf_cache(
+ primary_cache_target
+ )
except Exception:
_primary_preexisting = True
- security_targets = [scan_target]
+ requested_scan_target = scan_target
+ requested_security_targets = [requested_scan_target]
try:
from utils.models.model_config import get_base_model_from_lora_identifier
# Resolve a LOCAL or REMOTE adapter's base so its code/weights are scanned too.
- _base = get_base_model_from_lora_identifier(scan_target, hf_token)
+ _base = get_base_model_from_lora_identifier(requested_scan_target, hf_token)
if _base:
- security_targets.append(_base)
+ requested_security_targets.append(_base)
except Exception:
pass
- security_targets = list(dict.fromkeys(security_targets))
+ security_targets: list[str] = []
+ consent_load_subdirs: dict[str, tuple] = {}
+ for _requested_target in dict.fromkeys(requested_security_targets):
+ _subdirs = security_load_subdirs(_requested_target, hf_token)
+ if _requested_target == requested_scan_target and requested_scan_target != model_name:
+ _subdirs = tuple(
+ dict.fromkeys((*_subdirs, *security_load_subdirs(model_name, hf_token)))
+ )
+ _target, _subdirs = load_scan_target(_requested_target, _subdirs)
+ if _target not in consent_load_subdirs:
+ security_targets.append(_target)
+ consent_load_subdirs[_target] = ()
+ _subdirs = tuple(dict.fromkeys((*consent_load_subdirs[_target], *_subdirs)))
+ consent_load_subdirs[_target] = _subdirs
# Record every repo OUR scan is first to pull into the cache (adapter, base, and external
# auto_map repos), so a decline purges exactly what was downloaded. Computed BEFORE the
# preflight downloads, against every cache the discard searches, so pre-existing repos stay.
@@ -2363,13 +2384,21 @@ async def scan_model_remote_code(
for _target in security_targets:
# Use the pre-base-resolution snapshot for the primary (see above).
_mark_scan_created(
- _target, preexisting = _primary_preexisting if _target == model_name else None
+ _target,
+ preexisting = _primary_preexisting if _target == primary_cache_target else None,
)
- for _ext in external_auto_map_repos(_target, hf_token):
+ for _ext in external_auto_map_repos(
+ _target,
+ hf_token,
+ load_subdirs = consent_load_subdirs[_target],
+ ):
external_refs.append(_ext)
_mark_scan_created(_ext)
decision = preflight_remote_code_consent_for_targets(
- security_targets, hf_token = hf_token, subject = current_subject
+ security_targets,
+ hf_token = hf_token,
+ subject = current_subject,
+ load_subdirs_by_target = consent_load_subdirs,
)
payload = decision.response_payload()
payload["model_name"] = exact_snapshot_repo_id if exact_snapshot_path else model_name
@@ -2381,23 +2410,24 @@ async def scan_model_remote_code(
and decision.reason == "approved by fingerprint"
)
# created_by_scan = primary flag (older clients); scan_created_repos drives cleanup.
- payload["created_by_scan"] = model_name in scan_created_repos
+ payload["created_by_scan"] = primary_cache_target in scan_created_repos
payload["scan_created_repos"] = scan_created_repos
# Provider tag decided here, where locality/scan scope/external refs are known.
- payload["provider"] = _consent_provider(
- exact_snapshot_repo_id if exact_snapshot_path else model_name,
- security_targets,
- external_refs,
- )
+ provider_target = exact_snapshot_repo_id if exact_snapshot_path else model_name
+ if requested_scan_target == model_name and primary_cache_target != model_name:
+ provider_target = primary_cache_target
+ payload["provider"] = _consent_provider(provider_target, security_targets, external_refs)
# Malware gate (metadata-only): HF-flagged unsafe files, orthogonal to remote code.
- from utils.security import evaluate_file_security, security_load_subdirs
+ from utils.security import evaluate_file_security
unsafe_files: list = []
security_blocked = False
for _target in security_targets:
_sec = evaluate_file_security(
- _target, hf_token = hf_token, load_subdirs = security_load_subdirs(_target, hf_token)
+ _target,
+ hf_token = hf_token,
+ load_subdirs = consent_load_subdirs[_target],
)
security_blocked = security_blocked or _sec.blocked
unsafe_files.extend(_sec.unsafe_files)
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index f83df84969d..5fdebb79d57 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -13,9 +13,18 @@ import sys
import threading
from dataclasses import dataclass
from pathlib import Path
-from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile
+from fastapi import (
+ APIRouter,
+ Depends,
+ File,
+ Form,
+ HTTPException,
+ Path as ApiPath,
+ Request,
+ UploadFile,
+)
from fastapi.responses import StreamingResponse
-from typing import Dict, Optional, Any
+from typing import Dict, Literal, Optional, Any
import structlog
from loggers import get_logger
import asyncio
@@ -28,7 +37,10 @@ if str(backend_path) not in sys.path:
try:
from core.training import get_training_backend
- from core.training.training import TrainingStatusIdentitySnapshot
+ from core.training.training import (
+ TrainingStartCancellationCapacityError,
+ TrainingStatusIdentitySnapshot,
+ )
from core.training.resume import (
can_resume_run,
get_resume_checkpoint_path,
@@ -45,7 +57,10 @@ except ImportError:
if str(parent_backend) not in sys.path:
sys.path.insert(0, str(parent_backend))
from core.training import get_training_backend
- from core.training.training import TrainingStatusIdentitySnapshot
+ from core.training.training import (
+ TrainingStartCancellationCapacityError,
+ TrainingStatusIdentitySnapshot,
+ )
from core.training.resume import (
can_resume_run,
get_resume_checkpoint_path,
@@ -95,18 +110,36 @@ from models.training import (
DiffusionTrainingStartResponse,
DiffusionTrainingStatusResponse,
DiffusionTrainingStopRequest,
+ TRAINING_REQUEST_ID_PATTERN,
)
from models.responses import TrainingStopResponse, TrainingMetricsResponse
-from pydantic import BaseModel as PydanticBaseModel, ValidationError
+from pydantic import (
+ BaseModel as PydanticBaseModel,
+ Field as PydanticField,
+ ValidationError,
+)
class TrainingStopRequest(PydanticBaseModel):
save: bool = True
- expected_job_id: Optional[str] = None
+ expected_job_id: str = PydanticField(
+ ...,
+ min_length = 1,
+ max_length = 128,
+ pattern = TRAINING_REQUEST_ID_PATTERN,
+ )
class TrainingResetRequest(PydanticBaseModel):
- expected_job_id: Optional[str] = None
+ # Stays optional: every Studio build before the train-page rework posts /reset with no
+ # body, and those clients only ever reset a finished run. The backend refuses an
+ # unscoped reset that would touch a LIVE run instead, so the guard costs no compat.
+ expected_job_id: Optional[str] = PydanticField(
+ default = None,
+ min_length = 1,
+ max_length = 128,
+ pattern = TRAINING_REQUEST_ID_PATTERN,
+ )
router = APIRouter()
@@ -179,20 +212,21 @@ class _ModelPreflightResult:
_PROGRESS_STALL_TIMEOUT_POLLS = 1800 # ~30 min at 1 poll/sec
-def _stop_training_if_active(backend, *, save: bool, expected_job_id: Optional[str]):
+def _stop_training_if_active(
+ backend, *, save: bool, expected_job_id: str
+) -> Literal["idle", "stopped", "superseded"]:
from core.training.lifecycle import training_lifecycle_guard
with training_lifecycle_guard():
- is_active = _run_active(backend)
- if not is_active:
- stopped = False
- elif expected_job_id is None:
- stopped = backend.stop_training(save = save)
- else:
- stopped = backend.stop_training(
- save = save,
- expected_job_id = expected_job_id,
- )
- return is_active, stopped
+ if not _run_active(backend):
+ return "idle"
+ current_job_id = getattr(backend, "current_job_id", None)
+ if current_job_id is not None and current_job_id != expected_job_id:
+ return "superseded"
+ stopped = backend.stop_training(
+ save = save,
+ expected_job_id = expected_job_id,
+ )
+ return "stopped" if stopped else "idle"
def _is_finalizing(progress, msg_lower: str) -> bool:
@@ -1016,7 +1050,13 @@ async def get_visible_hardware_utilization(current_subject: str = Depends(get_cu
@router.get("/start-requests/{start_request_id}", response_model = TrainingStartRequestStatus)
async def get_training_start_request(
- start_request_id: str, current_subject: str = Depends(get_current_subject)
+ start_request_id: str = ApiPath(
+ ...,
+ min_length = 1,
+ max_length = 128,
+ pattern = TRAINING_REQUEST_ID_PATTERN,
+ ),
+ current_subject: str = Depends(get_current_subject),
):
backend = get_training_backend()
record = backend.get_start_request(start_request_id)
@@ -1038,7 +1078,13 @@ def _start_request_status_response(record) -> TrainingStartRequestStatus:
@router.post("/start-requests/{start_request_id}/acknowledge")
async def acknowledge_training_start_request(
- start_request_id: str, current_subject: str = Depends(get_current_subject)
+ start_request_id: str = ApiPath(
+ ...,
+ min_length = 1,
+ max_length = 128,
+ pattern = TRAINING_REQUEST_ID_PATTERN,
+ ),
+ current_subject: str = Depends(get_current_subject),
):
backend = get_training_backend()
if not backend.acknowledge_start_request(start_request_id):
@@ -1054,13 +1100,22 @@ async def acknowledge_training_start_request(
response_model = TrainingStartRequestStatus,
)
async def cancel_training_start_request(
- start_request_id: str, current_subject: str = Depends(get_current_subject)
+ start_request_id: str = ApiPath(
+ ...,
+ min_length = 1,
+ max_length = 128,
+ pattern = TRAINING_REQUEST_ID_PATTERN,
+ ),
+ current_subject: str = Depends(get_current_subject),
):
backend = get_training_backend()
- outcome, record = await asyncio.to_thread(
- backend.cancel_start_request,
- start_request_id,
- )
+ try:
+ outcome, record = await asyncio.to_thread(
+ backend.cancel_start_request,
+ start_request_id,
+ )
+ except TrainingStartCancellationCapacityError as exc:
+ raise HTTPException(status_code = 429, detail = str(exc)) from exc
if outcome == "superseded":
raise HTTPException(
status_code = 409,
@@ -1689,25 +1744,30 @@ async def start_training(
@router.post("/stop", response_model = TrainingStopResponse)
async def stop_training(
- body: TrainingStopRequest = TrainingStopRequest(),
- current_subject: str = Depends(get_current_subject),
+ body: TrainingStopRequest, current_subject: str = Depends(get_current_subject)
):
"""
Stop the currently running training job.
Body:
save (bool): If True (default), save the model at the current checkpoint.
+ expected_job_id (str): Identifier of the job the caller intends to stop.
"""
try:
backend = get_training_backend()
- is_active, stopped = await asyncio.to_thread(
+ outcome = await asyncio.to_thread(
_stop_training_if_active,
backend,
save = body.save,
expected_job_id = body.expected_job_id,
)
- logger.info("Stop requested: save=%s is_active=%s", body.save, is_active)
- if not is_active or not stopped:
+ logger.info("Stop requested: save=%s outcome=%s", body.save, outcome)
+ if outcome == "superseded":
+ raise HTTPException(
+ status_code = 409,
+ detail = "The requested training job is no longer active.",
+ )
+ if outcome == "idle":
return TrainingStopResponse(
status = "idle", message = "No training job is currently running"
)
@@ -1717,6 +1777,8 @@ async def stop_training(
message = "Stop requested. Training will stop at the next safe step.",
)
+ except HTTPException:
+ raise
except Exception as e:
raise log_and_http_error(
e,
diff --git a/studio/backend/tests/test_completion_masking.py b/studio/backend/tests/test_completion_masking.py
index be0d8a69bde..101f8c05901 100644
--- a/studio/backend/tests/test_completion_masking.py
+++ b/studio/backend/tests/test_completion_masking.py
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Completion-only masking policy: auto-detect first, manual table fallback.
+"""Completion-only masking policy shared across CUDA and MLX training.
Covers utils.datasets.completion_masking.apply_completion_masking, shared by
the CUDA trainer (core/training/trainer.py) and the MLX worker
@@ -11,6 +11,7 @@ the CUDA trainer (core/training/trainer.py) and the MLX worker
- gpt-oss goes auto-first too (its quantized checkpoints ship a template
the manual markers cannot match),
- an auto-detection failure falls back to the template table markers,
+ - explicit dataset templates take precedence over tokenizer markers,
- a table miss after an auto failure warns and leaves the trainer unchanged.
"""
@@ -92,6 +93,115 @@ def test_mapped_model_prefers_auto_detection():
assert train_fn.calls == [dict(_AUTO)]
+def test_dataset_template_uses_alpaca_markers_without_detection():
+ trainer = _Trainer()
+ train_fn = _Recorder()
+
+ def detect(_processor):
+ raise AssertionError("dataset template must bypass tokenizer detection")
+
+ result, applied = apply_completion_masking(
+ trainer,
+ "unsloth/Llama-3.2-1B-Instruct",
+ train_fn,
+ detect_fn = detect,
+ dataset_template = "alpaca",
+ )
+
+ expected = TEMPLATE_TO_RESPONSES_MAPPER["alpaca"]
+ assert applied is True
+ assert result.wrapped_from is trainer
+ assert train_fn.calls == [
+ {
+ "instruction_part": expected["instruction"],
+ "response_part": expected["response"],
+ }
+ ]
+
+
+def test_dataset_template_temporarily_replaces_tokenizer_markers():
+ class _Tok:
+ _unsloth_input_part = "<MODEL_INPUT>"
+ _unsloth_output_part = "<MODEL_OUTPUT>"
+
+ trainer = _Trainer()
+ trainer.processing_class = _Tok()
+ expected = TEMPLATE_TO_RESPONSES_MAPPER["alpaca"]
+ calls = []
+
+ def train_fn(current_trainer, **kwargs):
+ if kwargs and hasattr(current_trainer.processing_class, "_unsloth_input_part"):
+ raise ValueError("custom markers conflict with tokenizer markers")
+ calls.append(kwargs)
+ assert current_trainer.processing_class._unsloth_input_part == expected["instruction"]
+ assert current_trainer.processing_class._unsloth_output_part == expected["response"]
+ return current_trainer
+
+ result, applied = apply_completion_masking(
+ trainer,
+ "unsloth/Llama-3.2-1B-Instruct",
+ train_fn,
+ dataset_template = "alpaca",
+ )
+
+ assert applied is True
+ assert result is trainer
+ assert calls == [{}]
+ assert trainer.processing_class._unsloth_input_part == "<MODEL_INPUT>"
+ assert trainer.processing_class._unsloth_output_part == "<MODEL_OUTPUT>"
+
+
+def test_dataset_template_restores_tokenizer_markers_after_failure():
+ class _Tok:
+ _unsloth_input_part = "<MODEL_INPUT>"
+ _unsloth_output_part = "<MODEL_OUTPUT>"
+
+ trainer = _Trainer()
+ trainer.processing_class = _Tok()
+
+ def train_fn(_trainer, **_kwargs):
+ raise RuntimeError("masking failed")
+
+ with pytest.raises(RuntimeError, match = "masking failed"):
+ apply_completion_masking(
+ trainer,
+ "unsloth/Llama-3.2-1B-Instruct",
+ train_fn,
+ dataset_template = "alpaca",
+ )
+
+ assert trainer.processing_class._unsloth_input_part == "<MODEL_INPUT>"
+ assert trainer.processing_class._unsloth_output_part == "<MODEL_OUTPUT>"
+
+
+def test_dataset_template_forwards_num_proc():
+ train_fn = _Recorder()
+
+ apply_completion_masking(
+ _Trainer(),
+ "unsloth/Llama-3.2-1B-Instruct",
+ train_fn,
+ num_proc = 4,
+ dataset_template = "alpaca",
+ )
+
+ assert train_fn.calls[0]["num_proc"] == 4
+
+
+def test_unknown_dataset_template_fails_loudly():
+ train_fn = _Recorder()
+
+ with pytest.raises(ValueError, match = "Unknown completion masking template"):
+ apply_completion_masking(
+ _Trainer(),
+ "unsloth/Llama-3.2-1B-Instruct",
+ train_fn,
+ dataset_template = "missing",
+ )
+
+ assert train_fn.calls == []
+
+
def test_gpt_oss_uses_auto_detection_first():
# The quantized gpt-oss checkpoints ship a template without the
# <|channel|>final header, where the manual markers match nothing; auto
diff --git a/studio/backend/tests/test_consent_gate.py b/studio/backend/tests/test_consent_gate.py
index 802feca8396..4090101f145 100644
--- a/studio/backend/tests/test_consent_gate.py
+++ b/studio/backend/tests/test_consent_gate.py
@@ -24,6 +24,7 @@ from utils.security import (
evaluate_remote_code_consent_for_targets,
is_trusted_org_repo,
remote_code_fingerprint,
+ remote_code_config_paths,
scan_remote_code_files,
should_block_remote_code,
)
@@ -106,6 +107,71 @@ class TestConsentGate:
assert d.blocked is False
assert "no-op" in d.reason
+ def test_load_subdirectory_auto_map_is_scanned(self, tmp_path):
+ model = tmp_path / "model"
+ llm = model / "LLM"
+ llm.mkdir(parents = True)
+ (llm / "config.json").write_text(
+ '{"auto_map":{"AutoModel":"modeling_evil.Model"}}',
+ encoding = "utf-8",
+ )
+ (llm / "modeling_evil.py").write_text(
+ "import subprocess\nsubprocess.Popen(['id'])\n",
+ encoding = "utf-8",
+ )
+
+ decision = evaluate_remote_code_consent_for_targets(
+ [str(model)],
+ trust_remote_code = True,
+ load_subdirs_by_target = {str(model): ("LLM",)},
+ )
+
+ assert decision.has_remote_code is True
+ assert decision.blocked is True
+ assert decision.max_severity == HIGH
+ assert decision.fingerprint
+
+ def test_linked_load_subdirectory_fails_closed(self, tmp_path):
+ model = tmp_path / "model"
+ linked_llm = tmp_path / "linked-llm"
+ model.mkdir()
+ linked_llm.mkdir()
+ (linked_llm / "config.json").write_text(
+ '{"auto_map":{"AutoModel":"modeling_evil.Model"}}',
+ encoding = "utf-8",
+ )
+ (linked_llm / "modeling_evil.py").write_text("VALUE = 1\n", encoding = "utf-8")
+ try:
+ (model / "LLM").symlink_to(linked_llm, target_is_directory = True)
+ except OSError as error:
+ pytest.skip(f"directory symlinks are unavailable: {error}")
+
+ decision = evaluate_remote_code_consent_for_targets(
+ [str(model)],
+ trust_remote_code = True,
+ load_subdirs_by_target = {str(model): ("LLM",)},
+ )
+
+ assert decision.has_remote_code is True
+ assert decision.blocked is True
+ assert decision.approvable is False
+ assert "could not be downloaded and scanned" in decision.findings_summary
+
+ @pytest.mark.parametrize(
+ "subdir",
+ [
+ "../outside",
+ "/outside",
+ "C:/outside",
+ "C:outside",
+ "LLM/C:outside",
+ r"nested\\outside",
+ ],
+ )
+ def test_remote_code_config_paths_reject_escaping_subdirectories(self, subdir):
+ with pytest.raises(ValueError, match = "Invalid remote-code load subdirectory"):
+ remote_code_config_paths((subdir,))
+
def test_unknown_auto_map_is_scanned_not_skipped(self):
# Unreadable config (private/gated/offline) is "unknown", not "no code": scan, not no-op.
with (
@@ -711,7 +777,9 @@ class TestStructuredFindingsForDialog:
lambda target, *_args, **_kwargs: base_targets.append(target) or "someone/base",
)
monkeypatch.setattr(models_route, "_repo_in_any_hf_cache", lambda *_args: True)
- monkeypatch.setattr(remote_code_scan, "external_auto_map_repos", lambda *_args: set())
+ monkeypatch.setattr(
+ remote_code_scan, "external_auto_map_repos", lambda *_args, **_kwargs: set()
+ )
monkeypatch.setattr(
security,
"preflight_remote_code_consent_for_targets",
@@ -765,7 +833,9 @@ class TestStructuredFindingsForDialog:
lambda *_args, **_kwargs: None,
)
monkeypatch.setattr(models_route, "_repo_in_any_hf_cache", lambda *_args: True)
- monkeypatch.setattr(remote_code_scan, "external_auto_map_repos", lambda *_args: set())
+ monkeypatch.setattr(
+ remote_code_scan, "external_auto_map_repos", lambda *_args, **_kwargs: set()
+ )
monkeypatch.setattr(
security,
"preflight_remote_code_consent_for_targets",
@@ -839,7 +909,9 @@ class TestStructuredFindingsForDialog:
lambda target, *_args, **_kwargs: base_targets.append(target) or "someone/base",
)
monkeypatch.setattr(models_route, "_repo_in_any_hf_cache", lambda *_args: True)
- monkeypatch.setattr(remote_code_scan, "external_auto_map_repos", lambda *_args: set())
+ monkeypatch.setattr(
+ remote_code_scan, "external_auto_map_repos", lambda *_args, **_kwargs: set()
+ )
monkeypatch.setattr(
security,
"preflight_remote_code_consent_for_targets",
diff --git a/studio/backend/tests/test_gpu_selection.py b/studio/backend/tests/test_gpu_selection.py
index 8b6fdf3a1ba..26053411a37 100644
--- a/studio/backend/tests/test_gpu_selection.py
+++ b/studio/backend/tests/test_gpu_selection.py
@@ -685,6 +685,37 @@ class TestGpuAutoSelection(_GpuCacheResetMixin, unittest.TestCase):
self.assertEqual(model_size_bytes, 1234)
self.assertEqual(source, "vllm_utils")
+ def test_offline_safetensors_probe_uses_config_without_hub_access(self):
+ config = object()
+ for offline_variable in ("HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE"):
+ with self.subTest(offline_variable = offline_variable):
+ with (
+ patch.dict(os.environ, {offline_variable: "true"}, clear = True),
+ patch("huggingface_hub.model_info") as hub_info,
+ patch(
+ "utils.hardware.hardware._resolve_model_identifier_for_gpu_estimate",
+ return_value = "unsloth/test",
+ ),
+ patch(
+ "utils.hardware.hardware._load_config_for_gpu_estimate",
+ return_value = config,
+ ),
+ patch(
+ "utils.hardware.hardware._estimate_fp16_model_size_bytes_from_config",
+ return_value = 1234,
+ ),
+ patch(
+ "utils.hardware.hardware._get_local_weight_size_bytes",
+ return_value = None,
+ ),
+ ):
+ model_size_bytes, source = _hw_module.estimate_fp16_model_size_bytes(
+ "unsloth/test"
+ )
+
+ self.assertEqual((model_size_bytes, source), (1234, "config"))
+ hub_info.assert_not_called()
+
def test_auto_select_gpu_ids_chooses_smallest_fitting_subset(self):
fake_devices = {
"devices": [
diff --git a/studio/backend/tests/test_local_options_match_start_validation.py b/studio/backend/tests/test_local_options_match_start_validation.py
index 39b71e13d54..56e74b1430d 100644
--- a/studio/backend/tests/test_local_options_match_start_validation.py
+++ b/studio/backend/tests/test_local_options_match_start_validation.py
@@ -1,23 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""What the picker offers has to be what /training/start accepts.
-
-``local_options.py`` starts the cached-dataset subset and split options the picker shows,
-and ``TrainingStartRequest`` decides what a start request may carry. They were written with
-different grammars, which fails in both directions:
-
-- ``_SPLIT_RE`` was ``\\w+(?:\\.\\w+)*``, so it dropped the hyphen. A real split name like
- ``train-clean`` (LibriSpeech) never reached the picker, and an offline user had to type it
- by hand into a field that would have accepted it.
-- ``\\w`` is Unicode-aware in Python, so ``tréin`` was offered and then rejected by the
- ASCII-only split validator. ``_CONFIG_RE`` excluded only filesystem-hostile characters, so
- a config name with a space was offered and then rejected by the subset validator.
-
-Both directions are silent: one hides a usable option, the other turns a click into a 422.
-"""
-
-import re
+"""Cached dataset options must remain valid training request selections."""
import pytest
@@ -51,14 +35,34 @@ def _offered_split(value: str):
# (value, offered_by, accepted_by)
-_SPLITS = ["train", "validation", "test", "train-clean", "train.clean", "train[:10%]"]
-_CONFIGS = ["default", "cfg-1", "en.simple", "wikitext-103-raw-v1", "v1..v2"]
-_REJECTED = ["tréin", "my config", "träin", "tr..in"]
+_SPLITS = ["train", "validation", "test", "train.clean", "tréin"]
+_CONFIGS = [
+ "default",
+ "cfg-1",
+ "en.simple",
+ "config with spaces",
+ "cönfig",
+ "v1..v2",
+]
+_REJECTED = ["train-clean", "train name", "tr..in"]
+_SPLIT_INSTRUCTIONS = [
+ "train[:10%]",
+ "train[1_000:2_000]",
+ "test[:-5%](pct1_dropremainder) + train[40%:60%](pct1_dropremainder)",
+]
+_INVALID_SPLIT_INSTRUCTIONS = [
+ "train-clean",
+ "train[10%",
+ "train[101%:]",
+ "train[101:20%]",
+ "train[-101:20%]",
+ "train[10:20](closest)",
+ "test[:-5%] + train[40%:60%](pct1_dropremainder)",
+]
@pytest.mark.parametrize("value", _SPLITS)
def test_a_split_the_backend_accepts_is_offered(value):
- """The hiding direction: a start request would take it, so the picker must show it."""
assert _split_accepted(value), f"fixture wrong: {value!r} is not accepted by the backend"
assert _offered_split(value) == value, (
f"{value!r} is a valid split for /training/start but the picker filters it out, "
@@ -72,9 +76,18 @@ def test_a_subset_the_backend_accepts_is_offered(value):
assert _valid_option(value, _CONFIG_RE) == value
[email protected]("value", _SPLIT_INSTRUCTIONS)
+def test_backend_accepts_supported_split_instructions(value):
+ assert _split_accepted(value)
+
+
[email protected]("value", _INVALID_SPLIT_INSTRUCTIONS)
+def test_backend_rejects_invalid_split_instructions(value):
+ assert not _split_accepted(value)
+
+
@pytest.mark.parametrize("value", _REJECTED)
def test_nothing_the_backend_rejects_is_offered(value):
- """The 422 direction: offering it turns a click into a rejected start."""
offered_split = _offered_split(value)
assert offered_split is None or _split_accepted(offered_split), (
f"{value!r} is offered as split {offered_split!r} but /training/start rejects it, so "
@@ -87,8 +100,7 @@ def test_nothing_the_backend_rejects_is_offered(value):
def test_the_two_grammars_agree_over_a_generated_alphabet():
- """Neither side may drift: every string built from the union charset agrees."""
- alphabet = "abZ09_-.[]:%+ é/\\"
+ alphabet = "abZ09_-.[]:%+ é/\\\u200b\ud800"
mismatches = []
for a in alphabet:
for b in ("", "x", ".x"):
diff --git a/studio/backend/tests/test_mcp_server.py b/studio/backend/tests/test_mcp_server.py
index 71792605ae0..adcbe9869b8 100644
--- a/studio/backend/tests/test_mcp_server.py
+++ b/studio/backend/tests/test_mcp_server.py
@@ -181,6 +181,9 @@ def test_export_and_checkpoint_tools_expose_forwarded_fields():
checkpoint_props = set(_get_tool("load_checkpoint").parameters["properties"])
assert {"hf_token", "approved_remote_code_fingerprint"} <= checkpoint_props
+ stop_schema = _get_tool("stop_training").parameters
+ assert "expected_job_id" in stop_schema["required"]
+
def _stub_module(monkeypatch, name, **attrs):
module = types.ModuleType(name)
@@ -253,6 +256,35 @@ def test_load_checkpoint_forwards_token_and_fingerprint(monkeypatch):
assert captured["approved_remote_code_fingerprint"] == "sha256:abc"
+def test_stop_training_forwards_job_scope(monkeypatch):
+ captured = {}
+
+ class FakeTrainingStopRequest:
+ def __init__(self, **kwargs):
+ captured.update(kwargs)
+
+ async def fake_stop(request, current_subject):
+ assert isinstance(request, FakeTrainingStopRequest)
+ captured["current_subject"] = current_subject
+ return {"status": "stopped"}
+
+ _stub_module(monkeypatch, "routes")
+ _stub_module(
+ monkeypatch,
+ "routes.training",
+ TrainingStopRequest = FakeTrainingStopRequest,
+ stop_training = fake_stop,
+ )
+
+ tool = _get_tool("stop_training")
+ result = asyncio.run(tool.fn(expected_job_id = "job-A", save = False))
+
+ assert captured["expected_job_id"] == "job-A"
+ assert captured["save"] is False
+ assert captured["current_subject"] == "mcp"
+ assert result == {"status": "stopped"}
+
+
def test_list_training_runs_clamps_pagination(monkeypatch):
captured = {}
diff --git a/studio/backend/tests/test_offline_gguf_cache_fallback.py b/studio/backend/tests/test_offline_gguf_cache_fallback.py
index 8583f64bdf1..13135aaaad4 100644
--- a/studio/backend/tests/test_offline_gguf_cache_fallback.py
+++ b/studio/backend/tests/test_offline_gguf_cache_fallback.py
@@ -769,6 +769,21 @@ class TestListGgufVariantsOffline:
assert len(variants) == 1
assert variants[0].quant == "UD-Q4_K_XL"
+ @pytest.mark.parametrize("offline_variable", ["HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE"])
+ def test_offline_cache_miss_does_not_call_api(
+ self, hf_cache, clean_offline_env, monkeypatch, offline_variable
+ ):
+ monkeypatch.setenv(offline_variable, "yes")
+
+ def boom(*_args, **_kwargs):
+ raise AssertionError("API must not be called on an offline cache miss")
+
+ with patch("huggingface_hub.model_info", boom):
+ variants, has_vision = list_gguf_variants("unsloth/not-cached")
+
+ assert variants == []
+ assert has_vision is False
+
def test_api_exception_falls_back_to_cache(self, hf_cache, clean_offline_env):
_build_cache(hf_cache, "unsloth/a", {"a-Q4_K_M.gguf": 1})
@@ -859,6 +874,18 @@ class TestDetectGgufModelRemoteOffline:
with patch("huggingface_hub.model_info", boom):
assert detect_gguf_model_remote("unsloth/a") == "a-Q4_K_M.gguf"
+ @pytest.mark.parametrize("offline_variable", ["HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE"])
+ def test_offline_cache_miss_does_not_call_api(
+ self, hf_cache, clean_offline_env, monkeypatch, offline_variable
+ ):
+ monkeypatch.setenv(offline_variable, "on")
+
+ def boom(*_args, **_kwargs):
+ raise AssertionError("API must not be called on an offline cache miss")
+
+ with patch("huggingface_hub.model_info", boom):
+ assert detect_gguf_model_remote("unsloth/not-cached") is None
+
def test_api_3x_failure_then_cache(self, hf_cache, clean_offline_env):
_build_cache(hf_cache, "unsloth/a", {"a-Q4_K_M.gguf": 1})
diff --git a/studio/backend/tests/test_ssm_runtime.py b/studio/backend/tests/test_ssm_runtime.py
index b95747e56c2..71ec92ef346 100644
--- a/studio/backend/tests/test_ssm_runtime.py
+++ b/studio/backend/tests/test_ssm_runtime.py
@@ -8,9 +8,11 @@ worker wiring, and a drift guard so the constants/detection stay in lockstep wit
training worker (the original source of this behaviour).
"""
+import json
import sys
import types
from pathlib import Path
+from unittest import mock
import pytest
@@ -21,6 +23,12 @@ if str(_BACKEND) not in sys.path:
from utils import ssm_runtime # noqa: E402
[email protected](autouse = True)
+def _clear_offline_environment(monkeypatch):
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
+
+
class _Result:
def __init__(
self,
@@ -57,6 +65,11 @@ def test_ssm_models_detected(name):
"Qwen/Qwen3-Next-80B-A3B",
"unsloth/Qwen3.5-2B",
"LiquidAI/LFM2-1.2B",
+ "state-spaces/mamba-2.8b-hf",
+ "ai21labs/Jamba-v0.1",
+ "Zyphra/Zamba2-7B",
+ "ibm/Bamba-9B",
+ "tiiuae/falcon-mamba-7b",
],
)
def test_causal_conv1d_only_models(name):
@@ -133,9 +146,13 @@ def test_ssm_model_installs_causal_then_mamba(monkeypatch):
monkeypatch.setattr(ssm_runtime, "_install_kernel", fake_install)
ssm_runtime.ensure_ssm_runtime("unsloth/NVIDIA-Nemotron-3-Nano-4B")
- assert order == ["causal_conv1d", "mamba_ssm"]
+ expected = ["mamba_ssm"] if sys.platform == "win32" else ["causal_conv1d", "mamba_ssm"]
+ assert order == expected
+ sys.platform == "win32", reason = "causal-conv1d is skipped on Windows (no prebuilt wheel)"
+)
def test_causal_only_model_skips_mamba(monkeypatch):
order = []
monkeypatch.setattr(
@@ -171,6 +188,7 @@ def test_ssm_causal_failure_nonfatal_when_mamba_ok(monkeypatch):
def test_install_kernel_idempotent_when_present(monkeypatch):
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
monkeypatch.setattr(ssm_runtime, "_is_importable", lambda name: True)
called = []
monkeypatch.setattr(ssm_runtime, "url_exists", lambda u: called.append("url") or True)
@@ -188,6 +206,39 @@ def test_install_kernel_idempotent_when_present(monkeypatch):
assert called == [] # short-circuits before touching the network
[email protected]("offline_variable", ["HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE"])
+def test_install_kernel_skips_all_install_work_offline(monkeypatch, offline_variable):
+ monkeypatch.setenv(offline_variable, "on")
+ monkeypatch.setattr(ssm_runtime, "_is_importable", lambda name: False)
+ torch_probe = mock.Mock()
+ wheel_builder = mock.Mock()
+ url_probe = mock.Mock()
+ wheel_install = mock.Mock()
+ process_run = mock.Mock()
+ monkeypatch.setattr(ssm_runtime, "probe_torch_wheel_env", torch_probe)
+ monkeypatch.setattr(ssm_runtime, "direct_wheel_url", wheel_builder)
+ monkeypatch.setattr(ssm_runtime, "url_exists", url_probe)
+ monkeypatch.setattr(ssm_runtime, "install_wheel", wheel_install)
+
+ installed = ssm_runtime._install_kernel(
+ import_name = "causal_conv1d",
+ display_name = "causal-conv1d",
+ pypi_name = "causal-conv1d",
+ package_version = "1.6.1",
+ release_tag = "v1.6.1.post4",
+ release_base_url = "https://example.invalid/releases",
+ status_cb = None,
+ run = process_run,
+ )
+
+ assert installed is False
+ torch_probe.assert_not_called()
+ wheel_builder.assert_not_called()
+ url_probe.assert_not_called()
+ wheel_install.assert_not_called()
+ process_run.assert_not_called()
+
+
def test_install_kernel_uses_prebuilt_wheel(monkeypatch):
# not importable before install, importable after the wheel lands
states = iter([False, True])
@@ -525,6 +576,9 @@ def test_constants_match_training_worker():
pytest.skip(f"training worker not importable here: {exc}")
assert set(ssm_runtime.SSM_MODEL_SUBSTRINGS) == set(tw._SSM_MODEL_SUBSTRINGS)
+ assert set(ssm_runtime.CAUSAL_CONV1D_MODEL_SUBSTRINGS) == set(
+ tw._CAUSAL_CONV1D_MODEL_SUBSTRINGS
+ )
assert ssm_runtime.MAMBA_SSM_PACKAGE_VERSION == tw._MAMBA_SSM_PACKAGE_VERSION
assert ssm_runtime.MAMBA_SSM_RELEASE_TAG == tw._MAMBA_SSM_RELEASE_TAG
assert ssm_runtime.CAUSAL_CONV1D_PACKAGE_VERSION == tw._CAUSAL_CONV1D_PACKAGE_VERSION
@@ -538,9 +592,64 @@ def test_constants_match_training_worker():
"ibm-granite/granite-4.0-h-micro",
"Qwen/Qwen3-Next-80B",
"LiquidAI/LFM2-1.2B",
+ "state-spaces/mamba-2.8b-hf",
+ "ai21labs/Jamba-v0.1",
+ "Zyphra/Zamba2-7B",
+ "ibm/Bamba-9B",
"unsloth/Llama-3.2-1B-Instruct",
"unsloth/Qwen2.5-7B",
):
assert ssm_runtime.model_wants_causal_conv1d(name) == tw._model_wants_causal_conv1d(
name
), name
+
+
+# ── renamed / local checkpoints resolve from the config, not the name ─────────
+
+
+def _write_config(directory: Path, config: dict) -> Path:
+ directory.mkdir(parents = True, exist_ok = True)
+ (directory / "config.json").write_text(json.dumps(config), encoding = "utf-8")
+ return directory
+
+
+def test_renamed_local_checkpoint_resolves_causal_conv1d_from_its_config(tmp_path):
+ """A local Qwen3-Next checkpoint whose folder has no allowlisted substring must
+ still be detected, so the availability hook is installed for it."""
+ checkpoint = _write_config(
+ tmp_path / "my-model",
+ {"model_type": "qwen3_next", "architectures": ["Qwen3NextForCausalLM"]},
+ )
+ target = str(checkpoint)
+
+ # The name-only predicate cannot see it ...
+ assert ssm_runtime.model_wants_causal_conv1d(target) is False
+ # ... but the resolved predicate reads config.json off the local directory.
+ assert ssm_runtime.resolved_model_wants_causal_conv1d(target, target, None) is True
+ # Same for a renamed Hub id pointing at a local snapshot.
+ assert (
+ ssm_runtime.resolved_model_wants_causal_conv1d("acme/internal-llm-v3", target, None) is True
+ )
+
+
+def test_renamed_local_checkpoint_without_ssm_config_stays_off(tmp_path):
+ checkpoint = _write_config(
+ tmp_path / "my-model-llama",
+ {"model_type": "llama", "architectures": ["LlamaForCausalLM"]},
+ )
+ target = str(checkpoint)
+ assert ssm_runtime.resolved_model_wants_causal_conv1d(target, target, None) is False
+
+
+def test_nested_text_config_resolves_causal_conv1d(tmp_path):
+ checkpoint = _write_config(
+ tmp_path / "my-vl-model",
+ {
+ "model_type": "some_vlm",
+ "architectures": ["SomeVlmForConditionalGeneration"],
+ "text_config": {"model_type": "lfm2", "architectures": ["Lfm2ForCausalLM"]},
+ },
+ )
+ target = str(checkpoint)
+ assert ssm_runtime.model_wants_causal_conv1d(target) is False
+ assert ssm_runtime.resolved_model_wants_causal_conv1d(target, target, None) is True
diff --git a/studio/backend/tests/test_third_party_source.py b/studio/backend/tests/test_third_party_source.py
new file mode 100644
index 00000000000..87c915524ce
--- /dev/null
+++ b/studio/backend/tests/test_third_party_source.py
@@ -0,0 +1,876 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import errno
+import hashlib
+import io
+import importlib
+import py_compile
+import shutil
+import stat
+import subprocess
+import sys
+import tarfile
+from dataclasses import replace
+from pathlib import Path
+
+import pytest
+
+import utils.third_party_source as source
+import utils.utils as utils
+
+
+def _run_git(repository: Path, *arguments: str) -> str:
+ if shutil.which("git") is None:
+ pytest.skip("git is required for this test")
+ result = subprocess.run(
+ ["git", "-C", str(repository), *arguments],
+ check = True,
+ capture_output = True,
+ text = True,
+ encoding = "utf-8",
+ )
+ return result.stdout.strip()
+
+
+def _repository(tmp_path: Path) -> tuple[Path, str]:
+ repository = tmp_path / "upstream"
+ (repository / "sparktts" / "models").mkdir(parents = True)
+ (repository / "sparktts" / "utils").mkdir()
+ (repository / "sparktts" / "models" / "__init__.py").write_text("", encoding = "utf-8")
+ (repository / "sparktts" / "utils" / "__init__.py").write_text("", encoding = "utf-8")
+ (repository / ".gitignore").write_text("*.evil.py\n", encoding = "utf-8")
+ tokenizer = repository / "sparktts" / "models" / "audio_tokenizer.py"
+ tokenizer.write_text("VALUE = 'pinned'\n", encoding = "utf-8")
+ (repository / "sparktts" / "models" / "origin_injector.py").write_text(
+ "import sys\n"
+ "from pathlib import Path\n"
+ "from types import ModuleType\n"
+ "injected = ModuleType('sparktts.injected')\n"
+ "injected.__file__ = str(Path(__file__).resolve().parents[2] / 'outside.py')\n"
+ "sys.modules['sparktts.injected'] = injected\n",
+ encoding = "utf-8",
+ )
+ (repository / "sparktts" / "utils" / "audio.py").write_text(
+ "VALUE = 'audio'\n",
+ encoding = "utf-8",
+ )
+ _run_git(repository, "init", "--quiet")
+ _run_git(repository, "config", "user.name", "Test")
+ _run_git(repository, "config", "user.email", "[email protected]")
+ _run_git(repository, "add", ".")
+ _run_git(repository, "commit", "--quiet", "-m", "pinned")
+ pinned = _run_git(repository, "rev-parse", "HEAD")
+ tokenizer.write_text("VALUE = 'newer'\n", encoding = "utf-8")
+ _run_git(repository, "add", ".")
+ _run_git(repository, "commit", "--quiet", "-m", "newer")
+ return repository, pinned
+
+
+def _configure(monkeypatch, tmp_path: Path, repository: Path, revision: str) -> Path:
+ cache = tmp_path / "cache"
+ monkeypatch.setattr(
+ source,
+ "SPARK_TTS_SOURCE",
+ source.PinnedSource(
+ name = "Spark-TTS",
+ package = "sparktts",
+ repository = str(repository),
+ revision = revision,
+ required_files = (
+ "sparktts/models/audio_tokenizer.py",
+ "sparktts/utils/audio.py",
+ ),
+ generated_files = (("sparktts/__init__.py", ""),),
+ ),
+ )
+ monkeypatch.setattr(source, "cache_root", lambda: cache)
+ monkeypatch.setattr(utils, "hf_env_offline", lambda: False)
+ return cache
+
+
+def _sealed_spec(spec, checkout: Path, runtime: Path):
+ return replace(
+ spec,
+ source_tree_digest = source._manifest_digest(
+ source._filesystem_source_manifest(checkout, spec)
+ ),
+ runtime_tree_digest = source._manifest_digest(source._runtime_manifest(runtime, spec)),
+ )
+
+
+def test_manifest_digest_protocol_is_canonical():
+ manifest = {
+ "sparktts/z.py": "0" * 64,
+ "sparktts/a.py": "f" * 64,
+ }
+
+ assert source._manifest_digest(manifest) == (
+ "96ce9c498a9112e52fa1ef4f93e33003c2fdb26e0f1dfdc9408e701ecd66c173"
+ )
+
+
+def _write_source_archive(path: Path, root: str, files: dict[str, bytes]) -> None:
+ with tarfile.open(path, mode = "w:gz") as bundle:
+ for relative, content in files.items():
+ member = tarfile.TarInfo(f"{root}/{relative}")
+ member.size = len(content)
+ bundle.addfile(member, io.BytesIO(content))
+
+
+def test_fresh_sealed_source_installs_from_archive_without_git(monkeypatch, tmp_path):
+ revision = "1" * 40
+ repository = "https://github.com/example/Fixture"
+ root = f"Fixture-{revision}"
+ files = {
+ "README.md": b"not installed\n",
+ "sparktts/models/audio_tokenizer.py": b"VALUE = 'archive'\n",
+ "sparktts/utils/audio.py": b"VALUE = 'audio'\n",
+ }
+ archive = tmp_path / "source.tar.gz"
+ _write_source_archive(archive, root, files)
+ source_manifest = {
+ relative: hashlib.sha256(content).hexdigest()
+ for relative, content in files.items()
+ if relative.startswith("sparktts/")
+ }
+ runtime_manifest = {
+ **source_manifest,
+ "sparktts/__init__.py": hashlib.sha256(b"").hexdigest(),
+ }
+ spec = source.PinnedSource(
+ name = "Fixture",
+ package = "sparktts",
+ repository = repository,
+ revision = revision,
+ required_files = (
+ "sparktts/models/audio_tokenizer.py",
+ "sparktts/utils/audio.py",
+ ),
+ generated_files = (("sparktts/__init__.py", ""),),
+ source_tree_digest = source._manifest_digest(source_manifest),
+ runtime_tree_digest = source._manifest_digest(runtime_manifest),
+ archive_url = archive.as_uri(),
+ )
+ cache = tmp_path / "cache"
+ monkeypatch.setattr(source, "cache_root", lambda: cache)
+ monkeypatch.setattr(utils, "hf_env_offline", lambda: False)
+ monkeypatch.setattr(
+ source,
+ "_git",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ AssertionError("fresh archive provisioning must not invoke Git")
+ ),
+ )
+
+ runtime = source.ensure_pinned_source(spec)
+
+ assert source._valid_runtime(runtime, spec)
+ assert (runtime / "sparktts" / "models" / "audio_tokenizer.py").read_bytes() == (
+ files["sparktts/models/audio_tokenizer.py"]
+ )
+ assert not (runtime / "README.md").exists()
+
+
+def test_archive_download_enforces_deadline_with_read1(monkeypatch, tmp_path):
+ now = [0.0]
+ calls = {"read": 0, "read1": 0, "timeout": None}
+
+ class SlowResponse:
+ headers = {}
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+ def read(self, size):
+ calls["read"] += 1
+ raise AssertionError("read1 must be used when available")
+
+ def read1(self, size):
+ calls["read1"] += 1
+ now[0] += 0.6
+ return b"x"
+
+ def urlopen(request, *, timeout):
+ calls["timeout"] = timeout
+ return SlowResponse()
+
+ spec = source.PinnedSource(
+ name = "Fixture",
+ package = "sparktts",
+ repository = "https://github.com/example/Fixture",
+ revision = "3" * 40,
+ required_files = (),
+ )
+ monkeypatch.setattr(source.time, "monotonic", lambda: now[0])
+ monkeypatch.setattr(source, "_ARCHIVE_DOWNLOAD_DEADLINE_SECONDS", 1)
+ monkeypatch.setattr(source.urllib.request, "urlopen", urlopen)
+
+ with pytest.raises(RuntimeError, match = "Timed out downloading"):
+ source._download_archive("https://example.invalid/archive.tar.gz", tmp_path / "out", spec)
+
+ assert calls == {"read": 0, "read1": 2, "timeout": source._ARCHIVE_SOCKET_TIMEOUT_SECONDS}
+
+
+ ("member_name", "member_type"),
+ (
+ ("Fixture-" + "2" * 40 + "/sparktts/../escape.py", tarfile.REGTYPE),
+ ("Fixture-" + "2" * 40 + "\\sparktts\\escape.py", tarfile.REGTYPE),
+ ("/Fixture-" + "2" * 40 + "/sparktts/escape.py", tarfile.REGTYPE),
+ ("Fixture-" + "2" * 40 + "/sparktts/C:escape.py", tarfile.REGTYPE),
+ ("Fixture-" + "2" * 40 + "/sparktts/link.py", tarfile.SYMTYPE),
+ ),
+)
+def test_source_archive_rejects_unsafe_members(monkeypatch, tmp_path, member_name, member_type):
+ revision = "2" * 40
+ archive = tmp_path / "unsafe.tar.gz"
+ with tarfile.open(archive, mode = "w:gz") as bundle:
+ member = tarfile.TarInfo(member_name)
+ member.type = member_type
+ if member_type == tarfile.REGTYPE:
+ member.size = 1
+ bundle.addfile(member, io.BytesIO(b"x"))
+ else:
+ member.linkname = "target"
+ bundle.addfile(member)
+ spec = source.PinnedSource(
+ name = "Fixture",
+ package = "sparktts",
+ repository = "https://github.com/example/Fixture",
+ revision = revision,
+ required_files = (),
+ source_tree_digest = "0" * 64,
+ runtime_tree_digest = "0" * 64,
+ archive_url = archive.as_uri(),
+ )
+ monkeypatch.setattr(source, "cache_root", lambda: tmp_path / "cache")
+ monkeypatch.setattr(utils, "hf_env_offline", lambda: False)
+
+ with pytest.raises(RuntimeError, match = "archive"):
+ source.ensure_pinned_source(spec)
+
+
+def test_installs_the_exact_revision_instead_of_repository_head(monkeypatch, tmp_path):
+ repository, pinned = _repository(tmp_path)
+ cache = _configure(monkeypatch, tmp_path, repository, pinned)
+
+ installed = source.ensure_spark_tts_source()
+
+ assert (
+ installed == (cache / "third-party-sources" / "Spark-TTS" / pinned / "runtime-v1").resolve()
+ )
+ assert (installed / "sparktts" / "models" / "audio_tokenizer.py").read_text(
+ encoding = "utf-8"
+ ) == "VALUE = 'pinned'\n"
+ checkout = installed.parent / "source"
+ assert not (checkout / "sparktts" / "__init__.py").exists()
+ assert (installed / "sparktts" / "__init__.py").read_bytes() == b""
+ assert _run_git(checkout, "rev-parse", "HEAD") == pinned
+ assert _run_git(checkout, "rev-parse", "--abbrev-ref", "HEAD") == "HEAD"
+
+
+def test_valid_cached_revision_stays_offline(monkeypatch, tmp_path):
+ repository, pinned = _repository(tmp_path)
+ _configure(monkeypatch, tmp_path, repository, pinned)
+ expected = source.ensure_spark_tts_source()
+ checkout = expected.parent / "source"
+ monkeypatch.setattr(
+ source,
+ "SPARK_TTS_SOURCE",
+ _sealed_spec(source.SPARK_TTS_SOURCE, checkout, expected),
+ )
+
+ def reject_git(*args, **kwargs):
+ raise AssertionError("valid sealed runtime must not invoke Git")
+
+ monkeypatch.setattr(source, "_git", reject_git)
+ monkeypatch.setattr(utils, "hf_env_offline", lambda: True)
+
+ assert source.ensure_spark_tts_source() == expected
+
+
+def test_sealed_checkout_reconstructs_runtime_offline_without_git(monkeypatch, tmp_path):
+ repository, pinned = _repository(tmp_path)
+ _configure(monkeypatch, tmp_path, repository, pinned)
+ installed = source.ensure_spark_tts_source()
+ checkout = installed.parent / "source"
+ monkeypatch.setattr(
+ source,
+ "SPARK_TTS_SOURCE",
+ _sealed_spec(source.SPARK_TTS_SOURCE, checkout, installed),
+ )
+ shutil.rmtree(installed)
+ monkeypatch.setattr(utils, "hf_env_offline", lambda: True)
+ monkeypatch.setattr(
+ source,
+ "_git",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ AssertionError("sealed checkout reconstruction must not invoke Git")
+ ),
+ )
+
+ rebuilt = source.ensure_spark_tts_source()
+
+ assert source._valid_runtime(rebuilt, source.SPARK_TTS_SOURCE)
+
+
+def test_exact_legacy_source_migrates_offline_without_git(monkeypatch, tmp_path):
+ repository, pinned = _repository(tmp_path)
+ cache = _configure(monkeypatch, tmp_path, repository, pinned)
+ installed = source.ensure_spark_tts_source()
+ checkout = installed.parent / "source"
+ spec = _sealed_spec(source.SPARK_TTS_SOURCE, checkout, installed)
+ legacy = tmp_path / "Spark-TTS"
+ shutil.copytree(checkout, legacy, ignore = shutil.ignore_patterns(".git"))
+ # The cache holds a real checkout, and Windows will not delete Git's read-only objects.
+ source._remove_owned_path(cache)
+ monkeypatch.setattr(source, "SPARK_TTS_SOURCE", spec)
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setattr(utils, "hf_env_offline", lambda: True)
+ monkeypatch.setattr(
+ source,
+ "_git",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ AssertionError("legacy migration must not invoke Git")
+ ),
+ )
+
+ rebuilt = source.ensure_spark_tts_source()
+
+ assert source._valid_runtime(rebuilt, spec)
+
+
+def test_dirty_cached_revision_fails_closed_offline(monkeypatch, tmp_path):
+ repository, pinned = _repository(tmp_path)
+ _configure(monkeypatch, tmp_path, repository, pinned)
+ installed = source.ensure_spark_tts_source()
+ tokenizer = installed.parent / "source" / "sparktts" / "models" / "audio_tokenizer.py"
+ tokenizer.write_text("VALUE = 'tampered'\n", encoding = "utf-8")
+ monkeypatch.setattr(utils, "hf_env_offline", lambda: True)
+
+ with pytest.raises(RuntimeError, match = "not cached.*offline"):
+ source.ensure_spark_tts_source()
+
+ assert tokenizer.read_text(encoding = "utf-8") == "VALUE = 'tampered'\n"
+
+
+def test_failed_repair_keeps_existing_cache_untouched(monkeypatch, tmp_path):
+ repository, pinned = _repository(tmp_path)
+ _configure(monkeypatch, tmp_path, repository, pinned)
+ installed = source.ensure_spark_tts_source()
+ tokenizer = installed.parent / "source" / "sparktts" / "models" / "audio_tokenizer.py"
+ tokenizer.write_text("VALUE = 'tampered'\n", encoding = "utf-8")
+ real_git = source._git
+
+ def fail_fetch(arguments, **kwargs):
+ if "fetch" in arguments:
+ raise RuntimeError("network failed")
+ return real_git(arguments, **kwargs)
+
+ monkeypatch.setattr(source, "_git", fail_fetch)
+
+ with pytest.raises(RuntimeError, match = "network failed"):
+ source.ensure_spark_tts_source()
+
+ assert tokenizer.read_text(encoding = "utf-8") == "VALUE = 'tampered'\n"
+
+
+def test_ignored_checkout_files_are_rejected_and_never_enter_runtime(monkeypatch, tmp_path):
+ repository, pinned = _repository(tmp_path)
+ _configure(monkeypatch, tmp_path, repository, pinned)
+ installed = source.ensure_spark_tts_source()
+ checkout = installed.parent / "source"
+ ignored = checkout / "sparktts" / "payload.evil.py"
+ ignored.write_text("VALUE = 'untrusted'\n", encoding = "utf-8")
+
+ assert _run_git(checkout, "status", "--porcelain=v1", "--untracked-files=all") == ""
+ assert "sparktts/payload.evil.py" not in source._checkout_manifest(
+ checkout,
+ source.SPARK_TTS_SOURCE,
+ )
+ assert not source._valid_checkout(checkout, source.SPARK_TTS_SOURCE)
+
+ repaired = source.ensure_spark_tts_source()
+
+ assert repaired == installed
+ assert not (repaired / "sparktts" / "payload.evil.py").exists()
+ assert not (checkout / "sparktts" / "payload.evil.py").exists()
+
+
[email protected]("index_flag", ("--assume-unchanged", "--skip-worktree"))
+def test_index_flags_cannot_hide_modified_tracked_source(monkeypatch, tmp_path, index_flag):
+ repository, pinned = _repository(tmp_path)
+ _configure(monkeypatch, tmp_path, repository, pinned)
+ installed = source.ensure_spark_tts_source()
+ checkout = installed.parent / "source"
+ relative = "sparktts/models/audio_tokenizer.py"
+ tokenizer = checkout / relative
+ _run_git(checkout, "update-index", index_flag, relative)
+ tokenizer.write_text("VALUE = 'untrusted'\n", encoding = "utf-8")
+
+ assert _run_git(checkout, "status", "--porcelain=v1", "--untracked-files=all") == ""
+ with pytest.raises(ValueError, match = "does not match.*pinned"):
+ source._checkout_manifest(checkout, source.SPARK_TTS_SOURCE)
+ assert not source._valid_checkout(checkout, source.SPARK_TTS_SOURCE)
+
+ repaired = source.ensure_spark_tts_source()
+
+ assert repaired == installed
+ assert (checkout / relative).read_text(encoding = "utf-8") == "VALUE = 'pinned'\n"
+ assert (repaired / relative).read_text(encoding = "utf-8") == "VALUE = 'pinned'\n"
+
+
+def test_windows_drive_relative_components_are_rejected(monkeypatch, tmp_path):
+ revision = "0" * 40
+ base_spec = source.PinnedSource(
+ name = "Drive-Relative",
+ package = "sparktts",
+ repository = str(tmp_path),
+ revision = revision,
+ required_files = (),
+ )
+ generated_spec = source.PinnedSource(
+ name = base_spec.name,
+ package = base_spec.package,
+ repository = base_spec.repository,
+ revision = base_spec.revision,
+ required_files = (),
+ generated_files = (("sparktts/C:payload.py", ""),),
+ )
+
+ with pytest.raises(ValueError, match = "Invalid generated path"):
+ source._generated_file_contents(generated_spec)
+ with pytest.raises(ValueError, match = "Invalid required path"):
+ source._configured_package_paths(
+ ("sparktts/C:payload.py",),
+ base_spec,
+ kind = "required",
+ )
+ with pytest.raises(ValueError, match = "Invalid omitted path"):
+ source._configured_package_paths(
+ ("sparktts/C:payload.py",),
+ base_spec,
+ kind = "omitted",
+ )
+
+ def drive_relative_tree(*args, **kwargs):
+ return subprocess.CompletedProcess(
+ ["git"],
+ 0,
+ stdout = f"100644 blob {revision}\tsparktts/C:payload.py\0",
+ stderr = "",
+ )
+
+ monkeypatch.setattr(source, "_git", drive_relative_tree)
+ with pytest.raises(ValueError, match = "Invalid tracked path"):
+ source._tracked_package_blobs(tmp_path, base_spec)
+
+
+def test_import_replaces_a_module_from_outside_the_pinned_source(monkeypatch, tmp_path):
+ repository, pinned = _repository(tmp_path)
+ _configure(monkeypatch, tmp_path, repository, pinned)
+ installed = source.ensure_spark_tts_source()
+ untrusted = tmp_path / "untrusted"
+ (untrusted / "sparktts" / "models").mkdir(parents = True)
+ (untrusted / "sparktts" / "__init__.py").write_text("", encoding = "utf-8")
+ (untrusted / "sparktts" / "models" / "__init__.py").write_text("", encoding = "utf-8")
+ (untrusted / "sparktts" / "models" / "audio_tokenizer.py").write_text(
+ "VALUE = 'untrusted'\n",
+ encoding = "utf-8",
+ )
+ sys.path.insert(0, str(untrusted))
+ importlib.invalidate_caches()
+ try:
+ untrusted_module = importlib.import_module("sparktts.models.audio_tokenizer")
+ assert untrusted_module.VALUE == "untrusted"
+
+ pinned_module = source.import_sparktts_module(
+ "sparktts.models.audio_tokenizer",
+ installed,
+ )
+
+ assert pinned_module.VALUE == "pinned"
+ assert Path(pinned_module.__file__).resolve().is_relative_to(installed)
+ finally:
+ while str(untrusted) in sys.path:
+ sys.path.remove(str(untrusted))
+ while str(installed) in sys.path:
+ sys.path.remove(str(installed))
+ for name in list(sys.modules):
+ if name == "sparktts" or name.startswith("sparktts."):
+ sys.modules.pop(name, None)
+
+
+def test_generated_init_prevents_a_later_regular_package_from_taking_over(monkeypatch, tmp_path):
+ repository, pinned = _repository(tmp_path)
+ _configure(monkeypatch, tmp_path, repository, pinned)
+ installed = source.ensure_spark_tts_source()
+ untrusted = tmp_path / "untrusted"
+ marker = tmp_path / "outside-init-executed"
+ (untrusted / "sparktts" / "models").mkdir(parents = True)
+ (untrusted / "sparktts" / "__init__.py").write_text(
+ "from pathlib import Path\n"
+ f"Path({str(marker)!r}).write_text('executed', encoding='utf-8')\n",
+ encoding = "utf-8",
+ )
+ (untrusted / "sparktts" / "models" / "__init__.py").write_text("", encoding = "utf-8")
+ (untrusted / "sparktts" / "models" / "audio_tokenizer.py").write_text(
+ "VALUE = 'untrusted'\n",
+ encoding = "utf-8",
+ )
+ sys.path.insert(0, str(untrusted))
+ importlib.invalidate_caches()
+ try:
+ pinned_module = source.import_sparktts_module(
+ "sparktts.models.audio_tokenizer",
+ installed,
+ )
+
+ assert pinned_module.VALUE == "pinned"
+ assert not marker.exists()
+ finally:
+ while str(untrusted) in sys.path:
+ sys.path.remove(str(untrusted))
+ source.deactivate_pinned_package("sparktts", installed)
+
+
+def test_import_purges_unchecked_bytecode_before_loading(monkeypatch, tmp_path):
+ repository, pinned = _repository(tmp_path)
+ _configure(monkeypatch, tmp_path, repository, pinned)
+ installed = source.ensure_spark_tts_source()
+ tokenizer = installed / "sparktts" / "models" / "audio_tokenizer.py"
+ marker = tmp_path / "unchecked-bytecode-executed"
+ malicious_source = tmp_path / "malicious.py"
+ malicious_source.write_text(
+ "from pathlib import Path\n"
+ f"Path({str(marker)!r}).write_text('executed', encoding='utf-8')\n"
+ "VALUE = 'untrusted'\n",
+ encoding = "utf-8",
+ )
+ bytecode = Path(importlib.util.cache_from_source(str(tokenizer)))
+ bytecode.parent.mkdir(parents = True, exist_ok = True)
+ py_compile.compile(
+ str(malicious_source),
+ cfile = str(bytecode),
+ dfile = str(tokenizer),
+ doraise = True,
+ invalidation_mode = py_compile.PycInvalidationMode.UNCHECKED_HASH,
+ )
+
+ assert source.ensure_spark_tts_source() == installed
+ try:
+ pinned_module = source.import_sparktts_module(
+ "sparktts.models.audio_tokenizer",
+ installed,
+ )
+
+ assert pinned_module.VALUE == "pinned"
+ assert not marker.exists()
+ finally:
+ source.deactivate_pinned_package("sparktts", installed)
+
+
+def test_import_rejects_any_loaded_package_module_from_outside(monkeypatch, tmp_path):
+ repository, pinned = _repository(tmp_path)
+ _configure(monkeypatch, tmp_path, repository, pinned)
+ installed = source.ensure_spark_tts_source()
+
+ with pytest.raises(RuntimeError, match = "sparktts.injected"):
+ source.import_sparktts_module("sparktts.models.origin_injector", installed)
+
+ assert not any(name == "sparktts" or name.startswith("sparktts.") for name in sys.modules)
+ assert str(installed) not in sys.path
+
+
+def test_runtime_overlay_omits_incompatible_outetts_modules(monkeypatch, tmp_path):
+ repository = tmp_path / "outetts-upstream"
+ required = (
+ "outetts/models/config.py",
+ "outetts/utils/preprocessing.py",
+ "outetts/version/v3/audio_processor.py",
+ "outetts/version/v3/prompt_processor.py",
+ )
+ omitted = (
+ "outetts/interface.py",
+ "outetts/models/gguf_model.py",
+ )
+ upstream_only = ("outetts/__init__.py", *omitted)
+ for relative in (*required, *upstream_only):
+ path = repository / relative
+ path.parent.mkdir(parents = True, exist_ok = True)
+ path.write_text(f"SOURCE = {relative!r}\n", encoding = "utf-8")
+ _run_git(repository, "init", "--quiet")
+ _run_git(repository, "config", "user.name", "Test")
+ _run_git(repository, "config", "user.email", "[email protected]")
+ _run_git(repository, "add", ".")
+ _run_git(repository, "commit", "--quiet", "-m", "pinned")
+ revision = _run_git(repository, "rev-parse", "HEAD")
+ cache = tmp_path / "outetts-cache"
+ monkeypatch.setattr(source, "cache_root", lambda: cache)
+ monkeypatch.setattr(utils, "hf_env_offline", lambda: False)
+ spec = source.PinnedSource(
+ name = "OuteTTS",
+ package = "outetts",
+ repository = str(repository),
+ revision = revision,
+ required_files = required,
+ omitted_files = omitted,
+ generated_files = (("outetts/__init__.py", ""),),
+ )
+
+ runtime = source.ensure_pinned_source(spec)
+
+ checkout = runtime.parent / "source"
+ assert all((runtime / relative).is_file() for relative in required)
+ assert all(not (runtime / relative).exists() for relative in omitted)
+ assert (runtime / "outetts" / "__init__.py").read_bytes() == b""
+ assert all((checkout / relative).is_file() for relative in upstream_only)
+ assert (checkout / "outetts" / "__init__.py").read_text(encoding = "utf-8") != ""
+ assert _run_git(checkout, "status", "--porcelain") == ""
+
+
+def _configure_dac_artifact(monkeypatch, tmp_path: Path, payload: bytes) -> Path:
+ hub_cache = tmp_path / "hub"
+ monkeypatch.setattr(source, "_DAC_SIZE", len(payload))
+ monkeypatch.setattr(source, "_DAC_SHA256", hashlib.sha256(payload).hexdigest())
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.active_hf_hub_cache",
+ lambda: str(hub_cache),
+ )
+ return hub_cache
+
+
+def test_dac_weights_use_immutable_revision_and_active_cache(monkeypatch, tmp_path):
+ payload = b"pinned DAC weights"
+ hub_cache = _configure_dac_artifact(monkeypatch, tmp_path, payload)
+ downloaded = tmp_path / "downloaded.pth"
+ downloaded.write_bytes(payload)
+ calls = []
+
+ def download(**kwargs):
+ calls.append(kwargs)
+ return str(downloaded)
+
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", download)
+ monkeypatch.setattr(utils, "hf_env_offline", lambda: False)
+
+ result = source.ensure_dac_speech_weights()
+
+ # The download is installed into the pinned destination, so the next load hits the
+ # fast path instead of re-downloading and re-hashing the artifact.
+ assert result.is_relative_to(hub_cache)
+ assert result.read_bytes() == payload
+ assert calls == [
+ {
+ "repo_id": source._DAC_REPOSITORY,
+ "filename": source._DAC_FILENAME,
+ "revision": source._DAC_REVISION,
+ "cache_dir": str(hub_cache),
+ "local_files_only": False,
+ }
+ ]
+
+
+def test_exact_legacy_dac_weights_migrate_to_active_cache_offline(monkeypatch, tmp_path):
+ payload = b"legacy pinned DAC weights"
+ hub_cache = _configure_dac_artifact(monkeypatch, tmp_path, payload)
+ legacy = tmp_path / "legacy" / source._DAC_FILENAME
+ legacy.parent.mkdir()
+ legacy.write_bytes(payload)
+ monkeypatch.setattr(utils, "hf_env_offline", lambda: True)
+ calls = []
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", lambda **kwargs: calls.append(kwargs))
+
+ result = source.ensure_dac_speech_weights(legacy)
+
+ assert result.is_relative_to(hub_cache)
+ assert result.read_bytes() == payload
+ assert calls == []
+ legacy.write_bytes(b"tampered")
+ assert source.ensure_dac_speech_weights(legacy) == result
+
+
+def test_full_disk_falls_back_to_the_verified_legacy_dac_weights(monkeypatch, tmp_path):
+ """Migrating the 295 MB file is an optimisation, so a hub cache that cannot absorb a
+ second copy must not reject weights that already passed the size and sha256 check."""
+ payload = b"legacy pinned DAC weights"
+ _configure_dac_artifact(monkeypatch, tmp_path, payload)
+ legacy = tmp_path / "legacy" / source._DAC_FILENAME
+ legacy.parent.mkdir()
+ legacy.write_bytes(payload)
+ monkeypatch.setattr(utils, "hf_env_offline", lambda: True)
+
+ def no_space(*args, **kwargs):
+ raise OSError(errno.ENOSPC, "No space left on device")
+
+ monkeypatch.setattr(source, "_install_verified_artifact", no_space)
+
+ result = source.ensure_dac_speech_weights(legacy)
+
+ assert result == legacy.resolve()
+ assert result.read_bytes() == payload
+
+
+def test_default_legacy_dac_path_matches_windows_appdata(monkeypatch, tmp_path):
+ payload = b"Windows legacy DAC weights"
+ hub_cache = _configure_dac_artifact(monkeypatch, tmp_path, payload)
+ appdata = tmp_path / "AppData" / "Roaming"
+ legacy = appdata / "outeai" / "dac" / source._DAC_FILENAME
+ legacy.parent.mkdir(parents = True)
+ legacy.write_bytes(payload)
+ monkeypatch.setattr(source.sys, "platform", "win32")
+ monkeypatch.setenv("APPDATA", str(appdata))
+ calls = []
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", lambda **kwargs: calls.append(kwargs))
+
+ result = source.ensure_dac_speech_weights()
+
+ assert result.is_relative_to(hub_cache)
+ assert result.read_bytes() == payload
+ assert calls == []
+
+
+def test_dac_weight_hash_mismatch_fails_closed(monkeypatch, tmp_path):
+ payload = b"expected"
+ _configure_dac_artifact(monkeypatch, tmp_path, payload)
+ downloaded = tmp_path / "downloaded.pth"
+ downloaded.write_bytes(b"tampered")
+ monkeypatch.setattr(utils, "hf_env_offline", lambda: False)
+ monkeypatch.setattr("huggingface_hub.hf_hub_download", lambda **kwargs: str(downloaded))
+
+ with pytest.raises(RuntimeError, match = "failed integrity validation"):
+ source.ensure_dac_speech_weights(tmp_path / "missing.pth")
+
+
+def test_bytecode_purge_tolerates_a_concurrent_purge(tmp_path):
+ """The runtime tree is shared by the inference and training workers and the purge runs
+ without the install lock, so a __pycache__ vanishing mid-walk must not raise."""
+ package_root = tmp_path / "sparktts"
+ (package_root / "models" / "__pycache__").mkdir(parents = True)
+ (package_root / "models" / "__pycache__" / "a.cpython-313.pyc").write_bytes(b"")
+ (package_root / "stale.pyc").write_bytes(b"")
+
+ real_rmtree = source.shutil.rmtree
+
+ def rmtree_racing_another_worker(path, *args, **kwargs):
+ real_rmtree(path, ignore_errors = True)
+ return real_rmtree(path, *args, **kwargs)
+
+ source.shutil.rmtree = rmtree_racing_another_worker
+ try:
+ source._purge_package_bytecode(package_root)
+ finally:
+ source.shutil.rmtree = real_rmtree
+
+ assert not list(package_root.rglob("*.pyc"))
+
+
+def test_bytecode_purge_fails_closed_when_a_pyc_survives(monkeypatch, tmp_path):
+ """The purge is the only defence against a planted .pyc shadowing a verified .py: the
+ manifest skips __pycache__ and the origin audit reads __file__, which still names the
+ .py. So a .pyc we could not delete must fail the load, not be waved through."""
+ package_root = tmp_path / "sparktts"
+ package_root.mkdir(parents = True)
+ (package_root / "stale.pyc").write_bytes(b"")
+
+ def refuse(*args, **kwargs):
+ raise PermissionError("read-only cache")
+
+ monkeypatch.setattr(source.Path, "unlink", refuse)
+ with pytest.raises(PermissionError):
+ source._purge_package_bytecode(package_root)
+
+
+def test_bytecode_purge_fails_closed_when_a_pycache_dir_survives(monkeypatch, tmp_path):
+ """Same, for the __pycache__ branch, which is the route a planted .pyc actually takes."""
+ package_root = tmp_path / "sparktts"
+ cache_dir = package_root / "__pycache__"
+ cache_dir.mkdir(parents = True)
+ (cache_dir / "payload.cpython-313.pyc").write_bytes(b"")
+
+ def refuse(*args, **kwargs):
+ raise PermissionError("read-only cache")
+
+ monkeypatch.setattr(source.shutil, "rmtree", refuse)
+ with pytest.raises(PermissionError):
+ source._purge_package_bytecode(package_root)
+
+
+def test_git_invocations_opt_into_long_paths(monkeypatch):
+ """Git for Windows enforces MAX_PATH unless told otherwise, and the pinned cache nests a
+ revision, a staging dir and .git/objects under the studio home. Without this the checkout
+ dies with "Filename too long" on a perfectly normal Windows install."""
+ seen = []
+
+ def capture(arguments, **kwargs):
+ seen.append(arguments)
+ # text= tells us which wrapper called: _git decodes for us, _git_bytes does not.
+ stderr = "stop here" if kwargs.get("text") else b"stop here"
+ raise subprocess.CalledProcessError(1, arguments, stderr = stderr)
+
+ monkeypatch.setattr(source.subprocess, "run", capture)
+
+ for call in (
+ lambda: source._git(["status"], source_name = "Spark-TTS"),
+ lambda: source._git_bytes(["cat-file"], source_name = "Spark-TTS", input_data = b""),
+ ):
+ with pytest.raises(RuntimeError):
+ call()
+
+ assert len(seen) == 2
+ for arguments in seen:
+ assert arguments[:3] == ["git", "-c", "core.longpaths=true"], arguments
+
+
+def test_unwritable_hub_cache_still_uses_verified_legacy_dac_weights(monkeypatch, tmp_path):
+ """A read-only or full hub cache must not hide weights we can already verify: the
+ directory and lock are only needed to populate the cache, which is an optimisation."""
+ payload = b"legacy pinned DAC weights"
+ _configure_dac_artifact(monkeypatch, tmp_path, payload)
+ legacy = tmp_path / "legacy" / source._DAC_FILENAME
+ legacy.parent.mkdir()
+ legacy.write_bytes(payload)
+ monkeypatch.setattr(utils, "hf_env_offline", lambda: True)
+
+ def refuse(*args, **kwargs):
+ raise OSError(errno.EACCES, "read-only file system")
+
+ monkeypatch.setattr(source.Path, "mkdir", refuse)
+
+ assert source.ensure_dac_speech_weights(legacy) == legacy.resolve()
+
+
+def test_replacing_a_checkout_clears_read_only_files(tmp_path):
+ """Git marks .git/objects read-only and Windows refuses to delete a read-only file, so
+ replacing a pinned checkout died with WinError 5 there."""
+ tree = tmp_path / "checkout" / ".git" / "objects" / "ab"
+ tree.mkdir(parents = True)
+ blob = tree / "cdef"
+ blob.write_bytes(b"object")
+ blob.chmod(stat.S_IRUSR)
+
+ source._remove_owned_path(tmp_path / "checkout")
+
+ assert not (tmp_path / "checkout").exists()
+
+
+def test_read_only_handler_reraises_when_the_path_is_already_writable(tmp_path):
+ """A locked file (WinError 32 on Windows) is not a read-only problem, so it must surface
+ rather than be retried into a loop."""
+ victim = tmp_path / "locked"
+ victim.write_bytes(b"x")
+
+ def boom(_path):
+ raise PermissionError("in use")
+
+ with pytest.raises(PermissionError):
+ try:
+ boom(victim)
+ except PermissionError as error:
+ source._clear_read_only(boom, str(victim), error)
diff --git a/studio/backend/tests/test_training_cached_start.py b/studio/backend/tests/test_training_cached_start.py
index 132882d1ce5..c1d2fcd9789 100644
--- a/studio/backend/tests/test_training_cached_start.py
+++ b/studio/backend/tests/test_training_cached_start.py
@@ -30,6 +30,7 @@ def _load_route_module(name: str):
spec = importlib.util.spec_from_file_location(name, _BACKEND_ROOT / "routes" / "training.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
+ module._hub_unreachable = lambda: False
return module
@@ -1348,7 +1349,10 @@ def test_stop_route_passes_expected_job_id_to_backend():
stop_training = lambda **kwargs: calls.append(kwargs) or True,
)
- with patch.object(route, "get_training_backend", return_value = backend):
+ with (
+ patch.object(route, "get_training_backend", return_value = backend),
+ patch.object(route.asyncio, "to_thread", _inline_to_thread),
+ ):
response = asyncio.run(
route.stop_training(
route.TrainingStopRequest(
@@ -1363,6 +1367,38 @@ def test_stop_route_passes_expected_job_id_to_backend():
assert calls == [{"save": False, "expected_job_id": "job_old"}]
+def test_stop_route_reports_superseded_job_without_mutation():
+ route = _load_route_module("training_route_superseded_stop")
+ calls: list[dict] = []
+ backend = SimpleNamespace(
+ current_job_id = "job_new",
+ is_training_active = lambda: True,
+ stop_training = lambda **kwargs: calls.append(kwargs) or True,
+ )
+
+ with (
+ patch.object(route, "get_training_backend", return_value = backend),
+ patch.object(route.asyncio, "to_thread", _inline_to_thread),
+ pytest.raises(route.HTTPException) as exc_info,
+ ):
+ asyncio.run(
+ route.stop_training(
+ route.TrainingStopRequest(save = False, expected_job_id = "job_old"),
+ current_subject = "test-user",
+ )
+ )
+
+ assert exc_info.value.status_code == 409
+ assert calls == []
+
+
+def test_stop_request_requires_job_scope():
+ route = _load_route_module("training_route_required_stop_scope")
+
+ with pytest.raises(ValueError):
+ route.TrainingStopRequest(save = True)
+
+
def test_reset_route_reports_superseded_job_without_mutation():
route = _load_route_module("training_route_scoped_reset")
calls: list[str | None] = []
@@ -1372,7 +1408,10 @@ def test_reset_route_reports_superseded_job_without_mutation():
)
)
- with patch.object(route, "get_training_backend", return_value = backend):
+ with (
+ patch.object(route, "get_training_backend", return_value = backend),
+ patch.object(route.asyncio, "to_thread", _inline_to_thread),
+ ):
response = asyncio.run(
route.reset_training(
route.TrainingResetRequest(expected_job_id = "job_old"),
@@ -1384,7 +1423,8 @@ def test_reset_route_reports_superseded_job_without_mutation():
assert calls == ["job_old"]
-def test_reset_route_without_body_uses_unscoped_reset():
+def test_reset_route_without_body_stays_supported():
+ """Pre-rework clients POST /reset with no body; that must keep working when idle."""
route = _load_route_module("training_route_unscoped_reset")
calls: list[str | None] = []
backend = SimpleNamespace(
@@ -1401,6 +1441,30 @@ def test_reset_route_without_body_uses_unscoped_reset():
assert calls == [None]
+def test_unscoped_reset_cannot_touch_a_live_run(monkeypatch):
+ """...but it may not force-terminate a run it cannot prove it owns."""
+ from core.training.training import TrainingBackend
+
+ backend = TrainingBackend.__new__(TrainingBackend)
+ TrainingBackend.__init__(backend)
+ backend.current_job_id = "job_new"
+ backend._cancel_requested = True
+ monkeypatch.setattr(backend, "is_training_active", lambda: True)
+ monkeypatch.setattr(
+ backend, "force_terminate", lambda **_kw: pytest.fail("unscoped reset terminated a run")
+ )
+
+ # A stop was already requested, so this is the pre-rework cancel-then-dismiss flow and
+ # the client may clear its UI. Still no force_terminate: the stub above would fail.
+ assert backend.reset_training_state() == "superseded"
+ assert backend.reset_training_state(expected_job_id = "job_old") == "superseded"
+
+ # No stop requested, so a bodyless reset of a live run is stale: 409, not a 200 that
+ # would tell an older client a running job had been cleared.
+ backend._cancel_requested = False
+ assert backend.reset_training_state() == "active"
+
+
def test_runtime_4bit_resume_reaches_worker_with_source_resource_pins(tmp_path):
route = _load_route_module("training_route_resume_resource_provenance")
model_root = tmp_path / "models--unsloth--test"
@@ -2327,9 +2391,15 @@ def test_worker_security_consent_uses_exact_target_and_base():
snapshot = "/cache/models--org--adapter/snapshots/deadbeef"
consent_targets: list[str] = []
+ consent_kwargs: dict = {}
file_decision = SimpleNamespace(blocked = False)
consent_decision = SimpleNamespace(blocked = False)
+ def evaluate_consent(targets, **kwargs):
+ consent_targets.extend(targets)
+ consent_kwargs.update(kwargs)
+ return consent_decision
+
with (
patch(
"utils.models.model_config.get_base_model_from_lora_identifier",
@@ -2337,7 +2407,9 @@ def test_worker_security_consent_uses_exact_target_and_base():
),
patch(
"utils.security.security_load_subdirs",
- return_value = (),
+ side_effect = lambda target, _token: (
+ ("LLM",) if target in {snapshot, "org/adapter"} else ()
+ ),
),
patch(
"utils.security.evaluate_file_security",
@@ -2345,9 +2417,7 @@ def test_worker_security_consent_uses_exact_target_and_base():
),
patch(
"utils.security.evaluate_remote_code_consent_for_targets",
- side_effect = (
- lambda targets, **kwargs: consent_targets.extend(targets) or consent_decision
- ),
+ side_effect = evaluate_consent,
),
):
result = worker._model_load_security_error(
@@ -2362,6 +2432,10 @@ def test_worker_security_consent_uses_exact_target_and_base():
assert result is None
assert consent_targets == [snapshot, "org/base"]
+ assert consent_kwargs["load_subdirs_by_target"] == {
+ snapshot: ("LLM",),
+ "org/base": (),
+ }
def test_worker_resolves_cached_model_snapshot():
@@ -2771,6 +2845,40 @@ def test_worker_auto_eval_load_failure_warns_and_falls_back(monkeypatch):
assert "eval download failed" in warnings[0]
+def test_worker_auto_eval_excludes_every_split_in_training_instruction(monkeypatch):
+ from core.training import worker
+
+ train = SimpleNamespace(info = SimpleNamespace(splits = None))
+ held_out = list(range(20))
+ calls: list[str] = []
+ config = {
+ "hf_dataset": "org/dataset",
+ "train_split": "train + validation",
+ "eval_split": None,
+ "eval_steps": 0.1,
+ }
+ monkeypatch.setattr(
+ "datasets.get_dataset_split_names",
+ lambda **_kwargs: ["train", "validation", "test"],
+ )
+
+ def load_remote(_repo_id, **kwargs):
+ split = kwargs["split"]
+ calls.append(split)
+ return held_out if split == "test" else train
+
+ dataset, eval_dataset = worker._load_hf_train_and_eval_datasets(
+ config,
+ None,
+ load_remote,
+ lambda _message: None,
+ )
+
+ assert dataset is train
+ assert eval_dataset is held_out
+ assert calls == ["train + validation", "test"]
+
+
def test_worker_cached_auto_eval_without_split_metadata_stays_offline(monkeypatch):
from core.training import worker
diff --git a/studio/backend/tests/test_training_preflight.py b/studio/backend/tests/test_training_preflight.py
index 753a2d4c703..d6bfc4851e4 100644
--- a/studio/backend/tests/test_training_preflight.py
+++ b/studio/backend/tests/test_training_preflight.py
@@ -238,6 +238,22 @@ def test_cached_auto_eval_excludes_training_split():
assert local_calls == []
+def test_cached_auto_eval_excludes_every_split_in_training_instruction():
+ local_calls: list[str] = []
+
+ result = _auto_detect_eval(
+ SimpleNamespace(),
+ "org/dataset",
+ None,
+ available_splits = ["train", "validation", "test"],
+ split_loader = lambda split: local_calls.append(split) or _SizedDataset(20),
+ excluded_split = ("train", "validation"),
+ )
+
+ assert isinstance(result, _SizedDataset)
+ assert local_calls == ["test"]
+
+
def test_cached_auto_eval_propagates_loader_failure_for_exact_resume():
def fail_load(_split):
raise FileNotFoundError("validation")
diff --git a/studio/backend/tests/test_training_start_idempotency.py b/studio/backend/tests/test_training_start_idempotency.py
index 298cbb8743f..9302f7032f0 100644
--- a/studio/backend/tests/test_training_start_idempotency.py
+++ b/studio/backend/tests/test_training_start_idempotency.py
@@ -9,7 +9,11 @@ from types import SimpleNamespace
from unittest.mock import patch
import pytest
-from core.training.training import TrainingBackend
+from core.training.training import (
+ _MAX_START_CANCEL_TOMBSTONES,
+ TrainingBackend,
+ TrainingStartCancellationCapacityError,
+)
from models.training import TrainingStartRequest
@@ -99,6 +103,102 @@ def test_cancel_before_registration_creates_a_start_tombstone():
assert duplicate == cancelled
+def test_cancel_tombstone_survives_later_cancellation_records():
+ backend = TrainingBackend()
+ backend.cancel_start_request("request-before-start")
+
+ for index in range(64):
+ backend.cancel_start_request(f"later-cancellation-{index}")
+
+ reservation, record = backend.reserve_start_request(
+ "request-before-start",
+ "job-must-not-start",
+ )
+
+ assert reservation == "existing"
+ assert record.error_code == "training_start_cancelled"
+
+
+def test_cancel_tombstone_capacity_fails_without_eviction(monkeypatch):
+ import core.training.training as training_module
+
+ monkeypatch.setattr(training_module, "_MAX_START_CANCEL_TOMBSTONES", 2)
+ backend = TrainingBackend()
+ backend.cancel_start_request("request-1")
+ backend.cancel_start_request("request-2")
+
+ with pytest.raises(TrainingStartCancellationCapacityError):
+ backend.cancel_start_request("request-3")
+
+ assert len(backend._start_cancel_tombstones) == 2
+ assert backend.reserve_start_request("request-1", "job-1")[0] == "existing"
+ assert backend.reserve_start_request("request-2", "job-2")[0] == "existing"
+
+
+def test_expired_cancel_tombstone_releases_request_id():
+ backend = TrainingBackend()
+ _, record = backend.cancel_start_request("request-expired")
+ backend._start_cancel_tombstones["request-expired"] = (0.0, record)
+
+ reservation, pending = backend.reserve_start_request("request-expired", "job-new")
+
+ assert reservation == "reserved"
+ assert pending.job_id == "job-new"
+
+
+def test_cancel_tombstone_ttl_refreshes_on_duplicate_cancel(monkeypatch):
+ import core.training.training as training_module
+
+ now = [0.0]
+ monkeypatch.setattr(training_module.time, "monotonic", lambda: now[0])
+ backend = TrainingBackend()
+ backend.cancel_start_request("request-delayed")
+
+ now[0] = 299.0
+ backend.cancel_start_request("request-delayed")
+ now[0] = 301.0
+
+ assert backend.reserve_start_request("request-delayed", "job-must-not-start")[0] == "existing"
+
+
+def test_cancel_tombstone_ttl_refreshes_when_start_arrives(monkeypatch):
+ import core.training.training as training_module
+
+ now = [0.0]
+ monkeypatch.setattr(training_module.time, "monotonic", lambda: now[0])
+ backend = TrainingBackend()
+ backend.cancel_start_request("request-delayed")
+
+ now[0] = 299.0
+ assert backend.reserve_start_request("request-delayed", "job-first-retry")[0] == "existing"
+ now[0] = 301.0
+
+ assert backend.reserve_start_request("request-delayed", "job-second-retry")[0] == "existing"
+
+
+def test_registered_cancel_tombstone_survives_start_request_churn():
+ backend = TrainingBackend()
+ backend.reserve_start_request("request-cancelled", "job-cancelled")
+ backend.cancel_start_request("request-cancelled")
+
+ for index in range(64):
+ request_id = f"later-request-{index}"
+ backend.reserve_start_request(request_id, f"later-job-{index}")
+ backend.resolve_start_request(
+ request_id,
+ state = "rejected",
+ message = "Rejected",
+ )
+
+ reservation, record = backend.reserve_start_request(
+ "request-cancelled",
+ "job-must-not-start",
+ )
+
+ assert reservation == "existing"
+ assert record.error_code == "training_start_cancelled"
+
+
def test_cancel_pending_start_prevents_worker_spawn():
backend = TrainingBackend()
backend.reserve_start_request("request-pending", "job-pending")
@@ -341,6 +441,164 @@ def test_cancel_accepted_start_stops_and_resets_only_its_job(monkeypatch):
assert backend.current_start_request_id is None
[email protected]("failure_stage", ["stop", "reset"])
+def test_cancel_accepted_start_releases_tombstone_capacity_after_failure(
+ monkeypatch, failure_stage
+):
+ import core.training.training as training_module
+
+ monkeypatch.setattr(training_module, "_MAX_START_CANCEL_TOMBSTONES", 1)
+ backend = TrainingBackend()
+ backend.reserve_start_request("request-current", "job-current")
+ backend.resolve_start_request(
+ "request-current",
+ state = "accepted",
+ message = "Training queued",
+ )
+ backend.current_start_request_id = "request-current"
+ backend.current_job_id = "job-current"
+ backend._progress.is_training = True
+
+ def stop_training(**_kwargs):
+ if failure_stage == "stop":
+ raise RuntimeError("stop failed")
+ return True
+
+ def reset_training_state(**_kwargs):
+ if failure_stage == "reset":
+ raise RuntimeError("reset failed")
+ return "reset"
+
+ monkeypatch.setattr(backend, "_stop_training_with_lifecycle_reserved", stop_training)
+ monkeypatch.setattr(backend, "reset_training_state", reset_training_state)
+
+ with pytest.raises(RuntimeError, match = f"{failure_stage} failed"):
+ backend.cancel_start_request("request-current")
+
+ assert backend._start_cancel_tombstone_reservations == {}
+ assert backend.cancel_start_request("request-after-failure")[0] == "cancelled"
+
+
+def test_concurrent_duplicate_cancel_returns_the_cancelled_tombstone(monkeypatch):
+ backend = TrainingBackend()
+ backend.reserve_start_request("request-current", "job-current")
+ backend.resolve_start_request(
+ "request-current",
+ state = "accepted",
+ message = "Training queued",
+ )
+ backend.current_start_request_id = "request-current"
+ backend.current_job_id = "job-current"
+ backend._progress.is_training = True
+ stop_entered = threading.Event()
+ release_stop = threading.Event()
+ results = []
+
+ def stop_training(**_kwargs):
+ stop_entered.set()
+ assert release_stop.wait(timeout = 5)
+ return True
+
+ monkeypatch.setattr(backend, "_stop_training_with_lifecycle_reserved", stop_training)
+ monkeypatch.setattr(backend, "reset_training_state", lambda **_kwargs: "reset")
+
+ first = threading.Thread(
+ target = lambda: results.append(backend.cancel_start_request("request-current")),
+ daemon = True,
+ )
+ second = threading.Thread(
+ target = lambda: results.append(backend.cancel_start_request("request-current")),
+ daemon = True,
+ )
+ first.start()
+ assert stop_entered.wait(timeout = 5)
+ second.start()
+ release_stop.set()
+ first.join(timeout = 5)
+ second.join(timeout = 5)
+
+ assert not first.is_alive()
+ assert not second.is_alive()
+ assert [outcome for outcome, _record in results] == ["cancelled", "cancelled"]
+ assert all(record.error_code == "training_start_cancelled" for _outcome, record in results)
+ assert backend._start_cancel_tombstone_reservations == {}
+
+
+def test_duplicate_cancel_holds_capacity_when_the_first_cancel_fails(monkeypatch):
+ import core.training.training as training_module
+
+ monkeypatch.setattr(training_module, "_MAX_START_CANCEL_TOMBSTONES", 1)
+ backend = TrainingBackend()
+ backend.reserve_start_request("request-current", "job-current")
+ backend.resolve_start_request(
+ "request-current",
+ state = "accepted",
+ message = "Training queued",
+ )
+ backend.current_start_request_id = "request-current"
+ backend.current_job_id = "job-current"
+ backend._progress.is_training = True
+ reset_lock = threading.Lock()
+ reset_calls = 0
+ first_reset_entered = threading.Event()
+ second_reset_entered = threading.Event()
+ first_cancel_finished = threading.Event()
+ allow_second_reset = threading.Event()
+ outcomes = {}
+
+ def reset_training_state(**_kwargs):
+ nonlocal reset_calls
+ with reset_lock:
+ reset_calls += 1
+ call_number = reset_calls
+ if call_number == 1:
+ first_reset_entered.set()
+ assert second_reset_entered.wait(timeout = 5)
+ raise RuntimeError("first reset failed")
+ second_reset_entered.set()
+ assert allow_second_reset.wait(timeout = 5)
+ return "reset"
+
+ def cancel_first():
+ try:
+ backend.cancel_start_request("request-current")
+ except RuntimeError as error:
+ outcomes["first_error"] = str(error)
+ finally:
+ first_cancel_finished.set()
+
+ def cancel_second():
+ outcomes["second"] = backend.cancel_start_request("request-current")
+
+ monkeypatch.setattr(
+ backend,
+ "_stop_training_with_lifecycle_reserved",
+ lambda **_kwargs: True,
+ )
+ monkeypatch.setattr(backend, "reset_training_state", reset_training_state)
+ first = threading.Thread(target = cancel_first, daemon = True)
+ second = threading.Thread(target = cancel_second, daemon = True)
+ first.start()
+ assert first_reset_entered.wait(timeout = 5)
+ second.start()
+ assert second_reset_entered.wait(timeout = 5)
+ assert first_cancel_finished.wait(timeout = 5)
+
+ with pytest.raises(TrainingStartCancellationCapacityError):
+ backend.cancel_start_request("request-filler")
+
+ allow_second_reset.set()
+ first.join(timeout = 5)
+ second.join(timeout = 5)
+
+ assert not first.is_alive()
+ assert not second.is_alive()
+ assert outcomes["first_error"] == "first reset failed"
+ assert outcomes["second"][0] == "cancelled"
+ assert len(backend._start_cancel_tombstones) == 1
+ assert backend._start_cancel_tombstone_reservations == {}
+
+
def test_cancel_rejected_start_still_stops_its_owned_worker(monkeypatch):
backend = TrainingBackend()
backend.reserve_start_request("request-owned", "job-owned")
@@ -588,6 +846,30 @@ def test_cancel_start_route_returns_the_scoped_rejection():
assert response.error_code == "training_start_cancelled"
+def test_cancel_start_route_reports_tombstone_capacity():
+ route = _load_training_route("training_route_cancel_capacity_test")
+
+ def reject_cancel(_start_request_id):
+ raise TrainingStartCancellationCapacityError(
+ "Too many training start cancellations are pending"
+ )
+
+ backend = SimpleNamespace(cancel_start_request = reject_cancel)
+ with (
+ patch.object(route, "get_training_backend", return_value = backend),
+ patch.object(route.asyncio, "to_thread", new = _inline_to_thread),
+ pytest.raises(route.HTTPException) as exc_info,
+ ):
+ asyncio.run(
+ route.cancel_training_start_request(
+ "request-cancel",
+ current_subject = "test-user",
+ )
+ )
+
+ assert exc_info.value.status_code == 429
+
+
def test_cancelled_route_during_spawn_keeps_the_worker_result_authoritative():
route = _load_training_route("training_route_cancelled_start_test")
backend = TrainingBackend()
@@ -673,6 +955,7 @@ def test_cancelled_route_during_spawn_keeps_the_worker_result_authoritative():
with (
patch.object(route, "get_training_backend", return_value = backend),
+ patch.object(route, "_hub_unreachable", return_value = False),
patch.object(route, "_remote_untrainable_model_format", return_value = None),
patch.object(route, "_preflight_hf_dataset_request", new = lambda request: None),
patch.object(route, "load_model_defaults", return_value = {}),
@@ -687,3 +970,96 @@ def test_cancelled_route_during_spawn_keeps_the_worker_result_authoritative():
assert record.state == "accepted"
assert backend.current_job_id == record.job_id
assert backend.is_training_active() is True
+
+
+def test_owner_can_cancel_its_active_start_when_tombstone_capacity_is_full():
+ """Exhausted unknown-request tombstone capacity must not make the currently active
+ start uncancellable: the UI's Stop button routes to /start-requests/{id}/cancel while
+ a start request owns the run, so a 429 there would leave the worker running."""
+ backend = TrainingBackend()
+ backend.reserve_start_request("request-owned", "job-owned")
+ backend.resolve_start_request(
+ "request-owned",
+ state = "accepted",
+ message = "Training queued",
+ )
+ backend.current_start_request_id = "request-owned"
+ backend.current_job_id = "job-owned"
+ backend._progress.is_training = True
+
+ calls = []
+ backend._stop_training_with_lifecycle_reserved = (
+ lambda **kwargs: calls.append(("stop", kwargs)) or True
+ )
+ backend.reset_training_state = (
+ lambda expected_job_id = None: calls.append(("reset", expected_job_id)) or "reset"
+ )
+
+ for index in range(_MAX_START_CANCEL_TOMBSTONES):
+ backend.cancel_start_request(f"unknown-{index}")
+ assert len(backend._start_cancel_tombstones) == _MAX_START_CANCEL_TOMBSTONES
+
+ # Unregistered ids still hit the hard cap ...
+ with pytest.raises(TrainingStartCancellationCapacityError):
+ backend.cancel_start_request("unknown-overflow")
+
+ # ... but the owner of the active start reclaims a slot and really stops the run.
+ outcome, record = backend.cancel_start_request("request-owned")
+
+ assert outcome == "cancelled"
+ assert record.error_code == "training_start_cancelled"
+ assert calls == [
+ ("stop", {"save": False, "expected_job_id": "job-owned"}),
+ ("reset", "job-owned"),
+ ]
+ assert backend.current_start_request_id is None
+ # The owner overshoots the cap by its own slot rather than evicting a live cancellation.
+ assert len(backend._start_cancel_tombstones) <= _MAX_START_CANCEL_TOMBSTONES + 1
+ assert backend._start_cancel_tombstone_reservations == {}
+
+
+def test_owner_cancel_at_capacity_keeps_other_live_cancellations():
+ """Reclaiming a slot by evicting the soonest-expiring tombstone would forget a live
+ cancellation, so a delayed /start for that id could spawn the job we just cancelled.
+ The owner overshoots the cap instead; there is only ever one active start."""
+ backend = TrainingBackend()
+ backend.cancel_start_request("victim-race") # cancel-before-start race
+ backend.reserve_start_request("owner", "job-owner")
+ backend.resolve_start_request("owner", state = "accepted", message = "Training queued")
+ backend.current_start_request_id = "owner"
+ backend.current_job_id = "job-owner"
+ backend._progress.is_training = True
+ backend._stop_training_with_lifecycle_reserved = lambda **kwargs: True
+ backend.reset_training_state = lambda expected_job_id = None: "reset"
+
+ while len(backend._start_cancel_tombstones) < _MAX_START_CANCEL_TOMBSTONES:
+ backend.cancel_start_request(f"unknown-{len(backend._start_cancel_tombstones)}")
+
+ outcome, _ = backend.cancel_start_request("owner")
+
+ assert outcome == "cancelled"
+ assert "victim-race" in backend._start_cancel_tombstones
+ # The delayed start for the cancelled id must not spawn.
+ assert backend.reserve_start_request("victim-race", "job-victim")[0] == "existing"
+ # Unregistered ids keep hitting the hard cap.
+ with pytest.raises(TrainingStartCancellationCapacityError):
+ backend.cancel_start_request("stranger")
+
+
+def test_pending_cancels_cannot_grow_the_tombstone_table_past_the_cap():
+ """Only the owner of the active run gets the over-cap slot. A pending request is not it,
+ so start-then-cancel cannot be repeated to grow the table without bound."""
+ backend = TrainingBackend()
+ for index in range(_MAX_START_CANCEL_TOMBSTONES):
+ backend.cancel_start_request(f"unknown-{index}")
+
+ refused = 0
+ for index in range(50):
+ backend.reserve_start_request(f"pending-{index}", f"job-{index}")
+ try:
+ backend.cancel_start_request(f"pending-{index}")
+ except TrainingStartCancellationCapacityError:
+ refused += 1
+
+ assert refused >= 1
+ assert len(backend._start_cancel_tombstones) <= _MAX_START_CANCEL_TOMBSTONES
diff --git a/studio/backend/tests/test_training_status_terminal.py b/studio/backend/tests/test_training_status_terminal.py
index c9b9a0b949b..a097a0f3735 100644
--- a/studio/backend/tests/test_training_status_terminal.py
+++ b/studio/backend/tests/test_training_status_terminal.py
@@ -15,6 +15,8 @@ import asyncio
import sys
from pathlib import Path
+import pytest
+
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
@@ -24,6 +26,15 @@ import routes.training as rt
from core.training.training import TrainingBackend, TrainingProgress
+async def _inline_to_thread(function, /, *args, **kwargs):
+ return function(*args, **kwargs)
+
+
[email protected](autouse = True)
+def _run_route_helpers_inline(monkeypatch):
+ monkeypatch.setattr(rt.asyncio, "to_thread", _inline_to_thread)
+
+
class _WedgedProc:
"""A worker that reported terminal and then never exits."""
@@ -168,7 +179,12 @@ def test_late_stop_does_not_unfinish_a_completed_run(monkeypatch):
b = _running(monkeypatch)
b._handle_event(dict(_DONE))
- resp = asyncio.run(rt.stop_training(rt.TrainingStopRequest(save = True), current_subject = "t"))
+ resp = asyncio.run(
+ rt.stop_training(
+ rt.TrainingStopRequest(save = True, expected_job_id = "job_1"),
+ current_subject = "t",
+ )
+ )
assert resp.status == "idle"
assert b._should_stop is False
@@ -202,7 +218,12 @@ def test_stop_and_save_losing_the_race_to_the_pump_keeps_the_run_completed(monke
b.stop_training = stop_after_complete
- resp = asyncio.run(rt.stop_training(rt.TrainingStopRequest(save = True), current_subject = "t"))
+ resp = asyncio.run(
+ rt.stop_training(
+ rt.TrainingStopRequest(save = True, expected_job_id = "job_1"),
+ current_subject = "t",
+ )
+ )
assert resp.status == "idle"
assert b._should_stop is False, "a run that finished in the gap must not latch a stop"
assert (b._terminal_finalize_payload or {}).get("status") == "completed"
@@ -214,7 +235,12 @@ def test_stop_and_save_losing_the_race_to_the_pump_keeps_the_run_completed(monke
def test_stop_mid_run_still_works(monkeypatch):
b = _running(monkeypatch)
- resp = asyncio.run(rt.stop_training(rt.TrainingStopRequest(save = True), current_subject = "t"))
+ resp = asyncio.run(
+ rt.stop_training(
+ rt.TrainingStopRequest(save = True, expected_job_id = "job_1"),
+ current_subject = "t",
+ )
+ )
assert resp.status == "stopped"
assert b._should_stop is True
@@ -226,7 +252,12 @@ def test_cancel_mid_run_still_works(monkeypatch):
monkeypatch.setattr(
"storage.studio_db.mark_run_cancel_requested", lambda *a, **k: True, raising = False
)
- resp = asyncio.run(rt.stop_training(rt.TrainingStopRequest(save = False), current_subject = "t"))
+ resp = asyncio.run(
+ rt.stop_training(
+ rt.TrainingStopRequest(save = False, expected_job_id = "job_1"),
+ current_subject = "t",
+ )
+ )
assert resp.status == "stopped"
assert b._cancel_requested is True
diff --git a/studio/backend/tests/test_training_stop_watchdog.py b/studio/backend/tests/test_training_stop_watchdog.py
index f39e52ac3c9..92f4f6fb006 100644
--- a/studio/backend/tests/test_training_stop_watchdog.py
+++ b/studio/backend/tests/test_training_stop_watchdog.py
@@ -412,8 +412,9 @@ def test_finalize_after_escalation_clears_output_dir_on_cancel(monkeypatch):
def test_stop_training_starts_watchdog_only_when_worker_alive(monkeypatch):
# No worker -> nothing to escalate; the watchdog must not spawn.
b = TrainingBackend()
+ b.current_job_id = "job_idle"
b._proc = None
- assert b.stop_training(save = True) is True
+ assert b.stop_training(save = True, expected_job_id = "job_idle") is True
assert b._stop_watchdog is None
@@ -608,13 +609,13 @@ def test_stop_without_save_creates_missing_row_before_signal(monkeypatch):
b = TrainingBackend()
b.current_job_id, b._db_config = "job_missing", {"model_name": "m"}
b._stop_queue = queue.Queue()
- assert b.stop_training(save = False) is True
+ assert b.stop_training(save = False, expected_job_id = "job_missing") is True
assert [run["id"] for run in recs["created"]] == ["job_missing"]
assert b._stop_queue.get_nowait() == {"type": "stop", "save": False}
b._cancel_requested = b._should_stop = False
sys.modules["storage.studio_db"].mark_run_cancel_requested = lambda _run_id: False
- assert b.stop_training(save = False) is False
+ assert b.stop_training(save = False, expected_job_id = "job_missing") is False
assert not b._cancel_requested and b._stop_queue.empty()
new_queue = queue.Queue()
@@ -627,7 +628,7 @@ def test_stop_without_save_creates_missing_row_before_signal(monkeypatch):
return True
sys.modules["storage.studio_db"].mark_run_cancel_requested = _supersede
- assert b.stop_training(save = False) is False
+ assert b.stop_training(save = False, expected_job_id = "job_old") is False
assert not b._cancel_requested and new_queue.empty()
diff --git a/studio/backend/tests/test_training_streaming.py b/studio/backend/tests/test_training_streaming.py
index ddaa36a4213..cb0f244a35f 100644
--- a/studio/backend/tests/test_training_streaming.py
+++ b/studio/backend/tests/test_training_streaming.py
@@ -31,6 +31,8 @@ def _load_route_module(name: str, relative_path: str):
spec = importlib.util.spec_from_file_location(name, _BACKEND_ROOT / relative_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
+ if hasattr(module, "_hub_unreachable"):
+ module._hub_unreachable = lambda: False
return module
@@ -265,7 +267,10 @@ def test_streaming_start_rejects_train_on_completions_before_backend_start():
start_training = lambda **kwargs: pytest.fail("backend should not start"),
)
- with patch.object(training_route, "get_training_backend", return_value = backend):
+ with (
+ patch.object(training_route, "get_training_backend", return_value = backend),
+ patch.object(training_route.asyncio, "to_thread", new = _inline_to_thread),
+ ):
with pytest.raises(HTTPException) as exc_info:
asyncio.run(training_route.start_training(request, current_subject = "test-user"))
@@ -297,7 +302,10 @@ def test_streaming_start_requires_separate_eval_split(eval_split):
start_training = lambda **kwargs: pytest.fail("backend should not start"),
)
- with patch.object(training_route, "get_training_backend", return_value = backend):
+ with (
+ patch.object(training_route, "get_training_backend", return_value = backend),
+ patch.object(training_route.asyncio, "to_thread", new = _inline_to_thread),
+ ):
with pytest.raises(HTTPException) as exc_info:
asyncio.run(training_route.start_training(request, current_subject = "test-user"))
@@ -325,7 +333,10 @@ def test_streaming_start_rejects_missing_max_steps():
start_training = lambda **kwargs: pytest.fail("backend should not start"),
)
- with patch.object(training_route, "get_training_backend", return_value = backend):
+ with (
+ patch.object(training_route, "get_training_backend", return_value = backend),
+ patch.object(training_route.asyncio, "to_thread", new = _inline_to_thread),
+ ):
with pytest.raises(HTTPException) as exc_info:
asyncio.run(training_route.start_training(request, current_subject = "test-user"))
@@ -356,7 +367,10 @@ def test_streaming_start_rejects_embedding_models():
start_training = lambda **kwargs: pytest.fail("backend should not start"),
)
- with patch.object(training_route, "get_training_backend", return_value = backend):
+ with (
+ patch.object(training_route, "get_training_backend", return_value = backend),
+ patch.object(training_route.asyncio, "to_thread", new = _inline_to_thread),
+ ):
with pytest.raises(HTTPException) as exc_info:
asyncio.run(training_route.start_training(request, current_subject = "test-user"))
@@ -513,7 +527,10 @@ def test_training_status_exposes_the_current_start_request_id():
step_history = [],
)
- with patch.object(training_route, "get_training_backend", return_value = backend):
+ with (
+ patch.object(training_route, "get_training_backend", return_value = backend),
+ patch.object(training_route.asyncio, "to_thread", new = _inline_to_thread),
+ ):
status = asyncio.run(training_route.get_training_status(current_subject = "test-user"))
assert status.job_id == "job_test"
@@ -521,7 +538,7 @@ def test_training_status_exposes_the_current_start_request_id():
assert status.warnings == ["Evaluation was disabled."]
-# streaming rejects HF slice syntax in train_split / eval_split
+# streaming requires bare HF split names
@pytest.mark.parametrize(
@@ -529,11 +546,12 @@ def test_training_status_exposes_the_current_start_request_id():
[
("train_split", "train[:50%]"),
("train_split", "train[:20]"),
+ ("train_split", "train + test"),
("eval_split", "validation[:1000]"),
+ ("eval_split", "validation + test"),
],
)
-def test_streaming_rejects_bracketed_split_syntax(field, value):
- # _validate_streaming_splits raises when dataset_streaming=True and a split contains "[".
+def test_streaming_rejects_split_instructions(field, value):
kwargs = {
"model_name": "unsloth/test",
"training_type": "LoRA/QLoRA",
@@ -546,7 +564,7 @@ def test_streaming_rejects_bracketed_split_syntax(field, value):
with pytest.raises(ValidationError) as exc_info:
TrainingStartRequest(**kwargs)
detail = str(exc_info.value)
- assert "slice" in detail.lower() or "bracket" in detail.lower() or "[" in detail
+ assert "plain split name" in detail
# streaming rejects mixed sources (local_datasets)
@@ -575,7 +593,10 @@ def test_streaming_start_rejects_local_datasets():
start_training = lambda **kwargs: pytest.fail("backend should not start"),
)
- with patch.object(training_route, "get_training_backend", return_value = backend):
+ with (
+ patch.object(training_route, "get_training_backend", return_value = backend),
+ patch.object(training_route.asyncio, "to_thread", new = _inline_to_thread),
+ ):
with pytest.raises(HTTPException) as exc_info:
asyncio.run(training_route.start_training(request, current_subject = "test-user"))
diff --git a/studio/backend/tests/test_training_worker_flash_attn.py b/studio/backend/tests/test_training_worker_flash_attn.py
index d136821ea22..6f31f4b8c1c 100644
--- a/studio/backend/tests/test_training_worker_flash_attn.py
+++ b/studio/backend/tests/test_training_worker_flash_attn.py
@@ -32,6 +32,12 @@ not_on_windows = pytest.mark.skipif(
)
[email protected](autouse = True)
+def _clear_offline_environment(monkeypatch):
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
+
+
def _missing_flash_attn_import():
real_import = builtins.__import__
@@ -156,6 +162,56 @@ def test_runtime_flash_attn_skip_env_avoids_all_install_work(monkeypatch):
worker._sp.run.assert_not_called()
[email protected]("offline_variable", ["HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE"])
+def test_wheel_first_install_skips_all_install_work_offline(monkeypatch, offline_variable):
+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)
+ monkeypatch.setenv(offline_variable, "1")
+ monkeypatch.setattr(builtins, "__import__", _missing_module_import("missing_fast_path"))
+ probe = mock.Mock()
+ url_probe = mock.Mock()
+ wheel_install = mock.Mock()
+ process_run = mock.Mock()
+ monkeypatch.setattr(worker, "probe_torch_wheel_env", probe)
+ monkeypatch.setattr(worker, "url_exists", url_probe)
+ monkeypatch.setattr(worker, "install_wheel", wheel_install)
+ monkeypatch.setattr(worker._sp, "run", process_run)
+
+ installed = worker._install_package_wheel_first(
+ event_queue = [],
+ import_name = "missing_fast_path",
+ display_name = "missing-fast-path",
+ pypi_name = "missing-fast-path",
+ pypi_version = "1.0.0",
+ filename_prefix = "missing_fast_path",
+ release_tag = "v1.0.0",
+ release_base_url = "https://example.invalid/releases",
+ )
+
+ assert installed is False
+ probe.assert_not_called()
+ url_probe.assert_not_called()
+ wheel_install.assert_not_called()
+ process_run.assert_not_called()
+
+
+def test_wheel_first_install_uses_existing_package_offline(monkeypatch):
+ monkeypatch.setenv("HF_HUB_OFFLINE", "true")
+ probe = mock.Mock()
+ monkeypatch.setattr(worker, "probe_torch_wheel_env", probe)
+
+ installed = worker._install_package_wheel_first(
+ event_queue = [],
+ import_name = "sys",
+ display_name = "sys",
+ pypi_name = "sys",
+ pypi_version = "1.0.0",
+ )
+
+ assert installed is True
+ probe.assert_not_called()
+
+
@not_on_windows
def test_causal_conv1d_fast_path_preserves_wheel_first_install_args(monkeypatch):
install_mock = mock.Mock(return_value = True)
@@ -280,6 +336,39 @@ def test_flash_linear_attention_skips_for_unrelated_models(monkeypatch):
run_mock.assert_not_called()
+@not_on_windows
+def test_flash_linear_attention_skips_install_offline(monkeypatch):
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ monkeypatch.setattr(worker, "_installed_torch_version_tuple", lambda: (2, 9))
+ monkeypatch.setattr(worker, "_flash_linear_attention_importable", lambda: False)
+ run_mock = mock.Mock()
+ monkeypatch.setattr(worker._sp, "run", run_mock)
+
+ installed = worker._ensure_flash_linear_attention_unconditional(event_queue = [])
+
+ assert installed is False
+ run_mock.assert_not_called()
+
+
+@not_on_windows
+def test_flash_linear_attention_uses_current_install_offline(monkeypatch):
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ monkeypatch.setattr(worker, "_installed_torch_version_tuple", lambda: (2, 9))
+ monkeypatch.setattr(worker, "_flash_linear_attention_importable", lambda: True)
+ monkeypatch.setattr(
+ worker,
+ "_flash_linear_attention_current",
+ lambda already_importable = None: True,
+ )
+ run_mock = mock.Mock()
+ monkeypatch.setattr(worker._sp, "run", run_mock)
+
+ installed = worker._ensure_flash_linear_attention_unconditional(event_queue = [])
+
+ assert installed is True
+ run_mock.assert_not_called()
+
+
def test_flash_linear_attention_skips_for_ssm_only_models(monkeypatch):
# Nemotron-H / Falcon-H1 / Granite-H / LFM2 take the mamba_ssm path,
# never FLA's gated_delta_rule kernels.
@@ -487,6 +576,64 @@ def _force_missing_tilelang_imports(monkeypatch):
monkeypatch.setattr(builtins, "__import__", fake_import)
+def test_tilelang_backend_skips_install_offline(monkeypatch):
+ monkeypatch.setenv("TRANSFORMERS_OFFLINE", "yes")
+ monkeypatch.setattr(worker, "_tilelang_platform_supported", lambda: True)
+ monkeypatch.setattr(worker, "_installed_tvm_ffi_version", lambda: None)
+ monkeypatch.setattr(worker, "_tilelang_importable", lambda: False)
+ run_mock = mock.Mock()
+ monkeypatch.setattr(worker, "_run_pip", run_mock)
+
+ installed = worker._ensure_tilelang_backend_unconditional(event_queue = [])
+
+ assert installed is False
+ run_mock.assert_not_called()
+
+
+def test_tilelang_backend_uses_current_install_offline(monkeypatch):
+ monkeypatch.setenv("TRANSFORMERS_OFFLINE", "yes")
+ monkeypatch.setattr(worker, "_tilelang_platform_supported", lambda: True)
+ monkeypatch.setattr(worker, "_installed_tvm_ffi_version", lambda: "0.1.9")
+ monkeypatch.setattr(worker, "_tilelang_importable", lambda: True)
+ run_mock = mock.Mock()
+ monkeypatch.setattr(worker, "_run_pip", run_mock)
+
+ installed = worker._ensure_tilelang_backend_unconditional(event_queue = [])
+
+ assert installed is True
+ run_mock.assert_not_called()
+
+
+def test_tilelang_backend_disables_broken_runtime_offline(monkeypatch):
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ monkeypatch.delenv("FLA_TILELANG", raising = False)
+ monkeypatch.setattr(worker, "_tilelang_platform_supported", lambda: True)
+ monkeypatch.setattr(worker, "_installed_tvm_ffi_version", lambda: "0.1.11")
+ run_mock = mock.Mock()
+ monkeypatch.setattr(worker, "_run_pip", run_mock)
+
+ installed = worker._ensure_tilelang_backend_unconditional(event_queue = [])
+
+ assert installed is False
+ assert worker.os.environ["FLA_TILELANG"] == "0"
+ run_mock.assert_not_called()
+
+
+def test_tilelang_backend_preserves_offline_user_override(monkeypatch):
+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")
+ monkeypatch.setenv("FLA_TILELANG", "1")
+ monkeypatch.setattr(worker, "_tilelang_platform_supported", lambda: True)
+ monkeypatch.setattr(worker, "_installed_tvm_ffi_version", lambda: "0.1.10")
+ run_mock = mock.Mock()
+ monkeypatch.setattr(worker, "_run_pip", run_mock)
+
+ installed = worker._ensure_tilelang_backend_unconditional(event_queue = [])
+
+ assert installed is False
+ assert worker.os.environ["FLA_TILELANG"] == "1"
+ run_mock.assert_not_called()
+
+
@linux_only
def test_tilelang_backend_installs_pinned_pair_for_qwen3_5(monkeypatch):
_pin_fla_model_types(monkeypatch)
@@ -702,6 +849,28 @@ def _patch_iu_gates(monkeypatch, fla_gate, conv_gate):
monkeypatch.setattr(_iu, "is_causal_conv1d_available", conv_gate)
+def test_hook_leaves_causal_gate_unchanged_for_unrelated_model(monkeypatch):
+ fla_gate = _make_fake_gate(initial_return = True)
+ conv_gate = _make_fake_gate(initial_return = False)
+ _patch_iu_gates(monkeypatch, fla_gate, conv_gate)
+ conv_install = mock.Mock(return_value = True)
+ monkeypatch.setattr(worker, "_install_package_wheel_first", conv_install)
+ monkeypatch.setattr(worker, "_tilelang_importable", lambda: True)
+ monkeypatch.setattr(worker, "_installed_tvm_ffi_version", lambda: "0.1.9")
+ monkeypatch.delenv(worker._FAST_PATH_HOOKS_SKIP_ENV, raising = False)
+
+ worker._install_fast_path_hooks(
+ event_queue = _FakeQueue(),
+ model_name = "unsloth/Llama-3.2-1B-Instruct",
+ )
+
+ from transformers.utils import import_utils as _iu
+
+ assert _iu.is_causal_conv1d_available is conv_gate
+ assert _iu.is_causal_conv1d_available() is False
+ conv_install.assert_not_called()
+
+
@not_on_windows
def test_hook_installs_when_gate_returns_false(monkeypatch):
_pin_fla_model_types(monkeypatch)
@@ -1185,12 +1354,13 @@ def test_run_training_process_eagerly_installs_causal_conv1d_in_normal_mode():
import inspect
src = inspect.getsource(worker.run_training_process)
- # Orchestration block.
- assert "_ensure_causal_conv1d_fast_path(event_queue, model_name)" in src
- assert "_install_fast_path_hooks(event_queue, model_name)" in src
+ # Orchestration block. Match the call, not its formatting, so wrapping the args over
+ # several lines or adding a keyword does not break this.
+ assert "_ensure_causal_conv1d_fast_path(" in src
+ assert "_install_fast_path_hooks(" in src
# Eager causal_conv1d call must come BEFORE the hook-mode if/else, not
# nested inside the `if _FAST_PATH_HOOKS_SKIP_ENV` branch.
- eager_pos = src.find("_ensure_causal_conv1d_fast_path(event_queue, model_name)")
+ eager_pos = src.find("_ensure_causal_conv1d_fast_path(")
skip_check_pos = src.find('os.getenv(_FAST_PATH_HOOKS_SKIP_ENV) == "1"')
assert eager_pos < skip_check_pos, (
"_ensure_causal_conv1d_fast_path must be called BEFORE the hook-mode "
diff --git a/studio/backend/tests/test_validate_model_error.py b/studio/backend/tests/test_validate_model_error.py
index 16edd43f932..a62919f80db 100644
--- a/studio/backend/tests/test_validate_model_error.py
+++ b/studio/backend/tests/test_validate_model_error.py
@@ -27,6 +27,15 @@ import routes.inference as inf # noqa: E402
from models.inference import ValidateModelRequest # noqa: E402
+async def _inline_to_thread(function, /, *args, **kwargs):
+ return function(*args, **kwargs)
+
+
[email protected](autouse = True)
+def _run_route_helpers_inline(monkeypatch):
+ monkeypatch.setattr(inf.asyncio, "to_thread", _inline_to_thread)
+
+
def _provoke(
monkeypatch,
exc: BaseException,
@@ -162,6 +171,44 @@ def test_resolve_loaded_trc_falls_back_to_raw_auto_map(monkeypatch):
assert inf._resolve_loaded_trust_remote_code("org/plain", {}, {}) is False
+ "model_identifier, expected_target",
+ [
+ ("Spark-TTS-0.5B/LLM", "unsloth/Spark-TTS-0.5B"),
+ ("unsloth/Spark-TTS-0.5B", "unsloth/Spark-TTS-0.5B"),
+ ],
+)
+def test_requires_trc_checks_bicodec_load_subdirectory(
+ monkeypatch, model_identifier, expected_target
+):
+ import utils.inference as inference_utils
+ import utils.models.model_config as model_config
+ import utils.security.consent as consent
+
+ calls = []
+ monkeypatch.setattr(inference_utils, "load_inference_config", lambda *_a, **_k: {})
+ monkeypatch.setattr(model_config, "detect_audio_type", lambda *_a, **_k: "bicodec")
+ monkeypatch.setattr(
+ model_config,
+ "load_model_defaults",
+ lambda *_a, **_k: {"audio_type": "bicodec"},
+ )
+
+ def config_has_auto_map(
+ target,
+ token,
+ *,
+ load_subdirs = (),
+ ):
+ calls.append((target, token, load_subdirs))
+ return True
+
+ monkeypatch.setattr(consent, "_config_has_auto_map", config_has_auto_map)
+
+ assert inf._requires_trust_remote_code_for_model(model_identifier, "hf_test") is True
+ assert calls == [(expected_target, "hf_test", ("LLM",))]
+
+
def _drive_validate_lora(monkeypatch, *, adapter_needs_trc, base_needs_trc):
"""Run validate_model for a LoRA adapter whose base resolves, with per-target
trust_remote_code answers; return the response."""
diff --git a/studio/backend/utils/datasets/completion_masking.py b/studio/backend/utils/datasets/completion_masking.py
index c7c4a474e33..10a900aae6c 100644
--- a/studio/backend/utils/datasets/completion_masking.py
+++ b/studio/backend/utils/datasets/completion_masking.py
@@ -3,10 +3,11 @@
"""Completion-only masking policy shared by the CUDA and MLX training paths.
-Decides how train_on_responses_only is applied for a model: chat template
-auto-detection first, manual TEMPLATE_TO_RESPONSES_MAPPER markers as the
-fallback. gpt-oss included: its quantized checkpoints ship a different
-chat template, so only detection from the actual template is reliable.
+Decides how train_on_responses_only is applied for a model: explicit dataset
+markers when requested, otherwise chat template auto-detection with manual
+TEMPLATE_TO_RESPONSES_MAPPER markers as the fallback. gpt-oss included: its
+quantized checkpoints ship a different chat template, so only detection from
+the actual template is reliable.
"""
from .model_mappings import (
@@ -34,9 +35,10 @@ def apply_completion_masking(
num_proc = None,
notify = None,
detect_fn = None,
+ dataset_template = None,
):
- """Apply completion-only masking with auto-detection first and the manual
- template table as fallback.
+ """Apply completion-only masking with an explicit dataset template or
+ auto-detection followed by the manual model-template fallback.
Args:
trainer: The platform trainer (SFTTrainer or MLXTrainer).
@@ -49,6 +51,8 @@ def apply_completion_masking(
detect_fn: Marker detector (tokenizer/processor) -> (instruction_part,
response_part). Defaults to unsloth_zoo's get_chat_template_parts,
which raises loudly when the template cannot be parsed. Test seam.
+ dataset_template: Explicit template-table key for already-rendered
+ dataset text. Bypasses tokenizer marker detection when provided.
Returns:
(trainer, applied): the possibly wrapped trainer and whether masking
@@ -66,6 +70,43 @@ def apply_completion_masking(
if num_proc is not None:
kwargs["num_proc"] = num_proc
+ processor = getattr(trainer, "processing_class", None) or getattr(trainer, "tokenizer", None)
+ if type(processor).__name__ == "TokenizerWrapper":
+ wrapped = getattr(processor, "_tokenizer", None)
+ if wrapped is not None:
+ processor = wrapped
+ inner = getattr(processor, "tokenizer", processor)
+
+ if dataset_template is not None:
+ markers = TEMPLATE_TO_RESPONSES_MAPPER.get(dataset_template)
+ if not markers:
+ raise ValueError(f"Unknown completion masking template: {dataset_template}")
+ has_preset_markers = hasattr(inner, "_unsloth_input_part") and hasattr(
+ inner, "_unsloth_output_part"
+ )
+ if has_preset_markers:
+ previous_instruction = inner._unsloth_input_part
+ previous_response = inner._unsloth_output_part
+ inner._unsloth_input_part = markers["instruction"]
+ inner._unsloth_output_part = markers["response"]
+ try:
+ trainer = train_fn(trainer, **kwargs)
+ finally:
+ inner._unsloth_input_part = previous_instruction
+ inner._unsloth_output_part = previous_response
+ else:
+ trainer = train_fn(
+ trainer,
+ instruction_part = markers["instruction"],
+ response_part = markers["response"],
+ **kwargs,
+ )
+ notify(
+ "info",
+ f"Train on responses only configured with dataset template markers ({dataset_template})",
+ )
+ return trainer, True
+
template, instruction_part, response_part = lookup_manual_markers(model_name)
# gpt-oss goes auto-first: quantized/BF16 checkpoints ship a channel-less
@@ -79,15 +120,6 @@ def apply_completion_masking(
template = "gpt-oss"
instruction_part = markers["instruction"]
response_part = markers["response"]
- processor = getattr(trainer, "processing_class", None) or getattr(trainer, "tokenizer", None)
- # mlx-lm TokenizerWrapper hides underscore attrs, so preset _unsloth_*
- # markers are invisible through it. Unwrap to the real tokenizer (as
- # zoo's MLX resolver does) before the preset check and detection.
- if type(processor).__name__ == "TokenizerWrapper":
- wrapped = getattr(processor, "_tokenizer", None)
- if wrapped is not None:
- processor = wrapped
- inner = getattr(processor, "tokenizer", processor)
if hasattr(inner, "_unsloth_input_part") and hasattr(inner, "_unsloth_output_part"):
# Markers preset on the tokenizer; zoo reuses them on a bare call.
trainer = train_fn(trainer, **kwargs)
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 82ccc27369b..15156140ed6 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -2268,6 +2268,11 @@ def _get_hf_safetensors_total_params(
model_name: str, hf_token: Optional[str] = None
) -> Optional[int]:
try:
+ from utils.utils import hf_env_offline
+
+ if hf_env_offline():
+ return None
+
from huggingface_hub import model_info as hf_model_info
info = hf_model_info(model_name, token = hf_token)
diff --git a/studio/backend/utils/hf_dataset_options.py b/studio/backend/utils/hf_dataset_options.py
new file mode 100644
index 00000000000..fc386028cc0
--- /dev/null
+++ b/studio/backend/utils/hf_dataset_options.py
@@ -0,0 +1,90 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Validation for Hugging Face dataset configuration and split selectors."""
+
+from __future__ import annotations
+
+import re
+import unicodedata
+
+
+MAX_HF_DATASET_OPTION_LENGTH = 128
+HF_DATASET_SPLIT_NAME_PATTERN = re.compile(r"\w+(?:\.\w+)*")
+
+_CONFIG_FORBIDDEN_PATTERN = re.compile(r"[<>:/\\|?*]")
+_SPLIT_BOUNDARY = r"-?[0-9](?:_?[0-9])*%?"
+_SPLIT_PART_PATTERN = re.compile(
+ rf"({HF_DATASET_SPLIT_NAME_PATTERN.pattern})"
+ rf"(?:\[({_SPLIT_BOUNDARY})?:({_SPLIT_BOUNDARY})?\])?"
+ r"(?:\((closest|pct1_dropremainder)\))?"
+)
+
+
+def has_unsafe_hf_dataset_option_characters(value: str) -> bool:
+ return any(unicodedata.category(character) in {"Cc", "Cf", "Cs"} for character in value)
+
+
+def valid_hf_dataset_config_name(value: str, *, allow_empty: bool = False) -> bool:
+ if not value:
+ return allow_empty
+ if len(value) > MAX_HF_DATASET_OPTION_LENGTH:
+ return False
+ if value in {".", ".."} or has_unsafe_hf_dataset_option_characters(value):
+ return False
+ return _CONFIG_FORBIDDEN_PATTERN.search(value) is None
+
+
+def valid_hf_dataset_split_name(value: str) -> bool:
+ return bool(
+ value
+ and len(value) <= MAX_HF_DATASET_OPTION_LENGTH
+ and ".." not in value
+ and HF_DATASET_SPLIT_NAME_PATTERN.fullmatch(value)
+ )
+
+
+def _valid_percent_boundary(value: str | None, percent_mode: bool) -> bool:
+ if not value or not percent_mode:
+ return True
+ return abs(int(value.removesuffix("%").replace("_", ""))) <= 100
+
+
+def hf_dataset_split_instruction_names(value: str) -> tuple[str, ...]:
+ if (
+ not value
+ or len(value) > MAX_HF_DATASET_OPTION_LENGTH
+ or ".." in value
+ or "/" in value
+ or "\\" in value
+ or has_unsafe_hf_dataset_option_characters(value)
+ ):
+ return ()
+
+ names: list[str] = []
+ percent_rounding = None
+ for part in re.split(r"\s*\+\s*", value):
+ match = _SPLIT_PART_PATTERN.fullmatch(part)
+ if match is None:
+ return ()
+ name, start, end, rounding = match.groups()
+ uses_percent = bool((start and start.endswith("%")) or (end and end.endswith("%")))
+ if (
+ not _valid_percent_boundary(start, uses_percent)
+ or not _valid_percent_boundary(end, uses_percent)
+ or (rounding is not None and not uses_percent)
+ ):
+ return ()
+ if uses_percent:
+ effective_rounding = rounding or "closest"
+ if percent_rounding is not None and percent_rounding != effective_rounding:
+ return ()
+ percent_rounding = effective_rounding
+ names.append(name)
+ return tuple(dict.fromkeys(names))
+
+
+def valid_hf_dataset_split_instruction(value: str, *, allow_empty: bool = False) -> bool:
+ if not value:
+ return allow_empty
+ return bool(hf_dataset_split_instruction_names(value))
diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.py
index f6468f6e937..aec15bad6ad 100644
--- a/studio/backend/utils/models/model_config.py
+++ b/studio/backend/utils/models/model_config.py
@@ -2433,13 +2433,11 @@ def list_gguf_variants(
Returns:
(variants, has_vision): non-mmproj GGUF variants + vision flag.
"""
- from huggingface_hub import model_info as hf_model_info
-
- # Offline: skip the API and serve from cache
if _env_offline():
cached = _list_gguf_variants_from_hf_cache(repo_id)
- if cached is not None:
- return cached
+ return cached if cached is not None else ([], False)
+
+ from huggingface_hub import model_info as hf_model_info
try:
info = hf_model_info(repo_id, token = hf_token, files_metadata = True)
@@ -2702,14 +2700,12 @@ def detect_gguf_model_remote(repo_id: str, hf_token: Optional[str] = None) -> Op
silent None would make the caller treat a GGUF-only repo as non-GGUF and
fall through to MLX on Apple Silicon. Offline falls back to the local cache.
"""
+ if _env_offline():
+ return _detect_gguf_from_hf_cache(repo_id)
+
import time
from huggingface_hub import model_info as hf_model_info
- if _env_offline():
- cached = _detect_gguf_from_hf_cache(repo_id)
- if cached is not None:
- return cached
-
last_err: Optional[Exception] = None
for attempt in range(3):
try:
diff --git a/studio/backend/utils/security/__init__.py b/studio/backend/utils/security/__init__.py
index e99b150ced1..4e2b8cf6bd8 100644
--- a/studio/backend/utils/security/__init__.py
+++ b/studio/backend/utils/security/__init__.py
@@ -30,6 +30,7 @@ from utils.security.remote_code_scan import ( # noqa: F401
Finding,
RemoteCodeUnscannable,
ScanResult,
+ remote_code_config_paths,
remote_code_fingerprint,
repo_remote_code_files,
scan_remote_code_files,
@@ -42,6 +43,7 @@ __all__ = [
"repo_remote_code_files",
"RemoteCodeUnscannable",
"remote_code_fingerprint",
+ "remote_code_config_paths",
"should_block_remote_code",
"evaluate_remote_code_consent",
"evaluate_remote_code_consent_for_targets",
@@ -91,6 +93,7 @@ def preflight_remote_code_consent_for_targets(
trust_remote_code: bool = True,
approved_fingerprint = None,
subject = None,
+ load_subdirs_by_target = None,
) -> "RemoteCodeDecision":
"""Preflight consent over multiple repos (a LoRA adapter plus its base) scanned as
one combined unit with a single pinning fingerprint. Wrapper defaulting
@@ -102,6 +105,7 @@ def preflight_remote_code_consent_for_targets(
trust_remote_code = trust_remote_code,
approved_fingerprint = approved_fingerprint,
subject = subject,
+ load_subdirs_by_target = load_subdirs_by_target,
)
diff --git a/studio/backend/utils/security/consent.py b/studio/backend/utils/security/consent.py
index 3eb30fd73f4..a51e213dca8 100644
--- a/studio/backend/utils/security/consent.py
+++ b/studio/backend/utils/security/consent.py
@@ -30,8 +30,8 @@ from utils.security.remote_code_scan import (
CRITICAL,
HIGH,
MEDIUM,
- REMOTE_CODE_CONFIG_FILES,
RemoteCodeUnscannable,
+ remote_code_config_paths,
remote_code_fingerprint,
repo_remote_code_files,
scan_remote_code_files,
@@ -74,12 +74,12 @@ class RemoteCodeDecision:
}
-# trust_remote_code runs auto_map from ANY of these configs (model/tokenizer/processor), so all
-# of them gate consent. The list lives in remote_code_scan so gate and scanner stay in lockstep.
-_REMOTE_CODE_CONFIG_FILES = REMOTE_CODE_CONFIG_FILES
-
-
-def _config_has_auto_map(model_name: str, hf_token: Optional[str] = None) -> Optional[bool]:
+def _config_has_auto_map(
+ model_name: str,
+ hf_token: Optional[str] = None,
+ *,
+ load_subdirs = (),
+) -> Optional[bool]:
"""Whether any config (model/tokenizer/processor) declares an ``auto_map`` the load
would execute. Reads raw JSON with ``hf_token``; returns None when a config is
unreadable (transient/auth) so the caller treats it as "unknown" and scans, False
@@ -95,7 +95,7 @@ def _config_has_auto_map(model_name: str, hf_token: Optional[str] = None) -> Opt
# still ship safetensors + auto_map, so it falls through to the scan.
if _is_direct_gguf_file_ref(model_name):
return False
- configs = _load_remote_code_configs(model_name, hf_token)
+ configs = _load_remote_code_configs(model_name, hf_token, load_subdirs = load_subdirs)
if configs is None:
return None
if not any(bool((cfg or {}).get("auto_map")) for cfg in configs):
@@ -122,7 +122,12 @@ def _is_direct_gguf_file_ref(model_name: str) -> bool:
return name.count("/") >= 2
-def _load_remote_code_configs(model_name: str, hf_token: Optional[str] = None) -> Optional[list]:
+def _load_remote_code_configs(
+ model_name: str,
+ hf_token: Optional[str] = None,
+ *,
+ load_subdirs = (),
+) -> Optional[list]:
"""Read every config that can declare ``auto_map`` (model/tokenizer/processor) as
raw dicts. Returns the configs present (``[]`` when all 404, a definitive "no
auto_map"), or None when one is unreadable (transient/auth) so the caller scans.
@@ -137,8 +142,8 @@ def _load_remote_code_configs(model_name: str, hf_token: Optional[str] = None) -
if is_local_path(model_name):
root = Path(normalize_path(model_name)).expanduser()
configs = []
- for name in _REMOTE_CODE_CONFIG_FILES:
- p = root / name
+ for name in remote_code_config_paths(load_subdirs):
+ p = root.joinpath(*Path(name).parts)
if p.is_file():
configs.append(json.loads(p.read_text(encoding = "utf-8-sig")))
return configs
@@ -148,7 +153,7 @@ def _load_remote_code_configs(model_name: str, hf_token: Optional[str] = None) -
from utils.hf_cache_settings import active_hf_hub_cache
configs = []
- for name in _REMOTE_CODE_CONFIG_FILES:
+ for name in remote_code_config_paths(load_subdirs):
try:
p = hf_hub_download(
repo_id = model_name,
@@ -213,6 +218,7 @@ def evaluate_remote_code_consent_for_targets(
trust_remote_code: bool,
approved_fingerprint: Optional[str] = None,
subject: Optional[str] = None,
+ load_subdirs_by_target = None,
) -> RemoteCodeDecision:
"""Decide whether a ``trust_remote_code=True`` load may proceed, over every repo whose
code the load would execute. A LoRA load runs adapter AND base code, so all targets
@@ -254,12 +260,15 @@ def evaluate_remote_code_consent_for_targets(
# present but unscannable, fail the whole load closed.
combined: dict = {}
has_remote_code = False
+ load_subdirs_by_target = load_subdirs_by_target or {}
for target in targets:
- if _config_has_auto_map(target, hf_token) is False:
+ load_subdirs = tuple(load_subdirs_by_target.get(target, ()))
+ scan_kwargs = {"load_subdirs": load_subdirs} if load_subdirs else {}
+ if _config_has_auto_map(target, hf_token, **scan_kwargs) is False:
continue
has_remote_code = True
try:
- files = repo_remote_code_files(target, hf_token = hf_token)
+ files = repo_remote_code_files(target, hf_token = hf_token, **scan_kwargs)
except RemoteCodeUnscannable:
logger.warning(
"Blocking trust_remote_code load of '%s': remote code present (auto_map) "
diff --git a/studio/backend/utils/security/remote_code_scan.py b/studio/backend/utils/security/remote_code_scan.py
index 42f9d98efec..b624919b419 100644
--- a/studio/backend/utils/security/remote_code_scan.py
+++ b/studio/backend/utils/security/remote_code_scan.py
@@ -24,8 +24,10 @@ import hashlib
import io
import tokenize
import importlib.util
+import os
import pathlib
import re
+import stat
import sys
from dataclasses import dataclass, field
from typing import Optional
@@ -57,6 +59,23 @@ REMOTE_CODE_CONFIG_FILES = (
)
+def remote_code_config_paths(load_subdirs = ()) -> tuple[str, ...]:
+ paths = list(REMOTE_CODE_CONFIG_FILES)
+ for value in dict.fromkeys(load_subdirs):
+ raw = str(value)
+ subdir = pathlib.PurePosixPath(raw)
+ if (
+ not raw
+ or "\\" in raw
+ or subdir.is_absolute()
+ or any(pathlib.PureWindowsPath(part).drive for part in subdir.parts)
+ or any(part in {"", ".", ".."} for part in subdir.parts)
+ ):
+ raise ValueError(f"Invalid remote-code load subdirectory: {value!r}")
+ paths.extend(f"{subdir.as_posix()}/{name}" for name in REMOTE_CODE_CONFIG_FILES)
+ return tuple(paths)
+
+
class RemoteCodeUnscannable(Exception):
"""The repo's executable code could not be fully fetched/listed to scan.
@@ -406,6 +425,14 @@ def _read_python_source(path) -> str:
return data.decode(encoding, errors = "replace")
+def _is_linked_directory(path: pathlib.Path) -> bool:
+ if path.is_symlink():
+ return True
+ attributes = getattr(path.lstat(), "st_file_attributes", 0)
+ reparse_point = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0)
+ return bool(reparse_point and attributes & reparse_point)
+
+
def remote_code_fingerprint(files: dict[str, str]) -> str:
"""Stable sha256 over the (sorted) file contents, for pinning consent."""
h = hashlib.sha256()
@@ -417,8 +444,13 @@ def remote_code_fingerprint(files: dict[str, str]) -> str:
return h.hexdigest()
-def repo_remote_code_files(model_name: str, hf_token: Optional[str] = None) -> dict[str, str]:
- """Download a repo's executable ``.py`` (auto_map targets + modeling/config).
+def repo_remote_code_files(
+ model_name: str,
+ hf_token: Optional[str] = None,
+ *,
+ load_subdirs = (),
+) -> dict[str, str]:
+ """Download every executable ``.py`` in the repo plus external ``auto_map`` targets.
Returns {filename: content}. An EMPTY dict means the repo ships no executable ``.py``
(trust_remote_code is a no-op). Raises ``RemoteCodeUnscannable`` when code is present
@@ -436,22 +468,45 @@ def repo_remote_code_files(model_name: str, hf_token: Optional[str] = None) -> d
if is_local_path(model_name):
root = Path(normalize_path(model_name)).expanduser()
+
# Walk ALL .py, not just the auto_map entry's static import closure. This is
# DELIBERATE (see the remote-branch note): the entry can reach a sibling via
# an absolute import, importlib, or exec, which a relative-import closure
# misses, so closure-only scanning is a real bypass. Broad scan never
# under-scans; the cost is a benign script can over-block, the safe direction
# for an RCE gate (HIGH stays approvable; only CRITICAL hard-blocks).
- for p in root.rglob("*.py"):
- if p.is_file():
+ def raise_walk_error(error):
+ raise error
+
+ for directory, dirnames, filenames in os.walk(
+ root,
+ followlinks = False,
+ onerror = raise_walk_error,
+ ):
+ directory_path = Path(directory)
+ for name in dirnames:
+ child = directory_path / name
+ if _is_linked_directory(child):
+ raise RemoteCodeUnscannable(
+ f"{model_name}: linked directory {child.relative_to(root)} "
+ "could hide executable code"
+ )
+ for name in filenames:
+ if not name.endswith(".py"):
+ continue
+ p = directory_path / name
+ if not p.is_file():
+ raise RemoteCodeUnscannable(
+ f"{model_name}: Python source {p.relative_to(root)} is unreadable"
+ )
files[str(p.relative_to(root))] = _read_python_source(p)
# A local config can still point auto_map at an EXTERNAL Hub repo
# (owner/name--module.Class) that executes on load, so fetch it. Every config
# that can declare auto_map is checked, so a custom processor's external code
# is not missed.
ext_refs = set()
- for name in REMOTE_CODE_CONFIG_FILES:
- p = root / name
+ for name in remote_code_config_paths(load_subdirs):
+ p = root.joinpath(*pathlib.PurePosixPath(name).parts)
if p.is_file():
try:
ext_refs |= _auto_map_refs(json.loads(p.read_text(encoding = "utf-8-sig")))
@@ -468,7 +523,7 @@ def repo_remote_code_files(model_name: str, hf_token: Optional[str] = None) -> d
# (EntryNotFoundError) means the config is absent -> skip; any other failure is
# transient/auth and could hide an auto_map, so fail closed (unscannable).
refs = set()
- for cfg_name in REMOTE_CODE_CONFIG_FILES:
+ for cfg_name in remote_code_config_paths(load_subdirs):
try:
cfg_path = hf_hub_download(
model_name,
@@ -595,7 +650,12 @@ def _auto_map_py(cfg: dict) -> set[str]:
return {fn for repo, fn in _auto_map_refs(cfg) if repo is None}
-def external_auto_map_repos(model_name: str, hf_token: Optional[str] = None) -> set:
+def external_auto_map_repos(
+ model_name: str,
+ hf_token: Optional[str] = None,
+ *,
+ load_subdirs = (),
+) -> set:
"""External Hub repos referenced by any of this model's auto_map configs.
The ``owner/name`` repos ``_add_external_refs`` downloads. The scan route uses this so
@@ -611,8 +671,8 @@ def external_auto_map_repos(model_name: str, hf_token: Optional[str] = None) ->
if is_local_path(model_name):
root = Path(normalize_path(model_name)).expanduser()
- for cfg_name in REMOTE_CODE_CONFIG_FILES:
- p = root / cfg_name
+ for cfg_name in remote_code_config_paths(load_subdirs):
+ p = root.joinpath(*pathlib.PurePosixPath(cfg_name).parts)
if not p.is_file():
continue
try:
@@ -625,7 +685,7 @@ def external_auto_map_repos(model_name: str, hf_token: Optional[str] = None) ->
from huggingface_hub import hf_hub_download
from huggingface_hub.utils import EntryNotFoundError
- for cfg_name in REMOTE_CODE_CONFIG_FILES:
+ for cfg_name in remote_code_config_paths(load_subdirs):
try:
cfg_path = hf_hub_download(
model_name,
diff --git a/studio/backend/utils/ssm_runtime.py b/studio/backend/utils/ssm_runtime.py
index b864e786087..5de02ddc7bd 100644
--- a/studio/backend/utils/ssm_runtime.py
+++ b/studio/backend/utils/ssm_runtime.py
@@ -20,6 +20,7 @@ import shutil
import subprocess
import sys
import threading
+from pathlib import Path
from typing import Any, Callable, Optional
from loggers import get_logger
@@ -69,7 +70,12 @@ CAUSAL_CONV1D_MODEL_SUBSTRINGS = (
"granite-4.0-h",
"granitemoehybrid",
"lfm2",
+ "mamba",
+ "jamba",
+ "zamba",
+ "bamba",
)
+_TRANSFORMERS_CAUSAL_CONV1D_MODEL_TYPE_CACHE: dict[str, bool | None] = {}
def model_is_ssm(model_name: str) -> bool:
@@ -85,6 +91,105 @@ def model_wants_causal_conv1d(model_name: str) -> bool:
return any(sub in name for sub in CAUSAL_CONV1D_MODEL_SUBSTRINGS)
+def _normalized_model_identifier(value: str) -> str:
+ return "".join(
+ character for character in value.lower() if character.isascii() and character.isalnum()
+ )
+
+
+def _transformers_model_type_uses_causal_conv1d(model_type: str) -> bool | None:
+ candidate = model_type.strip().lower().replace("-", "_")
+ if not candidate or any(
+ not (character.isascii() and (character.isalnum() or character == "_"))
+ for character in candidate
+ ):
+ return None
+ if candidate in _TRANSFORMERS_CAUSAL_CONV1D_MODEL_TYPE_CACHE:
+ return _TRANSFORMERS_CAUSAL_CONV1D_MODEL_TYPE_CACHE[candidate]
+
+ result: bool | None = None
+ try:
+ import transformers
+ model_dir = Path(transformers.__file__).parent / "models" / candidate
+ if model_dir.is_dir():
+ for modeling_file in model_dir.glob("modeling_*.py"):
+ try:
+ source = modeling_file.read_text(encoding = "utf-8", errors = "ignore")
+ except OSError:
+ continue
+ result = False
+ if "causal_conv1d" in source:
+ result = True
+ break
+ except Exception as exc:
+ logger.debug("causal-conv1d model-type inspection skipped: %s", exc)
+
+ _TRANSFORMERS_CAUSAL_CONV1D_MODEL_TYPE_CACHE[candidate] = result
+ return result
+
+
+def model_config_wants_causal_conv1d(model_config: dict) -> bool | None:
+ model_types: set[str] = set()
+ architectures: set[str] = set()
+ pending: list[Any] = [model_config]
+ while pending:
+ value = pending.pop()
+ if isinstance(value, dict):
+ model_type = value.get("model_type")
+ if isinstance(model_type, str):
+ model_types.add(model_type)
+ model_architectures = value.get("architectures")
+ if isinstance(model_architectures, (list, tuple)):
+ architectures.update(
+ architecture
+ for architecture in model_architectures
+ if isinstance(architecture, str)
+ )
+ pending.extend(value.values())
+ elif isinstance(value, (list, tuple)):
+ pending.extend(value)
+
+ source_requirements = {
+ _transformers_model_type_uses_causal_conv1d(model_type) for model_type in model_types
+ }
+ if True in source_requirements:
+ return True
+ config_identifiers = model_types | architectures
+ normalized_needles = {
+ _normalized_model_identifier(value) for value in CAUSAL_CONV1D_MODEL_SUBSTRINGS
+ }
+ if any(
+ needle in _normalized_model_identifier(identifier)
+ for identifier in config_identifiers
+ for needle in normalized_needles
+ ):
+ return True
+ if False in source_requirements:
+ return False
+ return None
+
+
+def resolved_model_wants_causal_conv1d(
+ model_name: str, model_load_target: str, hf_token: str | None
+) -> bool:
+ try:
+ from utils.transformers_version import _load_config_json
+ model_config = _load_config_json(model_load_target, hf_token)
+ except Exception as exc:
+ logger.debug("Could not inspect model config for causal-conv1d: %s", exc)
+ model_config = None
+
+ if isinstance(model_config, dict):
+ requirement = model_config_wants_causal_conv1d(model_config)
+ if requirement is not None:
+ logger.info(
+ "causal-conv1d requirement resolved from model architecture: %s",
+ requirement,
+ )
+ return requirement
+ return model_wants_causal_conv1d(model_name)
+
+
def ssm_probe_identifier(model_name: str, base: str | None = None) -> str:
"""The identifier whose architecture decides the SSM kernels.
@@ -173,6 +278,12 @@ def _install_kernel(
logger.info("%s already installed", display_name)
return True
+ from utils.utils import hf_env_offline
+
+ if hf_env_offline():
+ logger.info("Skipping %s installation while offline", display_name)
+ return False
+
env = probe_torch_wheel_env(timeout = 30)
wheel_url = direct_wheel_url(
filename_prefix = import_name,
diff --git a/studio/backend/utils/third_party_source.py b/studio/backend/utils/third_party_source.py
new file mode 100644
index 00000000000..1977603e8ff
--- /dev/null
+++ b/studio/backend/utils/third_party_source.py
@@ -0,0 +1,1107 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import contextlib
+import gzip
+import hashlib
+import importlib
+import json
+import os
+import re
+import shutil
+import stat
+import subprocess
+import sys
+import tarfile
+import tempfile
+import threading
+import time
+import urllib.error
+import urllib.request
+import uuid
+from dataclasses import dataclass
+from pathlib import Path, PureWindowsPath
+from types import ModuleType
+
+from filelock import FileLock, Timeout
+
+from utils.native_path_leases import child_env_without_native_path_secret
+from utils.paths.storage_roots import cache_root
+from utils.subprocess_compat import (
+ windows_hidden_subprocess_kwargs as _windows_hidden_subprocess_kwargs,
+)
+
+
+@dataclass(frozen = True)
+class PinnedSource:
+ name: str
+ package: str
+ repository: str
+ revision: str
+ required_files: tuple[str, ...]
+ omitted_files: tuple[str, ...] = ()
+ generated_files: tuple[tuple[str, str], ...] = ()
+ source_tree_digest: str | None = None
+ runtime_tree_digest: str | None = None
+ archive_url: str | None = None
+
+
+SPARK_TTS_SOURCE = PinnedSource(
+ name = "Spark-TTS",
+ package = "sparktts",
+ repository = "https://github.com/SparkAudio/Spark-TTS",
+ revision = "2f1ea9082400547242641f5271b6f941c9f439d1",
+ required_files = (
+ "sparktts/models/audio_tokenizer.py",
+ "sparktts/utils/audio.py",
+ ),
+ generated_files = (("sparktts/__init__.py", ""),),
+ source_tree_digest = "20ff9f4c9e380b89248b828e9f39ec14572c43ff4a8d87b76190dbb3214b1b27",
+ runtime_tree_digest = "f14510e491a87ab287910e1d3f80e6b3d1bcea91b7f91f3baa45a3181a6993ba",
+ archive_url = (
+ "https://github.com/SparkAudio/Spark-TTS/archive/"
+ "2f1ea9082400547242641f5271b6f941c9f439d1.tar.gz"
+ ),
+)
+
+OUTETTS_SOURCE = PinnedSource(
+ name = "OuteTTS",
+ package = "outetts",
+ repository = "https://github.com/edwko/OuteTTS",
+ revision = "f5eac6e70d792844c6a6959d900a47af2c061a5b",
+ required_files = (
+ "outetts/models/config.py",
+ "outetts/utils/preprocessing.py",
+ "outetts/version/v3/audio_processor.py",
+ "outetts/version/v3/prompt_processor.py",
+ ),
+ omitted_files = (
+ "outetts/interface.py",
+ "outetts/models/gguf_model.py",
+ ),
+ generated_files = (("outetts/__init__.py", ""),),
+ source_tree_digest = "817299085cb018839d37bf43505c9a742188bdb0f6ead8e1ea19a8643f0bb49f",
+ runtime_tree_digest = "b9f878aeb2de4d3ab0a5b1f75a5d04f2a137e4369143099bb24f6d6a41301fab",
+ archive_url = (
+ "https://github.com/edwko/OuteTTS/archive/"
+ "f5eac6e70d792844c6a6959d900a47af2c061a5b.tar.gz"
+ ),
+)
+
+_REVISION_PATTERN = re.compile(r"[0-9a-f]{40}")
+_SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")
+_IMPORT_LOCK = threading.RLock()
+
+_DAC_REPOSITORY = "ibm-research/DAC.speech.v1.0"
+_DAC_REVISION = "1ea7f64cd0678415e2d8c32d67b190722cb9b149"
+_DAC_FILENAME = "weights_24khz_1.5kbps_v1.0.pth"
+_DAC_SIZE = 295731578
+_DAC_SHA256 = "d77ca0b04df942ec64e6a7a162bcac093b1127700acdaec0079f40d32c4405fb"
+
+_ARCHIVE_MAX_DOWNLOAD_BYTES = 32 * 1024 * 1024
+_ARCHIVE_MAX_MEMBERS = 10_000
+_ARCHIVE_MAX_UNCOMPRESSED_BYTES = 128 * 1024 * 1024
+_ARCHIVE_MAX_TAR_BYTES = 160 * 1024 * 1024
+_ARCHIVE_SOCKET_TIMEOUT_SECONDS = 15
+_ARCHIVE_DOWNLOAD_DEADLINE_SECONDS = 300
+
+# Git for Windows still enforces MAX_PATH (260) unless told otherwise, and the pinned cache
+# nests a 40-char revision, a staging dir and .git/objects under the studio home; a
+# venv-inferred home already reaches ~253 chars, so a slightly longer one fails the
+# checkout with "Filename too long". Passed per-invocation so no user config is touched.
+_GIT_LONG_PATHS = ["-c", "core.longpaths=true"]
+
+
+def _git(arguments: list[str], *, source_name: str) -> subprocess.CompletedProcess:
+ env = child_env_without_native_path_secret()
+ env["GIT_TERMINAL_PROMPT"] = "0"
+ env["GIT_LFS_SKIP_SMUDGE"] = "1"
+ env["GIT_NO_REPLACE_OBJECTS"] = "1"
+ try:
+ return subprocess.run(
+ ["git", *_GIT_LONG_PATHS, *arguments],
+ check = True,
+ capture_output = True,
+ text = True,
+ encoding = "utf-8",
+ errors = "replace",
+ timeout = 300,
+ env = env,
+ **_windows_hidden_subprocess_kwargs(),
+ )
+ except FileNotFoundError as error:
+ raise RuntimeError(f"Git is required to install the pinned {source_name} source") from error
+ except subprocess.TimeoutExpired as error:
+ raise RuntimeError(f"Timed out while installing the pinned {source_name} source") from error
+ except subprocess.CalledProcessError as error:
+ detail = (error.stderr or error.stdout or "").strip()
+ message = f"Could not install the pinned {source_name} source"
+ raise RuntimeError(f"{message}: {detail}" if detail else message) from error
+
+
+def _git_bytes(
+ arguments: list[str], *, source_name: str, input_data: bytes
+) -> subprocess.CompletedProcess:
+ env = child_env_without_native_path_secret()
+ env["GIT_TERMINAL_PROMPT"] = "0"
+ env["GIT_LFS_SKIP_SMUDGE"] = "1"
+ env["GIT_NO_REPLACE_OBJECTS"] = "1"
+ try:
+ return subprocess.run(
+ ["git", *_GIT_LONG_PATHS, *arguments],
+ check = True,
+ capture_output = True,
+ input = input_data,
+ timeout = 300,
+ env = env,
+ **_windows_hidden_subprocess_kwargs(),
+ )
+ except FileNotFoundError as error:
+ raise RuntimeError(f"Git is required to install the pinned {source_name} source") from error
+ except subprocess.TimeoutExpired as error:
+ raise RuntimeError(f"Timed out while installing the pinned {source_name} source") from error
+ except subprocess.CalledProcessError as error:
+ detail = (error.stderr or b"").decode("utf-8", errors = "replace").strip()
+ message = f"Could not install the pinned {source_name} source"
+ raise RuntimeError(f"{message}: {detail}" if detail else message) from error
+
+
+def _generated_cache_path(relative: str) -> bool:
+ normalized = relative.replace("\\", "/")
+ return "/__pycache__/" in f"/{normalized}" and normalized.endswith((".pyc", ".pyo"))
+
+
+def _package_path_parts(relative: str, spec: PinnedSource, *, kind: str) -> tuple[str, ...]:
+ normalized = relative.replace("\\", "/")
+ parts = tuple(normalized.split("/"))
+ if (
+ normalized != relative
+ or not normalized
+ or normalized.startswith("/")
+ or any(part in ("", ".", "..") for part in parts)
+ or any(PureWindowsPath(part).drive for part in parts)
+ or parts[0] != spec.package
+ ):
+ raise ValueError(f"Invalid {kind} path for {spec.name}: {relative}")
+ return parts
+
+
+def _configured_package_paths(
+ relatives: tuple[str, ...], spec: PinnedSource, *, kind: str
+) -> tuple[str, ...]:
+ validated = []
+ seen = set()
+ for relative in relatives:
+ _package_path_parts(relative, spec, kind = kind)
+ if relative in seen:
+ raise ValueError(f"Invalid {kind} path for {spec.name}: {relative}")
+ seen.add(relative)
+ validated.append(relative)
+ return tuple(validated)
+
+
+def _generated_file_contents(spec: PinnedSource) -> dict[str, bytes]:
+ generated = {}
+ for relative, content in spec.generated_files:
+ _package_path_parts(relative, spec, kind = "generated")
+ if relative in generated:
+ raise ValueError(f"Invalid generated path for {spec.name}: {relative}")
+ generated[relative] = content.encode("utf-8")
+ return generated
+
+
+def _tracked_package_blobs(checkout: Path, spec: PinnedSource) -> dict[str, str]:
+ output = _git(
+ [
+ "-C",
+ str(checkout),
+ "ls-tree",
+ "-r",
+ "-z",
+ spec.revision,
+ "--",
+ spec.package,
+ ],
+ source_name = spec.name,
+ ).stdout
+ blobs = {}
+ for record in (record for record in output.split("\0") if record):
+ metadata, separator, relative = record.partition("\t")
+ fields = metadata.split(" ")
+ if separator != "\t" or len(fields) != 3:
+ raise ValueError(f"Invalid tracked tree entry for {spec.name}")
+ mode, object_type, object_id = fields
+ _package_path_parts(relative, spec, kind = "tracked")
+ if (
+ mode not in ("100644", "100755")
+ or object_type != "blob"
+ or _REVISION_PATTERN.fullmatch(object_id) is None
+ or relative in blobs
+ ):
+ raise ValueError(f"Invalid tracked tree entry for {spec.name}: {relative}")
+ blobs[relative] = object_id
+ return blobs
+
+
+def _pinned_blob_digests(
+ checkout: Path, object_ids: tuple[str, ...], spec: PinnedSource
+) -> dict[str, str]:
+ unique_object_ids = tuple(dict.fromkeys(object_ids))
+ if not unique_object_ids:
+ return {}
+ result = _git_bytes(
+ ["-C", str(checkout), "cat-file", "--batch"],
+ source_name = spec.name,
+ input_data = "".join(f"{object_id}\n" for object_id in unique_object_ids).encode("ascii"),
+ ).stdout
+ digests = {}
+ offset = 0
+ for expected_object_id in unique_object_ids:
+ header_end = result.find(b"\n", offset)
+ if header_end < 0:
+ raise ValueError(f"Invalid pinned blob data for {spec.name}")
+ fields = result[offset:header_end].split(b" ")
+ if len(fields) != 3:
+ raise ValueError(f"Invalid pinned blob data for {spec.name}")
+ object_id, object_type, size_value = fields
+ try:
+ size = int(size_value)
+ except ValueError as error:
+ raise ValueError(f"Invalid pinned blob data for {spec.name}") from error
+ content_start = header_end + 1
+ content_end = content_start + size
+ if (
+ object_id.decode("ascii", errors = "replace") != expected_object_id
+ or object_type != b"blob"
+ or size < 0
+ or content_end >= len(result)
+ or result[content_end : content_end + 1] != b"\n"
+ ):
+ raise ValueError(f"Invalid pinned blob data for {spec.name}")
+ digests[expected_object_id] = hashlib.sha256(result[content_start:content_end]).hexdigest()
+ offset = content_end + 1
+ if offset != len(result):
+ raise ValueError(f"Invalid pinned blob data for {spec.name}")
+ return digests
+
+
+def _package_file(root: Path, relative: str, spec: PinnedSource) -> Path:
+ parts = _package_path_parts(relative, spec, kind = "tracked")
+ path = root.joinpath(*parts)
+ current = root
+ for part in parts:
+ current = current / part
+ if current.is_symlink():
+ raise ValueError(f"Symlinks are not allowed in {spec.name} source")
+ if not path.is_file():
+ raise ValueError(f"Missing tracked file in {spec.name} source: {relative}")
+ return path
+
+
+def _checkout_manifest(checkout: Path, spec: PinnedSource) -> dict[str, str]:
+ package_root = checkout / spec.package
+ if package_root.is_symlink() or not package_root.is_dir():
+ raise ValueError(f"Missing {spec.package} package")
+ omitted = _configured_package_paths(spec.omitted_files, spec, kind = "omitted")
+ excluded = set(omitted) | set(_generated_file_contents(spec))
+ tracked_blobs = _tracked_package_blobs(checkout, spec)
+ pinned_digests = _pinned_blob_digests(
+ checkout,
+ tuple(tracked_blobs.values()),
+ spec,
+ )
+ manifest = {}
+ for relative, object_id in tracked_blobs.items():
+ path = _package_file(checkout, relative, spec)
+ digest = hashlib.sha256(path.read_bytes()).hexdigest()
+ if digest != pinned_digests[object_id]:
+ raise ValueError(f"Tracked file does not match the pinned {spec.name} blob: {relative}")
+ if relative not in excluded:
+ manifest[relative] = digest
+ return manifest
+
+
+def _manifest_digest(manifest: dict[str, str]) -> str:
+ payload = json.dumps(
+ manifest,
+ sort_keys = True,
+ separators = (",", ":"),
+ ).encode("utf-8")
+ return hashlib.sha256(payload).hexdigest()
+
+
+def _filesystem_source_manifest(source: Path, spec: PinnedSource) -> dict[str, str]:
+ if source.is_symlink() or not source.is_dir():
+ raise ValueError(f"Missing {spec.name} source")
+ package_root = source / spec.package
+ if package_root.is_symlink() or not package_root.is_dir():
+ raise ValueError(f"Missing {spec.package} package")
+ excluded = set(_configured_package_paths(spec.omitted_files, spec, kind = "omitted")) | set(
+ _generated_file_contents(spec)
+ )
+ manifest = {}
+ for path in sorted(package_root.rglob("*")):
+ relative = path.relative_to(source).as_posix()
+ if path.is_symlink():
+ raise ValueError(f"Symlinks are not allowed in {spec.name} source")
+ if path.is_dir() or _generated_cache_path(relative):
+ continue
+ if not path.is_file():
+ raise ValueError(f"Special files are not allowed in {spec.name} source")
+ if relative not in excluded:
+ manifest[relative] = hashlib.sha256(path.read_bytes()).hexdigest()
+ return manifest
+
+
+def _sealed_source_manifest(source: Path, spec: PinnedSource) -> dict[str, str] | None:
+ if spec.source_tree_digest is None:
+ return None
+ try:
+ manifest = _filesystem_source_manifest(source, spec)
+ except (OSError, ValueError):
+ return None
+ if _manifest_digest(manifest) != spec.source_tree_digest:
+ return None
+ return manifest
+
+
+def _runtime_manifest(runtime: Path, spec: PinnedSource) -> dict[str, str]:
+ package_root = runtime / spec.package
+ if package_root.is_symlink() or not package_root.is_dir():
+ raise ValueError(f"Missing {spec.package} package")
+ manifest = {}
+ for path in sorted(package_root.rglob("*")):
+ relative = path.relative_to(runtime).as_posix()
+ if path.is_symlink():
+ raise ValueError(f"Symlinks are not allowed in {spec.name} runtime source")
+ if path.is_dir() or _generated_cache_path(relative):
+ continue
+ if not path.is_file():
+ raise ValueError(f"Special files are not allowed in {spec.name} runtime source")
+ manifest[relative] = hashlib.sha256(path.read_bytes()).hexdigest()
+ return manifest
+
+
+def _expected_runtime_manifest(checkout: Path, spec: PinnedSource) -> dict[str, str]:
+ manifest = _checkout_manifest(checkout, spec)
+ for relative, content in _generated_file_contents(spec).items():
+ manifest[relative] = hashlib.sha256(content).hexdigest()
+ return manifest
+
+
+def _valid_checkout(path: Path, spec: PinnedSource) -> bool:
+ if path.is_symlink() or not path.is_dir():
+ return False
+ try:
+ required_files = _configured_package_paths(
+ spec.required_files,
+ spec,
+ kind = "required",
+ )
+ for relative in required_files:
+ required = path.joinpath(*_package_path_parts(relative, spec, kind = "required"))
+ if required.is_symlink() or not required.is_file():
+ return False
+ head = (
+ _git(
+ ["-C", str(path), "rev-parse", "HEAD"],
+ source_name = spec.name,
+ )
+ .stdout.strip()
+ .lower()
+ )
+ branch = _git(
+ ["-C", str(path), "rev-parse", "--abbrev-ref", "HEAD"],
+ source_name = spec.name,
+ ).stdout.strip()
+ origin = _git(
+ ["-C", str(path), "remote", "get-url", "origin"],
+ source_name = spec.name,
+ ).stdout.strip()
+ status = _git(
+ ["-C", str(path), "status", "--porcelain=v1", "--untracked-files=all"],
+ source_name = spec.name,
+ ).stdout
+ ignored = _git(
+ ["-C", str(path), "ls-files", "--others", "--ignored", "--exclude-standard", "-z"],
+ source_name = spec.name,
+ ).stdout
+ _checkout_manifest(path, spec)
+ except (OSError, RuntimeError, ValueError):
+ return False
+ return (
+ head == spec.revision
+ and branch == "HEAD"
+ and origin.rstrip("/").removesuffix(".git")
+ == spec.repository.rstrip("/").removesuffix(".git")
+ and not status
+ and not ignored
+ )
+
+
+def _clear_read_only(function, path, _error) -> None:
+ # Git marks .git/objects read-only, and Windows refuses to delete a read-only file, so
+ # replacing a checkout dies with WinError 5. Only retry when the path really is not
+ # writable: an open handle (WinError 32) must still surface rather than spin.
+ if os.access(path, os.W_OK):
+ raise
+ os.chmod(path, os.stat(path).st_mode | stat.S_IWRITE)
+ function(path)
+
+
+def _remove_owned_path(path: Path) -> None:
+ if path.is_symlink() or path.is_file():
+ path.unlink(missing_ok = True)
+ elif path.is_dir():
+ # onexc replaced onerror in 3.12; the handler signature is the same either way.
+ handler = (
+ {"onexc": _clear_read_only}
+ if sys.version_info >= (3, 12)
+ else {"onerror": _clear_read_only}
+ )
+ shutil.rmtree(path, **handler)
+
+
+def _replace_owned_directory(staging: Path, destination: Path) -> None:
+ displaced = None
+ if destination.exists() or destination.is_symlink():
+ displaced = destination.with_name(f".{destination.name}.invalid-{uuid.uuid4().hex}")
+ os.replace(destination, displaced)
+ try:
+ os.replace(staging, destination)
+ except Exception:
+ if displaced is not None and not destination.exists():
+ os.replace(displaced, destination)
+ displaced = None
+ raise
+ finally:
+ if displaced is not None:
+ _remove_owned_path(displaced)
+
+
+def _install_checkout(destination: Path, spec: PinnedSource) -> None:
+ workspace = Path(tempfile.mkdtemp(prefix = ".source-", dir = destination.parent))
+ checkout = workspace / "checkout"
+ hooks = workspace / "hooks"
+ hooks.mkdir()
+ hook_config = f"core.hooksPath={hooks}"
+ try:
+ _git(["init", "--quiet", str(checkout)], source_name = spec.name)
+ _git(
+ ["-C", str(checkout), "config", "core.autocrlf", "false"],
+ source_name = spec.name,
+ )
+ _git(
+ ["-C", str(checkout), "remote", "add", "origin", spec.repository],
+ source_name = spec.name,
+ )
+ _git(
+ [
+ "-c",
+ hook_config,
+ "-C",
+ str(checkout),
+ "fetch",
+ "--quiet",
+ "--depth=1",
+ "--no-tags",
+ "origin",
+ spec.revision,
+ ],
+ source_name = spec.name,
+ )
+ fetched = (
+ _git(
+ ["-C", str(checkout), "rev-parse", "FETCH_HEAD^{commit}"],
+ source_name = spec.name,
+ )
+ .stdout.strip()
+ .lower()
+ )
+ if fetched != spec.revision:
+ raise RuntimeError(f"{spec.name} returned a different revision than the pinned source")
+ _git(
+ [
+ "-c",
+ hook_config,
+ "-C",
+ str(checkout),
+ "checkout",
+ "--quiet",
+ "--detach",
+ spec.revision,
+ ],
+ source_name = spec.name,
+ )
+ if not _valid_checkout(checkout, spec):
+ raise RuntimeError(f"The downloaded {spec.name} source failed integrity validation")
+ _replace_owned_directory(checkout, destination)
+ finally:
+ _remove_owned_path(workspace)
+
+
+def _archive_root_name(spec: PinnedSource) -> str:
+ repository_name = spec.repository.rstrip("/").rsplit("/", 1)[-1].removesuffix(".git")
+ if not repository_name:
+ raise RuntimeError(f"Invalid pinned {spec.name} repository")
+ return f"{repository_name}-{spec.revision}"
+
+
+def _download_archive(url: str, destination: Path, spec: PinnedSource) -> None:
+ request = urllib.request.Request(url, headers = {"User-Agent": "Unsloth-Studio"})
+ deadline = time.monotonic() + _ARCHIVE_DOWNLOAD_DEADLINE_SECONDS
+ try:
+ if time.monotonic() >= deadline:
+ raise RuntimeError(f"Timed out downloading the pinned {spec.name} source archive")
+ with urllib.request.urlopen(
+ request,
+ timeout = _ARCHIVE_SOCKET_TIMEOUT_SECONDS,
+ ) as response:
+ if time.monotonic() >= deadline:
+ raise RuntimeError(f"Timed out downloading the pinned {spec.name} source archive")
+ content_length = response.headers.get("Content-Length")
+ if content_length is not None:
+ try:
+ advertised_size = int(content_length)
+ except ValueError as error:
+ raise RuntimeError(f"Invalid {spec.name} archive response size") from error
+ if advertised_size < 0 or advertised_size > _ARCHIVE_MAX_DOWNLOAD_BYTES:
+ raise RuntimeError(f"The pinned {spec.name} archive is too large")
+ total = 0
+ read_chunk = getattr(response, "read1", None)
+ if not callable(read_chunk):
+ read_chunk = response.read
+ with destination.open("wb") as handle:
+ while True:
+ if time.monotonic() >= deadline:
+ raise RuntimeError(
+ f"Timed out downloading the pinned {spec.name} source archive"
+ )
+ chunk = read_chunk(1024 * 1024)
+ if time.monotonic() >= deadline:
+ raise RuntimeError(
+ f"Timed out downloading the pinned {spec.name} source archive"
+ )
+ if not chunk:
+ break
+ total += len(chunk)
+ if total > _ARCHIVE_MAX_DOWNLOAD_BYTES:
+ raise RuntimeError(f"The pinned {spec.name} archive is too large")
+ handle.write(chunk)
+ except RuntimeError:
+ raise
+ except (OSError, urllib.error.URLError) as error:
+ raise RuntimeError(f"Could not download the pinned {spec.name} source archive") from error
+
+
+def _archive_member_parts(member: tarfile.TarInfo, spec: PinnedSource) -> tuple[str, ...]:
+ name = member.name[:-1] if member.isdir() and member.name.endswith("/") else member.name
+ parts = tuple(name.split("/"))
+ if (
+ not name
+ or name.startswith("/")
+ or "\\" in name
+ or any(part in ("", ".", "..") for part in parts)
+ or any(PureWindowsPath(part).drive for part in parts)
+ or parts[0] != _archive_root_name(spec)
+ ):
+ raise RuntimeError(f"Invalid path in the pinned {spec.name} source archive")
+ return parts
+
+
+class _BoundedArchiveReader:
+ def __init__(self, handle, limit: int):
+ self._handle = handle
+ self._limit = limit
+ self._read = 0
+
+ def read(self, size: int = -1) -> bytes:
+ remaining = self._limit - self._read
+ requested = remaining + 1 if size < 0 else min(size, remaining + 1)
+ data = self._handle.read(requested)
+ self._read += len(data)
+ if self._read > self._limit:
+ raise RuntimeError("The pinned source archive expands too large")
+ return data
+
+
+def _install_archive_source(destination: Path, spec: PinnedSource) -> None:
+ if spec.archive_url is None or spec.source_tree_digest is None:
+ raise RuntimeError(f"The pinned {spec.name} source archive is not configured")
+ workspace = Path(tempfile.mkdtemp(prefix = ".archive-", dir = destination.parent))
+ archive = workspace / "source.tar.gz"
+ staging = workspace / "source"
+ staging.mkdir()
+ try:
+ _download_archive(spec.archive_url, archive, spec)
+ member_count = 0
+ uncompressed_bytes = 0
+ extracted = set()
+ try:
+ with archive.open("rb") as compressed:
+ with gzip.GzipFile(fileobj = compressed, mode = "rb") as decompressed:
+ reader = _BoundedArchiveReader(decompressed, _ARCHIVE_MAX_TAR_BYTES)
+ with tarfile.open(fileobj = reader, mode = "r|") as bundle:
+ for member in bundle:
+ member_count += 1
+ if member_count > _ARCHIVE_MAX_MEMBERS:
+ raise RuntimeError(
+ f"The pinned {spec.name} archive has too many entries"
+ )
+ parts = _archive_member_parts(member, spec)
+ if member.isdir():
+ continue
+ if not member.isfile() or member.size < 0:
+ raise RuntimeError(
+ f"The pinned {spec.name} archive contains a non-regular file"
+ )
+ uncompressed_bytes += member.size
+ if uncompressed_bytes > _ARCHIVE_MAX_UNCOMPRESSED_BYTES:
+ raise RuntimeError(
+ f"The pinned {spec.name} archive expands too large"
+ )
+ if len(parts) < 3 or parts[1] != spec.package:
+ continue
+ relative = "/".join(parts[1:])
+ _package_path_parts(relative, spec, kind = "archive")
+ if relative in extracted:
+ raise RuntimeError(
+ f"The pinned {spec.name} archive contains duplicate files"
+ )
+ extracted.add(relative)
+ source_file = bundle.extractfile(member)
+ if source_file is None:
+ raise RuntimeError(
+ f"The pinned {spec.name} archive contains an unreadable file"
+ )
+ destination_file = staging.joinpath(*parts[1:])
+ destination_file.parent.mkdir(parents = True, exist_ok = True)
+ remaining = member.size
+ with source_file, destination_file.open("wb") as handle:
+ while remaining:
+ chunk = source_file.read(min(1024 * 1024, remaining))
+ if not chunk:
+ raise RuntimeError(
+ f"The pinned {spec.name} archive ended unexpectedly"
+ )
+ handle.write(chunk)
+ remaining -= len(chunk)
+ except (tarfile.TarError, EOFError, OSError) as error:
+ raise RuntimeError(f"The pinned {spec.name} source archive is invalid") from error
+ if _sealed_source_manifest(staging, spec) is None:
+ raise RuntimeError(f"The pinned {spec.name} source archive failed integrity validation")
+ _replace_owned_directory(staging, destination)
+ finally:
+ _remove_owned_path(workspace)
+
+
+def _valid_runtime(
+ runtime: Path,
+ spec: PinnedSource,
+ checkout: Path | None = None,
+) -> bool:
+ if runtime.is_symlink() or not runtime.is_dir():
+ return False
+ try:
+ required_files = _configured_package_paths(
+ spec.required_files,
+ spec,
+ kind = "required",
+ )
+ omitted_files = _configured_package_paths(
+ spec.omitted_files,
+ spec,
+ kind = "omitted",
+ )
+ top_level = {path.name for path in runtime.iterdir() if path.name != "__pycache__"}
+ if top_level != {spec.package}:
+ return False
+ for relative in required_files:
+ required = runtime.joinpath(*_package_path_parts(relative, spec, kind = "required"))
+ if required.is_symlink() or not required.is_file():
+ return False
+ for relative in omitted_files:
+ omitted = runtime.joinpath(*_package_path_parts(relative, spec, kind = "omitted"))
+ if omitted.exists() or omitted.is_symlink():
+ return False
+ for relative, content in _generated_file_contents(spec).items():
+ generated = runtime / relative
+ if generated.is_symlink() or not generated.is_file():
+ return False
+ if generated.read_bytes() != content:
+ return False
+ manifest = _runtime_manifest(runtime, spec)
+ if spec.runtime_tree_digest is not None:
+ return _manifest_digest(manifest) == spec.runtime_tree_digest
+ return checkout is not None and manifest == _expected_runtime_manifest(checkout, spec)
+ except (OSError, RuntimeError, ValueError):
+ return False
+
+
+def _install_runtime(runtime: Path, checkout: Path, spec: PinnedSource) -> None:
+ workspace = Path(tempfile.mkdtemp(prefix = ".runtime-", dir = runtime.parent))
+ staging = workspace / "runtime"
+ staging.mkdir()
+ try:
+ if spec.source_tree_digest is not None:
+ source_manifest = _sealed_source_manifest(checkout, spec)
+ if source_manifest is None:
+ raise RuntimeError(f"The cached {spec.name} source failed integrity validation")
+ else:
+ source_manifest = _checkout_manifest(checkout, spec)
+ for relative, expected_digest in source_manifest.items():
+ source_file = checkout / relative
+ destination_file = staging / relative
+ destination_file.parent.mkdir(parents = True, exist_ok = True)
+ shutil.copy2(source_file, destination_file)
+ if hashlib.sha256(destination_file.read_bytes()).hexdigest() != expected_digest:
+ raise RuntimeError(f"{spec.name} source changed while preparing its runtime")
+ for relative, content in _generated_file_contents(spec).items():
+ destination_file = staging / relative
+ destination_file.parent.mkdir(parents = True, exist_ok = True)
+ destination_file.write_bytes(content)
+ if not _valid_runtime(staging, spec, checkout):
+ raise RuntimeError(f"The prepared {spec.name} runtime failed integrity validation")
+ _replace_owned_directory(staging, runtime)
+ finally:
+ _remove_owned_path(workspace)
+
+
+def ensure_pinned_source(
+ spec: PinnedSource, *, legacy_sources: tuple[Path | str, ...] = ()
+) -> Path:
+ revision = spec.revision.lower()
+ if _REVISION_PATTERN.fullmatch(revision) is None or revision != spec.revision:
+ raise RuntimeError(f"{spec.name} source revision must be a lowercase full Git commit")
+ for digest in (spec.source_tree_digest, spec.runtime_tree_digest):
+ if digest is not None and _SHA256_PATTERN.fullmatch(digest) is None:
+ raise RuntimeError(f"{spec.name} source digest must be a lowercase SHA-256")
+ if (spec.source_tree_digest is None) != (spec.runtime_tree_digest is None):
+ raise RuntimeError(f"{spec.name} source and runtime digests must be configured together")
+
+ parent = cache_root() / "third-party-sources" / spec.name
+ version_root = parent / revision
+ checkout = version_root / "source"
+ runtime = version_root / "runtime-v1"
+ if _valid_runtime(runtime, spec):
+ return runtime.resolve()
+
+ version_root.mkdir(parents = True, exist_ok = True)
+ try:
+ with FileLock(str(parent / ".install.lock"), timeout = 300):
+ if _valid_runtime(runtime, spec):
+ return runtime.resolve()
+
+ source = None
+ if spec.source_tree_digest is not None:
+ for candidate in (checkout, *(Path(value) for value in legacy_sources)):
+ if _sealed_source_manifest(candidate, spec) is not None:
+ source = candidate
+ break
+ elif _valid_checkout(checkout, spec):
+ source = checkout
+
+ if source is not None and _valid_runtime(runtime, spec, source):
+ return runtime.resolve()
+
+ if source is None:
+ from utils.utils import hf_env_offline
+
+ if hf_env_offline():
+ raise RuntimeError(
+ f"The pinned {spec.name} source is not cached and Studio is offline"
+ )
+ if spec.archive_url is not None:
+ _install_archive_source(checkout, spec)
+ else:
+ _install_checkout(checkout, spec)
+ source = checkout
+ _install_runtime(runtime, source, spec)
+ except Timeout as error:
+ raise RuntimeError(f"Timed out waiting for another {spec.name} installation") from error
+
+ if not _valid_runtime(runtime, spec, checkout):
+ raise RuntimeError(f"The installed {spec.name} source failed integrity validation")
+ return runtime.resolve()
+
+
+def ensure_spark_tts_source(model_repo_path: Path | str | None = None) -> Path:
+ legacy_parent = Path(model_repo_path).parent if model_repo_path is not None else Path.cwd()
+ legacy_sources = (legacy_parent / "Spark-TTS",)
+ return ensure_pinned_source(SPARK_TTS_SOURCE, legacy_sources = legacy_sources)
+
+
+def ensure_outetts_source() -> Path:
+ backend_root = Path(__file__).resolve().parents[1]
+ return ensure_pinned_source(
+ OUTETTS_SOURCE,
+ legacy_sources = (
+ backend_root / "core" / "inference" / "OuteTTS",
+ backend_root / "core" / "training" / "inference" / "OuteTTS",
+ ),
+ )
+
+
+def _artifact_matches(path: Path, *, expected_size: int, expected_sha256: str) -> bool:
+ try:
+ if not path.is_file() or path.stat().st_size != expected_size:
+ return False
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest() == expected_sha256
+ except OSError:
+ return False
+
+
+def _install_verified_artifact(source: Path, destination: Path) -> None:
+ workspace = Path(tempfile.mkdtemp(prefix = ".artifact-", dir = destination.parent))
+ staging = workspace / destination.name
+ try:
+ shutil.copyfile(source, staging)
+ if not _artifact_matches(
+ staging,
+ expected_size = _DAC_SIZE,
+ expected_sha256 = _DAC_SHA256,
+ ):
+ raise RuntimeError("The cached DAC speech weights changed during migration")
+ os.replace(staging, destination)
+ finally:
+ _remove_owned_path(workspace)
+
+
+def _default_legacy_dac_weights_path() -> Path | None:
+ if sys.platform == "win32":
+ appdata = (os.environ.get("APPDATA") or "").strip()
+ if not appdata:
+ return None
+ return Path(appdata) / "outeai" / "dac" / _DAC_FILENAME
+ return Path.home() / ".cache" / "outeai" / "dac" / _DAC_FILENAME
+
+
+def ensure_dac_speech_weights(legacy_path: Path | str | None = None) -> Path:
+ from huggingface_hub import hf_hub_download
+ from utils.hf_cache_settings import active_hf_hub_cache
+ from utils.utils import hf_env_offline
+
+ hub_cache = Path(active_hf_hub_cache())
+ destination = (
+ hub_cache
+ / "studio-pinned-artifacts"
+ / _DAC_REPOSITORY.replace("/", "--")
+ / _DAC_REVISION
+ / _DAC_FILENAME
+ )
+ if _artifact_matches(
+ destination,
+ expected_size = _DAC_SIZE,
+ expected_sha256 = _DAC_SHA256,
+ ):
+ return destination.resolve()
+
+ def _verified_legacy() -> Path | None:
+ candidate = (
+ Path(legacy_path) if legacy_path is not None else _default_legacy_dac_weights_path()
+ )
+ if candidate is not None and _artifact_matches(
+ candidate,
+ expected_size = _DAC_SIZE,
+ expected_sha256 = _DAC_SHA256,
+ ):
+ return candidate.resolve()
+ return None
+
+ try:
+ destination.parent.mkdir(parents = True, exist_ok = True)
+ except OSError:
+ # A read-only or full hub cache must not hide weights we can already verify.
+ fallback = _verified_legacy()
+ if fallback is None:
+ raise
+ return fallback
+ try:
+ with FileLock(str(destination.parent / ".install.lock"), timeout = 300):
+ if _artifact_matches(
+ destination,
+ expected_size = _DAC_SIZE,
+ expected_sha256 = _DAC_SHA256,
+ ):
+ return destination.resolve()
+
+ legacy = (
+ Path(legacy_path) if legacy_path is not None else _default_legacy_dac_weights_path()
+ )
+ if legacy is not None and _artifact_matches(
+ legacy,
+ expected_size = _DAC_SIZE,
+ expected_sha256 = _DAC_SHA256,
+ ):
+ # Same as the download branch below: the copy is an optimisation, so a full
+ # disk must not reject weights that already passed the size and sha256 check.
+ try:
+ _install_verified_artifact(legacy, destination)
+ except OSError:
+ return legacy.resolve()
+ return destination.resolve()
+
+ offline = hf_env_offline()
+ download_error = None
+ downloaded = None
+ try:
+ downloaded = Path(
+ hf_hub_download(
+ repo_id = _DAC_REPOSITORY,
+ filename = _DAC_FILENAME,
+ revision = _DAC_REVISION,
+ cache_dir = str(hub_cache),
+ local_files_only = offline,
+ )
+ )
+ except Exception as error:
+ download_error = error
+
+ if downloaded is not None and _artifact_matches(
+ downloaded,
+ expected_size = _DAC_SIZE,
+ expected_sha256 = _DAC_SHA256,
+ ):
+ # Populate the pinned destination so later loads hit the fast path above
+ # instead of re-downloading and re-hashing 295 MB under the install lock.
+ # The copy is an optimisation, so a full disk must not fail a verified
+ # download; fall back to the hub path the caller used before.
+ try:
+ _install_verified_artifact(downloaded, destination)
+ except OSError:
+ return downloaded.resolve()
+ return destination.resolve()
+
+ if download_error is not None:
+ raise RuntimeError(
+ "The pinned DAC speech weights are unavailable in the active Hugging Face cache"
+ ) from download_error
+ raise RuntimeError("The downloaded DAC speech weights failed integrity validation")
+ except OSError:
+ # Same reasoning as the mkdir above: taking the lock needs a writable cache, and
+ # verified weights we already hold are a better answer than failing the load.
+ fallback = _verified_legacy()
+ if fallback is None:
+ raise
+ return fallback
+ except Timeout as error:
+ raise RuntimeError("Timed out waiting for the DAC speech weights installation") from error
+
+
+def _module_is_inside(module: ModuleType, package_root: Path) -> bool:
+ origins = []
+ origin = getattr(module, "__file__", None)
+ if origin:
+ origins.append(origin)
+ origins.extend(getattr(module, "__path__", ()) or ())
+ if not origins:
+ return False
+ for value in origins:
+ try:
+ if not Path(value).resolve().is_relative_to(package_root):
+ return False
+ except (OSError, ValueError):
+ return False
+ return True
+
+
+def _purge_package_bytecode(package_root: Path) -> None:
+ # This is the only thing stopping a stale or planted .pyc from shadowing a verified .py:
+ # the manifest skips __pycache__ entirely, and the origin audit reads __file__, which
+ # still names the .py. So only the concurrent-purge race is tolerated (another worker
+ # deleting the same tree without the install lock); a PermissionError must stay fatal.
+ for directory, child_directories, files in os.walk(package_root, topdown = True):
+ directory_path = Path(directory)
+ for name in tuple(child_directories):
+ path = directory_path / name
+ if path.is_symlink():
+ child_directories.remove(name)
+ if name == "__pycache__":
+ with contextlib.suppress(FileNotFoundError):
+ path.unlink()
+ elif name == "__pycache__":
+ child_directories.remove(name)
+ with contextlib.suppress(FileNotFoundError):
+ shutil.rmtree(path)
+ for name in files:
+ if name.endswith((".pyc", ".pyo")):
+ (directory_path / name).unlink(missing_ok = True)
+
+
+def _remove_package_modules(package: str) -> None:
+ for name in list(sys.modules):
+ if name == package or name.startswith(f"{package}."):
+ sys.modules.pop(name, None)
+
+
+def import_pinned_module(module_name: str, *, package: str, source: Path | str) -> ModuleType:
+ if module_name != package and not module_name.startswith(f"{package}."):
+ raise ValueError(f"Only {package} modules can be imported from this pinned source")
+ source_root = Path(source).resolve()
+ unresolved_package_root = source_root / package
+ if unresolved_package_root.is_symlink() or not unresolved_package_root.is_dir():
+ raise RuntimeError(f"The pinned {package} package is missing")
+ package_root = unresolved_package_root.resolve()
+ package_init = package_root / "__init__.py"
+ if package_init.is_symlink() or not package_init.is_file():
+ raise RuntimeError(f"The pinned {package} package is not sealed")
+
+ with _IMPORT_LOCK:
+ for name, loaded_module in list(sys.modules.items()):
+ if name != package and not name.startswith(f"{package}."):
+ continue
+ if not _module_is_inside(loaded_module, package_root):
+ sys.modules.pop(name, None)
+
+ source_value = str(source_root)
+ while source_value in sys.path:
+ sys.path.remove(source_value)
+ sys.path.insert(0, source_value)
+ try:
+ # Inside the try: anything raising here would otherwise strand the cache dir at
+ # sys.path[0] for the process lifetime, with nothing imported and no rollback.
+ _purge_package_bytecode(package_root)
+ importlib.invalidate_caches()
+ module = importlib.import_module(module_name)
+ invalid_modules = sorted(
+ name
+ # Snapshot: another thread importing here would otherwise raise
+ # "dictionary changed size during iteration" out of a good codec load.
+ for name, loaded_module in list(sys.modules.items())
+ if (name == package or name.startswith(f"{package}."))
+ and not _module_is_inside(loaded_module, package_root)
+ )
+ if invalid_modules:
+ names = ", ".join(invalid_modules)
+ raise RuntimeError(
+ f"{package} loaded package modules from outside the pinned source: {names}"
+ )
+ return module
+ except BaseException:
+ while source_value in sys.path:
+ sys.path.remove(source_value)
+ _remove_package_modules(package)
+ raise
+
+
+def deactivate_pinned_package(package: str, source: Path | str | None) -> None:
+ with _IMPORT_LOCK:
+ if source is not None:
+ source_value = str(Path(source).resolve())
+ while source_value in sys.path:
+ sys.path.remove(source_value)
+ _remove_package_modules(package)
+
+
+def import_sparktts_module(module_name: str, source: Path | str) -> ModuleType:
+ return import_pinned_module(module_name, package = "sparktts", source = source)
+
+
+def import_outetts_module(module_name: str, source: Path | str) -> ModuleType:
+ return import_pinned_module(module_name, package = "outetts", source = source)
diff --git a/studio/frontend/src/features/onboarding/components/steps/dataset-step.tsx b/studio/frontend/src/features/onboarding/components/steps/dataset-step.tsx
index 73be5a07a41..fdf812c2702 100644
--- a/studio/frontend/src/features/onboarding/components/steps/dataset-step.tsx
+++ b/studio/frontend/src/features/onboarding/components/steps/dataset-step.tsx
@@ -82,6 +82,8 @@ export function DatasetStep() {
setDatasetSplit,
datasetEvalSplit,
setDatasetEvalSplit,
+ setManualDatasetOptionsValid,
+ markManualDatasetOptionsEdited,
uploadedFile,
selectLocalDataset,
} = useTrainingConfigStore(
@@ -99,6 +101,8 @@ export function DatasetStep() {
setDatasetSplit: state.setDatasetSplit,
datasetEvalSplit: state.datasetEvalSplit,
setDatasetEvalSplit: state.setDatasetEvalSplit,
+ setManualDatasetOptionsValid: state.setManualDatasetOptionsValid,
+ markManualDatasetOptionsEdited: state.markManualDatasetOptionsEdited,
uploadedFile: state.uploadedFile,
selectLocalDataset: state.selectLocalDataset,
})),
@@ -166,6 +170,9 @@ export function DatasetStep() {
setDatasetSplit={setDatasetSplit}
datasetEvalSplit={datasetEvalSplit}
setDatasetEvalSplit={setDatasetEvalSplit}
+ datasetStreaming={datasetStreaming}
+ setManualDatasetOptionsValid={setManualDatasetOptionsValid}
+ markManualDatasetOptionsEdited={markManualDatasetOptionsEdited}
/>
)}
diff --git a/studio/frontend/src/features/onboarding/components/steps/summary-step.tsx b/studio/frontend/src/features/onboarding/components/steps/summary-step.tsx
index 88002d94bfc..cdca5a5fdcf 100644
--- a/studio/frontend/src/features/onboarding/components/steps/summary-step.tsx
+++ b/studio/frontend/src/features/onboarding/components/steps/summary-step.tsx
@@ -4,8 +4,10 @@
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
-import { useTrainingConfigStore } from "@/features/training";
-import { getTrainingMethodLabel } from "@/features/training/lib/training-methods";
+import {
+ getTrainingMethodLabel,
+ useTrainingConfigStore,
+} from "@/features/training";
import { useHardwareInfo } from "@/hooks";
import { isAdapterMethod } from "@/types/training";
import { ChipIcon, Database02Icon, GpuIcon, Settings04Icon } from "@hugeicons/core-free-icons";
diff --git a/studio/frontend/src/features/studio/sections/dataset-selection.tsx b/studio/frontend/src/features/studio/sections/dataset-selection.tsx
index eda92cdca01..32c5cd11184 100644
--- a/studio/frontend/src/features/studio/sections/dataset-selection.tsx
+++ b/studio/frontend/src/features/studio/sections/dataset-selection.tsx
@@ -44,6 +44,8 @@ function DatasetSubsetConfiguration({
datasetSplit: state.datasetSplit,
datasetSubset: state.datasetSubset,
setDatasetEvalSplit: state.setDatasetEvalSplit,
+ setManualDatasetOptionsValid: state.setManualDatasetOptionsValid,
+ markManualDatasetOptionsEdited: state.markManualDatasetOptionsEdited,
setDatasetSplit: state.setDatasetSplit,
setDatasetSubset: state.setDatasetSubset,
})),
@@ -65,6 +67,9 @@ function DatasetSubsetConfiguration({
setDatasetSplit={settings.setDatasetSplit}
datasetEvalSplit={settings.datasetEvalSplit}
setDatasetEvalSplit={settings.setDatasetEvalSplit}
+ datasetStreaming={settings.datasetStreaming}
+ setManualDatasetOptionsValid={settings.setManualDatasetOptionsValid}
+ markManualDatasetOptionsEdited={settings.markManualDatasetOptionsEdited}
/>
);
}
diff --git a/studio/frontend/src/features/studio/sections/progress-section.tsx b/studio/frontend/src/features/studio/sections/progress-section.tsx
index c5bf57798b7..25b6bb6bd44 100644
--- a/studio/frontend/src/features/studio/sections/progress-section.tsx
+++ b/studio/frontend/src/features/studio/sections/progress-section.tsx
@@ -23,12 +23,12 @@ import { usePlatformStore } from "@/config/env";
import { MLX_OPTIMIZER_OPTIONS, OPTIMIZER_OPTIONS } from "@/config/training";
import { setTrainingCompareHandoff } from "@/features/chat";
import {
+ getTrainingMethodLabel,
+ type TrainingViewData,
useTrainingActions,
useTrainingConfigStore,
useTrainingRuntimeStore,
} from "@/features/training";
-import type { TrainingViewData } from "@/features/training";
-import { getTrainingMethodLabel } from "@/features/training/lib/training-methods";
import { useGpuUtilization } from "@/hooks";
import type { GpuUtilization } from "@/hooks/use-gpu-utilization";
import { type TranslationKey, useT } from "@/i18n";
@@ -46,7 +46,7 @@ import {
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { Link, useNavigate } from "@tanstack/react-router";
-import { type ReactElement, type ReactNode, useEffect, useState } from "react";
+import { type ReactElement, type ReactNode, useState } from "react";
import { useShallow } from "zustand/react/shallow";
import { ChartSettingsSheet } from "./charts/chart-settings-sheet";
import {
@@ -402,14 +402,9 @@ function LiveGpuPanel({
? [gpuData]
: [];
- useEffect(() => {
- if (selectedGpu > 0 && selectedGpu >= gpus.length) {
- setSelectedGpu(0);
- }
- }, [gpus.length, selectedGpu]);
-
const gpuCount = gpus.length;
- const currentGpu: Partial<GpuUtilization> = gpus[selectedGpu] || gpus[0] || {};
+ const selectedGpuIndex = selectedGpu >= 0 && selectedGpu < gpuCount ? selectedGpu : 0;
+ const currentGpu: Partial<GpuUtilization> = gpus[selectedGpuIndex] || {};
return (
<div className="flex flex-col gap-3">
@@ -420,7 +415,7 @@ function LiveGpuPanel({
</p>
{gpuCount > 1 && (
<select
- value={selectedGpu}
+ value={selectedGpuIndex}
onChange={(e) => setSelectedGpu(Number(e.target.value))}
className="h-6 cursor-pointer rounded-md border border-border bg-popover px-1.5 py-0.5 text-ui-11 text-popover-foreground outline-none hover:bg-muted focus:border-ring transition-colors font-medium appearance-none"
title="Select GPU"
diff --git a/studio/frontend/src/features/training/api/train-api.ts b/studio/frontend/src/features/training/api/train-api.ts
index bdd17f3a892..0fb61dcddcc 100644
--- a/studio/frontend/src/features/training/api/train-api.ts
+++ b/studio/frontend/src/features/training/api/train-api.ts
@@ -252,6 +252,10 @@ interface TrainingJobScope {
expectedJobId?: string;
}
+interface RequiredTrainingJobScope {
+ expectedJobId: string;
+}
+
function scopedTrainingBody(
payload: Record<string, unknown>,
scope?: TrainingJobScope,
@@ -265,8 +269,8 @@ function scopedTrainingBody(
}
export async function stopTraining(
- save = true,
- scope?: TrainingJobScope,
+ save: boolean,
+ scope: RequiredTrainingJobScope,
): Promise<TrainingStopResponse> {
const response = await authFetch("/api/train/stop", {
method: "POST",
@@ -277,17 +281,12 @@ export async function stopTraining(
}
export async function resetTraining(
- scope?: TrainingJobScope,
+ scope: RequiredTrainingJobScope,
): Promise<TrainingResetResponse> {
- const hasScope = scope?.expectedJobId !== undefined;
const response = await authFetch("/api/train/reset", {
method: "POST",
- ...(hasScope
- ? {
- headers: { "Content-Type": "application/json" },
- body: scopedTrainingBody({}, scope),
- }
- : {}),
+ headers: { "Content-Type": "application/json" },
+ body: scopedTrainingBody({}, scope),
});
return parseJson<TrainingResetResponse>(response);
}
diff --git a/studio/frontend/src/features/training/components/hf-dataset-subset-split-selectors.tsx b/studio/frontend/src/features/training/components/hf-dataset-subset-split-selectors.tsx
index b7008edfebe..576b5b8f073 100644
--- a/studio/frontend/src/features/training/components/hf-dataset-subset-split-selectors.tsx
+++ b/studio/frontend/src/features/training/components/hf-dataset-subset-split-selectors.tsx
@@ -23,9 +23,13 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { type KeyboardEvent, useEffect, useState } from "react";
import { nextHfDatasetOptionSelection } from "../lib/hf-dataset-option-selection";
import {
+ type ManualDatasetOptionDrafts,
type ManualDatasetOptionError,
+ createManualDatasetOptionDrafts,
+ manualDatasetOptionsFormKey,
manualDatasetSplitDefault,
normalizeManualDatasetOption,
+ synchronizeManualDatasetOptionDrafts,
validateManualDatasetSplit,
validateManualDatasetSubset,
} from "../lib/manual-dataset-options";
@@ -44,8 +48,30 @@ type Props = {
setDatasetSplit: (v: string | null) => void;
datasetEvalSplit: string | null;
setDatasetEvalSplit: (v: string | null) => void;
+ datasetStreaming: boolean;
+ setManualDatasetOptionsValid: (v: boolean) => void;
+ markManualDatasetOptionsEdited: (optionsValid: boolean) => void;
};
+function manualDatasetDraftsAreValid(
+ subset: string,
+ split: string,
+ evalSplit: string,
+ requireExplicitSplit: boolean,
+ allowSplitInstructions: boolean,
+) {
+ return (
+ validateManualDatasetSubset(subset) === null &&
+ validateManualDatasetSplit(
+ split,
+ requireExplicitSplit,
+ allowSplitInstructions,
+ ) === null &&
+ validateManualDatasetSplit(evalSplit, false, allowSplitInstructions) ===
+ null
+ );
+}
+
export function HfDatasetSubsetSplitSelectors({
variant,
enabled,
@@ -60,6 +86,9 @@ export function HfDatasetSubsetSplitSelectors({
setDatasetSplit,
datasetEvalSplit,
setDatasetEvalSplit,
+ datasetStreaming,
+ setManualDatasetOptionsValid,
+ markManualDatasetOptionsEdited,
}: Props) {
const t = useT();
const {
@@ -183,7 +212,11 @@ export function HfDatasetSubsetSplitSelectors({
{requiresManualEntry && datasetName && (
<ManualDatasetOptions
- key={JSON.stringify([datasetName, localPath, preferLocalCache])}
+ key={manualDatasetOptionsFormKey(
+ datasetName,
+ localPath,
+ preferLocalCache,
+ )}
variant={variant}
datasetSubset={datasetSubset}
setDatasetSubset={setDatasetSubset}
@@ -191,6 +224,9 @@ export function HfDatasetSubsetSplitSelectors({
setDatasetSplit={setDatasetSplit}
datasetEvalSplit={datasetEvalSplit}
setDatasetEvalSplit={setDatasetEvalSplit}
+ datasetStreaming={datasetStreaming}
+ setManualDatasetOptionsValid={setManualDatasetOptionsValid}
+ markManualDatasetOptionsEdited={markManualDatasetOptionsEdited}
requireExplicitSplit={preferLocalCache}
/>
)}
@@ -206,6 +242,9 @@ function ManualDatasetOptions({
setDatasetSplit,
datasetEvalSplit,
setDatasetEvalSplit,
+ datasetStreaming,
+ setManualDatasetOptionsValid,
+ markManualDatasetOptionsEdited,
requireExplicitSplit,
}: Pick<
Props,
@@ -216,35 +255,63 @@ function ManualDatasetOptions({
| "setDatasetSplit"
| "datasetEvalSplit"
| "setDatasetEvalSplit"
+ | "datasetStreaming"
+ | "setManualDatasetOptionsValid"
+ | "markManualDatasetOptionsEdited"
> & {
requireExplicitSplit: boolean;
}) {
const t = useT();
const defaultSplit = manualDatasetSplitDefault(requireExplicitSplit);
- const [subsetDraft, setSubsetDraft] = useState(datasetSubset ?? "");
- const [splitDraft, setSplitDraft] = useState(datasetSplit ?? defaultSplit);
- const [evalDraft, setEvalDraft] = useState(datasetEvalSplit ?? "");
- const [subsetError, setSubsetError] =
- useState<ManualDatasetOptionError | null>(null);
- const [splitError, setSplitError] = useState<ManualDatasetOptionError | null>(
- null,
+ const allowSplitInstructions = !datasetStreaming;
+ const draftSources = {
+ datasetSubset,
+ datasetSplit,
+ datasetEvalSplit,
+ defaultSplit,
+ };
+ const [storedDrafts, setStoredDrafts] = useState<ManualDatasetOptionDrafts>(
+ () => createManualDatasetOptionDrafts(draftSources),
);
- const [evalError, setEvalError] = useState<ManualDatasetOptionError | null>(
- null,
+ const drafts = synchronizeManualDatasetOptionDrafts(
+ storedDrafts,
+ draftSources,
);
+ if (drafts !== storedDrafts) {
+ // Persist observed prop transitions so an A -> B -> A cycle cannot revive
+ // an obsolete draft. The identity guard makes this a single adjustment.
+ setStoredDrafts(drafts);
+ }
+ const subsetDraft = drafts.subset.value;
+ const splitDraft = drafts.split.value;
+ const evalDraft = drafts.evalSplit.value;
+ const subsetError = drafts.subset.error;
+ const splitError = drafts.split.error;
+ const evalError = drafts.evalSplit.error;
useEffect(() => {
- setSubsetDraft(datasetSubset ?? "");
- setSubsetError(null);
- }, [datasetSubset]);
- useEffect(() => {
- setSplitDraft(datasetSplit ?? defaultSplit);
- setSplitError(null);
- }, [datasetSplit, defaultSplit]);
- useEffect(() => {
- setEvalDraft(datasetEvalSplit ?? "");
- setEvalError(null);
- }, [datasetEvalSplit]);
+ setManualDatasetOptionsValid(
+ manualDatasetDraftsAreValid(
+ subsetDraft,
+ splitDraft,
+ evalDraft,
+ requireExplicitSplit,
+ allowSplitInstructions,
+ ),
+ );
+ }, [
+ subsetDraft,
+ splitDraft,
+ evalDraft,
+ requireExplicitSplit,
+ allowSplitInstructions,
+ setManualDatasetOptionsValid,
+ ]);
+
+ useEffect(
+ () => () => setManualDatasetOptionsValid(true),
+ [setManualDatasetOptionsValid],
+ );
const errorMessage = (error: ManualDatasetOptionError | null) => {
if (error === "required") {
@@ -265,53 +332,136 @@ function ManualDatasetOptions({
};
const commitSubset = () => {
const nextError = validateManualDatasetSubset(subsetDraft);
- setSubsetError(nextError);
if (nextError) {
+ setStoredDrafts({
+ ...drafts,
+ subset: { ...drafts.subset, error: nextError },
+ });
+ setManualDatasetOptionsValid(false);
return;
}
const normalized = normalizeManualDatasetOption(subsetDraft);
const value = normalized || null;
if (value === datasetSubset) {
+ setStoredDrafts({
+ ...drafts,
+ subset: {
+ committedValue: value,
+ value: normalized,
+ error: null,
+ },
+ });
return;
}
+ const nextDrafts: ManualDatasetOptionDrafts = {
+ subset: {
+ committedValue: value,
+ value: normalized,
+ error: null,
+ },
+ split: {
+ committedValue: null,
+ value: defaultSplit,
+ error: null,
+ },
+ evalSplit: {
+ committedValue: null,
+ value: "",
+ error: null,
+ },
+ };
setDatasetSubset(value);
- setSplitDraft(defaultSplit);
- setEvalDraft("");
- setSplitError(null);
- setEvalError(null);
+ // It nulls datasetEvalSplit but not evalSteps, so this is what stops evaluation staying
+ // armed with no split (a 422 once streaming is on). setDatasetSplit(null) is not needed:
+ // it only adds a runDatasetCheck against an assumed "train" split.
+ setDatasetEvalSplit(null);
+ setStoredDrafts(nextDrafts);
+ setManualDatasetOptionsValid(
+ manualDatasetDraftsAreValid(
+ nextDrafts.subset.value,
+ nextDrafts.split.value,
+ nextDrafts.evalSplit.value,
+ requireExplicitSplit,
+ allowSplitInstructions,
+ ),
+ );
};
const commitSplit = () => {
const nextError = validateManualDatasetSplit(
splitDraft,
requireExplicitSplit,
+ allowSplitInstructions,
);
- setSplitError(nextError);
if (nextError) {
- if (requireExplicitSplit && datasetSplit !== null) {
- setDatasetSplit(null);
- }
+ setStoredDrafts({
+ ...drafts,
+ split: { ...drafts.split, error: nextError },
+ });
+ setManualDatasetOptionsValid(false);
return;
}
const normalized = normalizeManualDatasetOption(splitDraft);
const value = normalized || null;
- if (value === null && requireExplicitSplit === false) {
- setSplitDraft(defaultSplit);
- }
+ const nextSplitDraft = value ?? defaultSplit;
+ const nextDrafts: ManualDatasetOptionDrafts = {
+ ...drafts,
+ split: {
+ committedValue: value,
+ value: nextSplitDraft,
+ error: null,
+ },
+ };
if (value !== datasetSplit) {
setDatasetSplit(value);
}
+ setStoredDrafts(nextDrafts);
+ setManualDatasetOptionsValid(
+ manualDatasetDraftsAreValid(
+ nextDrafts.subset.value,
+ nextDrafts.split.value,
+ nextDrafts.evalSplit.value,
+ requireExplicitSplit,
+ allowSplitInstructions,
+ ),
+ );
};
const commitEvalSplit = () => {
- const nextError = validateManualDatasetSplit(evalDraft, false);
- setEvalError(nextError);
+ const nextError = validateManualDatasetSplit(
+ evalDraft,
+ false,
+ allowSplitInstructions,
+ );
if (nextError) {
+ setStoredDrafts({
+ ...drafts,
+ evalSplit: { ...drafts.evalSplit, error: nextError },
+ });
+ setManualDatasetOptionsValid(false);
return;
}
const normalized = normalizeManualDatasetOption(evalDraft);
const value = normalized || null;
+ const nextDrafts: ManualDatasetOptionDrafts = {
+ ...drafts,
+ evalSplit: {
+ committedValue: value,
+ value: normalized,
+ error: null,
+ },
+ };
if (value !== datasetEvalSplit) {
setDatasetEvalSplit(value);
}
+ setStoredDrafts(nextDrafts);
+ setManualDatasetOptionsValid(
+ manualDatasetDraftsAreValid(
+ nextDrafts.subset.value,
+ nextDrafts.split.value,
+ nextDrafts.evalSplit.value,
+ requireExplicitSplit,
+ allowSplitInstructions,
+ ),
+ );
};
const fields = (
@@ -326,8 +476,21 @@ function ManualDatasetOptions({
placeholder={t("studio.dataset.selectors.manualSubsetPlaceholder")}
aria-invalid={subsetError !== null}
onChange={(event) => {
- setSubsetDraft(event.target.value);
- setSubsetError(null);
+ const value = event.target.value;
+ const nextDrafts: ManualDatasetOptionDrafts = {
+ ...drafts,
+ subset: { ...drafts.subset, value, error: null },
+ };
+ setStoredDrafts(nextDrafts);
+ markManualDatasetOptionsEdited(
+ manualDatasetDraftsAreValid(
+ nextDrafts.subset.value,
+ nextDrafts.split.value,
+ nextDrafts.evalSplit.value,
+ requireExplicitSplit,
+ allowSplitInstructions,
+ ),
+ );
}}
onBlur={commitSubset}
onKeyDown={blurOnEnter}
@@ -344,8 +507,21 @@ function ManualDatasetOptions({
placeholder={t("studio.dataset.selectors.selectSplit")}
aria-invalid={splitError !== null}
onChange={(event) => {
- setSplitDraft(event.target.value);
- setSplitError(null);
+ const value = event.target.value;
+ const nextDrafts: ManualDatasetOptionDrafts = {
+ ...drafts,
+ split: { ...drafts.split, value, error: null },
+ };
+ setStoredDrafts(nextDrafts);
+ markManualDatasetOptionsEdited(
+ manualDatasetDraftsAreValid(
+ nextDrafts.subset.value,
+ nextDrafts.split.value,
+ nextDrafts.evalSplit.value,
+ requireExplicitSplit,
+ allowSplitInstructions,
+ ),
+ );
}}
onBlur={commitSplit}
onKeyDown={blurOnEnter}
@@ -362,8 +538,21 @@ function ManualDatasetOptions({
placeholder={t("studio.dataset.selectors.none")}
aria-invalid={evalError !== null}
onChange={(event) => {
- setEvalDraft(event.target.value);
- setEvalError(null);
+ const value = event.target.value;
+ const nextDrafts: ManualDatasetOptionDrafts = {
+ ...drafts,
+ evalSplit: { ...drafts.evalSplit, value, error: null },
+ };
+ setStoredDrafts(nextDrafts);
+ markManualDatasetOptionsEdited(
+ manualDatasetDraftsAreValid(
+ nextDrafts.subset.value,
+ nextDrafts.split.value,
+ nextDrafts.evalSplit.value,
+ requireExplicitSplit,
+ allowSplitInstructions,
+ ),
+ );
}}
onBlur={commitEvalSplit}
onKeyDown={blurOnEnter}
diff --git a/studio/frontend/src/features/training/index.ts b/studio/frontend/src/features/training/index.ts
index f288d77b38f..0a31a57bbc1 100644
--- a/studio/frontend/src/features/training/index.ts
+++ b/studio/frontend/src/features/training/index.ts
@@ -19,6 +19,7 @@ export {
shouldShowTrainingArtifactsDeleted,
} from "./lib/run-display";
export {
+ getTrainingMethodLabel,
isRawTextDatasetFormat,
isTrainingLoraVariantSupportedOnDevice,
isTrainingMethodSupportedOnDevice,
diff --git a/studio/frontend/src/features/training/lib/manual-dataset-options.ts b/studio/frontend/src/features/training/lib/manual-dataset-options.ts
index c395cf1f3e2..c01dcdbc789 100644
--- a/studio/frontend/src/features/training/lib/manual-dataset-options.ts
+++ b/studio/frontend/src/features/training/lib/manual-dataset-options.ts
@@ -3,10 +3,31 @@
export type ManualDatasetOptionError = "invalid" | "required" | "too_long";
+export type ManualDatasetOptionDraft = {
+ committedValue: string | null;
+ value: string;
+ error: ManualDatasetOptionError | null;
+};
+
+export type ManualDatasetOptionDrafts = {
+ subset: ManualDatasetOptionDraft;
+ split: ManualDatasetOptionDraft;
+ evalSplit: ManualDatasetOptionDraft;
+};
+
+type ManualDatasetOptionDraftSources = {
+ datasetSubset: string | null;
+ datasetSplit: string | null;
+ datasetEvalSplit: string | null;
+ defaultSplit: string;
+};
+
const MAX_OPTION_LENGTH = 128;
const CONFIG_FORBIDDEN_PATTERN = /[<>:/\\|?*]/;
const PATH_SEPARATOR_PATTERN = /[/\\]/;
+const UNSAFE_UNICODE_PATTERN = /[\p{Cc}\p{Cf}\p{Cs}]/u;
const SPLIT_NAME_PATTERN = String.raw`[\p{L}\p{N}_]+(?:\.[\p{L}\p{N}_]+)*`;
+const BARE_SPLIT_PATTERN = new RegExp(String.raw`^${SPLIT_NAME_PATTERN}$`, "u");
const SPLIT_BOUNDARY_PATTERN = String.raw`-?\d(?:_?\d)*%?`;
const SPLIT_PART_PATTERN = new RegExp(
String.raw`^(${SPLIT_NAME_PATTERN})(?:\[(${SPLIT_BOUNDARY_PATTERN})?:(${SPLIT_BOUNDARY_PATTERN})?\])?(?:\((closest|pct1_dropremainder)\))?$`,
@@ -19,11 +40,84 @@ export function manualDatasetSplitDefault(
return requireExplicitSplit ? "" : "train";
}
+export function manualDatasetOptionsFormKey(
+ datasetName: string,
+ localPath: string | null | undefined,
+ preferLocalCache: boolean,
+): string {
+ return JSON.stringify([datasetName, localPath, preferLocalCache]);
+}
+
+function createManualDatasetOptionDraft(
+ committedValue: string | null,
+ fallback: string,
+): ManualDatasetOptionDraft {
+ return {
+ committedValue,
+ value: committedValue ?? fallback,
+ error: null,
+ };
+}
+
+export function createManualDatasetOptionDrafts({
+ datasetSubset,
+ datasetSplit,
+ datasetEvalSplit,
+ defaultSplit,
+}: ManualDatasetOptionDraftSources): ManualDatasetOptionDrafts {
+ return {
+ subset: createManualDatasetOptionDraft(datasetSubset, ""),
+ split: createManualDatasetOptionDraft(datasetSplit, defaultSplit),
+ evalSplit: createManualDatasetOptionDraft(datasetEvalSplit, ""),
+ };
+}
+
+function synchronizeManualDatasetOptionDraft(
+ draft: ManualDatasetOptionDraft,
+ committedValue: string | null,
+ fallback: string,
+): ManualDatasetOptionDraft {
+ return draft.committedValue === committedValue
+ ? draft
+ : createManualDatasetOptionDraft(committedValue, fallback);
+}
+
+export function synchronizeManualDatasetOptionDrafts(
+ drafts: ManualDatasetOptionDrafts,
+ {
+ datasetSubset,
+ datasetSplit,
+ datasetEvalSplit,
+ defaultSplit,
+ }: ManualDatasetOptionDraftSources,
+): ManualDatasetOptionDrafts {
+ const subset = synchronizeManualDatasetOptionDraft(
+ drafts.subset,
+ datasetSubset,
+ "",
+ );
+ const split = synchronizeManualDatasetOptionDraft(
+ drafts.split,
+ datasetSplit,
+ defaultSplit,
+ );
+ const evalSplit = synchronizeManualDatasetOptionDraft(
+ drafts.evalSplit,
+ datasetEvalSplit,
+ "",
+ );
+ return subset === drafts.subset &&
+ split === drafts.split &&
+ evalSplit === drafts.evalSplit
+ ? drafts
+ : { subset, split, evalSplit };
+}
+
function commonError(value: string): ManualDatasetOptionError | null {
- if (value.length > MAX_OPTION_LENGTH) {
+ if (Array.from(value).length > MAX_OPTION_LENGTH) {
return "too_long";
}
- if (hasControlCharacter(value)) {
+ if (UNSAFE_UNICODE_PATTERN.test(value)) {
return "invalid";
}
if (value === "." || value === ".." || PATH_SEPARATOR_PATTERN.test(value)) {
@@ -32,34 +126,24 @@ function commonError(value: string): ManualDatasetOptionError | null {
return null;
}
-function hasControlCharacter(value: string): boolean {
- for (const character of value) {
- const codePoint = character.codePointAt(0);
- if (codePoint !== undefined && (codePoint <= 0x1f || codePoint === 0x7f)) {
- return true;
- }
- }
- return false;
-}
-
export function normalizeManualDatasetOption(value: string): string {
return value.trim();
}
-function validPercentBoundary(value: string | undefined): boolean {
- if (!value?.endsWith("%")) {
+function validPercentBoundary(
+ value: string | undefined,
+ percentMode: boolean,
+): boolean {
+ if (!value || !percentMode) {
return true;
}
- const parsed = Number(value.slice(0, -1).replaceAll("_", ""));
+ const parsed = Number(value.replace(/%$/u, "").replaceAll("_", ""));
return Number.isInteger(parsed) && Math.abs(parsed) <= 100;
}
function validSplitInstruction(value: string): boolean {
let percentRounding: string | null = null;
const parts = value.split(/\s*\+\s*/u);
- if (parts.length === 0) {
- return false;
- }
for (const part of parts) {
const match = SPLIT_PART_PATTERN.exec(part);
if (!match) {
@@ -68,8 +152,8 @@ function validSplitInstruction(value: string): boolean {
const [, , from, to, rounding] = match;
const usesPercent = from?.endsWith("%") || to?.endsWith("%");
if (
- !validPercentBoundary(from) ||
- !validPercentBoundary(to) ||
+ !validPercentBoundary(from, Boolean(usesPercent)) ||
+ !validPercentBoundary(to, Boolean(usesPercent)) ||
(rounding !== undefined && !usesPercent)
) {
return false;
@@ -99,6 +183,7 @@ export function validateManualDatasetSubset(
export function validateManualDatasetSplit(
value: string,
required: boolean,
+ allowInstructions = true,
): ManualDatasetOptionError | null {
const normalized = normalizeManualDatasetOption(value);
if (!normalized) {
@@ -108,5 +193,8 @@ export function validateManualDatasetSplit(
if (error) {
return error;
}
- return validSplitInstruction(normalized) ? null : "invalid";
+ const valid = allowInstructions
+ ? validSplitInstruction(normalized)
+ : BARE_SPLIT_PATTERN.test(normalized);
+ return valid ? null : "invalid";
}
diff --git a/studio/frontend/src/features/training/lib/start-fresh-training-run.ts b/studio/frontend/src/features/training/lib/start-fresh-training-run.ts
index d8aab676376..7bfc6d2814b 100644
--- a/studio/frontend/src/features/training/lib/start-fresh-training-run.ts
+++ b/studio/frontend/src/features/training/lib/start-fresh-training-run.ts
@@ -32,7 +32,7 @@ import { shouldUseVisionDatasetCheck } from "./fresh-dataset-check";
import { isMissingLocalDatasetCacheError } from "./local-cache-errors";
import { isRawTextDatasetFormat } from "./training-methods";
import { normalizeTrainingStartError } from "./training-start-errors";
-import { normalizeTrainingStartPayloadForComparison } from "./training-start-inputs";
+import { createTrainingStartInputIdentity } from "./training-start-inputs";
import {
TRAINING_SETUP_CHANGED_ERROR,
type TrainingStartLease,
@@ -56,15 +56,10 @@ const ROLE_REMAP: Record<string, Record<string, string>> = {
type AttemptPhase = "preflight" | "transport" | "finished";
function captureTrainingStartInputs(config: TrainingConfigState) {
- const payload = normalizeTrainingStartPayloadForComparison(
+ return createTrainingStartInputIdentity(
buildTrainingStartPayload(config, null),
+ config,
);
- return {
- payload,
- modelType: config.modelType,
- isVisionModel: config.isVisionModel,
- isAudioModel: config.isAudioModel,
- };
}
type TrainingStartInputs = ReturnType<typeof captureTrainingStartInputs>;
diff --git a/studio/frontend/src/features/training/lib/training-start-inputs.ts b/studio/frontend/src/features/training/lib/training-start-inputs.ts
index b6804e22bf5..eab2f441e82 100644
--- a/studio/frontend/src/features/training/lib/training-start-inputs.ts
+++ b/studio/frontend/src/features/training/lib/training-start-inputs.ts
@@ -2,8 +2,18 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import type { TrainingStartRequest } from "../types/api";
+import type { TrainingConfigState } from "../types/config";
import { isUntrainableModelFormat } from "./model-support";
+type TrainingStartIdentityConfig = Pick<
+ TrainingConfigState,
+ | "modelType"
+ | "isVisionModel"
+ | "isAudioModel"
+ | "manualDatasetOptionsValid"
+ | "userEditRevision"
+>;
+
export function normalizeTrainingStartPayloadForComparison(
payload: TrainingStartRequest,
): TrainingStartRequest {
@@ -13,3 +23,17 @@ export function normalizeTrainingStartPayloadForComparison(
: null;
return normalized;
}
+
+export function createTrainingStartInputIdentity(
+ payload: TrainingStartRequest,
+ config: TrainingStartIdentityConfig,
+) {
+ return {
+ payload: normalizeTrainingStartPayloadForComparison(payload),
+ modelType: config.modelType,
+ isVisionModel: config.isVisionModel,
+ isAudioModel: config.isAudioModel,
+ manualDatasetOptionsValid: config.manualDatasetOptionsValid,
+ userEditRevision: config.userEditRevision,
+ };
+}
diff --git a/studio/frontend/src/features/training/lib/validation.ts b/studio/frontend/src/features/training/lib/validation.ts
index 09ecbe349c5..4f1017515b2 100644
--- a/studio/frontend/src/features/training/lib/validation.ts
+++ b/studio/frontend/src/features/training/lib/validation.ts
@@ -5,6 +5,10 @@ import { validateHubResourceId } from "@/components/resource-picker/hub-resource
import type { TranslationKey } from "@/i18n";
import type { TrainingConfigState } from "../types/config";
import { requiresExplicitCachedDatasetSplit } from "./dataset-split-policy";
+import {
+ validateManualDatasetSplit,
+ validateManualDatasetSubset,
+} from "./manual-dataset-options";
import { isLocalTrainingModelSelection } from "./model-selection";
import { isUntrainableModelFormat } from "./model-support";
import {
@@ -98,12 +102,37 @@ function validateDatasetSelection(
errorKey: "studio.datasetPicker.reasonInvalidHubId",
};
}
- if (requiresExplicitCachedDatasetSplit(config)) {
+ if (config.manualDatasetOptionsValid === false) {
+ return {
+ ok: false,
+ errorKey: "studio.dataset.selectors.manualInvalid",
+ };
+ }
+ const requiresSplit = requiresExplicitCachedDatasetSplit(config);
+ if (requiresSplit) {
return {
ok: false,
errorKey: "studio.training.validation.hfDatasetSplitRequired",
};
}
+ if (
+ validateManualDatasetSubset(config.datasetSubset ?? "") !== null ||
+ validateManualDatasetSplit(
+ config.datasetSplit ?? "",
+ false,
+ !config.datasetStreaming,
+ ) !== null ||
+ validateManualDatasetSplit(
+ config.datasetEvalSplit ?? "",
+ false,
+ !config.datasetStreaming,
+ ) !== null
+ ) {
+ return {
+ ok: false,
+ errorKey: "studio.dataset.selectors.manualInvalid",
+ };
+ }
} else if (config.datasetSource === "upload") {
if (!config.uploadedFile) {
return {
diff --git a/studio/frontend/src/features/training/stores/training-config-persistence.ts b/studio/frontend/src/features/training/stores/training-config-persistence.ts
index dbfafa64025..f11ed5f139d 100644
--- a/studio/frontend/src/features/training/stores/training-config-persistence.ts
+++ b/studio/frontend/src/features/training/stores/training-config-persistence.ts
@@ -39,6 +39,7 @@ const NON_PERSISTED_STATE_KEYS: ReadonlySet<keyof TrainingConfigState> =
"isDatasetImage",
"isDatasetAudio",
"datasetCheckFailed",
+ "manualDatasetOptionsValid",
"trainOnCompletionsDefaultPendingFor",
"maxPositionEmbeddings",
"s3Config",
diff --git a/studio/frontend/src/features/training/stores/training-config-policy.ts b/studio/frontend/src/features/training/stores/training-config-policy.ts
index a3bf046c072..b07b8d1c543 100644
--- a/studio/frontend/src/features/training/stores/training-config-policy.ts
+++ b/studio/frontend/src/features/training/stores/training-config-policy.ts
@@ -83,6 +83,7 @@ export const initialTrainingConfigState: TrainingConfigState = {
datasetSplit: null,
datasetEvalSplit: null,
datasetStreaming: false,
+ manualDatasetOptionsValid: true,
datasetManualMapping: emptyManualMapping(),
datasetSystemPrompt: "",
datasetLabelMapping: {},
@@ -126,7 +127,9 @@ export function canProceedForTrainingStep(state: TrainingConfigState): boolean {
return validateS3Source(state).ok;
}
return (
- state.dataset !== null && !requiresExplicitCachedDatasetSplit(state)
+ state.dataset !== null &&
+ state.manualDatasetOptionsValid &&
+ !requiresExplicitCachedDatasetSplit(state)
);
}
case 4:
diff --git a/studio/frontend/src/features/training/stores/training-config-store.ts b/studio/frontend/src/features/training/stores/training-config-store.ts
index 94ebe72b81b..359b817ff17 100644
--- a/studio/frontend/src/features/training/stores/training-config-store.ts
+++ b/studio/frontend/src/features/training/stores/training-config-store.ts
@@ -617,6 +617,7 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(
datasetSubset: null,
datasetSplit: null,
datasetEvalSplit: null,
+ manualDatasetOptionsValid: true,
datasetManualMapping: emptyManualMapping(),
datasetSystemPrompt: "",
datasetLabelMapping: {},
@@ -1038,6 +1039,7 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(
datasetSubset: null,
datasetSplit: null,
datasetEvalSplit: null,
+ manualDatasetOptionsValid: true,
datasetManualMapping: emptyManualMapping(),
datasetSliceStart: null,
datasetSliceEnd: null,
@@ -1065,6 +1067,7 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(
datasetSubset,
datasetSplit: null,
datasetEvalSplit: null,
+ manualDatasetOptionsValid: true,
datasetManualMapping: emptyManualMapping(),
isDatasetImage: null,
isDatasetAudio: false,
@@ -1199,6 +1202,17 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(
);
}
},
+ setManualDatasetOptionsValid: (manualDatasetOptionsValid) =>
+ set((state) =>
+ state.manualDatasetOptionsValid === manualDatasetOptionsValid
+ ? state
+ : { manualDatasetOptionsValid },
+ ),
+ markManualDatasetOptionsEdited: (manualDatasetOptionsValid) =>
+ set((state) => ({
+ manualDatasetOptionsValid,
+ userEditRevision: state.userEditRevision + 1,
+ })),
setDatasetManualMapping: (datasetManualMapping) =>
setUserEdit({ datasetManualMapping }),
setDatasetAdvisorFields: (fields) =>
@@ -1232,6 +1246,7 @@ export const useTrainingConfigStore = create<TrainingConfigStore>()(
datasetSubset: null,
datasetSplit: null,
datasetEvalSplit: null,
+ manualDatasetOptionsValid: true,
datasetManualMapping: emptyManualMapping(),
datasetSliceStart: null,
datasetSliceEnd: null,
diff --git a/studio/frontend/src/features/training/types/config.ts b/studio/frontend/src/features/training/types/config.ts
index dad8eaa20a5..f0cbf3dbc5a 100644
--- a/studio/frontend/src/features/training/types/config.ts
+++ b/studio/frontend/src/features/training/types/config.ts
@@ -76,6 +76,7 @@ export interface TrainingConfigState {
datasetSplit: string | null;
datasetEvalSplit: string | null;
datasetStreaming: boolean;
+ manualDatasetOptionsValid: boolean;
datasetManualMapping: DatasetManualMapping;
datasetSystemPrompt: string;
datasetLabelMapping: Record<string, Record<string, string>>;
@@ -210,6 +211,8 @@ export interface TrainingConfigActions {
setDatasetSplit: (split: string | null) => void;
setDatasetEvalSplit: (split: string | null) => void;
setDatasetStreaming: (value: boolean) => void;
+ setManualDatasetOptionsValid: (value: boolean) => void;
+ markManualDatasetOptionsEdited: (optionsValid: boolean) => void;
setDatasetManualMapping: (mapping: DatasetManualMapping) => void;
setDatasetAdvisorFields: (fields: {
systemPrompt?: string;
diff --git a/studio/frontend/tests/manual-dataset-options.test.ts b/studio/frontend/tests/manual-dataset-options.test.ts
index eab38ee8893..f934e0d0a2d 100644
--- a/studio/frontend/tests/manual-dataset-options.test.ts
+++ b/studio/frontend/tests/manual-dataset-options.test.ts
@@ -5,8 +5,12 @@ import assert from "node:assert/strict";
import test from "node:test";
import {
+ type ManualDatasetOptionDrafts,
+ createManualDatasetOptionDrafts,
+ manualDatasetOptionsFormKey,
manualDatasetSplitDefault,
normalizeManualDatasetOption,
+ synchronizeManualDatasetOptionDrafts,
validateManualDatasetSplit,
validateManualDatasetSubset,
} from "../src/features/training/lib/manual-dataset-options.ts";
@@ -19,9 +23,11 @@ test("manual split defaults preserve remote behavior but require local certainty
test("manual dataset options accept backend-compatible config and split names", () => {
assert.equal(validateManualDatasetSubset("en_US-v2.1"), null);
assert.equal(validateManualDatasetSubset("config with spaces"), null);
+ assert.equal(validateManualDatasetSubset("cönfig"), null);
assert.equal(validateManualDatasetSubset("v1..v2"), null);
assert.equal(validateManualDatasetSubset(""), null);
assert.equal(validateManualDatasetSplit("validation", true), null);
+ assert.equal(validateManualDatasetSplit("tréin", true), null);
assert.equal(validateManualDatasetSplit("train.clean", true), null);
assert.equal(validateManualDatasetSplit("train[:10%]", true), null);
assert.equal(validateManualDatasetSplit("train[1_000:2_000]", true), null);
@@ -43,9 +49,14 @@ test("manual dataset options reject missing, traversing, and unsupported values"
assert.equal(validateManualDatasetSubset("config:name"), "invalid");
assert.equal(validateManualDatasetSubset("config\nname"), "invalid");
assert.equal(validateManualDatasetSplit("train/value", true), "invalid");
+ assert.equal(validateManualDatasetSplit("train-clean", true), "invalid");
assert.equal(validateManualDatasetSplit("train evil", true), "invalid");
assert.equal(validateManualDatasetSplit("train[10%", true), "invalid");
assert.equal(validateManualDatasetSplit("train[101%:]", true), "invalid");
+ assert.equal(validateManualDatasetSplit("train[101:20%]", true), "invalid");
+ assert.equal(validateManualDatasetSplit("train[-101:20%]", true), "invalid");
+ assert.equal(validateManualDatasetSubset("config\u200bname"), "invalid");
+ assert.equal(validateManualDatasetSubset("config\ud800name"), "invalid");
assert.equal(
validateManualDatasetSplit("train[10:20](closest)", true),
"invalid",
@@ -59,3 +70,117 @@ test("manual dataset options reject missing, traversing, and unsupported values"
);
assert.equal(validateManualDatasetSplit("x".repeat(129), true), "too_long");
});
+
+test("manual option length counts Unicode code points like the backend", () => {
+ const astralLetter = "\u{10400}";
+
+ assert.equal(validateManualDatasetSubset(astralLetter.repeat(128)), null);
+ assert.equal(
+ validateManualDatasetSubset(astralLetter.repeat(129)),
+ "too_long",
+ );
+ assert.equal(validateManualDatasetSplit(astralLetter.repeat(128), true), null);
+ assert.equal(
+ validateManualDatasetSplit(astralLetter.repeat(129), true),
+ "too_long",
+ );
+});
+
+test("manual form identity and field synchronization preserve unrelated drafts", () => {
+ const formKey = manualDatasetOptionsFormKey("org/dataset", null, false);
+ const initial = createManualDatasetOptionDrafts({
+ datasetSubset: null,
+ datasetSplit: "train",
+ datasetEvalSplit: null,
+ defaultSplit: "train",
+ });
+ const withInvalidSubset: ManualDatasetOptionDrafts = {
+ ...initial,
+ subset: {
+ ...initial.subset,
+ value: "../private",
+ error: "invalid",
+ },
+ };
+ const synchronized = synchronizeManualDatasetOptionDrafts(
+ withInvalidSubset,
+ {
+ datasetSubset: null,
+ datasetSplit: "validation",
+ datasetEvalSplit: null,
+ defaultSplit: "train",
+ },
+ );
+
+ assert.equal(
+ manualDatasetOptionsFormKey("org/dataset", null, false),
+ formKey,
+ );
+ assert.strictEqual(synchronized.subset, withInvalidSubset.subset);
+ assert.deepEqual(synchronized.subset, {
+ committedValue: null,
+ value: "../private",
+ error: "invalid",
+ });
+ assert.deepEqual(synchronized.split, {
+ committedValue: "validation",
+ value: "validation",
+ error: null,
+ });
+ assert.strictEqual(synchronized.evalSplit, withInvalidSubset.evalSplit);
+ assert.notEqual(
+ manualDatasetOptionsFormKey("org/other-dataset", null, false),
+ formKey,
+ );
+});
+
+test("manual field synchronization does not revive a draft after A to B to A", () => {
+ const atTrain: ManualDatasetOptionDrafts = {
+ ...createManualDatasetOptionDrafts({
+ datasetSubset: null,
+ datasetSplit: "train",
+ datasetEvalSplit: null,
+ defaultSplit: "train",
+ }),
+ split: {
+ committedValue: "train",
+ value: "train[",
+ error: "invalid",
+ },
+ };
+ const atValidation = synchronizeManualDatasetOptionDrafts(atTrain, {
+ datasetSubset: null,
+ datasetSplit: "validation",
+ datasetEvalSplit: null,
+ defaultSplit: "train",
+ });
+ const backAtTrain = synchronizeManualDatasetOptionDrafts(atValidation, {
+ datasetSubset: null,
+ datasetSplit: "train",
+ datasetEvalSplit: null,
+ defaultSplit: "train",
+ });
+
+ assert.deepEqual(atValidation.split, {
+ committedValue: "validation",
+ value: "validation",
+ error: null,
+ });
+ assert.deepEqual(backAtTrain.split, {
+ committedValue: "train",
+ value: "train",
+ error: null,
+ });
+});
+
+test("streaming manual options require bare split names", () => {
+ assert.equal(validateManualDatasetSplit("train", true, false), null);
+ assert.equal(
+ validateManualDatasetSplit("train[:10%]", true, false),
+ "invalid",
+ );
+ assert.equal(
+ validateManualDatasetSplit("train + validation", true, false),
+ "invalid",
+ );
+});
diff --git a/studio/frontend/tests/training-dataset-source-transitions.test.ts b/studio/frontend/tests/training-dataset-source-transitions.test.ts
index 3b93ca42208..3d3fd7f49fa 100644
--- a/studio/frontend/tests/training-dataset-source-transitions.test.ts
+++ b/studio/frontend/tests/training-dataset-source-transitions.test.ts
@@ -293,3 +293,18 @@ test("reselecting a non-Hub source repairs stale streaming state", () => {
assert.equal(useTrainingConfigStore.getState().evalSteps, 0.1);
}
});
+
+test("every manual dataset draft edit advances the user edit revision", () => {
+ resetState({ manualDatasetOptionsValid: true, userEditRevision: 41 });
+
+ useTrainingConfigStore.getState().markManualDatasetOptionsEdited(true);
+ assert.equal(useTrainingConfigStore.getState().userEditRevision, 42);
+ assert.equal(useTrainingConfigStore.getState().manualDatasetOptionsValid, true);
+
+ useTrainingConfigStore.getState().markManualDatasetOptionsEdited(false);
+ assert.equal(useTrainingConfigStore.getState().userEditRevision, 43);
+ assert.equal(
+ useTrainingConfigStore.getState().manualDatasetOptionsValid,
+ false,
+ );
+});
diff --git a/studio/frontend/tests/training-start-inputs.test.ts b/studio/frontend/tests/training-start-inputs.test.ts
index 76ff59799f3..eb084a03b54 100644
--- a/studio/frontend/tests/training-start-inputs.test.ts
+++ b/studio/frontend/tests/training-start-inputs.test.ts
@@ -9,7 +9,10 @@ import { registerBundlerResolver } from "./helpers/kit.ts";
registerBundlerResolver();
-const { normalizeTrainingStartPayloadForComparison } = await import(
+const {
+ createTrainingStartInputIdentity,
+ normalizeTrainingStartPayloadForComparison,
+} = await import(
"../src/features/training/lib/training-start-inputs.ts"
);
@@ -76,3 +79,29 @@ test("untrainable model formats remain part of training start identity", () => {
assert.equal(normalized.model_format, "gguf");
});
+
+test("manual draft edits remain part of training start identity before blur", () => {
+ const config = {
+ modelType: "text" as const,
+ isVisionModel: false,
+ isAudioModel: false,
+ manualDatasetOptionsValid: true,
+ userEditRevision: 7,
+ };
+ const identity = createTrainingStartInputIdentity(startPayload(), config);
+
+ assert.notDeepEqual(
+ createTrainingStartInputIdentity(startPayload(), {
+ ...config,
+ userEditRevision: 8,
+ }),
+ identity,
+ );
+ assert.notDeepEqual(
+ createTrainingStartInputIdentity(startPayload(), {
+ ...config,
+ manualDatasetOptionsValid: false,
+ }),
+ identity,
+ );
+});
diff --git a/studio/frontend/tests/training-validation.test.ts b/studio/frontend/tests/training-validation.test.ts
index 9b902311085..f76502e9eba 100644
--- a/studio/frontend/tests/training-validation.test.ts
+++ b/studio/frontend/tests/training-validation.test.ts
@@ -23,6 +23,7 @@ const validConfig = {
datasetSource: "huggingface" as const,
dataset: "org/dataset",
datasetSplit: "train",
+ manualDatasetOptionsValid: true,
uploadedFile: null,
s3Config: null,
modelType: "text" as const,
@@ -99,6 +100,41 @@ test("training validation requires an explicit split for local cached datasets",
);
});
+test("training validation blocks an invalid uncommitted manual dataset option", () => {
+ assert.deepEqual(
+ validateTrainingConfig({
+ ...validConfig,
+ manualDatasetOptionsValid: false,
+ }),
+ {
+ ok: false,
+ errorKey: "studio.dataset.selectors.manualInvalid",
+ },
+ );
+});
+
+test("training validation rejects committed split instructions in streaming mode", () => {
+ assert.deepEqual(
+ validateTrainingConfig({
+ ...validConfig,
+ datasetStreaming: true,
+ datasetSplit: "train + validation",
+ }),
+ {
+ ok: false,
+ errorKey: "studio.dataset.selectors.manualInvalid",
+ },
+ );
+ assert.deepEqual(
+ validateTrainingConfig({
+ ...validConfig,
+ datasetStreaming: true,
+ datasetSplit: "train",
+ }),
+ { ok: true, errorKey: null },
+ );
+});
+
test("training validation enforces the CPT embedding learning-rate range", () => {
for (const embeddingLearningRate of [0, 1, -0.0001, Number.NaN]) {
assert.deepEqual(
diff --git a/tests/studio/test_hf_token_validation_tick_contract.py b/tests/studio/test_hf_token_validation_tick_contract.py
index 0850a6bb858..78650de5bee 100644
--- a/tests/studio/test_hf_token_validation_tick_contract.py
+++ b/tests/studio/test_hf_token_validation_tick_contract.py
@@ -309,11 +309,14 @@ def test_training_start_aborts_when_semantic_config_or_token_changes():
assert "payload.model_local_path =" not in snapshot
assert "payload.dataset_known_cached =" not in snapshot
assert "payload.dataset_local_path =" not in snapshot
- assert "normalizeTrainingStartPayloadForComparison(" in snapshot
+ # The identity shape now lives in createTrainingStartInputIdentity, so assert the
+ # snapshot delegates to it and that the identity still normalizes and carries the flags.
+ assert "createTrainingStartInputIdentity(" in snapshot
+ assert "normalizeTrainingStartPayloadForComparison(" in start_inputs
assert "isUntrainableModelFormat(payload.model_format)" in start_inputs
- assert "modelType: config.modelType" in snapshot
- assert "isVisionModel: config.isVisionModel" in snapshot
- assert "isAudioModel: config.isAudioModel" in snapshot
+ assert "modelType: config.modelType" in start_inputs
+ assert "isVisionModel: config.isVisionModel" in start_inputs
+ assert "isAudioModel: config.isAudioModel" in start_inputs
assert "useTrainingConfigStore.getState() === this.expectedConfig" not in source
token_acceptance = source.split("acceptPreparedHfToken(token: string | null): boolean", 1)[
@@ -409,7 +412,9 @@ def test_superseded_start_cleanup_scopes_both_backend_mutations():
reset_transport = api.split("export async function resetTraining", 1)[1].split(
"export async function getTrainingStatus", 1
)[0]
- assert "const hasScope = scope?.expectedJobId !== undefined" in reset_transport
+ # The scope is no longer conditional: resetTraining takes a RequiredTrainingJobScope
+ # and always sends the body, which is strictly stronger than the old hasScope branch.
+ assert "scope: RequiredTrainingJobScope" in reset_transport
assert "body: scopedTrainingBody({}, scope)" in reset_transport