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.

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

"""A malformed response must be skipped, not fatal, since the dispatcher is the sole queue consumer."""

from __future__ import annotations

import ast
import queue
import sys
import threading
from pathlib import Path

import pytest

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

from core.inference.orchestrator import InferenceOrchestrator  # noqa: E402


class _ScriptedQueue:
    def __init__(self, items):
        self._items = list(items)

    def get(self, timeout = None):
        if self._items:
            return self._items.pop(0)
        raise queue.Empty


def _dispatcher():
    o = InferenceOrchestrator.__new__(InferenceOrchestrator)
    o._stop_ledger = None
    o._pending_teardowns = None
    o._dispatcher_stop = threading.Event()
    o._mailbox_lock = threading.Lock()
    o._mailboxes = {}
    o._direct_mailboxes = {}
    o._request_cancel_events = {}
    o._proc = None  # no worker, so no routed response retires anything
    return o


def test_dispatcher_survives_malformed_response_and_routes_next():
    o = _dispatcher()
    rid = "req-1"
    mbox = queue.Queue()
    o._mailboxes = {rid: mbox}
    # A non-dict response (resp.get -> AttributeError) must not kill the loop;
    # the following valid response must still reach its mailbox.
    o._resp_queue = _ScriptedQueue([12345, {"request_id": rid, "type": "token", "text": "hi"}])

    t = threading.Thread(target = o._dispatcher_loop, daemon = True)
    t.start()
    try:
        got = mbox.get(timeout = 5)
        assert got["text"] == "hi", "valid response must route despite the prior bad one"
        assert t.is_alive(), "dispatcher must survive a malformed response"
    finally:
        o._dispatcher_stop.set()
        t.join(timeout = 5)
    assert not t.is_alive()


def test_dispatcher_survives_mailbox_put_error():
    o = _dispatcher()
    rid = "req-2"

    class _BadMailbox:
        def put(self, _resp):
            raise RuntimeError("mailbox is broken")

    good = queue.Queue()
    o._mailboxes = {rid: _BadMailbox(), "req-3": good}
    o._resp_queue = _ScriptedQueue(
        [
            {"request_id": rid, "type": "token", "text": "boom"},
            {"request_id": "req-3", "type": "token", "text": "ok"},
        ]
    )

    t = threading.Thread(target = o._dispatcher_loop, daemon = True)
    t.start()
    try:
        got = good.get(timeout = 5)
        assert got["text"] == "ok"
        assert t.is_alive()
    finally:
        o._dispatcher_stop.set()
        t.join(timeout = 5)
    assert not t.is_alive()


def _is_local_async_client(func) -> bool:
    # gated_async_client (#14546) wraps httpx.AsyncClient so archive embedding pauses for the request.
    if isinstance(func, ast.Attribute):
        return (
            func.attr == "AsyncClient"
            and isinstance(func.value, ast.Name)
            and func.value.id == "httpx"
        )
    return isinstance(func, ast.Name) and func.id == "gated_async_client"


def test_route_llama_streaming_async_clients_disable_proxy_env():
    """Local llama-server streaming proxies must ignore ambient HTTP_PROXY."""
    backend = Path(__file__).resolve().parent.parent
    source = (backend / "routes" / "inference.py").read_text(encoding = "utf-8")
    calls = [
        node
        for node in ast.walk(ast.parse(source))
        if isinstance(node, ast.Call) and _is_local_async_client(node.func)
    ]

    # One factory per kind of llama-server client: streamed, and cancellable non-streaming.
    assert len(calls) == 2
    for call in calls:
        assert any(
            kw.arg == "trust_env" and isinstance(kw.value, ast.Constant) and kw.value.value is False
            for kw in call.keywords
        ), f"the local AsyncClient at line {call.lineno} must set trust_env=False"

    # The wrapper must hand trust_env (all its kwargs) to the httpx client it builds.
    gate = ast.parse(
        (backend / "core" / "inference" / "inference_gate.py").read_text(encoding = "utf-8")
    )
    wrapper = next(
        n
        for n in ast.walk(gate)
        if isinstance(n, ast.FunctionDef) and n.name == "gated_async_client"
    )
    built = [
        n
        for n in ast.walk(wrapper)
        if isinstance(n, ast.Call)
        and _is_local_async_client(n.func)
        and not isinstance(n.func, ast.Name)
    ]
    assert built and all(
        any(
            kw.arg is None
            and isinstance(kw.value, ast.Name)
            and kw.value.id == wrapper.args.kwarg.arg
            for kw in n.keywords
        )
        for n in built
    ), "gated_async_client must forward **kwargs to httpx.AsyncClient"


def _direct_reader_host():
    """Orchestrator with only what _direct_reader and the ownership helpers touch."""
    o = InferenceOrchestrator.__new__(InferenceOrchestrator)
    o._stop_ledger = None
    o._pending_teardowns = None
    o._mailbox_lock = threading.Lock()
    o._mailboxes = {}
    o._direct_mailboxes = {}
    o._request_cancel_events = {}
    o._active_cancel_lock = threading.Lock()
    o._active_cancel_events = []
    o._executing_cancel_events = []
    o._dispatcher_thread = None
    o._proc = None  # no worker, so no read retires anything
    return o


