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.

160 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

from __future__ import annotations

import sys
import threading
from pathlib import Path
from types import SimpleNamespace

import pytest

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

from hub.utils.download_manifest import ExpectedFile
from hub.utils.gguf import (
    is_mtp_drafter_path,
    list_local_gguf_variants as list_hub_local_gguf_variants,
)
from hub.utils.gguf_plan import (
    build_gguf_variant_plans,
    plan_from_expected_files,
    preferred_mtp_sibling,
)
from utils.models.model_config import (
    ModelConfig,
    _is_mtp_drafter,
    _local_gguf_companion_search_root,
    detect_gguf_model,
    detect_dflash_file,
    detect_dspark_file,
    detect_mtp_file,
    extract_model_size_b,
    list_local_gguf_variants,
)
from utils.native_path_leases import native_gguf_companion_parent_allowed


DRAFTER_CASES = [
    ("mtp-gemma-4-12b-it.gguf", True),
    ("MTP/gemma-4-12b-it-Q8_0-MTP.gguf", True),
    ("MTP/mtp-gemma-4-E4B-it-BF16.gguf", True),
    ("foo/MTP/bar.gguf", True),
    ("gemma-4-12b-it-Q8_0.gguf", False),
    # Baked-in Qwen MTP: the head is inside the main GGUF, so it is the model, not a companion.
    ("Qwen3.6-27B-MTP-Q4_K_M.gguf", False),
    ("prompt-mtp-test.gguf", False),
    ("smtp/model.gguf", False),
    ("mtp-readme.txt", False),
    ("dspark/dspark-DeepSeek-V4-Flash-0731-BF16.gguf", True),
    ("dspark/dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf", True),
    ("DSPARK/dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf", True),
    ("dspark/whatever.gguf", True),
    ("dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf", True),
    ("dspark\\dspark-DeepSeek-V4-Flash-0731-BF16.gguf", True),
    ("dflash/dflash-model-Q8_0.gguf", True),
    ("dflash-model.gguf", True),
    ("dflash-Qwen3.6-27B-BF16.gguf", True),
    # dflash is a family name, so a dflash/ directory is not a drafter marker.
    ("dflash/Qwen3.6-35B-A3B-DFlash-Q4_K_M.gguf", False),
    ("foo/dflash/bar.gguf", False),
    ("Qwen3.6-35B-A3B-DFlash-Q4_K_M.gguf", False),
    ("qwen36-35b-a3b-dflash-Q8_0.gguf", False),
    ("laguna-xs21-dflash-q4.gguf", False),
    ("xdspark/model.gguf", False),
    ("dspark/README.md", False),
    ("eagle3-gpt-oss-20b-Q8_0.gguf", True),
    ("EAGLE3-gpt-oss-20b-BF16.gguf", True),
    ("quants/eagle3-gpt-oss-20b-Q8_0.gguf", True),
    ("Llama-3.1-8B-Eagle3-Q4_K_M.gguf", False),
    ("eagle3/Llama-3.1-8B-Eagle3-Q4_K_M.gguf", False),
    # <model>-dspark-<quant>.gguf drafters; a name going on past the kind is the model.
    ("Ternary-Bonsai-27B-dspark-Q4_1.gguf", True),
    ("Bonsai-27B-dspark-bf16.gguf", True),
    ("Qwen3.6-27B-DSpark-Q4_K_M.gguf", True),
    ("model-dspark-Q8_0-00001-of-00002.gguf", True),
    ("DeepSeek-V4-Flash-Dspark-Abliterated-MXFP4-BF16-00001-of-00004.gguf", False),
]


@pytest.mark.parametrize("path,expected", DRAFTER_CASES)
def test_drafter_predicate_and_mirrors_agree(path, expected):
    from core.inference.llama_cpp import _is_companion_gguf_path

    assert is_mtp_drafter_path(path) is expected
    assert _is_mtp_drafter(path) is expected
    assert _is_companion_gguf_path(path) is expected


@pytest.mark.parametrize(
    "model_id,size_b",
    [
        ("unsloth/gemma-4-E2B-it-GGUF", 2.0),
        ("unsloth/gemma-4-E4B-it", 4.0),
        ("unsloth/gemma-3n-E4B-it", 4.0),
        ("unsloth/Qwen3.5-35B-A3B", 3.0),
        ("unsloth/gemma-4-12b-it-GGUF", 12.0),
        ("unsloth/Qwen3.5-9B-MTP-GGUF", 9.0),
        ("no-size-here", None),
    ],
)
def test_extract_model_size_b(model_id, size_b):
    assert extract_model_size_b(model_id) == size_b


def _sib(name: str, size: int, sha: str):
    return SimpleNamespace(rfilename = name, size = size, lfs = {"sha256": sha})


GEMMA_SIBLINGS = [
    _sib("gemma-4-12b-it-Q4_K_M.gguf", 4_000, "main-q4"),
    _sib("gemma-4-12b-it-Q8_0.gguf", 8_000, "main-q8"),
    _sib("mtp-gemma-4-12b-it.gguf", 100, "drafter"),
    _sib("MTP/gemma-4-12b-it-Q8_0-MTP.gguf", 100, "mtp-sub-q8"),
    _sib("MTP/gemma-4-12b-it-BF16-MTP.gguf", 200, "mtp-sub-bf16"),
    _sib("mmproj-F16.gguf", 500, "mmproj"),
]


def test_variant_plans_carry_drafter_as_companion():
    plans = build_gguf_variant_plans(GEMMA_SIBLINGS)

    assert set(plans) == {"q4_k_m", "q8_0"}
    for plan in plans.values():
        assert "mtp-gemma-4-12b-it.gguf" in plan.target_filenames
        assert not any("MTP/" in name for name in plan.target_filenames)
        assert "drafter" in plan.companion_hashes
        assert "drafter" not in plan.main_hashes
        assert plan.mmproj_filenames == frozenset({"mmproj-F16.gguf"})

    q4 = plans["q4_k_m"]
    assert q4.main_filenames == frozenset({"gemma-4-12b-it-Q4_K_M.gguf"})
    assert q4.main_size_bytes == 4_000
    assert q4.download_size_bytes == 4_600


GPT_OSS_FILES = [
    "eagle3-gpt-oss-20b-BF16.gguf",
    "eagle3-gpt-oss-20b-Q8_0.gguf",
    "gpt-oss-20b-MXFP4.gguf",
]


def test_eagle3_draft_head_is_not_a_variant_or_the_default():
    from hub.utils.gguf import pick_best_gguf

    assert pick_best_gguf(GPT_OSS_FILES) == "gpt-oss-20b-MXFP4.gguf"

    plans = build_gguf_variant_plans(
        [_sib(name, 1_000, f"sha-{i}") for i, name in enumerate(GPT_OSS_FILES)]
    )
    assert set(plans) == {"mxfp4"}
    assert plans["mxfp4"].target_filenames == ("gpt-oss-20b-MXFP4.gguf",)


BONSAI_FILES = [
    "Bonsai-27B-F16.gguf",
    "Bonsai-27B-Q1_0.gguf",
    "Bonsai-27B-dspark-Q4_1.gguf",
    "Bonsai-27B-dspark-bf16.gguf",
    "Bonsai-27B-mmproj-BF16.gguf",
]


def test_bonsai_dspark_drafter_is_not_a_variant():
    # #11259: the drafter was the smallest row, and llama-server cannot load it as a model.
    plans = build_gguf_variant_plans(
        [_sib(name, 1_000, f"sha-{i}") for i, name in enumerate(BONSAI_FILES)]
    )
    assert set(plans) == {"f16", "q1_0"}
    assert plans["q1_0"].main_filenames == frozenset({"Bonsai-27B-Q1_0.gguf"})


def test_baked_in_repo_plans_unchanged():
    plans = build_gguf_variant_plans([_sib("Qwen3.6-27B-MTP-Q4_K_M.gguf", 4_000, "q4")])
    assert plans["q4_k_m"].target_filenames == ("Qwen3.6-27B-MTP-Q4_K_M.gguf",)


def test_variant_plan_keeps_root_mtp_sidecar_until_metadata_is_available():
    siblings = [
        _sib("RVN-Q6_K-mtp.gguf", 4_000, "main"),
        _sib("mtp-RVN.gguf", 100, "drafter"),
        _sib("mmproj-F16.gguf", 500, "mmproj"),
    ]

    plan = build_gguf_variant_plans(siblings)["q6_k"]

    assert plan.target_filenames == ("RVN-Q6_K-mtp.gguf", "mmproj-F16.gguf", "mtp-RVN.gguf")
    assert plan.companion_hashes == frozenset({"drafter", "mmproj"})
    assert plan.required_hashes == frozenset({"drafter", "main", "mmproj"})
    assert plan.download_size_bytes == 4_600


def test_variant_plan_keeps_every_nested_mtp_shard_or_none():
    main = _sib("Qwen3.8-Flash-Next-Q4_K_M.gguf", 100, "main")
    first = _sib(
        "MTP/mtp-Qwen3.8-Flash-Next-Q8_0-00001-of-00002.gguf",
        20,
        "mtp-1",
    )
    second = _sib(
        "MTP/mtp-Qwen3.8-Flash-Next-Q8_0-00002-of-00002.gguf",
        20,
        "mtp-2",
    )

    complete = build_gguf_variant_plans([main, first, second])["q4_k_m"]
    assert complete.target_filenames == (
        "Qwen3.8-Flash-Next-Q4_K_M.gguf",
        "MTP/mtp-Qwen3.8-Flash-Next-Q8_0-00001-of-00002.gguf",
        "MTP/mtp-Qwen3.8-Flash-Next-Q8_0-00002-of-00002.gguf",
    )
    assert complete.companion_hashes == frozenset({"mtp-1", "mtp-2"})
    assert complete.download_size_bytes == 140

    incomplete = build_gguf_variant_plans([main, first])["q4_k_m"]
    assert incomplete.target_filenames == ("Qwen3.8-Flash-Next-Q4_K_M.gguf",)
    assert incomplete.companion_hashes == frozenset()
    assert incomplete.download_size_bytes == 100


def test_old_manifest_resume_reclassifies_drafter():
    old = [
        ExpectedFile(path = "gemma-4-12b-it-Q8_0.gguf", size = 8_000, sha256 = "main-q8"),
        ExpectedFile(path = "mtp-gemma-4-12b-it.gguf", size = 100, sha256 = "drafter"),
    ]
    plan = plan_from_expected_files("Q8_0", old)
    assert plan.main_hashes == frozenset({"main-q8"})
    assert plan.companion_hashes == frozenset({"drafter"})
    assert plan.mmproj_filenames == frozenset()


def test_detect_mtp_file_finds_root_sibling(tmp_path):
    (tmp_path / "model-Q4_K_M.gguf").write_bytes(b"x")
    (tmp_path / "mtp-model.gguf").write_bytes(b"x")
    (tmp_path / "MTP").mkdir()
    (tmp_path / "MTP" / "model-Q8_0-MTP.gguf").write_bytes(b"x")

    found = detect_mtp_file(str(tmp_path / "model-Q4_K_M.gguf"))
    assert found is not None
    assert found.endswith("mtp-model.gguf")


def test_detect_mtp_file_ignores_sidecar_for_embedded_head(tmp_path, monkeypatch):
    weight = tmp_path / "RVN-Q6_K-mtp.gguf"
    weight.write_bytes(b"main")
    (tmp_path / "mtp-RVN.gguf").write_bytes(b"draft")
    monkeypatch.setattr(
        "utils.models.model_config.read_gguf_nextn_predict_layers",
        lambda path: 1 if path == str(weight) else None,
    )

    assert detect_mtp_file(str(weight)) is None


def test_detect_mtp_file_none_without_sibling(tmp_path):
    (tmp_path / "model-Q4_K_M.gguf").write_bytes(b"x")
    assert detect_mtp_file(str(tmp_path / "model-Q4_K_M.gguf")) is None


def test_detect_dspark_file_prefers_matching_q8_sidecar(tmp_path):
    weight = tmp_path / "DeepSeek-V4-Flash-0731-UD-Q4_K_M.gguf"
    weight.write_bytes(b"target")
    folder = tmp_path / "dspark"
    folder.mkdir()
    q8 = folder / "dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf"
    q8.write_bytes(b"q8")
    (folder / "dspark-Other-Model-Q8_0.gguf").write_bytes(b"foreign")

    assert detect_dspark_file(str(weight)) == str(q8.resolve())


def test_detect_dspark_file_finds_the_sidecar_hermes_stages_under_assets(tmp_path):
    weight = tmp_path / "DeepSeek-V4-Flash-0731-UD-Q4_K_XL-00001-of-00002.gguf"
    weight.write_bytes(b"target")
    (tmp_path / "DeepSeek-V4-Flash-0731-UD-Q4_K_XL-00002-of-00002.gguf").write_bytes(b"target")
    assets = tmp_path / "assets"
    assets.mkdir()
    sidecar = assets / "dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf"
    sidecar.write_bytes(b"q8")
    (assets / "mmproj-Qwen3.8-27B-BF16.gguf").write_bytes(b"projector")

    assert detect_dspark_file(str(weight)) == str(sidecar.resolve())


def test_detect_mtp_file_finds_the_sidecar_hermes_stages_under_assets(tmp_path):
    (tmp_path / "gemma-4-12B-it-qat-Q4_0.gguf").write_bytes(b"x")
    assets = tmp_path / "assets"
    assets.mkdir()
    (assets / "mtp-gemma-4-12B-it.gguf").write_bytes(b"x")

    found = detect_mtp_file(str(tmp_path / "gemma-4-12B-it-qat-Q4_0.gguf"))
    assert found == str((assets / "mtp-gemma-4-12B-it.gguf").resolve())


def test_detect_dspark_file_accepts_the_suffix_naming_scheme(tmp_path):
    """``<model>-dspark.gguf`` pairs too, the same second scheme MTP accepts."""
    weight = tmp_path / "model-Q4_K_M.gguf"
    weight.write_bytes(b"target")
    folder = tmp_path / "dspark"
    folder.mkdir()
    sidecar = folder / "model-Q8_0-dspark.gguf"
    sidecar.write_bytes(b"draft")

    assert detect_dspark_file(str(weight)) == str(sidecar.resolve())


def test_detect_dspark_file_rejects_a_weight_copy_in_the_dspark_folder(tmp_path):
    """Even in dspark/, a published name is required, or a weight copy runs as --model-draft."""
    weight = tmp_path / "model-Q4_K_M.gguf"
    weight.write_bytes(b"target")
    folder = tmp_path / "dspark"
    folder.mkdir()
    (folder / "model-Q8_0.gguf").write_bytes(b"a full weight, not a sidecar")

    assert detect_dspark_file(str(weight)) is None


def test_detect_dspark_file_does_not_cross_attach_a_sibling_family(tmp_path):
    """A folder holding a model and its "-Lite" sibling must not pair across
    them: the family has to prefix the weight at a non-alphanumeric boundary."""
    base = tmp_path / "DeepSeek-V4-Flash-Q4_K_M.gguf"
    base.write_bytes(b"target")
    lite_sidecar = tmp_path / "dspark-DeepSeek-V4-Flash-Lite-Q8_0.gguf"
    lite_sidecar.write_bytes(b"foreign")

    assert detect_dspark_file(str(base)) is None

    own = tmp_path / "dspark-DeepSeek-V4-Flash-Q8_0.gguf"
    own.write_bytes(b"mine")
    assert detect_dspark_file(str(base)) == str(own.resolve())


def test_detect_dspark_file_skips_an_incomplete_split_set(tmp_path):
    """A partial split fails draft startup, so a complete lower-precision copy wins instead."""
    weight = tmp_path / "model-Q4_K_M.gguf"
    weight.write_bytes(b"target")
    (tmp_path / "dspark-model-Q8_0-00001-of-00002.gguf").write_bytes(b"x")
    complete = tmp_path / "dspark-model-BF16.gguf"
    complete.write_bytes(b"x")

    assert detect_dspark_file(str(weight)) == str(complete.resolve())


def test_detect_dspark_file_sums_shards_so_a_split_cannot_outrank_a_smaller_copy(tmp_path):
    """Candidates are collapsed to shard 1, so size must be summed across the
    set or a large split copy outranks a smaller single file at equal precision."""
    weight = tmp_path / "model-Q4_K_M.gguf"
    weight.write_bytes(b"target")
    folder = tmp_path / "dspark"
    folder.mkdir()
    for shard in (1, 2):
        (folder / f"dspark-model-Q8_0-0000{shard}-of-00002.gguf").write_bytes(b"x" * 4000)
    single = tmp_path / "dspark-model-Q8_0.gguf"
    single.write_bytes(b"x" * 5000)

    assert detect_dspark_file(str(weight)) == str(single.resolve())


def test_detect_dspark_file_keeps_a_split_sidecar_on_its_snapshot_path(tmp_path):
    """Split sidecars stay on the snapshot path: blob targets lack the sibling shard names."""
    blobs = tmp_path / "blobs"
    snapshot = tmp_path / "snapshots" / "abc"
    blobs.mkdir()
    snapshot.mkdir(parents = True)
    weight = snapshot / "model-Q4_K_M.gguf"
    weight.write_bytes(b"target")

    first = snapshot / "dspark-model-Q8_0-00001-of-00002.gguf"
    second = snapshot / "dspark-model-Q8_0-00002-of-00002.gguf"
    (blobs / "sha_1").write_bytes(b"d" * 4096)
    (blobs / "sha_2").write_bytes(b"d")
    try:
        first.symlink_to(blobs / "sha_1")
        second.symlink_to(blobs / "sha_2")
    except OSError:
        pytest.skip("symlinks unavailable")

    found = detect_dspark_file(str(weight), str(snapshot))
    assert found == str(first)
    assert (Path(found).parent / second.name).exists()


def test_detect_gguf_model_rejects_drafter_file(tmp_path):
    drafter = tmp_path / "mtp-model.gguf"
    drafter.write_bytes(b"x")
    assert detect_gguf_model(str(drafter)) is None


def test_detect_gguf_model_dir_skips_companions(tmp_path):
    main = tmp_path / "model-Q4_K_M.gguf"
    main.write_bytes(b"xxxx")
    # Companions are larger so a size-sorted pick would wrongly win.
    (tmp_path / "mtp-model.gguf").write_bytes(b"x" * 64)
    (tmp_path / "mmproj-F16.gguf").write_bytes(b"x" * 128)

    assert detect_gguf_model(str(tmp_path)) == str(main.resolve())


def test_detect_mtp_file_pairs_by_weight_name(tmp_path):
    (tmp_path / "gemma-4-12b-it-Q4_K_M.gguf").write_bytes(b"x")
    (tmp_path / "gemma-4-31B-it-Q4_K_M.gguf").write_bytes(b"x")
    (tmp_path / "mtp-gemma-4-12b-it.gguf").write_bytes(b"x")
    (tmp_path / "mtp-gemma-4-31B-it.gguf").write_bytes(b"x")

    found = detect_mtp_file(str(tmp_path / "gemma-4-31B-it-Q4_K_M.gguf"))
    assert found is not None and found.endswith("mtp-gemma-4-31B-it.gguf")


def test_detect_mtp_file_skips_foreign_drafter(tmp_path):
    (tmp_path / "qwen3-8b-Q4_K_M.gguf").write_bytes(b"x")
    (tmp_path / "mtp-gemma-4-12b-it.gguf").write_bytes(b"x")
    assert detect_mtp_file(str(tmp_path / "qwen3-8b-Q4_K_M.gguf")) is None


def test_detect_mtp_file_qat_prefix_layout(tmp_path):
    (tmp_path / "gemma-4-12B-it-qat-Q4_0.gguf").write_bytes(b"x")
    (tmp_path / "mtp-gemma-4-12B-it.gguf").write_bytes(b"x")
    found = detect_mtp_file(str(tmp_path / "gemma-4-12B-it-qat-Q4_0.gguf"))
    assert found is not None and found.endswith("mtp-gemma-4-12B-it.gguf")


def test_detect_mtp_file_search_root(tmp_path):
    sub = tmp_path / "Q4_K_M"
    sub.mkdir()
    (sub / "gemma-4-12b-it-Q4_K_M.gguf").write_bytes(b"x")
    (tmp_path / "mtp-gemma-4-12b-it.gguf").write_bytes(b"x")
    found = detect_mtp_file(str(sub / "gemma-4-12b-it-Q4_K_M.gguf"), search_root = str(tmp_path))
    assert found is not None and found.endswith("mtp-gemma-4-12b-it.gguf")


def test_quant_directory_selection_finds_repo_root_mtp(tmp_path):
    quant_dir = tmp_path / "Q4_0"
    quant_dir.mkdir()
    weight = quant_dir / "gemma-4-E4B-it-qat-Q4_0.gguf"
    weight.write_bytes(b"x")
    mtp_dir = tmp_path / "MTP"
    mtp_dir.mkdir()
    drafter = mtp_dir / "mtp-gemma-4-E4B-it-Q4_0.gguf"
    drafter.write_bytes(b"x")

    search_root = _local_gguf_companion_search_root(str(quant_dir), str(weight))
    assert Path(search_root).resolve() == tmp_path.resolve()
    config = ModelConfig.from_identifier(str(quant_dir))
    assert config.is_local
    assert config.gguf_file == str(weight.resolve())
    assert config.gguf_mtp_file == str(drafter.resolve())


def test_bare_relative_gguf_directory_is_local_source(tmp_path, monkeypatch):
    model_dir = tmp_path / "outputs" / "gemma"
    model_dir.mkdir(parents = True)
    weight = model_dir / "gemma-4-E4B-it-qat-Q4_0.gguf"
    weight.write_bytes(b"x")
    monkeypatch.chdir(tmp_path)

    config = ModelConfig.from_identifier("outputs/gemma")
    assert config.is_local
    assert config.gguf_file == str(weight.resolve())


def test_detect_mtp_file_falls_back_to_new_scheme_subdir(tmp_path):
    weight = tmp_path / "gemma-4-E4B-it-qat-Q4_0.gguf"
    weight.write_bytes(b"x")
    sub = tmp_path / "MTP"
    sub.mkdir()
    (sub / "mtp-gemma-4-E4B-it-BF16.gguf").write_bytes(b"x")
    q4 = sub / "mtp-gemma-4-E4B-it-Q4_0.gguf"
    q4.write_bytes(b"x")

    found = detect_mtp_file(str(weight))
    assert found == str(q4.resolve())


def test_detect_mtp_file_falls_back_to_old_scheme_subdir(tmp_path):
    weight = tmp_path / "gemma-4-12b-it-Q4_K_M.gguf"
    weight.write_bytes(b"x")
    sub = tmp_path / "MTP"
    sub.mkdir()
    drafter = sub / "gemma-4-12b-it-Q8_0-MTP.gguf"
    drafter.write_bytes(b"x")

    found = detect_mtp_file(str(weight))
    assert found == str(drafter.resolve())


