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.

15.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

"""Pinned STT downloads write no refs/main, and a cancelled run must not hold the shared repository."""

import subprocess
import sys
import threading
import time
from pathlib import Path
from types import SimpleNamespace

import pytest

from core.inference import stt_download_worker as worker_mod
from core.inference import stt_audiocpp_sidecar as audiocpp_mod
from core.inference import stt_ggml_sidecar as ggml_mod
from core.inference import stt_mtmd_sidecar as mtmd_mod
from core.inference import stt_sidecar as snapshot_mod


class _FakeMeta:
    """One Hub file's metadata, pinned to an immutable commit."""

    commit_hash = "a" * 40
    etag = "etag"
    size = 1


class _FakeInfo:
    """One repo's metadata, pinned to an immutable commit."""

    sha = "a" * 40


def _write_snapshot(hub_cache: Path, repo: str, revision: str, filename: str) -> Path:
    """Lay out one finished pinned download: a blob plus its snapshot entry."""
    repo_cache = hub_cache / f"models--{repo.replace('/', '--')}"
    blob = repo_cache / "blobs" / "etag"
    blob.parent.mkdir(parents = True, exist_ok = True)
    blob.write_bytes(b"weights")
    entry = repo_cache / "snapshots" / revision / filename
    entry.parent.mkdir(parents = True, exist_ok = True)
    entry.write_bytes(b"weights")
    return entry


def test_a_lost_revision_record_still_finds_the_downloaded_model(tmp_path, monkeypatch):
    """Pinned downloads skip refs/main and can lose the record; the snapshot is the fallback."""
    revision = "a" * 40
    repo = ggml_mod.GGML_STT_REPOS["tiny"]
    _write_snapshot(tmp_path, repo, revision, ggml_mod.GGML_STT_MODELS["tiny"])
    monkeypatch.setattr(ggml_mod, "_read_revision_record", lambda repo_id: None)
    recorded = []
    monkeypatch.setattr(
        ggml_mod, "_write_revision_record", lambda repo_id, rev: recorded.append((repo_id, rev))
    )

    assert snapshot_mod._fallback_revisions(repo, hub_cache = tmp_path) == [revision]
    assert ggml_mod._cached_model_path("tiny", hub_cache = tmp_path) is not None
    assert recorded == [(repo, revision)], "the record was not rebuilt from the cache"


def test_fallback_revisions_prefers_refs_main_and_skips_junk(tmp_path):
    """refs/main first when it exists, and only 40-hex snapshot dirs qualify."""
    repo = "owner/repo"
    repo_cache = tmp_path / "models--owner--repo"
    (repo_cache / "snapshots" / ("b" * 40)).mkdir(parents = True)
    (repo_cache / "snapshots" / "not-a-sha").mkdir(parents = True)
    (repo_cache / "refs").mkdir(parents = True)
    (repo_cache / "refs" / "main").write_text("c" * 40, encoding = "utf-8")

    assert snapshot_mod._fallback_revisions(repo, hub_cache = tmp_path) == ["c" * 40, "b" * 40]


@pytest.mark.parametrize(
    "module, state_factory, model_id",
    [
        (snapshot_mod, snapshot_mod._SnapshotDownloadState, "unsloth/whisper-tiny"),
        (ggml_mod, ggml_mod._GgmlDownloadState, "tiny"),
        (mtmd_mod, mtmd_mod._MtmdDownloadState, "qwen3-asr-0.6b"),
    ],
)
def test_a_cancel_during_metadata_leaves_the_shared_cache_alone(
    module, state_factory, model_id, monkeypatch, tmp_path
):
    """A cancel during metadata resolution must not claim the repository or purge the cache."""
    claims, prepares, spawns = [], [], []
    # Stub the Hub call: offline, it fails in _run's handler before the guard, passing vacuously.
    import huggingface_hub

    monkeypatch.setattr(huggingface_hub, "get_hf_file_metadata", lambda *a, **k: _FakeMeta())
    monkeypatch.setattr(
        huggingface_hub,
        "HfApi",
        lambda *a, **k: SimpleNamespace(model_info = lambda *a, **k: _FakeInfo()),
    )
    monkeypatch.setattr(
        module, "_claim_stt_repository", lambda repo: claims.append(repo) or (None, None)
    )
    monkeypatch.setattr(
        module, "_prepare_stt_cache_for_http", lambda repo, cache: prepares.append(repo)
    )
    monkeypatch.setattr(
        worker_mod, "spawn_download", lambda *a, **k: spawns.append(a) or pytest.fail("spawned")
    )

    state = state_factory()
    state._cancelled = True
    state._run(model_id, None, hub_cache = tmp_path)

    assert claims == [], "a cancelled run still reserved the repository"
    assert prepares == [], "a cancelled run still rewrote the shared cache"
    assert spawns == []


