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.

123 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
"""unload_model cancels generation first, so unload never queues behind a running generate."""

import inspect
import queue
import threading
import time

import pytest

from core.inference import orchestrator as orch_mod
from core.inference.orchestrator import InferenceOrchestrator


class _Llama:
    is_active = False
    is_loaded = False
    model_identifier = None


class _Unsloth:
    def get_loading_model(self):
        return None


class _RecordOfStops:
    """Stands in for the ledger; only whether the worker reads it matters here."""

    def __init__(self, read_by_worker: bool):
        self.stopped: list = []
        self._read_by_worker = read_by_worker

    def stop(self, request_id):
        self.stopped.append(request_id)
        return True

    def read_by_worker(self) -> bool:
        return self._read_by_worker


def _bare_orchestrator(reads_stops = False):
    """An orchestrator without the real __init__ subprocess/network."""
    o = InferenceOrchestrator.__new__(InferenceOrchestrator)
    o._stop_ledger = _RecordOfStops(True) if reads_stops else None
    o._pending_teardowns = None
    o._gen_lock = threading.Lock()
    o._send_order_lock = threading.Lock()
    o._subprocess_shutdown_lock = threading.Lock()
    o._active_cancel_lock = threading.Lock()
    o._active_cancel_events = []
    o._executing_cancel_events = []
    o._cancel_event = threading.Event()
    o._drain_event = threading.Event()
    o._proc = object()  # truthy so _ensure_subprocess_alive reports alive
    o._cmd_queue = object()
    o._resp_queue = object()
    o._dispatcher_thread = None
    o._dispatcher_stop = threading.Event()
    o._dispatcher_lifecycle_lock = threading.Lock()
    o._worker_released = threading.Condition(o._dispatcher_lifecycle_lock)
    o._unload_pending = False
    o._worker_reserved_for = None
    o._mailbox_lock = threading.Lock()
    o._mailboxes = {}
    o._direct_mailboxes = {}
    o._request_cancel_events = {}
    o.active_model_name = "m"
    o.models = {"m": {}}
    o.loading_models = set()
    return o


def test_adapter_control_raises_stream_errors(monkeypatch):
    o = _bare_orchestrator()
    monkeypatch.setattr(
        o,
        "_generate_dispatched",
        lambda **_kwargs: iter([orch_mod.GenStreamError("Error: adapter failed")]),
    )

    with pytest.raises(RuntimeError, match = "adapter failed"):
        list(o.generate_with_adapter_control(use_adapter = False))

    closed = []

    def _stream(**_kwargs):
        try:
            yield "token"
            yield "late token"
        finally:
            closed.append(True)

    monkeypatch.setattr(o, "_generate_dispatched", _stream)
    generator = o.generate_with_adapter_control(use_adapter = False)
    assert next(generator) == "token"
    generator.close()
    assert closed == [True]


def test_worker_closes_cancelled_generator_before_gen_done():
    from core.inference.worker import _handle_generate

    events = []

    class _Backend:
        last_generation_stats = None

        def generate_with_adapter_control(self, **_kwargs):
            try:
                yield "token"
                yield "late token"
            finally:
                events.append("closed")

    class _Responses:
        def __init__(self):
            self.items = []

        def put(self, item):
            if item["type"] == "gen_done":
                assert events == ["closed"]
            self.items.append(item)

    responses = _Responses()
    cancel = threading.Event()
    cancel.set()
    _handle_generate(
        _Backend(),
        {"request_id": "r1", "messages": [], "use_adapter": False},
        responses,
        cancel,
    )

    assert [item["type"] for item in responses.items if item["type"] != "batch_state"] == [
        "gen_done"
    ]


def test_unload_cancels_inflight_generation_then_unloads(monkeypatch):
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    sent = []
    monkeypatch.setattr(o, "_send_cmd", lambda cmd: sent.append(cmd))
    monkeypatch.setattr(o, "_wait_response", lambda t, timeout = 300.0: {"type": "unloaded"})
    monkeypatch.setattr(o, "_drain_queue", lambda: [])

    o._gen_lock.acquire()

    def releaser():
        o._cancel_event.wait(timeout = 5)
        o._gen_lock.release()

    t = threading.Thread(target = releaser)
    t.start()

    start = time.monotonic()
    ok = o.unload_model("m")
    elapsed = time.monotonic() - start
    t.join(timeout = 5)

    assert ok is True
    assert o._cancel_event.is_set(), "generation must be cancelled before the unload"
    assert {"type": "unload", "model_name": "m"} in sent
    assert o.active_model_name is None
    assert "m" not in o.models
    assert elapsed < 2.0


def test_unload_no_active_generation_unloads_normally(monkeypatch):
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    sent = []
    monkeypatch.setattr(o, "_send_cmd", lambda cmd: sent.append(cmd))
    monkeypatch.setattr(o, "_wait_response", lambda t, timeout = 300.0: {"type": "unloaded"})
    monkeypatch.setattr(o, "_drain_queue", lambda: [])

    ok = o.unload_model("m")

    assert ok is True
    assert {"type": "unload", "model_name": "m"} in sent
    assert o.active_model_name is None
    assert o._gen_lock.acquire(blocking = False)
    o._gen_lock.release()


def test_unload_falls_back_to_shutdown_when_generation_wont_yield(monkeypatch):
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(orch_mod, "_UNLOAD_GEN_LOCK_TIMEOUT", 0.2)
    shutdown = []
    monkeypatch.setattr(o, "_shutdown_subprocess", lambda timeout = 5: shutdown.append(timeout))
    monkeypatch.setattr(
        o,
        "_send_cmd",
        lambda cmd: pytest.fail("must not send unload when wedged")
        if cmd.get("type") == "unload"
        else None,
    )

    o._gen_lock.acquire()

    ok = o.unload_model("m")

    assert ok is True
    assert shutdown, "should tear the subprocess down to free the GPU"
    assert o.active_model_name is None


def test_unload_tears_down_when_compare_dispatcher_wedged(monkeypatch):
    # Compare-mode generations bypass _gen_lock, so unload must tear the subprocess down.
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(orch_mod, "_DISPATCH_IDLE_TIMEOUT", 0.2)

    o._mailbox_lock = threading.Lock()
    o._mailboxes = {"req-1": object()}

    class _AliveThread:
        def is_alive(self):
            return True

    o._dispatcher_thread = _AliveThread()

    shutdown = []
    monkeypatch.setattr(o, "_shutdown_subprocess", lambda timeout = 5: shutdown.append(timeout))
    monkeypatch.setattr(o, "_drain_queue", lambda: [])
    monkeypatch.setattr(
        o,
        "_send_cmd",
        lambda cmd: pytest.fail("must not send unload with a wedged dispatcher")
        if cmd.get("type") == "unload"
        else None,
    )
    monkeypatch.setattr(
        o,
        "_wait_response",
        lambda t, timeout = 300.0: pytest.fail(
            "must not wait on resp_queue with a wedged dispatcher"
        ),
    )

    ok = o.unload_model("m")

    assert ok is True
    assert shutdown, "should tear the subprocess down to free the GPU"
    assert o.active_model_name is None
    assert "m" not in o.models


def test_consume_token_stream_bails_when_subprocess_swapped(monkeypatch):
    # After a teardown a reload swaps _proc/_resp_queue; the live gen must bail on the swap.
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(
        o, "_subprocess_crash_message", lambda ctx, **kwargs: "inference subprocess restarted"
    )

    def read_one(timeout):
        o._proc = object()
        return None

    gen = o._consume_token_stream(read_one, lambda: None, crash_context = "generation")
    msg = next(gen)

    assert "restarted" in msg
    with pytest.raises(StopIteration):
        next(gen)


_GPU_TIMEOUT = (
    "[METAL] Command buffer execution failed: Caused GPU Timeout Error "
    "(00000002:kIOGPUCommandBufferCallbackErrorTimeout)"
)


def _watch_teardown(
    o,
    monkeypatch,
    *,
    dead = True,
):
    torn_down = []

    def shutdown(timeout):
        torn_down.append(timeout)
        if dead:
            o._proc = None
        return dead

    monkeypatch.setattr(o, "_shutdown_subprocess_locked", shutdown)
    return torn_down


def _queue_of(*responses):
    filled = queue.Queue()
    for resp in responses:
        filled.put(resp)
    return filled


def _mailbox_for(worker, *responses):
    filled = orch_mod._WorkerMailbox(worker)
    for resp in responses:
        filled.put(resp)
    return filled


class _LiveDispatcher:
    def is_alive(self):
        return True


def test_a_foreign_fault_reaches_its_mailbox_before_the_worker_is_retired(monkeypatch):
    o = _bare_orchestrator()
    torn_down = []

    def shutdown(timeout):
        torn_down.append(timeout)
        o._proc = None
        o._reset_worker_scoped_state()
        return True

    monkeypatch.setattr(o, "_shutdown_subprocess_locked", shutdown)
    theirs = threading.Event()
    o._request_cancel_events = {"theirs": theirs}
    o._claim_worker(theirs)
    compare_mailbox = queue.Queue()
    o._mailboxes = {"theirs": compare_mailbox}
    fault = {"type": "gen_error", "request_id": "theirs", "error": _GPU_TIMEOUT}
    o._resp_queue = _queue_of(fault)

    read_one, _drain, release = o._direct_reader("mine")
    try:
        assert read_one(timeout = 0.5) is None, "a foreign response is routed, not returned"
    finally:
        release()

    assert compare_mailbox.get_nowait() == fault, "the request it belongs to must see the fault"
    assert torn_down, "and the dead worker must still be retired"
    assert o.active_model_name is None


@pytest.mark.parametrize(
    "already_waiting, fault",
    [
        (True, {"type": "gen_error", "request_id": "r1", "error": _GPU_TIMEOUT}),
        (False, {"type": "audio_error", "request_id": "r1", "error": "SubmissionsIgnored"}),
    ],
    ids = ["already waiting", "routed a moment later"],
)
def test_a_direct_request_reading_past_a_live_dispatcher_still_retires(
    already_waiting, fault, monkeypatch
):
    o = _bare_orchestrator()
    torn_down = _watch_teardown(o, monkeypatch)
    o._dispatcher_thread = _LiveDispatcher()
    read_one, _drain, release = o._direct_reader("r1")
    mailbox = o._direct_mailboxes["r1"]
    if already_waiting:
        mailbox.put(fault)
    else:
        threading.Timer(0.05, mailbox.put, [fault]).start()

    try:
        assert read_one(timeout = 2.0) == fault
    finally:
        release()

    assert torn_down
    assert o.active_model_name is None


def test_a_dispatched_stream_retires_on_the_fault_the_dispatcher_routed(monkeypatch):
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    torn_down = _watch_teardown(o, monkeypatch)
    o._resp_queue = queue.Queue()
    monkeypatch.setattr(
        o,
        "_send_cmd",
        lambda cmd: o._resp_queue.put(
            {"type": "gen_error", "request_id": cmd["request_id"], "error": _GPU_TIMEOUT}
        ),
    )

    try:
        streamed = list(o._generate_dispatched(messages = [{"role": "user", "content": "hi"}]))
    finally:
        o._stop_dispatcher()

    assert torn_down, "a dispatched request must retire the worker its fault killed"
    assert o.active_model_name is None
    assert any("GPU Timeout" in str(item) for item in streamed)


@pytest.mark.parametrize(
    "leaves_a_mailbox", [False, True], ids = ["no mailbox left", "a mailbox nobody reads"]
)
def test_a_routed_fault_retires_the_worker_without_waiting_on_a_consumer(
    leaves_a_mailbox, monkeypatch
):
    o = _bare_orchestrator()
    if leaves_a_mailbox:
        o._mailboxes = {"gone": orch_mod._WorkerMailbox(o._proc)}
    torn_down = _watch_teardown(o, monkeypatch)
    observers = []
    observe = o._observe_response
    monkeypatch.setattr(
        o,
        "_observe_response",
        lambda resp, worker: (observers.append(threading.current_thread()), observe(resp, worker))[
            1
        ],
    )
    o._resp_queue = queue.Queue()
    o._resp_queue.put({"type": "gen_error", "request_id": "gone", "error": _GPU_TIMEOUT})
    o._dispatcher_stop = threading.Event()
    dispatcher = threading.Thread(target = o._dispatcher_loop, daemon = True)
    dispatcher.start()
    try:
        deadline = time.monotonic() + 5.0
        while not torn_down and time.monotonic() < deadline:
            time.sleep(0.01)
    finally:
        o._dispatcher_stop.set()
        dispatcher.join(timeout = 5.0)

    assert torn_down, "no consumer will read it, so routing is the last chance"
    assert o.active_model_name is None
    assert observers and dispatcher not in observers


def test_a_cancelled_generation_still_retires_the_worker_it_poisoned(monkeypatch):
    direct = _bare_orchestrator()
    monkeypatch.setattr(direct, "_ensure_subprocess_alive", lambda: True)
    direct_torn_down = _watch_teardown(direct, monkeypatch)
    direct._resp_queue = _queue_of(
        {"type": "token", "token": "a"}, {"type": "gen_error", "error": _GPU_TIMEOUT}
    )
    direct._drain_until_gen_done(timeout = 1.0)

    dispatched = _bare_orchestrator()
    dispatched_torn_down = _watch_teardown(dispatched, monkeypatch)
    dispatched._drain_mailbox(
        _mailbox_for(
            dispatched._proc,
            {"type": "token", "token": "a"},
            {"type": "gen_error", "error": _GPU_TIMEOUT},
        ),
        timeout = 1.0,
    )

    assert direct_torn_down and dispatched_torn_down
    assert direct.active_model_name is None and dispatched.active_model_name is None


def test_an_ordinary_generation_error_leaves_the_worker_alone(monkeypatch):
    o = _bare_orchestrator()
    torn_down = _watch_teardown(o, monkeypatch)
    o._resp_queue = _queue_of(
        {"type": "gen_error", "request_id": "r1", "error": "context too long"}
    )

    assert o._read_resp(timeout = 0.01)["error"] == "context too long"
    assert not torn_down
    assert o.active_model_name == "m"


def test_a_worker_that_outlives_the_kill_keeps_the_model_it_is_still_holding(monkeypatch):
    o = _bare_orchestrator()
    torn_down = _watch_teardown(o, monkeypatch, dead = False)
    o._resp_queue = _queue_of({"type": "gen_error", "error": _GPU_TIMEOUT})

    o._read_resp(timeout = 0.01)

    assert torn_down
    assert o.active_model_name == "m"
    assert o.models == {"m": {}}


class _SwappedDuringRead(queue.Queue):
    def __init__(self, orchestrator, replacement, resp):
        super().__init__()
        self._orchestrator = orchestrator
        self._replacement = replacement
        self._resp = resp

    def get(self, timeout = None):
        self._orchestrator._proc = self._replacement
        return self._resp


