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.

72.6 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

"""Pins the discrimination: forcing gpu_layers=0 on every Mac would discard Metal for real users."""

from __future__ import annotations

import ast
import inspect
from dataclasses import asdict
import sys
import textwrap
import types

import pytest

import core.inference.llama_cpp as llama_cpp
import core.inference.llama_server_args as llama_server_args
from core.inference.llama_cpp import _metal_device_is_paravirtual


@pytest.fixture(autouse = True)
def _clear_cache():
    """The detector is lru_cached so a real machine only pays for the probe once."""
    _metal_device_is_paravirtual.cache_clear()
    yield
    _metal_device_is_paravirtual.cache_clear()


def _fake_mlx(device_name: str):
    module = types.ModuleType("mlx.core")
    module.device_info = lambda: {"device_name": device_name}
    parent = types.ModuleType("mlx")
    parent.core = module
    return parent, module


@pytest.mark.parametrize(
    "device_name, expected",
    [
        ("Apple Paravirtual device", True),
        ("apple paravirtual device", True),  # matching must not be case-sensitive
        ("Apple M1", False),
        ("Apple M3 Max", False),
        ("Apple M4 Pro", False),
    ],
)
def test_only_virtualised_apple_gpus_fall_back(monkeypatch, device_name, expected):
    monkeypatch.setattr(sys, "platform", "darwin")
    parent, core = _fake_mlx(device_name)
    monkeypatch.setitem(sys.modules, "mlx", parent)
    monkeypatch.setitem(sys.modules, "mlx.core", core)
    monkeypatch.setattr(
        "core.inference.llama_cpp.subprocess.run",
        lambda *a, **k: types.SimpleNamespace(stdout = "Chipset Model: Apple M3 Max"),
    )
    assert _metal_device_is_paravirtual() is expected


def test_non_darwin_never_pays_for_the_probe(monkeypatch):
    """Linux and Windows short-circuit: there is no Metal to be virtualised."""
    monkeypatch.setattr(sys, "platform", "linux")

    def explode(*args, **kwargs):  # pragma: no cover - must never run
        raise AssertionError("probed for a Metal device off macOS")

    monkeypatch.setattr("core.inference.llama_cpp.subprocess.run", explode)
    assert _metal_device_is_paravirtual() is False


def test_system_profiler_catches_it_when_mlx_is_absent(monkeypatch):
    """Not every Mac has MLX; without this fallback, a VM without it reads as bare metal."""
    monkeypatch.setattr(sys, "platform", "darwin")
    monkeypatch.setitem(sys.modules, "mlx", None)
    monkeypatch.setattr(
        "core.inference.llama_cpp.subprocess.run",
        lambda *a, **k: types.SimpleNamespace(
            stdout = "Graphics/Displays:\n  Apple Paravirtual device:\n    Vendor: Apple"
        ),
    )
    assert _metal_device_is_paravirtual() is True


def _probe_dispatch(responses):
    """Stub keyed on the probe so SPDisplaysDataType and hw.model may answer differently."""

    def run(cmd, *a, **k):
        key = "hw.model" if "sysctl" in cmd[0] else "spdisplays"
        return types.SimpleNamespace(stdout = responses.get(key, ""))

    return run


def test_a_headless_vm_is_caught_when_spdisplays_says_nothing(monkeypatch):
    """With no display, SPDisplaysDataType reads zero bytes, so the hw.model fallback catches the VM."""
    monkeypatch.setattr(sys, "platform", "darwin")
    monkeypatch.setitem(sys.modules, "mlx", None)
    monkeypatch.setattr(
        "core.inference.llama_cpp.subprocess.run",
        _probe_dispatch({"hw.model": "VirtualMac2,1\n", "spdisplays": ""}),
    )
    assert _metal_device_is_paravirtual() is True


def test_a_physical_mac_is_not_dragged_down_by_the_model_probe(monkeypatch):
    """Negative: real hardware reports Mac<n>,<n>, which must not read as virtual."""
    monkeypatch.setattr(sys, "platform", "darwin")
    monkeypatch.setitem(sys.modules, "mlx", None)
    monkeypatch.setattr(
        "core.inference.llama_cpp.subprocess.run",
        _probe_dispatch(
            {
                "hw.model": "Mac15,3\n",
                "spdisplays": "Graphics/Displays:\n  Apple M3 Max:\n    Vendor: Apple",
            }
        ),
    )
    assert _metal_device_is_paravirtual() is False


def test_a_desktop_vm_still_answers_through_spdisplays(monkeypatch):
    """Even when hw.model does not say virtual, the display probe still catches a VM."""
    monkeypatch.setattr(sys, "platform", "darwin")
    monkeypatch.setitem(sys.modules, "mlx", None)
    monkeypatch.setattr(
        "core.inference.llama_cpp.subprocess.run",
        _probe_dispatch(
            {
                "hw.model": "Mac14,2\n",
                "spdisplays": "Graphics/Displays:\n  Apple Paravirtual device:",
            }
        ),
    )
    assert _metal_device_is_paravirtual() is True


def test_mlx_short_circuits_before_any_subprocess(monkeypatch):
    """MLX answering means no probe should spawn; SPDisplaysDataType is the slow one."""
    monkeypatch.setattr(sys, "platform", "darwin")
    parent, core = _fake_mlx("Apple Paravirtual device")
    monkeypatch.setitem(sys.modules, "mlx", parent)
    monkeypatch.setitem(sys.modules, "mlx.core", core)

    def explode(*args, **kwargs):  # pragma: no cover - must never run
        raise AssertionError("spawned a probe after MLX already named the device")

    monkeypatch.setattr("core.inference.llama_cpp.subprocess.run", explode)
    assert _metal_device_is_paravirtual() is True


def test_a_broken_probe_leaves_gpu_offload_alone(monkeypatch):
    """If neither source can answer, assume a real Mac: guessing "virtualised" would
    silently drop everyone the probe fails on to CPU."""
    monkeypatch.setattr(sys, "platform", "darwin")
    monkeypatch.setitem(sys.modules, "mlx", None)

    def explode(*args, **kwargs):
        raise OSError("system_profiler not found")

    monkeypatch.setattr("core.inference.llama_cpp.subprocess.run", explode)
    assert _metal_device_is_paravirtual() is False


class _FakeProcess:
    def poll(self):
        return None

    def terminate(self):
        pass

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


def _paravirtual(monkeypatch):
    monkeypatch.setattr(llama_cpp, "_metal_device_is_paravirtual", lambda: True)


def _load_model_source() -> str:
    return inspect.getsource(llama_cpp.LlamaCppBackend.load_model)


def test_fallback_is_settled_before_the_duplicate_load_check():
    """The launch records the normalized placement ("manual"/0), so a repeat Auto request
    must be normalized before comparison, or every duplicate /load tears down a healthy
    CPU server."""
    src = _load_model_source()
    assert src.index("_metal_device_is_paravirtual()") < src.index(
        "self.adopt_load_intent_if_matched("
    )


def test_repeat_auto_load_does_not_reload_a_healthy_cpu_server(monkeypatch, tmp_path):
    """End-to-end: the second identical Auto /load must take the fast path."""
    _paravirtual(monkeypatch)
    backend = llama_cpp.LlamaCppBackend()
    backend._process = _FakeProcess()
    backend._healthy = True
    backend._audio_probed = True
    backend._model_identifier = "owner/repo"
    gguf = tmp_path / "model.gguf"
    gguf.write_bytes(b"GGUF")
    backend._gguf_path = str(gguf)
    backend._requested_n_ctx = 8192
    backend._requested_n_parallel = 1
    backend._requested_spec_mode = "auto"
    backend._gpu_memory_mode = "manual"
    backend._gpu_layers = 0

    def _never(*args, **kwargs):  # pragma: no cover - must never run
        raise AssertionError("tore down a healthy server on a duplicate /load")

    # Binary lookup is on the fast path (revision check); fixed path keeps it unchanged.
    monkeypatch.setattr(
        backend, "_find_llama_server_binary", lambda *a, **k: "/nonexistent/llama-server"
    )
    monkeypatch.setattr(backend, "_kill_process", _never)

    assert (
        backend.load_model(
            llama_cpp.GgufLoadIntent(
                model_identifier = "owner/repo",
                gguf_path = str(gguf),
                n_ctx = 8192,
                gpu_memory_mode = "auto",
                gpu_layers = -1,
                n_parallel = 1,
            )
        )
        is True
    )


def test_a_pass_through_layer_flag_cannot_re_enable_the_corrupt_offload(monkeypatch):
    """Auto never strips -ngl at the route, and user extras are appended after the managed
    --gpu-layers 0, so llama.cpp's last-wins parser would undo the pin."""
    _paravirtual(monkeypatch)
    backend = llama_cpp.LlamaCppBackend()
    seen = {}

    def _capture(intent):
        captured = asdict(intent)
        for _key in ("extra_args", "tensor_split", "gpu_ids"):
            if captured.get(_key) is not None:
                captured[_key] = list(captured[_key])
        seen.update(captured)
        return True

    monkeypatch.setattr(backend, "adopt_load_intent_if_matched", _capture)
    monkeypatch.setattr(backend, "_apply_detected_audio", lambda _d: True)
    backend._audio_probed = True
    backend._healthy = True
    backend.load_model(
        llama_cpp.GgufLoadIntent(
            model_identifier = "owner/repo",
            gguf_path = "/nonexistent/model.gguf",
            gpu_memory_mode = "auto",
            gpu_layers = -1,
            extra_args = ["-ngl", "99", "--top-k", "40"],
        )
    )
    assert seen["gpu_memory_mode"] == "manual"
    assert seen["gpu_layers"] == 0
    assert seen["extra_args"] == ["--top-k", "40"]


