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.

62.8 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""_wait_for_health swallows transient httpx errors so a crashed llama-server logs its exit code."""

from __future__ import annotations

import subprocess
import sys
import threading
import time
import types as _types
from pathlib import Path
from unittest import mock

import pytest

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

_loggers_stub = _types.ModuleType("loggers")
_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
sys.modules.setdefault("loggers", _loggers_stub)
sys.modules.setdefault("structlog", _types.ModuleType("structlog"))

import httpx  # noqa: E402

from core.inference.llama_cpp import LlamaCppBackend  # noqa: E402
from core.inference.llama_cpp import GgufLoadIntent

from ._fake_llama_server import fake_llama_server

# Sibling tests may install an httpx stub lacking get; fill gaps so order does not matter.
if not hasattr(httpx, "get"):
    httpx.get = None
for _exc_name in (
    "ConnectError",
    "TimeoutException",
    "ReadError",
    "RemoteProtocolError",
    "WriteError",
):
    if not hasattr(httpx, _exc_name):
        setattr(httpx, _exc_name, type(_exc_name, (Exception,), {}))


def _make_backend(port: int = 12345) -> LlamaCppBackend:
    """Barebones LlamaCppBackend with only the attributes _wait_for_health touches (bypasses __init__)."""
    b = LlamaCppBackend.__new__(LlamaCppBackend)
    b._port = port
    b._stdout_thread = None
    b._stdout_lines = []
    b._process = mock.Mock()
    return b


class TestWaitForHealthResilience:
    def test_returns_true_on_first_200(self, monkeypatch):
        b = _make_backend()
        b._process.poll.return_value = None
        ok_resp = mock.Mock(status_code = 200)
        monkeypatch.setattr(httpx, "get", lambda *a, **kw: ok_resp)
        assert b._wait_for_health(timeout = 1.0, interval = 0.01) is True

    def test_timeout_records_marker_for_classification(self, monkeypatch):
        """A live, never-healthy server is a /health timeout, not a bad GGUF (issue 5740)."""
        b = _make_backend()
        b._process.poll.return_value = None
        monkeypatch.setattr(httpx, "get", lambda *a, **kw: mock.Mock(status_code = 503))
        assert b._wait_for_health(timeout = 0.02, interval = 0.01) is False
        assert any("health check timed out" in ln for ln in b._stdout_lines)

    def test_a_teardown_during_the_wait_is_a_failed_load_not_a_crash(self, monkeypatch):
        """Shutdown clears the reference mid-wait; reading it once and treating
        its absence as "gone" is what stops the AttributeError the user saw as
        "Error loading model: 'NoneType' object has no attribute 'poll'" (#10353)."""
        b = _make_backend()
        b._process.poll.return_value = None
        probes = []

        def probe(*a, **kw):
            probes.append(1)
            if len(probes) == 2:
                b._process = None
            return mock.Mock(status_code = 503)

        monkeypatch.setattr(httpx, "get", probe)
        assert b._wait_for_health(timeout = 30.0, interval = 0.01) is False
        assert len(probes) == 2
        assert not any("health check timed out" in ln for ln in b._stdout_lines)
        assert b._health_wait_cancelled is True

    def test_a_teardown_before_the_first_probe_is_still_not_a_crash(self, monkeypatch):
        b = _make_backend()
        b._process = None
        monkeypatch.setattr(httpx, "get", lambda *a, **kw: mock.Mock(status_code = 200))
        assert b._wait_for_health(timeout = 30.0, interval = 0.01) is False
        assert b._health_wait_cancelled is True

    def test_a_teardown_is_terminal_so_the_caller_reads_no_exit_code(self, monkeypatch):
        """False alone is not enough: _spawn_and_wait stops only on this flag, else
        it reads the cleared reference and raises one frame up, and respawns."""
        b = _make_backend()
        b._process = None
        monkeypatch.setattr(httpx, "get", lambda *a, **kw: mock.Mock(status_code = 503))
        assert b._wait_for_health(timeout = 30.0, interval = 0.01) is False
        assert b._health_wait_cancelled is True
        assert (
            b._process is not None and b._process.poll() is not None and b._process.returncode != 0
        ) is False

    def test_a_crash_leaves_the_wait_unmarked_so_the_retries_still_run(self, monkeypatch):
        """A real crash must not look terminal, or the --fit off and CPU retries never run."""
        b = _make_backend()
        b._process.poll.return_value = 1
        b._process.returncode = 1
        monkeypatch.setattr(httpx, "get", lambda *a, **kw: mock.Mock(status_code = 503))
        assert b._wait_for_health(timeout = 1.0, interval = 0.01) is False
        assert b._health_wait_cancelled is False

    def test_a_teardown_marker_does_not_leak_into_the_next_load(self, monkeypatch):
        b = _make_backend()
        b._process = None
        monkeypatch.setattr(httpx, "get", lambda *a, **kw: mock.Mock(status_code = 200))
        assert b._wait_for_health(timeout = 30.0, interval = 0.01) is False
        assert b._health_wait_cancelled is True
        b._process = mock.Mock()
        b._process.poll.return_value = None
        assert b._wait_for_health(timeout = 30.0, interval = 0.01) is True
        assert b._health_wait_cancelled is False

    def test_a_teardown_from_a_real_thread_is_not_a_crash(self, monkeypatch):
        """Use two real threads: the once-per-iteration read is what makes teardown safe."""
        b = _make_backend()
        b._process.poll.return_value = None
        in_probe = threading.Event()
        cleared = threading.Event()

        def probe(*a, **kw):
            in_probe.set()
            cleared.wait(2.0)
            return mock.Mock(status_code = 503)

        monkeypatch.setattr(httpx, "get", probe)

        def shutdown():
            in_probe.wait(2.0)
            b._process = None
            cleared.set()

        t = threading.Thread(target = shutdown)
        t.start()
        try:
            assert b._wait_for_health(timeout = 30.0, interval = 0.01) is False
        finally:
            t.join(5.0)
        assert b._health_wait_cancelled is True

    def test_a_signalled_exit_during_teardown_is_not_a_startup_crash(self, monkeypatch):
        """Publish teardown before signalling, or a SIGTERM exit reads as a startup crash and respawns."""
        b = _make_backend()
        b._process.poll.return_value = None

        def probe(*a, **kw):
            # Set mid-wait because the wait resets the flag on entry.
            b._torn_down_process = b._process
            b._process.poll.return_value = -15
            b._process.returncode = -15
            return mock.Mock(status_code = 503)

        monkeypatch.setattr(httpx, "get", probe)
        with mock.patch("core.inference.llama_cpp.logger") as log:
            assert b._wait_for_health(timeout = 1.0, interval = 0.01) is False
        assert b._health_wait_cancelled is True
        assert not any("exited with code" in str(c) for c in log.error.call_args_list)

    def test_a_teardown_between_the_spawn_and_the_wait_still_counts(self, monkeypatch):
        """Keyed to the process, a teardown between spawn and wait still counts."""
        b = _make_backend()
        b._torn_down_process = b._process
        b._process.poll.return_value = -15
        b._process.returncode = -15
        monkeypatch.setattr(httpx, "get", lambda *a, **kw: mock.Mock(status_code = 503))
        with mock.patch("core.inference.llama_cpp.logger") as log:
            assert b._wait_for_health(timeout = 1.0, interval = 0.01) is False
        assert b._health_wait_cancelled is True
        assert not any("exited with code" in str(c) for c in log.error.call_args_list)

    def test_shutdown_is_terminal_however_late_it_lands(self, monkeypatch):
        """Shutdown is one-way and re-read each loop, so a wait that sees it ends terminally."""
        b = _make_backend()
        b._process.poll.return_value = None

        def probe(*a, **kw):
            b._shutting_down = True
            return mock.Mock(status_code = 503)

        monkeypatch.setattr(httpx, "get", probe)
        assert b._wait_for_health(timeout = 30.0, interval = 0.01) is False
        assert b._health_wait_cancelled is True
        assert not any("health check timed out" in ln for ln in b._stdout_lines)

    def test_kill_process_marks_shutdown_only_for_a_teardown(self):
        """Retry ladder reaping its own child must not look like shutdown, or the load aborts."""
        for teardown in (True, False):
            b = _make_backend()
            b._stop_mtp_crash_watchdog = lambda *a, **kw: None
            b._reset_effective_parallel_slots = lambda *a, **kw: None
            b._leading_process_group = lambda *a, **kw: None
            b._collect_descendants = lambda *a, **kw: ([], True)
            b._kill_process_group = lambda *a, **kw: None
            b._terminate_descendants = lambda *a, **kw: None
            b._process.poll.return_value = 0
            b._kill_process(teardown = teardown)
            assert getattr(b, "_shutting_down", False) is teardown

    def test_a_started_shutdown_refuses_to_spawn(self, monkeypatch):
        """Refused shutdown spawns must be logged, or callers health-wait on the old child."""
        import subprocess

        b = _make_backend()
        b._shutting_down = True
        spawned = []
        monkeypatch.setattr(subprocess, "Popen", lambda cmd = None, *a, **kw: spawned.append(cmd))
        assert b._start_llama_process(["llama-server"], {}, child_gpu_physical_ids = None) is False
        # Check argv, not call count: on macOS the defensive kill shells out to ps via Popen.
        assert ["llama-server"] not in spawned, "started a server after shutdown had begun"

    def test_a_teardown_with_no_process_still_marks_shutdown(self):
        """Mark teardown even with no process, or a load can spawn a server after the shutdown sweep."""
        b = _make_backend()
        b._process = None
        b._stop_mtp_crash_watchdog = lambda *a, **kw: None
        b._reset_effective_parallel_slots = lambda *a, **kw: None
        b._kill_process(teardown = True)
        assert b._shutting_down is True

    def test_the_published_child_survives_post_spawn_setup(self, monkeypatch):
        """Use the Popen just made after spawn, since shutdown can clear self._process."""
        import subprocess

        b = _make_backend()
        b._shutting_down = False
        recorded = []
        b._record_server_pid = lambda pid: recorded.append(pid)
        b._drain_stdout = lambda *a, **kw: None
        b._llama_log_fh = None
        b._process = None
        proc = mock.Mock()
        proc.pid = 4242
        monkeypatch.setattr(subprocess, "Popen", lambda *a, **kw: proc)

        class _TeardownWinsTheLock:
            """Shutdown taking the lock the instant the spawn releases it, which is
            the whole window: it clears the reference before the pid is read."""

            def __enter__(self):
                return None

            def __exit__(self, *_exc):
                b._process = None
                return False

        b._spawn_lock = _TeardownWinsTheLock()
        assert b._start_llama_process(["llama-server"], {}, child_gpu_physical_ids = None) is True
        assert recorded == [4242]

    def test_a_new_server_lifecycle_clears_the_shutdown_state(self):
        """A latched shutdown flag would refuse every launch of a second run_server() in the same
        process."""
        b = _make_backend()
        b._shutting_down = True
        b._torn_down_process = b._process
        b._begin_server_lifecycle()
        assert b._shutting_down is False
        assert b._torn_down_process is None

    def test_a_healthy_probe_during_shutdown_is_not_a_healthy_server(self, monkeypatch):
        """The probe blocks for up to 2s. A 200 arriving as teardown begins must not
        publish a child the shutdown is already killing, exactly as for a cancel."""
        b = _make_backend()
        b._process.poll.return_value = None

        def probe(*a, **kw):
            b._shutting_down = True
            return mock.Mock(status_code = 200)

        monkeypatch.setattr(httpx, "get", probe)
        assert b._wait_for_health(timeout = 5.0, interval = 0.01) is False
        assert b._health_wait_cancelled is True

    def test_a_teardown_during_the_last_probe_is_not_reported_as_a_timeout(self, monkeypatch):
        """The deadline checks the teardown flag too, or a late teardown reads as a timeout."""
        b = _make_backend()
        b._process.poll.return_value = None

        def probe(*a, **kw):
            b._torn_down_process = b._process
            return mock.Mock(status_code = 503)

        monkeypatch.setattr(httpx, "get", probe)
        assert b._wait_for_health(timeout = 0.02, interval = 0.01) is False
        assert b._health_wait_cancelled is True
        assert not any("health check timed out" in ln for ln in b._stdout_lines)

    def test_a_timeout_with_no_teardown_still_reports_a_timeout(self, monkeypatch):
        """The check above must not swallow the ordinary #5740 classification."""
        b = _make_backend()
        b._process.poll.return_value = None
        b._torn_down_process = mock.Mock()
        monkeypatch.setattr(httpx, "get", lambda *a, **kw: mock.Mock(status_code = 503))
        assert b._wait_for_health(timeout = 0.02, interval = 0.01) is False
        assert b._health_wait_cancelled is False
        assert any("health check timed out" in ln for ln in b._stdout_lines)

    def test_an_earlier_childs_teardown_does_not_end_a_later_wait(self, monkeypatch):
        """Keyed to one child, so a load that replaced a torn-down child is not aborted by it."""
        b = _make_backend()
        b._torn_down_process = mock.Mock()
        b._process.poll.return_value = 1
        b._process.returncode = 1
        monkeypatch.setattr(httpx, "get", lambda *a, **kw: mock.Mock(status_code = 503))
        with mock.patch("core.inference.llama_cpp.logger") as log:
            assert b._wait_for_health(timeout = 1.0, interval = 0.01) is False
        assert b._health_wait_cancelled is False, "a stale teardown aborted a live load"
        assert any("exited with code 1" in str(c) for c in log.error.call_args_list)

    @pytest.mark.parametrize("teardown", [True, False])
    def test_kill_process_publishes_a_teardown_before_it_signals(self, teardown):
        """Teardown is published before terminate(); retry reaps must not mark it terminal."""
        b = _make_backend()
        b._torn_down_process = None
        b._stop_mtp_crash_watchdog = lambda *a, **kw: None
        b._reset_effective_parallel_slots = lambda *a, **kw: None
        b._leading_process_group = lambda *a, **kw: None
        b._collect_descendants = lambda *a, **kw: ([], True)
        b._kill_process_group = lambda *a, **kw: None
        b._terminate_descendants = lambda *a, **kw: None
        seen = {}

        def _terminate():
            seen["flag_at_signal"] = getattr(b, "_torn_down_process", None) is b._process
            seen["process_still_set"] = b._process is not None

        b._process.terminate = _terminate
        b._process.poll.return_value = -15
        b._kill_process(teardown = teardown)
        assert seen["process_still_set"] is True, "the window this guards would not exist"
        assert (
            seen["flag_at_signal"] is teardown
        ), "teardown published late, or a reap marked terminal"

    def test_a_crash_still_reports_the_exit_code(self, monkeypatch):
        """Teardown guard must not swallow the crash branch, which still names the exit code."""
        b = _make_backend()
        b._process.poll.return_value = 1
        b._process.returncode = 1
        b._stdout_lines = ["ROCm error: out of memory"]
        monkeypatch.setattr(httpx, "get", lambda *a, **kw: mock.Mock(status_code = 503))
        with mock.patch("core.inference.llama_cpp.logger") as log:
            assert b._wait_for_health(timeout = 1.0, interval = 0.01) is False
        assert any("exited with code 1" in str(c) for c in log.error.call_args_list)

    def test_cancel_stops_the_wait_without_a_timeout_marker(self, monkeypatch):
        b = _make_backend()
        b._process.poll.return_value = None
        b._cancel_event = threading.Event()
        b._cancel_event.set()
        monkeypatch.setattr(httpx, "get", lambda *a, **kw: mock.Mock(status_code = 503))
        started = time.monotonic()
        assert b._wait_for_health(timeout = 30.0, interval = 0.01) is False
        assert time.monotonic() - started < 1.0
        assert not any("health check timed out" in ln for ln in b._stdout_lines)

    def test_cancel_midway_stops_a_wait_already_in_progress(self, monkeypatch):
        b = _make_backend()
        b._process.poll.return_value = None
        b._cancel_event = threading.Event()
        probes = []

        def probe(*a, **kw):
            probes.append(1)
            if len(probes) == 3:
                b._cancel_event.set()
            return mock.Mock(status_code = 503)

        monkeypatch.setattr(httpx, "get", probe)
        assert b._wait_for_health(timeout = 30.0, interval = 0.01) is False
        assert len(probes) == 3

    def test_cancel_at_the_deadline_is_not_reported_as_a_timeout(self, monkeypatch):
        b = _make_backend()
        b._process.poll.return_value = None
        b._cancel_event = threading.Event()
        b._health_probe_event = mock.Mock()
        b._health_probe_event.wait.side_effect = lambda _interval: b._cancel_event.set()
        ticks = iter((0.0, 0.0, 1.0))
        monkeypatch.setattr(time, "monotonic", lambda: next(ticks))
        monkeypatch.setattr(httpx, "get", lambda *a, **kw: mock.Mock(status_code = 503))

        assert b._wait_for_health(timeout = 0.5, interval = 0.5) is False
        assert b._health_wait_cancelled is True
        assert not any("health check timed out" in ln for ln in b._stdout_lines)

    def test_a_scoped_load_cancel_stops_the_wait(self, monkeypatch):
        """Scoped cancels skip unload_model; the wait must honor the predicate or poll the full timeout."""
        b = _make_backend()
        b._process.poll.return_value = None
        b._cancel_event = threading.Event()
        scoped = threading.Event()
        scoped.set()
        monkeypatch.setattr(httpx, "get", lambda *a, **kw: mock.Mock(status_code = 503))
        started = time.monotonic()
        assert b._wait_for_health(timeout = 30.0, interval = 0.01, cancelled = scoped.is_set) is False
        assert time.monotonic() - started < 1.0
        assert not any("health check timed out" in ln for ln in b._stdout_lines)

    def test_a_cancel_during_the_probe_does_not_publish_the_model(self, monkeypatch):
        """The probe blocks for up to 2s. A cancel landing inside that window used to be
        ignored because the 200 returned first, so the unwanted model went live."""
        b = _make_backend()
        b._process.poll.return_value = None
        b._cancel_event = threading.Event()
        scoped = threading.Event()

        def probe(*a, **kw):
            scoped.set()
            return mock.Mock(status_code = 200)

        monkeypatch.setattr(httpx, "get", probe)
        assert b._wait_for_health(timeout = 30.0, interval = 0.01, cancelled = scoped.is_set) is False

    def test_read_error_loops_to_subprocess_poll(self, monkeypatch):
        """WinError 10054 (httpx.ReadError) must be swallowed; the next iteration sees the dead subprocess and returns False with a structured exit-code log."""
        b = _make_backend()
        b._process.poll.side_effect = [None, 1]
        b._process.returncode = 1
        b._stdout_lines = ["llama-server: ggml-cuda.dll failed to load"]

        def raise_read_error(*a, **kw):
            raise httpx.ReadError("WinError 10054")

        monkeypatch.setattr(httpx, "get", raise_read_error)
        assert b._wait_for_health(timeout = 5.0, interval = 0.01) is False
        assert b._process.poll.call_count >= 2

    def test_remote_protocol_error_also_swallowed(self, monkeypatch):
        """A partial/malformed probe response (server crashed mid-headers)
        raises RemoteProtocolError -- also non-fatal."""
        b = _make_backend()
        b._process.poll.side_effect = [None, -1]
        b._process.returncode = -1

        def raise_rpe(*a, **kw):
            raise httpx.RemoteProtocolError("partial response")

        monkeypatch.setattr(httpx, "get", raise_rpe)
        assert b._wait_for_health(timeout = 5.0, interval = 0.01) is False
        assert b._process.poll.call_count >= 2

    def test_write_error_also_swallowed(self, monkeypatch):
        """WriteError on send takes the same recovery path as ReadError."""
        b = _make_backend()
        b._process.poll.side_effect = [None, 1]
        b._process.returncode = 1

        def raise_we(*a, **kw):
            raise httpx.WriteError("connection broken on write")

        monkeypatch.setattr(httpx, "get", raise_we)
        assert b._wait_for_health(timeout = 5.0, interval = 0.01) is False
        assert b._process.poll.call_count >= 2

    def test_connect_error_swallowed_until_success(self, monkeypatch):
        """ConnectError is still swallowed; the loop retries until llama-server returns 200."""
        b = _make_backend()
        b._process.poll.return_value = None
        calls = {"n": 0}
        ok_resp = mock.Mock(status_code = 200)

        def cycling(*a, **kw):
            calls["n"] += 1
            if calls["n"] < 3:
                raise httpx.ConnectError("not yet")
            return ok_resp

        monkeypatch.setattr(httpx, "get", cycling)
        assert b._wait_for_health(timeout = 5.0, interval = 0.01) is True
        assert calls["n"] >= 3

    def test_stdout_readiness_wakes_probe_before_fallback_interval(self, monkeypatch):
        b = _make_backend()
        b._process.poll.return_value = None
        b._health_probe_event = threading.Event()
        calls = {"n": 0}

        def becomes_healthy(*a, **kw):
            calls["n"] += 1
            if calls["n"] == 1:
                raise httpx.ConnectError("not yet")
            return mock.Mock(status_code = 200)

        monkeypatch.setattr(httpx, "get", becomes_healthy)
        wake = threading.Timer(0.02, b._health_probe_event.set)
        wake.start()
        start = time.monotonic()
        try:
            assert b._wait_for_health(timeout = 1.0, interval = 0.5) is True
        finally:
            wake.cancel()
        assert time.monotonic() - start < 0.25
        assert calls["n"] == 2

    def test_stdout_drain_sets_health_event_on_readiness_line(self):
        b = _make_backend()
        b._health_probe_event = threading.Event()
        b._process.stdout = iter(["main: server is listening on http://127.0.0.1:12345\n"])
        event_seen_while_draining = []
        b._llama_log_fh = mock.Mock()
        b._llama_log_fh.write.side_effect = lambda _line: event_seen_while_draining.append(
            b._health_probe_event.is_set()
        )

        b._drain_stdout()

        assert event_seen_while_draining == [True]

    def test_dead_process_before_probe_returns_false(self, monkeypatch):
        """poll() != None on entry: _wait_for_health returns False without calling httpx."""
        b = _make_backend()
        b._process.poll.return_value = 137
        b._process.returncode = 137
        b._stdout_lines = ["llama-server: out of memory"]
        called = {"n": 0}

        def should_not_be_called(*a, **kw):
            called["n"] += 1
            raise AssertionError("httpx.get must not run when subprocess is dead")

        monkeypatch.setattr(httpx, "get", should_not_be_called)
        assert b._wait_for_health(timeout = 5.0, interval = 0.01) is False
        assert called["n"] == 0


class TestCrashLogTail:
    """The exit log keeps the tail of the output, since crash diagnostics print after the startup banner."""

    @staticmethod
    def _capture_error_logs(monkeypatch) -> list:
        """Capture .error() directly; sibling logging/structlog config can't interfere."""
        import core.inference.llama_cpp as _llama_mod

        records: list = []
        fake_logger = mock.Mock()
        fake_logger.error = mock.Mock(side_effect = lambda msg, *a, **k: records.append(msg))
        monkeypatch.setattr(_llama_mod, "logger", fake_logger)
        return records

    def test_crash_log_keeps_tail_not_head(self, monkeypatch):
        records = self._capture_error_logs(monkeypatch)
        b = _make_backend()
        b._process.poll.return_value = 1
        b._process.returncode = 1
        banner = [f"load_model: tensor blk.{i} buffer ROCm0" for i in range(80)]
        diagnostic = "ggml-cuda.cu:103: ROCm error: out of memory"
        b._stdout_lines = banner + [diagnostic]

        assert b._wait_for_health(timeout = 1.0, interval = 0.01) is False

        crash_logs = [m for m in records if "exited with code" in m]
        assert crash_logs, "crash must produce an exited-with-code log"
        assert diagnostic in crash_logs[-1]
        assert "Output (tail)" in crash_logs[-1]
        assert "blk.0 buffer" not in crash_logs[-1]

    def test_crash_log_mentions_log_file_when_present(self, monkeypatch):
        records = self._capture_error_logs(monkeypatch)
        b = _make_backend()
        b._process.poll.return_value = 1
        b._process.returncode = 1
        b._stdout_lines = ["boom"]
        b._llama_log_path = Path("C:/logs/llama-123-port-1234.log")

        assert b._wait_for_health(timeout = 1.0, interval = 0.01) is False

        crash_logs = [m for m in records if "exited with code" in m]
        assert crash_logs and "llama-123-port-1234.log" in crash_logs[-1]


class TestRetryLogFilenameUnique:
    """The log name needs the attempt index, or a same-second retry truncates the crash log."""

    def test_log_name_includes_attempt_index(self):
        src = (
            Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_cpp.py"
        ).read_text(encoding = "utf-8")
        assert "-try{_spawn_attempt}.log" in src


class TestFitOffRetryEligible:
    """The --fit off retry needs Unsloth's VRAM math to have placed the model and no explicit fit mode."""

    def test_eligible_for_plain_ngl_launch(self):
        cmd = ["llama-server", "-m", "x.gguf", "-ngl", "-1", "--jinja"]
        assert LlamaCppBackend._fit_off_retry_eligible(cmd, use_fit = False) is True

    def test_not_eligible_when_use_fit(self):
        cmd = ["llama-server", "-m", "x.gguf", "--fit", "on"]
        assert LlamaCppBackend._fit_off_retry_eligible(cmd, use_fit = True) is False

    @pytest.mark.parametrize(
        "fit_args",
        [
            ["--fit", "on"],
            ["--fit", "off"],
            ["-fit", "off"],
            ["--fit=on"],
            ["-fit=off"],
        ],
    )
    def test_not_eligible_with_explicit_fit_flag(self, fit_args):
        cmd = ["llama-server", "-m", "x.gguf", *fit_args]
        assert LlamaCppBackend._fit_off_retry_eligible(cmd, use_fit = False) is False

    @pytest.mark.parametrize(
        "tuning_args",
        [
            ["--fit-ctx", "8192"],
            ["--fit-target", "1024"],
            ["-fitc", "4096"],
            ["-fitt", "512"],
            ["--fit-ctx=8192"],
        ],
    )
    def test_fit_tuning_flags_do_not_block_retry(self, tuning_args):
        cmd = ["llama-server", "-m", "x.gguf", *tuning_args]
        assert LlamaCppBackend._fit_off_retry_eligible(cmd, use_fit = False) is True


class TestCancelledWaitEndsTheLoad:
    """An auto-switch cancel leaves the child alive; reading that as a start failure 500s early."""

    def test_a_cancelled_health_wait_returns_false_instead_of_raising(self, tmp_path):
        gguf = tmp_path / "model.gguf"
        gguf.write_bytes(b"GGUF" + b"\0" * 4096)

        b = LlamaCppBackend()
        fake_server = fake_llama_server(tmp_path / "bin")
        b._find_llama_server_binary = lambda *a, **kw: fake_server
        b._non_chat_gguf_refusal_for_path = lambda *a, **kw: None
        b._non_chat_gguf_refusal = lambda *a, **kw: None
        b._kill_process = lambda *a, **kw: None

        def _start(cmd, env, **kw):
            proc = mock.Mock()
            proc.poll.return_value = None
            proc.pid = 424242
            b._process = proc
            b._stdout_lines = ["build: 6543", "main: loading model"]
            return proc

        b._start_llama_process = _start
        scoped = threading.Event()
        real_wait = b._wait_for_health

        def _wait(
            timeout = 600.0,
            interval = 0.5,
            cancelled = None,
        ):
            scoped.set()
            return real_wait(timeout = 2.0, interval = 0.05, cancelled = cancelled)

        b._wait_for_health = _wait

        assert (
            b.load_model(
                GgufLoadIntent(
                    model_identifier = "owner/model",
                    gguf_path = str(gguf),
                    n_ctx = 4096,
                ),
                load_cancel_event = scoped,
            )
            is False
        )

    def test_a_teardown_mid_load_ends_the_load_instead_of_raising(self, tmp_path, monkeypatch):
        """The whole race through the real caller (#10353): the waiter tests above
        never reach _spawn_and_wait, which is where the traceback resurfaced."""
        gguf = tmp_path / "model.gguf"
        gguf.write_bytes(b"GGUF" + b"\0" * 4096)

        b = LlamaCppBackend()
        fake_server = fake_llama_server(tmp_path / "bin")
        b._find_llama_server_binary = lambda *a, **kw: fake_server
        b._non_chat_gguf_refusal_for_path = lambda *a, **kw: None
        b._non_chat_gguf_refusal = lambda *a, **kw: None
        # The drain thread would iterate a Mock's stdout forever.
        b._drain_stdout = lambda *a, **kw: None

        def _kill():
            b._process = None

        b._kill_process = _kill

        spawns = []
        _real_popen = subprocess.Popen

        def _popen(*a, **kw):
            argv = [str(x) for x in (a[0] if a else kw.get("args") or [])]
            # --help and nvidia-smi are not launches; run() needs a real Popen.
            if str(gguf) not in argv:
                return _real_popen(*a, **kw)
            spawns.append(argv)
            proc = mock.Mock()
            proc.poll.return_value = None
            proc.pid = 424242
            return proc

        monkeypatch.setattr(subprocess, "Popen", _popen)

        def probe(*a, **kw):
            _kill()
            return mock.Mock(status_code = 503)

        monkeypatch.setattr(httpx, "get", probe)

        assert (
            b.load_model(
                GgufLoadIntent(
                    model_identifier = "owner/model",
                    gguf_path = str(gguf),
                    n_ctx = 4096,
                ),
            )
            is False
        )
        assert len(spawns) == 1, f"respawned after shutdown (spawns={len(spawns)})"


def test_a_cancelled_diffusion_start_reaps_the_runner():
    """An auto-switch cancel skips unload, so nothing else reaps the shim or visual server."""
    b = LlamaCppBackend()
    kills = []
    b._kill_process = lambda *a, **kw: kills.append(1)
    b._find_diffusion_assets = lambda *a, **kw: (["/bin/true"], "/bin/true", None)
    b._find_free_port = lambda *a, **kw: 45999

    def _wait(
        timeout = 600.0,
        interval = 0.5,
        cancelled = None,
    ):
        b._health_wait_cancelled = True
        return False

    b._wait_for_health = _wait
    proc = mock.Mock()
    proc.poll.return_value = None
    proc.pid = 999
    with mock.patch.object(subprocess, "Popen", return_value = proc):
        assert (
            b._start_diffusion_server(
                model_path = "/m/x.gguf",
                gguf_path = "/m/x.gguf",
                hf_repo = None,
                hf_variant = None,
                model_identifier = "o/m",
                n_ctx = 4096,
                extra_args = None,
                # Cancelled during the health wait: a Stop before the spawn launches nothing.
                cancelled = lambda: getattr(b, "_health_wait_cancelled", False),
            )
            is False
        )
    assert len(kills) == 2, f"the cancelled runner was left running (kills={len(kills)})"


def test_a_diffusion_cancel_after_health_reaps_the_runner():
    b = LlamaCppBackend()
    kills = []
    b._kill_process = lambda *a, **kw: kills.append(1)
    b._find_diffusion_assets = lambda *a, **kw: (["/bin/true"], "/bin/true", None)
    b._find_free_port = lambda *a, **kw: 45999
    scoped = threading.Event()

    def _wait(
        timeout = 600.0,
        interval = 0.5,
        cancelled = None,
    ):
        scoped.set()
        return True

    b._wait_for_health = _wait
    proc = mock.Mock()
    proc.poll.return_value = None
    proc.pid = 999
    with mock.patch.object(subprocess, "Popen", return_value = proc):
        assert (
            b._start_diffusion_server(
                model_path = "/m/x.gguf",
                gguf_path = "/m/x.gguf",
                hf_repo = None,
                hf_variant = None,
                model_identifier = "o/m",
                n_ctx = 4096,
                extra_args = None,
                cancelled = scoped.is_set,
            )
            is False
        )
    assert b._healthy is False
    assert len(kills) == 2, f"the cancelled runner was left running (kills={len(kills)})"


def _cancel_scaffold(tmp_path, kills):
    """A backend wired far enough to run load_model without weights or a server."""
    b = LlamaCppBackend()
    fake_server = fake_llama_server(tmp_path / "bin")
    b._find_llama_server_binary = lambda *a, **kw: fake_server
    b._non_chat_gguf_refusal_for_path = lambda *a, **kw: None
    b._non_chat_gguf_refusal = lambda *a, **kw: None
    b._kill_process = lambda *a, **kw: kills.append(1)

    def _start(cmd, env, **kw):
        proc = mock.Mock()
        proc.poll.return_value = None
        proc.pid = 424242
        b._process = proc
        b._stdout_lines = ["build: 6543", "main: loading model"]
        return proc

    b._start_llama_process = _start
    gguf = tmp_path / "model.gguf"
    gguf.write_bytes(b"GGUF" + b"\0" * 4096)
    return b, gguf


def test_combined_download_cancel_wait_observes_the_scoped_event():
    from core.inference.llama_cpp import _CombinedCancelEvent

    shared = threading.Event()
    scoped = threading.Event()
    timer = threading.Timer(0.01, scoped.set)
    timer.start()
    try:
        assert _CombinedCancelEvent(shared, scoped).wait(0.5)
    finally:
        timer.cancel()


@pytest.mark.parametrize("cancel_source", ["shared", "scoped"])
def test_remote_download_observes_both_load_cancel_sources(tmp_path, cancel_source):
    kills = []
    b, gguf = _cancel_scaffold(tmp_path, kills)
    b._remote_non_chat_gguf_refusal = lambda **_kw: None
    scoped = threading.Event()
    seen = []

    def _download(**kwargs):
        cancel_event = kwargs["cancel_event"]
        seen.append(cancel_event)
        (b._cancel_event if cancel_source == "shared" else scoped).set()
        assert cancel_event.is_set()
        return str(gguf)

    b._download_gguf = _download
    assert (
        b.load_model(
            GgufLoadIntent(
                model_identifier = "owner/model",
                hf_repo = "owner/model-GGUF",
                speculative_type = "none",
                n_ctx = 4096,
            ),
            load_cancel_event = scoped,
        )
        is False
    )
    assert len(seen) == 1


def test_a_stale_cancel_marker_does_not_abort_the_next_load(tmp_path):
    """The marker belongs to one attempt. Left set, a guard that runs before this
    load's first health wait reads the previous request's cancellation and swallows
    a genuine start failure."""
    kills = []
    b, gguf = _cancel_scaffold(tmp_path, kills)
    b._health_wait_cancelled = True
    b._wait_for_health = lambda timeout = 600.0, interval = 0.5, cancelled = None: False

    with pytest.raises(RuntimeError):
        b.load_model(
            GgufLoadIntent(
                model_identifier = "owner/model",
                gguf_path = str(gguf),
                n_ctx = 4096,
            )
        )


def test_cancelled_health_wait_removes_the_staged_cpu_runtime(tmp_path):
    kills = []
    cleaned = []
    waits = []
    b, gguf = _cancel_scaffold(tmp_path, kills)
    scoped = threading.Event()

    def _wait(
        timeout = 600.0,
        interval = 0.5,
        cancelled = None,
    ):
        waits.append(1)
        b._process = mock.Mock(returncode = -9)
        b._process.poll.return_value = -9
        b._cpu_fallback_runtime = _types.SimpleNamespace(
            tempdir = _types.SimpleNamespace(cleanup = lambda: cleaned.append(1))
        )
        scoped.set()
        b._health_wait_cancelled = True
        return False

    b._wait_for_health = _wait
    assert (
        b.load_model(
            GgufLoadIntent(
                model_identifier = "owner/model",
                gguf_path = str(gguf),
                n_ctx = 4096,
            ),
            load_cancel_event = scoped,
        )
        is False
    )
    assert waits == [1]
    assert b._cpu_fallback_runtime is None
    assert cleaned == [1]


def test_a_cancel_after_the_server_is_healthy_does_not_publish_it(tmp_path):
    """A cancel after health must tear down the child; is_loaded makes the route skip it."""
    kills = []
    cleaned = []
    b, gguf = _cancel_scaffold(tmp_path, kills)

    def _wait(
        timeout = 600.0,
        interval = 0.5,
        cancelled = None,
    ):
        b._cpu_fallback_runtime = _types.SimpleNamespace(
            tempdir = _types.SimpleNamespace(cleanup = lambda: cleaned.append(1))
        )
        b._cancel_event.set()
        return True

    b._wait_for_health = _wait
    assert (
        b.load_model(
            GgufLoadIntent(
                model_identifier = "owner/model",
                gguf_path = str(gguf),
                n_ctx = 4096,
            )
        )
        is False
    )
    assert kills, "the healthy-but-cancelled child was left resident"
    assert b._cpu_fallback_runtime is None
    assert cleaned == [1]


def test_a_cancel_after_audio_setup_unloads_the_codec(tmp_path, monkeypatch):
    kills = []
    emptied = []
    b, gguf = _cancel_scaffold(tmp_path, kills)
    scoped = threading.Event()
    codec = mock.Mock()
    monkeypatch.setattr(LlamaCppBackend, "_codec_mgr", None)
    monkeypatch.setitem(
        sys.modules,
        "torch",
        _types.SimpleNamespace(
            cuda = _types.SimpleNamespace(
                is_available = lambda: True,
                empty_cache = lambda: emptied.append(1),
            )
        ),
    )

    def _apply_audio(_detected):
        LlamaCppBackend._codec_mgr = codec
        scoped.set()
        return True

    b._wait_for_health = lambda **_kwargs: True
    b._detect_audio_type_strict = lambda: "snac"
    b._apply_detected_audio = _apply_audio

    assert (
        b.load_model(
            GgufLoadIntent(
                model_identifier = "owner/model",
                gguf_path = str(gguf),
                n_ctx = 4096,
            ),
            load_cancel_event = scoped,
        )
        is False
    )
    codec.unload.assert_called_once_with()
    assert LlamaCppBackend._codec_mgr is None
    assert emptied == [1]


def _run_server_body() -> str:
    """Parses run.py with ast; importing it would pull in fastapi and the whole route tree."""
    import ast

    run_py = Path(__file__).resolve().parent.parent / "run.py"
    tree = ast.parse(run_py.read_text(encoding = "utf-8"))
    for node in tree.body:
        if isinstance(node, ast.FunctionDef) and node.name == "run_server":
            return ast.get_source_segment(run_py.read_text(encoding = "utf-8"), node) or ""
    raise AssertionError("run_server not found in run.py")


def test_the_lifecycle_reset_does_not_import_the_route_module_early():
    """The lifecycle reset must follow `from main import app`, which makes the backend singleton a
    lookup."""
    body = _run_server_body()

    main_import = body.index("from main import app")
    reset = body.index("_begin_server_lifecycle()")
    assert reset > main_import, (
        "the lifecycle reset imports routes.inference before `from main import app`, "
        "so it, not main, builds the backend singleton -- ahead of the startup steps "
        "run_server requires to come first"
    )

    for earlier in (
        'sys.stdout.reconfigure(encoding = "utf-8"',
        "_setup_server_disk_logging()",
        "LogConfig.setup_logging(",
        "initialize_parent_lifetime()",
        "write_startup_marker()",
    ):
        assert body.index(earlier) < reset, f"{earlier} must precede the lifecycle reset"


def test_the_lifecycle_reset_stays_below_the_argument_checks():
    """A rejected invocation must not touch the backend at all."""
    body = _run_server_body()

    assert body.index("choose an explicit port.") < body.index(
        "_begin_server_lifecycle()"
    ), "the reset runs before run_server has finished rejecting bad arguments"


def test_the_lifecycle_reset_is_the_last_thing_before_the_serve():
    """Nothing that can abort startup, such as a port conflict or SystemExit, may follow the flag reset."""
    body = _run_server_body()
    # Match statements, not text: surrounding comments name these calls too.
    reset = body.index("_llama_cpp_backend._begin_server_lifecycle()")
    serve = body.index("\n    thread.start()")
    assert reset < serve, "the lifecycle reset no longer precedes the serve"

    # Only the window between reset and serve; match sys.exit( as well as SystemExit.
    window = body[reset:serve]
    for fail_fast in ("raise SystemExit", "sys.exit(", "_resolve_port("):
        assert fail_fast not in window, (
            f"{fail_fast} runs after the lifecycle reset, so a failed restart leaves the "
            "spawn guard cleared"
        )


class TestARefusedSpawnClosesItsLog:
    """A refused spawn must close its tee log; with no process, nothing else ever closes it."""

    def _backend(self, tmp_path):
        b = _make_backend()
        b._shutting_down = True
        b._spawn_lock = threading.Lock()
        b._stop_mtp_crash_watchdog = lambda: None
        b._process = None
        b._redacted_cmd_for_log = lambda c: c
        b._llama_log_path = str(tmp_path / "llama.log")
        b._llama_log_fh = None
        return b

    def test_start_llama_process_closes_it(self, tmp_path):
        """The handle is one _start_llama_process opens itself, per attempt, before the shutdown check."""
        b = self._backend(tmp_path)
        opened = []
        real_open = open

        def tracking_open(*a, **k):
            fh = real_open(*a, **k)
            opened.append(fh)
            return fh

        import builtins

        with mock.patch.object(builtins, "open", tracking_open):
            assert (
                b._start_llama_process(["llama-server"], {}, child_gpu_physical_ids = None) is False
            )

        assert opened, "the method never opened an attempt log; this proves nothing"
        assert all(fh.closed for fh in opened), "the refused attempt left its tee log open"
        assert b._llama_log_fh is None

    def test_the_kill_path_does_not_cover_it(self, tmp_path):
        """Explicit close needed: _kill_process returns early when nothing was published."""
        b = self._backend(tmp_path)
        fh = open(tmp_path / "kill.log", "w", encoding = "utf-8")
        b._llama_log_fh = fh
        b._reset_effective_parallel_slots = lambda: None

        b._kill_process(teardown = True)

        assert not fh.closed, (
            "_kill_process now closes the handle with no process; if that is "
            "deliberate this test and the explicit close are both redundant"
        )
        fh.close()


def test_the_pid_is_recorded_before_the_spawn_lock_is_released():
    """The pid must be recorded before the spawn lock is released, or a sweep may have forgotten it."""
    b = _make_backend()
    b._shutting_down = False
    b._stop_mtp_crash_watchdog = lambda: None
    b._process = None
    b._redacted_cmd_for_log = lambda c: c
    b._llama_log_path = None
    b._llama_log_fh = None
    order = []

    class _Lock:
        def __enter__(self):
            order.append("lock")
            return None

        def __exit__(self, *_exc):
            order.append("unlock")
            return False

    b._spawn_lock = _Lock()
    b._record_server_pid = lambda pid: order.append("record")

    class _Proc:
        pid = 4242

        def poll(self):
            return None

    with mock.patch.object(subprocess, "Popen", lambda *a, **k: _Proc()):
        with mock.patch.object(threading, "Thread", lambda **k: mock.Mock()):
            assert b._start_llama_process(["llama-server"], {}, child_gpu_physical_ids = None) is True

    assert order.index("record") < order.index("unlock"), (
        f"the pid is recorded after the lock is released ({order}), so a teardown "
        "between the two writes a bare pid record for an already-reaped process"
    )


class TestHealthPublicationIsAtomicWithTeardown:
    """Health is published under the teardown lock, or a teardown between probe and commit is missed."""

    def _backend(self):
        b = _make_backend()
        b._stop_mtp_crash_watchdog = lambda: None
        b._healthy = False
        b._spawn_lock = threading.Lock()
        return b

    def test_a_teardown_before_the_commit_refuses_publication(self):
        b = self._backend()
        b._shutting_down = True

        assert b._publish_healthy() is False
        assert b._healthy is False, "a torn-down backend was published as healthy"

    def test_an_ordinary_load_still_publishes(self):
        b = self._backend()
        b._shutting_down = False

        assert b._publish_healthy() is True
        assert b._healthy is True

    def test_the_teardown_mark_and_the_commit_cannot_interleave(self):
        """Only publish-then-teardown or teardown-then-refused-publish is safe; the test drives the
        first."""
        b = self._backend()
        b._shutting_down = False
        # A real child: _kill_process returns before clearing _healthy when nothing to kill.
        b._process = object()
        b._reset_effective_parallel_slots = lambda: None
        b._leading_process_group = lambda _pid: None
        b._collect_descendants = lambda _pid: ([], True)
        b._diffusion_requested_ngl = None

        published = b._publish_healthy()
        assert published is True and b._healthy is True

        b._kill_process(teardown = True)

        assert (
            b._healthy is False
        ), "teardown left _healthy set, so a publication that won the race is never undone"
        assert b._publish_healthy() is False, "a later publication slipped past the teardown"


def test_the_deadline_asks_the_durable_flag_too(monkeypatch):
    """The deadline must also check the durable flag, or a teardown mid-kill is reported as a timeout."""
    b = _make_backend()
    b._process.poll.return_value = None
    b._shutting_down = False
    b._torn_down_process = None

    # Set during the LAST probe; setting it up front is caught by the top-of-loop check.
    def probe(*a, **kw):
        b._shutting_down = True
        return mock.Mock(status_code = 503)

    monkeypatch.setattr(httpx, "get", probe)

    assert b._wait_for_health(timeout = 0.01, interval = 0.05) is False
    assert b._health_wait_cancelled is True, "a teardown was recorded as a timeout"
    assert not any("health check timed out" in ln for ln in b._stdout_lines)


class TestAStaleLoadIsDroppedAtTheSerialScope:
    """A stale load must be refused at the serial scope, before replacement work can kill the new model."""

    def test_the_check_precedes_the_replacement_work(self):
        """Checked over the AST: a text match hit '_kill_process' in a comment and failed correct code."""
        import ast
        import inspect
        import textwrap

        tree = ast.parse(textwrap.dedent(inspect.getsource(LlamaCppBackend.load_model)))
        scope = next(
            n
            for n in ast.walk(tree)
            if isinstance(n, ast.With)
            and any("_serial_load_scope" in ast.unparse(i.context_expr) for i in n.items)
        )

        guard_line = next(
            n.lineno
            for n in ast.walk(scope)
            if isinstance(n, ast.Call) and "_spawn_is_stale" in ast.unparse(n.func)
        )

        early_kills = [
            n.lineno
            for n in ast.walk(scope)
            if isinstance(n, ast.Call)
            and "_kill_process" in ast.unparse(n.func)
            and n.lineno < guard_line
        ]
        assert not early_kills, (
            f"a stale load calls _kill_process at {early_kills}, before it is refused at "
            f"line {guard_line}, so it unloads the new lifecycle's model"
        )

        src = inspect.getsource(LlamaCppBackend.load_model)
        stale = src.index("_spawn_is_stale()")
        assert "return False" in src[stale : stale + 300], "the stale-load branch does not return"


def test_a_lifecycle_cannot_reopen_while_a_teardown_is_still_killing():
    """Teardown keeps the lock until _process is cleared, or a new load can spawn into the gap."""
    b = _make_backend()
    b._stop_mtp_crash_watchdog = lambda: None
    b._reset_effective_parallel_slots = lambda: None
    b._diffusion_requested_ngl = None
    b._leading_process_group = lambda _pid: None
    b._collect_descendants = lambda _pid: ([], True)
    b._spawn_lock = threading.RLock()

    reopened_during_kill = []
    in_kill = threading.Event()
    release = threading.Event()

    class _SlowProcess:
        pid = 999

        def terminate(self):
            in_kill.set()
            release.wait(2.0)

        def wait(self, timeout = None):
            return 0

        def kill(self):
            pass

    b._process = _SlowProcess()

    def restarter():
        in_kill.wait(2.0)
        # Probe _teardown_lock: the kill holds it throughout, _spawn_lock only briefly.
        got = b._teardown_lock.acquire(blocking = False)
        if got:
            b._teardown_lock.release()
        reopened_during_kill.append(got)
        release.set()

    t = threading.Thread(target = restarter)
    t.start()
    try:
        b._kill_process(teardown = True)
    finally:
        release.set()
        t.join(5.0)

    assert reopened_during_kill == [False], (
        "the teardown lock was free while the kill was still running, so "
        "_begin_server_lifecycle could reopen the lifecycle mid-kill"
    )


def test_the_shutdown_cancels_loads_before_it_kills_the_server():
    """Order matters: killing first leaves the load to respawn into the teardown."""
    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 == "_graceful_shutdown"
    )
    src = textwrap.dedent(ast.get_source_segment(run_py, fn) or "")

    assert "cancel_pending_loads()" in src, "shutdown does not cancel in-flight loads"
    assert src.index("cancel_pending_loads()") < src.index(
        "_kill_process(teardown = True)"
    ), "the loads are cancelled after the kill, so one can still spawn into the teardown"