@pytest.mark.parametrize(
    "state_factory, model_id",
    [
        (snapshot_mod._SnapshotDownloadState, "unsloth/whisper-tiny"),
        (ggml_mod._GgmlDownloadState, "tiny"),
        (mtmd_mod._MtmdDownloadState, "qwen3-asr-0.6b"),
    ],
)
def test_restarting_a_cancelling_download_is_not_a_silent_no_op(state_factory, model_id):
    """The same-model early return would join a run that will download nothing."""
    state = state_factory()
    release = threading.Event()
    state._model_id = model_id
    state._cancelled = True
    state._thread = threading.Thread(target = release.wait, daemon = True)
    state._thread.start()
    try:
        with pytest.raises(snapshot_mod.SttModelIdError, match = "cancelling"):
            state.start(model_id)
    finally:
        release.set()
        state._thread.join(timeout = 5)


@pytest.mark.parametrize(
    "state_factory, active_model, stale_model",
    [
        (snapshot_mod._SnapshotDownloadState, "unsloth/whisper-small", "unsloth/whisper-tiny"),
        (ggml_mod._GgmlDownloadState, "small", "tiny"),
        (mtmd_mod._MtmdDownloadState, "qwen3-asr-1.7b", "qwen3-asr-0.6b"),
        (
            audiocpp_mod._AudioCppDownloadState,
            "homebrew/repo:new-quant",
            "homebrew/repo:old-quant",
        ),
        (
            audiocpp_mod._AudioCppDownloadState,
            "audiocpp-moonshine-small",
            "audiocpp-moonshine-tiny",
        ),
    ],
)
def test_a_stale_cancel_cannot_stop_a_newer_download(
    state_factory, active_model, stale_model, monkeypatch
):
    state = state_factory()
    release = threading.Event()
    process = SimpleNamespace(poll = lambda: None)
    stopped = []
    monkeypatch.setattr(worker_mod, "terminate_download", stopped.append)
    state._model_id = active_model
    state._download_id = "new-download"
    state._process = process
    state._thread = threading.Thread(target = release.wait, daemon = True)
    state._thread.start()
    try:
        assert state.status()["download_id"] == "new-download"
        assert state.cancel(active_model, "old-download") is False
        assert state.cancel(stale_model) is False
        assert state._cancelled is False
        assert stopped == []
        assert state.cancel(active_model, "new-download") is True
        assert state._cancelled is True
        assert stopped == [process]
    finally:
        release.set()
        state._thread.join(timeout = 5)


@pytest.mark.parametrize(
    "state_factory, model_id",
    [
        (snapshot_mod._SnapshotDownloadState, "unsloth/whisper-tiny"),
        (ggml_mod._GgmlDownloadState, "tiny"),
        (mtmd_mod._MtmdDownloadState, "qwen3-asr-0.6b"),
        (audiocpp_mod._AudioCppDownloadState, "homebrew/repo:Q4_K_M"),
    ],
)
def test_a_completed_attempt_cannot_be_cancelled_during_thread_teardown(
    state_factory, model_id, monkeypatch
):
    state = state_factory()
    release = threading.Event()
    process = SimpleNamespace(poll = lambda: None)
    stopped = []
    monkeypatch.setattr(worker_mod, "terminate_download", stopped.append)
    state._model_id = model_id
    state._download_id = "completed-download"
    state._completed_download_ids.append("completed-download")
    state._process = process
    state._thread = threading.Thread(target = release.wait, daemon = True)
    state._thread.start()
    try:
        assert state.cancel(model_id, "completed-download") is False
        assert state._cancelled is False
        assert stopped == []
    finally:
        release.set()
        state._thread.join(timeout = 5)


