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.

223 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""
Training API routes
"""

from core.training.account_jobs import (
    account_event_stream,
    account_hf_token,
    account_path,
    job_busy,
    job_is_foreign,
    managed_account,
    require_job_owner,
    validate_job_paths,
)
import contextlib
import contextvars
import json
import os
import re
import sys
import threading
from collections import OrderedDict
from dataclasses import dataclass
from pathlib import Path
from fastapi import (
    APIRouter,
    Depends,
    File,
    Form,
    HTTPException,
    Path as ApiPath,
    Request,
    UploadFile,
)
from fastapi.responses import StreamingResponse
from typing import Dict, Literal, Optional, Any
import structlog
from loggers import get_logger
import asyncio
from datetime import datetime
import uuid as _uuid

backend_path = Path(__file__).parent.parent.parent
if str(backend_path) not in sys.path:
    sys.path.insert(0, str(backend_path))

try:
    from core.training import get_training_backend
    from core.training.diffusion_clip_formats import CLIP_EXTS as _CLIP_EXTS
    from core.training.eval_dataset import evaluation_enabled
    from core.training.training import (
        TrainingStartCancellationCapacityError,
        TrainingStatusIdentitySnapshot,
        normalize_training_optimizer_for_device,
    )
    from core.training.resume import (
        can_resume_run,
        get_resume_checkpoint_path,
        has_resume_state,
        normalize_resume_output_dir,
        training_run_config,
    )
    from storage.studio_db import get_resumable_run_by_output_dir
    from utils.models.model_config import (
        detect_gguf_model,
        is_decision_model,
        load_model_defaults,
    )
    from utils.paths import is_local_path, normalize_path, resolve_dataset_path
except ImportError:
    parent_backend = backend_path.parent / "backend"
    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.diffusion_clip_formats import CLIP_EXTS as _CLIP_EXTS
    from core.training.eval_dataset import evaluation_enabled
    from core.training.training import (
        TrainingStartCancellationCapacityError,
        TrainingStatusIdentitySnapshot,
        normalize_training_optimizer_for_device,
    )
    from core.training.resume import (
        can_resume_run,
        get_resume_checkpoint_path,
        has_resume_state,
        normalize_resume_output_dir,
        training_run_config,
    )
    from storage.studio_db import get_resumable_run_by_output_dir
    from utils.models.model_config import (
        detect_gguf_model,
        is_decision_model,
        load_model_defaults,
    )
    from utils.paths import is_local_path, normalize_path, resolve_dataset_path

from auth.authentication import authenticated_via_api_key, get_current_subject
from hub.dependencies import get_hf_token, get_request_hf_token
from hub.utils.host_paths import redact_host_paths
from hub.utils.hf_tokens import HfTokenArg, cached_read_refused, hf_token_arg

from utils.security.consent import managed_remote_code_refused
from utils.utils import (
    canonical_model_repo_id,
    hf_dns_dead,
    hf_env_offline,
    hf_reachability_memo,
    hf_unreachable,
    log_and_http_error,
)

from models import (
    TrainingStartRequest,
    TrainingStartRequestStatus,
    TrainingJobResponse,
    TrainingStatus,
    TrainingProgress,
)
from models.training import (
    DiffusionCaptionUpdateRequest,
    DiffusionDatasetExample,
    DiffusionDatasetExamplesResponse,
    DiffusionDatasetImageRecord,
    DiffusionDatasetImagesResponse,
    DiffusionDatasetImportRequest,
    DiffusionDatasetImportResponse,
    DiffusionDatasetSummary,
    DiffusionDatasetUploadResponse,
    DiffusionMetricHistory,
    DiffusionTrainableFamily,
    DiffusionTrainingInfoResponse,
    DiffusionTrainingRunDetail,
    DiffusionTrainingRunsResponse,
    DiffusionTrainingRunSummary,
    DiffusionTrainingStartRequest,
    DiffusionTrainingStartResponse,
    DiffusionTrainingStatusResponse,
    DiffusionTrainingStopRequest,
    TRAINING_REQUEST_ID_PATTERN,
    TokenPreviewRequest,
)
from models.responses import TrainingStopResponse, TrainingMetricsResponse
from pydantic import (
    BaseModel as PydanticBaseModel,
    Field as PydanticField,
    ValidationError,
)
from utils.paths.path_utils import drop_appledouble_metadata, is_appledouble_metadata


class TrainingStopRequest(PydanticBaseModel):
    save: bool = True
    expected_job_id: str = PydanticField(
        ...,
        min_length = 1,
        max_length = 128,
        pattern = TRAINING_REQUEST_ID_PATTERN,
    )


class TrainingResetRequest(PydanticBaseModel):
    # Optional: older clients post /reset with no body; the backend refuses an unscoped reset of a LIVE run.
    expected_job_id: Optional[str] = PydanticField(
        default = None,
        min_length = 1,
        max_length = 128,
        pattern = TRAINING_REQUEST_ID_PATTERN,
    )


router = APIRouter()
logger = get_logger(__name__)

_TRAINING_START_ERROR_RESPONSES = {
    400: {"description": "The requested training configuration or resource is not trainable"},
    409: {"description": "The requested start conflicts with offline, resume, or runtime state"},
    429: {"description": "Remote resource verification was rate-limited"},
    503: {"description": "Remote resource metadata is temporarily unavailable"},
}


def _hub_unreachable() -> bool:
    """Memoised probe, fails open; env-var offline checks miss a dead link that burns the timeout."""
    memo = hf_reachability_memo()
    if memo is not None:
        return memo
    return hf_dns_dead() or hf_unreachable()


_LOCAL_MODEL_PROBE_LIMIT = 2000
_REMOTE_MODEL_METADATA_TIMEOUT_SECONDS = 5.0
_REMOTE_MODEL_METADATA_RETRY_TIMEOUT_SECONDS = 10.0
_REMOTE_DATASET_METADATA_TIMEOUT_SECONDS = 5.0
_REMOTE_DATASET_METADATA_RETRY_TIMEOUT_SECONDS = 10.0


class _LocalModelProbeIncomplete(RuntimeError):
    pass


def _training_start_error(status_code: int, code: str, message: str) -> HTTPException:
    return HTTPException(
        status_code = status_code,
        detail = {"code": code, "message": message},
    )


def _hf_preflight_error(status_code: int, code: str, message: str) -> HTTPException:
    return _training_start_error(status_code, code, message)


def _http_exception_error(exc: HTTPException) -> tuple[str, Optional[str]]:
    detail = exc.detail
    if isinstance(detail, dict):
        message = detail.get("message")
        code = detail.get("code")
        if isinstance(message, str) and message:
            return message, code if isinstance(code, str) and code else None
    return str(detail), None


@dataclass(frozen = True)
class _ModelPreflightResult:
    model_name: str
    model_local_path: Optional[str]
    cached_model_pin: Optional[tuple[str, str]]
    # The base an admitted adapter named at preflight; the worker refuses a different one.
    adapter_base_pin: Optional[str] = None


# ~30 min of 1s polls. Applied only once stepping: model load + tokenization can take far longer.
_PROGRESS_STALL_TIMEOUT_POLLS = 1800


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():
        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:
    """Not terminal: the last step ends the loop, not the save; only is_completed ends the run."""
    if any(k in msg_lower for k in ("saving", "merging")):
        return True
    total = getattr(progress, "total_steps", 0) or 0
    step = getattr(progress, "step", 0) or 0
    return total > 0 and step >= total


def _run_finished(backend) -> bool:
    """Whether the run reported terminal (see TrainingBackend.is_run_finished), so status and
    progress stop waiting on the worker to exit. getattr-guarded like the other backend reads
    here: a stand-in without it keeps the old liveness-only behaviour."""
    check = getattr(backend, "is_run_finished", None)
    return bool(check()) if callable(check) else False


def _run_active(backend) -> bool:
    """Liveness minus terminal: a run that reported terminal is done even while its worker
    tears down. The GPU admission guards deliberately keep using is_training_active(), since
    a worker still winding down is still holding its VRAM."""
    return backend.is_training_active() and not _run_finished(backend)


def _validate_local_dataset_paths(paths: list[str], label: str = "Local dataset") -> list[str]:
    """Resolve and validate a list of local dataset paths. Returns validated absolute paths."""
    for path in paths:
        account_path(path)
    validated = []
    missing = []
    for dataset_path in paths:
        if not dataset_path.strip():
            raise HTTPException(
                status_code = 400,
                detail = f"{label} path must not be blank",
            )
        dataset_file = resolve_dataset_path(dataset_path)
        if not dataset_file.exists():
            missing.append(f"{dataset_path} (resolved: {dataset_file})")
            continue
        if is_appledouble_metadata(dataset_file):
            raise HTTPException(
                status_code = 400,
                detail = (
                    f"{label} '{dataset_path}' is macOS Finder metadata, not data. "
                    "Pick the file it sits beside."
                ),
            )
        logger.info(f"Found {label.lower()} file: {dataset_file}")
        validated.append(str(dataset_file))

    if missing:
        missing_detail = "; ".join(missing[:3])
        raise HTTPException(
            status_code = 400,
            detail = f"{label} not found: {missing_detail}",
        )
    return validated


def _start_request_response(record) -> TrainingJobResponse:
    return TrainingJobResponse(
        job_id = record.job_id,
        status = {
            "pending": "pending",
            "accepted": "queued",
            "rejected": "error",
        }[record.state],
        message = record.message,
        error = record.error,
        error_code = record.error_code,
    )


def _reject_start_request(
    backend,
    start_request_id: Optional[str],
    message: str,
    error_code: Optional[str] = None,
) -> None:
    if backend is None or start_request_id is None:
        return
    backend.resolve_start_request(
        start_request_id,
        state = "rejected",
        message = message,
        error = message,
        error_code = error_code,
    )


def _observe_training_start_task(task: asyncio.Task[bool]) -> None:
    if not task.cancelled():
        task.exception()


def _is_indexed_model_weight_name(name: str, expected_suffix: str) -> bool:
    lower = name.lower()
    return lower.endswith(expected_suffix) and not lower.startswith(
        ("adapter_model", "optimizer", "scheduler", "rng_state", "scaler")
    )


_MODEL_WEIGHT_CANDIDATES = (
    ("model.safetensors", None),
    ("model.safetensors.index.json", ".safetensors"),
    ("pytorch_model.bin", None),
    ("pytorch_model.bin.index.json", ".bin"),
)
_SHARDED_WEIGHT_NAME_PATTERN = re.compile(
    r"^(?P<family>.+)-(?P<part>\d+)-of-(?P<total>\d+)(?P<suffix>(?:\.[^.]+)+)$",
    re.IGNORECASE,
)


def _is_nonempty_file(path: Path) -> bool:
    try:
        return path.is_file() and path.stat().st_size > 0
    except (OSError, ValueError):
        return False


def _has_complete_indexed_weights(path: Path, index_name: str, expected_suffix: str) -> bool:
    snapshot = os.path.abspath(os.path.normpath(str(path)))
    snapshot_key = os.path.normcase(snapshot)
    try:
        index_text = (path / index_name).read_text(encoding = "utf-8-sig")
        payload = json.loads(index_text)
    except (OSError, UnicodeDecodeError, json.JSONDecodeError):
        return False
    weight_map = payload.get("weight_map") if isinstance(payload, dict) else None
    if not isinstance(weight_map, dict):
        return False
    shards = list(weight_map.values())
    if not shards or not all(isinstance(shard, str) and shard for shard in shards):
        return False
    families: dict[tuple[str, str, str, int], set[int]] = {}
    for shard in set(shards):
        joined = os.path.normpath(os.path.join(snapshot, shard))
        joined_key = os.path.normcase(joined)
        contained = joined_key == snapshot_key or joined_key.startswith(snapshot_key + os.sep)
        shard_path = Path(joined)
        if (
            not contained
            or not _is_indexed_model_weight_name(
                shard_path.name,
                expected_suffix,
            )
            or not _is_nonempty_file(shard_path)
        ):
            return False
        match = _SHARDED_WEIGHT_NAME_PATTERN.fullmatch(shard_path.name)
        if match is not None:
            part = int(match.group("part"))
            total = int(match.group("total"))
            if total < 1 or part < 0 or part > total:
                return False
            family = (
                os.path.normcase(str(shard_path.parent)),
                match.group("family").casefold(),
                match.group("suffix").casefold(),
                total,
            )
            families.setdefault(family, set()).add(part)
    # Some exporters number from zero; accept either complete run, never a mix.
    # count/min/max avoids building a range from the untrusted total.
    return all(
        len(parts) == total and (min(parts), max(parts)) in ((1, total), (0, total - 1))
        for (_, _, _, total), parts in families.items()
    )


def _trainable_local_roots(path: Path, model_name: Optional[str] = None) -> list[Path]:
    """The snapshot root plus any subdirectory a load reads from. Spark-TTS / BiCodec keep config.json
    and the weights under <snapshot>/LLM, so probing only the root reports a good cached model as
    having no trainable weights."""
    roots = [path]
    if not model_name:
        return roots
    from hub.utils.hf_cache_state import with_load_subdirs

    for name in with_load_subdirs(model_name, ("config.json",)):
        if "/" in name:
            candidate = path / name.rsplit("/", 1)[0]
            if candidate not in roots:
                roots.append(candidate)
    return roots


def _has_trainable_local_weights(path: Path, model_name: Optional[str] = None) -> bool:
    if model_name:
        return any(
            _has_trainable_local_weights(root) for root in _trainable_local_roots(path, model_name)
        )
    try:
        if not path.is_dir():
            return False
        config_text = (path / "config.json").read_text(encoding = "utf-8-sig")
        config = json.loads(config_text)
        if not isinstance(config, dict):
            return False
        for name, index_suffix in _MODEL_WEIGHT_CANDIDATES:
            candidate = path / name
            if not candidate.is_file():
                continue
            if index_suffix is None:
                return _is_nonempty_file(candidate)
            return _has_complete_indexed_weights(path, name, index_suffix)
        return False
    except (OSError, UnicodeDecodeError, json.JSONDecodeError):
        return False


def _has_adapter_metadata(path: Path) -> bool:
    return path.is_dir() and (path / "adapter_config.json").is_file()


def _continue_from_adapter_allowed(request: TrainingStartRequest) -> bool:
    """LoRA / CPT can load a saved adapter as the starting point; full finetune cannot (#13140).

    The embedding and decision runners always build a fresh adapter on top, so those still need
    a base model."""
    if request.training_type not in ("LoRA/QLoRA", "Continued Pretraining"):
        return False
    return not (getattr(request, "is_embedding", False) or getattr(request, "is_decision", False))


# The names PEFT and Unsloth's loader open; numbered adapter shards are not loaded.
_ADAPTER_WEIGHT_FILES = ("adapter_model.safetensors", "adapter_model.bin")
# The MLX loader imports PEFT safetensors (not .bin) and reads its own saved format.
_MLX_ADAPTER_WEIGHT_FILES = ("adapter_model.safetensors", "adapters.safetensors")


def _has_local_adapter_weights(path: Path) -> bool:
    if not path.is_dir():
        return False
    from core.training.training import should_use_mlx_training_backend

    names = (
        _MLX_ADAPTER_WEIGHT_FILES if should_use_mlx_training_backend() else _ADAPTER_WEIGHT_FILES
    )
    return any((path / name).is_file() for name in names)


_HF_MODEL_ACCESS_DENIED = (
    "Hugging Face denied access to this model. Add a valid Hugging Face "
    "token with repository access and accept any required access terms, "
    "then try again."
)


def _remote_untrainable_model_format(
    model_name: str,
    hf_token: HfTokenArg,
    is_embedding: bool = False,
) -> Optional[str]:
    from huggingface_hub import model_info as hf_model_info
    from hub.utils.hf_errors import hf_error_status
    from utils.models.unsloth_mirror import unsloth_public_mirror
    from utils.security import load_scan_target

    # Registry aliases ("Spark-TTS-0.5B/LLM") are not repos; probe the repo the trainer downloads.
    repo_id, load_subdirs = load_scan_target(canonical_model_repo_id(model_name), ())
    timeouts = (
        _REMOTE_MODEL_METADATA_TIMEOUT_SECONDS,
        _REMOTE_MODEL_METADATA_RETRY_TIMEOUT_SECONDS,
    )
    for attempt, timeout in enumerate(timeouts):
        try:
            info = hf_model_info(
                repo_id,
                token = account_hf_token(hf_token),
                timeout = timeout,
            )
            break
        except Exception as error:
            status_code = hf_error_status(error)
            if status_code is None:
                upstream_status = getattr(
                    getattr(error, "response", None),
                    "status_code",
                    None,
                )
                if isinstance(upstream_status, int) and 500 <= upstream_status < 600:
                    status_code = upstream_status
            transient_status = status_code in (408, 429) or (
                isinstance(status_code, int) and 500 <= status_code < 600
            )
            if status_code in (401, 403):
                raise _hf_preflight_error(
                    422,
                    "hf_model_access_denied",
                    _HF_MODEL_ACCESS_DENIED,
                ) from error
            retry_available = attempt + 1 < len(timeouts)
            if transient_status:
                if retry_available:
                    continue
                if status_code == 429:
                    raise _hf_preflight_error(
                        429,
                        "hf_model_verification_rate_limited",
                        "Hugging Face model verification is rate-limited. Retry shortly.",
                    ) from error
            elif status_code is not None:
                raise _hf_preflight_error(
                    status_code,
                    "hf_model_verification_failed",
                    (
                        "The Hugging Face model could not be verified. "
                        "Check the repository ID and your access token."
                    ),
                ) from error
            elif retry_available:
                continue
            logger.warning(
                "Could not inspect remote model files for %s after retry (%s)",
                model_name,
                type(error).__name__,
            )
            raise _hf_preflight_error(
                503,
                "hf_model_metadata_unavailable",
                (
                    "Hugging Face model metadata is temporarily unavailable. "
                    "Retry before starting training."
                ),
            ) from error

    # The worker's final mode (4-bit vs 16-bit) is unknowable here without importing torch/bnb, so a
    # mirror in EITHER mode admits. Unreadable mapper tables admit too. MLX and embedding runs never
    # consult the mapper, so they fetch the gated upstream and need the auth-check.
    from core.training.training import should_use_mlx_training_backend
    from utils.models.unsloth_mirror import mirror_lookup_available

    # Fail open only on the Torch path: MLX/embedding runs fetch the picked repo directly.
    torch_loader_path = not should_use_mlx_training_backend() and not is_embedding
    has_public_copy = torch_loader_path and (
        not mirror_lookup_available()
        or any(unsloth_public_mirror(repo_id, mode) is not None for mode in (True, False))
    )

    # Gated model metadata is public, so verify access to its files separately.
    if getattr(info, "gated", False) and not has_public_copy:
        from urllib.parse import quote
        from huggingface_hub import constants
        from huggingface_hub.utils import build_hf_headers, get_session, hf_raise_for_status

        url = f"{constants.ENDPOINT}/api/models/{quote(repo_id, safe = '/')}/auth-check"
        headers = build_hf_headers(token = account_hf_token(hf_token))
        # Retry transient failures, then fail open: only a definite denial may block a start.
        for attempt, timeout in enumerate(timeouts):
            try:
                hf_raise_for_status(get_session().get(url, headers = headers, timeout = timeout))
                break
            except Exception as error:
                status_code = hf_error_status(error)
                if status_code in (401, 403):
                    raise _hf_preflight_error(
                        422,
                        "hf_model_access_denied",
                        _HF_MODEL_ACCESS_DENIED,
                    ) from error
                if attempt + 1 < len(timeouts):
                    continue
                logger.warning(
                    "Could not verify access to gated %s (%s); starting anyway",
                    repo_id,
                    type(error).__name__,
                )

    load_roots = ("", *(f"{subdir.strip('/')}/" for subdir in load_subdirs if subdir))
    root_files: set[str] = set()
    has_gguf = False
    for sibling in getattr(info, "siblings", None) or ():
        name = getattr(sibling, "rfilename", None)
        if not isinstance(name, str):
            continue
        normalized = name.replace("\\", "/")
        if normalized.casefold().endswith(".gguf"):
            has_gguf = True
        for root in load_roots:
            if normalized.startswith(root) and "/" not in normalized[len(root) :]:
                root_files.add(normalized[len(root) :])
    if "adapter_config.json" in root_files:
        # Same weight files the local check accepts; config-only repos fail later in the loader.
        if any(name in root_files for name in _ADAPTER_WEIGHT_FILES):
            return "adapter"
        return "adapter_without_weights"
    has_trainable_weights = any(name in root_files for name, _ in _MODEL_WEIGHT_CANDIDATES)
    if has_gguf and not has_trainable_weights:
        return "gguf"
    return None


def _hf_dataset_is_the_source(request: Any) -> bool:
    """A Hub id beside local_datasets or s3_config is never loaded, so it cannot gate the start."""
    if getattr(request, "local_datasets", None):
        return False
    if getattr(request, "s3_config", None):
        return False
    return bool(getattr(request, "hf_dataset", None))


def _refuse_unauthorized_cached_dataset(
    request: TrainingStartRequest, hf_token: HfTokenArg
) -> None:
    from hub.utils.dataset_cache import dataset_cache_can_answer, training_dataset_cache_pin

    dataset_id = request.hf_dataset

    def has_cached_dataset():
        if dataset_cache_can_answer(dataset_id):
            return True
        pin, _ = training_dataset_cache_pin(
            dataset_id,
            request.dataset_snapshot_path or request.dataset_local_path,
        )
        return pin is not None

    # Cached and offline starts skip the Hub check below, and the worker then loads the cache.
    if cached_read_refused(
        hf_token,
        repo_id = dataset_id,
        repo_type = "dataset",
        is_cached = has_cached_dataset,
        offline = hf_env_offline(),
    ):
        raise _hf_preflight_error(
            422,
            "hf_dataset_access_denied",
            "Hugging Face denied access to this cached dataset. Add a token with repository access.",
        )


def _refuse_unauthorized_cached_local_paths(
    paths: list[str],
    hf_token: HfTokenArg,
    label: str = "dataset",
) -> None:
    """Local paths into the Hub cache are private repos in disguise; refused unless authorized."""
    from hub.utils.hf_cache_state import (
        cached_repo_ref_for_path,
        repo_cache_has_usable_snapshot,
    )

    repo_type = "dataset" if label.endswith("dataset") else label

    def cached_under_its_own_id(repo_id: str):
        # The remote probe can fail open and an offline worker reads the cache, so ask the disk.
        # Check for a SNAPSHOT, not the repo dir: an interrupted download leaves an empty repo dir.
        # No metadata filter (name differs by family). Unreadable still counts.
        def probe() -> bool:
            return repo_cache_has_usable_snapshot(repo_type, repo_id)

        return probe

    for dataset_path in paths:
        candidate = (dataset_path or "").strip()
        if not candidate:
            continue
        cached_ref = cached_repo_ref_for_path(candidate)
        if cached_ref is None:
            if is_local_path(candidate) or candidate.count("/") != 1:
                continue
            cached_ref = (candidate, repo_type)
            is_cached = cached_under_its_own_id(candidate)
        else:
            is_cached = lambda: True  # noqa: E731 -- the path itself is the evidence
        if cached_read_refused(
            hf_token,
            repo_id = cached_ref[0],
            repo_type = cached_ref[1],
            is_cached = is_cached,
            offline = hf_env_offline(),
        ):
            raise _hf_preflight_error(
                422,
                f"hf_{label}_access_denied",
                (
                    f"Hugging Face denied access to this cached {label}. "
                    "Add a token with repository access."
                ),
            )


def _preflight_hf_dataset_request(request: TrainingStartRequest) -> None:
    dataset_id = request.hf_dataset
    if not dataset_id:
        return

    from huggingface_hub.utils import HFValidationError, validate_repo_id

    try:
        validate_repo_id(dataset_id)
    except HFValidationError as error:
        raise _hf_preflight_error(
            400,
            "hf_dataset_verification_failed",
            (
                "The Hugging Face dataset could not be verified. "
                "Check the repository ID and your access token."
            ),
        ) from error

    cached_path = None
    if not request.dataset_streaming:
        from hub.utils.dataset_cache import training_dataset_cache_pin

        cached_path, _ = training_dataset_cache_pin(
            dataset_id,
            request.dataset_snapshot_path or request.dataset_local_path,
        )
        # Only a start that pins the cache may skip Hub verification; an unpinned start still downloads.
        pins_cache = bool(
            request.dataset_known_cached
            or request.dataset_local_path
            or request.dataset_snapshot_path
        )
        if cached_path is not None and pins_cache:
            return

    if hf_env_offline() or _hub_unreachable():
        if request.dataset_streaming:
            raise _hf_preflight_error(
                409,
                "hf_dataset_streaming_offline",
                (
                    "Streaming requires access to the Hugging Face Hub, which cannot be "
                    "reached while offline. Disable streaming to use a cached dataset."
                ),
            )
        if cached_path is not None:
            # No Hub probe ran and no cached claim was made, so grants must authorize it.
            _authorize_cache_fallback(dataset_id, "dataset")
            return
        raise _hf_preflight_error(
            409,
            "hf_dataset_not_cached_offline",
            (
                "The selected Hugging Face dataset is not available in the local cache, "
                "and Hugging Face cannot be reached while offline."
            ),
        )

    from hub.utils.hf_errors import hf_error_status
    from huggingface_hub import HfApi

    api = HfApi(token = request.hf_token or False)
    timeouts = (
        _REMOTE_DATASET_METADATA_TIMEOUT_SECONDS,
        _REMOTE_DATASET_METADATA_RETRY_TIMEOUT_SECONDS,
    )
    for attempt, timeout in enumerate(timeouts):
        try:
            api.dataset_info(dataset_id, timeout = timeout)
            return
        except Exception as error:
            status_code = hf_error_status(error)
            if status_code is None:
                upstream_status = getattr(
                    getattr(error, "response", None),
                    "status_code",
                    None,
                )
                if isinstance(upstream_status, int) and 500 <= upstream_status < 600:
                    status_code = upstream_status
            transient_status = status_code in (408, 429) or (
                isinstance(status_code, int) and 500 <= status_code < 600
            )
            if status_code in (401, 403):
                raise _hf_preflight_error(
                    422,
                    "hf_dataset_access_denied",
                    (
                        "Hugging Face denied access to this dataset. Add a valid Hugging "
                        "Face token with repository access and accept any required access "
                        "terms, then try again."
                    ),
                ) from error
            retry_available = attempt + 1 < len(timeouts)
            if transient_status:
                if retry_available:
                    continue
                if status_code == 429:
                    raise _hf_preflight_error(
                        429,
                        "hf_dataset_verification_rate_limited",
                        "Hugging Face dataset verification is rate-limited. Retry shortly.",
                    ) from error
            elif status_code is not None:
                raise _hf_preflight_error(
                    status_code,
                    "hf_dataset_verification_failed",
                    (
                        "The Hugging Face dataset could not be verified. "
                        "Check the repository ID and your access token."
                    ),
                ) from error
            elif retry_available:
                continue
            logger.warning(
                "Could not verify Hugging Face dataset %s after retry (%s)",
                dataset_id,
                type(error).__name__,
            )
            raise _hf_preflight_error(
                503,
                "hf_dataset_metadata_unavailable",
                (
                    "Hugging Face dataset metadata is temporarily unavailable. "
                    "Retry before starting training."
                ),
            ) from error


def _detect_local_gguf(path: Path) -> Optional[str]:
    try:
        try:
            is_directory = path.is_dir()
        except OSError:
            if path.suffix.lower() == ".gguf":
                return detect_gguf_model(str(path))
            raise
        if not is_directory:
            return detect_gguf_model(str(path))
        for index, entry in enumerate(path.rglob("*"), start = 1):
            if index > _LOCAL_MODEL_PROBE_LIMIT:
                raise _LocalModelProbeIncomplete
            if entry.suffix.lower() != ".gguf":
                continue
            detected = detect_gguf_model(str(entry))
            if detected is not None:
                return detected
    except _LocalModelProbeIncomplete:
        raise
    except (OSError, RuntimeError) as error:
        raise _LocalModelProbeIncomplete from error
    return None


def _authorize_cache_fallback(model_name: str, repo_type: str = "model") -> None:
    """A shared-cache snapshot was never authorized by the caller's token, so grants must be."""
    if managed_account():
        from hub.services.models import account_access
        reference = canonical_model_repo_id(model_name) if repo_type == "model" else model_name
        account_access.require_model_access(reference, repo_type)


def _refuse_hub_adapter_continuation(request: TrainingStartRequest) -> None:
    # Only saved local adapter folders are continued (#13140). A Hub adapter's tokenizer,
    # base capabilities and revision are resolved differently by the loader; follow-up work.
    if not is_local_path(request.model_name):
        raise _training_start_error(
            400,
            "training_hub_adapter_unsupported",
            "Continuing from a Hugging Face adapter repository is not supported yet. "
            "Download it to a local folder and select that folder.",
        )


def _refuse_multimodal_adapter_continuation(request: TrainingStartRequest) -> None:
    # The modality probes read the adapter, not its base, so an image or audio run would be
    # formatted as text. Refuse it until the base is resolved for those probes (#13140).
    if request.is_dataset_image or request.is_dataset_audio:
        raise _training_start_error(
            400,
            "training_adapter_multimodal_unsupported",
            "Continuing a saved adapter on an image or audio dataset is not supported yet. "
            "Start from its base model instead.",
        )


def _authorize_adapter_base(adapter: str, hf_token: HfTokenArg) -> Optional[str]:
    """A continued adapter also loads the base it names. Check that base the way the adapter
    was checked, or a public adapter could open a private base from the shared cache (#13140)."""
    from hub.utils.hf_cache_state import (
        cached_repo_ref_for_path,
        repo_cache_has_usable_snapshot,
    )
    from utils.models.model_config import get_base_model_from_lora_identifier

    base = get_base_model_from_lora_identifier(adapter, account_hf_token(hf_token))
    if not base:
        return None
    if is_local_path(base):
        # A managed account may only reach bases in its own workspace or the shared cache.
        account_path(base, shared_cache = True)
        base_path = Path(base).expanduser()
        if not base_path.is_dir():
            raise _training_start_error(
                400,
                "training_adapter_base_missing",
                "The base model folder this adapter names no longer exists.",
            )
        if not _has_trainable_local_weights(base_path):
            raise _training_start_error(
                400,
                "training_adapter_base_not_trainable",
                "The base model folder this adapter names has no trainable weights.",
            )
        # A base path inside the Hub cache is still that repository's cached weights.
        cached_ref = cached_repo_ref_for_path(base)
        if cached_ref is None:
            return base
        repo_id, repo_type = cached_ref
        is_cached = lambda: True  # noqa: E731 -- the path itself is the evidence
        # Reading the shared cache needs a grant, as for a selected cached model.
        _authorize_cache_fallback(repo_id, repo_type)
    else:
        repo_id, repo_type = canonical_model_repo_id(base), "model"
        is_cached = lambda: repo_cache_has_usable_snapshot("model", repo_id)  # noqa: E731
        # Like the selected model: a grant is needed only to read the shared cache, not the Hub.
        if is_cached():
            _authorize_cache_fallback(base)
        if hf_env_offline() and not is_cached():
            raise _hf_preflight_error(
                409,
                "hf_model_not_cached_offline",
                (
                    "Offline mode is enabled, but this adapter's base model is not available "
                    "in the local cache. Disable offline mode to download it before starting "
                    "training."
                ),
            )
        if not is_cached():
            # The same Hub probe a selected model gets: a private, missing or misspelled base
            # fails here with its access or not-found error, not later in the loader.
            if _remote_untrainable_model_format(base, hf_token) is not None:
                raise _training_start_error(
                    400,
                    "training_adapter_base_not_trainable",
                    "The base model this adapter names is GGUF-only or adapter-only, "
                    "so it cannot be trained.",
                )
    if cached_read_refused(
        hf_token,
        repo_id = repo_id,
        repo_type = repo_type,
        is_cached = is_cached,
        offline = hf_env_offline(),
    ):
        raise _hf_preflight_error(
            422,
            "hf_model_access_denied",
            "Hugging Face denied access to this adapter's cached base model. "
            "Add a token with repository access.",
        )
    return base


def _is_decision_checkpoint(request: TrainingStartRequest) -> bool:
    # A Laya or Clef checkpoint, not an LLM that is trained with a new decision head.
    return bool(request.is_decision) and request.decision_layout != "llm"


def _reject_untrainable_model_request(
    request: TrainingStartRequest,
    actual_model_repo_id: Optional[str] = None,
    hf_token: HfTokenArg = None,
) -> _ModelPreflightResult:
    model_format = (request.model_format or "").strip().lower()
    if model_format == "gguf":
        raise _training_start_error(
            400,
            "training_model_gguf_not_trainable",
            "GGUF models are inference-only and cannot be trained.",
        )
    if model_format == "adapter" and not _continue_from_adapter_allowed(request):
        raise _training_start_error(
            400,
            "training_model_adapter_not_trainable",
            "Adapter models are inference-only and cannot be trained as base models.",
        )
    path: Optional[Path] = None
    model_name = request.model_name
    model_local_path: Optional[str] = None
    cached_model_pin: Optional[tuple[str, str]] = None
    offline_mode = False
    if is_local_path(request.model_name):
        try:
            path = Path(normalize_path(request.model_name)).expanduser().resolve(strict = True)
        except (OSError, RuntimeError, ValueError) as error:
            raise _training_start_error(
                400,
                "training_local_model_unavailable",
                "Local model path was not found or could not be accessed.",
            ) from error
        model_name = str(path)
        if request.model_local_path:
            model_local_path = (
                model_name
                if request.model_local_path == request.model_name
                else normalize_path(request.model_local_path)
            )
        from hub.utils.hf_cache_state import cached_repo_ref_for_path

        # Any repo type counts: a dataset or space snapshot can hold config.json plus weights.
        cached_ref = cached_repo_ref_for_path(path)
        if cached_ref is not None and cached_read_refused(
            hf_token,
            repo_id = cached_ref[0],
            repo_type = cached_ref[1],
            is_cached = lambda: True,
            offline = hf_env_offline(),
        ):
            raise _hf_preflight_error(
                422,
                "hf_model_access_denied",
                "Hugging Face denied access to this cached model. Add a token with repository access.",
            )
    else:
        model_local_path = (
            normalize_path(request.model_local_path) if request.model_local_path else None
        )
        from hub.utils.hf_cache_state import (
            latest_snapshot_from_cache_path,
            with_load_subdirs,
        )

        snapshot = None
        offline_mode = hf_env_offline()
        if request.resume_from_checkpoint and request.model_snapshot_path:
            snapshot = latest_snapshot_from_cache_path(
                request.model_snapshot_path,
                "model",
                canonical_model_repo_id(actual_model_repo_id or request.model_name),
                with_load_subdirs(request.model_name, ("config.json", "adapter_config.json")),
            )
        elif request.model_known_cached or request.model_local_path or offline_mode:
            from core.training.training import _resolve_model_snapshot
            snapshot = _resolve_model_snapshot(
                request.model_name,
                model_local_path,
            )
            if snapshot and not model_local_path:
                _authorize_cache_fallback(request.model_name)
        if snapshot:
            path = Path(snapshot)
            if offline_mode and not request.resume_from_checkpoint:
                cached_model_pin = (
                    canonical_model_repo_id(request.model_name),
                    snapshot,
                )
        from hub.utils.hf_cache_state import repo_cache_has_usable_snapshot
        from utils.security import load_scan_target

        authorization_repo, _ = load_scan_target(
            canonical_model_repo_id(actual_model_repo_id or request.model_name), ()
        )

        def has_cached_model():
            if snapshot:
                return True
            # A repo dir without a snapshot is not a cached read; an unreadable root still counts (fail-closed).
            return repo_cache_has_usable_snapshot(
                "model",
                authorization_repo,
                with_load_subdirs(request.model_name, ("config.json", "adapter_config.json")),
            )

        def refuse_unauthorized_cache(is_cached):
            # HF can reuse cached weights even when remote metadata/HEAD denies access.
            if cached_read_refused(
                hf_token,
                repo_id = authorization_repo,
                is_cached = is_cached,
                offline = offline_mode,
            ):
                raise _hf_preflight_error(
                    422,
                    "hf_model_access_denied",
                    "Hugging Face denied access to this cached model. Add a token with repository access.",
                )

        refuse_unauthorized_cache(has_cached_model)
        if _is_decision_checkpoint(request):
            from core.systemone import laya_runtime
            from core.systemone.catalog import Checkpoint

            # Laya caches only the files a checkpoint loads, which the snapshot lookup above misses.
            if laya_runtime.is_cached(
                Checkpoint(
                    "base",
                    request.model_name,
                    request.model_subfolder,
                    "",
                    layout = request.decision_layout or "laya",
                )
            ):
                refuse_unauthorized_cache(lambda: True)
                return _ModelPreflightResult(model_name, model_local_path, None)
    if path is None and offline_mode:
        raise _hf_preflight_error(
            409,
            "hf_model_not_cached_offline",
            (
                "Offline mode is enabled, but the selected model is not available in the "
                "local cache. Disable offline mode to download it, or select an on-device "
                "model before starting training."
            ),
        )
    metadata_error: Optional[HTTPException] = None
    if path is None:
        try:
            # Raised inside the try on purpose: the HTTPException handler still pins a cached snapshot.
            if _hub_unreachable():
                raise _hf_preflight_error(
                    503,
                    "hf_model_metadata_unavailable",
                    (
                        "Hugging Face model metadata is temporarily unavailable. "
                        "Retry before starting training."
                    ),
                )
            # A decision checkpoint is checked at its subfolder below, whatever the repo root holds.
            remote_format = (
                None
                if _is_decision_checkpoint(request)
                else _remote_untrainable_model_format(
                    request.model_name,
                    hf_token,
                    is_embedding = bool(getattr(request, "is_embedding", False)),
                )
            )
        except HTTPException as error:
            metadata_error = error
            from core.training.training import _resolve_model_snapshot

            snapshot = _resolve_model_snapshot(
                request.model_name,
                model_local_path,
            )
            if snapshot is None:
                raise
            # The snapshot can land while the metadata probe is in flight.
            refuse_unauthorized_cache(lambda: True)
            # Independent axes: caller's HF token access vs managed-account grant.
            _authorize_cache_fallback(request.model_name)
            path = Path(snapshot)
            cached_model_pin = (
                canonical_model_repo_id(request.model_name),
                snapshot,
            )
        else:
            if remote_format is None:
                if _is_decision_checkpoint(request) and not is_decision_model(
                    request.model_name, hf_token, subfolder = request.model_subfolder
                ):
                    raise _training_start_error(
                        400,
                        "training_remote_model_not_decision",
                        f"{request.model_name} is not a decision model (Laya or Clef).",
                    )
                if _is_decision_checkpoint(request) and managed_account():
                    # A Hub decision adapter loads its base as well: authorize it like any adapter.
                    _authorize_adapter_base(request.model_name, hf_token)
                return _ModelPreflightResult(model_name, model_local_path, cached_model_pin)
            if remote_format == "gguf":
                raise _training_start_error(
                    400,
                    "training_remote_model_gguf_only",
                    "GGUF-only remote models are inference-only and cannot be trained.",
                )
            if not _continue_from_adapter_allowed(request):
                raise _training_start_error(
                    400,
                    "training_remote_model_adapter_only",
                    "Adapter models are inference-only and cannot be trained as base models.",
                )
            if remote_format == "adapter_without_weights":
                raise _training_start_error(
                    400,
                    "training_remote_model_adapter_weights_missing",
                    "Adapter repository is missing adapter_model weights.",
                )
            _refuse_hub_adapter_continuation(request)
            _refuse_multimodal_adapter_continuation(request)
            _authorize_adapter_base(request.model_name, hf_token)
            return _ModelPreflightResult(model_name, model_local_path, cached_model_pin)
    if _is_decision_checkpoint(request):
        folder = path / request.model_subfolder if request.model_subfolder else path
        if not is_decision_model(str(folder)):
            raise _training_start_error(
                400,
                "training_local_model_not_decision",
                "The selected model is not a decision checkpoint: Laya needs "
                "rl_agent_config.json, model.safetensors, encoder/ and tokenizer/, and Clef "
                "needs joint_head.safetensors and joint_head_config.json beside config.json "
                "(or LoRA adapters).",
            )
        if managed_account() and _has_adapter_metadata(folder):
            # FastDecisionModel loads the adapter's base: check and pin it like any adapter.
            from core.export.decision import DecisionExportError, adapter_base

            try:
                adapter_base(folder)
            except DecisionExportError as exc:
                raise _training_start_error(400, "training_decision_adapter_base", str(exc))
            base = _authorize_adapter_base(str(folder), hf_token)
            # The worker re-reads the pin at the model root, so pin only a root adapter.
            pin = None if request.model_subfolder else base or ""
            return _ModelPreflightResult(model_name, model_local_path, None, adapter_base_pin = pin)
        return _ModelPreflightResult(model_name, model_local_path, None)
    has_trainable_weights = _has_trainable_local_weights(path, request.model_name)
    if has_trainable_weights:
        if managed_account() and _has_adapter_metadata(path):
            # The loader still follows adapter_config.json to its base, so check and pin it.
            adapter_base = _authorize_adapter_base(str(path), hf_token)
            return _ModelPreflightResult(
                model_name, model_local_path, cached_model_pin, adapter_base_pin = adapter_base or ""
            )
        return _ModelPreflightResult(model_name, model_local_path, cached_model_pin)
    if _has_adapter_metadata(path) or (
        model_format == "adapter" and _has_local_adapter_weights(path)
    ):
        if not _continue_from_adapter_allowed(request):
            raise _training_start_error(
                400,
                "training_local_model_adapter_only",
                "Adapter-only local models are inference-only and cannot be trained as base models.",
            )
        if not _has_local_adapter_weights(path):
            raise _training_start_error(
                400,
                "training_local_model_adapter_weights_missing",
                "Adapter directory is missing adapter_model weights.",
            )
        # The loader needs adapter_config.json to find the base model.
        if not _has_adapter_metadata(path):
            raise _training_start_error(
                400,
                "training_local_model_adapter_config_missing",
                "Adapter directory is missing adapter_config.json.",
            )
        _refuse_hub_adapter_continuation(request)
        _refuse_multimodal_adapter_continuation(request)
        adapter_base = _authorize_adapter_base(str(path), hf_token)
        return _ModelPreflightResult(
            model_name, model_local_path, cached_model_pin, adapter_base_pin = adapter_base or ""
        )
    try:
        has_gguf = _detect_local_gguf(path) is not None
    except _LocalModelProbeIncomplete:
        raise _training_start_error(
            400,
            "training_local_model_scan_incomplete",
            (
                "The local model directory is too large or could not be read safely. "
                "Select its snapshot directory containing config.json and trainable weights."
            ),
        )
    if has_gguf:
        raise _training_start_error(
            400,
            "training_local_model_gguf_only",
            "GGUF-only local models are inference-only and cannot be trained.",
        )
    if metadata_error is not None:
        raise metadata_error
    raise _training_start_error(
        400,
        "training_local_model_weights_missing",
        "The selected local model does not contain trainable weights.",
    )


def _validate_training_platform(request: TrainingStartRequest) -> None:
    from utils.hardware import hardware

    if hardware.DEVICE == hardware.DeviceType.CPU and hardware.trains_on_cpu(
        hardware.current_chat_only_verdict()[0]
    ):
        # The CPU backend (unsloth/_cpu_init.py) trains text models with SFTTrainer only.
        if request.is_dataset_image or request.is_dataset_audio:
            unsupported = "Vision and audio training"
        elif request.is_embedding:
            unsupported = "Embedding model training"
        elif request.is_decision:
            unsupported = "Decision model training"
        elif request.drafter is not None and request.drafter.enabled:
            unsupported = "Drafter training"
        else:
            return
        raise HTTPException(
            status_code = 400,
            detail = (
                f"{unsupported} is not supported on CPU yet. No GPU was found, so this host "
                "trains text models only (LoRA or full finetuning)."
            ),
        )
    if hardware.DEVICE != hardware.DeviceType.MLX:
        return
    if request.is_embedding:
        raise HTTPException(
            status_code = 400,
            detail = "Embedding model training is not supported for MLX training yet.",
        )
    if request.use_loftq:
        raise HTTPException(
            status_code = 400,
            detail = "LoftQ is not supported for MLX training yet.",
        )


# A plain folder name: no separators, globs, drive letters or dot segments.
_CHECKPOINT_SUBFOLDER = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}")
# The frontend's LR_DEFAULT_DECISION_FULL; the model defaults hold the LoRA rate.
_DECISION_FULL_FINETUNING_LR = "2.5e-5"