def test_detect_mtp_file_root_still_wins_over_subdir(tmp_path):
    weight = tmp_path / "gemma-4-E4B-it-qat-Q4_0.gguf"
    weight.write_bytes(b"x")
    root = tmp_path / "mtp-gemma-4-E4B-it.gguf"
    root.write_bytes(b"x")
    sub = tmp_path / "MTP"
    sub.mkdir()
    (sub / "mtp-gemma-4-E4B-it-Q4_0.gguf").write_bytes(b"x")

    assert detect_mtp_file(str(weight)) == str(root.resolve())


def test_detect_mtp_file_subdir_skips_foreign_drafter(tmp_path):
    weight = tmp_path / "gemma-4-E4B-it-qat-Q4_0.gguf"
    weight.write_bytes(b"x")
    sub = tmp_path / "MTP"
    sub.mkdir()
    (sub / "mtp-gemma-4-12b-it-Q4_0.gguf").write_bytes(b"x")

    assert detect_mtp_file(str(weight)) is None


@pytest.mark.parametrize(
    "companion_path",
    ["mtp-gemma-4-E4B-it-Q4_0.gguf", "MTP/mtp-gemma-4-E4B-it-Q4_0.gguf"],
)
def test_detect_mtp_file_requires_model_name_boundary(tmp_path, companion_path):
    weight = tmp_path / "gemma-4-E4B-item-qat-Q4_0.gguf"
    weight.write_bytes(b"x")
    companion = tmp_path / companion_path
    companion.parent.mkdir(parents = True, exist_ok = True)
    companion.write_bytes(b"x")

    assert detect_mtp_file(str(weight)) is None


def test_detect_mtp_file_accepts_case_variant_subdir(tmp_path):
    weight = tmp_path / "gemma-4-E4B-it-qat-Q4_0.gguf"
    weight.write_bytes(b"x")
    sub = tmp_path / "mtp"
    sub.mkdir()
    drafter = sub / "mtp-gemma-4-E4B-it-Q4_0.gguf"
    drafter.write_bytes(b"x")

    assert detect_mtp_file(str(weight)) == str(drafter.resolve())


def test_native_companion_parent_accepts_root_and_mtp_subdir(tmp_path):
    weight = tmp_path / "gemma-4-E4B-it-qat-Q4_0.gguf"
    weight.write_bytes(b"x")
    root_drafter = tmp_path / "mtp-gemma-4-E4B-it.gguf"
    root_drafter.write_bytes(b"x")
    sub = tmp_path / "MtP"
    sub.mkdir()
    nested_drafter = sub / "mtp-gemma-4-E4B-it-Q4_0.gguf"
    nested_drafter.write_bytes(b"x")

    assert native_gguf_companion_parent_allowed(root_drafter, weight)
    assert native_gguf_companion_parent_allowed(nested_drafter, weight, allowed_subdirs = ("mtp",))


def test_native_companion_parent_rejects_other_nested_directory(tmp_path):
    weight = tmp_path / "gemma-4-E4B-it-qat-Q4_0.gguf"
    weight.write_bytes(b"x")
    sub = tmp_path / "other"
    sub.mkdir()
    drafter = sub / "mtp-gemma-4-E4B-it-Q4_0.gguf"
    drafter.write_bytes(b"x")

    assert not native_gguf_companion_parent_allowed(drafter, weight)


def test_native_companion_parent_rejects_mtp_symlink_escape(tmp_path):
    model_dir = tmp_path / "model"
    model_dir.mkdir()
    weight = model_dir / "gemma-4-E4B-it-qat-Q4_0.gguf"
    weight.write_bytes(b"x")
    outside = tmp_path / "outside"
    outside.mkdir()
    drafter = outside / "mtp-gemma-4-E4B-it-Q4_0.gguf"
    drafter.write_bytes(b"x")
    try:
        (model_dir / "MTP").symlink_to(outside, target_is_directory = True)
    except OSError as exc:
        pytest.skip(f"symlinks unavailable: {exc}")

    assert not native_gguf_companion_parent_allowed(
        model_dir / "MTP" / drafter.name, weight, allowed_subdirs = ("mtp",)
    )


def _loaded_backend(weight, drafter_path):
    from core.inference.llama_cpp import LlamaCppBackend

    b = LlamaCppBackend()
    b._process = SimpleNamespace(
        poll = lambda: None,
        terminate = lambda: None,
        wait = lambda timeout = None: 0,
        kill = lambda: None,
    )
    b._healthy = True
    b._model_identifier = "local-gemma"
    b._gguf_path = str(weight)
    b._hf_variant = None
    b._requested_n_ctx = 4096
    b._cache_type_kv = None
    b._requested_spec_mode = "auto"
    b._speculative_type = "draft-mtp" if drafter_path else "default"
    b._spec_draft_n_max = None
    b._chat_template_override = None
    b._extra_args = None
    b._mtp_draft_path = drafter_path
    return b


def _target_state_kwargs(weight, mtp_draft_path):
    return dict(
        model_identifier = "local-gemma",
        hf_variant = None,
        n_ctx = 4096,
        cache_type_kv = None,
        speculative_type = "auto",
        spec_draft_n_max = None,
        chat_template_override = None,
        extra_args = None,
        is_vision = False,
        gguf_path = str(weight),
        mtp_draft_path = mtp_draft_path,
    )


def test_already_in_target_state_bounces_on_new_drafter(tmp_path):
    from core.inference.llama_cpp import GgufLoadIntent

    weight = tmp_path / "gemma-4-12b-it-Q4_K_M.gguf"
    weight.write_bytes(b"x")
    drafter = tmp_path / "mtp-gemma-4-12b-it.gguf"
    drafter.write_bytes(b"x")

    b = _loaded_backend(weight, None)
    assert not b.adopt_load_intent_if_matched(
        GgufLoadIntent(**_target_state_kwargs(weight, str(drafter)))
    )
    b = _loaded_backend(weight, str(drafter))
    assert b.adopt_load_intent_if_matched(
        GgufLoadIntent(**_target_state_kwargs(weight, str(drafter)))
    )
    intent = dict(
        model_identifier = "local-gemma",
        n_ctx = 4096,
        mtp_draft_path = str(drafter),
        compare_mtp_draft = True,
    )
    assert b.adopt_load_intent_if_matched(GgufLoadIntent(**intent))
    intent["mtp_draft_path"] = None
    assert not b.adopt_load_intent_if_matched(GgufLoadIntent(**intent))


def test_detect_gguf_model_rejects_mtp_subdir_copy(tmp_path):
    sub = tmp_path / "MTP"
    sub.mkdir()
    copy = sub / "gemma-4-12b-it-BF16-MTP.gguf"
    copy.write_bytes(b"x")
    deep = sub / "BF16" / copy.name
    deep.parent.mkdir()
    deep.write_bytes(b"x")
    assert detect_gguf_model(str(copy)) is None
    assert detect_gguf_model(str(sub)) is None
    assert list_local_gguf_variants(str(tmp_path))[0] == []
    assert list_hub_local_gguf_variants(str(tmp_path))[0] == []


def test_registered_mtp_root_keeps_descendant_models_and_excludes_companions(tmp_path, monkeypatch):
    root = tmp_path / "MTP"
    nested = root / "BF16"
    nested.mkdir(parents = True)
    main = root / "Qwen3.6-27B-MTP-001-of-002.gguf"
    terminal = root / "gemma-4-12b-it-Q8_0-MTP.gguf"
    prefixed = root / "mtp-gemma-4-12b-it-Q8_0.gguf"
    nested_model = nested / "gemma-4-12b-it-Q8_0-MTP-001-of-002.gguf"
    for file, size in ((main, 100), (terminal, 20), (prefixed, 30), (nested_model, 40)):
        file.write_bytes(b"x" * size)
    monkeypatch.setattr("storage.studio_db.list_scan_folders", lambda: [{"path": str(root)}])

    assert detect_gguf_model(str(main)) == detect_gguf_model(str(root)) == str(main.resolve())
    assert all(detect_gguf_model(str(file)) is None for file in (terminal, prefixed))
    assert detect_gguf_model(str(nested_model)) == str(nested_model.resolve())
    assert [(v.quant, v.filename) for v in list_local_gguf_variants(str(root))[0]] == [
        ("MTP", main.name),
        ("Q8_0", f"BF16/{nested_model.name}"),
    ]
    hub_variants = list_hub_local_gguf_variants(str(root))[0]
    assert (hub_variants[0].quant, hub_variants[0].filename) == ("Qwen3.6-27B-MTP", main.name)
    assert (hub_variants[-1].quant, hub_variants[-1].filename) == (
        "Q8_0",
        f"BF16/{nested_model.name}",
    )
    config = ModelConfig.from_identifier(str(root), gguf_variant = hub_variants[0].quant)
    assert config and config.is_gguf and config.gguf_file == str(main.resolve())


# MTP/ copies share the mtp- prefix and sort first (uppercase); the root drafter must still win.

NEW_SCHEME_SIBLINGS = [
    _sib("gemma-4-12b-it-Q4_K_M.gguf", 4_000, "main-q4"),
    _sib("gemma-4-12b-it-Q8_0.gguf", 8_000, "main-q8"),
    _sib("mtp-gemma-4-12b-it.gguf", 100, "drafter"),
    _sib("MTP/mtp-gemma-4-12b-it-Q8_0.gguf", 100, "mtp-sub-q8"),
    _sib("MTP/mtp-gemma-4-12b-it-BF16.gguf", 200, "mtp-sub-bf16"),
    _sib("mmproj-F16.gguf", 500, "mmproj"),
]


def test_preferred_mtp_sibling_prefers_root_over_new_scheme_copies():
    picked = preferred_mtp_sibling(NEW_SCHEME_SIBLINGS)
    assert picked is not None and picked.rfilename == "mtp-gemma-4-12b-it.gguf"


def test_variant_plans_new_scheme_uses_root_drafter():
    plans = build_gguf_variant_plans(NEW_SCHEME_SIBLINGS)
    assert set(plans) == {"q4_k_m", "q8_0"}
    for plan in plans.values():
        assert "mtp-gemma-4-12b-it.gguf" in plan.target_filenames
        assert not any("MTP/" in name for name in plan.target_filenames)
        assert "drafter" in plan.companion_hashes
    assert plans["q4_k_m"].download_size_bytes == 4_600


def test_download_mtp_prefers_root_over_new_scheme_copies(monkeypatch):
    from core.inference.llama_cpp import LlamaCppBackend

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    captured = {}

    def _fake_companion(
        *,
        hf_repo,
        hf_token,
        pick,
        label,
        cancel_event = None,
        near_path = None,
        reuse_snapshot_sibling = True,
    ):
        captured["pick"] = pick
        return None

    b = LlamaCppBackend()
    b._download_companion_gguf = _fake_companion
    b._download_mtp(hf_repo = "unsloth/gemma-4-E4B-it-qat-mobile-GGUF")

    repo_files = [
        "MTP/mtp-gemma-4-E4B-it-BF16.gguf",
        "MTP/mtp-gemma-4-E4B-it-Q4_0.gguf",
        "MTP/mtp-gemma-4-E4B-it-Q8_0.gguf",
        "gemma-4-E4B-it-qat-UD-Q2_K_XL.gguf",
        "mmproj-F16.gguf",
        "mtp-gemma-4-E4B-it.gguf",
    ]
    assert captured["pick"](repo_files) == "mtp-gemma-4-E4B-it.gguf"


def test_companion_downloads_forward_the_load_cancel_event(monkeypatch):
    from core.inference.llama_cpp import LlamaCppBackend
    import core.inference.llama_cpp as llama_cpp_module

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr(
        llama_cpp_module, "_companion_snapshot_sibling", lambda near_path, pick: None
    )
    event = threading.Event()
    seen = []
    b = LlamaCppBackend()
    b.probe_server_capabilities = lambda binary = None: {
        "supports_dspark": True,
        "supports_dflash": True,
    }

    def _fake_companion(**kwargs):
        seen.append((kwargs["label"], kwargs["cancel_event"]))
        return None

    b._download_companion_gguf = _fake_companion
    b._download_mmproj(hf_repo = "org/repo", cancel_event = event)
    b._download_mtp(hf_repo = "org/repo", cancel_event = event)
    b._download_dspark(hf_repo = "org/repo", cancel_event = event)
    b._download_dflash(hf_repo = "org/repo", cancel_event = event)

    assert {label for label, _ in seen} == {
        "mmproj",
        "MTP drafter",
        "DSpark drafter",
        "DFlash drafter",
    }
    assert all(forwarded is event for _, forwarded in seen)


def _seed_snapshot(tmp_path, names):
    snap = tmp_path / "snap"
    for rel in names:
        f = snap / rel
        f.parent.mkdir(parents = True, exist_ok = True)
        f.write_bytes(b"x")
    return snap


def _hub_snapshot(tmp_path, names):
    """A snapshot in the layout _snapshot_dir_of recognises: .../snapshots/<rev>/."""
    snap = tmp_path / "hub" / "models--unsloth--Qwen3.8-Flash-Next-GGUF" / "snapshots" / "abc"
    for rel in names:
        f = snap / rel
        f.parent.mkdir(parents = True, exist_ok = True)
        f.write_bytes(b"x")
    return snap


def _capture_companion_download(backend):
    captured = {}

    def _fake(
        *,
        hf_repo,
        hf_token,
        pick,
        label,
        cancel_event = None,
        near_path = None,
        reuse_snapshot_sibling = True,
    ):
        captured["pick"] = pick
        captured["near_path"] = near_path
        captured["reuse_snapshot_sibling"] = reuse_snapshot_sibling
        return "/downloaded/mtp-Qwen3.8-Flash-Next-Q8_0.gguf"

    backend._download_companion_gguf = _fake
    return captured


def test_download_mtp_refetches_when_the_cache_holds_only_a_shared_head(tmp_path, monkeypatch):
    from core.inference.llama_cpp import LlamaCppBackend
    import utils.models.gguf_metadata as gm

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr(gm, "read_gguf_nextn_predict_layers", lambda p: 0)
    snap = _hub_snapshot(
        tmp_path,
        ["UD-IQ1_S/model.gguf", "MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"],
    )
    b = LlamaCppBackend()
    captured = _capture_companion_download(b)

    got = b._download_mtp(
        hf_repo = "unsloth/Qwen3.8-Flash-Next-GGUF", near_path = str(snap / "UD-IQ1_S" / "model.gguf")
    )
    assert "pick" in captured, "a lone shared head was reused without consulting the repo"
    assert got == "/downloaded/mtp-Qwen3.8-Flash-Next-Q8_0.gguf"


def test_download_mtp_still_reuses_a_cached_self_contained_head(tmp_path, monkeypatch):
    from core.inference.llama_cpp import LlamaCppBackend
    import utils.models.gguf_metadata as gm

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr(gm, "read_gguf_nextn_predict_layers", lambda p: 0)
    snap = _hub_snapshot(
        tmp_path,
        [
            "UD-IQ1_S/model.gguf",
            "MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf",
            "MTP/mtp-Qwen3.8-Flash-Next-Q8_0.gguf",
        ],
    )
    b = LlamaCppBackend()
    captured = _capture_companion_download(b)

    got = b._download_mtp(
        hf_repo = "unsloth/Qwen3.8-Flash-Next-GGUF", near_path = str(snap / "UD-IQ1_S" / "model.gguf")
    )
    assert "pick" not in captured
    assert got is not None and Path(got).name == "mtp-Qwen3.8-Flash-Next-Q8_0.gguf"


def test_download_mtp_keeps_a_lone_shared_head_offline(tmp_path, monkeypatch):
    from core.inference.llama_cpp import LlamaCppBackend
    import utils.models.gguf_metadata as gm

    monkeypatch.setenv("HF_HUB_OFFLINE", "1")
    monkeypatch.setattr(gm, "read_gguf_nextn_predict_layers", lambda p: 0)
    snap = _hub_snapshot(
        tmp_path,
        ["UD-IQ1_S/model.gguf", "MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"],
    )
    b = LlamaCppBackend()
    captured = _capture_companion_download(b)

    got = b._download_mtp(
        hf_repo = "unsloth/Qwen3.8-Flash-Next-GGUF", near_path = str(snap / "UD-IQ1_S" / "model.gguf")
    )
    assert "pick" not in captured
    assert got is not None and Path(got).name == "mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"


def _stub_hub(
    monkeypatch,
    published,
    *,
    listing_fails = False,
):
    """The live repo without a network, stubbed below the helper's own snapshot lookup."""
    import core.inference.llama_cpp as llama_cpp_module
    import huggingface_hub

    def _list(repo, token = None):
        if listing_fails:
            raise ConnectionError("hub unreachable")
        return list(published)

    monkeypatch.setattr(huggingface_hub, "list_repo_files", _list)
    monkeypatch.setattr(llama_cpp_module, "_hub_download_in_flight", lambda repo: False)
    monkeypatch.setattr(
        llama_cpp_module,
        "hf_hub_download_with_xet_fallback",
        lambda repo, fn, token, cancel_event = None, cache_dir = None: "/downloaded/" + fn,
    )


def test_download_mtp_lists_the_repo_past_the_helpers_own_snapshot_reuse(tmp_path, monkeypatch):
    """The helper repeats _companion_snapshot_sibling before listing, so the caller's
    fall-through returned the same borrowing head (unsloth#10322). Uses the real helper."""
    from core.inference.llama_cpp import LlamaCppBackend
    import utils.models.gguf_metadata as gm

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr(gm, "read_gguf_nextn_predict_layers", lambda p: 0)
    snap = _hub_snapshot(
        tmp_path,
        ["UD-IQ1_S/model.gguf", "MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"],
    )
    _stub_hub(
        monkeypatch,
        [
            "UD-IQ1_S/model.gguf",
            "MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf",
            "MTP/mtp-Qwen3.8-Flash-Next-Q8_0.gguf",
        ],
    )

    got = LlamaCppBackend()._download_mtp(
        hf_repo = "unsloth/Qwen3.8-Flash-Next-GGUF",
        near_path = str(snap / "UD-IQ1_S" / "model.gguf"),
    )
    assert got is not None and Path(got).name == "mtp-Qwen3.8-Flash-Next-Q8_0.gguf", (
        f"the fall-through handed back {got}; the helper reused the snapshot copy "
        f"before listing the repo"
    )


def test_download_mtp_keeps_the_borrowing_head_when_the_listing_never_answers(
    tmp_path, monkeypatch
):
    from core.inference.llama_cpp import LlamaCppBackend
    import utils.models.gguf_metadata as gm

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr(gm, "read_gguf_nextn_predict_layers", lambda p: 0)
    snap = _hub_snapshot(
        tmp_path,
        ["UD-IQ1_S/model.gguf", "MTP/mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"],
    )
    _stub_hub(monkeypatch, [], listing_fails = True)

    got = LlamaCppBackend()._download_mtp(
        hf_repo = "unsloth/Qwen3.8-Flash-Next-GGUF",
        near_path = str(snap / "UD-IQ1_S" / "model.gguf"),
    )
    assert got is not None and Path(got).name == "mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"


def test_download_mtp_reuses_cached_root_drafter_offline(tmp_path, monkeypatch):
    from core.inference.llama_cpp import LlamaCppBackend
    import utils.models.model_config as mc

    monkeypatch.setenv("HF_HUB_OFFLINE", "1")
    snap = _seed_snapshot(
        tmp_path,
        [
            "gemma-4-E4B-it-qat-UD-Q2_K_XL.gguf",
            "mtp-gemma-4-E4B-it.gguf",
            "MTP/mtp-gemma-4-E4B-it-BF16.gguf",
            "mmproj-F16.gguf",
        ],
    )
    monkeypatch.setattr(mc, "_iter_hf_cache_snapshots", lambda repo: [snap])

    got = LlamaCppBackend()._download_mtp(hf_repo = "unsloth/gemma-4-E4B-it-qat-mobile-GGUF")
    assert got is not None and Path(got).name == "mtp-gemma-4-E4B-it.gguf"


def test_download_mtp_reuses_cached_subdir_copy_when_no_root_offline(tmp_path, monkeypatch):
    from core.inference.llama_cpp import LlamaCppBackend
    import utils.models.model_config as mc

    monkeypatch.setenv("HF_HUB_OFFLINE", "1")
    snap = _seed_snapshot(
        tmp_path,
        [
            "gemma-4-E4B-it-qat-UD-Q2_K_XL.gguf",
            "MTP/mtp-gemma-4-E4B-it-BF16.gguf",
        ],
    )
    monkeypatch.setattr(mc, "_iter_hf_cache_snapshots", lambda repo: [snap])

    got = LlamaCppBackend()._download_mtp(hf_repo = "unsloth/gemma-4-E4B-it-qat-mobile-GGUF")
    assert got is not None and Path(got).name == "mtp-gemma-4-E4B-it-BF16.gguf"


def test_download_mtp_prefers_root_across_snapshots_offline(tmp_path, monkeypatch):
    from core.inference.llama_cpp import LlamaCppBackend
    import utils.models.model_config as mc

    monkeypatch.setenv("HF_HUB_OFFLINE", "1")
    snap_partial = _seed_snapshot(tmp_path / "new", ["MTP/mtp-gemma-4-E4B-it-BF16.gguf"])
    snap_full = _seed_snapshot(tmp_path / "old", ["mtp-gemma-4-E4B-it.gguf"])
    monkeypatch.setattr(mc, "_iter_hf_cache_snapshots", lambda repo: [snap_partial, snap_full])

    got = LlamaCppBackend()._download_mtp(hf_repo = "unsloth/gemma-4-E4B-it-qat-mobile-GGUF")
    assert got is not None and Path(got).name == "mtp-gemma-4-E4B-it.gguf"


def test_download_mtp_reuse_follows_snapshot_order_offline(tmp_path, monkeypatch):
    # Newest-first so a fresh main GGUF is not paired with a stale drafter revision.

    from core.inference.llama_cpp import LlamaCppBackend
    import utils.models.model_config as mc

    monkeypatch.setenv("HF_HUB_OFFLINE", "1")
    newest = _seed_snapshot(tmp_path / "newest", ["mtp-gemma-4-E4B-it.gguf"])
    oldest = _seed_snapshot(tmp_path / "oldest", ["mtp-gemma-4-E4B-it.gguf"])
    monkeypatch.setattr(mc, "_iter_hf_cache_snapshots", lambda repo: [newest, oldest])

    got = LlamaCppBackend()._download_mtp(hf_repo = "unsloth/gemma-4-E4B-it-qat-mobile-GGUF")
    assert got is not None and Path(got).parent.parent.name == "newest"