def test_a_fault_read_across_a_replacement_leaves_the_replacement_alone(monkeypatch):
    o = _bare_orchestrator()
    torn_down = _watch_teardown(o, monkeypatch)
    replacement = object()
    o._resp_queue = _SwappedDuringRead(o, replacement, {"type": "gen_error", "error": _GPU_TIMEOUT})

    assert o._read_resp(timeout = 0.01)["error"] == _GPU_TIMEOUT

    assert not torn_down, "the fault predates the replacement"
    assert o._proc is replacement
    assert o.active_model_name == "m"


def test_the_direct_read_takes_the_handle_before_the_queue(monkeypatch):
    o = _bare_orchestrator()
    torn_down = _watch_teardown(o, monkeypatch)
    replacement = object()
    abandoned = _queue_of({"type": "gen_error", "error": _GPU_TIMEOUT})

    def reload_as_the_queue_is_taken(_self):
        o._proc = replacement
        return abandoned

    monkeypatch.setattr(
        type(o), "_resp_queue", property(reload_as_the_queue_is_taken), raising = False
    )

    o._read_resp(timeout = 0.01)

    assert not torn_down, "the fault came off the queue the predecessor left behind"
    assert o.active_model_name == "m"


def test_a_fault_in_a_mailbox_that_outlived_its_worker_leaves_the_replacement_alone(monkeypatch):
    o = _bare_orchestrator()
    torn_down = _watch_teardown(o, monkeypatch)
    mailbox = _mailbox_for(o._proc, {"type": "gen_error", "error": _GPU_TIMEOUT})
    replacement = object()
    o._proc = replacement

    assert o._read_mailbox(mailbox, 0.01)["error"] == _GPU_TIMEOUT

    assert not torn_down, "the fault was the old worker's; the replacement never produced it"
    assert o._proc is replacement
    assert o.active_model_name == "m"
    assert o.models == {"m": {}}


def test_a_fault_from_a_replaced_worker_leaves_the_replacement_alone(monkeypatch):
    o = _bare_orchestrator()
    torn_down = _watch_teardown(o, monkeypatch)
    replacement = object()

    def reload():
        o._proc = replacement
        o._subprocess_shutdown_lock.release()

    o._subprocess_shutdown_lock.acquire()
    threading.Timer(0.05, reload).start()

    o._observe_response({"type": "gen_error", "error": _GPU_TIMEOUT}, o._proc)

    assert not torn_down, "the fault belonged to a worker that is already gone"
    assert o._proc is replacement
    assert o.active_model_name == "m"
    assert o.models == {"m": {}}


def test_a_fault_with_no_worker_behind_it_clears_nothing(monkeypatch):
    """``None is not None`` is False, so the check alone would let an absent worker through."""
    o = _bare_orchestrator()
    torn_down = _watch_teardown(o, monkeypatch)
    o._proc = None

    o._read_mailbox(_mailbox_for(None, {"type": "gen_error", "error": _GPU_TIMEOUT}), 0.01)

    assert not torn_down
    assert o.active_model_name == "m"
    assert o.models == {"m": {}}


def test_unload_pending_clears_after_unload(monkeypatch):
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(o, "_send_cmd", lambda cmd: None)
    monkeypatch.setattr(o, "_wait_response", lambda t, timeout = 300.0: {"type": "unloaded"})
    monkeypatch.setattr(o, "_drain_queue", lambda: [])

    o.unload_model("m")

    assert o._unload_pending is False


def test_generation_bails_when_unload_pending(monkeypatch):
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    o._unload_pending = True

    out = list(o._generate_inner(messages = [{"role": "user", "content": "hi"}]))

    assert any("unloaded" in chunk.lower() for chunk in out)
    assert o._gen_lock.acquire(blocking = False)
    o._gen_lock.release()


def test_dispatched_generation_bails_when_unload_pending(monkeypatch):
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(
        o, "_start_dispatcher", lambda: pytest.fail("must not start a generation mid-switch")
    )
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("must not send generate mid-switch")
    )
    o._unload_pending = True

    out = list(o._generate_dispatched(messages = [{"role": "user", "content": "hi"}]))

    assert any("unloaded" in chunk.lower() for chunk in out)


def test_audio_input_generation_bails_when_unload_pending(monkeypatch):
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("must not send generate mid-switch")
    )
    o._unload_pending = True

    out = list(o._generate_audio_input_inner(audio_array = [0.0, 0.1]))

    assert any("unloaded" in chunk.lower() for chunk in out)
    assert o._gen_lock.acquire(blocking = False)
    o._gen_lock.release()


def test_audio_response_bails_when_unload_pending(monkeypatch):
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("must not send audio generate mid-switch")
    )
    o._unload_pending = True

    with pytest.raises(RuntimeError, match = "unload"):
        o.generate_audio_response("hello")

    assert o._gen_lock.acquire(blocking = False)
    o._gen_lock.release()


def test_worker_drain_skip_emits_cancelled_gen_done_when_draining():
    # The worker clears cancel_event per generate; drain_event is the durable skip signal.

    import queue as _queue

    from core.inference.worker import _drain_skip_generate

    drain = threading.Event()
    rq: _queue.Queue = _queue.Queue()
    cmd = {"type": "generate", "request_id": "r1"}

    assert _drain_skip_generate(cmd, rq, drain) is False
    assert rq.empty()
    assert _drain_skip_generate(cmd, rq, None) is False
    assert rq.empty()

    drain.set()
    assert _drain_skip_generate(cmd, rq, drain) is True
    resp = rq.get_nowait()
    assert resp["type"] == "gen_done"
    assert resp["request_id"] == "r1"
    assert resp["cancelled"] is True


def test_worker_generate_branches_check_drain_before_clearing_cancel():
    import inspect

    from core.inference import worker

    # Each guarded branch checks twice: before and after clearing cancel_event.
    src = inspect.getsource(worker.run_inference_process)
    audio_prepare = inspect.getsource(worker._prepare_generate_audio)
    assert src.count("_drain_skip_generate(cmd, resp_queue, drain_event") == 6
    assert audio_prepare.count("_drain_skip_generate(cmd, resp_queue, drain_event") == 2


def test_worker_generate_rechecks_drain_after_clearing_cancel():
    # Re-check drain after clearing cancel, or a drain set in between is missed.

    import queue as _queue

    from core.inference.worker import _drain_skip_generate

    drain = threading.Event()
    cancel = threading.Event()
    rq: _queue.Queue = _queue.Queue()
    cmd = {"type": "generate", "request_id": "r1"}

    assert _drain_skip_generate(cmd, rq, drain) is False
    assert rq.empty()

    drain.set()
    cancel.set()

    cancel.clear()
    assert not cancel.is_set()

    assert _drain_skip_generate(cmd, rq, drain) is True
    resp = rq.get_nowait()
    assert resp["type"] == "gen_done" and resp["cancelled"] is True


def test_unload_sets_drain_event_during_switch_and_clears_after(monkeypatch):
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(o, "_drain_queue", lambda: [])
    monkeypatch.setattr(o, "_wait_response", lambda t, timeout = 300.0: {"type": "unloaded"})

    seen = {}

    def record_send(cmd):
        seen["drain_set"] = o._drain_event.is_set()

    monkeypatch.setattr(o, "_send_cmd", record_send)

    assert o.unload_model("m") is True
    assert seen.get("drain_set") is True
    assert o._drain_event.is_set() is False


def test_unload_clears_drain_event_even_on_wedged_teardown(monkeypatch):
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(orch_mod, "_UNLOAD_GEN_LOCK_TIMEOUT", 0.2)
    monkeypatch.setattr(
        o,
        "_send_cmd",
        lambda cmd: pytest.fail("must not send when wedged")
        if cmd.get("type") == "unload"
        else None,
    )

    def fake_shutdown(timeout = 5):
        o._drain_event = None

    monkeypatch.setattr(o, "_shutdown_subprocess", fake_shutdown)
    o._gen_lock.acquire()

    assert o.unload_model("m") is True


def _announcing_lock(lock, reached):
    """The held lock, saying so when someone starts waiting for it."""

    class _Announcing:
        def __enter__(self):
            reached.set()
            return lock.__enter__()

        def __exit__(self, *exc):
            return lock.__exit__(*exc)

    return _Announcing()


def test_generation_rechecks_model_after_lock_wait(monkeypatch):
    # The unload's finally may already reset _unload_pending; the under-lock model recheck must bail.
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("must not generate on a swapped/unloaded model")
    )

    reached_lock = threading.Event()
    o.active_model_name = "m"
    o._unload_pending = False
    held = o._gen_lock
    held.acquire()
    o._gen_lock = _announcing_lock(held, reached_lock)

    out: list = []

    def run():
        out.extend(o._generate_inner(messages = [{"role": "user", "content": "hi"}]))

    t = threading.Thread(target = run)
    t.start()
    assert reached_lock.wait(timeout = 5)
    o.active_model_name = "other"
    held.release()
    t.join(timeout = 5)

    assert out and any("unloaded" in chunk.lower() for chunk in out)


def test_generation_rechecks_model_when_unloaded_to_none(monkeypatch):
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("must not generate after the model was unloaded")
    )
    reached_lock = threading.Event()
    o.active_model_name = "m"
    o._unload_pending = False
    held = o._gen_lock
    held.acquire()
    o._gen_lock = _announcing_lock(held, reached_lock)

    out: list = []
    t = threading.Thread(
        target = lambda: out.extend(o._generate_inner(messages = [{"role": "user", "content": "hi"}]))
    )
    t.start()
    assert reached_lock.wait(timeout = 5)
    o.active_model_name = None
    held.release()
    t.join(timeout = 5)

    assert out and any("unloaded" in chunk.lower() for chunk in out)


def test_unload_of_stale_name_does_not_touch_active_model(monkeypatch):
    # The worker unloads its active model for an absent name, so a stale name must no-op.
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("must not send an unload for a stale model name")
    )
    o.active_model_name = "current"
    o.models = {"current": {}}

    assert o.unload_model("stale") is True
    assert o.active_model_name == "current"
    assert "current" in o.models


def test_unload_matches_active_model_case_insensitively(monkeypatch):
    # active_model_name is canonicalized; the stale-name guard must match case-insensitively.
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    sent = []
    monkeypatch.setattr(o, "_send_cmd", lambda cmd: sent.append(cmd))
    monkeypatch.setattr(o, "_wait_response", lambda t, timeout = 300.0: {"type": "unloaded"})
    monkeypatch.setattr(o, "_drain_queue", lambda: [])

    o.active_model_name = "unsloth/Qwen3-4B"
    o.models = {"unsloth/Qwen3-4B": {}}

    assert o.unload_model("unsloth/qwen3-4b") is True
    assert {"type": "unload", "model_name": "unsloth/Qwen3-4B"} in sent
    assert o.active_model_name is None
    assert o.models == {}


def test_unload_of_stale_name_still_no_ops_after_case_insensitive_match(monkeypatch):
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("must not send an unload for a stale model name")
    )
    o.active_model_name = "unsloth/Qwen3-4B"
    o.models = {"unsloth/Qwen3-4B": {}}

    assert o.unload_model("unsloth/Llama-3.1-8B") is True
    assert o.active_model_name == "unsloth/Qwen3-4B"
    assert "unsloth/Qwen3-4B" in o.models


def test_load_does_not_accumulate_stale_models_defeating_the_unload_guard(monkeypatch):
    # Each load spawns a fresh subprocess, so self.models must not accumulate old names.

    from utils import transformers_version as _tv
    import types

    o = _bare_orchestrator()
    o.active_model_name = None
    o.models = {}

    monkeypatch.setattr(_tv, "needs_transformers_5", lambda name: False)
    monkeypatch.setattr(orch_mod, "prepare_gpu_selection", lambda *a, **k: ([], {}))
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(o, "_shutdown_subprocess", lambda *a, **k: None)
    monkeypatch.setattr(o, "_spawn_subprocess", lambda cfg: None)
    monkeypatch.setattr(orch_mod.time, "sleep", lambda *_a, **_k: None)

    def _load(name):
        monkeypatch.setattr(
            o,
            "_wait_response",
            lambda expected, timeout = 300.0: {
                "type": "loaded",
                "success": True,
                "model_info": {"identifier": name, "display_name": name},
            },
        )
        assert o.load_model(types.SimpleNamespace(identifier = name, gguf_variant = None)) is True

    _load("modelA")
    _load("modelB")

    assert o.active_model_name == "modelB"
    assert set(o.models) == {"modelB"}

    monkeypatch.setattr(o, "_send_cmd", lambda cmd: pytest.fail("stale unload reached the worker"))
    assert o.unload_model("modelA") is True
    assert o.active_model_name == "modelB"
    assert "modelB" in o.models


def test_unload_route_serializes_with_loads_via_lifecycle_gate(monkeypatch):
    from models.inference import LoadRequest, UnloadRequest
    import asyncio
    import routes.inference as inference_route

    from core.inference import llama_keepwarm as kw
    from models.inference import UnloadRequest

    monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _Llama())
    monkeypatch.setattr(inference_route, "is_registered_native_path_label", lambda *a: False)

    unloaded: list = []

    class _Backend:
        active_model_name = "m"
        models = {"m": {}}

        def unload_model(self, name):
            unloaded.append(name)
            return True

    monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _Backend())

    async def scenario():
        assert kw._lifecycle_lock.acquire(blocking = False)
        try:
            task = asyncio.ensure_future(
                inference_route.unload_model(UnloadRequest(model_path = "m"), "tester")
            )
            for _ in range(10):
                await asyncio.sleep(0.01)
            assert unloaded == [], "unload ran while the lifecycle gate was held"
            assert not task.done()
        finally:
            kw._lifecycle_lock.release()
        resp = await task
        assert resp.status == "unloaded"
        assert unloaded == ["m"]

    asyncio.run(scenario())


def test_cancel_load_terminates_loading_subprocess_and_sends_no_command(monkeypatch):
    o = _bare_orchestrator()
    o.loading_models = {"m"}
    o.active_model_name = None
    o.models = {}
    shutdown = []
    monkeypatch.setattr(o, "_shutdown_subprocess", lambda timeout = 5: shutdown.append(timeout))
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("cancel_load must not send a worker command")
    )

    assert o.cancel_load("m") is True
    assert shutdown, "must tear the loading subprocess down"
    assert "m" not in o.loading_models
    assert o.active_model_name is None
    assert o.cancel_load("other") is False


def test_cancel_load_matches_loading_model_case_insensitively(monkeypatch):
    o = _bare_orchestrator()
    o.loading_models = {"unsloth/Qwen3-4B"}
    monkeypatch.setattr(o, "_shutdown_subprocess", lambda timeout = 5: None)

    assert o.cancel_load("unsloth/qwen3-4b") is True
    assert o.loading_models == set()


