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.

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

"""Where the planner declines, argv must be unchanged; a plan must carry --fit off and -ngl -1."""

from __future__ import annotations

from types import SimpleNamespace

import pytest

from core.inference.llama_cpp import LlamaCppBackend
from core.inference.offload_layout import LM_HEAD_PATTERN, BlockLayout, ModelLayout
from core.inference.offload_planner import Plan, plan_placement, smart_offload_enabled
from core.inference.llama_cpp import _extra_args_tensor_split
from core.inference.llama_cpp import _linux_math_core_count
import core.inference.llama_cpp as llama_mod
import inspect
import sys


class _SmtHost:
    @staticmethod
    def cpu_count(logical = True):
        return 16 if logical else 8


# Decision table is in test_offload_planner.py; this tests the launch-path seam.
FFN_SPILL_PATTERN = r"blk\.\d+\.ffn_"
LM_HEAD_SPILL_PATTERN = LM_HEAD_PATTERN

GIB = 1024**3
MIB = 1024 * 1024


@pytest.fixture(autouse = True)
def _discrete_host(monkeypatch):
    """Pin is_apple_silicon to False: the seam reads it live, so an arm64 Mac would grade the runner."""
    import utils.hardware
    monkeypatch.setattr(utils.hardware, "is_apple_silicon", lambda: False)


@pytest.fixture(scope = "session")
def sparse_adapter(tmp_path_factory):
    """Truncate a sparse 3 GiB file rather than write it: only st_size is read, and zeros spike RSS."""
    path = tmp_path_factory.mktemp("adapters") / "adapter.gguf"
    with open(path, "wb") as handle:
        handle.truncate(3 * GIB)
    return path


class _Stub:
    """Declare only what the seam touches: a declared _HOST_RAM_HEADROOM_MIB hides a missing attribute."""

    _PIPELINE_PER_DEVICE_OVERHEAD_MIB = 1024
    _unified = False
    _excluded_bytes = 0
    _integrated_cuda = False

    def _amd_apu_wants_unified_memory(self, gpu_indices = None):
        return self._unified

    def _integrated_cuda_unified_memory(self, gpu_indices = None):
        return self._integrated_cuda

    def __init__(
        self,
        avail_mib = 64 * 1024,
        ffn = 10 * GIB,
        lm_head = 1 * GIB,
        moe = 0,
    ):
        self._avail_mib = avail_mib
        self._ffn_weight_bytes = ffn
        self._lm_head_bytes = lm_head
        self.n_moe_layers = moe
        self._spill_plan_flags: list[str] = []

    def _available_system_memory_mib(self):
        return self._avail_mib

    def _can_estimate_kv(self):
        return True

    _planned_tensor_spill = LlamaCppBackend._planned_tensor_spill
    _drop_tensor_spill = LlamaCppBackend._drop_tensor_spill

    def _tensor_spill_layout(self, model_path):
        """Stub for the GGUF read; ffn = None stands for an unreadable model, which must abstain."""
        if self._ffn_weight_bytes is None or not model_path:
            return None
        n = 64
        return ModelLayout(
            arch = "qwen35moe" if self.n_moe_layers else "qwen35",
            n_layers = n,
            n_attention_layers = 16,
            blocks = tuple(
                BlockLayout(
                    index = i,
                    spillable_bytes = self._ffn_weight_bytes // n,
                    resident_bytes = (2 * GIB) // n,
                )
                for i in range(n)
            ),
            lm_head_bytes = self._lm_head_bytes or 0,
            token_embd_bytes = 512 * MIB,
            kv_bytes_per_token_f16 = 65536,
            n_ctx_train = 262144,
            is_moe = bool(self.n_moe_layers),
            n_expert = 256 if self.n_moe_layers else 0,
            n_expert_used = 8 if self.n_moe_layers else 0,
            has_excluded_blocks = bool(self._excluded_bytes),
            excluded_block_bytes = self._excluded_bytes,
            complete = True,
        )


def _inputs(
    model_size = 30 * GIB,
    kv = 2 * GIB,
    free_mib = 24 * 1024,
    indices = None,
    usable_mib = None,
    extra_gpu = 0,
    mtp = None,
    shared = None,
    gpus = None,
    n_parallel = 1,
    n_threads = None,
    compute_flat = 0,
    ctx_compute = 0,
    env_mmproj = 0,
    env_mmproj_unsized = False,
    separate_draft = False,
):
    return {
        "model_size": model_size,
        "kv_cache_bytes": kv,
        "gpus": list(gpus) if gpus is not None else [(0, free_mib)],
        "gpu_usable_mib": {} if usable_mib is None else {0: usable_mib},
        "compute_buffer_flat": compute_flat,
        "ctx_compute_per_device": ctx_compute,
        "extra_gpu_bytes": extra_gpu,
        "env_mmproj_bytes": env_mmproj,
        "env_mmproj_unsized": env_mmproj_unsized,
        "gpu_indices": indices,
        "soft_overhead": 0,
        "model_path": "/models/stub.gguf",
        "n_ctx": 32768,
        "n_parallel": n_parallel,
        "n_threads": n_threads,
        "shared_gpu_ids": set() if shared is None else set(shared),
        "separate_draft_on_gpu": separate_draft,
        **({} if mtp is None else {"mtp_will_engage": mtp}),
    }


def _plan(
    stub,
    env = None,
    extra_args = None,
    **kw,
):
    return stub._planned_tensor_spill(
        _inputs(**kw),
        extra_args = extra_args,
        env = {"UNSLOTH_SMART_OFFLOAD": "1", **(env or {})},
    )


def test_the_seam_reads_no_attribute_the_real_backend_lacks():
    """The seam may read only attributes the real backend has; a double once hid a missing one."""
    for name in ("_HOST_RAM_HEADROOM_MIB",):
        assert not hasattr(_Stub, name), (
            f"the double declares {name}, so it can hide a missing attribute on the "
            "real backend again"
        )
    source = inspect.getsource(LlamaCppBackend._planned_tensor_spill)
    assert "self._HOST_RAM_HEADROOM_MIB" not in source


def test_the_planner_is_off_by_default():
    """The planner must stay opt-in, and only spill-plan loads reveal a default that flipped back on."""
    assert smart_offload_enabled({}) is False
    assert _Stub()._planned_tensor_spill(_inputs(), env = {}) is None
    assert _Stub()._planned_tensor_spill(_inputs(free_mib = 14 * 1024), env = {}) is None

    tight = _Stub()._planned_tensor_spill(
        _inputs(free_mib = 14 * 1024), env = {"UNSLOTH_SMART_OFFLOAD": "1"}
    )
    assert tight is not None and tight.spills_anything


@pytest.mark.parametrize("value", ["1", "on", "true", "yes", "enabled", "ON", " 1 "])
def test_the_gate_accepts_the_usual_spellings(value):
    assert smart_offload_enabled({"UNSLOTH_SMART_OFFLOAD": value}) is True


@pytest.mark.parametrize("value", ["0", "off", "", "no", "disabled", "false"])
def test_an_explicit_off_still_disables(value):
    """The escape hatch has to keep working."""
    assert smart_offload_enabled({"UNSLOTH_SMART_OFFLOAD": value}) is False
    assert _Stub()._planned_tensor_spill(_inputs(), env = {"UNSLOTH_SMART_OFFLOAD": value}) is None


@pytest.mark.parametrize("value", ["nope", "flase", "onn", "2"])
def test_an_unrecognised_value_disables_rather_than_enables(value):
    """A fumbled on-spelling must not turn the planner on by accident, and now
    lands on the same answer as setting nothing at all."""
    assert smart_offload_enabled({"UNSLOTH_SMART_OFFLOAD": value}) is False


def test_an_unpriced_placement_abstains():
    """The except arm restores use_fit without pricing anything, so the seam
    reads None here rather than an UnboundLocal kv_cache_bytes."""
    assert _Stub()._planned_tensor_spill(None, env = {"UNSLOTH_SMART_OFFLOAD": "1"}) is None


@pytest.mark.parametrize(
    "extra_args",
    [
        ["-ot", ".ffn_.*=CPU"],
        ["--override-tensor", "x=CPU"],
        ["--cpu-moe"],
        ["--n-cpu-moe", "24"],
        ["-ngl", "12"],
        ["--gpu-layers", "0"],
        ["--device", "CUDA0"],
        ["-dev", "none"],
        ["--fit", "on"],
        # --fit off too: retries append "--fit on" after extras, so a plan would overturn the user.
        ["--fit", "off"],
        ["--fit=off"],
        ["-fit", "off"],
    ],
)
def test_a_pass_through_placement_override_declines(extra_args):
    """Pricing a placement the child won't receive is a recurring bug; decline instead."""
    assert _plan(_Stub(), extra_args = extra_args) is None


@pytest.mark.parametrize(
    "env",
    [
        {"LLAMA_ARG_N_GPU_LAYERS": "12"},
        {"LLAMA_ARG_DEVICE": "none"},
        {"LLAMA_ARG_OVERRIDE_TENSOR": ".ffn_.*=CPU"},
        {"LLAMA_ARG_CPU_MOE": "1"},
    ],
)
def test_an_inherited_placement_env_declines(env):
    """The child inherits these, so they outlive any flag stripping."""
    assert _plan(_Stub(), env = env) is None


def test_an_unsized_model_abstains():
    assert _plan(_Stub(), model_size = 0) is None


def test_an_unsized_cache_abstains():
    assert _plan(_Stub(), kv = 0) is None