def test_download_mtp_prefers_main_snapshot_offline(tmp_path, monkeypatch):
    from core.inference.llama_cpp import LlamaCppBackend
    import utils.models.model_config as mc

    monkeypatch.setenv("HF_HUB_OFFLINE", "1")
    snapshots = tmp_path / "models--unsloth--gemma" / "snapshots"
    old = snapshots / "old"
    new = snapshots / "new"
    old.mkdir(parents = True)
    new.mkdir(parents = True)
    main = old / "gemma-UD-Q4_K_XL.gguf"
    old_drafter = old / "mtp-gemma.gguf"
    new_drafter = new / "mtp-gemma.gguf"
    main.write_bytes(b"main")
    old_drafter.write_bytes(b"old")
    new_drafter.write_bytes(b"new")
    monkeypatch.setattr(mc, "_iter_hf_cache_snapshots", lambda _repo: [new, old])

    got = LlamaCppBackend()._download_mtp(
        hf_repo = "unsloth/gemma-GGUF",
        near_path = str(main),
    )

    assert got == str(old_drafter)


def test_download_mtp_skips_discovery_for_embedded_head(tmp_path, monkeypatch):
    from core.inference.llama_cpp import LlamaCppBackend

    main = tmp_path / "RVN-Q6_K-mtp.gguf"
    main.write_bytes(b"main")
    reached = False

    def _unexpected_download(**_kwargs):
        nonlocal reached
        reached = True
        return str(tmp_path / "mtp-RVN.gguf")

    monkeypatch.setattr(
        "utils.models.gguf_metadata.read_gguf_nextn_predict_layers",
        lambda path: 1 if path == str(main) else None,
    )
    backend = LlamaCppBackend()
    backend._download_companion_gguf = _unexpected_download

    assert backend._download_mtp(hf_repo = "org/repo", near_path = str(main)) is None
    assert reached is False


def test_download_mtp_online_skips_cache_reuse(tmp_path, monkeypatch):
    # Online, skip cached copy so hf_hub_download refetches a changed drafter.

    from core.inference.llama_cpp import LlamaCppBackend
    import utils.models.model_config as mc

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    snap = _seed_snapshot(tmp_path, ["mtp-gemma-4-E4B-it.gguf"])
    monkeypatch.setattr(mc, "_iter_hf_cache_snapshots", lambda repo: [snap])

    reached = {}

    def _fake_companion(
        *,
        hf_repo,
        hf_token,
        pick,
        label,
        cancel_event = None,
        near_path = None,
        reuse_snapshot_sibling = True,
    ):
        reached["hit"] = True
        return None

    b = LlamaCppBackend()
    b._download_companion_gguf = _fake_companion
    assert b._download_mtp(hf_repo = "unsloth/gemma-4-E4B-it-qat-mobile-GGUF") is None
    assert reached.get("hit") is True


def _dspark_download_probe(
    monkeypatch,
    *,
    supports_dspark,
    cached = None,
):
    """Run _download_dspark against a stubbed capability probe and an optionally
    cached sidecar; report whether the ~11 GB fetch (and even the repo listing)
    was reached."""
    from core.inference.llama_cpp import LlamaCppBackend
    import core.inference.llama_cpp as llama_cpp_module

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr(
        LlamaCppBackend,
        "probe_server_capabilities",
        classmethod(lambda cls, binary = None: {"supports_dspark": supports_dspark}),
    )
    monkeypatch.setattr(
        llama_cpp_module, "_companion_snapshot_sibling", lambda near_path, pick: cached
    )
    reached = {}

    def _fake_companion(
        *,
        hf_repo,
        hf_token,
        pick,
        label,
        cancel_event = None,
        near_path = None,
        outcome = None,
    ):
        reached["hit"] = True
        if outcome is not None:
            outcome["listed"] = True
        return "/cache/dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf"

    b = LlamaCppBackend()
    b._download_companion_gguf = _fake_companion
    got = b._download_dspark(
        hf_repo = "unsloth/DeepSeek-V4-Flash-0731-GGUF",
        near_path = "/cache/snap/DeepSeek-V4-Flash-0731-Q4_K_M.gguf",
        binary = "/fake/llama-server",
    )
    return got, reached.get("hit", False)


def test_download_dspark_skips_the_fetch_when_the_binary_cannot_run_it(monkeypatch):
    """The sidecar is ~11 GB; DSpark is dropped on any binary without --spec-type draft-dspark,
    known-broken prebuilts included, so check capability before download."""
    got, reached = _dspark_download_probe(monkeypatch, supports_dspark = False)
    assert got is None
    assert reached is False


def test_download_dspark_fetches_when_the_binary_supports_it(monkeypatch):
    got, reached = _dspark_download_probe(monkeypatch, supports_dspark = True)
    assert got == "/cache/dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf"
    assert reached is True


def test_download_dspark_records_whether_the_repo_publishes_a_sidecar(monkeypatch):
    """Failed fetches retry, a repo shipping no sidecar never does; the two None cases differ."""
    from core.inference.llama_cpp import LlamaCppBackend
    import core.inference.llama_cpp as llama_cpp_module

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr(
        LlamaCppBackend,
        "probe_server_capabilities",
        classmethod(lambda cls, binary = None: {"supports_dspark": True}),
    )
    monkeypatch.setattr(
        llama_cpp_module, "_companion_snapshot_sibling", lambda near_path, pick: None
    )

    def _companion(listed):
        def _fake(
            *,
            hf_repo,
            hf_token,
            pick,
            label,
            cancel_event = None,
            near_path = None,
            outcome = None,
        ):
            if outcome is not None:
                outcome["listed"] = listed
            return None

        return _fake

    for listed, expect_absent in ((False, True), (True, False)):
        b = LlamaCppBackend()
        b._download_companion_gguf = _companion(listed)
        assert b._download_dspark(hf_repo = "org/repo", binary = "/fake/llama-server") is None
        assert b._dspark_sidecar_absent is expect_absent


def test_an_unreachable_hub_is_not_recorded_as_a_missing_sidecar(monkeypatch, tmp_path):
    """A listing that never completed says nothing about the repo; recording it as absent would stop
    the reuse retry, so DSpark is never fetched after connectivity returns."""
    from core.inference.llama_cpp import LlamaCppBackend
    import core.inference.llama_cpp as llama_cpp_module

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr(
        llama_cpp_module, "_companion_snapshot_sibling", lambda near_path, pick: None
    )
    monkeypatch.setattr(llama_cpp_module, "_hub_download_in_flight", lambda repo: False)
    monkeypatch.setattr(
        llama_cpp_module, "_hub_cache_dir_for_snapshot_path", lambda p: str(tmp_path)
    )

    def _explode(repo, token = None):
        raise ConnectionError("hub unreachable")

    monkeypatch.setattr("huggingface_hub.list_repo_files", _explode)
    monkeypatch.setattr("utils.models.model_config._iter_hf_cache_snapshots", lambda *a, **k: [])

    outcome: dict = {}
    b = LlamaCppBackend()
    b._cancel_event.clear()
    assert (
        b._download_companion_gguf(
            hf_repo = "org/repo",
            hf_token = None,
            pick = lambda names: None,
            label = "DSpark drafter",
            outcome = outcome,
        )
        is None
    )
    assert "listed" not in outcome


def test_download_dspark_still_reports_a_cached_sidecar_it_cannot_run(monkeypatch):
    """Skipping the fetch must still report a cached sidecar, or Apply reloads the drafter-free server."""
    cached = "/cache/snap/dspark/dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf"
    got, reached = _dspark_download_probe(monkeypatch, supports_dspark = False, cached = cached)
    assert got == cached
    assert reached is False


@pytest.mark.parametrize("shape", ["dangling", "directory"])
def test_detect_dspark_file_skips_a_sidecar_it_cannot_open(tmp_path, shape):
    """A dangling symlink or directory named like a sidecar means no sidecar: the load would fail."""
    import os

    weight = tmp_path / "model-Q4_K_M.gguf"
    weight.write_bytes(b"target")
    sidecar = tmp_path / "dspark-model-Q8_0.gguf"
    if shape == "dangling":
        os.symlink(tmp_path / "missing_blob", sidecar)
    else:
        sidecar.mkdir()

    assert detect_dspark_file(str(weight)) is None
    mtp = tmp_path / "mtp-model.gguf"
    if shape == "dangling":
        os.symlink(tmp_path / "missing_blob", mtp)
    else:
        mtp.mkdir()
    assert detect_mtp_file(str(weight)) is None


@pytest.mark.parametrize("kind", ["dspark", "mtp"])
def test_a_release_specific_sidecar_outranks_the_base_family(tmp_path, kind):
    """Both prefix-match a 0731 weight, and only one is really its drafter. The
    prefix rule cannot be tightened to equality -- mtp-gemma-4-12B-it.gguf really
    does ship beside gemma-4-12B-it-qat-*.gguf -- so ranking settles it."""
    weight = tmp_path / "DeepSeek-V4-Flash-0731-UD-Q4_K_XL.gguf"
    weight.write_bytes(b"target")
    base = tmp_path / f"{kind}-DeepSeek-V4-Flash-Q8_0.gguf"
    exact = tmp_path / f"{kind}-DeepSeek-V4-Flash-0731-Q8_0.gguf"
    base.write_bytes(b"x" * 10)
    exact.write_bytes(b"x" * 4000)

    detect = detect_dspark_file if kind == "dspark" else detect_mtp_file
    found = detect(str(weight))
    assert found is not None and Path(found).name == exact.name


def test_root_mtp_candidates_are_ranked_not_taken_in_directory_order(tmp_path):
    """The root branch returns the first match it walks, so specificity has to be
    applied before the walk: mtp-model.gguf sorts ahead of mtp-model_v2-Q8_0.gguf
    yet only the second names this weight's family."""
    weight = tmp_path / "model_v2-Q4_K_M.gguf"
    weight.write_bytes(b"target")
    (tmp_path / "mtp-model.gguf").write_bytes(b"base")
    exact = tmp_path / "mtp-model_v2-Q8_0.gguf"
    exact.write_bytes(b"exact")

    found = detect_mtp_file(str(weight))
    assert found is not None and Path(found).name == exact.name


def test_root_mtp_ranking_spans_the_search_root(tmp_path):
    """Base in the model's folder, exact match in the search root: rank across both dirs."""
    home = tmp_path / "home"
    root = tmp_path / "root"
    home.mkdir()
    root.mkdir()
    weight = home / "model_v2-Q4_K_M.gguf"
    weight.write_bytes(b"target")
    (home / "mtp-model.gguf").write_bytes(b"base")
    exact = root / "mtp-model_v2-Q8_0.gguf"
    exact.write_bytes(b"exact")

    found = detect_mtp_file(str(weight), search_root = str(root))
    assert found is not None and Path(found).name == exact.name


def test_a_more_specific_subdir_drafter_beats_a_base_family_root_one(tmp_path):
    """Specificity is compared across layouts, not only within one: a root file naming another
    family is not this weight's drafter, so root preference cannot save it."""
    weight = tmp_path / "model_v2-Q4_K_M.gguf"
    weight.write_bytes(b"target")
    (tmp_path / "mtp-model.gguf").write_bytes(b"base")
    (tmp_path / "MTP").mkdir()
    exact = tmp_path / "MTP" / "mtp-model_v2-Q8_0.gguf"
    exact.write_bytes(b"exact")

    found = detect_mtp_file(str(weight))
    assert found is not None and Path(found).name == exact.name


def test_root_still_wins_when_both_layouts_name_the_same_family(tmp_path):
    """Negative control: at equal specificity, every published layout keeps root preference."""
    weight = tmp_path / "model-Q4_K_M.gguf"
    weight.write_bytes(b"target")
    root = tmp_path / "mtp-model.gguf"
    root.write_bytes(b"root")
    (tmp_path / "MTP").mkdir()
    (tmp_path / "MTP" / "model-Q8_0-MTP.gguf").write_bytes(b"sub")

    found = detect_mtp_file(str(weight))
    assert found is not None and Path(found).name == root.name


def test_an_unusable_candidate_does_not_win_the_tier_comparison(tmp_path):
    """Tier order follows specificity, so an unusable candidate must not win the tier comparison; it
    would hand back a less specific sibling."""
    import os

    weight = tmp_path / "model_v2_release-Q4_K_M.gguf"
    weight.write_bytes(b"target")
    os.symlink(tmp_path / "missing", tmp_path / "mtp-model_v2_release.gguf")
    (tmp_path / "mtp-model.gguf").write_bytes(b"base")
    (tmp_path / "MTP").mkdir()
    usable = tmp_path / "MTP" / "mtp-model_v2-Q8_0.gguf"
    usable.write_bytes(b"mid")

    found = detect_mtp_file(str(weight))
    assert found is not None and Path(found).name == usable.name


def test_a_rejected_candidate_does_not_win_the_tier_comparison(tmp_path):
    """A grant-rejected candidate must not claim its tier, or a base-family sibling goes out first."""
    weight = tmp_path / "model_v2_release-Q4_K_M.gguf"
    weight.write_bytes(b"target")
    rejected = tmp_path / "mtp-model_v2_release.gguf"
    rejected.write_bytes(b"out-of-grant")
    (tmp_path / "mtp-model.gguf").write_bytes(b"base")
    (tmp_path / "MTP").mkdir()
    accepted = tmp_path / "MTP" / "mtp-model_v2-Q8_0.gguf"
    accepted.write_bytes(b"mid")

    found = detect_mtp_file(str(weight), accept = lambda candidate: rejected.name not in candidate)
    assert found is not None and Path(found).name == accepted.name


def test_a_qat_weight_still_pairs_with_its_base_family_drafter(tmp_path):
    """Negative control for the ranking above: unsloth/gemma-4-12B-it-qat-GGUF
    ships mtp-gemma-4-12B-it.gguf, so the prefix rule has to keep working when no
    more specific sidecar exists."""
    weight = tmp_path / "gemma-4-12B-it-qat-UD-Q4_K_XL.gguf"
    weight.write_bytes(b"target")
    drafter = tmp_path / "mtp-gemma-4-12B-it.gguf"
    drafter.write_bytes(b"draft")

    found = detect_mtp_file(str(weight))
    assert found is not None and Path(found).name == drafter.name


def test_detect_mtp_file_returns_first_shard_of_split_subdir_drafter(tmp_path):
    """Split MTP/ drafter resolves to shard 1, the path llama-server takes, not the smallest."""
    weight = tmp_path / "model-Q4_0.gguf"
    weight.write_bytes(b"x")
    sub = tmp_path / "MTP"
    sub.mkdir()
    first = sub / "mtp-model-Q4_0-00001-of-00002.gguf"
    first.write_bytes(b"x" * 4096)
    (sub / "mtp-model-Q4_0-00002-of-00002.gguf").write_bytes(b"x")

    assert detect_mtp_file(str(weight)) == str(first.resolve())


def test_detect_mtp_file_skip_root_ignores_root_drafter(tmp_path):
    """skip_root is the native load's recovery when the root drafter exceeds its grant."""
    quant_dir = tmp_path / "Q4_0"
    quant_dir.mkdir()
    weight = quant_dir / "model.gguf"
    weight.write_bytes(b"x")
    (tmp_path / "mtp-model.gguf").write_bytes(b"x")
    sub = tmp_path / "MTP"
    sub.mkdir()
    subdir_copy = sub / "mtp-model-Q4_0.gguf"
    subdir_copy.write_bytes(b"x")

    assert detect_mtp_file(str(weight), str(tmp_path)) == str(
        (tmp_path / "mtp-model.gguf").resolve()
    )
    assert detect_mtp_file(str(weight), str(tmp_path), skip_root = True) == str(subdir_copy.resolve())


def test_detect_mtp_file_rejects_weight_copy_inside_mtp_dir(tmp_path):
    """MTP/ contents are hidden from menus; only a published name may launch as --model-draft."""
    weight = tmp_path / "gemma-4-E4B-it-qat-Q4_0.gguf"
    weight.write_bytes(b"x")
    sub = tmp_path / "MTP"
    sub.mkdir()
    (sub / "gemma-4-E4B-it-qat-Q4_0.gguf").write_bytes(b"x")

    assert detect_mtp_file(str(weight)) is None


def test_detect_mtp_file_pairs_k_quant_subdir_drafter(tmp_path):
    """Pairing must use the full quant vocabulary, not just Q<d>_<d>/BF16/F16."""
    weight = tmp_path / "gemma-4-12b-it-Q4_0.gguf"
    weight.write_bytes(b"x")
    sub = tmp_path / "MTP"
    sub.mkdir()
    drafter = sub / "mtp-gemma-4-12b-it-UD-Q4_K_XL.gguf"
    drafter.write_bytes(b"x")

    assert detect_mtp_file(str(weight)) == str(drafter.resolve())


def test_detect_mtp_file_keeps_snapshot_path_for_sharded_subdir_drafter(tmp_path):
    """Split symlinked copies launch from the snapshot path; blob targets lack sibling shards."""
    blobs = tmp_path / "blobs"
    snapshot = tmp_path / "snapshots" / "abc"
    sub = snapshot / "MTP"
    blobs.mkdir(parents = True)
    sub.mkdir(parents = True)

    (blobs / "sha_weight").write_bytes(b"w")
    weight = snapshot / "model-Q4_0.gguf"
    try:
        weight.symlink_to(blobs / "sha_weight")
    except OSError:
        pytest.skip("symlinks unavailable")

    first = sub / "mtp-model-Q4_0-00001-of-00002.gguf"
    second = sub / "mtp-model-Q4_0-00002-of-00002.gguf"
    (blobs / "sha_1").write_bytes(b"d" * 4096)
    (blobs / "sha_2").write_bytes(b"d")
    first.symlink_to(blobs / "sha_1")
    second.symlink_to(blobs / "sha_2")

    found = detect_mtp_file(str(weight), str(snapshot))
    assert found == str(first)
    assert (Path(found).parent / second.name).exists()


def test_detect_mtp_file_pairs_sharded_old_scheme_subdir_drafter(tmp_path):
    """Old-scheme split shards end in -mtp only once the shard suffix comes off the stem."""
    weight = tmp_path / "model-Q4_0.gguf"
    weight.write_bytes(b"x")
    sub = tmp_path / "MTP"
    sub.mkdir()
    first = sub / "model-Q8_0-MTP-00001-of-00002.gguf"
    first.write_bytes(b"x" * 4096)
    (sub / "model-Q8_0-MTP-00002-of-00002.gguf").write_bytes(b"x")

    assert detect_mtp_file(str(weight)) == str(first)


def test_detect_mtp_file_keeps_snapshot_path_for_sharded_root_drafter(tmp_path):
    """The root branch needs the same shard handling as the MTP/ branch."""
    blobs = tmp_path / "blobs"
    snapshot = tmp_path / "snapshots" / "abc"
    blobs.mkdir(parents = True)
    snapshot.mkdir(parents = True)

    (blobs / "sha_weight").write_bytes(b"w")
    weight = snapshot / "model-Q4_0.gguf"
    try:
        weight.symlink_to(blobs / "sha_weight")
    except OSError:
        pytest.skip("symlinks unavailable")

    first = snapshot / "mtp-model-Q4_0-00001-of-00002.gguf"
    second = snapshot / "mtp-model-Q4_0-00002-of-00002.gguf"
    (blobs / "sha_1").write_bytes(b"d" * 4096)
    (blobs / "sha_2").write_bytes(b"d")
    first.symlink_to(blobs / "sha_1")
    second.symlink_to(blobs / "sha_2")

    found = detect_mtp_file(str(weight), str(snapshot))
    assert found == str(first)
    assert (Path(found).parent / second.name).exists()


def test_detect_mtp_file_pairs_bpw_qualified_subdir_drafter(tmp_path):
    """_extract_quant_label supports bpw-qualified names, so pairing must too."""
    weight = tmp_path / "model-Q4_0.gguf"
    weight.write_bytes(b"x")
    sub = tmp_path / "MTP"
    sub.mkdir()
    drafter = sub / "mtp-model-IQ4_XS-3.53bpw.gguf"
    drafter.write_bytes(b"x")

    assert detect_mtp_file(str(weight)) == str(drafter.resolve())


def test_detect_mtp_file_skips_incomplete_split_drafter(tmp_path):
    """Incomplete shard sets fail draft startup; a complete copy must win over disabling MTP."""
    weight = tmp_path / "model-Q4_0.gguf"
    weight.write_bytes(b"x")
    sub = tmp_path / "MTP"
    sub.mkdir()
    (sub / "mtp-model-Q4_0-00001-of-00002.gguf").write_bytes(b"x" * 50)
    complete = sub / "mtp-model-BF16.gguf"
    complete.write_bytes(b"x" * 100)

    assert detect_mtp_file(str(weight)) == str(complete.resolve())


def test_detect_mtp_file_ranks_split_drafter_by_total_size(tmp_path):
    """Split copies are summed (candidates collapse to shard 1); precision outranks size."""
    weight = tmp_path / "model-Q4_0.gguf"
    weight.write_bytes(b"x")
    sub = tmp_path / "MTP"
    sub.mkdir()
    (sub / "mtp-model-Q8_0-00001-of-00002.gguf").write_bytes(b"x" * 90)
    (sub / "mtp-model-Q8_0-00002-of-00002.gguf").write_bytes(b"x" * 90)
    smaller = sub / "mtp-model-Q8_0.gguf"
    smaller.write_bytes(b"x" * 100)

    assert detect_mtp_file(str(weight)) == str(smaller.resolve())


def test_companion_search_root_promotes_bpw_quant_directory(tmp_path):
    """bpw-qualified quant dirs resolve to the repo root, so its MTP/ copy stays in scope."""
    quant_dir = tmp_path / "IQ4_XS-3.53bpw"
    quant_dir.mkdir()
    weight = quant_dir / "model.gguf"
    weight.write_bytes(b"x")
    sub = tmp_path / "MTP"
    sub.mkdir()
    drafter = sub / "mtp-model.gguf"
    drafter.write_bytes(b"x")

    assert _local_gguf_companion_search_root(str(quant_dir), str(weight)) == str(tmp_path)
    assert _local_gguf_companion_search_root(str(weight), str(weight)) == str(tmp_path)
    assert detect_mtp_file(str(weight), str(tmp_path)) == str(drafter.resolve())


def test_companion_search_root_keeps_non_quant_directories(tmp_path):
    """Sharing the quant vocabulary must not widen what gets promoted."""
    for name in ("DeepSeek-V3-UD-Q2_K_XL", "outputs", "Q4_0-extra", "Q4_0bpw"):
        directory = tmp_path / name
        directory.mkdir()
        weight = directory / "model.gguf"
        weight.write_bytes(b"x")
        assert _local_gguf_companion_search_root(str(directory), str(weight)) == str(directory)