def test_unload_model_cancels_a_loading_model_via_cancel_load(monkeypatch):
    o = _bare_orchestrator()
    o.loading_models = {"m"}
    o.active_model_name = None
    shutdown = []
    monkeypatch.setattr(o, "_shutdown_subprocess", lambda timeout = 5: shutdown.append(timeout))
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("must not send a command to cancel a load")
    )

    assert o.unload_model("m") is True
    assert shutdown
    assert "m" not in o.loading_models


def test_unload_route_cancels_in_flight_load_without_waiting_on_gate(monkeypatch):
    # /load holds the gate for the whole load, so Stop-loading must cancel off-gate.

    from models.inference import LoadRequest, UnloadRequest
    import asyncio
    import routes.inference as inference_route

    from core.inference import llama_keepwarm as kw
    from models.inference import UnloadRequest

    monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _Llama())
    monkeypatch.setattr(inference_route, "is_registered_native_path_label", lambda *a: False)

    cancelled: list = []

    class _Backend:
        active_model_name = None
        models: dict = {}

        def get_loading_model(self):
            return "m"

        def cancel_load(self, name):
            cancelled.append(name)
            return True

        def unload_model(self, name):
            pytest.fail("must not take the gated unload path for a still-loading model")

    monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _Backend())

    async def scenario():
        assert kw._lifecycle_lock.acquire(blocking = False)
        try:
            resp = await inference_route.unload_model(UnloadRequest(model_path = "m"), "tester")
            assert resp.status == "unloaded"
            assert cancelled == ["m"]
        finally:
            kw._lifecycle_lock.release()

    asyncio.run(scenario())


def test_scoped_unload_cancels_only_its_running_standard_load(monkeypatch):
    from models.inference import LoadRequest, UnloadRequest
    import asyncio
    import routes.inference as inference_route

    cancelled = []

    class _Backend:
        def get_loading_model(self):
            return "m"

        def cancel_load(self, name):
            cancelled.append(name)
            return True

    monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _Backend())
    monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _Llama())
    attempt = inference_route._begin_load_attempt(
        LoadRequest(model_path = "m", load_request_id = "audio-load-1"), "tester"
    )
    with inference_route._scoped_load_attempts_lock:
        inference_route._running_load_attempt = attempt
    try:
        response = asyncio.run(
            inference_route._unload_model_impl(
                UnloadRequest(model_path = "m", cancel_load_request_id = "audio-load-1"),
                "tester",
            )
        )
        assert response.status == "unloaded"
        assert cancelled == ["m"]
        assert attempt.cancel_event.is_set()
    finally:
        with inference_route._scoped_load_attempts_lock:
            inference_route._running_load_attempt = None
        inference_route._finish_load_attempt(attempt)


def test_scoped_unload_cannot_cancel_a_newer_same_model_load(monkeypatch):
    from models.inference import LoadRequest, UnloadRequest
    import asyncio
    import routes.inference as inference_route

    def _unexpected_backend():
        pytest.fail("a stale scoped cancel must not inspect or mutate any backend")

    monkeypatch.setattr(inference_route, "get_inference_backend", _unexpected_backend)
    monkeypatch.setattr(inference_route, "get_llama_cpp_backend", _unexpected_backend)
    newer = inference_route._begin_load_attempt(
        LoadRequest(model_path = "m", load_request_id = "audio-load-new"), "tester"
    )
    with inference_route._scoped_load_attempts_lock:
        inference_route._running_load_attempt = newer
    try:
        response = asyncio.run(
            inference_route._unload_model_impl(
                UnloadRequest(model_path = "m", cancel_load_request_id = "audio-load-old"),
                "tester",
            )
        )
        assert response.status == "unloaded"
        assert not newer.cancel_event.is_set()
    finally:
        with inference_route._scoped_load_attempts_lock:
            inference_route._running_load_attempt = None
        inference_route._finish_load_attempt(newer)


def test_scoped_cancel_before_load_registration_is_consumed(monkeypatch):
    from fastapi import HTTPException
    from models.inference import LoadRequest, UnloadRequest
    import asyncio
    import routes.inference as inference_route

    def _unexpected_backend():
        pytest.fail("cancel-first cleanup must not inspect a backend")

    async def _unexpected_load(*_args, **_kwargs):
        pytest.fail("a tombstoned load must not reach the load implementation")

    monkeypatch.setattr(inference_route, "get_inference_backend", _unexpected_backend)
    monkeypatch.setattr(inference_route, "get_llama_cpp_backend", _unexpected_backend)
    monkeypatch.setattr(inference_route, "_load_model_impl", _unexpected_load)
    response = asyncio.run(
        inference_route._unload_model_impl(
            UnloadRequest(model_path = "m", cancel_load_request_id = "audio-cancel-first"),
            "tester",
        )
    )
    assert response.status == "unloaded"

    request = LoadRequest(model_path = "m", load_request_id = "audio-cancel-first")
    attempt = inference_route._begin_load_attempt(request, "tester")
    try:
        assert attempt.cancel_event.is_set()
        assert attempt.cancel_complete.is_set()
        with pytest.raises(HTTPException, match = "cancelled"):
            asyncio.run(
                inference_route._run_tracked_load_model_impl(
                    request, object(), "tester", attempt = attempt
                )
            )
    finally:
        inference_route._finish_load_attempt(attempt)


def test_scoped_cancel_holds_load_ownership_until_backend_cancel_finishes(monkeypatch):
    from core.inference import llama_keepwarm
    from fastapi import HTTPException
    from models.inference import LoadRequest, UnloadRequest
    import asyncio
    import routes.inference as inference_route

    backend_cancel_entered = threading.Event()
    release_backend_cancel = threading.Event()

    class _Backend:
        def get_loading_model(self):
            return None

    def _get_backend():
        backend_cancel_entered.set()
        assert release_backend_cancel.wait(timeout = 5)
        return _Backend()

    monkeypatch.setattr(inference_route, "get_inference_backend", _get_backend)
    # Routing peeks for a dead worker; only the cancel may reach the blocking getter.
    monkeypatch.setattr(inference_route, "_peek_inference_backend", lambda: None)
    monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _Llama())
    monkeypatch.setattr(inference_route, "_raise_if_sidecar_swap_in_progress", lambda: None)

    async def scenario():
        gate = asyncio.Lock()
        first_started = asyncio.Event()
        second_started = asyncio.Event()

        class _Gate:
            async def __aenter__(self):
                await gate.acquire()

            async def __aexit__(self, *_args):
                gate.release()

        monkeypatch.setattr(llama_keepwarm, "inference_lifecycle_gate", lambda: _Gate())

        async def _fake_load(
            request,
            *_args,
            load_cancel_event = None,
            **_kwargs,
        ):
            if request.load_request_id == "audio-race-a":
                first_started.set()
                await asyncio.to_thread(load_cancel_event.wait)
                raise HTTPException(status_code = 409, detail = "Model load cancelled")
            second_started.set()
            return {"status": "loaded", "model": request.model_path}

        monkeypatch.setattr(inference_route, "_load_model_impl", _fake_load)
        first = asyncio.create_task(
            inference_route.load_model_gated(
                LoadRequest(model_path = "m", load_request_id = "audio-race-a"),
                object(),
                "tester",
            )
        )
        await first_started.wait()
        cancel = asyncio.create_task(
            inference_route._unload_model_impl(
                UnloadRequest(model_path = "m", cancel_load_request_id = "audio-race-a"),
                "tester",
            )
        )
        await asyncio.to_thread(backend_cancel_entered.wait, 5)

        second = asyncio.create_task(
            inference_route.load_model_gated(
                LoadRequest(model_path = "m", load_request_id = "audio-race-b"),
                object(),
                "tester",
            )
        )
        await asyncio.sleep(0.05)
        assert not second_started.is_set(), "newer load entered before A's cancel completed"

        release_backend_cancel.set()
        assert (await cancel).status == "unloaded"
        with pytest.raises(HTTPException, match = "cancelled"):
            await first
        assert (await second)["status"] == "loaded"

    asyncio.run(scenario())


def test_scoped_unload_of_queued_attempt_never_unloads_or_deadlocks(monkeypatch):
    from fastapi import HTTPException
    from models.inference import LoadRequest, UnloadRequest
    import asyncio
    import routes.inference as inference_route

    def _unexpected_backend():
        pytest.fail("cancel-only cleanup must never unload a resident model")

    monkeypatch.setattr(inference_route, "get_inference_backend", _unexpected_backend)
    monkeypatch.setattr(inference_route, "get_llama_cpp_backend", _unexpected_backend)

    async def _unexpected_load(*_args, **_kwargs):
        pytest.fail("a cancelled queued attempt must not reach backend load work")

    monkeypatch.setattr(inference_route, "_load_model_impl", _unexpected_load)
    attempt = inference_route._begin_load_attempt(
        LoadRequest(model_path = "m", load_request_id = "audio-load-done"), "tester"
    )
    try:
        response = asyncio.run(
            inference_route._unload_model_impl(
                UnloadRequest(model_path = "m", cancel_load_request_id = "audio-load-done"),
                "tester",
            )
        )
        assert response.status == "unloaded"
        assert attempt.cancel_event.is_set()
        assert attempt.cancel_complete.is_set()
        with pytest.raises(HTTPException, match = "cancelled"):
            asyncio.run(
                asyncio.wait_for(
                    inference_route._run_tracked_load_model_impl(
                        LoadRequest(model_path = "m", load_request_id = "audio-load-done"),
                        object(),
                        "tester",
                        attempt = attempt,
                    ),
                    timeout = 1,
                )
            )
    finally:
        inference_route._finish_load_attempt(attempt)


def test_scoped_unload_cancels_only_its_running_gguf_load(monkeypatch):
    from models.inference import LoadRequest, UnloadRequest
    import asyncio
    import routes.inference as inference_route

    class _Backend:
        def get_loading_model(self):
            return None

    class _Llama:
        is_active = True
        is_loaded = False
        model_identifier = "m"

        def __init__(self):
            self.unloaded = False

        def unload_model(self):
            self.unloaded = True

    llama = _Llama()
    monkeypatch.setattr(inference_route, "get_inference_backend", lambda: _Backend())
    monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: llama)
    monkeypatch.setattr(inference_route, "is_registered_native_path_label", lambda *a: False)
    attempt = inference_route._begin_load_attempt(
        LoadRequest(model_path = "m", load_request_id = "audio-gguf-1"), "tester"
    )
    with inference_route._scoped_load_attempts_lock:
        inference_route._running_load_attempt = attempt
    try:
        response = asyncio.run(
            inference_route._unload_model_impl(
                UnloadRequest(model_path = "m", cancel_load_request_id = "audio-gguf-1"),
                "tester",
            )
        )
        assert response.status == "unloaded"
        assert llama.unloaded is True
    finally:
        with inference_route._scoped_load_attempts_lock:
            inference_route._running_load_attempt = None
        inference_route._finish_load_attempt(attempt)


def test_standard_load_honors_scoped_cancel_before_worker_start():
    from types import SimpleNamespace

    attempt_cancelled = threading.Event()
    attempt_cancelled.set()
    orchestrator = _bare_orchestrator()

    assert (
        orchestrator.load_model(
            SimpleNamespace(identifier = "m"), load_cancel_event = attempt_cancelled
        )
        is False
    )
    assert orchestrator.loading_models == set()


def test_gguf_load_cancellation_includes_the_backend_unload_event():
    import asyncio
    import routes.inference as inference_route

    from core.inference.llama_cpp import GgufDownloadCancelled

    class _Llama:
        def load_cancelled(self):
            return True

    assert inference_route._gguf_load_cancelled(_Llama(), threading.Event()) is True

    scoped = threading.Event()

    class _CancellingLlama:
        def load_cancelled(self):
            return False

        def load_model(self, *, intent, load_cancel_event):
            load_cancel_event.set()
            raise GgufDownloadCancelled("Cancelled")

    assert (
        asyncio.run(
            inference_route._run_gguf_load_attempt(
                _CancellingLlama(),
                object(),
                scoped,
            )
        )
        is False
    )


def test_cancelled_gguf_download_uses_the_typed_signal():
    from core.inference.llama_cpp import GgufDownloadCancelled, LlamaCppBackend

    cancelled = threading.Event()
    cancelled.set()
    with pytest.raises(GgufDownloadCancelled):
        LlamaCppBackend()._download_gguf(
            hf_repo = "owner/model-GGUF",
            cancel_event = cancelled,
        )


def test_gguf_load_attempt_does_not_hide_a_real_resolver_failure():
    import asyncio
    import routes.inference as inference_route

    class _Llama:
        def load_cancelled(self):
            return True

        def load_model(self, *, intent, load_cancel_event):
            raise RuntimeError("resolver failed")

    with pytest.raises(RuntimeError, match = "resolver failed"):
        asyncio.run(
            inference_route._run_gguf_load_attempt(
                _Llama(),
                object(),
                threading.Event(),
            )
        )


def test_a_codec_missing_on_modelscope_stays_with_the_load_that_hit_it():
    import asyncio
    import routes.inference as inference_route
    from unittest import mock
    from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend
    from hub.utils.hf_errors import not_on_modelscope

    llama = LlamaCppBackend()
    llama._codec_failure.message, llama._llama_update_in_progress = "x", True
    pytest.raises(RuntimeError, llama.load_model, intent = GgufLoadIntent(model_identifier = "o/m"))
    assert llama.codec_failure() is None
    llama._healthy, failures = True, []
    llama.init_audio_codec = mock.Mock(side_effect = OSError(not_on_modelscope("o/c")))
    llama.load_model = lambda **_: llama._apply_detected_audio("snac")
    run = inference_route._run_gguf_load_attempt(llama, object(), threading.Event(), failures)
    assert asyncio.run(run) is False and failures == [not_on_modelscope("o/c")]
    assert llama.codec_failure() is None


def test_stale_unload_does_not_hide_an_update_refusal():
    import asyncio
    import routes.inference as inference_route

    from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend

    llama = LlamaCppBackend()
    llama._cancel_event.set()
    llama._llama_update_in_progress = True

    with pytest.raises(RuntimeError, match = "llama.cpp is updating"):
        asyncio.run(
            inference_route._run_gguf_load_attempt(
                llama,
                GgufLoadIntent(model_identifier = "owner/model"),
                threading.Event(),
            )
        )


def test_dispatched_bails_when_unload_flips_before_mailbox_registration(monkeypatch):
    # An unload set after the pre-work check must make the request bail, or its mailbox orphans.
    o = _bare_orchestrator()
    o._mailbox_lock = threading.Lock()
    o._mailboxes = {}
    o._request_cancel_events = {}
    o._unload_pending = False
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(o, "_start_dispatcher", lambda: None)

    def flip(*a, **k):
        o._unload_pending = True
        return {"type": "generate", "request_id": "r1"}

    monkeypatch.setattr(o, "_build_generate_cmd", flip)
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("must not send generate after the unload flipped")
    )

    out = list(o._generate_dispatched(messages = [{"role": "user", "content": "hi"}]))

    assert any("unloaded" in chunk.lower() for chunk in out)
    assert o._mailboxes == {}, "must not leave an orphaned mailbox"