def test_no_gpus_abstains():
    stub = _Stub()
    assert (
        stub._planned_tensor_spill({**_inputs(), "gpus": []}, env = {"UNSLOTH_SMART_OFFLOAD": "1"})
        is None
    )


def test_an_absent_layout_abstains():
    """_ffn_weight_bytes is the planner-core half and does not exist yet, so the
    feature is inert until it lands even with the gate on."""
    assert _plan(_Stub(ffn = None)) is None


def test_unreadable_host_ram_abstains():
    assert _plan(_Stub(avail_mib = None)) is None


def test_a_load_that_needs_ffn_spilled_gets_the_ffn_pattern():
    got = _plan(_Stub(), model_size = 30 * GIB, kv = 2 * GIB, free_mib = 12 * 1024)
    assert got is not None
    assert got.ot_patterns and all("ffn" in p for p in got.ot_patterns)


def test_a_moe_load_spills_expert_tensors_not_dense_ffn():
    got = _plan(_Stub(moe = 40), model_size = 30 * GIB, kv = 2 * GIB, free_mib = 12 * 1024)
    assert got is not None
    assert got.ot_patterns and all("ffn" in p for p in got.ot_patterns)


def test_lm_head_is_only_spilled_after_ffn():
    """lm_head is 43% of generation alone, 16% on a host-bound step, so it is never first."""
    # Single card no longer withholds a pipeline GiB, so free_mib is lower to reach lm_head.
    tight = _plan(_Stub(), model_size = 60 * GIB, kv = 2 * GIB, free_mib = 4608)
    assert tight is not None
    assert tight.spilled_lm_head is True
    assert tight.spilled_blocks, "lm_head is never the first rung"
    assert tight.ot_patterns[-1] == LM_HEAD_SPILL_PATTERN


def test_the_lm_head_pattern_is_anchored():
    """An unanchored "output\\.weight" also matches every blk.N.attn_output.weight
    under std::regex_search, which silently moves the attention output projections
    too (measured: an extra 357 MiB on a 27B)."""
    assert LM_HEAD_SPILL_PATTERN.startswith("^output")
    assert LM_HEAD_SPILL_PATTERN.endswith("$"), "must not match blk.N.attn_output.weight"


def test_a_spill_host_ram_cannot_hold_abstains():
    """--fit on at least demand-pages; a plan here would be an OOM kill."""
    got = _plan(_Stub(avail_mib = 3 * 1024), model_size = 30 * GIB, kv = 2 * GIB, free_mib = 12 * 1024)
    assert got is None or got.load_mode_none is False


def test_a_floor_that_does_not_fit_emits_no_flags():
    """Assert the flags, not the plan: a dataclass is always truthy, so abstained plans emit -ngl -1."""
    got = _plan(_Stub(), model_size = 30 * GIB, kv = 2 * GIB, free_mib = 3 * 1024)
    assert got is not None
    assert got.insufficient
    assert LlamaCppBackend._spill_plan_flags_for(got) == []


def test_an_abstaining_plan_emits_no_flags():
    """plan_placement abstentions return a Plan, not None, so no abstaining case reaches argv."""
    for plan in (
        plan_placement(ModelLayout(), [8 * GIB], 32 * GIB, 4096),
        plan_placement(
            ModelLayout(complete = True, n_ctx_train = 4096),
            [0],
            32 * GIB,
            4096,
        ),
    ):
        assert plan.spills_anything is False
        assert LlamaCppBackend._spill_plan_flags_for(plan) == []


def test_a_plan_that_already_fits_emits_no_flags():
    """The planner disagreeing with Unsloth ("it fits after all") is not licence
    to pin every layer and turn the fitter off."""
    got = _plan(_Stub(), free_mib = 200 * 1024)
    assert got is not None and not got.spills_anything
    assert LlamaCppBackend._spill_plan_flags_for(got) == []


def test_the_measured_cache_floors_the_planners_own_estimate():
    """kv_bytes is a bare f16 GQA estimate, so floor it at the measured cache: under-counting is unsafe."""
    stub = _Stub()
    layout = stub._tensor_spill_layout("/models/stub.gguf")
    unfloored = plan_placement(layout, [20 * GIB], 64 * GIB, 32768)
    floored = plan_placement(layout, [20 * GIB], 64 * GIB, 32768, kv_bytes_floor = 8 * GIB)
    assert len(floored.spilled_blocks) > len(unfloored.spilled_blocks)


def test_the_seam_hands_the_planner_studios_cache_size():
    """The byte-accurate KV size comes from the call site; a bigger cache must buy more spill."""
    small = _plan(_Stub(), kv = 2 * GIB, free_mib = 14 * 1024)
    large = _plan(_Stub(), kv = 10 * GIB, free_mib = 14 * 1024)
    assert small is not None and large is not None
    assert len(large.spilled_blocks) > len(small.spilled_blocks)


def test_a_retry_takes_the_plan_back_out_and_restores_the_fitter():
    stub = _Stub()
    stub._spill_plan_flags = ["-ngl", "-1", "--fit", "off", "-ot", FFN_SPILL_PATTERN]
    cmd = ["llama-server", "-m", "x.gguf", *stub._spill_plan_flags, "--port", "8080"]
    got = stub._drop_tensor_spill(cmd, "noflash")
    assert "-ot" not in got
    assert got[-2:] == ["--fit", "on"]
    assert got[:4] == ["llama-server", "-m", "x.gguf", "--port"]


def test_the_revocation_keeps_the_record_for_a_later_respawn():
    """The CPU fallback respawns from an argv that may still carry the tokens."""
    stub = _Stub()
    stub._spill_plan_flags = ["-ngl", "-1", "--fit", "off", "-ot", FFN_SPILL_PATTERN]
    stub._drop_tensor_spill(["a", *stub._spill_plan_flags], "retry")
    assert stub._spill_plan_flags


def test_the_revocation_is_a_no_op_without_a_plan():
    stub = _Stub()
    cmd = ["llama-server", "--fit", "on"]
    assert stub._drop_tensor_spill(cmd, "retry") == cmd


def test_the_revocation_is_a_no_op_when_the_argv_never_carried_it():
    """Stripping must not add --fit to the -cpu replay, whose argv never carried the plan."""
    stub = _Stub()
    stub._spill_plan_flags = ["-ngl", "-1", "--fit", "off", "-ot", FFN_SPILL_PATTERN]
    replay = ["llama-server", "--gpu-layers", "0", "--fit", "off", "--device", "none"]
    assert stub._drop_tensor_spill(replay, "cpu") == replay


def test_repeated_ot_flags_rather_than_a_joined_value():
    """llama-server accumulates repeated -ot and splits an -ot VALUE on ",".
    Joining with ";" is llama-bench's syntax and would be parsed as one pattern.
    """
    plan = Plan(ot_patterns = (FFN_SPILL_PATTERN, LM_HEAD_SPILL_PATTERN))
    tokens = [tok for pat in plan.ot_patterns for tok in ("-ot", f"{pat}=CPU")]
    assert tokens.count("-ot") == 2
    assert ";" not in " ".join(tokens)


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


def test_the_abstain_branch_still_emits_exactly_fit_on():
    """A declined plan must still emit exactly the old --fit on, checked through the real flag builder."""
    from core.inference.offload_planner import Plan

    for reason in (
        "layout or device inventory incomplete, leaving llama.cpp defaults",
        "unified memory host, spilling frees no device memory",
        "no creditable VRAM after per-device overhead",
        "no usable context length",
    ):
        plan = Plan(reason = reason)
        assert plan, "Plan is truthy, which is the trap this test exists for"
        assert LlamaCppBackend._spill_plan_flags_for(plan) == [], reason

    assert (
        LlamaCppBackend._spill_plan_flags_for(Plan(reason = "does not fit", insufficient = True)) == []
    )
    assert LlamaCppBackend._spill_plan_flags_for(None) == []


def test_the_plan_disables_the_fitter_and_pins_every_layer_to_a_gpu():
    """--fit off stops the fitter re-placing layers; -ngl -1 keeps every layer, and the cache, on a GPU."""
    got = _plan(_Stub(), free_mib = 12 * 1024)
    assert got is not None and got.spills_anything
    flags = LlamaCppBackend._spill_plan_flags_for(got)
    assert flags[:4] == ["-ngl", "-1", "--fit", "off"]
    assert flags.count("-ot") == len(got.ot_patterns) >= 1
    assert all(tok.endswith("=CPU") for tok in flags[5::2])


def test_a_spill_plan_startup_failure_can_revoke_the_plan():
    """A spill-plan startup failure must reach _drop_tensor_spill, or the --fit on retry is skipped."""
    body = inspect.getsource(LlamaCppBackend.load_model)
    body = body[body.index("def _spawn_and_wait") :]
    assert body.count("_drop_tensor_spill") >= 2


def test_the_revocation_runs_only_on_retries():
    """Gated on label, empty only on the first spawn, so any later retry gets the revocation."""
    src = inspect.getsource(LlamaCppBackend.load_model)
    idx = src.index("def _spawn_and_wait")
    head = src[idx : idx + 1600]
    assert "if label:" in head
    assert "_drop_tensor_spill" in head


def test_a_unified_memory_apu_is_declared_to_the_planner():
    """Tell the planner when memory is unified: shared_gpu_ids is Vulkan-only, so ROCm APUs count twice."""
    discrete = _Stub()
    apu = _Stub()
    apu._unified = True

    got_discrete = _plan(discrete, free_mib = 12 * 1024)
    got_apu = _plan(apu, free_mib = 12 * 1024)

    assert got_apu is not None
    assert not got_apu.spills_anything
    assert "unified memory" in got_apu.reason
    assert LlamaCppBackend._spill_plan_flags_for(got_apu) == []

    assert got_discrete is not None
    assert got_discrete.spills_anything, "the discrete host is free to plan"

    compact = "".join(inspect.getsource(LlamaCppBackend._planned_tensor_spill).split())
    assert "unified_memory=self._amd_apu_wants_unified_memory(" in compact