DEEPSEEK_SIBLINGS = [
    _sib("UD-Q4_K_XL/DeepSeek-V4-Flash-0731-UD-Q4_K_XL-00001-of-00002.gguf", 9_000, "q4-1"),
    _sib("UD-Q4_K_XL/DeepSeek-V4-Flash-0731-UD-Q4_K_XL-00002-of-00002.gguf", 8_000, "q4-2"),
    _sib("UD-IQ1_S/DeepSeek-V4-Flash-0731-UD-IQ1_S-00001-of-00002.gguf", 5_000, "iq1-1"),
    _sib("dspark/dspark-DeepSeek-V4-Flash-0731-BF16.gguf", 1_100, "dspark-bf16"),
    _sib("dspark/dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf", 1_000, "dspark-q8"),
]


def test_dspark_drafters_are_not_quants_and_are_not_auto_fetched():
    plans = build_gguf_variant_plans(DEEPSEEK_SIBLINGS)

    assert set(plans) == {"ud-q4_k_xl", "ud-iq1_s"}

    # DSpark is opt-in and ~11 GB per file, so it is not folded into every plan.
    for plan in plans.values():
        assert not any(name.startswith("dspark/") for name in plan.target_filenames)
        assert plan.companion_hashes == frozenset()

    q4 = plans["ud-q4_k_xl"]
    assert q4.main_size_bytes == 17_000
    assert q4.download_size_bytes == 17_000


def test_a_root_dflash_drafter_is_not_a_quant():
    """A root dflash- drafter is not a quant; merged, llama.cpp would load it as the model."""
    plans = build_gguf_variant_plans(
        [
            _sib("Qwen3.6-27B-BF16.gguf", 54_000, "bf16"),
            _sib("dflash-Qwen3.6-27B-BF16.gguf", 3_000, "dflash"),
        ]
    )
    assert set(plans) == {"bf16"}
    assert plans["bf16"].main_filenames == frozenset({"Qwen3.6-27B-BF16.gguf"})
    assert plans["bf16"].main_size_bytes == 54_000


def test_gemma_mtp_is_still_auto_downloaded():
    """Filtering only prunes quants; the root MTP drafter still downloads with each variant."""
    plans = build_gguf_variant_plans(GEMMA_SIBLINGS)
    for plan in plans.values():
        assert "mtp-gemma-4-12b-it.gguf" in plan.target_filenames


def test_a_cached_dspark_drafter_is_never_launched_as_an_mtp_drafter(tmp_path, monkeypatch):
    """_cached_repo_mtp_drafter uses the predicate inversely to pick a --spec-type draft-mtp
    drafter; DSpark needs draft-dspark, so broadening it must not widen launches."""
    import core.inference.llama_cpp as llama_cpp_module

    def _snapshot(files):
        snap = tmp_path / f"snap{len(list(tmp_path.iterdir()))}"
        for rel in files:
            path = snap / rel
            path.parent.mkdir(parents = True, exist_ok = True)
            path.write_bytes(b"x")
        return snap

    dspark_only = _snapshot(["dspark/dspark-model-Q8_0.gguf", "model-Q4_K_M.gguf"])
    with_mtp = _snapshot(["mtp-model.gguf", "model-Q4_K_M.gguf"])

    backend = llama_cpp_module.LlamaCppBackend.__new__(llama_cpp_module.LlamaCppBackend)
    snapshots: list[Path] = []
    monkeypatch.setattr(
        "utils.models.model_config._iter_hf_cache_snapshots",
        lambda *a, **k: list(snapshots),
    )

    snapshots[:] = [dspark_only]
    assert backend._cached_repo_mtp_drafter("some/repo") is None

    snapshots[:] = [with_mtp, dspark_only]
    found = backend._cached_repo_mtp_drafter("some/repo")
    assert found is not None and found.endswith("mtp-model.gguf")


def test_cached_mtp_lookup_ranks_nested_copies_like_the_download(tmp_path, monkeypatch):
    """Offline reuse must pick the same head as the online picker, preferring the self-contained one."""
    import core.inference.llama_cpp as llama_cpp_module

    published = [
        f"MTP/mtp-Qwen3.8-Flash-Next-{tier}.gguf"
        for tier in ("BF16", "Q4_K_M", "Q8_0", "shared-BF16", "shared-Q4_K_M", "shared-Q8_0")
    ]
    snap = tmp_path / "snap"
    for rel in [*published, "UD-IQ1_S/model.gguf"]:
        (snap / rel).parent.mkdir(parents = True, exist_ok = True)
        (snap / rel).write_bytes(b"x")

    monkeypatch.setattr(
        "utils.models.model_config._iter_hf_cache_snapshots", lambda *a, **k: [snap]
    )
    backend = llama_cpp_module.LlamaCppBackend.__new__(llama_cpp_module.LlamaCppBackend)

    found = backend._cached_repo_mtp_drafter("unsloth/Qwen3.8-Flash-Next-GGUF")
    assert found is not None
    assert Path(found).name == "mtp-Qwen3.8-Flash-Next-Q8_0.gguf", (
        f"offline reuse picked {Path(found).name}; the online picker takes "
        f"{llama_cpp_module._pick_mtp(published)}"
    )
    assert Path(found).name == Path(llama_cpp_module._pick_mtp(published)).name


def test_cached_mtp_lookup_rejects_non_drafters_parked_under_mtp(tmp_path, monkeypatch):
    """MTP/ contents are drafters: right to hide companions, wrong to pick a launch file."""
    import core.inference.llama_cpp as llama_cpp_module

    snap = tmp_path / "snap"
    for rel in ("MTP/mmproj-BF16.gguf", "MTP/imatrix_unsloth.gguf", "model-Q4_K_M.gguf"):
        (snap / rel).parent.mkdir(parents = True, exist_ok = True)
        (snap / rel).write_bytes(b"x")

    monkeypatch.setattr(
        "utils.models.model_config._iter_hf_cache_snapshots", lambda *a, **k: [snap]
    )
    backend = llama_cpp_module.LlamaCppBackend.__new__(llama_cpp_module.LlamaCppBackend)
    assert backend._cached_repo_mtp_drafter("some/repo") is None


def test_local_scan_prefers_the_fit_measurable_head_over_the_smaller_shared_one(tmp_path):
    root = tmp_path / "local"
    (root / "MTP").mkdir(parents = True)
    for i in (1, 2, 3):
        (root / f"Qwen3.8-Flash-Next-UD-IQ1_S-0000{i}-of-00003.gguf").write_bytes(b"x" * 64)
    (root / "MTP" / "mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf").write_bytes(b"x" * 64)
    (root / "MTP" / "mtp-Qwen3.8-Flash-Next-Q8_0.gguf").write_bytes(b"x" * 128)
    found = detect_mtp_file(
        str(root / "Qwen3.8-Flash-Next-UD-IQ1_S-00001-of-00003.gguf"), search_root = str(root)
    )
    assert found is not None and Path(found).name == "mtp-Qwen3.8-Flash-Next-Q8_0.gguf"


def test_local_scan_keeps_precision_above_the_borrow_tiebreak(tmp_path):
    root = tmp_path / "local"
    (root / "MTP").mkdir(parents = True)
    for i in (1, 2, 3):
        (root / f"Qwen3.8-Flash-Next-UD-IQ1_S-0000{i}-of-00003.gguf").write_bytes(b"x" * 64)
    (root / "MTP" / "mtp-Qwen3.8-Flash-Next-BF16.gguf").write_bytes(b"x" * 512)
    (root / "MTP" / "mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf").write_bytes(b"x" * 64)
    found = detect_mtp_file(
        str(root / "Qwen3.8-Flash-Next-UD-IQ1_S-00001-of-00003.gguf"), search_root = str(root)
    )
    assert found is not None and Path(found).name == "mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"


def test_a_shared_head_pairs_with_its_target_in_the_local_scan(tmp_path):
    """The -shared tag marks the head's form, not its family, so it must still pair with its target."""
    from utils.models.drafters.common import _drafter_matches_weight, _drafter_pairing_stem
    from utils.models.model_config import detect_mtp_file

    weight = "qwen3.8-flash-next-ud-iq1_s-00001-of-00003.gguf"
    for tier in ("Q8_0", "BF16", "Q4_K_M"):
        name = f"mtp-Qwen3.8-Flash-Next-shared-{tier}.gguf"
        assert _drafter_pairing_stem(name, kind = "mtp") == "qwen3.8-flash-next"
        assert _drafter_matches_weight(name, weight, kind = "mtp"), name
    assert not _drafter_matches_weight("mtp-Some-Other-shared-Q8_0.gguf", weight, kind = "mtp")
    assert _drafter_pairing_stem("dspark-Model-shared-Q8_0.gguf", kind = "dspark") == "model-shared"

    root = tmp_path / "local"
    (root / "MTP").mkdir(parents = True)
    for i in (1, 2, 3):
        (root / f"Qwen3.8-Flash-Next-UD-IQ1_S-0000{i}-of-00003.gguf").write_bytes(b"x" * 64)
    shared = root / "MTP" / "mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf"
    shared.write_bytes(b"x" * 64)
    found = detect_mtp_file(
        str(root / "Qwen3.8-Flash-Next-UD-IQ1_S-00001-of-00003.gguf"), search_root = str(root)
    )
    assert found is not None and Path(found).name == shared.name


def test_cached_dspark_lookup_prefers_q8_and_excludes_dflash(tmp_path, monkeypatch):
    import core.inference.llama_cpp as llama_cpp_module

    snap = tmp_path / "snapshot"
    for rel in (
        "dspark/dspark-model-BF16.gguf",
        "dspark/dspark-model-Q8_0.gguf",
        "dflash-model-Q8_0.gguf",
    ):
        path = snap / rel
        path.parent.mkdir(parents = True, exist_ok = True)
        path.write_bytes(b"x")
    monkeypatch.setattr(
        "utils.models.model_config._iter_hf_cache_snapshots",
        lambda *a, **k: [snap],
    )
    backend = llama_cpp_module.LlamaCppBackend.__new__(llama_cpp_module.LlamaCppBackend)

    # as_posix(): the lookup returns OS-native paths (backslashes on Windows).
    assert (
        Path(backend._cached_repo_dspark_drafter("some/repo"))
        .as_posix()
        .endswith("dspark/dspark-model-Q8_0.gguf")
    )


def _cache_repo(tmp_path: Path, repo_id: str, names: list[str]):
    """An HF cache repo: snapshot symlinks pointing at blobs."""
    repo_dir = tmp_path / f"models--{repo_id.replace('/', '--')}"
    snap = repo_dir / "snapshots" / "rev1"
    blobs = repo_dir / "blobs"
    snap.mkdir(parents = True)
    blobs.mkdir(parents = True)
    files = []
    for index, name in enumerate(names):
        blob = blobs / f"sha{index}"
        blob.write_bytes(b"x" * 64)
        link = snap / name
        link.parent.mkdir(parents = True, exist_ok = True)
        link.symlink_to(blob)
        files.append(
            SimpleNamespace(
                file_name = Path(name).name,
                file_path = str(link),
                blob_path = str(blob),
                size_on_disk = 64,
            )
        )
    return SimpleNamespace(
        repo_id = repo_id,
        repo_type = "model",
        repo_path = repo_dir,
        revisions = [SimpleNamespace(files = files, snapshot_path = str(snap))],
    ), snap


def test_deleting_one_of_several_variants_keeps_the_dspark_drafter(tmp_path):
    """A sibling quant still uses it, so only the last variant may reclaim it."""
    from hub.services.models.deletion import _delete_gguf_variant_from_repos

    repo, snap = _cache_repo(
        tmp_path,
        "unsloth/DeepSeek-V4-Flash-0731-GGUF",
        [
            "model-Q4_K_M.gguf",
            "model-Q8_0.gguf",
            "dspark/dspark-DeepSeek-V4-Flash-0731-BF16.gguf",
        ],
    )
    _delete_gguf_variant_from_repos(
        "unsloth/DeepSeek-V4-Flash-0731-GGUF", "Q4_K_M", [repo], None, root = tmp_path
    )

    assert not (snap / "model-Q4_K_M.gguf").is_symlink()
    assert (snap / "dspark" / "dspark-DeepSeek-V4-Flash-0731-BF16.gguf").is_symlink()


def test_deleting_the_last_variant_reclaims_an_opt_in_dspark_drafter(tmp_path):
    """Unsloth downloads the sidecar on opt-in and companion filtering hides it from menus, so
    deleting the last variant must reclaim its ~11 GB, as nothing can launch it."""
    from hub.services.models.deletion import _delete_gguf_variant_from_repos

    repo, snap = _cache_repo(
        tmp_path,
        "unsloth/DeepSeek-V4-Flash-0731-GGUF",
        ["model-Q4_K_M.gguf", "dspark/dspark-DeepSeek-V4-Flash-0731-BF16.gguf"],
    )
    _delete_gguf_variant_from_repos(
        "unsloth/DeepSeek-V4-Flash-0731-GGUF", "Q4_K_M", [repo], None, root = tmp_path
    )

    assert not (snap / "model-Q4_K_M.gguf").is_symlink()
    assert not (snap / "dspark" / "dspark-DeepSeek-V4-Flash-0731-BF16.gguf").is_symlink()


def test_a_suffix_scheme_sidecar_is_not_mistaken_for_a_quant(tmp_path):
    """A -dspark suffix sidecar has no drafter marker in its basename, so it reads as a real quant."""
    from hub.services.models.deletion import _delete_gguf_variant_from_repos

    repo, snap = _cache_repo(
        tmp_path,
        "unsloth/DeepSeek-V4-Flash-0731-GGUF",
        [
            "model-Q4_K_M.gguf",
            "model-Q8_0.gguf",
            "dspark/DeepSeek-V4-Flash-0731-Q8_0-dspark.gguf",
        ],
    )
    _delete_gguf_variant_from_repos(
        "unsloth/DeepSeek-V4-Flash-0731-GGUF", "Q8_0", [repo], None, root = tmp_path
    )

    assert not (snap / "model-Q8_0.gguf").is_symlink()
    assert (snap / "model-Q4_K_M.gguf").is_symlink()
    assert (snap / "dspark" / "DeepSeek-V4-Flash-0731-Q8_0-dspark.gguf").is_symlink()

    _delete_gguf_variant_from_repos(
        "unsloth/DeepSeek-V4-Flash-0731-GGUF", "Q4_K_M", [repo], None, root = tmp_path
    )
    assert not (snap / "dspark" / "DeepSeek-V4-Flash-0731-Q8_0-dspark.gguf").is_symlink()


def test_deleting_the_last_variant_keeps_a_dflash_weight(tmp_path):
    """Negative control: dflash is a family name for real weights, never a companion, so kept."""
    from hub.services.models.deletion import _delete_gguf_variant_from_repos

    repo, snap = _cache_repo(
        tmp_path, "org/Model-GGUF", ["model-Q4_K_M.gguf", "dflash-model-Q8_0.gguf"]
    )
    _delete_gguf_variant_from_repos("org/Model-GGUF", "Q4_K_M", [repo], None, root = tmp_path)

    assert not (snap / "model-Q4_K_M.gguf").is_symlink()
    assert (snap / "dflash-model-Q8_0.gguf").is_symlink()


def test_deleting_the_last_variant_still_reclaims_mtp_and_mmproj(tmp_path):
    """Positive control: those ARE fetched with every variant, so they still go."""
    from hub.services.models.deletion import _delete_gguf_variant_from_repos

    repo, snap = _cache_repo(
        tmp_path, "org/Model-GGUF", ["model-Q4_K_M.gguf", "mtp-model.gguf", "mmproj-F16.gguf"]
    )
    _delete_gguf_variant_from_repos("org/Model-GGUF", "Q4_K_M", [repo], None, root = tmp_path)

    assert not (snap / "model-Q4_K_M.gguf").is_symlink()
    assert not (snap / "mtp-model.gguf").is_symlink()
    assert not (snap / "mmproj-F16.gguf").is_symlink()


# DFlash is on under Auto (~1.5 GiB sidecar) and its filename names no family,
# so discovery confirms general.architecture instead of the filename.


DFLASH_PREDICATE_CASES = [
    ("dflash-kquant.gguf", True),
    ("dflash-Qwen3.6-27B-BF16.gguf", True),
    ("dflash-draft-3.6-q8_0.gguf", True),
    ("DFLASH-Qwen3.6-27B-Q8_0.gguf", True),
    ("Qwen3.6-35B-A3B-DFlash-Q4_K_M.gguf", False),
    ("qwen35-4b-dflash-Q8_0.gguf", False),
    ("laguna-s-2.1-dflash-Q4_K_M.gguf", False),
    ("dflash/Qwen3.6-35B-A3B-DFlash-Q4_K_M.gguf", False),
    ("foo/dflash/bar.gguf", False),
    ("dspark-DeepSeek-V4-Flash-0731-Q8_0.gguf", False),
    ("mtp-gemma-4-12b-it.gguf", False),
    ("dflash-notes.txt", False),
]


@pytest.mark.parametrize("path,expected", DFLASH_PREDICATE_CASES)
def test_is_dflash_drafter_path(path, expected):
    from core.inference.llama_cpp import (
        _is_dflash_drafter_path,
        _is_dspark_drafter_path,
        _is_mtp_only_drafter_path,
    )
    assert _is_dflash_drafter_path(path) is expected
    if expected:
        assert _is_dspark_drafter_path(path) is False
        assert _is_mtp_only_drafter_path(path) is False


@pytest.mark.parametrize(
    "value,expected",
    [
        ("dflash", "dflash"),
        ("DFlash", "dflash"),
        ("  dflash ", "dflash"),
        ("draft-dflash", "dflash"),
        ("DRAFT-DFLASH", "dflash"),
    ],
)
def test_canonicalize_spec_mode_accepts_dflash(value, expected):
    from core.inference.llama_cpp import _canonicalize_spec_mode
    assert _canonicalize_spec_mode(value) == expected


_NEEDS_BASH = pytest.mark.skipif(
    sys.platform == "win32",
    reason = "fake llama-server is a bash stub; Windows has no direct executor",
)


def _fake_llama_server(path: Path, help_text: str) -> Path:
    path.write_text(f"#!/usr/bin/env bash\ncat <<'EOF'\n{help_text}\nEOF\n")
    path.chmod(0o755)
    return path


@_NEEDS_BASH
@pytest.mark.parametrize(
    "spec_line,expected",
    [
        ("--spec-type none,draft-mtp,draft-dflash,draft-dspark,ngram-mod", True),
        ("--spec-type none,draft-mtp,draft-dspark,ngram-mod", False),
        ("--spec-type none,draft-dflash2,ngram-mod", False),
        ("--spec-type none,xdraft-dflash,ngram-mod", False),
    ],
)
def test_probe_server_capabilities_reports_dflash(tmp_path, spec_line, expected):
    from core.inference.llama_cpp import LlamaCppBackend

    fake = _fake_llama_server(tmp_path / "llama-server", spec_line)
    LlamaCppBackend._capability_cache.clear()
    caps = LlamaCppBackend.probe_server_capabilities(str(fake))
    assert caps["supports_dflash"] is expected
    assert caps["supports_dspark"] is ("draft-dspark" in spec_line)


def test_missing_binary_reports_no_dflash():
    """The not-found dict returns before parsing, so it must carry the key: .get() callers read
    absent as False only by luck; _estimate_gguf_required_gb default-denies on it."""
    from core.inference.llama_cpp import LlamaCppBackend

    caps = LlamaCppBackend.probe_server_capabilities("/nonexistent/llama-server")
    assert caps["found"] is False
    assert caps["supports_dflash"] is False


def _spec_backend(
    monkeypatch,
    *,
    supports_dflash = True,
    supports_dspark = True,
):
    from core.inference.llama_cpp import LlamaCppBackend

    caps = {
        "found": True,
        "mtp_token": "draft-mtp",
        "supports_mtp": True,
        "supports_dspark": supports_dspark,
        "supports_dflash": supports_dflash,
        "mtp_probe_inconclusive": False,
        "ngram_mod_flavor": "new",
        "supports_ngram_mod": True,
        "spec_draft_n_max_flag": "--spec-draft-n-max",
    }
    monkeypatch.setattr(
        LlamaCppBackend,
        "probe_server_capabilities",
        classmethod(lambda cls, binary = None: caps),
    )
    backend = LlamaCppBackend()
    backend._nextn_predict_layers = None
    return backend


def _spec_flags(backend, **kwargs):
    base = dict(
        speculative_type = None,
        spec_draft_n_max = None,
        extra_args = None,
        model_identifier = "unsloth/Muse-Glimmer-30B-GGUF",
        model_path = None,
        gpus = True,
        binary = "/fake/llama-server",
    )
    base.update(kwargs)
    return backend._build_speculative_flags(**base)


def test_auto_launches_dflash_when_a_sidecar_is_present(monkeypatch):
    """Unlike DSpark, DFlash is launched with no opt-in when its sidecar is present."""
    backend = _spec_backend(monkeypatch)
    flags = _spec_flags(backend, speculative_type = "auto", dflash_draft_path = "/m/dflash-kquant.gguf")

    assert flags == [
        "--model-draft",
        "/m/dflash-kquant.gguf",
        "--spec-type",
        "draft-dflash",
        "--spec-draft-n-max",
        "2",
    ]
    assert backend._speculative_type == "draft-dflash"
    assert backend._spec_drafter_kind == "dflash"
    assert backend._spec_fallback_reason is None


def test_auto_uses_the_cpu_draft_depth_off_gpu(monkeypatch):
    backend = _spec_backend(monkeypatch)
    flags = _spec_flags(backend, speculative_type = "auto", dflash_draft_path = "/m/d.gguf", gpus = False)
    assert flags[-2:] == ["--spec-draft-n-max", "3"]


def test_a_user_draft_depth_override_reaches_dflash(monkeypatch):
    backend = _spec_backend(monkeypatch)
    flags = _spec_flags(
        backend, speculative_type = "dflash", dflash_draft_path = "/m/d.gguf", spec_draft_n_max = 6
    )
    assert flags[-2:] == ["--spec-draft-n-max", "6"]
    assert backend._spec_draft_n_max == 6


def test_auto_does_not_emit_dflash_when_the_binary_cannot_run_it(monkeypatch):
    """An unknown --spec-type aborts launch, and published prebuilts predate the arch."""
    backend = _spec_backend(monkeypatch, supports_dflash = False)
    flags = _spec_flags(backend, speculative_type = "auto", dflash_draft_path = "/m/dflash-kquant.gguf")

    assert "draft-dflash" not in flags
    assert "--model-draft" not in flags
    assert flags == ["--spec-default"]
    assert backend._speculative_type == "default"


def test_forced_dflash_without_the_capability_falls_back(monkeypatch):
    backend = _spec_backend(monkeypatch, supports_dflash = False)
    flags = _spec_flags(backend, speculative_type = "dflash", dflash_draft_path = "/m/d.gguf")

    assert flags == ["--spec-default"]
    assert backend._speculative_type == "default"
    assert backend._spec_fallback_reason == "binary_no_mtp"


def test_forced_dflash_without_a_sidecar_falls_back(monkeypatch):
    backend = _spec_backend(monkeypatch)
    flags = _spec_flags(backend, speculative_type = "dflash", dflash_draft_path = None)

    assert flags == ["--spec-default"]
    assert backend._spec_fallback_reason == "drafter_not_found"
    assert backend._spec_drafter_kind == "dflash"