def _validate_decision_request(request: TrainingStartRequest, via_api_key: bool = False) -> None:
    request.decision_layout = None
    if not request.is_decision:
        return
    # Decision models train on one GPU, so admission and chat coexistence are sized for that one.
    if request.gpu_ids and len(request.gpu_ids) > 1:
        request.gpu_ids = request.gpu_ids[:1]
    from core.systemone.catalog import CHECKPOINTS, CLEF_DEFAULTS_REPO, LAYA_REPO
    from utils.account_context import is_owner_context
    from utils.models.model_config import decision_layout

    if not is_owner_context():
        raise HTTPException(
            status_code = 403,
            detail = "Only the Unsloth owner can fine-tune decision models, since only the "
            "owner's fine-tunes can be served by the Decision API.",
        )
    if sys.version_info < (3, 10):
        raise HTTPException(
            status_code = 400,
            detail = "Decision model training needs Python 3.10 or newer, like the Decision "
            "API that serves the fine-tunes.",
        )
    if request.training_type == "Continued Pretraining":
        raise HTTPException(
            status_code = 400,
            detail = "Decision models train with LoRA or full fine-tuning; continued "
            "pretraining is not available for them.",
        )
    if request.resume_from_checkpoint:
        raise HTTPException(
            status_code = 400,
            detail = "Decision model runs cannot be resumed; start a new run instead.",
        )
    if request.dataset_streaming:
        raise HTTPException(
            status_code = 400,
            detail = "dataset_streaming is not supported for decision model training.",
        )
    unset = TrainingStartRequest.model_fields.keys() - request.model_fields_set
    # Unknown (offline, no access) stays Laya: the preflight then names what is missing.
    layout = decision_layout(
        request.model_name,
        hf_token_arg(request.hf_token, allow_ambient_token = via_api_key is not True),
        subfolder = request.model_subfolder,
    )
    # A subfolder or a catalog repo still means Laya, so an uncached Laya checkpoint is not loaded as an LLM.
    llm = (
        layout is None
        and request.model_subfolder is None
        and request.model_name not in {c.source for c in CHECKPOINTS.values()}
    )
    if layout == "clef" or llm:
        from core.systemone.catalog import clef_unsupported_reason
        from utils.hardware import hardware

        # Apple Silicon trains Clef with MLX; elsewhere it needs the GPU the torch path runs on.
        mlx = hardware.get_device() == hardware.DeviceType.MLX
        if not mlx and (reason := clef_unsupported_reason()) is not None:
            raise HTTPException(status_code = 400, detail = reason)
        request.decision_layout = "llm" if llm else "clef"
        if request.model_subfolder is not None:
            raise HTTPException(
                status_code = 400,
                detail = "Clef repos hold one checkpoint, so model_subfolder must be left out.",
            )
        if request.use_dora or request.use_loftq:
            raise HTTPException(
                status_code = 400,
                detail = "Decision models train with plain LoRA, so DoRA and LoftQ are not "
                "available for them.",
            )
        if llm:
            from utils.models.model_config import load_llm_decision_defaults
            defaults = load_llm_decision_defaults()
        else:
            defaults = load_model_defaults(request.model_name)
            if defaults == load_model_defaults("default"):
                defaults = load_model_defaults(CLEF_DEFAULTS_REPO)
        for section in ("training", "lora", "logging"):
            for key, value in (defaults.get(section) or {}).items():
                if key in unset:
                    setattr(request, key, value)
        if "learning_rate" in unset and request.training_type == "Full Finetuning":
            request.learning_rate = _DECISION_FULL_FINETUNING_LR
        return
    request.decision_layout = "laya"
    if (
        request.training_type == "LoRA/QLoRA"
        and request.load_in_4bit
        and "load_in_4bit" not in unset
    ):
        raise HTTPException(
            status_code = 400,
            detail = "Decision models train in 16-bit, so QLoRA is not available for them. "
            "Set load_in_4bit to false to train with LoRA.",
        )
    subfolder = request.model_subfolder
    if subfolder is not None and (
        not _CHECKPOINT_SUBFOLDER.fullmatch(subfolder)
        or (
            request.model_name == LAYA_REPO
            and subfolder not in {c.subfolder for c in CHECKPOINTS.values()}
        )
    ):
        raise HTTPException(
            status_code = 400,
            detail = f"Invalid checkpoint subfolder {subfolder!r} for {request.model_name}.",
        )
    if request.use_dora or request.use_loftq:
        raise HTTPException(
            status_code = 400,
            detail = "Decision models train with plain LoRA, so DoRA and LoftQ are not "
            "available for them.",
        )
    request.load_in_4bit = False
    # Fields an API or MCP caller left out take the Laya recipe the UI starts from.
    defaults = load_model_defaults(LAYA_REPO)
    for section in ("training", "lora", "logging"):
        for key, value in (defaults.get(section) or {}).items():
            if key in unset:
                setattr(request, key, value)
    if "learning_rate" in unset and request.training_type == "Full Finetuning":
        request.learning_rate = _DECISION_FULL_FINETUNING_LR