def test_a_real_mac_keeps_its_offload_flags(monkeypatch):
    """The stripping is scoped to the fallback: a physical Mac must keep -ngl."""
    monkeypatch.setattr(llama_cpp, "_metal_device_is_paravirtual", lambda: False)
    backend = llama_cpp.LlamaCppBackend()
    seen = {}

    def _capture(intent):
        captured = asdict(intent)
        for _key in ("extra_args", "tensor_split", "gpu_ids"):
            if captured.get(_key) is not None:
                captured[_key] = list(captured[_key])
        seen.update(captured)
        return True

    monkeypatch.setattr(backend, "adopt_load_intent_if_matched", _capture)
    monkeypatch.setattr(backend, "_apply_detected_audio", lambda _d: True)
    backend._audio_probed = True
    backend._healthy = True
    backend.load_model(
        llama_cpp.GgufLoadIntent(
            model_identifier = "owner/repo",
            gguf_path = "/nonexistent/model.gguf",
            gpu_memory_mode = "auto",
            gpu_layers = -1,
            extra_args = ["-ngl", "99"],
        )
    )
    assert seen["gpu_memory_mode"] == "auto"
    assert seen["extra_args"] == ["-ngl", "99"]


def test_gpu_companions_are_pinned_to_cpu_too():
    """--gpu-layers 0 does not reach them: clip.cpp offloads per mmproj_use_gpu (default true), and
    the drafter's params.speculative.draft.n_gpu_layers defaults to -1 (auto)."""
    src = _load_model_source()
    assert '"--no-mmproj-offload"' in src
    # Drafter flag name comes from the probe, never a literal; --spec-draft-ngl needs b8955 or newer.
    assert (
        '"--spec-draft-ngl", "0"' not in src
    ), "hardcoding the flag defeats the capability probe on builds that only have -ngld"
    assert "_paravirtual_draft_ngl_flag(server_caps)" in src


@pytest.mark.parametrize(
    "caps, drops, pins",
    [
        ({"supports_no_mmproj_offload": False, "mtp_probe_inconclusive": False}, True, False),
        ({"supports_no_mmproj_offload": True, "mtp_probe_inconclusive": False}, False, True),
        # Unanswered probe must not drop vision: any launchable build has --no-mmproj-offload.
        ({"supports_no_mmproj_offload": False, "mtp_probe_inconclusive": True}, False, True),
    ],
)
def test_a_failed_probe_does_not_cost_the_user_their_projector(caps, drops, pins):
    mmproj, vision, _warnings = _mmproj_gate(
        paravirtual = True, caps = caps, mmproj = "/m/mmproj-F32.gguf", is_vision = True
    )
    assert (mmproj is None) is drops
    assert (vision is False) is drops
    assert llama_cpp._paravirtual_mmproj_pinnable(caps) is pins


@pytest.mark.parametrize(
    "caps, expected",
    [
        (
            {"spec_draft_ngl_flag": "--spec-draft-ngl", "mtp_probe_inconclusive": False},
            "--spec-draft-ngl",
        ),
        (
            {"spec_draft_ngl_flag": "--gpu-layers-draft", "mtp_probe_inconclusive": False},
            "--gpu-layers-draft",
        ),
        ({"spec_draft_ngl_flag": None, "mtp_probe_inconclusive": True}, "--gpu-layers-draft"),
        ({"spec_draft_ngl_flag": None, "mtp_probe_inconclusive": False}, None),
    ],
)
def test_the_drafter_pin_falls_back_before_it_gives_up(caps, expected):
    assert llama_cpp._paravirtual_draft_ngl_flag(caps) == expected


def test_a_failed_probe_does_not_cost_the_user_their_drafter():
    """The drop half of the same decision: an unanswered probe must not drop."""
    drafter, _extras, _warnings = _paravirtual_gate(
        caps = {"spec_draft_ngl_flag": None, "mtp_probe_inconclusive": True},
        drafter = "/m/mtp-model.gguf",
        extra_args = None,
    )
    assert drafter == "/m/mtp-model.gguf"


@pytest.mark.parametrize(
    "extras, kept",
    [
        (["-ot", ".*=Metal"], False),
        (["-ot=.*=Metal"], False),
        (["-otd", ".*=Metal"], False),
        (["--override-tensor", "blk.*=Metal"], False),
        (["-ot", "exps=CPU,attn=Metal"], False),
        (["-ot", "exps=CPU"], True),
        (["--override-tensor", "blk.*=CPU"], True),
        (["--top-k", "40"], True),
    ],
)
def test_only_gpu_bound_tensor_overrides_are_dropped(extras, kept):
    out = llama_cpp._paravirtual_strip_gpu_overrides(extras)
    assert (out == list(extras)) is kept


def test_the_override_strip_leaves_other_extras_alone():
    """Negative: stripping must not disturb neighbouring arguments."""
    out = llama_cpp._paravirtual_strip_gpu_overrides(
        ["--top-k", "40", "-ot", ".*=Metal", "--temp", "0.7"]
    )
    assert out == ["--top-k", "40", "--temp", "0.7"]


def _load_model_tree() -> ast.AST:
    return ast.parse(textwrap.dedent(_load_model_source()))


