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.

9.2 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

"""POST /audio/cancel stops the one /audio/run sent with that cancel_id, and nothing else."""

from __future__ import annotations

import asyncio
import sys
import threading
from pathlib import Path

import httpx

from core.inference.audio_errors import AudioGenerationCancelledError

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

import test_account_media_isolation as _media  # noqa: E402
from test_account_media_isolation import ALICE  # noqa: E402
import test_audio_run_extras as _extras  # noqa: E402
from test_audio_run_extras import Backend, app_for  # noqa: E402

KOKORO = "audio-cpp/audio.cpp-gguf/Kokoro-82M-GGUF"
SPEAK_INFO = {
    "is_audio": True,
    "audio_type": "audiocpp_tts",
    "audio_workflows": ["speak"],
    "audio_reference_text": None,
    "audio_required_inputs": [],
}
RUN_A, RUN_B, EARLY = "run-aaaaaaaa", "run-bbbbbbbb", "run-cccccccc"

# Shared fixtures, bound by assignment so pytest finds them in this module.
isolated = _media.isolated
use_backend = _extras.use_backend


def _blocking_backend():
    """Each run waits for its cancel event or ``release``; ``started`` names the runs under way."""
    started = {RUN_A: threading.Event(), RUN_B: threading.Event(), EARLY: threading.Event()}
    release = threading.Event()

    def run(kwargs):
        started[kwargs["text"]].set()
        cancel = kwargs["cancel_event"]
        while not release.is_set():
            if cancel.wait(0.02):
                raise AudioGenerationCancelledError("Audio generation cancelled")

    return Backend(KOKORO, SPEAK_INFO, run = run), started, release


def test_cancel_by_id_stops_only_that_run(use_backend):
    backend, started, release = _blocking_backend()
    use_backend(backend)

    async def scenario():
        transport = httpx.ASGITransport(app = app_for(ALICE))
        async with httpx.AsyncClient(transport = transport, base_url = "http://t") as client:

            def run(cancel_id):
                body = {"workflow": "speak", "text": cancel_id, "cancel_id": cancel_id}
                return asyncio.create_task(client.post("/api/inference/audio/run", json = body))

            a, b = run(RUN_A), run(RUN_B)
            for name in (RUN_A, RUN_B):
                assert await asyncio.to_thread(started[name].wait, 10)
            # A chat cancel_id lives in another namespace.
            chat = await client.post("/api/inference/cancel", json = {"cancel_id": RUN_A})
            stopped = await client.post("/v1/audio/cancel", json = {"cancel_id": RUN_A})
            try:
                done_a = await asyncio.wait_for(asyncio.shield(a), 10)
            finally:
                release.set()
            return chat.json(), stopped.json(), done_a, await b

    chat, stopped, done_a, done_b = asyncio.run(scenario())
    assert chat == {"cancelled": 0}
    assert stopped == {"cancelled": 1}
    assert done_a.status_code == 499
    assert done_b.status_code == 200 and len(done_b.json()["clips"]) == 1


def test_stopping_the_callers_generation_ticket_stops_the_run(use_backend):
    from core.inference.generation_ticket import GenerationTicket, generation_ticket

    backend, started, release = _blocking_backend()
    use_backend(backend)

    async def scenario():
        transport = httpx.ASGITransport(app = app_for(ALICE))
        async with httpx.AsyncClient(transport = transport, base_url = "http://t") as client:
            body = {"workflow": "speak", "text": RUN_A, "cancel_id": RUN_A}
            with generation_ticket(ticket := GenerationTicket()):
                run = asyncio.create_task(client.post("/api/inference/audio/run", json = body))
            assert await asyncio.to_thread(started[RUN_A].wait, 10) and ticket.stop() is True
            try:
                return await asyncio.wait_for(asyncio.shield(run), 10)
            finally:
                release.set()

    assert asyncio.run(scenario()).status_code == 499


def test_an_early_cancel_is_kept_for_the_run_that_follows(use_backend):
    backend, started, _release = _blocking_backend()
    use_backend(backend)

    async def scenario():
        transport = httpx.ASGITransport(app = app_for(ALICE))
        async with httpx.AsyncClient(transport = transport, base_url = "http://t") as client:
            early = await client.post("/api/inference/audio/cancel", json = {"cancel_id": EARLY})
            body = {"workflow": "speak", "text": EARLY, "cancel_id": EARLY}
            return early.json(), await client.post("/api/inference/audio/run", json = body)

    early, response = asyncio.run(scenario())
    assert early == {"cancelled": 0}
    assert response.status_code == 499