_RESUME_DATASET_DEFAULTS = {
    "hf_dataset": None,
    "local_datasets": [],
    "local_eval_datasets": [],
    "format_type": "",
    "subset": None,
    "train_split": "train",
    "eval_split": None,
    "dataset_streaming": False,
    "dataset_slice_start": None,
    "dataset_slice_end": None,
    "custom_format_mapping": None,
    "is_dataset_image": False,
    "is_dataset_audio": False,
    "is_embedding": False,
}
_RESUME_CACHE_FIELDS = (
    "model_known_cached",
    "model_local_path",
    "model_format",
    "model_snapshot_path",
    "dataset_known_cached",
    "dataset_local_path",
    "dataset_snapshot_path",
)
_RESUME_CHECKPOINT_STRUCTURE_FIELDS = (
    "load_in_4bit",
    "use_lora",
    "lora_r",
    "lora_alpha",
    "lora_dropout",
    "target_modules",
    "gradient_checkpointing",
    "use_rslora",
    "use_loftq",
    "use_dora",
    "finetune_vision_layers",
    "finetune_language_layers",
    "finetune_attention_modules",
    "finetune_mlp_modules",
    "optim",
    "lr_scheduler_type",
    "embedding_learning_rate",
)


def _normalized_optional_string(value: Any) -> Optional[str]:
    if not isinstance(value, str):
        return None
    value = value.strip()
    return value or None


def _prepare_resume_resource_provenance(
    request: TrainingStartRequest, resume_run: dict
) -> tuple[Optional[str], bool, bool, bool, Optional[str], dict[str, Any]]:
    stored = training_run_config(resume_run)
    from core.training.provenance import (
        ExactResumeResourcesUnavailable,
        RESOURCE_PROVENANCE_KEY,
        exact_resume_resource_requirements,
        local_model_resume_expectation,
        resource_provenance_is_complete,
        streamed_dataset_revision,
    )

    try:
        requires_exact_model, requires_exact_dataset = exact_resume_resource_requirements(stored)
    except ExactResumeResourcesUnavailable:
        raise HTTPException(
            status_code = 409,
            detail = (
                "The source run has invalid resource provenance or its exact snapshots "
                "are no longer available."
            ),
        )
    stored_model = _normalized_optional_string(resume_run.get("model_name")) or (
        _normalized_optional_string(stored.get("model_name"))
    )
    if stored_model is None:
        raise HTTPException(
            status_code = 409,
            detail = (
                "The source run does not contain model provenance and cannot be resumed safely."
            ),
        )
    if request.model_name != stored_model:
        raise HTTPException(
            status_code = 409,
            detail = "The selected model does not match the model used by the source run.",
        )

    stored_training_type = stored.get("training_type")
    if isinstance(stored_training_type, str) and stored_training_type:
        if request.training_type != stored_training_type:
            raise HTTPException(
                status_code = 409,
                detail = "The training type does not match the source run.",
            )
        request.training_type = stored_training_type
    for field in _RESUME_CHECKPOINT_STRUCTURE_FIELDS:
        if field not in stored:
            continue
        value = stored[field]
        setattr(request, field, list(value) if isinstance(value, list) else value)

    stored_dataset = _normalized_optional_string(stored.get("hf_dataset"))
    requested_dataset = _normalized_optional_string(request.hf_dataset)
    if requested_dataset != stored_dataset:
        raise HTTPException(
            status_code = 409,
            detail = "The selected dataset does not match the dataset used by the source run.",
        )

    request.model_name = stored_model
    for field, default in _RESUME_DATASET_DEFAULTS.items():
        value = stored.get(field, default)
        setattr(request, field, list(value) if isinstance(value, list) else value)
    request.s3_config = None
    for field in _RESUME_CACHE_FIELDS:
        default = False if field.endswith("_known_cached") else None
        setattr(request, field, stored.get(field, default))
    try:
        validated_request = TrainingStartRequest.model_validate(
            {field: getattr(request, field) for field in TrainingStartRequest.model_fields}
        )
    except ValidationError as error:
        raise HTTPException(
            status_code = 409,
            detail = (
                "The source run contains invalid training configuration and cannot "
                "be resumed safely."
            ),
        ) from error
    for field in TrainingStartRequest.model_fields:
        setattr(request, field, getattr(validated_request, field))
    overrides: dict[str, Any] = {}
    stream_revision = streamed_dataset_revision(stored)
    if stream_revision is not None:
        # Replay the streamed commit even if the run never attested, not the moving branch.
        overrides["dataset_revision"] = stream_revision
    expected_model = local_model_resume_expectation(stored)
    if expected_model is not None:
        # The worker checks the base it loads against this; the dataset pin still applies.
        return (
            None,
            False,
            requires_exact_dataset,
            False,
            None,
            {**overrides, "resume_expected_model": expected_model},
        )
    marker = stored.get(RESOURCE_PROVENANCE_KEY)
    model_load_mode = (
        _normalized_optional_string(marker.get("model_load_mode"))
        if requires_exact_model and isinstance(marker, dict)
        else None
    )
    return (
        _normalized_optional_string(stored.get("actual_model_repo_id")),
        requires_exact_model,
        requires_exact_dataset,
        resource_provenance_is_complete(stored),
        model_load_mode,
        overrides,
    )


@router.get("/hardware")
async def get_hardware_utilization(current_subject: str = Depends(get_current_subject)):
    """
    Live snapshot of GPU hardware utilization for the active backend.

    Polled by the frontend during training.
    """
    from utils.hardware import get_gpu_utilization, gpu_query

    # Off-loop: the first call blocks on detection while the warm is importing torch.
    with gpu_query.display_reads():
        return await asyncio.to_thread(get_gpu_utilization)


@router.get("/offload")
async def get_offload_state(current_subject: str = Depends(get_current_subject)):
    """Offload layers state from the last logged step: which decoder layers sit on the GPU or in
    host RAM, prefetch depth, copy / stall / compute time, VRAM. ``{"active": false}`` when the run
    does not offload. Polled by the live training view."""
    progress = get_training_backend().trainer.get_training_progress()
    offload = getattr(progress, "offload", None)
    if not offload:
        return {"active": False}
    return {"active": True, **offload}


@router.get("/drafter-capability")
async def get_drafter_capability(
    model_name: str,
    current_subject: str = Depends(get_current_subject),
    via_api_key: bool = Depends(authenticated_via_api_key),
    hf_token: Optional[str] = Depends(get_hf_token),
):
    """Which speculative-decoding drafter the Train tab can train for `model_name`: the native MTP head
    when the checkpoint ships one, else an EAGLE-3 drafter where vLLM or llama.cpp can run it."""
    from core.training.drafter import drafter_capability

    from models.inference import resolve_inventory_handle

    shown = (model_name or "").strip()
    if not shown or len(shown) > 512:
        raise HTTPException(status_code = 400, detail = "model_name is required")
    # A picker `ref:` handle resolves the way TrainingStartRequest resolves it; the answer keeps the handle.
    name = resolve_inventory_handle(shown)
    managed = managed_account()
    if managed:
        # Same rule as the training routes: Hub ids, or paths inside this account's workspace.
        try:
            account_path(name, reference = True, shared_cache = True)
            # A shared-cache snapshot is another tenant's unless this account may see that model.
            await asyncio.to_thread(_authorize_cache_fallback, name)
        except HTTPException:
            return {
                "model_name": shown,
                "has_native_mtp": False,
                "strategy": None,
                "supported": False,
                "reason": "This model is not available to this account.",
                "vllm": False,
                "llama_cpp": False,
            }
    # The caller's own token comes in the header; without one, ambient credentials for the owner
    # only, anonymous for API keys and managed accounts (the owner's token must not answer for them).
    token = hf_token_arg(hf_token, allow_ambient_token = not (via_api_key is True or managed))
    return {**await asyncio.to_thread(drafter_capability, name, token), "model_name": shown}


@router.get("/hardware/visible")
async def get_visible_hardware_utilization(current_subject: str = Depends(get_current_subject)):
    from utils.hardware import get_visible_gpu_utilization, gpu_query

    # Off the event loop: ROCm fallbacks shell out and the System view polls this route.
    with gpu_query.display_reads():
        return await asyncio.to_thread(get_visible_gpu_utilization)


# As many head rows as prepare_raw_text_dataset scores to pick a column; the worker shows a few at random.
_TOKEN_PREVIEW_POOL_ROWS = 100


def _token_preview_rows(request: TokenPreviewRequest, hf_token) -> list[dict]:
    from hub.schemas.datasets import CheckFormatRequest as HubCheckFormatRequest
    from hub.services.datasets.formatting import load_preview_slice

    from core.training.account_jobs import visible_cached_path

    from hub.utils import download_registry
    from hub.utils.hf_errors import hf_error_status

    visible_cached_path(request.dataset_local_path, "dataset")
    try:
        rows, _ = load_preview_slice(
            HubCheckFormatRequest(
                dataset_name = request.dataset_name,
                subset = request.subset,
                train_split = request.train_split or "train",
                prefer_local_cache = request.dataset_known_cached
                and bool(request.dataset_local_path),
                local_path = request.dataset_local_path,
            ),
            hf_token,
            _TOKEN_PREVIEW_POOL_ROWS,
            viewer_rows = True,
        )
    except HTTPException:
        raise
    except Exception as exc:
        raise HTTPException(
            status_code = hf_error_status(exc) or 400,
            detail = download_registry.scrub_secrets(str(exc), hf_token = hf_token),
        ) from exc
    return rows.to_list()


@router.post("/token-preview")
async def token_preview(
    request: TokenPreviewRequest,
    hf_token: HfTokenArg = Depends(get_request_hf_token),
    current_subject: str = Depends(get_current_subject),
):
    """Tokens and completion mask for a few rows of the selected dataset, or for ``text``, as
    training would produce them. Loads the tokenizer only, in a GPU-free subprocess."""
    from core.training.token_preview import (
        TokenPreviewError,
        run_token_preview,
    )
    from core.training.training import should_use_mlx_training_backend
    from routes.models import _require_model_access_or_caller_token
    from utils.account_context import current_account_id
    from hub.utils.hf_tokens import recording_a_request_token_fetch
    from utils.models.unsloth_mirror import unsloth_public_mirror
    from utils.paths import is_local_path
    from utils.utils import anonymous_and_offline

    if request.text is None and not request.dataset_name:
        raise HTTPException(status_code = 400, detail = "Pick a dataset or type a text to preview.")
    hf_token = account_hf_token(hf_token)
    model_name = request.model_name.strip()
    account_path(model_name, reference = True)
    if request.dataset_name:
        account_path(request.dataset_name, reference = True)
    await _require_model_access_or_caller_token(model_name, hf_token)
    # By repo id, not the picked cache folder: a cached repo still resolves from disk, and a folder
    # path would skip the account checks above.
    # Same repo the trainer reads: MLX loads the picked name as given (see _metadata_lookup_name).
    source = model_name
    if not should_use_mlx_training_backend():
        source = unsloth_public_mirror(model_name, request.load_in_4bit) or model_name
    remote = not is_local_path(source)
    if remote and anonymous_and_offline(hf_token, repo_id = source):
        raise HTTPException(status_code = 404, detail = "This model is not available offline.")

    def _run() -> dict:
        rows = None if request.text is not None else _token_preview_rows(request, hf_token)
        payload = {
            "rows": rows,
            "text": request.text,
            "final_format": request.final_format,
            "dataset_name": request.dataset_name,
            "format_type": request.format_type,
            "custom_format_mapping": request.custom_format_mapping,
            "raw_text": request.is_cpt or request.format_type == "raw",
            "is_cpt": request.is_cpt,
            # The trainer never masks audio models or DeepSeek OCR (it skips apply_completion_masking).
            "train_on_completions": request.train_on_completions
            and not request.is_cpt
            and request.model_type != "audio"
            and not ("deepseek" in model_name.lower() and "ocr" in model_name.lower()),
            "max_seq_length": request.max_seq_length,
            "num_samples": request.num_samples,
            "seed": request.seed,
        }
        key = (current_account_id(), model_name, source, hf_token)
        # The tokenizer is loaded only when a worker starts, and which files that load resolves is not
        # known up front, so every load is recorded; a warm worker fetches nothing.
        return run_token_preview(
            key,
            {"model_name": model_name, "tokenizer_source": source, "hf_token": hf_token},
            payload,
            (lambda: recording_a_request_token_fetch(hf_token, source, "model"))
            if remote
            else None,
        )

    try:
        return await asyncio.to_thread(_run)
    except TokenPreviewError as exc:
        from hub.utils import download_registry
        detail = download_registry.scrub_secrets(str(exc), hf_token = hf_token)
        raise HTTPException(status_code = 422, detail = detail) from exc


@router.get("/start-requests/{start_request_id}", response_model = TrainingStartRequestStatus)
async def get_training_start_request(
    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)
    if record is None:
        raise HTTPException(status_code = 404, detail = "Training start request not found")
    return _start_request_status_response(record)


def _start_request_status_response(record) -> TrainingStartRequestStatus:
    return TrainingStartRequestStatus(
        start_request_id = record.start_request_id,
        job_id = record.job_id,
        state = record.state,
        message = record.message,
        error = record.error,
        error_code = record.error_code,
    )


@router.post("/start-requests/{start_request_id}/acknowledge")
async def acknowledge_training_start_request(
    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):
        raise HTTPException(
            status_code = 409,
            detail = "Training start request is not ready to acknowledge",
        )
    return {"status": "ok"}


@router.post(
    "/start-requests/{start_request_id}/cancel",
    response_model = TrainingStartRequestStatus,
)
async def cancel_training_start_request(
    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()
    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,
            detail = "Training start request no longer owns the current job",
        )
    return _start_request_status_response(record)


def _background_video_generation_active() -> bool:
    """POST /video/generate returns early, so the in-flight count misses it; ask the backend."""
    try:
        from core.inference.video import get_video_backend
        return bool(get_video_backend().generate_progress().get("active"))
    except Exception as e:  # noqa: BLE001
        logger.warning("Could not check video generation state for training guard: %s", e)
        return False


async def _prepare_training_request(request: TrainingStartRequest, via_api_key: bool) -> None:
    await asyncio.to_thread(_validate_decision_request, request, via_api_key)
    if request.drafter is not None and request.drafter.enabled:
        from core.training.training import should_use_mlx_training_backend
        if should_use_mlx_training_backend():
            raise HTTPException(
                status_code = 400,
                detail = "Drafter training is not available on Apple Silicon (MLX) yet.",
            )
    from core.training.token_preview import stop_token_preview_worker

    # The run needs the host RAM more than the preview needs to stay warm; reaped off the request path.
    threading.Thread(target = stop_token_preview_worker, daemon = True).start()
    if managed_account():
        from utils.paths import tensorboard_root

        directory = request.tensorboard_dir
        if not directory or not Path(directory).is_absolute():
            request.tensorboard_dir = str(tensorboard_root() / (directory or ""))
        validate_job_paths(request.model_dump())


@dataclass
class _AdmittedTrainingRequest:
    training_kwargs: dict
    hf_token: Optional[str]
    resume_run: Optional[dict]


