

# arbi_serve/engine/__init__.py
# SPDX-License-Identifier: Apache-2.0
"""Engine: continuous-batching loop, per-request state, per-step batch struct.

``Engine`` is intentionally NOT re-exported here: importing it eagerly
would close a circular import chain
(scheduler -> engine.request -> engine.__init__ -> engine.engine ->
scheduler). Import it as ``from arbi_serve.engine.engine import Engine``.

Re-exports are wired through PEP 562 ``__getattr__`` so importing this
package does NOT eagerly pull ``arbi_serve.engine.batch`` (which
imports torch). Light-weight callers like ``dump_openapi`` (used by
``scripts/generate-client.sh`` in a torchless CI lane) reach
``arbi_serve.engine.request`` via fully-qualified import without
paying the torch tax.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from arbi_serve.engine.batch import (
        AttnPagedKVMeta,
        GDNMeta,
        MambaMeta,
        MLAMeta,
        MTPMeta,
        ScheduledBatch,
    )
    from arbi_serve.engine.request import Request, RequestState, SamplingParams


__all__ = [
    "AttnPagedKVMeta",
    "GDNMeta",
    "MLAMeta",
    "MTPMeta",
    "MambaMeta",
    "Request",
    "RequestState",
    "SamplingParams",
    "ScheduledBatch",
]


_BATCH_NAMES = frozenset(
    (
        "AttnPagedKVMeta",
        "GDNMeta",
        "MambaMeta",
        "MLAMeta",
        "MTPMeta",
        "ScheduledBatch",
    )
)
_REQUEST_NAMES = frozenset(("Request", "RequestState", "SamplingParams"))


def __getattr__(name: str):
    if name in _BATCH_NAMES:
        from arbi_serve.engine import batch as _batch

        return getattr(_batch, name)
    if name in _REQUEST_NAMES:
        from arbi_serve.engine import request as _request

        return getattr(_request, name)
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


# arbi_serve/engine/_distributed_driver_ops.py
# SPDX-License-Identifier: Apache-2.0
"""Shared distributed routing/counters and compatibility exports for driver helpers."""

from __future__ import annotations

from arbi_serve.engine.distributed_batch_staging import (
    publish_core_batch_tensors as publish_core_batch_tensors,
)
from arbi_serve.engine.distributed_control_ops import (
    ControlOp as ControlOp,
)
from arbi_serve.engine.distributed_control_ops import (
    _apply_profile_action as _apply_profile_action,
)
from arbi_serve.engine.distributed_control_ops import (
    _fail_slate as _fail_slate,
)
from arbi_serve.flag_truth import path_counter

#: The TP>1 MTP prefill seed (:meth:`DistributedEngineDriver._spmd_seed_mtp`).
#: ``fired`` counts ROWS seeded — every MTP-opted row must be seeded exactly
#: once, on the tick it finishes prefill. A run with MTP traffic and
#: ``spmd_mtp_seed.fired == 0`` means the seed never fired and every admission
#: is paying a cold tick (the pre-fix behaviour); ``mtp_cold_tick.fired``
#: (spmd.py) is the other half of the pair and must go to ~0 when this one
#: fires. Bound at import: the mark is a plain slotted store — no env
#: read, no name lookup, no allocation, no H2D/D2H, no collective.
_SPMD_MTP_SEED = path_counter("spmd_mtp_seed")

#: EFFECTIVE accept accounting, counted over EVERY decode row-tick (cold ones
#: included) at the SPMD rank-0 commit. The Prometheus mtp_proposed/_accepted
#: pair cannot see a cold row (it drafts 0 and commits 1, adding 0 to both), so
#: an acc_len derived from those is a warm-only average that flatters exactly
#: the collapse we are fixing. These give the honest, TPOT-determining number:
#:     effective accept_len = mtp_row_tokens / mtp_row_ticks
#: with mtp_zero_spec_tokens isolating the tokens emitted with NO speculation.
_MTP_ROW_TICKS = path_counter("mtp_row_ticks")
_MTP_ROW_TOKENS = path_counter("mtp_row_tokens", counted=True)
_MTP_ZERO_SPEC_TOKENS = path_counter("mtp_zero_spec_tokens", counted=True)


def spmd_mtp_seed_rows(
    slate: list[tuple[int, int]],
    mirror,
    driver,
    emit_idx: list[int],
) -> list[int]:
    """Slate indices that must have the MTP drafter seeded on THIS tick.

    A row qualifies iff it opted into MTP (``mtp_k > 0``), emits a token this
    step, AND is still a PREFILL row — i.e. this tick is the one finishing its
    prompt. That is the only tick on which an SPMD row can be seeded: from the
    next tick it is a decode row that the verify pass owns, and the verify
    derivation reads ``mtp_next_drafts`` as a precondition (the drafter chain
    inside the verify pass refreshes them from there on).

    Pure function of ``(slate, mirror, emit_idx)`` — all of which are
    bit-identical on every rank — so every rank computes the same list and
    takes the same forward branch, keeping the collectives in lockstep.

    This is a gate rather than an unconditional flag because a non-empty
    result makes the caller ask ``forward`` for the per-token hidden, and
    ``return_hidden_state=True`` de-captures any graph without a
    ``hidden_out`` buffer — which is every plain-decode (S=1) graph, and
    the seed helper has no decode-flavor replay rung at all (it replays
    prefill rungs only). A warm decode row in this list therefore forces
    a full eager whole-model forward on every rank every tick.

    The ``is_prefill`` term is what makes that unreachable, and it must not be
    inferred from the routing: whether a warm MTP row reaches this call site is
    a property of the verify-dispatch predicate in the SPMD step body, and a
    row that arrives here warm has, by construction, nothing to seed. Locked
    down by ``tests/test_mtp_spmd_seed.py``.
    """
    if driver is None:
        return []
    out: list[int] = []
    for i in emit_idx:
        mreq = mirror.reqs[slate[i][0]]
        if int(mreq.sampling.mtp_k) <= 0:
            continue
        if not bool(mreq.is_prefill):
            # Warm decode row on the plain-forward path: the verify pass owns
            # its drafts. Seeding it here would buy nothing and de-capture the
            # decode graph.
            _SPMD_MTP_SEED.refuse("warm decode row (verify pass owns its drafts)")
            continue
        out.append(i)
    return out


def configured_dflash_active(cfg) -> bool:
    """Return whether boot or any declared resident uses a DFlash drafter.

    The distributed step-loop routing is fixed before resident preparation,
    so every declared pool member must participate in this boot-time decision.
    Both convenience fields and general override keys are accepted by the
    pool-member schema.
    """
    if getattr(getattr(cfg, "mtp", None), "dflash_draft_path", None):
        return True
    for member in getattr(cfg, "pool_members", ()) or ():
        if getattr(member, "dflash_draft_path", None):
            return True
        overrides = getattr(member, "overrides", None) or {}
        if overrides.get("dflash_draft_path") or overrides.get("mtp.dflash_draft_path"):
            return True
    return False


def refuse_dflash_on_ep_only(cfg, parallel_cfg) -> None:
    """Refuse a DFlash drafter on a multi-rank topology with no TP and no PP.

    That is expert parallelism alone (``tp_size == 1``, ``ep_size > 1``). The
    drafter is tensor-sharded only across a TP group, so here it would be the
    unsharded rank-0-only build, which cannot run rank-symmetric drafter
    collectives on that topology. The check runs on
    every rank before any weight loads, from facts every rank holds, so all
    ranks refuse together.
    """
    world = int(getattr(parallel_cfg, "world_size", 1))
    tp = int(getattr(parallel_cfg, "tp_size", world))
    pp = int(getattr(parallel_cfg, "pp_size", 1))
    if world <= 1 or tp > 1 or pp > 1 or not configured_dflash_active(cfg):
        return
    from arbi_serve.boot_refusal import ConfigurationError

    ep = int(getattr(parallel_cfg, "ep_size", world))
    raise ConfigurationError(
        f"A DFlash drafter is not served on an expert-parallel-only topology "
        f"(--tp-size 1 --ep-size {ep}, world_size={world}): the drafter is "
        f"sharded across a TP group, and this topology has none. Ways out: "
        f"serve with --tp-size > 1 (the sharded drafter runs on the SPMD loop), "
        f"serve on one GPU (--tp-size 1 --ep-size 1), or drop "
        f"--dflash-draft-path (and any pool member's dflash_draft_path)."
    )


def refuse_prefill_only_on_pp(cfg, parallel_cfg) -> None:
    """Refuse a prefill-only task the pipeline cannot answer.

    Last-token EMBED pools on two stages: the last stage owns the final norm
    and returns one row per sequence to rank 0
    (:mod:`arbi_serve.engine.pp_pooling`). Rerank, decide and forward read the
    LM head or other rows, and more stages are not served. Every rank refuses
    together before any weight loads.
    """
    from arbi_serve.engine.pp_pooling import topology_refusal
    from arbi_serve.engine.serving_tasks import is_prefill_only

    task = getattr(cfg, "task", "generate")
    if int(getattr(parallel_cfg, "pp_size", 1)) <= 1 or not is_prefill_only(task):
        return
    reason = topology_refusal(task, parallel_cfg)
    if reason is None:
        return
    from arbi_serve.boot_refusal import ConfigurationError

    raise ConfigurationError(
        f"--task {task} is not served with --prefill-pipeline: {reason}. Drop "
        f"--prefill-pipeline, or serve with --tp-size 2."
    )


def refuse_pp_pooling_readout(engine, parallel_cfg) -> None:
    """After the build: refuse a pipeline pooling engine whose answer is not a
    last-stage last-position row. Every rank holds the same model."""
    from arbi_serve.engine.serving_tasks import is_prefill_only

    if int(getattr(parallel_cfg, "pp_size", 1)) <= 1:
        return
    if not is_prefill_only(getattr(engine, "task", "generate")):
        return
    from arbi_serve.engine.pp_pooling import note_armed, readout_refusal

    reason = readout_refusal(engine)
    if reason is not None:
        from arbi_serve.boot_refusal import ConfigurationError

        raise ConfigurationError(
            f"--task {engine.task} is not served with --prefill-pipeline: {reason}. "
            "Serve last-token pooling, or drop --prefill-pipeline."
        )
    note_armed()


def refuse_deferred_media_pooling_at_multi_rank(cfg, parallel_cfg, model) -> None:
    """Refuse a model that encodes its media inside the pooling step at world_size > 1.

    Such a model (an OCR stack, a hosted decision) encodes on the rank that
    runs the step; the SPMD pooling tick has no such encode on the peers.
    No deployment shards one. Every rank holds the same model, so every rank
    refuses together.
    """
    from arbi_serve.engine.serving_tasks import is_prefill_only

    task = getattr(cfg, "task", "generate")
    if int(getattr(parallel_cfg, "world_size", 1)) <= 1 or not is_prefill_only(task):
        return
    if not getattr(model, "deferred_media", False):
        return
    from arbi_serve.boot_refusal import ConfigurationError

    raise ConfigurationError(
        f"--task {task} on this model encodes its media inside the pooling step, which "
        f"runs on one GPU only. Serve it with --tp-size 1."
    )


def _spmd_needs_full_noise(emit_reqs) -> bool:
    """``True`` iff any emitting row carries a real top_k/top_p/min_p filter.

    Consulted only when the filtered fast path is rolled back via
    ``ARBI_SAMPLER_FILTERED_GUMBEL=0``: filtered rows must then ride the
    full-noise Gumbel path (the fused top-k/top-p kernel consumes a
    materialized ``(B, V)`` noise tensor) to stay rank-symmetric. Greedy
    rows sample nothing (argmax) so they never force the noise path.
    Conservative on ``top_k`` (any positive cap counts) — a false
    positive only costs the slower path, never correctness.
    """
    for req in emit_reqs:
        sp = req.sampling
        if sp.is_greedy:
            continue
        if sp.top_k is not None and sp.top_k > 0:
            return True
        if sp.top_p < 1.0:
            return True
        if sp.min_p > 0.0:
            return True
    return False


# arbi_serve/engine/activation_admission.py
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Arm the scheduler's admission-time activation gate from the boot profile.

The engine-side half of :mod:`arbi_serve.scheduler.activation_budget`: it reads
the boot activation profile and the serving floor, calibrates the step model,
hands it to the scheduler, and — the part that matters most on a ceiling-bound
card — states in the boot log whether the WIDEST slate admission can build fits
the bytes the floor reserved for one step.

That statement is the pair the KV budget has never had. The floor reserves for a
step; admission decides which steps exist; nothing has connected the two. When
the widest admissible slate costs more than the reserve, the excess is not a
theoretical worst case — it is a slate the scheduler will build, whose forward
then OOMs after the layout freeze. Naming the excess, and which term carries it,
is what lets the floor follow the real peak instead of a guess.

THE BUDGET IS RE-READ, not just armed. The boot reading is taken once and
everything the process maps afterwards comes out of it — ``scratch.forward_arena``
re-growing past what the post-capture grow accounted for, a cubin the driver
loads on a kernel no boot phase dispatched — so the gate went on enforcing a
number for a card that no longer existed and the forward met the difference as
an OOM. :func:`rearm_step_budget` takes the SAME measurement again on the two
edges where the card contradicts the gate (a serving OOM, and the first step
that succeeds after one) and re-arms every scheduler with it. Only
``budget_bytes`` moves: the slopes describe the model, not the card.
:func:`minimum_step_bytes` is the other half of that pair — the cost of the
smallest slate the gate can build, so a budget below it is the statement that
narrowing has run out. See :mod:`arbi_serve.engine.memory_pressure`.

A DEFICIT IS NOT AN EMPTY ROW, and the boot refuses on it. Free VRAM below the
reserve the floor holds for consumers OTHER than a step means those bytes are
already gone before admission has priced one slate. That reading used to be
clamped at zero and then restored up to the grow's own step reserve, which
handed the gate a budget better than the card and printed the deficit as
``0 B``; the first heavy request met the difference as a step OOM and every
request behind it was shed. :func:`_step_free_bytes` now carries the sign
through and bounds the restore by the share it repays — the STEP's reserve, the
only one whose bytes the post-freeze phase can have left as this process's
mapped segments — so a raided non-step share stays raided.
:func:`measure_step_budget_bytes` publishes what survives, and
:func:`arm_activation_admission` refuses on a deficit: no chunk narrowing or
deferred row returns bytes to a reserve the step never held. It refuses equally
on a budget that does not outlast :func:`minimum_step_bytes`, the point where
narrowing has nothing left to narrow to; a budget merely short of the WIDEST
slate still narrows, which is the gate working.
``activation_step_reserve_overcommitted`` and
``activation_step_budget_below_minimum`` are the counters that say which fired.
Serving-time re-arms never refuse: there the same reading is what the
memory-pressure ladder narrows and sheds against.

A READING AND AN ABSENCE ARE DIFFERENT ANSWERS, and this module keeps them
apart at every seam it owns. :func:`measure_step_budget_bytes` returns ``None``
when there is no reading to take and an integer — ``0`` included — when there
is; ``StepActivationModel.budget_bytes`` carries the same distinction into the
gate; and :func:`rearm_step_budget` returns ``None`` only for the one fact its
caller can do nothing about, that no scheduler carries an armed model. A zero
reading is the state where a step may spend nothing, which is the state where
admission most needs to narrow and the front door most needs to shut — so it
cannot share a value with the state where the gate is inert.

Explicit safety signals can request a rank-local re-arm: a serving JIT compile
or an idle arena restoration that failed to put its backing physical back.
Optional arena/driver diagnostics record observations and future-boot bounds;
they do not queue driver reads on successful serving steps. Ordinary card reads
are restricted to startup and idle seams; cooperative media consumes its existing
foreign-process observer.

Both re-arm paths use :func:`measure_step_budget_bytes` and the same model
replacement. The OOM path may use an all-rank agreement at world size one;
rank-local safety signals cannot enter a collective their peers might never
reach, so :func:`service_pending_rearm` measures with ``collective=False`` and
clamps to boot's all-rank budget. This changes only the budget, never the fitted
slopes, and recovery cannot widen admission beyond boot's agreement.
"""