class _AliveDispatcher:
    """Stand-in dispatcher thread that reports itself alive."""

    def is_alive(self):
        return True


def test_dispatched_bails_when_model_swapped_before_mailbox_registration(monkeypatch):
    o = _bare_orchestrator()
    o._mailbox_lock = threading.Lock()
    o._mailboxes = {}
    o._request_cancel_events = {}
    o._unload_pending = False
    o._dispatcher_thread = _AliveDispatcher()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(o, "_start_dispatcher", lambda: None)

    def swap(*a, **k):
        o.active_model_name = "other"
        return {"type": "generate", "request_id": "r1"}

    monkeypatch.setattr(o, "_build_generate_cmd", swap)
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("must not generate on the swapped-in model")
    )

    out = list(o._generate_dispatched(messages = [{"role": "user", "content": "hi"}]))

    assert any("unloaded" in chunk.lower() for chunk in out)
    assert o._mailboxes == {}, "must not leave an orphaned mailbox"


def test_dispatched_bails_when_dispatcher_stopped_before_mailbox_registration(monkeypatch):
    monkeypatch.setattr(orch_mod, "_DISPATCH_IDLE_TIMEOUT", 0.05)
    o = _bare_orchestrator()
    o._mailbox_lock = threading.Lock()
    o._mailboxes = {}
    o._request_cancel_events = {}
    o._unload_pending = False
    o._dispatcher_thread = _AliveDispatcher()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(o, "_start_dispatcher", lambda: None)

    def stop_dispatcher(*a, **k):
        o._dispatcher_thread = None
        return {"type": "generate", "request_id": "r1"}

    monkeypatch.setattr(o, "_build_generate_cmd", stop_dispatcher)
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("must not generate with the dispatcher stopped")
    )

    out = list(o._generate_dispatched(messages = [{"role": "user", "content": "hi"}]))

    assert any("nothing is routing replies" in chunk.lower() for chunk in out), out
    assert o._mailboxes == {}, "must not leave an orphaned mailbox"


def test_dispatched_happy_path_registers_and_sends(monkeypatch):
    o = _bare_orchestrator()
    o._mailbox_lock = threading.Lock()
    o._mailboxes = {}
    o._request_cancel_events = {}
    o._unload_pending = False
    o._dispatcher_thread = _AliveDispatcher()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(o, "_start_dispatcher", lambda: None)
    monkeypatch.setattr(
        o, "_build_generate_cmd", lambda *a, **k: {"type": "generate", "request_id": "r1"}
    )
    sent = []
    monkeypatch.setattr(o, "_send_cmd", lambda cmd: sent.append(cmd))

    def fake_consume(read_mailbox, drainer, **k):
        mbox = o._mailboxes.get("r1")
        if mbox is not None:
            mbox.put({"type": "gen_done", "request_id": "r1"})
        yield ""

    monkeypatch.setattr(o, "_consume_token_stream", fake_consume)

    list(o._generate_dispatched(messages = [{"role": "user", "content": "hi"}]))

    assert sent, "happy path must send the generate command"
    assert o._mailboxes == {}, "mailbox popped in finally"


def test_load_model_aborts_when_cancelled_before_spawn(monkeypatch):
    # cancel_load during GPU placement has no child to kill; load_model must not spawn.
    from utils import transformers_version as tv

    o = _bare_orchestrator()
    o.active_model_name = None
    o.models = {}
    o.loading_models = set()
    o._proc = None
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: False)
    monkeypatch.setattr(o, "_shutdown_subprocess", lambda *a, **k: None)
    monkeypatch.setattr(
        o, "_spawn_subprocess", lambda cfg: pytest.fail("must not spawn a worker after a cancel")
    )

    import utils.transformers_version as tv

    monkeypatch.setattr(tv, "needs_transformers_5", lambda name: False)

    def cancel_during_gpu(gpu_ids, **k):
        o.loading_models.discard("m")
        return ([0], "sel")

    monkeypatch.setattr(orch_mod, "prepare_gpu_selection", cancel_during_gpu)

    class _Cfg:
        identifier = "m"

    ok = o.load_model(_Cfg())

    assert ok is False
    assert o.active_model_name is None
    assert o.models == {}


def test_load_model_aborts_when_old_worker_survives_shutdown(monkeypatch):
    # A wedged worker outliving kill: do not spawn a second worker over it.

    from utils import transformers_version as tv
    import types

    o = _bare_orchestrator()
    o.active_model_name = "old"
    o.models = {"old": {}}
    o.loading_models = set()
    monkeypatch.setattr(tv, "needs_transformers_5", lambda name: False)
    monkeypatch.setattr(orch_mod, "prepare_gpu_selection", lambda *a, **k: ([0], "sel"))
    monkeypatch.setattr(orch_mod.time, "sleep", lambda *_a, **_k: None)
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(o, "_cancel_generation", lambda: None)
    monkeypatch.setattr(o, "_shutdown_subprocess", lambda *a, **k: False)
    monkeypatch.setattr(
        o, "_spawn_subprocess", lambda cfg: pytest.fail("must not spawn over a live survivor")
    )

    with pytest.raises(RuntimeError, match = "did not exit"):
        o.load_model(types.SimpleNamespace(identifier = "new", gguf_variant = None))
    assert "new" not in o.loading_models
    assert o.active_model_name is None


def test_load_model_proceeds_when_not_cancelled(monkeypatch):
    from utils import transformers_version as tv

    o = _bare_orchestrator()
    o.active_model_name = None
    o.models = {}
    o.loading_models = set()
    o._proc = None
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: False)
    monkeypatch.setattr(o, "_shutdown_subprocess", lambda *a, **k: None)

    spawned = []
    monkeypatch.setattr(o, "_spawn_subprocess", lambda cfg: spawned.append(cfg))
    monkeypatch.setattr(
        o,
        "_wait_response",
        lambda t, timeout = 300.0: {"success": True, "model_info": {"identifier": "m"}},
    )

    import utils.transformers_version as tv

    monkeypatch.setattr(tv, "needs_transformers_5", lambda name: False)
    monkeypatch.setattr(orch_mod, "prepare_gpu_selection", lambda gpu_ids, **k: ([0], "sel"))

    class _Cfg:
        identifier = "m"

    ok = o.load_model(_Cfg())

    assert ok is True
    assert spawned, "uncancelled load must spawn a worker"
    assert o.active_model_name == "m"


def test_load_model_reaps_worker_after_inactivity_timeout(monkeypatch):
    from utils import transformers_version as tv
    import types

    o = _bare_orchestrator()
    o.active_model_name = None
    o.models = {}
    o.loading_models = set()
    o._proc = None
    shutdowns = []
    monkeypatch.setattr(tv, "needs_transformers_5", lambda name: False)
    monkeypatch.setattr(orch_mod, "prepare_gpu_selection", lambda *a, **k: ([0], "sel"))
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: False)
    monkeypatch.setattr(o, "_spawn_subprocess", lambda cfg: None)
    monkeypatch.setattr(
        o,
        "_shutdown_subprocess",
        lambda timeout = 5: shutdowns.append(timeout) or True,
    )
    monkeypatch.setattr(
        o,
        "_wait_response",
        lambda t, timeout = 300.0: (_ for _ in ()).throw(
            RuntimeError("Timeout waiting for 'loaded' response (no activity for 300.0s)")
        ),
    )

    with pytest.raises(RuntimeError, match = "Timeout waiting for 'loaded'"):
        o.load_model(types.SimpleNamespace(identifier = "m", gguf_variant = None))

    assert shutdowns, "failed load must reap the worker after the inactivity timeout"
    assert o.active_model_name is None
    assert o.models == {}
    assert "m" not in o.loading_models


def test_worker_reported_load_failure_reaps_worker(monkeypatch):
    from utils import transformers_version as tv
    import types

    o = _bare_orchestrator()
    o.active_model_name = None
    o.models = {}
    o.loading_models = set()
    o._proc = None
    shutdowns = []
    monkeypatch.setattr(tv, "needs_transformers_5", lambda name: False)
    monkeypatch.setattr(orch_mod, "prepare_gpu_selection", lambda *a, **k: ([0], "sel"))
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: False)
    monkeypatch.setattr(o, "_spawn_subprocess", lambda cfg: None)
    monkeypatch.setattr(
        o,
        "_shutdown_subprocess",
        lambda timeout = 5: shutdowns.append(timeout) or True,
    )
    monkeypatch.setattr(
        o,
        "_wait_response",
        lambda t, timeout = 300.0: {"success": False, "message": "real worker load failure"},
    )

    with pytest.raises(Exception, match = "real worker load failure"):
        o.load_model(types.SimpleNamespace(identifier = "m", gguf_variant = None))

    assert shutdowns == [5]
    assert "m" not in o.loading_models


def test_failed_load_keeps_timeout_after_cancel_teardown(monkeypatch):
    from utils import transformers_version as tv
    import types

    o = _bare_orchestrator()
    o.active_model_name = None
    o.models = {}
    o.loading_models = set()
    o._proc = None

    monkeypatch.setattr(tv, "needs_transformers_5", lambda name: False)
    monkeypatch.setattr(orch_mod, "prepare_gpu_selection", lambda *a, **k: ([0], "sel"))
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: False)
    monkeypatch.setattr(o, "_spawn_subprocess", lambda cfg: None)

    parked = threading.Event()
    release_timeout = threading.Event()
    load_done = threading.Event()
    shutdowns = []

    def blocking_wait_response(expected, timeout = 300.0):
        parked.set()
        assert release_timeout.wait(timeout = 5)
        raise RuntimeError("Timeout waiting for 'loaded' response (no activity for 300.0s)")

    def record_shutdown(timeout = 5):
        shutdowns.append(timeout)
        o._cmd_queue = None

    monkeypatch.setattr(o, "_wait_response", blocking_wait_response)
    monkeypatch.setattr(o, "_shutdown_subprocess", record_shutdown)

    load_result: dict = {}

    def run_load():
        try:
            load_result["ok"] = o.load_model(
                types.SimpleNamespace(identifier = "m", gguf_variant = None)
            )
        except Exception as exc:  # noqa: BLE001
            load_result["exc"] = exc
        finally:
            load_done.set()

    loader = threading.Thread(target = run_load)
    loader.start()
    assert parked.wait(timeout = 5), "load_model must reach _wait_response"

    assert o.cancel_load("m") is True
    release_timeout.set()
    loader.join(timeout = 5)
    assert load_done.is_set()

    assert isinstance(load_result.get("exc"), RuntimeError), load_result
    assert "Timeout waiting for 'loaded'" in str(load_result["exc"])
    assert shutdowns == [0.5, 5]
    assert o.active_model_name is None
    assert o.models == {}
    assert "m" not in o.loading_models


def test_failed_load_keeps_the_timeout_when_teardown_raises(monkeypatch):
    from utils import transformers_version as tv
    import types

    o = _bare_orchestrator()
    o.active_model_name = None
    o.models = {}
    o.loading_models = set()
    o._proc = None

    monkeypatch.setattr(tv, "needs_transformers_5", lambda name: False)
    monkeypatch.setattr(orch_mod, "prepare_gpu_selection", lambda *a, **k: ([0], "sel"))
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: False)
    monkeypatch.setattr(o, "_spawn_subprocess", lambda cfg: None)
    monkeypatch.setattr(
        o,
        "_shutdown_subprocess",
        lambda timeout = 5: (_ for _ in ()).throw(
            AttributeError("'NoneType' object has no attribute 'put'")
        ),
    )
    monkeypatch.setattr(
        o,
        "_wait_response",
        lambda t, timeout = 300.0: (_ for _ in ()).throw(
            RuntimeError("Timeout waiting for 'loaded' response (no activity for 300.0s)")
        ),
    )

    with pytest.raises(RuntimeError, match = "Timeout waiting for 'loaded'"):
        o.load_model(types.SimpleNamespace(identifier = "m", gguf_variant = None))

    assert o.active_model_name is None
    assert o.models == {}
    assert "m" not in o.loading_models


def test_load_model_aborts_when_cancelled_during_spawn(monkeypatch):
    # Cancel can land while _spawn_subprocess runs (teardown no-ops); recheck after spawn.

    from utils import transformers_version as tv
    import types

    o = _bare_orchestrator()
    o.active_model_name = None
    o.models = {}
    o.loading_models = {"m"}
    o._proc = None
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: False)
    monkeypatch.setattr(tv, "needs_transformers_5", lambda name: False)
    monkeypatch.setattr(orch_mod, "prepare_gpu_selection", lambda gpu_ids, **k: ([0], "sel"))

    def spawn_then_cancel(cfg):
        o.loading_models.discard("m")

    monkeypatch.setattr(o, "_spawn_subprocess", spawn_then_cancel)

    shutdown = []
    monkeypatch.setattr(o, "_shutdown_subprocess", lambda timeout = 5: shutdown.append(timeout))
    monkeypatch.setattr(
        o,
        "_wait_response",
        lambda t, timeout = 300.0: pytest.fail(
            "must not wait for 'loaded' after a cancel during spawn"
        ),
    )

    ok = o.load_model(types.SimpleNamespace(identifier = "m", gguf_variant = None))

    assert ok is False
    assert shutdown, "must tear the orphaned worker down"
    assert o.active_model_name is None
    assert o.models == {}
    assert "m" not in o.loading_models


def test_unload_cancels_loading_gguf_off_gate(monkeypatch):
    from core.inference import llama_keepwarm
    import asyncio as _asyncio
    import routes.inference as ri

    gate_entered = {"v": False}

    class _Gate:
        async def __aenter__(self):
            gate_entered["v"] = True
            return self

        async def __aexit__(self, *a):
            return False

    class _LlamaBackend:
        is_active = True
        is_loaded = False
        model_identifier = "gguf-model"

        def __init__(self):
            self.unloaded = False

        def unload_model(self):
            self.unloaded = True

    llama = _LlamaBackend()

    monkeypatch.setattr(ri, "get_llama_cpp_backend", lambda: llama)
    monkeypatch.setattr(ri, "get_inference_backend", lambda: _Unsloth())
    monkeypatch.setattr(llama_keepwarm, "inference_lifecycle_gate", lambda: _Gate())
    monkeypatch.setattr(llama_keepwarm, "note_model_unloaded", lambda: None)

    req = ri.UnloadRequest(model_path = "gguf-model")
    resp = _asyncio.run(ri.unload_model(req, current_subject = "s"))

    assert getattr(resp, "status", None) == "unloaded"
    assert llama.unloaded is True, "must cancel the loading GGUF via unload_model()"
    assert gate_entered["v"] is False, "must handle the loading GGUF off the lifecycle gate"