async def _admit_training_request(
    request: TrainingStartRequest, current_subject: str, via_api_key: bool
) -> _AdmittedTrainingRequest:
    """Per-request validation and worker kwargs of a start; raises the start route's own errors."""
    resume_output_dir: Optional[str] = None
    resume_run: Optional[dict] = None
    resume_actual_model_repo_id: Optional[str] = None
    resume_model_load_mode: Optional[str] = None
    resume_requires_exact_resources = False
    resume_requires_exact_model = False
    resume_requires_exact_dataset = False
    resume_overrides: dict[str, Any] = {}
    if request.resume_from_checkpoint:
        try:
            resume_output_dir = await asyncio.to_thread(
                normalize_resume_output_dir,
                request.resume_from_checkpoint,
            )
        except ValueError as e:
            # Deliberate user-facing validation message.
            validation_message = str(e)
            raise HTTPException(status_code = 400, detail = validation_message)

        resume_run = await asyncio.to_thread(
            get_resumable_run_by_output_dir,
            resume_output_dir,
        )
        if not resume_run or not await asyncio.to_thread(can_resume_run, resume_run):
            detail = "Resume checkpoint must belong to a stopped or errored run with complete saved trainer state."
            # Only when the checkpoint itself is intact: can_resume_run refuses for several reasons, so asking
            # unconditionally answers a provenance sentence when the checkpoint is what is missing.
            # has_resume_state is the discriminator can_resume_run itself short-circuits on.
            if resume_run and await asyncio.to_thread(
                has_resume_state, resume_run.get("output_dir")
            ):
                from core.training.provenance import (
                    resource_provenance_resume_blocker,
                )
                blocker = await asyncio.to_thread(
                    resource_provenance_resume_blocker,
                    training_run_config(resume_run),
                )
                if blocker:
                    detail = blocker
            raise HTTPException(status_code = 400, detail = detail)
        resume_checkpoint = await asyncio.to_thread(
            get_resume_checkpoint_path,
            resume_output_dir,
        )
        if not resume_checkpoint:
            raise HTTPException(
                status_code = 400,
                detail = "Resume checkpoint must include saved trainer state.",
            )
        request.resume_from_checkpoint = resume_checkpoint
        (
            resume_actual_model_repo_id,
            resume_requires_exact_model,
            resume_requires_exact_dataset,
            resume_requires_exact_resources,
            resume_model_load_mode,
            resume_overrides,
        ) = await asyncio.to_thread(
            _prepare_resume_resource_provenance,
            request,
            resume_run,
        )

    if request.local_datasets:
        request.local_datasets = _validate_local_dataset_paths(
            request.local_datasets, "Local dataset"
        )
    # Not `eval_steps > 0`: inf passes that but reads as disabled everywhere in the trainer.
    if request.local_eval_datasets and evaluation_enabled(request.eval_steps):
        request.local_eval_datasets = _validate_local_dataset_paths(
            request.local_eval_datasets, "Local eval dataset"
        )

    from utils.hardware import hardware as _hw
    from utils.hardware import ensure_hardware_detected

    await asyncio.to_thread(ensure_hardware_detected)
    _validate_training_platform(request)

    if request.dataset_streaming:
        if not request.hf_dataset:
            raise HTTPException(
                status_code = 400,
                detail = "dataset_streaming requires hf_dataset; streaming is not supported for local datasets.",
            )
        if request.is_dataset_image or request.is_dataset_audio:
            raise HTTPException(
                status_code = 400,
                detail = "dataset_streaming is not supported for vision or audio datasets.",
            )
        if request.is_embedding:
            raise HTTPException(
                status_code = 400,
                detail = "dataset_streaming is not supported for embedding training; the embedding loader needs the full dataset.",
            )
        if request.max_steps is None or request.max_steps <= 0:
            raise HTTPException(
                status_code = 422,
                detail = "dataset_streaming requires max_steps > 0 because streaming datasets have no known length.",
            )
        if request.train_on_completions:
            raise HTTPException(
                status_code = 422,
                detail = "dataset_streaming is not supported with train_on_completions yet.",
            )
        if evaluation_enabled(request.eval_steps):
            train_split = request.train_split or "train"
            if not request.eval_split or request.eval_split == train_split:
                raise HTTPException(
                    status_code = 422,
                    detail = "dataset_streaming with evaluation requires a separate eval_split.",
                )
        # Streaming is HF-only: reject when the request also carries a local dataset path or an
        # S3 config, since those sources cannot be streamed via HF's loader.
        if request.local_datasets:
            raise HTTPException(
                status_code = 400,
                detail = (
                    "dataset_streaming is HF-only; remove local_datasets / S3 source. "
                    "Streaming is not supported with local file paths."
                ),
            )
        if request.s3_config is not None:
            raise HTTPException(
                status_code = 400,
                detail = (
                    "dataset_streaming is HF-only; remove local_datasets / S3 source. "
                    "Streaming is not supported with S3 datasets."
                ),
            )
        if request.dataset_known_cached or request.dataset_local_path:
            raise HTTPException(
                status_code = 422,
                detail = (
                    "dataset_streaming streams from the Hub and cannot use the local "
                    "dataset cache; disable streaming to train from the cached copy."
                ),
            )
    allow_ambient = via_api_key is not True
    hf_token = hf_token_arg(request.hf_token, allow_ambient_token = allow_ambient)
    # The local dataset paths were resolved above for existence only; authorize them now that
    # the caller's token is known, before anything reads them.
    # Eval paths only while evaluation is on, matching the validation above and the trainer,
    # which reads them under the same condition: a stale eval path nothing will open must not
    # refuse an otherwise valid run.
    for _local_paths, _label in (
        (request.local_datasets, "dataset"),
        (
            request.local_eval_datasets if evaluation_enabled(request.eval_steps) else [],
            "eval_dataset",
        ),
    ):
        if _local_paths:
            await asyncio.to_thread(
                _refuse_unauthorized_cached_local_paths, _local_paths, hf_token, _label
            )
    model_preflight = await asyncio.to_thread(
        _reject_untrainable_model_request,
        request,
        resume_actual_model_repo_id,
        hf_token,
    )
    cached_model_pin = model_preflight.cached_model_pin
    training_actual_model_repo_id = resume_actual_model_repo_id
    training_model_snapshot_path = request.model_snapshot_path
    if cached_model_pin is not None:
        training_actual_model_repo_id, training_model_snapshot_path = cached_model_pin

    if request.hf_dataset:
        await asyncio.to_thread(_preflight_hf_dataset_request, request)
        # After the preflight: a cache it pinned is still on disk for this scan to refuse.
        # Not for a streaming start: it reads the Hub (load_dataset(streaming = True)) and never
        # the materialized cache, the preflight above always verified the repo remotely, and
        # the route already refuses streaming with a pinned cache. Asking anyway would refuse a
        # valid start over an unrelated cached copy whenever /auth-check cannot be reached.
        # And only when the Hub repo is the EFFECTIVE source: load_and_format_dataset takes
        # local_datasets (and s3_config below it) ahead of dataset_source, so a payload carrying
        # both never reads the Hub cache, and refusing over it fails a run on a dataset it does
        # not use. The local paths took their own authorization pass above.
        if not request.dataset_streaming and _hf_dataset_is_the_source(request):
            await asyncio.to_thread(_refuse_unauthorized_cached_dataset, request, hf_token)

    device_backend = getattr(_hw.DEVICE, "value", "") or ""
    training_optimizer = normalize_training_optimizer_for_device(
        request.optim,
        device_backend = device_backend,
    )

    training_kwargs = {
        "model_name": model_preflight.model_name,
        "project_name": request.project_name,
        "training_type": request.training_type,
        "hf_token": (request.hf_token or "").strip(),
        "allow_ambient": allow_ambient,
        "load_in_4bit": request.load_in_4bit,
        "max_seq_length": request.max_seq_length,
        "vision_image_size": request.vision_image_size,
        "hf_dataset": request.hf_dataset or "",
        "model_known_cached": request.model_known_cached,
        "model_local_path": model_preflight.model_local_path,
        "model_format": request.model_format,
        "model_snapshot_path": training_model_snapshot_path,
        "actual_model_repo_id": training_actual_model_repo_id,
        "resume_model_load_mode": resume_model_load_mode,
        "dataset_known_cached": request.dataset_known_cached,
        "dataset_local_path": request.dataset_local_path,
        "dataset_snapshot_path": request.dataset_snapshot_path,
        "local_datasets": request.local_datasets,
        "local_eval_datasets": request.local_eval_datasets,
        "format_type": request.format_type,
        "subset": request.subset,
        "train_split": request.train_split,
        "dataset_streaming": request.dataset_streaming,
        "eval_split": request.eval_split,
        "eval_steps": request.eval_steps,
        "early_stopping_patience": request.early_stopping_patience,
        "drafter": (
            request.drafter.model_dump()
            if request.drafter is not None and request.drafter.enabled
            else None
        ),
        "dataset_slice_start": request.dataset_slice_start,
        "dataset_slice_end": request.dataset_slice_end,
        "custom_format_mapping": request.custom_format_mapping,
        "num_epochs": request.num_epochs,
        "learning_rate": request.learning_rate,
        "embedding_learning_rate": request.embedding_learning_rate,
        "batch_size": request.batch_size,
        "gradient_accumulation_steps": request.gradient_accumulation_steps,
        "warmup_steps": request.warmup_steps,
        "warmup_ratio": request.warmup_ratio,
        "max_steps": request.max_steps,
        "save_steps": request.save_steps,
        "weight_decay": request.weight_decay,
        "max_grad_norm": request.max_grad_norm,
        "max_grad_value": request.max_grad_value,
        "max_grad_leaf_norm": request.max_grad_leaf_norm,
        "cast_norm_output_to_input_dtype": request.cast_norm_output_to_input_dtype,
        "random_seed": request.random_seed,
        "packing": request.packing,
        "optim": training_optimizer,
        "lr_scheduler_type": request.lr_scheduler_type,
        "use_lora": request.use_lora,
        "lora_r": request.lora_r,
        "lora_alpha": request.lora_alpha,
        "lora_dropout": request.lora_dropout,
        "target_modules": request.target_modules if request.target_modules else None,
        "gradient_checkpointing": request.gradient_checkpointing.strip()
        if request.gradient_checkpointing and request.gradient_checkpointing.strip()
        else "unsloth",
        "offload_layers": request.offload_layers,
        "offload_vram_gb": request.offload_vram_gb,
        "offload_vram_gb_per_device": request.offload_vram_gb_per_device,
        "prefetch_depth": request.prefetch_depth,
        "use_rslora": request.use_rslora,
        "use_loftq": request.use_loftq,
        "use_dora": request.use_dora,
        "train_on_completions": request.train_on_completions,
        "finetune_vision_layers": request.finetune_vision_layers,
        "finetune_language_layers": request.finetune_language_layers,
        "finetune_attention_modules": request.finetune_attention_modules,
        "finetune_mlp_modules": request.finetune_mlp_modules,
        "is_dataset_image": request.is_dataset_image,
        "is_dataset_audio": request.is_dataset_audio,
        "is_embedding": request.is_embedding,
        "is_decision": request.is_decision,
        "model_subfolder": request.model_subfolder,
        "decision_layout": request.decision_layout,
        "decision_head": request.decision_head,
        "enable_wandb": request.enable_wandb,
        "wandb_token": request.wandb_token or "",
        "wandb_project": request.wandb_project or "",
        "enable_tensorboard": request.enable_tensorboard,
        "tensorboard_dir": request.tensorboard_dir or "",
        "output_dir": resume_output_dir,
        "resume_from_checkpoint": request.resume_from_checkpoint,
        "require_exact_resume_resources": resume_requires_exact_resources,
        "require_exact_model_resource": resume_requires_exact_model,
        "require_exact_dataset_resource": resume_requires_exact_dataset,
        "require_validated_model_snapshot": cached_model_pin is not None,
        "adapter_base_pin": getattr(model_preflight, "adapter_base_pin", None),
        # A managed account never forwards remote code to the worker.
        "trust_remote_code": request.trust_remote_code and not managed_remote_code_refused(),
        "approved_remote_code_fingerprint": request.approved_remote_code_fingerprint,
        "subject": current_subject,
        "gpu_ids": request.gpu_ids,
        "s3_config": request.s3_config.model_dump() if request.s3_config else None,
    }
    training_kwargs.update(resume_overrides)

    # Latest-sidecar models size and train 16-bit (same flip as chat load): 4-bit is disabled for brand-new
    # architectures, so VRAM checks must not underestimate a load the worker refuses.
    from core.training.provenance import (
        ExactResumeResourcesUnavailable,
        effective_training_load_in_4bit,
    )

    if training_kwargs["load_in_4bit"]:
        from core.training.training import resolve_training_model_load_target

        try:
            model_load_target = await asyncio.to_thread(
                resolve_training_model_load_target,
                training_kwargs,
            )
        except ExactResumeResourcesUnavailable as exc:
            raise HTTPException(status_code = 409, detail = str(exc))
        try:
            effective_load_in_4bit = await asyncio.to_thread(
                effective_training_load_in_4bit,
                training_kwargs,
                model_load_target,
                hf_token,
            )
        except ExactResumeResourcesUnavailable as exc:
            raise HTTPException(status_code = 409, detail = str(exc))
        if not effective_load_in_4bit:
            training_kwargs["load_in_4bit"] = False
            logger.info(
                "Latest-transformers sidecar active for %s - sizing and "
                "training in 16-bit (4-bit is disabled for brand-new "
                "architectures)",
                model_load_target,
            )

    # Training page has no trust_remote_code toggle.
    if not training_kwargs["trust_remote_code"]:
        from utils.security.trusted_org import is_trusted_org_repo

        model_defaults = load_model_defaults(request.model_name)
        yaml_trust = model_defaults.get("training", {}).get("trust_remote_code", False)
        if yaml_trust and is_trusted_org_repo(request.model_name, hf_token = hf_token):
            logger.info(f"YAML config sets trust_remote_code=True for {request.model_name}")
            training_kwargs["trust_remote_code"] = True
        elif yaml_trust:
            logger.warning(
                "YAML sets trust_remote_code=True for %s but it is not a trusted "
                "first-party repo; leaving disabled (user can opt in explicitly).",
                request.model_name,
            )

    return _AdmittedTrainingRequest(
        training_kwargs = training_kwargs,
        hf_token = hf_token,
        resume_run = resume_run,
    )


@router.post("/start", responses = _TRAINING_START_ERROR_RESPONSES)
async def start_training(
    request: TrainingStartRequest,
    current_subject: str = Depends(get_current_subject),
    via_api_key: bool = Depends(authenticated_via_api_key),
):
    """
    Start a training job.

    Initiates training in the background and returns immediately. Use /status
    to check progress.
    """
    await _prepare_training_request(request, via_api_key)
    backend = None
    reserved_start_request_id = None
    start_task: Optional[asyncio.Task[bool]] = None
    try:
        logger.info(f"Starting training job with model: {request.model_name}")
        backend = get_training_backend()
        job_id = f"job_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{_uuid.uuid4().hex[:8]}"
        if request.start_request_id:
            # A retry of a resolved id replays its outcome; peeking also refreshes a cancellation tombstone.
            existing_record = backend.peek_start_request(request.start_request_id)
            if existing_record is not None:
                return _start_request_response(existing_record)

        # API-key auth: refuse while a request is in flight (training unloads chat). Checked BEFORE
        # reserving start_request_id, or a transient refusal would be replayed forever.
        if via_api_key is True:
            from core.inference.llama_keepwarm import other_inference_request_count
            if (
                other_inference_request_count(current_request_counted = False) > 0
                or _background_video_generation_active()
            ):
                raise HTTPException(
                    status_code = 409,
                    detail = (
                        "Cannot start training over the API while an inference request is in "
                        "progress. Wait for it to finish, or start training from the Unsloth UI."
                    ),
                )

        if request.start_request_id:
            reservation, record = backend.reserve_start_request(
                request.start_request_id,
                job_id,
            )
            if reservation == "existing":
                return _start_request_response(record)
            if reservation == "conflict":
                return _start_request_response(record)
            reserved_start_request_id = request.start_request_id

        # No in-process ensure_transformers_version(): worker.py activates it before ML imports.
        from utils.transformers_latest import is_install_in_progress

        if is_install_in_progress():
            raise HTTPException(
                status_code = 409,
                detail = ("A transformers installation is in progress. Retry when it completes."),
            )

        # Install the optional SDK outside the event loop on the first S3 request.
        if request.s3_config is not None and not request.resume_from_checkpoint:
            from core.training.s3_dataset import boto3_available
            from utils.s3_runtime import S3DependencyUnavailable, ensure_boto3
            if not boto3_available():
                try:
                    await asyncio.to_thread(ensure_boto3)
                except S3DependencyUnavailable as exc:
                    raise HTTPException(status_code = 501, detail = str(exc)) from exc

        if await asyncio.to_thread(backend.is_training_active):
            existing_job_id: Optional[str] = getattr(backend, "current_job_id", "")
            _reject_start_request(
                backend,
                reserved_start_request_id,
                "Training already active",
            )
            return TrainingJobResponse(
                job_id = existing_job_id or "",
                status = "error",
                message = (
                    "Training is already in progress. "
                    "Stop current training before starting a new one."
                ),
                error = "Training already active",
            )

        # A diffusion LoRA job runs in its own subprocess on the same GPU, so refuse while one is active.
        if _diffusion_training_active():
            message = (
                "A diffusion (Images) LoRA training job is already running. "
                "Stop it before starting an LLM training run."
            )
            _reject_start_request(
                backend,
                reserved_start_request_id,
                message,
            )
            return TrainingJobResponse(
                job_id = "",
                status = "error",
                message = message,
                error = "Diffusion training already active",
            )

        admitted = await _admit_training_request(request, current_subject, via_api_key)
        training_kwargs = admitted.training_kwargs
        hf_token = admitted.hf_token
        resume_run = admitted.resume_run
        # Set only by start_training_batch: this start becomes one multi-LoRA batch.
        batch_members = _batch_members_for_start(training_kwargs)

        # before_spawn hook: runs only after start_training's guards pass.
        def _free_vram_for_training() -> None:
            try:
                from core.export import get_export_backend
                exp_backend = get_export_backend()
                # Any in-flight export: current_checkpoint is unset while the worker allocates GPU.
                if exp_backend.current_checkpoint or exp_backend.is_export_active():
                    logger.info("Shutting down export subprocess to free GPU memory for training")
                    exp_backend._shutdown_subprocess()
                    exp_backend.current_checkpoint = None
                    exp_backend.is_vision = False
                    exp_backend.is_peft = False
            except Exception as e:
                logger.warning("Could not shut down export subprocess: %s", e)

            try:
                from core.inference import gpu_arbiter
                from core.inference.diffusion_engine_router import (
                    get_active_diffusion_engine,
                )

                # The ACTIVE engine, not the diffusers singleton: on a native (sd_cpp) selection the diffusers backend
                # reports unloaded while the native engine still holds state.
                # The mask segmenter sits on torch's card whichever engine renders; one still running refuses the start.
                gpu_arbiter.release_mask_segmenter("training start")
                diffusion = get_active_diffusion_engine()
                if getattr(diffusion, "runs_off_torch_device", False) is True:
                    logger.info("Keeping the Images model: it runs outside torch's GPUs")
                else:
                    if diffusion.is_loaded:
                        logger.info(
                            "Unloading diffusion (Images) model to free GPU memory for training"
                        )
                    diffusion.unload()
                    gpu_arbiter.release(gpu_arbiter.DIFFUSION)
            except gpu_arbiter.SegmenterStillRunningError:
                raise
            except Exception as e:
                logger.warning("Could not unload diffusion model for training: %s", e)

            _free_restyle_for_training()
            try:
                # Video pipelines load under the VIDEO arbiter owner; tear down too. Must precede the chat block.
                from core.inference import gpu_arbiter
                from core.inference.video import get_video_backend

                video = get_video_backend()
                if video.status().get("loaded"):
                    logger.info("Unloading Video model to free GPU memory for training")
                video.unload()
                gpu_arbiter.release(gpu_arbiter.VIDEO)
            except Exception as e:
                logger.warning("Could not unload video model for training: %s", e)

            try:
                from core.systemone import laya_runtime
                if laya_runtime.status()["holds_gpu"]:
                    logger.info("Unloading the Decision API model to free GPU memory for training")
                    laya_runtime.unload(reload_after_training = True)
            except Exception as e:
                logger.warning("Could not unload the Decision API model for training: %s", e)

            try:
                from routes.training_vram import (
                    can_keep_chat_during_training,
                    coordinate_models_for_training,
                )

                def _can_keep_resident_models():
                    members = batch_members or [training_kwargs]
                    return can_keep_chat_during_training(
                        model_name = training_kwargs["model_name"],
                        hf_token = hf_token,
                        training_type = training_kwargs["training_type"],
                        load_in_4bit = training_kwargs["load_in_4bit"],
                        batch_size = sum(m["batch_size"] for m in members),
                        max_seq_length = training_kwargs["max_seq_length"],
                        lora_rank = sum(m["lora_r"] for m in members),
                        target_modules = training_kwargs["target_modules"],
                        gradient_checkpointing = training_kwargs["gradient_checkpointing"],
                        optimizer = training_kwargs["optim"],
                        gpu_ids = training_kwargs["gpu_ids"],
                    )

                freed = coordinate_models_for_training(_can_keep_resident_models)
                if freed:
                    logger.info("Freed models for training: %s", freed)
            except Exception as e:
                if getattr(e, "blocks_training", False):
                    raise
                logger.warning("Inference/training memory coordination failed; proceeding: %s", e)

        # The hook runs only once start guards pass -> VRAM freed iff training starts.
        from core.inference.gpu_arbiter import SegmenterStillRunningError
        from core.training.provenance import ExactResumeResourcesUnavailable
        from routes.training_vram import ManagedEngineStillRunning
        from utils.transformers_version import SidecarSwapInProgress

        def _run_backend_start_without_admission() -> bool:
            try:
                success = backend.start_training(
                    job_id = job_id,
                    start_request_id = request.start_request_id,
                    before_spawn = _free_vram_for_training,
                    resume_source_run_id = resume_run["id"] if resume_run else None,
                    **({"batch_members": batch_members} if batch_members else {}),
                    **training_kwargs,
                )
            except (
                SidecarSwapInProgress,
                ExactResumeResourcesUnavailable,
                ManagedEngineStillRunning,
                SegmenterStillRunningError,
            ) as exc:
                _reject_start_request(backend, reserved_start_request_id, str(exc))
                raise
            except ValueError as exc:
                _reject_start_request(backend, reserved_start_request_id, str(exc))
                raise
            except Exception:
                _reject_start_request(
                    backend,
                    reserved_start_request_id,
                    "Failed to start training",
                )
                raise

            if success:
                if reserved_start_request_id is not None:
                    backend.resolve_start_request(
                        reserved_start_request_id,
                        state = "accepted",
                        message = "Training job queued and starting in subprocess",
                    )
            else:
                progress_error = backend.trainer.training_progress.error
                _reject_start_request(
                    backend,
                    reserved_start_request_id,
                    progress_error or "Failed to start training subprocess",
                )
            return success

        def _run_backend_start() -> bool:
            try:
                # Hold the admission across the spawn: a disconnect must not release it mid VRAM free.
                with _diffusion_gpu_admission():
                    return _run_backend_start_without_admission()
            except _DiffusionStartInFlight as exc:
                _reject_start_request(
                    backend,
                    reserved_start_request_id,
                    str(exc),
                )
                raise

        try:
            start_task = asyncio.create_task(asyncio.to_thread(_run_backend_start))
            success = await asyncio.shield(start_task)
        except _DiffusionStartInFlight as exc:
            return TrainingJobResponse(
                job_id = "",
                status = "error",
                message = str(exc),
                error = "Diffusion training already active",
            )
        except SidecarSwapInProgress as exc:
            # Expected loss of the race against a sidecar install: a retryable 409, not an internal error.
            raise HTTPException(status_code = 409, detail = str(exc))
        except (
            ExactResumeResourcesUnavailable,
            ManagedEngineStillRunning,
            SegmenterStillRunningError,
        ) as exc:
            raise HTTPException(status_code = 409, detail = str(exc))

        if not success:
            progress_error = backend.trainer.training_progress.error
            failure_message = progress_error or "Failed to start training subprocess"
            return TrainingJobResponse(
                job_id = backend.current_job_id or "",
                status = "error",
                message = failure_message,
                error = progress_error or "subprocess_start_failed",
            )

        return TrainingJobResponse(
            job_id = job_id,
            status = "queued",
            message = "Training job queued and starting in subprocess",
            error = None,
        )

    except asyncio.CancelledError:
        if start_task is None:
            _reject_start_request(
                backend,
                reserved_start_request_id,
                "Training start was cancelled",
            )
        else:
            start_task.add_done_callback(_observe_training_start_task)
        raise
    except HTTPException as exc:
        # Deliberate rejections (S3 not implemented, resume validation) keep their original status.
        detail, error_code = _http_exception_error(exc)
        _reject_start_request(
            backend,
            reserved_start_request_id,
            detail,
            error_code,
        )
        raise
    except ValueError as e:
        logger.warning("Rejected training GPU selection: %s", e)
        # Deliberate user-facing GPU-selection validation message.
        validation_message = str(e)
        _reject_start_request(backend, reserved_start_request_id, validation_message)
        raise HTTPException(status_code = 400, detail = validation_message)
    except Exception as e:
        _reject_start_request(
            backend,
            reserved_start_request_id,
            "Failed to start training",
        )
        raise log_and_http_error(
            e,
            500,
            "Failed to start training",
            event = "training.start_failed",
            log = logger,
        )


# (first member's run id, the other members' entries) while start_training_batch drives start_training.
_PENDING_BATCH: contextvars.ContextVar[Optional[tuple[str, list[dict]]]] = contextvars.ContextVar(
    "studio_training_pending_batch", default = None
)


def _batch_members_for_start(training_kwargs: dict) -> Optional[list[dict]]:
    pending = _PENDING_BATCH.get()
    if pending is None:
        return None
    first_run_id, others = pending
    return [{"run_id": first_run_id, **training_kwargs}, *others]


async def start_training_batch(
    requests: list[TrainingStartRequest], current_subject: str, via_api_key: bool
) -> list[TrainingJobResponse]:
    """Start compatible LoRA requests as one multi-LoRA run; internal, not a route.

    Every member takes every per-request check; the shared ones (busy, inference conflict, install, VRAM, launch)
    run once, through start_training for the first member, whose job id becomes the batch id. One response per
    member, carrying that member's own run id.
    """
    if len(requests) < 2:
        raise ValueError("A training batch needs at least two requests.")
    if any(request.resume_from_checkpoint or request.start_request_id for request in requests):
        raise ValueError("A training batch cannot resume or carry a start_request_id.")
    run_ids = [
        f"job_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{_uuid.uuid4().hex[:8]}" for _ in requests
    ]
    others = []
    for run_id, request in zip(run_ids[1:], requests[1:]):
        await _prepare_training_request(request, via_api_key)
        try:
            admitted = await _admit_training_request(request, current_subject, via_api_key)
        except ValueError as e:
            raise HTTPException(status_code = 400, detail = str(e))
        others.append({"run_id": run_id, **admitted.training_kwargs})
    token = _PENDING_BATCH.set((run_ids[0], others))
    try:
        started = await start_training(
            requests[0], current_subject = current_subject, via_api_key = via_api_key
        )
    finally:
        _PENDING_BATCH.reset(token)
    if started.status == "error" or not started.job_id:
        return [started.model_copy() for _ in requests]
    return [
        TrainingJobResponse(
            job_id = run_id,
            status = started.status,
            message = started.message,
            error = started.error,
        )
        for run_id in run_ids
    ]