def test_the_companion_pins_are_keyed_on_the_hardware_not_the_request():
    """A caller already asking for Manual + 0 layers needs no placement rewrite, so
    skipping the whole block for it left _paravirtual_cpu_forced False and silently
    dropped the mmproj / drafter pins, which do not read --gpu-layers at all."""
    tree = _load_model_tree()
    assigns = [
        node
        for node in ast.walk(tree)
        if isinstance(node, ast.Assign)
        and any(isinstance(t, ast.Name) and t.id == "_paravirtual_cpu_forced" for t in node.targets)
    ]
    assert len(assigns) == 1, "the flag must have exactly one source of truth"
    (assign,) = assigns
    assert isinstance(assign.value, ast.Call)
    assert assign.value.func.id == "_metal_device_is_paravirtual"

    def _mentions(node, names):
        found = {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
        return names <= found

    for node in ast.walk(tree):
        if not isinstance(node, ast.If):
            continue
        if not _mentions(node.test, {"gpu_memory_mode", "gpu_layers"}):
            continue
        nested = [n for stmt in node.body for n in ast.walk(stmt)]
        assert (
            assign not in nested
        ), "_paravirtual_cpu_forced is gated on the requested placement again"


def test_a_user_owned_drafter_is_pinned_to_cpu_too():
    """A user --spec-type makes _build_speculative_flags emit nothing, so their
    --model-draft never appeared in spec_flags and the drafter kept running corrupt."""
    user_extras = ["--spec-type", "draft-simple", "--model-draft", "/models/d.gguf"]
    backend = llama_cpp.LlamaCppBackend()
    assert (
        backend._build_speculative_flags(
            speculative_type = "auto",
            spec_draft_n_max = None,
            extra_args = user_extras,
            model_identifier = "owner/repo",
            model_path = None,
            gpus = False,
            binary = None,
        )
        == []
    )
    assert llama_cpp._extra_args_mtp_draft_path([*[], *user_extras]) == "/models/d.gguf"
    assert llama_cpp._extra_args_mtp_draft_path(["--spec-type", "draft-mtp"], {}) is None

    tree = _load_model_tree()
    calls = [
        node
        for node in ast.walk(tree)
        if isinstance(node, ast.Call)
        and isinstance(node.func, ast.Name)
        and node.func.id == "_extra_args_mtp_draft_path"
    ]
    assert calls, "the drafter CPU pin no longer resolves a drafter path"
    assert any(
        {n.id for n in ast.walk(call) if isinstance(n, ast.Name)} >= {"spec_flags", "extra_args"}
        for call in calls
    ), "the pin still looks at spec_flags only, so a user-owned drafter is missed"


def test_the_drafter_cpu_pin_outlives_the_pass_through_extras():
    """llama.cpp is last-wins and the paravirtual strip covers only the main offload
    flags, so a user -ngld 99 after a managed --spec-draft-ngl 0 would put the drafter
    straight back on the corrupt device."""
    assert "-ngld" not in llama_server_args._OFFLOAD_SHADOWING_FLAGS
    assert "--spec-draft-ngl" not in llama_server_args._OFFLOAD_SHADOWING_FLAGS
    assert "-ngld" not in llama_server_args._SPEC_FLAGS
    assert (
        llama_cpp._extra_args_draft_offloaded_to_cpu(["--spec-draft-ngl", "0", "-ngld", "99"], {})
        is False
    )

    tree = _load_model_tree()
    extras_at = pin_at = None
    for node in ast.walk(tree):
        if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)):
            continue
        if node.func.attr != "extend":
            continue
        names = {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
        if "_emit_extra_args" in names:
            extras_at = node.lineno
        if "_pv_draft_cpu_pin" in names:
            pin_at = node.lineno
    assert extras_at is not None and pin_at is not None
    assert pin_at > extras_at, "the drafter CPU pin is emitted before the user extras"


class _FakeLogger:
    def __init__(self):
        self.warnings: list = []

    def warning(self, msg, *args):
        self.warnings.append(msg % args if args else msg)

    def info(self, msg, *args):
        pass


def _mmproj_gate(
    *,
    paravirtual: bool,
    caps: dict,
    is_vision: bool = True,
    mmproj = "/p.gguf",
):
    """Run load_model's real projector statements; report what the launch would see."""
    body = None
    for node in ast.walk(_load_model_tree()):
        stmts = getattr(node, "body", None)
        if not isinstance(stmts, list):
            continue
        starts = [
            i
            for i, s in enumerate(stmts)
            if isinstance(s, ast.Assign)
            and any(isinstance(t, ast.Name) and t.id == "launch_mmproj_path" for t in s.targets)
        ]
        ends = [
            i
            for i, s in enumerate(stmts)
            if isinstance(s, ast.If) and {"is_vision", "effective_is_vision"} <= _names(s.test)
        ]
        if starts and ends:
            body = stmts[starts[0] : ends[0] + 1]
            break
    assert body is not None, "the projector-resolution block moved out of load_model"
    log = _FakeLogger()
    scope = {
        **vars(llama_cpp),
        "extra_args": None,
        "extra_args_disable_mmproj": lambda _a: False,
        "self": types.SimpleNamespace(
            _resolve_launch_mmproj_path = lambda **_kw: mmproj,
        ),
        "model_path": "/m.gguf",
        "mmproj_path": None,
        "disable_vision": False,
        "_paravirtual_cpu_forced": paravirtual,
        "server_caps": caps,
        "is_vision": is_vision,
        "logger": log,
    }
    exec(ast.unparse(ast.Module(body = body, type_ignores = [])), scope)
    return scope["launch_mmproj_path"], scope["effective_is_vision"], log.warnings


def test_a_projector_that_cannot_be_pinned_is_dropped():
    """clip.cpp never reads --gpu-layers, so without --no-mmproj-offload the vision
    encoder stays on the virtualised device. Serving image embeddings built from corrupt
    output is the failure being prevented, so drop the projector."""
    path, vision, warnings = _mmproj_gate(paravirtual = True, caps = {})
    assert path is None
    assert vision is False
    assert any("--no-mmproj-offload" in w for w in warnings), "the reason must be named"
    assert any("unsloth studio update" in w for w in warnings), "the fix must be named"


def test_dropping_the_projector_does_not_double_warn():
    """Exactly one warning: the generic no-usable-mmproj line would blame a missing projector."""
    _path, _vision, warnings = _mmproj_gate(paravirtual = True, caps = {})
    assert len(warnings) == 1, warnings


def test_a_pinnable_projector_survives_on_the_same_hardware():
    """The negative that matters most: a build WITH the flag keeps vision, since
    --no-mmproj-offload puts the encoder on the CPU where it is correct."""
    path, vision, warnings = _mmproj_gate(
        paravirtual = True, caps = {"supports_no_mmproj_offload": True}
    )
    assert path == "/p.gguf"
    assert vision is True
    assert warnings == []


def test_a_real_mac_keeps_vision_on_a_build_without_the_flag():
    """Drop is scoped to the virtualised device; physical hardware keeps the projector on GPU."""
    path, vision, warnings = _mmproj_gate(paravirtual = False, caps = {})
    assert path == "/p.gguf"
    assert vision is True
    assert warnings == []


def test_a_text_only_gguf_is_unaffected_either_way():
    """No projector to drop, so the guard must not manufacture a warning."""
    for caps in ({}, {"supports_no_mmproj_offload": True}):
        path, vision, warnings = _mmproj_gate(
            paravirtual = True, caps = caps, is_vision = False, mmproj = None
        )
        assert path is None
        assert vision is False
        assert warnings == []


def test_the_drop_precedes_everything_the_projector_feeds():
    """launch_mmproj_path drives the --mmproj flag, the mmproj VRAM budget and the
    capability probe, so clearing it later would launch a projector the guard believes
    it dropped (or offer audio or image input that is gone)."""
    src = _load_model_source()
    gate_at = src.index("_pv_mmproj_unpinnable = bool(")
    assert gate_at < src.index('cmd.extend(["--mmproj", launch_mmproj_path])')
    assert gate_at < src.index("self._mmproj_vram_bytes(launch_mmproj_path)")
    assert gate_at < src.index("_mmproj_probe = launch_mmproj_path or (")
    assert gate_at < src.index("mmproj_capabilities(_mmproj_probe)")
    assert "self._is_vision = effective_is_vision" in src


def _drafter_gate(
    *,
    paravirtual: bool,
    caps: dict,
    drafter = "/models/mtp-gemma.gguf",
    extra_args = None,
):
    """Runs load_model's real unpinnable-drafter code and reports the drafter and warnings."""
    scope, warnings = _drafter_gate_scope(
        paravirtual = paravirtual, caps = caps, drafter = drafter, extra_args = extra_args
    )
    return scope["launch_mtp_draft_path"], scope["extra_args"], warnings


def _drafter_gate_scope(
    *,
    paravirtual: bool,
    caps: dict,
    drafter = "/models/mtp-gemma.gguf",
    extra_args = None,
    suppressed = None,
):
    """The same statements, returning the scope, for callers reading more than the drafter."""
    body = None
    for node in ast.walk(_load_model_tree()):
        stmts = getattr(node, "body", None)
        if not isinstance(stmts, list):
            continue
        starts = [
            i
            for i, s in enumerate(stmts)
            if isinstance(s, ast.Assign)
            and any(isinstance(t, ast.Name) and t.id == "_pv_draft_unpinnable" for t in s.targets)
        ]
        ends = [
            i
            for i, s in enumerate(stmts)
            if isinstance(s, ast.If)
            and isinstance(s.test, ast.Name)
            and s.test.id == "_pv_draft_unpinnable"
        ]
        if starts and ends:
            body = stmts[starts[0] : ends[0] + 1]
            break
    assert body is not None, "the unpinnable-drafter block moved out of load_model"
    log = _FakeLogger()
    scope = {
        **vars(llama_cpp),
        "_paravirtual_cpu_forced": paravirtual,
        "server_caps": caps,
        "launch_mtp_draft_path": drafter,
        "extra_args": list(extra_args) if extra_args else extra_args,
        "_extra_args_mtp_draft_path": llama_cpp._extra_args_mtp_draft_path,
        "_extra_args_draft_offloaded_to_cpu": llama_cpp._extra_args_draft_offloaded_to_cpu,
        "_extra_args_requests_mtp": llama_cpp._extra_args_requests_mtp,
        "_child_spec_env": llama_cpp._child_spec_env,
        "strip_shadowing_flags": llama_cpp.strip_shadowing_flags,
        "n_parallel": 1,
        "cmd": ["--parallel", "1"],
        "logger": log,
        "_suppressed_draft_path": suppressed,
    }
    exec(ast.unparse(ast.Module(body = body, type_ignores = [])), scope)
    return scope, log.warnings


def _paravirtual_gate(
    *args,
    caps = {},
    drafter = None,
    paravirtual = True,
    **kwargs,
):
    """_drafter_gate on a paravirtual host with no drafter and no probed caps."""
    return _drafter_gate(*args, caps = caps, drafter = drafter, paravirtual = paravirtual, **kwargs)


@pytest.fixture(autouse = True)
def _no_inherited_draft_env(monkeypatch):
    """Parsers fall back to os.environ, so a stray host variable must not decide the case."""
    for var in (
        "LLAMA_ARG_SPEC_DRAFT_MODEL",
        "LLAMA_ARG_SPEC_DRAFT_HF_REPO",
        "LLAMA_ARG_N_GPU_LAYERS_DRAFT",
    ):
        monkeypatch.delenv(var, raising = False)


def test_a_drafter_that_cannot_be_pinned_is_dropped(monkeypatch):
    """A separate drafter takes params.speculative.draft.n_gpu_layers (default -1 = auto),
    not the main --gpu-layers, so without a draft-layer flag it runs full-offload on the
    virtualised device."""
    drafter, extras, warnings = _drafter_gate(paravirtual = True, caps = {})
    assert drafter is None
    assert any("draft-layer flag" in w for w in warnings), "the reason must be named"
    assert any("unsloth studio update" in w for w in warnings), "the fix must be named"
    # Speculation cannot change emitted tokens, so the warning must not claim wrong output.
    assert not any("corrupt output" in w for w in warnings), warnings
    assert any("only costs speed" in w for w in warnings), warnings
    # Without extras --spec-type the launch scrubs LLAMA_ARG_SPEC_DRAFT_*, so no drop needed.
    monkeypatch.setenv("LLAMA_ARG_SPEC_DRAFT_MODEL", "/models/env.gguf")
    tuning = ["--spec-draft-n-max", "6"]
    drafter, extras, warnings = _paravirtual_gate(extra_args = tuning)
    assert warnings == []
    assert extras == tuning
    owned = ["--spec-type", "draft-simple"]
    drafter, _extras, warnings = _paravirtual_gate(extra_args = owned)
    assert any("draft-layer flag" in w for w in warnings), warnings


def test_the_drop_takes_a_user_owned_drafter_with_it():
    """Under a user --spec-type nothing is emitted, so clearing the path leaves --model-draft."""
    extras = ["--spec-type", "draft-simple", "--model-draft", "/models/d.gguf", "--top-k", "40"]
    drafter, out, warnings = _paravirtual_gate(extra_args = extras)
    assert drafter is None
    assert warnings
    assert llama_cpp._extra_args_mtp_draft_path(out, {}) is None
    assert "--spec-type" not in out and "draft-simple" not in out
    assert out == ["--top-k", "40"]


def test_a_drafter_free_spec_mode_keeps_the_speculation_it_asked_for():
    """Ngram modes load no drafter, so a sibling mtp-*.gguf must not cost the user their requested mode."""
    extras = [
        "--spec-type",
        "ngram-mod",
        "--spec-ngram-mod-n-max",
        "5",
        "--spec-ngram-mod-n-min",
        "2",
        "--top-k",
        "40",
    ]
    drafter, out, warnings = _drafter_gate(paravirtual = True, caps = {}, extra_args = extras)
    assert drafter == "/models/mtp-gemma.gguf"
    assert out == extras
    assert warnings == []


def test_a_sibling_drafter_still_goes_when_unsloth_owns_the_spec_block():
    """The negative for the case above: with no user --spec-type the resolver may emit
    --model-draft for the sibling, so it is a real placement and still drops."""
    drafter, out, warnings = _drafter_gate(paravirtual = True, caps = {}, extra_args = ["--top-k", "40"])
    assert drafter is None
    assert out == ["--top-k", "40"]
    assert warnings


def test_a_drafter_requiring_mode_still_loses_its_drafter():
    """draft-simple and draft-eagle3 load a separate model, so a user-owned spec type is no exemption."""
    for mode in ("draft-simple", "draft-eagle3"):
        extras = ["--spec-type", mode, "--model-draft", "/models/d.gguf", "--top-k", "40"]
        drafter, out, warnings = _drafter_gate(paravirtual = True, caps = {}, extra_args = extras)
        assert drafter is None
        assert out == ["--top-k", "40"]
        assert warnings


def test_a_drafter_free_mode_that_names_its_own_drafter_still_drops_it():
    """llama.cpp loads any set draft path, so --model-draft under ngram-mod still hits the device."""
    extras = ["--spec-type", "ngram-mod", "--model-draft", "/models/d.gguf"]
    drafter, out, warnings = _drafter_gate(paravirtual = True, caps = {}, extra_args = extras)
    assert drafter is None
    assert llama_cpp._extra_args_mtp_draft_path(out, {}) is None
    assert warnings


def test_an_inherited_drafter_env_is_not_exempted_by_a_drafter_free_mode(monkeypatch):
    """Drafter-free mode does not exempt the inherited env: child loads what --spec-type says."""
    monkeypatch.setenv("LLAMA_ARG_SPEC_DRAFT_MODEL", "/models/env.gguf")
    drafter, _out, warnings = _paravirtual_gate(extra_args = ["--spec-type", "ngram-mod"])
    assert drafter is None
    assert warnings


def test_a_real_mac_keeps_the_sibling_and_the_mode_alike():
    """Exemption changes nothing off the virtualised device; physical Macs keep both."""
    extras = ["--spec-type", "ngram-mod", "--model-draft", "/models/d.gguf"]
    drafter, out, warnings = _drafter_gate(paravirtual = False, caps = {}, extra_args = extras)
    assert drafter == "/models/mtp-gemma.gguf"
    assert out == extras
    assert warnings == []


def test_the_env_the_child_inherits_is_dropped_too():
    """argv cannot un-set LLAMA_ARG_SPEC_DRAFT_MODEL; llama.cpp appends spec types, so scrub the env."""
    src = _load_model_source()
    for var in (
        "LLAMA_ARG_SPEC_DRAFT_MODEL",
        "LLAMA_ARG_SPEC_DRAFT_HF_REPO",
        "LLAMA_ARG_SPEC_TYPE",
        "LLAMA_ARG_MODEL_DRAFT",
        "LLAMA_ARG_HFD_REPO",
    ):
        assert (
            var in llama_cpp._SPEC_ENV_VARS
        ), f"{var} survives the drafter drop into the child env"
    gate_at = src.index("for _pv_spec_var in _SPEC_ENV_VARS")
    assert "env.pop(_pv_spec_var, None)" in src[gate_at : gate_at + 200]


def test_a_managed_spec_block_clears_the_inherited_spec_env():
    """llama.cpp appends spec types, so argv cannot undo an inherited LLAMA_ARG_SPEC_TYPE; clear it."""
    src = _load_model_source()
    at = src.index("for _pv_spec_var in _SPEC_ENV_VARS")
    gate = src[src.rindex("if ", 0, at) : at]
    assert "not _extra_args_set_spec_type(extra_args)" in gate
    assert "_pv_draft_unpinnable" in gate


def test_the_training_guard_sizes_the_cpu_pin_not_the_raw_request():
    """Raw Auto request overstates VRAM: load_model rewrites GGUF placement to CPU first."""
    guard_src = inspect.getsource(_routes()._guard_chat_load_against_training)
    assert "_metal_device_is_paravirtual()" in guard_src
    assert "paravirtual_normalized_request(" in guard_src
    assert guard_src.index("paravirtual_normalized_request(") < guard_src.index(
        'gpu_memory_mode == "manual"'
    )


def test_a_diffusion_split_that_cannot_be_pinned_is_refused():
    """cpu_only checks torch.cuda alone, so a shim without --ngl must be refused, not left on Metal."""
    src = inspect.getsource(llama_cpp.LlamaCppBackend._start_diffusion_server)
    drop_at = src.index("not _shim_supports_ngl(shim_cmd)")
    guard = src[drop_at : drop_at + 700]
    assert "_metal_device_is_paravirtual()" in guard
    assert "_PARAVIRTUAL_DIFFUSION_NO_NGL_ERROR" in guard
    assert "manual_ngl == 0" in guard
    assert guard.index("raise ValueError") < guard.index("logger.warning")
    msg = llama_cpp._PARAVIRTUAL_DIFFUSION_NO_NGL_ERROR
    assert "unsloth studio update" in msg
    assert "UNSLOTH_ALLOW_PARAVIRTUAL_METAL=1" in msg
    load_src = _load_model_source()
    assert load_src.index("_PARAVIRTUAL_DIFFUSION_NO_NGL_ERROR") < load_src.index(
        "self._kill_process()"
    )


def test_the_hf_diffusion_refusal_also_lands_above_the_teardown():
    """An HF load has no gguf_path before Phase 1, so the refusal used to fire after the healthy
    server was killed and the model downloaded; the cheap shim probe now gates the preflight."""
    src = _load_model_source()
    probe_at = src.index("_pv_diffusion_unpinnable = bool(")
    kill_at = src.index("self._kill_process()")
    assert probe_at < kill_at
    hf_raise = src.index("if _pv_diffusion_unpinnable:\n                        raise ValueError(")
    assert hf_raise < kill_at
    assert "or _pv_diffusion_unpinnable" in src[: src.index("_preflight_is_diffusion =")]


def test_the_crash_replay_keeps_the_extras_the_caller_still_sends():
    """The replay launches a stripped list but the caller keeps sending the original, so
    a comparator seeing only the stripped one would reload the MTP setup that crashed."""
    src = inspect.getsource(llama_cpp.LlamaCppBackend._maybe_recover_from_mtp_crash)
    load_at = src.index("self.load_model(fallback)")
    restore_at = src.index("self._requested_extra_args = (")
    assert load_at < restore_at
    assert "if fallback_extra_args is not snapshot.extra_args:" in src
    assert "self._strip_device_extra_args(_ea)" in src


def test_a_pinnable_drafter_survives_on_the_same_hardware():
    """The negative that matters most: a build WITH a draft-layer flag keeps its drafter,
    because --spec-draft-ngl 0 puts it on the CPU where it is correct."""
    extras = ["--model-draft", "/models/d.gguf"]
    drafter, out, warnings = _drafter_gate(
        paravirtual = True,
        caps = {"spec_draft_ngl_flag": "--spec-draft-ngl"},
        extra_args = extras,
    )
    assert drafter == "/models/mtp-gemma.gguf"
    assert out == extras
    assert warnings == []
    drafter, out, warnings = _drafter_gate(
        paravirtual = True,
        caps = {"spec_draft_ngl_flag": "--gpu-layers-draft"},
        extra_args = extras,
    )
    assert drafter == "/models/mtp-gemma.gguf"
    assert out == extras
    assert warnings == []


@pytest.mark.parametrize(
    "pin",
    [
        ["--spec-draft-ngl", "0"],
        ["-ngld", "0"],
        ["--gpu-layers-draft=0"],
        ["--spec-draft-device", "cpu"],
        ["--device-draft", "none"],
    ],
)
def test_a_drafter_the_user_already_pinned_is_left_alone(pin):
    """The probe only decides whether the flag can be emitted; a user-pinned drafter is already on CPU."""
    extras = [*pin, "--model-draft", "/models/d.gguf"]
    drafter, out, warnings = _drafter_gate(paravirtual = True, caps = {}, extra_args = extras)
    assert drafter == "/models/mtp-gemma.gguf"
    assert out == extras
    assert warnings == []
    overridden = ["--spec-draft-ngl", "0", "-ngld", "99", "--model-draft", "/models/d.gguf"]
    drafter, _out, warnings = _drafter_gate(paravirtual = True, caps = {}, extra_args = overridden)
    assert drafter is None
    assert warnings


def test_a_real_mac_keeps_its_drafter():
    """Drop only hits the virtualised device; physical Apple Silicon keeps the drafter on GPU."""
    extras = ["--spec-type", "draft-simple", "--model-draft", "/models/d.gguf"]
    drafter, out, warnings = _drafter_gate(paravirtual = False, caps = {}, extra_args = extras)
    assert drafter == "/models/mtp-gemma.gguf"
    assert out == extras
    assert warnings == []


def test_a_load_with_no_separate_drafter_is_unaffected():
    """With no separate drafter, nothing is dropped: an embedded MTP head already follows --gpu-layers 0."""
    for caps in ({}, {"spec_draft_ngl_flag": "--spec-draft-ngl"}):
        extras = ["--spec-type", "draft-mtp", "--spec-draft-n-max", "2"]
        drafter, out, warnings = _paravirtual_gate(caps = caps, extra_args = extras)
        assert drafter is None
        assert out == extras
        assert warnings == []
    drafter, out, warnings = _drafter_gate(paravirtual = True, caps = {}, drafter = None)
    assert (drafter, out, warnings) == (None, None, [])


def test_mtp_detection_reads_every_accumulated_type():
    """llama.cpp inserts each --spec-type rather than replacing, and applies the env
    first, so MTP is on if ANY source names it. The VRAM budget rides on reading them all."""
    f = llama_cpp._extra_args_requests_mtp
    env = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}
    assert f(["--spec-type", "ngram-mod"], env) is True
    assert f(["--spec-type", "draft-mtp", "--spec-type", "ngram-mod"], {}) is True
    assert f(["--spec_type=draft-mtp"], {}) is True
    assert f([], env) is True
    assert f(None, {}) is False
    assert f(["--spec-type", "ngram-mod"], {}) is False
    assert f(["--spec-default"], {}) is False