def test_a_dropped_unloadable_drafter_reports_its_own_reason(monkeypatch):
    """A present but unopenable drafter must not say drafter_not_found; local loads would re-place it."""
    backend = _spec_backend(monkeypatch)
    flags = _spec_flags(
        backend,
        model_identifier = "unsloth/gemma-4-12b-it-GGUF",
        speculative_type = "mtp",
        mtp_draft_path = None,
        mtp_drafter_unloadable = True,
    )

    assert backend._spec_fallback_reason == "drafter_unloadable"
    assert "--model-draft" not in flags


@pytest.mark.parametrize("mode", ["auto", "mtp"])
def test_a_dropped_sidecar_is_explained_on_a_non_gemma_quant(monkeypatch, mode):
    """A non-Gemma quant's sidecar is its only MTP signal; dropping it turned MTP off with no reason."""
    backend = _spec_backend(monkeypatch)
    flags = _spec_flags(
        backend,
        model_identifier = "0bserverx/Qwen3.8-27B-Heretic-Abliterated-Uncensored-GGUF",
        speculative_type = mode,
        mtp_draft_path = None,
        mtp_drafter_unloadable = True,
    )

    assert backend._spec_fallback_reason == "drafter_unloadable"
    assert "--model-draft" not in flags
    assert "draft-mtp" not in flags


def test_a_plain_quant_with_no_sidecar_at_all_is_untouched(monkeypatch):
    """The negative: keeping the dropped sidecar as a signal must not invent MTP for a
    model that never had any. Nothing was dropped here, so nothing is explained."""
    backend = _spec_backend(monkeypatch)
    _spec_flags(
        backend,
        model_identifier = "0bserverx/Qwen3.8-27B-Heretic-Abliterated-Uncensored-GGUF",
        speculative_type = "auto",
        mtp_draft_path = None,
    )

    assert backend._spec_fallback_reason is None


def test_a_genuinely_absent_drafter_still_reports_not_found(monkeypatch):
    """The negative: the new reason must not swallow the case it was split out of."""
    backend = _spec_backend(monkeypatch)
    _spec_flags(
        backend,
        model_identifier = "unsloth/gemma-4-12b-it-GGUF",
        speculative_type = "mtp",
        mtp_draft_path = None,
    )

    assert backend._spec_fallback_reason == "drafter_not_found"


def test_dspark_keeps_first_refusal_when_a_repo_ships_both(monkeypatch):
    """Mirrors llama.cpp's downloader, which ranks dspark ahead of dflash; a repo ships one kind or
    neither, and this pins that adding DFlash did not change DSpark's first refusal."""
    backend = _spec_backend(monkeypatch)
    flags = _spec_flags(
        backend,
        speculative_type = "auto",
        dspark_draft_path = "/m/dspark-x-Q8_0.gguf",
        dflash_draft_path = "/m/dflash-kquant.gguf",
    )
    assert "draft-dspark" in flags
    assert "draft-dflash" not in flags
    assert backend._spec_drafter_kind == "dspark"


def test_dspark_emission_is_unchanged(monkeypatch):
    """Regression guard on the behaviour this PR must not touch."""
    backend = _spec_backend(monkeypatch)
    flags = _spec_flags(
        backend, speculative_type = "dspark", dspark_draft_path = "/m/dspark-x-Q8_0.gguf"
    )
    assert flags == [
        "--model-draft",
        "/m/dspark-x-Q8_0.gguf",
        "--spec-type",
        "draft-dspark",
        "--spec-draft-n-max",
        "3",
    ]
    assert backend._speculative_type == "draft-dspark"


def test_a_dflash_sidecar_alone_does_not_change_the_mtp_or_off_paths(monkeypatch):
    """Forced modes stay forced: a sidecar sitting on disk must not promote."""
    backend = _spec_backend(monkeypatch)
    assert _spec_flags(backend, speculative_type = "off", dflash_draft_path = "/m/d.gguf") == []
    flags = _spec_flags(backend, speculative_type = "ngram", dflash_draft_path = "/m/d.gguf")
    assert "draft-dflash" not in flags
    assert flags[:2] == ["--spec-type", "ngram-mod"]


def _write_gguf(path: Path, architecture: str) -> Path:
    """A real GGUF header carrying one general.architecture string, which is
    what detect_dflash_file confirms."""
    import struct

    key = b"general.architecture"
    value = architecture.encode()
    blob = struct.pack("<IIQQ", 0x46554747, 3, 0, 1)
    blob += struct.pack("<Q", len(key)) + key
    blob += struct.pack("<I", 8) + struct.pack("<Q", len(value)) + value
    path.write_bytes(blob)
    return path


def test_detect_dflash_file_leaves_a_shared_assets_pool_alone(tmp_path):
    weight = _write_gguf(tmp_path / "Muse-Glimmer-30B-UD-Q4_K_XL.gguf", "muse-glimmer")
    (tmp_path / "assets").mkdir()
    _write_gguf(tmp_path / "assets" / "dflash-kquant.gguf", "dflash")

    assert detect_dflash_file(str(weight)) is None


def test_detect_dflash_file_finds_the_unpaired_published_sidecar(tmp_path):
    """The published sidecar is dflash-kquant.gguf, which names no model family,
    so the filename pairing DSpark uses would reject the one file this exists to
    find. The header settles it instead."""
    weight = _write_gguf(tmp_path / "Muse-Glimmer-30B-UD-Q4_K_XL.gguf", "muse-glimmer")
    sidecar = _write_gguf(tmp_path / "dflash-kquant.gguf", "dflash")

    assert detect_dflash_file(str(weight)) == str(sidecar.resolve())


def test_detect_dflash_file_rejects_a_real_model_that_is_merely_named_dflash(tmp_path):
    """Two layers must hold: the dflash- name prefix rule and the header check behind it."""
    weight = _write_gguf(tmp_path / "Qwen3.6-27B-Q4_K_M.gguf", "qwen3")
    _write_gguf(tmp_path / "Qwen3.6-35B-A3B-DFlash-Q4_K_M.gguf", "qwen3moe")

    assert detect_dflash_file(str(weight)) is None


def test_detect_dflash_file_rejects_a_dflash_prefixed_file_of_another_architecture(tmp_path):
    """Prefix alone is not enough; a real weight named that way would load as --model-draft."""
    weight = _write_gguf(tmp_path / "model-Q4_K_M.gguf", "llama")
    _write_gguf(tmp_path / "dflash-something-Q8_0.gguf", "llama")

    assert detect_dflash_file(str(weight)) is None


def test_detect_dflash_file_ignores_a_dflash_directory(tmp_path):
    """dflash/ is a user-picked family folder, so unlike dspark/ it is never scanned; reaching into
    it would hand llama-server a real weight as --model-draft."""
    weight = _write_gguf(tmp_path / "model-Q4_K_M.gguf", "llama")
    sub = tmp_path / "dflash"
    sub.mkdir()
    _write_gguf(sub / "dflash-kquant.gguf", "dflash")

    assert detect_dflash_file(str(weight)) is None


def test_detect_dflash_file_prefers_the_sidecar_that_names_this_weight(tmp_path):
    """Both schemes are published; the sidecar naming this weight wins over a foreign one."""
    weight = _write_gguf(tmp_path / "Qwen3.6-27B-Q4_K_M.gguf", "qwen3")
    _write_gguf(tmp_path / "dflash-kquant.gguf", "dflash")
    paired = _write_gguf(tmp_path / "dflash-Qwen3.6-27B-Q8_0.gguf", "dflash")

    assert detect_dflash_file(str(weight)) == str(paired.resolve())


@pytest.mark.parametrize("shape", ["dangling", "directory"])
def test_detect_dflash_file_skips_a_sidecar_it_cannot_open(tmp_path, shape):
    """Same guard as detect_dspark_file: a --model-draft llama-server cannot open
    fails the whole load rather than falling back to no speculation."""
    import os

    weight = _write_gguf(tmp_path / "model-Q4_K_M.gguf", "llama")
    sidecar = tmp_path / "dflash-kquant.gguf"
    if shape == "dangling":
        os.symlink(tmp_path / "missing_blob", sidecar)
    else:
        sidecar.mkdir()

    assert detect_dflash_file(str(weight)) is None


def test_model_config_reports_a_local_dflash_sidecar(tmp_path):
    """The field the load intent and the VRAM guard both read."""
    _write_gguf(tmp_path / "Muse-Glimmer-30B-UD-Q4_K_XL.gguf", "muse-glimmer")
    sidecar = _write_gguf(tmp_path / "dflash-kquant.gguf", "dflash")

    config = ModelConfig.from_identifier(str(tmp_path / "Muse-Glimmer-30B-UD-Q4_K_XL.gguf"))
    assert config.is_gguf is True
    assert config.gguf_dflash_file == str(sidecar.resolve())
    assert config.gguf_dspark_file is None


def _dflash_download_probe(
    tmp_path,
    monkeypatch,
    *,
    supports_dflash,
    cached = None,
):
    from core.inference.llama_cpp import LlamaCppBackend
    import core.inference.llama_cpp as llama_cpp_module

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr(
        LlamaCppBackend,
        "probe_server_capabilities",
        classmethod(lambda cls, binary = None: {"supports_dflash": supports_dflash}),
    )
    monkeypatch.setattr(
        llama_cpp_module, "_companion_snapshot_sibling", lambda near_path, pick: cached
    )
    reached = {}

    def _fake_companion(
        *,
        hf_repo,
        hf_token,
        pick,
        label,
        cancel_event = None,
        near_path = None,
        outcome = None,
        on_transient_failure = None,
    ):
        reached["hit"] = True
        reached["picked"] = pick(
            [
                "Muse-Glimmer-30B-UD-Q4_K_XL.gguf",
                "mmproj-Muse-Glimmer-30B-Q8_0.gguf",
                "dflash-kquant.gguf",
            ]
        )
        if outcome is not None:
            outcome["listed"] = True
        return str(_write_gguf(tmp_path / "dflash-kquant.gguf", "dflash"))

    b = LlamaCppBackend()
    b._download_companion_gguf = _fake_companion
    got = b._download_dflash(
        hf_repo = "unsloth/Muse-Glimmer-30B-GGUF",
        near_path = "/cache/snap/Muse-Glimmer-30B-UD-Q4_K_XL.gguf",
        binary = "/fake/llama-server",
    )
    return got, reached


def test_download_dflash_fetches_when_the_binary_supports_it(tmp_path, monkeypatch):
    got, reached = _dflash_download_probe(tmp_path, monkeypatch, supports_dflash = True)
    assert got == str(tmp_path / "dflash-kquant.gguf")
    assert reached["hit"] is True
    assert reached["picked"] == "dflash-kquant.gguf"


def test_download_dflash_skips_the_fetch_when_the_binary_cannot_run_it(tmp_path, monkeypatch):
    """Gated like DSpark: without --spec-type draft-dflash the sidecar is never opened."""
    got, reached = _dflash_download_probe(tmp_path, monkeypatch, supports_dflash = False)
    assert got is None
    assert reached.get("hit", False) is False


def test_download_dflash_still_reports_a_cached_sidecar_it_cannot_run(tmp_path, monkeypatch):
    """Skipping the fetch must still report a cached DFlash sidecar, or Apply reloads the same server."""
    cached = str(_write_gguf(tmp_path / "dflash-kquant.gguf", "dflash"))
    got, reached = _dflash_download_probe(
        tmp_path, monkeypatch, supports_dflash = False, cached = cached
    )
    assert got == cached
    assert reached.get("hit", False) is False


def test_download_dflash_records_whether_the_repo_publishes_a_sidecar(monkeypatch):
    """Repos without a sidecar are not re-listed on every Apply; failed fetches still retry."""
    from core.inference.llama_cpp import LlamaCppBackend
    import core.inference.llama_cpp as llama_cpp_module

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr(
        LlamaCppBackend,
        "probe_server_capabilities",
        classmethod(lambda cls, binary = None: {"supports_dflash": True}),
    )
    monkeypatch.setattr(
        llama_cpp_module, "_companion_snapshot_sibling", lambda near_path, pick: None
    )

    def _companion(listed):
        def _fake(
            *,
            hf_repo,
            hf_token,
            pick,
            label,
            cancel_event = None,
            near_path = None,
            outcome = None,
            on_transient_failure = None,
        ):
            if outcome is not None:
                outcome["listed"] = listed
            return None

        return _fake

    for listed, expect_absent in ((False, True), (True, False)):
        b = LlamaCppBackend()
        b._download_companion_gguf = _companion(listed)
        assert b._download_dflash(hf_repo = "org/repo", binary = "/fake/llama-server") is None
        assert b._dflash_sidecar_absent is expect_absent


def test_a_cached_dflash_drafter_is_never_launched_as_an_mtp_drafter(tmp_path, monkeypatch):
    """Each kind needs its own --spec-type, so offline MTP reuse must skip DFlash sidecars."""
    from core.inference.llama_cpp import LlamaCppBackend

    snap = tmp_path / "snapshots" / "abc"
    snap.mkdir(parents = True)
    for name in ("dflash-kquant.gguf", "model-Q4_K_M.gguf"):
        _write_gguf(snap / name, "dflash" if name.startswith("dflash-") else "llama")
    monkeypatch.setattr(
        "utils.models.model_config._iter_hf_cache_snapshots", lambda *a, **k: [snap]
    )

    b = LlamaCppBackend()
    assert b._cached_repo_mtp_drafter("org/repo") is None
    assert b._cached_repo_dspark_drafter("org/repo") is None
    assert b._cached_repo_dflash_drafter("org/repo") == str(snap / "dflash-kquant.gguf")


# Download, offline cache reuse and local detection all pair via dflash_repo_preference_key.
_MULTI_FAMILY_LISTING = [
    "model-A-Q4_K_M.gguf",
    "model-B-Q4_K_M.gguf",
    "dflash-model-A-Q8_0.gguf",
    "dflash-kquant.gguf",
]


def _dflash_download_pick(monkeypatch, *, listing, near_path):
    """The sidecar _download_dflash's picker chooses out of a repo listing."""
    from core.inference.llama_cpp import LlamaCppBackend
    import core.inference.llama_cpp as llama_cpp_module

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr(
        LlamaCppBackend,
        "probe_server_capabilities",
        classmethod(lambda cls, binary = None: {"supports_dflash": True}),
    )
    monkeypatch.setattr(
        llama_cpp_module, "_companion_snapshot_sibling", lambda near_path, pick: None
    )
    picked = {}

    def _fake_companion(
        *,
        hf_repo,
        hf_token,
        pick,
        label,
        cancel_event = None,
        near_path = None,
        outcome = None,
        on_transient_failure = None,
    ):
        picked["name"] = pick(listing)
        return None

    b = LlamaCppBackend()
    b._download_companion_gguf = _fake_companion
    b._download_dflash(
        hf_repo = "org/repo",
        near_path = near_path,
        binary = "/fake/llama-server",
    )
    return picked.get("name")


def test_download_dflash_skips_a_sidecar_named_after_another_weight(monkeypatch):
    """Model B must get the generic sidecar, not the higher-precision one that names model A."""
    assert (
        _dflash_download_pick(
            monkeypatch,
            listing = _MULTI_FAMILY_LISTING,
            near_path = "/cache/snap/model-B-Q4_K_M.gguf",
        )
        == "dflash-kquant.gguf"
    )


def test_download_dflash_takes_the_sidecar_naming_this_weight(monkeypatch):
    """The other direction: model A's own sidecar still wins over the generic
    one, as it does in detect_dflash_file."""
    assert (
        _dflash_download_pick(
            monkeypatch,
            listing = _MULTI_FAMILY_LISTING,
            near_path = "/cache/snap/model-A-Q4_K_M.gguf",
        )
        == "dflash-model-A-Q8_0.gguf"
    )


@pytest.mark.parametrize("sidecar", ["dflash-kquant.gguf", "dflash-bf16.gguf"])
def test_download_dflash_keeps_the_single_published_sidecar(monkeypatch, sidecar):
    """The shipped unsloth/Muse-Glimmer-30B-GGUF layout. Its sidecar's stem is a
    precision token, not a family, so nothing may treat "names no weight here"
    as a rejection."""
    assert (
        _dflash_download_pick(
            monkeypatch,
            listing = [
                "Muse-Glimmer-30B-UD-Q4_K_XL.gguf",
                "mmproj-Muse-Glimmer-30B-Q8_0.gguf",
                sidecar,
            ],
            near_path = "/cache/snap/Muse-Glimmer-30B-UD-Q4_K_XL.gguf",
        )
        == sidecar
    )


def test_cached_dflash_lookup_pairs_with_the_selected_weight(tmp_path, monkeypatch):
    """Offline reuse must pick what a download would fetch, or reloads swap drafters."""
    from core.inference.llama_cpp import LlamaCppBackend

    snap = tmp_path / "snapshots" / "abc"
    snap.mkdir(parents = True)
    for name in _MULTI_FAMILY_LISTING:
        _write_gguf(snap / name, "dflash" if name.startswith("dflash-") else "llama")
    monkeypatch.setattr(
        "utils.models.model_config._iter_hf_cache_snapshots", lambda *a, **k: [snap]
    )

    b = LlamaCppBackend()
    for weight, expected in (
        ("model-B-Q4_K_M.gguf", "dflash-kquant.gguf"),
        ("model-A-Q4_K_M.gguf", "dflash-model-A-Q8_0.gguf"),
    ):
        assert b._cached_repo_dflash_drafter("org/repo", near_path = str(snap / weight)) == str(
            snap / expected
        )
    assert b._cached_repo_dflash_drafter("org/repo") == str(snap / "dflash-model-A-Q8_0.gguf")


def test_cached_dflash_lookup_keeps_the_single_published_sidecar(tmp_path, monkeypatch):
    from core.inference.llama_cpp import LlamaCppBackend

    snap = tmp_path / "snapshots" / "abc"
    snap.mkdir(parents = True)
    for name in ("Muse-Glimmer-30B-UD-Q4_K_XL.gguf", "dflash-kquant.gguf"):
        _write_gguf(snap / name, "dflash" if name.startswith("dflash-") else "muse-glimmer")
    monkeypatch.setattr(
        "utils.models.model_config._iter_hf_cache_snapshots", lambda *a, **k: [snap]
    )

    b = LlamaCppBackend()
    assert b._cached_repo_dflash_drafter(
        "org/repo", near_path = str(snap / "Muse-Glimmer-30B-UD-Q4_K_XL.gguf")
    ) == str(snap / "dflash-kquant.gguf")


def test_local_and_remote_dflash_pairing_agree(tmp_path):
    """One rule, three call sites: the local scan, download picker and cache lookup all go through
    dflash_repo_preference_key and _drafter_names_other_weight."""
    from utils.models.drafters import dflash_repo_preference_key

    others = ["model-A-Q4_K_M.gguf", "model-B-Q4_K_M.gguf"]
    ranked = sorted(
        ("dflash-model-A-Q8_0.gguf", "dflash-kquant.gguf"),
        key = lambda name: dflash_repo_preference_key(name, "model-B-Q4_K_M.gguf", others),
    )
    assert ranked[0] == "dflash-kquant.gguf"

    for name in _MULTI_FAMILY_LISTING:
        _write_gguf(tmp_path / name, "dflash" if name.startswith("dflash-") else "llama")
    assert detect_dflash_file(str(tmp_path / "model-B-Q4_K_M.gguf")) == str(
        (tmp_path / "dflash-kquant.gguf").resolve()
    )


def test_dflash_stays_unreclaimable_even_though_auto_now_launches_it(tmp_path):
    """dflash-*.gguf stays unreclaimable: some repos hold only that file, which may be a chosen model."""
    from hub.services.models.deletion import _delete_gguf_variant_from_repos

    from hub.utils.gguf import is_reclaimable_drafter_path

    assert is_reclaimable_drafter_path("dflash-kquant.gguf") is False
    assert is_reclaimable_drafter_path("dspark-model-Q8_0.gguf") is True
    assert is_reclaimable_drafter_path("Ternary-Bonsai-27B-dspark-Q4_1.gguf") is True
    assert is_reclaimable_drafter_path("DeepSeek-V4-Flash-Dspark-Abliterated-MXFP4.gguf") is False

    repo, snap = _cache_repo(
        tmp_path,
        "org/Model-GGUF",
        ["model-Q4_K_M.gguf", "dflash-kquant.gguf", "dspark-model-Q8_0.gguf"],
    )
    _delete_gguf_variant_from_repos("org/Model-GGUF", "Q4_K_M", [repo], None, root = tmp_path)

    assert not (snap / "model-Q4_K_M.gguf").is_symlink()
    assert (snap / "dflash-kquant.gguf").is_symlink()
    assert not (snap / "dspark-model-Q8_0.gguf").is_symlink()


def test_deleting_the_last_bonsai_variant_reclaims_its_dspark_drafter(tmp_path):
    """The menu hides the dspark companion, so deleting the last variant must reclaim it."""
    from hub.services.models.deletion import _delete_gguf_variant_from_repos

    repo, snap = _cache_repo(
        tmp_path,
        "prism-ml/Bonsai-27B-gguf",
        ["Bonsai-27B-Q1_0.gguf", "Bonsai-27B-dspark-Q4_1.gguf"],
    )
    _delete_gguf_variant_from_repos("prism-ml/Bonsai-27B-gguf", "Q1_0", [repo], None, root = tmp_path)

    assert not (snap / "Bonsai-27B-Q1_0.gguf").is_symlink()
    assert not (snap / "Bonsai-27B-dspark-Q4_1.gguf").is_symlink()


def test_detect_dflash_file_skips_a_sidecar_named_for_another_weight(tmp_path):
    """A sidecar named for another model must not attach: its real dflash header passes the arch check."""
    weight = _write_gguf(tmp_path / "Muse-Glimmer-30B-UD-Q4_K_XL.gguf", "muse-glimmer")
    _write_gguf(tmp_path / "Qwen3.6-27B-Q4_K_M.gguf", "qwen3")
    foreign = _write_gguf(tmp_path / "dflash-Qwen3.6-27B-Q8_0.gguf", "dflash")
    generic = _write_gguf(tmp_path / "dflash-kquant.gguf", "dflash")

    assert foreign.exists()
    assert detect_dflash_file(str(weight)) == str(generic.resolve())


def test_detect_dflash_file_still_prefers_a_sidecar_that_names_this_weight(tmp_path):
    """The skip must not cost the paired case: a sidecar naming this weight beats generic."""
    weight = _write_gguf(tmp_path / "Muse-Glimmer-30B-UD-Q4_K_XL.gguf", "muse-glimmer")
    paired = _write_gguf(tmp_path / "dflash-Muse-Glimmer-30B-Q8_0.gguf", "dflash")
    _write_gguf(tmp_path / "dflash-kquant.gguf", "dflash")

    assert detect_dflash_file(str(weight)) == str(paired.resolve())