@router.post("/stop", response_model = TrainingStopResponse)
async def stop_training(
    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.
    """
    require_job_owner(get_training_backend())
    try:
        backend = get_training_backend()
        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 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"
            )

        return TrainingStopResponse(
            status = "stopped",
            message = "Stop requested. Training will stop at the next safe step.",
        )

    except HTTPException:
        raise
    except Exception as e:
        raise log_and_http_error(
            e,
            500,
            "Failed to stop training",
            event = "training.stop_failed",
            log = logger,
        )


@router.post("/reset")
async def reset_training(
    body: Optional[TrainingResetRequest] = None, current_subject: str = Depends(get_current_subject)
):
    """Reset training state so the user can return to configuration."""
    require_job_owner(get_training_backend())
    try:
        backend = get_training_backend()
        result = await asyncio.to_thread(
            backend.reset_training_state,
            expected_job_id = body.expected_job_id if body is not None else None,
        )
        if result == "superseded":
            return {"status": "superseded"}
        if result == "active":
            raise HTTPException(
                status_code = 409,
                detail = "Training is still running. Stop training and wait for it to finish before resetting.",
            )
        return {"status": "ok"}
    except HTTPException:
        raise
    except Exception as e:
        raise log_and_http_error(
            e,
            500,
            "Failed to reset training",
            event = "training.reset_failed",
            log = logger,
        )


def _training_status_identity(backend) -> TrainingStatusIdentitySnapshot:
    snapshot = getattr(backend, "training_status_identity", None)
    if callable(snapshot):
        return snapshot()
    status_start_request = getattr(backend, "status_start_request", None)
    current_start_request_id = getattr(backend, "current_start_request_id", None)
    current_start_request = (
        backend.get_start_request(current_start_request_id)
        if current_start_request_id is not None
        else None
    )
    status_start_request = getattr(backend, "status_start_request", None)
    return TrainingStatusIdentitySnapshot(
        current_job_id = getattr(backend, "current_job_id", "") or "",
        current_start_request_id = current_start_request_id,
        current_start_request = current_start_request,
        status_start_request = status_start_request() if callable(status_start_request) else None,
        new_job_spawn_id = getattr(backend, "_new_job_spawn_id", None),
        spawn_in_progress = getattr(backend, "_spawn_in_progress", False),
    )


def _build_training_status(
    backend, identity: TrainingStatusIdentitySnapshot, is_active: bool
) -> TrainingStatus:
    if job_is_foreign(backend):
        return TrainingStatus(
            job_id = "",
            phase = "idle",
            is_training_running = False,
            message = "Busy" if job_busy(backend) else "Ready to train",
        )
    owner_job_id = identity.current_job_id
    job_id = owner_job_id
    start_request_id = identity.current_start_request_id
    start_request = identity.current_start_request
    status_start_request = identity.status_start_request
    new_job_spawn_id = identity.new_job_spawn_id

    if new_job_spawn_id is not None:
        job_id = new_job_spawn_id
        start_request = next(
            (
                request
                for request in (status_start_request, identity.current_start_request)
                if request is not None and request.job_id == new_job_spawn_id
            ),
            None,
        )
        start_request_id = start_request.start_request_id if start_request is not None else None
    elif is_active:
        start_request = identity.current_start_request
        start_request_id = identity.current_start_request_id
    elif status_start_request is not None and status_start_request.state in {
        "pending",
        "rejected",
    }:
        start_request = status_start_request
        job_id = "" if start_request.state == "rejected" else start_request.job_id
        start_request_id = start_request.start_request_id
    elif start_request is None and (
        status_start_request is not None and status_start_request.job_id == owner_job_id
    ):
        start_request = status_start_request
        start_request_id = status_start_request.start_request_id

    start_request_state = start_request.state if start_request is not None else None
    exposes_owner_state = (
        job_id == owner_job_id
        and start_request_state not in {"pending", "rejected"}
        and new_job_spawn_id is None
    )
    progress = None
    if exposes_owner_state:
        try:
            progress = backend.trainer.get_training_progress()
        except Exception:
            progress = None

    status_message = (
        getattr(progress, "status_message", None) if progress else None
    ) or "Ready to train"
    error_message = getattr(progress, "error", None) if progress else None
    warnings = list(getattr(progress, "warnings", ()) or ()) if progress else []
    if start_request is not None and start_request.state == "pending":
        status_message = start_request.message
        error_message = None
        warnings = []
    elif start_request is not None and start_request.state == "rejected":
        status_message = start_request.message
        error_message = start_request.error or start_request.message
        warnings = []
    elif new_job_spawn_id is not None:
        status_message = "Training job is starting"

    trainer_stopped = getattr(backend, "_should_stop", False)
    if start_request_state == "pending":
        phase = "configuring"
    elif start_request_state == "rejected":
        phase = "error"
    elif new_job_spawn_id is not None:
        phase = "configuring"
    elif error_message:
        phase = "error"
    elif is_active:
        msg_lower = status_message.lower()
        if msg_lower.startswith("training drafter"):
            phase = "training_drafter"
        elif "loading" in msg_lower or "importing" in msg_lower:
            phase = "loading_model"
        elif any(k in msg_lower for k in ["preparing", "initializing", "configuring"]):
            phase = "configuring"
        elif _is_finalizing(progress, msg_lower):
            phase = "finalizing"
        else:
            phase = "training"
    elif trainer_stopped:
        phase = "stopped"
    elif progress and getattr(progress, "is_completed", False):
        phase = "completed"
    else:
        phase = "idle"

    details = None
    if progress:
        details = {
            "epoch": getattr(progress, "epoch", 0),
            "step": getattr(progress, "step", 0),
            "total_steps": getattr(progress, "total_steps", 0),
            "loss": getattr(progress, "loss", None),
            "learning_rate": getattr(progress, "learning_rate", None),
            "elapsed_seconds": getattr(progress, "elapsed_seconds", None),
            # A stopped run keeps its last ETA; only a live run has time remaining.
            "eta_seconds": getattr(progress, "eta_seconds", None) if is_active else None,
            "output_dir": getattr(backend, "_output_dir", None) or None,
            "drafter": getattr(progress, "drafter", None),
            "model_download_repo_id": (
                getattr(backend, "_model_download_repo_id", None) if is_active else None
            ),
        }

    metric_history = None
    if exposes_owner_state and backend.step_history:
        metric_history = {
            "steps": list(backend.step_history),
            "loss": list(backend.loss_history),
            "lr": list(backend.lr_history),
            "grad_norm": list(getattr(backend, "grad_norm_history", [])),
            "grad_norm_steps": list(getattr(backend, "grad_norm_step_history", [])),
            "eval_loss": list(backend.eval_loss_history),
            "eval_steps": list(backend.eval_step_history),
        }

    return TrainingStatus(
        job_id = job_id,
        start_request_id = start_request_id,
        start_request_state = start_request_state,
        phase = phase,
        is_training_running = is_active,
        eval_enabled = backend.eval_enabled if exposes_owner_state else False,
        message = status_message,
        error = error_message,
        warnings = warnings,
        details = details,
        metric_history = metric_history,
    )


@router.get("/status")
async def get_training_status(
    current_subject: str = Depends(get_current_subject),
    via_api_key: bool = Depends(authenticated_via_api_key),
):
    """
    Get the current training status.

    Redacted for an API-key caller like every other route that can name a host path: the
    worker's own progress line quotes the model it is loading, and for a local model that is
    an absolute path, which would hand back what the inventory took the trouble to hide.
    """
    try:
        backend = get_training_backend()
        for _ in range(3):
            identity_before = _training_status_identity(backend)
            is_active = await asyncio.to_thread(_run_active, backend)
            identity = _training_status_identity(backend)
            if identity != identity_before:
                continue
            status = _build_training_status(backend, identity, is_active)
            if _training_status_identity(backend) == identity:
                return redact_host_paths(status, via_api_key = via_api_key)
        raise HTTPException(status_code = 409, detail = "Training state changed during status read")
    except HTTPException:
        raise
    except Exception as e:
        raise log_and_http_error(
            e,
            500,
            "Failed to get training status",
            event = "training.status_failed",
            log = logger,
        )


@router.get("/metrics", response_model = TrainingMetricsResponse)
async def get_training_metrics(
    expected_job_id: Optional[str] = None, current_subject: str = Depends(get_current_subject)
):
    """
    Get training metrics (loss, learning rate, steps).
    """
    if job_is_foreign(get_training_backend()):
        return TrainingMetricsResponse(
            job_id = "",
            loss_history = [],
            lr_history = [],
            step_history = [],
            current_loss = None,
            current_lr = None,
            current_step = None,
        )
    try:
        backend = get_training_backend()
        job_id = getattr(backend, "current_job_id", "") or ""
        if getattr(backend, "_new_job_spawn_id", None) is not None or (
            expected_job_id is not None and expected_job_id != job_id
        ):
            raise HTTPException(status_code = 409, detail = "Training job was superseded")

        loss_history = list(backend.loss_history)
        lr_history = list(backend.lr_history)
        step_history = list(backend.step_history)
        grad_norm_history = list(getattr(backend, "grad_norm_history", []))
        grad_norm_step_history = list(getattr(backend, "grad_norm_step_history", []))

        if (
            getattr(backend, "_new_job_spawn_id", None) is not None
            or (getattr(backend, "current_job_id", "") or "") != job_id
        ):
            raise HTTPException(status_code = 409, detail = "Training job was superseded")

        current_loss = loss_history[-1] if loss_history else None
        current_lr = lr_history[-1] if lr_history else None
        current_step = step_history[-1] if step_history else None

        return TrainingMetricsResponse(
            job_id = job_id,
            loss_history = loss_history,
            lr_history = lr_history,
            step_history = step_history,
            grad_norm_history = grad_norm_history,
            grad_norm_step_history = grad_norm_step_history,
            current_loss = current_loss,
            current_lr = current_lr,
            current_step = current_step,
        )

    except HTTPException:
        raise
    except Exception as e:
        raise log_and_http_error(
            e,
            500,
            "Failed to get training metrics",
            event = "training.metrics_failed",
            log = logger,
        )


# POST too: quick tunnels hold a streamed GET until it closes. The hidden GET keeps old clients.
@router.post("/progress")
@router.get("/progress", include_in_schema = False)
async def stream_training_progress(
    request: Request,
    expected_job_id: Optional[str] = None,
    current_subject: str = Depends(get_current_subject),
):
    """
    Stream training progress via Server-Sent Events (SSE).

    Real-time progress with reconnection support per the SSE spec:
      - `id:` per event so the browser tracks position.
      - `retry:` to control reconnection interval.
      - Named `event:` types (progress, heartbeat, complete, error).
      - Reads `Last-Event-ID` on reconnect to replay missed steps.
    """
    last_event_id = request.headers.get("last-event-id")
    resume_from_step: Optional[int] = None
    if last_event_id is not None:
        try:
            resume_from_step = int(last_event_id)
            # Fires on every reconnect; the meaningful signal is the "replayed N missed steps" line.
            logger.debug(f"SSE reconnect: resuming from step {resume_from_step}")
        except ValueError:
            logger.warning(f"Invalid Last-Event-ID: {last_event_id}")

    async def event_generator():
        backend = get_training_backend()
        if job_is_foreign(backend):
            yield 'event: busy\ndata: {"status":"busy"}\n\n'
            return
        backend_job_id = getattr(backend, "current_job_id", "") or ""
        job_id = expected_job_id if expected_job_id is not None else backend_job_id

        def is_current_job() -> bool:
            return (
                getattr(backend, "_new_job_spawn_id", None) is None
                and (getattr(backend, "current_job_id", "") or "") == job_id
            )

        def run_active() -> bool:
            """A run that reported terminal is done, even while its worker tears down."""
            return _run_active(backend)

        def build_progress(
            step: int,
            loss: Optional[float],
            learning_rate: Optional[float],
            total_steps: int,
            epoch: Optional[float] = None,
            progress: Optional[Any] = None,
            grad_norm_override: Optional[float] = None,
            eval_loss_override: Optional[float] = None,
        ) -> TrainingProgress:
            total = max(total_steps, 0)
            if step < 0 or total == 0:
                progress_percent = 0.0
            else:
                progress_percent = float(step) / float(total) * 100.0 if total > 0 else 0.0

            elapsed_seconds = getattr(progress, "elapsed_seconds", None) if progress else None
            eta_seconds = getattr(progress, "eta_seconds", None) if progress else None
            session_start_step = getattr(progress, "session_start_step", None) if progress else None
            grad_norm = grad_norm_override
            if grad_norm is None and progress:
                grad_norm = getattr(progress, "grad_norm", None)
            num_tokens = getattr(progress, "num_tokens", None) if progress else None
            eval_loss = eval_loss_override
            if eval_loss is None and progress:
                eval_loss = getattr(progress, "eval_loss", None)

            return TrainingProgress(
                job_id = job_id,
                step = step,
                total_steps = total,
                loss = loss,
                learning_rate = learning_rate,
                progress_percent = progress_percent,
                epoch = epoch,
                elapsed_seconds = elapsed_seconds,
                eta_seconds = eta_seconds,
                session_start_step = session_start_step,
                grad_norm = grad_norm,
                num_tokens = num_tokens,
                eval_loss = eval_loss,
            )

        def format_sse(
            data: str,
            event: str = "progress",
            event_id: Optional[int] = None,
        ) -> str:
            lines = []
            if event_id is not None:
                lines.append(f"id: {event_id}")
            lines.append(f"event: {event}")
            lines.append(f"data: {data}")
            lines.append("")
            lines.append("")
            return "\n".join(lines)

        if not is_current_job():
            return

        yield "retry: 3000\n\n"

        if not is_current_job():
            return
        if resume_from_step is not None and backend.step_history:
            replayed = 0
            grad_norm_by_step = {
                step_val: grad_val
                for step_val, grad_val in zip(
                    getattr(backend, "grad_norm_step_history", []),
                    getattr(backend, "grad_norm_history", []),
                )
            }
            for i, step_val in enumerate(backend.step_history):
                if not is_current_job():
                    return
                if step_val > resume_from_step:
                    loss_val = backend.loss_history[i] if i < len(backend.loss_history) else None
                    lr_val = backend.lr_history[i] if i < len(backend.lr_history) else None
                    tp_replay = getattr(
                        getattr(backend, "trainer", None), "training_progress", None
                    )
                    total_replay = (
                        getattr(tp_replay, "total_steps", step_val) if tp_replay else step_val
                    )
                    epoch_replay = getattr(tp_replay, "epoch", None) if tp_replay else None
                    payload = build_progress(
                        step_val,
                        loss_val,
                        lr_val,
                        total_replay,
                        epoch_replay,
                        progress = tp_replay,
                        grad_norm_override = grad_norm_by_step.get(step_val),
                    )
                    if not is_current_job():
                        return
                    yield format_sse(payload.model_dump_json(), event = "progress", event_id = step_val)
                    replayed += 1
            if replayed:
                logger.info(f"SSE reconnect: replayed {replayed} missed steps")

        if resume_from_step is None:
            if not is_current_job():
                return
            is_active = await asyncio.to_thread(run_active)
            if not is_current_job():
                return
            tp = getattr(getattr(backend, "trainer", None), "training_progress", None)
            initial_total_steps = getattr(tp, "total_steps", 0) if tp else 0
            initial_epoch = getattr(tp, "epoch", None) if tp else None

            initial_progress = build_progress(
                step = 0,
                loss = None,
                learning_rate = None,
                total_steps = initial_total_steps,
                epoch = initial_epoch,
                progress = tp,
            )
            if not is_current_job():
                return
            yield format_sse(initial_progress.model_dump_json(), event = "progress", event_id = 0)

            if not is_active:
                _live = (getattr(tp, "step", 0) or 0) if tp else 0
                if backend.step_history or _live > 0:
                    final_step = backend.step_history[-1] if backend.step_history else 0
                    final_loss = backend.loss_history[-1] if backend.loss_history else None
                    final_lr = backend.lr_history[-1] if backend.lr_history else None
                    # Histories skip non-finite steps; report the live step with loss=None.
                    if _live > final_step:
                        final_step = _live
                        final_loss = getattr(tp, "loss", None)
                        final_lr = getattr(tp, "learning_rate", final_lr)
                    final_total_steps = getattr(tp, "total_steps", final_step) if tp else final_step
                    final_epoch = getattr(tp, "epoch", None) if tp else None
                    payload = build_progress(
                        final_step,
                        final_loss,
                        final_lr,
                        final_total_steps,
                        final_epoch,
                        progress = tp,
                    )
                    if not is_current_job():
                        return
                    yield format_sse(
                        payload.model_dump_json(), event = "complete", event_id = final_step
                    )
                else:
                    payload = build_progress(-1, None, None, 0, progress = tp)
                    if not is_current_job():
                        return
                    yield format_sse(
                        payload.model_dump_json(),
                        event = "complete",
                        event_id = 0,
                    )
                return

        last_step = resume_from_step if resume_from_step is not None else -1
        no_update_count = 0
        # The stall timeout applies only once the run is stepping
        seen_live_step = (resume_from_step is not None and resume_from_step > 0) or bool(
            backend.step_history
        )

        while True:
            if job_is_foreign(backend):
                yield 'event: busy\ndata: {"status":"busy"}\n\n'
                return
            if not is_current_job():
                return
            is_active = await asyncio.to_thread(run_active)
            if not is_current_job():
                return
            if not is_active:
                break
            # Client gone: end the generator without the final "complete" frame.
            if await request.is_disconnected():
                return
            if not is_current_job():
                return
            try:
                tp_inner = getattr(getattr(backend, "trainer", None), "training_progress", None)
                live_step = (getattr(tp_inner, "step", 0) or 0) if tp_inner else 0
                if backend.step_history or live_step > 0:
                    current_step = backend.step_history[-1] if backend.step_history else 0
                    current_loss = backend.loss_history[-1] if backend.loss_history else None
                    current_lr = backend.lr_history[-1] if backend.lr_history else None
                    # Histories skip non-finite steps; follow the live step and report its loss.
                    if live_step > current_step:
                        current_step = live_step
                        current_loss = getattr(tp_inner, "loss", None)
                        current_lr = getattr(tp_inner, "learning_rate", current_lr)
                    current_total_steps = (
                        getattr(tp_inner, "total_steps", current_step) if tp_inner else current_step
                    )
                    current_epoch = getattr(tp_inner, "epoch", None) if tp_inner else None

                    if current_step != last_step:
                        progress_payload = build_progress(
                            current_step,
                            current_loss,
                            current_lr,
                            current_total_steps,
                            current_epoch,
                            progress = tp_inner,
                        )
                        if not is_current_job():
                            return
                        yield format_sse(
                            progress_payload.model_dump_json(),
                            event = "progress",
                            event_id = current_step,
                        )
                        last_step = current_step
                        no_update_count = 0
                        seen_live_step = True
                    else:
                        no_update_count += 1
                        if no_update_count % 10 == 0:
                            heartbeat_payload = build_progress(
                                current_step,
                                current_loss,
                                current_lr,
                                current_total_steps,
                                current_epoch,
                                progress = tp_inner,
                            )
                            if not is_current_job():
                                return
                            yield format_sse(
                                heartbeat_payload.model_dump_json(),
                                event = "heartbeat",
                                event_id = current_step,
                            )
                else:
                    # No steps yet, but training is active (model loading, etc.).
                    no_update_count += 1
                    if no_update_count % 5 == 0:
                        # Pull total_steps + status so the frontend can show "Tokenizing..." etc.
                        tp_prep = getattr(
                            getattr(backend, "trainer", None),
                            "training_progress",
                            None,
                        )
                        prep_total = getattr(tp_prep, "total_steps", 0) if tp_prep else 0
                        preparing_payload = build_progress(
                            0,
                            None,
                            None,
                            prep_total,
                            progress = tp_prep,
                        )
                        if not is_current_job():
                            return
                        yield format_sse(
                            preparing_payload.model_dump_json(),
                            event = "heartbeat",
                            event_id = 0,
                        )

                # Fires only once stepping: a long pre-first-step prep phase is not a stall.
                if seen_live_step and no_update_count > _PROGRESS_STALL_TIMEOUT_POLLS:
                    logger.warning("Progress stream timeout - no updates received")
                    tp_timeout = getattr(
                        getattr(backend, "trainer", None), "training_progress", None
                    )
                    timeout_payload = build_progress(last_step, None, None, 0, progress = tp_timeout)
                    if not is_current_job():
                        return
                    yield format_sse(
                        timeout_payload.model_dump_json(),
                        event = "error",
                        event_id = last_step if last_step >= 0 else 0,
                    )
                    return

                await asyncio.sleep(1)

            except Exception as e:
                if not is_current_job():
                    return
                logger.error(f"Error in progress stream: {e}", exc_info = True)
                tp_error = getattr(getattr(backend, "trainer", None), "training_progress", None)
                error_payload = build_progress(0, None, None, 0, progress = tp_error)
                if not is_current_job():
                    return
                yield format_sse(
                    error_payload.model_dump_json(),
                    event = "error",
                    event_id = last_step if last_step >= 0 else 0,
                )
                return

        if not is_current_job():
            return
        final_step = backend.step_history[-1] if backend.step_history else last_step
        final_loss = backend.loss_history[-1] if backend.loss_history else None
        final_lr = backend.lr_history[-1] if backend.lr_history else None
        final_tp = getattr(getattr(backend, "trainer", None), "training_progress", None)
        # If the run ended on a non-finite stretch, report the live step with loss=None.
        _final_live_step = (getattr(final_tp, "step", 0) or 0) if final_tp else 0
        if _final_live_step > (final_step if final_step is not None else -1):
            final_step = _final_live_step
            final_loss = getattr(final_tp, "loss", None)
            final_lr = getattr(final_tp, "learning_rate", final_lr)
        final_total_steps = getattr(final_tp, "total_steps", final_step) if final_tp else final_step
        final_epoch = getattr(final_tp, "epoch", None) if final_tp else None
        final_payload = build_progress(
            final_step,
            final_loss,
            final_lr,
            final_total_steps,
            final_epoch,
            progress = final_tp,
        )
        if not is_current_job():
            return
        yield format_sse(
            final_payload.model_dump_json(),
            event = "complete",
            event_id = final_step if final_step >= 0 else 0,
        )

    return StreamingResponse(
        account_event_stream(get_training_backend(), event_generator()),
        media_type = "text/event-stream",
        headers = {
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "X-Accel-Buffering": "no",
        },
    )


# ── Diffusion (SDXL) LoRA training ────────────────────────────────────────────
# Diffusion (SDXL) LoRA training: separate job path via DiffusionTrainingService.
def _diffusion_training_active() -> bool:
    """Whether a diffusion (SDXL) LoRA job is currently running. Best-effort so the
    interlock never blocks a start just because the service could not be imported."""
    try:
        from core.training.diffusion_training_service import get_diffusion_training_service
        return get_diffusion_training_service().is_active()
    except Exception:  # noqa: BLE001
        return False


class _DiffusionStartInFlight(RuntimeError):
    """An LLM start lost the race to a diffusion start (route: refuse, don't spawn)."""


@contextlib.contextmanager
def _diffusion_gpu_admission():
    """Holds diffusion GPU admission across the LLM spawn so only one of two racing starts proceeds."""
    try:
        from core.training.diffusion_training_service import (
            TrainingActiveError,
            get_diffusion_training_service,
        )
        service = get_diffusion_training_service()
    except Exception:  # noqa: BLE001 -- no diffusion stack: nothing to coordinate with
        yield
        return
    try:
        cm = service.gpu_load_admission()
    except Exception:  # noqa: BLE001
        yield
        return
    try:
        cm.__enter__()
    except TrainingActiveError as exc:
        raise _DiffusionStartInFlight(
            "A diffusion (Images) LoRA training job is already running. "
            "Stop it before starting an LLM training run."
        ) from exc
    try:
        yield
    finally:
        cm.__exit__(None, None, None)


def _require_diffusion_dataset_mutable() -> None:
    """The trainer re-opens images mid-run, so a mutation underneath can raise FileNotFoundError."""
    if _diffusion_training_active():
        raise HTTPException(
            status_code = 409,
            detail = (
                "Training images cannot be changed while diffusion training is active. "
                "Stop the run before uploading, importing, editing captions, or deleting images."
            ),
        )


def diffusion_dataset_interlock():
    """A yield dependency, so the reservation spans the endpoint, not just the instant of the check."""
    try:
        from core.training.diffusion_training_service import (
            TrainingActiveError,
            get_diffusion_training_service,
        )
        service = get_diffusion_training_service()
    except Exception:  # noqa: BLE001 -- unknowable state never blocks a mutation
        yield
        return
    try:
        with service.dataset_mutation():
            yield
    except TrainingActiveError as exc:
        raise HTTPException(status_code = 409, detail = str(exc)) from exc


def _free_restyle_for_training() -> None:
    """The restyle sd-server sits outside the arbiter's owners; a running restyle refuses the start."""
    from core.inference import video_restyle
    from routes.training_vram import ManagedEngineStillRunning

    try:
        idle = video_restyle.runner.unload_if_idle()
    except Exception as e:  # noqa: BLE001
        logger.warning("Could not unload the video restyle server for training: %s", e)
        return
    if not idle:
        raise ManagedEngineStillRunning(
            "A video restyle is running. Cancel it or wait for it to finish."
        )


def _free_gpu_for_diffusion_training() -> None:
    """Frees resident GPU models first; the trainer's SDXL pipeline would OOM beside them."""
    try:
        from core.export import get_export_backend
        exp_backend = get_export_backend()
        if exp_backend.current_checkpoint or exp_backend.is_export_active():
            logger.info("Shutting down export subprocess to free GPU memory for diffusion training")
            exp_backend._shutdown_subprocess()
            exp_backend.current_checkpoint = None
            exp_backend.is_vision = False
            exp_backend.is_peft = False
    except Exception as e:  # noqa: BLE001
        logger.warning("Could not shut down export subprocess: %s", e)

    try:
        from core.inference import gpu_arbiter
        from core.inference.diffusion_engine_router import get_active_diffusion_engine

        # The ACTIVE engine, not the diffusers singleton: on a native (sd_cpp) selection the resident sd-server still
        # holds the GPU, so unloading only the singleton is a no-op.
        # The mask segmenter sits on torch's card whichever engine renders; one still running refuses the start.
        gpu_arbiter.release_mask_segmenter("diffusion training start")
        diffusion = get_active_diffusion_engine()
        if getattr(diffusion, "runs_off_torch_device", False) is True:
            logger.info("Keeping the Images model: it runs outside torch's GPUs")
        else:
            if diffusion.is_loaded:
                logger.info("Unloading resident Images pipeline to free GPU memory for training")
            diffusion.unload()
            gpu_arbiter.release(gpu_arbiter.DIFFUSION)
    except gpu_arbiter.SegmenterStillRunningError:
        raise  # a RuntimeError: the start route answers 409
    except Exception as e:  # noqa: BLE001
        logger.warning("Could not unload Images pipeline for diffusion training: %s", e)

    _free_restyle_for_training()
    try:
        from core.inference import gpu_arbiter
        from core.inference.video import get_video_backend

        video = get_video_backend()
        if video.status().get("loaded"):
            logger.info("Unloading resident Video pipeline to free GPU memory for training")
        video.unload()
        gpu_arbiter.release(gpu_arbiter.VIDEO)
    except Exception as e:  # noqa: BLE001
        logger.warning("Could not unload Video pipeline for diffusion training: %s", e)

    try:
        # The SDXL trainer footprint cannot be sized against resident chat, so always free chat.
        from routes.training_vram import free_chat_models_for_training, summarize_resident_chat
        if summarize_resident_chat()["any"]:
            freed = free_chat_models_for_training(reason = "diffusion training starting")
            logger.info("Freed chat model(s) for diffusion training: %s", freed)
    except Exception as e:  # noqa: BLE001
        if getattr(e, "blocks_training", False):
            raise
        logger.warning("Could not free chat models for diffusion training: %s", e)


def _preflight_gated_base(base_model: str, hf_token: Optional[str]) -> None:
    """Gated or unauthorized base repos fail with 400 before GPU teardown can evict a loaded model."""
    import urllib.error
    import urllib.request

    from core.inference.diffusion_families import _is_local_path

    repo = (base_model or "").strip()
    # Only remote 'org/name' repos are gated. A relative clone dir named like the vendor id also has
    # one slash, hence the existence test.
    if (
        not repo
        or repo.count("/") != 1
        or repo.startswith((".", "/", "~"))
        or repo.endswith(".gguf")
        or _is_local_path(repo)
    ):
        return
    from utils.hf_endpoint import get_hf_endpoint
    from utils.utils import auth_safe_open

    url = f"{get_hf_endpoint()}/{repo}/resolve/main/model_index.json"
    headers = {"Authorization": f"Bearer {hf_token}"} if hf_token else {}
    req = urllib.request.Request(url, method = "HEAD", headers = headers)
    # Not urlopen: a mirror's cross-host 302 would carry this token off-origin.
    try:
        auth_safe_open(req, timeout = 5)
    except urllib.error.HTTPError as e:
        if e.code in (401, 403):
            raise HTTPException(
                status_code = 400,
                detail = (
                    f"Access to '{repo}' is gated or unauthorized. Accept the model's license "
                    f"on its Hugging Face page and add your HF token in Unsloth settings, then "
                    f"try again."
                ),
            )
        # 404 and other codes are not access problems; let the trainer surface genuine load errors.
    except Exception:  # noqa: BLE001 -- network/DNS hiccup must not block a start
        return


def _resolve_diffusion_data_dir(raw: str) -> Path:
    """A bare folder name prefers the image dataset root when it exists there, so no upload shadows it."""
    from utils.paths import datasets_root

    value = str(raw or "").strip()
    from utils.paths.path_utils import is_network_or_device_path

    # Before dataset resolution touches the disk: a share path is already an outbound SMB sign-in.
    if is_network_or_device_path(value) and managed_account():
        raise HTTPException(status_code = 403, detail = "Path is outside this account's workspace")
    if value and "\x00" not in value:
        p = Path(value)
        # A single component that is not "..", so joining under datasets_root() cannot escape it.
        if not p.is_absolute() and len(p.parts) == 1 and p.parts[0] != "..":
            direct = datasets_root() / value
            # Same protected resolver as the CRUD routes, so external symlinks (even broken) are rejected.
            if direct.is_dir() or direct.is_symlink():
                resolved = _resolve_dataset_folder(value)
                account_path(resolved)
                return resolved
    resolved = resolve_dataset_path(raw)
    account_path(resolved)
    return resolved


def _diffusion_resume_target_steps(normalized_cfg: Any, pairs: list) -> int:
    """The trainer's step target (bucketing and per-bucket batches settled alike); a smaller one refuses late checkpoints."""
    from core.training import diffusion_train_common as _dtc

    cfg = _dtc.resolve_bucketing(normalized_cfg)
    return _dtc.resolve_train_steps(cfg, len(pairs), [p for p, _ in pairs])


def _preflight_diffusion_resume(
    config: dict,
    identity: Any,
    target_steps: int,
    *,
    pin: bool = True,
) -> None:
    """Pinning happens only in the fingerprinted pass; the first pass lacks the dataset fingerprint."""
    from core.training.diffusion_checkpoint import preflight_resume

    path, _step = preflight_resume(
        config["resume_from_checkpoint"], identity = identity, target_steps = target_steps
    )
    if pin:
        config["resume_from_checkpoint"] = path


@router.post("/diffusion/start", response_model = DiffusionTrainingStartResponse)
async def start_diffusion_training(
    body: DiffusionTrainingStartRequest,
    current_subject: str = Depends(get_current_subject),
    via_api_key: bool = Depends(authenticated_via_api_key),
):
    """Start an SDXL LoRA training job from an image + caption dataset."""
    from core.training.diffusion_training_service import get_diffusion_training_service

    # API-key auth: refuse while a request is in flight, since freeing GPU kills the stream.
    if via_api_key is True:
        from core.inference.llama_keepwarm import other_inference_request_count
        if (
            other_inference_request_count(current_request_counted = False) > 0
            or _background_video_generation_active()
        ):
            raise HTTPException(
                status_code = 409,
                detail = (
                    "Cannot start diffusion (Images) training over the API while an inference "
                    "request is in progress. Wait for it to finish, or start training from the "
                    "Unsloth UI."
                ),
            )

    # Refuse while an LLM training run holds the GPU (symmetric with start_training).
    try:
        if get_training_backend().is_training_active():
            raise HTTPException(
                status_code = 409,
                detail = (
                    "An LLM training job is already running. "
                    "Stop it before starting diffusion (Images) training."
                ),
            )
    except HTTPException:
        raise
    except Exception:  # noqa: BLE001 -- backend import/health issue must not block a start
        pass

    # Contain dataset and output paths BEFORE spawning; the trainer would resolve them against its cwd.
    config = body.model_dump()
    # An API key with no token of its own must not reach the operator's saved HF login.
    config["allow_ambient"] = via_api_key is not True
    try:
        from utils.paths import outputs_root, resolve_output_dir

        config["data_dir"] = str(_resolve_diffusion_data_dir(config["data_dir"]))
        # A name cleaning to nothing resolves to the outputs ROOT, where listings never see the adapter.
        root = outputs_root().resolve()
        out_dir = resolve_output_dir(config["output_dir"])
        if Path(out_dir).resolve() == root:
            raise HTTPException(
                status_code = 400,
                detail = (
                    f"'{config['output_dir']}' is the outputs folder itself, not a run inside it. "
                    "Pick a name for this run."
                ),
            )
        config["output_dir"] = str(out_dir)
        # Persistent cond cache gets the same containment; blank means in-memory, never the outputs root.
        cond_cache = str(config.get("cond_cache_dir") or "").strip()
        cond_cache_dir = resolve_output_dir(cond_cache) if cond_cache else None
        # A cache resolving to the trained-models dir is disabled, not one flat safetensors per latent there.
        if cond_cache_dir is not None and Path(cond_cache_dir).resolve() == root:
            cond_cache_dir = None
        config["cond_cache_dir"] = str(cond_cache_dir) if cond_cache_dir is not None else None
    except ValueError as e:
        raise HTTPException(status_code = 400, detail = str(e))

    validate_job_paths(config)

    # Validate BEFORE freeing GPU residents so a refused start never tears down chat/Images.
    from core.training.diffusion_lora_trainer import _config_from_dict

    try:
        # Off the event loop: resume may read checkpoint bundles.
        normalized_cfg = await asyncio.to_thread(_config_from_dict(config).normalized)
    except ValueError as e:
        raise HTTPException(status_code = 400, detail = str(e))

    # Only the DiT trainer reads cond_cache_dir; check the RESOLVED family.
    if cond_cache and normalized_cfg.resolved_family == "sdxl":
        raise HTTPException(
            status_code = 400,
            detail = (
                "cond_cache_dir is not supported for the sdxl family: its trainer uses a "
                "per-run in-memory latent cache and would ignore the persistent one. Omit it, "
                "or train a DiT family (flux.1, flux.2-klein, flux.2-dev, qwen-image, "
                "z-image, krea-2), which reuses conditioning across runs."
            ),
        )

    # H3 restrictions (batch > 1, non-bf16, weighting, compile, cond cache) must 400 before eviction.
    from core.training.diffusion_train_common import h3_train_unsupported_reason

    _h3_reason = h3_train_unsupported_reason(normalized_cfg)
    if _h3_reason:
        raise HTTPException(status_code = 400, detail = _h3_reason)

    # Preflights below run BEFORE freeing GPU residents: the trainer's own checks fire after eviction.
    from core.training.diffusion_train_common import training_precision_preflight_error

    _precision_reason = training_precision_preflight_error(
        normalized_cfg.resolved_family, normalized_cfg.base_precision
    )
    if _precision_reason:
        raise HTTPException(status_code = 400, detail = _precision_reason)

    # Trainer child imports the pipeline in this interpreter; refuse a broken import before GPU teardown.
    from core.training.diffusion_train_common import training_pipeline_import_error

    _pipeline_reason = training_pipeline_import_error(normalized_cfg.resolved_family)
    if _pipeline_reason:
        raise HTTPException(status_code = 400, detail = _pipeline_reason)

    # Resume checkpoint mismatches (family, base, LoRA shape, precision) must 400 before GPU eviction.
    from core.training.diffusion_checkpoint import (
        ResumeError,
        dataset_fingerprint,
        identity_for_config,
        resolve_resume_dir,
    )

    resuming = bool(normalized_cfg.resume_from_checkpoint)
    # Resume only: identity_for_config scans the local Hub cache.
    resume_identity = identity_for_config(normalized_cfg) if resuming else None
    if resuming:
        try:
            # Resolve a relative resume path here, not in the trainer subprocess cwd, as with data_dir.
            config["resume_from_checkpoint"] = str(
                resolve_resume_dir(normalized_cfg.resume_from_checkpoint)
            )
            # Epochs target known after sizing, so the finished check runs below; offloaded: must not block loop.
            await asyncio.to_thread(
                _preflight_diffusion_resume,
                config,
                resume_identity,
                # No dataset fingerprint here, so a terminal "already at target" refusal would be wrong.
                0,
                # Leave the request pointing at the user's input; the discovery pass may need to scan the directory.
                pin = False,
            )
        except ResumeError as e:
            raise HTTPException(status_code = 400, detail = str(e))

    # Run the trainers' trust gate here so an untrusted base 400s before eviction.
    from core.training.diffusion_train_common import (
        MODULAR_BASE_FAMILIES,
        _assert_trusted_base_model,
    )

    try:
        # A local MiniMax-H3 pipeline is modular (modular_model_index.json, no model_index.json).
        _assert_trusted_base_model(
            config.get("base_model", ""),
            allow_modular = normalized_cfg.resolved_family in MODULAR_BASE_FAMILIES,
        )
    except ValueError as e:
        raise HTTPException(status_code = 400, detail = str(e))

    # Preflight the repo the trainer fetches (a gated base may map to a mirror); run in a thread.
    await asyncio.to_thread(
        _preflight_gated_base,
        normalized_cfg.fetch_base_model or normalized_cfg.base_model,
        normalized_cfg.hf_token,
    )

    # A cached local base bypasses both checks above, so authorize the EFFECTIVE target as the LLM
    # start does; authorizing the original base too could refuse a public mirror.
    await asyncio.to_thread(
        _refuse_unauthorized_cached_local_paths,
        [normalized_cfg.fetch_base_model or normalized_cfg.base_model or ""],
        hf_token_arg(normalized_cfg.hf_token, allow_ambient_token = config["allow_ambient"]),
        "model",
    )

    from core.training import diffusion_train_common as _dtc

    service = get_diffusion_training_service()
    # Reserve the slot BEFORE the dataset preflight so concurrent upload/delete is fenced.
    reserved = False
    try:
        service.reserve()
        reserved = True
        # Fail closed on clips before discovery, for IMAGE-trained families only, or MiniMax-H3 gets refused.
        mixed_refusal = await asyncio.to_thread(
            _mixed_media_refusal, config["data_dir"], normalized_cfg.resolved_family
        )
        if mixed_refusal is not None:
            raise HTTPException(status_code = 400, detail = mixed_refusal)
        # Preflight the dataset so a missing or empty data_dir fails before GPU eviction, not after.
        try:
            pairs = await asyncio.to_thread(
                _dtc.discover_training_pairs,
                normalized_cfg.resolved_family,
                config["data_dir"],
                instance_prompt = config.get("instance_prompt") or None,
                caption_column = config.get("caption_column") or "text",
                # Decode-probe every image (cheap PIL header check) so a corrupt upload 400s before GPU teardown.
                verify_images = True,
            )
        except (FileNotFoundError, ValueError) as e:
            raise HTTPException(status_code = 400, detail = str(e))
        if resuming:
            try:
                target_steps = await asyncio.to_thread(
                    _diffusion_resume_target_steps, normalized_cfg, pairs
                )
                await asyncio.to_thread(
                    _preflight_diffusion_resume,
                    config,
                    resume_identity.with_dataset(dataset_fingerprint(pairs)),
                    target_steps,
                )
            except ResumeError as e:
                raise HTTPException(status_code = 400, detail = str(e))
        # Offloaded: teardown blocks on generation locks and a subprocess join.
        await asyncio.to_thread(_free_gpu_for_diffusion_training)
        job_id = service.start(config)
    except ValueError as e:
        raise HTTPException(status_code = 400, detail = str(e))
    except RuntimeError as e:
        # A running job, a reserved start, or an open DatasetMutationInFlight also maps to 409.
        raise HTTPException(status_code = 409, detail = str(e))
    except HTTPException:
        raise
    except Exception as e:
        raise log_and_http_error(
            e,
            500,
            "Failed to start diffusion training",
            event = "diffusion_training.start_failed",
            log = logger,
        )
    finally:
        # On success the live proc keeps is_active() true; only the reserving request clears it.
        if reserved:
            service.unreserve()
    return DiffusionTrainingStartResponse(job_id = job_id, status = "running")


@router.post("/diffusion/stop")
async def stop_diffusion_training(
    body: Optional[DiffusionTrainingStopRequest] = None,
    current_subject: str = Depends(get_current_subject),
):
    """Request a clean stop of the running diffusion training job. The optional body's
    ``save`` mirrors the LLM /stop: true (default, also for an empty POST) exports the
    partial adapter, false cancels without saving one."""
    from core.training.diffusion_training_service import get_diffusion_training_service

    save = body.save if body is not None else True
    stopped = get_diffusion_training_service().stop(save = save)
    return {"status": "stopping" if stopped else "idle"}


@router.get("/diffusion/status", response_model = DiffusionTrainingStatusResponse)
async def diffusion_training_status(current_subject: str = Depends(get_current_subject)):
    """Poll the current diffusion training job's status/progress (JSON)."""
    from core.training.diffusion_training_service import get_diffusion_training_service

    snap = get_diffusion_training_service().status()
    # Fold the service's flat history arrays into the nested metric_history the UI charts.
    metric_history = DiffusionMetricHistory(
        steps = snap.pop("metric_steps", []),
        loss = snap.pop("metric_loss", []),
        lr = snap.pop("metric_lr", []),
        grad_norm = snap.pop("metric_grad_norm", []),
        video_loss = snap.pop("metric_video_loss", []),
        audio_loss = snap.pop("metric_audio_loss", []),
    )
    return DiffusionTrainingStatusResponse(**snap, metric_history = metric_history)


@router.get("/diffusion/runs", response_model = DiffusionTrainingRunsResponse)
async def list_diffusion_training_runs(
    limit: int = 20, current_subject: str = Depends(get_current_subject)
):
    """Previous diffusion training runs (terminal), newest first, from the persisted
    per-run records. Summaries only; fetch one run for its config + metric logs."""
    from core.training.diffusion_training_service import list_diffusion_runs

    # Offloaded: can_resume re-validates checkpoint bundles on disk; must not block the event loop.
    records = await asyncio.to_thread(list_diffusion_runs, limit = limit)
    summaries: list[DiffusionTrainingRunSummary] = []
    for r in records:
        # Catch per record so one wrong-typed file never breaks the panel.
        try:
            summaries.append(DiffusionTrainingRunSummary(**r))
        except ValidationError:
            continue
    return DiffusionTrainingRunsResponse(runs = summaries)


@router.get("/diffusion/runs/{job_id}", response_model = DiffusionTrainingRunDetail)
async def get_diffusion_training_run(
    job_id: str, current_subject: str = Depends(get_current_subject)
):
    """One persisted diffusion run's full record: summary + scrubbed start config + the
    step/loss/grad-norm logs (for re-plotting a past run's charts)."""
    from core.training.diffusion_training_service import get_diffusion_run

    # Offloaded for the same reason as the listing: the read re-validates the run's checkpoints.
    rec = await asyncio.to_thread(get_diffusion_run, job_id)
    # A non-dict record raises TypeError, not ValidationError; treat it as absent.
    if not isinstance(rec, dict):
        raise HTTPException(status_code = 404, detail = "No such training run.")
    try:
        return DiffusionTrainingRunDetail(**rec)
    except ValidationError:
        # A malformed on-disk record reads as absent (404), not a 500, as the list route skips bad records.
        raise HTTPException(status_code = 404, detail = "No such training run.")


@router.get("/diffusion/runs/{job_id}/sample")
async def get_diffusion_training_sample(
    job_id: str,
    path: str,
    current_subject: str = Depends(get_current_subject),
):
    """Serve one preview image a run reported (``samples[].path``). Only a path the run itself
    listed is served, from inside that run's output_dir under this account's outputs root: the
    live job answers through the service's owner check, a finished one through its run record."""
    from fastapi.responses import FileResponse

    from core.training.diffusion_samples import SAMPLE_PATH_RE
    from core.training.diffusion_training_service import (
        get_diffusion_run,
        get_diffusion_training_service,
    )
    from utils.paths import outputs_root

    not_found = HTTPException(status_code = 404, detail = "Sample image not found.")
    if not SAMPLE_PATH_RE.match(path or ""):
        raise not_found
    source = get_diffusion_training_service().sample_source(job_id)
    if source is None:
        rec = await asyncio.to_thread(get_diffusion_run, job_id)
        if not isinstance(rec, dict):
            raise not_found
        samples = rec.get("samples") if isinstance(rec.get("samples"), list) else []
        out_dir = rec.get("output_dir")
    else:
        out_dir, samples = source
    if not out_dir or path not in {e.get("path") for e in samples if isinstance(e, dict)}:
        raise not_found
    try:
        base = Path(out_dir).resolve(strict = True)
        base.relative_to(outputs_root().resolve())
        target = (base / path).resolve(strict = True)
        target.relative_to(base)
    except (OSError, ValueError):
        raise not_found
    if not target.is_file():
        raise not_found
    return FileResponse(str(target), media_type = "image/png")


# Extensions accepted into a diffusion-training dataset folder: the media the trainer reads, plus its caption sources
# (per-item sidecars and metadata/captions jsonl).
_DIFFUSION_DATASET_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".bmp"}
# Shared definition so the trainer's discovery and this endpoint cannot drift apart.
_DIFFUSION_DATASET_CLIP_EXTS = set(_CLIP_EXTS)
# Images and clips are disjoint with identical caption rules; test_diffusion_dataset_clips.py
# asserts both.
_DIFFUSION_DATASET_MEDIA_EXTS = _DIFFUSION_DATASET_IMAGE_EXTS | _DIFFUSION_DATASET_CLIP_EXTS
_DIFFUSION_DATASET_TEXT_EXTS = {".txt", ".caption", ".jsonl"}


def _reserved_diffusion_dataset_names() -> frozenset[str]:
    """Names below the dataset root owned by other Studio dataset workflows."""
    from utils.paths import (
        dataset_uploads_root,
        recipe_datasets_root,
        seed_uploads_root,
        unstructured_uploads_root,
    )
    return frozenset(
        path.name.casefold()
        for path in (
            dataset_uploads_root(),
            recipe_datasets_root(),
            seed_uploads_root(),
            unstructured_uploads_root(),
        )
    )


def _resolve_dataset_caption(
    folder: Path, image_path: Path, meta_captions: dict[str, str]
) -> Optional[str]:
    """An empty sidecar still shadows metadata and yields no caption, so it must not count as captioned."""
    caption: Optional[str] = None
    sidecar_present = False
    for ext in (".txt", ".caption"):
        sidecar = image_path.with_suffix(ext)
        if sidecar.is_file():
            sidecar_present = True
            try:
                caption = sidecar.read_text(encoding = "utf-8").strip()
            except (OSError, UnicodeError):
                # Unreadable sidecar is the EMPTY TOMBSTONE, not absent: reading it as absent shows a stale caption.
                caption = ""
            break
    if not sidecar_present:
        try:
            rel = image_path.relative_to(folder).as_posix()
        except ValueError:
            rel = None
        caption = meta_captions.get(image_path.name) or (
            meta_captions.get(rel) if rel is not None else None
        )
    return caption


_DATASET_IMPORT_LOCKS: Dict[str, "threading.Lock"] = {}
_DATASET_IMPORT_LOCKS_GUARD = threading.Lock()


def _dataset_import_lock(folder: Path) -> "threading.Lock":
    """serialize imports by case-folded resolved path; process-lifetime locks cannot disappear while held."""
    key = str(folder.resolve(strict = False)).casefold()
    with _DATASET_IMPORT_LOCKS_GUARD:
        lock = _DATASET_IMPORT_LOCKS.get(key)
        if lock is None:
            lock = threading.Lock()
            _DATASET_IMPORT_LOCKS[key] = lock
        return lock


def _import_response(
    entry: dict, folder: Path, *, imported: int
) -> "DiffusionDatasetImportResponse":
    summary = _diffusion_dataset_summary(folder)
    return DiffusionDatasetImportResponse(
        name = folder.name,
        path = str(folder),
        image_count = summary.image_count,
        clip_count = summary.clip_count,
        caption_count = summary.caption_count,
        imported = imported,
        license = entry["license"],
        source_repo = entry["repo"],
    )


def _diffusion_dataset_summary(folder: Path) -> DiffusionDatasetSummary:
    # Captioned only when it resolves to a NON-EMPTY caption (sidecar over metadata), as the trainer.
    meta_captions = _load_metadata_captions(folder)
    images = clips = captions = 0
    for f in drop_appledouble_metadata(list(folder.iterdir())):
        if not f.is_file():
            continue
        ext = f.suffix.lower()
        if ext in _DIFFUSION_DATASET_IMAGE_EXTS:
            images += 1
        elif ext in _DIFFUSION_DATASET_CLIP_EXTS:
            clips += 1
        else:
            continue
        if _resolve_dataset_caption(folder, f, meta_captions):
            captions += 1
    return DiffusionDatasetSummary(
        name = folder.name,
        path = str(folder),
        image_count = images,
        clip_count = clips,
        caption_count = captions,
    )


def _mixed_media_refusal(data_dir: str, resolved_family: str) -> Optional[str]:
    """Mixed images and clips train only one medium's subset, silently; the folder is refused."""
    from core.training.diffusion_train_common import CLIP_TRAINED_FAMILIES

    if str(resolved_family or "").strip().lower() in CLIP_TRAINED_FAMILIES:
        return _image_dataset_refusal(data_dir)
    return _clip_dataset_refusal(data_dir)


def _image_dataset_refusal(data_dir: str) -> Optional[str]:
    """The converse of ``_clip_dataset_refusal``, for a family that trains from clips.
    ``discover_clip_caption_pairs`` enumerates video extensions only, so a still in a clip folder is
    dropped from the run while /diffusion/info and the picker both count it as a training item."""
    try:
        summary = _diffusion_dataset_summary(Path(data_dir).expanduser())
    except OSError:
        return None
    if summary.image_count <= 0:
        return None
    images = f"{summary.image_count} still image" + ("" if summary.image_count == 1 else "s")
    return (
        f"'{Path(data_dir).expanduser().name}' holds {images} alongside its clips. This model "
        "trains from clips, so a run started here would leave the stills out. Take the images "
        "out of this folder, or choose a dataset of clips."
    )


def _clip_dataset_refusal(data_dir: str) -> Optional[str]:
    """Refuses any folder holding a clip, since no trainer reads clips yet; drop this once they do."""
    try:
        summary = _diffusion_dataset_summary(Path(data_dir).expanduser())
    except OSError:
        return None
    if summary.clip_count <= 0:
        return None
    clips = f"{summary.clip_count} video clip" + ("" if summary.clip_count == 1 else "s")
    return (
        f"'{Path(data_dir).expanduser().name}' holds {clips}. Training from clips is not "
        "supported yet, and a run started here would train on the still images alone. "
        "Choose a dataset of images, or take the clips out of this folder."
    )


def _listed_dataset_clip_count(summary: DiffusionDatasetSummary) -> int:
    """Read from the summary: while the dataset layer is image-only, every folder reports 0 clips."""
    try:
        return int(getattr(summary, "clip_count", 0) or 0)
    except (TypeError, ValueError):
        return 0


def _listed_dataset_trains_clips(summary: DiffusionDatasetSummary) -> bool:
    """Same two conditions as _image_dataset_refusal (clips present, no stills), so they cannot drift."""
    if _listed_dataset_clip_count(summary) <= 0:
        return False
    try:
        return int(getattr(summary, "image_count", 0) or 0) <= 0
    except (TypeError, ValueError):
        return False


def _ui_trainable_families(datasets: list[DiffusionDatasetSummary]) -> list[dict]:
    """Offers CLIP families only when a listed folder holds clips and no stills, else Start fails."""
    from core.training.diffusion_train_common import CLIP_TRAINED_FAMILIES, family_train_infos

    infos = family_train_infos()
    if any(_listed_dataset_trains_clips(s) for s in datasets):
        return infos
    return [
        i for i in infos if str(i.get("name") or "").strip().lower() not in CLIP_TRAINED_FAMILIES
    ]


@router.get("/diffusion/info", response_model = DiffusionTrainingInfoResponse)
async def diffusion_training_info(current_subject: str = Depends(get_current_subject)):
    """Describe where diffusion training reads/writes, and list usable dataset folders.

    A dataset folder is any direct child of the datasets root that contains at least one
    trainable item: an image, or a clip for the families that train from video. The UI uses
    this to offer a picker instead of a blind free-text path.

    The family list is the trainable set NARROWED to what these datasets can feed: see
    ``_ui_trainable_families``. Only the advertisement narrows -- ``/diffusion/start`` still
    accepts every family that has a trainer."""
    from utils.paths import datasets_root, outputs_root

    def scan() -> DiffusionTrainingInfoResponse:
        root = datasets_root()
        found: list[DiffusionDatasetSummary] = []
        continuations: list[str] = []
        reserved_names = _reserved_diffusion_dataset_names()
        try:
            # Skip dot-prefixed dirs: not user datasets; example import stages into a hidden sibling.
            children = sorted(
                p
                for p in root.iterdir()
                # The CRUD resolver rejects symlinked dirs, so do not advertise them.
                if p.is_dir() and not p.is_symlink() and not p.name.startswith(".")
            )
        except OSError:
            children = []
        for child in children:
            try:
                summary = _diffusion_dataset_summary(child)
            except OSError:
                continue
            # clip-only folders are valid for video families.
            if summary.image_count > 0 or summary.clip_count > 0:
                found.append(summary)
            elif child.name.casefold() not in reserved_names:
                # captions-only, or emptied by deleting its last item (hidden .thumbs may remain).
                try:
                    visible = [e for e in child.iterdir() if not e.name.startswith(".")]
                    continuable = not visible or any(
                        e.is_file() and e.suffix.lower() in _DIFFUSION_DATASET_TEXT_EXTS
                        for e in visible
                    )
                except OSError:
                    continuable = False
                if continuable:
                    continuations.append(child.name)
        families = [DiffusionTrainableFamily(**info) for info in _ui_trainable_families(found)]
        return DiffusionTrainingInfoResponse(
            datasets_root = str(root),
            outputs_root = str(outputs_root()),
            datasets = found,
            dataset_names = [p.name for p in children],
            continuation_dataset_names = continuations,
            families = families,
        )

    return await asyncio.to_thread(scan)


_DATASET_NAME_RE = None


# Windows reserves these names with any extension; superscript COM/LPT digits also count as digits in Win32.
_WINDOWS_RESERVED_NAMES = frozenset(
    {"con", "prn", "aux", "nul"}
    | {f"com{d}" for d in "123456789¹²³"}
    | {f"lpt{d}" for d in "123456789¹²³"}
)


_DATASETS_CASE_INSENSITIVE: Optional[bool] = None


def _dataset_folder_is_case_insensitive(folder: Path) -> bool:
    """Probes the filesystem rather than trusting sys.platform; a failed probe means case-sensitive."""
    global _DATASETS_CASE_INSENSITIVE
    if _DATASETS_CASE_INSENSITIVE is None:
        import tempfile
        try:
            with tempfile.NamedTemporaryFile(prefix = ".case-probe-", dir = folder) as probe:
                probe_name = Path(probe.name).name
                _DATASETS_CASE_INSENSITIVE = (folder / probe_name.upper()).exists()
        except OSError:
            return False
    return _DATASETS_CASE_INSENSITIVE


def _clean_diffusion_dataset_name(name: str) -> str:
    """Windows path rules on every OS: reserved names crash mkdir; a trailing dot maps to the bare name."""
    import re

    global _DATASET_NAME_RE
    if _DATASET_NAME_RE is None:
        _DATASET_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._ -]{0,127}$")
    cleaned = (name or "").strip()
    if not _DATASET_NAME_RE.fullmatch(cleaned) or ".." in cleaned:
        raise HTTPException(
            status_code = 400,
            detail = (
                "Dataset name must be a plain folder name (letters, numbers, dots, "
                "dashes, spaces; no slashes), e.g. 'my-style-photos'."
            ),
        )
    if cleaned.endswith("."):
        raise HTTPException(
            status_code = 400,
            detail = (
                "Dataset name cannot end with a period: Windows strips it, so this name would "
                f"open the existing '{cleaned.rstrip('.')}' dataset instead of a new one."
            ),
        )
    # The stem alone is checked, since NUL.txt is the NUL device too.
    if cleaned.split(".", 1)[0].casefold() in _WINDOWS_RESERVED_NAMES:
        raise HTTPException(
            status_code = 400,
            detail = (
                f"'{cleaned}' is a reserved device name on Windows and cannot be a folder. "
                "Pick another dataset name."
            ),
        )
    return cleaned