def test_a_diffusion_load_drops_the_drafter_state_it_inherits():
    """Diffusion returns before recording the drafter; only unload clears it, so a stale drafter
    would make the dedupe reload a healthy diffusion server."""
    src = _load_model_source()
    at = src.index("self._layer_preserves_tensor_intent = False")
    tail = src[at : at + 600]
    assert "self._mtp_draft_path = None" in tail
    assert "self._mtp_draft_suppressed_path = None" in tail
    assert at < src.index("return self._start_diffusion_server(")


def test_the_drafter_pin_covers_the_device_not_just_the_layers():
    """common_base_params_to_speculative replaces the draft device list; --device none never reaches it."""
    src = _load_model_source()
    pin_at = src.index("_pv_draft_cpu_pin = [")
    pin = src[pin_at : src.index("]", pin_at)]
    assert "--device-draft" in pin
    assert '"none"' in pin
    cmd = ["llama-server", "-md", "d.gguf", "--gpu-layers-draft", "0", "--device-draft", "none"]
    assert llama_cpp._extra_args_draft_offloaded_to_cpu(cmd) is True
    assert llama_cpp.LlamaCppBackend._cmd_has_gpu_companion(cmd, {}) is False


def test_the_drafter_drop_precedes_the_flags_it_feeds():
    """launch_mtp_draft_path becomes --model-draft and extra_args the pass-through tail,
    so clearing either after _build_speculative_flags ran would launch a drafter the
    guard believes it dropped."""
    src = _load_model_source()
    gate_at = src.index("_pv_draft_unpinnable = bool(")
    assert gate_at < src.index("spec_flags = self._build_speculative_flags(")
    assert gate_at < src.index("cmd.extend(str(a) for a in _emit_extra_args)")
    assert gate_at < src.index("_pv_draft_cpu_pin = [")