class TestATeardownDoesNotBlockASpawnItWillRefuse:
    """Teardown and spawn use separate locks, so a refused spawn never queues behind SIGTERM."""

    def _backend(self, on_terminate):
        b = _make_backend()
        b._stop_mtp_crash_watchdog = lambda: None
        b._reset_effective_parallel_slots = lambda: None
        b._diffusion_requested_ngl = None
        b._leading_process_group = lambda _p: None
        b._collect_descendants = lambda _p: ([], True)

        class _Stubborn:
            pid = 4242

            def __init__(self):
                self.killed = False

            def terminate(self):
                on_terminate()

            def wait(self, timeout = None):
                if not self.killed:
                    raise subprocess.TimeoutExpired("llama-server", timeout)

            def kill(self):
                self.killed = True

        b._process = _Stubborn()
        return b

    def test_a_spawn_is_refused_without_waiting_for_the_kill(self):
        in_kill = threading.Event()
        release = threading.Event()
        b = self._backend(lambda: (in_kill.set(), release.wait(5.0)))
        seen = []

        def spawner():
            in_kill.wait(5.0)
            start = time.monotonic()
            with b._spawn_lock:
                stale = b._spawn_is_stale()
            seen.append((time.monotonic() - start, stale))
            release.set()

        t = threading.Thread(target = spawner)
        t.start()
        try:
            b._kill_process(teardown = True)
        finally:
            release.set()
            t.join(10)

        waited, refused = seen[0]
        assert refused is True, "the spawn was allowed through during a teardown"
        assert waited < 1.0, (
            f"the spawn waited {waited:.2f}s for the kill before being refused; the "
            "teardown hold and the flag read must not share one lock"
        )

    def test_a_lifecycle_reset_still_waits_for_the_kill(self):
        """The other half, and the reason the long hold exists at all: clearing the
        flag mid-kill would let a new load spawn a child this teardown then drops."""
        in_kill = threading.Event()
        release = threading.Event()
        b = self._backend(lambda: (in_kill.set(), release.wait(2.0)))
        order = []

        def resetter():
            in_kill.wait(5.0)
            b._begin_server_lifecycle()
            order.append("reset")

        t = threading.Thread(target = resetter)
        t.start()
        try:
            b._kill_process(teardown = True)
            order.append("kill_done")
        finally:
            release.set()
            t.join(10)

        assert order == [
            "kill_done",
            "reset",
        ], f"the lifecycle reopened before the kill finished: {order}"