@router.post("/diffusion/dataset", response_model = DiffusionDatasetUploadResponse)
async def upload_diffusion_dataset(
    name: str = Form(...),
    files: list[UploadFile] = File(...),
    create_only: bool = Form(False),
    current_subject: str = Depends(get_current_subject),
    _interlock: None = Depends(diffusion_dataset_interlock),
):
    """repeat uploads accumulate in one Unsloth dataset folder; pass its name as ``data_dir`` to /diffusion/start."""
    _require_diffusion_dataset_mutable()
    cleaned = _clean_diffusion_dataset_name(name)
    if cleaned.casefold() in _reserved_diffusion_dataset_names():
        raise HTTPException(
            status_code = 400,
            detail = f"'{cleaned}' is reserved for Unsloth's internal dataset storage.",
        )
    folder = _resolve_dataset_folder(name, must_exist = False)
    # serialize same-folder imports because the training interlock permits mutations; duplicate checks run here
    _lock = _dataset_import_lock(folder)
    if not _lock.acquire(blocking = False):
        raise HTTPException(
            status_code = 409,
            detail = (
                f"An import into '{folder.name}' is already running. Wait for it to finish, "
                "then upload again."
            ),
        )
    return await _run_holding_import_lock(
        _lock, _store_diffusion_dataset_upload, folder, cleaned, files, create_only
    )


