# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Warm turbo-attn's decode split-K autotune before cudagraph capture.

Because the decode kernel is captured into a cudagraph, an unwarmed autotune
table makes the dispatcher fall to ``_static_splits_heuristic`` — a
context-blind, fixed split count — and that config is then frozen into the
captured graph for the life of the server. Warming the table before capture
lets the graph bake the autotuned-optimal split config instead, so every
later decode is a warm-table cache hit.

This module assembles a :class:`tkv.runtime.autotune.WarmLayerSpec` from each
per-layer :class:`~arbi_serve.backends.tkv_backend.TkvAttnOp` (its installed
codec + byte layout) and the pool's live per-layer slab, dedups by
``(k_bw, v_bw)`` (so a smart-mix bundle's N combos each sweep once), and calls
the shared engine-agnostic ``warm_autotune_layers``. That also force-compiles
the per-(gqa, bits) decode/.compress-store ``.so`` so smart-mix layers never
JIT under capture (which can deadlock).

``mtp_block_ms`` carries the verify widths that reach the split-K register
kernel: the dispatchable set (:func:`_reachable_mtp_block_ms`) narrowed by
the route tkv RESOLVED (:func:`_plan_splitk_family`). The module is keyed by
``block_m`` and is compiled by no other boot path, so a width on that route
must be listed or the first verify batch JITs it under the request; a width
the Turbo prefill verify route owns must NOT be, because listing it spends
per-block_m nvcc builds and a measured split sweep on a kernel the process
never launches. A skipped width is guarded, not merely omitted — see
:mod:`arbi_serve.spec_decode.mtp_splitk_family`.

``warm_autotune_layers`` (turbo-attn >= 0.21.0) raises on a combo it cannot
pre-compile instead of warning and deferring it to the first request, and
returns per-combo coverage. So this module asserts ``loaded == reachable``
rather than reporting a reachable count it cannot confirm was loaded.

Wire-up: called once from the build path right before the cudagraph capture
sweep, after codecs are installed and the KV pool exists.
"""

from __future__ import annotations

import logging
import time
from collections.abc import Callable
from typing import Any

logger = logging.getLogger("arbi_serve.tkv")


class TkvWarmCoverageError(RuntimeError):
    """A reachable ``(k_bw, v_bw)`` combo was not pre-loaded at boot."""


def _is_already_actionable(exc: BaseException) -> bool:
    """True for errors that already name the variant and the operator action.

    turbo-attn's :class:`~tkv.runtime.autotune.WarmCompileError`, our own
    coverage mismatch and the split-K family refusals all already state
    exactly which combo or width failed and what to do about it. Re-wrapping
    any of them in the generic "unwarmed table" diagnosis below would bury
    that name behind the wrong cause.
    """
    from arbi_serve.spec_decode.mtp_splitk_family import SkippedSplitKFamilyRequested

    if isinstance(exc, TkvWarmCoverageError | SkippedSplitKFamilyRequested):
        return True
    # The family planner refuses a tree that resolved onto split-K by name;
    # it is not a sweep failure and must not be re-framed as one.
    if type(exc) is RuntimeError and "ancestors-only mask" in str(exc):
        return True
    try:
        from tkv.runtime.autotune import WarmCompileError
    except Exception:  # noqa: BLE001 — tkv absent: nothing to pass through
        return False
    return isinstance(exc, WarmCompileError)


def _combo_key(k_bw: Any, v_bw: Any, vq_k: Any, vq_v: Any) -> tuple[int, int, bool, bool]:
    """One pre-compile identity: the widths AND each side's codec family."""
    return (int(k_bw), int(v_bw), bool(vq_k), bool(vq_v))


def _reachable_combos(specs: list[Any]) -> set[tuple[int, int, bool, bool]]:
    """The distinct ``(k_bw, v_bw, vq_k, vq_v)`` combos this boot can dispatch.

    ``warm_autotune_layers`` dedups its pre-compile by exactly this key, so
    this set is the ``reachable`` side of the coverage assertion: every combo
    in it must come back in ``WarmResult.combos`` (the ``loaded`` side).

    The per-side quantizer family belongs in the key, not just the widths: a
    group-2 VQ side compiles a DIFFERENT kernel than the scalar Lloyd one at
    the same width, so a bundle that mixes them (K=vq2 everywhere, V=vq2 on
    one layer) is two reachable combos that a widths-only key would report as
    one — and a pre-load that built only the scalar of the pair would pass a
    coverage check it should have failed, leaving the miss to surface much
    later as a cache-miss abort under ``TKV_NO_JIT=1``.
    """
    return {
        _combo_key(
            s.k_bw,
            s.v_bw,
            getattr(s.ops, "vq_mode_k", False),
            getattr(s.ops, "vq_mode_v", False),
        )
        for s in specs
    }


def _assert_loaded_covers_reachable(
    reachable: set[tuple[int, int, bool, bool]], result: Any
) -> tuple[int, int]:
    """Fail loud unless every reachable combo was actually pre-loaded.

    Returns ``(n_loaded, n_variants)``. ``warm_autotune_layers`` raises on a
    combo it cannot pre-compile (turbo-attn >= 0.21.0), so a short
    ``result.combos`` is not a compile failure — it means the primitive
    silently skipped a combo serving can reach, i.e. the two sides disagree
    about what is reachable. That is the drift the counter exists to catch, so
    it must crash the boot rather than log a coverage number nobody checked.
    """
    # getattr for the family: WarmComboResult grew vq_k/vq_v alongside the
    # vq2 pre-bake, and an older turbo-attn reports every combo as scalar. A
    # vq2 boot on such a build then shows up here as a missing vq combo, which
    # is the truth — that build cannot bake the kernel the codec will request.
    loaded = {
        _combo_key(c.k_bw, c.v_bw, getattr(c, "vq_k", False), getattr(c, "vq_v", False))
        for c in result.combos
    }
    missing = reachable - loaded
    if missing:
        raise TkvWarmCoverageError(
            "TKV kernel pre-load coverage MISMATCH: "
            f"loaded={len(loaded)} of reachable={len(reachable)} combo(s); "
            f"NOT pre-loaded (k_bw, v_bw, vq_k, vq_v): {sorted(missing)}. "
            "Every reachable combo must be compiled before cudagraph capture — "
            "an uncompiled one JITs on the first request that needs it (a "
            "multi-second stall, and a deadlock under capture; under TKV_NO_JIT=1 "
            "it is a hard cache-miss abort instead). warm_autotune_layers "
            "raises on a combo it cannot build, so a missing combo means it never "
            "attempted this one: the reachable set arbi-serve derives and the set "
            "the primitive dedups by have drifted apart. A missing combo whose "
            "vq_k/vq_v is True on a bundle that declares a vq2 quantizer kind "
            "means this turbo-attn build pre-dates the vq2 pre-bake and cannot "
            "serve that bundle without JIT. Aborting boot."
        )
    # A combo loaded that we never called reachable is a derivation bug in the
    # OTHER direction — the pre-load is wasting a cold nvcc compile on a kernel
    # serving never requests. Not fatal (nothing serves slow), but it means one
    # of the two derivations is wrong; say so.
    extra = loaded - reachable
    if extra:
        logger.warning(
            "TKV kernel pre-load compiled %d combo(s) arbi-serve did not derive as "
            "reachable: %s — a wasted cold compile, and one of the two derivations "
            "is wrong.",
            len(extra),
            sorted(extra),
        )
    return len(loaded), sum(int(c.variants) for c in result.combos)


def _fingerprint_summary(specs: list[Any]) -> list[str]:
    """Human-readable per-``(k_bw, v_bw, vq_k, vq_v)`` fingerprint lines.

    ``warm_autotune_layers`` dedups the sweep by exactly this key, so the
    number of distinct fingerprints — not the layer count — is what drives
    the (potentially minutes-long) nvcc JIT. Each fingerprint compiles the
    per-(gqa, bits, family) decode + compress-store kernel variant set, so
    naming them up-front makes a long compile obvious in the boot log.
    """
    by_fp: dict[tuple[int, int, bool, bool], dict[str, Any]] = {}
    for s in specs:
        fp = _combo_key(
            s.k_bw,
            s.v_bw,
            getattr(s.ops, "vq_mode_k", False),
            getattr(s.ops, "vq_mode_v", False),
        )
        e = by_fp.setdefault(fp, {"n_layers": 0, "spec": s})
        e["n_layers"] += 1
    lines: list[str] = []
    for (k_bw, v_bw, vq_k, vq_v), e in sorted(by_fp.items()):
        s = e["spec"]
        gqa = int(s.num_heads) // max(1, int(s.num_kv_heads))
        codec = f", codec=K{'vq2' if vq_k else 'lloyd'}/V{'vq2' if vq_v else 'lloyd'}"
        lines.append(
            f"K{k_bw}/V{v_bw} bits{codec}, head_dim={int(s.head_size)}, "
            f"kv_heads={int(s.num_kv_heads)}, q_heads={int(s.num_heads)} "
            f"(gqa={gqa}), {e['n_layers']} layer(s)"
        )
    return lines


def _reachable_mtp_block_ms(eng) -> tuple[int, ...]:
    """MTP-verify ``block_m`` (= K+1) widths this boot can dispatch.

    Derived from the same inputs the verify cudagraph capture enumerates —
    :func:`arbi_serve.engine.cudagraph_admin._verify_s_set` over the MTP
    driver's ``max_k``, the tkv served ceiling, and
    ``cfg.mtp.capture_full_k_ladder`` — so the pre-compiled variant set and
    the captured verify set cannot drift. ``()`` when MTP is off.

    The MTP split-K module is block_m-specific and is not covered by the
    plain-decode variants: without these widths the first verify batch JITs
    the kernel on the request path. ``compile_decode_and_cs`` clamps each
    width to the split-K register ceiling — widths served by the Turbo prefill high-K
    route carry no split-K ``.so`` and are skipped there.

    This is the DISPATCHABLE set, not the set to compile: which of these
    widths actually reaches the split-K kernel is the routing question
    :func:`_plan_splitk_family` answers from the route tkv resolved.
    """
    driver = getattr(eng, "mtp_driver", None)
    if driver is None:
        return ()
    from arbi_serve.engine.cudagraph_admin import _verify_s_set
    from arbi_serve.spec_decode.k_calibration import tkv_max_verify_block_m

    full_ladder = bool(getattr(eng.cfg.mtp, "capture_full_k_ladder", False))
    return tuple(
        _verify_s_set(int(driver.max_k), tkv_max_verify_block_m(), full_ladder=full_ladder)
    )


def _decode_attends(eng) -> list[Any]:
    """The BUILT per-layer decode attend objects, if any core exists yet.

    ``TkvAttnOp`` builds its :class:`TKVCore` eagerly at boot, but a test
    double (and a layer whose codec is not installed) has none — those
    layers simply contribute no evidence, and the caller falls back to the
    flag-derived floor rather than assuming an answer nobody gave.
    """
    out: list[Any] = []
    for op in getattr(eng, "attn_ops", ()) or ():
        core = getattr(op, "_core", None)
        attend = getattr(core, "_decode_attend", None) if core is not None else None
        if attend is not None and callable(getattr(attend, "verify_routes_to_prefill", None)):
            out.append(attend)
    return out


def _confirm_prefill_floor(eng, widths: tuple[int, ...], floor: int) -> int:
    """Raise ``floor`` above any width a BUILT layer still keeps on split-K.

    ``tkv_prefill_verify_min_block_m`` answers for the process; this asks
    the resolved per-layer objects — ``DecodeAttend.verify_routes_to_prefill``
    is the same predicate the dispatch reads, so it also carries the
    conditions the process-level floor cannot see (a core with no prefill
    engine bound, a subclass that owns the verify body). A layer that
    declines at width ``w`` pushes the floor to ``w + 1``, which puts ``w``
    and everything under it back in the build set. Layers that cannot be
    asked leave the floor alone.
    """
    attends = _decode_attends(eng)
    if not attends:
        return floor
    for w in sorted(widths):
        if w < floor:
            continue
        for attend in attends:
            try:
                routes = bool(attend.verify_routes_to_prefill(int(w)))
            except Exception:  # noqa: BLE001 — an unaskable layer is not evidence
                continue
            if not routes:
                floor = w + 1
                break
    return floor


def _plan_splitk_family(eng, block_ms: tuple[int, ...]):
    """Which of ``block_ms`` still needs the block_m-keyed split-K family.

    The floor comes from tkv — :func:`tkv_prefill_verify_min_block_m` reads
    ``tkv.runtime.attention``'s own resolved rule — and is then confirmed
    against the built layers. Never from the environment: this side must
    not re-derive a routing decision the attention engine already made.
    """
    from arbi_serve.spec_decode.k_calibration import tkv_prefill_verify_min_block_m
    from arbi_serve.spec_decode.mtp_splitk_family import plan_splitk_family

    if not block_ms:
        return plan_splitk_family((), prefill_min_block_m=0)
    try:
        floor = int(tkv_prefill_verify_min_block_m())
    except Exception:  # noqa: BLE001 — unreadable route ⇒ build the family
        return plan_splitk_family(block_ms, prefill_min_block_m=max(block_ms) + 1)
    floor = _confirm_prefill_floor(eng, block_ms, floor)
    try:
        from arbi_serve.spec_decode.tree_spec import active_tree_spec

        tree_active = active_tree_spec() is not None
    except Exception:  # noqa: BLE001 — no tree module ⇒ chain verify
        tree_active = False
    return plan_splitk_family(block_ms, prefill_min_block_m=floor, tree_active=tree_active)


def _warm_cache_dir() -> str:
    """Best-effort path where tkv persists the compiled kernel .so + the
    autotune splits table (for the loud start line). The .so land in the
    torch_extensions build dir; the splits table under the tkv cache dir."""
    try:
        import os

        from torch.utils.cpp_extension import _get_build_directory

        so_dir = os.path.dirname(_get_build_directory("tkv_unified_splitk", False))
    except Exception:  # noqa: BLE001
        so_dir = "<torch_extensions>"
    return so_dir


def build_warm_specs(
    attn_ops: list[Any],
    slab_for_layer: Callable[[int], Any],
) -> list[Any]:
    """Assemble ``WarmLayerSpec`` per TKV attention layer.

    ``attn_ops`` is ``eng.attn_ops`` (mixed: only :class:`TkvAttnOp`
    entries with an installed codec are used). ``slab_for_layer(layer_idx)``
    maps a global layer index to its live packed-KV buffer (or ``None`` to
    skip) — the same global index the pool's ``layer_view`` keys on. Pure /
    engine-free so it can be unit-tested without standing up a full engine.
    """
    from tkv.runtime.autotune import WarmLayerSpec

    from arbi_serve.backends.tkv_backend import TkvAttnOp

    served_state = _served_layer_state_fields(WarmLayerSpec)
    specs: list[Any] = []
    for op in attn_ops:
        if not isinstance(op, TkvAttnOp):
            continue
        ops = getattr(op, "_ops", None)
        if ops is None:  # codec not installed yet -> cannot warm this layer
            continue
        slab = slab_for_layer(int(op.layer_idx))
        if slab is None:
            continue
        layout_offsets = _slab_layout_offsets(op, slab)
        specs.append(
            WarmLayerSpec(
                k_bw=int(op.k_bits),
                v_bw=int(op.v_bits),
                ops=ops,
                layout_offsets=layout_offsets,
                kv_cache=slab,
                head_size=int(op.head_dim),
                num_kv_heads=int(op.num_kv_heads),
                num_heads=int(op.num_heads),
                **served_state(op),
            )
        )
    return specs


def _slab_layout_offsets(op: Any, slab: Any) -> tuple:
    """The ``(k_packed_off, k_norm_off, v_packed_off, v_norm_off, k_pd, v_pd)``
    the slab holds. A slab sized at the pool's page size holds tkv's page-tail
    slots where those are smaller, and the serving Core rebinds to that layout
    at its first attend; the op's own offsets are the row layout's, so the
    tuning Core would otherwise time reads at offsets serving never uses."""
    from tkv.kernels.cuda_compress_store import layout_of_cache

    lay = layout_of_cache(slab, int(op.num_kv_heads), int(op.k_pd), int(op.v_pd))
    return (
        lay["k_packed_off"],
        lay["k_norm_off"],
        lay["v_packed_off"],
        lay["v_norm_off"],
        op.k_pd,
        op.v_pd,
    )


def _served_layer_state_fields(spec_cls: Any) -> Callable[[Any], dict[str, Any]]:
    """``op -> {field: value}`` for the served-layer state the warm keys on.

    Both select the decode kernels a layer launches, so a warm that does not
    see them builds kernels serving never runs and leaves the ones it does run
    to compile inside a request:

    * ``o_proj_folded`` -- a folded OSCAR layer runs the ``_oo0`` kernel, an
      unfolded one ``_oo1``;
    * ``ring`` -- the recent ring the layer's decode reads (None for none). A
      layer with one runs the ring build (``_rg1``) of whichever pick its
      table made, and turbo-attn sweeps and keys that table on the ring's
      window, so the ring itself is handed over, not whether there is one.

    Each is handed over only when the installed turbo-attn's spec declares
    it; an older spec builds exactly what it did before.
    """
    fields = set(getattr(spec_cls, "_fields", ()))

    def state(op: Any) -> dict[str, Any]:
        core = getattr(op, "_core", None)
        out: dict[str, Any] = {}
        if "o_proj_folded" in fields:
            out["o_proj_folded"] = bool(getattr(core, "_o_proj_folded", False))
        if "ring" in fields:
            out["ring"] = getattr(core, "_ring", None)
        return out

    return state


def _slab_resolver(eng) -> Callable[[int], Any]:
    """Return ``slab_for_layer(global_layer_idx)`` backed by the engine
    pool's ``layer_view`` — the same aliasing-aware accessor the runtime
    and cudagraph capture use to hand a layer its live per-layer KV view
    (honours Gemma-4 ``kv_source_layer`` sharing). Returns ``None`` for a
    layer the pool can't resolve (best-effort)."""
    pool = getattr(eng, "pool", None)
    layer_view = getattr(pool, "layer_view", None)
    if not callable(layer_view):
        return lambda _idx: None

    def resolve(global_idx: int):
        try:
            return layer_view(global_idx)
        except Exception:  # noqa: BLE001 — a non-paged / out-of-range layer
            return None

    return resolve


#: Progress-probe owner for the decode warm's compilers
#: (:func:`arbi_serve.engine.boot_heartbeat.register_progress_probe`).
TKV_DECODE_BUILD_PROBE = "tkv-decode-kernel-build"


def warm_tkv_decode_autotune(eng, *, device=None) -> int:
    """:func:`_warm_tkv_decode_autotune`, with its compilers reporting progress.

    The warm compiles turbo-attn's decode variant grid (the split-K SIMT and
    tensor-core mma bodies) and keeps no counter of its own, so between two
    finished extensions nothing in this process moves. The compilers' CPU time
    is the evidence (:mod:`arbi_serve.engine.compiler_progress`): it renews the
    wedge deadline while they work and stands still when they hang, and the
    probe names the variant in flight for the stall report. Registered only
    around the warm, so every other phase keeps the bound it had.
    """
    from arbi_serve.engine.boot_heartbeat import (
        register_progress_probe,
        unregister_progress_probe,
    )
    from arbi_serve.engine.compiler_progress import compiler_build_probe

    probe, describe = compiler_build_probe("turbo-attn decode kernels")
    register_progress_probe(TKV_DECODE_BUILD_PROBE, probe, describe=describe)
    try:
        swept = _warm_tkv_decode_autotune(eng, device=device)
    finally:
        unregister_progress_probe(TKV_DECODE_BUILD_PROBE)
    # Each rank swept (or read) its tables alone. Before the decode capture
    # freezes their picks, every rank takes the ones the tune dir holds.
    from arbi_serve.engine.capture_admin.boot_pick_consensus import agree_split_tables

    _diag_tables("before_consensus", int(swept))
    agree_split_tables(eng)
    _diag_tables("after_consensus", int(swept))
    return swept


def _warm_tkv_decode_autotune(eng, *, device=None) -> int:
    """Warm the tkv decode autotune for every served layer.

    Returns the number of distinct ``(k_bw, v_bw)`` fingerprints swept.
    Returns 0 — an explicit, by-design skip — only when there is nothing
    to warm: a prefill-only task, tkv not present, ``autotune_splits``
    disabled, no TKV attention layers, or no warmable specs. In those cases the static
    heuristic is the correct (and only) config, so the no-op is silent.

    If the sweep is required (there are warmable TKV specs) but the
    autotune fails, this boot-fails (raises). An unwarmed table freezes
    the context-blind ``_static_splits_heuristic`` into the captured
    decode graph for the life of the process — a permanent throughput
    loss invisible to the API caller. That degradation must crash the
    boot (``/health/ready`` stays 503), never warn-and-serve.

    Coverage is asserted, not assumed: every reachable ``(k_bw, v_bw)``
    combo must come back in ``WarmResult.combos``, or this raises
    :class:`TkvWarmCoverageError`. turbo-attn >= 0.21.0 raises on a combo
    it cannot pre-compile rather than deferring it to the first request,
    which is what makes ``loaded`` observable here at all — before that,
    this line could only report ``reachable`` and hope.
    """
    from arbi_serve.engine.serving_tasks import executes_local_decode

    if not executes_local_decode(eng):
        return 0  # a prefill-only task serves no decode step: no decode table to warm
    try:
        from tkv.config import tkv_flags
        from tkv.runtime.autotune import warm_autotune_layers
    except Exception:  # noqa: BLE001 — tkv not present
        return 0
    if not tkv_flags().autotune_splits:
        return 0
    attn_ops = getattr(eng, "attn_ops", None)
    if not attn_ops:
        return 0
    # Cap tkv's autotune batch grid at the deployment's --max-batch
    # (TKV_AUTOTUNE_MAX_BATCH, honoured by tkv >= 0.14.2's sweep; older
    # tkv ignores the env — graceful, no lockstep upgrade needed). The
    # sweep otherwise times batch cells up to 256 that this deployment can
    # never serve. ``setdefault`` so an operator-set value wins. Set here
    # — before the FIRST decode dispatch of the boot — so tkv's lazy
    # sweep path (should it ever fire) is capped too.
    _batch_cfg = getattr(getattr(eng, "cfg", None), "batch", None)
    try:
        _mb = int(getattr(_batch_cfg, "max_batch", 0) or 0)
    except (TypeError, ValueError):  # a test double without the field
        _mb = 0
    if _mb > 0:
        import os

        os.environ.setdefault("TKV_AUTOTUNE_MAX_BATCH", str(_mb))
    # Cap the seq-len buckets at the deployment's max context the same way:
    # buckets past it are sequence lengths no request can reach. The env, not
    # warm_autotune_layers' ``max_context_len``, because tkv's lazy
    # first-decode sweep reads only the env, and the kwarg would override an
    # operator-set value.
    _cache_cfg = getattr(getattr(eng, "cfg", None), "cache", None)
    try:
        _mc = int(getattr(_cache_cfg, "max_context", 0) or 0)
    except (TypeError, ValueError):  # a test double without the field
        _mc = 0
    if _mc > 0:
        import os

        os.environ.setdefault("TKV_AUTOTUNE_MAX_CONTEXT", str(_mc))
    if device is None:
        import torch

        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    try:
        specs = build_warm_specs(attn_ops, _slab_resolver(eng))
        if not specs:
            return 0
        fp_lines = _fingerprint_summary(specs)
        n_fp = len(fp_lines)
        reachable = _reachable_combos(specs)
        cache_dir = _warm_cache_dir()
        # Verify widths this boot can dispatch, narrowed to the ones whose
        # route actually reaches the split-K kernel. ``warm_autotune_layers``
        # spends BOTH the per-block_m nvcc builds and the measured MTP split
        # sweep on whatever this list carries, and neither is recoverable
        # afterwards (the sweep is capture-gated), so the list has to be the
        # served route's answer rather than the dispatchable set.
        dispatchable_block_ms = _reachable_mtp_block_ms(eng)
        plan = _plan_splitk_family(eng, dispatchable_block_ms)
        mtp_block_ms = plan.build
        if plan.skips_family:
            from arbi_serve.spec_decode.mtp_splitk_family import (
                arm_splitk_family_guard,
                splitk_family_skipped_counter,
            )

            # Receipt: one INFO line naming the widths, the resolved route
            # that owns them, and the flag that brings the family back.
            logger.info("%s", plan.receipt())
            splitk_family_skipped_counter().fired = 1
            # A width planned away must never JIT on the request path — refuse
            # it at tkv's accessor instead of deferring it silently.
            arm_splitk_family_guard(plan)
        from arbi_serve.engine.attn_path_reachability import reachability_receipt

        logger.info("%s", reachability_receipt(eng, plan, dispatchable_block_ms))
        # One label for both the start and the finish line, so a reader
        # cannot mistake "MTP is off" for "MTP is on and split-K is unused".
        if mtp_block_ms:
            bm_label = str(list(mtp_block_ms))
        elif dispatchable_block_ms:
            bm_label = f"none (Turbo prefill verify route owns {list(plan.skipped)})"
        else:
            bm_label = "none (MTP off)"
        # Start line: terse, facts only. A cache MISS runs a one-time nvcc JIT
        # (minutes, GPU idle — NOT a hang); kernels cache to ``cache_dir``.
        logger.info(
            "TKV warm-autotune: %d fp × %d layers, MTP verify block_m=%s "
            "(miss → 1-time nvcc JIT, GPU idle, NOT a hang → %s)",
            n_fp,
            len(specs),
            bm_label,
            cache_dir,
        )
        for i, line in enumerate(fp_lines, 1):
            logger.info("TKV warm-autotune fingerprint %d/%d: %s", i, n_fp, line)

        t0 = time.monotonic()
        # WarmResult.swept = fingerprints FRESHLY swept (cache hits are not
        # counted, so hits = total - swept). WarmResult.combos = the per-combo
        # pre-load coverage; presence IS success (the primitive raises on a
        # combo it cannot build), which is what makes `loaded` observable at
        # all. Requires turbo-attn >= 0.21.0 — enforced by uv.lock + the
        # backend-version guard, not by a getattr probe here.
        result = warm_autotune_layers(
            specs,
            device=device,
            label="arbi-serve",
            mtp_block_ms=mtp_block_ms or None,
        )
        elapsed = time.monotonic() - t0

        n_loaded, n_variants = _assert_loaded_covers_reachable(reachable, result)
        n_swept = int(result.swept)
        n_hits = max(0, n_fp - n_swept)
        logger.info(
            "TKV warm-autotune complete: %d fp × %d layers, MTP verify block_m=%s "
            "— loaded %d/%d combo(s) (%d kernel variants), %d swept, %d cache-hit, %.1fs",
            n_fp,
            len(specs),
            bm_label,
            n_loaded,
            len(reachable),
            n_variants,
            n_swept,
            n_hits,
            elapsed,
        )
        return n_swept
    except Exception as e:
        # Already-named failures (a turbo-attn pre-compile refusal, our own
        # coverage mismatch) propagate VERBATIM: they name the combo and the
        # fix, and both already boot-fail. Re-wrapping them would misdiagnose
        # a compile refusal as an unwarmed table.
        if _is_already_actionable(e):
            raise
        # A warmable-spec set exists but the sweep failed — this is a real
        # capture-quality failure that costs throughput for the LIFE of the
        # process (the static heuristic gets frozen into the captured decode
        # graph). Boot-fail loudly so the degradation is client-visible
        # (process crashes / readiness stays 503), never a silent serve.
        raise RuntimeError(
            "TKV decode-kernel warm-autotune FAILED for a config with "
            "warmable TKV layers. An unwarmed table bakes the context-blind "
            "static-splits heuristic into the captured decode graph for the "
            "life of the server (permanent throughput loss, invisible to the "
            f"API caller) — aborting boot instead of serving degraded. Cause: {e}"
        ) from e


def _diag_tables(where: str, swept: int) -> None:
    """DIAGNOSTIC (two-boot determinism): each rank's in-memory split tables against the files on disk, one JSON line."""
    try:
        import hashlib as _h, json as _j, os as _o, time as _t
        from tkv.runtime import autotune as _AT
        from tkv.runtime._autotune_cache import _autotune_cache_path, _fingerprint_sha8
        rank = _o.environ.get("RANK", _o.environ.get("LOCAL_RANK", "x"))
        out = []
        for name in ("_AUTOTUNE_TABLES", "_MTP_AUTOTUNE_TABLES"):
            for _fp, _tab in list(getattr(_AT, name, {}).items()):
                try:
                    _mem = {":".join(str(x) for x in k): list(v) for k, v in sorted(_tab.items())}
                except Exception as _e:  # noqa: BLE001
                    _mem = repr(_tab)[:2000]
                _disk = None
                if name == "_AUTOTUNE_TABLES":
                    try:
                        _disk = _j.loads(_autotune_cache_path(_fp).read_text()).get("table")
                    except Exception as _e:  # noqa: BLE001
                        _disk = f"unreadable: {_e}"
                sha = lambda o: _h.sha256(_j.dumps(o, sort_keys=True, default=str).encode()).hexdigest()[:12]
                _pp = _autotune_cache_path(_fp) if name == "_AUTOTUNE_TABLES" else None
                _st = None
                try:
                    _st = [str(_pp), _pp.stat().st_mtime, _pp.stat().st_ino] if _pp is not None else None
                except Exception as _e:  # noqa: BLE001
                    _st = [str(_pp), repr(_e)]
                out.append({"kind": name, "fp": _fingerprint_sha8(_fp), "path": _st, "fp_tuple": [str(x) for x in _fp], "mem_sha": sha(_mem),
                            "disk_sha": sha(_disk), "mem_eq_disk": _mem == _disk, "mem": _mem, "disk": _disk})
        with open(f"/dump/diag_{_o.environ.get('DIAG_TAG', 'x')}_rank{rank}.jsonl", "a") as f:
            f.write(_j.dumps({"t": _t.time(), "where": where, "rank": rank, "pid": _o.getpid(), "swept": swept, "tables": out}) + "\n")
    except Exception as _e:  # noqa: BLE001
        logger.warning("DIAG tkv table failed: %r", _e)


def _diag_patch_picks() -> None:
    """DIAGNOSTIC: record every distinct split pick the decode dispatch resolves (table present or not, capturing or not)."""
    try:
        import hashlib as _h, json as _j, os as _o, time as _t

        import torch as _torch
        from tkv.runtime.attend import decode_attend as _da

        if getattr(_da, "_diag_patched", False):
            return
        orig = _da.cached_picks
        seen = set()
        rank = _o.environ.get("RANK", _o.environ.get("LOCAL_RANK", "x"))
        path = f"/dump/picks_{_o.environ.get('DIAG_TAG', 'x')}_rank{rank}.jsonl"

        def cached_picks(table, batch, grid_blocks, num_sms, max_seq_len, **kw):
            picks = orig(table, batch, grid_blocks, num_sms, max_seq_len, **kw)
            try:
                cap = bool(_torch.cuda.is_current_stream_capturing())
                tsha = (
                    _h.sha256(_j.dumps({f"{k[0]}:{k[1]}": list(v) for k, v in sorted(table.items())}, sort_keys=True).encode()).hexdigest()[:12]
                    if table
                    else "EMPTY"
                )
                rec = (tsha, int(batch), int(grid_blocks), int(max_seq_len), cap, tuple(picks))
                if rec not in seen:
                    seen.add(rec)
                    with open(path, "a") as f:
                        f.write(_j.dumps({"t": _t.time(), "table": tsha, "batch": int(batch), "grid_blocks": int(grid_blocks),
                                          "max_seq_len": int(max_seq_len), "capturing": cap, "kw": {k: int(v) for k, v in kw.items()},
                                          "picks": list(picks)}) + "\n")
            except Exception:  # noqa: BLE001
                pass
            return picks

        _da.cached_picks = cached_picks
        _da._diag_patched = True
    except Exception as _e:  # noqa: BLE001
        logger.warning("DIAG picks patch failed: %r", _e)


_diag_patch_picks()