def test_detect_dflash_file_ignores_the_suffix_form_the_picker_cannot_hide(tmp_path):
    """Detection ignores the -dflash suffix form, which the quant picker cannot hide as a drafter."""
    from core.inference.llama_cpp import _is_companion_gguf_path

    weight = _write_gguf(tmp_path / "Muse-Glimmer-30B-UD-Q4_K_XL.gguf", "muse-glimmer")
    suffix_form = tmp_path / "Muse-Glimmer-30B-Q8_0-dflash.gguf"
    _write_gguf(suffix_form, "dflash")

    assert detect_dflash_file(str(weight)) is None
    assert _is_companion_gguf_path(suffix_form.name) is False
    assert _is_companion_gguf_path("dflash-kquant.gguf") is True


def test_detect_dflash_file_validates_a_candidate_before_reading_its_header(tmp_path, monkeypatch):
    """Ask accept before reading any header: a symlink may escape the lease, and a read is irreversible."""
    import os
    import utils.models.model_config as mc

    leased = tmp_path / "leased"
    leased.mkdir()
    outside = tmp_path / "outside"
    outside.mkdir()
    weight = _write_gguf(leased / "Muse-Glimmer-30B-UD-Q4_K_XL.gguf", "muse-glimmer")
    target = _write_gguf(outside / "dflash-kquant.gguf", "dflash")
    os.symlink(target, leased / "dflash-kquant.gguf")

    reads: list[str] = []
    real_read = mc.read_gguf_general_metadata

    def _recording_read(path, *args, **kwargs):
        reads.append(str(path))
        return real_read(path, *args, **kwargs)

    monkeypatch.setattr(mc, "read_gguf_general_metadata", _recording_read)

    def _inside_the_lease(launch: str) -> bool:
        return leased in Path(launch).parents

    assert detect_dflash_file(str(weight), accept = _inside_the_lease) is None
    assert reads == []


def test_detect_dflash_file_still_checks_the_header_of_an_accepted_candidate(tmp_path):
    """The reorder keeps the architecture check; an accepted non-dflash file is still dropped."""
    weight = _write_gguf(tmp_path / "model-Q4_K_M.gguf", "llama")
    _write_gguf(tmp_path / "dflash-something-Q8_0.gguf", "llama")

    assert detect_dflash_file(str(weight), accept = lambda launch: True) is None


# Validate remote candidates by GGUF header, not name, or a dflash-*.gguf weight gets downloaded.


def _dflash_repo_download(
    tmp_path,
    monkeypatch,
    *,
    listing,
    sibling = None,
):
    """Drive _download_dflash over a repo listing whose files exist in tmp_path."""
    from core.inference.llama_cpp import LlamaCppBackend
    import core.inference.llama_cpp as llama_cpp_module

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr(
        LlamaCppBackend,
        "probe_server_capabilities",
        classmethod(lambda cls, binary = None: {"supports_dflash": True}),
    )
    monkeypatch.setattr(
        llama_cpp_module, "_companion_snapshot_sibling", lambda near_path, pick: sibling
    )
    fetched: list[str] = []

    def _fake_companion(
        *,
        hf_repo,
        hf_token,
        pick,
        label,
        cancel_event = None,
        near_path = None,
        outcome = None,
        on_transient_failure = None,
    ):
        target = pick(listing)
        if outcome is not None:
            outcome["listed"] = target is not None
        if target is None:
            return None
        fetched.append(target)
        return str(tmp_path / target)

    b = LlamaCppBackend()
    b._download_companion_gguf = _fake_companion
    got = b._download_dflash(
        hf_repo = "org/repo",
        near_path = str(tmp_path / "model-Q4_K_M.gguf"),
        binary = "/fake/llama-server",
    )
    return b, got, fetched


def test_download_dflash_falls_through_a_candidate_that_is_not_a_dflash_model(
    tmp_path, monkeypatch
):
    """A candidate whose header is not dflash must fall through to the next, not return None."""
    _write_gguf(tmp_path / "model-Q4_K_M.gguf", "llama")
    _write_gguf(tmp_path / "dflash-model-Q8_0.gguf", "llama")
    sidecar = _write_gguf(tmp_path / "dflash-kquant.gguf", "dflash")

    b, got, fetched = _dflash_repo_download(
        tmp_path,
        monkeypatch,
        listing = ["model-Q4_K_M.gguf", "dflash-model-Q8_0.gguf", "dflash-kquant.gguf"],
    )

    assert got == str(sidecar)
    assert fetched == ["dflash-model-Q8_0.gguf", "dflash-kquant.gguf"]
    assert b._dflash_sidecar_absent is False


def test_download_dflash_reports_no_sidecar_when_every_candidate_is_a_weight(tmp_path, monkeypatch):
    """A dflash-named weight is no sidecar; the absence is recorded so Apply stops re-listing."""
    _write_gguf(tmp_path / "model-Q4_K_M.gguf", "llama")
    _write_gguf(tmp_path / "dflash-model-Q8_0.gguf", "llama")

    b, got, fetched = _dflash_repo_download(
        tmp_path,
        monkeypatch,
        listing = ["model-Q4_K_M.gguf", "dflash-model-Q8_0.gguf"],
    )

    assert got is None
    assert fetched == ["dflash-model-Q8_0.gguf"]
    assert b._dflash_sidecar_absent is True


def test_download_dflash_validates_the_snapshot_sibling_it_reuses(tmp_path, monkeypatch):
    """Reuse never downloads, yet its file goes to --model-draft, so the header rule applies."""
    from core.inference.llama_cpp import LlamaCppBackend

    snap = tmp_path / "models--org--repo" / "snapshots" / "abc"
    snap.mkdir(parents = True)
    _write_gguf(snap / "model-Q4_K_M.gguf", "llama")
    _write_gguf(snap / "dflash-model-Q8_0.gguf", "llama")
    sidecar = _write_gguf(snap / "dflash-kquant.gguf", "dflash")

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr(
        LlamaCppBackend,
        "probe_server_capabilities",
        classmethod(lambda cls, binary = None: {"supports_dflash": True}),
    )

    b = LlamaCppBackend()
    b._download_companion_gguf = lambda **kwargs: pytest.fail("the reuse must not download")
    assert b._download_dflash(
        hf_repo = "org/repo",
        near_path = str(snap / "model-Q4_K_M.gguf"),
        binary = "/fake/llama-server",
    ) == str(sidecar)


def test_cached_dflash_lookup_skips_a_prefixed_file_of_another_architecture(tmp_path, monkeypatch):
    """Offline lookup also ranks by name, so a weight named like a sidecar must be skipped."""
    from core.inference.llama_cpp import LlamaCppBackend

    snap = tmp_path / "snapshots" / "abc"
    snap.mkdir(parents = True)
    _write_gguf(snap / "model-Q4_K_M.gguf", "llama")
    _write_gguf(snap / "dflash-model-Q8_0.gguf", "llama")
    _write_gguf(snap / "dflash-kquant.gguf", "dflash")
    monkeypatch.setattr(
        "utils.models.model_config._iter_hf_cache_snapshots", lambda *a, **k: [snap]
    )

    b = LlamaCppBackend()
    assert b._cached_repo_dflash_drafter(
        "org/repo", near_path = str(snap / "model-Q4_K_M.gguf")
    ) == str(snap / "dflash-kquant.gguf")


def test_local_and_remote_dflash_architecture_checks_agree(tmp_path):
    """One rule, one place: detect_dflash_file and the remote paths both ask
    is_dflash_architecture, so neither can start trusting the name alone."""
    from utils.models.drafters import is_dflash_architecture

    weight = _write_gguf(tmp_path / "model-Q4_K_M.gguf", "llama")
    impostor = _write_gguf(tmp_path / "dflash-model-Q8_0.gguf", "llama")
    sidecar = _write_gguf(tmp_path / "dflash-kquant.gguf", "dflash")

    assert is_dflash_architecture(str(impostor)) is False
    assert is_dflash_architecture(str(sidecar)) is True
    assert is_dflash_architecture(str(tmp_path / "missing.gguf")) is False
    assert detect_dflash_file(str(weight)) == str(sidecar.resolve())


# _download_dspark returns a cached path even if the binary cannot run it, so Auto must not
# skip DFlash on that path alone.


class _StopAfterDownloads(Exception):
    """Ends the load once Phase 2 is done, which is all these tests observe."""


def _dflash_fetch_during_auto_load(
    monkeypatch,
    *,
    supports_dspark,
    supports_dflash,
    dspark_cached,
    speculative_type = "auto",
    tensor_parallel = False,
    extra_args = None,
    gguf_path = None,
    dflash_draft_path = None,
    mtp_draft_path = None,
    mtp_loads = True,
    mtp_token = "draft-mtp",
    model_file = "/cache/snap/model-Q4_K_M.gguf",
    dflash_file = "/cache/snap/dflash-kquant.gguf",
    mmproj_file = None,
    disable_vision = False,
):
    """Suppression sits inline in load_model's download phase, so only the real load path can pin it."""
    from core.inference.llama_cpp import LlamaCppBackend
    import core.inference.llama_cpp as llama_cpp_module

    from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend

    monkeypatch.setattr(
        LlamaCppBackend,
        "probe_server_capabilities",
        classmethod(
            lambda cls, binary = None: {
                "found": True,
                "supports_dspark": supports_dspark,
                "supports_dflash": supports_dflash,
                "mtp_token": mtp_token,
            }
        ),
    )
    monkeypatch.setattr(llama_cpp_module, "_resolve_repo_id_casing", lambda repo: repo)
    monkeypatch.setattr(
        llama_cpp_module,
        "_hf_offline_if_unreachable",
        lambda: __import__("contextlib").nullcontext(),
    )

    backend = LlamaCppBackend()
    seen: dict = {"dflash_fetched": False}
    monkeypatch.setattr(backend, "_find_llama_server_binary", lambda **_kwargs: "/bin/llama")
    monkeypatch.setattr(backend, "_is_vulkan_backend", lambda _binary = None: False)
    monkeypatch.setattr(backend, "_get_gpu_memory", lambda _binary = None, **_kw: [(0, 4096, 8192)])
    monkeypatch.setattr(backend, "_gguf_path_is_diffusion", lambda *_args: False)
    monkeypatch.setattr(backend, "_kill_process", lambda: None)
    monkeypatch.setattr(backend, "_download_gguf", lambda **_kwargs: model_file)
    monkeypatch.setattr(backend, "_resolve_launch_mmproj_path", lambda **_kwargs: mmproj_file)
    monkeypatch.setattr(backend, "_download_mtp", lambda **_kwargs: mtp_draft_path)
    monkeypatch.setattr(llama_cpp_module, "_mtp_drafter_loads_standalone", lambda _path: mtp_loads)
    # Exactly what _download_dspark does for a cached sidecar on a binary that
    # cannot run it: the path comes back regardless of the capability.
    monkeypatch.setattr(backend, "_download_dspark", lambda **_kwargs: dspark_cached)

    def _fetch_dflash(**_kwargs):
        seen["dflash_fetched"] = True
        return dflash_file

    monkeypatch.setattr(backend, "_download_dflash", _fetch_dflash)
    seen["log"] = []
    _real_info = llama_cpp_module.logger.info

    def _info(msg, *args, **kwargs):
        seen["log"].append(str(msg))
        return _real_info(msg, *args, **kwargs)

    monkeypatch.setattr(llama_cpp_module.logger, "info", _info)
    seen["warnings"] = []
    _real_warning = llama_cpp_module.logger.warning

    def _warning(msg, *args, **kwargs):
        seen["warnings"].append(str(msg))
        return _real_warning(msg, *args, **kwargs)

    monkeypatch.setattr(llama_cpp_module.logger, "warning", _warning)

    def _stop(*_args, **_kwargs):
        raise _StopAfterDownloads

    monkeypatch.setattr(backend, "_read_gguf_metadata", _stop)

    source = (
        {"gguf_path": gguf_path, "model_identifier": gguf_path}
        if gguf_path
        else {"hf_repo": "org/repo", "hf_variant": "Q4_K_M", "model_identifier": "org/repo"}
    )
    with pytest.raises(_StopAfterDownloads):
        backend.load_model(
            GgufLoadIntent(
                **source,
                speculative_type = speculative_type,
                tensor_parallel = tensor_parallel,
                extra_args = tuple(extra_args) if extra_args is not None else None,
                dflash_draft_path = dflash_draft_path,
                mtp_draft_path = mtp_draft_path if gguf_path else None,
                disable_vision = disable_vision,
            )
        )
    seen["dflash_promoted"] = any("using draft-dflash" in m for m in seen["log"])
    return seen


def test_auto_still_fetches_dflash_when_the_binary_cannot_run_dspark(monkeypatch):
    """A cached DSpark sidecar this binary cannot run must not block a DFlash drafter it can."""
    seen = _dflash_fetch_during_auto_load(
        monkeypatch,
        supports_dspark = False,
        supports_dflash = True,
        dspark_cached = "/cache/snap/dspark-model-Q8_0.gguf",
    )
    assert seen["dflash_fetched"] is True


def test_auto_stands_down_on_dflash_for_a_dspark_it_can_launch(monkeypatch):
    """DSpark takes first refusal, so a ~1.5 GiB DFlash fetch would buy an unopened file."""
    seen = _dflash_fetch_during_auto_load(
        monkeypatch,
        supports_dspark = True,
        supports_dflash = True,
        dspark_cached = "/cache/snap/dspark-model-Q8_0.gguf",
    )
    assert seen["dflash_fetched"] is False


def test_auto_fetches_dflash_when_the_repo_ships_no_dspark_sidecar(monkeypatch):
    """Positive control: DSpark's capability does not gate a repo shipping only DFlash."""
    seen = _dflash_fetch_during_auto_load(
        monkeypatch,
        supports_dspark = True,
        supports_dflash = True,
        dspark_cached = None,
    )
    assert seen["dflash_fetched"] is True


# #11308: DFlash2 + --split-mode tensor aborts at startup, so Auto keeps tensor split with MTP.

_MTP = "/cache/snap/MTP/mtp-model-Q4_0.gguf"


@pytest.mark.parametrize(
    "tensor_parallel, extra_args",
    [(True, None), (False, ["-sm", "tensor"]), (False, ["--split-mode", "tensor"])],
)
def test_auto_skips_dflash_under_tensor_split_when_mtp_is_available(
    monkeypatch, tensor_parallel, extra_args
):
    seen = _dflash_fetch_during_auto_load(
        monkeypatch,
        supports_dspark = False,
        supports_dflash = True,
        dspark_cached = None,
        tensor_parallel = tensor_parallel,
        extra_args = extra_args,
        mtp_draft_path = _MTP,
    )
    assert seen["dflash_fetched"] is False
    assert seen["dflash_promoted"] is False


def test_auto_skips_dflash_under_tensor_split_from_env(monkeypatch):
    monkeypatch.setenv("LLAMA_ARG_SPLIT_MODE", "tensor")
    seen = _dflash_fetch_during_auto_load(
        monkeypatch,
        supports_dspark = False,
        supports_dflash = True,
        dspark_cached = None,
        mtp_draft_path = _MTP,
    )
    assert seen["dflash_fetched"] is False


def test_auto_keeps_dflash_under_tensor_split_when_the_mtp_sidecar_cannot_load(monkeypatch):
    seen = _dflash_fetch_during_auto_load(
        monkeypatch,
        supports_dspark = False,
        supports_dflash = True,
        dspark_cached = None,
        tensor_parallel = True,
        mtp_draft_path = _MTP,
        mtp_loads = False,
    )
    assert seen["dflash_fetched"] is True
    assert seen["dflash_promoted"] is True


def test_auto_keeps_dflash_under_tensor_split_when_the_binary_cannot_run_mtp(monkeypatch):
    seen = _dflash_fetch_during_auto_load(
        monkeypatch,
        supports_dspark = False,
        supports_dflash = True,
        dspark_cached = None,
        tensor_parallel = True,
        mtp_draft_path = _MTP,
        mtp_token = None,
    )
    assert seen["dflash_promoted"] is True


def test_auto_keeps_dflash_under_tensor_split_for_an_extras_drafter(monkeypatch):
    seen = _dflash_fetch_during_auto_load(
        monkeypatch,
        supports_dspark = False,
        supports_dflash = True,
        dspark_cached = None,
        extra_args = ["-sm", "tensor", "--model-draft", "/models/dflash-model.gguf"],
        mtp_draft_path = _MTP,
    )
    assert seen["dflash_promoted"] is True


def test_auto_keeps_dflash_under_tensor_split_for_a_target_with_an_embedded_head(monkeypatch):
    import utils.models.gguf_metadata as gguf_metadata

    monkeypatch.setattr(gguf_metadata, "read_gguf_nextn_predict_layers", lambda _path: 1)
    seen = _dflash_fetch_during_auto_load(
        monkeypatch,
        supports_dspark = False,
        supports_dflash = True,
        dspark_cached = None,
        tensor_parallel = True,
        mtp_draft_path = _MTP,
    )
    assert seen["dflash_promoted"] is True


def test_auto_keeps_dflash_under_tensor_split_without_an_mtp_drafter(monkeypatch):
    seen = _dflash_fetch_during_auto_load(
        monkeypatch,
        supports_dspark = False,
        supports_dflash = True,
        dspark_cached = None,
        tensor_parallel = True,
    )
    assert seen["dflash_fetched"] is True
    assert seen["dflash_promoted"] is True


def test_auto_does_not_promote_a_local_dflash_sidecar_under_tensor_split(monkeypatch, tmp_path):
    model = tmp_path / "Qwen3.8-27B-UD-Q6_K_XL.gguf"
    model.write_bytes(b"GGUF")
    sidecar = tmp_path / "dflash-Qwen3.8-27B-Q8_0.gguf"
    sidecar.write_bytes(b"GGUF")
    mtp = tmp_path / "MTP" / "mtp-Qwen3.8-27B-Q4_0.gguf"
    mtp.parent.mkdir()
    mtp.write_bytes(b"GGUF")
    kwargs = dict(
        supports_dspark = False,
        supports_dflash = True,
        dspark_cached = None,
        gguf_path = str(model),
        dflash_draft_path = str(sidecar),
        mtp_draft_path = str(mtp),
    )
    tensor = _dflash_fetch_during_auto_load(monkeypatch, extra_args = ["-sm", "tensor"], **kwargs)
    assert tensor["dflash_promoted"] is False
    assert any("keeping tensor split" in m for m in tensor["log"])
    layer = _dflash_fetch_during_auto_load(monkeypatch, **kwargs)
    assert layer["dflash_promoted"] is True


@pytest.mark.parametrize("extra_args", [None, ["-sm", "layer"]])
def test_auto_still_uses_dflash_without_tensor_split(monkeypatch, extra_args):
    seen = _dflash_fetch_during_auto_load(
        monkeypatch,
        supports_dspark = False,
        supports_dflash = True,
        dspark_cached = None,
        tensor_parallel = extra_args is not None,
        extra_args = extra_args,
        mtp_draft_path = _MTP,
    )
    assert seen["dflash_fetched"] is True
    assert seen["dflash_promoted"] is True


def test_explicit_dflash_still_fetches_under_tensor_split(monkeypatch):
    seen = _dflash_fetch_during_auto_load(
        monkeypatch,
        supports_dspark = False,
        supports_dflash = True,
        dspark_cached = None,
        speculative_type = "dflash",
        tensor_parallel = True,
        mtp_draft_path = _MTP,
    )
    assert seen["dflash_fetched"] is True


# The grant boundary must reach discovery, since the DFlash scan opens headers before rejection.


def test_from_identifier_hands_the_boundary_to_every_drafter_kind(tmp_path, monkeypatch):
    """All three kinds, not only the header reader, share one discovery, so each gets the boundary
    check; skipping it hands the load a sidecar to reject twice."""
    import utils.models.model_config as mc

    weight = _write_gguf(tmp_path / "model-Q4_K_M.gguf", "llama")
    seen: dict[str, tuple] = {}

    def _recorder(kind):
        def _detect(
            path,
            search_root = None,
            accept = None,
            **kwargs,
        ):
            seen[kind] = (path, search_root, accept)
            return None

        return _detect

    for kind, name in (
        ("mtp", "detect_mtp_file"),
        ("dspark", "detect_dspark_file"),
        ("dflash", "detect_dflash_file"),
    ):
        monkeypatch.setattr(mc, name, _recorder(kind))

    calls: list[tuple[str, str, str, str]] = []

    def _accept(candidate, gguf_file, kind, search_root):
        calls.append((candidate, gguf_file, kind, search_root))
        return False

    config = ModelConfig.from_identifier(str(weight), drafter_accept = _accept)

    assert config is not None
    assert set(seen) == {"mtp", "dspark", "dflash"}
    for kind, (path, search_root, accept) in seen.items():
        assert path == str(weight)
        assert accept is not None, kind
        assert accept("/candidate.gguf") is False
        assert calls[-1] == ("/candidate.gguf", str(weight), kind, search_root)


def test_from_identifier_without_a_boundary_scans_exactly_as_before(tmp_path, monkeypatch):
    """Callers with no lease to impose must see the same candidates in the same order."""
    import utils.models.model_config as mc

    weight = _write_gguf(tmp_path / "model-Q4_K_M.gguf", "llama")
    accepts: list = []

    def _detect(
        path,
        search_root = None,
        accept = None,
        **kwargs,
    ):
        accepts.append(accept)
        return None

    for name in ("detect_mtp_file", "detect_dspark_file", "detect_dflash_file"):
        monkeypatch.setattr(mc, name, _detect)

    ModelConfig.from_identifier(str(weight))
    assert accepts == [None, None, None]


def test_from_identifier_never_reads_a_sidecar_outside_the_boundary(tmp_path, monkeypatch):
    """Escaping symlink target is never opened; the config reports no DFlash sidecar."""
    import os

    # Patch the module that resolves the name, not the re-exporter, or the patch never intercepts.
    import utils.models.drafters.dflash as dflash_mod

    leased = tmp_path / "leased"
    leased.mkdir()
    outside = tmp_path / "outside"
    outside.mkdir()
    weight = _write_gguf(leased / "model-Q4_K_M.gguf", "llama")
    target = _write_gguf(outside / "dflash-kquant.gguf", "dflash")
    os.symlink(target, leased / "dflash-kquant.gguf")

    reads: list[str] = []
    real_check = dflash_mod.is_dflash_architecture

    def _recording_check(path, *args, **kwargs):
        reads.append(str(path))
        return real_check(path, *args, **kwargs)

    monkeypatch.setattr(dflash_mod, "is_dflash_architecture", _recording_check)

    def _inside_the_lease(candidate, gguf_file, kind, search_root):
        return Path(search_root) in Path(candidate).parents

    config = ModelConfig.from_identifier(str(weight), drafter_accept = _inside_the_lease)

    assert config is not None
    assert config.gguf_dflash_file is None
    assert reads == []