@pytest.mark.parametrize(
    "extra_args, expected",
    [
        # -sm row fails in make_gpu_buft_list before layer assignment; Metal is always listed.
        (["-sm", "row"], ["--split-mode", "layer"]),
        (["--split-mode", "row"], ["--split-mode", "layer"]),
        (["--top-k", "40", "-sm", "tensor"], ["--split-mode", "layer"]),
        (["-sm", "none"], ["--split-mode", "layer"]),
        (["-sm=row"], ["--split-mode", "layer"]),
        (None, []),
        ([], []),
        (["--top-k", "40"], []),
        (["-sm", "layer"], []),
        (["--split-mode", "LAYER"], []),
        (["-sm", "row", "--split-mode", "layer"], []),
        (["--split-mode", "layer", "-sm", "row"], ["--split-mode", "layer"]),
        # --tensor-split is inert at --gpu-layers 0.
        (["-ts", "3,1"], []),
        (["--tensor-split", "3,1"], []),
    ],
)
def test_a_pass_through_split_mode_cannot_fail_the_cpu_only_load(extra_args, expected):
    assert llama_cpp._paravirtual_split_mode_pin(extra_args) == expected


def test_the_split_mode_override_is_scoped_to_the_virtualised_mac():
    """Real Macs keep the user's row/none split; the call site gates on the detector, not zero layers."""
    tree = _load_model_tree()
    calls = [
        node
        for node in ast.walk(tree)
        if isinstance(node, ast.Call)
        and isinstance(node.func, ast.Name)
        and node.func.id == "_paravirtual_split_mode_pin"
    ]
    assert len(calls) == 1, "expected exactly one split-mode override call site"
    guarded = False
    for node in ast.walk(tree):
        if not isinstance(node, ast.If):
            continue
        if not any(calls[0] in ast.walk(stmt) for stmt in node.body):
            continue
        assert {n.id for n in ast.walk(node.test) if isinstance(n, ast.Name)} == {
            "_paravirtual_cpu_forced"
        }, "the split-mode override is no longer gated on the hardware alone"
        guarded = True
    assert guarded, "the split-mode override lost its _paravirtual_cpu_forced guard"


def test_the_split_mode_override_outlives_the_pass_through_extras():
    """llama.cpp is last-wins, so an override placed before the user's extras gets undone."""
    # Overridden, not stripped: comparators compare stored extras verbatim.
    assert "-sm" not in llama_server_args._OFFLOAD_SHADOWING_FLAGS
    assert "--split-mode" not in llama_server_args._OFFLOAD_SHADOWING_FLAGS
    assert llama_server_args.resolve_tensor_parallel(["-sm", "tensor"], False) is True
    assert (
        llama_server_args.resolve_tensor_parallel(["-sm", "tensor", "--split-mode", "layer"], False)
        is False
    ), "the override must also clear the tensor state the zero-VRAM mask reads"

    tree = _load_model_tree()
    extras_at = pin_at = None
    for node in ast.walk(tree):
        if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)):
            continue
        if node.func.attr != "extend":
            continue
        names = {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
        if "_emit_extra_args" in names:
            extras_at = node.lineno
        if "_pv_split_mode_pin" in names:
            pin_at = node.lineno
    assert extras_at is not None and pin_at is not None
    assert pin_at > extras_at, "the split-mode override is emitted before the user extras"


def test_the_mtp_read_judges_the_env_the_child_will_actually_get():
    """An inherited draft-mtp is scrubbed whenever Unsloth owns the spec block, so os.environ would
    describe a server without MTP; the env counts only when extras own --spec-type."""
    env = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}
    assert llama_cpp._child_spec_env([]) == {}
    assert llama_cpp._extra_args_requests_mtp([], llama_cpp._child_spec_env([])) is False
    extras = ["--spec-type", "ngram-mod"]
    assert (
        llama_cpp._extra_args_requests_mtp(extras, llama_cpp._child_spec_env(extras, env)) is True
    )
    src = _load_model_source()
    assert "_child_spec_env(extra_args)" in src
    assert "_extra_args_requests_mtp(extra_args, env = {})" not in src


def test_the_training_guard_does_not_shrink_itself_for_mtp():
    """MTP launches at the slots it asked for; under-sizing evicts the training run it guards."""
    route_src = inspect.getsource(_routes())
    assert "_extra_args_requests_mtp(llama_extra_args" not in route_src
    assert "if diffusion_kind is True:" in route_src
    assert 'caps.get("supports_kv_unified")' in route_src


def _if_block(predicate, tree = None):
    """The one `if` statement in load_model whose test satisfies `predicate`."""
    found = [
        node
        for node in ast.walk(tree if tree is not None else _load_model_tree())
        if isinstance(node, ast.If) and predicate(node.test)
    ]
    assert len(found) == 1, f"expected exactly one matching block, found {len(found)}"
    return found[0]


def _names(node) -> set:
    return {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}


def _is_retry_spec_strip(test) -> bool:
    return "_launch_spec_env" in _names(test)


def test_the_startup_retry_drops_the_mtp_the_extras_and_the_env_carry():
    """Spec types append, so a trailing --spec-default cannot override MTP; retry must strip the group."""
    src = _load_model_source()
    retry = src[src.index("_fb_tail = cmd[_spec_at") : src.index("fallback_cmd = cmd[:_spec_at]")]
    compact = "".join(retry.split())
    assert "_extra_args_requests_mtp(extra_args,env=_launch_spec_env)" in compact
    assert "_extra_args_requests_dspark(extra_args,env=_launch_spec_env)" in compact
    assert "strip_spec = True" in retry
    assert "env.pop(_fb_spec_var, None)" in retry
    assert llama_cpp.strip_shadowing_flags(
        ["--spec-type", "draft-mtp", "--top-k", "40"],
        strip_context = False,
        strip_cache = False,
        strip_spec = True,
        strip_template = False,
        strip_split_mode = False,
    ) == ["--top-k", "40"]


def test_the_startup_fallback_records_the_extras_it_actually_launched():
    """The fallback launched without the spec group, so keeping the MTP list as launched lets the
    next Apply inherit it and repeat the crash; only the requested state keeps it."""
    src = _load_model_source()
    strip_at = src.index("_fb_stripped_extras = strip_shadowing_flags(")
    swap_at = src.index("extra_args = _fb_stripped_extras")
    record_at = src.index("self._extra_args = (")
    assert strip_at < swap_at < record_at, "the swap must land before the launch is recorded"
    kept = src[src.index("_pv_suppressed_spec_extra_args = (", swap_at - 400) : swap_at]
    assert "list(extra_args or [])" in kept
    assert src.index("_mtp_active_for_launched_server = False", 0, swap_at) < swap_at


def _loaded_cpu_backend(monkeypatch, tmp_path):
    """A healthy paravirtual CPU server, plus the drafter still sitting on disk."""
    _paravirtual(monkeypatch)
    monkeypatch.setattr(
        llama_cpp.LlamaCppBackend, "_kill_orphaned_servers", staticmethod(lambda: 0)
    )
    backend = llama_cpp.LlamaCppBackend()
    backend._process = _FakeProcess()
    backend._healthy = True
    backend._audio_probed = True
    backend._model_identifier = "owner/repo"
    gguf = tmp_path / "model.gguf"
    gguf.write_bytes(b"GGUF")
    drafter = tmp_path / "mtp-model.gguf"
    drafter.write_bytes(b"GGUF")
    backend._gguf_path = str(gguf)
    backend._requested_n_ctx = 8192
    backend._requested_n_parallel = 1
    backend._requested_spec_mode = "auto"
    backend._gpu_memory_mode = "manual"
    backend._gpu_layers = 0
    return backend, gguf, drafter