from __future__ import annotations

import logging
from dataclasses import replace
from typing import TYPE_CHECKING

from arbi_serve._log_change import log_if_changed
from arbi_serve.engine.arena_step_credit import (
    arena_step_credit_bytes,
    credit_arena_where_no_floor_ran,
)
from arbi_serve.engine.arena_step_credit import (
    offarena_held_free_bytes as _offarena_held_free_bytes,
)
from arbi_serve.flag_truth import FiringWindow, path_counter
from arbi_serve.runtime.activation_profile import verify_logits_epilogue_bound
from arbi_serve.scheduler.activation_budget import (
    ShapeObservation,
    StepActivationModel,
    calibrate,
    resolve_prefill_gather_max_kv_tokens,
)

if TYPE_CHECKING:
    from arbi_serve.engine.engine import Engine

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

_MIB = 1024 * 1024

#: The boot handed the calibrated step model to at least one scheduler, so the
#: gate admission enforces and the lever the memory-pressure ladder pulls are
#: the same object. BOOT window: a zero here on a boot that logged a step model
#: is the unreachable-gate defect, which is why the count exists separately
#: from the calibration succeeding.
GATE_ARMED = path_counter("activation_gate_armed", FiringWindow.BOOT)

#: A signal asked the gate to re-measure. The receipt that the MECHANISM RAN,
#: which is the half a re-arm count alone cannot carry: a zero on the re-arm
#: counter beside a nonzero here is a measurement that found the card whole,
#: and beside a zero here it is a mechanism that never fired. SERVE window --
#: every signal that raises it is a serving-time event.
_REARM_REQUESTED = path_counter("activation_gate_rearm_requested", FiringWindow.SERVE)

#: A re-measurement actually moved the budget. SERVE window, same reason.
_REARMED = path_counter("activation_gate_rearmed", FiringWindow.SERVE)

#: Outstanding re-measure requests, by reason. A module-level set rather than
#: engine state because :mod:`arbi_serve.jit_detector` raises one and has no
#: engine to raise it on; see :func:`request_rearm`.
_pending_rearm: set[str] = set()

#: Reason strings, named here so the signal sites and the tests that assert on
#: them cannot drift into two spellings of the same event.
REARM_ARENA_OVERAGE = "forward-arena over reserve"
REARM_DRIVER_GROWTH = "driver residency over reserve"
REARM_JIT_SERVING = "JIT compile after serving-ready"

#: The model calibrated and NO scheduler took it. A defect, counted so a smoke
#: scrape can disconfirm it rather than an operator having to read for the
#: absence of a log line.
GATE_ARM_NO_SCHEDULER = path_counter("activation_gate_arm_no_scheduler", FiringWindow.BOOT)

#: The step budget was re-measured and the card had nothing left for a step:
#: a reading of zero, not an absent reading. Separate from
#: ``step_oom_budget_rearmed`` because this is the branch where every narrowing
#: lever is at its stop, and a serve that reaches it is a serve whose front
#: door is about to shut.
BUDGET_MEASURED_ZERO = path_counter("activation_step_budget_measured_zero", FiringWindow.SERVE)

#: The card had less free VRAM than the serving floor reserved for consumers
#: OTHER than one step, at the moment admission armed: the boot is
#: over-committed before a step spends a byte. BOOT window, and MUST-NOT-FIRE on
#: any shipped config — a fire is a boot that :func:`arm_activation_admission`
#: refused rather than served.
STEP_RESERVE_OVERCOMMITTED = path_counter(
    "activation_step_reserve_overcommitted", FiringWindow.BOOT
)

#: The budget did not strictly exceed the cost of the SMALLEST slate the gate
#: can build, so admission's narrowing ladder is at its stop before the first
#: request arrives. BOOT window, MUST-NOT-FIRE on any shipped config.
STEP_BUDGET_BELOW_MINIMUM = path_counter("activation_step_budget_below_minimum", FiringWindow.BOOT)


def build_step_activation_model(
    eng: Engine, *, budget_bytes: int | None
) -> StepActivationModel | None:
    """Calibrate the step-activation model for this engine, or ``None``.

    ``None`` whenever the inputs are not there to calibrate honestly — no
    activation profile, fewer than two profiled token widths — and the gate
    then stays inert rather than enforcing a number nothing measured.
    """
    from arbi_serve.engine.memory_budget import tkv_prefill_gather_bytes_per_kv_token
    from arbi_serve.runtime.activation_profile import (
        SHAPE_PREFILL,
        SHAPE_VERIFY_FORWARD,
        SHAPE_VERIFY_STOCHASTIC,
    )

    prof = getattr(eng, "activation_profile", None)
    per_shape = list(getattr(prof, "per_shape", None) or ()) if prof is not None else []
    if not per_shape:
        return None

    g = tkv_prefill_gather_bytes_per_kv_token(
        layer_specs=getattr(getattr(eng, "model", None), "layer_specs", []) or [],
        parallel_cfg=getattr(eng, "parallel_cfg", None),
        active_backends=getattr(eng, "active_backends", None),
    )
    gather_max = resolve_prefill_gather_max_kv_tokens()

    observations: list[ShapeObservation] = []
    for p in per_shape:
        # The stochastic verify tail is reserved separately and additively by
        # the serving floor; folding it in here would price it twice.
        if p.label == SHAPE_VERIFY_STOCHASTIC:
            continue
        tokens = int(getattr(p, "num_tokens", 0) or 0)
        rows = int(getattr(p, "num_seqs", 0) or 0)
        # Only the single-row prefill probe takes tkv's padded gather (it needs
        # ``B == 1``), and being a fresh sequence its accumulated KV is exactly
        # its own token count.
        gathered = min(tokens, gather_max) if (p.label == SHAPE_PREFILL and rows == 1) else 0
        # The verify-width shape's EXTRA query tokens: its rows carry ``K + 1``
        # each and every other shape's carry one, so the excess over the row
        # count IS ``rows * K``. Derived from the recorded shape rather than
        # from a separately-stored K, so a profile restored from the boot
        # manifest describes its own calibration with no second source to drift.
        query_tokens = max(0, tokens - rows) if p.label == SHAPE_VERIFY_FORWARD else 0
        observations.append(
            ShapeObservation(
                tokens=tokens,
                rows=rows,
                gather_kv_tokens=gathered,
                peak_bytes=int(getattr(p, "peak_reserved_bytes", 0) or 0),
                query_tokens=query_tokens,
            )
        )
    return _floor_query_slope_at_logits_epilogue(
        eng,
        calibrate(
            observations=observations,
            gather_bytes_per_kv_token=g,
            gather_max_kv_tokens=gather_max,
            budget_bytes=budget_bytes,
        ),
    )


def _floor_query_slope_at_logits_epilogue(
    eng: Engine, model: StepActivationModel | None
) -> StepActivationModel | None:
    """Bind ``per_query_token_bytes`` below by the ``lm_head`` epilogue.

    The query slope is fitted from :data:`~arbi_serve.runtime.
    activation_profile.SHAPE_VERIFY_FORWARD`, and that probe is
    ``model.forward`` — whose head runs on the PER-SEQUENCE last-token gather,
    one row per sequence, exactly as a plain decode step's does. The served
    verify step does not: it takes the forward's hidden state back and runs
    ``logits_from_hidden`` over every drafted position
    (:mod:`arbi_serve.spec_decode.mtp_verify_offload`). So the fitted slope
    cannot contain one byte of the head's per-position cost, and a slope that
    does not contain it lets admission seat a slate whose epilogue has nowhere
    to allocate — which is an allocator failure standing in for a scheduling
    decision.

    Binds only DOWNWARD, the same rule the serving floor's verify tail follows:
    a fitted slope ABOVE the bound already covers the head and is left alone.
    Below it, the bound stands in, and the gate then narrows the chunk or defers
    the row (:meth:`~arbi_serve.scheduler.scheduler.Scheduler._activation_admits`)
    instead of the step OOMing.

    A head that cannot be read leaves the model exactly as calibrated.
    """
    if model is None:
        return None
    per_position = verify_logits_epilogue_bound(eng, rows=1)
    if per_position <= int(model.per_query_token_bytes):
        return model
    log_if_changed(
        logger,
        "activation_query_slope_floor",
        "activation admission: the fitted query slope (%.1f KiB/drafted token) is below the "
        "lm_head epilogue one drafted position allocates (%.1f KiB) — the verify-forward probe "
        "runs the head on its last-token gather, not on the slate. Binding the slope to the "
        "epilogue so a slate that cannot afford its own logits defers rows.",
        int(model.per_query_token_bytes) / 1024,
        per_position / 1024,
    )
    return replace(model, per_query_token_bytes=int(per_position))


def widest_admissible_bytes(eng: Engine, model: StepActivationModel) -> int:
    """Bytes the widest slate THIS engine's admission limits allow.

    THE ONLY PLACE THE WIDEST SLATE IS EVALUATED. Two consumers ask for it and
    they have to get the same answer or the reserve and the gate are about
    different steps: the serving floor asks
    (:func:`~arbi_serve.engine.inprocess_capture.forward_arena_step_bound_bytes`)
    so its activation rows can cover the widest step, and
    :func:`arm_activation_admission` asks so the boot line can say whether they
    do. They previously evaluated the same model at two different corners — one
    at ``max_batched_tokens``, the other at
    :func:`~arbi_serve.runtime.activation_profile.reachable_step_tokens` — so
    the floor could be sized for one step and the gate report on another.

    Every corner is a limit the scheduler enforces STRUCTURALLY, before any
    byte accounting, and the model is monotone non-decreasing in all of them,
    so no admissible slate evaluates above this. ``reachable_step_tokens`` is
    the token corner rather than the raw budget because a step is built from at
    most ``max_batch`` rows and every prefill row is capped at
    ``chunk_prefill``: a budget above their product names a step the scheduler
    cannot assemble.
    """
    from arbi_serve.runtime.activation_profile import reachable_step_tokens

    batch_cfg = getattr(eng.cfg, "batch", None)
    max_batch = int(getattr(batch_cfg, "max_batch", 1) or 1)
    tokens = reachable_step_tokens(
        int(getattr(batch_cfg, "max_batched_tokens", 0) or 0),
        max_batch,
        getattr(batch_cfg, "chunk_prefill", None),
    )
    max_context = int(getattr(getattr(eng.cfg, "cache", None), "max_context", 0) or 0)
    k = row_query_tokens(eng)

    def _at(prefill_tokens: int, query_tokens: int) -> int:
        return model.worst_admissible_bytes(
            max_batched_tokens=prefill_tokens,
            max_batch=max_batch,
            max_context=max_context,
            max_query_tokens=query_tokens,
        )

    if not k or tokens <= 0:
        return _at(tokens, max_batch * max(0, k))
    # THE AXES ARE CAPPED JOINTLY, NOT INDEPENDENTLY. A row is either being
    # prefilled or being verified: a row that has not generated a token yet
    # carries no drafts, and a row carrying ``K`` drafts contributes no chunk of
    # prefill. So a step that carries ANY prefill tokens spends at least one of
    # its ``max_batch`` rows on a row that has no query tokens, and the product
    # of the two independent maxima — ``chunk_prefill`` tokens AND ``max_batch *
    # K`` drafts in one slate — is a step ``Scheduler.schedule`` cannot
    # assemble. Reserving for it holds KV against a shape no request can build,
    # and (the half that bites) the GATE then reports a card short of a slate
    # that will never arrive and narrows the chunk for it.
    #
    # The corner is therefore the larger of the two REACHABLE extremes, each of
    # which the scheduler can build: the widest prefill-bearing step, whose
    # drafts come from the rows the prefill row leaves; and the all-decode step,
    # whose every row verifies. The model is monotone non-decreasing in all four
    # arguments, so every admissible slate is dominated by one of the two — this
    # is a TIGHTER bound than the product, never a weaker one.
    return max(_at(tokens, max(0, max_batch - 1) * k), _at(0, max_batch * k))