def test_unload_loaded_gguf_still_uses_gate(monkeypatch):
    from core.inference import llama_keepwarm
    import asyncio as _asyncio
    import routes.inference as ri

    gate_entered = {"v": False}

    class _Gate:
        async def __aenter__(self):
            gate_entered["v"] = True
            return self

        async def __aexit__(self, *a):
            return False

    class _LlamaBackend:
        is_active = True
        is_loaded = True
        model_identifier = "gguf-model"

        def __init__(self):
            self.unloaded = False

        def unload_model(self):
            self.unloaded = True

    llama = _LlamaBackend()

    monkeypatch.setattr(ri, "get_llama_cpp_backend", lambda: llama)
    monkeypatch.setattr(ri, "get_inference_backend", lambda: _Unsloth())
    monkeypatch.setattr(ri, "is_registered_native_path_label", lambda a, b: False)
    monkeypatch.setattr(llama_keepwarm, "inference_lifecycle_gate", lambda: _Gate())
    monkeypatch.setattr(llama_keepwarm, "note_model_unloaded", lambda: None)

    req = ri.UnloadRequest(model_path = "gguf-model")
    resp = _asyncio.run(ri.unload_model(req, current_subject = "s"))

    assert getattr(resp, "status", None) == "unloaded"
    assert llama.unloaded is True
    assert gate_entered["v"] is True, "loaded GGUF unload must still take the gate"


def test_unload_of_mismatched_loading_gguf_skips_off_gate_fast_path(monkeypatch):
    # The off-gate fast path means 'stop loading THIS model'; another target must use the gate.

    from core.inference import llama_keepwarm
    import asyncio as _asyncio
    import routes.inference as ri

    gate_entered = {"v": False}

    class _Gate:
        async def __aenter__(self):
            gate_entered["v"] = True
            return self

        async def __aexit__(self, *a):
            return False

    class _LlamaBackend:
        is_active = True
        is_loaded = False
        model_identifier = "gguf-X"

        def __init__(self):
            self.unloaded = False

        def unload_model(self):
            self.unloaded = True

    llama = _LlamaBackend()

    monkeypatch.setattr(ri, "get_llama_cpp_backend", lambda: llama)
    monkeypatch.setattr(ri, "get_inference_backend", lambda: _Unsloth())
    monkeypatch.setattr(ri, "is_registered_native_path_label", lambda a, b: False)
    monkeypatch.setattr(llama_keepwarm, "inference_lifecycle_gate", lambda: _Gate())
    monkeypatch.setattr(llama_keepwarm, "note_model_unloaded", lambda: None)

    req = ri.UnloadRequest(model_path = "gguf-Y")
    _asyncio.run(ri.unload_model(req, current_subject = "s"))

    assert gate_entered["v"] is True, (
        "a mismatched-target unload must not use the off-gate GGUF fast path; "
        "it would cancel the wrong in-flight load"
    )


def test_cancel_load_clears_marker_before_shutdown(monkeypatch):
    # Clear the marker before the blocking teardown, or a racing load passes its recheck.
    o = _bare_orchestrator()
    o.loading_models = {"m"}
    o.active_model_name = "m"
    o.models = {"m": {}}

    at_shutdown = {}

    def record_shutdown(timeout = 5):
        at_shutdown["marker_present"] = "m" in o.loading_models
        at_shutdown["active"] = o.active_model_name
        at_shutdown["models"] = dict(o.models)

    monkeypatch.setattr(o, "_shutdown_subprocess", record_shutdown)
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("cancel_load must not send a worker command")
    )

    assert o.cancel_load("m") is True
    assert at_shutdown.get("marker_present") is False, (
        "the loading marker must be cleared before _shutdown_subprocess so a concurrent "
        "load_model pre-spawn recheck observes the cancel during the shutdown window"
    )
    assert at_shutdown.get("active") is None
    assert at_shutdown.get("models") == {}
    assert "m" not in o.loading_models
    assert o.active_model_name is None
    assert o.models == {}


def test_cancel_load_reclears_state_when_racing_load_repopulates_during_teardown(monkeypatch):
    # A racing load can consume 'loaded' during teardown; cancel_load must re-clear after it.

    from utils import transformers_version as _tv
    import types

    o = _bare_orchestrator()
    o.loading_models = {"m"}
    o.active_model_name = None
    o.models = {}
    o._proc = None

    monkeypatch.setattr(_tv, "needs_transformers_5", lambda name: False)
    monkeypatch.setattr(orch_mod, "prepare_gpu_selection", lambda *a, **k: ([], {}))
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: False)
    monkeypatch.setattr(o, "_spawn_subprocess", lambda cfg: None)

    parked = threading.Event()
    release_loaded = threading.Event()
    load_done = threading.Event()

    def blocking_wait_response(expected, timeout = 300.0):
        parked.set()
        assert release_loaded.wait(timeout = 5)
        return {
            "type": "loaded",
            "success": True,
            "model_info": {"identifier": "m", "display_name": "m"},
        }

    monkeypatch.setattr(o, "_wait_response", blocking_wait_response)

    load_result: dict = {}

    def run_load():
        try:
            load_result["ok"] = o.load_model(
                types.SimpleNamespace(identifier = "m", gguf_variant = None)
            )
        except Exception as exc:  # noqa: BLE001
            load_result["exc"] = exc
        finally:
            load_done.set()

    loader = threading.Thread(target = run_load)
    loader.start()
    assert parked.wait(timeout = 5), "load_model must reach _wait_response"

    def racing_shutdown(timeout = 0.5):
        release_loaded.set()
        assert load_done.wait(timeout = 5), "the racing load must repopulate during teardown"

    monkeypatch.setattr(o, "_shutdown_subprocess", racing_shutdown)

    assert o.cancel_load("m") is True
    loader.join(timeout = 5)

    assert o.active_model_name is None, "cancel_load must not leave a repopulated active model"
    assert o.models == {}, "cancel_load must not leave a repopulated models mirror"
    assert "m" not in o.loading_models


def test_dispatched_bail_stops_orphan_dispatcher_it_started(monkeypatch):
    # A bail must stop the dispatcher it started, or it steals the worker's 'unloaded' reply.
    o = _bare_orchestrator()
    o._mailbox_lock = threading.Lock()
    o._mailboxes = {}
    o._request_cancel_events = {}
    o._unload_pending = False
    o._dispatcher_thread = None
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)

    started = {"v": False}
    stopped = {"v": False}

    def fake_start():
        started["v"] = True
        o._dispatcher_thread = _AliveDispatcher()
        return o._dispatcher_thread

    def fake_stop(thread = None):
        stopped["v"] = True
        o._dispatcher_thread = None

    monkeypatch.setattr(o, "_start_dispatcher", fake_start)
    monkeypatch.setattr(o, "_stop_dispatcher", fake_stop)

    def flip(*a, **k):
        o._unload_pending = True
        return {"type": "generate", "request_id": "r1"}

    monkeypatch.setattr(o, "_build_generate_cmd", flip)
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("must not send generate after the unload flipped")
    )

    out = list(o._generate_dispatched(messages = [{"role": "user", "content": "hi"}]))

    assert any("unloaded" in chunk.lower() for chunk in out)
    assert started["v"], "this call started the dispatcher"
    assert stopped["v"], "the bail must stop the dispatcher it started (no other mailboxes)"
    assert o._mailboxes == {}


def test_dispatched_bail_keeps_dispatcher_with_other_active_mailbox(monkeypatch):
    # Do not stop a dispatcher another compare request has registered on.
    o = _bare_orchestrator()
    o._mailbox_lock = threading.Lock()
    o._mailboxes = {}
    o._request_cancel_events = {}
    o._unload_pending = False
    o._dispatcher_thread = None
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(
        o, "_start_dispatcher", lambda: setattr(o, "_dispatcher_thread", _AliveDispatcher())
    )
    monkeypatch.setattr(
        o,
        "_stop_dispatcher",
        lambda: pytest.fail("must not stop a dispatcher another compare request is using"),
    )

    def flip(*a, **k):
        o._mailboxes["other"] = object()
        o._unload_pending = True
        return {"type": "generate", "request_id": "r1"}

    monkeypatch.setattr(o, "_build_generate_cmd", flip)
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("must not send generate after the unload flipped")
    )

    out = list(o._generate_dispatched(messages = [{"role": "user", "content": "hi"}]))

    assert any("unloaded" in chunk.lower() for chunk in out)
    assert set(o._mailboxes) == {"other"}, "the other request's mailbox is untouched"


def test_dispatched_bail_keeps_preexisting_dispatcher(monkeypatch):
    # A dispatcher already running before this request is not this request's to stop.
    o = _bare_orchestrator()
    o._mailbox_lock = threading.Lock()
    o._mailboxes = {}
    o._request_cancel_events = {}
    o._unload_pending = False
    o._dispatcher_thread = _AliveDispatcher()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(o, "_start_dispatcher", lambda: None)
    monkeypatch.setattr(
        o, "_stop_dispatcher", lambda: pytest.fail("must not stop a pre-existing dispatcher")
    )

    def flip(*a, **k):
        o._unload_pending = True
        return {"type": "generate", "request_id": "r1"}

    monkeypatch.setattr(o, "_build_generate_cmd", flip)
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("must not send generate after the unload flipped")
    )

    out = list(o._generate_dispatched(messages = [{"role": "user", "content": "hi"}]))

    assert any("unloaded" in chunk.lower() for chunk in out)


def test_load_model_aborts_publish_when_cancelled_after_wait_response(monkeypatch):
    # A publish after cancel_load returns survives its re-clear; load_model must recheck the marker.

    from utils import transformers_version as _tv
    import types

    o = _bare_orchestrator()
    o.loading_models = {"m"}
    o.active_model_name = None
    o.models = {}
    o._proc = None

    monkeypatch.setattr(_tv, "needs_transformers_5", lambda name: False)
    monkeypatch.setattr(orch_mod, "prepare_gpu_selection", lambda *a, **k: ([], {}))
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: False)
    monkeypatch.setattr(o, "_spawn_subprocess", lambda cfg: None)
    monkeypatch.setattr(o, "_shutdown_subprocess", lambda timeout = 5: None)

    parked = threading.Event()
    cancel_done = threading.Event()
    load_done = threading.Event()

    def blocking_wait_response(expected, timeout = 300.0):
        parked.set()
        assert cancel_done.wait(timeout = 5)
        return {
            "type": "loaded",
            "success": True,
            "model_info": {"identifier": "m", "display_name": "m"},
        }

    monkeypatch.setattr(o, "_wait_response", blocking_wait_response)

    load_result: dict = {}

    def run_load():
        try:
            load_result["ok"] = o.load_model(
                types.SimpleNamespace(identifier = "m", gguf_variant = None)
            )
        except Exception as exc:  # noqa: BLE001
            load_result["exc"] = exc
        finally:
            load_done.set()

    loader = threading.Thread(target = run_load)
    loader.start()
    assert parked.wait(timeout = 5), "load_model must reach _wait_response"

    assert o.cancel_load("m") is True
    cancel_done.set()

    loader.join(timeout = 5)
    assert load_done.is_set()

    assert load_result.get("ok") is False, "the cancelled load must not report success"
    assert o.active_model_name is None, "must not publish a cancelled model's active name"
    assert o.models == {}, "must not publish a cancelled model's mirror"
    assert "m" not in o.loading_models


# Compare mode bypasses _gen_lock, so _dispatcher_lifecycle_lock must serialize check-then-spawn.


def test_concurrent_start_dispatcher_spawns_exactly_one():
    import queue as _queue

    o = _bare_orchestrator()
    o._resp_queue = _queue.Queue()
    o._mailbox_lock = threading.Lock()
    o._mailboxes = {}
    o._request_cancel_events = {}
    o._dispatcher_thread = None
    o._dispatcher_stop = threading.Event()
    o._dispatcher_lifecycle_lock = threading.Lock()
    o._worker_released = threading.Condition(o._dispatcher_lifecycle_lock)

    n = 32
    barrier = threading.Barrier(n)
    results: list = []
    results_lock = threading.Lock()

    def racer():
        barrier.wait()
        started = o._start_dispatcher()
        with results_lock:
            results.append(started)

    threads = [threading.Thread(target = racer, name = f"racer-{i}") for i in range(n)]
    for t in threads:
        t.start()
    for t in threads:
        t.join(timeout = 5)

    try:
        spawned = [result for result in results if result is not None]
        assert len(spawned) == 1, f"expected exactly one spawn, got {len(spawned)}"
        assert results.count(None) == n - 1
        live = [
            t for t in threading.enumerate() if t.name == "inference-dispatcher" and t.is_alive()
        ]
        assert len(live) == 1, f"expected one live dispatcher, found {len(live)}"
        assert o._dispatcher_thread is live[0]
    finally:
        o._stop_dispatcher()

    assert o._dispatcher_thread is None
    remaining = [
        t for t in threading.enumerate() if t.name == "inference-dispatcher" and t.is_alive()
    ]
    assert remaining == [], "dispatcher must be stopped and joined"


# unload_model sets _unload_pending under the lifecycle lock before stopping, so a queued
# _start_dispatcher must refuse.


def test_start_dispatcher_refuses_while_unload_pending():
    import queue as _queue

    o = _bare_orchestrator()
    o._resp_queue = _queue.Queue()
    o._dispatcher_thread = None
    o._dispatcher_stop = threading.Event()
    o._dispatcher_lifecycle_lock = threading.Lock()
    o._worker_released = threading.Condition(o._dispatcher_lifecycle_lock)
    o._unload_pending = True

    started = o._start_dispatcher()

    assert started is None, "must not start a dispatcher while an unload is pending"
    assert o._dispatcher_thread is None, "no dispatcher thread may be created"
    live = [t for t in threading.enumerate() if t.name == "inference-dispatcher" and t.is_alive()]
    assert live == [], "no dispatcher may exist to consume the unloaded reply"


def test_start_dispatcher_resumes_after_unload_clears():
    import queue as _queue

    o = _bare_orchestrator()
    o._resp_queue = _queue.Queue()
    o._dispatcher_thread = None
    o._dispatcher_stop = threading.Event()
    o._dispatcher_lifecycle_lock = threading.Lock()
    o._worker_released = threading.Condition(o._dispatcher_lifecycle_lock)
    o._unload_pending = False

    try:
        assert (
            o._start_dispatcher() is o._dispatcher_thread is not None
        ), "a fresh dispatcher must start once no unload is pending"
        assert o._dispatcher_thread is not None and o._dispatcher_thread.is_alive()
    finally:
        o._stop_dispatcher()

    assert o._dispatcher_thread is None