def _target_state(backend, gguf, **overrides):
    kwargs = dict(
        model_identifier = "owner/repo",
        gguf_path = str(gguf),
        hf_variant = None,
        n_ctx = 8192,
        cache_type_kv = None,
        speculative_type = None,
        chat_template_override = None,
        extra_args = None,
        is_vision = False,
        gpu_memory_mode = "manual",
        gpu_layers = 0,
        n_parallel = 1,
    )
    kwargs.update(overrides)
    return backend.adopt_load_intent_if_matched(llama_cpp.GgufLoadIntent(**kwargs))


def _target_state_auto(
    *args,
    gpu_layers = -1,
    gpu_memory_mode = "auto",
    speculative_type = "auto",
    **kwargs,
):
    """_target_state for a full-offload auto load, the shape every case here starts from."""
    return _target_state(
        *args,
        gpu_layers = gpu_layers,
        gpu_memory_mode = gpu_memory_mode,
        speculative_type = speculative_type,
        **kwargs,
    )


def _gpu_pin_recorders():
    """Every `if` in load_model that writes self._gpu_ids, in source order. load_model
    records the pin more than once, so judging one site would miss a later overwrite."""
    tree = _load_model_tree()
    found = [
        node
        for node in ast.walk(tree)
        if isinstance(node, ast.If)
        and any(
            isinstance(n, ast.Attribute) and n.attr == "_gpu_ids" and isinstance(n.ctx, ast.Store)
            for stmt in [*node.body, *node.orelse]
            for n in ast.walk(stmt)
        )
    ]
    assert found, "no _gpu_ids recording block found in load_model"
    # ast.walk descends into elif chains; skip else-branch ifs to keep their guard.
    nested = {id(alt) for node in found for alt in node.orelse if isinstance(alt, ast.If)}
    return sorted((n for n in found if id(n) not in nested), key = lambda n: n.lineno)


def test_a_forced_cpu_launch_records_no_effective_gpu_pin():
    """--device none runs no GPU, so an echoed pin misreports /status and reloads on clear."""
    scope = {
        "self": types.SimpleNamespace(_gpu_ids = None, _requested_gpu_ids = None),
        "_paravirtual_cpu_forced": True,
        "is_vulkan_backend": False,
        "gpu_ids": [0],
        "gpu_indices": [0],
        "_vulkan_pin_ids": None,
        "_vulkan_explicit_unmatched": False,
    }
    for node in _gpu_pin_recorders():
        exec(ast.unparse(node), {}, scope)
        assert scope["self"]._gpu_ids is None, f"recorder at line {node.lineno} re-pinned a GPU"
    backend = llama_cpp.LlamaCppBackend.__new__(llama_cpp.LlamaCppBackend)
    backend._is_diffusion = False
    backend._requested_gpu_ids, backend._gpu_ids = [0], None
    assert backend.matches_gpu_ids([0]) is True
    assert backend.matches_gpu_ids(None) is True


def test_a_forced_cpu_diffusion_runner_records_no_effective_gpu_pin():
    """A zero-layer split on virtualised Metal masks devices, so recording the pick misreports
    /status and reloads the CPU runner on clear; the pick must still round-trip."""
    src = inspect.getsource(llama_cpp.LlamaCppBackend._start_diffusion_server)
    assert "_pv_diffusion_cpu = manual_ngl == 0 and _metal_device_is_paravirtual()" in src
    assert "self._gpu_ids = _pinned if not _pv_diffusion_cpu else None" in src

    backend = llama_cpp.LlamaCppBackend.__new__(llama_cpp.LlamaCppBackend)
    backend._is_diffusion = True
    backend._gpu_ids, backend._requested_gpu_ids = None, [1]
    assert backend.matches_gpu_ids([1]) is True  # re-sending the pick must not reload
    assert backend.matches_gpu_ids(None) is True
    backend._gpu_ids = backend._requested_gpu_ids = [1]
    assert backend.matches_gpu_ids([0]) is False


def test_a_real_mac_still_records_the_gpu_it_pinned(monkeypatch):
    """The negative: on physical Apple Silicon the pick is effective and must be echoed."""
    monkeypatch.setattr(llama_cpp, "_metal_device_is_paravirtual", lambda: False)
    backend = llama_cpp.LlamaCppBackend.__new__(llama_cpp.LlamaCppBackend)
    backend._is_diffusion = False
    backend._requested_gpu_ids = backend._gpu_ids = [0]
    assert backend.matches_gpu_ids(None) is False  # dropping a real pin must reload


def test_a_suppressed_drafter_does_not_reload_the_server_it_left_healthy(monkeypatch, tmp_path):
    """Caller keeps sending the drafter after a drop; comparing with stored None respawns on each Apply."""
    backend, gguf, drafter = _loaded_cpu_backend(monkeypatch, tmp_path)
    backend._mtp_draft_path = None
    backend._mtp_draft_suppressed_path = str(drafter)

    def _never(*args, **kwargs):  # pragma: no cover - must never run
        raise AssertionError("tore down a healthy server on a duplicate /load")

    # Binary lookup is on the fast path (revision check); fixed path keeps it unchanged.
    monkeypatch.setattr(
        backend, "_find_llama_server_binary", lambda *a, **k: "/nonexistent/llama-server"
    )
    monkeypatch.setattr(backend, "_kill_process", _never)

    assert (
        backend.load_model(
            llama_cpp.GgufLoadIntent(
                model_identifier = "owner/repo",
                gguf_path = str(gguf),
                mtp_draft_path = str(drafter),
                n_ctx = 8192,
                gpu_memory_mode = "auto",
                gpu_layers = -1,
                n_parallel = 1,
            )
        )
        is True
    )


def test_the_route_dedupe_reads_the_suppressed_drafter_too(monkeypatch, tmp_path):
    """Route re-detects the sibling; backend-only handling would still reload on every Apply."""
    from models.inference import LoadRequest
    from routes.inference import _active_gguf_intent

    _paravirtual_everywhere(monkeypatch)
    monkeypatch.setattr(
        llama_cpp.LlamaCppBackend, "_kill_orphaned_servers", staticmethod(lambda: 0)
    )
    gguf = tmp_path / "model.gguf"
    gguf.write_bytes(b"GGUF")
    drafter = tmp_path / "mtp-model.gguf"
    drafter.write_bytes(b"GGUF")
    backend = llama_cpp.LlamaCppBackend()
    backend._process = _FakeProcess()
    backend._healthy = True
    backend._model_identifier = str(gguf)
    backend._gguf_path = str(gguf)
    backend._requested_n_ctx = 4096
    backend._requested_n_parallel = 1
    backend._mtp_draft_path = None
    backend._mtp_draft_suppressed_path = str(drafter)
    backend._gpu_memory_mode = "manual"
    backend._gpu_layers = 0
    request = LoadRequest(model_path = str(gguf), max_seq_length = 4096)

    def _intent():
        return _active_gguf_intent(
            request,
            backend,
            model_identifier = str(gguf),
            chat_template_override = None,
            n_parallel = 1,
            native_grant_backed = False,
        )

    assert backend.adopt_load_intent_if_matched(_intent())
    backend._mtp_draft_suppressed_path = None
    assert not backend.adopt_load_intent_if_matched(_intent())


def test_a_drafter_that_genuinely_appeared_still_reloads(monkeypatch, tmp_path):
    """No suppression on record: a drafter dropped beside the weights still forces reload."""
    backend, gguf, drafter = _loaded_cpu_backend(monkeypatch, tmp_path)
    backend._mtp_draft_path = None
    backend._mtp_draft_suppressed_path = None
    assert _target_state(backend, gguf, mtp_draft_path = str(drafter)) is False


def test_only_the_drafter_that_was_suppressed_dedupes(monkeypatch, tmp_path):
    """Another drafter, or the suppressed one vanishing, is a real change; the match is exact."""
    backend, gguf, drafter = _loaded_cpu_backend(monkeypatch, tmp_path)
    backend._mtp_draft_path = None
    backend._mtp_draft_suppressed_path = str(drafter)
    other = tmp_path / "mtp-other.gguf"
    other.write_bytes(b"GGUF")
    assert _target_state(backend, gguf, mtp_draft_path = str(other)) is False
    assert _target_state(backend, gguf, mtp_draft_path = None) is False
    assert _target_state(backend, gguf, mtp_draft_path = str(drafter)) is True


def test_the_suppression_does_not_outlive_the_server(monkeypatch, tmp_path):
    """Unload clears the suppression beside the launched path; an update unloads first to lift it."""
    backend, _gguf, drafter = _loaded_cpu_backend(monkeypatch, tmp_path)
    backend._mtp_draft_suppressed_path = str(drafter)
    backend.unload_model()
    assert backend.mtp_draft_suppressed_path is None


def test_a_launched_drafter_records_no_suppression(monkeypatch, tmp_path):
    """A build that can pin the drafter launches it, so nothing is suppressed."""
    backend, _gguf, _drafter = _loaded_cpu_backend(monkeypatch, tmp_path)
    assert backend.mtp_draft_suppressed_path is None
    src = _load_model_source()
    assert src.index("_suppressed_draft_path = launch_mtp_draft_path") < src.index(
        "                    launch_mtp_draft_path = None"
    )
    assert "self._mtp_draft_suppressed_path = _suppressed_draft_path" in src