async def _run_holding_import_lock(_lock: "threading.Lock", fn, *args):
    """Runs ``fn(*args, _lock, cancelled)`` on a worker that releases ``_lock``, so a cancel never frees it mid-import."""
    cancelled = threading.Event()
    guard = threading.Lock()
    started = False

    def run():
        nonlocal started
        with guard:
            if cancelled.is_set():
                return None
            started = True
        return fn(*args, _lock, cancelled)

    worker = asyncio.ensure_future(asyncio.to_thread(run))
    try:
        return await asyncio.shield(worker)
    except BaseException:
        with guard:
            cancelled.set()
            if not started:
                _lock.release()
                raise
        # Keep the request (interlock, open uploads) alive until the worker stops at its next chunk read.
        while not worker.done():
            try:
                await asyncio.shield(worker)
            except BaseException:
                pass
        raise


def _read_upload_chunk(f: UploadFile, cancelled: "threading.Event") -> bytes:
    """A cancelled request stops staging at the next chunk."""
    if cancelled.is_set():
        raise asyncio.CancelledError()
    return f.file.read(1024 * 1024)


def _store_diffusion_dataset_upload(
    folder: Path,
    cleaned: str,
    files: list[UploadFile],
    create_only: bool,
    _lock: "threading.Lock",
    cancelled: "threading.Event",
) -> "DiffusionDatasetUploadResponse":
    """Validates, stages and commits one upload slice; called with ``_lock`` held and releases it."""
    created_folder = False
    try:
        from utils.upload_limits import get_upload_limit_bytes, get_upload_limit_label

        if create_only:
            occupied = (
                next(
                    (
                        p
                        for p in folder.parent.iterdir()
                        if p.is_dir()
                        and not p.is_symlink()
                        and p.name.casefold() == cleaned.casefold()
                    ),
                    None,
                )
                if folder.parent.is_dir()
                else None
            )
            if occupied is not None:
                raise HTTPException(
                    status_code = 409,
                    detail = (
                        f"Dataset '{occupied.name}' already exists. Pick it in the dataset list "
                        "to add files, or choose another name."
                    ),
                )
        try:
            folder.mkdir(parents = True, exist_ok = not create_only)
            created_folder = create_only
        except FileExistsError:
            raise HTTPException(
                status_code = 409,
                detail = (
                    f"Dataset '{cleaned}' already exists. Pick it in the dataset list to add "
                    "files, or choose another name."
                ),
            )
        limit_bytes = get_upload_limit_bytes()
        total_bytes = 0
        uploaded = 0
        allowed = _DIFFUSION_DATASET_MEDIA_EXTS | _DIFFUSION_DATASET_TEXT_EXTS
        # validate all filenames first so an invalid name cannot leave earlier files on disk
        names: list[str] = []
        # use insertion-ordered indexes to avoid O(N^2) scans while preserving the filename reported in errors
        seen_names: set = set()
        first_name_by_casefold: dict = {}
        media_names_by_stem_cf: dict = {}
        # Listed lazily, once; iterdir order keeps the reported clash the first listed match.
        existing_media_by_stem_cf: Optional[dict] = None
        for f in files:
            # Path.name does not split on a backslash on POSIX, so fold them first.
            filename = Path((f.filename or "").replace("\\", "/")).name.strip().replace("\x00", "")
            ext = Path(filename).suffix.lower()
            if not filename or ".." in filename or ext not in allowed:
                exts = ", ".join(sorted(allowed))
                raise HTTPException(
                    status_code = 400,
                    detail = f"Unsupported file '{f.filename}'. Allowed: {exts}",
                )
            # Reject an exact duplicate within THIS batch; the later replace would discard the earlier.
            fname_cf = filename.casefold()
            if filename in seen_names:
                raise HTTPException(
                    status_code = 400,
                    detail = (
                        f"Duplicate file '{filename}' appears more than once in this upload. "
                        "Files sharing a name would overwrite each other; rename one before "
                        "uploading."
                    ),
                )
            # Items sharing a stem (any extension, image or clip) collide on one <stem>.txt sidecar.
            if ext in _DIFFUSION_DATASET_MEDIA_EXTS:
                stem = Path(filename).stem
                # Case-insensitive filesystems map stems differing only by case to the SAME sidecar.
                stem_cf = stem.casefold()

                def _shares_sidecar(other_name: str) -> bool:
                    other = Path(other_name)
                    if (
                        other_name == filename
                        or other.suffix.lower() not in _DIFFUSION_DATASET_MEDIA_EXTS
                        or other.stem.casefold() != stem_cf
                    ):
                        return False
                    # A casefold-equal name is exempt unless the stems match exactly.
                    return other.stem == stem or other_name.casefold() != fname_cf

                if existing_media_by_stem_cf is None:
                    existing_media_by_stem_cf = {}
                    for p in folder.iterdir():
                        other = Path(p.name)
                        if other.suffix.lower() in _DIFFUSION_DATASET_MEDIA_EXTS:
                            existing_media_by_stem_cf.setdefault(other.stem.casefold(), []).append(
                                p
                            )
                clash = next(
                    (
                        p.name
                        for p in existing_media_by_stem_cf.get(stem_cf, ())
                        if p.is_file() and _shares_sidecar(p.name)
                    ),
                    None,
                )
                if clash is None:
                    # Only a media name with this casefolded stem can share the sidecar.
                    clash = next(
                        (n for n in media_names_by_stem_cf.get(stem_cf, ()) if _shares_sidecar(n)),
                        None,
                    )
                if clash is not None:
                    kind = "clip" if ext in _DIFFUSION_DATASET_CLIP_EXTS else "image"
                    raise HTTPException(
                        status_code = 400,
                        detail = (
                            f"Duplicate {kind} name '{stem}'. '{clash}' is already in this "
                            f"dataset; two files sharing a name would share one '{stem}.txt' "
                            f"caption. Rename one before uploading."
                        ),
                    )
            # Case variants in one batch are ONE destination where the filesystem folds case.
            clash_cf = first_name_by_casefold.get(fname_cf)
            if clash_cf is not None and _dataset_folder_is_case_insensitive(folder):
                raise HTTPException(
                    status_code = 400,
                    detail = (
                        f"Duplicate file '{filename}' differs from '{clash_cf}' only by letter "
                        "case, so on this filesystem they are one file and would overwrite each "
                        "other. Rename one before uploading."
                    ),
                )
            seen_names.add(filename)
            first_name_by_casefold.setdefault(fname_cf, filename)
            if ext in _DIFFUSION_DATASET_MEDIA_EXTS:
                media_names_by_stem_cf.setdefault(Path(filename).stem.casefold(), []).append(
                    filename
                )
            names.append(filename)
        staged: list[tuple[Path, Path]] = []
        # Stage to temp names and commit at the end; a mid-batch failure would truncate a same-name file.
        committed = False
        try:
            for f, filename in zip(files, names):
                dest = folder / filename
                # Filename-independent temp name so a long filename cannot overflow NAME_MAX.
                tmp = folder / f".upload-{_uuid.uuid4().hex}.part"
                staged.append((tmp, dest))
                with open(tmp, "wb") as out:
                    while chunk := _read_upload_chunk(f, cancelled):
                        total_bytes += len(chunk)
                        if total_bytes > limit_bytes:
                            raise HTTPException(
                                status_code = 413,
                                detail = (
                                    "Dataset upload too large. "
                                    f"Maximum is {get_upload_limit_label()} per upload; "
                                    "add the remaining files in another batch."
                                ),
                            )
                        out.write(chunk)
                # Reject decompression bombs before commit (images only; clips are resized by the trainer).
                if Path(filename).suffix.lower() in _DIFFUSION_DATASET_IMAGE_EXTS:
                    _validate_uploaded_training_image(tmp, filename)
                uploaded += 1
            # Re-check: /diffusion/start may have reserved the slot while we streamed.
            _require_diffusion_dataset_mutable()
            backups: list[tuple[Path, Optional[Path]]] = []
            # A replace loop is not atomic: back up displaced files and restore all on failure.
            installed: list[Path] = []
            try:
                for tmp, dest in staged:
                    backup: Optional[Path] = None
                    if dest.exists():
                        backup = folder / f".upload-backup-{_uuid.uuid4().hex}.part"
                        dest.replace(backup)
                    backups.append((dest, backup))
                    tmp.replace(dest)
                    installed.append(dest)
                committed = True
            except BaseException:
                # Roll back: drop every new version, then restore every displaced original.
                for dest in reversed(installed):
                    try:
                        dest.unlink(missing_ok = True)
                    except OSError:
                        pass
                for dest, backup in reversed(backups):
                    if backup is not None and backup.exists():
                        try:
                            backup.replace(dest)
                        except OSError:
                            pass
                raise
            else:
                for _, backup in backups:
                    if backup is not None:
                        try:
                            backup.unlink(missing_ok = True)
                        except OSError:
                            pass
        finally:
            if not committed:
                for tmp, _ in staged:
                    try:
                        tmp.unlink(missing_ok = True)
                    except OSError:
                        pass

        summary = _diffusion_dataset_summary(folder)
        return DiffusionDatasetUploadResponse(
            name = cleaned,
            path = str(folder),
            image_count = summary.image_count,
            clip_count = summary.clip_count,
            caption_count = summary.caption_count,
            uploaded = uploaded,
        )
    except BaseException:
        if created_folder:
            try:
                folder.rmdir()
            except OSError:
                pass
        raise
    finally:
        _lock.release()


# ── Dataset labeling (per-image caption editing) + one-click example imports ── Thumbnails live in
# Thumbnails live in a hidden subdir, invisible to listings and the trainer's discovery.
_THUMBS_DIRNAME = ".thumbs"
_MAX_CAPTION_CHARS = 2000


def _resolve_dataset_folder(name: str, *, must_exist: bool = True) -> Path:
    """Validate ``name`` (single component, no traversal) and resolve it under the Unsloth
    datasets root. 404 when a read target is missing."""
    from utils.paths import datasets_root

    cleaned = _clean_diffusion_dataset_name(name)
    root = datasets_root().resolve()
    folder = root / cleaned
    # Reject a symlinked dataset dir and prove it resolves under root; the image-path check does not.
    if folder.is_symlink():
        raise HTTPException(
            status_code = 400,
            detail = f"Dataset '{cleaned}' must not be a symbolic link.",
        )
    if must_exist and not folder.is_dir():
        raise HTTPException(status_code = 404, detail = f"Dataset '{cleaned}' not found.")
    try:
        folder.resolve(strict = must_exist).relative_to(root)
    except (OSError, ValueError):
        raise HTTPException(
            status_code = 400,
            detail = f"Dataset '{cleaned}' escapes the Unsloth datasets directory.",
        )
    return folder


# Match diffusion's 4096px decoded-image limit.
_MAX_TRAINING_IMAGE_SIDE = 4096


def _validate_uploaded_training_image(path: Path, original_name: str) -> None:
    """Reads only the header, never img.load(), so huge-dimension images are refused before decoding."""
    from PIL import Image, UnidentifiedImageError

    try:
        with Image.open(path) as image:
            width, height = image.size
    except Image.DecompressionBombError:
        # Past Pillow's ~179 MP limit Image.open() raises a bare Exception subclass; avoid a 500.
        raise HTTPException(
            status_code = 400,
            detail = (
                f"Image '{original_name}' is too large; maximum is "
                f"{_MAX_TRAINING_IMAGE_SIDE}px per side."
            ),
        )
    except (OSError, UnidentifiedImageError, ValueError):
        return
    if width > _MAX_TRAINING_IMAGE_SIDE or height > _MAX_TRAINING_IMAGE_SIDE:
        raise HTTPException(
            status_code = 400,
            detail = (
                f"Image '{original_name}' is too large ({width}x{height}); maximum is "
                f"{_MAX_TRAINING_IMAGE_SIDE}px per side."
            ),
        )


def _safe_dataset_image_path(folder: Path, filename: str) -> Path:
    """Resolve ``filename`` to an image path strictly inside ``folder``. Rejects any path
    separators / traversal / null bytes and non-image extensions."""
    raw = filename or ""
    if "/" in raw or "\\" in raw or ".." in raw or "\x00" in raw or raw != Path(raw).name:
        raise HTTPException(status_code = 400, detail = "Invalid image filename.")
    if Path(raw).suffix.lower() not in _DIFFUSION_DATASET_IMAGE_EXTS:
        exts = ", ".join(sorted(_DIFFUSION_DATASET_IMAGE_EXTS))
        raise HTTPException(status_code = 400, detail = f"Not an image file. Allowed: {exts}")
    path = folder / raw
    # Defense in depth: the real path must stay under the dataset folder.
    try:
        path.resolve().relative_to(folder.resolve())
    except ValueError:
        raise HTTPException(status_code = 400, detail = "Invalid image filename.")
    if is_appledouble_metadata(path):
        raise HTTPException(status_code = 400, detail = "Not an image file.")
    return path


def _load_metadata_captions(folder: Path) -> dict[str, str]:
    """Read metadata.jsonl / captions.jsonl into {file_name: caption}, mirroring the
    trainer's discovery (keys file_name/video/image/file; caption in the ``text`` column)."""
    import json

    out: dict[str, str] = {}
    for meta_name in ("metadata.jsonl", "captions.jsonl"):
        meta_path = folder / meta_name
        if not meta_path.is_file():
            continue
        # Tolerate a bad upload (invalid UTF-8, or non-object JSON): skip the record so these endpoints do not 500.
        # split("\n"), not splitlines(): JSON keeps U+2028, U+2029 and U+0085 raw inside a string.
        try:
            lines = meta_path.read_text(encoding = "utf-8").split("\n")
        except (OSError, UnicodeError):
            continue
        for line in lines:
            line = line.strip()
            if not line:
                continue
            try:
                row = json.loads(line)
            except (json.JSONDecodeError, TypeError):
                continue
            if not isinstance(row, dict):
                continue
            # "video" too: clip discovery accepts it.
            key = row.get("file_name") or row.get("video") or row.get("image") or row.get("file")
            value = row.get("text")
            # A JSON null is "no caption", not the string "None".
            if key and value is not None:
                out[str(key)] = str(value)
    return out