def test_the_lock_order_is_teardown_then_spawn():
    """Two locks means an order, and taking them the other way round deadlocks."""
    import ast
    import inspect

    tree = ast.parse(inspect.getsource(LlamaCppBackend))
    inversions = []
    for node in ast.walk(tree):
        if isinstance(node, ast.With) and any(
            "_spawn_lock" in ast.unparse(i.context_expr) for i in node.items
        ):
            for inner in ast.walk(node):
                if inner is node:
                    continue
                if isinstance(inner, ast.With) and any(
                    "_teardown_lock" in ast.unparse(i.context_expr) for i in inner.items
                ):
                    inversions.append(inner.lineno)
    assert not inversions, f"_teardown_lock taken inside _spawn_lock at {inversions}"


def test_no_kill_double_still_returns_the_legacy_shape():
    """Kill-path doubles must return _collect_descendants' (descendants, known) pair, not a bare list."""
    import ast
    import inspect
    import sys

    module = sys.modules[__name__]
    tree = ast.parse(inspect.getsource(module))
    for node in ast.walk(tree):
        if not isinstance(node, ast.Assign):
            continue
        target = node.targets[0]
        if not isinstance(target, ast.Attribute) or target.attr != "_collect_descendants":
            continue
        assert isinstance(node.value, ast.Lambda), ast.unparse(node)
        body = node.value.body
        assert isinstance(body, ast.Tuple) and len(body.elts) == 2, ast.unparse(node)