def max_query_tokens(eng: Engine) -> int:
    """Extra decode-row query tokens the widest slate admission can build.

    ``max_batch * K``: every row opted into speculation at this boot's resolved
    draft depth, charged the ``K`` drafts its verify step carries beside the
    committed tail the row's own per-row term already prices. Zero when the
    engine does not speculate, which leaves the widest-slate number exactly
    what it was.

    Resolved through :func:`row_query_tokens`, which reads
    :func:`~arbi_serve.runtime.activation_profile.verify_forward_geometry` — the
    same predicate that decides whether the shape this term is calibrated from
    gets measured at all. One read of the depth for the widest slate and the
    smallest one alike: a second reading of ``n_draft`` here could charge for a
    depth the profile never ran, or disagree with the floor the OOM ladder
    compares against.
    """
    k = row_query_tokens(eng)
    if not k:
        return 0
    max_batch = int(getattr(getattr(eng.cfg, "batch", None), "max_batch", 1) or 1)
    return max(0, max_batch) * k


def _nonstep_reserve_rows(eng: Engine) -> str:
    """This rank's own non-step reserve, itemised. Empty when there is nothing.

    The subtraction the gate makes is over the GROUP's largest reserve, and the
    rank that holds it is not usually the rank that logs the floor: the
    serving-floor provenance lines are rank 0's, and the stdout sink drops a
    non-zero rank's INFO and WARNING. Without the breakdown travelling with the
    number, a refusal on any other rank names bytes whose row appears nowhere
    in the log.

    Rows are read from the floor's own itemisation
    (:attr:`~arbi_serve.engine.boot_state.BootState.serving_step_terms`) rather
    than re-derived, so the breakdown and the reserve cannot disagree — which
    is also why the selection is exactly the reserve's own members and not
    every row the itemisation carries. ``transient.serving_step.*`` less the
    two activation rows IS the complement the floor publishes as the non-step
    reserve; the ``unclaimed.*`` rows beside them are MAX-ed against the term
    sum rather than added to it, so listing them under this number would print
    a breakdown that does not add up to what it breaks down.
    """
    rows = tuple(getattr(getattr(eng, "boot_state", None), "serving_step_terms", ()) or ())
    named = [
        (str(r[0]).rsplit(".", 1)[-1], int(r[1]))
        for r in rows
        if r
        and int(r[1]) > 0
        and str(r[0]).startswith("transient.serving_step.")
        and str(r[0]).rsplit(".", 1)[-1] not in ("base", "arena_regrow")
    ]
    if not named:
        return ""
    named.sort(key=lambda kv: -kv[1])
    return ", ".join(f"{k} {v} B" for k, v in named)


def _refuse_an_overcommitted_card(eng: Engine) -> None:
    """Refuse a boot whose non-step reserve is not free at the moment it arms.

    ``serving_nonforward_reserve_bytes`` is the part of the serving floor that
    must stay DRIVER-free while a step runs and that a step may not spend: the
    additive spec-decode reserve (the stochastic verify tail, the DFlash draft
    transient, and the verify slate's ``lm_head`` epilogue — a fresh
    ``max_batch x (K + 1)`` by vocab block on the default allocator every verify
    step, reserved because no pool holds it), the media and TTS holes, the
    separate vocoder process's physical hole, the ``gpu_memory_utilization``
    headroom. A free reading below it says those bytes are already gone — spent
    by something that allocated after the last residency bracket the floor was
    measured from — and the reserve is breached before admission has priced a
    single slate. The first step to reach for one of those reserved
    allocations then meets an OOM the ledger said could not happen.

    NO ADMISSION LEVER REACHES IT. Narrowing a prefill chunk and deferring rows
    return bytes to the STEP's own share; the deficit is in a reserve the step
    never held, and the consumers it belongs to (another process, a hard
    utilization cap) cannot be served out of this process's allocator at all. So
    there is no narrower configuration to fall back to and the honest answer is
    the one the KV floor and the post-freeze gate already give: refuse the boot
    rather than serve a layout whose first heavy request meets the shortfall as
    a step OOM, which sheds every request behind it.

    Reads the SIGNED row admission published
    (:attr:`~arbi_serve.engine.boot_state.BootState.
    serving_step_free_restored_bytes`) rather than re-deriving it, so the number
    the refusal names is the number the gate was about to arm against.
    ``activation_step_reserve_overcommitted`` is the counter that says this
    fired.

    RUNS BEFORE THE ARMED BOOT'S TERMS LINE, which is why it states the terms
    itself: that line reports what a scheduler took, and on this path nothing
    does. One format string carries both the log and the exception so the two
    cannot come to say different things about the same reading.
    """
    from arbi_serve.engine.memory_budget import MemoryBudgetError

    bs = getattr(eng, "boot_state", None)
    if bs is None:
        return
    restored = int(getattr(bs, "serving_step_free_restored_bytes", 0) or 0)
    if restored >= 0:
        return
    free = int(getattr(bs, "serving_step_free_bytes", 0) or 0)
    nonfwd = int(getattr(bs, "serving_nonforward_reserve_bytes", 0) or 0)
    group = int(getattr(bs, "serving_nonforward_group_reserve_bytes", nonfwd) or 0)
    reserve = int(getattr(bs, "serving_step_free_reserve_bytes", 0) or 0)
    arena = int(getattr(bs, "serving_arena_resident_credit_bytes", 0) or 0)
    realized = int(getattr(bs, "serving_nonforward_realized_bytes", 0) or 0)
    rows = _nonstep_reserve_rows(eng)
    STEP_RESERVE_OVERCOMMITTED.fired = 1
    from arbi_serve.engine.admission_refusal_text import overcommit_refusal_detail

    detail = overcommit_refusal_detail(
        free=free,
        group=group,
        restored=restored,
        reserve=reserve,
        arena=arena,
        nonfwd=nonfwd,
        realized=realized,
        rows=rows,
    )
    logger.error("activation admission: %s", detail)
    raise MemoryBudgetError(detail)


def _refuse_a_budget_below_the_smallest_slate(eng: Engine, model: StepActivationModel) -> None:
    """Refuse a boot whose budget does not outlast admission's last lever.

    :func:`minimum_step_bytes` is the cost of the smallest slate the gate can
    build — one row, no prefill tokens, no padded gather, and on a speculating
    boot the ``K`` drafts that row's verify step carries. Admission narrows
    towards it and stops there: the chunk cap floors an empty slate at one token
    and ``_activation_admits`` seats a solo row that does not fit rather than
    starving it (a windowless boot never splits a prompt, so its smallest step
    is one whole ``max_context`` prompt). A budget at or below that number says
    every narrowing lever is at its stop before the first request arrives.

    NARROWING FIRST, REFUSAL ONLY WHERE NARROWING RUNS OUT. A budget under the
    WIDEST slate is not this: the gate answers it by narrowing the chunk and
    deferring rows, which is the mechanism working, and the line above reports
    it. This refuses only the case with nothing left to narrow to, where serving
    means handing every request a step OOM that sheds the queue behind it.

    ``activation_step_budget_below_minimum`` is the counter that says this
    fired. A minimum of zero — a model whose smallest slate costs nothing —
    cannot be missed by any budget and is left alone.
    """
    from arbi_serve.engine.memory_budget import MemoryBudgetError

    budget = model.budget_bytes
    if budget is None:
        return
    from arbi_serve.engine.windowless_kv import smallest_step_bytes

    min_step, why = smallest_step_bytes(
        eng, model, minimum_step_bytes(model, query_tokens=row_query_tokens(eng))
    )
    if min_step <= 0 or int(budget) > min_step:
        return
    STEP_BUDGET_BELOW_MINIMUM.fired = 1
    raise MemoryBudgetError(
        "Boot REFUSED — a step may spend "
        f"{int(budget)} B and the SMALLEST slate admission can build costs "
        f"{min_step} B, so the gate has no narrower configuration to fall back "
        f"to: {why}Serving from here means every request "
        "meets the shortfall as a step OOM, which sheds the queue behind it. "
        "The budget's terms are on the line above (boot_state.serving_step_* on "
        "the boot ledger); the slate's cost is the calibrated step model's "
        "constant plus one row plus this boot's draft depth."
    )


def arm_activation_admission(eng: Engine) -> StepActivationModel | None:
    """Arm every scheduler, then log the fit against the reserve.

    Best-effort about the INPUTS: an engine without a profile or a resolvable
    floor keeps the page-only admission it has always had, and says so at INFO.
    The gate is a tightening, never a prerequisite for serving. A calibrated
    model with no scheduler to receive it is a different thing — the inputs were
    all there and the gate is unreachable anyway — and that is an ERROR.

    THE LOG LINE REPORTS WHAT WAS ARMED, which is why the arming runs first.
    A line describing a calibrated model says nothing about whether any
    scheduler received it, and an engine whose gate is unreachable reads
    identically to one whose gate is enforcing — the boot's only statement
    about the gate has to be a statement about the schedulers holding it, or a
    silent miss is indistinguishable from a healthy arm until an OOM asks.
    """
    # BEFORE the reading: on a boot no serving floor sized, the arena credit the
    # budget adds is resolved here, from the one expression the floor uses.
    credit_arena_where_no_floor_ran(eng)
    try:
        budget = measure_step_budget_bytes(eng)
        model = (
            build_step_activation_model(eng, budget_bytes=budget) if budget is not None else None
        )
    except Exception:  # noqa: BLE001 — a calibration failure must not wedge boot
        logger.exception(
            "activation admission: calibration FAILED; admission keeps its "
            "page-only gate and the serving floor's step reserve is unenforced."
        )
        model = None
    # OUTSIDE the calibration guard, and before the unarmed exit below. An
    # over-committed card is a fact about the card, not about whether a model
    # could be fitted to it, and the guard above exists so a failed FIT leaves
    # the page-only gate standing — not so a refusal can be swallowed into it.
    _refuse_an_overcommitted_card(eng)
    if model is None:
        logger.info(
            "activation admission: not armed — this boot has no serving floor "
            "or no activation profile to calibrate against, so admission gates "
            "KV pages only."
        )
        return None

    armed = 0
    for sched in _schedulers(eng):
        sched.set_activation_model(model)
        armed += 1
    if not armed:
        GATE_ARM_NO_SCHEDULER.fired = 1
        logger.error(
            "activation admission: the step model CALIBRATED but no scheduler "
            "was there to receive it, so the gate is unreachable: admission "
            "gates KV pages only and the memory-pressure ladder has no budget "
            "to narrow. This is a boot-ordering defect, not a configuration — "
            "the model is armed onto the schedulers the engine builds slates "
            "with (activation_admission._schedulers), and there were none."
        )
        return None
    GATE_ARMED.fired = 1

    from arbi_serve.runtime.activation_profile import reachable_step_tokens

    batch_cfg = getattr(eng.cfg, "batch", None)
    max_batch = int(getattr(batch_cfg, "max_batch", 1) or 1)
    # The corner the FLOOR was sized against, read through the one expression
    # that evaluates it. Reporting the raw ``max_batched_tokens`` here while the
    # floor reserved for the reachable width made the boot line a statement
    # about a step the scheduler cannot assemble.
    mbt = reachable_step_tokens(
        int(getattr(batch_cfg, "max_batched_tokens", 0) or 0),
        max_batch,
        getattr(batch_cfg, "chunk_prefill", None),
    )
    max_context = int(getattr(getattr(eng.cfg, "cache", None), "max_context", 0) or 0)
    max_query = max_query_tokens(eng)
    worst = widest_admissible_bytes(eng, model)
    gather_worst = model.per_gather_kv_token_bytes * model.gather_charge_tokens(max_context)
    logger.info(
        "activation admission: ARMED on %d scheduler(s) — step model = %.0f MiB "
        "const + %.1f KiB/token x %d + %.0f MiB/row x %d + %.1f KiB/kv-token x %d "
        "gather + %.1f KiB/draft-token x %d -> widest admissible slate %.0f MiB vs "
        "%.0f MiB the step may spend (measured free VRAM plus %.0f MiB of "
        "forward-arena physical already mapped).",
        armed,
        model.const_bytes / _MIB,
        model.per_prefill_token_bytes / 1024,
        mbt,
        model.per_row_bytes / _MIB,
        max_batch,
        model.per_gather_kv_token_bytes / 1024,
        model.gather_charge_tokens(max_context),
        model.per_query_token_bytes / 1024,
        max_query,
        worst / _MIB,
        model.budget_bytes / _MIB,
        max(
            0,
            int(
                getattr(getattr(eng, "boot_state", None), "serving_arena_resident_credit_bytes", 0)
                or 0
            ),
        )
        / _MIB,
    )
    # THE BUDGET'S OWN TERMS, IN BYTES. The line above states the comparison in
    # MiB, and a shortfall of a few hundred KiB reads there as two equal
    # numbers and a "SHORT by 1 MiB" beneath them — which sends a reader
    # looking for a megabyte that is not the defect. These are the three
    # readings :func:`measure_step_budget_bytes` combined, so which of them the
    # gap came out of is legible without a second boot.
    _bs_terms = getattr(eng, "boot_state", None)
    _free = int(getattr(_bs_terms, "serving_step_free_bytes", 0) or 0)
    _nonfwd = int(getattr(_bs_terms, "serving_nonforward_reserve_bytes", 0) or 0)
    _arena = int(getattr(_bs_terms, "serving_arena_resident_credit_bytes", 0) or 0)
    _reserve = int(getattr(_bs_terms, "serving_step_free_reserve_bytes", 0) or 0)
    # SIGNED, both of them. The subtraction is the one term that can come out
    # below zero, and below zero it is the whole story — a card that cannot hold
    # the non-step reserve free. Formatting it through a ``max(0, ...)`` showed
    # a reader ``0 B`` for a deficit and made the two states one number.
    _restored = int(getattr(_bs_terms, "serving_step_free_restored_bytes", 0) or 0)
    _realized = int(getattr(_bs_terms, "serving_nonforward_realized_bytes", 0) or 0)
    _group = int(getattr(_bs_terms, "serving_nonforward_group_reserve_bytes", _nonfwd) or 0)
    logger.debug(
        "activation admission: budget terms — free VRAM %d B - non-step reserve "
        "%d B = %+d B, restored to %+d B against the "
        "%d B the grow reserved for a step (the boot's own post-freeze phase "
        "holds the difference as mapped allocator segments), + arena residency "
        "credit %d B = %d B, against a widest slate of %d B (%+d B). This rank "
        "holds %d B of the reserve (%s), less the %d B of its driver row this "
        "boot has already taken since the freeze.",
        _free,
        _group,
        _free - _group,
        _restored,
        _reserve,
        _arena,
        int(model.budget_bytes),
        int(worst),
        int(model.budget_bytes) - int(worst),
        _nonfwd,
        _nonstep_reserve_rows(eng) or "no rows",
        _realized,
    )
    if model.budget_bytes is not None and worst > model.budget_bytes:
        # Name the gather's share only while it HAS one. A tkv that bounds the
        # padded gather at the current chunk retires the context-scaled term
        # entirely, and reporting "0 MiB, up to 0 KV tokens" alongside advice to
        # make it stop being context-scaled describes a state that has already
        # arrived — the remaining shortfall is then some other term's, and
        # pointing at the gather sends the reader to the wrong place.
        gather_clause = (
            (
                f", of which {gather_worst / _MIB:.0f} MiB is the tkv Turbo prefill padded gather (one prefill "
                f"row's accumulated context, up to {model.gather_charge_tokens(max_context)} KV tokens; the floor's "
                "staging term prices the query-width residue only). It shrinks "
                "when the gather stops being context-scaled"
            )
            if gather_worst > 0
            else (
                ". The padded gather is bounded at one chunk and costs nothing "
                "here, so this shortfall is elsewhere in the step"
            )
        )
        logger.warning(
            "activation admission: the widest slate the step limits allow needs "
            "%.0f MiB but the card has %.0f MiB free for one step — SHORT by "
            "%.0f MiB%s. Admission narrows the prefill chunk to what fits rather "
            "than letting that slate's forward OOM after the layout freeze, so "
            "the shortfall costs chunk width instead of the engine.",
            worst / _MIB,
            model.budget_bytes / _MIB,
            (worst - model.budget_bytes) / _MIB,
            gather_clause,
        )

    # AFTER the two lines above, so the refusal below is read beside the terms
    # that produced it rather than in place of them.
    _refuse_a_budget_below_the_smallest_slate(eng, model)

    # The all-rank-agreed ceiling every later re-measurement is clamped to. Held
    # on the engine rather than in ``boot_state`` because ``boot_state.
    # serving_step_budget_bytes`` is the LIVE budget the gate enforces, and a
    # re-arm moves it; the two have to be separate values or the clamp would
    # ratchet against whatever it last wrote. Absent means "no gate was armed on
    # this boot"; a zero here is a boot that armed one at zero.
    eng._activation_budget_boot_bytes = int(model.budget_bytes)
    return model