_IMAGE_SIZE_CACHE_MAX = 8192
_image_size_cache: "OrderedDict[str, tuple[tuple, tuple[int, int]]]" = OrderedDict()
_image_size_cache_lock = threading.Lock()


def _dataset_image_size(image_path: Path, info: Optional[os.stat_result]) -> tuple[int, int]:
    """Header size (0x0 if unreadable), reused while the file's stat ``info`` is unchanged."""
    key = None
    name = str(image_path)
    if info is not None:
        # POSIX: any write moves ctime, even with mtime restored; a replace moves the inode.
        key = (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
        with _image_size_cache_lock:
            hit = _image_size_cache.get(name)
            if hit is not None and hit[0] == key:
                _image_size_cache.move_to_end(name)
                return hit[1]
    try:
        from PIL import Image
        with Image.open(image_path) as im:
            size = im.size
    except Exception:  # noqa: BLE001 -- lists as 0x0 rather than 500; not cached, so retried
        return 0, 0
    if key is not None:
        with _image_size_cache_lock:
            _image_size_cache[name] = (key, size)
            _image_size_cache.move_to_end(name)
            while len(_image_size_cache) > _IMAGE_SIZE_CACHE_MAX:
                _image_size_cache.popitem(last = False)
    return size


def _image_record(
    folder: Path, image_path: Path, meta_captions: dict[str, str]
) -> DiffusionDatasetImageRecord:
    """A sidecar beats metadata or captions rows: it is the user's explicit edit from the labeling grid."""
    caption: Optional[str] = None
    source = "none"
    sidecar_present = False
    for ext in (".txt", ".caption"):
        sidecar = image_path.with_suffix(ext)
        if sidecar.is_file():
            sidecar_present = True
            try:
                caption = sidecar.read_text(encoding = "utf-8").strip()
                source = "sidecar"
            except (OSError, UnicodeError):
                # UnicodeDecodeError is a ValueError, not OSError; the trainer treats any sidecar as a tombstone.
                caption = None
                source = "sidecar"
            break
    if caption is None and not sidecar_present:
        # Basename first, then the relative posix path: discover_image_caption_pairs order.
        meta = meta_captions.get(image_path.name)
        if meta is None:
            try:
                meta = meta_captions.get(image_path.relative_to(folder).as_posix())
            except ValueError:
                meta = None
        if meta is not None:
            caption = meta
            source = "metadata"
    try:
        info = image_path.stat()
        size_bytes = info.st_size
    except OSError:
        info = None
        size_bytes = 0
    is_clip = image_path.suffix.lower() in _DIFFUSION_DATASET_CLIP_EXTS
    width = height = 0
    if not is_clip:
        width, height = _dataset_image_size(image_path, info)
    return DiffusionDatasetImageRecord(
        filename = image_path.name,
        caption = caption,
        caption_source = source,  # type: ignore[arg-type]
        kind = "clip" if is_clip else "image",
        width = width,
        height = height,
        size_bytes = size_bytes,
    )


@router.get("/diffusion/dataset/{name}/images", response_model = DiffusionDatasetImagesResponse)
async def list_diffusion_dataset_images(
    name: str, current_subject: str = Depends(get_current_subject)
):
    """List every item in a dataset folder with its resolved caption (including
    uncaptioned ones), for the labeling grid.

    Clips are listed with ``kind: "clip"`` and 0x0 dimensions. The grid renders images only,
    but the upload's pre-flight needs every name that holds a ``<stem>.txt`` sidecar open, and
    a clip does that just as an image does."""
    folder = _resolve_dataset_folder(name)

    def scan() -> DiffusionDatasetImagesResponse:
        meta = _load_metadata_captions(folder)
        records: list[DiffusionDatasetImageRecord] = []
        for p in drop_appledouble_metadata(sorted(folder.iterdir())):
            if p.is_file() and p.suffix.lower() in _DIFFUSION_DATASET_MEDIA_EXTS:
                records.append(_image_record(folder, p, meta))
        return DiffusionDatasetImagesResponse(name = folder.name, path = str(folder), images = records)

    return await asyncio.to_thread(scan)


@router.get("/diffusion/dataset/{name}/image/{filename}")
async def get_diffusion_dataset_image(
    name: str,
    filename: str,
    thumb: Optional[int] = None,
    current_subject: str = Depends(get_current_subject),
):
    """Serve a dataset image. ``?thumb=<px>`` returns a cached downscaled JPEG (regenerated
    when the source is newer), used by the labeling grid to stay light."""
    from fastapi.responses import FileResponse

    folder = _resolve_dataset_folder(name)
    image_path = _safe_dataset_image_path(folder, filename)
    if not image_path.is_file():
        raise HTTPException(status_code = 404, detail = "Image not found.")
    if not thumb:
        return FileResponse(str(image_path))

    size = max(32, min(1024, int(thumb)))

    def make_thumb() -> Path:
        from PIL import Image

        from core.inference.mcp_images import flattened_rgb

        thumbs_dir = folder / _THUMBS_DIRNAME
        thumbs_dir.mkdir(exist_ok = True)
        # use the full filename because same-stem images would otherwise share a cache entry
        thumb_path = thumbs_dir / f"{image_path.name}_{size}_w.jpg"
        src_mtime = image_path.stat().st_mtime
        if thumb_path.is_file() and thumb_path.stat().st_mtime >= src_mtime:
            return thumb_path
        with Image.open(image_path) as im:
            im = flattened_rgb(im, background = (255, 255, 255))
            im.thumbnail((size, size), Image.LANCZOS)
            im.save(thumb_path, format = "JPEG", quality = 85)
        return thumb_path

    try:
        thumb_path = await asyncio.to_thread(make_thumb)
    except Exception as e:  # noqa: BLE001 -- fall back to the original on any decode failure
        logger.warning("Thumbnail generation failed for %s: %s", image_path, e)
        return FileResponse(str(image_path))
    return FileResponse(str(thumb_path), media_type = "image/jpeg")


@router.put(
    "/diffusion/dataset/{name}/caption/{filename}",
    response_model = DiffusionDatasetImageRecord,
)
async def set_diffusion_dataset_caption(
    name: str,
    filename: str,
    body: DiffusionCaptionUpdateRequest,
    current_subject: str = Depends(get_current_subject),
    _interlock: None = Depends(diffusion_dataset_interlock),
):
    """Write (or, when blank, clear) an image's ``.txt`` caption sidecar. Returns the
    updated image record."""
    _require_diffusion_dataset_mutable()
    folder = _resolve_dataset_folder(name)
    image_path = _safe_dataset_image_path(folder, filename)
    if not image_path.is_file():
        raise HTTPException(status_code = 404, detail = "Image not found.")
    caption = (body.caption or "").strip()
    if len(caption) > _MAX_CAPTION_CHARS:
        raise HTTPException(
            status_code = 400,
            detail = f"Caption too long (max {_MAX_CAPTION_CHARS} characters).",
        )

    def write() -> DiffusionDatasetImageRecord:
        sidecar = image_path.with_suffix(".txt")
        if caption:
            sidecar.write_text(caption, encoding = "utf-8")
            image_path.with_suffix(".caption").unlink(missing_ok = True)
            return _image_record(folder, image_path, _load_metadata_captions(folder))
        # Write an EMPTY sidecar (tombstone): unlinking would resurface the metadata caption.
        meta = _load_metadata_captions(folder)
        try:
            rel = image_path.relative_to(folder).as_posix()
        except ValueError:
            rel = image_path.name
        if image_path.name in meta or rel in meta:
            sidecar.write_text("", encoding = "utf-8")
        else:
            sidecar.unlink(missing_ok = True)
        image_path.with_suffix(".caption").unlink(missing_ok = True)
        return _image_record(folder, image_path, meta)

    return await asyncio.to_thread(write)


@router.delete("/diffusion/dataset/{name}/image/{filename}")
async def delete_diffusion_dataset_image(
    name: str,
    filename: str,
    current_subject: str = Depends(get_current_subject),
    _interlock: None = Depends(diffusion_dataset_interlock),
):
    """Remove an image, its caption sidecars, and any cached thumbnails."""
    _require_diffusion_dataset_mutable()
    folder = _resolve_dataset_folder(name)
    image_path = _safe_dataset_image_path(folder, filename)
    if not image_path.is_file():
        raise HTTPException(status_code = 404, detail = "Image not found.")

    def remove() -> dict:
        import glob as _glob

        image_path.unlink(missing_ok = True)
        # Sidecars key on stem; fold case only on case-folding filesystems or a survivor loses its caption.
        folds_case = _dataset_folder_is_case_insensitive(folder)

        def same_stem(p: Path) -> bool:
            return (
                p.stem.casefold() == image_path.stem.casefold()
                if folds_case
                else p.stem == image_path.stem
            )

        stem_still_used = any(
            p.is_file()
            and p != image_path
            and same_stem(p)
            # Clips share the stem-keyed sidecar with images; an image-only delete check strips clip captions.
            and p.suffix.lower() in _DIFFUSION_DATASET_MEDIA_EXTS
            for p in folder.iterdir()
        )
        if not stem_still_used:
            for ext in (".txt", ".caption"):
                image_path.with_suffix(ext).unlink(missing_ok = True)
        thumbs_dir = folder / _THUMBS_DIRNAME
        if thumbs_dir.is_dir():
            # Thumbs keyed on full filename; escape it so glob metacharacters cannot match siblings.
            for t in thumbs_dir.glob(f"{_glob.escape(image_path.name)}_*.jpg"):
                t.unlink(missing_ok = True)
        return {"deleted": image_path.name}

    return await asyncio.to_thread(remove)


# ``loader``: "hf_dataset" streams rows; "imagefolder_jsonl" snapshot-downloads *.jsonl captions.
_DATASET_EXAMPLES: list[dict] = [
    {
        "id": "dreambooth-dog",
        "label": "Dog (DreamBooth subject)",
        "repo": "diffusers/dog-example",
        "description": "5 photos of one dog. Teach a subject, then call it with the trigger.",
        "license": "Google, research and demos",
        "image_cap": 10,
        "suggested_trigger": "a photo of sks dog",
        "loader": "hf_dataset",
        "caption_column": None,
        "no_checks": False,
    },
    {
        "id": "tuxemon",
        "label": "Tuxemon (captioned style set)",
        "repo": "linoyts/Tuxemon",
        "description": "Captioned cartoon monster art. A style set, no trigger needed.",
        "license": "cc-by-sa-3.0",
        "image_cap": 60,
        "suggested_trigger": None,
        "loader": "hf_dataset",
        "caption_column": "prompt",
        "no_checks": True,
    },
    {
        "id": "tarot-1920",
        "label": "1920 Tarot (public domain style set)",
        "repo": "multimodalart/1920-raider-waite-tarot-public-domain",
        "description": "Captioned 1920 Raider-Waite tarot art. A permissive style set.",
        "license": "public domain",
        "image_cap": 60,
        "suggested_trigger": None,
        "loader": "imagefolder_jsonl",
        "caption_column": "text",
        "no_checks": True,
    },
    {
        "id": "smithsonian-butterflies",
        "label": "Smithsonian Butterflies",
        "repo": "huggan/smithsonian_butterflies_subset",
        "description": "100 butterfly photos. No captions, so use the trigger prompt.",
        "license": "CC0",
        "image_cap": 100,
        # Metadata columns are species names, not captions, so train as a subject set.
        "suggested_trigger": "a photo of a sks butterfly",
        "loader": "hf_dataset",
        "caption_column": None,
        "no_checks": False,
    },
    {
        "id": "pixel-nouns",
        "label": "Nouns (pixel avatars)",
        "repo": "m1guelpf/nouns",
        "description": "100 captioned pixel-art avatars. A style set, no trigger needed.",
        "license": "cc0-1.0",
        "image_cap": 100,
        "suggested_trigger": None,
        "loader": "hf_dataset",
        "caption_column": "text",
        "no_checks": False,
    },
]


def _example_by_id(example_id: str) -> dict:
    for entry in _DATASET_EXAMPLES:
        if entry["id"] == example_id:
            return entry
    raise HTTPException(status_code = 404, detail = f"Unknown example dataset '{example_id}'.")


@router.get("/diffusion/dataset-examples", response_model = DiffusionDatasetExamplesResponse)
async def list_diffusion_dataset_examples(current_subject: str = Depends(get_current_subject)):
    """List the curated example datasets available for one-click import."""
    return DiffusionDatasetExamplesResponse(
        examples = [
            DiffusionDatasetExample(
                id = e["id"],
                label = e["label"],
                repo = e["repo"],
                description = e["description"],
                license = e["license"],
                image_cap = e["image_cap"],
                suggested_trigger = e["suggested_trigger"],
            )
            for e in _DATASET_EXAMPLES
        ]
    )


def _detect_image_column(features) -> Optional[str]:
    try:
        from datasets import Image as HFImage
    except Exception:  # noqa: BLE001
        HFImage = None  # type: ignore[assignment]
    for col, feat in features.items():
        if HFImage is not None and isinstance(feat, HFImage):
            return col
        if type(feat).__name__ == "Image":
            return col
    return None


def _detect_image_column_from_row(row: dict) -> Optional[str]:
    """Image column picked from one materialized row, for a streamed dataset that arrives with no
    feature metadata to inspect."""
    try:
        from PIL.Image import Image as PILImage
    except Exception:  # noqa: BLE001 -- no Pillow -> the caller reports "no image column"
        return None
    for col, value in row.items():
        if isinstance(value, PILImage):
            return col
    return None


def _detect_caption_column(entry: dict, columns: list[str]) -> Optional[str]:
    """Pick the caption column: the entry's declared one if present, else a common name."""
    declared = entry.get("caption_column")
    if declared and declared in columns:
        return declared
    for cand in ("text", "prompt", "caption", "captions"):
        if cand in columns:
            return cand
    return None


def _materialize_hf_dataset(entry: dict, dest: Path, cap: int) -> int:
    """Stream rows from datasets.load_dataset into ``dest`` as numbered images + optional
    .txt sidecars. Returns the number of images written."""
    from datasets import load_dataset

    kwargs = {"split": "train"}
    if entry.get("no_checks"):
        kwargs["verification_mode"] = "no_checks"
    try:
        ds = load_dataset(entry["repo"], streaming = True, **kwargs)
        features = ds.features
    except Exception:  # noqa: BLE001 -- not streamable; the prepared load is the fallback
        ds = load_dataset(entry["repo"], **kwargs)
        features = ds.features
    # Streaming exposes features only after a row is read; resolve the image column from the first row.
    image_col = _detect_image_column(features) if features else None
    if image_col is None and features:
        raise HTTPException(
            status_code = 502,
            detail = f"'{entry['repo']}' has no image column to import.",
        )
    caption_col = _detect_caption_column(entry, list(features.keys())) if features else None
    written = 0
    for row in ds:
        if written >= cap:
            break
        if image_col is None:
            image_col = _detect_image_column_from_row(row)
            if image_col is None:
                raise HTTPException(
                    status_code = 502,
                    detail = f"'{entry['repo']}' has no image column to import.",
                )
            caption_col = _detect_caption_column(entry, list(row.keys()))
        img = row[image_col]
        if img is None:
            continue
        img = img.convert("RGB")
        stem = f"img_{written:04d}"
        img.save(dest / f"{stem}.png", format = "PNG")
        if caption_col:
            cap_text = row.get(caption_col)
            if cap_text:
                (dest / f"{stem}.txt").write_text(str(cap_text).strip(), encoding = "utf-8")
        written += 1
    return written


def _materialize_imagefolder_jsonl(entry: dict, dest: Path, cap: int) -> int:
    """Snapshot-download a dataset repo whose captions live in *.jsonl (file_name/text),
    then copy referenced images + write .txt sidecars. Returns images written."""
    import json
    import shutil

    from huggingface_hub import snapshot_download

    caption_col = entry.get("caption_column") or "text"
    snap = Path(
        snapshot_download(
            entry["repo"],
            repo_type = "dataset",
            allow_patterns = [
                "*.jsonl",
                "*.jpg",
                "*.jpeg",
                "*.png",
                "*.webp",
                "*.bmp",
                "**/*.jpg",
                "**/*.jpeg",
                "**/*.png",
                "**/*.webp",
                "**/*.bmp",
            ],
        )
    )
    # Map basename -> caption from every jsonl carrying file_name + caption column.
    captions: dict[str, str] = {}
    # read_text on a companion raises and fails the whole import.
    for jf in drop_appledouble_metadata(sorted(snap.rglob("*.jsonl"))):
        for line in jf.read_text(encoding = "utf-8").split("\n"):
            line = line.strip()
            if not line:
                continue
            try:
                row = json.loads(line)
            except json.JSONDecodeError:
                continue
            fn = row.get("file_name") or row.get("image") or row.get("file")
            value = row.get(caption_col)
            # A JSON null is "no caption", not the string "None".
            if fn and value is not None:
                # First writer wins over sorted manifests, for deterministic results.
                captions.setdefault(Path(str(fn)).name, str(value))
    # Copy images (those with a caption first, so a cap keeps captioned pairs).
    images = drop_appledouble_metadata(
        sorted(
            p
            for p in snap.rglob("*")
            if p.is_file() and p.suffix.lower() in _DIFFUSION_DATASET_IMAGE_EXTS
        )
    )
    images.sort(key = lambda p: (p.name not in captions, p.name))
    written = 0
    for src in images:
        if written >= cap:
            break
        stem = f"img_{written:04d}"
        shutil.copyfile(src, dest / f"{stem}{src.suffix.lower()}")
        cap_text = captions.get(src.name)
        if cap_text:
            (dest / f"{stem}.txt").write_text(cap_text.strip(), encoding = "utf-8")
        written += 1
    return written


@router.post("/diffusion/dataset/import-example", response_model = DiffusionDatasetImportResponse)
async def import_diffusion_dataset_example(
    body: DiffusionDatasetImportRequest,
    current_subject: str = Depends(get_current_subject),
    _interlock: None = Depends(diffusion_dataset_interlock),
):
    """Materialize a curated example dataset into an Unsloth dataset folder (images + .txt
    captions), ready to train. Idempotent: a folder that already holds images is returned
    as-is rather than re-downloaded."""
    _require_diffusion_dataset_mutable()
    entry = _example_by_id(body.id)
    folder = _resolve_dataset_folder(body.name or entry["id"], must_exist = False)

    def do_import() -> DiffusionDatasetImportResponse:
        folder.mkdir(parents = True, exist_ok = True)
        # Any trainable item makes this a no-op, so two dataset kinds never mix.
        summary = _diffusion_dataset_summary(folder)
        if summary.image_count > 0 or summary.clip_count > 0:
            return _import_response(entry, folder, imported = 0)
        # One import per folder: the training interlock COUNTS mutations rather than excluding them.
        lock = _dataset_import_lock(folder)
        if not lock.acquire(blocking = False):
            raise HTTPException(
                status_code = 409,
                detail = (
                    f"An import into '{folder.name}' is already running. Wait for it to finish, "
                    "then reload the dataset list."
                ),
            )
        try:
            return _do_import_locked(entry, folder)
        finally:
            lock.release()

    def _do_import_locked(entry: dict, folder: Path) -> DiffusionDatasetImportResponse:
        import os
        import shutil
        import tempfile

        imported = 0
        # Re-read under the lock: a winner may have promoted its staging dir meanwhile.
        existing = _diffusion_dataset_summary(folder)
        if existing.image_count == 0 and existing.clip_count == 0:
            cap = int(entry["image_cap"])
            # Stage in a hidden same-filesystem sibling so promotion is an atomic rename.
            staging = Path(tempfile.mkdtemp(dir = folder.parent, prefix = f".{folder.name}.import-"))
            # Parked, not deleted, so a failed promotion can restore them.
            rescue = Path(tempfile.mkdtemp(dir = folder.parent, prefix = f".{folder.name}.rescue-"))
            # (entry's new home, where it came from) for every pre-existing entry moved out of the folder.
            folded: list[tuple[Path, Path]] = []

            def restore_folded() -> None:
                """Undo the fold-in so a failed promotion leaves the dataset as it was."""
                folder.mkdir(parents = True, exist_ok = True)
                for moved, original in folded:
                    try:
                        if moved.exists() and not original.exists():
                            shutil.move(str(moved), str(original))
                    except OSError:
                        # Best effort: one unrestorable entry must not mask the original failure.
                        pass

            # Hold the datasets registry across the fetch: these loaders bypass managed downloads, so
            # without the claim a cache purge could delete the snapshot mid-copy.
            _import_registry = None
            _import_owner = object()
            try:
                from hub.utils.download_registry import get_datasets_registry
                _import_registry = get_datasets_registry()
            except Exception as exc:  # noqa: BLE001 - a broken registry must not kill an import
                logger.debug(f"Could not reach the datasets registry for the import: {exc}")
            if _import_registry is not None:
                granted, reason = _import_registry.claim_repository_owner(
                    entry["repo"], _import_owner
                )
                if not granted:
                    if reason == "deleting":
                        raise HTTPException(
                            status_code = 409,
                            detail = "A cache clear is running. Try the import again in a moment.",
                        )
                    _import_registry = None  # already busy with this repo; do not release it
            try:
                try:
                    if entry["loader"] == "imagefolder_jsonl":
                        imported = _materialize_imagefolder_jsonl(entry, staging, cap)
                    else:
                        imported = _materialize_hf_dataset(entry, staging, cap)
                except HTTPException:
                    raise
                except Exception as e:  # noqa: BLE001 -- surface a readable fetch/parse failure
                    raise HTTPException(
                        status_code = 502,
                        detail = f"Could not import '{entry['repo']}': {e}",
                    )
                if imported == 0:
                    raise HTTPException(
                        status_code = 502,
                        detail = f"No images found in '{entry['repo']}'.",
                    )
                # Promote staging as a UNIT via atomic rename; fold pre-existing files into staging first.
                try:
                    for p in sorted(folder.iterdir()):
                        # Same name in both: the imported file wins; park the old one in rescue.
                        dest = (rescue if (staging / p.name).exists() else staging) / p.name
                        shutil.move(str(p), str(dest))
                        folded.append((dest, p))
                    os.rmdir(folder)
                    os.replace(str(staging), str(folder))
                except (OSError, shutil.Error) as e:
                    # Folder entries now live only in staging/rescue, which the finally deletes.
                    restore_folded()
                    raise HTTPException(
                        status_code = 409,
                        detail = (
                            f"Could not update '{folder.name}' with the imported example "
                            f"({getattr(e, 'strerror', None) or e}). Nothing was written; try again."
                        ),
                    )
            finally:
                if _import_registry is not None:
                    try:
                        _import_registry.release_repository_owner(entry["repo"], _import_owner)
                    except Exception as exc:  # noqa: BLE001 - a held claim must not mask the error
                        logger.debug(f"Could not release the import claim: {exc}")
                shutil.rmtree(staging, ignore_errors = True)
                shutil.rmtree(rescue, ignore_errors = True)
        return _import_response(entry, folder, imported = imported)

    return await asyncio.to_thread(do_import)