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.

36.1 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

"""Job lifecycle endpoints for data recipe."""

from __future__ import annotations

from utils.account_context import (
    OWNER,
    AccountContext,
    bind_account,
    current_account,
    reset_account,
)
from core.training.account_jobs import account_event_stream, managed_account
import copy
import hashlib
import hmac
import secrets
import tempfile
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Annotated, Any, Optional
from urllib.parse import urlencode, urlparse

from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request

from auth.authentication import (
    allow_ambient_hf_token,
    authenticated_via_api_key,
    get_current_credential,
    request_admitted_without_credential,
    require_ui_session_for_local_commands,
    subject_for_header_or_query_token,
)
from auth.storage import CredentialRotated
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
from pydantic import ValidationError
from starlette.concurrency import run_in_threadpool

from core.data_recipe.export import (
    ExportFormat,
    RecipeDatasetExportError,
    build_dataset_download,
    download_filename,
    safe_filename_stem,
    write_jsonl_rows,
)
from core.data_recipe.huggingface import (
    RecipeDatasetPublishError,
    publish_recipe_dataset,
)
from core.data_recipe.jobs import get_job_manager
from core.data_recipe.service import (
    recipe_has_stdio_mcp,
    require_ui_session_for_host_env_credentials,
    validate_recipe_names,
)
from loggers import get_logger
from models.data_recipe import (
    JobCreateResponse,
    PublishDatasetRequest,
    PublishDatasetResponse,
    RecipePayload,
)
from utils.client_ip import client_ip
from utils.hf_endpoint import client_reachable_endpoint, get_hf_endpoint
from utils.host_policy import dial_host, self_request_host
from utils.utils import safe_error_detail, safe_curated_detail, log_and_http_error

logger = get_logger(__name__)
router = APIRouter()

# Fetched without auth, so the link carries an HMAC capability, not the session token (download history keeps it); TTL outlasts save dialog.
_DOWNLOAD_LINK_TTL = 30 * 60
_DOWNLOAD_LINK_SECRET = secrets.token_bytes(32)


def _download_link_payload(
    *,
    job_id: str,
    export_format: str,
    artifact_path: str | None,
    filename: str | None,
    account_id: str,
) -> str:
    # Sign every export param so a holder cannot swap artifact_path, and the account (selects roots); length-prefix: a separator join is not injective.
    parts = [account_id, job_id, export_format, artifact_path or "", filename or ""]
    return "\x1f".join(f"{len(part)}:{part}" for part in parts)


def _sign_download_link(**parts: Any) -> str:
    account = current_account()
    account_id = "" if account.is_owner else account.account_id
    expires_at = int(time.time()) + _DOWNLOAD_LINK_TTL
    payload = f"{_download_link_payload(account_id = account_id, **parts)}\x1f{expires_at}"
    signature = hmac.new(_DOWNLOAD_LINK_SECRET, payload.encode(), hashlib.sha256).hexdigest()
    return f"{expires_at}.{account_id}.{signature}"