def test_every_successful_return_records_the_drafter_it_launched():
    """The auto-Vulkan CPU replay must record its drafter too, or it keeps the previous load's pair."""
    src = _load_model_source()
    assert (
        src.count("self._mtp_draft_suppressed_path = _suppressed_draft_path") == 2
    ), "both successful returns must record the drafter they launched"
    replay = src.index("loaded successfully on CPU after the")
    assert src.rindex("self._mtp_draft_path = launch_mtp_draft_path", 0, replay) < replay
    assert (
        src.rindex("self._mtp_draft_suppressed_path = _suppressed_draft_path", 0, replay) < replay
    )


def _mmproj_env_scrub(*, paravirtual: bool) -> dict:
    """Run load_model's real inherited-projector env scrub and report the child's env."""
    block = _if_block(
        lambda test: isinstance(test, ast.Name) and test.id == "_paravirtual_cpu_forced",
        _mmproj_env_tree(),
    )
    scope = {
        "_paravirtual_cpu_forced": paravirtual,
        "env": {
            "LLAMA_ARG_MMPROJ": "/inherited/proj.gguf",
            "LLAMA_ARG_MMPROJ_URL": "https://example.invalid/proj.gguf",
            "LLAMA_ARG_THREADS": "8",
        },
    }
    exec(ast.unparse(ast.Module(body = [block], type_ignores = [])), scope)
    return scope["env"]


def _mmproj_env_tree() -> ast.AST:
    """load_model's statements, narrowed to the ones mentioning _pv_mmproj_var."""
    keep = [
        node
        for node in ast.walk(_load_model_tree())
        if isinstance(node, ast.If) and "_pv_mmproj_var" in _names(node)
    ]
    assert keep, "the inherited-projector env scrub left load_model"
    return ast.Module(body = keep, type_ignores = [])


def test_an_inherited_projector_is_dropped_from_the_child_env():
    """argv cannot un-set LLAMA_ARG_MMPROJ; llama.cpp reads the env itself, so the child env is scrubbed."""
    env = _mmproj_env_scrub(paravirtual = True)
    assert "LLAMA_ARG_MMPROJ" not in env
    assert "LLAMA_ARG_MMPROJ_URL" not in env
    assert env == {"LLAMA_ARG_THREADS": "8"}


def test_a_real_mac_keeps_its_inherited_projector():
    """The scrub is scoped to the virtualised device: on physical Apple Silicon (or any
    non-Mac) the projector runs correctly on the GPU, so a deliberate LLAMA_ARG_MMPROJ
    must reach llama-server untouched."""
    env = _mmproj_env_scrub(paravirtual = False)
    assert env["LLAMA_ARG_MMPROJ"] == "/inherited/proj.gguf"
    assert env["LLAMA_ARG_MMPROJ_URL"] == "https://example.invalid/proj.gguf"


def test_the_env_scrub_lands_before_the_spawn():
    """Env is built once and given to Popen; a scrub after spawn leaves the projector loaded."""
    src = _load_model_source()
    scrub = 'for _pv_mmproj_var in ("LLAMA_ARG_MMPROJ", "LLAMA_ARG_MMPROJ_URL")'
    assert src.index(scrub) < src.index("_spawn_and_wait(")


# Launch and both duplicate-load comparators share one normalization.


def _routes():
    """routes/inference.py is imported lazily so cheap AST tests do not pay for FastAPI."""
    from routes import inference as routes_inference
    return routes_inference


def _paravirtual_everywhere(monkeypatch):
    """The route imports the detector by value, so patching llama_cpp alone misses it."""
    _paravirtual(monkeypatch)
    monkeypatch.setattr(_routes(), "_metal_device_is_paravirtual", lambda: True)


def _real_mac_everywhere(monkeypatch):
    monkeypatch.setattr(llama_cpp, "_metal_device_is_paravirtual", lambda: False)
    monkeypatch.setattr(_routes(), "_metal_device_is_paravirtual", lambda: False)


def _normalized(**kwargs):
    return llama_cpp.paravirtual_normalized_request(**kwargs)


def test_the_normalizer_pins_every_placement_knob_to_cpu():
    """The one definition of the rewrite: whatever came in, this is what launches."""
    out = _normalized(
        gpu_memory_mode = "auto",
        gpu_layers = -1,
        tensor_parallel = True,
        tensor_split = [0.5, 0.5],
        n_cpu_moe = 8,
        extra_args = ["-ngl", "99", "--top-k", "40"],
    )
    assert out.gpu_memory_mode == "manual"
    assert out.gpu_layers == 0
    assert out.tensor_parallel is False
    assert out.tensor_split is None
    assert out.n_cpu_moe == 0
    assert out.extra_args == ["--top-k", "40"]


def test_the_normalizer_is_idempotent():
    """load_model and the comparator both normalize; a second pass must change nothing."""
    once = _normalized(
        gpu_memory_mode = "auto", gpu_layers = -1, extra_args = ["-ot", ".*=Metal", "--top-k", "40"]
    )
    twice = _normalized(
        gpu_memory_mode = once.gpu_memory_mode,
        gpu_layers = once.gpu_layers,
        tensor_parallel = once.tensor_parallel,
        tensor_split = once.tensor_split,
        n_cpu_moe = once.n_cpu_moe,
        extra_args = once.extra_args,
    )
    assert twice == once


def test_the_normalizer_still_runs_for_a_request_that_already_asks_for_cpu():
    """Manual + 0 layers must be normalized too, or an -ot in extras lands weights on the corrupt device."""
    out = _normalized(
        gpu_memory_mode = "manual",
        gpu_layers = 0,
        extra_args = ["-ot", ".*=Metal", "--top-k", "40"],
    )
    assert out.extra_args == ["--top-k", "40"]


def test_the_normalizer_keeps_extras_it_has_no_business_touching():
    """The negatives: a CPU-targeted override does what this fallback does, a --split-mode
    is neutralised at the launch instead (the comparators compare the stored list
    verbatim), and "no opinion" must stay None, not become []."""
    out = _normalized(extra_args = ["-ot", "exps=CPU", "-sm", "row", "--temp", "0.7"])
    assert out.extra_args == ["-ot", "exps=CPU", "-sm", "row", "--temp", "0.7"]
    assert _normalized(extra_args = None).extra_args is None
    assert _normalized(extra_args = []).extra_args == []


def test_the_launch_normalizes_a_manual_cpu_request_too(monkeypatch):
    """Duplicate-load check sees the flags that launch, even for a Manual + 0 request."""
    _paravirtual(monkeypatch)
    backend = llama_cpp.LlamaCppBackend()
    seen = {}

    def _capture(intent):
        captured = asdict(intent)
        for _key in ("extra_args", "tensor_split", "gpu_ids"):
            if captured.get(_key) is not None:
                captured[_key] = list(captured[_key])
        seen.update(captured)
        return True

    monkeypatch.setattr(backend, "adopt_load_intent_if_matched", _capture)
    monkeypatch.setattr(backend, "_apply_detected_audio", lambda _d: True)
    backend._audio_probed = True
    backend._healthy = True
    backend.load_model(
        llama_cpp.GgufLoadIntent(
            model_identifier = "owner/repo",
            gguf_path = "/nonexistent/model.gguf",
            gpu_memory_mode = "manual",
            gpu_layers = 0,
            n_cpu_moe = 8,
            tensor_parallel = True,
            extra_args = ["-ot", ".*=Metal", "--top-k", "40"],
        )
    )
    assert seen["extra_args"] == ["--top-k", "40"]
    assert seen["n_cpu_moe"] == 0
    assert seen["tensor_parallel"] is False
    assert seen["tensor_split"] is None


def test_a_real_mac_keeps_its_tensor_override_on_a_manual_cpu_load(monkeypatch):
    """Physical Apple Silicon is exempt: a deliberate -ot must reach llama-server as written."""
    monkeypatch.setattr(llama_cpp, "_metal_device_is_paravirtual", lambda: False)
    backend = llama_cpp.LlamaCppBackend()
    seen = {}

    def _capture(intent):
        captured = asdict(intent)
        for _key in ("extra_args", "tensor_split", "gpu_ids"):
            if captured.get(_key) is not None:
                captured[_key] = list(captured[_key])
        seen.update(captured)
        return True

    monkeypatch.setattr(backend, "adopt_load_intent_if_matched", _capture)
    monkeypatch.setattr(backend, "_apply_detected_audio", lambda _d: True)
    backend._audio_probed = True
    backend._healthy = True
    backend.load_model(
        llama_cpp.GgufLoadIntent(
            model_identifier = "owner/repo",
            gguf_path = "/nonexistent/model.gguf",
            gpu_memory_mode = "manual",
            gpu_layers = 0,
            n_cpu_moe = 8,
            extra_args = ["-ot", ".*=Metal", "--top-k", "40"],
        )
    )
    assert seen["extra_args"] == ["-ot", ".*=Metal", "--top-k", "40"]
    assert seen["n_cpu_moe"] == 8


def _cpu_server(
    monkeypatch,
    tmp_path,
    *,
    launched_extras,
    requested_extras = None,
):
    """A healthy paravirtual CPU server that recorded a normalized placement."""
    monkeypatch.setattr(
        llama_cpp.LlamaCppBackend, "_kill_orphaned_servers", staticmethod(lambda: 0)
    )
    backend = llama_cpp.LlamaCppBackend()
    backend._process = _FakeProcess()
    backend._healthy = True
    backend._audio_probed = True
    backend._model_identifier = "owner/repo"
    gguf = tmp_path / "model.gguf"
    gguf.write_bytes(b"GGUF")
    backend._gguf_path = str(gguf)
    backend._requested_n_ctx = 8192
    backend._requested_n_parallel = 1
    backend._requested_spec_mode = "auto"
    backend._gpu_memory_mode = "manual"
    backend._gpu_layers = 0
    backend._n_cpu_moe = 0
    backend._tensor_split = None
    backend._tensor_parallel = False
    backend._extra_args = list(launched_extras)
    backend._requested_extra_args = list(
        requested_extras if requested_extras is not None else launched_extras
    )
    backend._extra_args_source = ("owner/repo", None)
    return backend, gguf