def minimum_step_bytes(model: StepActivationModel, *, query_tokens: int = 0) -> int:
    """Bytes the SMALLEST slate admission can build costs.

    One row, no prefill tokens, no padded gather — the shape the scheduler
    falls back to when every narrowing lever has been pulled
    (:meth:`~arbi_serve.scheduler.scheduler.Scheduler._activation_chunk_cap`
    floors an empty slate at one token, and ``_activation_admits`` admits a solo
    row that does not fit rather than starving it). It is therefore the floor of
    what the gate can do, and a budget below it is the statement that no slate
    exists which fits the card. Read from the model, so it moves with the same
    calibration the gate enforces rather than standing a second number beside
    it.

    ``query_tokens`` IS THAT ROW'S DRAFTS, and on a speculating boot they are
    not optional. The chunk cap narrows PREFILL tokens and is called on prefill
    rows only; a decode row goes through
    :meth:`~arbi_serve.scheduler.scheduler.Scheduler._activation_admits` at the
    full ``K`` its :meth:`~arbi_serve.scheduler.scheduler.Scheduler.
    _query_charge` reports, with no lever between "charge ``K``" and "admit it
    anyway because one row is the minimum unit of progress". So on a boot that
    speculates the smallest slate the gate can be handed is a ``K + 1``-token
    verify row, and pricing it at one token would tell the memory-pressure
    ladder there is narrowing left where there is none — the door would stay
    open for another OOM, on exactly the card the ladder exists for.

    Zero — the default, and every non-speculating boot — leaves this the number
    it has always been. The spec valve can still zero ``K`` on the emitted
    slate, which only makes the executed step cheaper than the one priced here;
    it fires on decode-batch WIDTH, so an engine drained to one row under
    pressure is precisely where it leaves ``K`` standing.
    """
    return model.demand_bytes(
        prefill_tokens=0, rows=1, gather_kv_tokens=0, query_tokens=query_tokens
    )


def row_query_tokens(eng: Engine) -> int:
    """Extra query tokens ONE decode row's verify step runs beyond its tail.

    ``K``. The per-row half of :func:`max_query_tokens`, off the same predicate,
    so the widest slate and the smallest one cannot disagree about whether this
    boot speculates or how deep.
    """
    from arbi_serve.runtime.activation_profile import verify_forward_geometry

    return int(verify_forward_geometry(eng) or 0)


def rearm_step_budget(eng: Engine, *, free_bytes: int | None = None) -> tuple[int, int] | None:
    """Re-measure what a step may spend and re-arm every scheduler with it.

    Returns ``(budget_bytes, minimum_step_bytes)``, or ``None`` on the ONE fact
    the caller cannot act on: no scheduler on this engine carries an armed
    activation model. There is then nothing calibrated to narrow and no measured
    minimum to compare a budget against, and saying so is better than inventing
    either.

    EVERY OTHER OUTCOME RETURNS A PAIR, including the one an exhausted card
    produces. A budget of zero is the reading that a step may spend nothing —
    the state in which the ladder's remaining rungs (shut the front door, let
    the in-flight rows drain, escalate if an OOM lands before one succeeds) are
    the only reaction left. Folding it into the ``None`` return would disarm the
    ladder in exactly the condition the ladder exists for, and would report it
    as "no armed model" to an engine whose boot armed one.

    A card that cannot be READ (no CUDA, no boot state) is the third case, and
    it re-arms nothing: the gate keeps the budget it holds, and that budget —
    the number admission is enforcing, not an invented one — is what the pair
    reports. Re-arming with a fabricated value would replace a measurement with
    a guess at the moment the measurement is missing.

    THE SAME MEASUREMENT THE BOOT TOOK, taken again. ``budget_bytes`` is the
    only field that moves: the slopes and the constant come from the boot
    activation profile and describe the model, not the card, so re-calibrating
    them here would re-fit a shape nothing re-profiled. What changed is how much
    the card has left, which is exactly what :func:`measure_step_budget_bytes`
    reads.

    WHY IT IS RE-READ AT ALL. The boot reading is taken once, at the moment
    serving begins. Everything the process maps afterwards comes out of it —
    ``scratch.forward_arena`` re-growing past what the post-capture grow
    accounted for, a cubin the driver loads on a kernel no boot phase
    dispatched — and none of that moved the number admission was enforcing. So
    the gate went on admitting slates priced against a card that no longer
    existed, and the forward discovered the difference as an OOM. Re-reading on
    the edges where the card contradicts the gate is what keeps the two the same
    quantity.

    OFF THE STEP PATH. ``mem_get_info`` is a driver call this repo keeps off
    the hot path, and the reading is collapsed to the all-rank minimum, which is
    a collective. Callers reach this only from the OOM edge and the first
    success after one, and only at world size 1 (see
    :mod:`arbi_serve.engine.memory_pressure` for why the multi-rank ladder stops
    before here).
    """
    scheds = [s for s in _schedulers(eng) if getattr(s, "activation_model", None) is not None]
    if not scheds:
        return None
    # ``free_bytes``: the caller's own reading of what the process may still map (the allocator
    # cap's headroom, when the cap is the limit that refused; ``engine.allocator_cap``).
    budget = measure_step_budget_bytes(eng, free_bytes=free_bytes)
    if budget == 0:
        BUDGET_MEASURED_ZERO.fired = 1

    min_step = 0
    # The drafts the smallest buildable slate carries on this boot, resolved
    # once for every scheduler: the depth is the engine's, not the scheduler's.
    row_drafts = row_query_tokens(eng)
    standing: list[int] = []
    for sched in scheds:
        model = sched.activation_model
        if budget is not None:
            sched.set_activation_model(replace(model, budget_bytes=budget))
        elif model.budget_bytes is not None:
            standing.append(int(model.budget_bytes))
        min_step = max(min_step, minimum_step_bytes(model, query_tokens=row_drafts))
    if budget is None:
        if not standing:
            # Nothing to read and nothing armed to read back: the gate is
            # inert, which is the same fact an unarmed engine reports.
            return None
        # The binding scheduler's budget, for the same reason the reading is
        # collapsed to the all-rank minimum: the slate is executed against the
        # tightest of them.
        budget = min(standing)
    return budget, min_step


def request_rearm(reason: str) -> None:
    """Ask the next served step to re-measure the admission gate's budget.

    A serving JIT fires inside a forward; a failed idle restoration has changed
    backing physical. Their safety reads belong on the engine thread after a
    forward has freed its transients. Optional metrics/export observations must
    not call this function: accounting is not a serving-time safety signal.

    Free of engine state on purpose: :mod:`arbi_serve.jit_detector` has no
    engine handle, and giving it one to raise this signal would be a worse
    coupling than a module-level latch. The reasons ACCUMULATE (a set, bounded
    by the number of distinct signal sites) so one service call can name every
    signal that stood behind it.

    Never raises: a signal that breaks the path it observes is worse than the
    shortfall it reports.
    """
    try:
        _REARM_REQUESTED.fired = 1
        _pending_rearm.add(str(reason))
    except Exception:  # noqa: BLE001 — a telemetry latch must never break its caller
        pass


def rearm_pending() -> bool:
    """Whether a signal has asked for a re-measurement (a set truth test).

    Read on the post-step seam, so it is the one thing here that a served step
    pays for. Deliberately not a function of the engine: the whole point of the
    latch is that its writers have no engine.
    """
    return bool(_pending_rearm)


def _restore_enforced_budget(bs, budget: int) -> None:
    """Record on the boot state the budget the schedulers actually carry.

    ``measure_step_budget_bytes`` writes its RAW reading here, which is correct
    for the boot seam that arms straight off it and wrong for every path that
    clamps, declines or fails after taking it. One helper so the three exits
    that have to undo it cannot drift into two of them doing it.
    """
    if bs is not None:
        bs.serving_step_budget_bytes = int(budget)