class TestHealthWaitMeasuresStalls:
    _WORKER = (
        "import sys, time\n"
        "held = []\n"
        "end = time.monotonic() + float(sys.argv[1])\n"
        "while time.monotonic() < end:\n"
        "    held.append(b'\\x01' * (4 << 20))\n"
        "    time.sleep(0.05)\n"
        "time.sleep(60)\n"
    )

    def _wait_on_child(
        self,
        monkeypatch,
        argv,
        *,
        healthy_after = None,
        timeout = 0.6,
    ):
        monkeypatch.setattr(LlamaCppBackend, "_STARTUP_PROGRESS_SAMPLE_S", 0.1)
        # /health is mocked and the worker never listens, so the port-owner check doesn't apply.
        monkeypatch.setattr(
            LlamaCppBackend, "_health_listener_is_ours", staticmethod(lambda process, port: True)
        )
        b = _make_backend()
        b._process = subprocess.Popen([sys.executable, "-c", *argv])
        started = time.monotonic()

        def probe(*a, **kw):
            if healthy_after is not None and time.monotonic() - started >= healthy_after:
                return mock.Mock(status_code = 200)
            return mock.Mock(status_code = 503)

        monkeypatch.setattr(httpx, "get", probe)
        try:
            ok = b._wait_for_health(timeout = timeout, interval = 0.02)
            elapsed = time.monotonic() - started
        finally:
            import psutil

            for descendant in psutil.Process(b._process.pid).children(recursive = True):
                descendant.kill()
            b._process.kill()
            b._process.wait()
        return b, ok, elapsed

    # 1.5s stall window: a loaded runner can spend 0.6s just starting the worker interpreter.
    _WORKING_TIMEOUT = 1.5

    def test_a_load_that_keeps_working_outlives_the_timeout(self, monkeypatch):
        b, ok, elapsed = self._wait_on_child(
            monkeypatch, [self._WORKER, "3.0"], healthy_after = 2.5, timeout = self._WORKING_TIMEOUT
        )
        assert ok is True
        assert elapsed >= 2.5
        assert not any("health check timed out" in ln for ln in b._stdout_lines)

    def test_a_child_doing_nothing_still_times_out(self, monkeypatch):
        b, ok, elapsed = self._wait_on_child(monkeypatch, [self._WORKER, "0.0"])
        assert ok is False
        assert elapsed < 3.0
        assert any("no startup progress for 0.6s" in ln for ln in b._stdout_lines)

    def test_a_load_that_stalls_times_out_one_timeout_after_its_last_work(self, monkeypatch):
        timeout = self._WORKING_TIMEOUT
        b, ok, elapsed = self._wait_on_child(monkeypatch, [self._WORKER, "1.5"], timeout = timeout)
        assert ok is False
        assert 1.5 + timeout - 0.2 <= elapsed < 1.5 + timeout + 3.0
        assert any("health check timed out" in ln for ln in b._stdout_lines)

    def test_work_done_by_a_descendant_counts(self, monkeypatch):
        shim = (
            "import subprocess, sys, time\n"
            "subprocess.Popen([sys.executable, '-c', sys.argv[1], '3.0'])\n"
            "time.sleep(60)\n"
        )
        # 1.5s: interpreter startup alone can outlast the 0.6s default on a loaded runner.
        b, ok, elapsed = self._wait_on_child(
            monkeypatch, [shim, self._WORKER], healthy_after = 2.5, timeout = 1.5
        )
        assert ok is True
        assert elapsed >= 2.5

    @pytest.mark.parametrize("faults_progress", [True, False])
    def test_mmap_page_ins_with_flat_resident_memory_count(self, monkeypatch, faults_progress):
        import contextlib
        import psutil

        module = sys.modules[LlamaCppBackend.__module__]
        clock = _types.SimpleNamespace(now = 0.0)
        fake_time = _types.SimpleNamespace(monotonic = lambda: clock.now)
        monkeypatch.setattr(module, "time", fake_time)
        monkeypatch.setattr(module, "_local_ssl_context", lambda: None)
        monkeypatch.setattr(LlamaCppBackend, "_STARTUP_PROGRESS_SAMPLE_S", 0.1)
        monkeypatch.setattr(
            LlamaCppBackend, "_health_listener_is_ours", staticmethod(lambda p, port: True)
        )

        class Event:
            def clear(self):
                pass

            def wait(self, interval):
                clock.now = round(clock.now + interval, 6)

        fake_pid = (1 << 63) - 1
        member = mock.Mock(pid = fake_pid)
        member.children.return_value = []
        member.oneshot.side_effect = contextlib.nullcontext
        member.cpu_times.return_value = _types.SimpleNamespace(user = 1.0, system = 0.0)
        member.io_counters.return_value = _types.SimpleNamespace(read_bytes = 100, read_chars = 100)
        member.memory_info.side_effect = lambda: _types.SimpleNamespace(
            rss = 1000, pfaults = 1000 + (round(clock.now * 10) * 128 if faults_progress else 0)
        )
        monkeypatch.setattr(psutil, "Process", lambda pid: member)
        monkeypatch.setattr(
            httpx, "get", lambda *a, **kw: mock.Mock(status_code = 200 if clock.now >= 2.5 else 503)
        )
        b = _make_backend()
        b._process.pid = fake_pid
        b._process.poll.return_value = None
        b._health_probe_event = Event()
        ok = b._wait_for_health(timeout = 1.5, interval = 0.1)
        assert ok is faults_progress
        if faults_progress:
            assert clock.now >= 2.5
            assert not b._health_wait_stalled
        else:
            assert clock.now == pytest.approx(1.5)
            assert b._health_wait_stalled
            assert any("no startup progress for 1.5s" in ln for ln in b._stdout_lines)

    def test_page_fault_counters_from_platform_and_linux_stat(self, monkeypatch):
        import io

        member = _types.SimpleNamespace(pid = (1 << 63) - 1)
        assert LlamaCppBackend._page_faults(member, _types.SimpleNamespace(pfaults = 71)) == 71
        assert (
            LlamaCppBackend._page_faults(member, _types.SimpleNamespace(num_page_faults = 93)) == 93
        )
        opened = []

        def fake_open(path, mode):
            opened.append((path, mode))
            return io.BytesIO(
                f"{member.pid} (name with ) in it) R 1 2 3 4 5 6 123 8 45 10".encode()
            )

        monkeypatch.setattr("builtins.open", fake_open)
        assert LlamaCppBackend._page_faults(member, _types.SimpleNamespace()) == 168
        assert opened == [(f"/proc/{member.pid}/stat", "rb")]

    def test_unreadable_counters_keep_the_fixed_deadline(self, monkeypatch):
        monkeypatch.setattr(LlamaCppBackend, "_startup_work_sample", staticmethod(lambda p: None))
        b, ok, elapsed = self._wait_on_child(monkeypatch, [self._WORKER, "3.0"])
        assert ok is False
        assert elapsed < 1.5

    def test_cpu_after_an_unreadable_sample_is_measured_from_the_last_readable_one(
        self, monkeypatch
    ):
        samples = iter([(1.0, 0, 0, 0), *[None] * 8, (1.02, 0, 0, 0)])
        monkeypatch.setattr(
            LlamaCppBackend,
            "_startup_work_sample",
            staticmethod(lambda p: next(samples, None)),
        )
        b, ok, elapsed = self._wait_on_child(monkeypatch, [self._WORKER, "0.0"], timeout = 1.5)
        assert ok is False
        # Bound sits below the 2.4s floor a wrong measurement would produce.
        assert elapsed < 2.3

    def test_resident_memory_regained_after_eviction_is_not_progress(self):
        peak = (10.0, 500 << 20, 0, 0)
        assert not LlamaCppBackend._made_startup_progress(peak, (10.0, 499 << 20, 0, 0), 5.0)
        assert LlamaCppBackend._made_startup_progress(peak, (10.0, 502 << 20, 0, 0), 5.0)

    def test_answering_health_probes_is_not_progress(self):
        before = (1.0, 100 << 20, 50 << 20, 1000)
        assert not LlamaCppBackend._made_startup_progress(
            before, (1.02, 100 << 20, 50 << 20, 1033), 5.0
        )
        assert LlamaCppBackend._made_startup_progress(before, (1.5, 100 << 20, 50 << 20, 1000), 5.0)
        assert LlamaCppBackend._made_startup_progress(before, (1.0, 100 << 20, 50 << 20, 1064), 5.0)