def _route_matches(request, backend):
    """The route rebuilds intent from the request; the single backend comparator judges it."""
    intent = _routes()._active_gguf_intent(
        request,
        backend,
        model_identifier = "owner/repo",
        chat_template_override = None,
        n_parallel = 1,
        native_grant_backed = False,
    )
    return backend.adopt_load_intent_if_matched(intent)


def _load_request(gguf, **overrides):
    from models.inference import LoadRequest

    fields = dict(
        model_path = str(gguf),
        max_seq_length = 8192,
        speculative_type = "auto",
        gpu_memory_mode = "auto",
        gpu_layers = -1,
    )
    fields.update(overrides)
    return LoadRequest(**fields)


def test_a_repeat_auto_request_with_extras_matches_the_cpu_server_it_left(monkeypatch, tmp_path):
    """API clients, a second tab and saved presets keep sending Auto, which the browser normalized
    echo does not cover; it never covers the extras box, which the UI does not round-trip."""
    _paravirtual_everywhere(monkeypatch)
    backend, gguf = _cpu_server(monkeypatch, tmp_path, launched_extras = ["--top-k", "40"])
    request = _load_request(
        gguf,
        llama_extra_args = ["-ngl", "99", "--top-k", "40"],
        tensor_parallel = True,
        n_cpu_moe = 8,
    )
    assert _route_matches(request, backend) is True
    assert (
        _target_state_auto(
            backend,
            gguf,
            tensor_parallel = True,
            n_cpu_moe = 8,
            extra_args = ["-ngl", "99", "--top-k", "40"],
        )
        is True
    )


def test_the_same_pair_still_mismatches_on_a_real_mac(monkeypatch, tmp_path):
    """The negative that keeps the normalization honest: off this hardware an Auto request
    against a Manual/0 server is a genuine settings change and must reload."""
    _real_mac_everywhere(monkeypatch)
    backend, gguf = _cpu_server(monkeypatch, tmp_path, launched_extras = ["--top-k", "40"])
    request = _load_request(gguf, llama_extra_args = ["--top-k", "40"])
    assert _route_matches(request, backend) is False
    assert _target_state_auto(backend, gguf, extra_args = ["--top-k", "40"]) is False


def test_a_genuinely_different_extras_box_still_reloads(monkeypatch, tmp_path):
    """Normalizing must not swallow a real edit: only the offload family and GPU-bound
    tensor overrides are rewritten, so a changed sampler flag is still a change."""
    _paravirtual_everywhere(monkeypatch)
    backend, gguf = _cpu_server(monkeypatch, tmp_path, launched_extras = ["--top-k", "40"])
    request = _load_request(gguf, llama_extra_args = ["--top-k", "20"])
    assert _route_matches(request, backend) is False
    assert _target_state_auto(backend, gguf, extra_args = ["--top-k", "20"]) is False


def test_a_tensor_split_mode_in_extras_does_not_reload_a_cpu_server(monkeypatch, tmp_path):
    """Pin overrides --split-mode at launch rather than stripping it, so stored extras still say
    tensor while nothing tensor launched; judging the raw extras would reload on every Apply."""
    _paravirtual_everywhere(monkeypatch)
    backend, gguf = _cpu_server(monkeypatch, tmp_path, launched_extras = ["-sm", "tensor"])
    request = _load_request(gguf, llama_extra_args = ["-sm", "tensor"], tensor_parallel = True)
    assert _route_matches(request, backend) is True
    assert (
        _target_state_auto(backend, gguf, tensor_parallel = True, extra_args = ["-sm", "tensor"])
        is True
    )


def test_a_dropped_drafter_does_not_reload_over_the_extras_it_rewrote(monkeypatch, tmp_path):
    """Drop strips the spec group and stores the rewrite, but a caller resending its own list
    mismatches the launched one and reloads on every Apply without bound."""
    _paravirtual_everywhere(monkeypatch)
    asked = ["--draft-max", "8", "--top-k", "40"]
    backend, gguf = _cpu_server(
        monkeypatch, tmp_path, launched_extras = ["--top-k", "40"], requested_extras = asked
    )
    request = _load_request(gguf, llama_extra_args = list(asked))
    assert _route_matches(request, backend) is True
    assert _target_state_auto(backend, gguf, extra_args = list(asked)) is True


def test_an_apply_that_inherits_the_extras_does_not_reload_the_rewritten_server(
    monkeypatch, tmp_path
):
    """Browser omits llama_extra_args, so the route inherits the launched list and tears down on Apply."""
    _paravirtual_everywhere(monkeypatch)
    backend, gguf = _cpu_server(
        monkeypatch,
        tmp_path,
        launched_extras = ["--top-k", "40"],
        requested_extras = ["--draft-max", "8", "--top-k", "40"],
    )
    assert _route_matches(_load_request(gguf), backend) is True
    assert _route_matches(_load_request(gguf, llama_extra_args = ["--top-k", "20"]), backend) is False
    # Naming exactly the stripped list is a deliberate clear, not an inherit.
    assert _route_matches(_load_request(gguf, llama_extra_args = ["--top-k", "40"]), backend) is False


def test_an_edited_spec_flag_still_reloads_after_a_dropped_drafter(monkeypatch, tmp_path):
    """Requested-vs-requested must still catch a real change to the flags the drop removed."""
    _paravirtual_everywhere(monkeypatch)
    backend, gguf = _cpu_server(
        monkeypatch,
        tmp_path,
        launched_extras = ["--top-k", "40"],
        requested_extras = ["--draft-max", "8", "--top-k", "40"],
    )
    request = _load_request(gguf, llama_extra_args = ["--draft-max", "4", "--top-k", "40"])
    assert _route_matches(request, backend) is False
    assert (
        _target_state_auto(backend, gguf, extra_args = ["--draft-max", "4", "--top-k", "40"]) is False
    )


def test_the_requested_extras_default_to_the_launched_ones():
    """Nothing rewritten means the two records are the same list, so a load that never hits
    the drop keeps comparing exactly what it compared before."""
    backend = llama_cpp.LlamaCppBackend()
    assert backend.requested_extra_args is None
    backend._extra_args = ["--top-k", "40"]
    assert backend.requested_extra_args == ["--top-k", "40"]
    backend._requested_extra_args = ["--draft-max", "8", "--top-k", "40"]
    assert backend.requested_extra_args == ["--draft-max", "8", "--top-k", "40"]
    backend.requested_extra_args.append("--temp")
    assert backend.requested_extra_args == ["--draft-max", "8", "--top-k", "40"]


def test_the_drop_records_the_requested_extras_before_rewriting_them():
    """The recording contract, mirroring _suppressed_draft_path: capture, then strip."""
    src = _load_model_source()
    assert src.index("_pv_suppressed_spec_extra_args = list(extra_args)") < src.index(
        "                            strip_spec = True,"
    )
    assert "self._requested_extra_args = (" in src


def _restore_requested_spec_mode(*, requested_extras):
    """Runs load_model's real spec-mode restore; the backend already judged the stripped list."""
    block = _if_block(
        lambda test: "_pv_suppressed_spec_extra_args" in _names(test),
    )
    backend = llama_cpp.LlamaCppBackend()
    backend._requested_spec_mode = "auto"
    scope = {
        "self": backend,
        "_pv_suppressed_spec_extra_args": requested_extras,
        "_extra_args_set_spec_type": llama_cpp._extra_args_set_spec_type,
    }
    exec(ast.unparse(ast.Module(body = [block], type_ignores = [])), scope)
    return backend._requested_spec_mode


def test_a_user_owned_spec_type_survives_the_drafter_drop():
    """The drop removed --spec-type before _build_speculative_flags saw the list, so the
    backend recorded "auto" while the caller's extras still mean "the user owns it"
    (None), and the spec-mode compare mismatched forever."""
    assert (
        _restore_requested_spec_mode(
            requested_extras = ["--spec-type", "draft-simple", "--model-draft", "/m/d.gguf"]
        )
        is None
    )


def test_the_restore_is_scoped_to_a_drop_that_owned_spec_type():
    """No drop, or a drop whose extras never set --spec-type, must leave the mode as resolved."""
    assert _restore_requested_spec_mode(requested_extras = None) == "auto"
    assert _restore_requested_spec_mode(requested_extras = ["--draft-max", "8"]) == "auto"


def test_the_route_really_can_deliver_a_manual_cpu_request_carrying_an_override():
    """The -ot survives the route's --gpu-layers strip, so Manual + 0 can reach the normalizer with it."""
    extras = ["-ot", ".*=Metal", "--top-k", "40"]
    assert llama_server_args.parse_gpu_layers_override(extras) is None
    assert (
        llama_server_args.strip_shadowing_flags(
            extras,
            strip_context = False,
            strip_cache = False,
            strip_spec = False,
            strip_template = False,
            strip_split_mode = False,
            strip_tensor_split = True,
            strip_offload = True,
        )
        == extras
    )


def test_the_drop_records_only_the_drafter_it_removed():
    """Extras can trigger it with none launched; recording None would erase an earlier record."""
    earlier = "/cache/snapshots/abc/mtp-model.gguf"
    scope, _warnings = _drafter_gate_scope(
        paravirtual = True,
        caps = {},
        drafter = None,
        extra_args = ["--model-draft", "/models/user-drafter.gguf"],
        suppressed = earlier,
    )
    assert scope["launch_mtp_draft_path"] is None
    assert scope["_suppressed_draft_path"] == earlier