def service_pending_rearm(eng: Engine) -> StepActivationModel | None:
    """Re-measure the step budget and re-arm every scheduler, or ``None``.

    ``None`` whenever nothing changed — no request outstanding, no reading to
    take, the gate was never armed, or the card still holds what the gate
    believes. That last case is a RESULT, not a failure: the signals below say
    "something permanent may have happened", and only the measurement says
    whether it cost the step anything. The pair of counters is what tells the
    two apart from outside — ``activation_gate_rearm_requested`` says the
    mechanism ran, ``activation_gate_rearmed`` says it found something — so a
    zero on the second can never be read as "did not run".

    THE SIBLING OF :func:`rearm_step_budget`, and the two now differ in exactly
    two things: which callers reach them, and the clamp that follows from it.
    They take the SAME reading, from :func:`measure_step_budget_bytes`, because
    it is the same quantity — a second expression for it would mean this
    function's decision to narrow was a comparison between two different
    numbers, which is the defect class this module exists to keep out. That one
    is the OOM edge's, runs at world size 1, and may therefore take the all-rank
    collective; this one is reached from explicit rank-local safety signals during
    ordinary serving, so it passes ``collective=False`` and clamps instead.
    Both end at the same place: every scheduler re-armed through the same
    ``replace`` with a model whose only moved field is ``budget_bytes``.

    CLAMPED TO THE BOOT BUDGET, never to the last re-armed one. The boot reading
    is the all-rank minimum; this one is rank-local, because the signals that
    raise it are rank-local. Clamping to the boot value keeps every re-armed
    budget at or below a number every rank agreed to, so this can only ever be
    TIGHTER than the gate the boot armed, which is the direction the whole
    mechanism exists to move in. It does not see a peer's own new shortfall —
    but neither did the gate before, so that is the state this leaves unchanged
    rather than one it introduces.

    Clamping to the BOOT value rather than the last re-armed one is also what
    keeps a transient reading from ratcheting: a budget cut by one bad moment
    recovers on the next signal that finds the card whole again, instead of
    holding the narrow chunk for the life of the process.

    A MEASURED ZERO RE-ARMS, and the clamp cannot turn the gate off. The card
    reporting that a step may spend nothing is the state where narrowing is the
    only reaction left, so it takes the same path every other reading takes:
    the model is re-armed at zero, the chunk cap goes to zero tokens, and the
    scheduler's empty-slate floor still advances a row one token per step. Only
    an UNREADABLE card (``None``) leaves the gate on the budget it holds. This
    is the same distinction :func:`measure_step_budget_bytes` and
    ``StepActivationModel.budget_bytes`` draw, at the one seam that would
    otherwise re-fold them: ``min(ceiling, 0)`` is ``0``, and a ``0`` treated as
    "nothing to do here" would disarm the reaction on the fullest cards.
    """
    # Retire only the serviced snapshot: a safety signal may be latched while
    # this measurement releases the GIL, and it must survive for the next seam.
    serviced = set(_pending_rearm)
    reasons = ", ".join(sorted(serviced)) or "unknown"
    bs = getattr(eng, "boot_state", None)
    # The budget the gate is ENFORCING, read before anything below can move it.
    # ``measure_step_budget_bytes`` records its own raw reading on the boot
    # state, and every exit path here has to leave that field holding what the
    # schedulers actually carry.
    current = int(getattr(bs, "serving_step_budget_bytes", 0) or 0) if bs is not None else 0
    try:
        # ``None``, not ``0``, for "this boot armed no gate" — for the reason
        # every other seam here keeps the two apart. A boot that measured a
        # genuine zero armed a gate at zero, and reading that back as "never
        # armed" would strand the one engine whose card most needs re-measuring.
        ceiling = getattr(eng, "_activation_budget_boot_bytes", None)
        if ceiling is None:
            _pending_rearm.difference_update(serviced)
            return None
        ceiling = int(ceiling)
        # Before the reading, not after: a measurement taken with nothing to arm
        # would leave the boot state recording a budget the gate is not
        # enforcing, which is the same kind of lie as an unarmed gate logging a
        # healthy line.
        scheds = [s for s in _schedulers(eng) if getattr(s, "activation_model", None) is not None]
        if not scheds:
            _pending_rearm.difference_update(serviced)
            return None
        measured = measure_step_budget_bytes(eng, collective=False)
        _pending_rearm.difference_update(serviced)
        if measured is None:
            # No reading to take (no boot state, or a driver that will not
            # answer). The gate keeps the budget it is enforcing rather than
            # trading a measurement for a guess, and the request is cleared so
            # a process that can never read the card pays one attempt and not
            # one per step.
            _restore_enforced_budget(bs, current)
            return None
        if measured == 0:
            BUDGET_MEASURED_ZERO.fired = 1
        budget = min(ceiling, measured)
        if budget == current:
            # Nothing moved. Put back the number the schedulers carry: the
            # measurement wrote its RAW reading, which the clamp may be below,
            # and leaving that standing would report a budget the gate never had.
            _restore_enforced_budget(bs, current)
            return None
        # ONLY ``budget_bytes`` MOVES, through the same ``replace`` its sibling
        # uses. The slopes and the constant come from the boot activation
        # profile and describe the model, not the card; re-running the
        # calibration here would re-fit a shape nothing re-profiled and would
        # drag a tkv import onto a step-adjacent path for a term that cannot
        # have changed.
        model = None
        for sched in scheds:
            model = replace(sched.activation_model, budget_bytes=budget)
            sched.set_activation_model(model)
        # AFTER the arming, never before. This field is what the gate enforces,
        # and a write ahead of the loop that then raises leaves the boot state
        # holding a budget no scheduler carries — which the next signal reads
        # back as ``current``, matches, and returns on, so the divergence is
        # permanent and silent.
        _restore_enforced_budget(bs, budget)
    except Exception:  # noqa: BLE001 — a re-measurement must never break the loop
        _pending_rearm.difference_update(serviced)
        _restore_enforced_budget(bs, current)
        logger.exception(
            "activation admission: re-arm FAILED (%s); the gate keeps the budget "
            "it has, which is the boot reading.",
            reasons,
        )
        return None
    _REARMED.fired = 1
    # Both directions are real and the line has to say which one it is. A FALL
    # is the case the mechanism exists for: something took VRAM the process
    # cannot give back, and the gate now narrows instead of letting a forward
    # find the shortfall as an OOM. A RISE is the recovery the boot-clamp makes
    # possible, and reporting it as a taking would read as a leak.
    logger.warning(
        "activation admission RE-ARMED (%s): the step budget %s to %.0f MiB, "
        "%+.0f MiB on the %.0f MiB it was enforcing and %.0f MiB the boot "
        "reading armed. %s",
        reasons,
        "FELL" if budget < current else "rose",
        budget / _MIB,
        (budget - current) / _MIB,
        current / _MIB,
        ceiling / _MIB,
        (
            "The widest slate admission will build is narrower from here — "
            "narrower prefill chunks and deferred rows instead of a forward "
            "that OOMs after the layout freeze."
            if budget < current
            else "The card gave those bytes back, so admission stops reserving "
            "for a shortfall that is no longer there."
        ),
    )
    return model


def measure_step_budget_bytes(
    eng: Engine, *, collective: bool = True, free_bytes: int | None = None
) -> int | None:
    """Bytes one step's forward may allocate, or ``None`` when unreadable.

    THE ONLY PLACE THIS QUANTITY IS COMPUTED. Three callers ask it — the boot
    seam, :func:`rearm_step_budget` on the OOM edge, and
    :func:`service_pending_rearm` on the signals that fire before one — and they
    ask the same question about the same card. A second implementation of it
    would be two numbers that only look like one, which is how the sentinel this
    module now keeps apart got in: the boot arms a budget from one expression
    and a re-measurement compares against it with another, so the comparison
    that decides whether to narrow is between different quantities. One
    expression, one credit source, one set of reserves.

    MEASURED, on this boot, at the moment it is asked for — the boot seam asks
    at the moment serving begins, and :func:`rearm_step_budget` asks again on
    the edges where a serving OOM contradicts that first reading. The driver's
    own free reading, minus the part of the serving floor that belongs to
    consumers other than the step (:attr:`~arbi_serve.engine.boot_state.BootState.
    serving_nonforward_reserve_bytes`), plus the physical ``scratch.
    forward_arena`` already holds and a step can therefore spend without
    touching free VRAM (:attr:`~arbi_serve.engine.boot_state.BootState.
    serving_arena_resident_credit_bytes`). Nothing here is predicted, cached or
    carried from another boot, because nothing else can be: what a step may
    spend is whatever the card still holds once every pool is mapped, and only
    the card can say what that is.

    THE ARENA TERM IS NOT A CUSHION, it is the other half of a reading the
    driver cannot give. ``mem_get_info`` reports what is unmapped; a private
    cuMem pool's reserve is mapped and so invisible to it, while the model this
    budget gates is calibrated on per-shape peaks that include the pool's
    allocations. Free VRAM alone therefore prices a step's whole live set
    against only the part of the card that can pay for some of it, and the gate
    answers by narrowing the prefill chunk — the arena's residency, charged to
    the request that cannot use it. The floor and this budget now split the pool
    exactly once between them: the floor stops holding it, and this credits it.

    Read HERE rather than from the floor's own activation rows, which is where a
    gate drifts from the physical truth. The floor is computed at the
    post-capture grow and the grow leaves exactly that many bytes free — but the
    boot's own serve-kernel warmup and readiness forward then draw from them,
    and so does every driver allocation landing after the last residency
    bracket. A budget cut from the floor promises a step bytes the card no
    longer has; a budget cut from the reading taken after all of that has
    happened promises exactly what is there.

    The reading is collapsed to the ALL-RANK MINIMUM. Free VRAM diverges across
    ranks structurally (rank-0-only pools, per-rank driver residency), the
    scheduler that spends this budget runs on rank 0 alone, and the slate it
    builds is executed by EVERY rank — so the binding card is the tightest one,
    not the scheduler's own. One int64 all-reduce, at boot, on a path every rank
    reaches.

    ``collective=False`` is the caller stating that its own call site is NOT one
    every rank reaches, which is a fact about the CALLER and never about the
    quantity — the arithmetic below is identical either way. The signals
    :func:`service_pending_rearm` services are rank-local (one rank's arena
    grows, one rank's kernel compiles), and an all-reduce entered by the rank
    that saw the signal and not by its peers is a hang, not an agreement. That
    caller clamps its rank-local reading to the boot budget instead, which is
    where the all-rank agreement already lives, so its result is still bounded
    by a number every rank consented to.

    ``None`` when there is no reading to take — no boot state, or a driver that
    will not answer — which leaves the gate unarmed rather than enforcing a
    number nothing measured.

    ZERO IS A READING. Free VRAM at or below the reserve that belongs to
    consumers other than the step is the card stating that a step may spend
    nothing, and it is the state an OOM leaves behind almost by definition: an
    allocation failed because the card was full. Returning it as the same value
    that means "unreadable" would make every consumer treat the fullest cards as
    the ones with nothing to say.
    """
    import torch

    from arbi_serve.engine.inprocess_capture import _all_rank_max_int, _all_rank_min_int

    bs = getattr(eng, "boot_state", None)
    if bs is None:
        return None
    try:
        # A caller that read the card this instant hands the reading in.
        if free_bytes is None:
            free_bytes = int(torch.cuda.mem_get_info(eng.device)[0])
    except Exception:  # noqa: BLE001 — no reading ⇒ nothing measured to gate on
        return None
    if collective:
        free_bytes = int(_all_rank_min_int(eng, free_bytes))
    reserved_elsewhere = max(0, int(getattr(bs, "serving_nonforward_reserve_bytes", 0) or 0))
    # A RESERVE THE BOOT HAS ALREADY REALIZED IS NOT STILL OWED. See
    # :func:`_driver_growth_already_taken`: the driver row of the non-step
    # reserve is measured over a bracket that opens at the FREEZE, and the
    # boot's own serve-kernel warmup and readiness forward run inside it. Those
    # bytes are gone from the free reading above by the time this runs, so
    # subtracting the whole row again charges the card for them twice — and
    # the second charge is not recoverable by the restore below, because
    # driver residency is not a segment this allocator can hand back.
    already_taken = _driver_growth_already_taken(eng)
    reserved_elsewhere = max(0, reserved_elsewhere - already_taken)
    bs.serving_nonforward_realized_bytes = int(already_taken)
    if collective:
        # Collapsed for the SAME reason the free reading and the arena credit
        # are, and it is the one input to ``step_free`` that was not: the slate
        # rank 0 builds is executed by every rank, so a term that varies per
        # rank cannot decide alone. Per-rank divergence here is structural, not
        # noise — rank-0-only pools (the DFlash drafter, driver buffers) give
        # the ranks different floors — so left un-collapsed one rank refuses a
        # boot its peer has already admitted, and its raise takes down a group
        # that was serving.
        #
        # MAX, not MIN: this is a DEBIT. Free VRAM and the arena credit are
        # what a step MAY spend and bind on the smallest; a reserve is what it
        # may NOT, and binds on the largest any rank must hold.
        #
        # THE SPREAD IS TAKEN TOO, and the rank holding the maximum names its
        # rows. Every byte the group's largest reserve exceeds the smallest by
        # is KV no rank gets, charged to all of them — and the only rank that
        # can say which row carried it is the one holding it, which is the rank
        # whose serving-floor provenance lines are NOT in the log (they are
        # rank 0's) and whose WARNING the stdout sink drops unless the call
        # site opts in. An asymmetry here otherwise spends the whole group's
        # budget invisibly. The min costs one more int64 all-reduce on a path
        # every rank already enters twice.
        _group_min = int(_all_rank_min_int(eng, reserved_elsewhere))
        _group_max = int(_all_rank_max_int(eng, reserved_elsewhere))
        # Rendered on EVERY rank, before the rank-local test that decides who
        # logs it. Only the rank holding the maximum needs the string, but
        # evaluating it there would put an unguarded expression between two
        # reduces on one rank alone: the caller wraps this whole function in a
        # blanket ``except``, so a raise would be swallowed and that rank would
        # skip the reduces below while its peers entered them.
        _rows = _nonstep_reserve_rows(eng) or "none"
        if _group_max > _group_min and reserved_elsewhere >= _group_max:
            logger.warning(
                "activation admission: this rank holds the group's LARGEST "
                "non-step reserve, %d B against the smallest rank's %d B, and "
                "the gate subtracts the largest from every rank's free VRAM "
                "because every rank executes the slate rank 0 builds. The "
                "%d B of spread is KV no rank was given. This rank's rows: %s.",
                _group_max,
                _group_min,
                _group_max - _group_min,
                _rows,
                # The maximum is usually held off rank 0, whose WARNINGs the stdout sink drops.
                extra={"all_ranks": True},
            )
        reserved_elsewhere = _group_max
    # The debit actually taken, published so the lines that report the subtraction state the
    # number it was made with (the group's, not this rank's).
    bs.serving_nonforward_group_reserve_bytes = int(reserved_elsewhere)
    # ``scratch.forward_arena``'s resident physical is not in the driver's free reading but a step
    # spends it, and the model this budget gates is calibrated on peaks that include it, so the
    # credit belongs here and not in the floor. It is zero whenever the reclaim opt-in handed those
    # bytes to the KV grow instead, so the two paths credit them exactly once. Collapsed to the
    # all-rank minimum because every rank executes the slate rank 0 builds.
    # The published credit is the arena's residency at the boot; a floor that held the step as free
    # VRAM published zero, and the arena then maps its working set out of that reading. Read the
    # residency again and take the larger.
    arena_credit = max(
        0,
        int(getattr(bs, "serving_arena_resident_credit_bytes", 0) or 0),
        int(arena_step_credit_bytes(eng)),
    )
    if collective:
        arena_credit = int(_all_rank_min_int(eng, arena_credit))
    step_free = _step_free_bytes(eng, free_bytes - reserved_elsewhere, collective=collective)
    # CLAMP THE CAPACITY, NEVER THE MEASUREMENT. A deficit nets against the
    # credit: the two terms answer one question — how many bytes may a step
    # allocate — and the arena's resident physical really can pay for the part
    # of a step that lands in it, so a negative free row does not void it. The
    # SUM is recorded as taken, sign and all, and only the capacity handed to
    # the gate is clamped, because a step may spend nothing but a card may
    # certainly be short. Both readings are published, and they are different
    # facts: the sum going negative is a card that cannot pay for a step at all,
    # while the free ROW going negative is the reserve held for every OTHER
    # consumer being breached — which the credit hides in the sum, and which is
    # the one the boot seam refuses on.
    measured = step_free + arena_credit
    budget = max(0, measured)
    bs.serving_step_measured_bytes = int(measured)
    bs.serving_step_budget_bytes = budget
    bs.serving_step_free_bytes = int(free_bytes)
    bs.serving_step_free_restored_bytes = int(step_free)
    return budget


#: Floor rows the driver's post-freeze growth spends (see arena_watch).
_DRIVER_GROWTH_ROWS = (
    "transient.serving_step.driver_growth",
    "transient.serving_step.host_page_tables",
)