def test_the_download_identity_is_authoritative_for_an_audio_variant(monkeypatch):
    state = audiocpp_mod._AudioCppDownloadState()
    release = threading.Event()
    process = SimpleNamespace(poll = lambda: None)
    stopped = []
    monkeypatch.setattr(worker_mod, "terminate_download", stopped.append)
    state._model_id = "homebrew/repo:new-quant"
    state._download_id = "new-download"
    state._process = process
    state._thread = threading.Thread(target = release.wait, daemon = True)
    state._thread.start()
    try:
        assert state.status()["variant"] == "new-quant"
        assert state.cancel("homebrew/repo", "new-download") is True
        assert stopped == [process]
    finally:
        release.set()
        state._thread.join(timeout = 5)


def test_completed_download_history_is_bounded_and_ignores_missing_identity():
    history = [f"attempt-{index}" for index in range(8)]

    assert snapshot_mod._remember_completed_download(history, None, cancelled = False) is False
    assert snapshot_mod._remember_completed_download(history, "cancelled", cancelled = True) is False
    assert snapshot_mod._remember_completed_download(history, "attempt-8", cancelled = False) is True

    assert history == [f"attempt-{index}" for index in range(1, 9)]


@pytest.mark.parametrize(
    "state_factory",
    [
        snapshot_mod._SnapshotDownloadState,
        ggml_mod._GgmlDownloadState,
        mtmd_mod._MtmdDownloadState,
        audiocpp_mod._AudioCppDownloadState,
    ],
)
def test_download_status_copies_completed_attempt_history(state_factory):
    state = state_factory()
    state._completed_download_ids.append("attempt-a")

    status = state.status()
    status["completed_download_ids"].append("caller-mutation")

    assert state.status()["completed_download_ids"] == ["attempt-a"]


def test_a_bare_audio_row_remains_a_legacy_cancel_target(monkeypatch):
    state = audiocpp_mod._AudioCppDownloadState()
    release = threading.Event()
    process = SimpleNamespace(poll = lambda: None)
    stopped = []
    monkeypatch.setattr(worker_mod, "terminate_download", stopped.append)
    state._model_id = "homebrew/repo:new-quant"
    state._process = process
    state._thread = threading.Thread(target = release.wait, daemon = True)
    state._thread.start()
    try:
        assert state.cancel("homebrew/repo") is True
        assert stopped == [process]
    finally:
        release.set()
        state._thread.join(timeout = 5)


def test_cancel_route_forwards_the_request_identity():
    from routes import inference

    cancelled = []
    module = SimpleNamespace(
        cancel_model_download = lambda model, download_id: cancelled.append((model, download_id))
        or False,
        download_status = lambda: {"downloading": True, "model": "new"},
    )

    result = inference._cancel_account_stt_download(module, "transformers", "old", "old-download")

    assert cancelled == [("old", "old-download")]
    assert result["cancelled"] is False


def test_start_account_download_returns_the_attempt_identity(monkeypatch):
    from routes import inference

    monkeypatch.setattr(inference.account_access, "account_scope", lambda: None)
    module = SimpleNamespace(start_model_download = lambda *args: "attempt-a")

    assert (
        inference._start_account_stt_download(module, "transformers", "small", None, "a" * 40)
        == "attempt-a"
    )