def test_queued_start_behind_unload_stop_spawns_no_dispatcher():
    import queue as _queue

    o = _bare_orchestrator()
    o._resp_queue = _queue.Queue()
    o._mailbox_lock = threading.Lock()
    o._mailboxes = {}
    o._request_cancel_events = {}
    o._dispatcher_stop = threading.Event()
    o._dispatcher_lifecycle_lock = threading.Lock()
    o._worker_released = threading.Condition(o._dispatcher_lifecycle_lock)
    o._unload_pending = False

    start_queued = threading.Event()
    join_may_finish = threading.Event()

    class _IdleDispatcher:
        def is_alive(self):
            return True

        def join(self, timeout = None):
            assert start_queued.wait(timeout = 5), "compare start must queue behind the stop"
            assert join_may_finish.wait(timeout = 5)

    o._dispatcher_thread = _IdleDispatcher()

    def unload_side():
        with o._dispatcher_lifecycle_lock:
            o._unload_pending = True
        o._stop_dispatcher()

    started_result = {}

    def compare_side():
        started_result["v"] = o._start_dispatcher()

    u = threading.Thread(target = unload_side, name = "unload-side")
    u.start()
    time.sleep(0.2)

    c = threading.Thread(target = compare_side, name = "compare-side")
    c.start()
    time.sleep(0.2)

    start_queued.set()
    join_may_finish.set()

    u.join(timeout = 5)
    c.join(timeout = 5)

    assert started_result.get("v") is None, "the queued start must refuse while unloading"
    assert o._dispatcher_thread is None, "the stop cleared it and the queued start spawned nothing"
    live = [t for t in threading.enumerate() if t.name == "inference-dispatcher" and t.is_alive()]
    assert live == [], "no fresh dispatcher may be left to consume the unloaded reply"


def _dispatch(o, resps):
    """Run the dispatcher over a fixed response list and stop it."""
    import queue as _queue

    o._resp_queue = _queue.Queue()
    for r in resps:
        o._resp_queue.put(r)
    o._dispatcher_stop = threading.Event()
    t = threading.Thread(target = o._dispatcher_loop, daemon = True)
    t.start()
    deadline = time.monotonic() + 5.0
    while not o._resp_queue.empty() and time.monotonic() < deadline:
        time.sleep(0.01)
    o._dispatcher_stop.set()
    t.join(timeout = 5.0)


def test_worker_ownership_follows_the_worker_not_the_consumer():
    # The worker can start B before A's consumer drains; A must release ownership at gen_done.

    import queue as _queue

    o = _bare_orchestrator()
    o._mailbox_lock = threading.Lock()
    a_cancel, b_cancel = threading.Event(), threading.Event()
    o._mailboxes = {"a": _queue.Queue(), "b": _queue.Queue()}
    o._request_cancel_events = {"a": a_cancel, "b": b_cancel}
    o._claim_worker(a_cancel)
    o._claim_worker(b_cancel)

    _dispatch(o, [{"type": "token", "request_id": "a", "token": "hi"}])
    assert o._owns_worker(a_cancel), "the request the worker is answering owns it"
    assert not o._owns_worker(b_cancel), "a queued request does not"

    _dispatch(o, [{"type": "gen_done", "request_id": "a"}])
    assert not o._owns_worker(a_cancel), "a finished request stops owning the worker"
    assert o._owns_worker(b_cancel), "the next queued request is the one prefilling"

    _dispatch(o, [{"type": "token", "request_id": "b", "token": "yo"}])
    assert not o._owns_worker(a_cancel), "a finished request must not cancel its successor"
    assert o._owns_worker(b_cancel), "the worker moved on to B, so B owns it"

    o._release_worker(a_cancel)
    assert o._owns_worker(b_cancel)


def test_status_responses_do_not_transfer_worker_ownership():
    import queue as _queue

    o = _bare_orchestrator()
    o._mailbox_lock = threading.Lock()
    a_cancel, b_cancel = threading.Event(), threading.Event()
    o._mailboxes = {"a": _queue.Queue(), "b": _queue.Queue()}
    o._request_cancel_events = {"a": a_cancel, "b": b_cancel}
    o._claim_worker(a_cancel)
    o._claim_worker(b_cancel)

    _dispatch(o, [{"type": "status", "request_id": "b", "message": "loading"}])
    assert o._owns_worker(a_cancel)
    assert not o._owns_worker(b_cancel)


def test_only_the_latest_responder_executes():
    # Answering B means the worker left A; both must not count as executing.
    o = _bare_orchestrator()
    a_cancel, b_cancel = threading.Event(), threading.Event()
    o._claim_worker(a_cancel)
    o._claim_worker(b_cancel)

    o._mark_worker_started(a_cancel)
    assert o._owns_worker(a_cancel)
    o._mark_worker_started(b_cancel)
    assert o._owns_worker(b_cancel), "the latest responder is the one executing"
    assert not o._owns_worker(a_cancel), "and it is the only one"
    o._mark_worker_started(b_cancel)
    assert o._owns_worker(b_cancel)


def test_a_stale_mailbox_read_does_not_cancel_the_running_generation():
    # Stopping a retired consumer must not signal the shared worker event.

    import queue as _queue

    o = _bare_orchestrator()
    o._mailbox_lock = threading.Lock()
    a_cancel, b_cancel = threading.Event(), threading.Event()
    o._mailboxes = {"a": _queue.Queue(), "b": _queue.Queue()}
    o._request_cancel_events = {"a": a_cancel, "b": b_cancel}
    o._claim_worker(a_cancel)
    o._claim_worker(b_cancel)
    _dispatch(
        o,
        [
            {"type": "gen_done", "request_id": "a"},
            {"type": "token", "request_id": "b", "token": "yo"},
        ],
    )
    assert o._owns_worker(b_cancel) and not o._owns_worker(a_cancel)

    a_cancel.set()
    stale = [{"type": "token", "request_id": "a", "text": "late"}]
    drained = []
    list(
        o._consume_token_stream(
            lambda timeout: stale.pop(0) if stale else None,
            lambda: drained.append(True),
            crash_context = "generation",
            cancel_event = a_cancel,
            mark_started = False,
        )
    )
    assert drained, "the stopped stream still tears itself down"
    assert not o._cancel_event.is_set(), "a retired request must not signal the shared worker event"

    b_cancel.set()
    stale_b = [{"type": "token", "request_id": "b", "text": "live"}]
    list(
        o._consume_token_stream(
            lambda timeout: stale_b.pop(0) if stale_b else None,
            lambda: None,
            crash_context = "generation",
            cancel_event = b_cancel,
            mark_started = False,
        )
    )
    assert o._cancel_event.is_set(), "the running generation's own Stop must reach the worker"


def test_a_dispatcher_started_mid_stream_still_reaches_the_direct_reader():
    # Once the dispatcher owns resp_queue, a direct reader needs a mailbox or its tokens drop.

    o = _bare_orchestrator()

    read_one, _drain, release = o._direct_reader("direct-1")
    try:
        _dispatch(
            o,
            [
                {"type": "token", "request_id": "direct-1", "text": "hi"},
                {"type": "gen_done", "request_id": "direct-1"},
            ],
        )
        assert read_one(timeout = 0.1) == {
            "type": "token",
            "request_id": "direct-1",
            "text": "hi",
        }, "the dispatcher must route to the direct reader, not drop"
        assert read_one(timeout = 0.1)["type"] == "gen_done"
    finally:
        release()
    assert o._direct_mailboxes == {}, "the mailbox is dropped when the stream ends"


def test_the_direct_reader_hands_back_a_compare_response_it_took():
    import queue as _queue

    o = _bare_orchestrator()
    o._mailbox_lock = threading.Lock()
    compare_box: _queue.Queue = _queue.Queue()
    o._mailboxes = {"compare-1": compare_box}
    o._direct_mailboxes = {}
    o._request_cancel_events = {}
    o._resp_queue = _queue.Queue()
    o._dispatcher_thread = None

    read_one, _drain, release = o._direct_reader("direct-1")
    try:
        o._resp_queue.put({"type": "token", "request_id": "compare-1", "text": "theirs"})
        o._resp_queue.put({"type": "token", "request_id": "direct-1", "text": "mine"})
        assert read_one(timeout = 0.1) is None, "a foreign response is not ours to yield"
        assert compare_box.get_nowait()["text"] == "theirs", "it goes to its own mailbox"
        assert read_one(timeout = 0.1)["text"] == "mine"
    finally:
        release()


def test_a_direct_mailbox_is_not_mistaken_for_compare_activity():
    # _mailboxes means compare requests in flight; keep an ordinary chat's mailbox elsewhere.
    o = _bare_orchestrator()
    o._mailbox_lock = threading.Lock()
    o._mailboxes = {}
    o._direct_mailboxes = {}
    _read_one, _drain, release = o._direct_reader("direct-1")
    try:
        assert o._mailboxes == {}
        assert "direct-1" in o._direct_mailboxes
    finally:
        release()


def test_replacing_the_subprocess_clears_worker_scoped_state():
    # Ownership is keyed by cancel-event identity; a stale consumer must not block the new worker.

    import queue as _queue

    o = _bare_orchestrator()
    o._mailbox_lock = threading.Lock()
    dead = threading.Event()
    o._mailboxes = {"compare-1": _queue.Queue()}
    o._direct_mailboxes = {"direct-1": _queue.Queue()}
    o._request_cancel_events = {"compare-1": dead}
    o._claim_worker(dead)
    o._mark_worker_started(dead)
    assert o._owns_worker(dead)

    o._reset_worker_scoped_state()

    assert o._mailboxes == {} and o._direct_mailboxes == {}
    assert o._request_cancel_events == {}
    assert o._active_cancel_events == [] and o._executing_cancel_events == []
    fresh = threading.Event()
    o._claim_worker(fresh)
    assert o._owns_worker(fresh), "the dead worker's request must not outrank a live one"


def test_audio_input_claims_the_worker_before_sending():
    import ast
    import pathlib

    src = pathlib.Path(orch_mod.__file__).read_text(encoding = "utf-8")
    tree = ast.parse(src)
    fn = next(
        n
        for n in ast.walk(tree)
        if isinstance(n, ast.FunctionDef) and n.name == "_generate_audio_input_inner"
    )
    body = ast.get_source_segment(src, fn) or ""
    claim = body.find("self._claim_worker(cancel_event)")
    send = body.find("self._send_cmd(cmd)")
    assert claim != -1, "_generate_audio_input_inner must claim the worker"
    assert send != -1
    assert claim < send, "the claim has to happen before the command is enqueued"
    assert "with self._send_order_lock:" in body, "claim and send must be one critical section"
    assert "self._release_worker(cancel_event)" in body


def test_generation_stopped_while_queued_is_never_sent(monkeypatch):
    # Cancel is only checked on a token, so a cancelled waiter must not be sent at all.
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("must not send a generation already stopped")
    )
    stopped = threading.Event()
    stopped.set()

    out = list(
        o._generate_inner(messages = [{"role": "user", "content": "hi"}], cancel_event = stopped)
    )

    assert out == [], "a stopped request yields nothing rather than an error banner"
    assert o._active_cancel_events == [], "it must not claim the worker either"
    assert o._gen_lock.acquire(blocking = False)
    o._gen_lock.release()


def test_audio_input_stopped_while_queued_is_never_sent(monkeypatch):
    o = _bare_orchestrator()
    monkeypatch.setattr(o, "_ensure_subprocess_alive", lambda: True)
    monkeypatch.setattr(
        o, "_send_cmd", lambda cmd: pytest.fail("must not send a generation already stopped")
    )
    stopped = threading.Event()
    stopped.set()

    out = list(o._generate_audio_input_inner(audio_array = [0.0, 0.1], cancel_event = stopped))

    assert out == []
    assert o._active_cancel_events == []
    assert o._gen_lock.acquire(blocking = False)
    o._gen_lock.release()


def test_a_scoped_load_cancel_that_never_reports_back_releases_the_load():
    """A load cancel must release even if nothing reports back, or it parks the lifecycle gate forever."""
    from models.inference import LoadRequest, UnloadRequest
    import asyncio

    import routes.inference as inf

    request = LoadRequest(model_path = "org/a", load_request_id = "handshake-drop")
    original_impl = inf._load_model_impl
    original_timeout = inf._SCOPED_LOAD_CANCEL_HANDSHAKE_TIMEOUT_S

    async def cancel_then_die(*args, **kwargs):
        attempt, is_running = inf._cancel_scoped_load_attempt(
            UnloadRequest(model_path = "org/a", cancel_load_request_id = "handshake-drop"), "s"
        )
        assert attempt is not None and is_running
        attempt.cancel_complete.clear()
        return {"status": "loaded"}

    inf._load_model_impl = cancel_then_die
    inf._SCOPED_LOAD_CANCEL_HANDSHAKE_TIMEOUT_S = 0.25
    try:
        asyncio.run(
            asyncio.wait_for(inf._run_tracked_load_model_impl(request, None, "s"), timeout = 30)
        )
    finally:
        inf._load_model_impl = original_impl
        inf._SCOPED_LOAD_CANCEL_HANDSHAKE_TIMEOUT_S = original_timeout
        with inf._scoped_load_attempts_lock:
            inf._scoped_load_attempts.clear()
            inf._scoped_load_cancel_tombstones.clear()


def test_a_cancelled_row_stream_shows_no_token_a_single_reply_would_have_dropped():
    o = _bare_orchestrator()
    cancel = threading.Event()
    cancel.set()
    events = [
        {"type": "token", "request_id": "r1", "row": 0, "text": "buffered"},
        {"type": "row_done", "request_id": "r1", "row": 0},
        {"type": "row_done", "request_id": "r1", "row": 1},
        {"type": "gen_done", "request_id": "r1"},
    ]

    seen = list(
        o._consume_token_stream(
            lambda timeout: events.pop(0) if events else None,
            lambda: None,
            crash_context = "generation",
            request_id = "r1",
            cancel_event = cancel,
            mark_started = False,
            rows = 2,
        )
    )

    assert seen == [(0, None), (1, None)]


def _real_send_order_lock():
    """The send-order lock exactly as InferenceOrchestrator.__init__ makes it."""
    source = inspect.getsource(InferenceOrchestrator.__init__)
    line = next(one for one in source.splitlines() if "self._send_order_lock = " in one)
    return eval(line.split("=", 1)[1].strip(), {"threading": threading})


def test_a_recovering_caller_resets_the_worker_without_deadlocking_on_itself():
    """The reset decides under the send-order lock and then sends under it."""
    from types import SimpleNamespace

    backend = InferenceOrchestrator.__new__(InferenceOrchestrator)
    backend._send_order_lock = _real_send_order_lock()
    backend._mailbox_lock = threading.Lock()
    backend._request_cancel_events = {}
    backend._cancel_event = threading.Event()
    backend._proc = SimpleNamespace(is_alive = lambda: True)
    sent = []
    backend._send_cmd = sent.append
    backend._teardown_going_out = backend._teardown_not_sent = lambda: None
    backend._owns_worker = lambda event: True
    done = threading.Event()

    def reset():
        backend.reset_generation_state(threading.Event())
        done.set()

    worker = threading.Thread(target = reset, daemon = True)
    worker.start()
    worker.join(timeout = 5)

    assert done.is_set(), "the reset deadlocked on the lock it already held"
    assert sent == [{"type": "reset"}]