def _driver_growth_already_taken(eng: Engine) -> int:
    """Of the floor's driver row, the part this boot has ALREADY spent.

    ``transient.serving_step.driver_growth`` holds the physical the driver
    takes on the bracket the freeze opens — cubins loaded on first dispatch, a
    re-grown kernel stack, a graph instantiated after boot. The bracket opens
    at the freeze and NOT at the ready banner, so the boot's own post-freeze
    phase is inside it: the serve-kernel warmup and the readiness forward
    dispatch kernels no earlier phase launched, and the driver loads their
    cubins out of exactly the bytes this row reserves.

    That makes the row unlike every other term of the non-step reserve at the
    moment admission arms. The rest are still ahead of the gate, and the free
    reading has them. This one is partly BEHIND it, already out of the free
    reading — and it is the one share the restore in :func:`_step_free_bytes`
    cannot repay, because driver residency is not a caching-allocator segment
    and nothing in this process can hand it back.

    Measured on this boot, at the instant it is asked for, from the same meter
    and the same bracket the reserve was recorded over
    (:func:`~arbi_serve.engine.arena_watch.realized_driver_growth_bytes`);
    nothing here is inherited or forecast.

    CAPPED AT THE ROW, because a credit is a repayment: a boot whose row is
    UNBUDGETED (a configuration never watched serving) held nothing, so there
    is nothing for its own growth to repay and the cap is 0. 0 also whenever
    the reading cannot be trusted, which leaves the debit exactly as the floor
    published it.
    """
    held = 0
    for row in tuple(getattr(getattr(eng, "boot_state", None), "serving_step_terms", ()) or ()):
        if row and row[0] in _DRIVER_GROWTH_ROWS:
            held += max(0, int(row[1]))
    if held <= 0:
        return 0
    try:
        from arbi_serve.engine.arena_watch import realized_driver_growth_bytes

        taken = realized_driver_growth_bytes(eng)
    except Exception:  # noqa: BLE001 — no reading ⇒ hold the whole row
        return 0
    if taken is None:
        return 0
    return min(held, max(0, int(taken)))


def _step_free_bytes(eng: Engine, free_row: int, *, collective: bool) -> int:
    """FREE VRAM a step may spend, holding the KV sizing to its own promise.

    The grow reserved ``serving_step_free_reserve_bytes`` of free VRAM for one
    step and left exactly that much. Then the boot's OWN post-freeze phase — the
    serve-kernel warmup, the JIT replay, the readiness forward — ran, and those
    are the classes a served step reaches: they took the reserve out of free
    VRAM and put it back as caching-allocator segments they no longer hold live.
    That phase is measurable at both shipped shapes: ``unpooled.
    torch_default_pool`` grows by roughly the reserve between the freeze and the
    arm, and ``free - the non-step reserve`` lands at the zero mark — so without
    the restore the gate would run on the arena's residency alone and report a
    card short of a slate it can serve. The boot's own ledger reports the two
    readings for the boot in hand; the terms line
    (:func:`arm_activation_admission`) states them side by side, signed.

    Those bytes did not leave. They are mapped, they are not live, and the next
    allocation of a size the warmup already realized is served from them without
    touching the driver — which is the same fact the forward arena's credit
    rests on, for the same reason, and this is the rest of the pool table
    stating it.

    So the row is restored to the promise and NEVER PAST IT. The cap is the
    reserve the floor itself computed, so the gate can never admit against more
    free VRAM than the KV sizing held back — the reserve and the gate stay one
    quantity, and a card that genuinely never had the bytes is unaffected
    because nothing is mapped to restore them from. A surplus above the reserve
    (a grow that left more free than its floor asked for) still counts in full.

    Reads the allocator at the SAME instant as the free reading it corrects, and
    nets out the arena's own held-free bytes because
    ``serving_arena_resident_credit_bytes`` already spends those — each byte is
    credited once, by exactly one of the two.

    THE ROW IS SIGNED, AND THE RESTORE REPAYS ONE SHARE. ``free_row`` below zero
    is the card stating that free VRAM no longer covers even the reserve that
    belongs to consumers OTHER than the step: the boot spent past its own step
    reserve and into theirs. Clamping it at zero first and restoring on top of
    the clamp handed that state the full promise back — a card 60 MiB in the
    hole and a card that had merely spent its row into mapped segments returned
    the same number — so the sign is carried through instead.

    What the restore may return is bounded by what it is repaying: every share
    of the floor whose consumer allocates THROUGH THIS ALLOCATOR. That is the
    step's own reserve and the in-process part of the non-step reserve — the
    verify tail and its lm_head epilogue, the draft transient, the codec
    scratches, the logprobs tile, the media and TTS holes — because a segment
    the boot mapped and no longer holds live serves any of them without a
    driver call, which is the same fact the arena's credit rests on.

    Excluded is the share owed outside it: a separate vocoder PROCESS's
    physical hole, which that process must find as real free VRAM, and the
    driver's own growth. A segment in this allocator repays neither.

    The reading is capped at that sum before it is added, which changes nothing
    for a row at or above zero (the sum was already capped there) and stops an
    externally-owed share from being repaid out of recoverable bytes. What
    survives goes out signed to
    :attr:`~arbi_serve.engine.boot_state.BootState.
    serving_step_free_restored_bytes`, where the boot seam refuses on it.
    """
    from arbi_serve.engine.inprocess_capture import _all_rank_min_int

    row = int(free_row)
    bs = getattr(eng, "boot_state", None)
    reserve = max(0, int(getattr(bs, "serving_step_free_reserve_bytes", 0) or 0))
    # What a mapped segment can repay is the step's own reserve PLUS the part
    # of the non-step reserve this allocator holds bytes for. Both are shares
    # of the same floor and both are satisfied the same way — the boot mapped
    # the bytes, no longer holds them live, and the next allocation of a size
    # it already realized is served without a driver call.
    #
    # Only the share owed OUTSIDE this allocator is excluded: the sibling
    # vocoder process's physical hole, which another process must find as real
    # free VRAM, and the driver's own growth, which is not the allocator's to
    # hand out. Capping at the step's share alone treated every in-process
    # consumer as if it were one of those two, and refused boots whose bytes
    # were sitting mapped and reusable a few hundred lines away.
    #
    # NOTHING HERE IS A MARGIN. Each term is the value the floor already held
    # back, with its own provenance, and the sum is still bounded below by the
    # MEASURED ``held_free`` — so a card that does not actually hold the bytes
    # gets none of them back however the entitlement is split.
    local = max(0, int(getattr(bs, "serving_nonforward_local_reserve_bytes", 0) or 0))
    repayable = reserve + local
    # THE REDUCE IS UNCONDITIONAL, AND IT RUNS BEFORE THE TEST BELOW. Both
    # sides of that test are RANK-LOCAL — ``repayable`` is this rank's own
    # entitlement, and ``row`` is the collapsed subtraction — so a reduce
    # placed after it is entered by the ranks that have something to restore
    # and skipped by the ranks that do not. That is a half-issued collective
    # at boot: NCCL matches by ORDER, so the peers deadlock at the next
    # rendezvous with no exception anywhere, and the boot dies on a watchdog
    # timeout naming a broadcast several phases downstream. Every rank reaches
    # this line; the reading itself is a cheap allocator query.
    held_free = _offarena_held_free_bytes(eng)
    if collective:
        held_free = int(_all_rank_min_int(eng, held_free))
    if repayable <= row:
        return row
    restorable = min(repayable, max(0, held_free))
    return max(row, min(repayable, row + restorable))


def _schedulers(eng: Engine):
    """Every scheduler that builds slates for this engine (one per attention-DP
    set on the group path, otherwise the single scheduler)."""
    sched = getattr(eng, "scheduler", None)
    if sched is None:
        return ()
    members = getattr(sched, "members", None)
    if members:
        return tuple(members)
    return (sched,) if hasattr(sched, "set_activation_model") else ()


# arbi_serve/engine/active.py
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 Arbi City (Dmitri Evseev <dmitri.evseev@arbi.city>)
"""Per-StateKind active-state builder + teardown.

:func:`build_active` constructs the production
:class:`MultiStatePool`, page-table, scheduler, metadata builders, and
per-layer attn ops; called both at boot (by
:func:`arbi_serve.engine.build.build`) and during per-StateKind
hot-swap. :func:`teardown_kind` drops a kind ahead of a rebuild.

:mod:`arbi_serve.engine.build` re-exports both for legacy import
paths.
"""

from __future__ import annotations

import gc
import logging
import weakref
from typing import TYPE_CHECKING, Any, NamedTuple

import torch

from arbi_serve._log_change import log_if_changed
from arbi_serve._units import GIB, cdiv
from arbi_serve.backends import make_layer_attn_op
from arbi_serve.backends._paged_base import PagedKvBackend
from arbi_serve.backends.tkv_backend import TkvBackend
from arbi_serve.cache._blob_vault import runtime_cache_tier
from arbi_serve.cache._recurrent_lifecycle import savepoint_row_ledger
from arbi_serve.cache._state_pool_common import (
    kv_parking_serves_here,
    pool_carries_recurrent_state,
    prefix_cache_can_serve,
    prefix_retention_serves,
)
from arbi_serve.cache.multi_state_pool import MultiStatePool
from arbi_serve.cache.pagetable import FlatPageTable
from arbi_serve.cache.radix_pagetable import RadixPageTable
from arbi_serve.cache.recurrent_savepoint import (
    RecurrentSavepointStore,
    recurrent_fold_grid,
    savepoint_resume_grid,
)
from arbi_serve.engine.attn_call_extras import reserve_call_extras
from arbi_serve.engine.boot_state import block_table_width
from arbi_serve.engine.deferred_calibration_kv import deferred_calibration_basket
from arbi_serve.engine.savepoint_arm import savepoint_subsystem_arm as savepoint_subsystem_arm
from arbi_serve.engine.savepoint_ring_probe import ring_transfer_us_once
from arbi_serve.engine.scheduler_build import build_scheduler as _build_scheduler
from arbi_serve.engine.serving_tasks import reads_prefix_cache
from arbi_serve.flag_truth import FiringWindow, path_counter
from arbi_serve.kvtier.wiring import build_savepoint_store
from arbi_serve.models.layer_spec import StateKind

if TYPE_CHECKING:
    from arbi_serve.engine.engine import Engine

logger = logging.getLogger("arbi_serve.engine.active")

#: ``ARBI_PREFIX_TIER`` and its disk-tier sibling, counted where the store
#: is BUILT. The children are read only under the parent's arm, so each
#: carries its own counter — a built store must not certify a child value
#: nobody consumed. Value children fire only on an override away from the
#: compiled default (a restated default selects identical behavior).
_SAVEPOINT_RING = path_counter("savepoint_device_ring_attached", FiringWindow.BOOT)
#: The MASTER switch's own path, so the OFF arm is a stated refusal with a
#: reason rather than an absence a reader has to interpret.
_SAVEPOINT_SUBSYSTEM = path_counter("savepoint_subsystem_on", FiringWindow.BOOT)
#: Whether the fold-state emit's device slot was attached at boot
#: (:mod:`arbi_serve.cache._fold_emit_staging`). Refused by name when the
#: savepoint machinery is off, the pool has no GDN view, or the flag is off —
#: every mid-step savepoint then reads ``fold_split_not_staged`` at commit.
_FOLD_EMIT_STAGING = path_counter("savepoint_fold_emit_attached", FiringWindow.BOOT)
_PREFIX_TIER_STORE = path_counter("prefix_tier_store_built")
_PREFIX_TIER_HOST_GB = path_counter("prefix_tier_host_gb_read")

#: Flag-truth counter for the decode-KV ring. Fired at the ARM — the only
#: moment the ring decision is made — on the flat page table, at engine
#: activation (boot). Every not-armed branch records WHY:
#: ``arch_declares_no_ring`` is the canonical config's answer (only an arch
#: that DECLARES a ring, e.g. Unlimited-OCR's sliding_window_size, can arm
#: one), and ``radix_pagetable_cannot_ring``
#: is the real footgun — a model that declares a ring served on the radix
#: table silently gets no ring and repetition-loops.
_DECODE_KV_RING = path_counter("decode_kv_ring_armed")

#: Extra capture-time scratch rows above the worst-case served batch. The boot
#: profiler / readiness warmup runs a MIXED synthetic batch (one prefill chunk +
#: one decode row), so a capture-time scratch pool sees one row above the served
#: batch even at ``--max-batch 1``. Sizing the pool to exactly the served batch
#: made every tkv boot on that path die in ``TQBufferPool.ensure`` (the pool
#: refuses a post-capture realloc to protect captured-graph pointers).

_CAPTURE_SYNTHETIC_EXTRA_ROWS = 1


def capture_pool_num_seqs(
    resolved_max_batch: int,
    *,
    max_batched_tokens: int,
    max_context: int,
    chunk_prefill: int | None,
) -> int:
    """Worst-case ``num_seqs`` a capture-time scratch pool must pre-size for.

    Two boot-time consumers request rows against this pool:

      1. the scheduler's decode slate (tops out at ``resolved_max_batch``),
         plus the boot mixed-batch warmup's one extra row
         (:data:`_CAPTURE_SYNTHETIC_EXTRA_ROWS`); and
      2. :func:`arbi_serve.runtime.activation_profile.profile_engine`'s pure-
         prefill probe, which spreads ``max_batched_tokens`` q-tokens across
         ``prefill_probe_num_seqs(...)`` rows whenever one row cannot hold
         them — a row carries at most
         :func:`~arbi_serve.runtime.activation_profile.prefill_row_cap`
         (``min(max_context, chunk_prefill)``), so e.g. 8192 tokens at
         ``chunk_prefill=2048`` is 4 rows. At a low ``--max-batch`` that probe
         row count EXCEEDS ``resolved_max_batch``, so sizing the pool to
         ``max_batch + 1`` alone made the probe's ``TQBufferPool.ensure``
         overflow the pre-sized cap and abort the boot.

    Pre-sizing to ``max(resolved_max_batch, probe_seqs) + extra`` covers BOTH
    from ONE call: any boot-time ``ensure(B)`` with ``B`` from either consumer
    can never exceed the cap, so the pool never needs a post-capture realloc
    (which would invalidate captured-graph pointers) and the batch dimension
    can't silently clamp below the resolved value. Both inputs are config
    quantities (no magic literals); the probe row count is derived from the
    same :func:`prefill_probe_num_seqs` the probe itself uses, so the two can
    never diverge.
    """
    from arbi_serve.runtime.activation_profile import prefill_probe_num_seqs

    mb = int(resolved_max_batch)
    if mb < 1:
        raise ValueError(
            f"capture_pool_num_seqs: max_batch={mb} < 1 — the batch dimension "
            f"is unservable. The configured max_batch is >= 1 by construction "
            f"(``parse_max_batch``); a value below 1 here is a plumbing bug."
        )
    probe_seqs = prefill_probe_num_seqs(
        max_batched_tokens, max_context, chunk_prefill=chunk_prefill
    )
    return max(mb, probe_seqs) + _CAPTURE_SYNTHETIC_EXTRA_ROWS