@pytest.mark.parametrize("extra_args", [["--split-mode", "row"], ["-sm", "row"]])
def test_tensor_parallel_split_still_declines(extra_args):
    """-sm row is tensor parallelism, which the row split model does not describe."""
    assert _plan(_Stub(), extra_args = extra_args) is None
    assert _plan(_Stub()) is not None, "not vacuous: the same load plans without it"


@pytest.mark.parametrize(
    "extra_args",
    [["--split-mode", "none"], ["-sm", "none"], ["-sm=none"]],
)
def test_split_mode_none_plans_against_one_card(extra_args):
    """-sm none is a device list of ONE and not a reason to decline: llama.cpp keeps only
    devices[main_gpu] (llama.cpp:288-299), so plan one card, not a two-card pool."""
    two_cards = [(0, 14 * 1024), (1, 14 * 1024)]
    got = _plan(_Stub(), gpus = two_cards, extra_args = extra_args)
    assert got is not None

    one_card = _plan(_Stub(), gpus = [(0, 14 * 1024)])
    assert len(got.spilled_blocks) == len(one_card.spilled_blocks)


@pytest.mark.parametrize(
    "extra_args,env",
    [
        (["--split-mode", "tensor"], None),
        (["-sm", "tensor"], None),
        (["-sm=tensor"], None),
        (None, {"LLAMA_ARG_SPLIT_MODE": "tensor"}),
    ],
)
def test_tensor_parallel_split_mode_tensor_declines(extra_args, env):
    """-sm tensor declines: llama.cpp makes one meta device, so a per-device budget describes nothing."""
    two_cards = [(0, 14 * 1024), (1, 14 * 1024)]
    assert _plan(_Stub(), gpus = two_cards, extra_args = extra_args, env = env) is None
    assert _plan(_Stub(), gpus = two_cards) is not None, "not vacuous"


def test_split_mode_none_with_an_explicit_main_gpu_still_declines():
    """-sm none is budgeted only at the default main GPU 0; an explicit --main-gpu declines the plan."""
    two_cards = [(0, 14 * 1024), (1, 14 * 1024)]
    assert _plan(_Stub(), gpus = two_cards, extra_args = ["-sm", "none", "-mg", "1"]) is None
    assert (
        _plan(
            _Stub(),
            gpus = two_cards,
            extra_args = ["-sm", "none"],
            env = {"LLAMA_ARG_MAIN_GPU": "1"},
        )
        is None
    )
    assert _plan(_Stub(), gpus = two_cards, extra_args = ["-sm", "none"]) is not None
    assert (
        _plan(_Stub(), gpus = two_cards, env = {"LLAMA_ARG_MAIN_GPU": "0"}) is None
    ), "0 is still a pin the guard cannot verify against its own device order"


@pytest.mark.parametrize(
    "extra_args,env",
    [
        (["--tensor-split", "3,1"], None),
        (["-ts", "3,1"], None),
        (None, {"LLAMA_ARG_TENSOR_SPLIT": "3,1"}),
    ],
)
def test_tensor_split_becomes_the_row_weights(extra_args, env):
    """-ts replaces the free-memory split, so its shares are the row weights for the per-device check."""
    two_cards = [(0, 14 * 1024), (1, 14 * 1024)]
    assert _plan(_Stub(), gpus = two_cards, extra_args = extra_args, env = env) is not None


@pytest.mark.parametrize(
    "extra_args,env",
    [
        (["--tensor-split", "3/1"], None),
        (["-ts", "3/1"], None),
        (None, {"LLAMA_ARG_TENSOR_SPLIT": "3/1"}),
    ],
)
def test_a_slash_delimited_tensor_split_is_the_same_override(extra_args, env):
    """llama.cpp splits -ts on ``[,/]+`` (common/arg.cpp:2791-2804), so ``3/1`` IS
    ``3,1`` to the child. Failing to parse it returned None, which the caller
    cannot tell from "no override": it planned 1:1 while the child ran 3:1."""
    assert _extra_args_tensor_split(extra_args, env or {}) == [3.0, 1.0]

    two_cards = [(0, 14 * 1024), (1, 14 * 1024)]
    skewed = _plan(_Stub(), gpus = two_cards, extra_args = extra_args, env = env)
    comma = _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", "3,1"])
    assert skewed is not None and comma is not None
    assert skewed.spilled_blocks == comma.spilled_blocks


def test_a_malformed_or_short_tensor_split_declines():
    """A malformed or short -ts must decline rather than fall through; semicolons are no delimiter."""
    two_cards = [(0, 14 * 1024), (1, 14 * 1024)]
    assert _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", "3"]) is None
    assert _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", "abc"]) is None
    assert _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", "3;1"]) is None
    assert _plan(_Stub(), gpus = two_cards, env = {"LLAMA_ARG_TENSOR_SPLIT": "abc"}) is None
    assert _plan(_Stub(), gpus = two_cards) is not None
    assert _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", "3,1"]) is not None


def test_the_planner_gets_the_budget_the_fit_tested_not_raw_free():
    """The planner gets the budget the fit tested, not raw free VRAM: the user's budget fraction applies."""
    stub = _Stub()
    on_free = _plan(stub, free_mib = 14 * 1024)
    on_budget = _plan(stub, free_mib = 14 * 1024, usable_mib = 13 * 1024)

    assert on_free is not None and on_budget is not None
    assert on_free.spills_anything and on_budget.spills_anything
    assert len(on_budget.spilled_blocks) > len(on_free.spilled_blocks)


def test_the_projector_and_mtp_reserve_reach_the_planner():
    """Projector and MTP reserve are invisible to the GGUF layout, so they must be passed in explicitly."""
    stub = _Stub()
    without = _plan(stub, free_mib = 14 * 1024)
    with_extra = _plan(stub, free_mib = 14 * 1024, extra_gpu = 2 * GIB)

    assert without is not None and with_extra is not None
    assert without.spills_anything and with_extra.spills_anything
    assert len(with_extra.spilled_blocks) > len(without.spilled_blocks)


def test_the_layout_cache_notices_a_gguf_replaced_in_place(tmp_path, monkeypatch):
    """The layout cache must notice a GGUF replaced in place, or a larger file understates the deficit."""
    from core.inference import offload_layout

    class _CacheStub:
        _tensor_spill_layout = LlamaCppBackend._tensor_spill_layout

    reads: list[int] = []

    def _fake(path):
        reads.append(len(reads))
        return ModelLayout(arch = "llama", n_layers = len(reads), complete = True)

    monkeypatch.setattr(offload_layout, "layout_from_gguf", _fake)

    gguf = tmp_path / "model.gguf"
    gguf.write_bytes(b"a")
    backend = _CacheStub()

    first = backend._tensor_spill_layout(str(gguf))
    assert backend._tensor_spill_layout(str(gguf)) is first, "unchanged file is cached"
    assert len(reads) == 1

    gguf.write_bytes(b"bb")
    second = backend._tensor_spill_layout(str(gguf))
    assert len(reads) == 2, "a replaced file is re-read"
    assert second.n_layers != first.n_layers


@pytest.mark.parametrize("extra_args", [["-nkvo"], ["--no-kv-offload"]])
def test_a_forced_cpu_kv_cache_is_priced_not_declined(extra_args):
    """-nkvo is priced rather than declined: the whole cache goes to host RAM whatever -ngl says."""
    baseline = _plan(_Stub(), free_mib = 14 * 1024)
    forced = _plan(_Stub(), free_mib = 14 * 1024, extra_args = extra_args)
    assert forced is not None, "a host-resident cache is not a reason to abstain"

    assert len(forced.spilled_blocks) < len(baseline.spilled_blocks)

    # host_bytes must carry the cache too, or the mmap decision underestimates the footprint.
    assert forced.host_bytes >= 512 * MIB + 2 * GIB


@pytest.mark.parametrize("env", [{"LLAMA_ARG_KV_OFFLOAD": "0"}, {"LLAMA_ARG_KV_OFFLOAD": "false"}])
def test_an_inherited_kv_offload_env_is_priced_too(env):
    """Same resolution as argv: LLAMA_ARG_ is rewritten to LLAMA_ARG_NO_ and
    presence alone forces the value (common/arg.cpp:127-141)."""
    forced = _plan(_Stub(), free_mib = 14 * 1024, env = env)
    baseline = _plan(_Stub(), free_mib = 14 * 1024)
    assert forced is not None
    assert len(forced.spilled_blocks) < len(baseline.spilled_blocks)
    assert forced.host_bytes >= 512 * MIB + 2 * GIB


def test_the_positive_kv_offload_form_still_plans():
    """-kvo / --kv-offload is the enabling half of the paired -nkvo argument
    (common/arg.cpp:2402-2409); argv is last-wins, so a re-enable is not a decline."""
    assert _plan(_Stub(), extra_args = ["-kvo"]) is not None
    assert _plan(_Stub(), extra_args = ["-nkvo", "--kv-offload"]) is not None
    assert _plan(_Stub(), env = {"LLAMA_ARG_KV_OFFLOAD": "1"}) is not None