def test_rerouting_a_foreign_response_moves_worker_ownership():
    # A _gen_lock reader can beat the compare dispatcher; it must promote the request,
    # or Stop targets the wrong generation.
    o = _direct_reader_host()
    mine, theirs = threading.Event(), threading.Event()
    o._request_cancel_events = {"mine": mine, "theirs": theirs}
    o._claim_worker(mine)
    o._mark_worker_started(mine)
    o._claim_worker(theirs)
    compare_mailbox = queue.Queue()
    o._mailboxes["theirs"] = compare_mailbox

    read_one, _drain, release = _direct_reader_calls(o, "mine")
    o._scripted = [{"request_id": "theirs", "type": "token", "text": "hi"}]

    assert read_one(timeout = 0.1) is None, "a foreign response is routed, not returned"
    assert compare_mailbox.get_nowait()["text"] == "hi"
    assert o._owns_worker(theirs), "the compare request is the one the worker answered"
    assert not o._owns_worker(mine), "so a late reset from the direct request must not fire"
    release()


def test_rerouting_a_foreign_gen_done_retires_that_request():
    # Once its last response is routed the request no longer owns the worker.
    o = _direct_reader_host()
    mine, theirs = threading.Event(), threading.Event()
    o._request_cancel_events = {"mine": mine, "theirs": theirs}
    o._claim_worker(theirs)
    o._mark_worker_started(theirs)
    o._claim_worker(mine)
    o._mailboxes["theirs"] = queue.Queue()

    read_one, _drain, release = _direct_reader_calls(o, "mine")
    o._scripted = [{"request_id": "theirs", "type": "gen_done"}]

    assert read_one(timeout = 0.1) is None
    assert not o._owns_worker(theirs), "retired once its last response was routed"
    assert o._owns_worker(mine), "the next claim takes over"
    release()


def _direct_reader_calls(
    o,
    request_id,
    cancel_event = None,
):
    """_direct_reader wired to a scripted _read_resp (o._scripted, popped in order)."""
    o._read_resp = lambda timeout = 1.0, observe = True: (o._scripted.pop(0) if o._scripted else None)
    return o._direct_reader(request_id, cancel_event)


@pytest.mark.parametrize(
    "response_type", ["token", "gen_done", "gen_error", "audio_done", "audio_error"]
)
def test_direct_reader_discards_responses_from_released_requests(response_type):
    # Consumers dispatch on type alone: a released request's late frame becomes this one's answer.
    o = _direct_reader_host()
    current = {"request_id": "current", "type": "token", "text": "current answer"}
    o._scripted = [
        {"request_id": "cancelled", "type": response_type, "text": "old answer"},
        current,
    ]
    read_one, _drain, release = _direct_reader_calls(o, "current")
    try:
        assert read_one(timeout = 0.1) is None
        assert read_one(timeout = 0.1) == current
    finally:
        release()


def test_direct_reader_discards_only_what_is_addressed_to_someone_else():
    # Dropping the `rid and` half would swallow the worker's unaddressed crash error and hang the chat.
    o = _direct_reader_host()
    worker_error = {"type": "error", "error": "Command 'generate' failed: out of memory"}
    o._scripted = [worker_error, {"request_id": "", "type": "gen_done"}]
    read_one, _drain, release = _direct_reader_calls(o, "current")
    try:
        assert read_one(timeout = 0.1) == worker_error
        assert read_one(timeout = 0.1) == {"request_id": "", "type": "gen_done"}
    finally:
        release()


def test_discarding_a_released_response_leaves_worker_ownership_alone():
    # Ownership must not move on a discarded frame, or the live chat's Stop hits the wrong generation.
    o = _direct_reader_host()
    mine, theirs = threading.Event(), threading.Event()
    o._request_cancel_events = {"current": mine, "cancelled": theirs}
    o._claim_worker(mine)
    o._mark_worker_started(mine)
    o._scripted = [{"request_id": "cancelled", "type": "token", "text": "late"}]

    read_one, _drain, release = _direct_reader_calls(o, "current")
    try:
        assert read_one(timeout = 0.1) is None
        assert o._owns_worker(mine), "a discarded frame must not move the executor"
        assert not o._owns_worker(theirs)
    finally:
        release()


def test_direct_reader_drain_waits_for_its_own_terminal_response():
    # Ending the drain on an orphan terminal hands the next request a worker that never stopped.
    o = _direct_reader_host()
    o._scripted = [
        {"request_id": "cancelled", "type": "gen_done"},
        {"request_id": "current", "type": "token", "text": "still running"},
        {"request_id": "current", "type": "gen_done"},
    ]
    o._ensure_subprocess_alive = lambda: True
    _read_one, drain, release = _direct_reader_calls(o, "current")
    try:
        assert drain(timeout = 1.0)
        assert not o._scripted, "an orphan gen_done must not end the current drain early"
    finally:
        release()