def capture_pool_num_tokens(cfg: Any) -> int:
    """Worst-case flat ``num_tokens`` a capture-time scratch pool must hold.

    The token-dim sibling of :func:`capture_pool_num_seqs`, and it exists
    for the same reason: a boot-time consumer that requests more than the
    pre-size gets a refusal, not a realloc — a realloc would invalidate
    captured-graph pointers, so :meth:`TQBufferPool.ensure` fails the
    capture instead.

    Two consumers:

      1. the scheduler, bounded at ``max_batched_tokens``; and
      2. the MIXED capture sweep, whose graph runs a PADDED
         ``(max_batch - 1) + bucket_n`` flat tokens. That width is
         reachable only by the capture — a live mixed step still fits the
         scheduler's budget — so sizing from ``max_batched_tokens`` alone
         is exactly ``max_batch - 1`` tokens short whenever the top
         mixed bucket equals the budget, which is the shipped
         configuration. Measured on the served 27B at max_batch 4 /
         chunk 2048: ``ensure(num_tokens=2051)`` against a 2048 cap, and
         every mixed graph failed to capture.

    """
    return int(cfg.batch.max_batched_tokens)


def _census_boot() -> bool:
    from arbi_serve.engine.boot_census.mode import is_census_boot

    return is_census_boot()


def _prefix_tier_host_gib() -> int:
    """The warm tier's host budget in GiB, asked of the flag that sets it.

    The boot line reports what the store was BUILT with rather than
    re-deriving a number beside it, so the log and the page-locked arena
    cannot disagree.
    """
    from arbi_serve.runtime_flags import runtime_flags
    from arbi_serve.runtime_flags_parsers import prefix_tier_host_gib

    return prefix_tier_host_gib(runtime_flags().prefix_tier) or 0


def _build_prefix_tier_store():
    """Build the multi-tier prefix-cache store from runtime flags, or None.

    Returns a :class:`PrefixTierStore` when ``ARBI_PREFIX_TIER`` names a tier,
    else ``None`` (drop-on-evict). The one flag carries both arms: the warm
    tier's host budget and its existence, and — only when the value spells
    ``disk:<GiB>`` or the default ``on`` (sized from free space, RAM-only
    with a warning when there is no safe budget) — the cold tier below it,
    sealed under a key only the tier process holds. ``host:<GiB>`` and ``off``
    never have one; an explicit arm with no local cache directory is refused by name.

    A break-even threshold left at 0 in the env falls back to
    ``DEFAULT_{WARM,COLD}_BREAK_EVEN_TOKENS``, which are UNVALIDATED
    placeholders, not a measured crossover — see
    :mod:`arbi_serve.cache.prefix_tier_store` for what would replace them.
    """
    from arbi_serve.runtime_flags import PREFIX_TIER_DEFAULT_HOST_GIB, runtime_flags
    from arbi_serve.runtime_flags_parsers import PREFIX_TIER_DISK_AUTO, prefix_tier_budgets

    flags = runtime_flags()
    host_gib, disk_gib = prefix_tier_budgets(flags.prefix_tier)
    if host_gib is None:
        return None
    from arbi_serve.kvtier.wiring import build_prefix_store, resolve_disk_gib

    offload_dir = None
    if disk_gib is not None:
        offload_dir = runtime_cache_tier("prefix_tier")
        if disk_gib == PREFIX_TIER_DISK_AUTO:
            disk_gib = resolve_disk_gib(flags.prefix_tier, offload_dir)
        if disk_gib is None:
            offload_dir = None
        elif offload_dir is None:
            raise RuntimeError(
                f"ARBI_PREFIX_TIER={flags.prefix_tier!r} asks for the cold (disk) tier, "
                "but no local writable runtime-cache directory resolved. On-disk KV is "
                "request-path I/O, so it may not fall back to a network or read-only "
                "path — set ARBI_RUNTIME_CACHE_DIR to a local directory, or drop the "
                "'disk:<GiB>' arm."
            )
    _PREFIX_TIER_STORE.fired = 1
    if host_gib != PREFIX_TIER_DEFAULT_HOST_GIB:
        _PREFIX_TIER_HOST_GB.fired = 1
    else:
        _PREFIX_TIER_HOST_GB.refuse("compiled_default")
    # The warm/cold crossover lengths are NOT operator flags. They were
    # ``ARBI_PREFIX_TIER_{WARM,COLD}_BREAK_EVEN``, defaulting to 0 and meaning
    # "not zero — use the store's 512/2048"; a knob whose zero is not zero is
    # a knob read wrong. They are unvalidated placeholders, so exposing them
    # invited tuning on a guess. PrefixTierStore owns them until somebody
    # measures the crossover, and then it owns the measured value.
    return build_prefix_store(
        host_max_bytes=host_gib * GIB,
        disk_max_bytes=(disk_gib or 0) * GIB,
        offload_dir=offload_dir,
    )


def resolve_parking(page_table: Any, cache_cfg: Any, pool: Any) -> tuple[bool, str]:
    """Whether this boot PARKS, and the line that says so.

    A parked request's KV is its own PREFIX: its full pages are committed into
    the radix tree and their digests pinned in the prefix tier, so the pages go
    back to the allocator and the copy is paid one page at a time by the
    evictor, for the pages pressure actually takes. There is no second store —
    see :mod:`arbi_serve.cache.radix_pagetable_offload`.

    Parking backs the PARK, which pool pressure drives. It is not what stands a
    row down: an interactive arrival needs the GPU's compute, and a freeze
    gives it that without moving any pages at all.

    THREE conditions, all of which the boot decides and names. Parking is the
    default, so none of them is an operator's explicit ask: a boot that cannot
    park serves without it and the line says which condition failed, which is
    what keeps a quiet park counter distinguishable from a broken one.

      * parking is not turned off (``cache.kv_offload_enabled``,
        ``--disable-kv-parking``);
      * there is somewhere to pin a parked prefix — a radix page table with the
        prefix tier on;
      * a park can free the parked request's pages on EVERY rank. The SPMD
        delta wire carries admit, inject and preempt and no park, so a sharded
        deployment falls back to preemption, which re-prefills — the stability
        answer, not the fast one.
    """
    if not bool(getattr(cache_cfg, "kv_offload_enabled", False)):
        return False, "KV parking: disabled (cache.kv_offload_enabled is off)"
    # TOPOLOGY BEFORE TIER, because only one of the two is the operator's to
    # correct. A deployment whose ranks cannot park does not get a tier either
    # (the boot declines what nothing can consume), so asking about the tier
    # first would report the absence it caused as the reason and REFUSE a boot
    # over a topology — the one condition here that is deliberately a warning.
    park_ok, park_why = kv_parking_serves_here(pool)
    if not park_ok:
        return False, f"KV parking: disabled — {park_why}"
    tier = getattr(page_table, "_tier_store", None)
    if tier is None:
        missing = (
            "the page table is FLAT (ARBI_USE_RADIX_PAGETABLE=0), and a park keys "
            "its retention on the radix tree's prefix digests"
            if not isinstance(page_table, RadixPageTable)
            else "the prefix tier is OFF (ARBI_PREFIX_TIER=off), and a park pins its "
            "prefix in that tier"
        )
        return False, f"KV parking: disabled — {missing}"
    return True, (
        f"KV parking: enabled (pinned prefix retention, cap "
        f"{tier.pin_max_bytes / GIB:.1f} GiB of the {tier.host_max_bytes / GIB:.1f} "
        f"GiB warm tier)"
    )


class RetentionArms(NamedTuple):
    """What a pool build decides about prefix retention, before its page table."""

    use_radix: bool
    has_recurrent_view: bool
    savepoint_on: bool
    savepoint_arm_why: str
    parking_asked: bool
    parks_here: bool
    prefix_serves: bool
    prefix_inert_why: str
    prefix_retains: bool
    prefix_retain_why: str


def retention_arms(
    pool: Any, cache_cfg: Any, *, task: str = "generate", media_only_forward: bool = False
) -> RetentionArms:
    """The retention decisions ``build_active`` takes for ``pool``. Pure.

    One function so the eager KV sizing, which page-locks the prefix tier's
    arena ahead of its free reading, asks exactly what the build asks. Neither arm
    has a consumer on embed / rerank (``reads_prefix_cache``): no 4 GiB host tier.
    """
    from arbi_serve.runtime_flags import runtime_flags

    use_radix = runtime_flags().use_radix_pagetable
    # THE predicate, not a mirror of it. A ShortConv-only model reports
    # ``has_recurrent_pools() == False`` and still carries per-request rows, so
    # the answer needs both sources -- which is exactly why it is a function and
    # not an expression written out at each of the sites that asked it.
    has_recurrent_view = pool_carries_recurrent_state(pool)
    # Decide retention before the page table: the ring, store, worker and
    # tier allocation all belong to this arm. OFF must allocate none of them.
    _savepoint_on, _savepoint_arm_why = savepoint_subsystem_arm(
        savepoint_enabled=bool(runtime_flags().savepoint_enabled),
        max_bytes=int(cache_cfg.savepoint_max_bytes),
        has_recurrent_view=bool(has_recurrent_view),
        prefix_caching_on=bool(use_radix),
        pool=pool,
    )
    # Does this boot PARK? Asked HERE, above the page table, because a park is
    # the other consumer of the retention the predicate below governs and the
    # tier it pins in is built inside that branch. These are the two of
    # :func:`resolve_parking`'s three conditions that are answerable before the
    # table exists — the deployment's ask and the topology; the third (a tier
    # to pin in) is what this decision goes on to provide, and
    # ``resolve_parking`` below still refuses by name if it is missing anyway.
    _parking_asked = bool(getattr(cache_cfg, "kv_offload_enabled", False))
    _parks_here = _parking_asked and kv_parking_serves_here(pool)[0]
    # TWO questions (the scheduler registers two per-request flags). MATCH: may
    # a request read a prefix someone else produced? Not on a hybrid whose
    # savepoint subsystem is off (it cannot resume the recurrent half), and then
    # nothing walks. RETAIN: may a request's own pages be kept? A park pins its
    # own prefix and returns with its own recurrent row, so wherever this boot
    # parks. The scheduler derives both from the same two functions; this is the
    # boot half: build nothing nothing reads, withhold nothing a park needs.
    _prefix_serves, _prefix_inert_why = prefix_cache_can_serve(
        has_recurrent_view=bool(has_recurrent_view),
        savepoint_store_wired=bool(_savepoint_on),
        pool=pool,
    )
    _prefix_retains, _prefix_retain_why = prefix_retention_serves(
        prefix_cache_serves=bool(_prefix_serves),
        parks_here=bool(_parks_here),
    )
    if not reads_prefix_cache(task) or media_only_forward:
        _savepoint_on = False
        _savepoint_arm_why = f"--task {task} requests never use prefix retention"
        if media_only_forward:
            _savepoint_arm_why = "media-only forward builds no token batch"
        _prefix_serves = _prefix_retains = False
        _prefix_inert_why = _prefix_retain_why = _savepoint_arm_why
    return RetentionArms(
        use_radix=bool(use_radix),
        has_recurrent_view=bool(has_recurrent_view),
        savepoint_on=bool(_savepoint_on),
        savepoint_arm_why=str(_savepoint_arm_why),
        parking_asked=bool(_parking_asked),
        parks_here=bool(_parks_here),
        prefix_serves=bool(_prefix_serves),
        prefix_inert_why=str(_prefix_inert_why),
        prefix_retains=bool(_prefix_retains),
        prefix_retain_why=str(_prefix_retain_why),
    )