# Remote DFlash discovery is root level only, matching the local scan.


@pytest.mark.parametrize(
    "path,expected",
    [
        ("dflash-kquant.gguf", True),
        ("dflash-model-Q8_0.gguf", True),
        ("quants/dflash-kquant.gguf", False),
        ("dflash/dflash-kquant.gguf", False),
        (r"quants\dflash-kquant.gguf", False),
        ("model-Q4_K_M.gguf", False),
        ("model-dflash-Q8_0.gguf", False),
    ],
)
def test_is_root_dflash_drafter_path(path, expected):
    from core.inference.llama_cpp import _is_root_dflash_drafter_path
    assert _is_root_dflash_drafter_path(path) is expected


def test_the_basename_predicate_keeps_its_own_semantics():
    """Kept separate: _is_dflash_drafter_path also serves callers that have only a filename."""
    from core.inference.llama_cpp import _is_dflash_drafter_path

    assert _is_dflash_drafter_path("quants/dflash-kquant.gguf") is True
    assert _is_dflash_drafter_path("dflash-kquant.gguf") is True


def test_download_dflash_never_fetches_a_nested_dflash_named_weight(tmp_path, monkeypatch):
    """Regression: a nested dflash-named weight was fetched in full before the header check rejected it."""
    _write_gguf(tmp_path / "model-Q4_K_M.gguf", "llama")

    b, got, fetched = _dflash_repo_download(
        tmp_path,
        monkeypatch,
        listing = ["model-Q4_K_M.gguf", "quants/dflash-model-Q8_0.gguf"],
    )

    assert got is None
    assert fetched == []
    assert b._dflash_sidecar_absent is True


def test_download_dflash_still_takes_the_root_sidecar_beside_a_nested_one(tmp_path, monkeypatch):
    """Positive control: the nested name is skipped, not the whole repo."""
    _write_gguf(tmp_path / "model-Q4_K_M.gguf", "llama")
    sidecar = _write_gguf(tmp_path / "dflash-kquant.gguf", "dflash")

    b, got, fetched = _dflash_repo_download(
        tmp_path,
        monkeypatch,
        listing = ["model-Q4_K_M.gguf", "quants/dflash-model-Q8_0.gguf", "dflash-kquant.gguf"],
    )

    assert got == str(sidecar)
    assert fetched == ["dflash-kquant.gguf"]


def test_cached_dflash_lookup_ignores_a_nested_dflash_named_weight(tmp_path, monkeypatch):
    """Same rule for the offline cache scan, which feeds --model-draft directly."""
    from core.inference.llama_cpp import LlamaCppBackend

    snap = tmp_path / "snapshots" / "abc"
    (snap / "quants").mkdir(parents = True)
    _write_gguf(snap / "model-Q4_K_M.gguf", "llama")
    _write_gguf(snap / "quants" / "dflash-model-Q8_0.gguf", "dflash")
    monkeypatch.setattr(
        "utils.models.model_config._iter_hf_cache_snapshots", lambda *a, **k: [snap]
    )

    b = LlamaCppBackend()
    assert (
        b._cached_repo_dflash_drafter("org/repo", near_path = str(snap / "model-Q4_K_M.gguf")) is None
    )


# llama-server finds split drafter shards beside shard 1, so the whole set must be fetched.


def _split_companion_download(tmp_path, monkeypatch, listing):
    from core.inference.llama_cpp import LlamaCppBackend
    import core.inference.llama_cpp as llama_cpp_module

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr("huggingface_hub.list_repo_files", lambda repo, token = None: list(listing))
    monkeypatch.setattr(llama_cpp_module, "_hub_download_in_flight", lambda hf_repo: False)
    fetched: list[str] = []

    def _fake_download(
        repo,
        filename,
        token,
        *,
        cancel_event = None,
        cache_dir = None,
    ):
        fetched.append(filename)
        path = tmp_path / filename
        path.parent.mkdir(parents = True, exist_ok = True)
        path.write_bytes(b"x")
        return str(path)

    monkeypatch.setattr(llama_cpp_module, "hf_hub_download_with_xet_fallback", _fake_download)

    def _pick(names):
        return next((n for n in sorted(names) if Path(n).name.startswith("dflash-")), None)

    got = LlamaCppBackend()._download_companion_gguf(
        hf_repo = "org/repo",
        hf_token = None,
        pick = _pick,
        label = "DFlash drafter",
    )
    return got, fetched


def test_download_companion_gguf_fetches_every_shard_of_a_split_sidecar(tmp_path, monkeypatch):
    got, fetched = _split_companion_download(
        tmp_path,
        monkeypatch,
        [
            "model-Q4_K_M.gguf",
            "dflash-kquant-00001-of-00002.gguf",
            "dflash-kquant-00002-of-00002.gguf",
        ],
    )

    assert got == str(tmp_path / "dflash-kquant-00001-of-00002.gguf")
    assert fetched == ["dflash-kquant-00001-of-00002.gguf", "dflash-kquant-00002-of-00002.gguf"]


def test_download_companion_gguf_leaves_a_single_file_sidecar_alone(tmp_path, monkeypatch):
    """Single-file companions skip split handling: one fetch, and the same path comes back."""
    got, fetched = _split_companion_download(
        tmp_path, monkeypatch, ["model-Q4_K_M.gguf", "dflash-kquant.gguf"]
    )

    assert got == str(tmp_path / "dflash-kquant.gguf")
    assert fetched == ["dflash-kquant.gguf"]


def test_companion_snapshot_reuse_skips_an_incomplete_split_sidecar(tmp_path):
    """A snapshot holding only shard 1 is no reuse: that would skip the download completing the set."""
    from core.inference.llama_cpp import _companion_snapshot_sibling

    snap = tmp_path / "models--org--repo" / "snapshots" / "abc"
    snap.mkdir(parents = True)
    (snap / "model-Q4_K_M.gguf").write_bytes(b"x")
    first = snap / "dflash-kquant-00001-of-00002.gguf"
    first.write_bytes(b"y")

    def _pick(names):
        return next((n for n in sorted(names) if Path(n).name.startswith("dflash-")), None)

    near = str(snap / "model-Q4_K_M.gguf")
    assert _companion_snapshot_sibling(near, _pick) is None

    (snap / "dflash-kquant-00002-of-00002.gguf").write_bytes(b"z")
    assert _companion_snapshot_sibling(near, _pick) == str(first)


def test_offline_companion_cache_hit_skips_an_incomplete_split(tmp_path, monkeypatch):
    """Offline, the cache lookup is a third route for a shard to reach --model-draft."""
    from core.inference.llama_cpp import LlamaCppBackend
    import core.inference.llama_cpp as llama_cpp_module

    monkeypatch.setenv("HF_HUB_OFFLINE", "1")
    monkeypatch.setattr(llama_cpp_module, "_hub_download_in_flight", lambda hf_repo: False)
    monkeypatch.setattr(
        "huggingface_hub.list_repo_files",
        lambda repo, token = None: ["dflash-kquant-00001-of-00002.gguf"],
    )
    first = tmp_path / "dflash-kquant-00001-of-00002.gguf"
    first.write_bytes(b"x")
    monkeypatch.setattr(llama_cpp_module, "_cached_hf_snapshot_file", lambda *a, **k: str(first))

    def _offline_fetch(*_args, **_kwargs):
        raise RuntimeError("offline mode is enabled")

    monkeypatch.setattr(llama_cpp_module, "hf_hub_download_with_xet_fallback", _offline_fetch)

    def _pick(names):
        return next((n for n in sorted(names) if Path(n).name.startswith("dflash-")), None)

    b = LlamaCppBackend()
    assert (
        b._download_companion_gguf(
            hf_repo = "org/repo", hf_token = None, pick = _pick, label = "DFlash drafter"
        )
        is None
    )

    (tmp_path / "dflash-kquant-00002-of-00002.gguf").write_bytes(b"y")
    assert b._download_companion_gguf(
        hf_repo = "org/repo", hf_token = None, pick = _pick, label = "DFlash drafter"
    ) == str(first)


def test_cached_dflash_lookup_skips_an_incomplete_split_set(tmp_path, monkeypatch):
    """A lone shard as --model-draft cannot open its siblings, so an incomplete split set is skipped."""
    from core.inference.llama_cpp import LlamaCppBackend

    snap = tmp_path / "snapshots" / "abc"
    snap.mkdir(parents = True)
    weight = _write_gguf(snap / "model-Q4_K_M.gguf", "llama")
    first = _write_gguf(snap / "dflash-kquant-00001-of-00002.gguf", "dflash")
    monkeypatch.setattr(
        "utils.models.model_config._iter_hf_cache_snapshots", lambda *a, **k: [snap]
    )

    b = LlamaCppBackend()
    assert b._cached_repo_dflash_drafter("org/repo", near_path = str(weight)) is None

    _write_gguf(snap / "dflash-kquant-00002-of-00002.gguf", "dflash")
    assert b._cached_repo_dflash_drafter("org/repo", near_path = str(weight)) == str(first)


def test_cached_dflash_lookup_falls_through_from_a_half_split_to_a_whole_one(tmp_path, monkeypatch):
    """A half set is skipped, not fatal, as the header check does; a whole sidecar loads."""
    from core.inference.llama_cpp import LlamaCppBackend

    snap = tmp_path / "snapshots" / "abc"
    snap.mkdir(parents = True)
    weight = _write_gguf(snap / "model-Q4_K_M.gguf", "llama")
    _write_gguf(snap / "dflash-kquant-Q8_0-00001-of-00002.gguf", "dflash")
    whole = _write_gguf(snap / "dflash-kquant-BF16.gguf", "dflash")
    monkeypatch.setattr(
        "utils.models.model_config._iter_hf_cache_snapshots", lambda *a, **k: [snap]
    )

    assert LlamaCppBackend()._cached_repo_dflash_drafter("org/repo", near_path = str(weight)) == str(
        whole
    )


# A dropped fetch must stay retryable; only 'repo publishes none' is permanent.


def _dflash_hub_download(tmp_path, monkeypatch, *, listing, fetch):
    """Drive _download_dflash through the real _download_companion_gguf, with only
    the two Hub calls stubbed out."""
    from core.inference.llama_cpp import LlamaCppBackend
    import core.inference.llama_cpp as llama_cpp_module

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr(
        LlamaCppBackend,
        "probe_server_capabilities",
        classmethod(lambda cls, binary = None: {"supports_dflash": True}),
    )
    monkeypatch.setattr(llama_cpp_module, "_hub_download_in_flight", lambda hf_repo: False)
    monkeypatch.setattr("huggingface_hub.list_repo_files", listing)
    monkeypatch.setattr(llama_cpp_module, "hf_hub_download_with_xet_fallback", fetch)
    # Unstubbed, the scan would answer from this machine's HF cache.
    monkeypatch.setattr("utils.models.model_config._iter_hf_cache_snapshots", lambda *a, **k: [])

    b = LlamaCppBackend()
    got = b._download_dflash(hf_repo = "org/repo", binary = "/fake/llama-server")
    return b, got


def _never_fetched(*_args, **_kwargs):
    raise AssertionError("nothing should be downloaded")


def test_download_dflash_asks_again_after_a_listing_that_never_answered(tmp_path, monkeypatch):
    """An unreachable Hub says nothing about the repo, so recording it as "publishes
    none" would strand the model without the sidecar it does publish."""

    def _listing(repo, token = None):
        raise ConnectionError("hub unreachable")

    b, got = _dflash_hub_download(tmp_path, monkeypatch, listing = _listing, fetch = _never_fetched)

    assert got is None
    assert b._dflash_sidecar_absent is False
    assert b._dflash_retry_needed is True


def test_download_dflash_asks_again_after_a_download_that_dropped(tmp_path, monkeypatch):
    """The listing names the file, so the repo does publish it; only the bytes are missing."""

    def _fetch(
        repo,
        filename,
        token,
        *,
        cancel_event = None,
        cache_dir = None,
    ):
        raise ConnectionError("connection reset")

    b, got = _dflash_hub_download(
        tmp_path,
        monkeypatch,
        listing = lambda repo, token = None: ["model-Q4_K_M.gguf", "dflash-kquant.gguf"],
        fetch = _fetch,
    )

    assert got is None
    assert b._dflash_sidecar_absent is False
    assert b._dflash_retry_needed is True


def test_download_dflash_does_not_ask_again_after_a_permanent_hub_error(tmp_path, monkeypatch):
    """Gone, gated or offline repos are final, since retrying would relaunch the same server."""

    class RepositoryNotFoundError(Exception):
        pass

    def _listing(repo, token = None):
        raise RepositoryNotFoundError("404")

    b, got = _dflash_hub_download(tmp_path, monkeypatch, listing = _listing, fetch = _never_fetched)

    assert got is None
    assert b._dflash_retry_needed is False


def test_download_dflash_does_not_ask_again_when_this_machine_is_the_problem(tmp_path, monkeypatch):
    """Disk-full or unwritable cache is final; classify by errno, since Hub network errors are OSError."""
    import errno

    def _fetch(
        repo,
        filename,
        token,
        *,
        cancel_event = None,
        cache_dir = None,
    ):
        raise OSError(errno.ENOSPC, "No space left on device")

    b, got = _dflash_hub_download(
        tmp_path,
        monkeypatch,
        listing = lambda repo, token = None: ["model-Q4_K_M.gguf", "dflash-kquant.gguf"],
        fetch = _fetch,
    )

    assert got is None
    assert b._dflash_retry_needed is False


def test_download_dflash_treats_a_header_rejection_as_settled(tmp_path, monkeypatch):
    """A header rejection is settled, not a dropped fetch: treating it as one reloads on every Apply."""

    def _fetch(
        repo,
        filename,
        token,
        *,
        cancel_event = None,
        cache_dir = None,
    ):
        return str(_write_gguf(tmp_path / filename, "llama"))

    b, got = _dflash_hub_download(
        tmp_path,
        monkeypatch,
        listing = lambda repo, token = None: ["model-Q4_K_M.gguf", "dflash-model-Q8_0.gguf"],
        fetch = _fetch,
    )

    assert got is None
    assert b._dflash_sidecar_absent is True
    assert b._dflash_retry_needed is False


def test_download_dflash_reaches_the_real_sidecar_behind_an_impostor(tmp_path, monkeypatch):
    """Rejecting an impostor removes only its name, so the real sidecar ranked behind it is fetched."""

    def _fetch(
        repo,
        filename,
        token,
        *,
        cancel_event = None,
        cache_dir = None,
    ):
        arch = "dflash" if filename == "dflash-kquant.gguf" else "llama"
        return str(_write_gguf(tmp_path / filename, arch))

    b, got = _dflash_hub_download(
        tmp_path,
        monkeypatch,
        listing = lambda repo, token = None: [
            "model-Q4_K_M.gguf",
            "dflash-model-Q8_0.gguf",
            "dflash-kquant.gguf",
        ],
        fetch = _fetch,
    )

    assert got == str(tmp_path / "dflash-kquant.gguf")
    assert b._dflash_retry_needed is False


def test_variant_plans_carry_every_shard_of_a_split_dflash_sidecar():
    """Loader refuses an incomplete split set, so planning shard 1 alone would lose DFlash."""
    plans = build_gguf_variant_plans(
        [
            _sib("model-Q4_K_M.gguf", 15_000, "main"),
            _sib("dflash-kquant-00001-of-00002.gguf", 800, "d1"),
            _sib("dflash-kquant-00002-of-00002.gguf", 800, "d2"),
        ]
    )
    targets = set(plans["q4_k_m"].target_filenames)
    assert "dflash-kquant-00001-of-00002.gguf" in targets
    assert "dflash-kquant-00002-of-00002.gguf" in targets


def test_variant_plans_pair_dflash_with_the_weight_family_they_keep():
    """Pair the sidecar with the family _one_shard_family keeps, not the first listed weight."""
    plans = build_gguf_variant_plans(
        [
            _sib("QwQ-32B.BF16-00001-of-00002.gguf", 30_000, "b1"),
            _sib("QwQ-32B.BF16-00002-of-00002.gguf", 30_000, "b2"),
            _sib("QwQ-32B-BF16-00001-of-00002.gguf", 30_000, "a1"),
            _sib("QwQ-32B-BF16-00002-of-00002.gguf", 30_000, "a2"),
            _sib("dflash-QwQ-32B-BF16-Q8_0.gguf", 2_000, "da"),
            _sib("dflash-QwQ-32B.BF16-Q8_0.gguf", 2_000, "db"),
        ]
    )
    plan = plans["bf16"]
    assert plan.main_filenames == frozenset(
        {"QwQ-32B-BF16-00001-of-00002.gguf", "QwQ-32B-BF16-00002-of-00002.gguf"}
    )
    assert "dflash-QwQ-32B-BF16-Q8_0.gguf" in plan.target_filenames
    assert "dflash-QwQ-32B.BF16-Q8_0.gguf" not in plan.target_filenames


def test_variant_plans_skip_a_dflash_prefixed_file_too_big_to_be_a_drafter():
    """dflash- is a prefix real weights carry and a listing cannot read architecture, so size is the
    only bound: a drafter is a few layers of its target and cannot outweigh it"""
    plans = build_gguf_variant_plans(
        [
            _sib("Qwen3.6-27B-Q4_K_M.gguf", 15_000, "main"),
            _sib("dflash-Qwen3.6-27B-BF16.gguf", 54_000, "impostor"),
        ]
    )
    plan = plans["q4_k_m"]
    assert "dflash-Qwen3.6-27B-BF16.gguf" not in plan.target_filenames
    assert plan.download_size_bytes == 15_000


def test_variant_plans_still_carry_the_published_dflash_sidecar():
    """The Muse-Glimmer shape the feature ships for stays planned."""
    plans = build_gguf_variant_plans(
        [
            _sib("Muse-Glimmer-30B-UD-Q4_K_XL.gguf", 15_878, "main"),
            _sib("mmproj-kquant.gguf", 1_400, "mmproj"),
            _sib("dflash-kquant.gguf", 1_631, "dflash"),
        ]
    )
    assert "dflash-kquant.gguf" in plans["ud-q4_k_xl"].target_filenames


def test_download_dflash_skips_a_root_weight_too_big_to_be_a_drafter(monkeypatch, tmp_path):
    """Runtime picker needs the plan's size bound: a root dflash-*.gguf weight passes the name test,
    and the header only answers once the whole object is on disk"""
    from core.inference.llama_cpp import LlamaCppBackend

    weight = tmp_path / "Qwen3.6-27B-Q4_K_M.gguf"
    weight.write_bytes(b"x" * 4_000)
    monkeypatch.setattr(
        LlamaCppBackend,
        "_remote_root_gguf_sizes",
        staticmethod(
            lambda repo, token = None: {
                "dflash-Qwen3.6-27B-BF16.gguf": 40_000,
                "dflash-kquant.gguf": 500,
            }
        ),
    )
    picked = _dflash_download_pick(
        monkeypatch,
        listing = ["Qwen3.6-27B-Q4_K_M.gguf", "dflash-Qwen3.6-27B-BF16.gguf", "dflash-kquant.gguf"],
        near_path = str(weight),
    )
    assert picked == "dflash-kquant.gguf"


def test_download_companion_refuses_a_listing_missing_part_of_a_split_set(monkeypatch):
    """Download refuses a half split set, not returning shard 1 that llama-server cannot open."""
    from core.inference.llama_cpp import LlamaCppBackend
    import core.inference.llama_cpp as llama_cpp_module
    import huggingface_hub

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr(
        llama_cpp_module, "_companion_snapshot_sibling", lambda near_path, pick: None
    )
    # _download_companion_gguf imports list_repo_files locally, so patch at the source.

    monkeypatch.setattr(
        huggingface_hub,
        "list_repo_files",
        lambda repo, token = None: ["dflash-kquant-00001-of-00002.gguf"],
    )
    downloads: list = []
    monkeypatch.setattr(
        llama_cpp_module,
        "hf_hub_download_with_xet_fallback",
        lambda *a, **k: downloads.append(a) or "/tmp/x.gguf",
        raising = False,
    )
    b = LlamaCppBackend()
    got = b._download_companion_gguf(
        hf_repo = "org/repo",
        hf_token = None,
        pick = lambda files: next(iter(files), None),
        label = "DFlash drafter",
    )
    assert got is None
    assert downloads == []


def test_variant_plans_skip_a_half_published_split_sidecar():
    """Planning a half-listed split set reports it complete, then the loader refuses it."""
    plans = build_gguf_variant_plans(
        [
            _sib("model-Q4_K_M.gguf", 15_000, "main"),
            _sib("dflash-kquant-00001-of-00002.gguf", 800, "d1"),
        ]
    )
    assert not [f for f in plans["q4_k_m"].target_filenames if f.startswith("dflash-")]


def test_variant_plans_fall_through_to_a_usable_sidecar_behind_an_oversized_one():
    """Filters run before ranking, so a top impostor steps aside instead of sinking the plan."""
    plans = build_gguf_variant_plans(
        [
            _sib("model-B-Q4_K_M.gguf", 15_000, "main"),
            _sib("dflash-model-B-BF16.gguf", 54_000, "impostor"),
            _sib("dflash-kquant.gguf", 900, "real"),
        ]
    )
    targets = plans["q4_k_m"].target_filenames
    assert "dflash-kquant.gguf" in targets
    assert "dflash-model-B-BF16.gguf" not in targets


def test_download_dflash_sums_a_split_family_before_the_size_bound(monkeypatch, tmp_path):
    """Each shard of a split ordinary weight can sit under the target while the set
    does not, so bounding the picked shard alone still fetched the whole thing."""
    from core.inference.llama_cpp import LlamaCppBackend

    weight = tmp_path / "model-Q4_K_M.gguf"
    weight.write_bytes(b"x" * 10_000)
    monkeypatch.setattr(
        LlamaCppBackend,
        "_remote_root_gguf_sizes",
        staticmethod(
            lambda repo, token = None: {
                "dflash-big-00001-of-00002.gguf": 6_000,
                "dflash-big-00002-of-00002.gguf": 6_000,
                "dflash-kquant.gguf": 500,
            }
        ),
    )
    picked = _dflash_download_pick(
        monkeypatch,
        listing = [
            "model-Q4_K_M.gguf",
            "dflash-big-00001-of-00002.gguf",
            "dflash-big-00002-of-00002.gguf",
            "dflash-kquant.gguf",
        ],
        near_path = str(weight),
    )
    assert picked == "dflash-kquant.gguf"