def test_the_idle_wait_is_bounded_when_no_timeout_is_asked_for():
    default = (
        inspect.signature(InferenceOrchestrator._wait_worker_idle).parameters["timeout"].default
    )
    assert isinstance(default, float) and default > 0, default


def test_shutdown_cancels_loads_that_have_not_reached_the_backend():
    """Shutdown must cancel loads that have not reached the backend, through each attempt's own event."""
    import importlib

    inf = importlib.import_module("routes.inference")

    def _attempt(token, path):
        return inf._ScopedLoadAttempt(
            token = token,
            request_id = None,
            model_path = path,
            subject = "s",
            cancel_event = threading.Event(),
            cancel_complete = threading.Event(),
        )

    pending = _attempt("pending-token", "owner/model")
    running = _attempt("running-token", "owner/other")

    with inf._scoped_load_attempts_lock:
        inf._pending_load_attempts[pending.token] = pending
    prior_running = inf._running_load_attempt
    inf._running_load_attempt = running
    try:
        assert inf.cancel_pending_loads() == 2
        assert pending.cancel_event.is_set(), "a queued load survived the shutdown"
        assert running.cancel_event.is_set(), "the running load survived the shutdown"
    finally:
        inf._running_load_attempt = prior_running
        with inf._scoped_load_attempts_lock:
            inf._pending_load_attempts.pop(pending.token, None)


def test_a_running_attempt_already_in_the_pending_map_is_not_counted_twice():
    import importlib

    inf = importlib.import_module("routes.inference")

    both = inf._ScopedLoadAttempt(
        token = "same-token",
        request_id = None,
        model_path = "owner/model",
        subject = "s",
        cancel_event = threading.Event(),
        cancel_complete = threading.Event(),
    )
    with inf._scoped_load_attempts_lock:
        inf._pending_load_attempts[both.token] = both
    prior_running = inf._running_load_attempt
    inf._running_load_attempt = both
    try:
        assert inf.cancel_pending_loads() == 1
        assert both.cancel_event.is_set()
    finally:
        inf._running_load_attempt = prior_running
        with inf._scoped_load_attempts_lock:
            inf._pending_load_attempts.pop(both.token, None)


def _mk_attempt(
    inf,
    token,
    path = "owner/model",
):
    return inf._ScopedLoadAttempt(
        token = token,
        request_id = None,
        model_path = path,
        subject = "s",
        cancel_event = threading.Event(),
        cancel_complete = threading.Event(),
    )


def test_shutdown_closes_the_cancel_handshake_itself():
    """Shutdown must set the cancel handshake itself, since only /unload sets cancel_complete."""
    import importlib

    inf = importlib.import_module("routes.inference")
    attempt = _mk_attempt(inf, "handshake-token")
    with inf._scoped_load_attempts_lock:
        inf._pending_load_attempts[attempt.token] = attempt
    try:
        inf.cancel_pending_loads()
        assert attempt.cancel_event.is_set()
        assert attempt.cancel_complete.is_set(), (
            "shutdown left the handshake open, so the load waits the full timeout in a "
            "non-daemon executor thread and delays process exit"
        )
    finally:
        inf.begin_load_lifecycle()
        with inf._scoped_load_attempts_lock:
            inf._pending_load_attempts.pop(attempt.token, None)


def test_a_load_registering_after_the_sweep_is_still_cancelled():
    """uvicorn's should_exit stops new connections but not admitted request tasks, so a /load can
    register after the shutdown snapshot and must still be cancelled."""
    import importlib

    inf = importlib.import_module("routes.inference")
    try:
        assert inf.cancel_pending_loads() == 0

        late = _mk_attempt(inf, "late-token")
        with inf._scoped_load_attempts_lock:
            inf._pending_load_attempts[late.token] = late
            latched = inf._loads_shutting_down
        assert latched is True, "the shutdown latch did not survive an empty sweep"
        if latched:
            inf._cancel_for_shutdown(late)
        assert late.cancel_event.is_set(), "a load admitted during shutdown was not cancelled"
    finally:
        inf.begin_load_lifecycle()
        with inf._scoped_load_attempts_lock:
            inf._pending_load_attempts.pop("late-token", None)


def test_the_latch_is_scoped_to_a_lifecycle_not_the_process():
    """A permanent latch would refuse every /load in an embedded host's second run_server."""
    import importlib

    inf = importlib.import_module("routes.inference")
    try:
        inf.cancel_pending_loads()
        with inf._scoped_load_attempts_lock:
            assert inf._loads_shutting_down is True

        inf.begin_load_lifecycle()
        with inf._scoped_load_attempts_lock:
            assert (
                inf._loads_shutting_down is False
            ), "the second session would cancel every load it admitted"
    finally:
        inf.begin_load_lifecycle()


def test_run_server_clears_the_route_latch_too():
    import ast
    import textwrap
    from pathlib import Path

    run_py = (Path(__file__).resolve().parent.parent / "run.py").read_text(encoding = "utf-8")
    tree = ast.parse(run_py)
    fn = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "run_server")
    src = textwrap.dedent(ast.get_source_segment(run_py, fn) or "")
    assert "begin_load_lifecycle()" in src, (
        "run_server resets the backend but not the route latch, so a restarted "
        "server cancels every load it admits"
    )


def _run_server_call_lines(name, *, owner = None):
    """Finds the first line of each call to a name inside run_server by AST, since text offsets go stale."""
    import ast
    from pathlib import Path

    run_py = (Path(__file__).resolve().parent.parent / "run.py").read_text(encoding = "utf-8")
    fn = next(
        n
        for n in ast.parse(run_py).body
        if isinstance(n, ast.FunctionDef) and n.name == "run_server"
    )
    lines = []
    for node in ast.walk(fn):
        if not isinstance(node, ast.Call):
            continue
        func = node.func
        if isinstance(func, ast.Attribute) and func.attr == name:
            if owner is not None and getattr(func.value, "id", None) != owner:
                continue
            lines.append(node.lineno)
        elif isinstance(func, ast.Name) and func.id == name and owner is None:
            lines.append(node.lineno)
    assert lines, f"run_server no longer calls {name}"
    return min(lines)


def test_the_route_latch_clears_only_after_the_backend_lifecycle_reopens():
    """Route latch clears after the backend reopens, or an old-lifecycle load adopts the new generation."""
    backend_reset = _run_server_call_lines("_begin_server_lifecycle")
    route_reset = _run_server_call_lines("begin_load_lifecycle")
    serve = _run_server_call_lines("start", owner = "thread")

    assert backend_reset < route_reset, (
        "the route latch is cleared before the backend lifecycle reopens, so a "
        "request admitted by the old lifecycle can cross the teardown wait"
    )
    assert route_reset < serve, "the route latch is still set when the server starts serving"


def _load_impl_ast():
    """(module source, the _load_model_impl node) from routes/inference.py."""
    import ast
    from pathlib import Path

    src = (Path(__file__).resolve().parent.parent / "routes" / "inference.py").read_text(
        encoding = "utf-8"
    )
    fn = next(
        n
        for n in ast.parse(src).body
        if isinstance(n, ast.AsyncFunctionDef) and n.name == "_load_model_impl"
    )
    return src, fn


def test_the_shutdown_latch_is_enforced_in_the_load_impl_not_only_at_the_route():
    """The shutdown latch must be enforced in the load impl, since auto-switch and preview bypass /load."""
    import ast

    src, impl = _load_impl_ast()

    tracked = {"_run_tracked_load_model_impl", "_load_model_impl"}
    direct = [
        node.name
        for node in ast.walk(ast.parse(src))
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
        and node.name not in tracked
        and any(
            isinstance(c, ast.Call)
            and isinstance(c.func, ast.Name)
            and c.func.id == "_load_model_impl"
            for c in ast.walk(node)
        )
    ]
    assert direct, (
        "no direct _load_model_impl callers left; if registration now covers every "
        "path this guard can move back to the route"
    )

    reads = [
        n.id for n in ast.walk(impl) if isinstance(n, ast.Name) and n.id == "_loads_shutting_down"
    ]
    assert reads, (
        "_load_model_impl never consults the shutdown latch, so these direct "
        f"callers bypass it entirely: {sorted(set(direct))}"
    )


def test_the_impl_cancel_check_refuses_a_load_once_shutdown_has_latched():
    """Runs the shipped cancel-check closure, so a load past shutdown is refused before it spawns."""
    import ast
    import textwrap
    import threading
    from types import SimpleNamespace

    from fastapi import HTTPException

    src, impl = _load_impl_ast()
    helper = next(
        n
        for n in impl.body
        if isinstance(n, ast.FunctionDef) and n.name == "_raise_if_scoped_load_cancelled"
    )
    ns = {
        "HTTPException": HTTPException,
        "_scoped_load_attempts_lock": threading.Lock(),
        "_loads_shutting_down": False,
        "load_cancel_event": None,
        "account_access": SimpleNamespace(require_live_account = lambda: None),
    }
    exec(textwrap.dedent(ast.get_source_segment(src, helper) or ""), ns)
    check = ns["_raise_if_scoped_load_cancelled"]

    check()

    ns["_loads_shutting_down"] = True
    with pytest.raises(HTTPException) as excinfo:
        check()
    assert excinfo.value.status_code == 409

    ns["_loads_shutting_down"] = False
    ns["load_cancel_event"] = threading.Event()
    check()
    ns["load_cancel_event"].set()
    with pytest.raises(HTTPException):
        check()


def test_a_second_backend_instance_is_covered_by_the_shutdown_latch():
    """Helper and advisor loads build their own LlamaCppBackend (hub/utils/llm_assist.py,
    utils/datasets/llm_assist.py); run.py tears down only the routes singleton, and
    _shutting_down is per-instance, so such a backend could Popen after terminate_all's snapshot."""
    from core.inference.llama_cpp import LlamaCppBackend
    from utils import process_lifetime

    torn_down = LlamaCppBackend.__new__(LlamaCppBackend)
    helper = LlamaCppBackend.__new__(LlamaCppBackend)
    try:
        assert helper._spawn_is_stale() is False, "a fresh backend must be able to spawn"

        torn_down._shutting_down = True
        process_lifetime.mark_process_shutting_down()

        assert (
            helper._spawn_is_stale() is True
        ), "a backend the shutdown never touched still thinks it may spawn"
    finally:
        process_lifetime.begin_process_lifecycle()

    assert (
        helper._spawn_is_stale() is False
    ), "the latch outlived the lifecycle, so an embedded second session cannot spawn"


def test_the_worker_spawn_refuses_once_shutdown_has_latched():
    """The worker spawn must check the latch itself, since the preview path's earlier read goes stale."""
    from core.inference.orchestrator import InferenceOrchestrator
    from utils import process_lifetime

    orch = InferenceOrchestrator.__new__(InferenceOrchestrator)
    try:
        process_lifetime.mark_process_shutting_down()
        with pytest.raises(RuntimeError, match = "shutting down"):
            orch._spawn_subprocess({})
    finally:
        process_lifetime.begin_process_lifecycle()


def test_the_process_latch_clears_between_the_backend_and_the_route():
    """The process latch must clear between the backend and the route, after teardown and before serving."""
    backend = _run_server_call_lines("_begin_server_lifecycle")
    process = _run_server_call_lines("begin_process_lifecycle")
    route = _run_server_call_lines("begin_load_lifecycle")
    serve = _run_server_call_lines("start", owner = "thread")

    assert backend < process < route < serve, (
        "the process latch must clear after the backend teardown completes and "
        "before the server starts serving"
    )


def test_shutdown_latches_the_process_before_any_subsystem_is_torn_down():
    """Shutdown must latch the process before any teardown step, not beside the llama-server kill."""
    import ast
    import textwrap
    from pathlib import Path

    run_py = (Path(__file__).resolve().parent.parent / "run.py").read_text(encoding = "utf-8")
    tree = ast.parse(run_py)
    fn = next(
        n
        for n in ast.walk(tree)
        if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name == "_graceful_shutdown"
    )
    src = textwrap.dedent(ast.get_source_segment(run_py, fn) or "")

    latch = src.index("mark_process_shutting_down()")
    orchestrator_stop = src.index("_shutdown_subprocess(timeout = 5.0)")
    sweep = src.index("cancel_pending_loads()")

    assert latch < orchestrator_stop, (
        "the inference subprocess is stopped before anything latches, so a load in "
        "flight can restart it"
    )
    assert latch < sweep


def test_a_shutdown_that_begins_during_the_spawn_reaps_the_new_worker():
    """A shutdown during the spawn must reap the new worker, since the post-spawn recheck closes the gap."""
    from unittest import mock

    from core.inference.orchestrator import InferenceOrchestrator
    from utils import process_lifetime

    orch = InferenceOrchestrator.__new__(InferenceOrchestrator)
    torn_down = []
    orch._shutdown_subprocess = lambda timeout = None: torn_down.append(timeout)

    started = mock.Mock()
    started.pid = 4242

    class _Ctx:
        Queue = staticmethod(lambda: mock.Mock())
        Event = staticmethod(lambda: mock.Mock())
        Lock = staticmethod(lambda: mock.Mock())
        Array = staticmethod(lambda *a, **k: mock.Mock())
        Value = staticmethod(lambda *a, **k: mock.Mock())

        @staticmethod
        def Process(**kw):
            process_lifetime.mark_process_shutting_down()
            return started

    try:
        with (
            mock.patch.object(orch_mod, "_CTX", _Ctx),
            mock.patch.object(orch_mod, "adopt_pid", lambda pid: None, create = True),
        ):
            with pytest.raises(RuntimeError, match = "shutting down"):
                orch._spawn_subprocess({})
    finally:
        process_lifetime.begin_process_lifecycle()

    assert torn_down, "the worker born during shutdown was never torn down"


def test_a_llama_server_spawned_as_shutdown_began_is_reaped():
    """A llama-server spawned as shutdown began must be reaped by the recheck after its pid is recorded."""
    import ast
    import textwrap
    from pathlib import Path

    src = (
        Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_cpp.py"
    ).read_text(encoding = "utf-8")
    fn = next(
        n
        for n in ast.walk(ast.parse(src))
        if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))
        and n.name == "_start_llama_process"
    )
    body = textwrap.dedent(ast.get_source_segment(src, fn) or "")

    publish = body.index("self._note_server_pid(")
    recheck = body.index("_spawn_is_stale", publish)
    kill = body.index("self._kill_process()", publish)
    assert publish < recheck < kill, (
        "nothing rechecks after the child is published, so a spawn that raced the "
        "latch leaves a server the sweep has already passed"
    )