def test_an_engaged_draft_charges_the_excluded_mtp_blocks():
    """An engaged draft makes trailing MTP blocks resident; omitting them understates the deficit."""
    stub = _Stub()
    stub._excluded_bytes = 3 * GIB

    idle = _plan(stub, free_mib = 14 * 1024, mtp = False)
    drafting = _plan(stub, free_mib = 14 * 1024, mtp = True)

    assert idle is not None and drafting is not None
    assert idle.spills_anything and drafting.spills_anything
    assert len(drafting.spilled_blocks) > len(idle.spilled_blocks)


def test_an_ordinary_model_is_unaffected_by_the_draft_flag():
    """No excluded blocks, nothing to charge: the draft flag must not move a non-MTP plan."""
    stub = _Stub()
    assert stub._excluded_bytes == 0
    idle = _plan(stub, free_mib = 14 * 1024, mtp = False)
    drafting = _plan(stub, free_mib = 14 * 1024, mtp = True)
    assert idle.spilled_blocks == drafting.spilled_blocks


def test_a_shared_device_the_child_keeps_declines_the_plan():
    """A shared iGPU that the child keeps declines the plan; the budget cannot stop llama.cpp using it."""
    stub = _Stub()
    gpus = [(0, 12 * 1024), (1, 12 * 1024)]
    assert _plan(stub, gpus = gpus, shared = {1}) is None
    assert _plan(stub, gpus = gpus, shared = {1}, indices = [0, 1]) is None
    kept = _plan(stub, gpus = gpus, shared = {1}, indices = [0])
    assert kept is not None
    assert _plan(stub, gpus = gpus) is not None


def test_the_compute_buffer_reaches_the_planner():
    """The compute buffer and _cc_bytes must reach the planner, or long contexts under-reserve."""
    stub = _Stub()
    base = _plan(stub, free_mib = 14 * 1024)
    assert base is not None and base.spills_anything

    per_device = _plan(stub, free_mib = 14 * 1024, ctx_compute = 3 * GIB)
    flat = _plan(stub, free_mib = 14 * 1024, compute_flat = 3 * GIB)
    for tighter in (per_device, flat):
        assert tighter is not None
        assert len(tighter.spilled_blocks) > len(
            base.spilled_blocks
        ), "charging the compute buffer has to spill MORE, not the same"


def test_the_seam_hands_the_planner_raw_free_vram_for_the_split():
    """Pass raw free VRAM for the row split: llama.cpp sizes its ranges from raw free, not the budget."""
    seen = {}
    stub = _Stub()
    import core.inference.offload_planner as mod

    real = mod.plan_placement

    def spy(*a, **kw):
        seen.update(kw)
        seen["vram"] = a[1]
        return real(*a, **kw)

    mod.plan_placement = spy
    try:
        _plan(stub, gpus = [(0, 8 * 1024), (1, 16 * 1024)], usable_mib = 6 * 1024)
    finally:
        mod.plan_placement = real

    # The split weights must be raw free on both devices, ignoring usable_mib overrides.
    assert seen["split_weights_per_device"] == [8 * 1024 * MIB, 16 * 1024 * MIB]
    assert seen["vram"] == [6 * 1024 * MIB, 16 * 1024 * MIB]


def test_a_pinned_draft_device_declines_the_plan():
    """A drafter pinned to a card declines the plan: its reserve would be booked on device 0."""
    stub = _Stub()
    assert _plan(stub, extra_args = ["--spec-draft-device", "CUDA1"]) is None
    assert _plan(stub, extra_args = ["--device-draft", "CUDA0,CUDA1"]) is None
    assert _plan(stub, extra_args = ["--spec-draft-device", "cpu"]) is not None
    assert _plan(stub, extra_args = ["--spec-draft-device", "none"]) is not None
    assert _plan(stub) is not None


def test_a_pass_through_parallel_that_grows_the_cache_declines_the_plan():
    """A pass-through --parallel that grows the cache past Unsloth's count declines the plan."""
    stub = _Stub()
    assert _plan(stub, n_parallel = 1, extra_args = ["--parallel", "8"]) is None
    assert _plan(stub, n_parallel = 1, extra_args = ["-np", "4"]) is None
    assert _plan(stub, n_parallel = 1, extra_args = ["--parallel=8"]) is None
    assert _plan(stub, n_parallel = 8, extra_args = ["--parallel", "8"]) is not None
    assert _plan(stub, n_parallel = 8, extra_args = ["--parallel", "2"]) is not None
    assert _plan(stub, n_parallel = 1, env = {"LLAMA_ARG_N_PARALLEL": "8"}) is None
    assert _plan(stub, n_parallel = 4, extra_args = ["--parallel", "8", "-np", "2"]) is not None
    assert _plan(stub, n_parallel = 1) is not None


@pytest.mark.parametrize(
    "extra_args,env",
    [
        (["--rpc", "10.0.0.2:50052"], None),
        (["--rpc=10.0.0.2:50052"], None),
        (None, {"LLAMA_ARG_RPC": "10.0.0.2:50052"}),
    ],
)
def test_an_rpc_device_declines_the_plan(extra_args, env):
    """An --rpc device is remote and first in llama.cpp's device list, so local VRAM cannot price it."""
    assert _plan(_Stub(), extra_args = extra_args, env = env) is None
    assert _plan(_Stub()) is not None, "not vacuous: the same load plans without it"


@pytest.mark.parametrize(
    "extra_args,env",
    [
        (["--fit-target", "4096"], None),
        (["-fitt", "4096"], None),
        (["--fit-target=4096,4096"], None),
        (None, {"LLAMA_ARG_FIT_TARGET": "4096"}),
    ],
)
def test_an_explicit_fit_target_declines_the_plan(extra_args, env):
    """An explicit --fit-target reserves VRAM for others; emitting --fit off would silently drop that."""
    assert _plan(_Stub(), extra_args = extra_args, env = env) is None
    assert _plan(_Stub()) is not None, "not vacuous"


def test_a_pass_through_adapter_is_charged_as_resident_vram(sparse_adapter, monkeypatch):
    """LoRA and control-vector sidecars are GPU-resident and in no other term; price them as VRAM."""
    adapter = sparse_adapter

    # Sized so the adapter is what tips the load over: the term must be load-bearing.
    stub = _Stub()
    free = 17 * 1024
    bare = _plan(stub, free_mib = free)
    with_lora = _plan(stub, free_mib = free, extra_args = ["--lora", str(adapter)])
    assert bare is not None and with_lora is not None
    assert not bare.spills_anything, "the base load fits on its own"
    assert with_lora.spills_anything, "3 GiB of resident adapter comes out of the same VRAM"

    ctrl = _plan(stub, free_mib = free, extra_args = ["--control-vector", str(adapter)])
    assert ctrl.spilled_blocks == with_lora.spilled_blocks

    # Relative path: an absolute Windows path has a drive colon that llama.cpp's split rejects.
    monkeypatch.chdir(adapter.parent)
    scaled = _plan(stub, free_mib = free, extra_args = ["--lora-scaled", "adapter.gguf:0.5"])
    assert scaled.spilled_blocks == with_lora.spilled_blocks


def test_a_drive_lettered_scaled_adapter_is_skipped_rather_than_priced():
    """A drive-lettered scaled adapter is skipped: the child cannot parse it, leaving nothing to price."""
    drive_lettered = "C:\\dir\\adapter.gguf:0.5"

    stub = _Stub()
    free = 17 * 1024
    plan = _plan(stub, free_mib = free, extra_args = ["--lora-scaled", drive_lettered])
    assert plan is not None, "a form the child rejects is not the unsized-abstain case"
    assert not plan.spills_anything, "nothing priced, so the base load still fits"


def test_an_unreadable_adapter_abstains():
    """Adapter os.stat fails: abstain rather than plan a footprint short by an unknown amount."""
    assert _plan(_Stub(), extra_args = ["--lora", "/no/such/adapter.gguf"]) is None
    assert _plan(_Stub()) is not None, "not vacuous"


def test_an_inherited_projector_is_charged_rather_than_ignored():
    """LLAMA_ARG_MMPROJ applies before argv, so an inherited projector is GPU-resident; charge it."""
    stub = _Stub()
    free = 17 * 1024
    bare = _plan(stub, free_mib = free)
    inherited = _plan(stub, free_mib = free, env_mmproj = 3 * GIB)
    assert bare is not None and inherited is not None
    assert not bare.spills_anything, "the base load fits on its own"
    assert inherited.spills_anything, "3 GiB of inherited projector comes out of the same VRAM"


def test_an_unsized_inherited_projector_abstains():
    """An LLAMA_ARG_MMPROJ_URL projector has unknown size until fetched: abstain, do not plan short."""
    assert _plan(_Stub(), free_mib = 14 * 1024, env_mmproj_unsized = True) is None
    assert _plan(_Stub(), free_mib = 14 * 1024) is not None, "not vacuous"


def test_the_seam_hands_the_planner_the_inherited_projector():
    """Planner can only charge snapshotted launch values; load-mode fit already computes them."""
    compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
    assert '_spill_inputs["env_mmproj_unsized"]=_fit_env_mmproj_unsized' in compact
    assert '_spill_inputs["env_mmproj_bytes"]=' in compact