def test_download_companion_records_an_incomplete_listing_as_settled():
    """The completeness rejection lands after outcome["listed"] was set true, so
    without this the caller reads a settled answer as one worth retrying forever."""
    from core.inference.llama_cpp import LlamaCppBackend
    import core.inference.llama_cpp as llama_cpp_module
    import huggingface_hub

    import pytest as _pytest

    mp = _pytest.MonkeyPatch()
    try:
        mp.delenv("HF_HUB_OFFLINE", raising = False)
        mp.setattr(llama_cpp_module, "_companion_snapshot_sibling", lambda near_path, pick: None)
        mp.setattr(
            huggingface_hub,
            "list_repo_files",
            lambda repo, token = None: ["dspark-kquant-00001-of-00002.gguf"],
        )
        outcome: dict = {}
        got = LlamaCppBackend()._download_companion_gguf(
            hf_repo = "org/repo",
            hf_token = None,
            pick = lambda files: next(iter(files), None),
            label = "DSpark drafter",
            outcome = outcome,
        )
    finally:
        mp.undo()
    assert got is None
    assert outcome.get("listed") is False


def test_download_dflash_reaches_the_complete_family_behind_an_incomplete_one(
    monkeypatch, tmp_path
):
    """A half-published shard makes _download_companion_gguf return None and end the loop."""
    from core.inference.llama_cpp import LlamaCppBackend

    weight = tmp_path / "model-B-Q4_K_M.gguf"
    weight.write_bytes(b"x" * 10_000)
    monkeypatch.setattr(
        LlamaCppBackend, "_remote_root_gguf_sizes", staticmethod(lambda repo, token = None: {})
    )
    picked = _dflash_download_pick(
        monkeypatch,
        listing = [
            "model-B-Q4_K_M.gguf",
            "dflash-model-B-00001-of-00002.gguf",
            "dflash-kquant.gguf",
        ],
        near_path = str(weight),
    )
    assert picked == "dflash-kquant.gguf"


def test_split_completeness_reads_shard_indices_not_a_shard_count():
    """Completeness uses shard indices: a stray 00003-of-00002 beside shard 1 hides missing shard 2."""
    from utils.models.drafters import split_listing_is_complete

    names = ["model-00001-of-00002.gguf", "model-00003-of-00002.gguf"]
    assert not split_listing_is_complete(names, names[0])
    dupes = ["dir/model-00001-of-00002.gguf", "dir/model-00001-of-00002.gguf"]
    assert not split_listing_is_complete(dupes, dupes[0])
    whole = ["model-00001-of-00002.gguf", "model-00002-of-00002.gguf"]
    assert split_listing_is_complete(whole, whole[0])


def test_split_completeness_is_scoped_to_the_files_own_directory():
    """Completeness is per directory: matching basenames across quant folders would pair unrelated
    halves."""
    from utils.models.drafters import split_listing_is_complete

    names = ["Q4/model-00001-of-00002.gguf", "Q8/model-00002-of-00002.gguf"]
    assert not split_listing_is_complete(names, names[0])
    assert not split_listing_is_complete(names, names[1])
    whole = ["Q4/model-00001-of-00002.gguf", "Q4/model-00002-of-00002.gguf"]
    assert split_listing_is_complete(whole, whole[0])


def _write_drafter_gguf(
    path: Path,
    *,
    tensors: list[str],
    arch: str = "qwen35",
    shared: bool = False,
    split_count: int = 0,
) -> Path:
    import numpy as np
    from gguf import GGUFWriter

    writer = GGUFWriter(str(path), arch)
    if shared:
        writer.add_bool(f"{arch}.nextn_shared_target_tensors", True)
    if split_count:
        writer.add_uint16("split.count", split_count)
    for name in tensors:
        writer.add_tensor(name, np.zeros((2, 2), dtype = np.float32))
    writer.write_header_to_file()
    writer.write_kv_data_to_file()
    writer.write_tensors_to_file()
    writer.close()
    return path


_HEAD_EXTRACT = ["output.weight", "blk.64.attn_norm.weight", "blk.64.nextn.eh_proj.weight"]


@pytest.mark.parametrize(
    "tensors,shared,expected",
    [
        (_HEAD_EXTRACT, False, False),
        (["token_embd.weight", "output_norm.weight", *_HEAD_EXTRACT], False, True),
        (_HEAD_EXTRACT, True, True),
    ],
)
def test_mtp_drafter_loads_standalone(tmp_path, tensors, shared, expected):
    from core.inference.llama_cpp import _mtp_drafter_loads_standalone
    drafter = _write_drafter_gguf(tmp_path / "mtp-model.gguf", tensors = tensors, shared = shared)
    assert _mtp_drafter_loads_standalone(str(drafter)) is expected


def test_a_lone_file_claiming_to_be_a_split_set_is_still_judged(tmp_path):
    """split.count alone is no exemption: llama-server opens shards by filename, so judge the lone file."""
    from core.inference.llama_cpp import _mtp_drafter_loads_standalone

    drafter = _write_drafter_gguf(tmp_path / "mtp-model.gguf", tensors = _HEAD_EXTRACT, split_count = 2)
    assert _mtp_drafter_loads_standalone(str(drafter)) is False


def test_a_complete_split_drafter_is_judged_across_every_shard(tmp_path):
    """Shard 1 need not list every tensor, so the whole set answers, as for cls.*."""
    from core.inference.llama_cpp import _mtp_drafter_loads_standalone

    _write_drafter_gguf(
        tmp_path / "mtp-model-00001-of-00002.gguf", tensors = _HEAD_EXTRACT, split_count = 2
    )
    _write_drafter_gguf(
        tmp_path / "mtp-model-00002-of-00002.gguf",
        tensors = ["token_embd.weight"],
        split_count = 2,
    )
    assert _mtp_drafter_loads_standalone(str(tmp_path / "mtp-model-00001-of-00002.gguf")) is True

    headless = tmp_path / "headless"
    headless.mkdir()
    _write_drafter_gguf(
        headless / "mtp-model-00001-of-00002.gguf", tensors = _HEAD_EXTRACT, split_count = 2
    )
    _write_drafter_gguf(
        headless / "mtp-model-00002-of-00002.gguf",
        tensors = ["blk.65.nextn.eh_proj.weight"],
        split_count = 2,
    )
    assert _mtp_drafter_loads_standalone(str(headless / "mtp-model-00001-of-00002.gguf")) is False


def test_an_incomplete_split_drafter_fails_open(tmp_path):
    """A shard that is not here could hold the embeddings, so llama-server decides."""
    from core.inference.llama_cpp import _mtp_drafter_loads_standalone

    lone = _write_drafter_gguf(
        tmp_path / "mtp-model-00001-of-00003.gguf", tensors = _HEAD_EXTRACT, split_count = 3
    )
    assert _mtp_drafter_loads_standalone(str(lone)) is True


def test_the_drafter_verdict_is_cached_per_file_version(tmp_path):
    """The estimate route asks on every settings change; it must not reparse each time."""
    from core.inference.llama_cpp import _mtp_drafter_loads_standalone
    from utils.models import gguf_metadata

    drafter = _write_drafter_gguf(tmp_path / "mtp-model.gguf", tensors = _HEAD_EXTRACT)
    calls: list[str] = []
    real = gguf_metadata._parse_gguf_has_named_tensor

    def counting(path, wanted_name):
        calls.append(path)
        return real(path, wanted_name)

    gguf_metadata._parse_gguf_has_named_tensor = counting
    try:
        assert _mtp_drafter_loads_standalone(str(drafter)) is False
        assert _mtp_drafter_loads_standalone(str(drafter)) is False
        assert _mtp_drafter_loads_standalone(str(drafter)) is False
        assert len(calls) == 1

        _write_drafter_gguf(
            tmp_path / "mtp-model.gguf", tensors = ["token_embd.weight", *_HEAD_EXTRACT]
        )
        assert _mtp_drafter_loads_standalone(str(drafter)) is True
    finally:
        gguf_metadata._parse_gguf_has_named_tensor = real


def test_mtp_drafter_loads_standalone_fails_open_on_an_unreadable_header(tmp_path):
    """A refusal that rejects working input is worse than the crash it prevents."""
    from core.inference.llama_cpp import _mtp_drafter_loads_standalone

    junk = tmp_path / "mtp-model.gguf"
    junk.write_bytes(b"not a gguf")
    assert _mtp_drafter_loads_standalone(str(junk))
    assert _mtp_drafter_loads_standalone(str(tmp_path / "missing.gguf"))


def test_mtp_drafter_loads_standalone_needs_only_token_embd(tmp_path):
    from core.inference.llama_cpp import _mtp_drafter_loads_standalone
    drafter = _write_drafter_gguf(
        tmp_path / "mtp-model.gguf",
        tensors = ["token_embd.weight", "output.weight", "blk.48.nextn.eh_proj.weight"],
        arch = "qwen4exp",
    )
    assert _mtp_drafter_loads_standalone(str(drafter))


# #13511: a NeoX DFlash drafter cannot follow an M-RoPE image, so Auto keeps vision without it.


def _gguf_header(path, arch, kv):
    import struct

    entries = [("general.architecture", arch), *kv.items()]
    out = [struct.pack("<IIQQ", 0x46554747, 3, 0, len(entries))]
    for key, val in entries:
        out.append(struct.pack("<Q", len(key)) + key.encode())
        if isinstance(val, str):
            out.append(struct.pack("<IQ", 8, len(val)) + val.encode())
        elif isinstance(val, bool):
            out.append(struct.pack("<I?", 7, val))
        elif isinstance(val, list):
            out.append(struct.pack("<IIQ", 9, 5, len(val)) + struct.pack(f"<{len(val)}i", *val))
        else:
            out.append(struct.pack("<II", 4, val))
    path.write_bytes(b"".join(out))
    return str(path)


@pytest.fixture
def vision_files(tmp_path):
    return {
        "mrope_model": _gguf_header(
            tmp_path / "Qwen3.8-27B-Q4_K_M.gguf",
            "qwen35",
            {"qwen35.rope.dimension_sections": [11, 11, 10, 0], "qwen35.block_count": 64},
        ),
        "neox_model": _gguf_header(
            tmp_path / "Muse-30B-Q4_K_M.gguf", "llama", {"llama.block_count": 2}
        ),
        "neox_dflash": _gguf_header(
            tmp_path / "dflash-Qwen3.8-27B-BF16.gguf",
            "dflash",
            {"dflash.rope.freq_base_u": 1, "tokenizer.ggml.pre": "qwen35"},
        ),
        "mrope_dflash": _gguf_header(
            tmp_path / "dflash-mrope.gguf",
            "dflash",
            {"dflash.rope.dimension_sections": [11, 11, 10, 0]},
        ),
        "zero_dflash": _gguf_header(
            tmp_path / "dflash-zero.gguf",
            "dflash",
            {"dflash.rope.dimension_sections": [0, 0, 0, 0]},
        ),
        "image_mmproj": _gguf_header(
            tmp_path / "mmproj-F16.gguf", "clip", {"clip.has_vision_encoder": True}
        ),
        "audio_mmproj": _gguf_header(
            tmp_path / "mmproj-audio.gguf",
            "clip",
            {"clip.has_vision_encoder": False, "clip.has_audio_encoder": True},
        ),
    }


def test_mrope_sections_reader(vision_files, tmp_path):
    from utils.models.gguf_metadata import gguf_has_mrope_sections

    assert gguf_has_mrope_sections(vision_files["mrope_model"]) is True
    assert gguf_has_mrope_sections(vision_files["mrope_dflash"]) is True
    assert gguf_has_mrope_sections(vision_files["neox_dflash"]) is False
    assert gguf_has_mrope_sections(vision_files["zero_dflash"]) is False
    assert gguf_has_mrope_sections(vision_files["neox_model"]) is False
    # Another namespace's sections are not this architecture's.
    other = _gguf_header(
        tmp_path / "other.gguf", "dflash", {"qwen35.rope.dimension_sections": [1, 1, 1, 0]}
    )
    assert gguf_has_mrope_sections(other) is False
    garbage = tmp_path / "garbage.gguf"
    garbage.write_bytes(b"not a gguf at all")
    assert gguf_has_mrope_sections(str(garbage)) is None
    truncated = tmp_path / "truncated.gguf"
    truncated.write_bytes(Path(vision_files["mrope_model"]).read_bytes()[:40])
    assert gguf_has_mrope_sections(str(truncated)) is None
    assert gguf_has_mrope_sections(str(tmp_path / "missing.gguf")) is None


@pytest.mark.parametrize(
    "model, dflash, mmproj, expected",
    [
        ("mrope_model", "neox_dflash", "image_mmproj", True),
        ("mrope_model", "zero_dflash", "image_mmproj", True),
        ("mrope_model", "mrope_dflash", "image_mmproj", False),
        ("neox_model", "neox_dflash", "image_mmproj", False),
        ("mrope_model", "neox_dflash", "audio_mmproj", False),
        ("mrope_model", "neox_dflash", None, False),
        ("mrope_model", "missing", "image_mmproj", False),
    ],
)
def test_dflash_drafter_breaks_on_images(vision_files, tmp_path, model, dflash, mmproj, expected):
    from core.inference.llama_cpp import _dflash_drafter_breaks_on_images
    files = {**vision_files, "missing": str(tmp_path / "missing.gguf")}
    assert (
        _dflash_drafter_breaks_on_images(
            files[model], files[dflash], files[mmproj] if mmproj else None
        )
        is expected
    )


def test_auto_skips_neox_dflash_on_an_mrope_vision_load(monkeypatch, vision_files):
    seen = _dflash_fetch_during_auto_load(
        monkeypatch,
        supports_dspark = False,
        supports_dflash = True,
        dspark_cached = None,
        model_file = vision_files["mrope_model"],
        dflash_file = vision_files["neox_dflash"],
        mmproj_file = vision_files["image_mmproj"],
    )
    assert seen["dflash_fetched"] is True
    assert seen["dflash_promoted"] is False
    assert any("no M-RoPE sections" in m for m in seen["log"])


@pytest.mark.parametrize(
    "dflash, mmproj, model, disable_vision",
    [
        ("mrope_dflash", "image_mmproj", "mrope_model", False),
        ("neox_dflash", "image_mmproj", "neox_model", False),
        ("neox_dflash", "audio_mmproj", "mrope_model", False),
        ("neox_dflash", None, "mrope_model", False),
        ("neox_dflash", "image_mmproj", "mrope_model", True),
    ],
)
def test_auto_keeps_dflash_when_images_cannot_break_it(
    monkeypatch, vision_files, dflash, mmproj, model, disable_vision
):
    seen = _dflash_fetch_during_auto_load(
        monkeypatch,
        supports_dspark = False,
        supports_dflash = True,
        dspark_cached = None,
        model_file = vision_files[model],
        dflash_file = vision_files[dflash],
        mmproj_file = vision_files[mmproj] if mmproj else None,
        disable_vision = disable_vision,
    )
    assert seen["dflash_promoted"] is True


def test_forced_dflash_on_an_mrope_vision_load_still_launches_and_warns(monkeypatch, vision_files):
    seen = _dflash_fetch_during_auto_load(
        monkeypatch,
        supports_dspark = False,
        supports_dflash = True,
        dspark_cached = None,
        speculative_type = "dflash",
        model_file = vision_files["mrope_model"],
        dflash_file = vision_files["neox_dflash"],
        mmproj_file = vision_files["image_mmproj"],
    )
    assert seen["dflash_fetched"] is True
    assert any("DFlash forced" in m for m in seen["warnings"])


@pytest.mark.parametrize(
    "listing, sized",
    [
        (["model-Q4_K_M.gguf", "mmproj-F16.gguf", "MTP/mtp-model.gguf"], False),
        (["model-Q4_K_M.gguf", "sub/dflash-model.gguf"], False),
        (["model-Q4_K_M.gguf", "dflash-model-00001-of-00002.gguf"], False),
        (["model-Q4_K_M.gguf", "dflash-model.gguf"], True),
    ],
)
def test_download_dflash_asks_the_hub_for_sizes_only_with_a_candidate(
    monkeypatch, tmp_path, listing, sized
):
    """No eligible root sidecar, no model_info(files_metadata=True) call."""
    from core.inference.llama_cpp import LlamaCppBackend

    weight = tmp_path / "model-Q4_K_M.gguf"
    weight.write_bytes(b"x" * 10_000)
    calls = []

    def _sizes(repo, token = None):
        calls.append(repo)
        return {}

    monkeypatch.setattr(LlamaCppBackend, "_remote_root_gguf_sizes", staticmethod(_sizes))
    picked = _dflash_download_pick(monkeypatch, listing = listing, near_path = str(weight))
    assert picked == ("dflash-model.gguf" if sized else None)
    assert len(calls) == (1 if sized else 0)


def _dflash_snapshot_load(
    monkeypatch,
    tmp_path,
    files,
    weight,
    *,
    hub_sizes = True,
):
    """``files``: name -> (architecture, bytes, on disk); the Hub lists them all or answers nothing."""
    from core.inference.llama_cpp import LlamaCppBackend

    snap = tmp_path / "models--org--repo" / "snapshots" / "abc"
    snap.mkdir(parents = True)
    for name, (arch, size, on_disk) in files.items():
        if on_disk:
            path = _write_gguf(snap / name, arch)
            with open(path, "ab") as fh:
                fh.write(b"\0" * (size - path.stat().st_size))
    calls: list = []

    def _sizes(repo, token = None):
        calls.append(repo)
        return {name: size for name, (_, size, _) in files.items()} if hub_sizes else {}

    monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)
    monkeypatch.setattr(LlamaCppBackend, "_remote_root_gguf_sizes", staticmethod(_sizes))
    monkeypatch.setattr(
        LlamaCppBackend,
        "probe_server_capabilities",
        classmethod(lambda cls, binary = None: {"supports_dflash": True}),
    )

    def _fake_companion(
        *,
        pick,
        outcome = None,
        **_,
    ):
        target = pick(list(files))
        return str(snap / target) if target and (snap / target).is_file() else None

    b = LlamaCppBackend()
    b._download_companion_gguf = _fake_companion
    got = b._download_dflash(
        hf_repo = "org/repo", near_path = str(snap / weight), binary = "/fake/llama-server"
    )
    return (got and Path(got).relative_to(snap).as_posix()), len(calls)


def test_download_dflash_reuses_a_cached_sidecar_without_asking_the_hub_for_sizes(
    monkeypatch, tmp_path
):
    """An unreachable Hub not flagged offline otherwise stalls the load until the client timeout."""
    files = {
        "model-Q4_K_M.gguf": ("llama", 100_000, True),
        "dflash-kquant.gguf": ("dflash", 2_000, True),
    }
    got, hub_calls = _dflash_snapshot_load(monkeypatch, tmp_path, files, "model-Q4_K_M.gguf")
    assert got == "dflash-kquant.gguf"
    assert hub_calls == 0


_D, _L = "dflash", "llama"


@pytest.mark.parametrize("hub_sizes", [True, False], ids = ["hub-answers", "hub-down"])
@pytest.mark.parametrize(
    "weight, files, expected, expected_calls",
    [
        # Picks and model_info calls as (Hub answers, Hub down).
        pytest.param(
            "model-Q4_K_M-00001-of-00002.gguf",
            {
                "model-Q4_K_M-00001-of-00002.gguf": (_L, 3_000, True),
                "model-Q4_K_M-00002-of-00002.gguf": (_L, 3_000, True),
                "dflash-kquant.gguf": (_D, 5_000, True),
            },
            ("dflash-kquant.gguf", "dflash-kquant.gguf"),
            (0, 0),
            id = "split-target",
        ),
        pytest.param(
            "model-Q4_K_M.gguf",
            {
                "model-Q4_K_M.gguf": (_L, 100_000, True),
                "dflash-kquant-00001-of-00002.gguf": (_D, 2_000, True),
                "dflash-kquant-00002-of-00002.gguf": (_D, 2_000, True),
            },
            ("dflash-kquant-00001-of-00002.gguf", "dflash-kquant-00001-of-00002.gguf"),
            (0, 0),
            id = "local-split",
        ),
        pytest.param(
            "model-Q4_K_M.gguf",
            {
                "model-Q4_K_M.gguf": (_L, 100_000, True),
                "dflash-kquant-00001-of-00002.gguf": (_D, 2_000, True),
                "dflash-kquant-00002-of-00002.gguf": (_D, 2_000, False),
            },
            ("dflash-kquant-00001-of-00002.gguf", "dflash-kquant-00001-of-00002.gguf"),
            (1, 1),
            id = "local-split-incomplete",
        ),
        pytest.param(
            "model-B-Q4_K_M.gguf",
            {
                "model-A-Q4_K_M.gguf": (_L, 100_000, True),
                "model-B-Q4_K_M.gguf": (_L, 100_000, True),
                "dflash-model-A-Q8_0.gguf": (_D, 2_000, True),
                "dflash-kquant.gguf": (_D, 2_000, True),
            },
            ("dflash-kquant.gguf", "dflash-kquant.gguf"),
            (0, 0),
            id = "mixed-families",
        ),
        pytest.param(
            "model-Q4_K_M.gguf",
            {
                "model-Q4_K_M.gguf": (_L, 4_000, True),
                "dflash-model-BF16.gguf": (_D, 40_000, True),
                "dflash-kquant.gguf": (_D, 500, True),
            },
            # An unanswered size request keeps every candidate, as before.
            ("dflash-kquant.gguf", "dflash-model-BF16.gguf"),
            (1, 1),
            id = "oversize",
        ),
        pytest.param(
            "model-Q4_K_M.gguf",
            {
                "model-Q4_K_M.gguf": (_L, 10_000, True),
                "dflash-big-00001-of-00002.gguf": (_D, 6_000, True),
                "dflash-big-00002-of-00002.gguf": (_D, 6_000, True),
            },
            (None, "dflash-big-00001-of-00002.gguf"),
            (1, 1),
            id = "split-set-over-the-bound",
        ),
        pytest.param(
            "model-Q4_K_M.gguf",
            {
                "model-Q4_K_M.gguf": (_L, 100_000, True),
                "dflash-model-Q4_K_M.gguf": (_L, 2_000, True),
                "dflash-kquant.gguf": (_D, 2_000, True),
            },
            ("dflash-kquant.gguf", "dflash-kquant.gguf"),
            (0, 0),
            id = "impostor",
        ),
        pytest.param(
            "model-Q4_K_M.gguf",
            {
                "model-Q4_K_M.gguf": (_L, 100_000, True),
                "dflash-kquant.gguf": (_D, 2_000, False),
            },
            (None, None),
            (1, 1),
            id = "not-cached",
        ),
    ],
)
def test_download_dflash_local_sizes_keep_the_hub_sized_picks(
    monkeypatch, tmp_path, weight, files, expected, expected_calls, hub_sizes
):
    """Picks match the Hub-sized scan; only a bound dropping an on-disk file asks, at most once."""
    got, hub_calls = _dflash_snapshot_load(
        monkeypatch, tmp_path, files, weight, hub_sizes = hub_sizes
    )
    assert got == expected[0 if hub_sizes else 1]
    assert hub_calls == expected_calls[0 if hub_sizes else 1]