def _download_link_account(token: str, **parts: Any) -> AccountContext | None:
    """Empty account id in the link means the owner; None once it is invalid or deactivated."""
    try:
        expires_at, account_id, signature = token.split(".", 2)
    except ValueError:
        return None
    if "." in signature:
        return None
    # Compare bytes: compare_digest raises TypeError on non-ASCII str (500 instead of 401).
    try:
        provided = signature.encode("ascii")
    except UnicodeEncodeError:
        return None
    payload = f"{_download_link_payload(account_id = account_id, **parts)}\x1f{expires_at}"
    expected = hmac.new(_DOWNLOAD_LINK_SECRET, payload.encode(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(provided, expected.encode("ascii")):
        return None
    try:
        if int(expires_at) < int(time.time()):
            return None
    except ValueError:
        return None
    if not account_id:
        return OWNER
    from auth.storage import get_account_by_id

    # None once the account is deactivated or deleted: the link dies with it.
    account = get_account_by_id(account_id)
    return None if account is None or account.is_owner else account


async def _authorize_dataset_download(
    request: Request,
    job_id: str,
    export_format: ExportFormat = Query(default = "jsonl", alias = "format"),
    artifact_path: str | None = Query(default = None),
    filename: str | None = Query(default = None),
    token: str | None = Query(default = None),
):
    """A signed link for exactly this export, or the ordinary Authorization header for an API
    client. The session bearer is deliberately not read from the query."""
    # Threadpool: sync SQLite with 5s busy timeout would stall the event loop.
    account = (
        await run_in_threadpool(
            _download_link_account,
            token,
            job_id = job_id,
            export_format = export_format,
            artifact_path = artifact_path,
            filename = filename,
        )
        if token
        else None
    )
    if account is not None:
        # No auth dependency here, so bind the account or reads resolve under the wrong root.
        marker = bind_account(account)
        try:
            yield
        finally:
            reset_account(marker)
        return
    await subject_for_header_or_query_token(request, None)
    yield


download_router = APIRouter(dependencies = [Depends(_authorize_dataset_download)])

# Keepalive cadence, well inside the ~100s a quick tunnel allows between body bytes.
_KEEPALIVE_EVERY_S = 15.0

# Only UI sessions may supply stdio commands, since this host would run them; Annotated so direct calls get False.
ViaApiKey = Annotated[bool, Depends(authenticated_via_api_key)]


def _resolve_local_v1_endpoint(request: Request) -> str:
    """The /v1 URL of this process's own backend, at the address it is bound to. Port order:
    ``server_port`` (survives proxies/tunnels), the request scope, ``base_url``."""
    from utils.studio_tls import loopback_http_port

    loopback_port = loopback_http_port(request.app.state)
    if loopback_port is not None:
        return f"http://127.0.0.1:{loopback_port}/v1"
    server = request.scope.get("server")
    port: Any = getattr(request.app.state, "server_port", None)
    if not isinstance(port, int) or port <= 0:
        if (
            isinstance(server, tuple)
            and len(server) >= 2
            and isinstance(server[1], int)
            and server[1] > 0
        ):
            port = server[1]
        else:
            parsed = urlparse(str(request.base_url))
            port = parsed.port if parsed.port is not None else 8888
    host = dial_host(self_request_host(request.app.state, server))
    return f"http://{host}:{int(port)}/v1"


def _used_llm_model_aliases(recipe: dict[str, Any]) -> set[str]:
    """Return model_aliases actually referenced by an LLM column. Narrows the "Chat model loaded" gate
    so orphan model_config nodes don't block unrelated runs. The ``llm-`` prefix matches
    ``service.py::_recipe_has_llm_columns`` and covers all LLM column types."""
    aliases: set[str] = set()
    for column in recipe.get("columns", []):
        if not isinstance(column, dict):
            continue
        column_type = column.get("column_type")
        if not isinstance(column_type, str) or not column_type.startswith("llm-"):
            continue
        alias = column.get("model_alias")
        if isinstance(alias, str) and alias:
            aliases.add(alias)
    return aliases


def _used_local_model_selections(
    recipe: dict[str, Any], local_provider_names: set[str]
) -> dict[tuple[str, str], list[str]]:
    used_aliases = _used_llm_model_aliases(recipe)
    selections: dict[tuple[str, str], list[str]] = {}
    for mc in recipe.get("model_configs", []):
        if not isinstance(mc, dict):
            continue
        alias = mc.get("alias")
        if not isinstance(alias, str) or alias not in used_aliases:
            continue
        provider = mc.get("provider")
        if not isinstance(provider, str) or provider not in local_provider_names:
            continue
        model = mc.get("model")
        target = model.strip() if isinstance(model, str) else ""
        if not target or target.lower() == "local":
            continue
        variant = mc.get("gguf_variant")
        gguf_variant = variant.strip() if isinstance(variant, str) else ""
        selections.setdefault((target, gguf_variant), []).append(alias)
    return selections


def _single_used_local_model_selection(
    recipe: dict[str, Any], local_provider_names: set[str]
) -> tuple[str, str] | None:
    selections = _used_local_model_selections(recipe, local_provider_names)
    if not selections:
        return None
    if len(selections) > 1:
        aliases = ", ".join(alias for values in selections.values() for alias in values)
        raise ValueError(
            "Recipes supports one active local model per run. "
            f"Select the same local model and GGUF variant for: {aliases}."
        )
    return next(iter(selections))


def _local_chat_serves_gguf() -> bool:
    from routes.inference import get_llama_cpp_backend
    return bool(get_llama_cpp_backend().is_loaded)


def _loaded_local_model_identity() -> tuple[bool, str, str]:
    from routes.inference import get_llama_cpp_backend
    from core.inference import get_inference_backend

    llama = get_llama_cpp_backend()
    if llama.is_loaded:
        model = str(getattr(llama, "model_identifier", "") or "").strip()
        variant = str(getattr(llama, "hf_variant", "") or "").strip()
        return True, model, variant

    backend = get_inference_backend()
    active_model = str(getattr(backend, "active_model_name", "") or "").strip()
    if active_model:
        return True, active_model, ""
    return False, "", ""


def _ensure_selected_local_model_loaded(
    recipe: dict[str, Any], local_provider_names: set[str]
) -> None:
    model_loaded, active_model, active_variant = _loaded_local_model_identity()
    if not model_loaded:
        raise ValueError("No model loaded in Chat. Load a model first, then run the recipe.")

    selection = _single_used_local_model_selection(recipe, local_provider_names)
    if selection is None:
        return

    target, gguf_variant = selection
    variant_matches = not gguf_variant or active_variant == gguf_variant
    if active_model.lower() != target.lower() or not variant_matches:
        selected = f"{target} ({gguf_variant})" if gguf_variant else target
        active = f"{active_model} ({active_variant})" if active_variant else active_model
        raise ValueError(
            "Selected local model is not loaded. "
            f"Selected {selected}; active {active or 'none'}. "
            "Load the selected model again, then run the recipe."
        )


def _inject_local_structured_response_format(
    recipe: dict[str, Any], local_provider_names: set[str]
) -> None:
    """Clone each llm-structured column model config so llama-server grammar-constrains only it; prompt-only JSON breaks small GGUFs."""
    columns = recipe.get("columns")
    model_configs = recipe.get("model_configs")
    if not isinstance(columns, list) or not isinstance(model_configs, list):
        return

    # alias -> model_config (only configs referencing a local provider qualify).
    alias_to_local_mc: dict[str, dict[str, Any]] = {}
    for mc in model_configs:
        if not isinstance(mc, dict):
            continue
        if mc.get("provider") in local_provider_names and isinstance(mc.get("alias"), str):
            alias_to_local_mc[mc["alias"]] = mc

    if not alias_to_local_mc:
        return

    # Clone per (alias, column) so response_format doesn't leak to other columns.
    seen_clone_aliases: set[str] = {
        mc.get("alias") for mc in model_configs if isinstance(mc.get("alias"), str)
    }
    new_configs: list[dict[str, Any]] = []
    for column in columns:
        if not isinstance(column, dict):
            continue
        if column.get("column_type") != "llm-structured":
            continue
        alias = column.get("model_alias")
        if not isinstance(alias, str) or alias not in alias_to_local_mc:
            continue
        output_format = column.get("output_format")
        if not isinstance(output_format, dict) or not output_format:
            continue
        base_mc = alias_to_local_mc[alias]
        column_name = column.get("name") or "structured"
        clone_alias_base = f"{alias}__{column_name}_structured"
        clone_alias = clone_alias_base
        counter = 1
        while clone_alias in seen_clone_aliases:
            counter += 1
            clone_alias = f"{clone_alias_base}_{counter}"
        seen_clone_aliases.add(clone_alias)

        clone = copy.deepcopy(base_mc)
        clone["alias"] = clone_alias
        params = clone.get("inference_parameters")
        if not isinstance(params, dict):
            params = {}
            clone["inference_parameters"] = params
        # BaseInferenceParams forbids extras, so response_format rides extra_body; llama-server reads the schema directly under it, not in json_schema.
        extra_body = params.get("extra_body")
        if not isinstance(extra_body, dict):
            extra_body = {}
        extra_body["response_format"] = {
            "type": "json_schema",
            "schema": output_format,
        }
        # Re-enables the ```json fence data_designer's structured-output parser expects.
        extra_body["_unsloth_guided_fence"] = True
        params["extra_body"] = extra_body
        new_configs.append(clone)
        column["model_alias"] = clone_alias

    if new_configs:
        model_configs.extend(new_configs)


def _inject_local_providers(
    recipe: dict[str, Any],
    request: Request,
    expect_gen: Optional[str] = None,
) -> Optional[int]:
    """Points is_local providers at this server and mints a short-lived sk-unsloth-* key; returns
    its row id (caller revokes on completion) or None if no local provider."""
    providers = recipe.get("model_providers")
    if not providers:
        return None

    # Strict `is True` so malformed values (1, "true") don't trigger the loopback rewrite.
    local_indices: list[int] = []
    for i, provider in enumerate(providers):
        if not isinstance(provider, dict):
            continue
        is_local = provider.pop("is_local", None)
        if is_local is True:
            local_indices.append(i)

    if not local_indices:
        return None

    endpoint = _resolve_local_v1_endpoint(request)

    # Orphan model_config nodes never reach /v1, so they must not block runs.
    local_names = {providers[i].get("name") for i in local_indices if providers[i].get("name")}
    used_aliases = _used_llm_model_aliases(recipe)
    referenced_providers = {
        mc.get("provider")
        for mc in recipe.get("model_configs", [])
        if (isinstance(mc, dict) and mc.get("provider") and mc.get("alias") in used_aliases)
    }

    token = ""
    internal_key_id: Optional[int] = None
    if local_names & referenced_providers:
        # Point-in-time check; /v1 still returns a clear 400 if the model changes later.
        _ensure_selected_local_model_loaded(recipe, local_names)

        from auth import storage

        # Internal key, hidden from the user's list; revoked when the job ends.
        expires_at = (datetime.now(timezone.utc) + timedelta(hours = 24)).isoformat()
        token, row = storage.create_api_key(
            username = current_account().username,
            name = "data-recipe workflow",
            expires_at = expires_at,
            internal = True,
            expect_gen = expect_gen,
        )
        internal_key_id = int(row["id"])

    # A provider flipped external -> local must not carry stale headers/auth into /v1.
    for i in local_indices:
        providers[i]["endpoint"] = endpoint
        providers[i]["api_key"] = token
        providers[i]["provider_type"] = "openai"
        providers[i].pop("api_key_env", None)
        providers[i].pop("extra_headers", None)
        providers[i].pop("extra_body", None)

    # llama-server's /v1/models ids can differ from the selection, so skip the health check.
    for mc in recipe.get("model_configs", []):
        if not isinstance(mc, dict):
            continue
        if mc.get("provider") in local_names:
            mc["skip_health_check"] = True
            # Disable thinking: <think> doubles tokens and breaks data_designer's json-fence regex.
            params = mc.get("inference_parameters")
            if not isinstance(params, dict):
                params = {}
                mc["inference_parameters"] = params
            extra_body = params.get("extra_body")
            if not isinstance(extra_body, dict):
                extra_body = {}
            tpl_kwargs = extra_body.get("chat_template_kwargs")
            if not isinstance(tpl_kwargs, dict):
                tpl_kwargs = {}
            tpl_kwargs["enable_thinking"] = False
            extra_body["chat_template_kwargs"] = tpl_kwargs
            params["extra_body"] = extra_body

    # Only llama.cpp has a grammar engine; other backends refuse response_format.
    if _local_chat_serves_gguf():
        _inject_local_structured_response_format(recipe, local_names)

    return internal_key_id


def _normalize_run_name(value: Any) -> str | None:
    if value is None:
        return None
    if not isinstance(value, str):
        raise HTTPException(status_code = 400, detail = "invalid run_name: must be a string")
    trimmed = value.strip()
    if not trimmed:
        return None
    return trimmed[:120]


def _resolve_seed_endpoint(recipe: dict[str, Any]) -> None:
    """Seed fetch runs in this process: no client endpoint means HF_ENDPOINT here; typed endpoints
    stay, but managed accounts may only use this server endpoint, since redirects could reach
    loopback, LAN or metadata."""
    seed_config = recipe.get("seed_config")
    if not isinstance(seed_config, dict):
        return
    source = seed_config.get("source")
    if not isinstance(source, dict) or source.get("seed_type") != "hf":
        return
    typed = str(source.get("endpoint") or "").strip()
    if not typed:
        source["endpoint"] = get_hf_endpoint()
    elif typed.rstrip("/") != get_hf_endpoint().rstrip("/") and managed_account():
        raise HTTPException(
            status_code = 403,
            detail = "Managed accounts use this server's Hugging Face endpoint; leave the seed endpoint blank.",
        )


@router.post("/jobs", response_class = JSONResponse, response_model = JobCreateResponse)
def create_job(
    payload: RecipePayload,
    request: Request,
    credential: tuple = Depends(get_current_credential),
    via_api_key: ViaApiKey = False,
):
    recipe = payload.recipe
    if not recipe.get("columns"):
        raise HTTPException(status_code = 400, detail = "Recipe must include columns.")
    try:
        validate_recipe_names(recipe)
    except ValueError as exc:
        raise HTTPException(status_code = 400, detail = str(exc)) from exc
    if recipe_has_stdio_mcp(recipe):
        require_ui_session_for_local_commands(via_api_key)
    require_ui_session_for_host_env_credentials(recipe, via_api_key)

    run: dict[str, Any] = payload.run or {}
    run.pop("artifact_path", None)
    run.pop("dataset_name", None)
    execution_type = str(run.get("execution_type") or "full").strip().lower()
    if execution_type not in {"preview", "full"}:
        raise HTTPException(
            status_code = 400,
            detail = "invalid execution_type: must be 'preview' or 'full'",
        )
    run["execution_type"] = execution_type
    run["run_name"] = _normalize_run_name(run.get("run_name"))
    run_config_raw = run.get("run_config")
    if run_config_raw is not None:
        try:
            from data_designer.config.run_config import RunConfig
            RunConfig.model_validate(run_config_raw)
        except (ImportError, ValidationError, TypeError, ValueError) as exc:
            raise log_and_http_error(
                exc,
                400,
                "invalid run_config",
                event = "data_recipe.jobs.run_config_invalid",
                log = logger,
            ) from exc

    _resolve_seed_endpoint(recipe)

    try:
        internal_api_key_id = _inject_local_providers(recipe, request, credential[1])
    except CredentialRotated as exc:
        # A password reset revoked the workflow key; answer 401, not 500.
        raise HTTPException(status_code = 401, detail = "Invalid or expired token") from exc
    except ValueError as exc:
        raise log_and_http_error(
            exc,
            400,
            safe_curated_detail(exc),
            event = "data_recipe.jobs.inject_local_providers_failed",
            log = logger,
        ) from exc

    # One try over both so a failure can't leave a 24h key alive.
    try:
        mgr = get_job_manager()
        job_id = mgr.start(
            recipe = recipe,
            run = run,
            internal_api_key_id = internal_api_key_id,
        )
    except RuntimeError as exc:
        if internal_api_key_id is not None:
            _revoke_internal_api_key_safe(internal_api_key_id)
        raise log_and_http_error(
            exc,
            409,
            safe_curated_detail(exc),
            event = "data_recipe.jobs.start_conflict",
            log = logger,
        ) from exc
    except ValueError as exc:
        if internal_api_key_id is not None:
            _revoke_internal_api_key_safe(internal_api_key_id)
        raise log_and_http_error(
            exc,
            400,
            safe_curated_detail(exc),
            event = "data_recipe.jobs.start_failed",
            log = logger,
        ) from exc
    except Exception:
        if internal_api_key_id is not None:
            _revoke_internal_api_key_safe(internal_api_key_id)
        raise

    return {"job_id": job_id}


def _revoke_internal_api_key_safe(key_id: int) -> None:
    """Best-effort revoke of a workflow-minted key; never mask the caller's error."""
    try:
        from auth import storage
        storage.revoke_internal_api_key(key_id)
    except Exception:
        pass


@router.get("/jobs/{job_id}/status")
def job_status(job_id: str):
    mgr = get_job_manager()
    state = mgr.get_status(job_id)
    if state is None:
        raise HTTPException(status_code = 404, detail = "job not found")
    return state


@router.get("/jobs/current")
def current_job():
    mgr = get_job_manager()
    state = mgr.get_current_status()
    if state is None:
        raise HTTPException(status_code = 404, detail = "no job")
    return state


@router.post("/jobs/{job_id}/cancel")
def cancel_job(job_id: str):
    mgr = get_job_manager()
    ok = mgr.cancel(job_id)
    if not ok:
        raise HTTPException(status_code = 404, detail = "job not found")
    return mgr.get_status(job_id)


@router.get("/jobs/{job_id}/analysis")
def job_analysis(job_id: str):
    mgr = get_job_manager()
    analysis = mgr.get_analysis(job_id)
    if analysis is None:
        raise HTTPException(status_code = 404, detail = "analysis not ready")
    return analysis


@router.get("/jobs/{job_id}/dataset")
def job_dataset(
    job_id: str,
    limit: int = Query(default = 20, ge = 1, le = 500),
    offset: int = Query(default = 0, ge = 0),
):
    mgr = get_job_manager()
    result = mgr.get_dataset(job_id, limit = limit, offset = offset)
    if result is None:
        raise HTTPException(status_code = 404, detail = "dataset not ready")
    if "error" in result:
        raise HTTPException(status_code = 422, detail = result["error"])
    return {
        "dataset": result["dataset"],
        "total": result["total"],
        "limit": limit,
        "offset": offset,
    }


def _content_disposition_attachment(filename: str) -> str:
    ascii_name = "".join(
        ch if 32 <= ord(ch) < 127 and ch not in {'"', "\\"} else "_" for ch in filename
    )
    if not ascii_name.strip("_"):
        ascii_name = "dataset.jsonl"
    from urllib.parse import quote

    return f"attachment; filename=\"{ascii_name}\"; filename*=UTF-8''{quote(filename)}"


_IN_MEMORY_DOWNLOAD_PAGE_SIZE = 10_000


def _build_in_memory_job_dataset_download(
    mgr, job_id: str, *, filename_stem: str
) -> tuple[Path, str, str]:
    tmp = tempfile.NamedTemporaryFile(delete = False, suffix = ".jsonl")
    tmp.close()
    jsonl_path = Path(tmp.name)
    offset = 0
    total: int | None = None
    # Nothing has registered the temp file for cleanup yet, so an early return has to unlink it.
    try:
        with jsonl_path.open("w", encoding = "utf-8") as handle:
            while True:
                result = mgr.get_dataset(
                    job_id,
                    limit = _IN_MEMORY_DOWNLOAD_PAGE_SIZE,
                    offset = offset,
                )
                if result is None:
                    raise HTTPException(status_code = 404, detail = "dataset not ready")
                if "error" in result:
                    raise HTTPException(status_code = 422, detail = result["error"])
                rows = result.get("dataset")
                if not isinstance(rows, list):
                    raise HTTPException(status_code = 404, detail = "dataset not ready")
                if total is None:
                    total_value = result.get("total")
                    total = int(total_value) if isinstance(total_value, int) else len(rows)
                if not rows:
                    break
                write_jsonl_rows(handle, rows)
                offset += len(rows)
                if offset >= total:
                    break
        if offset == 0:
            raise HTTPException(status_code = 404, detail = "dataset not ready")
    except BaseException:
        jsonl_path.unlink(missing_ok = True)
        raise
    stem = safe_filename_stem(filename_stem.strip() or job_id)
    return jsonl_path, "application/x-ndjson", f"{stem}.jsonl"


def _resolve_download_artifact_path(*, job_id: str, artifact_path: str | None) -> str | None:
    resolved = (
        artifact_path.strip() if isinstance(artifact_path, str) and artifact_path.strip() else None
    )
    mgr = get_job_manager()
    status = mgr.get_status(job_id)
    if status is not None:
        if status.get("status") != "completed":
            raise HTTPException(
                status_code = 409,
                detail = "Only completed runs can be downloaded.",
            )
        status_artifact = status.get("artifact_path")
        if isinstance(status_artifact, str) and status_artifact.strip():
            resolved = status_artifact.strip()
    return resolved


@router.get("/jobs/{job_id}/download-url")
def create_job_dataset_download_url(
    job_id: str,
    export_format: ExportFormat = Query(default = "jsonl", alias = "format"),
    artifact_path: str | None = Query(default = None),
    filename: str | None = Query(default = None),
    no_credential: Annotated[bool, Depends(request_admitted_without_credential)] = False,
):
    """Mint the signed link the browser or the native downloader then fetches.

    Bearer-gated like the rest of the package. It settles here whether the run can be exported at
    all, and under what name, so a failure lands in the UI instead of after the save dialog has
    opened. The URL is relative, so it survives whatever proxy the page itself came through."""
    if no_credential:
        # The capability outlives the setting that admitted this caller. As the video links do.
        raise HTTPException(
            status_code = 403,
            detail = "Dataset download links can only be created from the Unsloth UI or with an API key.",
        )
    resolved = _resolve_download_artifact_path(job_id = job_id, artifact_path = artifact_path)
    stem = safe_filename_stem(
        filename.strip() if isinstance(filename, str) and filename.strip() else job_id
    )
    if resolved:
        try:
            name = download_filename(artifact_path = resolved, export_format = export_format, stem = stem)
        except RecipeDatasetExportError as exc:
            raise log_and_http_error(
                exc,
                400,
                safe_curated_detail(exc),
                event = "data_recipe.jobs.download_url_failed",
                log = logger,
            ) from exc
    else:
        if export_format == "parquet":
            raise HTTPException(
                status_code = 400,
                detail = "Parquet download requires persisted recipe artifacts.",
            )
        # An in-memory preview lives only while its job is current: ask before the chooser opens.
        if get_job_manager().get_dataset(job_id, limit = 1, offset = 0) is None:
            raise HTTPException(status_code = 404, detail = "dataset not ready")
        name = f"{stem}.jsonl"

    token = _sign_download_link(
        job_id = job_id,
        export_format = export_format,
        artifact_path = artifact_path,
        filename = filename,
    )
    query = {"format": export_format, "token": token}
    if artifact_path:
        query["artifact_path"] = artifact_path
    if filename:
        query["filename"] = filename
    # Relative to this router: the frontend's data-recipe base is configurable.
    return {"path": f"/jobs/{job_id}/download?{urlencode(query)}", "filename": name}


@download_router.get("/jobs/{job_id}/download")
def download_job_dataset(
    job_id: str,
    background_tasks: BackgroundTasks,
    export_format: ExportFormat = Query(default = "jsonl", alias = "format"),
    artifact_path: str | None = Query(default = None),
    filename: str | None = Query(default = None),
):
    resolved_artifact = _resolve_download_artifact_path(
        job_id = job_id,
        artifact_path = artifact_path,
    )
    filename_stem = filename.strip() if isinstance(filename, str) and filename.strip() else job_id

    try:
        if resolved_artifact:
            if export_format == "parquet":
                file_path, media_type, download_name = build_dataset_download(
                    artifact_path = resolved_artifact,
                    export_format = "parquet",
                    filename_stem = filename_stem,
                )
            else:
                file_path, media_type, download_name = build_dataset_download(
                    artifact_path = resolved_artifact,
                    export_format = "jsonl",
                    filename_stem = filename_stem,
                )
        else:
            if export_format == "parquet":
                raise HTTPException(
                    status_code = 400,
                    detail = "Parquet download requires persisted recipe artifacts.",
                )
            mgr = get_job_manager()
            file_path, media_type, download_name = _build_in_memory_job_dataset_download(
                mgr,
                job_id,
                filename_stem = filename_stem,
            )
    except RecipeDatasetExportError as exc:
        raise log_and_http_error(
            exc,
            400,
            safe_curated_detail(exc),
            event = "data_recipe.jobs.download_failed",
            log = logger,
        ) from exc
    except HTTPException:
        raise
    except Exception as exc:
        raise log_and_http_error(
            exc,
            500,
            safe_error_detail(exc),
            event = "data_recipe.jobs.download_error",
            log = logger,
        ) from exc

    background_tasks.add_task(file_path.unlink, missing_ok = True)
    return FileResponse(
        file_path,
        media_type = media_type,
        filename = download_name,
        headers = {"Content-Disposition": _content_disposition_attachment(download_name)},
    )


@router.post(
    "/jobs/{job_id}/publish",
    response_class = JSONResponse,
    response_model = PublishDatasetResponse,
)
def publish_job_dataset(
    request: Request,
    job_id: str,
    payload: PublishDatasetRequest,
    allow_ambient: bool = Depends(allow_ambient_hf_token),
):
    repo_id = payload.repo_id.strip()
    description = payload.description.strip()
    hf_token = payload.hf_token.strip() if isinstance(payload.hf_token, str) else None
    hf_token = hf_token or None
    # publish_recipe_dataset hands this to the Hub client, so None publishes as the host.
    if hf_token is None and not allow_ambient:
        raise HTTPException(
            status_code = 400,
            detail = "Hugging Face token is required to publish datasets when authenticated via API key.",
        )
    artifact_path = (
        payload.artifact_path.strip() if isinstance(payload.artifact_path, str) else None
    )

    if not repo_id:
        raise HTTPException(status_code = 400, detail = "repo_id is required")
    if not description:
        raise HTTPException(status_code = 400, detail = "description is required")

    mgr = get_job_manager()
    status = mgr.get_status(job_id)
    if status is not None:
        if status.get("status") != "completed" or status.get("execution_type") != "full":
            raise HTTPException(
                status_code = 409,
                detail = "Only completed full runs can be published.",
            )
        status_artifact = status.get("artifact_path")
        if isinstance(status_artifact, str) and status_artifact.strip():
            artifact_path = status_artifact.strip()

    if not artifact_path:
        raise HTTPException(
            status_code = 400,
            detail = "This execution does not have publishable dataset artifacts.",
        )

    try:
        url = publish_recipe_dataset(
            artifact_path = artifact_path,
            repo_id = repo_id,
            description = description,
            hf_token = hf_token or None,
            private = payload.private,
            # client_ip: behind the tunnel the socket peer is cloudflared.
            link_endpoint = client_reachable_endpoint(client_ip(request)),
        )
    except RecipeDatasetPublishError as exc:
        raise log_and_http_error(
            exc,
            400,
            safe_curated_detail(exc),
            event = "data_recipe.jobs.publish_failed",
            log = logger,
        ) from exc
    except Exception as exc:
        raise log_and_http_error(
            exc,
            500,
            safe_error_detail(exc),
            event = "data_recipe.jobs.publish_error",
            log = logger,
        ) from exc

    return {
        "success": True,
        "url": url,
        "message": f"Published dataset to {repo_id}.",
    }


# POST too: quick tunnels hold a streamed GET until it closes. The hidden GET keeps old clients.
@router.post("/jobs/{job_id}/events")
@router.get("/jobs/{job_id}/events", include_in_schema = False)
async def job_events(request: Request, job_id: str):
    mgr = get_job_manager()
    last_id = request.headers.get("last-event-id")
    after_seq: int | None = None
    if last_id:
        try:
            after_seq = int(str(last_id).strip())
        except (TypeError, ValueError):
            after_seq = None

    after_q = request.query_params.get("after")
    if after_q:
        try:
            after_seq = int(str(after_q).strip())
        except (TypeError, ValueError):
            pass

    sub = mgr.subscribe(job_id, after_seq = after_seq)
    if sub is None:
        raise HTTPException(status_code = 404, detail = "job not found")

    async def gen():
        try:
            last_sent = time.monotonic()
            for event in sub.replay:
                yield sub.format_sse(event)

            while True:
                if await request.is_disconnected():
                    break
                event = await sub.next_event(timeout_sec = 1.0)
                if event is None:
                    # A quiet job would otherwise go silent for minutes and take a tunnel 524.
                    if time.monotonic() - last_sent >= _KEEPALIVE_EVERY_S:
                        last_sent = time.monotonic()
                        yield ": keepalive\n\n"
                    continue
                last_sent = time.monotonic()
                yield sub.format_sse(event)
        finally:
            mgr.unsubscribe(sub)

    return StreamingResponse(
        account_event_stream(mgr, gen()),
        media_type = "text/event-stream",
        headers = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
    )