class _FlatAttentionStub(_Stub):
    """Every layer caches, no window, no trailing blocks: the layout _per_device_shortfall can check."""

    def _tensor_spill_layout(self, model_path):
        n = 8
        return ModelLayout(
            arch = "qwen35",
            n_layers = n,
            n_attention_layers = n,
            blocks = tuple(
                BlockLayout(index = i, spillable_bytes = 2 * GIB, resident_bytes = GIB // 2)
                for i in range(n)
            ),
            lm_head_bytes = 1 * GIB,
            token_embd_bytes = 512 * MIB,
            kv_bytes_per_token_f16 = 16384,
            n_ctx_train = 262144,
            complete = True,
        )


def test_a_multi_gpu_adapter_declines_rather_than_booking_it_all_on_device_0(sparse_adapter):
    """Multi-GPU adapters decline: LoRA follows its base layer's card, but extra bytes book to device 0."""
    adapter = sparse_adapter

    stub = _FlatAttentionStub()
    # Only an all-blocks spill reaches the per-device check; the adapter rows belong to device 1.
    two_cards = dict(model_size = 21 * GIB, kv = 2 * GIB, gpus = [(0, 10 * 1024), (1, 3 * 1024)])
    for flag in ("--lora", "--control-vector"):
        assert _plan(stub, extra_args = [flag, str(adapter)], **two_cards) is None

    assert _plan(stub, **two_cards) is not None

    one_card = _plan(_Stub(), free_mib = 17 * 1024, extra_args = ["--lora", str(adapter)])
    assert one_card is not None and one_card.spills_anything


def test_apple_silicon_declines_the_plan(monkeypatch):
    """Apple silicon declines: a spill inside unified memory frees nothing."""
    import utils.hardware

    monkeypatch.setattr(utils.hardware, "is_apple_silicon", lambda: True)
    assert _plan(_Stub(), free_mib = 14 * 1024) is None

    monkeypatch.setattr(utils.hardware, "is_apple_silicon", lambda: False)
    assert _plan(_Stub(), free_mib = 14 * 1024) is not None, "not vacuous"


def test_an_integrated_cuda_device_declines_the_plan():
    """An integrated CUDA SoC is unified memory no other guard sees, so its VRAM and RAM count twice."""
    discrete = _Stub()
    soc = _Stub()
    soc._integrated_cuda = True

    assert _plan(soc, free_mib = 14 * 1024) is None
    assert _plan(discrete, free_mib = 14 * 1024) is not None, "not vacuous"


def test_a_multi_gpu_separate_drafter_declines_rather_than_booking_it_on_device_0():
    """A multi-GPU separate drafter declines: it spreads across cards, but its reserve books on device 0."""
    stub = _FlatAttentionStub()
    # Only all-blocks spill reaches the per-device check; extra_gpu carries the drafter reserve.
    two_cards = dict(
        model_size = 21 * GIB,
        kv = 2 * GIB,
        extra_gpu = 3 * GIB,
        # 9 GiB: split reserve is now charged only for the second card.
        gpus = [(0, 9 * 1024), (1, 3 * 1024)],
    )
    assert _plan(stub, separate_draft = True, **two_cards) is None

    without = _plan(stub, **two_cards)
    assert without is not None and without.spills_anything

    one_card = _plan(_Stub(), free_mib = 14 * 1024, separate_draft = True)
    assert one_card is not None and one_card.spills_anything


def test_the_flat_mtp_reserve_reaches_the_spill_budget():
    """An unsized draft KV means the budget must drop _MTP_VRAM_RESERVE_FRAC, or the plan spends it."""
    compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
    assert '"gpu_usable_mib":{_idx:max(0.0,_gpu_usable((_idx,_free),_pin_fraction))' in compact

    stub = _Stub()
    generous = _plan(stub, free_mib = 24 * 1024, usable_mib = 15 * 1024)
    reserved = _plan(stub, free_mib = 24 * 1024, usable_mib = 14 * 1024)
    assert generous is not None and reserved is not None
    assert len(reserved.spilled_blocks) > len(generous.spilled_blocks)


def test_the_seam_computes_a_per_layer_kv_vector():
    """Only RATIOS cross to the planner: full attention holds the context, a window layer its window."""
    b = LlamaCppBackend.__new__(LlamaCppBackend)
    b._n_layers = 6
    b._n_kv_heads = 8
    b._n_heads = 8
    b._kv_key_length = 128
    b._kv_value_length = 128
    b._kv_key_length_swa = None
    b._kv_value_length_swa = None
    b._sliding_window = 1024
    b._sliding_window_pattern = [False, True, True, True, True, True]
    b._n_kv_heads_by_layer = None
    b._shared_kv_layers = None
    b._kv_lora_rank = None
    b._ssm_inner_size = None
    b._full_attention_interval = None

    weights = b._kv_layer_weights(131072)
    assert len(weights) == 6
    assert weights[0] == max(weights), "the full-attention layer is the big one"
    # Compact SWA allowance = window + one micro-batch, padded to 256 cells.
    assert weights[0] // weights[1] == 131072 // (1024 + 512)

    b._sliding_window_pattern = None
    assert b._kv_layer_weights(131072) == []
    b._sliding_window_pattern = [False, True, True, True, True, True]
    b._sliding_window = 0
    assert b._kv_layer_weights(131072) == []


def _swa_backend(n_layers = 6, shared = None):
    b = LlamaCppBackend.__new__(LlamaCppBackend)
    b._n_layers = n_layers
    b._n_kv_heads = 8
    b._n_heads = 8
    b._kv_key_length = 128
    b._kv_value_length = 128
    b._kv_key_length_swa = None
    b._kv_value_length_swa = None
    b._sliding_window = 1024
    b._sliding_window_pattern = [i % 2 == 1 for i in range(n_layers)]
    b._n_kv_heads_by_layer = None
    b._shared_kv_layers = shared
    b._kv_lora_rank = None
    b._ssm_inner_size = None
    b._full_attention_interval = None
    return b


def test_shared_kv_layers_carry_no_weight():
    """Gemma shared-KV trailing layers allocate no cache, so they carry no weight; else cards under-book."""
    plain = _swa_backend(shared = None)
    gemma = _swa_backend(shared = 2)

    w = gemma._kv_layer_weights(131072)
    assert len(w) == 6, "length must still match layout.n_layers or the vector is dropped"
    assert w[4] == 0 and w[5] == 0, "the shared-KV tail allocates no cache"
    assert w[:4] == plain._kv_layer_weights(131072)[:4], "the cached layers are unchanged"

    assert any(_swa_backend(shared = 99)._kv_layer_weights(131072))


def test_swa_weights_follow_the_effective_cache_geometry():
    """Cache weights follow launch geometry: --swa-full makes each SWA layer hold full context."""
    b = _swa_backend()

    full = b._kv_layer_weights(131072, swa_full = True)
    assert len(set(full)) == 1, "--swa-full: every layer holds the full context"

    one = b._kv_layer_weights(131072, n_parallel = 1)
    four = b._kv_layer_weights(131072, n_parallel = 4)
    assert four[1] > one[1], "4 slots hold 4 windows' worth of SWA cells"
    assert four[0] == one[0], "the full-attention layer is unaffected in unified mode"

    assert b._kv_layer_weights(131072, n_ubatch = 4096)[1] > one[1]


def test_the_seam_passes_the_launch_geometry_to_the_kv_vector():
    """Knobs must travel from the launch path, or the fixes only hold in a unit test."""
    src = inspect.getsource(LlamaCppBackend.load_model)
    call = src[src.index('"kv_layer_weights"') :][:400]
    compact = "".join(call.split())
    assert "swa_full=swa_full" in compact
    assert "n_parallel=n_parallel" in compact
    assert "kv_unified=planned_kv_unified" in compact
    assert "n_ubatch=_effective_ubatch" in compact


def test_an_inherited_split_mode_none_declines():
    """An inherited non-layer LLAMA_ARG_SPLIT_MODE is scrubbed at launch, so the plan must decline."""
    two_cards = [(0, 14 * 1024), (1, 14 * 1024)]
    assert _plan(_Stub(), gpus = two_cards, env = {"LLAMA_ARG_SPLIT_MODE": "none"}) is None
    assert _plan(_Stub(), gpus = two_cards, extra_args = ["-sm", "none"]) is not None
    assert (
        _plan(
            _Stub(),
            gpus = two_cards,
            extra_args = ["-sm", "none"],
            env = {"LLAMA_ARG_SPLIT_MODE": "none"},
        )
        is not None
    )
    assert _plan(_Stub(), gpus = two_cards) is not None
    assert _plan(_Stub(), gpus = two_cards, env = {"LLAMA_ARG_SPLIT_MODE": "layer"}) is not None


def test_a_reconciliation_still_strips_a_non_layer_split_mode_env():
    """Anchors the decline: if load_model stops scrubbing an inherited split mode, this must fail."""
    assert "self._reconcile_split_mode_env(env" in inspect.getsource(LlamaCppBackend.load_model)
    compact = "".join(inspect.getsource(LlamaCppBackend._reconcile_split_mode_env).split())
    assert 'if_inherited_smand_inherited_sm!="layer":' in compact
    assert 'env.pop("LLAMA_ARG_SPLIT_MODE",None)' in compact
    assert 'env.pop("LLAMA_ARG_SPLIT_MODE",None)env.pop("LLAMA_ARG_TENSOR_SPLIT",None)' in compact


def test_an_inherited_tensor_split_scrubbed_with_its_mode_is_not_planned_against():
    """An inherited LLAMA_ARG_TENSOR_SPLIT is scrubbed with its mode; never plan against its shares."""
    import core.inference.offload_planner as mod

    two_cards = [(0, 8 * 1024), (1, 16 * 1024)]
    seen = {}
    real = mod.plan_placement

    def spy(*a, **kw):
        seen["w"] = kw.get("split_weights_per_device")
        return real(*a, **kw)

    mod.plan_placement = spy
    try:
        _plan(
            _Stub(),
            gpus = two_cards,
            extra_args = ["-sm", "layer"],
            env = {"LLAMA_ARG_SPLIT_MODE": "row", "LLAMA_ARG_TENSOR_SPLIT": "9,1"},
        )
        scrubbed = seen.pop("w", None)
        _plan(_Stub(), gpus = two_cards, env = {"LLAMA_ARG_TENSOR_SPLIT": "9,1"})
        survives = seen.pop("w", None)
    finally:
        mod.plan_placement = real

    assert scrubbed == [8 * 1024 * MIB, 16 * 1024 * MIB], "the child never sees that -ts"
    assert survives == [9.0, 1.0]


@pytest.mark.parametrize("value", ["nan,1", "inf,1", "1,nan", "-nan,1", "infinity,1"])
def test_a_non_finite_tensor_split_declines_instead_of_raising(value):
    """A non-finite -ts value (nan, inf) must decline: it passes the guards, then raises and aborts."""
    assert _extra_args_tensor_split(["-ts", value], {}) is None
    two_cards = [(0, 14 * 1024), (1, 14 * 1024)]
    assert _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", value]) is None
    assert _plan(_Stub(), gpus = two_cards, env = {"LLAMA_ARG_TENSOR_SPLIT": value}) is None
    assert _extra_args_tensor_split(["-ts", "3,1"], {}) == [3.0, 1.0]
    assert _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", "3,1"]) is not None


def test_a_cumulative_float32_tensor_split_overflow_declines_instead_of_raising():
    value = "3e38,3e38"
    assert _extra_args_tensor_split(["-ts", value], {}) is None
    two_cards = [(0, 14 * 1024), (1, 14 * 1024)]
    assert _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", value]) is None
    assert _plan(_Stub(), gpus = two_cards, env = {"LLAMA_ARG_TENSOR_SPLIT": value}) is None


def test_the_vector_refuses_a_cache_the_estimator_prices_on_another_path():
    """A window vector must refuse MLA and hybrid caches, priced on another path."""
    b = _swa_backend()
    assert b._kv_layer_weights(131072), "the plain SWA model still answers"

    mla = _swa_backend()
    mla._kv_lora_rank = 512
    assert mla._kv_layer_weights(131072) == []

    hybrid = _swa_backend()
    hybrid._ssm_inner_size = 4096
    hybrid._full_attention_interval = 4
    assert hybrid._kv_layer_weights(131072) == []

    half = _swa_backend()
    half._ssm_inner_size = 4096
    assert half._kv_layer_weights(131072)


def test_a_recurrent_hybrid_stays_on_the_abstain_path():
    """No vector: _per_device_shortfall abstains, so recurrent_bytes is never left unplaced."""
    from core.inference.offload_planner import PlanOptions, _per_device_shortfall

    layout = ModelLayout(
        arch = "qwen35moe",
        n_layers = 4,
        n_attention_layers = 1,
        blocks = tuple(
            BlockLayout(index = i, spillable_bytes = GIB, resident_bytes = GIB // 4) for i in range(4)
        ),
        lm_head_bytes = GIB // 2,
        kv_bytes_per_token_f16 = 65536,
        recurrent_bytes = 2 * GIB,
        complete = True,
    )
    why = _per_device_shortfall(
        layout,
        PlanOptions(),
        32768,
        set(),
        False,
        [8 * GIB, 8 * GIB],
        quantised = False,
        kv_bytes_floor = 0,
        kv_layer_weights = (),
    )
    assert why is not None and "recurrent" in why


def test_flash_disabled_v_padding_reaches_the_layer_weights():
    """With flash attention off, V pads to the model's max width, so layer weights must pad too."""
    b = _swa_backend()
    # SWA layers wider than global, so the max width is SWA and the padding moves.
    b._kv_key_length_swa = 256
    b._kv_value_length_swa = 256

    assert b._max_kv_value_width(128, 256) == 8 * 256

    on = b._kv_layer_weights(131072, flash_attn = True)
    off = b._kv_layer_weights(131072, flash_attn = False)
    assert on and off
    assert off != on, "the padding has to reach the vector"

    full_cells, swa_cells = 131072, 1024 + 512
    pad = 8 * 256
    glob = (8 * 128 * 2 + pad * 2) * full_cells
    swa = (8 * 256 * 2 + pad * 2) * swa_cells
    assert off[0] == glob and off[1] == swa

    # A quantised K floors bpe_v at f16, moving the ratio too.
    from core.inference.llama_cpp import _kv_bytes_per_elem

    bpe_k = _kv_bytes_per_elem("q8_0")
    q8 = b._kv_layer_weights(131072, flash_attn = False, cache_type_kv = "q8_0")
    assert q8 != off
    assert q8[0] == int((8 * 128 * bpe_k + pad * 2) * full_cells)


def test_the_seam_passes_the_flash_state_and_cache_type_to_the_kv_vector():
    """The call site is checked by AST: the flash state and cache type must reach the KV vector."""
    import ast
    import textwrap

    tree = ast.parse(textwrap.dedent(inspect.getsource(LlamaCppBackend.load_model)))
    calls = [
        node
        for node in ast.walk(tree)
        if isinstance(node, ast.Call)
        and isinstance(node.func, ast.Attribute)
        and node.func.attr == "_kv_layer_weights"
    ]
    assert calls, "the launch path no longer builds a KV layer vector"

    for call in calls:
        passed = {
            kw.arg: kw.value for kw in call.keywords if kw.arg and isinstance(kw.value, ast.Name)
        }
        assert getattr(passed.get("flash_attn"), "id", None) == "planned_flash_attn"
        assert getattr(passed.get("cache_type_kv"), "id", None) == "cache_type_kv"


def test_a_single_card_pays_no_split_reserve():
    """The pipeline reserve is a layer-split cost: a single card pays none of it."""
    from core.inference.offload_planner import ContextPolicy, PlanOptions, plan_placement

    layout = _Stub()._tensor_spill_layout("/models/stub.gguf")
    opts = PlanOptions(
        overhead_bytes_per_device = 0,
        pipeline_overhead_bytes = 1 * GIB,
        context_policy = ContextPolicy.NEVER_REDUCE,
    )
    resident = sum(b.resident_bytes for b in layout.blocks) + layout.token_embd_bytes
    spillable = sum(b.spillable_bytes for b in layout.blocks)
    need = resident + spillable + layout.lm_head_bytes

    one = plan_placement(layout, [need + 512 * MIB], 64 * GIB, 4096, opts = opts)
    assert not one.spills_anything, (
        "a single card paid a split reserve it does not owe, so a load that fits "
        f"was spilled anyway: {one.reason}"
    )

    # Charged once per device after the first; asserted on budgets since plans hide it.
    from core.inference.offload_planner import _usable_vram

    card = 8 * GIB
    assert _usable_vram([card], opts) == card
    assert _usable_vram([card, card], opts) == 2 * card - 1 * GIB
    assert _usable_vram([card, card, card], opts) == 3 * card - 2 * GIB


def test_the_cost_model_is_told_physical_cores_not_hyperthreads(monkeypatch):
    """Tell the cost model physical cores: an unset --threads makes llama.cpp size its pool by them."""
    monkeypatch.setattr(llama_mod, "_linux_math_core_count", lambda: None)
    assert llama_mod._spilled_decode_threads() >= 1

    class _FakePsutil:
        @staticmethod
        def cpu_count(logical = True):
            return 12 if logical else 6

    saved = sys.modules.get("psutil")
    sys.modules["psutil"] = _FakePsutil
    monkeypatch.setattr(
        llama_mod.os, "sched_getaffinity", lambda _pid: set(range(12)), raising = False
    )
    try:
        assert llama_mod._spilled_decode_threads() == 6, "logical count reached the cost model"
    finally:
        if saved is None:
            del sys.modules["psutil"]
        else:
            sys.modules["psutil"] = saved

    class _NoAnswer:
        @staticmethod
        def cpu_count(logical = True):
            return None

    sys.modules["psutil"] = _NoAnswer
    try:
        for logical, expected in ((2, 2), (4, 4), (8, 4), (16, 8), (None, 4)):
            monkeypatch.setattr(llama_mod.os, "cpu_count", lambda answer = logical: answer)
            monkeypatch.setattr(
                llama_mod.os,
                "sched_getaffinity",
                lambda _pid, answer = logical: set(range(answer or 1)),
            )
            assert llama_mod._spilled_decode_threads() == expected
    finally:
        if saved is None:
            del sys.modules["psutil"]
        else:
            sys.modules["psutil"] = saved


def test_thread_overrides_reach_the_cost_model(monkeypatch):
    seen = []

    def _threads(n_threads = None, extra_args = None):
        seen.append((n_threads, extra_args))
        return int(n_threads or 8)

    monkeypatch.setattr(llama_mod, "_spilled_decode_threads", _threads)
    plan = _plan(
        _Stub(),
        free_mib = 14 * 1024,
        n_threads = 3,
        extra_args = ["--threads", "2"],
        env = {"LLAMA_ARG_THREADS": "1"},
    )

    assert plan is not None and plan.spills_anything
    expected = [(3, ["--threads", "2"])]
    assert seen == expected


def test_thread_override_precedence_matches_the_launched_command(monkeypatch):
    monkeypatch.setattr(llama_mod, "_linux_math_core_count", lambda: None)

    class _FakePsutil:
        @staticmethod
        def cpu_count(logical = True):
            return 12 if logical else 6

    monkeypatch.setitem(sys.modules, "psutil", _FakePsutil)
    monkeypatch.setattr(
        llama_mod.os, "sched_getaffinity", lambda _pid: set(range(12)), raising = False
    )
    assert llama_mod._spilled_decode_threads() == 6
    assert llama_mod._spilled_decode_threads(3) == 3
    assert llama_mod._spilled_decode_threads(3, ["--threads", "4"]) == 4
    assert llama_mod._spilled_decode_threads(3, ["-t=5", "--threads=1"]) == 1


def test_smt_workers_do_not_multiply_math_core_capacity(monkeypatch):
    monkeypatch.setattr(llama_mod, "_linux_math_core_count", lambda: None)

    monkeypatch.setitem(sys.modules, "psutil", _SmtHost)
    monkeypatch.setattr(
        llama_mod.os, "sched_getaffinity", lambda _pid: set(range(16)), raising = False
    )
    monkeypatch.setattr(llama_mod.os, "cpu_count", lambda: 16)
    assert llama_mod._spilled_decode_threads(extra_args = ["--threads", "4"]) == 4
    assert llama_mod._spilled_decode_threads(extra_args = ["--threads", "16"]) is None
    assert llama_mod._spilled_decode_threads(extra_args = ["--threads", "-1"]) is None
    assert llama_mod._spilled_decode_threads(extra_args = ["--threads", "0"]) is None

    class _NonSmtHost:
        @staticmethod
        def cpu_count(logical = True):
            return 8

    monkeypatch.setitem(sys.modules, "psutil", _NonSmtHost)
    monkeypatch.setattr(llama_mod.os, "cpu_count", lambda: 8)
    assert llama_mod._spilled_decode_threads(extra_args = ["--threads", "-1"]) == 8


def test_default_thread_override_uses_native_logical_count(monkeypatch):
    monkeypatch.setattr(llama_mod, "_linux_math_core_count", lambda: 8)
    monkeypatch.setattr(llama_mod.os, "cpu_count", lambda: 2)
    monkeypatch.setitem(sys.modules, "psutil", _SmtHost)
    assert llama_mod._spilled_decode_threads(extra_args = ["--threads", "-1"]) is None


def test_inherited_linux_cpu_affinity_declines_spill_pricing(monkeypatch):
    monkeypatch.setattr(llama_mod, "_linux_math_core_count", lambda: 8)
    monkeypatch.setattr(llama_mod.sys, "platform", "linux")
    monkeypatch.setattr(
        llama_mod.os,
        "uname",
        lambda: SimpleNamespace(machine = "x86_64"),
        raising = False,
    )
    monkeypatch.setattr(llama_mod.os, "sched_getaffinity", lambda _pid: {0, 1}, raising = False)
    monkeypatch.setitem(sys.modules, "psutil", _SmtHost)
    assert llama_mod._spilled_decode_threads() is None

    monkeypatch.setattr(llama_mod.os, "sched_getaffinity", lambda _pid: set(range(16)))
    assert llama_mod._spilled_decode_threads() == 8


def test_inherited_linux_arm_cpu_affinity_declines_spill_pricing(monkeypatch):
    class _ArmHost:
        @staticmethod
        def cpu_count(logical = True):
            return 72 if logical else 36

    monkeypatch.setattr(llama_mod.sys, "platform", "linux")
    monkeypatch.setattr(
        llama_mod.os,
        "uname",
        lambda: SimpleNamespace(machine = "aarch64"),
        raising = False,
    )
    monkeypatch.setattr(
        llama_mod.os, "sched_getaffinity", lambda _pid: set(range(4)), raising = False
    )
    monkeypatch.setitem(sys.modules, "psutil", _ArmHost)
    assert llama_mod._spilled_decode_threads() is None


def test_oversubscribed_decode_threads_decline_spill_planning(monkeypatch):
    monkeypatch.setattr(llama_mod, "_linux_math_core_count", lambda: 8)
    monkeypatch.setattr(llama_mod.sys, "platform", "linux")
    monkeypatch.setattr(
        llama_mod.os,
        "uname",
        lambda: SimpleNamespace(machine = "x86_64"),
        raising = False,
    )
    monkeypatch.setattr(
        llama_mod.os, "sched_getaffinity", lambda _pid: set(range(16)), raising = False
    )
    # Pin psutil to the 16/8 host so the affinity reads unrestricted on wide CI boxes.
    monkeypatch.setitem(sys.modules, "psutil", _SmtHost)
    assert _plan(_Stub(), free_mib = 14 * 1024, extra_args = ["--threads", "16"]) is None
    plan = _plan(
        _Stub(),
        free_mib = 14 * 1024,
        extra_args = ["--threads", "4"],
    )
    assert plan is not None and plan.spills_anything


@pytest.mark.parametrize(
    "extra_args",
    [
        ["--cpu-range", "0-2", "--cpu-strict", "1"],
        ["-C", "0x3"],
        ["--cpu-mask=0x3"],
    ],
)
def test_affinity_constrained_decode_declines_spill_planning(monkeypatch, extra_args):
    monkeypatch.setattr(llama_mod, "_linux_math_core_count", lambda: 8)
    assert _plan(_Stub(), free_mib = 14 * 1024, extra_args = extra_args) is None


def test_linux_hybrid_math_cores_exclude_efficiency_cores(tmp_path):
    sibling_sets = [f"{core},{core + 8}" for core in range(8)]
    sibling_sets.extend(f"{core},{core + 8}" for core in range(8))
    sibling_sets.extend(str(cpu) for cpu in range(16, 32))
    for cpu, sibling_set in enumerate(sibling_sets):
        cpu_path = tmp_path / f"cpu{cpu}"
        (cpu_path / "topology").mkdir(parents = True)
        (cpu_path / "topology" / "thread_siblings").write_text(sibling_set)
        capacity = 1024 if cpu < 16 else 512
        (cpu_path / "cpu_capacity").write_text(str(capacity))

    assert _linux_math_core_count(tmp_path, logical_cpus = 32, vendor_id = "GenuineIntel") == 8


def test_linux_hybrid_pmu_excludes_efficiency_cores_without_capacity(tmp_path):
    cpu_root = tmp_path / "cpu"
    event_root = tmp_path / "events"
    sibling_sets = [f"{core},{core + 4}" for core in range(4)]
    sibling_sets.extend(f"{core},{core + 4}" for core in range(4))
    sibling_sets.extend(str(cpu) for cpu in range(8, 16))
    for cpu, sibling_set in enumerate(sibling_sets):
        cpu_path = cpu_root / f"cpu{cpu}" / "topology"
        cpu_path.mkdir(parents = True)
        (cpu_path / "thread_siblings").write_text(sibling_set)
    (event_root / "cpu_core").mkdir(parents = True)
    (event_root / "cpu_core" / "cpus").write_text("0-7")
    (event_root / "cpu_atom").mkdir()
    (event_root / "cpu_atom" / "cpus").write_text("8-15")

    assert (
        _linux_math_core_count(
            cpu_root,
            vendor_id = "GenuineIntel",
            event_source_root = event_root,
        )
        == 4
    )


@pytest.mark.parametrize("source", ["pmu", "capacity"])
def test_linux_no_smt_hybrid_matches_llama_cpu_loop(tmp_path, source):
    cpu_root = tmp_path / "cpu"
    event_root = tmp_path / "events"
    for cpu in range(8):
        cpu_path = cpu_root / f"cpu{cpu}"
        (cpu_path / "topology").mkdir(parents = True)
        (cpu_path / "topology" / "thread_siblings").write_text(str(cpu))
        if source == "capacity":
            (cpu_path / "cpu_capacity").write_text("1024" if cpu < 4 else "512")
    if source == "pmu":
        (event_root / "cpu_core").mkdir(parents = True)
        (event_root / "cpu_core" / "cpus").write_text("0-3")
        (event_root / "cpu_atom").mkdir()
        (event_root / "cpu_atom" / "cpus").write_text("4-7")

    assert (
        _linux_math_core_count(
            cpu_root,
            vendor_id = "GenuineIntel",
            event_source_root = event_root,
        )
        == 2
    )


def test_linux_sparse_online_hybrid_matches_llama_physical_fallback(tmp_path):
    cpu_root = tmp_path / "cpu"
    event_root = tmp_path / "events"
    sibling_sets = [f"{cpu},{cpu + 8}" for cpu in range(8)]
    sibling_sets.extend(f"{cpu - 8},{cpu}" for cpu in range(8, 16))
    sibling_sets.extend(str(cpu) for cpu in range(16, 24))
    for cpu, sibling_set in enumerate(sibling_sets):
        cpu_path = cpu_root / f"cpu{cpu}" / "topology"
        cpu_path.mkdir(parents = True)
        (cpu_path / "thread_siblings").write_text(sibling_set)
    (cpu_root / "online").write_text("0-7,16-23")
    (event_root / "cpu_core").mkdir(parents = True)
    (event_root / "cpu_core" / "cpus").write_text("0-7")
    (event_root / "cpu_atom").mkdir()
    (event_root / "cpu_atom" / "cpus").write_text("16-23")

    assert (
        _linux_math_core_count(
            cpu_root,
            vendor_id = "GenuineIntel",
            event_source_root = event_root,
        )
        == 16
    )


def test_linux_smt_disabled_hybrid_skips_offline_siblings(tmp_path):
    cpu_root = tmp_path / "cpu"
    event_root = tmp_path / "events"
    sibling_sets = [f"{cpu // 2 * 2},{cpu // 2 * 2 + 1}" for cpu in range(16)]
    sibling_sets.extend(str(cpu) for cpu in range(16, 24))
    for cpu, sibling_set in enumerate(sibling_sets):
        cpu_path = cpu_root / f"cpu{cpu}" / "topology"
        cpu_path.mkdir(parents = True)
        (cpu_path / "thread_siblings").write_text(sibling_set)
    (cpu_root / "online").write_text("0,2,4,6,8,10,12,14,16-23")
    (event_root / "cpu_core").mkdir(parents = True)
    (event_root / "cpu_core" / "cpus").write_text("0,2,4,6,8,10,12,14")
    (event_root / "cpu_atom").mkdir()
    (event_root / "cpu_atom" / "cpus").write_text("16-23")

    assert (
        _linux_math_core_count(
            cpu_root,
            vendor_id = "GenuineIntel",
            event_source_root = event_root,
        )
        == 8
    )


def test_linux_hybrid_unpinnable_cpu_matches_llama_physical_fallback(tmp_path):
    cpu_root = tmp_path / "cpu"
    event_root = tmp_path / "events"
    sibling_sets = [f"{cpu // 2 * 2},{cpu // 2 * 2 + 1}" for cpu in range(16)]
    sibling_sets.extend(str(cpu) for cpu in range(16, 24))
    for cpu, sibling_set in enumerate(sibling_sets):
        cpu_path = cpu_root / f"cpu{cpu}" / "topology"
        cpu_path.mkdir(parents = True)
        (cpu_path / "thread_siblings").write_text(sibling_set)
    (cpu_root / "online").write_text("0-23")
    (event_root / "cpu_core").mkdir(parents = True)
    (event_root / "cpu_core" / "cpus").write_text("0-15")
    (event_root / "cpu_atom").mkdir()
    (event_root / "cpu_atom" / "cpus").write_text("16-23")

    assert (
        _linux_math_core_count(
            cpu_root,
            vendor_id = "GenuineIntel",
            event_source_root = event_root,
            pinnable_cpus = set(range(8)),
        )
        == 16
    )


def test_linux_hybrid_affinity_probe_failure_matches_physical_fallback(tmp_path, monkeypatch):
    cpu_root = tmp_path / "cpu"
    event_root = tmp_path / "events"
    for cpu in range(8):
        cpu_path = cpu_root / f"cpu{cpu}" / "topology"
        cpu_path.mkdir(parents = True)
        (cpu_path / "thread_siblings").write_text(str(cpu))
    (event_root / "cpu_core").mkdir(parents = True)
    (event_root / "cpu_core" / "cpus").write_text("0-3")
    (event_root / "cpu_atom").mkdir()
    (event_root / "cpu_atom" / "cpus").write_text("4-7")

    def fail_affinity(_pid):
        raise OSError("unavailable")

    monkeypatch.setattr(llama_mod.os, "sched_getaffinity", fail_affinity, raising = False)
    monkeypatch.setattr(llama_mod.os, "sched_setaffinity", lambda _pid, _cpus: None, raising = False)
    assert (
        llama_mod._linux_math_core_count(
            cpu_root,
            vendor_id = "GenuineIntel",
            event_source_root = event_root,
            probe_affinity = True,
        )
        == 8
    )


def test_linux_hybrid_affinity_restore_failure_stays_in_worker(tmp_path, monkeypatch):
    cpu_root = tmp_path / "cpu"
    event_root = tmp_path / "events"
    for cpu in range(8):
        cpu_path = cpu_root / f"cpu{cpu}" / "topology"
        cpu_path.mkdir(parents = True)
        (cpu_path / "thread_siblings").write_text(str(cpu))
    (event_root / "cpu_core").mkdir(parents = True)
    (event_root / "cpu_core" / "cpus").write_text("0-3")
    (event_root / "cpu_atom").mkdir()
    (event_root / "cpu_atom" / "cpus").write_text("4-7")
    monkeypatch.setattr(
        llama_mod.os, "sched_getaffinity", lambda _pid: set(range(8)), raising = False
    )
    caller_thread = llama_mod.threading.get_ident()
    affinity_threads = []

    def restore_fails(_pid, cpus):
        affinity_threads.append(llama_mod.threading.get_ident())
        if len(cpus) > 1:
            raise OSError("restore failed")

    monkeypatch.setattr(llama_mod.os, "sched_setaffinity", restore_fails, raising = False)
    assert (
        llama_mod._linux_math_core_count(
            cpu_root,
            vendor_id = "GenuineIntel",
            event_source_root = event_root,
            probe_affinity = True,
        )
        == 2
    )
    assert affinity_threads
    assert all(thread != caller_thread for thread in affinity_threads)


def test_linux_hybrid_with_unreadable_core_mask_is_conservative(tmp_path):
    cpu_root = tmp_path / "cpu"
    event_root = tmp_path / "events"
    for cpu in range(4):
        cpu_path = cpu_root / f"cpu{cpu}" / "topology"
        cpu_path.mkdir(parents = True)
        (cpu_path / "thread_siblings").write_text(str(cpu))
    (event_root / "cpu_atom").mkdir(parents = True)
    (event_root / "cpu_atom" / "cpus").write_text("2-3")

    assert (
        _linux_math_core_count(
            cpu_root,
            vendor_id = "GenuineIntel",
            event_source_root = event_root,
        )
        == 1
    )


def test_linux_hybrid_with_only_efficiency_cores_matches_llama_fallback(tmp_path):
    cpu_root = tmp_path / "cpu"
    event_root = tmp_path / "events"
    for cpu in range(4):
        cpu_path = cpu_root / f"cpu{cpu}" / "topology"
        cpu_path.mkdir(parents = True)
        (cpu_path / "thread_siblings").write_text(str(cpu))
    (event_root / "cpu_core").mkdir(parents = True)
    (event_root / "cpu_core" / "cpus").write_text("")
    (event_root / "cpu_atom").mkdir()
    (event_root / "cpu_atom" / "cpus").write_text("0-3")

    assert (
        _linux_math_core_count(
            cpu_root,
            vendor_id = "GenuineIntel",
            event_source_root = event_root,
        )
        == 4
    )


def test_linux_topology_ignores_python_cpu_count_override(tmp_path, monkeypatch):
    for cpu in range(4):
        cpu_path = tmp_path / f"cpu{cpu}" / "topology"
        cpu_path.mkdir(parents = True)
        (cpu_path / "thread_siblings").write_text(str(cpu))
    monkeypatch.setattr(llama_mod.os, "cpu_count", lambda: 2)

    assert llama_mod._linux_math_core_count(tmp_path, vendor_id = "AuthenticAMD") == 4


def test_linux_non_hybrid_topology_excludes_offline_cores(tmp_path):
    sibling_sets = ["0,4", "1,5", "2,6", "3,7", "0,4", "1,5", "2,6", "3,7"]
    for cpu, sibling_set in enumerate(sibling_sets):
        cpu_path = tmp_path / f"cpu{cpu}" / "topology"
        cpu_path.mkdir(parents = True)
        (cpu_path / "thread_siblings").write_text(sibling_set)
    (tmp_path / "online").write_text("0-2,4-6")

    assert _linux_math_core_count(tmp_path, vendor_id = "AuthenticAMD") == 3


def test_linux_amd_capacity_classes_keep_all_physical_cores(tmp_path):
    for cpu in range(24):
        cpu_path = tmp_path / f"cpu{cpu}"
        (cpu_path / "topology").mkdir(parents = True)
        (cpu_path / "topology" / "thread_siblings").write_text(str(cpu))
        (cpu_path / "cpu_capacity").write_text("1024" if cpu < 8 else "512")

    assert _linux_math_core_count(tmp_path, logical_cpus = 24, vendor_id = "AuthenticAMD") == 24


@pytest.mark.parametrize(
    ("sibling_sets", "expected"),
    [
        (["0,4", "1,5", "2,6", "3,7", "0,4", "1,5", "2,6", "3,7"], 4),
        ([str(cpu) for cpu in range(8)], 8),
    ],
)
def test_linux_smt_and_non_smt_core_counts(tmp_path, sibling_sets, expected):
    for cpu, sibling_set in enumerate(sibling_sets):
        cpu_path = tmp_path / f"cpu{cpu}"
        (cpu_path / "topology").mkdir(parents = True)
        (cpu_path / "topology" / "thread_siblings").write_text(sibling_set)

    assert _linux_math_core_count(tmp_path, logical_cpus = len(sibling_sets)) == expected


def test_invalid_linux_topology_falls_back_to_psutil(monkeypatch):
    class _PhysicalHost:
        @staticmethod
        def cpu_count(logical = True):
            return 24 if logical else 12

    monkeypatch.setattr(llama_mod, "_linux_math_core_count", lambda: None)
    monkeypatch.setattr(
        llama_mod.os, "sched_getaffinity", lambda _pid: set(range(24)), raising = False
    )
    monkeypatch.setitem(sys.modules, "psutil", _PhysicalHost)
    assert llama_mod._spilled_decode_threads() == 12


def test_a_larger_micro_batch_compute_buffer_spills_more_experts():
    """The expert-spill raise (ubatch 512 -> 2048) adds ~0.5-0.9 GiB of compute
    buffer. Priced into compute_buffer_flat, it comes out of the experts kept on the
    GPU instead of becoming a graph_reserve OOM."""
    stub = _Stub(moe = 40)
    at_512 = _plan(
        stub, model_size = 30 * GIB, kv = 2 * GIB, free_mib = 12 * 1024, compute_flat = 300 * MIB
    )
    at_2048 = _plan(
        stub, model_size = 30 * GIB, kv = 2 * GIB, free_mib = 12 * 1024, compute_flat = 1100 * MIB
    )

    assert at_512.spills_anything and at_2048.spills_anything
    assert len(at_2048.spilled_blocks) > len(at_512.spilled_blocks)
    assert at_2048.vram_bytes < at_512.vram_bytes