def test_a_worker_that_ignores_sigterm_is_killed():
    """The canceller holds the repository reservation until the reap returns."""
    process = subprocess.Popen(
        [
            sys.executable,
            "-c",
            "import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(30)",
        ]
    )
    try:
        with pytest.MonkeyPatch.context() as patch:
            patch.setattr(worker_mod, "TERMINATE_GRACE_SECONDS", 0.2)
            started = time.monotonic()
            worker_mod.terminate_download(process)
            assert time.monotonic() - started < 0.2, "cancel() waited on the worker"
            assert process.wait(timeout = 10) != 0
    finally:
        if process.poll() is None:
            process.kill()
            process.wait(timeout = 10)


@pytest.mark.parametrize(
    "state_factory, model_id",
    [
        (snapshot_mod._SnapshotDownloadState, "unsloth/whisper-tiny"),
        (ggml_mod._GgmlDownloadState, "tiny"),
        (mtmd_mod._MtmdDownloadState, "qwen3-asr-0.6b"),
    ],
)
def test_status_never_stats_the_cache_under_the_download_lock(state_factory, model_id):
    """Progress is now three stats per selected file; a cancel must not queue."""
    state = state_factory()
    observed = []

    def probe(*args, **kwargs):
        observed.append(state._lock.acquire(blocking = False))
        if observed[-1]:
            state._lock.release()
        return 1

    state._downloaded_bytes = probe
    state._model_id = model_id
    state._thread = threading.Thread(target = lambda: time.sleep(0.3), daemon = True)
    state._thread.start()
    try:
        assert state.status()["bytes_done"] == 1
    finally:
        state._thread.join(timeout = 5)
    assert observed == [True], "progress was computed while holding the download lock"


@pytest.mark.parametrize(
    "state_factory, model_id, restart",
    [
        (
            snapshot_mod._SnapshotDownloadState,
            "unsloth/whisper-tiny",
            lambda s: setattr(s, "_repo", "org/next") or setattr(s, "_selected_files", ()),
        ),
        (ggml_mod._GgmlDownloadState, "tiny", lambda s: setattr(s, "_etag", None)),
        (
            mtmd_mod._MtmdDownloadState,
            "qwen3-asr-0.6b",
            lambda s: setattr(s, "_selected_files", ()),
        ),
    ],
)
def test_progress_cannot_mix_a_new_runs_bytes_with_the_old_runs_total(
    state_factory, model_id, restart, tmp_path
):
    """status() reads bytes_total under the lock: a run starting before the cache probe would mix totals."""
    state = state_factory()
    state._model_id = model_id
    state._repo = "org/repo"
    state._hub_cache = tmp_path
    state._total_bytes = 1000
    state._etag = "etag"
    state._selected_files = (snapshot_mod._SelectedHubFile(path = "f", size = 1000, blob_key = None),)
    release = threading.Event()
    state._thread = threading.Thread(target = release.wait, daemon = True)
    state._thread.start()

    real = state._downloaded_bytes

    def probe_after_a_restart(*args, **kwargs):
        restart(state)
        return real(*args, **kwargs)

    state._downloaded_bytes = probe_after_a_restart
    try:
        status = state.status()
    finally:
        release.set()
        state._thread.join(timeout = 5)

    assert status["bytes_total"] == 1000
    assert status["bytes_done"] == 0, "the probe read the restarted run's fields"


def test_mtmd_rejects_a_revision_that_is_not_an_immutable_commit(monkeypatch, tmp_path):
    """Other backends check the SHA; a bad one pinned into --revision is silently dropped."""

    class _Meta:
        commit_hash = "main"
        etag = "etag"
        size = 1

    monkeypatch.setattr(mtmd_mod, "_claim_stt_repository", lambda repo: pytest.fail("claimed"))
    import huggingface_hub

    monkeypatch.setattr(huggingface_hub, "get_hf_file_metadata", lambda *a, **k: _Meta())
    state = mtmd_mod._MtmdDownloadState()
    state._run("qwen3-asr-0.6b", None, hub_cache = tmp_path)

    assert state.status()["error"] is not None