def test_a_load_that_finishes_during_shutdown_is_not_published_as_resident():
    """A load that finishes during shutdown must not be published as resident; the fast path trusts it."""
    from core.inference.orchestrator import InferenceOrchestrator
    from utils import process_lifetime

    orch = InferenceOrchestrator.__new__(InferenceOrchestrator)
    orch.active_model_name = None
    orch.models = {}
    orch.loading_models = {"m"}
    orch.load_generation = 0

    try:
        process_lifetime.mark_process_shutting_down()
        stale = process_lifetime.is_process_shutting_down()
        assert stale is True, "the load no longer belongs to a live session"

        if stale:
            orch.loading_models.discard("m")
            orch.active_model_name = None
            orch.models.clear()

        assert (
            orch.active_model_name is None and not orch.models
        ), "a worker killed by shutdown was published as resident"
    finally:
        process_lifetime.begin_process_lifecycle()


def test_the_publish_branch_rechecks_shutdown_before_recording_the_model():
    """Pins the recheck in the shipped code, ahead of the first field it publishes."""
    import ast
    import textwrap
    from pathlib import Path

    src = (
        Path(__file__).resolve().parent.parent / "core" / "inference" / "orchestrator.py"
    ).read_text(encoding = "utf-8")
    fn = next(
        n
        for n in ast.walk(ast.parse(src))
        if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name == "load_model"
    )
    body = textwrap.dedent(ast.get_source_segment(src, fn) or "")

    check = body.index("if is_process_shutting_down(")
    publish = body.index("self.active_model_name = model_info.get(")
    assert check < publish, (
        "the load publishes active_model_name before rechecking shutdown, so a worker "
        "killed mid-load is recorded as resident"
    )


def _fn_named(source, name):
    import ast
    return next(
        n
        for n in ast.walk(ast.parse(source))
        if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name == name
    )


def test_the_primary_llama_launch_rechecks_after_recording_the_pid():
    """The launch must recheck the shutdown latch after recording the pid; the in-lock check races it."""
    import ast
    from pathlib import Path

    src = (
        Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_cpp.py"
    ).read_text(encoding = "utf-8")
    fn = _fn_named(src, "_spawn_and_wait")
    record = [
        n.lineno
        for n in ast.walk(fn)
        if isinstance(n, ast.Call) and getattr(n.func, "attr", None) == "_note_server_pid"
    ]
    stale = [
        n.lineno
        for n in ast.walk(fn)
        if isinstance(n, ast.Call) and getattr(n.func, "attr", None) == "_spawn_is_stale"
    ]
    health = [
        n.lineno
        for n in ast.walk(fn)
        if isinstance(n, ast.Call) and getattr(n.func, "attr", None) == "_wait_for_health"
    ]
    assert record and stale and health, "the spawn path no longer looks like itself"
    assert any(max(record) < s < min(health) for s in stale), (
        "no staleness recheck between recording the pid and the health wait: a spawn "
        "that raced the latch is left running outside the sweep that already finished"
    )


def test_the_worker_mirrors_are_published_under_the_shutdown_lock():
    """Publish worker mirrors under the shutdown lock; active_model_name does not test liveness."""
    import ast
    from pathlib import Path

    src = (
        Path(__file__).resolve().parent.parent / "core" / "inference" / "orchestrator.py"
    ).read_text(encoding = "utf-8")
    fn = _fn_named(src, "load_model")
    holding = [
        n
        for n in ast.walk(fn)
        if isinstance(n, ast.With)
        and any(
            getattr(item.context_expr, "attr", None) == "_subprocess_shutdown_lock"
            for item in n.items
        )
    ]
    assert holding, "load_model never holds the subprocess shutdown lock"
    covered = False
    for w in holding:
        checks = [
            n
            for n in ast.walk(w)
            if isinstance(n, ast.Call) and getattr(n.func, "id", None) == "is_process_shutting_down"
        ]
        publishes = [
            n
            for n in ast.walk(w)
            if isinstance(n, ast.Assign)
            and any(
                getattr(t, "attr", None) == "active_model_name"
                and not isinstance(n.value, ast.Constant)
                for t in n.targets
            )
        ]
        if checks and publishes:
            covered = True
    assert covered, (
        "the shutdown check and the active_model_name publication are not inside the "
        "same held lock, so a kill can land between them"
    )


def test_the_worker_handle_is_captured_before_start_not_after():
    """Capture the worker handle before start(); a concurrent shutdown can clear _proc afterwards."""
    import ast
    from pathlib import Path

    src = (
        Path(__file__).resolve().parent.parent / "core" / "inference" / "orchestrator.py"
    ).read_text(encoding = "utf-8")
    fn = _fn_named(src, "_spawn_subprocess")

    # The local must be bound from the Process(...) construction, never from self._proc.
    binds = [
        n
        for n in ast.walk(fn)
        if isinstance(n, ast.Assign)
        and any(getattr(t, "id", None) == "_spawned_proc" for t in n.targets)
    ]
    assert binds, "_spawn_subprocess no longer keeps a local handle on the worker"
    for n in binds:
        assert not (isinstance(n.value, ast.Attribute) and n.value.attr == "_proc"), (
            "the local handle is snapshotted from self._proc, which a concurrent "
            "shutdown can have cleared by then; build it from Process(...) instead"
        )

    # And start() must be called through the local, not through the attribute.
    starts = [
        n
        for n in ast.walk(fn)
        if isinstance(n, ast.Call) and getattr(n.func, "attr", None) == "start"
    ]
    assert starts, "the worker is never started"
    for n in starts:
        owner = n.func.value
        assert getattr(owner, "id", None) == "_spawned_proc", (
            "start() is called on self._proc rather than the local handle, so a "
            "shutdown clearing the attribute mid-start loses the child"
        )


def test_the_rag_embed_server_spawn_is_gated_and_rechecked():
    """No _graceful_shutdown step stops this backend, so the process-wide latch is the
    only thing standing between an in-flight encode and a server that outlives quit.
    """
    import ast
    from pathlib import Path

    src = (
        Path(__file__).resolve().parent.parent / "core" / "rag" / "embed_llama_server.py"
    ).read_text(encoding = "utf-8")
    fn = _fn_named(src, "_spawn_once")

    checks = [
        n.lineno
        for n in ast.walk(fn)
        if isinstance(n, ast.Call) and getattr(n.func, "id", None) == "is_process_shutting_down"
    ]
    popen = [
        n.lineno
        for n in ast.walk(fn)
        if isinstance(n, ast.Call) and getattr(n.func, "attr", None) == "Popen"
    ]
    adopt = [
        n.lineno
        for n in ast.walk(fn)
        if isinstance(n, ast.Call) and getattr(n.func, "id", None) == "adopt_pid"
    ]
    assert popen and adopt, "the embed spawn no longer looks like itself"
    assert any(c < min(popen) for c in checks), (
        "the embed server spawns without consulting the shutdown latch, so a quit "
        "during an encode can start one after the sweep has run"
    )
    assert any(c > max(adopt) for c in checks), (
        "no recheck after the pid is recorded: a latch set during the spawn leaves "
        "this child outside a sweep that has already finished"
    )


def test_the_stt_sidecar_spawns_are_gated_and_rechecked():
    """STT sidecar spawns must be gated, since no shutdown step or cancel_pending_loads reaches them."""
    import ast
    from pathlib import Path

    root = Path(__file__).resolve().parent.parent / "core" / "inference"
    for filename, func in (
        ("stt_ggml_sidecar.py", "load"),
        ("stt_mtmd_sidecar.py", "_load_locked"),
    ):
        src = (root / filename).read_text(encoding = "utf-8")
        fn = _fn_named(src, func)
        checks = [
            n.lineno
            for n in ast.walk(fn)
            if isinstance(n, ast.Call) and getattr(n.func, "id", None) == "is_process_shutting_down"
        ]
        popen = [
            n.lineno
            for n in ast.walk(fn)
            if isinstance(n, ast.Call) and getattr(n.func, "attr", None) == "Popen"
        ]
        adopt = [
            n.lineno
            for n in ast.walk(fn)
            if isinstance(n, ast.Call) and getattr(n.func, "id", None) == "adopt_pid"
        ]
        assert popen and adopt, f"{filename}:{func} no longer looks like a spawn"
        assert any(c < min(popen) for c in checks), (
            f"{filename} spawns without consulting the shutdown latch, so quitting "
            "during an STT load can start a server after the sweep has run"
        )
        assert any(c > max(adopt) for c in checks), (
            f"{filename} has no recheck after recording the pid, so a latch set during "
            "the spawn leaves the child outside a sweep that already finished"
        )


def test_the_latch_is_set_before_the_atexit_sweep():
    """The latch must be set before the atexit sweep, which runs ahead of the backend's cleanup hook."""
    import ast
    from pathlib import Path

    run_py = (Path(__file__).resolve().parent.parent / "run.py").read_text(encoding = "utf-8")
    tree = ast.parse(run_py)
    registrations = [
        (n.lineno, n.args[0].id)
        for n in ast.walk(tree)
        if isinstance(n, ast.Call)
        and getattr(n.func, "attr", None) == "register"
        and getattr(n.func.value, "id", None) == "atexit"
        and n.args
        and isinstance(n.args[0], ast.Name)
    ]
    names = [name for _, name in registrations]
    assert "terminate_all" in names, "run.py no longer registers the backstop sweep"
    assert "mark_process_shutting_down" in names, (
        "nothing latches shutdown on the atexit path, so the sweep snapshots while "
        "spawners still believe they may start children"
    )
    sweep_line = max(l for l, name in registrations if name == "terminate_all")
    latch_line = max(l for l, name in registrations if name == "mark_process_shutting_down")
    assert latch_line > sweep_line, (
        "the latch is registered before the sweep, so under LIFO it runs after it and "
        "the snapshot is taken unguarded"
    )


def test_every_long_lived_spawner_consults_the_shutdown_latch():
    """Every long-lived spawner must consult the shutdown latch, or it is a hole in the guarantee."""
    import ast
    from pathlib import Path

    backend = Path(__file__).resolve().parent.parent
    guarded = {
        "core/export/orchestrator.py",
        "core/inference/audio_cpp_server.py",
        "core/inference/diffusion_vae_prebuild.py",
        "core/inference/engine_install.py",
        "core/inference/flux3_prompt_upsampler.py",
        "core/inference/lemonade_server.py",
        "core/inference/llama_cpp.py",
        "core/inference/managed_engine.py",
        "core/inference/npu_backend.py",
        "core/inference/orchestrator.py",
        "core/inference/sd_cpp_engine.py",
        "core/inference/sd_cpp_server.py",
        "core/inference/stt_ggml_sidecar.py",
        "core/inference/stt_mtmd_sidecar.py",
        "core/inference/stt_transformers_worker.py",
        "core/inference/video_ltx25.py",
        "core/rag/embed_llama_server.py",
        "core/systemone/clef_runtime.py",
        "core/systemone/native_worker.py",
        "core/systemone/laya_worker.py",
        "core/training/token_preview.py",
        "core/training/training.py",
    }
    # Deliberately ungated adopters, listed so the completeness check cannot pass by omission.
    not_gated_here = {
        "cloudflare_tunnel.py",
        "core/data_recipe/jobs/manager.py",
        "core/inference/diffusion_transformer_quant.py",
        "core/inference/stt_download_worker.py",
        "core/inference/tools.py",
        "core/training/diffusion_training_service.py",
        "utils/diffusers_repair.py",
        "utils/prebuilt/update_flow.py",
        "utils/process_lifetime.py",
        "utils/torch_device_probe.py",
    }
    adopters = {
        str(path.relative_to(backend)).replace("\\", "/")
        for path in backend.rglob("*.py")
        if "adopt_pid(" in path.read_text(encoding = "utf-8")
        and not str(path.relative_to(backend)).replace("\\", "/").startswith("tests/")
        and "vendor/" not in str(path.relative_to(backend)).replace("\\", "/")
    }
    assert adopters == guarded | not_gated_here, (
        "a module adopts a child but is in neither set; decide whether it needs the "
        f"shutdown gate and put it in one of them: {adopters ^ (guarded | not_gated_here)}"
    )
    for rel in sorted(guarded):
        src = (backend / rel).read_text(encoding = "utf-8")
        tree = ast.parse(src)
        adopts = [
            n.lineno
            for n in ast.walk(tree)
            if isinstance(n, ast.Call) and getattr(n.func, "id", None) == "adopt_pid"
        ]
        checks = [
            n.lineno
            for n in ast.walk(tree)
            if isinstance(n, ast.Call) and getattr(n.func, "id", None) == "is_process_shutting_down"
        ]
        assert adopts, f"{rel} no longer adopts a child"
        assert checks, f"{rel} adopts a child without ever consulting the shutdown latch"
        assert any(c > min(adopts) for c in checks), (
            f"{rel} never rechecks the latch after adopting, so a spawn that raced it "
            "is left outside a sweep that has already finished"
        )


def test_the_adapter_path_accepts_the_same_images_kwarg_as_the_locked_one():
    """The tool loop passes both paths one common_kwargs; without images on the dispatched path, an
    adapter vision chat raises TypeError and its markers have no pixels."""
    import inspect

    from core.inference.orchestrator import InferenceOrchestrator

    dispatched = inspect.signature(InferenceOrchestrator._generate_dispatched).parameters
    locked = inspect.signature(InferenceOrchestrator._generate_inner).parameters

    assert "images" in locked
    assert "images" in dispatched, (
        "generate_with_adapter_control forwards **common_kwargs straight into "
        "_generate_dispatched, so a missing `images` is an immediate TypeError"
    )


def test_the_adapter_path_forwards_images_to_the_worker_command():
    import inspect

    from core.inference.orchestrator import InferenceOrchestrator

    body = inspect.getsource(InferenceOrchestrator._generate_dispatched)
    assert (
        "images_b64 = images" in body
    ), "_build_generate_cmd carries the list to the worker as images_b64"


def test_both_generation_paths_forward_the_image_ordinal():
    """Both paths must forward the image ordinal, or the marker top-up hits the wrong turn."""
    import inspect

    from core.inference.orchestrator import InferenceOrchestrator

    for method in (
        InferenceOrchestrator._generate_dispatched,
        InferenceOrchestrator._generate_inner,
    ):
        assert "image_ordinal" in inspect.signature(method).parameters, method.__name__
        assert "image_ordinal = image_ordinal" in inspect.getsource(method), (
            f"{method.__name__} accepts the ordinal but does not put it on the " "worker command"
        )


def test_a_count_during_a_dispatched_generation_is_refused_at_once():
    o = _bare_orchestrator(reads_stops = True)
    o._mailboxes["running"] = queue.Queue()
    sent = []
    o._send_cmd = sent.append

    with pytest.raises(RuntimeError, match = "generation is in progress"):
        o.count_chat_tokens([{"role": "user", "content": "hi"}])

    assert sent == [], "the count reached a worker that reads no command until the reply ends"
    assert o._gen_lock.acquire(blocking = False), "the refusal kept the generation lock"