def build_active(eng: Engine) -> None:
    """Construct ``(pool, page_table, scheduler, metadata_builders, attn_ops)``.

    Idempotent in the sense that calling it after :func:`teardown_kind`
    leaves the engine in a clean ready-to-step state.
    """
    bs = eng.cfg.cache.block_size
    per_seq_pages = cdiv(eng.cfg.cache.max_context, bs)
    # Block-table PAGE CAP for the paged-KV metadata builders' TKV page-metadata
    # scratch (``TQBufferPool`` Turbo prefill + split-K CSR). It must match the persistent
    # PiecewiseBuffers block-table width — the pool page ceiling — because the
    # capture sweep + readiness gate feed a ceiling-wide block_table slice into
    # ``ensure()``; a narrower cap there overruns the fixed Turbo-prefill/CSR scratch. The
    # ceiling falls back to the max_context window when unset (pre-profile /
    # non-paged-KV), so early build_active calls keep the old width.
    # The SAME ceiling the grow uses. Sizing this from the (narrower,
    # forecast-derived) serving ceiling while the pool grows to the reserved-VA
    # ceiling leaves the tail pages unaddressable — the #1489 stranding, from
    # the other direction.
    bt_pages = block_table_width(
        eng.boot_state,
        int(eng.cfg.cache.max_context),
        int(bs),
        va_pages=int(getattr(getattr(eng, "pool", None), "num_pages", 0) or 0),
    )
    # Sizing precedence:
    #   1. ``eng.boot_state.profiled_num_pages`` set by
    #      :func:`profile_and_size_kv_pool` (the deterministic budget
    #      path; honours any compatible user override).
    #   2. ``cfg.cache.num_pages`` if explicitly set (legacy / tests
    #      that bypass the profiling path).
    #   3. The ``max_batch × per_seq_pages`` floor — only reached when
    #      neither of the above is available (unit-test stubs).
    profiled = eng.boot_state.profiled_num_pages
    cfg_pages = eng.cfg.cache.num_pages
    # The "comfort" floor: pages to hold ``max_batch`` sequences each at
    # full ``max_context`` simultaneously. This is what we'd LIKE, not
    # what must fit — at default max_batch=32 / max_context=32768 it is
    # 32×129+1 = 4129 pages, which on a 24 GB card is ~24 GB of bf16 KV
    # and does not fit.
    batch_floor = eng.cfg.batch.max_batch * (per_seq_pages + 1) + 1
    if profiled is not None:
        # The profiled budget is AUTHORITATIVE: it is the page count
        # that actually fits in the VRAM budget (gpu_memory_utilization
        # × total, minus weights/activations/graphs). Never raise it to
        # ``batch_floor`` — if the floor exceeds the budget, the floor
        # does not fit and raising to it OOMs at boot (which is exactly
        # the failure this replaced: max() let the floor override a
        # budget that fit). max_context does not consume VRAM; only the
        # page budget does. The scheduler admits fewer concurrent
        # sequences when pages are scarce rather than over-reserving.
        target_pages = int(profiled)
        if target_pages < batch_floor and not eng.boot_state.kv_warmup_pool:
            # Suppressed for the throwaway warmup pool (Phase 2b), which is
            # deliberately tiny and gets resized to the real budget after
            # capture — emitting the tight-fit advisory there is a false alarm.
            logger.debug(
                "KV pool: %d pages (%d tok), below floor %d (mb=%d × ctx=%d) "
                "— fewer concurrent full-context seqs (raise --gpu-memory-utilization for headroom)",
                target_pages,
                target_pages * bs,
                batch_floor,
                eng.cfg.batch.max_batch,
                eng.cfg.cache.max_context,
            )
    elif cfg_pages is not None:
        # Explicit operator / test override — honour verbatim.
        target_pages = int(cfg_pages)
    else:
        # No budget profiled and no override (unit-test stubs): fall back
        # to the comfort floor.
        target_pages = batch_floor
    # Pass the engine's named MemPool registry into the MultiStatePool
    # so each per-kind pool view (paged-KV / MLA / recurrent /
    # short-conv) routes its slab allocations into the right named
    # bucket instead of the default caching allocator.
    named_pool_map: dict[str, Any] = {}
    for n in ("state.attn_kv", "state.mla_kv", "state.gdn_recurrent", "state.conv", "state.dsv4"):
        p = eng.named_pools.get(n)
        if p is not None:
            named_pool_map[n] = p
    # Option B (B2): single-process in-process capture grows KV physical at a
    # stable VA after the capture sweep. When the engine requested a growable
    # KV pool, reserve the slab VA at the (max) ``va_pages`` but physically
    # back only ``boot_state.kv_growable_prefix_pages`` — the capture sweep touches only
    # low pages, so the unmapped tail costs ~0 VRAM during capture and is grown
    # in afterward. Non-uint8 backends ignore the flag (full allocation).
    _kv_growable = bool(getattr(eng, "_kv_growable", False))
    _kv_growable_prefix = eng.boot_state.kv_growable_prefix_pages
    # The reserved VA must span the SERVING ceiling, not just the conservative
    # pre-capture page count: ``boot_state.profiled_num_pages`` subtracts the
    # full prefill arena (a one-time boot transient), so reserving VA at it
    # would cap the post-capture grow below the freed-arena headroom — exactly
    # the ~5.4 GiB strand. Reserving at ``boot_state.kv_serving_ceiling_pages`` (≥
    # ``target_pages``; costs ~0 physical) lets the grow fill the freed prefill
    # arena. Non-growable pools allocate ``target_pages`` PHYSICALLY (no grow),
    # so they keep the conservative budget — the ceiling only widens the VA the
    # grow can reach. Falls back to ``target_pages`` when the ceiling is unset
    # (unit-test stubs / non-paged-KV).
    _serving_ceiling = int(eng.boot_state.kv_serving_ceiling_pages or 0)
    # The reserved VA spans the TRANSIENT-INDEPENDENT ceiling (kv_va_ceiling_pages
    # ≥ kv_serving_ceiling_pages) so a member built under co-resident/load
    # pressure can still grow into VRAM freed later — VA is ~0 physical and the
    # grow stays free-bounded. Falls back to serving_ceiling when unset.
    _va_ceiling = max(_serving_ceiling, int(getattr(eng.boot_state, "kv_va_ceiling_pages", 0) or 0))
    va_pages = max(int(target_pages), _va_ceiling) if _kv_growable else int(target_pages)
    from arbi_serve.cache.swa_split import num_swa_pages_for_cfg

    eng.pool = MultiStatePool(
        layer_specs=eng.model.layer_specs,
        backends=eng.active_backends,
        model_dims=eng.model.dims,
        num_pages=va_pages,
        page_size=bs,
        device=eng.device,
        parallel_cfg=eng.parallel_cfg,
        max_num_seqs=eng.cfg.batch.max_batch,
        dtype=eng.dtype,
        named_pools=named_pool_map,
        growable_kv=_kv_growable,
        growable_prefix_pages=_kv_growable_prefix,
        num_swa_pages=num_swa_pages_for_cfg(eng.model.layer_specs, eng.cfg, bs),
    )
    from arbi_serve.distributed.spmd_state_resume import arm_resume_wire

    arm_resume_wire(
        eng.pool,
        driver_wired=getattr(eng, "_spmd_state_wire", False),
        max_bytes=int(eng.cfg.cache.savepoint_max_bytes),
    )
    paged_view = eng.pool._views.get(StateKind.PAGED_KV)
    paged_layer_count = (
        getattr(paged_view, "num_paged_layers", None) if paged_view is not None else None
    )
    # ARBI_PP_KV_REPLICATE_DECODE_HANDOFF (no-op otherwise): the one buffer
    # every cross-rank KV/recurrent shipment streams through. Armed HERE —
    # after the pool exists, before the post-capture grow reads free VRAM —
    # so it is resident when the grow prices what is left, and priced in the
    # plan by ``capture_io_buffer_terms``' ``pp_kv_handoff_staging`` term.
    from arbi_serve.distributed.pp_send_staging import reserve_send_staging
    from arbi_serve.distributed.pp_transport_helpers import arm_bulk_transfer_staging

    reserve_send_staging(eng)
    arm_bulk_transfer_staging(
        eng.pool,
        eng.device,
        num_layers=sum(1 for s in eng.model.layer_specs if not s.is_mtp_layer),
        named_pools=eng.named_pools,
    )
    # The pool-detail block below is identical for the throwaway warmup pool
    # (Phase 2b) and the real post-capture pool, so it printed twice. Route it
    # to DEBUG for the warmup build — the real build still logs it at INFO.
    _plog = logger.debug if eng.boot_state.kv_warmup_pool else logger.info
    # Whole-pool B/tok, derived from the GiB total and token capacity on this
    # same line so the two stay consistent (GiB = B/tok × token-capacity).
    # Paged-KV B/tok MUST come from the same base as the page count printed
    # beside it. This used to divide ``gigabytes_total()`` — which spans the VA
    # page count AND the non-paged state pools (GDN recurrent, conv, io) — by
    # ``target_pages × block_size``: a mixed base where neither side is the
    # MAPPED pool. It over-stated per-token cost ~15% (reported 14084 B/tok on a
    # 6-paged-layer bf16 model whose true cost is per_page/block_size =
    # 3,145,728/256 = 12288 B/tok, i.e. exactly 2(K,V) × 2 kv_heads × 256
    # head_dim × 2 B × 6 layers) — and that inflated figure was then used to
    # reason about capacity against another engine.
    _tok_capacity = int(target_pages) * int(bs)
    _per_page_b = 0
    try:
        _paged_view = eng.pool._views.get(StateKind.PAGED_KV)
        _per_page_b = int(getattr(_paged_view, "per_page_bytes", 0) or 0)
    except Exception:  # noqa: BLE001 — the report degrades, it never fails a boot
        _per_page_b = 0
    _bytes_per_tok_all = int(round(_per_page_b / int(bs))) if (_per_page_b and bs) else 0
    # TWO TOTALS, both named, because they are different pools and the line
    # used to print one page count between them. ``target_pages`` and the
    # B/tok are PAGED_KV; ``gigabytes_total`` is EVERY state pool, so on a
    # hybrid — where the recurrent state is its own pool — pages x per-page
    # did not multiply out to the GiB standing beside it, and the reader who
    # checked the arithmetic was the one who got a wrong answer.
    _paged_gib = (int(target_pages) * _per_page_b) / GIB if _per_page_b else 0.0
    _plog(
        "pool: %d model layers (%s paged), %d pages × %d tok = %.2f GiB paged KV "
        "(%d B/tok summed over the paged layers); %.2f GiB PHYSICAL across ALL "
        "state pools (%.2f GiB reserved VA — paged KV + recurrent/conv/MLA state)",
        eng.model.dims.num_layers,
        paged_layer_count if paged_layer_count is not None else "n/a",
        target_pages,
        bs,
        _paged_gib,
        _bytes_per_tok_all,
        eng.pool.gigabytes_total(),
        eng.pool.gigabytes_reserved_va(),
    )
    # Slabs and rows are different units of the same pool; the line states
    # both so neither has to be inferred from the other.
    _row_ledger = savepoint_row_ledger(eng.pool)
    if _row_ledger is not None:
        _plog("%s", _row_ledger)

    # Phase H.2 — radix prefix-cache page table is the default. The
    # ``ARBI_USE_RADIX_PAGETABLE=0`` env var falls back to the flat
    # allocator for parity gates (bit-identical to pre-H.2 behaviour
    # because the flat table never aliases pages across requests).

    _media_only = bool(getattr(eng.model, "media_only_forward", False))
    _task = str(getattr(eng, "task", "generate"))
    _arms = retention_arms(eng.pool, eng.cfg.cache, task=_task, media_only_forward=_media_only)
    use_radix = _arms.use_radix
    _savepoint_on, _savepoint_arm_why = _arms.savepoint_on, _arms.savepoint_arm_why
    _parking_asked, _parks_here = _arms.parking_asked, _arms.parks_here
    _prefix_serves, _prefix_inert_why = _arms.prefix_serves, _arms.prefix_inert_why
    _prefix_retains, _prefix_retain_why = _arms.prefix_retains, _arms.prefix_retain_why
    if use_radix:
        # Optional multi-tier (VRAM→RAM→disk) prefix cache. When enabled,
        # LRU-evicted radix prefix pages are demoted to a warm host-RAM
        # tier (and an OPT-IN encrypted disk tier) instead of dropped, and
        # restored on a later lookup — gated on a break-even prefix length
        # whose shipped value is an unvalidated placeholder (see
        # ``cache/prefix_tier_store``). The
        # tier hooks live inside the radix evictor, so this requires radix.
        # NOT on the throwaway warmup build. ``build_active`` runs twice: once
        # against the 16-page warmup pool and again after the deferred resize
        # sizes the real one. The tier arena page-locks its WHOLE warm budget
        # at construction, so attaching it to the pool that is about to be torn
        # down page-locks that budget twice and throws the first away.
        #
        # The waste is the smaller half. The first arena's free returns its
        # pages to the caching host allocator, so the REAL arena is then served
        # out of that cached block and its VmRSS delta reads as a few KiB — the
        # ledger row degrades to "falls back to the ask and may UNDER-report"
        # for exactly the allocation whose resident cost is the one that
        # matters. A discarded arena blinds the instrument that prices the
        # kept one.
        #
        # A warmup page table serves no request and can evict nothing, so it
        # has nothing to demote and needs no tier. Neither can a table whose
        # retention is off: nothing is ever committed, so nothing is ever
        # evicted, so the tier would page-lock its whole warm budget to hold
        # pages it can never be handed — and arm an encrypted disk tier whose
        # every write would be unreadable back.
        if eng.boot_state.kv_warmup_pool:
            tier_store = None
        elif deferred_calibration_basket(eng.cfg) is not None:
            # The CALIBRATION-scoped pool: its only traffic is the capture, which
            # runs with the prefix cache off, so nothing is evicted into a tier.
            # The arena would page-lock the whole warm budget through the one
            # phase that also holds the host-resident capture and the fit, and
            # the codec swap's pool has another page geometry, so the arena is
            # replaced there, never reused. Priced against the host before the
            # capture existed, it leaves the capture to the OOM killer.
            tier_store = None
            _PREFIX_TIER_STORE.refuse("calibration_scoped_pool")
        elif _census_boot():
            # A census boot serves a few short requests that evict nothing, beside the
            # boot that launched it in the same memory limit: a warm tier holds nothing.
            tier_store = None
            _PREFIX_TIER_STORE.refuse("census_boot")
        elif not (_prefix_serves or _prefix_retains):
            # Neither half has a consumer: nothing matches, so nothing would
            # read a restored entry, and nothing retains, so nothing is ever
            # evicted into one. RETENTION alone is enough to need the tier —
            # it is where a park pins.
            tier_store = None
            _PREFIX_TIER_STORE.refuse("prefix_cache_inert")
        else:
            tier_store = _build_prefix_tier_store()
        eng.page_table = RadixPageTable(eng.pool, tier_store=tier_store)
        from arbi_serve.flag_truth import path_counter

        # Flag-truth (``ARBI_USE_RADIX_PAGETABLE``): the radix table is
        # what actually serves; the flag alone proves nothing.
        path_counter("radix_pagetable_built").fired = 1
        _plog("page table: RadixPageTable")
        if tier_store is not None:
            _plog(
                "prefix tiers: warm=%d GiB%s, break-even warm/cold=%d/%d tok",
                _prefix_tier_host_gib(),
                (
                    f", cold(disk)={tier_store.disk_max_bytes // GIB} GiB ENCRYPTED"
                    if tier_store.disk_enabled
                    