def test_a_cancel_during_a_slow_model_load_stops_the_run(use_backend, monkeypatch):
    from routes import inference

    backend, started, release = _blocking_backend()
    use_backend(backend)
    loading, loaded = threading.Event(), threading.Event()

    async def slow_switch(*args, **kwargs):
        loading.set()
        # Stands in for a cold load that outlasts the 30 s a stashed cancel is kept.
        await asyncio.to_thread(loaded.wait, 10)
        inference._PENDING_CANCELS.clear()

    monkeypatch.setattr(inference, "_maybe_auto_switch_model", slow_switch)

    async def scenario():
        transport = httpx.ASGITransport(app = app_for(ALICE))
        async with httpx.AsyncClient(transport = transport, base_url = "http://t") as client:
            body = {"workflow": "speak", "text": RUN_A, "cancel_id": RUN_A}
            run = asyncio.create_task(client.post("/api/inference/audio/run", json = body))
            assert await asyncio.to_thread(loading.wait, 10)
            stopped = await client.post("/api/inference/audio/cancel", json = {"cancel_id": RUN_A})
            loaded.set()
            try:
                return stopped.json(), await asyncio.wait_for(asyncio.shield(run), 10)
            finally:
                release.set()

    stopped, response = asyncio.run(scenario())
    assert stopped == {"cancelled": 1}
    assert response.status_code == 499
    assert not started[RUN_A].is_set()


def test_a_cancel_while_the_clip_saves_removes_it(use_backend, monkeypatch):
    from routes import inference

    backend, _started, release = _blocking_backend()
    release.set()
    use_backend(backend)
    saved_paths, saving, go_on = [], threading.Event(), threading.Event()
    persist = inference._persist_tts_clip

    def slow_persist(*args, **kwargs):
        record = persist(*args, **kwargs)
        from core.inference import audio_gallery

        saved_paths.append(audio_gallery.audio_path(record["id"]))
        saving.set()
        go_on.wait(10)
        return record

    monkeypatch.setattr(inference, "_persist_tts_clip", slow_persist)

    async def scenario():
        transport = httpx.ASGITransport(app = app_for(ALICE))
        async with httpx.AsyncClient(transport = transport, base_url = "http://t") as client:
            body = {"workflow": "speak", "text": RUN_A, "cancel_id": RUN_A}
            run = asyncio.create_task(client.post("/api/inference/audio/run", json = body))
            try:
                assert await asyncio.to_thread(saving.wait, 10)
                stopped = await client.post(
                    "/api/inference/audio/cancel", json = {"cancel_id": RUN_A}
                )
            finally:
                go_on.set()
            return stopped.json(), await asyncio.wait_for(run, 10)

    stopped, response = asyncio.run(scenario())
    assert stopped == {"cancelled": 1}
    assert response.status_code == 499
    assert saved_paths and saved_paths[0] is not None and not saved_paths[0].exists()


def test_a_cancel_id_already_running_is_refused(use_backend):
    backend, started, release = _blocking_backend()
    use_backend(backend)

    async def scenario():
        transport = httpx.ASGITransport(app = app_for(ALICE))
        async with httpx.AsyncClient(transport = transport, base_url = "http://t") as client:
            body = {"workflow": "speak", "text": RUN_A, "cancel_id": RUN_A}
            first = asyncio.create_task(client.post("/api/inference/audio/run", json = body))
            try:
                assert await asyncio.to_thread(started[RUN_A].wait, 10)
                second = await client.post("/api/inference/audio/run", json = body)
            finally:
                release.set()
            done = await asyncio.wait_for(first, 10)
            # The id is free again once its run ends.
            again = await client.post("/api/inference/audio/run", json = body)
            return second, done, again

    second, done, again = asyncio.run(scenario())
    assert second.status_code == 409
    assert done.status_code == 200 and again.status_code == 200


def test_cancel_ids_are_checked():
    from fastapi.testclient import TestClient
    with TestClient(app_for(ALICE)) as client:
        for bad in ("short", "has space!", "x" * 65):
            response = client.post("/api/inference/audio/cancel", json = {"cancel_id": bad})
            assert response.status_code == 422
        run = {"workflow": "speak", "text": "hi", "cancel_id": "no"}
        assert client.post("/api/inference/audio/run", json = run).status_code == 422